-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathInliner.scala
1221 lines (1106 loc) · 51.9 KB
/
Inliner.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package dotty.tools
package dotc
package inlines
import ast.*, core.*
import Flags.*, Symbols.*, Types.*, Decorators.*, Constants.*, Contexts.*
import StdNames.nme
import typer.*
import Names.Name
import NameKinds.InlineBinderName
import ProtoTypes.shallowSelectionProto
import SymDenotations.SymDenotation
import Inferencing.isFullyDefined
import config.Printers.inlining
import ErrorReporting.errorTree
import util.{SimpleIdentitySet, SrcPos}
import Nullables.computeNullableDeeply
import collection.mutable
import reporting.trace
import util.Spans.Span
import dotty.tools.dotc.transform.Splicer
import dotty.tools.dotc.transform.BetaReduce
import quoted.QuoteUtils
import staging.StagingLevel.{level, spliceContext}
import scala.annotation.constructorOnly
/** General support for inlining */
object Inliner:
import tpd.*
private[inlines] type DefBuffer = mutable.ListBuffer[ValOrDefDef]
/** Very similar to TreeInfo.isPureExpr, but with the following inliner-only exceptions:
* - synthetic case class apply methods, when the case class constructor is empty, are
* elideable but not pure. Elsewhere, accessing the apply method might cause the initialization
* of a containing object so they are merely idempotent.
*/
object isElideableExpr:
def isStatElideable(tree: Tree)(using Context): Boolean = unsplice(tree) match {
case EmptyTree
| TypeDef(_, _)
| Import(_, _)
| DefDef(_, _, _, _) =>
true
case vdef @ ValDef(_, _, _) =>
if (vdef.symbol.flags is Mutable) false else apply(vdef.rhs)
case _ =>
false
}
def apply(tree: Tree)(using Context): Boolean = unsplice(tree) match {
case EmptyTree
| This(_)
| Super(_, _)
| Literal(_) =>
true
case Ident(_) =>
isPureRef(tree) || tree.symbol.isAllOf(InlineParam)
case Select(qual, _) =>
if (tree.symbol.is(Erased)) true
else isPureRef(tree) && apply(qual)
case New(_) | Closure(_, _, _) =>
true
case TypeApply(fn, _) =>
if (fn.symbol.is(Erased) || fn.symbol == defn.QuotedTypeModule_of) true else apply(fn)
case Apply(fn, args) =>
val isCaseClassApply = {
val cls = tree.tpe.classSymbol
val meth = fn.symbol
meth.name == nme.apply &&
meth.flags.is(Synthetic) &&
meth.owner.linkedClass.is(Case) &&
cls.isNoInitsRealClass &&
funPart(fn).match
case Select(qual, _) => qual.symbol.is(Synthetic) // e.g: disallow `{ ..; Foo }.apply(..)`
case meth @ Ident(_) => meth.symbol.is(Synthetic) // e.g: allow `import Foo.{ apply => foo }; foo(..)`
case _ => false
}
if isPureApply(tree, fn) then
apply(fn) && args.forall(apply)
else if (isCaseClassApply)
args.forall(apply)
else if (fn.symbol.is(Erased)) true
else false
case Typed(expr, _) =>
apply(expr)
case Block(stats, expr) =>
apply(expr) && stats.forall(isStatElideable)
case Inlined(_, bindings, expr) =>
apply(expr) && bindings.forall(isStatElideable)
case NamedArg(_, expr) =>
apply(expr)
case _ =>
false
}
end isElideableExpr
// InlinerMap is a TreeTypeMap with special treatment for inlined arguments:
// They are generally left alone (not mapped further, and if they wrap a type
// the type Inlined wrapper gets dropped.
// As a side effect, register @nowarn annotations from annotated expressions.
private class InlinerMap(
typeMap: Type => Type,
treeMap: Tree => Tree,
oldOwners: List[Symbol],
newOwners: List[Symbol],
substFrom: List[Symbol],
substTo: List[Symbol])(using Context)
extends TreeTypeMap(
typeMap, treeMap, oldOwners, newOwners, substFrom, substTo,
// It is necessary to use the `ConservativeTreeCopier` since we copy at
// the same time as establishing the proper context in which the copied
// tree should be evaluated. This matters for opaque types, see
// neg/i14653.scala.
ConservativeTreeCopier()
):
override def transform(tree: Tree)(using Context): Tree =
tree match
case Typed(expr, tpt) =>
def loop(tpe: Type): Unit =
tpe match
case AnnotatedType(parent, annot) =>
if annot.hasSymbol(defn.NowarnAnnot) then
val argPos = annot.argument(0).getOrElse(tree).sourcePos
val conf = annot.argumentConstantString(0).getOrElse("")
ctx.run.nn.suppressions.registerNowarn(tree.sourcePos, expr.span)(conf, argPos)
else
loop(parent)
case _ =>
loop(tpt.tpe)
case _ =>
super.transform(tree)
override def copy(
typeMap: Type => Type,
treeMap: Tree => Tree,
oldOwners: List[Symbol],
newOwners: List[Symbol],
substFrom: List[Symbol],
substTo: List[Symbol])(using Context) =
new InlinerMap(typeMap, treeMap, oldOwners, newOwners, substFrom, substTo)
override def transformInlined(tree: Inlined)(using Context) =
if tree.inlinedFromOuterScope then
tree.expansion match
case expansion: TypeTree => expansion
case _ => tree
else super.transformInlined(tree)
end InlinerMap
object OpaqueProxy:
def apply(ref: TermRef, cls: ClassSymbol, span: Span)(using Context): TermRef =
def openOpaqueAliases(selfType: Type): List[(Name, Type)] = selfType match
case RefinedType(parent, rname, TypeAlias(alias)) =>
val opaq = cls.info.member(rname).symbol
if opaq.isOpaqueAlias then
(rname, alias.stripLazyRef.asSeenFrom(ref, cls))
:: openOpaqueAliases(parent)
else Nil
case _ => Nil
val refinements = openOpaqueAliases(cls.givenSelfType)
// Map references in the refinements from the proxied termRef
// to the recursive type of the refined type
// e.g.: Obj.type{type A = Obj.B; type B = Int} -> Obj.type{type A = <recthis>.B; type B = Int}
def mapRecTermRefReferences(recType: RecType, refinedType: Type) =
new TypeMap {
def apply(tp: Type) = tp match
case RefinedType(a: RefinedType, b, info) => RefinedType(apply(a), b, apply(info))
case RefinedType(a, b, info) => RefinedType(a, b, apply(info))
case TypeRef(prefix, des) => TypeRef(apply(prefix), des)
case termRef: TermRef if termRef == ref => recType.recThis
case _ => mapOver(tp)
}.apply(refinedType)
val refinedType = refinements.foldLeft(ref: Type): (parent, refinement) =>
RefinedType(parent, refinement._1, TypeAlias(refinement._2))
val recType = RecType.closeOver ( recType =>
mapRecTermRefReferences(recType, refinedType)
)
val refiningSym = newSym(InlineBinderName.fresh(), Synthetic, recType, span)
refiningSym.termRef
def unapply(refiningRef: TermRef)(using Context): Option[TermRef] =
val refiningSym = refiningRef.symbol
if refiningSym.name.is(InlineBinderName) && refiningSym.is(Synthetic, butNot=InlineProxy) then
refiningRef.info match
case refinedType: RefinedType => refinedType.stripRefinement match
case ref: TermRef => Some(ref)
case _ => None
case _ => None
else
None
end OpaqueProxy
private[inlines] def newSym(name: Name, flags: FlagSet, info: Type, span: Span)(using Context): Symbol =
newSymbol(ctx.owner, name, flags, info, coord = span)
end Inliner
/** Produces an inlined version of `call` via its `inlined` method.
*
* @param call the original call to an inlineable method
* @param rhsToInline the body of the inlineable method that replaces the call.
*/
class Inliner(val call: tpd.Tree)(using Context):
import tpd.*
import Inliner.*
private val methPart = funPart(call)
protected val callTypeArgs = typeArgss(call).flatten
protected val callValueArgss = termArgss(call)
protected val inlinedMethod = methPart.symbol
private val inlineCallPrefix =
qualifier(methPart).orElse(This(inlinedMethod.enclosingClass.asClass))
// Make sure all type arguments to the call are fully determined,
// but continue if that's not achievable (or else i7459.scala would crash).
for arg <- callTypeArgs do
isFullyDefined(arg.tpe, ForceDegree.flipBottom)
/** A map from parameter names of the inlineable method to references of the actual arguments.
* For a type argument this is the full argument type.
* For a value argument, it is a reference to either the argument value
* (if the argument is a pure expression of singleton type), or to `val` or `def` acting
* as a proxy (if the argument is something else).
*/
private val paramBinding = new mutable.HashMap[Name, Type]
/** A map from parameter names of the inlineable method to spans of the actual arguments */
private val paramSpan = new mutable.HashMap[Name, Span]
/** A map from references to (type and value) parameters of the inlineable method
* to their corresponding argument or proxy references, as given by `paramBinding`.
*/
private[inlines] val paramProxy = new mutable.HashMap[Type, Type]
/** A map from the classes of (direct and outer) this references in `rhsToInline`
* to references of their proxies.
* Note that we can't index by the ThisType itself since there are several
* possible forms to express what is logically the same ThisType. E.g.
*
* ThisType(TypeRef(ThisType(p), cls))
*
* vs
*
* ThisType(TypeRef(TermRef(ThisType(<root>), p), cls))
*
* These are different (wrt ==) types but represent logically the same key
*/
private val thisProxy = new mutable.HashMap[ClassSymbol, TermRef]
/** A buffer for bindings that define proxies for actual arguments */
private val bindingsBuf = new mutable.ListBuffer[ValOrDefDef]
private[inlines] def newSym(name: Name, flags: FlagSet, info: Type)(using Context): Symbol =
Inliner.newSym(name, flags, info, call.span)
/** A binding for the parameter of an inline method. This is a `val` def for
* by-value parameters and a `def` def for by-name parameters. `val` defs inherit
* inline annotations from their parameters. The generated `def` is appended
* to `buf`.
* @param name the name of the parameter
* @param formal the type of the parameter
* @param arg0 the argument corresponding to the parameter
* @param buf the buffer to which the definition should be appended
*/
private[inlines] def paramBindingDef(name: Name, formal: Type, arg0: Tree,
buf: DefBuffer)(using Context): ValOrDefDef = {
val isByName = formal.dealias.isInstanceOf[ExprType]
val arg =
def dropNameArg(arg: Tree): Tree = arg match
case NamedArg(_, arg1) => arg1
case SeqLiteral(elems, tpt) =>
cpy.SeqLiteral(arg)(elems.mapConserve(dropNameArg), tpt)
case _ => arg
arg0 match
case Typed(seq, tpt) if tpt.tpe.isRepeatedParam =>
if seq.tpe.derivesFrom(defn.ArrayClass) then wrapArray(dropNameArg(seq), arg0.tpe.elemType)
else cpy.Typed(arg0)(dropNameArg(seq), tpt)
case arg0 =>
dropNameArg(arg0)
val argtpe = arg.tpe.dealiasKeepAnnots.translateFromRepeated(toArray = false)
val argIsBottom = argtpe.isBottomTypeAfterErasure
val bindingType =
if argIsBottom then formal
else if isByName then ExprType(argtpe.widen)
else argtpe.widen
var bindingFlags: FlagSet = InlineProxy
if formal.widenExpr.hasAnnotation(defn.InlineParamAnnot) then
bindingFlags |= Inline
if formal.widenExpr.hasAnnotation(defn.ErasedParamAnnot) then
bindingFlags |= Erased
if isByName then
bindingFlags |= Method
val boundSym = newSym(InlineBinderName.fresh(name.asTermName), bindingFlags, bindingType).asTerm
val binding = {
var newArg = arg.changeOwner(ctx.owner, boundSym)
if bindingFlags.is(Inline) && argIsBottom then
newArg = Typed(newArg, TypeTree(formal.widenExpr)) // type ascribe RHS to avoid type errors in expansion. See i8612.scala
if isByName then DefDef(boundSym, newArg)
else ValDef(boundSym, newArg, inferred = true)
}.withSpan(boundSym.span)
inlining.println(i"parameter binding: $binding, $argIsBottom")
buf += binding
binding
}
/** Populate `paramBinding` and `buf` by matching parameters with
* corresponding arguments. `bindingbuf` will be further extended later by
* proxies to this-references. Issue an error if some arguments are missing.
*/
private def computeParamBindings(
tp: Type, targs: List[Tree],
argss: List[List[Tree]], formalss: List[List[Type]],
buf: DefBuffer): Boolean =
tp match
case tp: PolyType =>
tp.paramNames.lazyZip(targs).foreach { (name, arg) =>
paramSpan(name) = arg.span
paramBinding(name) = arg.tpe.stripTypeVar
}
computeParamBindings(tp.resultType, targs.drop(tp.paramNames.length), argss, formalss, buf)
case tp: MethodType =>
if argss.isEmpty then
report.error(em"missing arguments for inline method $inlinedMethod", call.srcPos)
false
else
tp.paramNames.lazyZip(formalss.head).lazyZip(argss.head).foreach { (name, formal, arg) =>
paramSpan(name) = arg.span
paramBinding(name) = arg.tpe.dealias match
case _: SingletonType if isIdempotentPath(arg) =>
arg.tpe
case _ =>
paramBindingDef(name, formal, arg, buf).symbol.termRef
}
computeParamBindings(tp.resultType, targs, argss.tail, formalss.tail, buf)
case _ =>
assert(targs.isEmpty)
assert(argss.isEmpty)
true
/** The number of enclosing classes of this class, plus one */
private def classNestingLevel(cls: Symbol) = cls.ownersIterator.count(_.isClass)
// Compute val-definitions for all this-proxies and append them to `bindingsBuf`
private def computeThisBindings() = {
// All needed this-proxies, paired-with and sorted-by nesting depth of
// the classes they represent (innermost first)
val sortedProxies = thisProxy.toList
.map((cls, proxy) => (classNestingLevel(cls), proxy.symbol, cls))
.sortBy(-_._1)
def outerSelect(prefix: Tree, prefixCls: Symbol, hops: Int, info: Type) =
val tpt = TypeTree(adaptToPrefix(prefixCls.appliedRef))
val qual = Typed(prefix, tpt)
qual.outerSelect(hops, info)
var lastSelf: Symbol = NoSymbol
var lastCls: Symbol = NoSymbol
var lastLevel: Int = 0
for ((level, selfSym, cls) <- sortedProxies) {
val rhs = selfSym.info.dealias match
case info: TermRef
if info.isStable && (lastSelf.exists || isPureExpr(inlineCallPrefix)) =>
// If this is the first proxy, optimize to `ref(info)` only if call prefix is pure.
// Otherwise we might forget side effects. See run/i12829.scala.
ref(info)
case info =>
val rhsClsSym = info.widenDealias.classSymbol
if rhsClsSym.is(Module) && rhsClsSym.isStatic then
ref(rhsClsSym.sourceModule)
else if lastSelf.exists then
outerSelect(ref(lastSelf), lastCls, lastLevel - level, selfSym.info)
else
val pre = inlineCallPrefix match
case Super(qual, _) => qual
case pre => pre
val preLevel = classNestingLevel(inlinedMethod.owner)
if preLevel > level then outerSelect(pre, inlinedMethod.owner.enclosingClass, preLevel - level, selfSym.info)
else pre
val binding = accountForOpaques(
ValDef(selfSym.asTerm, QuoteUtils.changeOwnerOfTree(rhs, selfSym), inferred = true).withSpan(selfSym.span))
bindingsBuf += binding
inlining.println(i"proxy at $level: $selfSym = ${bindingsBuf.last}")
lastSelf = selfSym
lastLevel = level
lastCls = cls
}
}
/** A list of pairs between TermRefs appearing in thisProxy bindings that
* refer to objects with opaque type aliases and local proxy symbols
* that contain refined versions of these TermRefs where the aliases
* are exposed.
*/
private val opaqueProxies = new mutable.ListBuffer[(TermRef, TermRef)]
/** TermRefs for which we already started synthesising proxies */
private val visitedTermRefs = new mutable.HashSet[TermRef]
protected def hasOpaqueProxies = opaqueProxies.nonEmpty
/** Map first halves of opaqueProxies pairs to second halves, using =:= as equality */
private def mapRef(ref: TermRef): Option[TermRef] =
opaqueProxies.collectFirst {
case (from, to) if from.symbol == ref.symbol && from =:= ref => to
}
/** If `tp` contains TermRefs that refer to objects with opaque
* type aliases, add proxy definitions to `opaqueProxies` that expose these aliases.
*/
private def addOpaqueProxies(tp: Type, span: Span, forThisProxy: Boolean)(using Context): Unit =
val foreachTpPart =
(p: Type => Unit) =>
if forThisProxy then
// Performs operations on all parts of this type, outside of the applied type arguments
new ForeachAccumulator(p, StopAt.None) {
override def apply(x: Unit, tp: Type) = tp match
case AppliedType(tycon, _) => super.apply(x, tycon)
case other => super.apply(x, other)
}.apply((), tp)
else tp.foreachPart(p)
foreachTpPart {
case ref: TermRef =>
for cls <- ref.widen.baseClasses do
if cls.containsOpaques
&& (forThisProxy || inlinedMethod.isContainedIn(cls))
&& !visitedTermRefs.contains(ref)
then
visitedTermRefs += ref
val refiningRef = OpaqueProxy(ref, cls, call.span)
val refiningSym = refiningRef.symbol.asTerm
val refinedType = refiningRef.info
val refiningDef = addProxiesForRecurrentOpaques(
ValDef(refiningSym, tpd.ref(ref).cast(refinedType), inferred = true).withSpan(span)
)
inlining.println(i"add opaque alias proxy $refiningDef for $ref in $tp")
bindingsBuf += refiningDef
opaqueProxies += ((ref, refiningSym.termRef))
case _ =>
}
/** Map all TermRefs that match left element in `opaqueProxies` to the
* corresponding right element.
*/
private val mapOpaques = TreeTypeMap(
typeMap = new TypeMap:
override def stopAt = StopAt.Package
def apply(t: Type) = mapOver {
t match
case ref: TermRef => mapRef(ref).getOrElse(ref)
case _ => t
}
)
/** Transforms proxies that reference other opaque types, like for:
* object Obj1 { opaque type A = Int }
* object Obj2 { opaque type B = A }
* and proxy$1 of type Obj2.type{type B = Obj1.A}
* creates proxy$2 of type Obj1.type{type A = Int}
* and transforms proxy$1 into Obj2.type{type B = proxy$2.A}
*/
private def addProxiesForRecurrentOpaques(binding: ValDef)(using Context): ValDef =
def fixRefinedTypes(ref: Type): Unit =
ref match
case recType: RecType => fixRefinedTypes(recType.underlying)
case RefinedType(parent, name, info) =>
addOpaqueProxies(info.widen, binding.span, true)
fixRefinedTypes(parent)
case _ =>
fixRefinedTypes(binding.symbol.info)
binding.symbol.info = mapOpaques.typeMap(binding.symbol.info)
mapOpaques.transform(binding).asInstanceOf[ValDef]
.showing(i"transformed this binding exposing opaque aliases: $result", inlining)
end addProxiesForRecurrentOpaques
/** If `binding` contains TermRefs that refer to objects with opaque
* type aliases, add proxy definitions that expose these aliases
* and substitute such TermRefs with theproxies. Example from pos/opaque-inline1.scala:
*
* object refined:
* opaque type Positive = Int
* inline def Positive(value: Int): Positive = f(value)
* def f(x: Positive): Positive = x
* def run: Unit = { val x = 9; val nine = refined.Positive(x) }
*
* This generates the following proxies:
*
* val $proxy1: refined.type{type Positive = Int} =
* refined.$asInstanceOf$[refined.type{type Positive = Int}]
* val refined$_this: ($proxy1 : refined.type{Positive = Int}) =
* $proxy1
*
* and every reference to `refined` in the inlined expression is replaced by
* `refined_$this`.
*/
private def accountForOpaques(binding: ValDef)(using Context): ValDef =
addOpaqueProxies(binding.symbol.info, binding.span, forThisProxy = true)
if opaqueProxies.isEmpty then binding
else
binding.symbol.info = mapOpaques.typeMap(binding.symbol.info)
mapOpaques.transform(binding).asInstanceOf[ValDef]
.showing(i"transformed this binding exposing opaque aliases: $result", inlining)
end accountForOpaques
/** If value argument contains references to objects that contain opaque types,
* map them to their opaque proxies.
*/
private def mapOpaquesInValueArg(arg: Tree)(using Context): Tree =
val argType = arg.tpe.widenDealias
addOpaqueProxies(argType, arg.span, forThisProxy = false)
if opaqueProxies.nonEmpty then
val mappedType = mapOpaques.typeMap(argType)
if mappedType ne argType then arg.cast(AndType(arg.tpe, mappedType))
else arg
else arg
private def canElideThis(tpe: ThisType): Boolean =
inlineCallPrefix.tpe == tpe && ctx.owner.isContainedIn(tpe.cls)
|| tpe.cls.isContainedIn(inlinedMethod)
|| tpe.cls.is(Package)
|| tpe.cls.isStaticOwner && !(tpe.cls.seesOpaques && inlinedMethod.isContainedIn(tpe.cls))
private def adaptToPrefix(tp: Type) = tp.asSeenFrom(inlineCallPrefix.tpe, inlinedMethod.owner)
/** Populate `thisProxy` and `paramProxy` as follows:
*
* 1a. If given type refers to a static this, thisProxy binds it to corresponding global reference,
* 1b. If given type refers to an instance this to a class that is not contained in the
* inline method, create a proxy symbol and bind the thistype to refer to the proxy.
* The proxy is not yet entered in `bindingsBuf`; that will come later.
* 2. If given type refers to a parameter, make `paramProxy` refer to the entry stored
* in `paramNames` under the parameter's name. This roundabout way to bind parameter
* references to proxies is done because we don't know a priori what the parameter
* references of a method are (we only know the method's type, but that contains TypeParamRefs
* and MethodParams, not TypeRefs or TermRefs.
*/
private def registerType(tpe: Type): Unit = tpe match {
case tpe: ThisType if !canElideThis(tpe) && !thisProxy.contains(tpe.cls) =>
val proxyName = s"${tpe.cls.name}_this".toTermName
val proxyType = inlineCallPrefix.tpe.dealias.tryNormalize match {
case typeMatchResult if typeMatchResult.exists => typeMatchResult
case _ => adaptToPrefix(tpe).widenIfUnstable
}
thisProxy(tpe.cls) = newSym(proxyName, InlineProxy, proxyType).termRef
for (param <- tpe.cls.typeParams)
paramProxy(param.typeRef) = adaptToPrefix(param.typeRef)
case tpe: NamedType
if tpe.symbol.is(Param)
&& tpe.symbol.owner == inlinedMethod
&& (tpe.symbol.isTerm || inlinedMethod.paramSymss.exists(_.contains(tpe.symbol)))
// this test is needed to rule out nested LambdaTypeTree parameters
// with the same name as the method's parameters. Note that the nested
// LambdaTypeTree parameters also have the inlineMethod as owner. C.f. i13460.scala.
&& !paramProxy.contains(tpe) =>
paramBinding.get(tpe.name) match
case Some(bound) => paramProxy(tpe) = bound
case _ => // can happen for params bound by type-lambda trees.
// The widened type may contain param types too (see tests/pos/i12379a.scala)
if tpe.isTerm then registerType(tpe.widenTermRefExpr)
case _ =>
}
private val registerTypes = new TypeTraverser:
override def stopAt = StopAt.Package
override def traverse(t: Type) =
registerType(t)
traverseChildren(t)
/** Register type of leaf node */
private def registerLeaf(tree: Tree): Unit = tree match
case _: This | _: Ident | _: TypeTree => registerTypes.traverse(tree.typeOpt)
case tree: Quote => registerTypes.traverse(tree.bodyType)
case _ =>
/** Make `tree` part of inlined expansion. This means its owner has to be changed
* from its `originalOwner`, and, if it comes from outside the inlined method
* itself, it has to be marked as an inlined argument.
*/
private def integrate(tree: Tree, originalOwner: Symbol)(using Context): Tree =
// assertAllPositioned(tree) // debug
tree.changeOwner(originalOwner, ctx.owner)
def tryConstValue(tpe: Type): Tree =
TypeComparer.constValue(tpe) match {
case Some(c) => Literal(c).withSpan(call.span)
case _ => EmptyTree
}
val reducer = new InlineReducer(this)
/** The Inlined node representing the inlined call */
def inlined(rhsToInline: tpd.Tree): (List[MemberDef], Tree) =
inlining.println(i"-----------------------\nInlining $call\nWith RHS $rhsToInline")
def paramTypess(call: Tree, acc: List[List[Type]]): List[List[Type]] = call match
case Apply(fn, args) =>
fn.tpe.widen.match
case mt: MethodType => paramTypess(fn, mt.instantiateParamInfos(args.tpes) :: acc)
case _ => Nil
case TypeApply(fn, _) => paramTypess(fn, acc)
case _ => acc
val paramBindings =
val mappedCallValueArgss = callValueArgss.nestedMapConserve(mapOpaquesInValueArg)
if mappedCallValueArgss ne callValueArgss then
inlining.println(i"mapped value args = ${mappedCallValueArgss.flatten}%, %")
val paramBindingsBuf = new DefBuffer
// Compute bindings for all parameters, appending them to bindingsBuf
if !computeParamBindings(
inlinedMethod.info, callTypeArgs,
mappedCallValueArgss, paramTypess(call, Nil),
paramBindingsBuf)
then
return (Nil, EmptyTree)
paramBindingsBuf.toList
end paramBindings
// make sure prefix is executed if it is impure
if !isIdempotentExpr(inlineCallPrefix) then registerType(inlinedMethod.owner.thisType)
// Register types of all leaves of inlined body so that the `paramProxy` and `thisProxy` maps are defined.
rhsToInline.foreachSubTree(registerLeaf)
// Compute bindings for all this-proxies, appending them to bindingsBuf
computeThisBindings()
// Parameter bindings come after this bindings, reflecting order of evaluation
bindingsBuf ++= paramBindings
val inlineTyper = new InlineTyper(ctx.reporter.errorCount)
val inlineCtx = inlineContext(Inlined(call, Nil, ref(defn.Predef_undefined))).fresh.setTyper(inlineTyper).setNewScope
def inlinedFromOutside(tree: Tree)(span: Span): Tree =
Inlined(EmptyTree, Nil, tree)(using ctx.withSource(inlinedMethod.topLevelClass.source)).withSpan(span)
// A tree type map to prepare the inlined body for typechecked.
// The translation maps references to `this` and parameters to
// corresponding arguments or proxies on the type and term level. It also changes
// the owner from the inlined method to the current owner.
val inliner = new InlinerMap(
typeMap =
new DeepTypeMap {
override def stopAt =
if opaqueProxies.isEmpty then StopAt.Static else StopAt.Package
def apply(t: Type) = t match {
case t: ThisType => thisProxy.getOrElse(t.cls, t)
case t: TypeRef => paramProxy.getOrElse(t, mapOver(t))
case t: SingletonType =>
if t.termSymbol.isAllOf(InlineParam) then apply(t.widenTermRefExpr)
else paramProxy.getOrElse(t, mapOver(t))
case t => mapOver(t)
}
},
treeMap = {
case tree: This =>
tree.tpe match {
case thistpe: ThisType =>
thisProxy.get(thistpe.cls) match {
case Some(t) =>
val thisRef = ref(t).withSpan(call.span)
inlinedFromOutside(thisRef)(tree.span)
case None => tree
}
case _ => tree
}
case tree: Ident =>
/* Span of the argument. Used when the argument is inlined directly without a binding */
def argSpan =
if (tree.name == nme.WILDCARD) tree.span // From type match
else if (tree.symbol.isTypeParam && tree.symbol.owner.isClass) tree.span // TODO is this the correct span?
else paramSpan(tree.name)
val inlinedCtx = ctx.withSource(inlinedMethod.topLevelClass.source)
paramProxy.get(tree.tpe) match {
case Some(t) if tree.isTerm && t.isSingleton =>
val inlinedSingleton = singleton(t).withSpan(argSpan)
inlinedFromOutside(inlinedSingleton)(tree.span)
case Some(t) if tree.isType =>
inlinedFromOutside(new InferredTypeTree().withType(t).withSpan(argSpan))(tree.span)
case _ => tree
}
case tree @ Select(qual: This, name) if tree.symbol.is(Private) && tree.symbol.isInlineMethod =>
// This inline method refers to another (private) inline method (see tests/pos/i14042.scala).
// We insert upcast to access the private inline method once inlined. This makes the selection
// keep the symbol when re-typechecking in the InlineTyper. The method is inlined and hence no
// reference to a private method is kept at runtime.
cpy.Select(tree)(qual.asInstance(qual.tpe.widen), name)
case tree => tree
},
oldOwners = inlinedMethod :: Nil,
newOwners = ctx.owner :: Nil,
substFrom = Nil,
substTo = Nil
)(using inlineCtx)
inlining.println(
i"""inliner transform with
|thisProxy = ${thisProxy.toList.map(_._1)}%, % --> ${thisProxy.toList.map(_._2)}%, %
|paramProxy = ${paramProxy.toList.map(_._1.typeSymbol.showLocated)}%, % --> ${paramProxy.toList.map(_._2)}%, %""")
// Apply inliner to `rhsToInline`, split off any implicit bindings from result, and
// make them part of `bindingsBuf`. The expansion is then the tree that remains.
val expansion = inliner.transform(rhsToInline)
def issueError() = callValueArgss match {
case (msgArg :: Nil) :: Nil =>
val message = msgArg.tpe match {
case ConstantType(Constant(msg: String)) => msg.toMessage
case _ => em"A literal string is expected as an argument to `compiletime.error`. Got $msgArg"
}
// Usually `error` is called from within a rewrite method. In this
// case we need to report the error at the point of the outermost enclosing inline
// call. This way, a defensively written rewrite method can always
// report bad inputs at the point of call instead of revealing its internals.
val callToReport = if (enclosingInlineds.nonEmpty) enclosingInlineds.last else call
val ctxToReport = ctx.outersIterator.dropWhile(enclosingInlineds(using _).nonEmpty).next
// The context in which we report should still use the existing context reporter
val ctxOrigReporter = ctxToReport.fresh.setReporter(ctx.reporter)
inContext(ctxOrigReporter) {
report.error(message, callToReport.srcPos)
}
case _ =>
}
/** The number of nodes in this tree, excluding code in nested inline
* calls and annotations of definitions.
*/
def treeSize(x: Any): Int =
var siz = 0
x match
case x: Trees.Inlined[?] =>
case x: Positioned =>
var i = 0
while i < x.productArity do
siz += treeSize(x.productElement(i))
i += 1
case x: List[?] =>
var xs = x
while xs.nonEmpty do
siz += treeSize(xs.head)
xs = xs.tail
case _ =>
siz
trace(i"inlining $call", inlining, show = true) {
// The normalized bindings collected in `bindingsBuf`
bindingsBuf.mapInPlace { binding =>
// Set trees to symbols allow macros to see the definition tree.
// This is used by `underlyingArgument`.
val binding1 = reducer.normalizeBinding(binding)(using inlineCtx).setDefTree
binding1.foreachSubTree {
case tree: MemberDef => tree.setDefTree
case _ =>
}
binding1
}
// Run a typing pass over the inlined tree. See InlineTyper for details.
val expansion1 = inlineTyper.typed(expansion)(using inlineCtx)
if (ctx.settings.verbose.value) {
inlining.println(i"to inline = $rhsToInline")
inlining.println(i"original bindings = ${bindingsBuf.toList}%\n%")
inlining.println(i"original expansion = $expansion1")
}
// Drop unused bindings
val (finalBindings, finalExpansion) = dropUnusedDefs(bindingsBuf.toList, expansion1)
if (inlinedMethod == defn.Compiletime_error) issueError()
addInlinedTrees(treeSize(finalExpansion))
(finalBindings, finalExpansion)
}
end inlined
/** An extractor for references to inlineable arguments. These are :
* - by-value arguments marked with `inline`
* - all by-name arguments
*/
private object InlineableArg {
lazy val paramProxies = paramProxy.values.toSet
def unapply(tree: Trees.Ident[?])(using Context): Option[Tree] = {
def search(buf: DefBuffer) = buf.find(_.name == tree.name)
if (paramProxies.contains(tree.typeOpt))
search(bindingsBuf) match {
case Some(bind: ValOrDefDef) if bind.symbol.is(Inline) =>
Some(integrate(bind.rhs, bind.symbol))
case _ => None
}
else None
}
}
private[inlines] def tryInlineArg(tree: Tree)(using Context): Tree = tree match {
case InlineableArg(rhs) =>
inlining.println(i"inline arg $tree -> $rhs")
rhs
case _ =>
EmptyTree
}
/** A typer for inlined bodies. Beyond standard typing, an inline typer performs
* the following functions:
*
* 1. Implement constant folding over inlined code
* 2. Selectively expand ifs with constant conditions
* 3. Inline arguments that are by-name closures
* 4. Make sure inlined code is type-correct.
* 5. Make sure that the tree's typing is idempotent (so that future -Ycheck passes succeed)
*/
class InlineTyper(initialErrorCount: Int, @constructorOnly nestingLevel: Int = ctx.nestingLevel + 1)
extends ReTyper(nestingLevel):
import reducer.*
override def ensureAccessible(tpe: Type, superAccess: Boolean, pos: SrcPos)(using Context): Type = {
tpe match {
case tpe: NamedType if tpe.symbol.exists && !tpe.symbol.isAccessibleFrom(tpe.prefix, superAccess) =>
tpe.info match {
case TypeAlias(alias) => return ensureAccessible(alias, superAccess, pos)
case info: ConstantType if tpe.symbol.isStableMember => return info
case _ =>
}
case _ =>
}
super.ensureAccessible(tpe, superAccess, pos)
}
/** Enter implicits in scope so that they can be found in implicit search.
* This is important for non-transparent inlines
*/
override def index(trees: List[untpd.Tree])(using Context): Context =
for case tree: untpd.MemberDef <- trees do
if tree.symbol.isOneOf(Flags.GivenOrImplicit) then
ctx.scope.openForMutations.enter(tree.symbol)
ctx
override def typedIdent(tree: untpd.Ident, pt: Type)(using Context): Tree =
val locked = ctx.typerState.ownedVars
val tree0 = tryInlineArg(tree.asInstanceOf[tpd.Tree]) `orElse` super.typedIdent(tree, pt)
val tree1 = inlineIfNeeded(tree0, pt, locked)
tree1 match
case id: Ident if tpd.needsSelect(id.tpe) =>
inlining.println(i"expanding $id to selection")
ref(id.tpe.asInstanceOf[TermRef]).withSpan(id.span)
case _ =>
tree1
override def typedSelect(tree: untpd.Select, pt: Type)(using Context): Tree = {
val locked = ctx.typerState.ownedVars
val qual1 = typed(tree.qualifier, shallowSelectionProto(tree.name, pt, this, tree.nameSpan))
// Make sure that the named type has the correct denotation.
// For instance in tests/pos/i22070 when we type `Featureful[?]#toFeatures`,
// `selectionType` will skolemize the prefix, find the denotation,
// and then set that denotation for the `TermRef(Featureful[?], symbol toFeatures)`.
selectionType(tree, qual1)
val resNoReduce = untpd.cpy.Select(tree)(qual1, tree.name).withType(tree.typeOpt)
val reducedProjection = reducer.reduceProjection(resNoReduce)
if reducedProjection.isType then
//if the projection leads to a typed tree then we stop reduction
resNoReduce
else
val res = constToLiteral(reducedProjection)
if resNoReduce ne res then
typed(res, pt) // redo typecheck if reduction changed something
else if res.symbol.isInlineMethod then
inlineIfNeeded(res, pt, locked)
else
ensureAccessible(res.tpe, tree.qualifier.isInstanceOf[untpd.Super], tree.srcPos)
res
}
override def typedIf(tree: untpd.If, pt: Type)(using Context): Tree =
val condCtx = if tree.isInline then ctx.addMode(Mode.ForceInline) else ctx
typed(tree.cond, defn.BooleanType)(using condCtx) match {
case cond1 @ ConstantValue(b: Boolean) =>
val selected0 = if (b) tree.thenp else tree.elsep
val selected = if (selected0.isEmpty) tpd.unitLiteral else typed(selected0, pt)
if (isIdempotentExpr(cond1)) selected
else Block(cond1 :: Nil, selected)
case cond1 =>
if (tree.isInline)
errorTree(tree,
em"Cannot reduce `inline if` because its condition is not a constant value: $cond1")
else
cond1.computeNullableDeeply()
val if1 = untpd.cpy.If(tree)(cond = untpd.TypedSplice(cond1))
super.typedIf(if1, pt)
}
override def typedValDef(vdef: untpd.ValDef, sym: Symbol)(using Context): Tree =
val vdef1 =
if sym.is(Inline) then
val rhs = typed(vdef.rhs)
sym.info = rhs.tpe
untpd.cpy.ValDef(vdef)(vdef.name, untpd.TypeTree(rhs.tpe), untpd.TypedSplice(rhs))
else vdef
super.typedValDef(vdef1, sym)
override def typedApply(tree: untpd.Apply, pt: Type)(using Context): Tree =
val locked = ctx.typerState.ownedVars
specializeEq(inlineIfNeeded(constToLiteral(BetaReduce(super.typedApply(tree, pt))), pt, locked))
override def typedTypeApply(tree: untpd.TypeApply, pt: Type)(using Context): Tree =
val locked = ctx.typerState.ownedVars
val tree1 = inlineIfNeeded(constToLiteral(BetaReduce(super.typedTypeApply(tree, pt))), pt, locked)
if tree1.symbol == defn.QuotedTypeModule_of then
ctx.compilationUnit.needsStaging = true
tree1
override def typedQuote(tree: untpd.Quote, pt: Type)(using Context): Tree =
super.typedQuote(tree, pt) match
case Quote(Splice(inner), _) => inner
case tree1 =>
ctx.compilationUnit.needsStaging = true
tree1
override def typedSplice(tree: untpd.Splice, pt: Type)(using Context): Tree =
super.typedSplice(tree, pt) match
case tree1 @ Splice(expr) if level == 0 && !hasInliningErrors && !ctx.usedBestEffortTasty =>
val expanded = expandMacro(expr, tree1.srcPos)
transform.TreeChecker.checkMacroGeneratedTree(tree1, expanded)
typedExpr(expanded) // Inline calls and constant fold code generated by the macro
case tree1 => tree1
override def typedMatch(tree: untpd.Match, pt: Type)(using Context): Tree =
val tree1 =
if tree.isInline then
// TODO this might not be useful if we do not support #11291
val sel1 = typedExpr(tree.selector)(using ctx.addMode(Mode.ForceInline))
untpd.cpy.Match(tree)(sel1, tree.cases)
else tree
super.typedMatch(tree1, pt)
override def typedMatchFinish(tree: untpd.Match, sel: Tree, wideSelType: Type, cases: List[untpd.CaseDef], pt: Type)(using Context) =
if (!tree.isInline || ctx.owner.isInlineMethod) // don't reduce match of nested inline method yet
super.typedMatchFinish(tree, sel, wideSelType, cases, pt)
else {
def selTyped(sel: Tree): Type = sel match {
case Typed(sel2, _) => selTyped(sel2)
case Block(Nil, sel2) => selTyped(sel2)
case Inlined(_, Nil, sel2) => selTyped(sel2)
case _ => sel.tpe
}
val selType = if (sel.isEmpty) wideSelType else selTyped(sel)
/** Make an Inlined that has no bindings. */
def flattenInlineBlock(tree: Tree): Tree = {
def inlineBlock(call: Tree, stats: List[Tree], expr: Tree): Block =
def inlinedTree(tree: Tree) = Inlined(call, Nil, tree).withSpan(tree.span)
val stats1 = stats.map:
case stat: ValDef => cpy.ValDef(stat)(rhs = inlinedTree(stat.rhs))
case stat: DefDef => cpy.DefDef(stat)(rhs = inlinedTree(stat.rhs))
case stat => inlinedTree(stat)
cpy.Block(tree)(stats1, flattenInlineBlock(inlinedTree(expr)))
tree match
case tree @ Inlined(call, bindings, expr) if !bindings.isEmpty =>
inlineBlock(call, bindings, expr)
case tree @ Inlined(call, Nil, Block(stats, expr)) =>
inlineBlock(call, stats, expr)
case _ =>
tree
}
def reduceInlineMatchExpr(sel: Tree): Tree = flattenInlineBlock(sel) match
case Block(stats, expr) =>
cpy.Block(sel)(stats, reduceInlineMatchExpr(expr))
case _ =>
reduceInlineMatch(sel, selType, cases.asInstanceOf[List[CaseDef]], this) match {
case Some((caseBindings, rhs0)) =>
// drop type ascriptions/casts hiding pattern-bound types (which are now aliases after reducing the match)
// note that any actually necessary casts will be reinserted by the typing pass below
val rhs1 = rhs0 match {
case Block(stats, t) if t.span.isSynthetic =>
t match {
case Typed(expr, _) =>
Block(stats, expr)
case TypeApply(sel@Select(expr, _), _) if sel.symbol.isTypeCast =>
Block(stats, expr)
case _ =>
rhs0
}