1 /*
2 * Copyright (c) 1999, 2025, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26 package com.sun.tools.javac.comp;
27
28 import java.util.*;
29 import java.util.stream.Collectors;
30
31 import com.sun.source.tree.LambdaExpressionTree.BodyKind;
32 import com.sun.tools.javac.code.*;
33 import com.sun.tools.javac.code.Kinds.KindSelector;
34 import com.sun.tools.javac.code.Scope.WriteableScope;
35 import com.sun.tools.javac.jvm.*;
36 import com.sun.tools.javac.jvm.PoolConstant.LoadableConstant;
37 import com.sun.tools.javac.main.Option.PkgInfo;
38 import com.sun.tools.javac.resources.CompilerProperties.Fragments;
39 import com.sun.tools.javac.resources.CompilerProperties.Notes;
40 import com.sun.tools.javac.tree.*;
41 import com.sun.tools.javac.util.*;
42 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
43 import com.sun.tools.javac.util.List;
44
45 import com.sun.tools.javac.code.Symbol.*;
46 import com.sun.tools.javac.code.Symbol.OperatorSymbol.AccessCode;
47 import com.sun.tools.javac.resources.CompilerProperties.Errors;
48 import com.sun.tools.javac.tree.JCTree.*;
49 import com.sun.tools.javac.code.Type.*;
50
51 import com.sun.tools.javac.jvm.Target;
52 import com.sun.tools.javac.tree.EndPosTable;
53
54 import static com.sun.tools.javac.code.Flags.*;
55 import static com.sun.tools.javac.code.Flags.BLOCK;
56 import static com.sun.tools.javac.code.Scope.LookupKind.NON_RECURSIVE;
57 import static com.sun.tools.javac.code.TypeTag.*;
58 import static com.sun.tools.javac.code.Kinds.Kind.*;
59 import com.sun.tools.javac.code.Source.Feature;
60 import static com.sun.tools.javac.jvm.ByteCodes.*;
61 import com.sun.tools.javac.tree.JCTree.JCBreak;
62 import com.sun.tools.javac.tree.JCTree.JCCase;
63 import com.sun.tools.javac.tree.JCTree.JCExpression;
64 import com.sun.tools.javac.tree.JCTree.JCExpressionStatement;
65
66 import static com.sun.tools.javac.tree.JCTree.JCOperatorExpression.OperandPos.LEFT;
67 import com.sun.tools.javac.tree.JCTree.JCSwitchExpression;
68
69 import static com.sun.tools.javac.tree.JCTree.Tag.*;
70
71 /** This pass translates away some syntactic sugar: inner classes,
72 * class literals, assertions, foreach loops, etc.
73 *
74 * <p><b>This is NOT part of any supported API.
75 * If you write code that depends on this, you do so at your own risk.
76 * This code and its internal interfaces are subject to change or
77 * deletion without notice.</b>
78 */
79 public class Lower extends TreeTranslator {
80 protected static final Context.Key<Lower> lowerKey = new Context.Key<>();
81
82 public static Lower instance(Context context) {
83 Lower instance = context.get(lowerKey);
84 if (instance == null)
85 instance = new Lower(context);
86 return instance;
87 }
88
89 private final Names names;
90 private final Log log;
91 private final Symtab syms;
92 private final Resolve rs;
93 private final Operators operators;
94 private final Check chk;
95 private final Attr attr;
96 private TreeMaker make;
97 private DiagnosticPosition make_pos;
98 private final ConstFold cfolder;
99 private final Target target;
100 private final TypeEnvs typeEnvs;
101 private final Name dollarAssertionsDisabled;
102 private final Types types;
103 private final TransTypes transTypes;
104 private final boolean debugLower;
105 private final boolean disableProtectedAccessors; // experimental
106 private final PkgInfo pkginfoOpt;
107 private final boolean optimizeOuterThis;
108 private final boolean nullCheckOuterThis;
109 private final boolean useMatchException;
110 private final HashMap<TypePairs, String> typePairToName;
111 private final boolean allowValueClasses;
112 private int variableIndex = 0;
113
114 @SuppressWarnings("this-escape")
115 protected Lower(Context context) {
116 context.put(lowerKey, this);
117 names = Names.instance(context);
118 log = Log.instance(context);
119 syms = Symtab.instance(context);
120 rs = Resolve.instance(context);
121 operators = Operators.instance(context);
122 chk = Check.instance(context);
123 attr = Attr.instance(context);
124 make = TreeMaker.instance(context);
125 cfolder = ConstFold.instance(context);
126 target = Target.instance(context);
127 typeEnvs = TypeEnvs.instance(context);
128 dollarAssertionsDisabled = names.
129 fromString(target.syntheticNameChar() + "assertionsDisabled");
130
131 types = Types.instance(context);
132 transTypes = TransTypes.instance(context);
133 Options options = Options.instance(context);
134 debugLower = options.isSet("debuglower");
135 pkginfoOpt = PkgInfo.get(options);
136 optimizeOuterThis =
137 target.optimizeOuterThis() ||
138 options.getBoolean("optimizeOuterThis", false);
139 nullCheckOuterThis = options.getBoolean("nullCheckOuterThis",
140 target.nullCheckOuterThisByDefault());
141 disableProtectedAccessors = options.isSet("disableProtectedAccessors");
142 Source source = Source.instance(context);
143 Preview preview = Preview.instance(context);
144 useMatchException = Feature.PATTERN_SWITCH.allowedInSource(source) &&
145 (preview.isEnabled() || !preview.isPreview(Feature.PATTERN_SWITCH));
146 typePairToName = TypePairs.initialize(syms);
147 this.allowValueClasses = (!preview.isPreview(Feature.VALUE_CLASSES) || preview.isEnabled()) &&
148 Feature.VALUE_CLASSES.allowedInSource(source);
149 }
150
151 /** The currently enclosing class.
152 */
153 ClassSymbol currentClass;
154
155 /** A queue of all translated classes.
156 */
157 ListBuffer<JCTree> translated;
158
159 /** Environment for symbol lookup, set by translateTopLevelClass.
160 */
161 Env<AttrContext> attrEnv;
162
163 /** A hash table mapping syntax trees to their ending source positions.
164 */
165 EndPosTable endPosTable;
166
167 /* ************************************************************************
168 * Global mappings
169 *************************************************************************/
170
171 /** A hash table mapping local classes to their definitions.
172 */
173 Map<ClassSymbol, JCClassDecl> classdefs;
174
175 /** A hash table mapping local classes to a list of pruned trees.
176 */
177 public Map<ClassSymbol, List<JCTree>> prunedTree = new WeakHashMap<>();
178
179 /** A hash table mapping virtual accessed symbols in outer subclasses
180 * to the actually referred symbol in superclasses.
181 */
182 Map<Symbol,Symbol> actualSymbols;
183
184 /**
185 * The current expected return type.
186 */
187 Type currentRestype;
188
189 /** The current method definition.
190 */
191 JCMethodDecl currentMethodDef;
192
193 /** The current method symbol.
194 */
195 MethodSymbol currentMethodSym;
196
197 /** The currently enclosing outermost class definition.
198 */
199 JCClassDecl outermostClassDef;
200
201 /** The currently enclosing outermost member definition.
202 */
203 JCTree outermostMemberDef;
204
205 /** A hash table mapping local classes to a set of outer this fields
206 */
207 public Map<ClassSymbol, Set<JCExpression>> initializerOuterThis = new WeakHashMap<>();
208
209 /** A navigator class for assembling a mapping from local class symbols
210 * to class definition trees.
211 * There is only one case; all other cases simply traverse down the tree.
212 */
213 class ClassMap extends TreeScanner {
214
215 /** All encountered class defs are entered into classdefs table.
216 */
217 public void visitClassDef(JCClassDecl tree) {
218 classdefs.put(tree.sym, tree);
219 super.visitClassDef(tree);
220 }
221 }
222 ClassMap classMap = new ClassMap();
223
224 /** Map a class symbol to its definition.
225 * @param c The class symbol of which we want to determine the definition.
226 */
227 JCClassDecl classDef(ClassSymbol c) {
228 // First lookup the class in the classdefs table.
229 JCClassDecl def = classdefs.get(c);
230 if (def == null && outermostMemberDef != null) {
231 // If this fails, traverse outermost member definition, entering all
232 // local classes into classdefs, and try again.
233 classMap.scan(outermostMemberDef);
234 def = classdefs.get(c);
235 }
236 if (def == null) {
237 // If this fails, traverse outermost class definition, entering all
238 // local classes into classdefs, and try again.
239 classMap.scan(outermostClassDef);
240 def = classdefs.get(c);
241 }
242 return def;
243 }
244
245 /**
246 * Get the enum constants for the given enum class symbol, if known.
247 * They will only be found if they are defined within the same top-level
248 * class as the class being compiled, so it's safe to assume that they
249 * can't change at runtime due to a recompilation.
250 */
251 List<Name> enumNamesFor(ClassSymbol c) {
252
253 // Find the class definition and verify it is an enum class
254 final JCClassDecl classDef = classDef(c);
255 if (classDef == null ||
256 (classDef.mods.flags & ENUM) == 0 ||
257 (types.supertype(currentClass.type).tsym.flags() & ENUM) != 0) {
258 return null;
259 }
260
261 // Gather the enum identifiers
262 ListBuffer<Name> idents = new ListBuffer<>();
263 for (List<JCTree> defs = classDef.defs; defs.nonEmpty(); defs=defs.tail) {
264 if (defs.head.hasTag(VARDEF) &&
265 (((JCVariableDecl) defs.head).mods.flags & ENUM) != 0) {
266 JCVariableDecl var = (JCVariableDecl)defs.head;
267 idents.append(var.name);
268 }
269 }
270 return idents.toList();
271 }
272
273 /** A hash table mapping class symbols to lists of free variables.
274 * accessed by them. Only free variables of the method immediately containing
275 * a class are associated with that class.
276 */
277 Map<ClassSymbol,List<VarSymbol>> freevarCache;
278
279 /** A navigator class for collecting the free variables accessed
280 * from a local class.
281 */
282 class FreeVarCollector extends CaptureScanner {
283
284 FreeVarCollector(JCTree ownerTree) {
285 super(ownerTree);
286 }
287
288 void addFreeVars(ClassSymbol c) {
289 List<VarSymbol> fvs = freevarCache.get(c);
290 if (fvs != null) {
291 for (List<VarSymbol> l = fvs; l.nonEmpty(); l = l.tail) {
292 addFreeVar(l.head);
293 }
294 }
295 }
296
297 /** If tree refers to a class instance creation expression
298 * add all free variables of the freshly created class.
299 */
300 public void visitNewClass(JCNewClass tree) {
301 ClassSymbol c = (ClassSymbol)tree.constructor.owner;
302 addFreeVars(c);
303 super.visitNewClass(tree);
304 }
305
306 /** If tree refers to a superclass constructor call,
307 * add all free variables of the superclass.
308 */
309 public void visitApply(JCMethodInvocation tree) {
310 if (TreeInfo.name(tree.meth) == names._super) {
311 addFreeVars((ClassSymbol) TreeInfo.symbol(tree.meth).owner);
312 }
313 super.visitApply(tree);
314 }
315 }
316
317 /** Return the variables accessed from within a local class, which
318 * are declared in the local class' owner.
319 * (in reverse order of first access).
320 */
321 List<VarSymbol> freevars(ClassSymbol c) {
322 List<VarSymbol> fvs = freevarCache.get(c);
323 if (fvs != null) {
324 return fvs;
325 }
326 FreeVarCollector collector = new FreeVarCollector(classDef(c));
327 fvs = collector.analyzeCaptures().reverse();
328 freevarCache.put(c, fvs);
329 return fvs;
330 }
331
332 Map<TypeSymbol,EnumMapping> enumSwitchMap = new LinkedHashMap<>();
333
334 EnumMapping mapForEnum(DiagnosticPosition pos, TypeSymbol enumClass) {
335
336 // If enum class is part of this compilation, just switch on ordinal value
337 if (enumClass.kind == TYP) {
338 final List<Name> idents = enumNamesFor((ClassSymbol)enumClass);
339 if (idents != null)
340 return new CompileTimeEnumMapping(idents);
341 }
342
343 // Map identifiers to ordinal values at runtime, and then switch on that
344 return enumSwitchMap.computeIfAbsent(enumClass, ec -> new RuntimeEnumMapping(pos, ec));
345 }
346
347 /** Generates a test value and corresponding cases for a switch on an enum type.
348 */
349 interface EnumMapping {
350
351 /** Given an expression for the enum value's ordinal, generate an expression for the switch statement.
352 */
353 JCExpression switchValue(JCExpression ordinalExpr);
354
355 /** Generate the switch statement case value corresponding to the given enum value.
356 */
357 JCLiteral caseValue(VarSymbol v);
358
359 default void translate() {
360 }
361 }
362
363 /** EnumMapping using compile-time constants. Only valid when compiling the enum class itself,
364 * because otherwise the ordinals we use could become obsolete if/when the enum class is recompiled.
365 */
366 class CompileTimeEnumMapping implements EnumMapping {
367
368 final List<Name> enumNames;
369
370 CompileTimeEnumMapping(List<Name> enumNames) {
371 Assert.check(enumNames != null);
372 this.enumNames = enumNames;
373 }
374
375 @Override
376 public JCExpression switchValue(JCExpression ordinalExpr) {
377 return ordinalExpr;
378 }
379
380 @Override
381 public JCLiteral caseValue(VarSymbol v) {
382 final int ordinal = enumNames.indexOf(v.name);
383 Assert.check(ordinal != -1);
384 return make.Literal(ordinal);
385 }
386 }
387
388 /** EnumMapping using run-time ordinal lookup.
389 *
390 * This builds a translation table to be used for enum switches.
391 *
392 * <p>For each enum that appears as the type of a switch
393 * expression, we maintain an EnumMapping to assist in the
394 * translation, as exemplified by the following example:
395 *
396 * <p>we translate
397 * <pre>
398 * switch(colorExpression) {
399 * case red: stmt1;
400 * case green: stmt2;
401 * }
402 * </pre>
403 * into
404 * <pre>
405 * switch(Outer$0.$EnumMap$Color[colorExpression.ordinal()]) {
406 * case 1: stmt1;
407 * case 2: stmt2
408 * }
409 * </pre>
410 * with the auxiliary table initialized as follows:
411 * <pre>
412 * class Outer$0 {
413 * synthetic final int[] $EnumMap$Color = new int[Color.values().length];
414 * static {
415 * try { $EnumMap$Color[red.ordinal()] = 1; } catch (NoSuchFieldError ex) {}
416 * try { $EnumMap$Color[green.ordinal()] = 2; } catch (NoSuchFieldError ex) {}
417 * }
418 * }
419 * </pre>
420 * class EnumMapping provides mapping data and support methods for this translation.
421 */
422 class RuntimeEnumMapping implements EnumMapping {
423 RuntimeEnumMapping(DiagnosticPosition pos, TypeSymbol forEnum) {
424 this.forEnum = forEnum;
425 this.values = new LinkedHashMap<>();
426 this.pos = pos;
427 Name varName = names
428 .fromString(target.syntheticNameChar() +
429 "SwitchMap" +
430 target.syntheticNameChar() +
431 ClassWriter.externalize(forEnum.type.tsym.flatName().toString())
432 .replace('/', '.')
433 .replace('.', target.syntheticNameChar()));
434 ClassSymbol outerCacheClass = outerCacheClass();
435 this.mapVar = new VarSymbol(STATIC | SYNTHETIC | FINAL,
436 varName,
437 new ArrayType(syms.intType, syms.arrayClass),
438 outerCacheClass);
439 enterSynthetic(pos, mapVar, outerCacheClass.members());
440 }
441
442 DiagnosticPosition pos = null;
443
444 // the next value to use
445 int next = 1; // 0 (unused map elements) go to the default label
446
447 // the enum for which this is a map
448 final TypeSymbol forEnum;
449
450 // the field containing the map
451 final VarSymbol mapVar;
452
453 // the mapped values
454 final Map<VarSymbol,Integer> values;
455
456 @Override
457 public JCExpression switchValue(JCExpression ordinalExpr) {
458 return make.Indexed(mapVar, ordinalExpr);
459 }
460
461 @Override
462 public JCLiteral caseValue(VarSymbol v) {
463 Integer result = values.get(v);
464 if (result == null)
465 values.put(v, result = next++);
466 return make.Literal(result);
467 }
468
469 // generate the field initializer for the map
470 @Override
471 public void translate() {
472 boolean prevAllowProtectedAccess = attrEnv.info.allowProtectedAccess;
473 try {
474 make.at(pos.getStartPosition());
475 attrEnv.info.allowProtectedAccess = true;
476 JCClassDecl owner = classDef((ClassSymbol)mapVar.owner);
477
478 // synthetic static final int[] $SwitchMap$Color = new int[Color.values().length];
479 MethodSymbol valuesMethod = lookupMethod(pos,
480 names.values,
481 forEnum.type,
482 List.nil());
483 JCExpression size = make // Color.values().length
484 .Select(make.App(make.QualIdent(valuesMethod)),
485 syms.lengthVar);
486 JCExpression mapVarInit = make
487 .NewArray(make.Type(syms.intType), List.of(size), null)
488 .setType(new ArrayType(syms.intType, syms.arrayClass));
489
490 // try { $SwitchMap$Color[red.ordinal()] = 1; } catch (java.lang.NoSuchFieldError ex) {}
491 ListBuffer<JCStatement> stmts = new ListBuffer<>();
492 Symbol ordinalMethod = lookupMethod(pos,
493 names.ordinal,
494 forEnum.type,
495 List.nil());
496 List<JCCatch> catcher = List.<JCCatch>nil()
497 .prepend(make.Catch(make.VarDef(new VarSymbol(PARAMETER, names.ex,
498 syms.noSuchFieldErrorType,
499 syms.noSymbol),
500 null),
501 make.Block(0, List.nil())));
502 for (Map.Entry<VarSymbol,Integer> e : values.entrySet()) {
503 VarSymbol enumerator = e.getKey();
504 Integer mappedValue = e.getValue();
505 JCExpression assign = make
506 .Assign(make.Indexed(mapVar,
507 make.App(make.Select(make.QualIdent(enumerator),
508 ordinalMethod))),
509 make.Literal(mappedValue))
510 .setType(syms.intType);
511 JCStatement exec = make.Exec(assign);
512 JCStatement _try = make.Try(make.Block(0, List.of(exec)), catcher, null);
513 stmts.append(_try);
514 }
515
516 owner.defs = owner.defs
517 .prepend(make.Block(STATIC, stmts.toList()))
518 .prepend(make.VarDef(mapVar, mapVarInit));
519 } finally {
520 attrEnv.info.allowProtectedAccess = prevAllowProtectedAccess;
521 }
522 }
523 }
524
525
526 /* ************************************************************************
527 * Tree building blocks
528 *************************************************************************/
529
530 /** Equivalent to make.at(pos.getStartPosition()) with side effect of caching
531 * pos as make_pos, for use in diagnostics.
532 **/
533 TreeMaker make_at(DiagnosticPosition pos) {
534 make_pos = pos;
535 return make.at(pos);
536 }
537
538 /** Make an attributed tree representing a literal. This will be an
539 * Ident node in the case of boolean literals, a Literal node in all
540 * other cases.
541 * @param type The literal's type.
542 * @param value The literal's value.
543 */
544 JCExpression makeLit(Type type, Object value) {
545 return make.Literal(type.getTag(), value).setType(type.constType(value));
546 }
547
548 /** Make an attributed tree representing null.
549 */
550 JCExpression makeNull() {
551 return makeLit(syms.botType, null);
552 }
553
554 /** Make an attributed class instance creation expression.
555 * @param ctype The class type.
556 * @param args The constructor arguments.
557 */
558 JCNewClass makeNewClass(Type ctype, List<JCExpression> args) {
559 JCNewClass tree = make.NewClass(null,
560 null, make.QualIdent(ctype.tsym), args, null);
561 tree.constructor = rs.resolveConstructor(
562 make_pos, attrEnv, ctype, TreeInfo.types(args), List.nil());
563 tree.type = ctype;
564 return tree;
565 }
566
567 /** Make an attributed unary expression.
568 * @param optag The operators tree tag.
569 * @param arg The operator's argument.
570 */
571 JCUnary makeUnary(JCTree.Tag optag, JCExpression arg) {
572 JCUnary tree = make.Unary(optag, arg);
573 tree.operator = operators.resolveUnary(tree, optag, arg.type);
574 tree.type = tree.operator.type.getReturnType();
575 return tree;
576 }
577
578 /** Make an attributed binary expression.
579 * @param optag The operators tree tag.
580 * @param lhs The operator's left argument.
581 * @param rhs The operator's right argument.
582 */
583 JCBinary makeBinary(JCTree.Tag optag, JCExpression lhs, JCExpression rhs) {
584 JCBinary tree = make.Binary(optag, lhs, rhs);
585 tree.operator = operators.resolveBinary(tree, optag, lhs.type, rhs.type);
586 tree.type = tree.operator.type.getReturnType();
587 return tree;
588 }
589
590 /** Make an attributed assignop expression.
591 * @param optag The operators tree tag.
592 * @param lhs The operator's left argument.
593 * @param rhs The operator's right argument.
594 */
595 JCAssignOp makeAssignop(JCTree.Tag optag, JCTree lhs, JCTree rhs) {
596 JCAssignOp tree = make.Assignop(optag, lhs, rhs);
597 tree.operator = operators.resolveBinary(tree, tree.getTag().noAssignOp(), lhs.type, rhs.type);
598 tree.type = lhs.type;
599 return tree;
600 }
601
602 /** Convert tree into string object, unless it has already a
603 * reference type..
604 */
605 JCExpression makeString(JCExpression tree) {
606 if (!tree.type.isPrimitiveOrVoid()) {
607 return tree;
608 } else {
609 Symbol valueOfSym = lookupMethod(tree.pos(),
610 names.valueOf,
611 syms.stringType,
612 List.of(tree.type));
613 return make.App(make.QualIdent(valueOfSym), List.of(tree));
614 }
615 }
616
617 /** Create an empty anonymous class definition and enter and complete
618 * its symbol. Return the class definition's symbol.
619 * and create
620 * @param flags The class symbol's flags
621 * @param owner The class symbol's owner
622 */
623 JCClassDecl makeEmptyClass(long flags, ClassSymbol owner) {
624 return makeEmptyClass(flags, owner, null, true);
625 }
626
627 JCClassDecl makeEmptyClass(long flags, ClassSymbol owner, Name flatname,
628 boolean addToDefs) {
629 // Create class symbol.
630 ClassSymbol c = syms.defineClass(names.empty, owner);
631 if (flatname != null) {
632 c.flatname = flatname;
633 } else {
634 c.flatname = chk.localClassName(c);
635 }
636 c.sourcefile = owner.sourcefile;
637 c.completer = Completer.NULL_COMPLETER;
638 c.members_field = WriteableScope.create(c);
639 c.flags_field = flags;
640 ClassType ctype = (ClassType) c.type;
641 ctype.supertype_field = syms.objectType;
642 ctype.interfaces_field = List.nil();
643
644 JCClassDecl odef = classDef(owner);
645
646 // Enter class symbol in owner scope and compiled table.
647 enterSynthetic(odef.pos(), c, owner.members());
648 chk.putCompiled(c);
649
650 // Create class definition tree.
651 JCClassDecl cdef = make.ClassDef(
652 make.Modifiers(flags), names.empty,
653 List.nil(),
654 null, List.nil(), List.nil());
655 cdef.sym = c;
656 cdef.type = c.type;
657
658 // Append class definition tree to owner's definitions.
659 if (addToDefs) odef.defs = odef.defs.prepend(cdef);
660 return cdef;
661 }
662
663 /* ************************************************************************
664 * Symbol manipulation utilities
665 *************************************************************************/
666
667 /** Enter a synthetic symbol in a given scope, but complain if there was already one there.
668 * @param pos Position for error reporting.
669 * @param sym The symbol.
670 * @param s The scope.
671 */
672 private void enterSynthetic(DiagnosticPosition pos, Symbol sym, WriteableScope s) {
673 s.enter(sym);
674 }
675
676 /** Create a fresh synthetic name within a given scope - the unique name is
677 * obtained by appending '$' chars at the end of the name until no match
678 * is found.
679 *
680 * @param name base name
681 * @param s scope in which the name has to be unique
682 * @return fresh synthetic name
683 */
684 private Name makeSyntheticName(Name name, Scope s) {
685 do {
686 name = name.append(
687 target.syntheticNameChar(),
688 names.empty);
689 } while (lookupSynthetic(name, s) != null);
690 return name;
691 }
692
693 /** Check whether synthetic symbols generated during lowering conflict
694 * with user-defined symbols.
695 *
696 * @param translatedTrees lowered class trees
697 */
698 void checkConflicts(List<JCTree> translatedTrees) {
699 for (JCTree t : translatedTrees) {
700 t.accept(conflictsChecker);
701 }
702 }
703
704 JCTree.Visitor conflictsChecker = new TreeScanner() {
705
706 TypeSymbol currentClass;
707
708 @Override
709 public void visitMethodDef(JCMethodDecl that) {
710 checkConflicts(that.pos(), that.sym, currentClass);
711 super.visitMethodDef(that);
712 }
713
714 @Override
715 public void visitVarDef(JCVariableDecl that) {
716 if (that.sym.owner.kind == TYP) {
717 checkConflicts(that.pos(), that.sym, currentClass);
718 }
719 super.visitVarDef(that);
720 }
721
722 @Override
723 public void visitClassDef(JCClassDecl that) {
724 TypeSymbol prevCurrentClass = currentClass;
725 currentClass = that.sym;
726 try {
727 super.visitClassDef(that);
728 }
729 finally {
730 currentClass = prevCurrentClass;
731 }
732 }
733
734 void checkConflicts(DiagnosticPosition pos, Symbol sym, TypeSymbol c) {
735 for (Type ct = c.type; ct != Type.noType ; ct = types.supertype(ct)) {
736 for (Symbol sym2 : ct.tsym.members().getSymbolsByName(sym.name, NON_RECURSIVE)) {
737 // VM allows methods and variables with differing types
738 if (sym.kind == sym2.kind &&
739 types.isSameType(types.erasure(sym.type), types.erasure(sym2.type)) &&
740 sym != sym2 &&
741 (sym.flags() & Flags.SYNTHETIC) != (sym2.flags() & Flags.SYNTHETIC) &&
742 (sym.flags() & BRIDGE) == 0 && (sym2.flags() & BRIDGE) == 0) {
743 syntheticError(pos, (sym2.flags() & SYNTHETIC) == 0 ? sym2 : sym);
744 return;
745 }
746 }
747 }
748 }
749
750 /** Report a conflict between a user symbol and a synthetic symbol.
751 */
752 private void syntheticError(DiagnosticPosition pos, Symbol sym) {
753 if (!sym.type.isErroneous()) {
754 log.error(pos, Errors.CannotGenerateClass(sym.location(), Fragments.SyntheticNameConflict(sym, sym.location())));
755 }
756 }
757 };
758
759 /** Look up a synthetic name in a given scope.
760 * @param s The scope.
761 * @param name The name.
762 */
763 private Symbol lookupSynthetic(Name name, Scope s) {
764 Symbol sym = s.findFirst(name);
765 return (sym==null || (sym.flags()&SYNTHETIC)==0) ? null : sym;
766 }
767
768 /** Look up a method in a given scope.
769 */
770 private MethodSymbol lookupMethod(DiagnosticPosition pos, Name name, Type qual, List<Type> args) {
771 return rs.resolveInternalMethod(pos, attrEnv, qual, name, args, List.nil());
772 }
773
774 /** Anon inner classes are used as access constructor tags.
775 * accessConstructorTag will use an existing anon class if one is available,
776 * and synthesize a class (with makeEmptyClass) if one is not available.
777 * However, there is a small possibility that an existing class will not
778 * be generated as expected if it is inside a conditional with a constant
779 * expression. If that is found to be the case, create an empty class tree here.
780 */
781 private void checkAccessConstructorTags() {
782 for (List<ClassSymbol> l = accessConstrTags; l.nonEmpty(); l = l.tail) {
783 ClassSymbol c = l.head;
784 if (isTranslatedClassAvailable(c))
785 continue;
786 // Create class definition tree.
787 // IDENTITY_TYPE will be interpreted as ACC_SUPER for older class files so we are fine
788 JCClassDecl cdec = makeEmptyClass(STATIC | SYNTHETIC | IDENTITY_TYPE,
789 c.outermostClass(), c.flatname, false);
790 swapAccessConstructorTag(c, cdec.sym);
791 translated.append(cdec);
792 }
793 }
794 // where
795 private boolean isTranslatedClassAvailable(ClassSymbol c) {
796 for (JCTree tree: translated) {
797 if (tree.hasTag(CLASSDEF)
798 && ((JCClassDecl) tree).sym == c) {
799 return true;
800 }
801 }
802 return false;
803 }
804
805 void swapAccessConstructorTag(ClassSymbol oldCTag, ClassSymbol newCTag) {
806 for (MethodSymbol methodSymbol : accessConstrs.values()) {
807 Assert.check(methodSymbol.type.hasTag(METHOD));
808 MethodType oldMethodType =
809 (MethodType)methodSymbol.type;
810 if (oldMethodType.argtypes.head.tsym == oldCTag)
811 methodSymbol.type =
812 types.createMethodTypeWithParameters(oldMethodType,
813 oldMethodType.getParameterTypes().tail
814 .prepend(newCTag.erasure(types)));
815 }
816 }
817
818 /* ************************************************************************
819 * Access methods
820 *************************************************************************/
821
822 /** A mapping from symbols to their access numbers.
823 */
824 private Map<Symbol,Integer> accessNums;
825
826 /** A mapping from symbols to an array of access symbols, indexed by
827 * access code.
828 */
829 private Map<Symbol,MethodSymbol[]> accessSyms;
830
831 /** A mapping from (constructor) symbols to access constructor symbols.
832 */
833 private Map<Symbol,MethodSymbol> accessConstrs;
834
835 /** A list of all class symbols used for access constructor tags.
836 */
837 private List<ClassSymbol> accessConstrTags;
838
839 /** A queue for all accessed symbols.
840 */
841 private ListBuffer<Symbol> accessed;
842
843 /** return access code for identifier,
844 * @param tree The tree representing the identifier use.
845 * @param enclOp The closest enclosing operation node of tree,
846 * null if tree is not a subtree of an operation.
847 */
848 private static int accessCode(JCTree tree, JCTree enclOp) {
849 if (enclOp == null)
850 return AccessCode.DEREF.code;
851 else if (enclOp.hasTag(ASSIGN) &&
852 tree == TreeInfo.skipParens(((JCAssign) enclOp).lhs))
853 return AccessCode.ASSIGN.code;
854 else if ((enclOp.getTag().isIncOrDecUnaryOp() || enclOp.getTag().isAssignop()) &&
855 tree == TreeInfo.skipParens(((JCOperatorExpression) enclOp).getOperand(LEFT)))
856 return (((JCOperatorExpression) enclOp).operator).getAccessCode(enclOp.getTag());
857 else
858 return AccessCode.DEREF.code;
859 }
860
861 /** Return binary operator that corresponds to given access code.
862 */
863 private OperatorSymbol binaryAccessOperator(int acode, Tag tag) {
864 return operators.lookupBinaryOp(op -> op.getAccessCode(tag) == acode);
865 }
866
867 /** Return tree tag for assignment operation corresponding
868 * to given binary operator.
869 */
870 private static JCTree.Tag treeTag(OperatorSymbol operator) {
871 switch (operator.opcode) {
872 case ByteCodes.ior: case ByteCodes.lor:
873 return BITOR_ASG;
874 case ByteCodes.ixor: case ByteCodes.lxor:
875 return BITXOR_ASG;
876 case ByteCodes.iand: case ByteCodes.land:
877 return BITAND_ASG;
878 case ByteCodes.ishl: case ByteCodes.lshl:
879 case ByteCodes.ishll: case ByteCodes.lshll:
880 return SL_ASG;
881 case ByteCodes.ishr: case ByteCodes.lshr:
882 case ByteCodes.ishrl: case ByteCodes.lshrl:
883 return SR_ASG;
884 case ByteCodes.iushr: case ByteCodes.lushr:
885 case ByteCodes.iushrl: case ByteCodes.lushrl:
886 return USR_ASG;
887 case ByteCodes.iadd: case ByteCodes.ladd:
888 case ByteCodes.fadd: case ByteCodes.dadd:
889 case ByteCodes.string_add:
890 return PLUS_ASG;
891 case ByteCodes.isub: case ByteCodes.lsub:
892 case ByteCodes.fsub: case ByteCodes.dsub:
893 return MINUS_ASG;
894 case ByteCodes.imul: case ByteCodes.lmul:
895 case ByteCodes.fmul: case ByteCodes.dmul:
896 return MUL_ASG;
897 case ByteCodes.idiv: case ByteCodes.ldiv:
898 case ByteCodes.fdiv: case ByteCodes.ddiv:
899 return DIV_ASG;
900 case ByteCodes.imod: case ByteCodes.lmod:
901 case ByteCodes.fmod: case ByteCodes.dmod:
902 return MOD_ASG;
903 default:
904 throw new AssertionError();
905 }
906 }
907
908 /** The name of the access method with number `anum' and access code `acode'.
909 */
910 Name accessName(int anum, int acode) {
911 return names.fromString(
912 "access" + target.syntheticNameChar() + anum + acode / 10 + acode % 10);
913 }
914
915 /** Return access symbol for a private or protected symbol from an inner class.
916 * @param sym The accessed private symbol.
917 * @param tree The accessing tree.
918 * @param enclOp The closest enclosing operation node of tree,
919 * null if tree is not a subtree of an operation.
920 * @param protAccess Is access to a protected symbol in another
921 * package?
922 * @param refSuper Is access via a (qualified) C.super?
923 */
924 MethodSymbol accessSymbol(Symbol sym, JCTree tree, JCTree enclOp,
925 boolean protAccess, boolean refSuper) {
926 ClassSymbol accOwner = refSuper && protAccess
927 // For access via qualified super (T.super.x), place the
928 // access symbol on T.
929 ? (ClassSymbol)((JCFieldAccess) tree).selected.type.tsym
930 // Otherwise pretend that the owner of an accessed
931 // protected symbol is the enclosing class of the current
932 // class which is a subclass of the symbol's owner.
933 : accessClass(sym, protAccess, tree);
934
935 Symbol vsym = sym;
936 if (sym.owner != accOwner) {
937 vsym = sym.clone(accOwner);
938 actualSymbols.put(vsym, sym);
939 }
940
941 Integer anum // The access number of the access method.
942 = accessNums.get(vsym);
943 if (anum == null) {
944 anum = accessed.length();
945 accessNums.put(vsym, anum);
946 accessSyms.put(vsym, new MethodSymbol[AccessCode.numberOfAccessCodes]);
947 accessed.append(vsym);
948 // System.out.println("accessing " + vsym + " in " + vsym.location());
949 }
950
951 int acode; // The access code of the access method.
952 List<Type> argtypes; // The argument types of the access method.
953 Type restype; // The result type of the access method.
954 List<Type> thrown; // The thrown exceptions of the access method.
955 switch (vsym.kind) {
956 case VAR:
957 acode = accessCode(tree, enclOp);
958 if (acode >= AccessCode.FIRSTASGOP.code) {
959 OperatorSymbol operator = binaryAccessOperator(acode, enclOp.getTag());
960 if (operator.opcode == string_add)
961 argtypes = List.of(syms.objectType);
962 else
963 argtypes = operator.type.getParameterTypes().tail;
964 } else if (acode == AccessCode.ASSIGN.code)
965 argtypes = List.of(vsym.erasure(types));
966 else
967 argtypes = List.nil();
968 restype = vsym.erasure(types);
969 thrown = List.nil();
970 break;
971 case MTH:
972 acode = AccessCode.DEREF.code;
973 argtypes = vsym.erasure(types).getParameterTypes();
974 restype = vsym.erasure(types).getReturnType();
975 thrown = vsym.type.getThrownTypes();
976 break;
977 default:
978 throw new AssertionError();
979 }
980
981 // For references via qualified super, increment acode by one,
982 // making it odd.
983 if (protAccess && refSuper) acode++;
984
985 // Instance access methods get instance as first parameter.
986 // For protected symbols this needs to be the instance as a member
987 // of the type containing the accessed symbol, not the class
988 // containing the access method.
989 if ((vsym.flags() & STATIC) == 0) {
990 argtypes = argtypes.prepend(vsym.owner.erasure(types));
991 }
992 MethodSymbol[] accessors = accessSyms.get(vsym);
993 MethodSymbol accessor = accessors[acode];
994 if (accessor == null) {
995 accessor = new MethodSymbol(
996 STATIC | SYNTHETIC | (accOwner.isInterface() ? PUBLIC : 0),
997 accessName(anum.intValue(), acode),
998 new MethodType(argtypes, restype, thrown, syms.methodClass),
999 accOwner);
1000 enterSynthetic(tree.pos(), accessor, accOwner.members());
1001 accessors[acode] = accessor;
1002 }
1003 return accessor;
1004 }
1005
1006 /** The qualifier to be used for accessing a symbol in an outer class.
1007 * This is either C.sym or C.this.sym, depending on whether or not
1008 * sym is static.
1009 * @param sym The accessed symbol.
1010 */
1011 JCExpression accessBase(DiagnosticPosition pos, Symbol sym) {
1012 return (sym.flags() & STATIC) != 0
1013 ? access(make.at(pos.getStartPosition()).QualIdent(sym.owner))
1014 : makeOwnerThis(pos, sym, true);
1015 }
1016
1017 /** Do we need an access method to reference private symbol?
1018 */
1019 boolean needsPrivateAccess(Symbol sym) {
1020 if (target.hasNestmateAccess()) {
1021 return false;
1022 }
1023 if ((sym.flags() & PRIVATE) == 0 || sym.owner == currentClass) {
1024 return false;
1025 } else if (sym.name == names.init && sym.owner.isDirectlyOrIndirectlyLocal()) {
1026 // private constructor in local class: relax protection
1027 sym.flags_field &= ~PRIVATE;
1028 return false;
1029 } else {
1030 return true;
1031 }
1032 }
1033
1034 /** Do we need an access method to reference symbol in other package?
1035 */
1036 boolean needsProtectedAccess(Symbol sym, JCTree tree) {
1037 if (disableProtectedAccessors) return false;
1038 if ((sym.flags() & PROTECTED) == 0 ||
1039 sym.owner.owner == currentClass.owner || // fast special case
1040 sym.packge() == currentClass.packge())
1041 return false;
1042 if (!currentClass.isSubClass(sym.owner, types))
1043 return true;
1044 if ((sym.flags() & STATIC) != 0 ||
1045 !tree.hasTag(SELECT) ||
1046 TreeInfo.name(((JCFieldAccess) tree).selected) == names._super)
1047 return false;
1048 return !((JCFieldAccess) tree).selected.type.tsym.isSubClass(currentClass, types);
1049 }
1050
1051 /** The class in which an access method for given symbol goes.
1052 * @param sym The access symbol
1053 * @param protAccess Is access to a protected symbol in another
1054 * package?
1055 */
1056 ClassSymbol accessClass(Symbol sym, boolean protAccess, JCTree tree) {
1057 if (protAccess) {
1058 Symbol qualifier = null;
1059 ClassSymbol c = currentClass;
1060 if (tree.hasTag(SELECT) && (sym.flags() & STATIC) == 0) {
1061 qualifier = ((JCFieldAccess) tree).selected.type.tsym;
1062 while (!qualifier.isSubClass(c, types)) {
1063 c = c.owner.enclClass();
1064 }
1065 return c;
1066 } else {
1067 while (!c.isSubClass(sym.owner, types)) {
1068 c = c.owner.enclClass();
1069 }
1070 }
1071 return c;
1072 } else {
1073 // the symbol is private
1074 return sym.owner.enclClass();
1075 }
1076 }
1077
1078 private boolean noClassDefIn(JCTree tree) {
1079 var scanner = new TreeScanner() {
1080 boolean noClassDef = true;
1081 @Override
1082 public void visitClassDef(JCClassDecl tree) {
1083 noClassDef = false;
1084 }
1085 };
1086 scanner.scan(tree);
1087 return scanner.noClassDef;
1088 }
1089
1090 private void addPrunedInfo(JCTree tree) {
1091 List<JCTree> infoList = prunedTree.get(currentClass);
1092 infoList = (infoList == null) ? List.of(tree) : infoList.prepend(tree);
1093 prunedTree.put(currentClass, infoList);
1094 }
1095
1096 /** Ensure that identifier is accessible, return tree accessing the identifier.
1097 * @param sym The accessed symbol.
1098 * @param tree The tree referring to the symbol.
1099 * @param enclOp The closest enclosing operation node of tree,
1100 * null if tree is not a subtree of an operation.
1101 * @param refSuper Is access via a (qualified) C.super?
1102 */
1103 JCExpression access(Symbol sym, JCExpression tree, JCExpression enclOp, boolean refSuper) {
1104 // Access a free variable via its proxy, or its proxy's proxy
1105 while (sym.kind == VAR && sym.owner.kind == MTH &&
1106 sym.owner.enclClass() != currentClass) {
1107 // A constant is replaced by its constant value.
1108 Object cv = ((VarSymbol)sym).getConstValue();
1109 if (cv != null) {
1110 make.at(tree.pos);
1111 return makeLit(sym.type, cv);
1112 }
1113 // Otherwise replace the variable by its proxy.
1114 sym = proxies.get(sym);
1115 Assert.check(sym != null && (sym.flags_field & FINAL) != 0);
1116 tree = make.at(tree.pos).Ident(sym);
1117 }
1118 JCExpression base = (tree.hasTag(SELECT)) ? ((JCFieldAccess) tree).selected : null;
1119 switch (sym.kind) {
1120 case TYP:
1121 if (sym.owner.kind != PCK) {
1122 // Convert type idents to
1123 // <flat name> or <package name> . <flat name>
1124 Name flatname = Convert.shortName(sym.flatName());
1125 while (base != null &&
1126 TreeInfo.symbol(base) != null &&
1127 TreeInfo.symbol(base).kind != PCK) {
1128 base = (base.hasTag(SELECT))
1129 ? ((JCFieldAccess) base).selected
1130 : null;
1131 }
1132 if (tree.hasTag(IDENT)) {
1133 ((JCIdent) tree).name = flatname;
1134 } else if (base == null) {
1135 tree = make.at(tree.pos).Ident(sym);
1136 ((JCIdent) tree).name = flatname;
1137 } else {
1138 ((JCFieldAccess) tree).selected = base;
1139 ((JCFieldAccess) tree).name = flatname;
1140 }
1141 }
1142 break;
1143 case MTH: case VAR:
1144 if (sym.owner.kind == TYP) {
1145
1146 // Access methods are required for
1147 // - private members,
1148 // - protected members in a superclass of an
1149 // enclosing class contained in another package.
1150 // - all non-private members accessed via a qualified super.
1151 boolean protAccess = refSuper && !needsPrivateAccess(sym)
1152 || needsProtectedAccess(sym, tree);
1153 boolean accReq = protAccess || needsPrivateAccess(sym);
1154
1155 // A base has to be supplied for
1156 // - simple identifiers accessing variables in outer classes.
1157 boolean baseReq =
1158 base == null &&
1159 sym.owner != syms.predefClass &&
1160 !sym.isMemberOf(currentClass, types);
1161
1162 if (accReq || baseReq) {
1163 make.at(tree.pos);
1164
1165 // Constants are replaced by their constant value.
1166 if (sym.kind == VAR) {
1167 Object cv = ((VarSymbol)sym).getConstValue();
1168 if (cv != null) {
1169 addPrunedInfo(tree);
1170 return makeLit(sym.type, cv);
1171 }
1172 }
1173
1174 // Private variables and methods are replaced by calls
1175 // to their access methods.
1176 if (accReq) {
1177 List<JCExpression> args = List.nil();
1178 if ((sym.flags() & STATIC) == 0) {
1179 // Instance access methods get instance
1180 // as first parameter.
1181 if (base == null)
1182 base = makeOwnerThis(tree.pos(), sym, true);
1183 args = args.prepend(base);
1184 base = null; // so we don't duplicate code
1185 }
1186 Symbol access = accessSymbol(sym, tree,
1187 enclOp, protAccess,
1188 refSuper);
1189 JCExpression receiver = make.Select(
1190 base != null ? base : make.QualIdent(access.owner),
1191 access);
1192 return make.App(receiver, args);
1193
1194 // Other accesses to members of outer classes get a
1195 // qualifier.
1196 } else if (baseReq) {
1197 return make.at(tree.pos).Select(
1198 accessBase(tree.pos(), sym), sym).setType(tree.type);
1199 }
1200 }
1201 }
1202 }
1203 return tree;
1204 }
1205
1206 /** Ensure that identifier is accessible, return tree accessing the identifier.
1207 * @param tree The identifier tree.
1208 */
1209 JCExpression access(JCExpression tree) {
1210 Symbol sym = TreeInfo.symbol(tree);
1211 return sym == null ? tree : access(sym, tree, null, false);
1212 }
1213
1214 /** Return access constructor for a private constructor,
1215 * or the constructor itself, if no access constructor is needed.
1216 * @param pos The position to report diagnostics, if any.
1217 * @param constr The private constructor.
1218 */
1219 Symbol accessConstructor(DiagnosticPosition pos, Symbol constr) {
1220 if (needsPrivateAccess(constr)) {
1221 ClassSymbol accOwner = constr.owner.enclClass();
1222 MethodSymbol aconstr = accessConstrs.get(constr);
1223 if (aconstr == null) {
1224 List<Type> argtypes = constr.type.getParameterTypes();
1225 if ((accOwner.flags_field & ENUM) != 0)
1226 argtypes = argtypes
1227 .prepend(syms.intType)
1228 .prepend(syms.stringType);
1229 aconstr = new MethodSymbol(
1230 SYNTHETIC,
1231 names.init,
1232 new MethodType(
1233 argtypes.append(
1234 accessConstructorTag().erasure(types)),
1235 constr.type.getReturnType(),
1236 constr.type.getThrownTypes(),
1237 syms.methodClass),
1238 accOwner);
1239 enterSynthetic(pos, aconstr, accOwner.members());
1240 accessConstrs.put(constr, aconstr);
1241 accessed.append(constr);
1242 }
1243 return aconstr;
1244 } else {
1245 return constr;
1246 }
1247 }
1248
1249 /** Return an anonymous class nested in this toplevel class.
1250 */
1251 ClassSymbol accessConstructorTag() {
1252 ClassSymbol topClass = currentClass.outermostClass();
1253 ModuleSymbol topModle = topClass.packge().modle;
1254 for (int i = 1; ; i++) {
1255 Name flatname = names.fromString("" + topClass.getQualifiedName() +
1256 target.syntheticNameChar() +
1257 i);
1258 ClassSymbol ctag = chk.getCompiled(topModle, flatname);
1259 if (ctag == null)
1260 // IDENTITY_TYPE will be interpreted as ACC_SUPER for older class files so we are fine
1261 ctag = makeEmptyClass(STATIC | SYNTHETIC | IDENTITY_TYPE, topClass).sym;
1262 else if (!ctag.isAnonymous())
1263 continue;
1264 // keep a record of all tags, to verify that all are generated as required
1265 accessConstrTags = accessConstrTags.prepend(ctag);
1266 return ctag;
1267 }
1268 }
1269
1270 /** Add all required access methods for a private symbol to enclosing class.
1271 * @param sym The symbol.
1272 */
1273 void makeAccessible(Symbol sym) {
1274 JCClassDecl cdef = classDef(sym.owner.enclClass());
1275 if (cdef == null) Assert.error("class def not found: " + sym + " in " + sym.owner);
1276 if (sym.name == names.init) {
1277 cdef.defs = cdef.defs.prepend(
1278 accessConstructorDef(cdef.pos, sym, accessConstrs.get(sym)));
1279 } else {
1280 MethodSymbol[] accessors = accessSyms.get(sym);
1281 for (int i = 0; i < AccessCode.numberOfAccessCodes; i++) {
1282 if (accessors[i] != null)
1283 cdef.defs = cdef.defs.prepend(
1284 accessDef(cdef.pos, sym, accessors[i], i));
1285 }
1286 }
1287 }
1288
1289 /** Construct definition of an access method.
1290 * @param pos The source code position of the definition.
1291 * @param vsym The private or protected symbol.
1292 * @param accessor The access method for the symbol.
1293 * @param acode The access code.
1294 */
1295 JCTree accessDef(int pos, Symbol vsym, MethodSymbol accessor, int acode) {
1296 // System.err.println("access " + vsym + " with " + accessor);//DEBUG
1297 currentClass = vsym.owner.enclClass();
1298 make.at(pos);
1299 JCMethodDecl md = make.MethodDef(accessor, null);
1300
1301 // Find actual symbol
1302 Symbol sym = actualSymbols.get(vsym);
1303 if (sym == null) sym = vsym;
1304
1305 JCExpression ref; // The tree referencing the private symbol.
1306 List<JCExpression> args; // Any additional arguments to be passed along.
1307 if ((sym.flags() & STATIC) != 0) {
1308 ref = make.Ident(sym);
1309 args = make.Idents(md.params);
1310 } else {
1311 JCExpression site = make.Ident(md.params.head);
1312 if (acode % 2 != 0) {
1313 //odd access codes represent qualified super accesses - need to
1314 //emit reference to the direct superclass, even if the referred
1315 //member is from an indirect superclass (JLS 13.1)
1316 site.setType(types.erasure(types.supertype(vsym.owner.enclClass().type)));
1317 }
1318 ref = make.Select(site, sym);
1319 args = make.Idents(md.params.tail);
1320 }
1321 JCStatement stat; // The statement accessing the private symbol.
1322 if (sym.kind == VAR) {
1323 // Normalize out all odd access codes by taking floor modulo 2:
1324 int acode1 = acode - (acode & 1);
1325
1326 JCExpression expr; // The access method's return value.
1327 AccessCode aCode = AccessCode.getFromCode(acode1);
1328 switch (aCode) {
1329 case DEREF:
1330 expr = ref;
1331 break;
1332 case ASSIGN:
1333 expr = make.Assign(ref, args.head);
1334 break;
1335 case PREINC: case POSTINC: case PREDEC: case POSTDEC:
1336 expr = makeUnary(aCode.tag, ref);
1337 break;
1338 default:
1339 expr = make.Assignop(
1340 treeTag(binaryAccessOperator(acode1, JCTree.Tag.NO_TAG)), ref, args.head);
1341 ((JCAssignOp) expr).operator = binaryAccessOperator(acode1, JCTree.Tag.NO_TAG);
1342 }
1343 stat = make.Return(expr.setType(sym.type));
1344 } else {
1345 stat = make.Call(make.App(ref, args));
1346 }
1347 md.body = make.Block(0, List.of(stat));
1348
1349 // Make sure all parameters, result types and thrown exceptions
1350 // are accessible.
1351 for (List<JCVariableDecl> l = md.params; l.nonEmpty(); l = l.tail)
1352 l.head.vartype = access(l.head.vartype);
1353 md.restype = access(md.restype);
1354 for (List<JCExpression> l = md.thrown; l.nonEmpty(); l = l.tail)
1355 l.head = access(l.head);
1356
1357 return md;
1358 }
1359
1360 /** Construct definition of an access constructor.
1361 * @param pos The source code position of the definition.
1362 * @param constr The private constructor.
1363 * @param accessor The access method for the constructor.
1364 */
1365 JCTree accessConstructorDef(int pos, Symbol constr, MethodSymbol accessor) {
1366 make.at(pos);
1367 JCMethodDecl md = make.MethodDef(accessor,
1368 accessor.externalType(types),
1369 null);
1370 JCIdent callee = make.Ident(names._this);
1371 callee.sym = constr;
1372 callee.type = constr.type;
1373 md.body =
1374 make.Block(0, List.of(
1375 make.Call(
1376 make.App(
1377 callee,
1378 make.Idents(md.params.reverse().tail.reverse())))));
1379 return md;
1380 }
1381
1382 /* ************************************************************************
1383 * Free variables proxies and this$n
1384 *************************************************************************/
1385
1386 /** A map which allows to retrieve the translated proxy variable for any given symbol of an
1387 * enclosing scope that is accessed (the accessed symbol could be the synthetic 'this$n' symbol).
1388 * Inside a constructor, the map temporarily overrides entries corresponding to proxies and any
1389 * 'this$n' symbols, where they represent the constructor parameters.
1390 */
1391 Map<Symbol, Symbol> proxies;
1392
1393 /** A scope containing all unnamed resource variables/saved
1394 * exception variables for translated TWR blocks
1395 */
1396 WriteableScope twrVars;
1397
1398 /** A stack containing the this$n field of the currently translated
1399 * classes (if needed) in innermost first order.
1400 * Inside a constructor, proxies and any this$n symbol are duplicated
1401 * in an additional innermost scope, where they represent the constructor
1402 * parameters.
1403 */
1404 List<VarSymbol> outerThisStack;
1405
1406 /** The name of a free variable proxy.
1407 */
1408 Name proxyName(Name name, int index) {
1409 Name proxyName = names.fromString("val" + target.syntheticNameChar() + name);
1410 if (index > 0) {
1411 proxyName = proxyName.append(names.fromString("" + target.syntheticNameChar() + index));
1412 }
1413 return proxyName;
1414 }
1415
1416 /** Proxy definitions for all free variables in given list, in reverse order.
1417 * @param pos The source code position of the definition.
1418 * @param freevars The free variables.
1419 * @param owner The class in which the definitions go.
1420 * @param additionalFlags Any additional flags
1421 */
1422 List<JCVariableDecl> freevarDefs(int pos, List<VarSymbol> freevars, Symbol owner) {
1423 return freevarDefs(pos, freevars, owner, LOCAL_CAPTURE_FIELD);
1424 }
1425
1426 List<JCVariableDecl> freevarDefs(int pos, List<VarSymbol> freevars, Symbol owner,
1427 long additionalFlags) {
1428 long flags = FINAL | SYNTHETIC | additionalFlags;
1429 List<JCVariableDecl> defs = List.nil();
1430 Set<Name> proxyNames = new HashSet<>();
1431 for (List<VarSymbol> l = freevars; l.nonEmpty(); l = l.tail) {
1432 VarSymbol v = l.head;
1433 int index = 0;
1434 Name proxyName;
1435 do {
1436 proxyName = proxyName(v.name, index++);
1437 } while (!proxyNames.add(proxyName));
1438 VarSymbol proxy = new VarSymbol(
1439 flags, proxyName, v.erasure(types), owner) {
1440 @Override
1441 public Symbol baseSymbol() {
1442 return v;
1443 }
1444 };
1445 proxies.put(v, proxy);
1446 JCVariableDecl vd = make.at(pos).VarDef(proxy, null);
1447 vd.vartype = access(vd.vartype);
1448 defs = defs.prepend(vd);
1449 }
1450 return defs;
1451 }
1452
1453 /** The name of a this$n field
1454 * @param type The class referenced by the this$n field
1455 */
1456 Name outerThisName(Type type, Symbol owner) {
1457 Type t = type.getEnclosingType();
1458 int nestingLevel = 0;
1459 while (t.hasTag(CLASS)) {
1460 t = t.getEnclosingType();
1461 nestingLevel++;
1462 }
1463 Name result = names.fromString("this" + target.syntheticNameChar() + nestingLevel);
1464 while (owner.kind == TYP && ((ClassSymbol)owner).members().findFirst(result) != null)
1465 result = names.fromString(result.toString() + target.syntheticNameChar());
1466 return result;
1467 }
1468
1469 private VarSymbol makeOuterThisVarSymbol(Symbol owner, long flags) {
1470 Type target = owner.innermostAccessibleEnclosingClass().erasure(types);
1471 // Set NOOUTERTHIS for all synthetic outer instance variables, and unset
1472 // it when the variable is accessed. If the variable is never accessed,
1473 // we skip creating an outer instance field and saving the constructor
1474 // parameter to it.
1475 VarSymbol outerThis =
1476 new VarSymbol(flags | NOOUTERTHIS, outerThisName(target, owner), target, owner);
1477 outerThisStack = outerThisStack.prepend(outerThis);
1478 return outerThis;
1479 }
1480
1481 private JCVariableDecl makeOuterThisVarDecl(int pos, VarSymbol sym) {
1482 JCVariableDecl vd = make.at(pos).VarDef(sym, null);
1483 vd.vartype = access(vd.vartype);
1484 return vd;
1485 }
1486
1487 /** Definition for this$n field.
1488 * @param pos The source code position of the definition.
1489 * @param owner The method in which the definition goes.
1490 */
1491 JCVariableDecl outerThisDef(int pos, MethodSymbol owner) {
1492 ClassSymbol c = owner.enclClass();
1493 boolean isMandated =
1494 // Anonymous constructors
1495 (owner.isConstructor() && owner.isAnonymous()) ||
1496 // Constructors of non-private inner member classes
1497 (owner.isConstructor() && c.isInner() &&
1498 !c.isPrivate() && !c.isStatic());
1499 long flags =
1500 FINAL | (isMandated ? MANDATED : SYNTHETIC) | PARAMETER;
1501 VarSymbol outerThis = makeOuterThisVarSymbol(owner, flags);
1502 owner.extraParams = owner.extraParams.prepend(outerThis);
1503 return makeOuterThisVarDecl(pos, outerThis);
1504 }
1505
1506 /** Definition for this$n field.
1507 * @param pos The source code position of the definition.
1508 * @param owner The class in which the definition goes.
1509 */
1510 JCVariableDecl outerThisDef(int pos, ClassSymbol owner) {
1511 VarSymbol outerThis = makeOuterThisVarSymbol(owner, FINAL | SYNTHETIC | (allowValueClasses && owner.isValueClass() ? STRICT : 0));
1512 return makeOuterThisVarDecl(pos, outerThis);
1513 }
1514
1515 /** Return a list of trees that load the free variables in given list,
1516 * in reverse order.
1517 * @param pos The source code position to be used for the trees.
1518 * @param freevars The list of free variables.
1519 */
1520 List<JCExpression> loadFreevars(DiagnosticPosition pos, List<VarSymbol> freevars) {
1521 List<JCExpression> args = List.nil();
1522 for (List<VarSymbol> l = freevars; l.nonEmpty(); l = l.tail)
1523 args = args.prepend(loadFreevar(pos, l.head));
1524 return args;
1525 }
1526 //where
1527 JCExpression loadFreevar(DiagnosticPosition pos, VarSymbol v) {
1528 return access(v, make.at(pos).Ident(v), null, false);
1529 }
1530
1531 /** Construct a tree simulating the expression {@code C.this}.
1532 * @param pos The source code position to be used for the tree.
1533 * @param c The qualifier class.
1534 */
1535 JCExpression makeThis(DiagnosticPosition pos, TypeSymbol c) {
1536 if (currentClass == c) {
1537 // in this case, `this' works fine
1538 return make.at(pos).This(c.erasure(types));
1539 } else {
1540 // need to go via this$n
1541 return makeOuterThis(pos, c);
1542 }
1543 }
1544
1545 /**
1546 * Optionally replace a try statement with the desugaring of a
1547 * try-with-resources statement. The canonical desugaring of
1548 *
1549 * try ResourceSpecification
1550 * Block
1551 *
1552 * is
1553 *
1554 * {
1555 * final VariableModifiers_minus_final R #resource = Expression;
1556 *
1557 * try ResourceSpecificationtail
1558 * Block
1559 * } body-only-finally {
1560 * if (#resource != null) //nullcheck skipped if Expression is provably non-null
1561 * #resource.close();
1562 * } catch (Throwable #primaryException) {
1563 * if (#resource != null) //nullcheck skipped if Expression is provably non-null
1564 * try {
1565 * #resource.close();
1566 * } catch (Throwable #suppressedException) {
1567 * #primaryException.addSuppressed(#suppressedException);
1568 * }
1569 * throw #primaryException;
1570 * }
1571 * }
1572 *
1573 * @param tree The try statement to inspect.
1574 * @return a desugared try-with-resources tree, or the original
1575 * try block if there are no resources to manage.
1576 */
1577 JCTree makeTwrTry(JCTry tree) {
1578 make_at(tree.pos());
1579 twrVars = twrVars.dup();
1580 JCBlock twrBlock = makeTwrBlock(tree.resources, tree.body, 0);
1581 if (tree.catchers.isEmpty() && tree.finalizer == null)
1582 result = translate(twrBlock);
1583 else
1584 result = translate(make.Try(twrBlock, tree.catchers, tree.finalizer));
1585 twrVars = twrVars.leave();
1586 return result;
1587 }
1588
1589 private JCBlock makeTwrBlock(List<JCTree> resources, JCBlock block, int depth) {
1590 if (resources.isEmpty())
1591 return block;
1592
1593 // Add resource declaration or expression to block statements
1594 ListBuffer<JCStatement> stats = new ListBuffer<>();
1595 JCTree resource = resources.head;
1596 JCExpression resourceUse;
1597 boolean resourceNonNull;
1598 if (resource instanceof JCVariableDecl variableDecl) {
1599 resourceUse = make.Ident(variableDecl.sym).setType(resource.type);
1600 resourceNonNull = variableDecl.init != null && TreeInfo.skipParens(variableDecl.init).hasTag(NEWCLASS);
1601 stats.add(variableDecl);
1602 } else {
1603 Assert.check(resource instanceof JCExpression);
1604 VarSymbol syntheticTwrVar =
1605 new VarSymbol(SYNTHETIC | FINAL,
1606 makeSyntheticName(names.fromString("twrVar" +
1607 depth), twrVars),
1608 (resource.type.hasTag(BOT)) ?
1609 syms.autoCloseableType : resource.type,
1610 currentMethodSym);
1611 twrVars.enter(syntheticTwrVar);
1612 JCVariableDecl syntheticTwrVarDecl =
1613 make.VarDef(syntheticTwrVar, (JCExpression)resource);
1614 resourceUse = (JCExpression)make.Ident(syntheticTwrVar);
1615 resourceNonNull = false;
1616 stats.add(syntheticTwrVarDecl);
1617 }
1618
1619 //create (semi-) finally block that will be copied into the main try body:
1620 int oldPos = make.pos;
1621 make.at(TreeInfo.endPos(block));
1622
1623 // if (#resource != null) { #resource.close(); }
1624 JCStatement bodyCloseStatement = makeResourceCloseInvocation(resourceUse);
1625
1626 if (!resourceNonNull) {
1627 bodyCloseStatement = make.If(makeNonNullCheck(resourceUse),
1628 bodyCloseStatement,
1629 null);
1630 }
1631
1632 JCBlock finallyClause = make.Block(BODY_ONLY_FINALIZE, List.of(bodyCloseStatement));
1633 make.at(oldPos);
1634
1635 // Create catch clause that saves exception, closes the resource and then rethrows the exception:
1636 VarSymbol primaryException =
1637 new VarSymbol(FINAL|SYNTHETIC,
1638 names.fromString("t" +
1639 target.syntheticNameChar()),
1640 syms.throwableType,
1641 currentMethodSym);
1642 JCVariableDecl primaryExceptionDecl = make.VarDef(primaryException, null);
1643
1644 // close resource:
1645 // try {
1646 // #resource.close();
1647 // } catch (Throwable #suppressedException) {
1648 // #primaryException.addSuppressed(#suppressedException);
1649 // }
1650 VarSymbol suppressedException =
1651 new VarSymbol(SYNTHETIC, make.paramName(2),
1652 syms.throwableType,
1653 currentMethodSym);
1654 JCStatement addSuppressedStatement =
1655 make.Exec(makeCall(make.Ident(primaryException),
1656 names.addSuppressed,
1657 List.of(make.Ident(suppressedException))));
1658 JCBlock closeResourceTryBlock =
1659 make.Block(0L, List.of(makeResourceCloseInvocation(resourceUse)));
1660 JCVariableDecl catchSuppressedDecl = make.VarDef(suppressedException, null);
1661 JCBlock catchSuppressedBlock = make.Block(0L, List.of(addSuppressedStatement));
1662 List<JCCatch> catchSuppressedClauses =
1663 List.of(make.Catch(catchSuppressedDecl, catchSuppressedBlock));
1664 JCTry closeResourceTry = make.Try(closeResourceTryBlock, catchSuppressedClauses, null);
1665 closeResourceTry.finallyCanCompleteNormally = true;
1666
1667 JCStatement exceptionalCloseStatement = closeResourceTry;
1668
1669 if (!resourceNonNull) {
1670 // if (#resource != null) { }
1671 exceptionalCloseStatement = make.If(makeNonNullCheck(resourceUse),
1672 exceptionalCloseStatement,
1673 null);
1674 }
1675
1676 JCStatement exceptionalRethrow = make.Throw(make.Ident(primaryException));
1677 JCBlock exceptionalCloseBlock = make.Block(0L, List.of(exceptionalCloseStatement, exceptionalRethrow));
1678 JCCatch exceptionalCatchClause = make.Catch(primaryExceptionDecl, exceptionalCloseBlock);
1679
1680 //create the main try statement with the close:
1681 JCTry outerTry = make.Try(makeTwrBlock(resources.tail, block, depth + 1),
1682 List.of(exceptionalCatchClause),
1683 finallyClause);
1684
1685 outerTry.finallyCanCompleteNormally = true;
1686 stats.add(outerTry);
1687
1688 JCBlock newBlock = make.Block(0L, stats.toList());
1689 return newBlock;
1690 }
1691
1692 private JCStatement makeResourceCloseInvocation(JCExpression resource) {
1693 // convert to AutoCloseable if needed
1694 if (types.asSuper(resource.type, syms.autoCloseableType.tsym) == null) {
1695 resource = convert(resource, syms.autoCloseableType);
1696 }
1697
1698 // create resource.close() method invocation
1699 JCExpression resourceClose = makeCall(resource,
1700 names.close,
1701 List.nil());
1702 return make.Exec(resourceClose);
1703 }
1704
1705 private JCExpression makeNonNullCheck(JCExpression expression) {
1706 return makeBinary(NE, expression, makeNull());
1707 }
1708
1709 /** Construct a tree that represents the outer instance
1710 * {@code C.this}. Never pick the current `this'.
1711 * @param pos The source code position to be used for the tree.
1712 * @param c The qualifier class.
1713 */
1714 JCExpression makeOuterThis(DiagnosticPosition pos, TypeSymbol c) {
1715 List<VarSymbol> ots = outerThisStack;
1716 if (ots.isEmpty()) {
1717 log.error(pos, Errors.NoEnclInstanceOfTypeInScope(c));
1718 return makeNull();
1719 }
1720 VarSymbol ot = ots.head;
1721 JCExpression tree = access(make.at(pos).Ident(ot));
1722 ot.flags_field &= ~NOOUTERTHIS;
1723 TypeSymbol otc = ot.type.tsym;
1724 while (otc != c) {
1725 do {
1726 ots = ots.tail;
1727 if (ots.isEmpty()) {
1728 log.error(pos, Errors.NoEnclInstanceOfTypeInScope(c));
1729 Assert.error(); // should have been caught in Attr
1730 return tree;
1731 }
1732 ot = ots.head;
1733 } while (ot.owner != otc);
1734 if (otc.owner.kind != PCK && !otc.hasOuterInstance()) {
1735 log.error(pos, Errors.NoEnclInstanceOfTypeInScope(c));
1736 Assert.error(); // should have been caught in Attr
1737 return makeNull();
1738 }
1739 tree = access(make.at(pos).Select(tree, ot));
1740 ot.flags_field &= ~NOOUTERTHIS;
1741 otc = ot.type.tsym;
1742 }
1743 return tree;
1744 }
1745
1746 /** Construct a tree that represents the closest outer instance
1747 * {@code C.this} such that the given symbol is a member of C.
1748 * @param pos The source code position to be used for the tree.
1749 * @param sym The accessed symbol.
1750 * @param preciseMatch should we accept a type that is a subtype of
1751 * sym's owner, even if it doesn't contain sym
1752 * due to hiding, overriding, or non-inheritance
1753 * due to protection?
1754 */
1755 JCExpression makeOwnerThis(DiagnosticPosition pos, Symbol sym, boolean preciseMatch) {
1756 if (preciseMatch ? sym.isMemberOf(currentClass, types)
1757 : currentClass.isSubClass(sym.owner, types)) {
1758 // in this case, `this' works fine
1759 return make.at(pos).This(currentClass.erasure(types));
1760 } else {
1761 // need to go via this$n
1762 return makeOwnerThisN(pos, sym, preciseMatch);
1763 }
1764 }
1765
1766 /**
1767 * Similar to makeOwnerThis but will never pick "this".
1768 */
1769 JCExpression makeOwnerThisN(DiagnosticPosition pos, Symbol sym, boolean preciseMatch) {
1770 Symbol c = sym.owner;
1771 List<VarSymbol> ots = outerThisStack;
1772 if (ots.isEmpty()) {
1773 log.error(pos, Errors.NoEnclInstanceOfTypeInScope(c));
1774 return makeNull();
1775 }
1776 VarSymbol ot = ots.head;
1777 JCExpression tree = access(make.at(pos).Ident(ot));
1778 ot.flags_field &= ~NOOUTERTHIS;
1779 TypeSymbol otc = ot.type.tsym;
1780 while (!(preciseMatch ? sym.isMemberOf(otc, types) : otc.isSubClass(sym.owner, types))) {
1781 do {
1782 ots = ots.tail;
1783 if (ots.isEmpty()) {
1784 log.error(pos, Errors.NoEnclInstanceOfTypeInScope(c));
1785 return tree;
1786 }
1787 ot = ots.head;
1788 } while (ot.owner != otc);
1789 tree = access(make.at(pos).Select(tree, ot));
1790 ot.flags_field &= ~NOOUTERTHIS;
1791 otc = ot.type.tsym;
1792 }
1793 return tree;
1794 }
1795
1796 /** Return tree simulating the assignment {@code this.name = name}, where
1797 * name is the name of a free variable.
1798 */
1799 JCStatement initField(int pos, Symbol rhs, Symbol lhs) {
1800 Assert.check(rhs.owner.kind == MTH);
1801 Assert.check(rhs.owner.owner == lhs.owner);
1802 make.at(pos);
1803 return
1804 make.Exec(
1805 make.Assign(
1806 make.Select(make.This(lhs.owner.erasure(types)), lhs),
1807 make.Ident(rhs)).setType(lhs.erasure(types)));
1808 }
1809
1810 /**
1811 * Return tree simulating null checking outer this and/or assigning. This is
1812 * called when a null check is required (nullCheckOuterThis), or a synthetic
1813 * field is generated (stores).
1814 */
1815 JCStatement initOuterThis(int pos, VarSymbol rhs, boolean stores) {
1816 Assert.check(rhs.owner.kind == MTH);
1817 Assert.check(nullCheckOuterThis || stores); // One of the flags must be true
1818 make.at(pos);
1819 JCExpression expression = make.Ident(rhs);
1820 if (nullCheckOuterThis) {
1821 expression = attr.makeNullCheck(expression);
1822 }
1823 if (stores) {
1824 VarSymbol lhs = outerThisStack.head;
1825 Assert.check(rhs.owner.owner == lhs.owner);
1826 expression = make.Assign(
1827 make.Select(make.This(lhs.owner.erasure(types)), lhs),
1828 expression).setType(lhs.erasure(types));
1829 }
1830 return make.Exec(expression);
1831 }
1832
1833 /* ************************************************************************
1834 * Code for .class
1835 *************************************************************************/
1836
1837 /** Return the symbol of a class to contain a cache of
1838 * compiler-generated statics such as class$ and the
1839 * $assertionsDisabled flag. We create an anonymous nested class
1840 * (unless one already exists) and return its symbol. However,
1841 * for backward compatibility in 1.4 and earlier we use the
1842 * top-level class itself.
1843 */
1844 private ClassSymbol outerCacheClass() {
1845 ClassSymbol clazz = outermostClassDef.sym;
1846 Scope s = clazz.members();
1847 for (Symbol sym : s.getSymbols(NON_RECURSIVE))
1848 if (sym.kind == TYP &&
1849 sym.name == names.empty &&
1850 (sym.flags() & INTERFACE) == 0) return (ClassSymbol) sym;
1851 // IDENTITY_TYPE will be interpreted as ACC_SUPER for older class files so we are fine
1852 return makeEmptyClass(STATIC | SYNTHETIC | IDENTITY_TYPE, clazz).sym;
1853 }
1854
1855 /** Create an attributed tree of the form left.name(). */
1856 private JCMethodInvocation makeCall(JCExpression left, Name name, List<JCExpression> args) {
1857 Assert.checkNonNull(left.type);
1858 Symbol funcsym = lookupMethod(make_pos, name, left.type,
1859 TreeInfo.types(args));
1860 return make.App(make.Select(left, funcsym), args);
1861 }
1862
1863 /** The tree simulating a T.class expression.
1864 * @param clazz The tree identifying type T.
1865 */
1866 private JCExpression classOf(JCTree clazz) {
1867 return classOfType(clazz.type, clazz.pos());
1868 }
1869
1870 private JCExpression classOfType(Type type, DiagnosticPosition pos) {
1871 switch (type.getTag()) {
1872 case BYTE: case SHORT: case CHAR: case INT: case LONG: case FLOAT:
1873 case DOUBLE: case BOOLEAN: case VOID:
1874 // replace with <BoxedClass>.TYPE
1875 ClassSymbol c = types.boxedClass(type);
1876 Symbol typeSym =
1877 rs.accessBase(
1878 rs.findIdentInType(pos, attrEnv, c.type, names.TYPE, KindSelector.VAR),
1879 pos, c.type, names.TYPE, true);
1880 if (typeSym.kind == VAR)
1881 ((VarSymbol)typeSym).getConstValue(); // ensure initializer is evaluated
1882 return make.QualIdent(typeSym);
1883 case CLASS: case ARRAY:
1884 VarSymbol sym = new VarSymbol(
1885 STATIC | PUBLIC | FINAL, names._class,
1886 syms.classType, type.tsym);
1887 return make_at(pos).Select(make.Type(type), sym);
1888 default:
1889 throw new AssertionError();
1890 }
1891 }
1892
1893 /* ************************************************************************
1894 * Code for enabling/disabling assertions.
1895 *************************************************************************/
1896
1897 private ClassSymbol assertionsDisabledClassCache;
1898
1899 /**Used to create an auxiliary class to hold $assertionsDisabled for interfaces.
1900 */
1901 private ClassSymbol assertionsDisabledClass() {
1902 if (assertionsDisabledClassCache != null) return assertionsDisabledClassCache;
1903
1904 // IDENTITY_TYPE will be interpreted as ACC_SUPER for older class files so we are fine
1905 assertionsDisabledClassCache = makeEmptyClass(STATIC | SYNTHETIC | IDENTITY_TYPE, outermostClassDef.sym).sym;
1906
1907 return assertionsDisabledClassCache;
1908 }
1909
1910 // This code is not particularly robust if the user has
1911 // previously declared a member named '$assertionsDisabled'.
1912 // The same faulty idiom also appears in the translation of
1913 // class literals above. We should report an error if a
1914 // previous declaration is not synthetic.
1915
1916 private JCExpression assertFlagTest(DiagnosticPosition pos) {
1917 // Outermost class may be either true class or an interface.
1918 ClassSymbol outermostClass = outermostClassDef.sym;
1919
1920 //only classes can hold a non-public field, look for a usable one:
1921 ClassSymbol container = !currentClass.isInterface() ? currentClass :
1922 assertionsDisabledClass();
1923
1924 VarSymbol assertDisabledSym =
1925 (VarSymbol)lookupSynthetic(dollarAssertionsDisabled,
1926 container.members());
1927 if (assertDisabledSym == null) {
1928 assertDisabledSym =
1929 new VarSymbol(STATIC | FINAL | SYNTHETIC,
1930 dollarAssertionsDisabled,
1931 syms.booleanType,
1932 container);
1933 enterSynthetic(pos, assertDisabledSym, container.members());
1934 Symbol desiredAssertionStatusSym = lookupMethod(pos,
1935 names.desiredAssertionStatus,
1936 types.erasure(syms.classType),
1937 List.nil());
1938 JCClassDecl containerDef = classDef(container);
1939 make_at(containerDef.pos());
1940 JCExpression notStatus = makeUnary(NOT, make.App(make.Select(
1941 classOfType(types.erasure(outermostClass.type),
1942 containerDef.pos()),
1943 desiredAssertionStatusSym)));
1944 JCVariableDecl assertDisabledDef = make.VarDef(assertDisabledSym,
1945 notStatus);
1946 containerDef.defs = containerDef.defs.prepend(assertDisabledDef);
1947
1948 if (currentClass.isInterface()) {
1949 //need to load the assertions enabled/disabled state while
1950 //initializing the interface:
1951 JCClassDecl currentClassDef = classDef(currentClass);
1952 make_at(currentClassDef.pos());
1953 JCStatement dummy = make.If(make.QualIdent(assertDisabledSym), make.Skip(), null);
1954 JCBlock clinit = make.Block(STATIC, List.of(dummy));
1955 currentClassDef.defs = currentClassDef.defs.prepend(clinit);
1956 }
1957 }
1958 make_at(pos);
1959 return makeUnary(NOT, make.Ident(assertDisabledSym));
1960 }
1961
1962
1963 /* ************************************************************************
1964 * Building blocks for let expressions
1965 *************************************************************************/
1966
1967 interface TreeBuilder {
1968 JCExpression build(JCExpression arg);
1969 }
1970
1971 /** Construct an expression using the builder, with the given rval
1972 * expression as an argument to the builder. However, the rval
1973 * expression must be computed only once, even if used multiple
1974 * times in the result of the builder. We do that by
1975 * constructing a "let" expression that saves the rvalue into a
1976 * temporary variable and then uses the temporary variable in
1977 * place of the expression built by the builder. The complete
1978 * resulting expression is of the form
1979 * <pre>
1980 * (let <b>TYPE</b> <b>TEMP</b> = <b>RVAL</b>;
1981 * in (<b>BUILDER</b>(<b>TEMP</b>)))
1982 * </pre>
1983 * where <code><b>TEMP</b></code> is a newly declared variable
1984 * in the let expression.
1985 */
1986 JCExpression abstractRval(JCExpression rval, Type type, TreeBuilder builder) {
1987 rval = TreeInfo.skipParens(rval);
1988 switch (rval.getTag()) {
1989 case LITERAL:
1990 return builder.build(rval);
1991 case IDENT:
1992 JCIdent id = (JCIdent) rval;
1993 if ((id.sym.flags() & FINAL) != 0 && id.sym.owner.kind == MTH)
1994 return builder.build(rval);
1995 }
1996 Name name = TreeInfo.name(rval);
1997 if (name == names._super || name == names._this)
1998 return builder.build(rval);
1999 VarSymbol var =
2000 new VarSymbol(FINAL|SYNTHETIC,
2001 names.fromString(
2002 target.syntheticNameChar()
2003 + "" + rval.hashCode()),
2004 type,
2005 currentMethodSym);
2006 rval = convert(rval,type);
2007 JCVariableDecl def = make.VarDef(var, rval); // XXX cast
2008 JCExpression built = builder.build(make.Ident(var));
2009 JCExpression res = make.LetExpr(def, built);
2010 res.type = built.type;
2011 return res;
2012 }
2013
2014 // same as above, with the type of the temporary variable computed
2015 JCExpression abstractRval(JCExpression rval, TreeBuilder builder) {
2016 return abstractRval(rval, rval.type, builder);
2017 }
2018
2019 // same as above, but for an expression that may be used as either
2020 // an rvalue or an lvalue. This requires special handling for
2021 // Select expressions, where we place the left-hand-side of the
2022 // select in a temporary, and for Indexed expressions, where we
2023 // place both the indexed expression and the index value in temps.
2024 JCExpression abstractLval(JCExpression lval, final TreeBuilder builder) {
2025 lval = TreeInfo.skipParens(lval);
2026 switch (lval.getTag()) {
2027 case IDENT:
2028 return builder.build(lval);
2029 case SELECT: {
2030 final JCFieldAccess s = (JCFieldAccess)lval;
2031 Symbol lid = TreeInfo.symbol(s.selected);
2032 if (lid != null && lid.kind == TYP) return builder.build(lval);
2033 return abstractRval(s.selected, selected -> builder.build(make.Select(selected, s.sym)));
2034 }
2035 case INDEXED: {
2036 final JCArrayAccess i = (JCArrayAccess)lval;
2037 return abstractRval(i.indexed, indexed -> abstractRval(i.index, syms.intType, index -> {
2038 JCExpression newLval = make.Indexed(indexed, index);
2039 newLval.setType(i.type);
2040 return builder.build(newLval);
2041 }));
2042 }
2043 case TYPECAST: {
2044 return abstractLval(((JCTypeCast)lval).expr, builder);
2045 }
2046 }
2047 throw new AssertionError(lval);
2048 }
2049
2050 // evaluate and discard the first expression, then evaluate the second.
2051 JCExpression makeComma(final JCExpression expr1, final JCExpression expr2) {
2052 JCExpression res = make.LetExpr(List.of(make.Exec(expr1)), expr2);
2053 res.type = expr2.type;
2054 return res;
2055 }
2056
2057 /* ************************************************************************
2058 * Translation methods
2059 *************************************************************************/
2060
2061 /** Visitor argument: enclosing operator node.
2062 */
2063 private JCExpression enclOp;
2064
2065 /** Visitor method: Translate a single node.
2066 * Attach the source position from the old tree to its replacement tree.
2067 */
2068 @Override
2069 public <T extends JCTree> T translate(T tree) {
2070 if (tree == null) {
2071 return null;
2072 } else {
2073 make_at(tree.pos());
2074 T result = super.translate(tree);
2075 if (endPosTable != null && result != tree) {
2076 endPosTable.replaceTree(tree, result);
2077 }
2078 return result;
2079 }
2080 }
2081
2082 /** Visitor method: Translate a single node, boxing or unboxing if needed.
2083 */
2084 public <T extends JCExpression> T translate(T tree, Type type) {
2085 return (tree == null) ? null : boxIfNeeded(translate(tree), type);
2086 }
2087
2088 /** Visitor method: Translate tree.
2089 */
2090 public <T extends JCTree> T translate(T tree, JCExpression enclOp) {
2091 JCExpression prevEnclOp = this.enclOp;
2092 this.enclOp = enclOp;
2093 T res = translate(tree);
2094 this.enclOp = prevEnclOp;
2095 return res;
2096 }
2097
2098 /** Visitor method: Translate list of trees.
2099 */
2100 public <T extends JCExpression> List<T> translate(List<T> trees, Type type) {
2101 if (trees == null) return null;
2102 for (List<T> l = trees; l.nonEmpty(); l = l.tail)
2103 l.head = translate(l.head, type);
2104 return trees;
2105 }
2106
2107 public void visitPackageDef(JCPackageDecl tree) {
2108 if (!needPackageInfoClass(tree))
2109 return;
2110
2111 long flags = Flags.ABSTRACT | Flags.INTERFACE;
2112 // package-info is marked SYNTHETIC in JDK 1.6 and later releases
2113 flags = flags | Flags.SYNTHETIC;
2114 ClassSymbol c = tree.packge.package_info;
2115 c.setAttributes(tree.packge);
2116 c.flags_field |= flags;
2117 ClassType ctype = (ClassType) c.type;
2118 ctype.supertype_field = syms.objectType;
2119 ctype.interfaces_field = List.nil();
2120 createInfoClass(tree.annotations, c);
2121 }
2122 // where
2123 private boolean needPackageInfoClass(JCPackageDecl pd) {
2124 switch (pkginfoOpt) {
2125 case ALWAYS:
2126 return true;
2127 case LEGACY:
2128 return pd.getAnnotations().nonEmpty();
2129 case NONEMPTY:
2130 for (Attribute.Compound a :
2131 pd.packge.getDeclarationAttributes()) {
2132 Attribute.RetentionPolicy p = types.getRetention(a);
2133 if (p != Attribute.RetentionPolicy.SOURCE)
2134 return true;
2135 }
2136 return false;
2137 }
2138 throw new AssertionError();
2139 }
2140
2141 public void visitModuleDef(JCModuleDecl tree) {
2142 ModuleSymbol msym = tree.sym;
2143 ClassSymbol c = msym.module_info;
2144 c.setAttributes(msym);
2145 c.flags_field |= Flags.MODULE;
2146 createInfoClass(List.nil(), tree.sym.module_info);
2147 }
2148
2149 private void createInfoClass(List<JCAnnotation> annots, ClassSymbol c) {
2150 long flags = Flags.ABSTRACT | Flags.INTERFACE;
2151 JCClassDecl infoClass =
2152 make.ClassDef(make.Modifiers(flags, annots),
2153 c.name, List.nil(),
2154 null, List.nil(), List.nil());
2155 infoClass.sym = c;
2156 translated.append(infoClass);
2157 }
2158
2159 public void visitClassDef(JCClassDecl tree) {
2160 Env<AttrContext> prevEnv = attrEnv;
2161 ClassSymbol currentClassPrev = currentClass;
2162 MethodSymbol currentMethodSymPrev = currentMethodSym;
2163
2164 currentClass = tree.sym;
2165 currentMethodSym = null;
2166 attrEnv = typeEnvs.remove(currentClass);
2167 if (attrEnv == null)
2168 attrEnv = prevEnv;
2169
2170 classdefs.put(currentClass, tree);
2171
2172 Map<Symbol, Symbol> prevProxies = proxies;
2173 proxies = new HashMap<>(proxies);
2174 List<VarSymbol> prevOuterThisStack = outerThisStack;
2175
2176 // If this is an enum definition
2177 if ((tree.mods.flags & ENUM) != 0 &&
2178 (types.supertype(currentClass.type).tsym.flags() & ENUM) == 0)
2179 visitEnumDef(tree);
2180
2181 if ((tree.mods.flags & RECORD) != 0) {
2182 visitRecordDef(tree);
2183 }
2184
2185 // If this is a nested class, define a this$n field for
2186 // it and add to proxies.
2187 JCVariableDecl otdef = null;
2188 if (currentClass.hasOuterInstance())
2189 otdef = outerThisDef(tree.pos, currentClass);
2190
2191 // If this is a local class, define proxies for all its free variables.
2192 List<JCVariableDecl> fvdefs = freevarDefs(
2193 tree.pos, freevars(currentClass), currentClass, allowValueClasses && currentClass.isValueClass() ? STRICT : LOCAL_CAPTURE_FIELD);
2194
2195 // Recursively translate superclass, interfaces.
2196 tree.extending = translate(tree.extending);
2197 tree.implementing = translate(tree.implementing);
2198
2199 if (currentClass.isDirectlyOrIndirectlyLocal()) {
2200 ClassSymbol encl = currentClass.owner.enclClass();
2201 if (encl.trans_local == null) {
2202 encl.trans_local = List.nil();
2203 }
2204 encl.trans_local = encl.trans_local.prepend(currentClass);
2205 }
2206
2207 // Recursively translate members, taking into account that new members
2208 // might be created during the translation and prepended to the member
2209 // list `tree.defs'.
2210 List<JCTree> seen = List.nil();
2211 while (tree.defs != seen) {
2212 List<JCTree> unseen = tree.defs;
2213 for (List<JCTree> l = unseen; l.nonEmpty() && l != seen; l = l.tail) {
2214 JCTree outermostMemberDefPrev = outermostMemberDef;
2215 if (outermostMemberDefPrev == null) outermostMemberDef = l.head;
2216 l.head = translate(l.head);
2217 outermostMemberDef = outermostMemberDefPrev;
2218 }
2219 seen = unseen;
2220 }
2221
2222 // Convert a protected modifier to public, mask static modifier.
2223 if ((tree.mods.flags & PROTECTED) != 0) tree.mods.flags |= PUBLIC;
2224 tree.mods.flags &= ClassFlags;
2225
2226 // Convert name to flat representation, replacing '.' by '$'.
2227 tree.name = Convert.shortName(currentClass.flatName());
2228
2229 // Add free variables proxy definitions to class.
2230
2231 for (List<JCVariableDecl> l = fvdefs; l.nonEmpty(); l = l.tail) {
2232 tree.defs = tree.defs.prepend(l.head);
2233 enterSynthetic(tree.pos(), l.head.sym, currentClass.members());
2234 }
2235 // If this$n was accessed, add the field definition and prepend
2236 // initializer code to any super() invocation to initialize it
2237 // otherwise prepend enclosing instance null check code if required
2238 emitOuter:
2239 if (currentClass.hasOuterInstance()) {
2240 boolean storesThis = shouldEmitOuterThis(currentClass);
2241 if (storesThis) {
2242 tree.defs = tree.defs.prepend(otdef);
2243 enterSynthetic(tree.pos(), otdef.sym, currentClass.members());
2244 } else if (!nullCheckOuterThis) {
2245 break emitOuter;
2246 }
2247
2248 for (JCTree def : tree.defs) {
2249 if (TreeInfo.isConstructor(def)) {
2250 JCMethodDecl mdef = (JCMethodDecl)def;
2251 if (TreeInfo.hasConstructorCall(mdef, names._super)) {
2252 List<JCStatement> initializer = List.of(initOuterThis(mdef.body.pos, mdef.params.head.sym, storesThis)) ;
2253 TreeInfo.mapSuperCalls(mdef.body, supercall -> make.Block(0, initializer.append(supercall)));
2254 }
2255 }
2256 }
2257 }
2258
2259 proxies = prevProxies;
2260 outerThisStack = prevOuterThisStack;
2261
2262 // Append translated tree to `translated' queue.
2263 translated.append(tree);
2264
2265 attrEnv = prevEnv;
2266 currentClass = currentClassPrev;
2267 currentMethodSym = currentMethodSymPrev;
2268
2269 // Return empty block {} as a placeholder for an inner class.
2270 result = make_at(tree.pos()).Block(SYNTHETIC, List.nil());
2271 }
2272
2273 private boolean shouldEmitOuterThis(ClassSymbol sym) {
2274 if (!optimizeOuterThis) {
2275 // Optimization is disabled
2276 return true;
2277 }
2278 if ((outerThisStack.head.flags_field & NOOUTERTHIS) == 0) {
2279 // Enclosing instance field is used
2280 return true;
2281 }
2282 if (rs.isSerializable(sym.type)) {
2283 // Class is serializable
2284 return true;
2285 }
2286 return false;
2287 }
2288
2289 List<JCTree> generateMandatedAccessors(JCClassDecl tree) {
2290 List<JCVariableDecl> fields = TreeInfo.recordFields(tree);
2291 return tree.sym.getRecordComponents().stream()
2292 .filter(rc -> (rc.accessor.flags() & Flags.GENERATED_MEMBER) != 0)
2293 .map(rc -> {
2294 // we need to return the field not the record component
2295 JCVariableDecl field = fields.stream().filter(f -> f.name == rc.name).findAny().get();
2296 make_at(tree.pos());
2297 return make.MethodDef(rc.accessor, make.Block(0,
2298 List.of(make.Return(make.Ident(field)))));
2299 }).collect(List.collector());
2300 }
2301
2302 /** Translate an enum class. */
2303 private void visitEnumDef(JCClassDecl tree) {
2304 make_at(tree.pos());
2305
2306 // add the supertype, if needed
2307 if (tree.extending == null)
2308 tree.extending = make.Type(types.supertype(tree.type));
2309
2310 // classOfType adds a cache field to tree.defs
2311 JCExpression e_class = classOfType(tree.sym.type, tree.pos()).
2312 setType(types.erasure(syms.classType));
2313
2314 // process each enumeration constant, adding implicit constructor parameters
2315 int nextOrdinal = 0;
2316 ListBuffer<JCExpression> values = new ListBuffer<>();
2317 ListBuffer<JCTree> enumDefs = new ListBuffer<>();
2318 ListBuffer<JCTree> otherDefs = new ListBuffer<>();
2319 for (List<JCTree> defs = tree.defs;
2320 defs.nonEmpty();
2321 defs=defs.tail) {
2322 if (defs.head.hasTag(VARDEF) && (((JCVariableDecl) defs.head).mods.flags & ENUM) != 0) {
2323 JCVariableDecl var = (JCVariableDecl)defs.head;
2324 visitEnumConstantDef(var, nextOrdinal++);
2325 values.append(make.QualIdent(var.sym));
2326 enumDefs.append(var);
2327 } else {
2328 otherDefs.append(defs.head);
2329 }
2330 }
2331
2332 // synthetic private static T[] $values() { return new T[] { a, b, c }; }
2333 // synthetic private static final T[] $VALUES = $values();
2334 Name valuesName = syntheticName(tree, "VALUES");
2335 Type arrayType = new ArrayType(types.erasure(tree.type), syms.arrayClass);
2336 VarSymbol valuesVar = new VarSymbol(PRIVATE|FINAL|STATIC|SYNTHETIC,
2337 valuesName,
2338 arrayType,
2339 tree.type.tsym);
2340 JCNewArray newArray = make.NewArray(make.Type(types.erasure(tree.type)),
2341 List.nil(),
2342 values.toList());
2343 newArray.type = arrayType;
2344
2345 MethodSymbol valuesMethod = new MethodSymbol(PRIVATE|STATIC|SYNTHETIC,
2346 syntheticName(tree, "values"),
2347 new MethodType(List.nil(), arrayType, List.nil(), tree.type.tsym),
2348 tree.type.tsym);
2349 enumDefs.append(make.MethodDef(valuesMethod, make.Block(0, List.of(make.Return(newArray)))));
2350 tree.sym.members().enter(valuesMethod);
2351
2352 enumDefs.append(make.VarDef(valuesVar, make.App(make.QualIdent(valuesMethod))));
2353 tree.sym.members().enter(valuesVar);
2354
2355 MethodSymbol valuesSym = lookupMethod(tree.pos(), names.values,
2356 tree.type, List.nil());
2357 List<JCStatement> valuesBody;
2358 if (useClone()) {
2359 // return (T[]) $VALUES.clone();
2360 JCTypeCast valuesResult =
2361 make.TypeCast(valuesSym.type.getReturnType(),
2362 make.App(make.Select(make.Ident(valuesVar),
2363 syms.arrayCloneMethod)));
2364 valuesBody = List.of(make.Return(valuesResult));
2365 } else {
2366 // template: T[] $result = new T[$values.length];
2367 Name resultName = syntheticName(tree, "result");
2368 VarSymbol resultVar = new VarSymbol(FINAL|SYNTHETIC,
2369 resultName,
2370 arrayType,
2371 valuesSym);
2372 JCNewArray resultArray = make.NewArray(make.Type(types.erasure(tree.type)),
2373 List.of(make.Select(make.Ident(valuesVar), syms.lengthVar)),
2374 null);
2375 resultArray.type = arrayType;
2376 JCVariableDecl decl = make.VarDef(resultVar, resultArray);
2377
2378 // template: System.arraycopy($VALUES, 0, $result, 0, $VALUES.length);
2379 if (systemArraycopyMethod == null) {
2380 systemArraycopyMethod =
2381 new MethodSymbol(PUBLIC | STATIC,
2382 names.fromString("arraycopy"),
2383 new MethodType(List.of(syms.objectType,
2384 syms.intType,
2385 syms.objectType,
2386 syms.intType,
2387 syms.intType),
2388 syms.voidType,
2389 List.nil(),
2390 syms.methodClass),
2391 syms.systemType.tsym);
2392 }
2393 JCStatement copy =
2394 make.Exec(make.App(make.Select(make.Ident(syms.systemType.tsym),
2395 systemArraycopyMethod),
2396 List.of(make.Ident(valuesVar), make.Literal(0),
2397 make.Ident(resultVar), make.Literal(0),
2398 make.Select(make.Ident(valuesVar), syms.lengthVar))));
2399
2400 // template: return $result;
2401 JCStatement ret = make.Return(make.Ident(resultVar));
2402 valuesBody = List.of(decl, copy, ret);
2403 }
2404
2405 JCMethodDecl valuesDef =
2406 make.MethodDef(valuesSym, make.Block(0, valuesBody));
2407
2408 enumDefs.append(valuesDef);
2409
2410 if (debugLower)
2411 System.err.println(tree.sym + ".valuesDef = " + valuesDef);
2412
2413 /** The template for the following code is:
2414 *
2415 * public static E valueOf(String name) {
2416 * return (E)Enum.valueOf(E.class, name);
2417 * }
2418 *
2419 * where E is tree.sym
2420 */
2421 MethodSymbol valueOfSym = lookupMethod(tree.pos(),
2422 names.valueOf,
2423 tree.sym.type,
2424 List.of(syms.stringType));
2425 Assert.check((valueOfSym.flags() & STATIC) != 0);
2426 VarSymbol nameArgSym = valueOfSym.params.head;
2427 JCIdent nameVal = make.Ident(nameArgSym);
2428 JCStatement enum_ValueOf =
2429 make.Return(make.TypeCast(tree.sym.type,
2430 makeCall(make.Ident(syms.enumSym),
2431 names.valueOf,
2432 List.of(e_class, nameVal))));
2433 JCMethodDecl valueOf = make.MethodDef(valueOfSym,
2434 make.Block(0, List.of(enum_ValueOf)));
2435 nameVal.sym = valueOf.params.head.sym;
2436 if (debugLower)
2437 System.err.println(tree.sym + ".valueOf = " + valueOf);
2438 enumDefs.append(valueOf);
2439
2440 enumDefs.appendList(otherDefs.toList());
2441 tree.defs = enumDefs.toList();
2442 }
2443 // where
2444 private MethodSymbol systemArraycopyMethod;
2445 private boolean useClone() {
2446 try {
2447 return syms.objectType.tsym.members().findFirst(names.clone) != null;
2448 }
2449 catch (CompletionFailure e) {
2450 return false;
2451 }
2452 }
2453
2454 private Name syntheticName(JCClassDecl tree, String baseName) {
2455 Name valuesName = names.fromString(target.syntheticNameChar() + baseName);
2456 while (tree.sym.members().findFirst(valuesName) != null) // avoid name clash
2457 valuesName = names.fromString(valuesName + "" + target.syntheticNameChar());
2458 return valuesName;
2459 }
2460
2461 /** Translate an enumeration constant and its initializer. */
2462 private void visitEnumConstantDef(JCVariableDecl var, int ordinal) {
2463 JCNewClass varDef = (JCNewClass)var.init;
2464 varDef.args = varDef.args.
2465 prepend(makeLit(syms.intType, ordinal)).
2466 prepend(makeLit(syms.stringType, var.name.toString()));
2467 }
2468
2469 private List<VarSymbol> recordVars(Type t) {
2470 List<VarSymbol> vars = List.nil();
2471 while (!t.hasTag(NONE)) {
2472 if (t.hasTag(CLASS)) {
2473 for (Symbol s : t.tsym.members().getSymbols(s -> s.kind == VAR && (s.flags() & RECORD) != 0)) {
2474 vars = vars.prepend((VarSymbol)s);
2475 }
2476 }
2477 t = types.supertype(t);
2478 }
2479 return vars;
2480 }
2481
2482 /** Translate a record. */
2483 private void visitRecordDef(JCClassDecl tree) {
2484 make_at(tree.pos());
2485 List<VarSymbol> vars = recordVars(tree.type);
2486 MethodHandleSymbol[] getterMethHandles = new MethodHandleSymbol[vars.size()];
2487 int index = 0;
2488 for (VarSymbol var : vars) {
2489 if (var.owner != tree.sym) {
2490 var = new VarSymbol(var.flags_field, var.name, var.type, tree.sym);
2491 }
2492 getterMethHandles[index] = var.asMethodHandle(true);
2493 index++;
2494 }
2495
2496 tree.defs = tree.defs.appendList(generateMandatedAccessors(tree));
2497 tree.defs = tree.defs.appendList(List.of(
2498 generateRecordMethod(tree, names.toString, vars, getterMethHandles),
2499 generateRecordMethod(tree, names.hashCode, vars, getterMethHandles),
2500 generateRecordMethod(tree, names.equals, vars, getterMethHandles)
2501 ));
2502 }
2503
2504 JCTree generateRecordMethod(JCClassDecl tree, Name name, List<VarSymbol> vars, MethodHandleSymbol[] getterMethHandles) {
2505 make_at(tree.pos());
2506 boolean isEquals = name == names.equals;
2507 MethodSymbol msym = lookupMethod(tree.pos(),
2508 name,
2509 tree.sym.type,
2510 isEquals ? List.of(syms.objectType) : List.nil());
2511 // compiler generated methods have the record flag set, user defined ones dont
2512 if ((msym.flags() & RECORD) != 0) {
2513 /* class java.lang.runtime.ObjectMethods provides a common bootstrap that provides a customized implementation
2514 * for methods: toString, hashCode and equals. Here we just need to generate and indy call to:
2515 * java.lang.runtime.ObjectMethods::bootstrap and provide: the record class, the record component names and
2516 * the accessors.
2517 */
2518 Name bootstrapName = names.bootstrap;
2519 LoadableConstant[] staticArgsValues = new LoadableConstant[2 + getterMethHandles.length];
2520 staticArgsValues[0] = (ClassType)tree.sym.type;
2521 String concatNames = vars.stream()
2522 .map(v -> v.name)
2523 .collect(Collectors.joining(";", "", ""));
2524 staticArgsValues[1] = LoadableConstant.String(concatNames);
2525 int index = 2;
2526 for (MethodHandleSymbol mho : getterMethHandles) {
2527 staticArgsValues[index] = mho;
2528 index++;
2529 }
2530
2531 List<Type> staticArgTypes = List.of(syms.classType,
2532 syms.stringType,
2533 new ArrayType(syms.methodHandleType, syms.arrayClass));
2534
2535 JCFieldAccess qualifier = makeIndyQualifier(syms.objectMethodsType, tree, msym,
2536 List.of(syms.methodHandleLookupType,
2537 syms.stringType,
2538 syms.typeDescriptorType).appendList(staticArgTypes),
2539 staticArgsValues, bootstrapName, name, false);
2540
2541 VarSymbol _this = new VarSymbol(SYNTHETIC, names._this, tree.sym.type, tree.sym);
2542
2543 JCMethodInvocation proxyCall;
2544 if (!isEquals) {
2545 proxyCall = make.Apply(List.nil(), qualifier, List.of(make.Ident(_this)));
2546 } else {
2547 VarSymbol o = msym.params.head;
2548 o.adr = 0;
2549 proxyCall = make.Apply(List.nil(), qualifier, List.of(make.Ident(_this), make.Ident(o)));
2550 }
2551 proxyCall.type = qualifier.type;
2552 return make.MethodDef(msym, make.Block(0, List.of(make.Return(proxyCall))));
2553 } else {
2554 return make.Block(SYNTHETIC, List.nil());
2555 }
2556 }
2557
2558 private String argsTypeSig(List<Type> typeList) {
2559 LowerSignatureGenerator sg = new LowerSignatureGenerator();
2560 sg.assembleSig(typeList);
2561 return sg.toString();
2562 }
2563
2564 /**
2565 * Signature Generation
2566 */
2567 private class LowerSignatureGenerator extends Types.SignatureGenerator {
2568
2569 /**
2570 * An output buffer for type signatures.
2571 */
2572 StringBuilder sb = new StringBuilder();
2573
2574 LowerSignatureGenerator() {
2575 types.super();
2576 }
2577
2578 @Override
2579 protected void append(char ch) {
2580 sb.append(ch);
2581 }
2582
2583 @Override
2584 protected void append(byte[] ba) {
2585 sb.append(new String(ba));
2586 }
2587
2588 @Override
2589 protected void append(Name name) {
2590 sb.append(name.toString());
2591 }
2592
2593 @Override
2594 public String toString() {
2595 return sb.toString();
2596 }
2597 }
2598
2599 /**
2600 * Creates an indy qualifier, helpful to be part of an indy invocation
2601 * @param site the site
2602 * @param tree a class declaration tree
2603 * @param msym the method symbol
2604 * @param staticArgTypes the static argument types
2605 * @param staticArgValues the static argument values
2606 * @param bootstrapName the bootstrap name to look for
2607 * @param argName normally bootstraps receives a method name as second argument, if you want that name
2608 * to be different to that of the bootstrap name pass a different name here
2609 * @param isStatic is it static or not
2610 * @return a field access tree
2611 */
2612 JCFieldAccess makeIndyQualifier(
2613 Type site,
2614 JCClassDecl tree,
2615 MethodSymbol msym,
2616 List<Type> staticArgTypes,
2617 LoadableConstant[] staticArgValues,
2618 Name bootstrapName,
2619 Name argName,
2620 boolean isStatic) {
2621 MethodSymbol bsm = rs.resolveInternalMethod(tree.pos(), attrEnv, site,
2622 bootstrapName, staticArgTypes, List.nil());
2623
2624 MethodType indyType = msym.type.asMethodType();
2625 indyType = new MethodType(
2626 isStatic ? List.nil() : indyType.argtypes.prepend(tree.sym.type),
2627 indyType.restype,
2628 indyType.thrown,
2629 syms.methodClass
2630 );
2631 DynamicMethodSymbol dynSym = new DynamicMethodSymbol(argName,
2632 syms.noSymbol,
2633 bsm.asHandle(),
2634 indyType,
2635 staticArgValues);
2636 JCFieldAccess qualifier = make.Select(make.QualIdent(site.tsym), argName);
2637 qualifier.sym = dynSym;
2638 qualifier.type = msym.type.asMethodType().restype;
2639 return qualifier;
2640 }
2641
2642 public void visitMethodDef(JCMethodDecl tree) {
2643 if (tree.name == names.init && (currentClass.flags_field&ENUM) != 0) {
2644 // Add "String $enum$name, int $enum$ordinal" to the beginning of the
2645 // argument list for each constructor of an enum.
2646 JCVariableDecl nameParam = make_at(tree.pos()).
2647 Param(names.fromString(target.syntheticNameChar() +
2648 "enum" + target.syntheticNameChar() + "name"),
2649 syms.stringType, tree.sym);
2650 nameParam.mods.flags |= SYNTHETIC; nameParam.sym.flags_field |= SYNTHETIC;
2651 JCVariableDecl ordParam = make.
2652 Param(names.fromString(target.syntheticNameChar() +
2653 "enum" + target.syntheticNameChar() +
2654 "ordinal"),
2655 syms.intType, tree.sym);
2656 ordParam.mods.flags |= SYNTHETIC; ordParam.sym.flags_field |= SYNTHETIC;
2657
2658 MethodSymbol m = tree.sym;
2659 tree.params = tree.params.prepend(ordParam).prepend(nameParam);
2660
2661 m.extraParams = m.extraParams.prepend(ordParam.sym);
2662 m.extraParams = m.extraParams.prepend(nameParam.sym);
2663 Type olderasure = m.erasure(types);
2664 m.erasure_field = new MethodType(
2665 olderasure.getParameterTypes().prepend(syms.intType).prepend(syms.stringType),
2666 olderasure.getReturnType(),
2667 olderasure.getThrownTypes(),
2668 syms.methodClass);
2669 }
2670
2671 Type prevRestype = currentRestype;
2672 JCMethodDecl prevMethodDef = currentMethodDef;
2673 MethodSymbol prevMethodSym = currentMethodSym;
2674 int prevVariableIndex = variableIndex;
2675 try {
2676 currentRestype = types.erasure(tree.type.getReturnType());
2677 currentMethodDef = tree;
2678 currentMethodSym = tree.sym;
2679 variableIndex = 0;
2680 visitMethodDefInternal(tree);
2681 } finally {
2682 currentRestype = prevRestype;
2683 currentMethodDef = prevMethodDef;
2684 currentMethodSym = prevMethodSym;
2685 variableIndex = prevVariableIndex;
2686 }
2687 }
2688
2689 private void visitMethodDefInternal(JCMethodDecl tree) {
2690 if (tree.name == names.init &&
2691 !currentClass.isStatic() &&
2692 (currentClass.isInner() || currentClass.isDirectlyOrIndirectlyLocal())) {
2693 // We are seeing a constructor of an inner class.
2694 MethodSymbol m = tree.sym;
2695
2696 // Push a new proxy scope for constructor parameters.
2697 // and create definitions for any this$n and proxy parameters.
2698 Map<Symbol, Symbol> prevProxies = proxies;
2699 proxies = new HashMap<>(proxies);
2700 List<VarSymbol> prevOuterThisStack = outerThisStack;
2701 List<VarSymbol> fvs = freevars(currentClass);
2702 JCVariableDecl otdef = null;
2703 if (currentClass.hasOuterInstance())
2704 otdef = outerThisDef(tree.pos, m);
2705 List<JCVariableDecl> fvdefs = freevarDefs(tree.pos, fvs, m, PARAMETER);
2706
2707 // Recursively translate result type, parameters and thrown list.
2708 tree.restype = translate(tree.restype);
2709 tree.params = translateVarDefs(tree.params);
2710 tree.thrown = translate(tree.thrown);
2711
2712 // when compiling stubs, don't process body
2713 if (tree.body == null) {
2714 result = tree;
2715 return;
2716 }
2717
2718 // Add this$n (if needed) in front of and free variables behind
2719 // constructor parameter list.
2720 tree.params = tree.params.appendList(fvdefs);
2721 if (currentClass.hasOuterInstance()) {
2722 tree.params = tree.params.prepend(otdef);
2723 }
2724
2725 // Determine whether this constructor has a super() invocation
2726 boolean invokesSuper = TreeInfo.hasConstructorCall(tree, names._super);
2727
2728 // Create initializers for this$n and proxies
2729 ListBuffer<JCStatement> added = new ListBuffer<>();
2730 if (fvs.nonEmpty()) {
2731 List<Type> addedargtypes = List.nil();
2732 for (List<VarSymbol> l = fvs; l.nonEmpty(); l = l.tail) {
2733 m.capturedLocals =
2734 m.capturedLocals.prepend((VarSymbol)
2735 (proxies.get(l.head)));
2736 if (invokesSuper) {
2737 added = added.prepend(
2738 initField(tree.body.pos, proxies.get(l.head), prevProxies.get(l.head)));
2739 }
2740 addedargtypes = addedargtypes.prepend(l.head.erasure(types));
2741 }
2742 Type olderasure = m.erasure(types);
2743 m.erasure_field = new MethodType(
2744 olderasure.getParameterTypes().appendList(addedargtypes),
2745 olderasure.getReturnType(),
2746 olderasure.getThrownTypes(),
2747 syms.methodClass);
2748 }
2749
2750 // Recursively translate existing local statements
2751 tree.body.stats = translate(tree.body.stats);
2752
2753 // Prepend initializers in front of super() call
2754 if (added.nonEmpty()) {
2755 List<JCStatement> initializers = added.toList();
2756 TreeInfo.mapSuperCalls(tree.body, supercall -> make.Block(0, initializers.append(supercall)));
2757 }
2758
2759 // pop local variables from proxy stack
2760 proxies = prevProxies;
2761
2762 outerThisStack = prevOuterThisStack;
2763 } else {
2764 super.visitMethodDef(tree);
2765 }
2766 if (tree.name == names.init && ((tree.sym.flags_field & Flags.COMPACT_RECORD_CONSTRUCTOR) != 0 ||
2767 (tree.sym.flags_field & (GENERATEDCONSTR | RECORD)) == (GENERATEDCONSTR | RECORD))) {
2768 // lets find out if there is any field waiting to be initialized
2769 ListBuffer<VarSymbol> fields = new ListBuffer<>();
2770 for (Symbol sym : currentClass.getEnclosedElements()) {
2771 if (sym.kind == Kinds.Kind.VAR && ((sym.flags() & RECORD) != 0))
2772 fields.append((VarSymbol) sym);
2773 }
2774 ListBuffer<JCStatement> initializers = new ListBuffer<>();
2775 for (VarSymbol field: fields) {
2776 if ((field.flags_field & Flags.UNINITIALIZED_FIELD) != 0) {
2777 VarSymbol param = tree.params.stream().filter(p -> p.name == field.name).findFirst().get().sym;
2778 make.at(tree.pos);
2779 initializers.add(make.Exec(
2780 make.Assign(
2781 make.Select(make.This(field.owner.erasure(types)), field),
2782 make.Ident(param)).setType(field.erasure(types))));
2783 field.flags_field &= ~Flags.UNINITIALIZED_FIELD;
2784 }
2785 }
2786 if (initializers.nonEmpty()) {
2787 if (allowValueClasses && (tree.sym.owner.isValueClass() || tree.sym.owner.hasStrict() || ((ClassSymbol)tree.sym.owner).isRecord())) {
2788 TreeInfo.mapSuperCalls(tree.body, supercall -> make.Block(0, initializers.toList().append(supercall)));
2789 } else {
2790 tree.body.stats = tree.body.stats.appendList(initializers);
2791 }
2792 }
2793 }
2794 result = tree;
2795 }
2796
2797 public void visitTypeCast(JCTypeCast tree) {
2798 tree.clazz = translate(tree.clazz);
2799 if (tree.type.isPrimitive() != tree.expr.type.isPrimitive())
2800 tree.expr = translate(tree.expr, tree.type);
2801 else
2802 tree.expr = translate(tree.expr);
2803 result = tree;
2804 }
2805
2806 /**
2807 * All the exactness checks between primitive types that require a run-time
2808 * check are in {@code java.lang.runtime.ExactConversionsSupport}. Those methods
2809 * are in the form {@code ExactConversionsSupport.is<S>To<T>Exact} where both
2810 * {@code S} and {@code T} are primitive types and correspond to the runtime
2811 * action that will be executed to check whether a certain value (that is passed
2812 * as a parameter) can be converted to {@code T} without loss of information.
2813 *
2814 * Rewrite {@code instanceof if expr : Object} and Type is primitive type:
2815 *
2816 * {@snippet :
2817 * Object v = ...
2818 * if (v instanceof float)
2819 * =>
2820 * if (let tmp$123 = v; tmp$123 instanceof Float)
2821 * }
2822 *
2823 * Rewrite {@code instanceof if expr : wrapper reference type}
2824 *
2825 * {@snippet :
2826 * Integer v = ...
2827 * if (v instanceof float)
2828 * =>
2829 * if (let tmp$123 = v; tmp$123 != null && ExactConversionsSupport.intToFloatExact(tmp$123.intValue()))
2830 * }
2831 *
2832 * Rewrite {@code instanceof if expr : primitive}
2833 *
2834 * {@snippet :
2835 * int v = ...
2836 * if (v instanceof float)
2837 * =>
2838 * if (let tmp$123 = v; ExactConversionsSupport.intToFloatExact(tmp$123))
2839 * }
2840 *
2841 * More rewritings:
2842 * <ul>
2843 * <li>If the {@code instanceof} check is unconditionally exact rewrite to true.</li>
2844 * <li>If expression type is {@code Byte}, {@code Short}, {@code Integer}, ..., an
2845 * unboxing conversion followed by a widening primitive conversion.</li>
2846 * <li>If expression type is a supertype: {@code Number}, a narrowing reference
2847 * conversion followed by an unboxing conversion.</li>
2848 * </ul>
2849 */
2850 public void visitTypeTest(JCInstanceOf tree) {
2851 if (tree.expr.type.isPrimitive() || tree.pattern.type.isPrimitive()) {
2852 JCStatement prefixStatement;
2853 JCExpression exactnessCheck;
2854 JCExpression instanceOfExpr = translate(tree.expr);
2855
2856 if (types.isUnconditionallyExact(tree.expr.type, tree.pattern.type)) {
2857 // instanceOfExpr; true
2858 prefixStatement = make.Exec(instanceOfExpr);
2859 exactnessCheck = make.Literal(BOOLEAN, 1).setType(syms.booleanType.constType(1));
2860 } else if (tree.expr.type.isPrimitive()) {
2861 // ExactConversionSupport.isXxxExact(instanceOfExpr)
2862 prefixStatement = null;
2863 exactnessCheck = getExactnessCheck(tree, instanceOfExpr);
2864 } else if (tree.expr.type.isReference()) {
2865 if (types.isUnconditionallyExact(types.unboxedType(tree.expr.type), tree.pattern.type)) {
2866 // instanceOfExpr != null
2867 prefixStatement = null;
2868 exactnessCheck = makeBinary(NE, instanceOfExpr, makeNull());
2869 } else {
2870 // We read the result of instanceOfExpr, so create variable
2871 VarSymbol dollar_s = new VarSymbol(FINAL | SYNTHETIC,
2872 names.fromString("tmp" + variableIndex++ + this.target.syntheticNameChar()),
2873 types.erasure(tree.expr.type),
2874 currentMethodSym);
2875 prefixStatement = make.at(tree.pos())
2876 .VarDef(dollar_s, instanceOfExpr);
2877
2878 JCExpression nullCheck =
2879 makeBinary(NE,
2880 make.Ident(dollar_s),
2881 makeNull());
2882
2883 if (types.unboxedType(tree.expr.type).isPrimitive()) {
2884 exactnessCheck =
2885 makeBinary(AND,
2886 nullCheck,
2887 getExactnessCheck(tree, boxIfNeeded(make.Ident(dollar_s), types.unboxedType(tree.expr.type))));
2888 } else {
2889 exactnessCheck =
2890 makeBinary(AND,
2891 nullCheck,
2892 make.at(tree.pos())
2893 .TypeTest(make.Ident(dollar_s), make.Type(types.boxedClass(tree.pattern.type).type))
2894 .setType(syms.booleanType));
2895 }
2896 }
2897 } else {
2898 throw Assert.error("Non primitive or reference type: " + tree.expr.type);
2899 }
2900 result = (prefixStatement == null ? exactnessCheck : make.LetExpr(List.of(prefixStatement), exactnessCheck))
2901 .setType(syms.booleanType);
2902 } else {
2903 tree.expr = translate(tree.expr);
2904 tree.pattern = translate(tree.pattern);
2905 result = tree;
2906 }
2907 }
2908
2909 // TypePairs should be in sync with the corresponding record in SwitchBootstraps
2910 record TypePairs(TypeSymbol from, TypeSymbol to) {
2911 public static TypePairs of(Symtab syms, Type from, Type to) {
2912 if (from == syms.byteType || from == syms.shortType || from == syms.charType) {
2913 from = syms.intType;
2914 }
2915 return new TypePairs(from, to);
2916 }
2917
2918 public TypePairs(Type from, Type to) {
2919 this(from.tsym, to.tsym);
2920 }
2921
2922 public static HashMap<TypePairs, String> initialize(Symtab syms) {
2923 HashMap<TypePairs, String> typePairToName = new HashMap<>();
2924 typePairToName.put(new TypePairs(syms.byteType, syms.charType), "isIntToCharExact"); // redirected
2925 typePairToName.put(new TypePairs(syms.shortType, syms.byteType), "isIntToByteExact"); // redirected
2926 typePairToName.put(new TypePairs(syms.shortType, syms.charType), "isIntToCharExact"); // redirected
2927 typePairToName.put(new TypePairs(syms.charType, syms.byteType), "isIntToByteExact"); // redirected
2928 typePairToName.put(new TypePairs(syms.charType, syms.shortType), "isIntToShortExact"); // redirected
2929 typePairToName.put(new TypePairs(syms.intType, syms.byteType), "isIntToByteExact");
2930 typePairToName.put(new TypePairs(syms.intType, syms.shortType), "isIntToShortExact");
2931 typePairToName.put(new TypePairs(syms.intType, syms.charType), "isIntToCharExact");
2932 typePairToName.put(new TypePairs(syms.intType, syms.floatType), "isIntToFloatExact");
2933 typePairToName.put(new TypePairs(syms.longType, syms.byteType), "isLongToByteExact");
2934 typePairToName.put(new TypePairs(syms.longType, syms.shortType), "isLongToShortExact");
2935 typePairToName.put(new TypePairs(syms.longType, syms.charType), "isLongToCharExact");
2936 typePairToName.put(new TypePairs(syms.longType, syms.intType), "isLongToIntExact");
2937 typePairToName.put(new TypePairs(syms.longType, syms.floatType), "isLongToFloatExact");
2938 typePairToName.put(new TypePairs(syms.longType, syms.doubleType), "isLongToDoubleExact");
2939 typePairToName.put(new TypePairs(syms.floatType, syms.byteType), "isFloatToByteExact");
2940 typePairToName.put(new TypePairs(syms.floatType, syms.shortType), "isFloatToShortExact");
2941 typePairToName.put(new TypePairs(syms.floatType, syms.charType), "isFloatToCharExact");
2942 typePairToName.put(new TypePairs(syms.floatType, syms.intType), "isFloatToIntExact");
2943 typePairToName.put(new TypePairs(syms.floatType, syms.longType), "isFloatToLongExact");
2944 typePairToName.put(new TypePairs(syms.doubleType, syms.byteType), "isDoubleToByteExact");
2945 typePairToName.put(new TypePairs(syms.doubleType, syms.shortType), "isDoubleToShortExact");
2946 typePairToName.put(new TypePairs(syms.doubleType, syms.charType), "isDoubleToCharExact");
2947 typePairToName.put(new TypePairs(syms.doubleType, syms.intType), "isDoubleToIntExact");
2948 typePairToName.put(new TypePairs(syms.doubleType, syms.longType), "isDoubleToLongExact");
2949 typePairToName.put(new TypePairs(syms.doubleType, syms.floatType), "isDoubleToFloatExact");
2950 return typePairToName;
2951 }
2952 }
2953
2954 private JCExpression getExactnessCheck(JCInstanceOf tree, JCExpression argument) {
2955 TypePairs pair = TypePairs.of(syms, types.unboxedTypeOrType(tree.expr.type), tree.pattern.type);
2956
2957 Name exactnessFunction = names.fromString(typePairToName.get(pair));
2958
2959 // Resolve the exactness method
2960 Symbol ecsym = lookupMethod(tree.pos(),
2961 exactnessFunction,
2962 syms.exactConversionsSupportType,
2963 List.of(pair.from.type));
2964
2965 // Generate the method call ExactnessChecks.<exactness method>(<argument>);
2966 JCFieldAccess select = make.Select(
2967 make.QualIdent(syms.exactConversionsSupportType.tsym),
2968 exactnessFunction);
2969 select.sym = ecsym;
2970 select.setType(syms.booleanType);
2971
2972 JCExpression exactnessCheck = make.Apply(List.nil(),
2973 select,
2974 List.of(argument));
2975 exactnessCheck.setType(syms.booleanType);
2976 return exactnessCheck;
2977 }
2978
2979 public void visitNewClass(JCNewClass tree) {
2980 ClassSymbol c = (ClassSymbol)tree.constructor.owner;
2981
2982 // Box arguments, if necessary
2983 boolean isEnum = (tree.constructor.owner.flags() & ENUM) != 0;
2984 List<Type> argTypes = tree.constructor.type.getParameterTypes();
2985 if (isEnum) argTypes = argTypes.prepend(syms.intType).prepend(syms.stringType);
2986 tree.args = boxArgs(argTypes, tree.args, tree.varargsElement);
2987 tree.varargsElement = null;
2988
2989 // If created class is local, add free variables after
2990 // explicit constructor arguments.
2991 if (c.isDirectlyOrIndirectlyLocal() && !c.isStatic()) {
2992 tree.args = tree.args.appendList(loadFreevars(tree.pos(), freevars(c)));
2993 }
2994
2995 // If an access constructor is used, append null as a last argument.
2996 Symbol constructor = accessConstructor(tree.pos(), tree.constructor);
2997 if (constructor != tree.constructor) {
2998 tree.args = tree.args.append(makeNull());
2999 tree.constructor = constructor;
3000 }
3001
3002 // If created class has an outer instance, and new is qualified, pass
3003 // qualifier as first argument. If new is not qualified, pass the
3004 // correct outer instance as first argument.
3005 if (c.hasOuterInstance()) {
3006 JCExpression thisArg;
3007 if (tree.encl != null) {
3008 thisArg = attr.makeNullCheck(translate(tree.encl));
3009 thisArg.type = tree.encl.type;
3010 } else if (c.isDirectlyOrIndirectlyLocal()) {
3011 // local class
3012 thisArg = makeThis(tree.pos(), c.innermostAccessibleEnclosingClass());
3013 } else {
3014 // nested class
3015 thisArg = makeOwnerThis(tree.pos(), c, false);
3016 if (currentMethodSym != null &&
3017 ((currentMethodSym.flags_field & (STATIC | BLOCK)) == BLOCK) &&
3018 currentMethodSym.owner.isValueClass()) {
3019 // instance initializer in a value class
3020 Set<JCExpression> outerThisSet = initializerOuterThis.get(currentClass);
3021 if (outerThisSet == null) {
3022 outerThisSet = new HashSet<>();
3023 }
3024 outerThisSet.add(thisArg);
3025 initializerOuterThis.put(currentClass, outerThisSet);
3026 }
3027 }
3028 tree.args = tree.args.prepend(thisArg);
3029 }
3030 tree.encl = null;
3031
3032 // If we have an anonymous class, create its flat version, rather
3033 // than the class or interface following new.
3034 if (tree.def != null) {
3035 translate(tree.def);
3036
3037 tree.clazz = access(make_at(tree.clazz.pos()).Ident(tree.def.sym));
3038 tree.def = null;
3039 } else {
3040 tree.clazz = access(c, tree.clazz, enclOp, false);
3041 }
3042 result = tree;
3043 }
3044
3045 // Simplify conditionals with known constant controlling expressions.
3046 // This allows us to avoid generating supporting declarations for
3047 // the dead code, which will not be eliminated during code generation.
3048 // Note that Flow.isFalse and Flow.isTrue only return true
3049 // for constant expressions in the sense of JLS 15.27, which
3050 // are guaranteed to have no side-effects. More aggressive
3051 // constant propagation would require that we take care to
3052 // preserve possible side-effects in the condition expression.
3053
3054 // One common case is equality expressions involving a constant and null.
3055 // Since null is not a constant expression (because null cannot be
3056 // represented in the constant pool), equality checks involving null are
3057 // not captured by Flow.isTrue/isFalse.
3058 // Equality checks involving a constant and null, e.g.
3059 // "" == null
3060 // are safe to simplify as no side-effects can occur.
3061
3062 private boolean isTrue(JCTree exp) {
3063 if (exp.type.isTrue())
3064 return true;
3065 Boolean b = expValue(exp);
3066 return b == null ? false : b;
3067 }
3068 private boolean isFalse(JCTree exp) {
3069 if (exp.type.isFalse())
3070 return true;
3071 Boolean b = expValue(exp);
3072 return b == null ? false : !b;
3073 }
3074 /* look for (in)equality relations involving null.
3075 * return true - if expression is always true
3076 * false - if expression is always false
3077 * null - if expression cannot be eliminated
3078 */
3079 private Boolean expValue(JCTree exp) {
3080 while (exp.hasTag(PARENS))
3081 exp = ((JCParens)exp).expr;
3082
3083 boolean eq;
3084 switch (exp.getTag()) {
3085 case EQ: eq = true; break;
3086 case NE: eq = false; break;
3087 default:
3088 return null;
3089 }
3090
3091 // we have a JCBinary(EQ|NE)
3092 // check if we have two literals (constants or null)
3093 JCBinary b = (JCBinary)exp;
3094 if (b.lhs.type.hasTag(BOT)) return expValueIsNull(eq, b.rhs);
3095 if (b.rhs.type.hasTag(BOT)) return expValueIsNull(eq, b.lhs);
3096 return null;
3097 }
3098 private Boolean expValueIsNull(boolean eq, JCTree t) {
3099 if (t.type.hasTag(BOT)) return Boolean.valueOf(eq);
3100 if (t.hasTag(LITERAL)) return Boolean.valueOf(!eq);
3101 return null;
3102 }
3103
3104 /** Visitor method for conditional expressions.
3105 */
3106 @Override
3107 public void visitConditional(JCConditional tree) {
3108 JCTree cond = tree.cond = translate(tree.cond, syms.booleanType);
3109 if (isTrue(cond) && noClassDefIn(tree.falsepart)) {
3110 result = convert(translate(tree.truepart, tree.type), tree.type);
3111 addPrunedInfo(cond);
3112 } else if (isFalse(cond) && noClassDefIn(tree.truepart)) {
3113 result = convert(translate(tree.falsepart, tree.type), tree.type);
3114 addPrunedInfo(cond);
3115 } else {
3116 // Condition is not a compile-time constant.
3117 tree.truepart = translate(tree.truepart, tree.type);
3118 tree.falsepart = translate(tree.falsepart, tree.type);
3119 result = tree;
3120 }
3121 }
3122 //where
3123 private JCExpression convert(JCExpression tree, Type pt) {
3124 if (tree.type == pt || tree.type.hasTag(BOT))
3125 return tree;
3126 JCExpression result = make_at(tree.pos()).TypeCast(make.Type(pt), tree);
3127 result.type = (tree.type.constValue() != null) ? cfolder.coerce(tree.type, pt)
3128 : pt;
3129 return result;
3130 }
3131
3132 /** Visitor method for if statements.
3133 */
3134 public void visitIf(JCIf tree) {
3135 JCTree cond = tree.cond = translate(tree.cond, syms.booleanType);
3136 if (isTrue(cond) && noClassDefIn(tree.elsepart)) {
3137 result = translate(tree.thenpart);
3138 addPrunedInfo(cond);
3139 } else if (isFalse(cond) && noClassDefIn(tree.thenpart)) {
3140 if (tree.elsepart != null) {
3141 result = translate(tree.elsepart);
3142 } else {
3143 result = make.Skip();
3144 }
3145 addPrunedInfo(cond);
3146 } else {
3147 // Condition is not a compile-time constant.
3148 tree.thenpart = translate(tree.thenpart);
3149 tree.elsepart = translate(tree.elsepart);
3150 result = tree;
3151 }
3152 }
3153
3154 /** Visitor method for assert statements. Translate them away.
3155 */
3156 public void visitAssert(JCAssert tree) {
3157 tree.cond = translate(tree.cond, syms.booleanType);
3158 if (!tree.cond.type.isTrue()) {
3159 JCExpression cond = assertFlagTest(tree.pos());
3160 List<JCExpression> exnArgs = (tree.detail == null) ?
3161 List.nil() : List.of(translate(tree.detail));
3162 if (!tree.cond.type.isFalse()) {
3163 cond = makeBinary
3164 (AND,
3165 cond,
3166 makeUnary(NOT, tree.cond));
3167 }
3168 result =
3169 make.If(cond,
3170 make_at(tree).
3171 Throw(makeNewClass(syms.assertionErrorType, exnArgs)),
3172 null);
3173 } else {
3174 result = make.Skip();
3175 }
3176 }
3177
3178 public void visitApply(JCMethodInvocation tree) {
3179 Symbol meth = TreeInfo.symbol(tree.meth);
3180 List<Type> argtypes = meth.type.getParameterTypes();
3181 if (meth.name == names.init && meth.owner == syms.enumSym)
3182 argtypes = argtypes.tail.tail;
3183 tree.args = boxArgs(argtypes, tree.args, tree.varargsElement);
3184 tree.varargsElement = null;
3185 Name methName = TreeInfo.name(tree.meth);
3186 if (meth.name==names.init) {
3187 // We are seeing a this(...) or super(...) constructor call.
3188 // If an access constructor is used, append null as a last argument.
3189 Symbol constructor = accessConstructor(tree.pos(), meth);
3190 if (constructor != meth) {
3191 tree.args = tree.args.append(makeNull());
3192 TreeInfo.setSymbol(tree.meth, constructor);
3193 }
3194
3195 // If we are calling a constructor of a local class, add
3196 // free variables after explicit constructor arguments.
3197 ClassSymbol c = (ClassSymbol)constructor.owner;
3198 if (c.isDirectlyOrIndirectlyLocal() && !c.isStatic()) {
3199 tree.args = tree.args.appendList(loadFreevars(tree.pos(), freevars(c)));
3200 }
3201
3202 // If we are calling a constructor of an enum class, pass
3203 // along the name and ordinal arguments
3204 if ((c.flags_field&ENUM) != 0 || c.getQualifiedName() == names.java_lang_Enum) {
3205 List<JCVariableDecl> params = currentMethodDef.params;
3206 if (currentMethodSym.owner.hasOuterInstance())
3207 params = params.tail; // drop this$n
3208 tree.args = tree.args
3209 .prepend(make_at(tree.pos()).Ident(params.tail.head.sym)) // ordinal
3210 .prepend(make.Ident(params.head.sym)); // name
3211 }
3212
3213 // If we are calling a constructor of a class with an outer
3214 // instance, and the call
3215 // is qualified, pass qualifier as first argument in front of
3216 // the explicit constructor arguments. If the call
3217 // is not qualified, pass the correct outer instance as
3218 // first argument. If we are a static class, there is no
3219 // such outer instance, so generate an error.
3220 if (c.hasOuterInstance()) {
3221 JCExpression thisArg;
3222 if (tree.meth.hasTag(SELECT)) {
3223 thisArg = attr.
3224 makeNullCheck(translate(((JCFieldAccess) tree.meth).selected));
3225 tree.meth = make.Ident(constructor);
3226 ((JCIdent) tree.meth).name = methName;
3227 } else if (c.isDirectlyOrIndirectlyLocal() || methName == names._this){
3228 // local class or this() call
3229 thisArg = makeThis(tree.meth.pos(), c.innermostAccessibleEnclosingClass());
3230 } else if (currentClass.isStatic()) {
3231 // super() call from static nested class - invalid
3232 log.error(tree.pos(),
3233 Errors.NoEnclInstanceOfTypeInScope(c.type.getEnclosingType().tsym));
3234 thisArg = make.Literal(BOT, null).setType(syms.botType);
3235 } else {
3236 // super() call of nested class - never pick 'this'
3237 thisArg = makeOwnerThisN(tree.meth.pos(), c, false);
3238 }
3239 tree.args = tree.args.prepend(thisArg);
3240 }
3241 } else {
3242 // We are seeing a normal method invocation; translate this as usual.
3243 tree.meth = translate(tree.meth);
3244
3245 // If the translated method itself is an Apply tree, we are
3246 // seeing an access method invocation. In this case, append
3247 // the method arguments to the arguments of the access method.
3248 if (tree.meth.hasTag(APPLY)) {
3249 JCMethodInvocation app = (JCMethodInvocation)tree.meth;
3250 app.args = tree.args.prependList(app.args);
3251 result = app;
3252 return;
3253 }
3254 }
3255 if (tree.args.stream().anyMatch(c -> c == null)) {
3256 throw new AssertionError("Whooops before: " + tree);
3257 }
3258 result = tree;
3259 }
3260
3261 List<JCExpression> boxArgs(List<Type> parameters, List<JCExpression> _args, Type varargsElement) {
3262 List<JCExpression> args = _args;
3263 if (parameters.isEmpty()) return args;
3264 boolean anyChanges = false;
3265 ListBuffer<JCExpression> result = new ListBuffer<>();
3266 while (parameters.tail.nonEmpty()) {
3267 JCExpression arg = translate(args.head, parameters.head);
3268 anyChanges |= (arg != args.head);
3269 result.append(arg);
3270 args = args.tail;
3271 parameters = parameters.tail;
3272 }
3273 Type parameter = parameters.head;
3274 if (varargsElement != null) {
3275 anyChanges = true;
3276 ListBuffer<JCExpression> elems = new ListBuffer<>();
3277 while (args.nonEmpty()) {
3278 JCExpression arg = translate(args.head, varargsElement);
3279 elems.append(arg);
3280 args = args.tail;
3281 }
3282 JCNewArray boxedArgs = make.NewArray(make.Type(varargsElement),
3283 List.nil(),
3284 elems.toList());
3285 boxedArgs.type = new ArrayType(varargsElement, syms.arrayClass);
3286 result.append(boxedArgs);
3287 } else {
3288 if (args.length() != 1) throw new AssertionError(args);
3289 JCExpression arg = translate(args.head, parameter);
3290 anyChanges |= (arg != args.head);
3291 result.append(arg);
3292 if (!anyChanges) return _args;
3293 }
3294 return result.toList();
3295 }
3296
3297 /** Expand a boxing or unboxing conversion if needed. */
3298 @SuppressWarnings("unchecked") // XXX unchecked
3299 <T extends JCExpression> T boxIfNeeded(T tree, Type type) {
3300 Assert.check(!type.hasTag(VOID));
3301 if (type.hasTag(NONE))
3302 return tree;
3303 boolean havePrimitive = tree.type.isPrimitive();
3304 if (havePrimitive == type.isPrimitive())
3305 return tree;
3306 if (havePrimitive) {
3307 Type unboxedTarget = types.unboxedType(type);
3308 if (!unboxedTarget.hasTag(NONE)) {
3309 if (!types.isSubtype(tree.type, unboxedTarget)) //e.g. Character c = 89;
3310 tree.type = unboxedTarget.constType(tree.type.constValue());
3311 return (T)boxPrimitive(tree, types.erasure(type));
3312 } else {
3313 tree = (T)boxPrimitive(tree);
3314 }
3315 } else {
3316 tree = (T)unbox(tree, type);
3317 }
3318 return tree;
3319 }
3320
3321 /** Box up a single primitive expression. */
3322 JCExpression boxPrimitive(JCExpression tree) {
3323 return boxPrimitive(tree, types.boxedClass(tree.type).type);
3324 }
3325
3326 /** Box up a single primitive expression. */
3327 JCExpression boxPrimitive(JCExpression tree, Type box) {
3328 make_at(tree.pos());
3329 Symbol valueOfSym = lookupMethod(tree.pos(),
3330 names.valueOf,
3331 box,
3332 List.<Type>nil()
3333 .prepend(tree.type));
3334 return make.App(make.QualIdent(valueOfSym), List.of(tree));
3335 }
3336
3337 /** Unbox an object to a primitive value. */
3338 JCExpression unbox(JCExpression tree, Type primitive) {
3339 Type unboxedType = types.unboxedType(tree.type);
3340 if (unboxedType.hasTag(NONE)) {
3341 unboxedType = primitive;
3342 if (!unboxedType.isPrimitive())
3343 throw new AssertionError(unboxedType);
3344 make_at(tree.pos());
3345 tree = make.TypeCast(types.boxedClass(unboxedType).type, tree);
3346 } else {
3347 // There must be a conversion from unboxedType to primitive.
3348 if (!types.isSubtype(unboxedType, primitive))
3349 throw new AssertionError(tree);
3350 }
3351 make_at(tree.pos());
3352 Symbol valueSym = lookupMethod(tree.pos(),
3353 unboxedType.tsym.name.append(names.Value), // x.intValue()
3354 tree.type,
3355 List.nil());
3356 return make.App(make.Select(tree, valueSym));
3357 }
3358
3359 /** Visitor method for parenthesized expressions.
3360 * If the subexpression has changed, omit the parens.
3361 */
3362 public void visitParens(JCParens tree) {
3363 JCTree expr = translate(tree.expr);
3364 result = ((expr == tree.expr) ? tree : expr);
3365 }
3366
3367 public void visitIndexed(JCArrayAccess tree) {
3368 tree.indexed = translate(tree.indexed);
3369 tree.index = translate(tree.index, syms.intType);
3370 result = tree;
3371 }
3372
3373 public void visitAssign(JCAssign tree) {
3374 tree.lhs = translate(tree.lhs, tree);
3375 tree.rhs = translate(tree.rhs, tree.lhs.type);
3376
3377 // If translated left hand side is an Apply, we are
3378 // seeing an access method invocation. In this case, append
3379 // right hand side as last argument of the access method.
3380 if (tree.lhs.hasTag(APPLY)) {
3381 JCMethodInvocation app = (JCMethodInvocation)tree.lhs;
3382 app.args = List.of(tree.rhs).prependList(app.args);
3383 result = app;
3384 } else {
3385 result = tree;
3386 }
3387 }
3388
3389 public void visitAssignop(final JCAssignOp tree) {
3390 final boolean boxingReq = !tree.lhs.type.isPrimitive() &&
3391 tree.operator.type.getReturnType().isPrimitive();
3392
3393 AssignopDependencyScanner depScanner = new AssignopDependencyScanner(tree);
3394 depScanner.scan(tree.rhs);
3395
3396 if (boxingReq || depScanner.dependencyFound) {
3397 // boxing required; need to rewrite as x = (unbox typeof x)(x op y);
3398 // or if x == (typeof x)z then z = (unbox typeof x)((typeof x)z op y)
3399 // (but without recomputing x)
3400 JCTree newTree = abstractLval(tree.lhs, lhs -> {
3401 Tag newTag = tree.getTag().noAssignOp();
3402 // Erasure (TransTypes) can change the type of
3403 // tree.lhs. However, we can still get the
3404 // unerased type of tree.lhs as it is stored
3405 // in tree.type in Attr.
3406 OperatorSymbol newOperator = operators.resolveBinary(tree,
3407 newTag,
3408 tree.type,
3409 tree.rhs.type);
3410 //Need to use the "lhs" at two places, once on the future left hand side
3411 //and once in the future binary operator. But further processing may change
3412 //the components of the tree in place (see visitSelect for e.g. <Class>.super.<ident>),
3413 //so cloning the tree to avoid interference between the uses:
3414 JCExpression expr = (JCExpression) lhs.clone();
3415 if (expr.type != tree.type)
3416 expr = make.TypeCast(tree.type, expr);
3417 JCBinary opResult = make.Binary(newTag, expr, tree.rhs);
3418 opResult.operator = newOperator;
3419 opResult.type = newOperator.type.getReturnType();
3420 JCExpression newRhs = boxingReq ?
3421 make.TypeCast(types.unboxedType(tree.type), opResult) :
3422 opResult;
3423 return make.Assign(lhs, newRhs).setType(tree.type);
3424 });
3425 result = translate(newTree);
3426 return;
3427 }
3428 tree.lhs = translate(tree.lhs, tree);
3429 tree.rhs = translate(tree.rhs, tree.operator.type.getParameterTypes().tail.head);
3430
3431 // If translated left hand side is an Apply, we are
3432 // seeing an access method invocation. In this case, append
3433 // right hand side as last argument of the access method.
3434 if (tree.lhs.hasTag(APPLY)) {
3435 JCMethodInvocation app = (JCMethodInvocation)tree.lhs;
3436 // if operation is a += on strings,
3437 // make sure to convert argument to string
3438 JCExpression rhs = tree.operator.opcode == string_add
3439 ? makeString(tree.rhs)
3440 : tree.rhs;
3441 app.args = List.of(rhs).prependList(app.args);
3442 result = app;
3443 } else {
3444 result = tree;
3445 }
3446 }
3447
3448 class AssignopDependencyScanner extends TreeScanner {
3449
3450 Symbol sym;
3451 boolean dependencyFound = false;
3452
3453 AssignopDependencyScanner(JCAssignOp tree) {
3454 this.sym = TreeInfo.symbol(tree.lhs);
3455 }
3456
3457 @Override
3458 public void scan(JCTree tree) {
3459 if (tree != null && sym != null) {
3460 tree.accept(this);
3461 }
3462 }
3463
3464 @Override
3465 public void visitAssignop(JCAssignOp tree) {
3466 if (TreeInfo.symbol(tree.lhs) == sym) {
3467 dependencyFound = true;
3468 return;
3469 }
3470 super.visitAssignop(tree);
3471 }
3472
3473 @Override
3474 public void visitUnary(JCUnary tree) {
3475 if (TreeInfo.symbol(tree.arg) == sym) {
3476 dependencyFound = true;
3477 return;
3478 }
3479 super.visitUnary(tree);
3480 }
3481 }
3482
3483 /** Lower a tree of the form e++ or e-- where e is an object type */
3484 JCExpression lowerBoxedPostop(final JCUnary tree) {
3485 // translate to tmp1=lval(e); tmp2=tmp1; tmp1 OP 1; tmp2
3486 // or
3487 // translate to tmp1=lval(e); tmp2=tmp1; (typeof tree)tmp1 OP 1; tmp2
3488 // where OP is += or -=
3489 final boolean cast = TreeInfo.skipParens(tree.arg).hasTag(TYPECAST);
3490 return abstractLval(tree.arg, tmp1 -> abstractRval(tmp1, tree.arg.type, tmp2 -> {
3491 Tag opcode = (tree.hasTag(POSTINC))
3492 ? PLUS_ASG : MINUS_ASG;
3493 //"tmp1" and "tmp2" may refer to the same instance
3494 //(for e.g. <Class>.super.<ident>). But further processing may
3495 //change the components of the tree in place (see visitSelect),
3496 //so cloning the tree to avoid interference between the two uses:
3497 JCExpression lhs = (JCExpression)tmp1.clone();
3498 lhs = cast
3499 ? make.TypeCast(tree.arg.type, lhs)
3500 : lhs;
3501 JCExpression update = makeAssignop(opcode,
3502 lhs,
3503 make.Literal(1));
3504 return makeComma(update, tmp2);
3505 }));
3506 }
3507
3508 public void visitUnary(JCUnary tree) {
3509 boolean isUpdateOperator = tree.getTag().isIncOrDecUnaryOp();
3510 if (isUpdateOperator && !tree.arg.type.isPrimitive()) {
3511 switch(tree.getTag()) {
3512 case PREINC: // ++ e
3513 // translate to e += 1
3514 case PREDEC: // -- e
3515 // translate to e -= 1
3516 {
3517 JCTree.Tag opcode = (tree.hasTag(PREINC))
3518 ? PLUS_ASG : MINUS_ASG;
3519 JCAssignOp newTree = makeAssignop(opcode,
3520 tree.arg,
3521 make.Literal(1));
3522 result = translate(newTree, tree.type);
3523 return;
3524 }
3525 case POSTINC: // e ++
3526 case POSTDEC: // e --
3527 {
3528 result = translate(lowerBoxedPostop(tree), tree.type);
3529 return;
3530 }
3531 }
3532 throw new AssertionError(tree);
3533 }
3534
3535 tree.arg = boxIfNeeded(translate(tree.arg, tree), tree.type);
3536
3537 if (tree.hasTag(NOT) && tree.arg.type.constValue() != null) {
3538 tree.type = cfolder.fold1(bool_not, tree.arg.type);
3539 }
3540
3541 // If translated left hand side is an Apply, we are
3542 // seeing an access method invocation. In this case, return
3543 // that access method invocation as result.
3544 if (isUpdateOperator && tree.arg.hasTag(APPLY)) {
3545 result = tree.arg;
3546 } else {
3547 result = tree;
3548 }
3549 }
3550
3551 public void visitBinary(JCBinary tree) {
3552 List<Type> formals = tree.operator.type.getParameterTypes();
3553 JCTree lhs = tree.lhs = translate(tree.lhs, formals.head);
3554 switch (tree.getTag()) {
3555 case OR:
3556 if (isTrue(lhs)) {
3557 result = lhs;
3558 return;
3559 }
3560 if (isFalse(lhs)) {
3561 result = translate(tree.rhs, formals.tail.head);
3562 return;
3563 }
3564 break;
3565 case AND:
3566 if (isFalse(lhs)) {
3567 result = lhs;
3568 return;
3569 }
3570 if (isTrue(lhs)) {
3571 result = translate(tree.rhs, formals.tail.head);
3572 return;
3573 }
3574 break;
3575 }
3576 tree.rhs = translate(tree.rhs, formals.tail.head);
3577 result = tree;
3578 }
3579
3580 public void visitIdent(JCIdent tree) {
3581 result = access(tree.sym, tree, enclOp, false);
3582 }
3583
3584 /** Translate away the foreach loop. */
3585 public void visitForeachLoop(JCEnhancedForLoop tree) {
3586 if (types.elemtype(tree.expr.type) == null)
3587 visitIterableForeachLoop(tree);
3588 else
3589 visitArrayForeachLoop(tree);
3590 }
3591 // where
3592 /**
3593 * A statement of the form
3594 *
3595 * <pre>
3596 * for ( T v : arrayexpr ) stmt;
3597 * </pre>
3598 *
3599 * (where arrayexpr is of an array type) gets translated to
3600 *
3601 * <pre>{@code
3602 * for ( { arraytype #arr = arrayexpr;
3603 * int #len = array.length;
3604 * int #i = 0; };
3605 * #i < #len; i$++ ) {
3606 * T v = arr$[#i];
3607 * stmt;
3608 * }
3609 * }</pre>
3610 *
3611 * where #arr, #len, and #i are freshly named synthetic local variables.
3612 */
3613 private void visitArrayForeachLoop(JCEnhancedForLoop tree) {
3614 make_at(tree.expr.pos());
3615 VarSymbol arraycache = new VarSymbol(SYNTHETIC,
3616 names.fromString("arr" + target.syntheticNameChar()),
3617 tree.expr.type,
3618 currentMethodSym);
3619 JCStatement arraycachedef = make.VarDef(arraycache, tree.expr);
3620 VarSymbol lencache = new VarSymbol(SYNTHETIC,
3621 names.fromString("len" + target.syntheticNameChar()),
3622 syms.intType,
3623 currentMethodSym);
3624 JCStatement lencachedef = make.
3625 VarDef(lencache, make.Select(make.Ident(arraycache), syms.lengthVar));
3626 VarSymbol index = new VarSymbol(SYNTHETIC,
3627 names.fromString("i" + target.syntheticNameChar()),
3628 syms.intType,
3629 currentMethodSym);
3630
3631 JCVariableDecl indexdef = make.VarDef(index, make.Literal(INT, 0));
3632 indexdef.init.type = indexdef.type = syms.intType.constType(0);
3633
3634 List<JCStatement> loopinit = List.of(arraycachedef, lencachedef, indexdef);
3635 JCBinary cond = makeBinary(LT, make.Ident(index), make.Ident(lencache));
3636
3637 JCExpressionStatement step = make.Exec(makeUnary(PREINC, make.Ident(index)));
3638
3639 Type elemtype = types.elemtype(tree.expr.type);
3640 JCExpression loopvarinit = make.Indexed(make.Ident(arraycache),
3641 make.Ident(index)).setType(elemtype);
3642 JCVariableDecl loopvardef = (JCVariableDecl)make.VarDef(tree.var.mods,
3643 tree.var.name,
3644 tree.var.vartype,
3645 loopvarinit).setType(tree.var.type);
3646 loopvardef.sym = tree.var.sym;
3647 JCBlock body = make.
3648 Block(0, List.of(loopvardef, tree.body));
3649
3650 result = translate(make.
3651 ForLoop(loopinit,
3652 cond,
3653 List.of(step),
3654 body));
3655 patchTargets(body, tree, result);
3656 }
3657 /** Patch up break and continue targets. */
3658 private void patchTargets(JCTree body, final JCTree src, final JCTree dest) {
3659 class Patcher extends TreeScanner {
3660 public void visitBreak(JCBreak tree) {
3661 if (tree.target == src)
3662 tree.target = dest;
3663 }
3664 public void visitYield(JCYield tree) {
3665 if (tree.target == src)
3666 tree.target = dest;
3667 scan(tree.value);
3668 }
3669 public void visitContinue(JCContinue tree) {
3670 if (tree.target == src)
3671 tree.target = dest;
3672 }
3673 public void visitClassDef(JCClassDecl tree) {}
3674 }
3675 new Patcher().scan(body);
3676 }
3677 /**
3678 * A statement of the form
3679 *
3680 * <pre>
3681 * for ( T v : coll ) stmt ;
3682 * </pre>
3683 *
3684 * (where coll implements {@code Iterable<? extends T>}) gets translated to
3685 *
3686 * <pre>{@code
3687 * for ( Iterator<? extends T> #i = coll.iterator(); #i.hasNext(); ) {
3688 * T v = (T) #i.next();
3689 * stmt;
3690 * }
3691 * }</pre>
3692 *
3693 * where #i is a freshly named synthetic local variable.
3694 */
3695 private void visitIterableForeachLoop(JCEnhancedForLoop tree) {
3696 make_at(tree.expr.pos());
3697 Type iteratorTarget = syms.objectType;
3698 Type iterableType = types.asSuper(types.cvarUpperBound(tree.expr.type),
3699 syms.iterableType.tsym);
3700 if (iterableType.getTypeArguments().nonEmpty())
3701 iteratorTarget = types.erasure(iterableType.getTypeArguments().head);
3702 tree.expr.type = types.erasure(types.skipTypeVars(tree.expr.type, false));
3703 tree.expr = transTypes.coerce(attrEnv, tree.expr, types.erasure(iterableType));
3704 Symbol iterator = lookupMethod(tree.expr.pos(),
3705 names.iterator,
3706 tree.expr.type,
3707 List.nil());
3708 Assert.check(types.isSameType(types.erasure(types.asSuper(iterator.type.getReturnType(), syms.iteratorType.tsym)), types.erasure(syms.iteratorType)));
3709 VarSymbol itvar = new VarSymbol(SYNTHETIC, names.fromString("i" + target.syntheticNameChar()),
3710 types.erasure(syms.iteratorType),
3711 currentMethodSym);
3712
3713 JCStatement init = make.
3714 VarDef(itvar, make.App(make.Select(tree.expr, iterator)
3715 .setType(types.erasure(iterator.type))));
3716
3717 Symbol hasNext = lookupMethod(tree.expr.pos(),
3718 names.hasNext,
3719 itvar.type,
3720 List.nil());
3721 JCMethodInvocation cond = make.App(make.Select(make.Ident(itvar), hasNext));
3722 Symbol next = lookupMethod(tree.expr.pos(),
3723 names.next,
3724 itvar.type,
3725 List.nil());
3726 JCExpression vardefinit = make.App(make.Select(make.Ident(itvar), next));
3727 if (tree.var.type.isPrimitive())
3728 vardefinit = make.TypeCast(types.cvarUpperBound(iteratorTarget), vardefinit);
3729 else
3730 vardefinit = make.TypeCast(tree.var.type, vardefinit);
3731 JCVariableDecl indexDef = (JCVariableDecl)make.VarDef(tree.var.mods,
3732 tree.var.name,
3733 tree.var.vartype,
3734 vardefinit).setType(tree.var.type);
3735 indexDef.sym = tree.var.sym;
3736 JCBlock body = make.Block(0, List.of(indexDef, tree.body));
3737 body.bracePos = TreeInfo.endPos(tree.body);
3738 result = translate(make.
3739 ForLoop(List.of(init),
3740 cond,
3741 List.nil(),
3742 body));
3743 patchTargets(body, tree, result);
3744 }
3745
3746 public void visitVarDef(JCVariableDecl tree) {
3747 MethodSymbol oldMethodSym = currentMethodSym;
3748 int prevVariableIndex = variableIndex;
3749 tree.mods = translate(tree.mods);
3750 tree.vartype = translate(tree.vartype);
3751 if (currentMethodSym == null) {
3752 // A class or instance field initializer.
3753 currentMethodSym =
3754 new MethodSymbol((tree.mods.flags&STATIC) | BLOCK,
3755 names.empty, null,
3756 currentClass);
3757 }
3758 try {
3759 if (tree.init != null) tree.init = translate(tree.init, tree.type);
3760 result = tree;
3761 } finally {
3762 currentMethodSym = oldMethodSym;
3763 variableIndex = prevVariableIndex;
3764 }
3765 }
3766
3767 public void visitBlock(JCBlock tree) {
3768 MethodSymbol oldMethodSym = currentMethodSym;
3769 if (currentMethodSym == null) {
3770 // Block is a static or instance initializer.
3771 currentMethodSym =
3772 new MethodSymbol(tree.flags | BLOCK,
3773 names.empty, null,
3774 currentClass);
3775 }
3776 int prevVariableIndex = variableIndex;
3777 try {
3778 variableIndex = 0;
3779 super.visitBlock(tree);
3780 } finally {
3781 currentMethodSym = oldMethodSym;
3782 variableIndex = prevVariableIndex;
3783 }
3784 }
3785
3786 public void visitDoLoop(JCDoWhileLoop tree) {
3787 tree.body = translate(tree.body);
3788 tree.cond = translate(tree.cond, syms.booleanType);
3789 result = tree;
3790 }
3791
3792 public void visitWhileLoop(JCWhileLoop tree) {
3793 tree.cond = translate(tree.cond, syms.booleanType);
3794 tree.body = translate(tree.body);
3795 result = tree;
3796 }
3797
3798 public void visitForLoop(JCForLoop tree) {
3799 tree.init = translate(tree.init);
3800 if (tree.cond != null)
3801 tree.cond = translate(tree.cond, syms.booleanType);
3802 tree.step = translate(tree.step);
3803 tree.body = translate(tree.body);
3804 result = tree;
3805 }
3806
3807 public void visitReturn(JCReturn tree) {
3808 if (tree.expr != null)
3809 tree.expr = translate(tree.expr,
3810 currentRestype);
3811 result = tree;
3812 }
3813
3814 @Override
3815 public void visitLambda(JCLambda tree) {
3816 Type prevRestype = currentRestype;
3817 try {
3818 currentRestype = types.erasure(tree.getDescriptorType(types)).getReturnType();
3819 // represent void results as NO_TYPE, to avoid unnecessary boxing in boxIfNeeded
3820 if (currentRestype.hasTag(VOID))
3821 currentRestype = Type.noType;
3822 tree.body = tree.getBodyKind() == BodyKind.EXPRESSION ?
3823 translate((JCExpression) tree.body, currentRestype) :
3824 translate(tree.body);
3825 } finally {
3826 currentRestype = prevRestype;
3827 }
3828 result = tree;
3829 }
3830
3831 public void visitSwitch(JCSwitch tree) {
3832 List<JCCase> cases = tree.patternSwitch ? addDefaultIfNeeded(tree.patternSwitch,
3833 tree.wasEnumSelector,
3834 tree.cases)
3835 : tree.cases;
3836 handleSwitch(tree, tree.selector, cases);
3837 }
3838
3839 @Override
3840 public void visitSwitchExpression(JCSwitchExpression tree) {
3841 List<JCCase> cases = addDefaultIfNeeded(tree.patternSwitch, tree.wasEnumSelector, tree.cases);
3842 handleSwitch(tree, tree.selector, cases);
3843 }
3844
3845 private List<JCCase> addDefaultIfNeeded(boolean patternSwitch, boolean wasEnumSelector,
3846 List<JCCase> cases) {
3847 if (cases.stream().flatMap(c -> c.labels.stream()).noneMatch(p -> p.hasTag(Tag.DEFAULTCASELABEL))) {
3848 boolean matchException = useMatchException;
3849 matchException |= patternSwitch && !wasEnumSelector;
3850 Type exception = matchException ? syms.matchExceptionType
3851 : syms.incompatibleClassChangeErrorType;
3852 List<JCExpression> params = matchException ? List.of(makeNull(), makeNull())
3853 : List.nil();
3854 JCThrow thr = make.Throw(makeNewClass(exception, params));
3855 JCCase c = make.Case(JCCase.STATEMENT, List.of(make.DefaultCaseLabel()), null, List.of(thr), null);
3856 cases = cases.prepend(c);
3857 }
3858
3859 return cases;
3860 }
3861
3862 private void handleSwitch(JCTree tree, JCExpression selector, List<JCCase> cases) {
3863 //expand multiple label cases:
3864 ListBuffer<JCCase> convertedCases = new ListBuffer<>();
3865
3866 for (JCCase c : cases) {
3867 switch (c.labels.size()) {
3868 case 0: //default
3869 case 1: //single label
3870 convertedCases.append(c);
3871 break;
3872 default: //multiple labels, expand:
3873 //case C1, C2, C3: ...
3874 //=>
3875 //case C1:
3876 //case C2:
3877 //case C3: ...
3878 List<JCCaseLabel> patterns = c.labels;
3879 while (patterns.tail.nonEmpty()) {
3880 convertedCases.append(make_at(c.pos()).Case(JCCase.STATEMENT,
3881 List.of(patterns.head),
3882 null,
3883 List.nil(),
3884 null));
3885 patterns = patterns.tail;
3886 }
3887 c.labels = patterns;
3888 convertedCases.append(c);
3889 break;
3890 }
3891 }
3892
3893 for (JCCase c : convertedCases) {
3894 if (c.caseKind == JCCase.RULE && c.completesNormally) {
3895 JCBreak b = make.at(TreeInfo.endPos(c.stats.last())).Break(null);
3896 b.target = tree;
3897 c.stats = c.stats.append(b);
3898 }
3899 }
3900
3901 cases = convertedCases.toList();
3902
3903 Type selsuper = types.supertype(selector.type);
3904 boolean enumSwitch = selsuper != null &&
3905 (selector.type.tsym.flags() & ENUM) != 0;
3906 boolean stringSwitch = selsuper != null &&
3907 types.isSameType(selector.type, syms.stringType);
3908 boolean boxedSwitch = !enumSwitch && !stringSwitch && !selector.type.isPrimitive();
3909 selector = translate(selector, selector.type);
3910 cases = translateCases(cases);
3911 if (tree.hasTag(SWITCH)) {
3912 ((JCSwitch) tree).selector = selector;
3913 ((JCSwitch) tree).cases = cases;
3914 } else if (tree.hasTag(SWITCH_EXPRESSION)) {
3915 ((JCSwitchExpression) tree).selector = selector;
3916 ((JCSwitchExpression) tree).cases = cases;
3917 } else {
3918 Assert.error();
3919 }
3920 if (enumSwitch) {
3921 result = visitEnumSwitch(tree, selector, cases);
3922 } else if (stringSwitch) {
3923 result = visitStringSwitch(tree, selector, cases);
3924 } else if (boxedSwitch) {
3925 //An switch over boxed primitive. Pattern matching switches are already translated
3926 //by TransPatterns, so all non-primitive types are only boxed primitives:
3927 result = visitBoxedPrimitiveSwitch(tree, selector, cases);
3928 } else {
3929 result = tree;
3930 }
3931 }
3932
3933 public JCTree visitEnumSwitch(JCTree tree, JCExpression selector, List<JCCase> cases) {
3934 TypeSymbol enumSym = selector.type.tsym;
3935 EnumMapping map = mapForEnum(tree.pos(), enumSym);
3936 make_at(tree.pos());
3937 Symbol ordinalMethod = lookupMethod(tree.pos(),
3938 names.ordinal,
3939 selector.type,
3940 List.nil());
3941 JCExpression newSelector;
3942
3943 if (cases.stream().anyMatch(c -> TreeInfo.isNullCaseLabel(c.labels.head))) {
3944 //for enum switches with case null, do:
3945 //switch ($selector != null ? $mapVar[$selector.ordinal()] : -1) {...}
3946 //replacing case null with case -1:
3947 VarSymbol dollar_s = new VarSymbol(FINAL|SYNTHETIC,
3948 names.fromString("s" + variableIndex++ + this.target.syntheticNameChar()),
3949 selector.type,
3950 currentMethodSym);
3951 JCStatement var = make.at(tree.pos()).VarDef(dollar_s, selector).setType(dollar_s.type);
3952 newSelector = map.switchValue(
3953 make.App(make.Select(make.Ident(dollar_s),
3954 ordinalMethod)));
3955 newSelector =
3956 make.LetExpr(List.of(var),
3957 make.Conditional(makeBinary(NE, make.Ident(dollar_s), makeNull()),
3958 newSelector,
3959 makeLit(syms.intType, -1))
3960 .setType(newSelector.type))
3961 .setType(newSelector.type);
3962 } else {
3963 newSelector = map.switchValue(
3964 make.App(make.Select(selector,
3965 ordinalMethod)));
3966 }
3967 ListBuffer<JCCase> newCases = new ListBuffer<>();
3968 for (JCCase c : cases) {
3969 if (c.labels.head.hasTag(CONSTANTCASELABEL)) {
3970 JCExpression pat;
3971 if (TreeInfo.isNullCaseLabel(c.labels.head)) {
3972 pat = makeLit(syms.intType, -1);
3973 } else {
3974 VarSymbol label = (VarSymbol)TreeInfo.symbol(((JCConstantCaseLabel) c.labels.head).expr);
3975 pat = map.caseValue(label);
3976 }
3977 newCases.append(make.Case(JCCase.STATEMENT, List.of(make.ConstantCaseLabel(pat)), null, c.stats, null));
3978 } else {
3979 newCases.append(c);
3980 }
3981 }
3982 JCTree enumSwitch;
3983 if (tree.hasTag(SWITCH)) {
3984 enumSwitch = make.Switch(newSelector, newCases.toList());
3985 } else if (tree.hasTag(SWITCH_EXPRESSION)) {
3986 enumSwitch = make.SwitchExpression(newSelector, newCases.toList());
3987 enumSwitch.setType(tree.type);
3988 } else {
3989 Assert.error();
3990 throw new AssertionError();
3991 }
3992 patchTargets(enumSwitch, tree, enumSwitch);
3993 return enumSwitch;
3994 }
3995
3996 public JCTree visitStringSwitch(JCTree tree, JCExpression selector, List<JCCase> caseList) {
3997 int alternatives = caseList.size();
3998
3999 if (alternatives == 0) { // Strange but legal possibility (only legal for switch statement)
4000 return make.at(tree.pos()).Exec(attr.makeNullCheck(selector));
4001 } else {
4002 /*
4003 * The general approach used is to translate a single
4004 * string switch statement into a series of two chained
4005 * switch statements: the first a synthesized statement
4006 * switching on the argument string's hash value and
4007 * computing a string's position in the list of original
4008 * case labels, if any, followed by a second switch on the
4009 * computed integer value. The second switch has the same
4010 * code structure as the original string switch statement
4011 * except that the string case labels are replaced with
4012 * positional integer constants starting at 0.
4013 *
4014 * The first switch statement can be thought of as an
4015 * inlined map from strings to their position in the case
4016 * label list. An alternate implementation would use an
4017 * actual Map for this purpose, as done for enum switches.
4018 *
4019 * With some additional effort, it would be possible to
4020 * use a single switch statement on the hash code of the
4021 * argument, but care would need to be taken to preserve
4022 * the proper control flow in the presence of hash
4023 * collisions and other complications, such as
4024 * fallthroughs. Switch statements with one or two
4025 * alternatives could also be specially translated into
4026 * if-then statements to omit the computation of the hash
4027 * code.
4028 *
4029 * The generated code assumes that the hashing algorithm
4030 * of String is the same in the compilation environment as
4031 * in the environment the code will run in. The string
4032 * hashing algorithm in the SE JDK has been unchanged
4033 * since at least JDK 1.2. Since the algorithm has been
4034 * specified since that release as well, it is very
4035 * unlikely to be changed in the future.
4036 *
4037 * Different hashing algorithms, such as the length of the
4038 * strings or a perfect hashing algorithm over the
4039 * particular set of case labels, could potentially be
4040 * used instead of String.hashCode.
4041 */
4042
4043 ListBuffer<JCStatement> stmtList = new ListBuffer<>();
4044
4045 // Map from String case labels to their original position in
4046 // the list of case labels.
4047 Map<String, Integer> caseLabelToPosition = new LinkedHashMap<>(alternatives + 1, 1.0f);
4048
4049 // Map of hash codes to the string case labels having that hashCode.
4050 Map<Integer, Set<String>> hashToString = new LinkedHashMap<>(alternatives + 1, 1.0f);
4051
4052 int casePosition = 0;
4053 JCCase nullCase = null;
4054 int nullCaseLabel = -1;
4055
4056 for(JCCase oneCase : caseList) {
4057 if (oneCase.labels.head.hasTag(CONSTANTCASELABEL)) {
4058 if (TreeInfo.isNullCaseLabel(oneCase.labels.head)) {
4059 nullCase = oneCase;
4060 nullCaseLabel = casePosition;
4061 } else {
4062 JCExpression expression = ((JCConstantCaseLabel) oneCase.labels.head).expr;
4063 String labelExpr = (String) expression.type.constValue();
4064 Integer mapping = caseLabelToPosition.put(labelExpr, casePosition);
4065 Assert.checkNull(mapping);
4066 int hashCode = labelExpr.hashCode();
4067
4068 Set<String> stringSet = hashToString.get(hashCode);
4069 if (stringSet == null) {
4070 stringSet = new LinkedHashSet<>(1, 1.0f);
4071 stringSet.add(labelExpr);
4072 hashToString.put(hashCode, stringSet);
4073 } else {
4074 boolean added = stringSet.add(labelExpr);
4075 Assert.check(added);
4076 }
4077 }
4078 }
4079 casePosition++;
4080 }
4081
4082 // Synthesize a switch statement that has the effect of
4083 // mapping from a string to the integer position of that
4084 // string in the list of case labels. This is done by
4085 // switching on the hashCode of the string followed by an
4086 // if-then-else chain comparing the input for equality
4087 // with all the case labels having that hash value.
4088
4089 /*
4090 * s$ = top of stack;
4091 * tmp$ = -1;
4092 * switch($s.hashCode()) {
4093 * case caseLabel.hashCode:
4094 * if (s$.equals("caseLabel_1")
4095 * tmp$ = caseLabelToPosition("caseLabel_1");
4096 * else if (s$.equals("caseLabel_2"))
4097 * tmp$ = caseLabelToPosition("caseLabel_2");
4098 * ...
4099 * break;
4100 * ...
4101 * }
4102 */
4103
4104 VarSymbol dollar_s = new VarSymbol(FINAL|SYNTHETIC,
4105 names.fromString("s" + variableIndex++ + target.syntheticNameChar()),
4106 syms.stringType,
4107 currentMethodSym);
4108 stmtList.append(make.at(tree.pos()).VarDef(dollar_s, selector).setType(dollar_s.type));
4109
4110 VarSymbol dollar_tmp = new VarSymbol(SYNTHETIC,
4111 names.fromString("tmp" + variableIndex++ + target.syntheticNameChar()),
4112 syms.intType,
4113 currentMethodSym);
4114 JCVariableDecl dollar_tmp_def =
4115 (JCVariableDecl)make.VarDef(dollar_tmp, make.Literal(INT, -1)).setType(dollar_tmp.type);
4116 dollar_tmp_def.init.type = dollar_tmp.type = syms.intType;
4117 stmtList.append(dollar_tmp_def);
4118 ListBuffer<JCCase> caseBuffer = new ListBuffer<>();
4119 // hashCode will trigger nullcheck on original switch expression
4120 JCMethodInvocation hashCodeCall = makeCall(make.Ident(dollar_s),
4121 names.hashCode,
4122 List.nil()).setType(syms.intType);
4123 JCSwitch switch1 = make.Switch(hashCodeCall,
4124 caseBuffer.toList());
4125 for(Map.Entry<Integer, Set<String>> entry : hashToString.entrySet()) {
4126 int hashCode = entry.getKey();
4127 Set<String> stringsWithHashCode = entry.getValue();
4128 Assert.check(stringsWithHashCode.size() >= 1);
4129
4130 JCStatement elsepart = null;
4131 for(String caseLabel : stringsWithHashCode ) {
4132 JCMethodInvocation stringEqualsCall = makeCall(make.Ident(dollar_s),
4133 names.equals,
4134 List.of(make.Literal(caseLabel)));
4135 elsepart = make.If(stringEqualsCall,
4136 make.Exec(make.Assign(make.Ident(dollar_tmp),
4137 make.Literal(caseLabelToPosition.get(caseLabel))).
4138 setType(dollar_tmp.type)),
4139 elsepart);
4140 }
4141
4142 ListBuffer<JCStatement> lb = new ListBuffer<>();
4143 JCBreak breakStmt = make.Break(null);
4144 breakStmt.target = switch1;
4145 lb.append(elsepart).append(breakStmt);
4146
4147 caseBuffer.append(make.Case(JCCase.STATEMENT,
4148 List.of(make.ConstantCaseLabel(make.Literal(hashCode))),
4149 null,
4150 lb.toList(),
4151 null));
4152 }
4153
4154 switch1.cases = caseBuffer.toList();
4155
4156 if (nullCase != null) {
4157 stmtList.append(make.If(makeBinary(NE, make.Ident(dollar_s), makeNull()), switch1, make.Exec(make.Assign(make.Ident(dollar_tmp),
4158 make.Literal(nullCaseLabel)).
4159 setType(dollar_tmp.type))).setType(syms.intType));
4160 } else {
4161 stmtList.append(switch1);
4162 }
4163
4164 // Make isomorphic switch tree replacing string labels
4165 // with corresponding integer ones from the label to
4166 // position map.
4167
4168 ListBuffer<JCCase> lb = new ListBuffer<>();
4169 for(JCCase oneCase : caseList ) {
4170 boolean isDefault = !oneCase.labels.head.hasTag(CONSTANTCASELABEL);
4171 JCExpression caseExpr;
4172 if (isDefault)
4173 caseExpr = null;
4174 else if (oneCase == nullCase) {
4175 caseExpr = make.Literal(nullCaseLabel);
4176 } else {
4177 JCExpression expression = ((JCConstantCaseLabel) oneCase.labels.head).expr;
4178 String name = (String) TreeInfo.skipParens(expression)
4179 .type.constValue();
4180 caseExpr = make.Literal(caseLabelToPosition.get(name));
4181 }
4182
4183 lb.append(make.Case(JCCase.STATEMENT, caseExpr == null ? List.of(make.DefaultCaseLabel())
4184 : List.of(make.ConstantCaseLabel(caseExpr)),
4185 null,
4186 oneCase.stats, null));
4187 }
4188
4189 if (tree.hasTag(SWITCH)) {
4190 JCSwitch switch2 = make.Switch(make.Ident(dollar_tmp), lb.toList());
4191 // Rewire up old unlabeled break statements to the
4192 // replacement switch being created.
4193 patchTargets(switch2, tree, switch2);
4194
4195 stmtList.append(switch2);
4196
4197 JCBlock res = make.Block(0L, stmtList.toList());
4198 res.bracePos = TreeInfo.endPos(tree);
4199 return res;
4200 } else {
4201 JCSwitchExpression switch2 = make.SwitchExpression(make.Ident(dollar_tmp), lb.toList());
4202
4203 // Rewire up old unlabeled break statements to the
4204 // replacement switch being created.
4205 patchTargets(switch2, tree, switch2);
4206
4207 switch2.setType(tree.type);
4208
4209 LetExpr res = make.LetExpr(stmtList.toList(), switch2);
4210
4211 res.needsCond = true;
4212 res.setType(tree.type);
4213
4214 return res;
4215 }
4216 }
4217 }
4218
4219 private JCTree visitBoxedPrimitiveSwitch(JCTree tree, JCExpression selector, List<JCCase> cases) {
4220 JCExpression newSelector;
4221
4222 if (cases.stream().anyMatch(c -> TreeInfo.isNullCaseLabel(c.labels.head))) {
4223 //a switch over a boxed primitive, with a null case. Pick two constants that are
4224 //not used by any branch in the case (c1 and c2), close to other constants that are
4225 //used in the switch. Then do:
4226 //switch ($selector != null ? $selector != c1 ? $selector : c2 : c1) {...}
4227 //replacing case null with case c1
4228 Set<Integer> constants = new LinkedHashSet<>();
4229 JCCase nullCase = null;
4230
4231 for (JCCase c : cases) {
4232 if (TreeInfo.isNullCaseLabel(c.labels.head)) {
4233 nullCase = c;
4234 } else if (!c.labels.head.hasTag(DEFAULTCASELABEL)) {
4235 constants.add((int) ((JCConstantCaseLabel) c.labels.head).expr.type.constValue());
4236 }
4237 }
4238
4239 Assert.checkNonNull(nullCase);
4240
4241 int nullValue = constants.isEmpty() ? 0 : constants.iterator().next();
4242
4243 while (constants.contains(nullValue)) nullValue++;
4244
4245 constants.add(nullValue);
4246 nullCase.labels.head = make.ConstantCaseLabel(makeLit(syms.intType, nullValue));
4247
4248 int replacementValue = nullValue;
4249
4250 while (constants.contains(replacementValue)) replacementValue++;
4251
4252 VarSymbol dollar_s = new VarSymbol(FINAL|SYNTHETIC,
4253 names.fromString("s" + variableIndex++ + this.target.syntheticNameChar()),
4254 selector.type,
4255 currentMethodSym);
4256 JCStatement var = make.at(tree.pos()).VarDef(dollar_s, selector).setType(dollar_s.type);
4257 JCExpression nullValueReplacement =
4258 make.Conditional(makeBinary(NE,
4259 unbox(make.Ident(dollar_s), syms.intType),
4260 makeLit(syms.intType, nullValue)),
4261 unbox(make.Ident(dollar_s), syms.intType),
4262 makeLit(syms.intType, replacementValue))
4263 .setType(syms.intType);
4264 JCExpression nullCheck =
4265 make.Conditional(makeBinary(NE, make.Ident(dollar_s), makeNull()),
4266 nullValueReplacement,
4267 makeLit(syms.intType, nullValue))
4268 .setType(syms.intType);
4269 newSelector = make.LetExpr(List.of(var), nullCheck).setType(syms.intType);
4270 } else {
4271 newSelector = unbox(selector, syms.intType);
4272 }
4273
4274 if (tree.hasTag(SWITCH)) {
4275 ((JCSwitch) tree).selector = newSelector;
4276 } else {
4277 ((JCSwitchExpression) tree).selector = newSelector;
4278 }
4279
4280 return tree;
4281 }
4282
4283 @Override
4284 public void visitBreak(JCBreak tree) {
4285 result = tree;
4286 }
4287
4288 @Override
4289 public void visitYield(JCYield tree) {
4290 tree.value = translate(tree.value, tree.target.type);
4291 result = tree;
4292 }
4293
4294 public void visitNewArray(JCNewArray tree) {
4295 tree.elemtype = translate(tree.elemtype);
4296 for (List<JCExpression> t = tree.dims; t.tail != null; t = t.tail)
4297 if (t.head != null) t.head = translate(t.head, syms.intType);
4298 tree.elems = translate(tree.elems, types.elemtype(tree.type));
4299 result = tree;
4300 }
4301
4302 public void visitSelect(JCFieldAccess tree) {
4303 // need to special case-access of the form C.super.x
4304 // these will always need an access method, unless C
4305 // is a default interface subclassed by the current class.
4306 boolean qualifiedSuperAccess =
4307 tree.selected.hasTag(SELECT) &&
4308 TreeInfo.name(tree.selected) == names._super &&
4309 !types.isDirectSuperInterface(((JCFieldAccess)tree.selected).selected.type.tsym, currentClass);
4310 tree.selected = translate(tree.selected);
4311 if (tree.name == names._class && tree.selected.type.isPrimitiveOrVoid()) {
4312 result = classOf(tree.selected);
4313 }
4314 else if (tree.name == names._super &&
4315 types.isDirectSuperInterface(tree.selected.type.tsym, currentClass)) {
4316 //default super call!! Not a classic qualified super call
4317 TypeSymbol supSym = tree.selected.type.tsym;
4318 Assert.checkNonNull(types.asSuper(currentClass.type, supSym));
4319 result = tree;
4320 }
4321 else if (tree.name == names._this || tree.name == names._super) {
4322 result = makeThis(tree.pos(), tree.selected.type.tsym);
4323 }
4324 else
4325 result = access(tree.sym, tree, enclOp, qualifiedSuperAccess);
4326 }
4327
4328 public void visitLetExpr(LetExpr tree) {
4329 tree.defs = translate(tree.defs);
4330 tree.expr = translate(tree.expr, tree.type);
4331 result = tree;
4332 }
4333
4334 // There ought to be nothing to rewrite here;
4335 // we don't generate code.
4336 public void visitAnnotation(JCAnnotation tree) {
4337 result = tree;
4338 }
4339
4340 @Override
4341 public void visitTry(JCTry tree) {
4342 if (tree.resources.nonEmpty()) {
4343 result = makeTwrTry(tree);
4344 return;
4345 }
4346
4347 boolean hasBody = tree.body.getStatements().nonEmpty();
4348 boolean hasCatchers = tree.catchers.nonEmpty();
4349 boolean hasFinally = tree.finalizer != null &&
4350 tree.finalizer.getStatements().nonEmpty();
4351
4352 if (!hasCatchers && !hasFinally) {
4353 result = translate(tree.body);
4354 return;
4355 }
4356
4357 if (!hasBody) {
4358 if (hasFinally) {
4359 result = translate(tree.finalizer);
4360 } else {
4361 result = translate(tree.body);
4362 }
4363 return;
4364 }
4365
4366 // no optimizations possible
4367 super.visitTry(tree);
4368 }
4369
4370 /* ************************************************************************
4371 * main method
4372 *************************************************************************/
4373
4374 /** Translate a toplevel class and return a list consisting of
4375 * the translated class and translated versions of all inner classes.
4376 * @param env The attribution environment current at the class definition.
4377 * We need this for resolving some additional symbols.
4378 * @param cdef The tree representing the class definition.
4379 */
4380 public List<JCTree> translateTopLevelClass(Env<AttrContext> env, JCTree cdef, TreeMaker make) {
4381 ListBuffer<JCTree> translated = null;
4382 try {
4383 attrEnv = env;
4384 this.make = make;
4385 endPosTable = env.toplevel.endPositions;
4386 currentClass = null;
4387 currentRestype = null;
4388 currentMethodDef = null;
4389 outermostClassDef = (cdef.hasTag(CLASSDEF)) ? (JCClassDecl)cdef : null;
4390 outermostMemberDef = null;
4391 this.translated = new ListBuffer<>();
4392 classdefs = new HashMap<>();
4393 actualSymbols = new HashMap<>();
4394 freevarCache = new HashMap<>();
4395 proxies = new HashMap<>();
4396 twrVars = WriteableScope.create(syms.noSymbol);
4397 outerThisStack = List.nil();
4398 accessNums = new HashMap<>();
4399 accessSyms = new HashMap<>();
4400 accessConstrs = new HashMap<>();
4401 accessConstrTags = List.nil();
4402 accessed = new ListBuffer<>();
4403 translate(cdef, (JCExpression)null);
4404 for (List<Symbol> l = accessed.toList(); l.nonEmpty(); l = l.tail)
4405 makeAccessible(l.head);
4406 for (EnumMapping map : enumSwitchMap.values())
4407 map.translate();
4408 checkConflicts(this.translated.toList());
4409 checkAccessConstructorTags();
4410 translated = this.translated;
4411 } finally {
4412 // note that recursive invocations of this method fail hard
4413 attrEnv = null;
4414 this.make = null;
4415 endPosTable = null;
4416 currentClass = null;
4417 currentRestype = null;
4418 currentMethodDef = null;
4419 outermostClassDef = null;
4420 outermostMemberDef = null;
4421 this.translated = null;
4422 classdefs = null;
4423 actualSymbols = null;
4424 freevarCache = null;
4425 proxies = null;
4426 outerThisStack = null;
4427 accessNums = null;
4428 accessSyms = null;
4429 accessConstrs = null;
4430 accessConstrTags = null;
4431 accessed = null;
4432 enumSwitchMap.clear();
4433 assertionsDisabledClassCache = null;
4434 }
4435 return translated.toList();
4436 }
4437
4438 // needed for the lambda deserialization method, which is expressed as a big switch on strings
4439 public JCMethodDecl translateMethod(Env<AttrContext> env, JCMethodDecl methodDecl, TreeMaker make) {
4440 try {
4441 this.attrEnv = env;
4442 this.make = make;
4443 this.currentClass = methodDecl.sym.enclClass();
4444 proxies = new HashMap<>();
4445 return translate(methodDecl);
4446 } finally {
4447 this.attrEnv = null;
4448 this.make = null;
4449 this.currentClass = null;
4450 // the two fields below are set when visiting the method
4451 this.currentMethodSym = null;
4452 this.currentMethodDef = null;
4453 this.proxies = null;
4454 }
4455 }
4456 }