forked from Konloch/bytecode-viewer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnitCompiler.java
More file actions
10542 lines (9401 loc) · 497 KB
/
Copy pathUnitCompiler.java
File metadata and controls
10542 lines (9401 loc) · 497 KB
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
/*
* Janino - An embedded Java[TM] compiler
*
* Copyright (c) 2001-2013, Arno Unkrig
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.codehaus.janino;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeMap;
import org.codehaus.commons.compiler.CompileException;
import org.codehaus.commons.compiler.ErrorHandler;
import org.codehaus.commons.compiler.Location;
import org.codehaus.commons.compiler.UncheckedCompileException;
import org.codehaus.commons.compiler.WarningHandler;
import org.codehaus.janino.CodeContext.Inserter;
import org.codehaus.janino.CodeContext.Offset;
import org.codehaus.janino.IClass.IConstructor;
import org.codehaus.janino.IClass.IField;
import org.codehaus.janino.IClass.IInvocable;
import org.codehaus.janino.IClass.IMethod;
import org.codehaus.janino.Java.AbstractTypeDeclaration;
import org.codehaus.janino.Java.AlternateConstructorInvocation;
import org.codehaus.janino.Java.AmbiguousName;
import org.codehaus.janino.Java.Annotation;
import org.codehaus.janino.Java.AnonymousClassDeclaration;
import org.codehaus.janino.Java.ArrayAccessExpression;
import org.codehaus.janino.Java.ArrayInitializer;
import org.codehaus.janino.Java.ArrayInitializerOrRvalue;
import org.codehaus.janino.Java.ArrayLength;
import org.codehaus.janino.Java.ArrayType;
import org.codehaus.janino.Java.AssertStatement;
import org.codehaus.janino.Java.Assignment;
import org.codehaus.janino.Java.Atom;
import org.codehaus.janino.Java.BasicType;
import org.codehaus.janino.Java.BinaryOperation;
import org.codehaus.janino.Java.Block;
import org.codehaus.janino.Java.BlockStatement;
import org.codehaus.janino.Java.BooleanLiteral;
import org.codehaus.janino.Java.BooleanRvalue;
import org.codehaus.janino.Java.BreakStatement;
import org.codehaus.janino.Java.BreakableStatement;
import org.codehaus.janino.Java.Cast;
import org.codehaus.janino.Java.CatchClause;
import org.codehaus.janino.Java.CharacterLiteral;
import org.codehaus.janino.Java.ClassDeclaration;
import org.codehaus.janino.Java.ClassLiteral;
import org.codehaus.janino.Java.CompilationUnit;
import org.codehaus.janino.Java.CompilationUnit.ImportDeclaration;
import org.codehaus.janino.Java.CompilationUnit.SingleStaticImportDeclaration;
import org.codehaus.janino.Java.CompilationUnit.SingleTypeImportDeclaration;
import org.codehaus.janino.Java.CompilationUnit.StaticImportOnDemandDeclaration;
import org.codehaus.janino.Java.CompilationUnit.TypeImportOnDemandDeclaration;
import org.codehaus.janino.Java.ConditionalExpression;
import org.codehaus.janino.Java.ConstructorDeclarator;
import org.codehaus.janino.Java.ConstructorInvocation;
import org.codehaus.janino.Java.ContinuableStatement;
import org.codehaus.janino.Java.ContinueStatement;
import org.codehaus.janino.Java.Crement;
import org.codehaus.janino.Java.DoStatement;
import org.codehaus.janino.Java.DocCommentable;
import org.codehaus.janino.Java.EmptyStatement;
import org.codehaus.janino.Java.EnclosingScopeOfTypeDeclaration;
import org.codehaus.janino.Java.ExpressionStatement;
import org.codehaus.janino.Java.FieldAccess;
import org.codehaus.janino.Java.FieldAccessExpression;
import org.codehaus.janino.Java.FieldDeclaration;
import org.codehaus.janino.Java.FloatingPointLiteral;
import org.codehaus.janino.Java.ForEachStatement;
import org.codehaus.janino.Java.ForStatement;
import org.codehaus.janino.Java.FunctionDeclarator;
import org.codehaus.janino.Java.FunctionDeclarator.FormalParameter;
import org.codehaus.janino.Java.FunctionDeclarator.FormalParameters;
import org.codehaus.janino.Java.IfStatement;
import org.codehaus.janino.Java.Initializer;
import org.codehaus.janino.Java.InnerClassDeclaration;
import org.codehaus.janino.Java.Instanceof;
import org.codehaus.janino.Java.IntegerLiteral;
import org.codehaus.janino.Java.InterfaceDeclaration;
import org.codehaus.janino.Java.Invocation;
import org.codehaus.janino.Java.LabeledStatement;
import org.codehaus.janino.Java.Literal;
import org.codehaus.janino.Java.LocalClassDeclaration;
import org.codehaus.janino.Java.LocalClassDeclarationStatement;
import org.codehaus.janino.Java.LocalVariable;
import org.codehaus.janino.Java.LocalVariableAccess;
import org.codehaus.janino.Java.LocalVariableDeclarationStatement;
import org.codehaus.janino.Java.LocalVariableSlot;
import org.codehaus.janino.Java.Locatable;
import org.codehaus.janino.Java.Located;
import org.codehaus.janino.Java.Lvalue;
import org.codehaus.janino.Java.MemberClassDeclaration;
import org.codehaus.janino.Java.MemberInterfaceDeclaration;
import org.codehaus.janino.Java.MemberTypeDeclaration;
import org.codehaus.janino.Java.MethodDeclarator;
import org.codehaus.janino.Java.MethodInvocation;
import org.codehaus.janino.Java.Modifiers;
import org.codehaus.janino.Java.NamedClassDeclaration;
import org.codehaus.janino.Java.NamedTypeDeclaration;
import org.codehaus.janino.Java.NewAnonymousClassInstance;
import org.codehaus.janino.Java.NewArray;
import org.codehaus.janino.Java.NewClassInstance;
import org.codehaus.janino.Java.NewInitializedArray;
import org.codehaus.janino.Java.NullLiteral;
import org.codehaus.janino.Java.Package;
import org.codehaus.janino.Java.PackageMemberClassDeclaration;
import org.codehaus.janino.Java.PackageMemberInterfaceDeclaration;
import org.codehaus.janino.Java.PackageMemberTypeDeclaration;
import org.codehaus.janino.Java.Padder;
import org.codehaus.janino.Java.ParameterAccess;
import org.codehaus.janino.Java.ParenthesizedExpression;
import org.codehaus.janino.Java.QualifiedThisReference;
import org.codehaus.janino.Java.ReferenceType;
import org.codehaus.janino.Java.ReturnStatement;
import org.codehaus.janino.Java.Rvalue;
import org.codehaus.janino.Java.RvalueMemberType;
import org.codehaus.janino.Java.Scope;
import org.codehaus.janino.Java.SimpleConstant;
import org.codehaus.janino.Java.SimpleType;
import org.codehaus.janino.Java.Statement;
import org.codehaus.janino.Java.StringLiteral;
import org.codehaus.janino.Java.SuperConstructorInvocation;
import org.codehaus.janino.Java.SuperclassFieldAccessExpression;
import org.codehaus.janino.Java.SuperclassMethodInvocation;
import org.codehaus.janino.Java.SwitchStatement;
import org.codehaus.janino.Java.SynchronizedStatement;
import org.codehaus.janino.Java.ThisReference;
import org.codehaus.janino.Java.ThrowStatement;
import org.codehaus.janino.Java.TryStatement;
import org.codehaus.janino.Java.Type;
import org.codehaus.janino.Java.TypeBodyDeclaration;
import org.codehaus.janino.Java.TypeDeclaration;
import org.codehaus.janino.Java.TypeParameter;
import org.codehaus.janino.Java.UnaryOperation;
import org.codehaus.janino.Java.VariableDeclarator;
import org.codehaus.janino.Java.WhileStatement;
import org.codehaus.janino.Visitor.AtomVisitor;
import org.codehaus.janino.Visitor.BlockStatementVisitor;
import org.codehaus.janino.Visitor.ElementValueVisitor;
import org.codehaus.janino.Visitor.ImportVisitor;
import org.codehaus.janino.Visitor.LvalueVisitor;
import org.codehaus.janino.Visitor.RvalueVisitor;
import org.codehaus.janino.Visitor.TypeDeclarationVisitor;
import org.codehaus.janino.util.ClassFile;
/**
* This class actually implements the Java™ compiler. It is associated with exactly one compilation unit which it
* compiles.
*/
@SuppressWarnings({ "rawtypes", "unchecked" }) public
class UnitCompiler {
private static final boolean DEBUG = false;
/**
* This constant determines the number of operands up to which the
* <pre>
* a.concat(b).concat(c)
* </pre>
* strategy is used to implement string concatenation. For more operands, the
* <pre>
* new StringBuilder(a).append(b).append(c).append(d).toString()
* </pre>
* strategy is chosen.
* <p>
* <a href="http://www.tomgibara.com/janino-evaluation/string-concatenation-benchmark">A very good article from Tom
* Gibara</a> analyzes the impact of this decision and recommends a value of three.
*/
private static final int STRING_CONCAT_LIMIT = 3;
/**
* Special value for the {@code orientation} parameter of the {@link #compileBoolean(Java.Rvalue,
* CodeContext.Offset, boolean)} methods, indicating that the code should be generated such that execution branches
* if the value on top of the operand stack is TRUE.
*/
public static final boolean JUMP_IF_TRUE = true;
/**
* Special value for the {@code orientation} parameter of the {@link #compileBoolean(Java.Rvalue,
* CodeContext.Offset, boolean)} methods, indicating that the code should be generated such that execution branches
* if the value on top of the operand stack is FALSE.
*/
public static final boolean JUMP_IF_FALSE = false;
public
UnitCompiler(CompilationUnit compilationUnit, IClassLoader iClassLoader) {
this.compilationUnit = compilationUnit;
this.iClassLoader = iClassLoader;
}
/** @return The {@link CompilationUnit} that this {@link UnitCompiler} compiles */
public CompilationUnit
getCompilationUnit() { return this.compilationUnit; }
private void
import2(SingleStaticImportDeclaration ssid) throws CompileException {
String name = UnitCompiler.last(ssid.identifiers);
List<Object/*IField+IMethod+IClass*/>
importedObjects = (List<Object/*IField+IMethod+IClass*/>) this.singleStaticImports.get(name);
if (importedObjects == null) {
importedObjects = new ArrayList();
this.singleStaticImports.put(name, importedObjects);
}
// Type?
{
IClass iClass = this.findTypeByFullyQualifiedName(ssid.getLocation(), ssid.identifiers);
if (iClass != null) {
importedObjects.add(iClass);
return;
}
}
String[] typeName = UnitCompiler.allButLast(ssid.identifiers);
IClass iClass = this.findTypeByFullyQualifiedName(ssid.getLocation(), typeName);
if (iClass == null) {
this.compileError("Could not load \"" + Java.join(typeName, ".") + "\"", ssid.getLocation());
return;
}
// Static field?
IField iField = iClass.getDeclaredIField(name);
if (iField != null) {
if (!iField.isStatic()) {
this.compileError(
"Field \"" + name + "\" of \"" + Java.join(typeName, ".") + "\" must be static",
ssid.getLocation()
);
}
importedObjects.add(iField);
return;
}
// Static method?
IMethod[] ms = iClass.getDeclaredIMethods(name);
if (ms.length > 0) {
importedObjects.addAll(Arrays.asList(ms));
return;
}
// Give up.
this.compileError(
"\"" + Java.join(typeName, ".") + "\" has no static member \"" + name + "\"",
ssid.getLocation()
);
}
private void
import2(StaticImportOnDemandDeclaration siodd) throws CompileException {
IClass iClass = this.findTypeByFullyQualifiedName(siodd.getLocation(), siodd.identifiers);
if (iClass == null) {
this.compileError("Could not load \"" + Java.join(siodd.identifiers, ".") + "\"", siodd.getLocation());
return;
}
this.staticImportsOnDemand.add(iClass);
}
/**
* Generates an array of {@link ClassFile} objects which represent the classes and interfaces declared in the
* compilation unit.
*/
public ClassFile[]
compileUnit(boolean debugSource, boolean debugLines, boolean debugVars) throws CompileException {
this.debugSource = debugSource;
this.debugLines = debugLines;
this.debugVars = debugVars;
// Compile static import declarations.
// Notice: The single-type and on-demand imports are needed BEFORE the unit is compiled, thus they are
// processed in 'getSingleTypeImport()' and 'importOnDemand()'.
for (ImportDeclaration id : this.compilationUnit.importDeclarations) {
try {
id.accept(new ImportVisitor() {
// CHECKSTYLE LineLengthCheck:OFF
@Override public void visitSingleTypeImportDeclaration(SingleTypeImportDeclaration stid) {}
@Override public void visitTypeImportOnDemandDeclaration(TypeImportOnDemandDeclaration tiodd) {}
@Override public void visitSingleStaticImportDeclaration(SingleStaticImportDeclaration ssid) { try { UnitCompiler.this.import2(ssid); } catch (CompileException e) { throw new UncheckedCompileException(e); } }
@Override public void visitStaticImportOnDemandDeclaration(StaticImportOnDemandDeclaration siodd) { try { UnitCompiler.this.import2(siodd); } catch (CompileException e) { throw new UncheckedCompileException(e); } }
// CHECKSTYLE LineLengthCheck:ON
});
} catch (UncheckedCompileException uce) {
throw uce.compileException; // SUPPRESS CHECKSTYLE AvoidHidingCause
}
}
this.generatedClassFiles = new ArrayList();
for (PackageMemberTypeDeclaration pmtd : this.compilationUnit.packageMemberTypeDeclarations) {
this.compile(pmtd);
}
if (this.compileErrorCount > 0) {
throw new CompileException((
this.compileErrorCount
+ " error(s) while compiling unit \""
+ this.compilationUnit.optionalFileName
+ "\""
), null);
}
List<ClassFile> l = this.generatedClassFiles;
return (ClassFile[]) l.toArray(new ClassFile[l.size()]);
}
// ------------ TypeDeclaration.compile() -------------
private void
compile(TypeDeclaration td) throws CompileException {
TypeDeclarationVisitor tdv = new TypeDeclarationVisitor() {
// CHECKSTYLE LineLengthCheck:OFF
@Override public void visitAnonymousClassDeclaration(AnonymousClassDeclaration acd) { try { UnitCompiler.this.compile2(acd); } catch (CompileException e) { throw new UncheckedCompileException(e); } }
@Override public void visitLocalClassDeclaration(LocalClassDeclaration lcd) { try { UnitCompiler.this.compile2(lcd); } catch (CompileException e) { throw new UncheckedCompileException(e); } }
@Override public void visitPackageMemberClassDeclaration(PackageMemberClassDeclaration pmcd) { try { UnitCompiler.this.compile2((PackageMemberTypeDeclaration) pmcd); } catch (CompileException e) { throw new UncheckedCompileException(e); } }
@Override public void visitMemberInterfaceDeclaration(MemberInterfaceDeclaration mid) { try { UnitCompiler.this.compile2(mid); } catch (CompileException e) { throw new UncheckedCompileException(e); } }
@Override public void visitPackageMemberInterfaceDeclaration(PackageMemberInterfaceDeclaration pmid) { try { UnitCompiler.this.compile2((PackageMemberTypeDeclaration) pmid); } catch (CompileException e) { throw new UncheckedCompileException(e); } }
@Override public void visitMemberClassDeclaration(MemberClassDeclaration mcd) { try { UnitCompiler.this.compile2(mcd); } catch (CompileException e) { throw new UncheckedCompileException(e); } }
// CHECKSTYLE LineLengthCheck:ON
};
try {
td.accept(tdv);
} catch (UncheckedCompileException uce) {
throw uce.compileException; // SUPPRESS CHECKSTYLE AvoidHidingCause
}
}
private void
compile2(PackageMemberTypeDeclaration pmtd) throws CompileException {
CompilationUnit declaringCompilationUnit = pmtd.getDeclaringCompilationUnit();
// Check for conflict with single-type-import (7.6).
{
String[] ss = this.getSingleTypeImport(pmtd.getName(), pmtd.getLocation());
if (ss != null) {
this.compileError((
"Package member type declaration \""
+ pmtd.getName()
+ "\" conflicts with single-type-import \""
+ Java.join(ss, ".")
+ "\""
), pmtd.getLocation());
}
}
// Check for redefinition within compilation unit (7.6).
{
PackageMemberTypeDeclaration otherPmtd = declaringCompilationUnit.getPackageMemberTypeDeclaration(
pmtd.getName()
);
if (otherPmtd != pmtd) {
this.compileError((
"Redeclaration of type \""
+ pmtd.getName()
+ "\", previously declared in "
+ otherPmtd.getLocation()
), pmtd.getLocation());
}
}
if (pmtd instanceof NamedClassDeclaration) {
this.compile2((NamedClassDeclaration) pmtd);
} else
if (pmtd instanceof InterfaceDeclaration) {
this.compile2((InterfaceDeclaration) pmtd);
} else
{
throw new JaninoRuntimeException("PMTD of unexpected type " + pmtd.getClass().getName());
}
}
private void
compile2(ClassDeclaration cd) throws CompileException {
IClass iClass = this.resolve(cd);
// Check that all methods of the non-abstract class are implemented.
if (!Mod.isAbstract(cd.getModifierFlags())) {
IMethod[] ms = iClass.getIMethods();
for (IMethod base : ms) {
if (base.isAbstract()) {
IMethod override = iClass.findIMethod(base.getName(), base.getParameterTypes());
if (
override == null // It wasn't overridden
|| override.isAbstract() // It was overridden with an abstract method
// The override does not provide a covariant return type
|| !base.getReturnType().isAssignableFrom(override.getReturnType())
) {
this.compileError(
"Non-abstract class \"" + iClass + "\" must implement method \"" + base + "\"",
cd.getLocation()
);
}
}
}
}
// Create "ClassFile" object.
ClassFile cf = new ClassFile(
(short) (cd.getModifierFlags() | Mod.SUPER), // accessFlags
iClass.getDescriptor(), // thisClassFD
iClass.getSuperclass().getDescriptor(), // superclassFD
IClass.getDescriptors(iClass.getInterfaces()) // interfaceFDs
);
// TODO: Add annotations with retention != SOURCE.
// for (Annotation a : cd.getAnnotations()) {
// assert false : "Class '" + iClass + "' has annotation '" + a + "'";
// }
// Add InnerClasses attribute entry for this class declaration.
if (cd.getEnclosingScope() instanceof CompilationUnit) {
;
} else
if (cd.getEnclosingScope() instanceof Block) {
short innerClassInfoIndex = cf.addConstantClassInfo(iClass.getDescriptor());
short innerNameIndex = (
this instanceof NamedTypeDeclaration
? cf.addConstantUtf8Info(((NamedTypeDeclaration) this).getName())
: (short) 0
);
assert cd.getAnnotations().length == 0 : "NYI";
cf.addInnerClassesAttributeEntry(new ClassFile.InnerClassesAttribute.Entry(
innerClassInfoIndex, // innerClassInfoIndex
(short) 0, // outerClassInfoIndex
innerNameIndex, // innerNameIndex
cd.getModifierFlags() // innerClassAccessFlags
));
} else
if (cd.getEnclosingScope() instanceof TypeDeclaration) {
short innerClassInfoIndex = cf.addConstantClassInfo(iClass.getDescriptor());
short outerClassInfoIndex = cf.addConstantClassInfo(
this.resolve(((TypeDeclaration) cd.getEnclosingScope())).getDescriptor()
);
short innerNameIndex = cf.addConstantUtf8Info(((MemberTypeDeclaration) cd).getName());
assert cd.getAnnotations().length == 0 : "NYI";
cf.addInnerClassesAttributeEntry(new ClassFile.InnerClassesAttribute.Entry(
innerClassInfoIndex, // innerClassInfoIndex
outerClassInfoIndex, // outerClassInfoIndex
innerNameIndex, // innerNameIndex
cd.getModifierFlags() // innerClassAccessFlags
));
}
// Set "SourceFile" attribute.
if (this.debugSource) {
String sourceFileName;
{
String s = cd.getLocation().getFileName();
if (s != null) {
sourceFileName = new File(s).getName();
} else if (cd instanceof NamedTypeDeclaration) {
sourceFileName = ((NamedTypeDeclaration) cd).getName() + ".java";
} else {
sourceFileName = "ANONYMOUS.java";
}
}
cf.addSourceFileAttribute(sourceFileName);
}
// Add "Deprecated" attribute (JVMS 4.7.10).
if (cd instanceof DocCommentable) {
if (((DocCommentable) cd).hasDeprecatedDocTag()) cf.addDeprecatedAttribute();
}
// Optional: Generate and compile class initialization method.
{
List<BlockStatement> statements = new ArrayList();
for (BlockStatement vdoi : cd.variableDeclaratorsAndInitializers) {
if (((TypeBodyDeclaration) vdoi).isStatic()) statements.add(vdoi);
}
this.maybeCreateInitMethod(cd, cf, statements);
}
this.compileDeclaredMethods(cd, cf);
// Compile declared constructors.
// As a side effect of compiling methods and constructors, synthetic "class-dollar" methods (which implement
// class literals) are generated on-the fly. We need to note how many we have here so we can compile the
// extras.
final int declaredMethodCount = cd.getMethodDeclarations().size();
{
int syntheticFieldCount = cd.syntheticFields.size();
ConstructorDeclarator[] ctords = cd.getConstructors();
for (ConstructorDeclarator ctord : ctords) {
this.compile(ctord, cf);
if (syntheticFieldCount != cd.syntheticFields.size()) {
throw new JaninoRuntimeException(
"SNO: Compilation of constructor \""
+ ctord
+ "\" ("
+ ctord.getLocation()
+ ") added synthetic fields!?"
);
}
}
}
// A side effect of this call may create synthetic functions to access protected parent variables.
this.compileDeclaredMemberTypes(cd, cf);
// Compile the aforementioned extras.
this.compileDeclaredMethods(cd, cf, declaredMethodCount);
{
// for every method look for bridge methods that need to be supplied this is used to correctly dispatch
// into covariant return types from existing code.
IMethod[] ms = iClass.getIMethods();
for (IMethod base : ms) {
if (!base.isStatic()) {
IMethod override = iClass.findIMethod(base.getName(), base.getParameterTypes());
// If we overrode the method but with a DIFFERENT return type.
if (
override != null
&& !base.getReturnType().equals(override.getReturnType())
) {
this.compileBridgeMethod(cf, base, override);
}
}
}
}
// Class and instance variables.
for (BlockStatement vdoi : cd.variableDeclaratorsAndInitializers) {
if (vdoi instanceof FieldDeclaration) this.addFields((FieldDeclaration) vdoi, cf);
}
// Synthetic fields.
for (IField f : cd.syntheticFields.values()) {
cf.addFieldInfo(
new Modifiers(Mod.PACKAGE), // modifiers
f.getName(), // fieldName
f.getType().getDescriptor(), // fieldTypeFD
null // optionalConstantValue
);
}
// Add the generated class file to a thread-local store.
this.generatedClassFiles.add(cf);
}
/** Creates {@link ClassFile.FieldInfo}s for all fields declared by the given {@link FieldDeclaration}. */
private void
addFields(FieldDeclaration fd, ClassFile cf) throws CompileException {
for (VariableDeclarator vd : fd.variableDeclarators) {
Type type = fd.type;
for (int i = 0; i < vd.brackets; ++i) type = new ArrayType(type);
Object ocv = UnitCompiler.NOT_CONSTANT;
if (Mod.isFinal(fd.modifiers.flags) && vd.optionalInitializer instanceof Rvalue) {
ocv = this.getConstantValue((Rvalue) vd.optionalInitializer);
}
ClassFile.FieldInfo fi;
if (Mod.isPrivateAccess(fd.modifiers.flags)) {
// To make the private field accessible for enclosing types, enclosed types and types enclosed by the
// same type, it is modified as follows:
// + Access is changed from PRIVATE to PACKAGE
assert fd.modifiers.annotations.length == 0 : "NYI";
fi = cf.addFieldInfo(
fd.modifiers.changeAccess(Mod.PACKAGE), // modifiers
vd.name, // fieldName
this.getType(type).getDescriptor(), // fieldTypeFD
ocv == UnitCompiler.NOT_CONSTANT ? null : ocv // optionalConstantValue
);
} else
{
assert fd.modifiers.annotations.length == 0 : "NYI";
fi = cf.addFieldInfo(
fd.modifiers, // modifiers
vd.name, // fieldName
this.getType(type).getDescriptor(), // fieldTypeFD
ocv == UnitCompiler.NOT_CONSTANT ? null : ocv // optionalConstantValue
);
}
// Add "Deprecated" attribute (JVMS 4.7.10).
if (fd.hasDeprecatedDocTag()) {
fi.addAttribute(new ClassFile.DeprecatedAttribute(cf.addConstantUtf8Info("Deprecated")));
}
}
}
private void
compile2(AnonymousClassDeclaration acd) throws CompileException {
this.compile2((InnerClassDeclaration) acd);
}
private void
compile2(LocalClassDeclaration lcd) throws CompileException {
this.compile2((InnerClassDeclaration) lcd);
}
private void
compile2(InnerClassDeclaration icd) throws CompileException {
// Define a synthetic "this$..." field if there is an enclosing instance.
{
List<TypeDeclaration> ocs = UnitCompiler.getOuterClasses(icd);
final int nesting = ocs.size();
if (nesting >= 2) {
icd.defineSyntheticField(new SimpleIField(
this.resolve(icd),
"this$" + (nesting - 2),
this.resolve((TypeDeclaration) ocs.get(1))
));
}
}
// For classes that enclose surrounding scopes, trawl their field initializers looking for synthetic fields.
if (icd instanceof AnonymousClassDeclaration || icd instanceof LocalClassDeclaration) {
ClassDeclaration cd = (ClassDeclaration) icd;
// Compilation of field declarations can create synthetic variables, so we must not use an iterator.
List<BlockStatement> vdais = cd.variableDeclaratorsAndInitializers;
for (int i = 0; i < vdais.size(); i++) {
BlockStatement vdoi = (BlockStatement) vdais.get(i);
this.fakeCompile(vdoi);
}
}
this.compile2((ClassDeclaration) icd);
}
private void
compile2(final MemberClassDeclaration mcd) throws CompileException { this.compile2((InnerClassDeclaration) mcd); }
private void
compile2(InterfaceDeclaration id) throws CompileException {
final IClass iClass = this.resolve(id);
// Determine extended interfaces.
id.interfaces = new IClass[id.extendedTypes.length];
String[] interfaceDescriptors = new String[id.interfaces.length];
for (int i = 0; i < id.extendedTypes.length; ++i) {
id.interfaces[i] = this.getType(id.extendedTypes[i]);
interfaceDescriptors[i] = id.interfaces[i].getDescriptor();
}
// Create "ClassFile" object.
ClassFile cf = new ClassFile(
(short) (id.getModifierFlags() | Mod.SUPER | Mod.INTERFACE | Mod.ABSTRACT), // accessFlags
iClass.getDescriptor(), // thisClassFD
Descriptor.JAVA_LANG_OBJECT, // superclassFD
interfaceDescriptors // interfaceFDs
);
// TODO: Add annotations with retention != SOURCE.
// for (Annotation a : id.getAnnotations()) {
// assert false : "Interface '" + iClass + "' has annotation '" + a + "'";
// }
// Set "SourceFile" attribute.
if (this.debugSource) {
String sourceFileName;
{
String s = id.getLocation().getFileName();
if (s != null) {
sourceFileName = new File(s).getName();
} else {
sourceFileName = id.getName() + ".java";
}
}
cf.addSourceFileAttribute(sourceFileName);
}
// Add "Deprecated" attribute (JVMS 4.7.10).
if (id.hasDeprecatedDocTag()) cf.addDeprecatedAttribute();
// Interface initialization method.
if (!id.constantDeclarations.isEmpty()) {
List<BlockStatement> statements = new ArrayList();
statements.addAll(id.constantDeclarations);
this.maybeCreateInitMethod(id, cf, statements);
}
this.compileDeclaredMethods(id, cf);
// Class variables.
for (FieldDeclaration constantDeclaration : id.constantDeclarations) this.addFields(constantDeclaration, cf);
this.compileDeclaredMemberTypes(id, cf);
// Add the generated class file to a thread-local store.
this.generatedClassFiles.add(cf);
}
/**
* Create class initialization method iff there is any initialization code.
*
* @param decl The type declaration
* @param cf The class file into which to put the method
* @param b The block for the method (possibly empty)
* @throws CompileException
*/
private void
maybeCreateInitMethod(
AbstractTypeDeclaration decl,
ClassFile cf,
List<BlockStatement> statements
) throws CompileException {
// Create interface initialization method iff there is any initialization code.
if (this.generatesCode2(statements)) {
MethodDeclarator md = new MethodDeclarator(
decl.getLocation(), // location
null, // optionalDocComment
new Modifiers((short) (Mod.STATIC | Mod.PUBLIC)), // modifiers
new BasicType( // type
decl.getLocation(),
BasicType.VOID
),
"<clinit>", // name
new FormalParameters(), // formalParameters
new ReferenceType[0], // thrownExceptions
statements // optionalStatements
);
md.setDeclaringType(decl);
this.compile(md, cf);
}
}
/**
* Compile all of the types for this declaration
* <p>
* NB: as a side effect this will fill in the synthetic field map
*/
private void
compileDeclaredMemberTypes(TypeDeclaration decl, ClassFile cf) throws CompileException {
for (MemberTypeDeclaration mtd : decl.getMemberTypeDeclarations()) {
this.compile(mtd);
// Add InnerClasses attribute entry for member type declaration.
short innerClassInfoIndex = cf.addConstantClassInfo(this.resolve(mtd).getDescriptor());
short outerClassInfoIndex = cf.addConstantClassInfo(this.resolve(decl).getDescriptor());
short innerNameIndex = cf.addConstantUtf8Info(mtd.getName());
assert mtd.getAnnotations().length == 0;
cf.addInnerClassesAttributeEntry(new ClassFile.InnerClassesAttribute.Entry(
innerClassInfoIndex, // innerClassInfoIndex
outerClassInfoIndex, // outerClassInfoIndex
innerNameIndex, // innerNameIndex
mtd.getModifierFlags() // innerClassAccessFlags
));
}
}
/**
* Compile all of the methods for this declaration
* <p>
* NB: as a side effect this will fill in the synthetic field map
*
* @throws CompileException
*/
private void
compileDeclaredMethods(AbstractTypeDeclaration typeDeclaration, ClassFile cf) throws CompileException {
this.compileDeclaredMethods(typeDeclaration, cf, 0);
}
/**
* Compile methods for this declaration starting at {@code startPos}.
*
* @param startPos Starting parameter to fill in
* @throws CompileException
*/
private void
compileDeclaredMethods(TypeDeclaration typeDeclaration, ClassFile cf, int startPos) throws CompileException {
// Notice that as a side effect of compiling methods, synthetic "class-dollar" methods (which implement class
// literals) are generated on-the fly. Hence, we must not use an Iterator here.
for (int i = startPos; i < typeDeclaration.getMethodDeclarations().size(); ++i) {
MethodDeclarator md = (MethodDeclarator) typeDeclaration.getMethodDeclarations().get(i);
IMethod m = this.toIMethod(md);
boolean overrides = this.overridesMethodFromSupertype(m, this.resolve(md.getDeclaringType()));
boolean hasOverrideAnnotation = this.hasAnnotation(md, this.iClassLoader.ANNO_java_lang_Override);
if (overrides && !hasOverrideAnnotation && !(typeDeclaration instanceof InterfaceDeclaration)) {
this.warning("MO", "Missing @Override", md.getLocation());
} else
if (!overrides && hasOverrideAnnotation) {
this.compileError("Method does not override a method declared in a supertype", md.getLocation());
}
this.compile(md, cf);
}
}
private boolean
hasAnnotation(FunctionDeclarator fd, IClass methodAnnotation) throws CompileException {
Annotation[] methodAnnotations = fd.modifiers.annotations;
for (Annotation ma : methodAnnotations) {
if (this.getType(ma.getType()) == methodAnnotation) return true;
}
return false;
}
private boolean
overridesMethodFromSupertype(IMethod m, IClass type) throws CompileException {
// Check whether it overrides a method declared in the superclass (or any of its supertypes).
{
IClass superclass = type.getSuperclass();
if (superclass != null && this.overridesMethod(m, superclass)) return true;
}
// Check whether it overrides a method declared in an interface (or any of its superinterfaces).
IClass[] ifs = type.getInterfaces();
for (IClass i : ifs) {
if (this.overridesMethod(m, i)) return true;
}
// Special handling for interfaces that don't extend other interfaces: JLS7 dictates that these stem from
// 'Object', but 'getSuperclass()' returns NULL for interfaces.
if (ifs.length == 0 && type.isInterface()) {
return this.overridesMethod(m, this.iClassLoader.TYPE_java_lang_Object);
}
return false;
}
/** @return Whether {@code method} overrides a method of {@code type} or any of its supertypes */
private boolean
overridesMethod(IMethod method, IClass type) throws CompileException {
// Check whether it overrides a method declared in THIS type.
IMethod[] ms = type.getDeclaredIMethods(method.getName());
for (IMethod m : ms) {
if (Arrays.equals(method.getParameterTypes(), m.getParameterTypes())) return true;
}
// Check whether it overrides a method declared in a supertype.
return this.overridesMethodFromSupertype(method, type);
}
/** Compiles a bridge method which will add a method of the signature of base that delegates to override. */
private void
compileBridgeMethod(ClassFile cf, IMethod base, IMethod override) throws CompileException {
ClassFile.MethodInfo mi = cf.addMethodInfo(
new Modifiers((short) (Mod.PUBLIC | Mod.SYNTHETIC)),
base.getName(),
base.getDescriptor()
);
// Add "Exceptions" attribute (JVMS 4.7.4).
IClass[] thrownExceptions = base.getThrownExceptions();
if (thrownExceptions.length > 0) {
final short eani = cf.addConstantUtf8Info("Exceptions");
short[] tecciis = new short[thrownExceptions.length];
for (int i = 0; i < thrownExceptions.length; ++i) {
tecciis[i] = cf.addConstantClassInfo(thrownExceptions[i].getDescriptor());
}
mi.addAttribute(new ClassFile.ExceptionsAttribute(eani, tecciis));
}
final CodeContext codeContext = new CodeContext(mi.getClassFile(), base.toString());
final CodeContext savedCodeContext = this.replaceCodeContext(codeContext);
// Allocate all our local variables.
codeContext.saveLocalVariables();
codeContext.allocateLocalVariable((short) 1, "this", override.getDeclaringIClass());
IClass[] paramTypes = override.getParameterTypes();
LocalVariableSlot[] locals = new LocalVariableSlot[paramTypes.length];
for (int i = 0; i < paramTypes.length; ++i) {
locals[i] = codeContext.allocateLocalVariable(
Descriptor.size(paramTypes[i].getDescriptor()),
"param" + i,
paramTypes[i]
);
}
this.writeOpcode(Located.NOWHERE, Opcode.ALOAD_0);
for (LocalVariableSlot l : locals) this.load(Located.NOWHERE, l.getType(), l.getSlotIndex());
this.invoke(Located.NOWHERE, override);
this.writeOpcode(Located.NOWHERE, Opcode.ARETURN);
this.replaceCodeContext(savedCodeContext);
codeContext.flowAnalysis(override.getName());
// Add the code context as a code attribute to the MethodInfo.
mi.addAttribute(new ClassFile.AttributeInfo(cf.addConstantUtf8Info("Code")) {
@Override protected void
storeBody(DataOutputStream dos) throws IOException {
codeContext.storeCodeAttributeBody(dos, (short) 0, (short) 0);
}
});
}
/** @return Whether this statement can complete normally (JLS7 14.1) */
private boolean
compile(BlockStatement bs) throws CompileException {
final boolean[] res = new boolean[1];
BlockStatementVisitor bsv = new BlockStatementVisitor() {
// CHECKSTYLE LineLengthCheck:OFF
@Override public void visitInitializer(Initializer i) { try { res[0] = UnitCompiler.this.compile2(i); } catch (CompileException e) { throw new UncheckedCompileException(e); } }
@Override public void visitFieldDeclaration(FieldDeclaration fd) { try { res[0] = UnitCompiler.this.compile2(fd); } catch (CompileException e) { throw new UncheckedCompileException(e); } }
@Override public void visitLabeledStatement(LabeledStatement ls) { try { res[0] = UnitCompiler.this.compile2(ls); } catch (CompileException e) { throw new UncheckedCompileException(e); } }
@Override public void visitBlock(Block b) { try { res[0] = UnitCompiler.this.compile2(b); } catch (CompileException e) { throw new UncheckedCompileException(e); } }
@Override public void visitExpressionStatement(ExpressionStatement es) { try { res[0] = UnitCompiler.this.compile2(es); } catch (CompileException e) { throw new UncheckedCompileException(e); } }
@Override public void visitIfStatement(IfStatement is) { try { res[0] = UnitCompiler.this.compile2(is); } catch (CompileException e) { throw new UncheckedCompileException(e); } }
@Override public void visitForStatement(ForStatement fs) { try { res[0] = UnitCompiler.this.compile2(fs); } catch (CompileException e) { throw new UncheckedCompileException(e); } }
@Override public void visitForEachStatement(ForEachStatement fes) { try { res[0] = UnitCompiler.this.compile2(fes); } catch (CompileException e) { throw new UncheckedCompileException(e); } }
@Override public void visitWhileStatement(WhileStatement ws) { try { res[0] = UnitCompiler.this.compile2(ws); } catch (CompileException e) { throw new UncheckedCompileException(e); } }
@Override public void visitTryStatement(TryStatement ts) { try { res[0] = UnitCompiler.this.compile2(ts); } catch (CompileException e) { throw new UncheckedCompileException(e); } }
@Override public void visitSwitchStatement(SwitchStatement ss) { try { res[0] = UnitCompiler.this.compile2(ss); } catch (CompileException e) { throw new UncheckedCompileException(e); } }
@Override public void visitSynchronizedStatement(SynchronizedStatement ss) { try { res[0] = UnitCompiler.this.compile2(ss); } catch (CompileException e) { throw new UncheckedCompileException(e); } }
@Override public void visitDoStatement(DoStatement ds) { try { res[0] = UnitCompiler.this.compile2(ds); } catch (CompileException e) { throw new UncheckedCompileException(e); } }
@Override public void visitLocalVariableDeclarationStatement(LocalVariableDeclarationStatement lvds) { try { res[0] = UnitCompiler.this.compile2(lvds); } catch (CompileException e) { throw new UncheckedCompileException(e); } }
@Override public void visitReturnStatement(ReturnStatement rs) { try { res[0] = UnitCompiler.this.compile2(rs); } catch (CompileException e) { throw new UncheckedCompileException(e); } }
@Override public void visitThrowStatement(ThrowStatement ts) { try { res[0] = UnitCompiler.this.compile2(ts); } catch (CompileException e) { throw new UncheckedCompileException(e); } }
@Override public void visitBreakStatement(BreakStatement bs) { try { res[0] = UnitCompiler.this.compile2(bs); } catch (CompileException e) { throw new UncheckedCompileException(e); } }
@Override public void visitContinueStatement(ContinueStatement cs) { try { res[0] = UnitCompiler.this.compile2(cs); } catch (CompileException e) { throw new UncheckedCompileException(e); } }
@Override public void visitAssertStatement(AssertStatement as) { try { res[0] = UnitCompiler.this.compile2(as); } catch (CompileException e) { throw new UncheckedCompileException(e); } }
@Override public void visitEmptyStatement(EmptyStatement es) { res[0] = UnitCompiler.this.compile2(es); }
@Override public void visitLocalClassDeclarationStatement(LocalClassDeclarationStatement lcds) { try { res[0] = UnitCompiler.this.compile2(lcds); } catch (CompileException e) { throw new UncheckedCompileException(e); } }
@Override public void visitAlternateConstructorInvocation(AlternateConstructorInvocation aci) { try { res[0] = UnitCompiler.this.compile2(aci); } catch (CompileException e) { throw new UncheckedCompileException(e); } }
@Override public void visitSuperConstructorInvocation(SuperConstructorInvocation sci) { try { res[0] = UnitCompiler.this.compile2(sci); } catch (CompileException e) { throw new UncheckedCompileException(e); } }
// CHECKSTYLE LineLengthCheck:ON
};
try {
bs.accept(bsv);
return res[0];
} catch (UncheckedCompileException uce) {
throw uce.compileException; // SUPPRESS CHECKSTYLE AvoidHidingCause
}
}
/**
* Called to check whether the given {@link Rvalue} compiles or not.
*
* @return Whether the block statement can complete normally
*/
private boolean
fakeCompile(BlockStatement bs) throws CompileException {
Offset from = this.codeContext.newOffset();
boolean ccn = this.compile(bs);
Offset to = this.codeContext.newOffset();
this.codeContext.removeCode(from, to);
return ccn;
}
private boolean
compile2(Initializer i) throws CompileException {
return this.compile(i.block);
}
private boolean
compile2(Block b) throws CompileException {
this.codeContext.saveLocalVariables();
try {
return this.compileStatements(b.statements);
} finally {
this.codeContext.restoreLocalVariables();
}
}
private boolean
compileStatements(List<? extends BlockStatement> statements) throws CompileException {