Skip to content

Commit 230925d

Browse files
jmesyouJames You
andauthored
Check protected parent constructor accesses only occurs in child constructors (scala#25511)
Fixes scala#25442. Currently, protected parent class constructor calls that occur outside of their subclass constructors are not properly checked. So it possible to call a parent constructor in any method of subclass. This change checks that such accesses only occur inside subclass constructors. No LLM-based tools were used. negative test case from issue included. Co-authored-by: James You <jyou@protonmail.com>
1 parent 3be6338 commit 230925d

File tree

2 files changed

+12
-2
lines changed

2 files changed

+12
-2
lines changed

compiler/src/dotty/tools/dotc/core/SymDenotations.scala

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -946,10 +946,12 @@ object SymDenotations {
946946
val cls = owner.enclosingSubClass
947947
if !cls.exists then
948948
pre.termSymbol.isPackageObject && accessWithin(pre.termSymbol.owner)
949-
else
949+
else {
950+
val isConstructorAccessOK = isConstructor && ctx.owner.isConstructor
950951
// allow accesses to types from arbitrary subclasses fixes #4737
951952
// don't perform this check for static members
952-
isType || pre.derivesFrom(cls) || isConstructor || owner.is(ModuleClass)
953+
isType || pre.derivesFrom(cls) || isConstructorAccessOK || owner.is(ModuleClass)
954+
}
953955
end isProtectedAccessOK
954956

955957
if pre eq NoPrefix then true

tests/neg/i25442/test.scala

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
class I protected (x: Int) {
2+
protected def f = x
3+
}
4+
5+
class M protected () extends I(42) {
6+
def t1 = new M() // ok
7+
def t2 = new I(42) // error
8+
}

0 commit comments

Comments
 (0)