/
ClassfileParser.scala
1316 lines (1165 loc) · 49.8 KB
/
ClassfileParser.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package dotty.tools
package dotc
package core
package classfile
import dotty.tools.tasty.{ TastyReader, TastyHeaderUnpickler }
import Contexts._, Symbols._, Types._, Names._, StdNames._, NameOps._, Scopes._, Decorators._
import SymDenotations._, unpickleScala2.Scala2Unpickler._, Constants._, Annotations._, util.Spans._
import Phases._
import NameKinds.DefaultGetterName
import ast.{ tpd, untpd }
import ast.tpd._, util._
import java.io.{ ByteArrayInputStream, ByteArrayOutputStream, DataInputStream, IOException }
import java.lang.Integer.toHexString
import java.net.URLClassLoader
import java.util.UUID
import scala.collection.immutable
import scala.collection.mutable.{ ListBuffer, ArrayBuffer }
import scala.annotation.switch
import typer.Checking.checkNonCyclic
import io.{AbstractFile, PlainFile, ZipArchive}
import scala.util.control.NonFatal
object ClassfileParser {
/** Marker trait for unpicklers that can be embedded in classfiles. */
trait Embedded
/** Indicate that there is nothing to unpickle and the corresponding symbols can
* be invalidated. */
object NoEmbedded extends Embedded
/** Replace raw types with wildcard applications */
def cook(using Context): TypeMap = new TypeMap {
def apply(tp: Type): Type = tp match {
case tp: TypeRef if tp.symbol.typeParams.nonEmpty =>
AppliedType(tp, tp.symbol.typeParams.map(Function.const(TypeBounds.empty)))
case tp @ AppliedType(tycon, args) =>
// disregard tycon itself, but map over it to visit the prefix
tp.derivedAppliedType(mapOver(tycon), args.mapConserve(this))
case tp @ TempPolyType(_, tpe) =>
val tpe1 = this(tpe)
if (tpe1 eq tpe) tp else tp.copy(tpe = tpe1)
case tp @ TempClassInfoType(parents, _, _) =>
val parents1 = parents.mapConserve(this)
if (parents eq parents1) tp else tp.copy(parentTypes = parents1)
case _ =>
mapOver(tp)
}
}
}
class ClassfileParser(
classfile: AbstractFile,
classRoot: ClassDenotation,
moduleRoot: ClassDenotation)(ictx: Context) {
//println(s"parsing ${classRoot.name.debugString} ${moduleRoot.name.debugString}")
import ClassfileConstants._
import ClassfileParser._
protected val staticModule: Symbol = moduleRoot.sourceModule(using ictx)
protected val instanceScope: MutableScope = newScope // the scope of all instance definitions
protected val staticScope: MutableScope = newScope // the scope of all static definitions
protected var pool: ConstantPool = _ // the classfile's constant pool
protected var currentClassName: SimpleName = _ // JVM name of the current class
protected var classTParams: Map[Name, Symbol] = Map()
private var Scala2UnpicklingMode = Mode.Scala2Unpickling
classRoot.info = NoLoader().withDecls(instanceScope)
moduleRoot.info = NoLoader().withDecls(staticScope).withSourceModule(staticModule)
private def currentIsTopLevel(using Context) = classRoot.owner.is(Flags.PackageClass)
private def mismatchError(className: SimpleName) =
throw new IOException(s"class file '${classfile.canonicalPath}' has location not matching its contents: contains class $className")
def run()(using Context): Option[Embedded] = try ctx.base.reusableDataReader.withInstance { reader =>
implicit val reader2 = reader.reset(classfile)
report.debuglog("[class] >> " + classRoot.fullName)
parseHeader()
this.pool = new ConstantPool
val res = parseClass()
this.pool = null
res
}
catch {
case e: RuntimeException =>
if (ctx.debug) e.printStackTrace()
throw new IOException(
i"""class file ${classfile.canonicalPath} is broken, reading aborted with ${e.getClass}
|${Option(e.getMessage).getOrElse("")}""")
}
private def parseHeader()(using in: DataReader): Unit = {
val magic = in.nextInt
if (magic != JAVA_MAGIC)
throw new IOException(s"class file '${classfile}' has wrong magic number 0x${toHexString(magic)}, should be 0x${toHexString(JAVA_MAGIC)}")
val minorVersion = in.nextChar.toInt
val majorVersion = in.nextChar.toInt
if ((majorVersion < JAVA_MAJOR_VERSION) ||
((majorVersion == JAVA_MAJOR_VERSION) &&
(minorVersion < JAVA_MINOR_VERSION)))
throw new IOException(
s"class file '${classfile}' has unknown version $majorVersion.$minorVersion, should be at least $JAVA_MAJOR_VERSION.$JAVA_MINOR_VERSION")
}
/** Return the class symbol of the given name. */
def classNameToSymbol(name: Name)(using Context): Symbol = innerClasses.get(name.toString) match {
case Some(entry) => innerClasses.classSymbol(entry)
case None => requiredClass(name)
}
var sawPrivateConstructor: Boolean = false
def parseClass()(using ctx: Context, in: DataReader): Option[Embedded] = {
val jflags = in.nextChar
val isAnnotation = hasAnnotation(jflags)
val sflags = classTranslation.flags(jflags)
val isEnum = (jflags & JAVA_ACC_ENUM) != 0
val nameIdx = in.nextChar
currentClassName = pool.getClassName(nameIdx).name
if (currentIsTopLevel &&
currentClassName != classRoot.fullName.toSimpleName &&
currentClassName != classRoot.fullName.encode.toSimpleName)
mismatchError(currentClassName)
addEnclosingTParams()
/** Parse parents for Java classes. For Scala, return AnyRef, since the real type will be unpickled.
* Updates the read pointer of 'in'. */
def parseParents: List[Type] = {
val superType =
if (isAnnotation) {
in.nextChar
defn.AnnotationClass.typeRef
}
else if (classRoot.symbol == defn.ComparableClass ||
classRoot.symbol == defn.JavaCloneableClass ||
classRoot.symbol == defn.JavaSerializableClass) {
// Treat these interfaces as universal traits
in.nextChar
defn.AnyType
}
else
pool.getSuperClass(in.nextChar).typeRef
val ifaceCount = in.nextChar
var ifaces = for (i <- (0 until ifaceCount).toList) yield pool.getSuperClass(in.nextChar).typeRef
// Dotty deviation: was
// var ifaces = for (i <- List.range(0, ifaceCount)) ...
// This does not typecheck because the type parameter of List is now lower-bounded by Int | Char.
// Consequently, no best implicit for the "Integral" evidence parameter of "range"
// is found. Previously, this worked because of weak conformance, which has been dropped.
if (isAnnotation) ifaces = defn.ClassfileAnnotationClass.typeRef :: ifaces
superType :: ifaces
}
val result = unpickleOrParseInnerClasses()
if (!result.isDefined) {
var classInfo: Type = TempClassInfoType(parseParents, instanceScope, classRoot.symbol)
// might be reassigned by later parseAttributes
val staticInfo = TempClassInfoType(List(), staticScope, moduleRoot.symbol)
enterOwnInnerClasses()
classRoot.setFlag(sflags)
moduleRoot.setFlag(Flags.JavaDefined | Flags.ModuleClassCreationFlags)
val privateWithin = getPrivateWithin(jflags)
classRoot.setPrivateWithin(privateWithin)
moduleRoot.setPrivateWithin(privateWithin)
moduleRoot.sourceModule.setPrivateWithin(privateWithin)
for (i <- 0 until in.nextChar) parseMember(method = false)
for (i <- 0 until in.nextChar) parseMember(method = true)
classRoot.registerCompanion(moduleRoot.symbol)
moduleRoot.registerCompanion(classRoot.symbol)
setClassInfo(moduleRoot, staticInfo, fromScala2 = false)
classInfo = parseAttributes(classRoot.symbol).complete(classInfo)
if (isAnnotation)
// classInfo must be a TempClassInfoType and not a TempPolyType,
// because Java annotations cannot have type parameters.
addAnnotationConstructor(classInfo.asInstanceOf[TempClassInfoType])
setClassInfo(classRoot, classInfo, fromScala2 = false)
}
else if (result == Some(NoEmbedded))
for (sym <- List(moduleRoot.sourceModule, moduleRoot.symbol, classRoot.symbol)) {
classRoot.owner.asClass.delete(sym)
if (classRoot.owner == defn.ScalaShadowingPackage.moduleClass)
// Symbols in scalaShadowing are also added to scala
defn.ScalaPackageClass.delete(sym)
sym.markAbsent()
}
result
}
/** Add type parameters of enclosing classes */
def addEnclosingTParams()(using Context): Unit = {
var sym = classRoot.owner
while (sym.isClass && !sym.is(Flags.ModuleClass)) {
for (tparam <- sym.typeParams)
classTParams = classTParams.updated(tparam.name, tparam)
sym = sym.owner
}
}
def parseMember(method: Boolean)(using ctx: Context, in: DataReader): Unit = {
val start = indexCoord(in.bp)
val jflags = in.nextChar
val sflags =
if (method) Flags.Method | methodTranslation.flags(jflags)
else fieldTranslation.flags(jflags)
val preName = pool.getName(in.nextChar)
if (!sflags.isOneOf(Flags.PrivateOrArtifact) || preName.name == nme.CONSTRUCTOR) {
val sig = pool.getExternalName(in.nextChar).value
val completer = MemberCompleter(preName.name, jflags, sig)
val member = newSymbol(
getOwner(jflags), preName.name, sflags, completer,
getPrivateWithin(jflags), coord = start)
completer.attrCompleter = parseAttributes(member)
getScope(jflags).enter(member)
}
else {
in.nextChar // info
skipAttributes()
}
}
class MemberCompleter(name: SimpleName, jflags: Int, sig: String) extends LazyType {
var attrCompleter: AttributeCompleter = null
def complete(denot: SymDenotation)(using Context): Unit = {
val sym = denot.symbol
val isEnum = (jflags & JAVA_ACC_ENUM) != 0
val isConstructor = name eq nme.CONSTRUCTOR
/** Strip leading outer param from constructor and trailing access tag for
* private inner constructors.
*/
def normalizeConstructorParams() = innerClasses.get(currentClassName.toString) match {
case Some(entry) if !isStatic(entry.jflags) =>
val mt @ MethodTpe(paramNames, paramTypes, resultType) = denot.info
var normalizedParamNames = paramNames.tail
var normalizedParamTypes = paramTypes.tail
if ((jflags & JAVA_ACC_SYNTHETIC) != 0) {
// SI-7455 strip trailing dummy argument ("access constructor tag") from synthetic constructors which
// are added when an inner class needs to access a private constructor.
normalizedParamNames = paramNames.dropRight(1)
normalizedParamTypes = paramTypes.dropRight(1)
}
denot.info = mt.derivedLambdaType(normalizedParamNames, normalizedParamTypes, resultType)
case _ =>
}
/** Make return type of constructor be the enclosing class type,
* and make constructor type polymorphic in the type parameters of the class
*/
def normalizeConstructorInfo() = {
val rt = classRoot.typeRef appliedTo (classRoot.typeParams map (_.typeRef))
def resultType(tpe: Type): Type = tpe match {
case mt @ MethodType(paramNames) => mt.derivedLambdaType(paramNames, mt.paramInfos, rt)
case pt : PolyType => pt.derivedLambdaType(pt.paramNames, pt.paramInfos, resultType(pt.resType))
}
denot.info = resultType(denot.info)
addConstructorTypeParams(denot)
}
val isVarargs = denot.is(Flags.Method) && (jflags & JAVA_ACC_VARARGS) != 0
denot.info = sigToType(sig, isVarargs = isVarargs)
if (isConstructor) normalizeConstructorParams()
denot.info = translateTempPoly(attrCompleter.complete(denot.info, isVarargs))
if (isConstructor) normalizeConstructorInfo()
if (ctx.explicitNulls) denot.info = JavaNullInterop.nullifyMember(denot.symbol, denot.info, isEnum)
// seal java enums
if (isEnum) {
val enumClass = sym.owner.linkedClass
if (!enumClass.exists)
report.warning(s"no linked class for java enum $sym in ${sym.owner}. A referencing class file might be missing an InnerClasses entry.")
else {
if (!enumClass.is(Flags.Sealed)) enumClass.setFlag(Flags.AbstractSealed)
enumClass.addAnnotation(Annotation.Child(sym, NoSpan))
}
}
}
}
def constantTagToType(tag: Int)(using Context): Type =
(tag: @switch) match {
case BYTE_TAG => defn.ByteType
case CHAR_TAG => defn.CharType
case DOUBLE_TAG => defn.DoubleType
case FLOAT_TAG => defn.FloatType
case INT_TAG => defn.IntType
case LONG_TAG => defn.LongType
case SHORT_TAG => defn.ShortType
case VOID_TAG => defn.UnitType
case BOOL_TAG => defn.BooleanType
}
/** As specified in https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.7.16.1,
* an annotation argument of type boolean, byte, char or short will
* be represented as a CONSTANT_INTEGER, so we need to convert it to
* produce a correctly-typed tree. We need to do this each time the
* constant is accessed instead of storing the result of the
* conversion in the `values` cache, because the same constant might
* be used for annotation arguments of different type.
*/
def convertTo(ct: Constant, pt: Type)(using Context): Constant = {
if (pt eq defn.BooleanType) && ct.tag == IntTag then
Constant(ct.value != 0)
else
ct.convertTo(pt)
}
private def sigToType(sig: String, owner: Symbol = null, isVarargs: Boolean = false)(using Context): Type = {
var index = 0
val end = sig.length
def accept(ch: Char): Unit = {
assert(sig(index) == ch, (sig(index), ch))
index += 1
}
def subName(isDelimiter: Char => Boolean): SimpleName = {
val start = index
while (!isDelimiter(sig(index))) { index += 1 }
termName(sig.slice(start, index))
}
// Warning: sigToType contains nested completers which might be forced in a later run!
// So local methods need their own ctx parameters.
def sig2type(tparams: immutable.Map[Name, Symbol], skiptvs: Boolean)(using Context): Type = {
val tag = sig(index); index += 1
(tag: @switch) match {
case 'L' =>
def processInner(tp: Type): Type = tp match {
case tp: TypeRef if !tp.symbol.owner.is(Flags.ModuleClass) =>
TypeRef(processInner(tp.prefix.widen), tp.symbol.asType)
case _ =>
tp
}
def processClassType(tp: Type): Type = tp match {
case tp: TypeRef =>
if (sig(index) == '<') {
accept('<')
val argsBuf = if (skiptvs) null else new ListBuffer[Type]
while (sig(index) != '>') {
val arg = sig(index) match {
case variance @ ('+' | '-' | '*') =>
index += 1
variance match {
case '+' => TypeBounds.upper(sig2type(tparams, skiptvs))
case '-' =>
val argTp = sig2type(tparams, skiptvs)
// Interpret `sig2type` returning `Any` as "no bounds";
// morally equivalent to TypeBounds.empty, but we're representing Java code, so use FromJavaObjectType as the upper bound
if (argTp.typeSymbol == defn.AnyClass) TypeBounds.upper(defn.FromJavaObjectType)
else TypeBounds(argTp, defn.FromJavaObjectType)
case '*' => TypeBounds.upper(defn.FromJavaObjectType)
}
case _ => sig2type(tparams, skiptvs)
}
if (argsBuf != null) argsBuf += arg
}
accept('>')
if (skiptvs) tp else tp.appliedTo(argsBuf.toList)
}
else tp
case tp =>
assert(sig(index) != '<', tp)
tp
}
val classSym = classNameToSymbol(subName(c => c == ';' || c == '<'))
val classTpe = if (classSym eq defn.ObjectClass) defn.FromJavaObjectType else classSym.typeRef
var tpe = processClassType(processInner(classTpe))
while (sig(index) == '.') {
accept('.')
val name = subName(c => c == ';' || c == '<' || c == '.').toTypeName
val clazz = tpe.member(name).symbol
tpe = processClassType(processInner(TypeRef(tpe, clazz)))
}
accept(';')
tpe
case ARRAY_TAG =>
while ('0' <= sig(index) && sig(index) <= '9') index += 1
val elemtp = sig2type(tparams, skiptvs)
defn.ArrayOf(elemtp.translateJavaArrayElementType)
case '(' =>
def isMethodEnd(i: Int) = sig(i) == ')'
def isArray(i: Int) = sig(i) == '['
/** Is this a repeated parameter type?
* This is true if we're in a vararg method and this is the last parameter.
*/
def isRepeatedParam(i: Int): Boolean =
if !isVarargs then return false
var cur = i
// Repeated parameters are represented as arrays
if !isArray(cur) then return false
// Handle nested arrays: int[]...
while isArray(cur) do
cur += 1
// Simple check to see if we're the last parameter: there should be no
// array in the signature until the method end.
while !isMethodEnd(cur) do
if isArray(cur) then return false
cur += 1
true
end isRepeatedParam
val paramtypes = new ListBuffer[Type]()
var paramnames = new ListBuffer[TermName]()
while !isMethodEnd(index) do
paramnames += nme.syntheticParamName(paramtypes.length)
paramtypes += {
if isRepeatedParam(index) then
index += 1
val elemType = sig2type(tparams, skiptvs)
// `ElimRepeated` is responsible for correctly erasing this.
defn.RepeatedParamType.appliedTo(elemType)
else
sig2type(tparams, skiptvs)
}
index += 1
val restype = sig2type(tparams, skiptvs)
JavaMethodType(paramnames.toList, paramtypes.toList, restype)
case 'T' =>
val n = subName(';'.==).toTypeName
index += 1
//assert(tparams contains n, s"classTparams = $classTParams, tparams = $tparams, key = $n")
if (skiptvs) defn.AnyType else tparams(n).typeRef
case tag =>
constantTagToType(tag)
}
}
// sig2type(tparams, skiptvs)
def sig2typeBounds(tparams: immutable.Map[Name, Symbol], skiptvs: Boolean)(using Context): Type = {
val ts = new ListBuffer[Type]
while (sig(index) == ':') {
index += 1
if (sig(index) != ':') { // guard against empty class bound
val tp = sig2type(tparams, skiptvs)
if (!skiptvs)
ts += cook(tp)
}
}
if (!skiptvs) {
val bound = if ts.isEmpty then defn.AnyType else ts.reduceLeft(AndType.apply)
TypeBounds.upper(bound)
}
else NoType
}
var tparams = classTParams
def typeParamCompleter(start: Int) = new LazyType {
def complete(denot: SymDenotation)(using Context): Unit = {
val savedIndex = index
try {
index = start
denot.info =
checkNonCyclic( // we need the checkNonCyclic call to insert LazyRefs for F-bounded cycles
denot.symbol,
sig2typeBounds(tparams, skiptvs = false),
reportErrors = false)
}
finally
index = savedIndex
}
}
val newTParams = new ListBuffer[Symbol]()
if (sig(index) == '<') {
assert(owner != null)
index += 1
val start = index
while (sig(index) != '>') {
val tpname = subName(':'.==).toTypeName
val s = newSymbol(
owner, tpname, owner.typeParamCreationFlags,
typeParamCompleter(index), coord = indexCoord(index))
if (owner.isClass) owner.asClass.enter(s)
tparams = tparams + (tpname -> s)
sig2typeBounds(tparams, skiptvs = true)
newTParams += s
}
index += 1
}
val ownTypeParams = newTParams.toList.asInstanceOf[List[TypeSymbol]]
val tpe =
if ((owner == null) || !owner.isClass)
sig2type(tparams, skiptvs = false)
else {
classTParams = tparams
val parents = new ListBuffer[Type]()
while (index < end)
parents += sig2type(tparams, skiptvs = false) // here the variance doesn't matter
TempClassInfoType(parents.toList, instanceScope, owner)
}
if (ownTypeParams.isEmpty) tpe else TempPolyType(ownTypeParams, tpe)
}
// sigToType
class EnumTag(sig: String, name: NameOrString) {
def toTree(using ctx: Context): untpd.Tree = {
val enumClassTp = sigToType(sig)
val enumModuleClass = enumClassTp.classSymbol.companionModule
val tmref = TermRef(enumModuleClass.termRef, name.name)
untpd.TypedSplice(ref(tmref))
}
}
def parseAnnotArg(skip: Boolean = false)(using ctx: Context, in: DataReader): Option[untpd.Tree | EnumTag] = {
// If we encounter an empty array literal, we need the type of the corresponding
// parameter to properly type it, but that would require forcing the annotation
// early. To avoid this we store annotation arguments as untyped trees
// ... but constants need to actually be typed with a ConstantType, so we
// can't rely on type inference, and type them early.
def lit(c: Constant): untpd.Tree = untpd.TypedSplice(tpd.Literal(c))
val tag = in.nextByte.toChar
val index = in.nextChar
tag match {
case STRING_TAG =>
if (skip) None else Some(lit(Constant(pool.getName(index).value)))
case BOOL_TAG | BYTE_TAG | CHAR_TAG | SHORT_TAG =>
if (skip) None else {
val constant = convertTo(pool.getConstant(index), constantTagToType(tag))
Some(lit(constant))
}
case INT_TAG | LONG_TAG | FLOAT_TAG | DOUBLE_TAG =>
if (skip) None else Some(lit(pool.getConstant(index)))
case CLASS_TAG =>
if (skip) None else Some(lit(Constant(pool.getType(index))))
case ENUM_TAG =>
val sig = pool.getExternalName(index).value
val enumCaseName = pool.getName(in.nextChar)
if (skip) None else Some(EnumTag(sig, enumCaseName))
case ARRAY_TAG =>
val arr = new ArrayBuffer[untpd.Tree]()
var hasError = false
for (i <- 0 until index)
parseAnnotArg(skip) match {
case Some(c: untpd.Tree) => arr += c
case Some(tag: EnumTag) => arr += tag.toTree
case None => hasError = true
}
if (hasError) None
else if (skip) None
else {
val elems = arr.toList
Some(untpd.JavaSeqLiteral(elems, untpd.TypeTree()))
}
case ANNOTATION_TAG =>
parseAnnotation(index, skip).map(_.untpdTree)
}
}
class ClassfileAnnotation(annotType: Type, lazyArgs: List[(NameOrString, untpd.Tree | EnumTag)]) extends LazyAnnotation {
private def args(using Context): List[untpd.Tree] =
lazyArgs.map {
case (name, tree: untpd.Tree) => untpd.NamedArg(name.name, tree).withSpan(NoSpan)
case (name, tag: EnumTag) => untpd.NamedArg(name.name, tag.toTree).withSpan(NoSpan)
}
protected var mySym: Symbol | (Context ?=> Symbol) =
(using ctx: Context) => annotType.classSymbol
protected var myTree: Tree | (Context ?=> Tree) =
(using ctx: Context) => untpd.resolveConstructor(annotType, args)
def untpdTree(using Context): untpd.Tree =
untpd.New(untpd.TypeTree(annotType), List(args))
}
/** Parse and return a single annotation. If it is malformed,
* return None.
*/
def parseAnnotation(attrNameIndex: Char, skip: Boolean = false)(using ctx: Context, in: DataReader): Option[ClassfileAnnotation] = try {
val attrType = pool.getType(attrNameIndex)
attrType match
case tp: TypeRef =>
// Silently ignore missing annotation classes like javac
if tp.denot.infoOrCompleter.isInstanceOf[StubInfo] then
if ctx.debug then
report.warning(i"Error while parsing annotations in ${classfile}: annotation class $tp not present on classpath")
return None
case _ =>
val nargs = in.nextChar
val argbuf = new ListBuffer[(NameOrString, untpd.Tree | EnumTag)]
var hasError = false
for (i <- 0 until nargs) {
val name = pool.getName(in.nextChar)
parseAnnotArg(skip) match {
case Some(arg) =>
argbuf += name -> arg
case None =>
hasError = !skip
}
}
if (hasError || skip) None
else Some(ClassfileAnnotation(attrType, argbuf.toList))
}
catch {
case f: FatalError => throw f // don't eat fatal errors, they mean a class was not found
case NonFatal(ex) =>
// We want to be robust when annotations are unavailable, so the very least
// we can do is warn the user about the exception
// There was a reference to ticket 1135, but that is outdated: a reference to a class not on
// the classpath would *not* end up here. A class not found is signaled
// with a `FatalError` exception, handled above. Here you'd end up after a NPE (for example),
// and that should never be swallowed silently.
report.warning("Caught: " + ex + " while parsing annotations in " + classfile)
if (ctx.debug) ex.printStackTrace()
None // ignore malformed annotations
}
/** A completer for attributes
*
* Top-level classes complete attributes eagerly, while members complete lazily.
*
* @note We cannot simply store the bytes of attributes, as the bytes may
* contain references to the constant pool, where the constants are loaded
* lazily.
*/
class AttributeCompleter(sym: Symbol) {
var sig: String = null
var constant: Constant = null
var exceptions: List[NameOrString] = Nil
var annotations: List[Annotation] = Nil
def complete(tp: Type, isVarargs: Boolean = false)(using Context): Type = {
val updatedType =
if sig == null then tp
else {
val newType = sigToType(sig, sym, isVarargs)
if (ctx.debug && ctx.verbose)
println("" + sym + "; signature = " + sig + " type = " + newType)
newType
}
val newType =
if this.constant != null then
val ct = convertTo(this.constant, updatedType)
if ct != null then ConstantType(ct) else updatedType
else updatedType
annotations.foreach(annot => sym.addAnnotation(annot))
exceptions.foreach { ex =>
val cls = getClassSymbol(ex.name)
sym.addAnnotation(ThrowsAnnotation(cls.asClass))
}
cook.apply(newType)
}
}
def parseAttributes(sym: Symbol)(using ctx: Context, in: DataReader): AttributeCompleter = {
val res = new AttributeCompleter(sym)
def parseAttribute(): Unit = {
val attrName = pool.getName(in.nextChar).name.toTypeName
val attrLen = in.nextInt
val end = in.bp + attrLen
attrName match {
case tpnme.SignatureATTR =>
val sig = pool.getExternalName(in.nextChar)
res.sig = sig.value
case tpnme.SyntheticATTR =>
sym.setFlag(Flags.SyntheticArtifact)
case tpnme.BridgeATTR =>
sym.setFlag(Flags.Bridge)
case tpnme.DeprecatedATTR =>
val msg = Literal(Constant("see corresponding Javadoc for more information."))
val since = Literal(Constant(""))
res.annotations ::= Annotation.deferredSymAndTree(defn.DeprecatedAnnot) {
New(defn.DeprecatedAnnot.typeRef, msg :: since :: Nil)
}
case tpnme.ConstantValueATTR =>
val c = pool.getConstant(in.nextChar)
if (c ne null) res.constant = c
else report.warning(s"Invalid constant in attribute of ${sym.showLocated} while parsing ${classfile}")
case tpnme.AnnotationDefaultATTR =>
sym.addAnnotation(Annotation(defn.AnnotationDefaultAnnot, Nil))
// Java annotations on classes / methods / fields with RetentionPolicy.RUNTIME
case tpnme.RuntimeVisibleAnnotationATTR
| tpnme.RuntimeInvisibleAnnotationATTR =>
parseAnnotations(attrLen)
// TODO 1: parse runtime visible annotations on parameters
// case tpnme.RuntimeParamAnnotationATTR
// TODO 2: also parse RuntimeInvisibleParamAnnotation
// i.e. java annotations with RetentionPolicy.CLASS?
case tpnme.ExceptionsATTR =>
parseExceptions(attrLen)
case tpnme.CodeATTR =>
in.skip(attrLen)
// flag test will trigger completion and cycles, thus have to be lazy
if (sym.owner.flagsUNSAFE.isAllOf(Flags.JavaInterface)) {
sym.resetFlag(Flags.Deferred)
sym.owner.resetFlag(Flags.PureInterface)
report.log(s"$sym in ${sym.owner} is a java 8+ default method.")
}
case _ =>
}
in.bp = end
}
/**
* Parse the "Exceptions" attribute which denotes the exceptions
* thrown by a method.
*/
def parseExceptions(len: Int): Unit = {
val nClasses = in.nextChar
for (n <- 0 until nClasses) {
// FIXME: this performs an equivalent of getExceptionTypes instead of getGenericExceptionTypes (SI-7065)
val cls = pool.getClassName(in.nextChar.toInt)
res.exceptions ::= cls
}
}
/** Parse a sequence of annotations and attaches them to the
* current symbol sym, except for the ScalaSignature annotation that it returns, if it is available. */
def parseAnnotations(len: Int): Unit = {
val nAttr = in.nextChar
for (n <- 0 until nAttr)
parseAnnotation(in.nextChar) match {
case Some(annot) =>
sym.addAnnotation(annot)
case None =>
}
}
// begin parseAttributes
for (i <- 0 until in.nextChar)
parseAttribute()
res
}
/** Annotations in Scala are assumed to get all their arguments as constructor
* parameters. For Java annotations we need to fake it by making up the constructor.
*/
def addAnnotationConstructor(classInfo: TempClassInfoType)(using Context): Unit =
newSymbol(
owner = classRoot.symbol,
name = nme.CONSTRUCTOR,
flags = Flags.Synthetic | Flags.JavaDefined | Flags.Method,
info = new AnnotConstructorCompleter(classInfo)
).entered
class AnnotConstructorCompleter(classInfo: TempClassInfoType) extends LazyType {
def complete(denot: SymDenotation)(using Context): Unit = {
val attrs = classInfo.decls.toList.filter(sym => sym.isTerm && sym != denot.symbol)
val paramNames = attrs.map(_.name.asTermName)
val paramTypes = attrs.map(_.info.resultType)
denot.info = MethodType(paramNames, paramTypes, classRoot.typeRef)
}
}
/** Enter own inner classes in the right scope. It needs the scopes to be set up,
* and implicitly current class' superclasses.
*/
private def enterOwnInnerClasses()(using Context, DataReader): Unit = {
def enterClassAndModule(entry: InnerClassEntry, file: AbstractFile, jflags: Int) =
SymbolLoaders.enterClassAndModule(
getOwner(jflags),
entry.originalName,
new ClassfileLoader(file),
classTranslation.flags(jflags),
getScope(jflags))
for entry <- innerClasses.valuesIterator do
// create a new class member for immediate inner classes
if entry.outer.name == currentClassName then
val file = ctx.platform.classPath.findClassFile(entry.externalName.toString) getOrElse {
throw new AssertionError(entry.externalName)
}
enterClassAndModule(entry, file, entry.jflags)
}
// Nothing$ and Null$ were incorrectly emitted with a Scala attribute
// instead of ScalaSignature before 2.13.0-M2, see https://github.com/scala/scala/pull/5952
private val scalaUnpickleWhitelist = List(tpnme.nothingClass, tpnme.nullClass)
/** Parse inner classes. Expects `in.bp` to point to the superclass entry.
* Restores the old `bp`.
* @return true iff classfile is from Scala, so no Java info needs to be read.
*/
def unpickleOrParseInnerClasses()(using ctx: Context, in: DataReader): Option[Embedded] = {
val oldbp = in.bp
try {
skipSuperclasses()
skipMembers() // fields
skipMembers() // methods
val attrs = in.nextChar
val attrbp = in.bp
def scan(target: TypeName): Boolean = {
in.bp = attrbp
var i = 0
while (i < attrs && pool.getName(in.nextChar).name.toTypeName != target) {
val attrLen = in.nextInt
in.skip(attrLen)
i += 1
}
i < attrs
}
def unpickleScala(bytes: Array[Byte]): Some[Embedded] = {
val allowed = ctx.settings.Yscala2Unpickler.value
def failUnless(cond: Boolean) =
assert(cond,
s"Unpickling ${classRoot.symbol.showLocated} from ${classRoot.symbol.associatedFile} is not allowed with -Yscala2-unpickler $allowed")
if (allowed != "always") {
failUnless(allowed != "never")
val allowedList = allowed.split(java.io.File.pathSeparator).toList
val file = classRoot.symbol.associatedFile
// Using `.toString.contains` isn't great, but it's good enough for a debug flag.
failUnless(file == null || allowedList.exists(path => file.toString.contains(path)))
}
val unpickler = new unpickleScala2.Scala2Unpickler(bytes, classRoot, moduleRoot)(ctx)
withMode(Scala2UnpicklingMode)(unpickler.run())
Some(unpickler)
}
def unpickleTASTY(bytes: Array[Byte]): Some[Embedded] = {
val unpickler = new tasty.DottyUnpickler(bytes)
unpickler.enter(roots = Set(classRoot, moduleRoot, moduleRoot.sourceModule))(using ctx.withSource(util.NoSource))
Some(unpickler)
}
def parseScalaSigBytes: Array[Byte] = {
val tag = in.nextByte.toChar
assert(tag == STRING_TAG, tag)
pool getBytes in.nextChar
}
def parseScalaLongSigBytes: Array[Byte] = {
val tag = in.nextByte.toChar
assert(tag == ARRAY_TAG, tag)
val stringCount = in.nextChar
val entries =
for (i <- 0 until stringCount) yield {
val stag = in.nextByte.toChar
assert(stag == STRING_TAG, stag)
in.nextChar.toInt
}
pool.getBytes(entries.toList)
}
if (scan(tpnme.TASTYATTR)) {
val attrLen = in.nextInt
val bytes = in.nextBytes(attrLen)
if (attrLen == 16) { // A tasty attribute with that has only a UUID (16 bytes) implies the existence of the .tasty file
val tastyBytes: Array[Byte] = classfile match { // TODO: simplify when #3552 is fixed
case classfile: io.ZipArchive#Entry => // We are in a jar
val path = classfile.parent.lookupName(
classfile.name.stripSuffix(".class") + ".tasty", directory = false
)
if (path != null) {
val stream = path.input
try {
val tastyOutStream = new ByteArrayOutputStream()
val buffer = new Array[Byte](1024)
var read = stream.read(buffer, 0, buffer.length)
while (read != -1) {
tastyOutStream.write(buffer, 0, read)
read = stream.read(buffer, 0, buffer.length)
}
tastyOutStream.flush()
tastyOutStream.toByteArray
} finally {
stream.close()
}
}
else {
report.error(s"Could not find $path in ${classfile.underlyingSource}")
Array.empty
}
case _ =>
if (classfile.jpath == null) {
report.error("Could not load TASTY from .tasty for virtual file " + classfile)
Array.empty
} else {
val plainFile = new PlainFile(io.File(classfile.jpath).changeExtension("tasty"))
if (plainFile.exists) plainFile.toByteArray
else {
report.error("Could not find " + plainFile)
Array.empty
}
}
}
if (tastyBytes.nonEmpty) {
val reader = new TastyReader(bytes, 0, 16)
val expectedUUID = new UUID(reader.readUncompressedLong(), reader.readUncompressedLong())
val tastyUUID = new TastyHeaderUnpickler(tastyBytes).readHeader()
if (expectedUUID != tastyUUID)
report.warning(s"$classfile is out of sync with its TASTy file. Loaded TASTy file. Try cleaning the project to fix this issue", NoSourcePosition)
return unpickleTASTY(tastyBytes)
}
}
else return unpickleTASTY(bytes)
}
if (scan(tpnme.ScalaATTR) && !scalaUnpickleWhitelist.contains(classRoot.name))
// To understand the situation, it's helpful to know that:
// - Scalac emits the `ScalaSig` attribute for classfiles with pickled information
// and the `Scala` attribute for everything else.
// - Dotty emits the `TASTY` attribute for classfiles with pickled information
// and the `Scala` attribute for _every_ classfile.
//
// Therefore, if the `Scala` attribute is present but the `TASTY`
// attribute isn't, this classfile is a compilation artifact.
return Some(NoEmbedded)
if (scan(tpnme.RuntimeVisibleAnnotationATTR) || scan(tpnme.RuntimeInvisibleAnnotationATTR)) {
val attrLen = in.nextInt
val nAnnots = in.nextChar
var i = 0
while (i < nAnnots) {
val attrClass = pool.getType(in.nextChar).typeSymbol
val nArgs = in.nextChar
var j = 0
while (j < nArgs) {
val argName = pool.getName(in.nextChar)
if (argName.name == nme.bytes) {
if (attrClass == defn.ScalaSignatureAnnot)
return unpickleScala(parseScalaSigBytes)
else if (attrClass == defn.ScalaLongSignatureAnnot)
return unpickleScala(parseScalaLongSigBytes)
else if (attrClass == defn.TASTYSignatureAnnot)
return unpickleTASTY(parseScalaSigBytes)
else if (attrClass == defn.TASTYLongSignatureAnnot)
return unpickleTASTY(parseScalaLongSigBytes)
}
parseAnnotArg(skip = true)
j += 1
}
i += 1
}
}
if (scan(tpnme.InnerClassesATTR)) {
val attrLen = in.nextInt
val entries = in.nextChar.toInt
for (i <- 0 until entries) {
val innerIndex = in.nextChar
val outerIndex = in.nextChar
val nameIndex = in.nextChar
val jflags = in.nextChar
if (innerIndex != 0 && outerIndex != 0 && nameIndex != 0) {
val inner = pool.getClassName(innerIndex)
val outer = pool.getClassName(outerIndex)
val name = pool.getName(nameIndex)
val entry = InnerClassEntry(inner, outer, name, jflags)
innerClasses(inner.value) = entry