-
Notifications
You must be signed in to change notification settings - Fork 1k
/
RefinedPrinter.scala
992 lines (901 loc) · 40.3 KB
/
RefinedPrinter.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
package dotty.tools.dotc
package printing
import core._
import Texts._
import Types._
import Flags._
import Names._
import Symbols._
import NameOps._
import TypeErasure.ErasedValueType
import Contexts._
import Annotations.Annotation
import Denotations._
import SymDenotations._
import StdNames.{nme, tpnme}
import ast.{Trees, untpd}
import typer.{Implicits, Namer, Applications}
import typer.ProtoTypes._
import Trees._
import TypeApplications._
import Decorators._
import scala.internal.Chars.isOperatorPart
import transform.TypeUtils._
import transform.SymUtils._
import language.implicitConversions
import dotty.tools.dotc.util.{NameTransformer, SourcePosition}
import dotty.tools.dotc.ast.untpd.{MemberDef, Modifiers, PackageDef, RefTree, Template, TypeDef, ValOrDefDef}
class RefinedPrinter(_ctx: Context) extends PlainPrinter(_ctx) {
/** A stack of enclosing DefDef, TypeDef, or ClassDef, or ModuleDefs nodes */
private var enclosingDef: untpd.Tree = untpd.EmptyTree
private var myCtx: Context = super.curCtx
private var printPos = ctx.settings.YprintPos.value
private val printLines = ctx.settings.printLines.value
override protected def curCtx: Context = myCtx
def withEnclosingDef(enclDef: Tree[? >: Untyped])(op: => Text): Text = {
val savedCtx = myCtx
if (enclDef.hasType && enclDef.symbol.exists)
myCtx = ctx.withOwner(enclDef.symbol)
val savedDef = enclosingDef
enclosingDef = enclDef
try op finally {
myCtx = savedCtx
enclosingDef = savedDef
}
}
def inPattern(op: => Text): Text = {
val savedCtx = myCtx
myCtx = ctx.addMode(Mode.Pattern)
try op finally myCtx = savedCtx
}
def withoutPos(op: => Text): Text = {
val savedPrintPos = printPos
printPos = false
try op finally printPos = savedPrintPos
}
protected def enclDefIsClass: Boolean = enclosingDef match {
case owner: TypeDef => owner.isClassDef
case owner: untpd.ModuleDef => true
case _ => false
}
protected def PrintableFlags(isType: Boolean): FlagSet = {
val fs =
if (isType) TypeSourceModifierFlags | Module | Local // DOTTY problem: cannot merge these two statements
else TermSourceModifierFlags | Module | Local
fs.toCommonFlags
}
override def nameString(name: Name): String =
if ctx.settings.YdebugNames.value
then name.debugString
else super.nameString(name)
override protected def simpleNameString(sym: Symbol): String =
nameString(if (ctx.property(XprintMode).isEmpty) sym.initial.name else sym.name)
override def fullNameString(sym: Symbol): String =
if (isEmptyPrefix(sym.maybeOwner)) nameString(sym)
else super.fullNameString(sym)
override protected def fullNameOwner(sym: Symbol): Symbol = {
val owner = super.fullNameOwner(sym)
if (owner.is(ModuleClass)) owner.sourceModule else owner
}
override def toTextRef(tp: SingletonType): Text = controlled {
tp match {
case tp: ThisType if !printDebug =>
if (tp.cls.isAnonymousClass) keywordStr("this")
if (tp.cls.is(ModuleClass)) fullNameString(tp.cls.sourceModule)
else super.toTextRef(tp)
case _ =>
super.toTextRef(tp)
}
}
override def toTextPrefix(tp: Type): Text = controlled {
def isOmittable(sym: Symbol) =
if (printDebug) false
else if (homogenizedView) isEmptyPrefix(sym) // drop <root> and anonymous classes, but not scala, Predef.
else isOmittablePrefix(sym)
tp match {
case tp: ThisType if isOmittable(tp.cls) =>
""
case tp @ TermRef(pre, _) =>
val sym = tp.symbol
if (sym.isPackageObject && !homogenizedView) toTextPrefix(pre)
else if (isOmittable(sym)) ""
else super.toTextPrefix(tp)
case _ => super.toTextPrefix(tp)
}
}
override protected def toTextParents(parents: List[Type]): Text =
Text(parents.map(toTextLocal).map(typeText), keywordStr(" with "))
override protected def refinementNameString(tp: RefinedType): String =
if (tp.parent.isInstanceOf[WildcardType] || tp.refinedName == nme.WILDCARD)
super.refinementNameString(tp)
else {
val tsym = tp.parent.member(tp.refinedName).symbol
if (!tsym.exists) super.refinementNameString(tp)
else simpleNameString(tsym)
}
private def arrow(isGiven: Boolean): String =
if isGiven then "?=>" else "=>"
override def toText(tp: Type): Text = controlled {
def toTextTuple(args: List[Type]): Text =
"(" ~ argsText(args) ~ ")"
def toTextFunction(args: List[Type], isGiven: Boolean, isErased: Boolean): Text =
changePrec(GlobalPrec) {
val argStr: Text =
if args.length == 2
&& !defn.isTupleType(args.head)
&& !isGiven && !isErased
then
atPrec(InfixPrec) { argText(args.head) }
else
"("
~ keywordText("erased ").provided(isErased)
~ argsText(args.init)
~ ")"
argStr ~ " " ~ arrow(isGiven) ~ " " ~ argText(args.last)
}
def toTextDependentFunction(appType: MethodType): Text =
"("
~ keywordText("erased ").provided(appType.isErasedMethod)
~ paramsText(appType)
~ ") "
~ arrow(appType.isImplicitMethod)
~ " "
~ toText(appType.resultType)
def isInfixType(tp: Type): Boolean = tp match {
case AppliedType(tycon, args) =>
args.length == 2 &&
tycon.typeSymbol.getAnnotation(defn.ShowAsInfixAnnot).map(_.argumentConstant(0).forall(_.booleanValue))
.getOrElse(!Character.isUnicodeIdentifierStart(tycon.typeSymbol.name.toString.head))
case _ => false
}
def tyconName(tp: Type): Name = tp.typeSymbol.name
def checkAssocMismatch(tp: Type, isRightAssoc: Boolean) = tp match {
case AppliedType(tycon, _) => isInfixType(tp) && tyconName(tycon).endsWith(":") != isRightAssoc
case AndType(_, _) => isRightAssoc
case OrType(_, _) => isRightAssoc
case _ => false
}
def toTextInfixType(opName: Name, l: Type, r: Type)(op: => Text): Text = {
val isRightAssoc = opName.endsWith(":")
val opPrec = parsing.precedence(opName)
changePrec(opPrec) {
val leftPrec = if (isRightAssoc || checkAssocMismatch(l, isRightAssoc)) opPrec + 1 else opPrec
val rightPrec = if (!isRightAssoc || checkAssocMismatch(r, isRightAssoc)) opPrec + 1 else opPrec
atPrec(leftPrec) { argText(l) } ~ " " ~ op ~ " " ~ atPrec(rightPrec) { argText(r) }
}
}
homogenize(tp) match {
case tp @ AppliedType(tycon, args) =>
val cls = tycon.typeSymbol
if (tycon.isRepeatedParam) toTextLocal(args.head) ~ "*"
else if (defn.isFunctionClass(cls)) toTextFunction(args, cls.name.isContextFunction, cls.name.isErasedFunction)
else if (tp.tupleArity >= 2 && !printDebug) toTextTuple(tp.tupleElementTypes)
else if (isInfixType(tp)) {
val l :: r :: Nil = args
val opName = tyconName(tycon)
toTextInfixType(tyconName(tycon), l, r) { simpleNameString(tycon.typeSymbol) }
}
else super.toText(tp)
// Since RefinedPrinter, unlike PlainPrinter, can output right-associative type-operators, we must override handling
// of AndType and OrType to account for associativity
case AndType(tp1, tp2) =>
toTextInfixType(tpnme.raw.AMP, tp1, tp2) { toText(tpnme.raw.AMP) }
case OrType(tp1, tp2) =>
toTextInfixType(tpnme.raw.BAR, tp1, tp2) { toText(tpnme.raw.BAR) }
case EtaExpansion(tycon) if !printDebug =>
toText(tycon)
case tp: RefinedType if defn.isFunctionType(tp) && !printDebug =>
toTextDependentFunction(tp.refinedInfo.asInstanceOf[MethodType])
case tp: TypeRef =>
if (tp.symbol.isAnonymousClass && !showUniqueIds)
toText(tp.info)
else if (tp.symbol.is(Param))
tp.prefix match {
case pre: ThisType if pre.cls == tp.symbol.owner =>
nameString(tp.symbol)
case _ => super.toText(tp)
}
else super.toText(tp)
case ErasedValueType(tycon, underlying) =>
"ErasedValueType(" ~ toText(tycon) ~ ", " ~ toText(underlying) ~ ")"
case tp: ClassInfo =>
toTextParents(tp.parents) ~~ "{...}"
case JavaArrayType(elemtp) =>
toText(elemtp) ~ "[]"
case tp: SelectionProto =>
"?{ " ~ toText(tp.name) ~
(Str(" ") provided !tp.name.toSimpleName.last.isLetterOrDigit) ~
": " ~ toText(tp.memberProto) ~ " }"
case tp: ViewProto =>
toText(tp.argType) ~ " ?=>? " ~ toText(tp.resultType)
case tp @ FunProto(args, resultType) =>
val argsText = args match {
case dummyTreeOfType(tp) :: Nil if !(tp isRef defn.NullClass) => "null: " ~ toText(tp)
case _ => toTextGlobal(args, ", ")
}
"[applied to ("
~ keywordText("using ").provided(tp.isContextualMethod)
~ keywordText("erased ").provided(tp.isErasedMethod)
~ argsText
~ ") returning "
~ toText(resultType)
~ "]"
case IgnoredProto(ignored) =>
"?" ~ (("(ignored: " ~ toText(ignored) ~ ")") provided printDebug)
case tp @ PolyProto(targs, resType) =>
"[applied to [" ~ toTextGlobal(targs, ", ") ~ "] returning " ~ toText(resType)
case _ =>
super.toText(tp)
}
}
protected def exprToText(tp: ExprType): Text =
"=> " ~ toText(tp.resType)
protected def blockToText[T >: Untyped](block: Block[T]): Text =
blockText(block.stats :+ block.expr)
protected def blockText[T >: Untyped](trees: List[Tree[T]]): Text =
("{" ~ toText(trees, "\n") ~ "}").close
protected def typeApplyText[T >: Untyped](tree: TypeApply[T]): Text = {
val funText = toTextLocal(tree.fun)
tree.fun match {
case Select(New(tpt), nme.CONSTRUCTOR) if tpt.typeOpt.dealias.isInstanceOf[AppliedType] =>
funText // type was already printed by toText(new)
case _ =>
funText ~ "[" ~ toTextGlobal(tree.args, ", ") ~ "]"
}
}
protected def toTextCore[T >: Untyped](tree: Tree[T]): Text = {
import untpd._
def isLocalThis(tree: Tree) = tree.typeOpt match {
case tp: ThisType => tp.cls == ctx.owner.enclosingClass
case _ => false
}
def optDotPrefix(tree: This) = optText(tree.qual)(_ ~ ".") provided !isLocalThis(tree)
def caseBlockText(tree: Tree): Text = tree match {
case Block(stats, expr) => toText(stats :+ expr, "\n")
case expr => toText(expr)
}
// Dotty deviation: called with an untpd.Tree, so cannot be a untpd.Tree[T] (seems to be a Scala2 problem to allow this)
// More deviations marked below as // DD
def enumText(tree: untpd.Tree) = tree match { // DD
case _: untpd.GenFrom | _: untpd.GenAlias => toText(tree)
case _ => keywordStr("if ") ~ toText(tree)
}
def forText(enums: List[untpd.Tree], expr: untpd.Tree, sep: String): Text = // DD
changePrec(GlobalPrec) { keywordStr("for ") ~ Text(enums map enumText, "; ") ~ sep ~ toText(expr) }
def cxBoundToText(bound: untpd.Tree): Text = bound match { // DD
case AppliedTypeTree(tpt, _) => " : " ~ toText(tpt)
case untpd.Function(_, tpt) => " <% " ~ toText(tpt)
}
def varianceText(mods: untpd.Modifiers) =
if (mods.is(Covariant)) "+"
else if (mods.is(Contravariant)) "-"
else ""
def argText(arg: Tree): Text = arg match {
case arg: TypeBoundsTree => "?" ~ toTextGlobal(arg)
case arg: TypeTree =>
arg.typeOpt match {
case tp: TypeBounds => "?" ~ toTextGlobal(arg)
case _ => toTextGlobal(arg)
}
case _ => toTextGlobal(arg)
}
def dropBlock(tree: Tree): Tree = tree match {
case Block(Nil, expr) => expr
case _ => tree
}
def importText(expr: Tree, selectors: List[untpd.ImportSelector]) =
def selectorText(sel: untpd.ImportSelector): Text =
val id: Text =
if sel.isGiven then keywordText("given") else toText(sel.imported)
val rename: Text =
if sel.renamed.isEmpty then "" else Str(" => ") ~ toText(sel.renamed)
val bound: Text =
if sel.bound.isEmpty then ""
else if sel.isGiven then Str(" ") ~ toText(sel.bound)
else Str(" : ") ~ toText(sel.bound)
id ~ rename ~ bound
val selectorsText: Text = selectors match
case (sel @ untpd.ImportSelector(name, EmptyTree, EmptyTree)) :: Nil =>
selectorText(sel)
case _ =>
"{" ~ Text(selectors.map(selectorText), ", ") ~ "}"
toTextLocal(expr) ~ "." ~ selectorsText
tree match {
case id: Trees.SearchFailureIdent[?] =>
tree.typeOpt match {
case reason: Implicits.SearchFailureType =>
toText(id.name)
~ ("summon[" ~ toText(reason.clarify(reason.expectedType)) ~ "]").close
case _ =>
toText(id.name)
}
case id @ Ident(name) =>
val txt = tree.typeOpt match {
case tp: NamedType if name != nme.WILDCARD =>
val pre = if (tp.symbol.is(JavaStatic)) tp.prefix.widen else tp.prefix
toTextPrefix(pre) ~ withPos(selectionString(tp), tree.sourcePos)
case _ =>
toText(name)
}
if (isBackquoted(tree) && !homogenizedView) "`" ~ toText(name) ~ "`"
else if (name.isTypeName) typeText(txt)
else txt
case tree @ Select(qual, name) =>
if (!printDebug && tree.hasType && tree.symbol.isTypeSplice) typeText("${") ~ toTextLocal(qual) ~ typeText("}")
else if (qual.isType) toTextLocal(qual) ~ "#" ~ typeText(toText(name))
else toTextLocal(qual) ~ ("." ~ nameIdText(tree) provided (name != nme.CONSTRUCTOR || printDebug))
case tree: This =>
optDotPrefix(tree) ~ keywordStr("this") ~ idText(tree)
case Super(qual: This, mix) =>
optDotPrefix(qual) ~ keywordStr("super") ~ optText(mix)("[" ~ _ ~ "]")
case app @ Apply(fun, args) =>
if (fun.hasType && fun.symbol == defn.throwMethod)
changePrec (GlobalPrec) {
keywordStr("throw ") ~ toText(args.head)
}
else if (!printDebug && fun.hasType && fun.symbol == defn.InternalQuoted_exprQuote)
keywordStr("'{") ~ toTextGlobal(args, ", ") ~ keywordStr("}")
else if (!printDebug && fun.hasType && fun.symbol.isExprSplice)
keywordStr("${") ~ toTextGlobal(args, ", ") ~ keywordStr("}")
else
toTextLocal(fun)
~ "("
~ Str("using ").provided(app.applyKind == ApplyKind.Using && !homogenizedView)
~ toTextGlobal(args, ", ")
~ ")"
case tree: TypeApply =>
typeApplyText(tree)
case Literal(c) =>
tree.typeOpt match {
case ConstantType(tc) => withPos(toText(tc), tree.sourcePos)
case _ => withPos(toText(c), tree.sourcePos)
}
case New(tpt) =>
keywordStr("new ") ~ {
tpt match {
case tpt: Template => toTextTemplate(tpt, ofNew = true)
case _ => toTextLocal(tpt)
}
}
case Typed(expr, tpt) =>
changePrec(InfixPrec) {
val exprText = toText(expr)
val line = exprText.lastLine
val colon = if (!line.isEmpty && isOperatorPart(line.last)) " :" else ":"
exprText ~ colon ~ toText(tpt) }
case NamedArg(name, arg) =>
toText(name) ~ " = " ~ toText(arg)
case Assign(lhs, rhs) =>
changePrec(GlobalPrec) { toTextLocal(lhs) ~ " = " ~ toText(rhs) }
case block: Block =>
blockToText(block)
case If(cond, thenp, elsep) =>
val isInline = tree.isInstanceOf[Trees.InlineIf[?]]
changePrec(GlobalPrec) {
keywordStr(if (isInline) "inline if " else "if ") ~
toText(cond) ~ (keywordText(" then") provided !cond.isInstanceOf[Parens]) ~~
toText(thenp) ~ optText(elsep)(keywordStr(" else ") ~ _)
}
case Closure(env, ref, target) =>
"closure(" ~ (toTextGlobal(env, ", ") ~ " | " provided env.nonEmpty) ~
toTextGlobal(ref) ~ (":" ~ toText(target) provided !target.isEmpty) ~ ")"
case Match(sel, cases) =>
val isInline = tree.isInstanceOf[Trees.InlineMatch[?]]
if (sel.isEmpty && !isInline) blockText(cases)
else changePrec(GlobalPrec) {
val selTxt: Text =
if (isInline)
if (sel.isEmpty) keywordStr("implicit")
else keywordStr("inline ") ~ toText(sel)
else toText(sel)
selTxt ~ keywordStr(" match ") ~ blockText(cases)
}
case CaseDef(pat, guard, body) =>
keywordStr("case ") ~ inPattern(toText(pat)) ~ optText(guard)(keywordStr(" if ") ~ _) ~ " => " ~ caseBlockText(body)
case Labeled(bind, expr) =>
changePrec(GlobalPrec) { toText(bind.name) ~ keywordStr("[") ~ toText(bind.symbol.info) ~ keywordStr("]: ") ~ toText(expr) }
case Return(expr, from) =>
val sym = from.symbol
if (sym.is(Label))
changePrec(GlobalPrec) { keywordStr("return[") ~ toText(sym.name) ~ keywordStr("]") ~ optText(expr)(" " ~ _) }
else
changePrec(GlobalPrec) { keywordStr("return") ~ optText(expr)(" " ~ _) }
case WhileDo(cond, body) =>
changePrec(GlobalPrec) { keywordStr("while ") ~ toText(cond) ~ keywordStr(" do ") ~ toText(body) }
case Try(expr, cases, finalizer) =>
changePrec(GlobalPrec) {
keywordStr("try ") ~ toText(expr) ~ optText(cases)(keywordStr(" catch ") ~ _) ~ optText(finalizer)(keywordStr(" finally ") ~ _)
}
case Throw(expr) =>
changePrec(GlobalPrec) {
keywordStr("throw ") ~ toText(expr)
}
case SeqLiteral(elems, elemtpt) =>
"[" ~ toTextGlobal(elems, ",") ~ " : " ~ toText(elemtpt) ~ "]"
case tree @ Inlined(call, bindings, body) =>
(("/* inlined from " ~ (if (call.isEmpty) "outside" else toText(call)) ~ " */ ") `provided`
!homogenizedView && ctx.settings.XprintInline.value) ~
blockText(bindings :+ body)
case tpt: untpd.DerivedTypeTree =>
"<derived typetree watching " ~ tpt.watched.showSummary() ~ ">"
case TypeTree() =>
typeText(toText(tree.typeOpt))
case SingletonTypeTree(ref) =>
toTextLocal(ref) ~ "." ~ keywordStr("type")
case RefinedTypeTree(tpt, refines) =>
toTextLocal(tpt) ~ " " ~ blockText(refines)
case AppliedTypeTree(tpt, args) =>
if (tpt.symbol == defn.orType && args.length == 2)
changePrec(OrTypePrec) { toText(args(0)) ~ " | " ~ atPrec(OrTypePrec + 1) { toText(args(1)) } }
else if (tpt.symbol == defn.andType && args.length == 2)
changePrec(AndTypePrec) { toText(args(0)) ~ " & " ~ atPrec(AndTypePrec + 1) { toText(args(1)) } }
else args match
case arg :: _ if arg.isTerm =>
toTextLocal(tpt) ~ "(" ~ Text(args.map(argText), ", ") ~ ")"
case _ =>
toTextLocal(tpt) ~ "[" ~ Text(args.map(argText), ", ") ~ "]"
case LambdaTypeTree(tparams, body) =>
changePrec(GlobalPrec) {
tparamsText(tparams) ~ " =>> " ~ toText(body)
}
case TermLambdaTypeTree(params, body) =>
changePrec(GlobalPrec) {
paramsText(params) ~ " =>> " ~ toText(body)
}
case MatchTypeTree(bound, sel, cases) =>
changePrec(GlobalPrec) {
toText(sel) ~ keywordStr(" match ") ~ blockText(cases) ~
(" <: " ~ toText(bound) provided !bound.isEmpty)
}
case ByNameTypeTree(tpt) =>
"=> " ~ toTextLocal(tpt)
case TypeBoundsTree(lo, hi, alias) =>
if (lo eq hi) && alias.isEmpty then optText(lo)(" = " ~ _)
else optText(lo)(" >: " ~ _) ~ optText(hi)(" <: " ~ _) ~ optText(alias)(" = " ~ _)
case Bind(name, body) =>
keywordText("given ").provided(tree.symbol.isOneOf(GivenOrImplicit) && !homogenizedView) ~ // Used for scala.quoted.Type in quote patterns (not pickled)
changePrec(InfixPrec) { toText(name) ~ " @ " ~ toText(body) }
case Alternative(trees) =>
changePrec(OrPrec) { toText(trees, " | ") }
case UnApply(fun, implicits, patterns) =>
val extractor = fun match {
case Select(extractor, name) if name.isUnapplyName => extractor
case _ => fun
}
toTextLocal(extractor) ~
"(" ~ toTextGlobal(patterns, ", ") ~ ")" ~
("(" ~ toTextGlobal(implicits, ", ") ~ ")" provided implicits.nonEmpty)
case tree @ ValDef(_, _, _) =>
valDefToText(tree)
case tree @ DefDef(_, _, _, _, _) =>
defDefToText(tree)
case tree @ TypeDef(name, rhs) =>
def typeDefText(tparamsText: => Text, rhsText: => Text) =
dclTextOr(tree) {
modText(tree.mods, tree.symbol, keywordStr("type"), isType = true) ~~
(varianceText(tree.mods) ~ typeText(nameIdText(tree))) ~
withEnclosingDef(tree) { tparamsText ~ rhsText }
}
def recur(rhs: Tree, tparamsTxt: => Text, printMemberArgs: Boolean): Text = rhs match {
case impl: Template =>
templateText(tree, impl)
case rhs: TypeBoundsTree =>
typeDefText(tparamsTxt, toText(rhs))
case LambdaTypeTree(tparams, body) if printMemberArgs =>
recur(body, tparamsText(tparams), false)
case rhs: TypeTree if isBounds(rhs.typeOpt) =>
typeDefText(tparamsTxt, toText(rhs))
case rhs =>
typeDefText(tparamsTxt, optText(rhs)(" = " ~ _))
}
recur(rhs, "", true)
case Import(expr, selectors) =>
keywordText("import ") ~ importText(expr, selectors)
case Export(expr, selectors) =>
keywordText("export ") ~ importText(expr, selectors)
case ExtMethods(tparams, vparamss, mdefs) =>
keywordText("extension ")
~ addVparamssText(tparamsText(tparams), vparamss)
~ " " ~ (if mdefs.length == 1 then toText(mdefs.head) else blockText(mdefs))
case packageDef: PackageDef =>
packageDefText(packageDef)
case tree: Template =>
toTextTemplate(tree)
case Annotated(arg, annot) =>
toTextLocal(arg) ~~ annotText(annot)
case EmptyTree =>
"<empty>"
case TypedSplice(t) =>
if (printDebug) "[" ~ toText(t) ~ "]#TS#"
else toText(t)
case tree @ ModuleDef(name, impl) =>
withEnclosingDef(tree) {
modText(tree.mods, NoSymbol, keywordStr("object"), isType = false) ~~
nameIdText(tree) ~ toTextTemplate(impl)
}
case SymbolLit(str) =>
"'" + str
case InterpolatedString(id, segments) =>
def strText(str: Literal) = withPos(escapedString(str.const.stringValue), tree.sourcePos)
def segmentText(segment: Tree) = segment match {
case Thicket(List(str: Literal, expr)) => strText(str) ~ "{" ~ toTextGlobal(expr) ~ "}"
case str: Literal => strText(str)
}
toText(id) ~ "\"" ~ Text(segments map segmentText, "") ~ "\""
case Function(args, body) =>
var implicitSeen: Boolean = false
var isGiven: Boolean = false
var isErased: Boolean = false
def argToText(arg: Tree) = arg match {
case arg @ ValDef(name, tpt, _) =>
val implicitText =
if ((arg.mods.is(Given))) { isGiven = true; "" }
else if ((arg.mods.is(Erased))) { isErased = true; "" }
else if ((arg.mods.is(Implicit)) && !implicitSeen) { implicitSeen = true; keywordStr("implicit ") }
else ""
implicitText ~ toText(name) ~ optAscription(tpt)
case _ =>
toText(arg)
}
val argsText = args match {
case (arg @ ValDef(_, tpt, _)) :: Nil if tpt.isEmpty => argToText(arg)
case _ =>
"("
~ keywordText("erased ").provided(isErased)
~ Text(args.map(argToText), ", ")
~ ")"
}
argsText ~ " " ~ arrow(isGiven) ~ " " ~ toText(body)
case PolyFunction(targs, body) =>
val targsText = "[" ~ Text(targs.map((arg: Tree) => toText(arg)), ", ") ~ "]"
changePrec(GlobalPrec) {
targsText ~ " => " ~ toText(body)
}
case InfixOp(l, op, r) =>
val opPrec = parsing.precedence(op.name)
changePrec(opPrec) { toText(l) ~ " " ~ toText(op) ~ " " ~ toText(r) }
case PostfixOp(l, op) =>
changePrec(InfixPrec) { toText(l) ~ " " ~ toText(op) }
case PrefixOp(op, r) =>
changePrec(DotPrec) { toText(op) ~ " " ~ toText(r) }
case Parens(t) =>
"(" ~ toTextGlobal(t) ~ ")"
case Tuple(ts) =>
"(" ~ toTextGlobal(ts, ", ") ~ ")"
case ForYield(enums, expr) =>
forText(enums, expr, keywordStr(" yield "))
case ForDo(enums, expr) =>
forText(enums, expr, keywordStr(" do "))
case GenFrom(pat, expr, checkMode) =>
(Str("case ") provided checkMode == untpd.GenCheckMode.FilterAlways) ~
toText(pat) ~ " <- " ~ toText(expr)
case GenAlias(pat, expr) =>
toText(pat) ~ " = " ~ toText(expr)
case ContextBounds(bounds, cxBounds) =>
cxBounds.foldLeft(toText(bounds)) {(t, cxb) =>
t ~ cxBoundToText(cxb)
}
case PatDef(mods, pats, tpt, rhs) =>
modText(mods, NoSymbol, keywordStr("val"), isType = false) ~~
toText(pats, ", ") ~ optAscription(tpt) ~ optText(rhs)(" = " ~ _)
case ParsedTry(expr, handler, finalizer) =>
changePrec(GlobalPrec) {
keywordStr("try ") ~ toText(expr) ~ " " ~ keywordStr("catch") ~ " {" ~ toText(handler) ~ "}" ~ optText(finalizer)(keywordStr(" finally ") ~ _)
}
case Number(digits, kind) =>
digits
case Quote(tree) if tree.isTerm =>
keywordStr("'{") ~ toTextGlobal(dropBlock(tree)) ~ keywordStr("}")
case Splice(tree) =>
keywordStr("${") ~ toTextGlobal(dropBlock(tree)) ~ keywordStr("}")
case TypSplice(tree) =>
keywordStr("${") ~ toTextGlobal(dropBlock(tree)) ~ keywordStr("}")
case tree: Applications.IntegratedTypeArgs =>
toText(tree.app) ~ Str("(with integrated type args)").provided(printDebug)
case Thicket(trees) =>
"Thicket {" ~~ toTextGlobal(trees, "\n") ~~ "}"
case MacroTree(call) =>
keywordStr("macro ") ~ toTextGlobal(call)
case _ =>
tree.fallbackToText(this)
}
}
override def toText[T >: Untyped](tree: Tree[T]): Text = controlled {
import untpd._
var txt = toTextCore(tree)
def suppressTypes =
tree.isType || tree.isDef || // don't print types of types or defs
homogenizedView && ctx.mode.is(Mode.Pattern)
// When comparing pickled info, disregard types of patterns.
// The reason is that GADT matching can rewrite types of pattern trees
// without changing the trees themselves. (see Typer.typedCase.indexPatterns.transform).
// But then pickling and unpickling the original trees will yield trees
// with the original types before they are rewritten, which causes a discrepancy.
def suppressPositions = tree match {
case _: WithoutTypeOrPos[?] | _: TypeTree => true // TypeTrees never have an interesting position
case _ => false
}
if (ctx.settings.XprintTypes.value && tree.hasType) {
// add type to term nodes; replace type nodes with their types unless -Yprint-pos is also set.
val tp1 = tree.typeOpt match {
case tp: TermRef if tree.isInstanceOf[RefTree] && !tp.denot.isOverloaded => tp.underlying
case tp => tp
}
val tp2 = {
val tp = tp1.tryNormalize
if (tp != NoType) tp else tp1
}
val tp3 =
if (homogenizedView && tree.isInstanceOf[If | Match | Annotated | Block | CaseDef]) {
// Types of non-leaf trees are not pickled but reconstructed when
// unpickled using the TypeAssigner. Sometimes, this requires choosing
// arbitrarily between two =:= types (e.g., when typing an `if`, where
// one branch is typed with a type alias and the other with a
// dealiased version of the same type) and we cannot guarantee that
// the same choice was made by the original Typer (e.g., because the
// original choice involved type variables). So we need to get rid of
// any alias in these types to make -Ytest-pickler work (the list of
// types in the isInstanceOf check above is conservative and might
// need to be expanded).
val dealiasMap = new TypeMap {
def apply(tp: Type) = mapOver(tp.dealias)
}
dealiasMap(tp2)
}
else tp2
if (!suppressTypes)
txt = ("<" ~ txt ~ ":" ~ toText(tp3) ~ ">").close
else if (tree.isType && !homogenizedView)
txt = toText(tp3)
}
if (!suppressPositions) {
if (printPos) {
val posStr =
if (homogenizedView || debugPos)
if (tree.isInstanceOf[MemberDef]) Str(s"${tree.source}${tree.span}")
else Str(s"${tree.source}${tree.span.toSynthetic}")
else
"<" ~ toText(tree.sourcePos) ~ ">"
val clsStr = ""//if (tree.isType) tree.getClass.toString else ""
txt = (txt ~ "@" ~ posStr ~ clsStr).close
}
if (ctx.settings.YprintPosSyms.value && tree.isDef)
txt = (txt ~
s"@@(${tree.symbol.name}=" ~ tree.symbol.sourcePos.toString ~ ")").close
}
if (ctx.settings.YshowTreeIds.value)
txt = (txt ~ "#" ~ tree.uniqueId.toString).close
tree match {
case Block(_, _) | Template(_, _, _, _) => txt
case _ => txt.close
}
}
/** Print modifiers from symbols if tree has type, overriding the behavior in Trees. */
extension (mdef: untpd.DefTree) def mods: untpd.Modifiers =
if mdef.hasType then Modifiers(mdef.symbol) else mdef.rawMods
private def Modifiers(sym: Symbol): Modifiers = untpd.Modifiers(
sym.flags & (if (sym.isType) ModifierFlags | VarianceFlags | SuperTrait else ModifierFlags),
if (sym.privateWithin.exists) sym.privateWithin.asType.name else tpnme.EMPTY,
sym.annotations.filterNot(ann => dropAnnotForModText(ann.symbol)).map(_.tree))
protected def dropAnnotForModText(sym: Symbol): Boolean = sym == defn.BodyAnnot
protected def optAscription[T >: Untyped](tpt: Tree[T]): Text = optText(tpt)(": " ~ _)
private def idText(tree: untpd.Tree): Text =
if showUniqueIds && tree.hasType && tree.symbol.exists then s"#${tree.symbol.id}" else ""
private def useSymbol(tree: untpd.Tree) =
tree.hasType && tree.symbol.exists && ctx.settings.YprintSyms.value
protected def nameIdText[T >: Untyped](tree: NameTree[T], dropExtension: Boolean = false): Text =
if (tree.hasType && tree.symbol.exists) {
var str = nameString(tree.symbol)
if tree.symbol.is(ExtensionMethod) && dropExtension && str.startsWith("extension_") then
str = str.drop("extension_".length)
tree match {
case tree: RefTree => withPos(str, tree.sourcePos)
case tree: MemberDef => withPos(str, tree.sourcePos.withSpan(tree.nameSpan))
case _ => str
}
}
else toText(tree.name) ~ idText(tree)
private def toTextOwner(tree: Tree[?]) =
"[owner = " ~ tree.symbol.maybeOwner.show ~ "]" provided ctx.settings.YprintDebugOwners.value
protected def dclTextOr[T >: Untyped](tree: Tree[T])(treeText: => Text): Text =
toTextOwner(tree) ~ {
if (useSymbol(tree)) annotsText(tree.symbol) ~~ dclText(tree.symbol)
else treeText
}
def tparamsText[T >: Untyped](params: List[Tree[T]]): Text =
"[" ~ toText(params, ", ") ~ "]" provided params.nonEmpty
def addVparamssText[T >: Untyped](leading: Text, vparamss: List[List[ValDef[T]]]): Text =
vparamss.foldLeft(leading)((txt, params) => txt ~ paramsText(params))
protected def valDefToText[T >: Untyped](tree: ValDef[T]): Text = {
import untpd._
dclTextOr(tree) {
modText(tree.mods, tree.symbol, keywordStr(if (tree.mods.is(Mutable)) "var" else "val"), isType = false) ~~
valDefText(nameIdText(tree)) ~ optAscription(tree.tpt) ~
withEnclosingDef(tree) { optText(tree.rhs)(" = " ~ _) }
}
}
private def paramsText[T>: Untyped](params: List[ValDef[T]]) =
"(" ~ keywordText("using ").provided(params.nonEmpty && params.head.mods.is(Given))
~ keywordText("erased ").provided(params.nonEmpty && params.head.mods.is(Erased))
~ toText(params, ", ") ~ ")"
protected def defDefToText[T >: Untyped](tree: DefDef[T]): Text = {
import untpd._
dclTextOr(tree) {
val defKeyword = modText(tree.mods, tree.symbol, keywordStr("def"), isType = false)
val isExtension = tree.hasType && tree.symbol.is(ExtensionMethod)
withEnclosingDef(tree) {
val (prefix, vparamss) =
if isExtension then
val (leadingParams, otherParamss) = (tree.vparamss: @unchecked) match
case vparams1 :: vparams2 :: rest if !isLeftAssoc(tree.name) =>
(vparams2, vparams1 :: rest)
case vparams1 :: rest =>
(vparams1, rest)
(keywordStr("extension") ~~ paramsText(leadingParams)
~~ (defKeyword ~~ valDefText(nameIdText(tree, dropExtension = true))).close,
otherParamss)
else (defKeyword ~~ valDefText(nameIdText(tree)), tree.vparamss)
addVparamssText(prefix ~ tparamsText(tree.tparams), vparamss) ~
optAscription(tree.tpt) ~
optText(tree.rhs)(" = " ~ keywordText("macro ").provided(tree.symbol.isScala2Macro) ~ _)
}
}
}
protected def toTextTemplate(impl: Template, ofNew: Boolean = false): Text = {
val Template(constr @ DefDef(_, tparams, vparamss, _, _), _, self, _) = impl
val tparamsTxt = withEnclosingDef(constr) { tparamsText(tparams) }
val primaryConstrs = if (constr.rhs.isEmpty) Nil else constr :: Nil
val prefix: Text =
if (vparamss.isEmpty || primaryConstrs.nonEmpty) tparamsTxt
else {
var modsText = modText(constr.mods, constr.symbol, "", isType = false)
if (!modsText.isEmpty) modsText = " " ~ modsText
if (constr.mods.hasAnnotations && !constr.mods.hasFlags) modsText = modsText ~~ " this"
withEnclosingDef(constr) { addVparamssText(tparamsTxt ~~ modsText, vparamss) }
}
val parentsText = Text(impl.parents.map(constrText), if (ofNew) keywordStr(" with ") else ", ")
val derivedText = Text(impl.derived.map(toText(_)), ", ")
val selfText = {
val selfName = if (self.name == nme.WILDCARD) keywordStr("this") else self.name.toString
(selfName ~ optText(self.tpt)(": " ~ _) ~ " =>").close
}.provided(!self.isEmpty)
val body = if (ctx.settings.YtestPickler.value) {
// Pickling/unpickling reorders the body members, so we need to homogenize
val (params, rest) = impl.body partition {
case stat: TypeDef => stat.symbol.is(Param)
case stat: ValOrDefDef =>
stat.symbol.is(ParamAccessor) && !stat.symbol.isSetter
case _ => false
}
params ::: rest
}
else impl.body
val bodyText = " {" ~~ selfText ~ toTextGlobal(primaryConstrs ::: body, "\n") ~ "}"
prefix ~
keywordText(" extends").provided(!ofNew && impl.parents.nonEmpty) ~~ parentsText ~
keywordText(" derives").provided(impl.derived.nonEmpty) ~~ derivedText ~
bodyText
}
protected def templateText(tree: TypeDef, impl: Template): Text = {
val kw =
if tree.mods.is(SuperTrait) then "super trait"
else if tree.mods.is(Trait) then "trait"
else "class"
val decl = modText(tree.mods, tree.symbol, keywordStr(kw), isType = true)
( decl ~~ typeText(nameIdText(tree)) ~ withEnclosingDef(tree) { toTextTemplate(impl) }
// ~ (if (tree.hasType && printDebug) i"[decls = ${tree.symbol.info.decls}]" else "") // uncomment to enable
)
}
protected def toTextPackageId[T >: Untyped](pid: Tree[T]): Text =
if (homogenizedView && pid.hasType) toTextLocal(pid.tpe.asInstanceOf[Showable])
else toTextLocal(pid)
protected def packageDefText(tree: PackageDef): Text = {
val statsText = tree.stats match {
case (pdef: PackageDef) :: Nil => toText(pdef)
case _ => toTextGlobal(tree.stats, "\n")
}
val bodyText =
if (currentPrecedence == TopLevelPrec) "\n" ~ statsText else " {" ~ statsText ~ "}"
keywordStr("package ") ~ toTextPackageId(tree.pid) ~ bodyText
}
protected def constrText(tree: untpd.Tree): Text = toTextLocal(tree).stripPrefix(keywordStr("new ")) // DD
protected def annotText(tree: untpd.Tree): Text = "@" ~ constrText(tree) // DD
protected def modText(mods: untpd.Modifiers, sym: Symbol, kw: String, isType: Boolean): Text = { // DD
val suppressKw = if (enclDefIsClass) mods.isAllOf(LocalParam) else mods.is(Param)
var flagMask =
if (ctx.settings.YdebugFlags.value) AnyFlags
else if (suppressKw) PrintableFlags(isType) &~ Private
else PrintableFlags(isType)
if (homogenizedView && mods.flags.isTypeFlags) flagMask &~= GivenOrImplicit // drop implicit/given from classes
val rawFlags = if (sym.exists) sym.flags else mods.flags
if (rawFlags.is(Param)) flagMask = flagMask &~ Given
val flags = rawFlags & flagMask
var flagsText = toTextFlags(sym, flags)
if mods.hasMod(classOf[untpd.Mod.Transparent]) then
flagsText = "transparent " ~ flagsText
val annotations =
if (sym.exists) sym.annotations.filterNot(ann => dropAnnotForModText(ann.symbol)).map(_.tree)
else mods.annotations.filterNot(tree => dropAnnotForModText(tree.symbol))
Text(annotations.map(annotText), " ") ~~ flagsText ~~ (Str(kw) provided !suppressKw)
}
def optText(name: Name)(encl: Text => Text): Text =
if (name.isEmpty) "" else encl(toText(name))
def optText[T >: Untyped](tree: Tree[T])(encl: Text => Text): Text =
if (tree.isEmpty) "" else encl(toText(tree))
def optText[T >: Untyped](tree: List[Tree[T]])(encl: Text => Text): Text =
if (tree.exists(!_.isEmpty)) encl(blockText(tree)) else ""
override protected def ParamRefNameString(name: Name): String =
name.toString
override protected def treatAsTypeParam(sym: Symbol): Boolean = sym.is(TypeParam)
override protected def treatAsTypeArg(sym: Symbol): Boolean =
sym.isType && (sym.isAllOf(ProtectedLocal)) &&
(sym.allOverriddenSymbols exists (_.is(TypeParam)))
override def toText(sym: Symbol): Text = {
if (sym.isImport)
sym.infoOrCompleter match {
case info: Namer#Completer => return info.original.show
case info: ImportType => return s"import $info.expr.show"
case _ =>
}
def name =
if (printDebug)
nameString(sym)
else if sym.is(Package) then
fullNameString(sym)
else if (sym.is(ModuleClass) && sym.isPackageObject && sym.name.stripModuleClassSuffix == tpnme.PACKAGE)
nameString(sym.owner.name)
else if (sym.is(ModuleClass))
nameString(sym.name.stripModuleClassSuffix)
else if (hasMeaninglessName(sym))
simpleNameString(sym.owner) + idString(sym)
else
nameString(sym)
(keywordText(kindString(sym)) ~~ {
if (sym.isAnonymousClass)
toTextParents(sym.info.parents) ~~ "{...}"
else
typeText(name)
}).close
}
/** String representation of symbol's kind. */
override def kindString(sym: Symbol): String = {
val flags = sym.flagsUNSAFE
if (flags.is(Package)) "package"
else if (sym.isPackageObject) "package object"
else if (flags.is(Module)) "object"
else if (sym.isClassConstructor) "constructor"
else super.kindString(sym)
}
/** String representation of symbol's definition keyword */
override protected def keyString(sym: Symbol): String = {
val flags = sym.flagsUNSAFE
if (sym.isType && sym.owner.isTerm) ""
else if (sym.isPackageObject) "package object"
else if (flags.is(Module) && flags.is(Case)) "case object"
else if (sym.isClass && flags.is(Case)) "case class"
else if sym.isClass && flags.is(SuperTrait) then "super trait"
else super.keyString(sym)
}
override def toTextFlags(sym: Symbol): Text =
if (ctx.settings.YdebugFlags.value)
super.toTextFlags(sym)
else {
var flags = sym.flagsUNSAFE
if (flags.is(TypeParam)) flags = flags &~ Protected
toTextFlags(sym, flags & PrintableFlags(sym.isType))
}
override def toText(denot: Denotation): Text = denot match {
case denot: MultiDenotation => Text(denot.alternatives.map(dclText), " <and> ")
case NoDenotation => "NoDenotation"
case _ =>
if (denot.symbol.exists) toText(denot.symbol)
else "some " ~ toText(denot.info)
}
override def plain: PlainPrinter = new PlainPrinter(_ctx)
private def withPos(txt: Text, pos: SourcePosition): Text =
if (!printLines || !pos.exists) txt
else txt match {
case Str(s, _) => Str(s, LineRange(pos.line, pos.endLine))
case _ => txt
}
}