-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
QuotesImpl.scala
3305 lines (2745 loc) · 137 KB
/
QuotesImpl.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 scala.quoted
package runtime.impl
import scala.language.unsafeNulls
import dotty.tools.dotc
import dotty.tools.dotc.ast.tpd
import dotty.tools.dotc.ast.untpd
import dotty.tools.dotc.core.Annotations
import dotty.tools.dotc.core.Contexts.*
import dotty.tools.dotc.core.Decorators.*
import dotty.tools.dotc.core.NameKinds
import dotty.tools.dotc.core.NameOps.*
import dotty.tools.dotc.core.StdNames.*
import dotty.tools.dotc.core.Types
import dotty.tools.dotc.NoCompilationUnit
import dotty.tools.dotc.quoted.MacroExpansion
import dotty.tools.dotc.quoted.PickledQuotes
import dotty.tools.dotc.quoted.QuotePatterns
import dotty.tools.dotc.quoted.reflect.*
import scala.quoted.runtime.{QuoteUnpickler, QuoteMatching}
import scala.quoted.runtime.impl.printers.*
import scala.reflect.TypeTest
import dotty.tools.dotc.core.NameKinds.ExceptionBinderName
import dotty.tools.dotc.transform.TreeChecker
object QuotesImpl {
def apply()(using Context): Quotes =
new QuotesImpl
def showDecompiledTree(tree: tpd.Tree)(using Context): String =
import qctx.reflect.Printer.{TreeCode, TreeAnsiCode}
val qctx: QuotesImpl = new QuotesImpl(using MacroExpansion.context(tree))
if ctx.settings.color.value == "always" then TreeAnsiCode.show(tree)
else TreeCode.show(tree)
}
class QuotesImpl private (using val ctx: Context) extends Quotes, QuoteUnpickler, QuoteMatching:
import tpd.*
private val xCheckMacro: Boolean = ctx.settings.XcheckMacros.value
private val yDebugMacro: Boolean = ctx.settings.XdebugMacros.value
extension [T](self: scala.quoted.Expr[T])
def show: String =
reflect.Printer.TreeCode.show(reflect.asTerm(self))
def matches(that: scala.quoted.Expr[Any]): Boolean =
QuoteMatcher(yDebugMacro).treeMatch(reflect.asTerm(self), reflect.asTerm(that)).nonEmpty
def valueOrAbort(using fromExpr: FromExpr[T]): T =
def reportError =
val tree = reflect.asTerm(self)
val code = reflect.Printer.TreeCode.show(tree)
val msg = s"Expected a known value. \n\nThe value of: $code\ncould not be extracted using $fromExpr"
reflect.report.throwError(msg, self)
fromExpr.unapply(self)(using QuotesImpl.this).getOrElse(reportError)
end extension
extension (self: scala.quoted.Expr[Any])
/** Checks is the `quoted.Expr[?]` is valid expression of type `X` */
def isExprOf[X](using scala.quoted.Type[X]): Boolean =
reflect.TypeReprMethods.<:<(reflect.asTerm(self).tpe)(reflect.TypeRepr.of[X])
/** Convert this to an `quoted.Expr[X]` if this expression is a valid expression of type `X` or throws */
def asExprOf[X](using scala.quoted.Type[X]): scala.quoted.Expr[X] = {
if self.isExprOf[X] then
self.asInstanceOf[scala.quoted.Expr[X]]
else
throw ExprCastException(
expectedType = reflect.Printer.TypeReprCode.show(reflect.TypeRepr.of[X]),
actualType = reflect.Printer.TypeReprCode.show(reflect.asTerm(self).tpe),
exprCode = self.show
)
}
end extension
object reflect extends reflectModule:
object CompilationInfo extends CompilationInfoModule:
def isWhileTyping: Boolean = !ctx.isAfterTyper
def XmacroSettings: List[String] = ctx.settings.XmacroSettings.value
end CompilationInfo
extension (expr: Expr[Any])
def asTerm: Term = expr.asInstanceOf[ExprImpl].tree
end extension
type Tree = tpd.Tree
object Tree extends TreeModule
given TreeMethods: TreeMethods with
extension (self: Tree)
def pos: Position =
val treePos = self.sourcePos
if treePos.exists then treePos
else
if xCheckMacro then report.warning(s"Missing tree position (defaulting to position 0): ${Printer.TreeStructure.show(self)}\nThis is a compiler bug. Please report it.")
self.source.atSpan(dotc.util.Spans.Span(0))
def symbol: Symbol = self.symbol
def show(using printer: Printer[Tree]): String = printer.show(self)
def isExpr: Boolean =
self match
case TermTypeTest(self) =>
self.tpe.widen match
case _: MethodType | _: PolyType => false
case _ => true
case _ => false
def asExpr: scala.quoted.Expr[Any] =
if self.isExpr then
new ExprImpl(self, SpliceScope.getCurrent)
else self match
case TermTypeTest(self) => throw new Exception("Expected an expression. This is a partially applied Term. Try eta-expanding the term first.")
case _ => throw new Exception("Expected a Term but was: " + Printer.TreeStructure.show(self))
end extension
extension (self: Tree)
def asExprOf[T](using tp: scala.quoted.Type[T]): scala.quoted.Expr[T] =
QuotesImpl.this.asExprOf(self.asExpr)[T](using tp)
end extension
extension [ThisTree <: Tree](self: ThisTree)
def changeOwner(newOwner: Symbol): ThisTree =
tpd.TreeOps(self).changeNonLocalOwners(newOwner).asInstanceOf[ThisTree]
end extension
end TreeMethods
type PackageClause = tpd.PackageDef
object PackageClauseTypeTest extends TypeTest[Tree, PackageClause]:
def unapply(x: Tree): Option[PackageClause & x.type] = x match
case x: (tpd.PackageDef & x.type) => Some(x)
case _ => None
end PackageClauseTypeTest
object PackageClause extends PackageClauseModule:
def apply(pid: Ref, stats: List[Tree]): PackageClause =
withDefaultPos(tpd.PackageDef(pid.asInstanceOf[tpd.RefTree], stats))
def copy(original: Tree)(pid: Ref, stats: List[Tree]): PackageClause =
tpd.cpy.PackageDef(original)(pid, stats)
def unapply(tree: PackageClause): (Ref, List[Tree]) =
(tree.pid, tree.stats)
end PackageClause
given PackageClauseMethods: PackageClauseMethods with
extension (self: PackageClause)
def pid: Ref = self.pid
def stats: List[Tree] = self.stats
end extension
end PackageClauseMethods
type Import = tpd.Import
object ImportTypeTest extends TypeTest[Tree, Import]:
def unapply(x: Tree): Option[Import & x.type] = x match
case tree: (tpd.Import & x.type) => Some(tree)
case _ => None
end ImportTypeTest
object Import extends ImportModule:
def apply(expr: Term, selectors: List[Selector]): Import =
if selectors.isEmpty then throw IllegalArgumentException("Empty selectors")
withDefaultPos(tpd.Import(expr, selectors))
def copy(original: Tree)(expr: Term, selectors: List[Selector]): Import =
if selectors.isEmpty then throw IllegalArgumentException("Empty selectors")
tpd.cpy.Import(original)(expr, selectors)
def unapply(tree: Import): (Term, List[Selector]) =
(tree.expr, tree.selectors)
end Import
given ImportMethods: ImportMethods with
extension (self: Import)
def expr: Term = self.expr
def selectors: List[Selector] = self.selectors
end extension
end ImportMethods
type Export = tpd.Export
object ExportTypeTest extends TypeTest[Tree, Export]:
def unapply(x: Tree): Option[Export & x.type] = x match
case tree: (tpd.Export & x.type) => Some(tree)
case _ => None
end ExportTypeTest
object Export extends ExportModule:
def unapply(tree: Export): (Term, List[Selector]) =
(tree.expr, tree.selectors)
end Export
given ExportMethods: ExportMethods with
extension (self: Export)
def expr: Term = self.expr
def selectors: List[Selector] = self.selectors
end extension
end ExportMethods
type Statement = tpd.Tree
object StatementTypeTest extends TypeTest[Tree, Statement]:
def unapply(x: Tree): Option[Statement & x.type] = x match
case TermTypeTest(x: x.type) => Some(x)
case DefinitionTypeTest(x: x.type) => Some(x)
case ImportTypeTest(x: x.type) => Some(x)
case ExportTypeTest(x: x.type) => Some(x)
case _ => None
end StatementTypeTest
type Definition = tpd.MemberDef
object DefinitionTypeTest extends TypeTest[Tree, Definition]:
def unapply(x: Tree): Option[Definition & x.type] = x match
case x: (tpd.MemberDef & x.type) => Some(x)
case _ => None
end DefinitionTypeTest
object Definition extends DefinitionModule
given DefinitionMethods: DefinitionMethods with
extension (self: Definition)
def name: String = self match
case self: tpd.MemberDef => self.name.toString
end extension
end DefinitionMethods
type ClassDef = tpd.TypeDef
object ClassDefTypeTest extends TypeTest[Tree, ClassDef]:
def unapply(x: Tree): Option[ClassDef & x.type] = x match
case x: (tpd.TypeDef & x.type) if x.isClassDef => Some(x)
case _ => None
end ClassDefTypeTest
object ClassDef extends ClassDefModule:
def apply(cls: Symbol, parents: List[Tree], body: List[Statement]): ClassDef =
val untpdCtr = untpd.DefDef(nme.CONSTRUCTOR, Nil, tpd.TypeTree(dotc.core.Symbols.defn.UnitClass.typeRef), tpd.EmptyTree)
val ctr = ctx.typeAssigner.assignType(untpdCtr, cls.primaryConstructor)
tpd.ClassDefWithParents(cls.asClass, ctr, parents, body)
def copy(original: Tree)(name: String, constr: DefDef, parents: List[Tree], selfOpt: Option[ValDef], body: List[Statement]): ClassDef = {
val dotc.ast.Trees.TypeDef(_, originalImpl: tpd.Template) = original: @unchecked
tpd.cpy.TypeDef(original)(name.toTypeName, tpd.cpy.Template(originalImpl)(constr, parents, derived = Nil, selfOpt.getOrElse(tpd.EmptyValDef), body))
}
def unapply(cdef: ClassDef): (String, DefDef, List[Tree /* Term | TypeTree */], Option[ValDef], List[Statement]) =
val rhs = cdef.rhs.asInstanceOf[tpd.Template]
(cdef.name.toString, cdef.constructor, cdef.parents, cdef.self, rhs.body)
def module(module: Symbol, parents: List[Tree /* Term | TypeTree */], body: List[Statement]): (ValDef, ClassDef) = {
if xCheckMacro then TreeChecker.checkParents(module.moduleClass.asClass, parents)
val cls = module.moduleClass
val clsDef = ClassDef(cls, parents, body)
val newCls = Apply(Select(New(TypeIdent(cls)), cls.primaryConstructor), Nil)
val modVal = ValDef(module, Some(newCls))
(modVal, clsDef)
}
end ClassDef
given ClassDefMethods: ClassDefMethods with
extension (self: ClassDef)
def constructor: DefDef =
self.rhs.asInstanceOf[tpd.Template].constr
def parents: List[Tree] =
self.rhs.asInstanceOf[tpd.Template].parents
def self: Option[ValDef] =
optional(self.rhs.asInstanceOf[tpd.Template].self)
def body: List[Statement] =
self.rhs.asInstanceOf[tpd.Template].body
end extension
end ClassDefMethods
type ValOrDefDef = tpd.ValOrDefDef
object ValOrDefDefTypeTest extends TypeTest[Tree, ValOrDefDef]:
def unapply(x: Tree): Option[ValOrDefDef & x.type] = x match
case x: (tpd.ValOrDefDef & x.type) => Some(x)
case _ => None
end ValOrDefDefTypeTest
given ValOrDefDefMethods: ValOrDefDefMethods with
extension (self: ValOrDefDef)
def tpt: TypeTree = self.tpt
def rhs: Option[Term] = optional(self.rhs)
end extension
end ValOrDefDefMethods
type DefDef = tpd.DefDef
object DefDefTypeTest extends TypeTest[Tree, DefDef]:
def unapply(x: Tree): Option[DefDef & x.type] = x match
case x: (tpd.DefDef & x.type) => Some(x)
case _ => None
end DefDefTypeTest
object DefDef extends DefDefModule:
def apply(symbol: Symbol, rhsFn: List[List[Tree]] => Option[Term]): DefDef =
xCheckMacroAssert(symbol.isTerm, s"expected a term symbol, but received $symbol")
xCheckMacroAssert(symbol.flags.is(Flags.Method), "expected a symbol with `Method` flag set")
withDefaultPos(tpd.DefDef(symbol.asTerm, prefss =>
xCheckedMacroOwners(xCheckMacroValidExpr(rhsFn(prefss)), symbol).getOrElse(tpd.EmptyTree)
))
def copy(original: Tree)(name: String, paramss: List[ParamClause], tpt: TypeTree, rhs: Option[Term]): DefDef =
tpd.cpy.DefDef(original)(name.toTermName, paramss, tpt, xCheckedMacroOwners(rhs, original.symbol).getOrElse(tpd.EmptyTree))
def unapply(ddef: DefDef): (String, List[ParamClause], TypeTree, Option[Term]) =
(ddef.name.toString, ddef.paramss, ddef.tpt, optional(ddef.rhs))
end DefDef
given DefDefMethods: DefDefMethods with
extension (self: DefDef)
def paramss: List[ParamClause] = self.paramss
def leadingTypeParams: List[TypeDef] = self.leadingTypeParams
def trailingParamss: List[ParamClause] = self.trailingParamss
def termParamss: List[TermParamClause] = self.termParamss
def returnTpt: TypeTree = self.tpt
def rhs: Option[Term] = optional(self.rhs)
end extension
end DefDefMethods
type ValDef = tpd.ValDef
object ValDefTypeTest extends TypeTest[Tree, ValDef]:
def unapply(x: Tree): Option[ValDef & x.type] = x match
case x: (tpd.ValDef & x.type) => Some(x)
case _ => None
end ValDefTypeTest
object ValDef extends ValDefModule:
def apply(symbol: Symbol, rhs: Option[Term]): ValDef =
xCheckMacroAssert(!symbol.flags.is(Flags.Method), "expected a symbol without `Method` flag set")
withDefaultPos(tpd.ValDef(symbol.asTerm, xCheckedMacroOwners(xCheckMacroValidExpr(rhs), symbol).getOrElse(tpd.EmptyTree)))
def copy(original: Tree)(name: String, tpt: TypeTree, rhs: Option[Term]): ValDef =
tpd.cpy.ValDef(original)(name.toTermName, tpt, xCheckedMacroOwners(xCheckMacroValidExpr(rhs), original.symbol).getOrElse(tpd.EmptyTree))
def unapply(vdef: ValDef): (String, TypeTree, Option[Term]) =
(vdef.name.toString, vdef.tpt, optional(vdef.rhs))
def let(owner: Symbol, name: String, rhs: Term)(body: Ref => Term): Term =
val vdef = tpd.SyntheticValDef(name.toTermName, rhs)(using ctx.withOwner(owner))
val ref = tpd.ref(vdef.symbol).asInstanceOf[Ref]
Block(List(vdef), body(ref))
def let(owner: Symbol, terms: List[Term])(body: List[Ref] => Term): Term =
val ctx1 = ctx.withOwner(owner)
val vdefs = terms.map(term => tpd.SyntheticValDef("x".toTermName, term)(using ctx1))
val refs = vdefs.map(vdef => tpd.ref(vdef.symbol).asInstanceOf[Ref])
Block(vdefs, body(refs))
end ValDef
given ValDefMethods: ValDefMethods with
extension (self: ValDef)
def tpt: TypeTree = self.tpt
def rhs: Option[Term] = optional(self.rhs)
end extension
end ValDefMethods
type TypeDef = tpd.TypeDef
object TypeDefTypeTest extends TypeTest[Tree, TypeDef]:
def unapply(x: Tree): Option[TypeDef & x.type] = x match
case x: (tpd.TypeDef & x.type) if !x.isClassDef => Some(x)
case _ => None
end TypeDefTypeTest
object TypeDef extends TypeDefModule:
def apply(symbol: Symbol): TypeDef =
withDefaultPos(tpd.TypeDef(symbol.asType))
def copy(original: Tree)(name: String, rhs: Tree): TypeDef =
tpd.cpy.TypeDef(original)(name.toTypeName, rhs)
def unapply(tdef: TypeDef): (String, Tree /*TypeTree | TypeBoundsTree*/ /* TypeTree | TypeBoundsTree */) =
(tdef.name.toString, tdef.rhs)
end TypeDef
given TypeDefMethods: TypeDefMethods with
extension (self: TypeDef)
def rhs: Tree = self.rhs
end extension
end TypeDefMethods
type Term = tpd.Tree
object TermTypeTest extends TypeTest[Tree, Term]:
def unapply(x: Tree): Option[Term & x.type] = x match
case x: tpd.PatternTree => None
case x: (tpd.SeqLiteral & x.type) => Some(x)
case x: (tpd.Inlined & x.type) => Some(x)
case x: (tpd.NamedArg & x.type) => Some(x)
case x: (tpd.Typed & x.type) =>
TypedTypeTest.unapply(x) // Matches `Typed` but not `TypedOrTest`
case _ => if x.isTerm then Some(x) else None
end TermTypeTest
object Term extends TermModule:
def betaReduce(tree: Term): Option[Term] =
val tree1 = new dotty.tools.dotc.ast.tpd.TreeMap {
override def transform(tree: Tree)(using Context): Tree = tree match {
case tpd.Block(Nil, _) | tpd.Inlined(_, Nil, _) =>
super.transform(tree)
case tpd.Apply(sel @ tpd.Select(expr, nme), args) =>
val tree1 = cpy.Apply(tree)(cpy.Select(sel)(transform(expr), nme), args)
dotc.transform.BetaReduce(tree1).withSpan(tree.span)
case tpd.Apply(ta @ tpd.TypeApply(sel @ tpd.Select(expr: Apply, nme), tpts), args) =>
val tree1 = cpy.Apply(tree)(cpy.TypeApply(ta)(cpy.Select(sel)(transform(expr), nme), tpts), args)
dotc.transform.BetaReduce(tree1).withSpan(tree.span)
case _ =>
dotc.transform.BetaReduce(tree).withSpan(tree.span)
}
}.transform(tree)
if tree1 == tree then None else Some(tree1)
end Term
given TermMethods: TermMethods with
extension (self: Term)
def seal: scala.quoted.Expr[Any] =
if self.isExpr then new ExprImpl(self, SpliceScope.getCurrent)
else throw new Exception("Cannot seal a partially applied Term. Try eta-expanding the term first.")
def sealOpt: Option[scala.quoted.Expr[Any]] =
if self.isExpr then Some(new ExprImpl(self, SpliceScope.getCurrent))
else None
def tpe: TypeRepr = self.tpe.widenSkolem
def underlyingArgument: Term = new tpd.TreeOps(self).underlyingArgument
def underlying: Term = new tpd.TreeOps(self).underlying
def etaExpand(owner: Symbol): Term = self.tpe.widen match {
case mtpe: Types.MethodType if !mtpe.isParamDependent =>
val closureResType = mtpe.resType match {
case t: Types.MethodType => t.toFunctionType(isJava = self.symbol.is(dotc.core.Flags.JavaDefined))
case t => t
}
val closureTpe = Types.MethodType(mtpe.paramNames, mtpe.paramInfos, closureResType)
val closureMethod = dotc.core.Symbols.newAnonFun(owner, closureTpe)
tpd.Closure(closureMethod, tss => new tpd.TreeOps(self).appliedToTermArgs(tss.head).etaExpand(closureMethod))
case _ => self
}
def appliedTo(arg: Term): Term =
self.appliedToArgs(arg :: Nil)
def appliedTo(arg: Term, args: Term*): Term =
self.appliedToArgs(arg :: args.toList)
def appliedToArgs(args: List[Term]): Apply =
Apply(self, args)
def appliedToArgss(argss: List[List[Term]]): Term =
argss.foldLeft(self: Term)(Apply(_, _))
def appliedToNone: Apply =
self.appliedToArgs(Nil)
def appliedToType(targ: TypeRepr): Term =
self.appliedToTypes(targ :: Nil)
def appliedToTypes(targs: List[TypeRepr]): Term =
self.appliedToTypeTrees(targs map (Inferred(_)))
def appliedToTypeTrees(targs: List[TypeTree]): Term =
if (targs.isEmpty) self else TypeApply(self, targs)
def select(sym: Symbol): Select = Select(self, sym)
end extension
end TermMethods
type Ref = tpd.RefTree
object RefTypeTest extends TypeTest[Tree, Ref]:
def unapply(x: Tree): Option[Ref & x.type] = x match
case x: (tpd.RefTree & x.type) if x.isTerm => Some(x)
case _ => None
end RefTypeTest
object Ref extends RefModule:
def term(tp: TermRef): Ref =
withDefaultPos(tpd.ref(tp).asInstanceOf[tpd.RefTree])
def apply(sym: Symbol): Ref =
assert(sym.isTerm, s"expected a term symbol, but received $sym")
val refTree = tpd.ref(sym) match
case t @ tpd.This(ident) => // not a RefTree, so we need to work around this - issue #19732
// ident in `This` can be a TypeIdent of sym, so we manually prepare the ref here,
// knowing that the owner is actually `This`.
val term = Select(This(sym.owner), sym)
term.asInstanceOf[tpd.RefTree]
case other => other.asInstanceOf[tpd.RefTree]
withDefaultPos(refTree)
end Ref
type Ident = tpd.Ident
object IdentTypeTest extends TypeTest[Tree, Ident]:
def unapply(x: Tree): Option[Ident & x.type] = x match
case x: (tpd.Ident & x.type) if x.isTerm => Some(x)
case _ => None
end IdentTypeTest
object Ident extends IdentModule:
def apply(tmref: TermRef): Term =
withDefaultPos(tpd.ref(tmref).asInstanceOf[Term])
def copy(original: Tree)(name: String): Ident =
tpd.cpy.Ident(original)(name.toTermName)
def unapply(tree: Ident): Some[String] =
Some(tree.name.toString)
end Ident
given IdentMethods: IdentMethods with
extension (self: Ident)
def name: String = self.name.toString
end extension
end IdentMethods
type Wildcard = tpd.Ident
object WildcardTypeTest extends TypeTest[Tree, Wildcard]:
def unapply(x: Tree): Option[Wildcard & x.type] = x match
case x: (tpd.Ident & x.type) if x.name == nme.WILDCARD => Some(x)
case _ => None
end WildcardTypeTest
object Wildcard extends WildcardModule:
def apply(): Wildcard =
withDefaultPos(untpd.Ident(nme.WILDCARD).withType(dotc.core.Symbols.defn.AnyType))
def unapply(pattern: Wildcard): true = true
end Wildcard
type Select = tpd.Select
object SelectTypeTest extends TypeTest[Tree, Select]:
def unapply(x: Tree): Option[Select & x.type] = x match
case x: (tpd.Select & x.type) if x.isTerm => Some(x)
case _ => None
end SelectTypeTest
object Select extends SelectModule:
def apply(qualifier: Term, symbol: Symbol): Select =
withDefaultPos(tpd.Select(qualifier, Types.TermRef(qualifier.tpe, symbol)))
def unique(qualifier: Term, name: String): Select =
val denot = qualifier.tpe.member(name.toTermName)
assert(!denot.isOverloaded, s"The symbol `$name` is overloaded. The method Select.unique can only be used for non-overloaded symbols.")
withDefaultPos(tpd.Select(qualifier, name.toTermName))
def overloaded(qualifier: Term, name: String, targs: List[TypeRepr], args: List[Term]): Term =
withDefaultPos(tpd.applyOverloaded(qualifier, name.toTermName, args, targs, Types.WildcardType))
def overloaded(qualifier: Term, name: String, targs: List[TypeRepr], args: List[Term], returnType: TypeRepr): Term =
withDefaultPos(tpd.applyOverloaded(qualifier, name.toTermName, args, targs, returnType))
def copy(original: Tree)(qualifier: Term, name: String): Select =
tpd.cpy.Select(original)(qualifier, name.toTermName)
def unapply(x: Select): (Term, String) =
(x.qualifier, x.name.toString)
end Select
given SelectMethods: SelectMethods with
extension (self: Select)
def qualifier: Term = self.qualifier
def name: String = self.name.toString
def signature: Option[Signature] =
if self.symbol.signature == dotc.core.Signature.NotAMethod then None
else Some(self.symbol.signature)
end extension
end SelectMethods
type Literal = tpd.Literal
object LiteralTypeTest extends TypeTest[Tree, Literal]:
def unapply(x: Tree): Option[Literal & x.type] = x match
case x: (tpd.Literal & x.type) => Some(x)
case _ => None
end LiteralTypeTest
object Literal extends LiteralModule:
def apply(constant: Constant): Literal =
withDefaultPos(tpd.Literal(constant))
def copy(original: Tree)(constant: Constant): Literal =
tpd.cpy.Literal(original)(constant)
def unapply(x: Literal): Some[Constant] =
Some(x.constant)
end Literal
given LiteralMethods: LiteralMethods with
extension (self: Literal)
def constant: Constant = self.const
end extension
end LiteralMethods
type This = tpd.This
object ThisTypeTest extends TypeTest[Tree, This]:
def unapply(x: Tree): Option[This & x.type] = x match
case x: (tpd.This & x.type) => Some(x)
case _ => None
end ThisTypeTest
object This extends ThisModule:
def apply(cls: Symbol): This =
withDefaultPos(tpd.This(cls.asClass))
def copy(original: Tree)(qual: Option[String]): This =
tpd.cpy.This(original)(qual.map(x => untpd.Ident(x.toTypeName)).getOrElse(untpd.EmptyTypeIdent))
def unapply(x: This): Some[Option[String]] =
Some(optional(x.qual).map(_.name.toString))
end This
given ThisMethods: ThisMethods with
extension (self: This)
def id: Option[String] = optional(self.qual).map(_.name.toString)
end extension
end ThisMethods
type New = tpd.New
object NewTypeTest extends TypeTest[Tree, New]:
def unapply(x: Tree): Option[New & x.type] = x match
case x: (tpd.New & x.type) => Some(x)
case _ => None
end NewTypeTest
object New extends NewModule:
def apply(tpt: TypeTree): New =
withDefaultPos(tpd.New(tpt))
def copy(original: Tree)(tpt: TypeTree): New =
tpd.cpy.New(original)(tpt)
def unapply(x: New): Some[TypeTree] = Some(x.tpt)
end New
given NewMethods: NewMethods with
extension (self: New)
def tpt: TypeTree = self.tpt
end extension
end NewMethods
type NamedArg = tpd.NamedArg
object NamedArgTypeTest extends TypeTest[Tree, NamedArg]:
def unapply(x: Tree): Option[NamedArg & x.type] = x match
case x: (tpd.NamedArg & x.type) if x.name.isInstanceOf[dotc.core.Names.TermName] => Some(x) // TODO: Now, the name should alwas be a term name
case _ => None
end NamedArgTypeTest
object NamedArg extends NamedArgModule:
def apply(name: String, arg: Term): NamedArg =
withDefaultPos(tpd.NamedArg(name.toTermName, xCheckMacroValidExpr(arg)))
def copy(original: Tree)(name: String, arg: Term): NamedArg =
tpd.cpy.NamedArg(original)(name.toTermName, xCheckMacroValidExpr(arg))
def unapply(x: NamedArg): (String, Term) =
(x.name.toString, x.value)
end NamedArg
given NamedArgMethods: NamedArgMethods with
extension (self: NamedArg)
def name: String = self.name.toString
def value: Term = self.arg
end extension
end NamedArgMethods
type Apply = tpd.Apply | tpd.Quote | tpd.Splice
object ApplyTypeTest extends TypeTest[Tree, Apply]:
def unapply(x: Tree): Option[Apply & x.type] = x match
case x: (tpd.Apply & x.type) => Some(x)
case x: (tpd.Quote & x.type) => Some(x) // TODO expose Quote AST in Quotes
case x: (tpd.Splice & x.type) => Some(x) // TODO expose Splice AST in Quotes
case _ => None
end ApplyTypeTest
object Apply extends ApplyModule:
def apply(fun: Term, args: List[Term]): Apply =
xCheckMacroAssert(fun.tpe.widen.isInstanceOf[dotc.core.Types.MethodType], "Expected `fun.tpe` to widen into a `MethodType`")
xCheckMacroValidExprs(args)
withDefaultPos(tpd.Apply(fun, args))
def copy(original: Tree)(fun: Term, args: List[Term]): Apply =
xCheckMacroAssert(fun.tpe.widen.isInstanceOf[dotc.core.Types.MethodType], "Expected `fun.tpe` to widen into a `MethodType`")
xCheckMacroValidExprs(args)
tpd.cpy.Apply(original)(fun, args)
def unapply(x: Apply): (Term, List[Term]) =
(x.fun, x.args)
end Apply
given ApplyMethods: ApplyMethods with
extension (self: Apply)
def fun: Term = self match
case self: tpd.Apply => self.fun
case self: tpd.Quote => // TODO expose Quote AST in Quotes
import dotty.tools.dotc.ast.tpd.TreeOps
tpd.ref(dotc.core.Symbols.defn.QuotedRuntime_exprQuote)
.appliedToType(self.bodyType)
.withSpan(self.span)
case self: tpd.Splice => // TODO expose Splice AST in Quotes
import dotty.tools.dotc.ast.tpd.TreeOps
tpd.ref(dotc.core.Symbols.defn.QuotedRuntime_exprSplice)
.appliedToType(self.tpe)
.withSpan(self.span)
def args: List[Term] = self match
case self: tpd.Apply => self.args
case self: tpd.Quote => List(self.body) // TODO expose Quote AST in Quotes
case self: tpd.Splice => List(self.expr) // TODO expose Splice AST in Quotes
end extension
end ApplyMethods
type TypeApply = tpd.TypeApply
object TypeApplyTypeTest extends TypeTest[Tree, TypeApply]:
def unapply(x: Tree): Option[TypeApply & x.type] = x match
case x: (tpd.TypeApply & x.type) => Some(x)
case _ => None
end TypeApplyTypeTest
object TypeApply extends TypeApplyModule:
def apply(fun: Term, args: List[TypeTree]): TypeApply =
xCheckMacroAssert(fun.tpe.widen.isInstanceOf[dotc.core.Types.PolyType], "Expected `fun.tpe` to widen into a `PolyType`")
withDefaultPos(tpd.TypeApply(fun, args))
def copy(original: Tree)(fun: Term, args: List[TypeTree]): TypeApply =
xCheckMacroAssert(fun.tpe.widen.isInstanceOf[dotc.core.Types.PolyType], "Expected `fun.tpe` to widen into a `PolyType`")
tpd.cpy.TypeApply(original)(fun, args)
def unapply(x: TypeApply): (Term, List[TypeTree]) =
(x.fun, x.args)
end TypeApply
given TypeApplyMethods: TypeApplyMethods with
extension (self: TypeApply)
def fun: Term = self.fun
def args: List[TypeTree] = self.args
end extension
end TypeApplyMethods
type Super = tpd.Super
object SuperTypeTest extends TypeTest[Tree, Super]:
def unapply(x: Tree): Option[Super & x.type] = x match
case x: (tpd.Super & x.type) => Some(x)
case _ => None
end SuperTypeTest
object Super extends SuperModule:
def apply(qual: Term, mix: Option[String]): Super =
withDefaultPos(tpd.Super(qual, mix.map(x => untpd.Ident(x.toTypeName)).getOrElse(untpd.EmptyTypeIdent), dotc.core.Symbols.NoSymbol))
def copy(original: Tree)(qual: Term, mix: Option[String]): Super =
tpd.cpy.Super(original)(qual, mix.map(x => untpd.Ident(x.toTypeName)).getOrElse(untpd.EmptyTypeIdent))
def unapply(x: Super): (Term, Option[String]) =
(x.qualifier, x.id)
end Super
given SuperMethods: SuperMethods with
extension (self: Super)
def qualifier: Term = self.qual
def id: Option[String] = optional(self.mix).map(_.name.toString)
def idPos: Position = self.mix.sourcePos
end extension
end SuperMethods
type Typed = tpd.Typed
object TypedTypeTest extends TypeTest[Tree, Typed]:
def unapply(x: Tree): Option[Typed & x.type] = x match
case x: (tpd.Typed & x.type) =>
x.expr match
case TermTypeTest(_) => Some(x)
case _ => None
case _ => None
end TypedTypeTest
object Typed extends TypedModule:
def apply(expr: Term, tpt: TypeTree): Typed =
withDefaultPos(tpd.Typed(xCheckMacroValidExpr(expr), tpt))
def copy(original: Tree)(expr: Term, tpt: TypeTree): Typed =
tpd.cpy.Typed(original)(xCheckMacroValidExpr(expr), tpt)
def unapply(x: Typed): (Term, TypeTree) =
(x.expr, x.tpt)
end Typed
given TypedMethods: TypedMethods with
extension (self: Typed)
def expr: Term = self.expr
def tpt: TypeTree = self.tpt
end extension
end TypedMethods
type TypedOrTest = tpd.Typed
object TypedOrTestTypeTest extends TypeTest[Tree, TypedOrTest]:
def unapply(x: Tree): Option[TypedOrTest & x.type] = x match
case x: (tpd.Typed & x.type) => Some(x)
case _ => None
end TypedOrTestTypeTest
object TypedOrTest extends TypedOrTestModule:
def apply(expr: Term, tpt: TypeTree): Typed =
withDefaultPos(tpd.Typed(xCheckMacroValidExpr(expr), tpt))
def copy(original: Tree)(expr: Term, tpt: TypeTree): Typed =
tpd.cpy.Typed(original)(xCheckMacroValidExpr(expr), tpt)
def unapply(x: Typed): (Term, TypeTree) =
(x.expr, x.tpt)
end TypedOrTest
given TypedOrTestMethods: TypedOrTestMethods with
extension (self: Typed)
def tree: Tree = self.expr
def tpt: TypeTree = self.tpt
end extension
end TypedOrTestMethods
type Assign = tpd.Assign
object AssignTypeTest extends TypeTest[Tree, Assign]:
def unapply(x: Tree): Option[Assign & x.type] = x match
case x: (tpd.Assign & x.type) => Some(x)
case _ => None
end AssignTypeTest
object Assign extends AssignModule:
def apply(lhs: Term, rhs: Term): Assign =
withDefaultPos(tpd.Assign(lhs, xCheckMacroValidExpr(rhs)))
def copy(original: Tree)(lhs: Term, rhs: Term): Assign =
tpd.cpy.Assign(original)(lhs, xCheckMacroValidExpr(rhs))
def unapply(x: Assign): (Term, Term) =
(x.lhs, x.rhs)
end Assign
given AssignMethods: AssignMethods with
extension (self: Assign)
def lhs: Term = self.lhs
def rhs: Term = self.rhs
end extension
end AssignMethods
type Block = tpd.Block
object BlockTypeTest extends TypeTest[Tree, Block]:
def unapply(x: Tree): Option[Block & x.type] = x match
case x: (tpd.Block & x.type) => Some(x)
case _ => None
end BlockTypeTest
object Block extends BlockModule:
def apply(stats: List[Statement], expr: Term): Block =
xCheckMacroBlockOwners(withDefaultPos(tpd.Block(stats, xCheckMacroValidExpr(expr))))
def copy(original: Tree)(stats: List[Statement], expr: Term): Block =
xCheckMacroBlockOwners(tpd.cpy.Block(original)(stats, expr))
def unapply(x: Block): (List[Statement], Term) =
(x.statements, x.expr)
end Block
given BlockMethods: BlockMethods with
extension (self: Block)
def statements: List[Statement] = self.stats
def expr: Term = self.expr
end extension
end BlockMethods
type Closure = tpd.Closure
object ClosureTypeTest extends TypeTest[Tree, Closure]:
def unapply(x: Tree): Option[Closure & x.type] = x match
case x: (tpd.Closure & x.type) => Some(x)
case _ => None
end ClosureTypeTest
object Closure extends ClosureModule:
def apply(meth: Term, tpe: Option[TypeRepr]): Closure =
withDefaultPos(tpd.Closure(Nil, meth, tpe.map(tpd.TypeTree(_)).getOrElse(tpd.EmptyTree)))
def copy(original: Tree)(meth: Tree, tpe: Option[TypeRepr]): Closure =
tpd.cpy.Closure(original)(Nil, meth, tpe.map(tpd.TypeTree(_)).getOrElse(tpd.EmptyTree))
def unapply(x: Closure): (Term, Option[TypeRepr]) =
(x.meth, x.tpeOpt)
end Closure
given ClosureMethods: ClosureMethods with
extension (self: Closure)
def meth: Term = self.meth
def tpeOpt: Option[TypeRepr] = optional(self.tpt).map(_.tpe)
end extension
end ClosureMethods
object Lambda extends LambdaModule:
def apply(owner: Symbol, tpe: MethodType, rhsFn: (Symbol, List[Tree]) => Tree): Block =
val meth = dotc.core.Symbols.newAnonFun(owner, tpe)
withDefaultPos(tpd.Closure(meth, tss => xCheckedMacroOwners(xCheckMacroValidExpr(rhsFn(meth, tss.head.map(withDefaultPos))), meth)))
def unapply(tree: Block): Option[(List[ValDef], Term)] = tree match {
case Block((ddef @ DefDef(_, tpd.ValDefs(params) :: Nil, _, Some(body))) :: Nil, Closure(meth, _))
if ddef.symbol == meth.symbol =>
Some((params, body))
case _ => None
}
end Lambda
type If = tpd.If
object IfTypeTest extends TypeTest[Tree, If]:
def unapply(x: Tree): Option[If & x.type] = x match
case x: (tpd.If & x.type) => Some(x)
case _ => None
end IfTypeTest
object If extends IfModule:
def apply(cond: Term, thenp: Term, elsep: Term): If =
withDefaultPos(tpd.If(xCheckMacroValidExpr(cond), xCheckMacroValidExpr(thenp), xCheckMacroValidExpr(elsep)))
def copy(original: Tree)(cond: Term, thenp: Term, elsep: Term): If =
tpd.cpy.If(original)(xCheckMacroValidExpr(cond), xCheckMacroValidExpr(thenp), xCheckMacroValidExpr(elsep))
def unapply(tree: If): (Term, Term, Term) =
(tree.cond, tree.thenp, tree.elsep)
end If
given IfMethods: IfMethods with
extension (self: If)
def cond: Term = self.cond
def thenp: Term = self.thenp
def elsep: Term = self.elsep
def isInline: Boolean = self.isInline
end extension
end IfMethods
type Match = tpd.Match
object MatchTypeTest extends TypeTest[Tree, Match]:
def unapply(x: Tree): Option[Match & x.type] = x match
case x: (tpd.Match & x.type) if !x.selector.isEmpty => Some(x)
case _ => None
end MatchTypeTest
object Match extends MatchModule:
def apply(selector: Term, cases: List[CaseDef]): Match =
withDefaultPos(tpd.Match(xCheckMacroValidExpr(selector), cases))
def copy(original: Tree)(selector: Term, cases: List[CaseDef]): Match =
tpd.cpy.Match(original)(xCheckMacroValidExpr(selector), cases)
def unapply(x: Match): (Term, List[CaseDef]) =
(x.scrutinee, x.cases)
end Match
given MatchMethods: MatchMethods with
extension (self: Match)
def scrutinee: Term = self.selector
def cases: List[CaseDef] = self.cases
def isInline: Boolean = self.isInline
end extension
end MatchMethods
type SummonFrom = tpd.Match
object SummonFromTypeTest extends TypeTest[Tree, SummonFrom]:
def unapply(x: Tree): Option[SummonFrom & x.type] = x match
case x: (tpd.Match & x.type) if x.selector.isEmpty => Some(x)
case _ => None
end SummonFromTypeTest
object SummonFrom extends SummonFromModule:
def apply(cases: List[CaseDef]): SummonFrom =
withDefaultPos(tpd.Match(tpd.EmptyTree, cases))
def copy(original: Tree)(cases: List[CaseDef]): SummonFrom =
tpd.cpy.Match(original)(tpd.EmptyTree, cases)
def unapply(x: SummonFrom): Some[List[CaseDef]] =
Some(x.cases)
end SummonFrom
given SummonFromMethods: SummonFromMethods with
extension (self: SummonFrom)
def cases: List[CaseDef] = self.cases
end extension
end SummonFromMethods
type Try = tpd.Try
object TryTypeTest extends TypeTest[Tree, Try]:
def unapply(x: Tree): Option[Try & x.type] = x match
case x: (tpd.Try & x.type) => Some(x)
case _ => None
end TryTypeTest
object Try extends TryModule:
def apply(expr: Term, cases: List[CaseDef], finalizer: Option[Term]): Try =
withDefaultPos(tpd.Try(xCheckMacroValidExpr(expr), cases, finalizer.getOrElse(tpd.EmptyTree)))
def copy(original: Tree)(expr: Term, cases: List[CaseDef], finalizer: Option[Term]): Try =
tpd.cpy.Try(original)(xCheckMacroValidExpr(expr), cases, finalizer.getOrElse(tpd.EmptyTree))
def unapply(x: Try): (Term, List[CaseDef], Option[Term]) =
(x.body, x.cases, optional(x.finalizer))
end Try
given TryMethods: TryMethods with
extension (self: Try)
def body: Term = self.expr
def cases: List[CaseDef] = self.cases
def finalizer: Option[Term] = optional(self.finalizer)
end extension
end TryMethods
type Return = tpd.Return
object ReturnTypeTest extends TypeTest[Tree, Return]:
def unapply(x: Tree): Option[Return & x.type] = x match
case x: (tpd.Return & x.type) => Some(x)
case _ => None
end ReturnTypeTest
object Return extends ReturnModule:
def apply(expr: Term, from: Symbol): Return =
withDefaultPos(tpd.Return(xCheckMacroValidExpr(expr), from))
def copy(original: Tree)(expr: Term, from: Symbol): Return =
tpd.cpy.Return(original)(xCheckMacroValidExpr(expr), tpd.ref(from))
def unapply(x: Return): (Term, Symbol) =
(x.expr, x.from.symbol)
end Return