|
| 1 | +package dotty.tools.dotc |
| 2 | +package transform |
| 3 | + |
| 4 | +import MegaPhase._ |
| 5 | +import core.DenotTransformers.{IdentityDenotTransformer} |
| 6 | +import core.Symbols._ |
| 7 | +import core.Contexts._ |
| 8 | +import core.Types._ |
| 9 | +import core.Flags._ |
| 10 | +import core.StdNames.nme |
| 11 | +import core.Constants.Constant |
| 12 | +import core.Decorators._ |
| 13 | +import core.TypeErasure.erasure |
| 14 | +import ast.tpd |
| 15 | + |
| 16 | +object UncacheGivenAliases: |
| 17 | + val name: String = "uncacheAliasImplicits" |
| 18 | + |
| 19 | +/** This phase optimizes alias givens represented as lazy vals to be uncached |
| 20 | + * if that does not change runtime behavior. A definition does not need to be |
| 21 | + * cached if its right hand side has a stable type and is of one of them forms |
| 22 | + * |
| 23 | + * this |
| 24 | + * this.y |
| 25 | + * y |
| 26 | + */ |
| 27 | +class UncacheGivenAliases extends MiniPhase with IdentityDenotTransformer: |
| 28 | + thisPhase => |
| 29 | + import tpd._ |
| 30 | + |
| 31 | + override def phaseName: String = UncacheGivenAliases.name |
| 32 | + |
| 33 | + private def needsCache(sym: Symbol, rhs: Tree)(using Context): Boolean = rhs.tpe match |
| 34 | + case rhsTpe @ TermRef(NoPrefix, _) |
| 35 | + if rhsTpe.isStable => false |
| 36 | + case rhsTpe @ TermRef(pre: ThisType, _) |
| 37 | + if rhsTpe.isStable && pre.cls == sym.owner.enclosingClass => false |
| 38 | + case rhsTpe: ThisType => false |
| 39 | + case _ => true |
| 40 | + |
| 41 | + /** Transform |
| 42 | + * |
| 43 | + * lazy given val x = rhs |
| 44 | + * |
| 45 | + * to |
| 46 | + * |
| 47 | + * def x = rhs |
| 48 | + * |
| 49 | + * provided `rhs` has a stable type and is of one of them forms |
| 50 | + * |
| 51 | + * this |
| 52 | + * this.y |
| 53 | + * y |
| 54 | + */ |
| 55 | + override def transformValDef(tree: ValDef)(using Context): Tree = |
| 56 | + val sym = tree.symbol |
| 57 | + if sym.isAllOf(Given, Lazy) && !needsCache(sym, tree.rhs) then |
| 58 | + sym.copySymDenotation( |
| 59 | + initFlags = sym.flags &~ Lazy | Method, |
| 60 | + info = ExprType(sym.info)) |
| 61 | + .installAfter(thisPhase) |
| 62 | + cpy.DefDef(tree)(tree.name, Nil, Nil, tree.tpt, tree.rhs) |
| 63 | + else tree |
| 64 | +end UncacheGivenAliases |
| 65 | + |
| 66 | + |
| 67 | + |
0 commit comments