Skip to content

Check if the parent of class has an empty constr before expanding SAM #15909

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 20 additions & 2 deletions compiler/src/dotty/tools/dotc/transform/ExpandSAMs.scala
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,12 @@ class ExpandSAMs extends MiniPhase:
case tpe =>
val tpe1 = checkRefinements(tpe.stripNull, fn)
val Seq(samDenot) = tpe1.possibleSamMethods
cpy.Block(tree)(stats,
AnonClass(tpe1 :: Nil, fn.symbol.asTerm :: Nil, samDenot.symbol.asTerm.name :: Nil))
if hasNoArgConstr(tpe1) then
cpy.Block(tree)(stats,
AnonClass(tpe1 :: Nil, fn.symbol.asTerm :: Nil, samDenot.symbol.asTerm.name :: Nil))
else
report.error(em"${tpe1} cannot be instantiated with an empty constructor", tree.srcPos)
tree
}
case _ =>
tree
Expand Down Expand Up @@ -182,4 +186,18 @@ class ExpandSAMs extends MiniPhase:
case tpe =>
tpe
}

private def hasNoArgConstr(tpe: Type)(using Context): Boolean = {
def noArgs(ctpe: Type): Boolean = ctpe match {
case ctpe: PolyType =>
noArgs(ctpe.resType)
case ctpe: MethodType =>
ctpe.paramInfos.isEmpty
case _ =>
false
}
val parent :: _ = tpe.parents: @unchecked
val constr = parent.dealias.decl(nme.CONSTRUCTOR).suchThat(constr => noArgs(constr.info))
constr != SymDenotations.NoDenotation
}
end ExpandSAMs
56 changes: 56 additions & 0 deletions tests/neg/i15855.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
class MyFunction(arg: String) {
def a: String = arg
}

trait MyFun[+R] extends MyFunction {
def apply(i: Int): R
}

val myFun: MyFun[Int] = (i: Int) => 1 // error

//

class MyFunction1(arg: String = "") {
def a: String = arg
}

trait MyFun1[+R] extends MyFunction1 {
def apply(i: Int): R
}

val myFun1: MyFun1[Int] = (i: Int) => 1 // error

//

trait MyFunction2(arg: String = "") {
def a: String = arg
}

trait MyFun2[+R] extends MyFunction2 {
def apply(i: Int): R
}

val myFun2: MyFun2[Int] = (i: Int) => 1

//

trait MyFunction3(arg: String) {
def a: String = arg
}

trait MyFun3[+R] extends MyFunction3 {
def apply(i: Int): R
}

val myFun3: MyFun3[Int] = (i: Int) => 1

//

class MyFunction4() {
}

trait MyFun4[+R] extends MyFunction4 {
def apply(i: Int): R
}

val myFun4: MyFun4[Int] = (i: Int) => 1