/
GenJVM.scala
1991 lines (1722 loc) · 77.1 KB
/
GenJVM.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
/* NSC -- new Scala compiler
* Copyright 2005-2011 LAMP/EPFL
* @author Iulian Dragos
*/
package scala.tools.nsc
package backend.jvm
import java.io.{ByteArrayOutputStream, DataOutputStream, OutputStream }
import java.nio.ByteBuffer
import scala.collection.{ mutable, immutable }
import scala.reflect.internal.pickling.{ PickleFormat, PickleBuffer }
import scala.tools.reflect.SigParser
import scala.tools.nsc.symtab._
import scala.tools.nsc.util.{ SourceFile, NoSourceFile }
import scala.reflect.internal.ClassfileConstants._
import ch.epfl.lamp.fjbg._
import JAccessFlags._
import JObjectType.{ JAVA_LANG_STRING, JAVA_LANG_OBJECT }
import java.util.jar.{ JarEntry, JarOutputStream }
import scala.tools.nsc.io.AbstractFile
import language.postfixOps
/** This class ...
*
* @author Iulian Dragos
* @version 1.0
*
*/
abstract class GenJVM extends SubComponent with GenJVMUtil with GenAndroid with BytecodeWriters {
import global._
import icodes._
import icodes.opcodes._
import definitions._
val phaseName = "jvm"
/** Create a new phase */
override def newPhase(p: Phase): Phase = new JvmPhase(p)
private def outputDirectory(sym: Symbol): AbstractFile =
settings.outputDirs outputDirFor beforeFlatten(sym.sourceFile)
private def getFile(base: AbstractFile, clsName: String, suffix: String): AbstractFile = {
var dir = base
val pathParts = clsName.split("[./]").toList
for (part <- pathParts.init) {
dir = dir.subdirectoryNamed(part)
}
dir.fileNamed(pathParts.last + suffix)
}
private def getFile(sym: Symbol, clsName: String, suffix: String): AbstractFile =
getFile(outputDirectory(sym), clsName, suffix)
/** JVM code generation phase
*/
class JvmPhase(prev: Phase) extends ICodePhase(prev) {
def name = phaseName
override def erasedTypes = true
def apply(cls: IClass) = sys.error("no implementation")
def isJavaEntryPoint(clasz: IClass) = {
val sym = clasz.symbol
def fail(msg: String, pos: Position = sym.pos) = {
clasz.cunit.warning(sym.pos,
sym.name + " has a main method with parameter type Array[String], but " + sym.fullName('.') + " will not be a runnable program.\n" +
" Reason: " + msg
// TODO: make this next claim true, if possible
// by generating valid main methods as static in module classes
// not sure what the jvm allows here
// + " You can still run the program by calling it as " + sym.javaSimpleName + " instead."
)
false
}
def failNoForwarder(msg: String) = {
fail(msg + ", which means no static forwarder can be generated.\n")
}
val possibles = if (sym.hasModuleFlag) (sym.tpe nonPrivateMember nme.main).alternatives else Nil
val hasApproximate = possibles exists { m =>
m.info match {
case MethodType(p :: Nil, _) => p.tpe.typeSymbol == ArrayClass
case _ => false
}
}
// At this point it's a module with a main-looking method, so either
// succeed or warn that it isn't.
hasApproximate && {
// Before erasure so we can identify generic mains.
beforeErasure {
val companion = sym.linkedClassOfClass
val companionMain = companion.tpe.member(nme.main)
if (hasJavaMainMethod(companion))
failNoForwarder("companion contains its own main method")
else if (companion.tpe.member(nme.main) != NoSymbol)
// this is only because forwarders aren't smart enough yet
failNoForwarder("companion contains its own main method (implementation restriction: no main is allowed, regardless of signature)")
else if (companion.isTrait)
failNoForwarder("companion is a trait")
// Now either succeeed, or issue some additional warnings for things which look like
// attempts to be java main methods.
else possibles exists { m =>
m.info match {
case PolyType(_, _) =>
fail("main methods cannot be generic.")
case MethodType(params, res) =>
if (res.typeSymbol :: params exists (_.isAbstractType))
fail("main methods cannot refer to type parameters or abstract types.", m.pos)
else
isJavaMainMethod(m) || fail("main method must have exact signature (Array[String])Unit", m.pos)
case tp =>
fail("don't know what this is: " + tp, m.pos)
}
}
}
}
}
override def run() {
// we reinstantiate the bytecode generator at each run, to allow the GC
// to collect everything
if (settings.debug.value)
inform("[running phase " + name + " on icode]")
if (settings.Xverify.value && !SigParser.isParserAvailable)
global.warning("signature verification requested by signature parser unavailable: signatures not checked")
if (settings.Xdce.value)
for ((sym, cls) <- icodes.classes if inliner.isClosureClass(sym) && !deadCode.liveClosures(sym))
icodes.classes -= sym
// For predictably ordered error messages.
val sortedClasses = classes.values.toList sortBy ("" + _.symbol.fullName)
val entryPoints = sortedClasses filter isJavaEntryPoint
val bytecodeWriter = settings.outputDirs.getSingleOutput match {
case Some(f) if f hasExtension "jar" =>
// If no main class was specified, see if there's only one
// entry point among the classes going into the jar.
if (settings.mainClass.isDefault) {
entryPoints map (_.symbol fullName '.') match {
case Nil =>
log("No Main-Class designated or discovered.")
case name :: Nil =>
log("Unique entry point: setting Main-Class to " + name)
settings.mainClass.value = name
case names =>
log("No Main-Class due to multiple entry points:\n " + names.mkString("\n "))
}
}
else log("Main-Class was specified: " + settings.mainClass.value)
new DirectToJarfileWriter(f.file)
case _ =>
if (settings.Ygenjavap.isDefault) {
if(settings.Ydumpclasses.isDefault)
new ClassBytecodeWriter { }
else
new ClassBytecodeWriter with DumpBytecodeWriter { }
}
else new ClassBytecodeWriter with JavapBytecodeWriter { }
}
val codeGenerator = new BytecodeGenerator(bytecodeWriter)
debuglog("Created new bytecode generator for " + classes.size + " classes.")
sortedClasses foreach { c =>
try codeGenerator.genClass(c)
catch {
case e: JCode.CodeSizeTooBigException =>
log("Skipped class %s because it has methods that are too long.".format(c))
}
}
bytecodeWriter.close()
classes.clear()
}
}
var pickledBytes = 0 // statistics
/**
* Java bytecode generator.
*
*/
class BytecodeGenerator(bytecodeWriter: BytecodeWriter) extends BytecodeUtil {
def this() = this(new ClassBytecodeWriter { })
def debugLevel = settings.debuginfo.indexOfChoice
import bytecodeWriter.writeClass
val MIN_SWITCH_DENSITY = 0.7
val INNER_CLASSES_FLAGS =
(ACC_PUBLIC | ACC_PRIVATE | ACC_PROTECTED | ACC_STATIC | ACC_FINAL | ACC_INTERFACE | ACC_ABSTRACT)
val PublicStatic = ACC_PUBLIC | ACC_STATIC
val PublicStaticFinal = ACC_PUBLIC | ACC_STATIC | ACC_FINAL
val StringBuilderClassName = javaName(definitions.StringBuilderClass)
val BoxesRunTime = "scala.runtime.BoxesRunTime"
val StringBuilderType = new JObjectType(StringBuilderClassName) // TODO use ASMType.getObjectType
val toStringType = new JMethodType(JAVA_LANG_STRING, JType.EMPTY_ARRAY) // TODO use ASMType.getMethodType
val arrayCloneType = new JMethodType(JAVA_LANG_OBJECT, JType.EMPTY_ARRAY)
val MethodTypeType = new JObjectType("java.dyn.MethodType")
val JavaLangClassType = new JObjectType("java.lang.Class")
val MethodHandleType = new JObjectType("java.dyn.MethodHandle")
// Scala attributes
val BeanInfoAttr = definitions.getRequiredClass("scala.beans.BeanInfo")
val BeanInfoSkipAttr = definitions.getRequiredClass("scala.beans.BeanInfoSkip")
val BeanDisplayNameAttr = definitions.getRequiredClass("scala.beans.BeanDisplayName")
val BeanDescriptionAttr = definitions.getRequiredClass("scala.beans.BeanDescription")
final val ExcludedForwarderFlags = {
import Flags._
// Should include DEFERRED but this breaks findMember.
( CASE | SPECIALIZED | LIFTED | PROTECTED | STATIC | EXPANDEDNAME | BridgeAndPrivateFlags )
}
// Additional interface parents based on annotations and other cues
def newParentForAttr(attr: Symbol): Option[Symbol] = attr match {
case SerializableAttr => Some(SerializableClass)
case CloneableAttr => Some(JavaCloneableClass)
case RemoteAttr => Some(RemoteInterfaceClass)
case _ => None
}
val versionPickle = {
val vp = new PickleBuffer(new Array[Byte](16), -1, 0)
assert(vp.writeIndex == 0, vp)
vp writeNat PickleFormat.MajorVersion
vp writeNat PickleFormat.MinorVersion
vp writeNat 0
vp
}
private def helperBoxTo(kind: ValueTypeKind): Tuple2[String, JMethodType] = {
val boxedType = definitions.boxedClass(kind.toType.typeSymbol)
val mtype = new JMethodType(javaType(boxedType), Array(javaType(kind)))
Pair("boxTo" + boxedType.decodedName, mtype)
}
private val jBoxTo: Map[TypeKind, Tuple2[String, JMethodType]] = Map(
BOOL -> helperBoxTo(BOOL) ,
BYTE -> helperBoxTo(BYTE) ,
CHAR -> helperBoxTo(CHAR) ,
SHORT -> helperBoxTo(SHORT) ,
INT -> helperBoxTo(INT) ,
LONG -> helperBoxTo(LONG) ,
FLOAT -> helperBoxTo(FLOAT) ,
DOUBLE -> helperBoxTo(DOUBLE)
)
private def helperUnboxTo(kind: ValueTypeKind): Tuple2[String, JMethodType] = {
val mtype = new JMethodType(javaType(kind), Array(JAVA_LANG_OBJECT))
val mname = "unboxTo" + kind.toType.typeSymbol.decodedName
Pair(mname, mtype)
}
private val jUnboxTo: Map[TypeKind, Tuple2[String, JMethodType]] = Map(
BOOL -> helperUnboxTo(BOOL) ,
BYTE -> helperUnboxTo(BYTE) ,
CHAR -> helperUnboxTo(CHAR) ,
SHORT -> helperUnboxTo(SHORT) ,
INT -> helperUnboxTo(INT) ,
LONG -> helperUnboxTo(LONG) ,
FLOAT -> helperUnboxTo(FLOAT) ,
DOUBLE -> helperUnboxTo(DOUBLE)
)
var clasz: IClass = _
var method: IMethod = _
var jclass: JClass = _
var jmethod: JMethod = _
// var jcode: JExtendedCode = _
def isParcelableClass = isAndroidParcelableClass(clasz.symbol)
def isRemoteClass = clasz.symbol hasAnnotation RemoteAttr
def serialVUID = clasz.symbol getAnnotation SerialVersionUIDAttr collect {
case AnnotationInfo(_, Literal(const) :: _, _) => const.longValue
}
val fjbgContext = new FJBGContext(49, 0)
val emitSource = debugLevel >= 1
val emitLines = debugLevel >= 2
val emitVars = debugLevel >= 3
// bug had phase with wrong name; leaving enabled for brief pseudo deprecation
private val checkSignatures = (
(settings.check containsName phaseName)
|| (settings.check.value contains "genjvm") && {
global.warning("This option will be removed: please use -Ycheck:%s, not -Ycheck:genjvm." format phaseName)
true
}
)
/** For given symbol return a symbol corresponding to a class that should be declared as inner class.
*
* For example:
* class A {
* class B
* object C
* }
*
* then method will return NoSymbol for A, the same symbol for A.B (corresponding to A$B class) and A$C$ symbol
* for A.C.
*/
private def innerClassSymbolFor(s: Symbol): Symbol =
if (s.isClass) s else if (s.isModule) s.moduleClass else NoSymbol
override def javaName(sym: Symbol): String = { // TODO Miguel says: check whether a single pass over `icodes.classes` can populate `innerClassBuffer` faster.
/**
* Checks if given symbol corresponds to inner class/object and add it to innerClassBuffer
*
* Note: This method is called recursively thus making sure that we add complete chain
* of inner class all until root class.
*/
def collectInnerClass(s: Symbol): Unit = {
// TODO: some beforeFlatten { ... } which accounts for
// being nested in parameterized classes (if we're going to selectively flatten.)
val x = innerClassSymbolFor(s)
if(x ne NoSymbol) {
assert(x.isClass, "not an inner-class symbol")
val isInner = !x.rawowner.isPackageClass
if (isInner) {
innerClassBuffer += x
collectInnerClass(x.rawowner)
}
}
}
collectInnerClass(sym)
super.javaName(sym)
}
/** Write a class to disk, adding the Scala signature (pickled type
* information) and inner classes.
*
* @param jclass The FJBG class, where code was emitted
* @param sym The corresponding symbol, used for looking up pickled information
*/
def emitClass(jclass: JClass, sym: Symbol) {
addInnerClasses(jclass)
writeClass("" + sym.name, jclass.getName(), toByteArray(jclass), sym)
}
/** Returns the ScalaSignature annotation if it must be added to this class,
* none otherwise; furthermore, it adds to `jclass` the ScalaSig marker
* attribute (marking that a scala signature annotation is present) or the
* Scala marker attribute (marking that the signature for this class is in
* another file). The annotation that is returned by this method must be
* added to the class' annotations list when generating them.
*
* @param jclass The class file that is being readied.
* @param sym The symbol for which the signature has been entered in
* the symData map. This is different than the symbol
* that is being generated in the case of a mirror class.
* @return An option that is:
* - defined and contains an annotation info of the
* ScalaSignature type, instantiated with the pickle
* signature for sym (a ScalaSig marker attribute has
* been written);
* - undefined if the jclass/sym couple must not contain a
* signature (a Scala marker attribute has been written).
*/
def scalaSignatureAddingMarker(jclass: JClass, sym: Symbol): Option[AnnotationInfo] =
currentRun.symData get sym match {
case Some(pickle) if !nme.isModuleName(newTermName(jclass.getName)) =>
val scalaAttr =
fjbgContext.JOtherAttribute(jclass, jclass, tpnme.ScalaSignatureATTR.toString,
versionPickle.bytes, versionPickle.writeIndex)
jclass addAttribute scalaAttr
val scalaAnnot = {
val sigBytes = ScalaSigBytes(pickle.bytes.take(pickle.writeIndex))
AnnotationInfo(sigBytes.sigAnnot, Nil, List((nme.bytes, sigBytes)))
}
pickledBytes += pickle.writeIndex
currentRun.symData -= sym
currentRun.symData -= sym.companionSymbol
Some(scalaAnnot)
case _ =>
val markerAttr =
fjbgContext.JOtherAttribute(jclass, jclass, tpnme.ScalaATTR.toString, new Array[Byte](0), 0)
jclass addAttribute markerAttr
None
}
private var innerClassBuffer = mutable.LinkedHashSet[Symbol]()
/** Drop redundant interfaces (ones which are implemented by some other parent) from the immediate parents.
* This is important on Android because there is otherwise an interface explosion.
*/
private def minimizeInterfaces(interfaces: List[Symbol]): List[Symbol] = {
var rest = interfaces
var leaves = List.empty[Symbol]
while(!rest.isEmpty) {
val candidate = rest.head
val nonLeaf = leaves exists { lsym => lsym isSubClass candidate }
if(!nonLeaf) {
leaves = candidate :: (leaves filterNot { lsym => candidate isSubClass lsym })
}
rest = rest.tail
}
leaves
}
def genClass(c: IClass) {
clasz = c
innerClassBuffer.clear()
val name = javaName(c.symbol)
val ps = c.symbol.info.parents
val superClass: Symbol = if(ps.isEmpty) ObjectClass else ps.head.typeSymbol;
val superInterfaces0: List[Symbol] = if(ps.isEmpty) Nil else c.symbol.mixinClasses;
val superInterfaces = superInterfaces0 ++ c.symbol.annotations.flatMap(ann => newParentForAttr(ann.symbol)) distinct
val ifaces =
if(superInterfaces.isEmpty) JClass.NO_INTERFACES
else mkArray(minimizeInterfaces(superInterfaces) map javaName)
jclass = fjbgContext.JClass(javaFlags(c.symbol),
name,
javaName(superClass),
ifaces,
c.cunit.source.toString)
if (isStaticModule(c.symbol) || serialVUID != None || isParcelableClass) {
if (isStaticModule(c.symbol))
addModuleInstanceField
addStaticInit(jclass, c.lookupStaticCtor)
if (isTopLevelModule(c.symbol)) {
if (c.symbol.companionClass == NoSymbol)
generateMirrorClass(c.symbol, c.cunit.source)
else
log("No mirror class for module with linked class: " +
c.symbol.fullName)
}
}
else {
c.lookupStaticCtor foreach (constructor => addStaticInit(jclass, Some(constructor)))
// it must be a top level class (name contains no $s)
def isCandidateForForwarders(sym: Symbol): Boolean =
afterPickler {
!(sym.name.toString contains '$') && sym.hasModuleFlag && !sym.isImplClass && !sym.isNestedClass
}
// At some point this started throwing lots of exceptions as a compile was finishing.
// error: java.lang.AssertionError:
// assertion failed: List(object package$CompositeThrowable, object package$CompositeThrowable)
// ...is the one I've seen repeatedly. Suppressing.
val lmoc = (
try c.symbol.companionModule
catch { case x: AssertionError =>
Console.println("Suppressing failed assert: " + x)
NoSymbol
}
)
// add static forwarders if there are no name conflicts; see bugs #363 and #1735
if (lmoc != NoSymbol && !c.symbol.isInterface) {
if (isCandidateForForwarders(lmoc) && !settings.noForwarders.value) {
log("Adding static forwarders from '%s' to implementations in '%s'".format(c.symbol, lmoc))
addForwarders(jclass, lmoc.moduleClass)
}
}
}
clasz.fields foreach genField
clasz.methods foreach genMethod
val ssa = scalaSignatureAddingMarker(jclass, c.symbol)
addGenericSignature(jclass, c.symbol, c.symbol.owner)
addAnnotations(jclass, c.symbol.annotations ++ ssa)
addEnclosingMethodAttribute(jclass, c.symbol)
emitClass(jclass, c.symbol)
if (c.symbol hasAnnotation BeanInfoAttr)
genBeanInfoClass(c)
}
private def addEnclosingMethodAttribute(jclass: JClass, clazz: Symbol) {
val sym = clazz.originalEnclosingMethod
if (sym.isMethod) {
debuglog("enclosing method for %s is %s (in %s)".format(clazz, sym, sym.enclClass))
jclass addAttribute fjbgContext.JEnclosingMethodAttribute(
jclass,
javaName(sym.enclClass),
javaName(sym),
javaType(sym)
)
} else if (clazz.isAnonymousClass) {
val enclClass = clazz.rawowner
assert(enclClass.isClass, enclClass)
val sym = enclClass.primaryConstructor
if (sym == NoSymbol)
log("Ran out of room looking for an enclosing method for %s: no constructor here.".format(
enclClass, clazz)
)
else {
debuglog("enclosing method for %s is %s (in %s)".format(clazz, sym, enclClass))
jclass addAttribute fjbgContext.JEnclosingMethodAttribute(
jclass,
javaName(enclClass),
javaName(sym),
javaType(sym).asInstanceOf[JMethodType]
)
}
}
}
private def toByteArray(jc: JClass): Array[Byte] = {
val bos = new java.io.ByteArrayOutputStream()
val dos = new java.io.DataOutputStream(bos)
jc.writeTo(dos)
dos.close()
bos.toByteArray
}
/**
* Generate a bean info class that describes the given class.
*
* @author Ross Judson (ross.judson@soletta.com)
*/
def genBeanInfoClass(c: IClass) {
val description = c.symbol getAnnotation BeanDescriptionAttr
// informProgress(description.toString)
val beanInfoClass = fjbgContext.JClass(javaFlags(c.symbol),
javaName(c.symbol) + "BeanInfo",
"scala/beans/ScalaBeanInfo",
JClass.NO_INTERFACES,
c.cunit.source.toString)
var fieldList = List[String]()
for (f <- clasz.fields if f.symbol.hasGetter;
g = f.symbol.getter(c.symbol);
s = f.symbol.setter(c.symbol);
if g.isPublic && !(f.symbol.name startsWith "$")) // inserting $outer breaks the bean
fieldList = javaName(f.symbol) :: javaName(g) :: (if (s != NoSymbol) javaName(s) else null) :: fieldList
val methodList =
for (m <- clasz.methods
if !m.symbol.isConstructor &&
m.symbol.isPublic &&
!(m.symbol.name startsWith "$") &&
!m.symbol.isGetter &&
!m.symbol.isSetter) yield javaName(m.symbol)
val constructor = beanInfoClass.addNewMethod(ACC_PUBLIC, "<init>", JType.VOID, new Array[JType](0), new Array[String](0))
val jcode = constructor.getCode().asInstanceOf[JExtendedCode]
val strKind = new JObjectType(javaName(StringClass))
val stringArrayKind = new JArrayType(strKind)
val conType = new JMethodType(JType.VOID, Array(javaType(ClassClass), stringArrayKind, stringArrayKind))
def push(lst:Seq[String]) {
var fi = 0
for (f <- lst) {
jcode.emitDUP()
jcode emitPUSH fi
if (f != null)
jcode emitPUSH f
else
jcode.emitACONST_NULL()
jcode emitASTORE strKind
fi += 1
}
}
jcode.emitALOAD_0()
// push the class
jcode emitPUSH javaType(c.symbol).asInstanceOf[JReferenceType]
// push the string array of field information
jcode emitPUSH fieldList.length
jcode emitANEWARRAY strKind
push(fieldList)
// push the string array of method information
jcode emitPUSH methodList.length
jcode emitANEWARRAY strKind
push(methodList)
// invoke the superclass constructor, which will do the
// necessary java reflection and create Method objects.
jcode.emitINVOKESPECIAL("scala/beans/ScalaBeanInfo", "<init>", conType)
jcode.emitRETURN()
// write the bean information class file.
writeClass("BeanInfo ", beanInfoClass.getName(), toByteArray(beanInfoClass), c.symbol)
}
/** Add the given 'throws' attributes to jmethod */
def addExceptionsAttribute(jmethod: JMethod, excs: List[AnnotationInfo]) {
if (excs.isEmpty) return
val cpool = jmethod.getConstantPool
val buf: ByteBuffer = ByteBuffer.allocate(512)
var nattr = 0
// put some random value; the actual number is determined at the end
buf putShort 0xbaba.toShort
for (AnnotationInfo(tp, List(exc), _) <- excs.distinct if tp.typeSymbol == ThrowsClass) {
val Literal(const) = exc
buf.putShort(
cpool.addClass(
javaName(const.typeValue.typeSymbol)).shortValue)
nattr += 1
}
assert(nattr > 0, nattr)
buf.putShort(0, nattr.toShort)
addAttribute(jmethod, tpnme.ExceptionsATTR, buf)
}
/** Whether an annotation should be emitted as a Java annotation
* .initialize: if 'annot' is read from pickle, atp might be un-initialized
*/
private def shouldEmitAnnotation(annot: AnnotationInfo) =
annot.symbol.initialize.isJavaDefined &&
annot.matches(ClassfileAnnotationClass) &&
annot.args.isEmpty
private def emitJavaAnnotations(cpool: JConstantPool, buf: ByteBuffer, annotations: List[AnnotationInfo]): Int = {
def emitArgument(arg: ClassfileAnnotArg): Unit = arg match {
case LiteralAnnotArg(const) =>
const.tag match {
case BooleanTag =>
buf put 'Z'.toByte
buf putShort cpool.addInteger(if(const.booleanValue) 1 else 0).toShort
case ByteTag =>
buf put 'B'.toByte
buf putShort cpool.addInteger(const.byteValue).toShort
case ShortTag =>
buf put 'S'.toByte
buf putShort cpool.addInteger(const.shortValue).toShort
case CharTag =>
buf put 'C'.toByte
buf putShort cpool.addInteger(const.charValue).toShort
case IntTag =>
buf put 'I'.toByte
buf putShort cpool.addInteger(const.intValue).toShort
case LongTag =>
buf put 'J'.toByte
buf putShort cpool.addLong(const.longValue).toShort
case FloatTag =>
buf put 'F'.toByte
buf putShort cpool.addFloat(const.floatValue).toShort
case DoubleTag =>
buf put 'D'.toByte
buf putShort cpool.addDouble(const.doubleValue).toShort
case StringTag =>
buf put 's'.toByte
buf putShort cpool.addUtf8(const.stringValue).toShort
case ClazzTag =>
buf put 'c'.toByte
buf putShort cpool.addUtf8(javaType(const.typeValue).getSignature()).toShort
case EnumTag =>
buf put 'e'.toByte
buf putShort cpool.addUtf8(javaType(const.tpe).getSignature()).toShort
buf putShort cpool.addUtf8(const.symbolValue.name.toString).toShort
}
case sb@ScalaSigBytes(bytes) if !sb.isLong =>
buf put 's'.toByte
buf putShort cpool.addUtf8(sb.encodedBytes).toShort
case sb@ScalaSigBytes(bytes) if sb.isLong =>
buf put '['.toByte
val stringCount = (sb.encodedBytes.length / 65534) + 1
buf putShort stringCount.toShort
for (i <- 0 until stringCount) {
buf put 's'.toByte
val j = i * 65535
val string = sb.encodedBytes.slice(j, j + 65535)
buf putShort cpool.addUtf8(string).toShort
}
case ArrayAnnotArg(args) =>
buf put '['.toByte
buf putShort args.length.toShort
args foreach emitArgument
case NestedAnnotArg(annInfo) =>
buf put '@'.toByte
emitAnnotation(annInfo)
}
def emitAnnotation(annotInfo: AnnotationInfo) {
val AnnotationInfo(typ, args, assocs) = annotInfo
val jtype = javaType(typ)
buf putShort cpool.addUtf8(jtype.getSignature()).toShort
assert(args.isEmpty, args)
buf putShort assocs.length.toShort
for ((name, value) <- assocs) {
buf putShort cpool.addUtf8(name.toString).toShort
emitArgument(value)
}
}
var nannots = 0
val pos = buf.position()
// put some random value; the actual number of annotations is determined at the end
buf putShort 0xbaba.toShort
for (annot <- annotations if shouldEmitAnnotation(annot)) {
nannots += 1
emitAnnotation(annot)
}
// save the number of annotations
buf.putShort(pos, nannots.toShort)
nannots
}
/** Run the signature parser to catch bogus signatures.
*/
def isValidSignature(sym: Symbol, sig: String) = (
if (sym.isMethod) SigParser verifyMethod sig
else if (sym.isTerm) SigParser verifyType sig
else SigParser verifyClass sig
)
// @M don't generate java generics sigs for (members of) implementation
// classes, as they are monomorphic (TODO: ok?)
private def needsGenericSignature(sym: Symbol) = !(
// PP: This condition used to include sym.hasExpandedName, but this leads
// to the total loss of generic information if a private member is
// accessed from a closure: both the field and the accessor were generated
// without it. This is particularly bad because the availability of
// generic information could disappear as a consequence of a seemingly
// unrelated change.
sym.isSynthetic
|| sym.isLiftedMethod
|| sym.isBridge
|| (sym.ownerChain exists (_.isImplClass))
)
def addGenericSignature(jmember: JMember, sym: Symbol, owner: Symbol) {
if (needsGenericSignature(sym)) {
val memberTpe = beforeErasure(owner.thisType.memberInfo(sym))
erasure.javaSig(sym, memberTpe) foreach { sig =>
// This seems useful enough in the general case.
log(sig)
/** Since we're using a sun internal class for signature validation,
* we have to allow for it not existing or otherwise malfunctioning:
* in which case we treat every signature as valid. Medium term we
* should certainly write independent signature validation.
*/
if (settings.Xverify.value && SigParser.isParserAvailable && !isValidSignature(sym, sig)) {
clasz.cunit.warning(sym.pos,
"""|compiler bug: created invalid generic signature for %s in %s
|signature: %s
|if this is reproducible, please report bug at https://issues.scala-lang.org/
""".trim.stripMargin.format(sym, sym.owner.skipPackageObject.fullName, sig))
return
}
if (checkSignatures) {
val normalizedTpe = beforeErasure(erasure.prepareSigMap(memberTpe))
val bytecodeTpe = owner.thisType.memberInfo(sym)
if (!sym.isType && !sym.isConstructor && !(erasure.erasure(sym)(normalizedTpe) =:= bytecodeTpe)) {
clasz.cunit.warning(sym.pos,
"""|compiler bug: created generic signature for %s in %s that does not conform to its erasure
|signature: %s
|original type: %s
|normalized type: %s
|erasure type: %s
|if this is reproducible, please report bug at https://issues.scala-lang.org/
""".trim.stripMargin.format(sym, sym.owner.skipPackageObject.fullName, sig, memberTpe, normalizedTpe, bytecodeTpe))
return
}
}
val index = jmember.getConstantPool.addUtf8(sig).toShort
if (opt.verboseDebug)
beforeErasure(println("add generic sig "+sym+":"+sym.info+" ==> "+sig+" @ "+index))
val buf = ByteBuffer.allocate(2)
buf putShort index
addAttribute(jmember, tpnme.SignatureATTR, buf)
}
}
}
def addAnnotations(jmember: JMember, annotations: List[AnnotationInfo]) {
if (annotations exists (_ matches definitions.DeprecatedAttr)) {
val attr = jmember.getContext().JOtherAttribute(
jmember.getJClass(), jmember, tpnme.DeprecatedATTR.toString,
new Array[Byte](0), 0)
jmember addAttribute attr
}
val toEmit = annotations filter shouldEmitAnnotation
if (toEmit.isEmpty) return
val buf: ByteBuffer = ByteBuffer.allocate(2048)
emitJavaAnnotations(jmember.getConstantPool, buf, toEmit)
addAttribute(jmember, tpnme.RuntimeAnnotationATTR, buf)
}
def addParamAnnotations(jmethod: JMethod, pannotss: List[List[AnnotationInfo]]) {
val annotations = pannotss map (_ filter shouldEmitAnnotation)
if (annotations forall (_.isEmpty)) return
val buf: ByteBuffer = ByteBuffer.allocate(2048)
// number of parameters
buf.put(annotations.length.toByte)
for (annots <- annotations)
emitJavaAnnotations(jmethod.getConstantPool, buf, annots)
addAttribute(jmethod, tpnme.RuntimeParamAnnotationATTR, buf)
}
def addAttribute(jmember: JMember, name: Name, buf: ByteBuffer) {
if (buf.position() < 2)
return
val length = buf.position()
val arr = buf.array().slice(0, length)
val attr = jmember.getContext().JOtherAttribute(jmember.getJClass(),
jmember,
name.toString,
arr,
length)
jmember addAttribute attr
}
def addInnerClasses(jclass: JClass) {
/** The outer name for this inner class. Note that it returns null
* when the inner class should not get an index in the constant pool.
* That means non-member classes (anonymous). See Section 4.7.5 in the JVMS.
*/
def outerName(innerSym: Symbol): String = {
if (innerSym.originalEnclosingMethod != NoSymbol)
null
else {
val outerName = javaName(innerSym.rawowner)
if (isTopLevelModule(innerSym.rawowner)) "" + nme.stripModuleSuffix(newTermName(outerName))
else outerName
}
}
def innerName(innerSym: Symbol): String =
if (innerSym.isAnonymousClass || innerSym.isAnonymousFunction)
null
else
innerSym.rawname + innerSym.moduleSuffix
// add inner classes which might not have been referenced yet
afterErasure {
for (sym <- List(clasz.symbol, clasz.symbol.linkedClassOfClass); m <- sym.info.decls.map(innerClassSymbolFor) if m.isClass)
innerClassBuffer += m
}
val allInners = innerClassBuffer.toList
if (allInners.nonEmpty) {
debuglog(clasz.symbol.fullName('.') + " contains " + allInners.size + " inner classes.")
val innerClassesAttr = jclass.getInnerClasses()
// sort them so inner classes succeed their enclosing class
// to satisfy the Eclipse Java compiler
for (innerSym <- allInners sortBy (_.name.length)) {
val flags = {
val staticFlag = if (innerSym.rawowner.hasModuleFlag) ACC_STATIC else 0
(javaFlags(innerSym) | staticFlag) & INNER_CLASSES_FLAGS
}
val jname = javaName(innerSym)
val oname = outerName(innerSym)
val iname = innerName(innerSym)
// Mimicking javap inner class output
debuglog(
if (oname == null || iname == null) "//class " + jname
else "//%s=class %s of class %s".format(iname, jname, oname)
)
innerClassesAttr.addEntry(jname, oname, iname, flags)
}
}
}
def genField(f: IField) {
debuglog("Adding field: " + f.symbol.fullName)
val jfield = jclass.addNewField(
javaFieldFlags(f.symbol),
javaName(f.symbol),
javaType(f.symbol.tpe)
)
addGenericSignature(jfield, f.symbol, clasz.symbol)
addAnnotations(jfield, f.symbol.annotations)
}
def genMethod(m: IMethod) {
if (m.symbol.isStaticConstructor || definitions.isGetClass(m.symbol)) return
debuglog("Generating method " + m.symbol.fullName)
method = m
endPC.clear
computeLocalVarsIndex(m)
var resTpe = javaType(m.symbol.tpe.resultType)
if (m.symbol.isClassConstructor)
resTpe = JType.VOID
var flags = javaFlags(m.symbol)
if (jclass.isInterface)
flags |= ACC_ABSTRACT
if (m.symbol.isStrictFP)
flags |= ACC_STRICT
// native methods of objects are generated in mirror classes
if (method.native)
flags |= ACC_NATIVE
jmethod = jclass.addNewMethod(flags,
javaName(m.symbol),
resTpe,
mkArray(m.params map (p => javaType(p.kind))),
mkArray(m.params map (p => javaName(p.sym))))
addRemoteException(jmethod, m.symbol)
if (!jmethod.isAbstract() && !method.native) {
val jcode = jmethod.getCode().asInstanceOf[JExtendedCode]
// add a fake local for debugging purposes
if (emitVars && isClosureApply(method.symbol)) {
val outerField = clasz.symbol.info.decl(nme.OUTER_LOCAL)
if (outerField != NoSymbol) {
log("Adding fake local to represent outer 'this' for closure " + clasz)
val _this = new Local(
method.symbol.newVariable(nme.FAKE_LOCAL_THIS), toTypeKind(outerField.tpe), false)
m.locals = m.locals ::: List(_this)
computeLocalVarsIndex(m) // since we added a new local, we need to recompute indexes
jcode.emitALOAD_0()
jcode.emitGETFIELD(javaName(clasz.symbol),
javaName(outerField),
javaType(outerField))
jcode.emitSTORE(indexOf(_this), javaType(_this.kind))
}
}
for (local <- m.locals if ! m.params.contains(local)) {
debuglog("add local var: " + local)
jmethod.addNewLocalVariable(javaType(local.kind), javaName(local.sym))
}
genCode(m)
if (emitVars)
genLocalVariableTable(m, jcode)
}
addGenericSignature(jmethod, m.symbol, clasz.symbol)
val (excs, others) = m.symbol.annotations partition (_.symbol == ThrowsClass)
addExceptionsAttribute(jmethod, excs)
addAnnotations(jmethod, others)
addParamAnnotations(jmethod, m.params.map(_.sym.annotations))
// check for code size
try jmethod.freeze()
catch {
case e: JCode.CodeSizeTooBigException =>
clasz.cunit.error(m.symbol.pos, "Code size exceeds JVM limits: %d".format(e.codeSize))
throw e
}
}
/** Adds a @remote annotation, actual use unknown.
*/
private def addRemoteException(jmethod: JMethod, meth: Symbol) {
val needsAnnotation = (
(isRemoteClass || (meth hasAnnotation RemoteAttr) && jmethod.isPublic)
&& !(meth.throwsAnnotations contains RemoteExceptionClass)
)
if (needsAnnotation) {
val c = Constant(RemoteExceptionClass.tpe)
val arg = Literal(c) setType c.tpe
meth.addAnnotation(ThrowsClass, arg)
}
}
private def isClosureApply(sym: Symbol): Boolean = {
(sym.name == nme.apply) &&
sym.owner.isSynthetic &&
sym.owner.tpe.parents.exists { t =>
val TypeRef(_, sym, _) = t
FunctionClass contains sym