Skip to content

Commit c48bada

Browse files
committed
Mixin: fix the initialization of traits
Before this commit, the following code: trait Hello { println("Hello") val x: Int = 1 println("World") } Became: <trait> trait Hello extends Object { def <init>(): Hello = { { () } this } <accessor> def x(): Int protected def initial$x(): Int = { println("Hello") 1 } } Notice that the initialization statements after the last getter were missing, this is now fixed: <trait> trait Hello extends Object { def <init>(): Hello = { { println("World") () } this } <accessor> def x(): Int protected def initial$x(): Int = { println("Hello") 1 } }
1 parent bf81fb6 commit c48bada

File tree

3 files changed

+17
-2
lines changed

3 files changed

+17
-2
lines changed

src/dotty/tools/dotc/transform/Mixin.scala

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ class Mixin extends MiniPhaseTransform with SymTransformer { thisTransform =>
9696

9797
def traitDefs(stats: List[Tree]): List[Tree] = {
9898
val initBuf = new mutable.ListBuffer[Tree]
99-
stats flatMap {
99+
stats.flatMap({
100100
case stat: DefDef if stat.symbol.isGetter && !stat.rhs.isEmpty && !stat.symbol.is(Flags.Lazy) =>
101101
// make initializer that has all effects of previous getter,
102102
// replace getter rhs with empty tree.
@@ -114,7 +114,7 @@ class Mixin extends MiniPhaseTransform with SymTransformer { thisTransform =>
114114
case stat =>
115115
initBuf += stat
116116
Nil
117-
}
117+
}) ++ initBuf
118118
}
119119

120120
def transformSuper(tree: Tree): Tree = {

tests/run/traitInit.check

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Hello
2+
World

tests/run/traitInit.scala

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
trait Hello {
2+
println("Hello")
3+
val x: Int = 1
4+
println("World")
5+
}
6+
7+
class A extends Hello
8+
9+
object Test {
10+
def main(args: Array[String]): Unit = {
11+
new A
12+
}
13+
}

0 commit comments

Comments
 (0)