forked from openjdk/valhalla
/
Lower.java
4227 lines (3827 loc) · 174 KB
/
Lower.java
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
/*
* Copyright (c) 1999, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.comp;
import java.util.*;
import java.util.stream.Collectors;
import com.sun.tools.javac.code.*;
import com.sun.tools.javac.code.Kinds.KindSelector;
import com.sun.tools.javac.code.Scope.WriteableScope;
import com.sun.tools.javac.code.Source.Feature;
import com.sun.tools.javac.jvm.*;
import com.sun.tools.javac.jvm.PoolConstant.LoadableConstant;
import com.sun.tools.javac.main.Option.PkgInfo;
import com.sun.tools.javac.resources.CompilerProperties.Fragments;
import com.sun.tools.javac.tree.*;
import com.sun.tools.javac.util.*;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.code.Symbol.*;
import com.sun.tools.javac.code.Symbol.OperatorSymbol.AccessCode;
import com.sun.tools.javac.resources.CompilerProperties.Errors;
import com.sun.tools.javac.tree.JCTree.*;
import com.sun.tools.javac.code.Type.*;
import com.sun.tools.javac.jvm.Target;
import com.sun.tools.javac.tree.EndPosTable;
import static com.sun.tools.javac.code.Flags.*;
import static com.sun.tools.javac.code.Flags.BLOCK;
import static com.sun.tools.javac.code.Scope.LookupKind.NON_RECURSIVE;
import static com.sun.tools.javac.code.TypeTag.*;
import static com.sun.tools.javac.code.Kinds.Kind.*;
import static com.sun.tools.javac.jvm.ByteCodes.*;
import com.sun.tools.javac.tree.JCTree.JCBreak;
import com.sun.tools.javac.tree.JCTree.JCCase;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.tree.JCTree.JCExpressionStatement;
import static com.sun.tools.javac.tree.JCTree.JCOperatorExpression.OperandPos.LEFT;
import com.sun.tools.javac.tree.JCTree.JCSwitchExpression;
import static com.sun.tools.javac.tree.JCTree.Tag.*;
/** This pass translates away some syntactic sugar: inner classes,
* class literals, assertions, foreach loops, etc.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class Lower extends TreeTranslator {
protected static final Context.Key<Lower> lowerKey = new Context.Key<>();
public static Lower instance(Context context) {
Lower instance = context.get(lowerKey);
if (instance == null)
instance = new Lower(context);
return instance;
}
private final Names names;
private final Log log;
private final Symtab syms;
private final Resolve rs;
private final Operators operators;
private final Check chk;
private final Attr attr;
private TreeMaker make;
private DiagnosticPosition make_pos;
private final ConstFold cfolder;
private final Target target;
private final TypeEnvs typeEnvs;
private final Name dollarAssertionsDisabled;
private final Types types;
private final boolean debugLower;
private final boolean disableProtectedAccessors; // experimental
private final PkgInfo pkginfoOpt;
protected Lower(Context context) {
context.put(lowerKey, this);
names = Names.instance(context);
log = Log.instance(context);
syms = Symtab.instance(context);
rs = Resolve.instance(context);
operators = Operators.instance(context);
chk = Check.instance(context);
attr = Attr.instance(context);
make = TreeMaker.instance(context);
cfolder = ConstFold.instance(context);
target = Target.instance(context);
typeEnvs = TypeEnvs.instance(context);
dollarAssertionsDisabled = names.
fromString(target.syntheticNameChar() + "assertionsDisabled");
types = Types.instance(context);
Options options = Options.instance(context);
debugLower = options.isSet("debuglower");
pkginfoOpt = PkgInfo.get(options);
disableProtectedAccessors = options.isSet("disableProtectedAccessors");
}
/** The currently enclosing class.
*/
ClassSymbol currentClass;
/** A queue of all translated classes.
*/
ListBuffer<JCTree> translated;
/** Environment for symbol lookup, set by translateTopLevelClass.
*/
Env<AttrContext> attrEnv;
/** A hash table mapping syntax trees to their ending source positions.
*/
EndPosTable endPosTable;
/**************************************************************************
* Global mappings
*************************************************************************/
/** A hash table mapping local classes to their definitions.
*/
Map<ClassSymbol, JCClassDecl> classdefs;
/** A hash table mapping local classes to a list of pruned trees.
*/
public Map<ClassSymbol, List<JCTree>> prunedTree = new WeakHashMap<>();
/** A hash table mapping virtual accessed symbols in outer subclasses
* to the actually referred symbol in superclasses.
*/
Map<Symbol,Symbol> actualSymbols;
/** The current method definition.
*/
JCMethodDecl currentMethodDef;
/** The current method symbol.
*/
MethodSymbol currentMethodSym;
/** The currently enclosing outermost class definition.
*/
JCClassDecl outermostClassDef;
/** The currently enclosing outermost member definition.
*/
JCTree outermostMemberDef;
/** A map from local variable symbols to their translation (as per LambdaToMethod).
* This is required when a capturing local class is created from a lambda (in which
* case the captured symbols should be replaced with the translated lambda symbols).
*/
Map<Symbol, Symbol> lambdaTranslationMap = null;
/** A navigator class for assembling a mapping from local class symbols
* to class definition trees.
* There is only one case; all other cases simply traverse down the tree.
*/
class ClassMap extends TreeScanner {
/** All encountered class defs are entered into classdefs table.
*/
public void visitClassDef(JCClassDecl tree) {
classdefs.put(tree.sym, tree);
super.visitClassDef(tree);
}
}
ClassMap classMap = new ClassMap();
/** Map a class symbol to its definition.
* @param c The class symbol of which we want to determine the definition.
*/
JCClassDecl classDef(ClassSymbol c) {
// First lookup the class in the classdefs table.
JCClassDecl def = classdefs.get(c);
if (def == null && outermostMemberDef != null) {
// If this fails, traverse outermost member definition, entering all
// local classes into classdefs, and try again.
classMap.scan(outermostMemberDef);
def = classdefs.get(c);
}
if (def == null) {
// If this fails, traverse outermost class definition, entering all
// local classes into classdefs, and try again.
classMap.scan(outermostClassDef);
def = classdefs.get(c);
}
return def;
}
/** A hash table mapping class symbols to lists of free variables.
* accessed by them. Only free variables of the method immediately containing
* a class are associated with that class.
*/
Map<ClassSymbol,List<VarSymbol>> freevarCache;
/** A navigator class for collecting the free variables accessed
* from a local class. There is only one case; all other cases simply
* traverse down the tree. This class doesn't deal with the specific
* of Lower - it's an abstract visitor that is meant to be reused in
* order to share the local variable capture logic.
*/
abstract class BasicFreeVarCollector extends TreeScanner {
/** Add all free variables of class c to fvs list
* unless they are already there.
*/
abstract void addFreeVars(ClassSymbol c);
/** If tree refers to a variable in owner of local class, add it to
* free variables list.
*/
public void visitIdent(JCIdent tree) {
visitSymbol(tree.sym);
}
// where
abstract void visitSymbol(Symbol _sym);
/** If tree refers to a class instance creation expression
* add all free variables of the freshly created class.
*/
public void visitNewClass(JCNewClass tree) {
ClassSymbol c = (ClassSymbol)tree.constructor.owner;
addFreeVars(c);
super.visitNewClass(tree);
}
/** If tree refers to a superclass constructor call,
* add all free variables of the superclass.
*/
public void visitApply(JCMethodInvocation tree) {
if (TreeInfo.name(tree.meth) == names._super) {
addFreeVars((ClassSymbol) TreeInfo.symbol(tree.meth).owner);
}
super.visitApply(tree);
}
@Override
public void visitYield(JCYield tree) {
scan(tree.value);
}
}
/**
* Lower-specific subclass of {@code BasicFreeVarCollector}.
*/
class FreeVarCollector extends BasicFreeVarCollector {
/** The owner of the local class.
*/
Symbol owner;
/** The local class.
*/
ClassSymbol clazz;
/** The list of owner's variables accessed from within the local class,
* without any duplicates.
*/
List<VarSymbol> fvs;
FreeVarCollector(ClassSymbol clazz) {
this.clazz = clazz;
this.owner = clazz.owner;
this.fvs = List.nil();
}
/** Add free variable to fvs list unless it is already there.
*/
private void addFreeVar(VarSymbol v) {
for (List<VarSymbol> l = fvs; l.nonEmpty(); l = l.tail)
if (l.head == v) return;
fvs = fvs.prepend(v);
}
@Override
void addFreeVars(ClassSymbol c) {
List<VarSymbol> fvs = freevarCache.get(c);
if (fvs != null) {
for (List<VarSymbol> l = fvs; l.nonEmpty(); l = l.tail) {
addFreeVar(l.head);
}
}
}
@Override
void visitSymbol(Symbol _sym) {
Symbol sym = _sym;
if (sym.kind == VAR || sym.kind == MTH) {
if (sym != null && sym.owner != owner)
sym = proxies.get(sym);
if (sym != null && sym.owner == owner) {
VarSymbol v = (VarSymbol)sym;
if (v.getConstValue() == null) {
addFreeVar(v);
}
} else {
if (outerThisStack.head != null &&
outerThisStack.head != _sym)
visitSymbol(outerThisStack.head);
}
}
}
/** If tree refers to a class instance creation expression
* add all free variables of the freshly created class.
*/
public void visitNewClass(JCNewClass tree) {
ClassSymbol c = (ClassSymbol)tree.constructor.owner;
if (tree.encl == null &&
c.hasOuterInstance() &&
outerThisStack.head != null)
visitSymbol(outerThisStack.head);
super.visitNewClass(tree);
}
/** If tree refers to a qualified this or super expression
* for anything but the current class, add the outer this
* stack as a free variable.
*/
public void visitSelect(JCFieldAccess tree) {
if ((tree.name == names._this || tree.name == names._super) &&
tree.selected.type.tsym != clazz &&
outerThisStack.head != null)
visitSymbol(outerThisStack.head);
super.visitSelect(tree);
}
/** If tree refers to a superclass constructor call,
* add all free variables of the superclass.
*/
public void visitApply(JCMethodInvocation tree) {
if (TreeInfo.name(tree.meth) == names._super) {
Symbol constructor = TreeInfo.symbol(tree.meth);
ClassSymbol c = (ClassSymbol)constructor.owner;
if (c.hasOuterInstance() &&
!tree.meth.hasTag(SELECT) &&
outerThisStack.head != null)
visitSymbol(outerThisStack.head);
}
super.visitApply(tree);
}
}
ClassSymbol ownerToCopyFreeVarsFrom(ClassSymbol c) {
if (!c.isDirectlyOrIndirectlyLocal()) {
return null;
}
Symbol currentOwner = c.owner;
while (currentOwner.owner.kind.matches(KindSelector.TYP) && currentOwner.isDirectlyOrIndirectlyLocal()) {
currentOwner = currentOwner.owner;
}
if (currentOwner.owner.kind.matches(KindSelector.VAL_MTH) && c.isSubClass(currentOwner, types)) {
return (ClassSymbol)currentOwner;
}
return null;
}
/** Return the variables accessed from within a local class, which
* are declared in the local class' owner.
* (in reverse order of first access).
*/
List<VarSymbol> freevars(ClassSymbol c) {
List<VarSymbol> fvs = freevarCache.get(c);
if (fvs != null) {
return fvs;
}
if (c.owner.kind.matches(KindSelector.VAL_MTH)) {
FreeVarCollector collector = new FreeVarCollector(c);
collector.scan(classDef(c));
fvs = collector.fvs;
freevarCache.put(c, fvs);
return fvs;
} else {
ClassSymbol owner = ownerToCopyFreeVarsFrom(c);
if (owner != null) {
fvs = freevarCache.get(owner);
freevarCache.put(c, fvs);
return fvs;
} else {
return List.nil();
}
}
}
Map<TypeSymbol,EnumMapping> enumSwitchMap = new LinkedHashMap<>();
EnumMapping mapForEnum(DiagnosticPosition pos, TypeSymbol enumClass) {
EnumMapping map = enumSwitchMap.get(enumClass);
if (map == null)
enumSwitchMap.put(enumClass, map = new EnumMapping(pos, enumClass));
return map;
}
/** This map gives a translation table to be used for enum
* switches.
*
* <p>For each enum that appears as the type of a switch
* expression, we maintain an EnumMapping to assist in the
* translation, as exemplified by the following example:
*
* <p>we translate
* <pre>
* switch(colorExpression) {
* case red: stmt1;
* case green: stmt2;
* }
* </pre>
* into
* <pre>
* switch(Outer$0.$EnumMap$Color[colorExpression.ordinal()]) {
* case 1: stmt1;
* case 2: stmt2
* }
* </pre>
* with the auxiliary table initialized as follows:
* <pre>
* class Outer$0 {
* synthetic final int[] $EnumMap$Color = new int[Color.values().length];
* static {
* try { $EnumMap$Color[red.ordinal()] = 1; } catch (NoSuchFieldError ex) {}
* try { $EnumMap$Color[green.ordinal()] = 2; } catch (NoSuchFieldError ex) {}
* }
* }
* </pre>
* class EnumMapping provides mapping data and support methods for this translation.
*/
class EnumMapping {
EnumMapping(DiagnosticPosition pos, TypeSymbol forEnum) {
this.forEnum = forEnum;
this.values = new LinkedHashMap<>();
this.pos = pos;
Name varName = names
.fromString(target.syntheticNameChar() +
"SwitchMap" +
target.syntheticNameChar() +
names.fromUtf(ClassWriter.externalize(forEnum.type.tsym.flatName())).toString()
.replace('/', '.')
.replace('.', target.syntheticNameChar()));
ClassSymbol outerCacheClass = outerCacheClass();
this.mapVar = new VarSymbol(STATIC | SYNTHETIC | FINAL,
varName,
new ArrayType(syms.intType, syms.arrayClass),
outerCacheClass);
enterSynthetic(pos, mapVar, outerCacheClass.members());
}
DiagnosticPosition pos = null;
// the next value to use
int next = 1; // 0 (unused map elements) go to the default label
// the enum for which this is a map
final TypeSymbol forEnum;
// the field containing the map
final VarSymbol mapVar;
// the mapped values
final Map<VarSymbol,Integer> values;
JCLiteral forConstant(VarSymbol v) {
Integer result = values.get(v);
if (result == null)
values.put(v, result = next++);
return make.Literal(result);
}
// generate the field initializer for the map
void translate() {
make.at(pos.getStartPosition());
JCClassDecl owner = classDef((ClassSymbol)mapVar.owner);
// synthetic static final int[] $SwitchMap$Color = new int[Color.values().length];
MethodSymbol valuesMethod = lookupMethod(pos,
names.values,
forEnum.type,
List.nil());
JCExpression size = make // Color.values().length
.Select(make.App(make.QualIdent(valuesMethod)),
syms.lengthVar);
JCExpression mapVarInit = make
.NewArray(make.Type(syms.intType), List.of(size), null)
.setType(new ArrayType(syms.intType, syms.arrayClass));
// try { $SwitchMap$Color[red.ordinal()] = 1; } catch (java.lang.NoSuchFieldError ex) {}
ListBuffer<JCStatement> stmts = new ListBuffer<>();
Symbol ordinalMethod = lookupMethod(pos,
names.ordinal,
forEnum.type,
List.nil());
List<JCCatch> catcher = List.<JCCatch>nil()
.prepend(make.Catch(make.VarDef(new VarSymbol(PARAMETER, names.ex,
syms.noSuchFieldErrorType,
syms.noSymbol),
null),
make.Block(0, List.nil())));
for (Map.Entry<VarSymbol,Integer> e : values.entrySet()) {
VarSymbol enumerator = e.getKey();
Integer mappedValue = e.getValue();
JCExpression assign = make
.Assign(make.Indexed(mapVar,
make.App(make.Select(make.QualIdent(enumerator),
ordinalMethod))),
make.Literal(mappedValue))
.setType(syms.intType);
JCStatement exec = make.Exec(assign);
JCStatement _try = make.Try(make.Block(0, List.of(exec)), catcher, null);
stmts.append(_try);
}
owner.defs = owner.defs
.prepend(make.Block(STATIC, stmts.toList()))
.prepend(make.VarDef(mapVar, mapVarInit));
}
}
/**************************************************************************
* Tree building blocks
*************************************************************************/
/** Equivalent to make.at(pos.getStartPosition()) with side effect of caching
* pos as make_pos, for use in diagnostics.
**/
TreeMaker make_at(DiagnosticPosition pos) {
make_pos = pos;
return make.at(pos);
}
/** Make an attributed tree representing a literal. This will be an
* Ident node in the case of boolean literals, a Literal node in all
* other cases.
* @param type The literal's type.
* @param value The literal's value.
*/
JCExpression makeLit(Type type, Object value) {
return make.Literal(type.getTag(), value).setType(type.constType(value));
}
/** Make an attributed tree representing null.
*/
JCExpression makeNull() {
return makeLit(syms.botType, null);
}
/** Make an attributed class instance creation expression.
* @param ctype The class type.
* @param args The constructor arguments.
*/
JCNewClass makeNewClass(Type ctype, List<JCExpression> args) {
JCNewClass tree = make.NewClass(null,
null, make.QualIdent(ctype.tsym), args, null);
tree.constructor = rs.resolveConstructor(
make_pos, attrEnv, ctype, TreeInfo.types(args), List.nil());
tree.type = ctype;
return tree;
}
/** Make an attributed unary expression.
* @param optag The operators tree tag.
* @param arg The operator's argument.
*/
JCUnary makeUnary(JCTree.Tag optag, JCExpression arg) {
JCUnary tree = make.Unary(optag, arg);
tree.operator = operators.resolveUnary(tree, optag, arg.type);
tree.type = tree.operator.type.getReturnType();
return tree;
}
/** Make an attributed binary expression.
* @param optag The operators tree tag.
* @param lhs The operator's left argument.
* @param rhs The operator's right argument.
*/
JCBinary makeBinary(JCTree.Tag optag, JCExpression lhs, JCExpression rhs) {
JCBinary tree = make.Binary(optag, lhs, rhs);
tree.operator = operators.resolveBinary(tree, optag, lhs.type, rhs.type);
tree.type = tree.operator.type.getReturnType();
return tree;
}
/** Make an attributed assignop expression.
* @param optag The operators tree tag.
* @param lhs The operator's left argument.
* @param rhs The operator's right argument.
*/
JCAssignOp makeAssignop(JCTree.Tag optag, JCTree lhs, JCTree rhs) {
JCAssignOp tree = make.Assignop(optag, lhs, rhs);
tree.operator = operators.resolveBinary(tree, tree.getTag().noAssignOp(), lhs.type, rhs.type);
tree.type = lhs.type;
return tree;
}
/** Convert tree into string object, unless it has already a
* reference type..
*/
JCExpression makeString(JCExpression tree) {
if (!tree.type.isPrimitiveOrVoid()) {
return tree;
} else {
Symbol valueOfSym = lookupMethod(tree.pos(),
names.valueOf,
syms.stringType,
List.of(tree.type));
return make.App(make.QualIdent(valueOfSym), List.of(tree));
}
}
/** Create an empty anonymous class definition and enter and complete
* its symbol. Return the class definition's symbol.
* and create
* @param flags The class symbol's flags
* @param owner The class symbol's owner
*/
JCClassDecl makeEmptyClass(long flags, ClassSymbol owner) {
return makeEmptyClass(flags, owner, null, true);
}
JCClassDecl makeEmptyClass(long flags, ClassSymbol owner, Name flatname,
boolean addToDefs) {
// Create class symbol.
ClassSymbol c = syms.defineClass(names.empty, owner);
if (flatname != null) {
c.flatname = flatname;
} else {
c.flatname = chk.localClassName(c);
}
c.sourcefile = owner.sourcefile;
c.completer = Completer.NULL_COMPLETER;
c.members_field = WriteableScope.create(c);
c.flags_field = flags;
ClassType ctype = (ClassType) c.type;
ctype.supertype_field = syms.objectType;
ctype.interfaces_field = List.nil();
JCClassDecl odef = classDef(owner);
// Enter class symbol in owner scope and compiled table.
enterSynthetic(odef.pos(), c, owner.members());
chk.putCompiled(c);
// Create class definition tree.
JCClassDecl cdef = make.ClassDef(
make.Modifiers(flags), names.empty,
List.nil(),
null, List.nil(), List.nil());
cdef.sym = c;
cdef.type = c.type;
// Append class definition tree to owner's definitions.
if (addToDefs) odef.defs = odef.defs.prepend(cdef);
return cdef;
}
/**************************************************************************
* Symbol manipulation utilities
*************************************************************************/
/** Enter a synthetic symbol in a given scope, but complain if there was already one there.
* @param pos Position for error reporting.
* @param sym The symbol.
* @param s The scope.
*/
private void enterSynthetic(DiagnosticPosition pos, Symbol sym, WriteableScope s) {
s.enter(sym);
}
/** Create a fresh synthetic name within a given scope - the unique name is
* obtained by appending '$' chars at the end of the name until no match
* is found.
*
* @param name base name
* @param s scope in which the name has to be unique
* @return fresh synthetic name
*/
private Name makeSyntheticName(Name name, Scope s) {
do {
name = name.append(
target.syntheticNameChar(),
names.empty);
} while (lookupSynthetic(name, s) != null);
return name;
}
/** Check whether synthetic symbols generated during lowering conflict
* with user-defined symbols.
*
* @param translatedTrees lowered class trees
*/
void checkConflicts(List<JCTree> translatedTrees) {
for (JCTree t : translatedTrees) {
t.accept(conflictsChecker);
}
}
JCTree.Visitor conflictsChecker = new TreeScanner() {
TypeSymbol currentClass;
@Override
public void visitMethodDef(JCMethodDecl that) {
checkConflicts(that.pos(), that.sym, currentClass);
super.visitMethodDef(that);
}
@Override
public void visitVarDef(JCVariableDecl that) {
if (that.sym.owner.kind == TYP) {
checkConflicts(that.pos(), that.sym, currentClass);
}
super.visitVarDef(that);
}
@Override
public void visitClassDef(JCClassDecl that) {
TypeSymbol prevCurrentClass = currentClass;
currentClass = that.sym;
try {
super.visitClassDef(that);
}
finally {
currentClass = prevCurrentClass;
}
}
void checkConflicts(DiagnosticPosition pos, Symbol sym, TypeSymbol c) {
for (Type ct = c.type; ct != Type.noType ; ct = types.supertype(ct)) {
for (Symbol sym2 : ct.tsym.members().getSymbolsByName(sym.name, NON_RECURSIVE)) {
// VM allows methods and variables with differing types
if (sym.kind == sym2.kind &&
types.isSameType(types.erasure(sym.type), types.erasure(sym2.type)) &&
sym != sym2 &&
(sym.flags() & Flags.SYNTHETIC) != (sym2.flags() & Flags.SYNTHETIC) &&
(sym.flags() & BRIDGE) == 0 && (sym2.flags() & BRIDGE) == 0) {
syntheticError(pos, (sym2.flags() & SYNTHETIC) == 0 ? sym2 : sym);
return;
}
}
}
}
/** Report a conflict between a user symbol and a synthetic symbol.
*/
private void syntheticError(DiagnosticPosition pos, Symbol sym) {
if (!sym.type.isErroneous()) {
log.error(pos, Errors.CannotGenerateClass(sym.location(), Fragments.SyntheticNameConflict(sym, sym.location())));
}
}
};
/** Look up a synthetic name in a given scope.
* @param s The scope.
* @param name The name.
*/
private Symbol lookupSynthetic(Name name, Scope s) {
Symbol sym = s.findFirst(name);
return (sym==null || (sym.flags()&SYNTHETIC)==0) ? null : sym;
}
/** Look up a method in a given scope.
*/
private MethodSymbol lookupMethod(DiagnosticPosition pos, Name name, Type qual, List<Type> args) {
return rs.resolveInternalMethod(pos, attrEnv, qual, name, args, List.nil());
}
/** Anon inner classes are used as access constructor tags.
* accessConstructorTag will use an existing anon class if one is available,
* and synthesize a class (with makeEmptyClass) if one is not available.
* However, there is a small possibility that an existing class will not
* be generated as expected if it is inside a conditional with a constant
* expression. If that is found to be the case, create an empty class tree here.
*/
private void checkAccessConstructorTags() {
for (List<ClassSymbol> l = accessConstrTags; l.nonEmpty(); l = l.tail) {
ClassSymbol c = l.head;
if (isTranslatedClassAvailable(c))
continue;
// Create class definition tree.
JCClassDecl cdec = makeEmptyClass(STATIC | SYNTHETIC,
c.outermostClass(), c.flatname, false);
swapAccessConstructorTag(c, cdec.sym);
translated.append(cdec);
}
}
// where
private boolean isTranslatedClassAvailable(ClassSymbol c) {
for (JCTree tree: translated) {
if (tree.hasTag(CLASSDEF)
&& ((JCClassDecl) tree).sym == c) {
return true;
}
}
return false;
}
void swapAccessConstructorTag(ClassSymbol oldCTag, ClassSymbol newCTag) {
for (MethodSymbol methodSymbol : accessConstrs.values()) {
Assert.check(methodSymbol.type.hasTag(METHOD));
MethodType oldMethodType =
(MethodType)methodSymbol.type;
if (oldMethodType.argtypes.head.tsym == oldCTag)
methodSymbol.type =
types.createMethodTypeWithParameters(oldMethodType,
oldMethodType.getParameterTypes().tail
.prepend(newCTag.erasure(types)));
}
}
/**************************************************************************
* Access methods
*************************************************************************/
/** A mapping from symbols to their access numbers.
*/
private Map<Symbol,Integer> accessNums;
/** A mapping from symbols to an array of access symbols, indexed by
* access code.
*/
private Map<Symbol,MethodSymbol[]> accessSyms;
/** A mapping from (constructor) symbols to access constructor symbols.
*/
private Map<Symbol,MethodSymbol> accessConstrs;
/** A list of all class symbols used for access constructor tags.
*/
private List<ClassSymbol> accessConstrTags;
/** A queue for all accessed symbols.
*/
private ListBuffer<Symbol> accessed;
/** return access code for identifier,
* @param tree The tree representing the identifier use.
* @param enclOp The closest enclosing operation node of tree,
* null if tree is not a subtree of an operation.
*/
private static int accessCode(JCTree tree, JCTree enclOp) {
if (enclOp == null)
return AccessCode.DEREF.code;
else if (enclOp.hasTag(ASSIGN) &&
tree == TreeInfo.skipParens(((JCAssign) enclOp).lhs))
return AccessCode.ASSIGN.code;
else if (enclOp.hasTag(WITHFIELD) &&
tree == TreeInfo.skipParens(((JCWithField) enclOp).field))
return AccessCode.WITHFIELD.code;
else if ((enclOp.getTag().isIncOrDecUnaryOp() || enclOp.getTag().isAssignop()) &&
tree == TreeInfo.skipParens(((JCOperatorExpression) enclOp).getOperand(LEFT)))
return (((JCOperatorExpression) enclOp).operator).getAccessCode(enclOp.getTag());
else
return AccessCode.DEREF.code;
}
/** Return binary operator that corresponds to given access code.
*/
private OperatorSymbol binaryAccessOperator(int acode, Tag tag) {
return operators.lookupBinaryOp(op -> op.getAccessCode(tag) == acode);
}
/** Return tree tag for assignment operation corresponding
* to given binary operator.
*/
private static JCTree.Tag treeTag(OperatorSymbol operator) {
switch (operator.opcode) {
case ByteCodes.ior: case ByteCodes.lor:
return BITOR_ASG;
case ByteCodes.ixor: case ByteCodes.lxor:
return BITXOR_ASG;
case ByteCodes.iand: case ByteCodes.land:
return BITAND_ASG;
case ByteCodes.ishl: case ByteCodes.lshl:
case ByteCodes.ishll: case ByteCodes.lshll:
return SL_ASG;
case ByteCodes.ishr: case ByteCodes.lshr:
case ByteCodes.ishrl: case ByteCodes.lshrl:
return SR_ASG;
case ByteCodes.iushr: case ByteCodes.lushr:
case ByteCodes.iushrl: case ByteCodes.lushrl:
return USR_ASG;
case ByteCodes.iadd: case ByteCodes.ladd:
case ByteCodes.fadd: case ByteCodes.dadd:
case ByteCodes.string_add:
return PLUS_ASG;
case ByteCodes.isub: case ByteCodes.lsub:
case ByteCodes.fsub: case ByteCodes.dsub:
return MINUS_ASG;
case ByteCodes.imul: case ByteCodes.lmul:
case ByteCodes.fmul: case ByteCodes.dmul:
return MUL_ASG;
case ByteCodes.idiv: case ByteCodes.ldiv:
case ByteCodes.fdiv: case ByteCodes.ddiv:
return DIV_ASG;
case ByteCodes.imod: case ByteCodes.lmod:
case ByteCodes.fmod: case ByteCodes.dmod:
return MOD_ASG;
default:
throw new AssertionError();
}
}
/** The name of the access method with number `anum' and access code `acode'.
*/
Name accessName(int anum, int acode) {
return names.fromString(
"access" + target.syntheticNameChar() + anum + acode / 10 + acode % 10);
}
/** Return access symbol for a private or protected symbol from an inner class.
* @param sym The accessed private symbol.
* @param tree The accessing tree.
* @param enclOp The closest enclosing operation node of tree,
* null if tree is not a subtree of an operation.
* @param protAccess Is access to a protected symbol in another
* package?
* @param refSuper Is access via a (qualified) C.super?
*/
MethodSymbol accessSymbol(Symbol sym, JCTree tree, JCTree enclOp,
boolean protAccess, boolean refSuper) {
ClassSymbol accOwner = refSuper && protAccess
// For access via qualified super (T.super.x), place the
// access symbol on T.
? (ClassSymbol)((JCFieldAccess) tree).selected.type.tsym
// Otherwise pretend that the owner of an accessed
// protected symbol is the enclosing class of the current
// class which is a subclass of the symbol's owner.
: accessClass(sym, protAccess, tree);
Symbol vsym = sym;
if (sym.owner != accOwner) {
vsym = sym.clone(accOwner);
actualSymbols.put(vsym, sym);
}
Integer anum // The access number of the access method.
= accessNums.get(vsym);
if (anum == null) {
anum = accessed.length();
accessNums.put(vsym, anum);
accessSyms.put(vsym, new MethodSymbol[AccessCode.numberOfAccessCodes]);
accessed.append(vsym);
// System.out.println("accessing " + vsym + " in " + vsym.location());
}
int acode; // The access code of the access method.
List<Type> argtypes; // The argument types of the access method.
Type restype; // The result type of the access method.
List<Type> thrown; // The thrown exceptions of the access method.
switch (vsym.kind) {
case VAR:
acode = accessCode(tree, enclOp);
if (acode >= AccessCode.FIRSTASGOP.code) {
OperatorSymbol operator = binaryAccessOperator(acode, enclOp.getTag());
if (operator.opcode == string_add)
argtypes = List.of(syms.objectType);
else
argtypes = operator.type.getParameterTypes().tail;
} else if (acode == AccessCode.ASSIGN.code || acode == AccessCode.WITHFIELD.code)
argtypes = List.of(vsym.erasure(types));
else
argtypes = List.nil();
restype = acode == AccessCode.WITHFIELD.code ? vsym.owner.erasure(types) : vsym.erasure(types);
thrown = List.nil();
break;
case MTH:
acode = AccessCode.DEREF.code;
argtypes = vsym.erasure(types).getParameterTypes();
restype = vsym.erasure(types).getReturnType();
thrown = vsym.type.getThrownTypes();
break;
default: