Skip to content

Commit b885fc5

Browse files
committed
Fix #5006: Enforce asInstanceOf to be a Select node
1 parent 1beb55f commit b885fc5

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

compiler/src/dotty/tools/dotc/transform/FirstTransform.scala

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@ object FirstTransform {
3131
* - drops branches of ifs using the rules
3232
* if (true) A else B ==> A
3333
* if (false) A else B ==> B
34+
* - Notmalize asInsanceOf to always be a selection
35+
* asInsanceOf[X] ==> this.asInsanceOf[X]
3436
*/
3537
class FirstTransform extends MiniPhase with InfoTransformer { thisPhase =>
3638
import ast.tpd._
@@ -54,6 +56,8 @@ class FirstTransform extends MiniPhase with InfoTransformer { thisPhase =>
5456
qual.tpe.derivesFrom(tree.symbol.owner) ||
5557
tree.symbol.is(JavaStatic) && qual.tpe.derivesFrom(tree.symbol.enclosingClass),
5658
i"non member selection of ${tree.symbol.showLocated} from ${qual.tpe} in $tree")
59+
case _: Ident =>
60+
assert(tree.symbol != defn.Any_asInstanceOf)
5761
case _: TypeTree =>
5862
case _: Import | _: NamedArg | _: TypTree =>
5963
assert(false, i"illegal tree: $tree")
@@ -143,8 +147,15 @@ class FirstTransform extends MiniPhase with InfoTransformer { thisPhase =>
143147
case tree => if (tree.isType) toTypeTree(tree) else tree
144148
}
145149

146-
override def transformIdent(tree: Ident)(implicit ctx: Context): Tree =
147-
if (tree.isType) toTypeTree(tree) else constToLiteral(tree)
150+
override def transformIdent(tree: Ident)(implicit ctx: Context): Tree = {
151+
if (tree.symbol == defn.Any_asInstanceOf) {
152+
// Add missing `this` prefix
153+
val TermRef(ths: ThisType, _) = tree.tpe
154+
ref(ths.termSymbol).select(tree.name).withSpan(tree.span)
155+
}
156+
else if (tree.isType) toTypeTree(tree)
157+
else constToLiteral(tree)
158+
}
148159

149160
override def transformSelect(tree: Select)(implicit ctx: Context): Tree =
150161
if (tree.isType) toTypeTree(tree) else constToLiteral(tree)

tests/pos/i5006.scala

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
object i0 {
2+
def f: Int = asInstanceOf[Int].toInt
3+
}
4+
5+
class i2 {
6+
def f: Int = asInstanceOf[Int].toInt
7+
}
8+
9+
trait i3 {
10+
def f: Int = asInstanceOf[Int].toInt
11+
}

0 commit comments

Comments
 (0)