-
Notifications
You must be signed in to change notification settings - Fork 1k
/
TreePickler.scala
749 lines (708 loc) · 25.6 KB
/
TreePickler.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
package dotty.tools
package dotc
package core
package tasty
import dotty.tools.tasty.TastyFormat._
import dotty.tools.tasty.TastyBuffer._
import ast.Trees._
import ast.{untpd, tpd}
import Contexts._, Symbols._, Types._, Names._, Constants._, Decorators._, Annotations._, Flags._
import Denotations.MultiDenotation
import typer.Inliner
import NameKinds._
import StdNames.nme
import transform.SymUtils._
import printing.Printer
import printing.Texts._
import util.SourceFile
import annotation.constructorOnly
object TreePickler {
val sectionName = "ASTs"
case class Hole(isTermHole: Boolean, idx: Int, args: List[tpd.Tree])(implicit @constructorOnly src: SourceFile) extends tpd.Tree {
override def isTerm: Boolean = isTermHole
override def isType: Boolean = !isTermHole
override def fallbackToText(printer: Printer): Text =
if isTermHole then s"{{{ $idx |" ~~ printer.toTextGlobal(tpe) ~~ "|" ~~ printer.toTextGlobal(args, ", ") ~~ "}}}"
else s"[[[ $idx |" ~~ printer.toTextGlobal(tpe) ~~ "|" ~~ printer.toTextGlobal(args, ", ") ~~ "]]]"
}
}
class TreePickler(pickler: TastyPickler) {
val buf: TreeBuffer = new TreeBuffer
pickler.newSection(TreePickler.sectionName, buf)
import TreePickler._
import buf._
import pickler.nameBuffer.nameIndex
import tpd._
private val symRefs = Symbols.newMutableSymbolMap[Addr]
private val forwardSymRefs = Symbols.newMutableSymbolMap[List[Addr]]
private val pickledTypes = new java.util.IdentityHashMap[Type, Any] // Value type is really Addr, but that's not compatible with null
private def withLength(op: => Unit) = {
val lengthAddr = reserveRef(relative = true)
op
fillRef(lengthAddr, currentAddr, relative = true)
}
def addrOfSym(sym: Symbol): Option[Addr] =
symRefs.get(sym)
def preRegister(tree: Tree)(using Context): Unit = tree match {
case tree: MemberDef =>
if (!symRefs.contains(tree.symbol)) symRefs(tree.symbol) = NoAddr
case _ =>
}
def registerDef(sym: Symbol): Unit = {
symRefs(sym) = currentAddr
forwardSymRefs.get(sym) match {
case Some(refs) =>
refs.foreach(fillRef(_, currentAddr, relative = false))
forwardSymRefs -= sym
case None =>
}
}
def pickleName(name: Name): Unit = writeNat(nameIndex(name).index)
private def pickleNameAndSig(name: Name, sig: Signature): Unit =
pickleName(
if (sig eq Signature.NotAMethod) name
else SignedName(name.toTermName, sig))
private def pickleSymRef(sym: Symbol)(using Context) = symRefs.get(sym) match {
case Some(label) =>
if (label != NoAddr) writeRef(label) else pickleForwardSymRef(sym)
case None =>
// See pos/t1957.scala for an example where this can happen.
// I believe it's a bug in typer: the type of an implicit argument refers
// to a closure parameter outside the closure itself. TODO: track this down, so that we
// can eliminate this case.
report.log(i"pickling reference to as yet undefined $sym in ${sym.owner}", sym.srcPos)
pickleForwardSymRef(sym)
}
private def pickleForwardSymRef(sym: Symbol)(using Context) = {
val ref = reserveRef(relative = false)
assert(!sym.is(Flags.Package), sym)
forwardSymRefs(sym) = ref :: forwardSymRefs.getOrElse(sym, Nil)
}
private def isLocallyDefined(sym: Symbol)(using Context) =
sym.topLevelClass.isLinkedWith(pickler.rootCls)
def pickleConstant(c: Constant)(using Context): Unit = c.tag match {
case UnitTag =>
writeByte(UNITconst)
case BooleanTag =>
writeByte(if (c.booleanValue) TRUEconst else FALSEconst)
case ByteTag =>
writeByte(BYTEconst)
writeInt(c.byteValue)
case ShortTag =>
writeByte(SHORTconst)
writeInt(c.shortValue)
case CharTag =>
writeByte(CHARconst)
writeNat(c.charValue)
case IntTag =>
writeByte(INTconst)
writeInt(c.intValue)
case LongTag =>
writeByte(LONGconst)
writeLongInt(c.longValue)
case FloatTag =>
writeByte(FLOATconst)
writeInt(java.lang.Float.floatToRawIntBits(c.floatValue))
case DoubleTag =>
writeByte(DOUBLEconst)
writeLongInt(java.lang.Double.doubleToRawLongBits(c.doubleValue))
case StringTag =>
writeByte(STRINGconst)
pickleName(c.stringValue.toTermName)
case NullTag =>
writeByte(NULLconst)
case ClazzTag =>
writeByte(CLASSconst)
pickleType(c.typeValue)
case EnumTag =>
writeByte(ENUMconst)
pickleType(c.symbolValue.termRef)
}
def pickleVariances(tp: Type)(using Context): Unit = tp match
case tp: HKTypeLambda if tp.isDeclaredVarianceLambda =>
for v <- tp.declaredVariances do
writeByte(
if v.is(Covariant) then COVARIANT
else if v.is(Contravariant) then CONTRAVARIANT
else STABLE)
case _ =>
def pickleType(tpe0: Type, richTypes: Boolean = false)(using Context): Unit = {
val tpe = tpe0.stripTypeVar
try {
val prev = pickledTypes.get(tpe)
if (prev == null) {
pickledTypes.put(tpe, currentAddr)
pickleNewType(tpe, richTypes)
}
else {
writeByte(SHAREDtype)
writeRef(prev.asInstanceOf[Addr])
}
}
catch {
case ex: AssertionError =>
println(i"error when pickling type $tpe")
throw ex
}
}
private def pickleNewType(tpe: Type, richTypes: Boolean)(using Context): Unit = tpe match {
case AppliedType(tycon, args) =>
writeByte(APPLIEDtype)
withLength { pickleType(tycon); args.foreach(pickleType(_)) }
case ConstantType(value) =>
pickleConstant(value)
case tpe: NamedType =>
val sym = tpe.symbol
def pickleExternalRef(sym: Symbol) = {
val isShadowedRef =
sym.isClass && tpe.prefix.member(sym.name).symbol != sym
if (sym.is(Flags.Private) || isShadowedRef) {
writeByte(if (tpe.isType) TYPEREFin else TERMREFin)
withLength {
pickleNameAndSig(sym.name, tpe.symbol.signature)
pickleType(tpe.prefix)
pickleType(sym.owner.typeRef)
}
}
else {
writeByte(if (tpe.isType) TYPEREF else TERMREF)
pickleNameAndSig(sym.name, tpe.signature)
pickleType(tpe.prefix)
}
}
if (sym.is(Flags.Package)) {
writeByte(if (tpe.isType) TYPEREFpkg else TERMREFpkg)
pickleName(sym.fullName)
}
else if (tpe.prefix == NoPrefix) {
writeByte(if (tpe.isType) TYPEREFdirect else TERMREFdirect)
pickleSymRef(sym)
}
else tpe.designator match {
case name: Name =>
writeByte(if (tpe.isType) TYPEREF else TERMREF)
pickleName(name); pickleType(tpe.prefix)
case sym: Symbol =>
if (isLocallyDefined(sym)) {
writeByte(if (tpe.isType) TYPEREFsymbol else TERMREFsymbol)
pickleSymRef(sym); pickleType(tpe.prefix)
}
else pickleExternalRef(sym)
}
case tpe: ThisType =>
if (tpe.cls.is(Flags.Package) && !tpe.cls.isEffectiveRoot) {
writeByte(TERMREFpkg)
pickleName(tpe.cls.fullName)
}
else {
writeByte(THIS)
pickleType(tpe.tref)
}
case tpe: SuperType =>
writeByte(SUPERtype)
withLength { pickleType(tpe.thistpe); pickleType(tpe.supertpe) }
case tpe: RecThis =>
writeByte(RECthis)
val binderAddr = pickledTypes.get(tpe.binder)
assert(binderAddr != null, tpe.binder)
writeRef(binderAddr.asInstanceOf[Addr])
case tpe: SkolemType =>
pickleType(tpe.info)
case tpe: RefinedType =>
writeByte(REFINEDtype)
withLength {
pickleName(tpe.refinedName)
pickleType(tpe.parent)
pickleType(tpe.refinedInfo, richTypes = true)
}
case tpe: RecType =>
writeByte(RECtype)
pickleType(tpe.parent)
case tpe: TypeBounds =>
writeByte(TYPEBOUNDS)
withLength {
pickleType(tpe.lo, richTypes)
if !tpe.isInstanceOf[AliasingBounds] then
pickleType(tpe.hi, richTypes)
pickleVariances(tpe.hi)
}
case tpe: AnnotatedType =>
writeByte(ANNOTATEDtype)
withLength { pickleType(tpe.parent, richTypes); pickleTree(tpe.annot.tree) }
case tpe: AndType =>
writeByte(ANDtype)
withLength { pickleType(tpe.tp1, richTypes); pickleType(tpe.tp2, richTypes) }
case tpe: OrType =>
writeByte(ORtype)
withLength { pickleType(tpe.tp1, richTypes); pickleType(tpe.tp2, richTypes) }
case tpe: ExprType =>
writeByte(BYNAMEtype)
pickleType(tpe.underlying)
case tpe: HKTypeLambda =>
pickleMethodic(TYPELAMBDAtype, tpe, EmptyFlags)
case tpe: MatchType =>
writeByte(MATCHtype)
withLength {
pickleType(tpe.bound)
pickleType(tpe.scrutinee)
tpe.cases.foreach(pickleType(_))
}
case tpe: PolyType if richTypes =>
pickleMethodic(POLYtype, tpe, EmptyFlags)
case tpe: MethodType if richTypes =>
var mods = EmptyFlags
if tpe.isContextualMethod then mods |= Given
else if tpe.isImplicitMethod then mods |= Implicit
if tpe.isErasedMethod then mods |= Erased
pickleMethodic(METHODtype, tpe, mods)
case tpe: ParamRef =>
assert(pickleParamRef(tpe), s"orphan parameter reference: $tpe")
case tpe: LazyRef =>
pickleType(tpe.ref)
}
def pickleMethodic(tag: Int, tpe: LambdaType, mods: FlagSet)(using Context): Unit = {
writeByte(tag)
withLength {
pickleType(tpe.resultType, richTypes = true)
tpe.paramNames.lazyZip(tpe.paramInfos).foreach { (name, tpe) =>
pickleType(tpe); pickleName(name)
}
if (mods != EmptyFlags) pickleFlags(mods, tpe.isTermLambda)
}
}
def pickleParamRef(tpe: ParamRef)(using Context): Boolean = {
val binder = pickledTypes.get(tpe.binder)
val pickled = binder != null
if (pickled) {
writeByte(PARAMtype)
withLength { writeRef(binder.asInstanceOf[Addr]); writeNat(tpe.paramNum) }
}
pickled
}
def pickleTpt(tpt: Tree)(using Context): Unit =
pickleTree(tpt)
def pickleTreeUnlessEmpty(tree: Tree)(using Context): Unit = {
if (!tree.isEmpty) pickleTree(tree)
}
def pickleDef(tag: Int, sym: Symbol, tpt: Tree, rhs: Tree = EmptyTree, pickleParams: => Unit = ())(using Context): Unit = {
assert(symRefs(sym) == NoAddr, sym)
registerDef(sym)
writeByte(tag)
withLength {
pickleName(sym.name)
pickleParams
tpt match {
case _: Template | _: Hole => pickleTree(tpt)
case _ if tpt.isType => pickleTpt(tpt)
}
pickleTreeUnlessEmpty(rhs)
pickleModifiers(sym)
}
}
def pickleParam(tree: Tree)(using Context): Unit = {
registerTreeAddr(tree)
tree match {
case tree: ValDef => pickleDef(PARAM, tree.symbol, tree.tpt)
case tree: DefDef => pickleDef(PARAM, tree.symbol, tree.tpt, tree.rhs)
case tree: TypeDef => pickleDef(TYPEPARAM, tree.symbol, tree.rhs)
}
}
def pickleParams(trees: List[Tree])(using Context): Unit = {
trees.foreach(preRegister)
trees.foreach(pickleParam)
}
def pickleStats(stats: List[Tree])(using Context): Unit = {
stats.foreach(preRegister)
stats.foreach(stat => if (!stat.isEmpty) pickleTree(stat))
}
def pickleTree(tree: Tree)(using Context): Unit = {
val addr = registerTreeAddr(tree)
if (addr != currentAddr) {
writeByte(SHAREDterm)
writeRef(addr)
}
else
try tree match {
case Ident(name) =>
tree.tpe match {
case tp: TermRef if name != nme.WILDCARD =>
// wildcards are pattern bound, need to be preserved as ids.
pickleType(tp)
case tp =>
writeByte(if (tree.isType) IDENTtpt else IDENT)
pickleName(name)
pickleType(tp)
}
case This(qual) =>
if (qual.isEmpty) pickleType(tree.tpe)
else {
writeByte(QUALTHIS)
val ThisType(tref) = tree.tpe
pickleTree(qual.withType(tref))
}
case Select(qual, name) =>
name match {
case OuterSelectName(_, levels) =>
writeByte(SELECTouter)
withLength {
writeNat(levels)
pickleTree(qual)
val SkolemType(tp) = tree.tpe
pickleType(tp)
}
case _ =>
val sig = tree.tpe.signature
val isAmbiguous =
sig != Signature.NotAMethod
&& qual.tpe.nonPrivateMember(name).match
case d: MultiDenotation => d.atSignature(sig).isInstanceOf[MultiDenotation]
case _ => false
if isAmbiguous then
writeByte(SELECTin)
withLength {
pickleNameAndSig(name, tree.symbol.signature)
pickleTree(qual)
pickleType(tree.symbol.owner.typeRef)
}
else
writeByte(if (name.isTypeName) SELECTtpt else SELECT)
pickleNameAndSig(name, sig)
pickleTree(qual)
}
case Apply(fun, args) =>
if (fun.symbol eq defn.throwMethod) {
writeByte(THROW)
pickleTree(args.head)
}
else {
writeByte(APPLY)
withLength {
pickleTree(fun)
args.foreach(pickleTree)
}
}
case TypeApply(fun, args) =>
writeByte(TYPEAPPLY)
withLength {
pickleTree(fun)
args.foreach(pickleTpt)
}
case Literal(const1) =>
pickleConstant {
tree.tpe match {
case ConstantType(const2) => const2
case _ => const1
}
}
case Super(qual, mix) =>
writeByte(SUPER)
withLength {
pickleTree(qual);
if (!mix.isEmpty) {
val SuperType(_, mixinType: TypeRef) = tree.tpe
pickleTree(mix.withType(mixinType))
}
}
case New(tpt) =>
writeByte(NEW)
pickleTpt(tpt)
case Typed(expr, tpt) =>
writeByte(TYPED)
withLength { pickleTree(expr); pickleTpt(tpt) }
case NamedArg(name, arg) =>
writeByte(NAMEDARG)
pickleName(name)
pickleTree(arg)
case Assign(lhs, rhs) =>
writeByte(ASSIGN)
withLength { pickleTree(lhs); pickleTree(rhs) }
case Block(stats, expr) =>
writeByte(BLOCK)
stats.foreach(preRegister)
withLength { pickleTree(expr); stats.foreach(pickleTree) }
case tree @ If(cond, thenp, elsep) =>
writeByte(IF)
withLength {
if (tree.isInline) writeByte(INLINE)
pickleTree(cond)
pickleTree(thenp)
pickleTree(elsep)
}
case Closure(env, meth, tpt) =>
writeByte(LAMBDA)
assert(env.isEmpty)
withLength {
pickleTree(meth)
if (tpt.tpe.exists) pickleTpt(tpt)
}
case tree @ Match(selector, cases) =>
writeByte(MATCH)
withLength {
if (tree.isInline)
if (selector.isEmpty) writeByte(IMPLICIT)
else { writeByte(INLINE); pickleTree(selector) }
else pickleTree(selector)
tree.cases.foreach(pickleTree)
}
case CaseDef(pat, guard, rhs) =>
writeByte(CASEDEF)
withLength { pickleTree(pat); pickleTree(rhs); pickleTreeUnlessEmpty(guard) }
case Return(expr, from) =>
writeByte(RETURN)
withLength { pickleSymRef(from.symbol); pickleTreeUnlessEmpty(expr) }
case WhileDo(cond, body) =>
writeByte(WHILE)
withLength { pickleTree(cond); pickleTree(body) }
case Try(block, cases, finalizer) =>
writeByte(TRY)
withLength { pickleTree(block); cases.foreach(pickleTree); pickleTreeUnlessEmpty(finalizer) }
case SeqLiteral(elems, elemtpt) =>
writeByte(REPEATED)
withLength { pickleTree(elemtpt); elems.foreach(pickleTree) }
case Inlined(call, bindings, expansion) =>
writeByte(INLINED)
bindings.foreach(preRegister)
withLength {
pickleTree(expansion)
if (!call.isEmpty) pickleTree(call)
bindings.foreach { b =>
assert(b.isInstanceOf[DefDef] || b.isInstanceOf[ValDef])
pickleTree(b)
}
}
case Bind(name, body) =>
registerDef(tree.symbol)
writeByte(BIND)
withLength {
pickleName(name); pickleType(tree.symbol.info); pickleTree(body)
}
case Alternative(alts) =>
writeByte(ALTERNATIVE)
withLength { alts.foreach(pickleTree) }
case UnApply(fun, implicits, patterns) =>
writeByte(UNAPPLY)
withLength {
pickleTree(fun)
for (implicitArg <- implicits) {
writeByte(IMPLICITarg)
pickleTree(implicitArg)
}
pickleType(tree.tpe)
patterns.foreach(pickleTree)
}
case tree: ValDef =>
pickleDef(VALDEF, tree.symbol, tree.tpt, tree.rhs)
case tree: DefDef =>
def pickleParamss(paramss: List[List[ValDef]]): Unit = paramss match
case Nil =>
case params :: rest =>
pickleParams(params)
if params.isEmpty || rest.nonEmpty then writeByte(PARAMEND)
pickleParamss(rest)
def pickleAllParams =
pickleParams(tree.tparams)
pickleParamss(tree.vparamss)
pickleDef(DEFDEF, tree.symbol, tree.tpt, tree.rhs, pickleAllParams)
case tree: TypeDef =>
pickleDef(TYPEDEF, tree.symbol, tree.rhs)
case tree: Template =>
registerDef(tree.symbol)
writeByte(TEMPLATE)
val (params, rest) = decomposeTemplateBody(tree.body)
withLength {
pickleParams(params)
tree.parents.foreach(pickleTree)
val cinfo @ ClassInfo(_, _, _, _, selfInfo) = tree.symbol.owner.info
if (!tree.self.isEmpty) {
writeByte(SELFDEF)
pickleName(tree.self.name)
if (!tree.self.tpt.isEmpty) pickleTree(tree.self.tpt)
else {
if (!tree.self.isEmpty) registerTreeAddr(tree.self)
pickleType {
selfInfo match {
case sym: Symbol => sym.info
case tp: Type => tp
}
}
}
}
pickleStats(tree.constr :: rest)
}
case Import(expr, selectors) =>
writeByte(IMPORT)
withLength {
pickleTree(expr)
pickleSelectors(selectors)
}
case PackageDef(pid, stats) =>
writeByte(PACKAGE)
withLength { pickleType(pid.tpe); pickleStats(stats) }
case tree: TypeTree =>
pickleType(tree.tpe)
case SingletonTypeTree(ref) =>
writeByte(SINGLETONtpt)
pickleTree(ref)
case RefinedTypeTree(parent, refinements) =>
if (refinements.isEmpty) pickleTree(parent)
else {
val refineCls = refinements.head.symbol.owner.asClass
registerDef(refineCls)
pickledTypes.put(refineCls.typeRef, currentAddr)
writeByte(REFINEDtpt)
refinements.foreach(preRegister)
withLength { pickleTree(parent); refinements.foreach(pickleTree) }
}
case AppliedTypeTree(tycon, args) =>
writeByte(APPLIEDtpt)
withLength { pickleTree(tycon); args.foreach(pickleTree) }
case MatchTypeTree(bound, selector, cases) =>
writeByte(MATCHtpt)
withLength {
if (!bound.isEmpty) pickleTree(bound)
pickleTree(selector)
cases.foreach(pickleTree)
}
case ByNameTypeTree(tp) =>
writeByte(BYNAMEtpt)
pickleTree(tp)
case Annotated(tree, annot) =>
writeByte(ANNOTATEDtpt)
withLength { pickleTree(tree); pickleTree(annot) }
case LambdaTypeTree(tparams, body) =>
writeByte(LAMBDAtpt)
withLength { pickleParams(tparams); pickleTree(body) }
case TypeBoundsTree(lo, hi, alias) =>
writeByte(TYPEBOUNDStpt)
withLength {
pickleTree(lo);
if alias.isEmpty then
if hi ne lo then pickleTree(hi)
else
pickleTree(hi)
pickleTree(alias)
}
case Hole(_, idx, args) =>
writeByte(HOLE)
withLength {
writeNat(idx)
pickleType(tree.tpe, richTypes = true)
args.foreach(pickleTree)
}
}
catch {
case ex: TypeError =>
report.error(ex.toMessage, tree.srcPos.focus)
case ex: AssertionError =>
println(i"error when pickling tree $tree")
throw ex
}
}
def pickleSelectors(selectors: List[untpd.ImportSelector])(using Context): Unit =
for sel <- selectors do
pickleSelector(IMPORTED, sel.imported)
sel.renamed match
case to @ Ident(_) => pickleSelector(RENAMED, to)
case _ =>
sel.bound match
case bound @ untpd.TypedSplice(tpt) =>
registerTreeAddr(bound)
writeByte(BOUNDED)
pickleTree(tpt)
case _ =>
def pickleSelector(tag: Int, id: untpd.Ident)(using Context): Unit = {
registerTreeAddr(id)
writeByte(tag)
pickleName(id.name)
}
def pickleModifiers(sym: Symbol)(using Context): Unit = {
import Flags._
var flags = sym.flags
val privateWithin = sym.privateWithin
if (privateWithin.exists) {
writeByte(if (flags.is(Protected)) PROTECTEDqualified else PRIVATEqualified)
pickleType(privateWithin.typeRef)
flags = flags &~ Protected
}
if (flags.is(ParamAccessor) && sym.isTerm && !sym.isSetter)
flags = flags &~ ParamAccessor // we only generate a tag for parameter setters
pickleFlags(flags, sym.isTerm)
sym.annotations.foreach(pickleAnnotation(sym, _))
}
def pickleFlags(flags: FlagSet, isTerm: Boolean)(using Context): Unit = {
import Flags._
def writeModTag(tag: Int) = {
assert(isModifierTag(tag))
writeByte(tag)
}
assert(!flags.is(Scala2x))
if (flags.is(Private)) writeModTag(PRIVATE)
if (flags.is(Protected)) writeModTag(PROTECTED)
if (flags.is(Final, butNot = Module)) writeModTag(FINAL)
if (flags.is(Case)) writeModTag(CASE)
if (flags.is(Override)) writeModTag(OVERRIDE)
if (flags.is(Inline)) writeModTag(INLINE)
if (flags.is(InlineProxy)) writeModTag(INLINEPROXY)
if (flags.is(Macro)) writeModTag(MACRO)
if (flags.is(JavaStatic)) writeModTag(STATIC)
if (flags.is(Module)) writeModTag(OBJECT)
if (flags.is(Enum)) writeModTag(ENUM)
if (flags.is(Local)) writeModTag(LOCAL)
if (flags.is(Synthetic)) writeModTag(SYNTHETIC)
if (flags.is(Artifact)) writeModTag(ARTIFACT)
if (isTerm) {
if (flags.is(Implicit)) writeModTag(IMPLICIT)
if (flags.is(Given)) writeModTag(GIVEN)
if (flags.is(Erased)) writeModTag(ERASED)
if (flags.is(Lazy, butNot = Module)) writeModTag(LAZY)
if (flags.is(AbsOverride)) { writeModTag(ABSTRACT); writeModTag(OVERRIDE) }
if (flags.is(Mutable)) writeModTag(MUTABLE)
if (flags.is(Accessor)) writeModTag(FIELDaccessor)
if (flags.is(CaseAccessor)) writeModTag(CASEaccessor)
if (flags.is(HasDefault)) writeModTag(HASDEFAULT)
if (flags.is(StableRealizable)) writeModTag(STABLE)
if (flags.is(Extension)) writeModTag(EXTENSION)
if (flags.is(ParamAccessor)) writeModTag(PARAMsetter)
if (flags.is(SuperParamAlias)) writeModTag(PARAMalias)
if (flags.is(Exported)) writeModTag(EXPORTED)
assert(!(flags.is(Label)))
}
else {
if (flags.is(Sealed)) writeModTag(SEALED)
if (flags.is(Abstract)) writeModTag(ABSTRACT)
if (flags.is(Trait)) writeModTag(TRAIT)
if flags.is(SuperTrait) then writeModTag(SUPERTRAIT)
if (flags.is(Covariant)) writeModTag(COVARIANT)
if (flags.is(Contravariant)) writeModTag(CONTRAVARIANT)
if (flags.is(Opaque)) writeModTag(OPAQUE)
if (flags.is(Open)) writeModTag(OPEN)
}
}
private def isUnpicklable(owner: Symbol, ann: Annotation)(using Context) = ann match {
case Annotation.Child(sym) => sym.isInaccessibleChildOf(owner)
// If child annotation refers to a local class or enum value under
// a different toplevel class, it is impossible to pickle a reference to it.
// Such annotations will be reconstituted when unpickling the child class.
// See tests/pickling/i3149.scala
case _ =>
ann.symbol == defn.BodyAnnot // inline bodies are reconstituted automatically when unpickling
}
def pickleAnnotation(owner: Symbol, ann: Annotation)(using Context): Unit = {
if (!isUnpicklable(owner, ann)) {
writeByte(ANNOTATION)
withLength { pickleType(ann.symbol.typeRef); pickleTree(ann.tree) }
}
}
// ---- main entry points ---------------------------------------
def pickle(trees: List[Tree])(using Context): Unit = {
trees.foreach(tree => if (!tree.isEmpty) pickleTree(tree))
def missing = forwardSymRefs.keysIterator.map(sym => sym.showLocated + "(line " + sym.srcPos.line + ")").toList
assert(forwardSymRefs.isEmpty, i"unresolved symbols: $missing%, % when pickling ${ctx.source}")
}
def compactify(): Unit = {
buf.compactify()
def updateMapWithDeltas(mp: MutableSymbolMap[Addr]) =
for (key <- mp.keysIterator.toBuffer[Symbol]) mp(key) = adjusted(mp(key))
updateMapWithDeltas(symRefs)
}
}