Sun, 17 Feb 2013 16:44:55 -0500
Merge
1 /*
2 * Copyright (c) 1999, 2013, 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 */
26 package com.sun.tools.javac.comp;
28 import java.util.*;
30 import com.sun.tools.javac.code.*;
31 import com.sun.tools.javac.jvm.*;
32 import com.sun.tools.javac.main.Option.PkgInfo;
33 import com.sun.tools.javac.tree.*;
34 import com.sun.tools.javac.util.*;
35 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
36 import com.sun.tools.javac.util.List;
38 import com.sun.tools.javac.code.Symbol.*;
39 import com.sun.tools.javac.tree.JCTree.*;
40 import com.sun.tools.javac.code.Type.*;
42 import com.sun.tools.javac.jvm.Target;
43 import com.sun.tools.javac.tree.EndPosTable;
45 import static com.sun.tools.javac.code.Flags.*;
46 import static com.sun.tools.javac.code.Flags.BLOCK;
47 import static com.sun.tools.javac.code.Kinds.*;
48 import static com.sun.tools.javac.code.TypeTag.*;
49 import static com.sun.tools.javac.jvm.ByteCodes.*;
50 import static com.sun.tools.javac.tree.JCTree.Tag.*;
52 /** This pass translates away some syntactic sugar: inner classes,
53 * class literals, assertions, foreach loops, etc.
54 *
55 * <p><b>This is NOT part of any supported API.
56 * If you write code that depends on this, you do so at your own risk.
57 * This code and its internal interfaces are subject to change or
58 * deletion without notice.</b>
59 */
60 public class Lower extends TreeTranslator {
61 protected static final Context.Key<Lower> lowerKey =
62 new Context.Key<Lower>();
64 public static Lower instance(Context context) {
65 Lower instance = context.get(lowerKey);
66 if (instance == null)
67 instance = new Lower(context);
68 return instance;
69 }
71 private Names names;
72 private Log log;
73 private Symtab syms;
74 private Resolve rs;
75 private Check chk;
76 private Attr attr;
77 private TreeMaker make;
78 private DiagnosticPosition make_pos;
79 private ClassWriter writer;
80 private ClassReader reader;
81 private ConstFold cfolder;
82 private Target target;
83 private Source source;
84 private boolean allowEnums;
85 private final Name dollarAssertionsDisabled;
86 private final Name classDollar;
87 private Types types;
88 private boolean debugLower;
89 private PkgInfo pkginfoOpt;
91 protected Lower(Context context) {
92 context.put(lowerKey, this);
93 names = Names.instance(context);
94 log = Log.instance(context);
95 syms = Symtab.instance(context);
96 rs = Resolve.instance(context);
97 chk = Check.instance(context);
98 attr = Attr.instance(context);
99 make = TreeMaker.instance(context);
100 writer = ClassWriter.instance(context);
101 reader = ClassReader.instance(context);
102 cfolder = ConstFold.instance(context);
103 target = Target.instance(context);
104 source = Source.instance(context);
105 allowEnums = source.allowEnums();
106 dollarAssertionsDisabled = names.
107 fromString(target.syntheticNameChar() + "assertionsDisabled");
108 classDollar = names.
109 fromString("class" + target.syntheticNameChar());
111 types = Types.instance(context);
112 Options options = Options.instance(context);
113 debugLower = options.isSet("debuglower");
114 pkginfoOpt = PkgInfo.get(options);
115 }
117 /** The currently enclosing class.
118 */
119 ClassSymbol currentClass;
121 /** A queue of all translated classes.
122 */
123 ListBuffer<JCTree> translated;
125 /** Environment for symbol lookup, set by translateTopLevelClass.
126 */
127 Env<AttrContext> attrEnv;
129 /** A hash table mapping syntax trees to their ending source positions.
130 */
131 EndPosTable endPosTable;
133 /**************************************************************************
134 * Global mappings
135 *************************************************************************/
137 /** A hash table mapping local classes to their definitions.
138 */
139 Map<ClassSymbol, JCClassDecl> classdefs;
141 /** A hash table mapping local classes to a list of pruned trees.
142 */
143 public Map<ClassSymbol, List<JCTree>> prunedTree = new WeakHashMap<ClassSymbol, List<JCTree>>();
145 /** A hash table mapping virtual accessed symbols in outer subclasses
146 * to the actually referred symbol in superclasses.
147 */
148 Map<Symbol,Symbol> actualSymbols;
150 /** The current method definition.
151 */
152 JCMethodDecl currentMethodDef;
154 /** The current method symbol.
155 */
156 MethodSymbol currentMethodSym;
158 /** The currently enclosing outermost class definition.
159 */
160 JCClassDecl outermostClassDef;
162 /** The currently enclosing outermost member definition.
163 */
164 JCTree outermostMemberDef;
166 /** A navigator class for assembling a mapping from local class symbols
167 * to class definition trees.
168 * There is only one case; all other cases simply traverse down the tree.
169 */
170 class ClassMap extends TreeScanner {
172 /** All encountered class defs are entered into classdefs table.
173 */
174 public void visitClassDef(JCClassDecl tree) {
175 classdefs.put(tree.sym, tree);
176 super.visitClassDef(tree);
177 }
178 }
179 ClassMap classMap = new ClassMap();
181 /** Map a class symbol to its definition.
182 * @param c The class symbol of which we want to determine the definition.
183 */
184 JCClassDecl classDef(ClassSymbol c) {
185 // First lookup the class in the classdefs table.
186 JCClassDecl def = classdefs.get(c);
187 if (def == null && outermostMemberDef != null) {
188 // If this fails, traverse outermost member definition, entering all
189 // local classes into classdefs, and try again.
190 classMap.scan(outermostMemberDef);
191 def = classdefs.get(c);
192 }
193 if (def == null) {
194 // If this fails, traverse outermost class definition, entering all
195 // local classes into classdefs, and try again.
196 classMap.scan(outermostClassDef);
197 def = classdefs.get(c);
198 }
199 return def;
200 }
202 /** A hash table mapping class symbols to lists of free variables.
203 * accessed by them. Only free variables of the method immediately containing
204 * a class are associated with that class.
205 */
206 Map<ClassSymbol,List<VarSymbol>> freevarCache;
208 /** A navigator class for collecting the free variables accessed
209 * from a local class.
210 * There is only one case; all other cases simply traverse down the tree.
211 */
212 class FreeVarCollector extends TreeScanner {
214 /** The owner of the local class.
215 */
216 Symbol owner;
218 /** The local class.
219 */
220 ClassSymbol clazz;
222 /** The list of owner's variables accessed from within the local class,
223 * without any duplicates.
224 */
225 List<VarSymbol> fvs;
227 FreeVarCollector(ClassSymbol clazz) {
228 this.clazz = clazz;
229 this.owner = clazz.owner;
230 this.fvs = List.nil();
231 }
233 /** Add free variable to fvs list unless it is already there.
234 */
235 private void addFreeVar(VarSymbol v) {
236 for (List<VarSymbol> l = fvs; l.nonEmpty(); l = l.tail)
237 if (l.head == v) return;
238 fvs = fvs.prepend(v);
239 }
241 /** Add all free variables of class c to fvs list
242 * unless they are already there.
243 */
244 private void addFreeVars(ClassSymbol c) {
245 List<VarSymbol> fvs = freevarCache.get(c);
246 if (fvs != null) {
247 for (List<VarSymbol> l = fvs; l.nonEmpty(); l = l.tail) {
248 addFreeVar(l.head);
249 }
250 }
251 }
253 /** If tree refers to a variable in owner of local class, add it to
254 * free variables list.
255 */
256 public void visitIdent(JCIdent tree) {
257 result = tree;
258 visitSymbol(tree.sym);
259 }
260 // where
261 private void visitSymbol(Symbol _sym) {
262 Symbol sym = _sym;
263 if (sym.kind == VAR || sym.kind == MTH) {
264 while (sym != null && sym.owner != owner)
265 sym = proxies.lookup(proxyName(sym.name)).sym;
266 if (sym != null && sym.owner == owner) {
267 VarSymbol v = (VarSymbol)sym;
268 if (v.getConstValue() == null) {
269 addFreeVar(v);
270 }
271 } else {
272 if (outerThisStack.head != null &&
273 outerThisStack.head != _sym)
274 visitSymbol(outerThisStack.head);
275 }
276 }
277 }
279 /** If tree refers to a class instance creation expression
280 * add all free variables of the freshly created class.
281 */
282 public void visitNewClass(JCNewClass tree) {
283 ClassSymbol c = (ClassSymbol)tree.constructor.owner;
284 addFreeVars(c);
285 if (tree.encl == null &&
286 c.hasOuterInstance() &&
287 outerThisStack.head != null)
288 visitSymbol(outerThisStack.head);
289 super.visitNewClass(tree);
290 }
292 /** If tree refers to a qualified this or super expression
293 * for anything but the current class, add the outer this
294 * stack as a free variable.
295 */
296 public void visitSelect(JCFieldAccess tree) {
297 if ((tree.name == names._this || tree.name == names._super) &&
298 tree.selected.type.tsym != clazz &&
299 outerThisStack.head != null)
300 visitSymbol(outerThisStack.head);
301 super.visitSelect(tree);
302 }
304 /** If tree refers to a superclass constructor call,
305 * add all free variables of the superclass.
306 */
307 public void visitApply(JCMethodInvocation tree) {
308 if (TreeInfo.name(tree.meth) == names._super) {
309 addFreeVars((ClassSymbol) TreeInfo.symbol(tree.meth).owner);
310 Symbol constructor = TreeInfo.symbol(tree.meth);
311 ClassSymbol c = (ClassSymbol)constructor.owner;
312 if (c.hasOuterInstance() &&
313 !tree.meth.hasTag(SELECT) &&
314 outerThisStack.head != null)
315 visitSymbol(outerThisStack.head);
316 }
317 super.visitApply(tree);
318 }
319 }
321 /** Return the variables accessed from within a local class, which
322 * are declared in the local class' owner.
323 * (in reverse order of first access).
324 */
325 List<VarSymbol> freevars(ClassSymbol c) {
326 if ((c.owner.kind & (VAR | MTH)) != 0) {
327 List<VarSymbol> fvs = freevarCache.get(c);
328 if (fvs == null) {
329 FreeVarCollector collector = new FreeVarCollector(c);
330 collector.scan(classDef(c));
331 fvs = collector.fvs;
332 freevarCache.put(c, fvs);
333 }
334 return fvs;
335 } else {
336 return List.nil();
337 }
338 }
340 Map<TypeSymbol,EnumMapping> enumSwitchMap = new LinkedHashMap<TypeSymbol,EnumMapping>();
342 EnumMapping mapForEnum(DiagnosticPosition pos, TypeSymbol enumClass) {
343 EnumMapping map = enumSwitchMap.get(enumClass);
344 if (map == null)
345 enumSwitchMap.put(enumClass, map = new EnumMapping(pos, enumClass));
346 return map;
347 }
349 /** This map gives a translation table to be used for enum
350 * switches.
351 *
352 * <p>For each enum that appears as the type of a switch
353 * expression, we maintain an EnumMapping to assist in the
354 * translation, as exemplified by the following example:
355 *
356 * <p>we translate
357 * <pre>
358 * switch(colorExpression) {
359 * case red: stmt1;
360 * case green: stmt2;
361 * }
362 * </pre>
363 * into
364 * <pre>
365 * switch(Outer$0.$EnumMap$Color[colorExpression.ordinal()]) {
366 * case 1: stmt1;
367 * case 2: stmt2
368 * }
369 * </pre>
370 * with the auxiliary table initialized as follows:
371 * <pre>
372 * class Outer$0 {
373 * synthetic final int[] $EnumMap$Color = new int[Color.values().length];
374 * static {
375 * try { $EnumMap$Color[red.ordinal()] = 1; } catch (NoSuchFieldError ex) {}
376 * try { $EnumMap$Color[green.ordinal()] = 2; } catch (NoSuchFieldError ex) {}
377 * }
378 * }
379 * </pre>
380 * class EnumMapping provides mapping data and support methods for this translation.
381 */
382 class EnumMapping {
383 EnumMapping(DiagnosticPosition pos, TypeSymbol forEnum) {
384 this.forEnum = forEnum;
385 this.values = new LinkedHashMap<VarSymbol,Integer>();
386 this.pos = pos;
387 Name varName = names
388 .fromString(target.syntheticNameChar() +
389 "SwitchMap" +
390 target.syntheticNameChar() +
391 writer.xClassName(forEnum.type).toString()
392 .replace('/', '.')
393 .replace('.', target.syntheticNameChar()));
394 ClassSymbol outerCacheClass = outerCacheClass();
395 this.mapVar = new VarSymbol(STATIC | SYNTHETIC | FINAL,
396 varName,
397 new ArrayType(syms.intType, syms.arrayClass),
398 outerCacheClass);
399 enterSynthetic(pos, mapVar, outerCacheClass.members());
400 }
402 DiagnosticPosition pos = null;
404 // the next value to use
405 int next = 1; // 0 (unused map elements) go to the default label
407 // the enum for which this is a map
408 final TypeSymbol forEnum;
410 // the field containing the map
411 final VarSymbol mapVar;
413 // the mapped values
414 final Map<VarSymbol,Integer> values;
416 JCLiteral forConstant(VarSymbol v) {
417 Integer result = values.get(v);
418 if (result == null)
419 values.put(v, result = next++);
420 return make.Literal(result);
421 }
423 // generate the field initializer for the map
424 void translate() {
425 make.at(pos.getStartPosition());
426 JCClassDecl owner = classDef((ClassSymbol)mapVar.owner);
428 // synthetic static final int[] $SwitchMap$Color = new int[Color.values().length];
429 MethodSymbol valuesMethod = lookupMethod(pos,
430 names.values,
431 forEnum.type,
432 List.<Type>nil());
433 JCExpression size = make // Color.values().length
434 .Select(make.App(make.QualIdent(valuesMethod)),
435 syms.lengthVar);
436 JCExpression mapVarInit = make
437 .NewArray(make.Type(syms.intType), List.of(size), null)
438 .setType(new ArrayType(syms.intType, syms.arrayClass));
440 // try { $SwitchMap$Color[red.ordinal()] = 1; } catch (java.lang.NoSuchFieldError ex) {}
441 ListBuffer<JCStatement> stmts = new ListBuffer<JCStatement>();
442 Symbol ordinalMethod = lookupMethod(pos,
443 names.ordinal,
444 forEnum.type,
445 List.<Type>nil());
446 List<JCCatch> catcher = List.<JCCatch>nil()
447 .prepend(make.Catch(make.VarDef(new VarSymbol(PARAMETER, names.ex,
448 syms.noSuchFieldErrorType,
449 syms.noSymbol),
450 null),
451 make.Block(0, List.<JCStatement>nil())));
452 for (Map.Entry<VarSymbol,Integer> e : values.entrySet()) {
453 VarSymbol enumerator = e.getKey();
454 Integer mappedValue = e.getValue();
455 JCExpression assign = make
456 .Assign(make.Indexed(mapVar,
457 make.App(make.Select(make.QualIdent(enumerator),
458 ordinalMethod))),
459 make.Literal(mappedValue))
460 .setType(syms.intType);
461 JCStatement exec = make.Exec(assign);
462 JCStatement _try = make.Try(make.Block(0, List.of(exec)), catcher, null);
463 stmts.append(_try);
464 }
466 owner.defs = owner.defs
467 .prepend(make.Block(STATIC, stmts.toList()))
468 .prepend(make.VarDef(mapVar, mapVarInit));
469 }
470 }
473 /**************************************************************************
474 * Tree building blocks
475 *************************************************************************/
477 /** Equivalent to make.at(pos.getStartPosition()) with side effect of caching
478 * pos as make_pos, for use in diagnostics.
479 **/
480 TreeMaker make_at(DiagnosticPosition pos) {
481 make_pos = pos;
482 return make.at(pos);
483 }
485 /** Make an attributed tree representing a literal. This will be an
486 * Ident node in the case of boolean literals, a Literal node in all
487 * other cases.
488 * @param type The literal's type.
489 * @param value The literal's value.
490 */
491 JCExpression makeLit(Type type, Object value) {
492 return make.Literal(type.getTag(), value).setType(type.constType(value));
493 }
495 /** Make an attributed tree representing null.
496 */
497 JCExpression makeNull() {
498 return makeLit(syms.botType, null);
499 }
501 /** Make an attributed class instance creation expression.
502 * @param ctype The class type.
503 * @param args The constructor arguments.
504 */
505 JCNewClass makeNewClass(Type ctype, List<JCExpression> args) {
506 JCNewClass tree = make.NewClass(null,
507 null, make.QualIdent(ctype.tsym), args, null);
508 tree.constructor = rs.resolveConstructor(
509 make_pos, attrEnv, ctype, TreeInfo.types(args), List.<Type>nil());
510 tree.type = ctype;
511 return tree;
512 }
514 /** Make an attributed unary expression.
515 * @param optag The operators tree tag.
516 * @param arg The operator's argument.
517 */
518 JCUnary makeUnary(JCTree.Tag optag, JCExpression arg) {
519 JCUnary tree = make.Unary(optag, arg);
520 tree.operator = rs.resolveUnaryOperator(
521 make_pos, optag, attrEnv, arg.type);
522 tree.type = tree.operator.type.getReturnType();
523 return tree;
524 }
526 /** Make an attributed binary expression.
527 * @param optag The operators tree tag.
528 * @param lhs The operator's left argument.
529 * @param rhs The operator's right argument.
530 */
531 JCBinary makeBinary(JCTree.Tag optag, JCExpression lhs, JCExpression rhs) {
532 JCBinary tree = make.Binary(optag, lhs, rhs);
533 tree.operator = rs.resolveBinaryOperator(
534 make_pos, optag, attrEnv, lhs.type, rhs.type);
535 tree.type = tree.operator.type.getReturnType();
536 return tree;
537 }
539 /** Make an attributed assignop expression.
540 * @param optag The operators tree tag.
541 * @param lhs The operator's left argument.
542 * @param rhs The operator's right argument.
543 */
544 JCAssignOp makeAssignop(JCTree.Tag optag, JCTree lhs, JCTree rhs) {
545 JCAssignOp tree = make.Assignop(optag, lhs, rhs);
546 tree.operator = rs.resolveBinaryOperator(
547 make_pos, tree.getTag().noAssignOp(), attrEnv, lhs.type, rhs.type);
548 tree.type = lhs.type;
549 return tree;
550 }
552 /** Convert tree into string object, unless it has already a
553 * reference type..
554 */
555 JCExpression makeString(JCExpression tree) {
556 if (!tree.type.isPrimitiveOrVoid()) {
557 return tree;
558 } else {
559 Symbol valueOfSym = lookupMethod(tree.pos(),
560 names.valueOf,
561 syms.stringType,
562 List.of(tree.type));
563 return make.App(make.QualIdent(valueOfSym), List.of(tree));
564 }
565 }
567 /** Create an empty anonymous class definition and enter and complete
568 * its symbol. Return the class definition's symbol.
569 * and create
570 * @param flags The class symbol's flags
571 * @param owner The class symbol's owner
572 */
573 JCClassDecl makeEmptyClass(long flags, ClassSymbol owner) {
574 return makeEmptyClass(flags, owner, null, true);
575 }
577 JCClassDecl makeEmptyClass(long flags, ClassSymbol owner, Name flatname,
578 boolean addToDefs) {
579 // Create class symbol.
580 ClassSymbol c = reader.defineClass(names.empty, owner);
581 if (flatname != null) {
582 c.flatname = flatname;
583 } else {
584 c.flatname = chk.localClassName(c);
585 }
586 c.sourcefile = owner.sourcefile;
587 c.completer = null;
588 c.members_field = new Scope(c);
589 c.flags_field = flags;
590 ClassType ctype = (ClassType) c.type;
591 ctype.supertype_field = syms.objectType;
592 ctype.interfaces_field = List.nil();
594 JCClassDecl odef = classDef(owner);
596 // Enter class symbol in owner scope and compiled table.
597 enterSynthetic(odef.pos(), c, owner.members());
598 chk.compiled.put(c.flatname, c);
600 // Create class definition tree.
601 JCClassDecl cdef = make.ClassDef(
602 make.Modifiers(flags), names.empty,
603 List.<JCTypeParameter>nil(),
604 null, List.<JCExpression>nil(), List.<JCTree>nil());
605 cdef.sym = c;
606 cdef.type = c.type;
608 // Append class definition tree to owner's definitions.
609 if (addToDefs) odef.defs = odef.defs.prepend(cdef);
610 return cdef;
611 }
613 /**************************************************************************
614 * Symbol manipulation utilities
615 *************************************************************************/
617 /** Enter a synthetic symbol in a given scope, but complain if there was already one there.
618 * @param pos Position for error reporting.
619 * @param sym The symbol.
620 * @param s The scope.
621 */
622 private void enterSynthetic(DiagnosticPosition pos, Symbol sym, Scope s) {
623 s.enter(sym);
624 }
626 /** Create a fresh synthetic name within a given scope - the unique name is
627 * obtained by appending '$' chars at the end of the name until no match
628 * is found.
629 *
630 * @param name base name
631 * @param s scope in which the name has to be unique
632 * @return fresh synthetic name
633 */
634 private Name makeSyntheticName(Name name, Scope s) {
635 do {
636 name = name.append(
637 target.syntheticNameChar(),
638 names.empty);
639 } while (lookupSynthetic(name, s) != null);
640 return name;
641 }
643 /** Check whether synthetic symbols generated during lowering conflict
644 * with user-defined symbols.
645 *
646 * @param translatedTrees lowered class trees
647 */
648 void checkConflicts(List<JCTree> translatedTrees) {
649 for (JCTree t : translatedTrees) {
650 t.accept(conflictsChecker);
651 }
652 }
654 JCTree.Visitor conflictsChecker = new TreeScanner() {
656 TypeSymbol currentClass;
658 @Override
659 public void visitMethodDef(JCMethodDecl that) {
660 chk.checkConflicts(that.pos(), that.sym, currentClass);
661 super.visitMethodDef(that);
662 }
664 @Override
665 public void visitVarDef(JCVariableDecl that) {
666 if (that.sym.owner.kind == TYP) {
667 chk.checkConflicts(that.pos(), that.sym, currentClass);
668 }
669 super.visitVarDef(that);
670 }
672 @Override
673 public void visitClassDef(JCClassDecl that) {
674 TypeSymbol prevCurrentClass = currentClass;
675 currentClass = that.sym;
676 try {
677 super.visitClassDef(that);
678 }
679 finally {
680 currentClass = prevCurrentClass;
681 }
682 }
683 };
685 /** Look up a synthetic name in a given scope.
686 * @param s The scope.
687 * @param name The name.
688 */
689 private Symbol lookupSynthetic(Name name, Scope s) {
690 Symbol sym = s.lookup(name).sym;
691 return (sym==null || (sym.flags()&SYNTHETIC)==0) ? null : sym;
692 }
694 /** Look up a method in a given scope.
695 */
696 private MethodSymbol lookupMethod(DiagnosticPosition pos, Name name, Type qual, List<Type> args) {
697 return rs.resolveInternalMethod(pos, attrEnv, qual, name, args, List.<Type>nil());
698 }
700 /** Look up a constructor.
701 */
702 private MethodSymbol lookupConstructor(DiagnosticPosition pos, Type qual, List<Type> args) {
703 return rs.resolveInternalConstructor(pos, attrEnv, qual, args, null);
704 }
706 /** Look up a field.
707 */
708 private VarSymbol lookupField(DiagnosticPosition pos, Type qual, Name name) {
709 return rs.resolveInternalField(pos, attrEnv, qual, name);
710 }
712 /** Anon inner classes are used as access constructor tags.
713 * accessConstructorTag will use an existing anon class if one is available,
714 * and synthethise a class (with makeEmptyClass) if one is not available.
715 * However, there is a small possibility that an existing class will not
716 * be generated as expected if it is inside a conditional with a constant
717 * expression. If that is found to be the case, create an empty class tree here.
718 */
719 private void checkAccessConstructorTags() {
720 for (List<ClassSymbol> l = accessConstrTags; l.nonEmpty(); l = l.tail) {
721 ClassSymbol c = l.head;
722 if (isTranslatedClassAvailable(c))
723 continue;
724 // Create class definition tree.
725 JCClassDecl cdec = makeEmptyClass(STATIC | SYNTHETIC,
726 c.outermostClass(), c.flatname, false);
727 swapAccessConstructorTag(c, cdec.sym);
728 translated.append(cdec);
729 }
730 }
731 // where
732 private boolean isTranslatedClassAvailable(ClassSymbol c) {
733 for (JCTree tree: translated) {
734 if (tree.hasTag(CLASSDEF)
735 && ((JCClassDecl) tree).sym == c) {
736 return true;
737 }
738 }
739 return false;
740 }
742 void swapAccessConstructorTag(ClassSymbol oldCTag, ClassSymbol newCTag) {
743 for (MethodSymbol methodSymbol : accessConstrs.values()) {
744 Assert.check(methodSymbol.type.hasTag(METHOD));
745 MethodType oldMethodType =
746 (MethodType)methodSymbol.type;
747 if (oldMethodType.argtypes.head.tsym == oldCTag)
748 methodSymbol.type =
749 types.createMethodTypeWithParameters(oldMethodType,
750 oldMethodType.getParameterTypes().tail
751 .prepend(newCTag.erasure(types)));
752 }
753 }
755 /**************************************************************************
756 * Access methods
757 *************************************************************************/
759 /** Access codes for dereferencing, assignment,
760 * and pre/post increment/decrement.
761 * Access codes for assignment operations are determined by method accessCode
762 * below.
763 *
764 * All access codes for accesses to the current class are even.
765 * If a member of the superclass should be accessed instead (because
766 * access was via a qualified super), add one to the corresponding code
767 * for the current class, making the number odd.
768 * This numbering scheme is used by the backend to decide whether
769 * to issue an invokevirtual or invokespecial call.
770 *
771 * @see Gen#visitSelect(JCFieldAccess tree)
772 */
773 private static final int
774 DEREFcode = 0,
775 ASSIGNcode = 2,
776 PREINCcode = 4,
777 PREDECcode = 6,
778 POSTINCcode = 8,
779 POSTDECcode = 10,
780 FIRSTASGOPcode = 12;
782 /** Number of access codes
783 */
784 private static final int NCODES = accessCode(ByteCodes.lushrl) + 2;
786 /** A mapping from symbols to their access numbers.
787 */
788 private Map<Symbol,Integer> accessNums;
790 /** A mapping from symbols to an array of access symbols, indexed by
791 * access code.
792 */
793 private Map<Symbol,MethodSymbol[]> accessSyms;
795 /** A mapping from (constructor) symbols to access constructor symbols.
796 */
797 private Map<Symbol,MethodSymbol> accessConstrs;
799 /** A list of all class symbols used for access constructor tags.
800 */
801 private List<ClassSymbol> accessConstrTags;
803 /** A queue for all accessed symbols.
804 */
805 private ListBuffer<Symbol> accessed;
807 /** Map bytecode of binary operation to access code of corresponding
808 * assignment operation. This is always an even number.
809 */
810 private static int accessCode(int bytecode) {
811 if (ByteCodes.iadd <= bytecode && bytecode <= ByteCodes.lxor)
812 return (bytecode - iadd) * 2 + FIRSTASGOPcode;
813 else if (bytecode == ByteCodes.string_add)
814 return (ByteCodes.lxor + 1 - iadd) * 2 + FIRSTASGOPcode;
815 else if (ByteCodes.ishll <= bytecode && bytecode <= ByteCodes.lushrl)
816 return (bytecode - ishll + ByteCodes.lxor + 2 - iadd) * 2 + FIRSTASGOPcode;
817 else
818 return -1;
819 }
821 /** return access code for identifier,
822 * @param tree The tree representing the identifier use.
823 * @param enclOp The closest enclosing operation node of tree,
824 * null if tree is not a subtree of an operation.
825 */
826 private static int accessCode(JCTree tree, JCTree enclOp) {
827 if (enclOp == null)
828 return DEREFcode;
829 else if (enclOp.hasTag(ASSIGN) &&
830 tree == TreeInfo.skipParens(((JCAssign) enclOp).lhs))
831 return ASSIGNcode;
832 else if (enclOp.getTag().isIncOrDecUnaryOp() &&
833 tree == TreeInfo.skipParens(((JCUnary) enclOp).arg))
834 return mapTagToUnaryOpCode(enclOp.getTag());
835 else if (enclOp.getTag().isAssignop() &&
836 tree == TreeInfo.skipParens(((JCAssignOp) enclOp).lhs))
837 return accessCode(((OperatorSymbol) ((JCAssignOp) enclOp).operator).opcode);
838 else
839 return DEREFcode;
840 }
842 /** Return binary operator that corresponds to given access code.
843 */
844 private OperatorSymbol binaryAccessOperator(int acode) {
845 for (Scope.Entry e = syms.predefClass.members().elems;
846 e != null;
847 e = e.sibling) {
848 if (e.sym instanceof OperatorSymbol) {
849 OperatorSymbol op = (OperatorSymbol)e.sym;
850 if (accessCode(op.opcode) == acode) return op;
851 }
852 }
853 return null;
854 }
856 /** Return tree tag for assignment operation corresponding
857 * to given binary operator.
858 */
859 private static JCTree.Tag treeTag(OperatorSymbol operator) {
860 switch (operator.opcode) {
861 case ByteCodes.ior: case ByteCodes.lor:
862 return BITOR_ASG;
863 case ByteCodes.ixor: case ByteCodes.lxor:
864 return BITXOR_ASG;
865 case ByteCodes.iand: case ByteCodes.land:
866 return BITAND_ASG;
867 case ByteCodes.ishl: case ByteCodes.lshl:
868 case ByteCodes.ishll: case ByteCodes.lshll:
869 return SL_ASG;
870 case ByteCodes.ishr: case ByteCodes.lshr:
871 case ByteCodes.ishrl: case ByteCodes.lshrl:
872 return SR_ASG;
873 case ByteCodes.iushr: case ByteCodes.lushr:
874 case ByteCodes.iushrl: case ByteCodes.lushrl:
875 return USR_ASG;
876 case ByteCodes.iadd: case ByteCodes.ladd:
877 case ByteCodes.fadd: case ByteCodes.dadd:
878 case ByteCodes.string_add:
879 return PLUS_ASG;
880 case ByteCodes.isub: case ByteCodes.lsub:
881 case ByteCodes.fsub: case ByteCodes.dsub:
882 return MINUS_ASG;
883 case ByteCodes.imul: case ByteCodes.lmul:
884 case ByteCodes.fmul: case ByteCodes.dmul:
885 return MUL_ASG;
886 case ByteCodes.idiv: case ByteCodes.ldiv:
887 case ByteCodes.fdiv: case ByteCodes.ddiv:
888 return DIV_ASG;
889 case ByteCodes.imod: case ByteCodes.lmod:
890 case ByteCodes.fmod: case ByteCodes.dmod:
891 return MOD_ASG;
892 default:
893 throw new AssertionError();
894 }
895 }
897 /** The name of the access method with number `anum' and access code `acode'.
898 */
899 Name accessName(int anum, int acode) {
900 return names.fromString(
901 "access" + target.syntheticNameChar() + anum + acode / 10 + acode % 10);
902 }
904 /** Return access symbol for a private or protected symbol from an inner class.
905 * @param sym The accessed private symbol.
906 * @param tree The accessing tree.
907 * @param enclOp The closest enclosing operation node of tree,
908 * null if tree is not a subtree of an operation.
909 * @param protAccess Is access to a protected symbol in another
910 * package?
911 * @param refSuper Is access via a (qualified) C.super?
912 */
913 MethodSymbol accessSymbol(Symbol sym, JCTree tree, JCTree enclOp,
914 boolean protAccess, boolean refSuper) {
915 ClassSymbol accOwner = refSuper && protAccess
916 // For access via qualified super (T.super.x), place the
917 // access symbol on T.
918 ? (ClassSymbol)((JCFieldAccess) tree).selected.type.tsym
919 // Otherwise pretend that the owner of an accessed
920 // protected symbol is the enclosing class of the current
921 // class which is a subclass of the symbol's owner.
922 : accessClass(sym, protAccess, tree);
924 Symbol vsym = sym;
925 if (sym.owner != accOwner) {
926 vsym = sym.clone(accOwner);
927 actualSymbols.put(vsym, sym);
928 }
930 Integer anum // The access number of the access method.
931 = accessNums.get(vsym);
932 if (anum == null) {
933 anum = accessed.length();
934 accessNums.put(vsym, anum);
935 accessSyms.put(vsym, new MethodSymbol[NCODES]);
936 accessed.append(vsym);
937 // System.out.println("accessing " + vsym + " in " + vsym.location());
938 }
940 int acode; // The access code of the access method.
941 List<Type> argtypes; // The argument types of the access method.
942 Type restype; // The result type of the access method.
943 List<Type> thrown; // The thrown exceptions of the access method.
944 switch (vsym.kind) {
945 case VAR:
946 acode = accessCode(tree, enclOp);
947 if (acode >= FIRSTASGOPcode) {
948 OperatorSymbol operator = binaryAccessOperator(acode);
949 if (operator.opcode == string_add)
950 argtypes = List.of(syms.objectType);
951 else
952 argtypes = operator.type.getParameterTypes().tail;
953 } else if (acode == ASSIGNcode)
954 argtypes = List.of(vsym.erasure(types));
955 else
956 argtypes = List.nil();
957 restype = vsym.erasure(types);
958 thrown = List.nil();
959 break;
960 case MTH:
961 acode = DEREFcode;
962 argtypes = vsym.erasure(types).getParameterTypes();
963 restype = vsym.erasure(types).getReturnType();
964 thrown = vsym.type.getThrownTypes();
965 break;
966 default:
967 throw new AssertionError();
968 }
970 // For references via qualified super, increment acode by one,
971 // making it odd.
972 if (protAccess && refSuper) acode++;
974 // Instance access methods get instance as first parameter.
975 // For protected symbols this needs to be the instance as a member
976 // of the type containing the accessed symbol, not the class
977 // containing the access method.
978 if ((vsym.flags() & STATIC) == 0) {
979 argtypes = argtypes.prepend(vsym.owner.erasure(types));
980 }
981 MethodSymbol[] accessors = accessSyms.get(vsym);
982 MethodSymbol accessor = accessors[acode];
983 if (accessor == null) {
984 accessor = new MethodSymbol(
985 STATIC | SYNTHETIC,
986 accessName(anum.intValue(), acode),
987 new MethodType(argtypes, restype, thrown, syms.methodClass),
988 accOwner);
989 enterSynthetic(tree.pos(), accessor, accOwner.members());
990 accessors[acode] = accessor;
991 }
992 return accessor;
993 }
995 /** The qualifier to be used for accessing a symbol in an outer class.
996 * This is either C.sym or C.this.sym, depending on whether or not
997 * sym is static.
998 * @param sym The accessed symbol.
999 */
1000 JCExpression accessBase(DiagnosticPosition pos, Symbol sym) {
1001 return (sym.flags() & STATIC) != 0
1002 ? access(make.at(pos.getStartPosition()).QualIdent(sym.owner))
1003 : makeOwnerThis(pos, sym, true);
1004 }
1006 /** Do we need an access method to reference private symbol?
1007 */
1008 boolean needsPrivateAccess(Symbol sym) {
1009 if ((sym.flags() & PRIVATE) == 0 || sym.owner == currentClass) {
1010 return false;
1011 } else if (sym.name == names.init && (sym.owner.owner.kind & (VAR | MTH)) != 0) {
1012 // private constructor in local class: relax protection
1013 sym.flags_field &= ~PRIVATE;
1014 return false;
1015 } else {
1016 return true;
1017 }
1018 }
1020 /** Do we need an access method to reference symbol in other package?
1021 */
1022 boolean needsProtectedAccess(Symbol sym, JCTree tree) {
1023 if ((sym.flags() & PROTECTED) == 0 ||
1024 sym.owner.owner == currentClass.owner || // fast special case
1025 sym.packge() == currentClass.packge())
1026 return false;
1027 if (!currentClass.isSubClass(sym.owner, types))
1028 return true;
1029 if ((sym.flags() & STATIC) != 0 ||
1030 !tree.hasTag(SELECT) ||
1031 TreeInfo.name(((JCFieldAccess) tree).selected) == names._super)
1032 return false;
1033 return !((JCFieldAccess) tree).selected.type.tsym.isSubClass(currentClass, types);
1034 }
1036 /** The class in which an access method for given symbol goes.
1037 * @param sym The access symbol
1038 * @param protAccess Is access to a protected symbol in another
1039 * package?
1040 */
1041 ClassSymbol accessClass(Symbol sym, boolean protAccess, JCTree tree) {
1042 if (protAccess) {
1043 Symbol qualifier = null;
1044 ClassSymbol c = currentClass;
1045 if (tree.hasTag(SELECT) && (sym.flags() & STATIC) == 0) {
1046 qualifier = ((JCFieldAccess) tree).selected.type.tsym;
1047 while (!qualifier.isSubClass(c, types)) {
1048 c = c.owner.enclClass();
1049 }
1050 return c;
1051 } else {
1052 while (!c.isSubClass(sym.owner, types)) {
1053 c = c.owner.enclClass();
1054 }
1055 }
1056 return c;
1057 } else {
1058 // the symbol is private
1059 return sym.owner.enclClass();
1060 }
1061 }
1063 private void addPrunedInfo(JCTree tree) {
1064 List<JCTree> infoList = prunedTree.get(currentClass);
1065 infoList = (infoList == null) ? List.of(tree) : infoList.prepend(tree);
1066 prunedTree.put(currentClass, infoList);
1067 }
1069 /** Ensure that identifier is accessible, return tree accessing the identifier.
1070 * @param sym The accessed symbol.
1071 * @param tree The tree referring to the symbol.
1072 * @param enclOp The closest enclosing operation node of tree,
1073 * null if tree is not a subtree of an operation.
1074 * @param refSuper Is access via a (qualified) C.super?
1075 */
1076 JCExpression access(Symbol sym, JCExpression tree, JCExpression enclOp, boolean refSuper) {
1077 // Access a free variable via its proxy, or its proxy's proxy
1078 while (sym.kind == VAR && sym.owner.kind == MTH &&
1079 sym.owner.enclClass() != currentClass) {
1080 // A constant is replaced by its constant value.
1081 Object cv = ((VarSymbol)sym).getConstValue();
1082 if (cv != null) {
1083 make.at(tree.pos);
1084 return makeLit(sym.type, cv);
1085 }
1086 // Otherwise replace the variable by its proxy.
1087 sym = proxies.lookup(proxyName(sym.name)).sym;
1088 Assert.check(sym != null && (sym.flags_field & FINAL) != 0);
1089 tree = make.at(tree.pos).Ident(sym);
1090 }
1091 JCExpression base = (tree.hasTag(SELECT)) ? ((JCFieldAccess) tree).selected : null;
1092 switch (sym.kind) {
1093 case TYP:
1094 if (sym.owner.kind != PCK) {
1095 // Convert type idents to
1096 // <flat name> or <package name> . <flat name>
1097 Name flatname = Convert.shortName(sym.flatName());
1098 while (base != null &&
1099 TreeInfo.symbol(base) != null &&
1100 TreeInfo.symbol(base).kind != PCK) {
1101 base = (base.hasTag(SELECT))
1102 ? ((JCFieldAccess) base).selected
1103 : null;
1104 }
1105 if (tree.hasTag(IDENT)) {
1106 ((JCIdent) tree).name = flatname;
1107 } else if (base == null) {
1108 tree = make.at(tree.pos).Ident(sym);
1109 ((JCIdent) tree).name = flatname;
1110 } else {
1111 ((JCFieldAccess) tree).selected = base;
1112 ((JCFieldAccess) tree).name = flatname;
1113 }
1114 }
1115 break;
1116 case MTH: case VAR:
1117 if (sym.owner.kind == TYP) {
1119 // Access methods are required for
1120 // - private members,
1121 // - protected members in a superclass of an
1122 // enclosing class contained in another package.
1123 // - all non-private members accessed via a qualified super.
1124 boolean protAccess = refSuper && !needsPrivateAccess(sym)
1125 || needsProtectedAccess(sym, tree);
1126 boolean accReq = protAccess || needsPrivateAccess(sym);
1128 // A base has to be supplied for
1129 // - simple identifiers accessing variables in outer classes.
1130 boolean baseReq =
1131 base == null &&
1132 sym.owner != syms.predefClass &&
1133 !sym.isMemberOf(currentClass, types);
1135 if (accReq || baseReq) {
1136 make.at(tree.pos);
1138 // Constants are replaced by their constant value.
1139 if (sym.kind == VAR) {
1140 Object cv = ((VarSymbol)sym).getConstValue();
1141 if (cv != null) {
1142 addPrunedInfo(tree);
1143 return makeLit(sym.type, cv);
1144 }
1145 }
1147 // Private variables and methods are replaced by calls
1148 // to their access methods.
1149 if (accReq) {
1150 List<JCExpression> args = List.nil();
1151 if ((sym.flags() & STATIC) == 0) {
1152 // Instance access methods get instance
1153 // as first parameter.
1154 if (base == null)
1155 base = makeOwnerThis(tree.pos(), sym, true);
1156 args = args.prepend(base);
1157 base = null; // so we don't duplicate code
1158 }
1159 Symbol access = accessSymbol(sym, tree,
1160 enclOp, protAccess,
1161 refSuper);
1162 JCExpression receiver = make.Select(
1163 base != null ? base : make.QualIdent(access.owner),
1164 access);
1165 return make.App(receiver, args);
1167 // Other accesses to members of outer classes get a
1168 // qualifier.
1169 } else if (baseReq) {
1170 return make.at(tree.pos).Select(
1171 accessBase(tree.pos(), sym), sym).setType(tree.type);
1172 }
1173 }
1174 }
1175 }
1176 return tree;
1177 }
1179 /** Ensure that identifier is accessible, return tree accessing the identifier.
1180 * @param tree The identifier tree.
1181 */
1182 JCExpression access(JCExpression tree) {
1183 Symbol sym = TreeInfo.symbol(tree);
1184 return sym == null ? tree : access(sym, tree, null, false);
1185 }
1187 /** Return access constructor for a private constructor,
1188 * or the constructor itself, if no access constructor is needed.
1189 * @param pos The position to report diagnostics, if any.
1190 * @param constr The private constructor.
1191 */
1192 Symbol accessConstructor(DiagnosticPosition pos, Symbol constr) {
1193 if (needsPrivateAccess(constr)) {
1194 ClassSymbol accOwner = constr.owner.enclClass();
1195 MethodSymbol aconstr = accessConstrs.get(constr);
1196 if (aconstr == null) {
1197 List<Type> argtypes = constr.type.getParameterTypes();
1198 if ((accOwner.flags_field & ENUM) != 0)
1199 argtypes = argtypes
1200 .prepend(syms.intType)
1201 .prepend(syms.stringType);
1202 aconstr = new MethodSymbol(
1203 SYNTHETIC,
1204 names.init,
1205 new MethodType(
1206 argtypes.append(
1207 accessConstructorTag().erasure(types)),
1208 constr.type.getReturnType(),
1209 constr.type.getThrownTypes(),
1210 syms.methodClass),
1211 accOwner);
1212 enterSynthetic(pos, aconstr, accOwner.members());
1213 accessConstrs.put(constr, aconstr);
1214 accessed.append(constr);
1215 }
1216 return aconstr;
1217 } else {
1218 return constr;
1219 }
1220 }
1222 /** Return an anonymous class nested in this toplevel class.
1223 */
1224 ClassSymbol accessConstructorTag() {
1225 ClassSymbol topClass = currentClass.outermostClass();
1226 Name flatname = names.fromString("" + topClass.getQualifiedName() +
1227 target.syntheticNameChar() +
1228 "1");
1229 ClassSymbol ctag = chk.compiled.get(flatname);
1230 if (ctag == null)
1231 ctag = makeEmptyClass(STATIC | SYNTHETIC, topClass).sym;
1232 // keep a record of all tags, to verify that all are generated as required
1233 accessConstrTags = accessConstrTags.prepend(ctag);
1234 return ctag;
1235 }
1237 /** Add all required access methods for a private symbol to enclosing class.
1238 * @param sym The symbol.
1239 */
1240 void makeAccessible(Symbol sym) {
1241 JCClassDecl cdef = classDef(sym.owner.enclClass());
1242 if (cdef == null) Assert.error("class def not found: " + sym + " in " + sym.owner);
1243 if (sym.name == names.init) {
1244 cdef.defs = cdef.defs.prepend(
1245 accessConstructorDef(cdef.pos, sym, accessConstrs.get(sym)));
1246 } else {
1247 MethodSymbol[] accessors = accessSyms.get(sym);
1248 for (int i = 0; i < NCODES; i++) {
1249 if (accessors[i] != null)
1250 cdef.defs = cdef.defs.prepend(
1251 accessDef(cdef.pos, sym, accessors[i], i));
1252 }
1253 }
1254 }
1256 /** Maps unary operator integer codes to JCTree.Tag objects
1257 * @param unaryOpCode the unary operator code
1258 */
1259 private static Tag mapUnaryOpCodeToTag(int unaryOpCode){
1260 switch (unaryOpCode){
1261 case PREINCcode:
1262 return PREINC;
1263 case PREDECcode:
1264 return PREDEC;
1265 case POSTINCcode:
1266 return POSTINC;
1267 case POSTDECcode:
1268 return POSTDEC;
1269 default:
1270 return NO_TAG;
1271 }
1272 }
1274 /** Maps JCTree.Tag objects to unary operator integer codes
1275 * @param tag the JCTree.Tag
1276 */
1277 private static int mapTagToUnaryOpCode(Tag tag){
1278 switch (tag){
1279 case PREINC:
1280 return PREINCcode;
1281 case PREDEC:
1282 return PREDECcode;
1283 case POSTINC:
1284 return POSTINCcode;
1285 case POSTDEC:
1286 return POSTDECcode;
1287 default:
1288 return -1;
1289 }
1290 }
1292 /** Construct definition of an access method.
1293 * @param pos The source code position of the definition.
1294 * @param vsym The private or protected symbol.
1295 * @param accessor The access method for the symbol.
1296 * @param acode The access code.
1297 */
1298 JCTree accessDef(int pos, Symbol vsym, MethodSymbol accessor, int acode) {
1299 // System.err.println("access " + vsym + " with " + accessor);//DEBUG
1300 currentClass = vsym.owner.enclClass();
1301 make.at(pos);
1302 JCMethodDecl md = make.MethodDef(accessor, null);
1304 // Find actual symbol
1305 Symbol sym = actualSymbols.get(vsym);
1306 if (sym == null) sym = vsym;
1308 JCExpression ref; // The tree referencing the private symbol.
1309 List<JCExpression> args; // Any additional arguments to be passed along.
1310 if ((sym.flags() & STATIC) != 0) {
1311 ref = make.Ident(sym);
1312 args = make.Idents(md.params);
1313 } else {
1314 ref = make.Select(make.Ident(md.params.head), sym);
1315 args = make.Idents(md.params.tail);
1316 }
1317 JCStatement stat; // The statement accessing the private symbol.
1318 if (sym.kind == VAR) {
1319 // Normalize out all odd access codes by taking floor modulo 2:
1320 int acode1 = acode - (acode & 1);
1322 JCExpression expr; // The access method's return value.
1323 switch (acode1) {
1324 case DEREFcode:
1325 expr = ref;
1326 break;
1327 case ASSIGNcode:
1328 expr = make.Assign(ref, args.head);
1329 break;
1330 case PREINCcode: case POSTINCcode: case PREDECcode: case POSTDECcode:
1331 expr = makeUnary(mapUnaryOpCodeToTag(acode1), ref);
1332 break;
1333 default:
1334 expr = make.Assignop(
1335 treeTag(binaryAccessOperator(acode1)), ref, args.head);
1336 ((JCAssignOp) expr).operator = binaryAccessOperator(acode1);
1337 }
1338 stat = make.Return(expr.setType(sym.type));
1339 } else {
1340 stat = make.Call(make.App(ref, args));
1341 }
1342 md.body = make.Block(0, List.of(stat));
1344 // Make sure all parameters, result types and thrown exceptions
1345 // are accessible.
1346 for (List<JCVariableDecl> l = md.params; l.nonEmpty(); l = l.tail)
1347 l.head.vartype = access(l.head.vartype);
1348 md.restype = access(md.restype);
1349 for (List<JCExpression> l = md.thrown; l.nonEmpty(); l = l.tail)
1350 l.head = access(l.head);
1352 return md;
1353 }
1355 /** Construct definition of an access constructor.
1356 * @param pos The source code position of the definition.
1357 * @param constr The private constructor.
1358 * @param accessor The access method for the constructor.
1359 */
1360 JCTree accessConstructorDef(int pos, Symbol constr, MethodSymbol accessor) {
1361 make.at(pos);
1362 JCMethodDecl md = make.MethodDef(accessor,
1363 accessor.externalType(types),
1364 null);
1365 JCIdent callee = make.Ident(names._this);
1366 callee.sym = constr;
1367 callee.type = constr.type;
1368 md.body =
1369 make.Block(0, List.<JCStatement>of(
1370 make.Call(
1371 make.App(
1372 callee,
1373 make.Idents(md.params.reverse().tail.reverse())))));
1374 return md;
1375 }
1377 /**************************************************************************
1378 * Free variables proxies and this$n
1379 *************************************************************************/
1381 /** A scope containing all free variable proxies for currently translated
1382 * class, as well as its this$n symbol (if needed).
1383 * Proxy scopes are nested in the same way classes are.
1384 * Inside a constructor, proxies and any this$n symbol are duplicated
1385 * in an additional innermost scope, where they represent the constructor
1386 * parameters.
1387 */
1388 Scope proxies;
1390 /** A scope containing all unnamed resource variables/saved
1391 * exception variables for translated TWR blocks
1392 */
1393 Scope twrVars;
1395 /** A stack containing the this$n field of the currently translated
1396 * classes (if needed) in innermost first order.
1397 * Inside a constructor, proxies and any this$n symbol are duplicated
1398 * in an additional innermost scope, where they represent the constructor
1399 * parameters.
1400 */
1401 List<VarSymbol> outerThisStack;
1403 /** The name of a free variable proxy.
1404 */
1405 Name proxyName(Name name) {
1406 return names.fromString("val" + target.syntheticNameChar() + name);
1407 }
1409 /** Proxy definitions for all free variables in given list, in reverse order.
1410 * @param pos The source code position of the definition.
1411 * @param freevars The free variables.
1412 * @param owner The class in which the definitions go.
1413 */
1414 List<JCVariableDecl> freevarDefs(int pos, List<VarSymbol> freevars, Symbol owner) {
1415 long flags = FINAL | SYNTHETIC;
1416 if (owner.kind == TYP &&
1417 target.usePrivateSyntheticFields())
1418 flags |= PRIVATE;
1419 List<JCVariableDecl> defs = List.nil();
1420 for (List<VarSymbol> l = freevars; l.nonEmpty(); l = l.tail) {
1421 VarSymbol v = l.head;
1422 VarSymbol proxy = new VarSymbol(
1423 flags, proxyName(v.name), v.erasure(types), owner);
1424 proxies.enter(proxy);
1425 JCVariableDecl vd = make.at(pos).VarDef(proxy, null);
1426 vd.vartype = access(vd.vartype);
1427 defs = defs.prepend(vd);
1428 }
1429 return defs;
1430 }
1432 /** The name of a this$n field
1433 * @param type The class referenced by the this$n field
1434 */
1435 Name outerThisName(Type type, Symbol owner) {
1436 Type t = type.getEnclosingType();
1437 int nestingLevel = 0;
1438 while (t.hasTag(CLASS)) {
1439 t = t.getEnclosingType();
1440 nestingLevel++;
1441 }
1442 Name result = names.fromString("this" + target.syntheticNameChar() + nestingLevel);
1443 while (owner.kind == TYP && ((ClassSymbol)owner).members().lookup(result).scope != null)
1444 result = names.fromString(result.toString() + target.syntheticNameChar());
1445 return result;
1446 }
1448 private VarSymbol makeOuterThisVarSymbol(Symbol owner, long flags) {
1449 if (owner.kind == TYP &&
1450 target.usePrivateSyntheticFields())
1451 flags |= PRIVATE;
1452 Type target = types.erasure(owner.enclClass().type.getEnclosingType());
1453 VarSymbol outerThis =
1454 new VarSymbol(flags, outerThisName(target, owner), target, owner);
1455 outerThisStack = outerThisStack.prepend(outerThis);
1456 return outerThis;
1457 }
1459 private JCVariableDecl makeOuterThisVarDecl(int pos, VarSymbol sym) {
1460 JCVariableDecl vd = make.at(pos).VarDef(sym, null);
1461 vd.vartype = access(vd.vartype);
1462 return vd;
1463 }
1465 /** Definition for this$n field.
1466 * @param pos The source code position of the definition.
1467 * @param owner The method in which the definition goes.
1468 */
1469 JCVariableDecl outerThisDef(int pos, MethodSymbol owner) {
1470 ClassSymbol c = owner.enclClass();
1471 boolean isMandated =
1472 // Anonymous constructors
1473 (owner.isConstructor() && owner.isAnonymous()) ||
1474 // Constructors of non-private inner member classes
1475 (owner.isConstructor() && c.isInner() &&
1476 !c.isPrivate() && !c.isStatic());
1477 long flags =
1478 FINAL | (isMandated ? MANDATED : SYNTHETIC);
1479 VarSymbol outerThis = makeOuterThisVarSymbol(owner, flags);
1480 owner.extraParams = owner.extraParams.prepend(outerThis);
1481 return makeOuterThisVarDecl(pos, outerThis);
1482 }
1484 /** Definition for this$n field.
1485 * @param pos The source code position of the definition.
1486 * @param owner The class in which the definition goes.
1487 */
1488 JCVariableDecl outerThisDef(int pos, ClassSymbol owner) {
1489 VarSymbol outerThis = makeOuterThisVarSymbol(owner, FINAL | SYNTHETIC);
1490 return makeOuterThisVarDecl(pos, outerThis);
1491 }
1493 /** Return a list of trees that load the free variables in given list,
1494 * in reverse order.
1495 * @param pos The source code position to be used for the trees.
1496 * @param freevars The list of free variables.
1497 */
1498 List<JCExpression> loadFreevars(DiagnosticPosition pos, List<VarSymbol> freevars) {
1499 List<JCExpression> args = List.nil();
1500 for (List<VarSymbol> l = freevars; l.nonEmpty(); l = l.tail)
1501 args = args.prepend(loadFreevar(pos, l.head));
1502 return args;
1503 }
1504 //where
1505 JCExpression loadFreevar(DiagnosticPosition pos, VarSymbol v) {
1506 return access(v, make.at(pos).Ident(v), null, false);
1507 }
1509 /** Construct a tree simulating the expression {@code C.this}.
1510 * @param pos The source code position to be used for the tree.
1511 * @param c The qualifier class.
1512 */
1513 JCExpression makeThis(DiagnosticPosition pos, TypeSymbol c) {
1514 if (currentClass == c) {
1515 // in this case, `this' works fine
1516 return make.at(pos).This(c.erasure(types));
1517 } else {
1518 // need to go via this$n
1519 return makeOuterThis(pos, c);
1520 }
1521 }
1523 /**
1524 * Optionally replace a try statement with the desugaring of a
1525 * try-with-resources statement. The canonical desugaring of
1526 *
1527 * try ResourceSpecification
1528 * Block
1529 *
1530 * is
1531 *
1532 * {
1533 * final VariableModifiers_minus_final R #resource = Expression;
1534 * Throwable #primaryException = null;
1535 *
1536 * try ResourceSpecificationtail
1537 * Block
1538 * catch (Throwable #t) {
1539 * #primaryException = t;
1540 * throw #t;
1541 * } finally {
1542 * if (#resource != null) {
1543 * if (#primaryException != null) {
1544 * try {
1545 * #resource.close();
1546 * } catch(Throwable #suppressedException) {
1547 * #primaryException.addSuppressed(#suppressedException);
1548 * }
1549 * } else {
1550 * #resource.close();
1551 * }
1552 * }
1553 * }
1554 *
1555 * @param tree The try statement to inspect.
1556 * @return A a desugared try-with-resources tree, or the original
1557 * try block if there are no resources to manage.
1558 */
1559 JCTree makeTwrTry(JCTry tree) {
1560 make_at(tree.pos());
1561 twrVars = twrVars.dup();
1562 JCBlock twrBlock = makeTwrBlock(tree.resources, tree.body, 0);
1563 if (tree.catchers.isEmpty() && tree.finalizer == null)
1564 result = translate(twrBlock);
1565 else
1566 result = translate(make.Try(twrBlock, tree.catchers, tree.finalizer));
1567 twrVars = twrVars.leave();
1568 return result;
1569 }
1571 private JCBlock makeTwrBlock(List<JCTree> resources, JCBlock block, int depth) {
1572 if (resources.isEmpty())
1573 return block;
1575 // Add resource declaration or expression to block statements
1576 ListBuffer<JCStatement> stats = new ListBuffer<JCStatement>();
1577 JCTree resource = resources.head;
1578 JCExpression expr = null;
1579 if (resource instanceof JCVariableDecl) {
1580 JCVariableDecl var = (JCVariableDecl) resource;
1581 expr = make.Ident(var.sym).setType(resource.type);
1582 stats.add(var);
1583 } else {
1584 Assert.check(resource instanceof JCExpression);
1585 VarSymbol syntheticTwrVar =
1586 new VarSymbol(SYNTHETIC | FINAL,
1587 makeSyntheticName(names.fromString("twrVar" +
1588 depth), twrVars),
1589 (resource.type.hasTag(BOT)) ?
1590 syms.autoCloseableType : resource.type,
1591 currentMethodSym);
1592 twrVars.enter(syntheticTwrVar);
1593 JCVariableDecl syntheticTwrVarDecl =
1594 make.VarDef(syntheticTwrVar, (JCExpression)resource);
1595 expr = (JCExpression)make.Ident(syntheticTwrVar);
1596 stats.add(syntheticTwrVarDecl);
1597 }
1599 // Add primaryException declaration
1600 VarSymbol primaryException =
1601 new VarSymbol(SYNTHETIC,
1602 makeSyntheticName(names.fromString("primaryException" +
1603 depth), twrVars),
1604 syms.throwableType,
1605 currentMethodSym);
1606 twrVars.enter(primaryException);
1607 JCVariableDecl primaryExceptionTreeDecl = make.VarDef(primaryException, makeNull());
1608 stats.add(primaryExceptionTreeDecl);
1610 // Create catch clause that saves exception and then rethrows it
1611 VarSymbol param =
1612 new VarSymbol(FINAL|SYNTHETIC,
1613 names.fromString("t" +
1614 target.syntheticNameChar()),
1615 syms.throwableType,
1616 currentMethodSym);
1617 JCVariableDecl paramTree = make.VarDef(param, null);
1618 JCStatement assign = make.Assignment(primaryException, make.Ident(param));
1619 JCStatement rethrowStat = make.Throw(make.Ident(param));
1620 JCBlock catchBlock = make.Block(0L, List.<JCStatement>of(assign, rethrowStat));
1621 JCCatch catchClause = make.Catch(paramTree, catchBlock);
1623 int oldPos = make.pos;
1624 make.at(TreeInfo.endPos(block));
1625 JCBlock finallyClause = makeTwrFinallyClause(primaryException, expr);
1626 make.at(oldPos);
1627 JCTry outerTry = make.Try(makeTwrBlock(resources.tail, block, depth + 1),
1628 List.<JCCatch>of(catchClause),
1629 finallyClause);
1630 stats.add(outerTry);
1631 return make.Block(0L, stats.toList());
1632 }
1634 private JCBlock makeTwrFinallyClause(Symbol primaryException, JCExpression resource) {
1635 // primaryException.addSuppressed(catchException);
1636 VarSymbol catchException =
1637 new VarSymbol(0, make.paramName(2),
1638 syms.throwableType,
1639 currentMethodSym);
1640 JCStatement addSuppressionStatement =
1641 make.Exec(makeCall(make.Ident(primaryException),
1642 names.addSuppressed,
1643 List.<JCExpression>of(make.Ident(catchException))));
1645 // try { resource.close(); } catch (e) { primaryException.addSuppressed(e); }
1646 JCBlock tryBlock =
1647 make.Block(0L, List.<JCStatement>of(makeResourceCloseInvocation(resource)));
1648 JCVariableDecl catchExceptionDecl = make.VarDef(catchException, null);
1649 JCBlock catchBlock = make.Block(0L, List.<JCStatement>of(addSuppressionStatement));
1650 List<JCCatch> catchClauses = List.<JCCatch>of(make.Catch(catchExceptionDecl, catchBlock));
1651 JCTry tryTree = make.Try(tryBlock, catchClauses, null);
1653 // if (primaryException != null) {try...} else resourceClose;
1654 JCIf closeIfStatement = make.If(makeNonNullCheck(make.Ident(primaryException)),
1655 tryTree,
1656 makeResourceCloseInvocation(resource));
1658 // if (#resource != null) { if (primaryException ... }
1659 return make.Block(0L,
1660 List.<JCStatement>of(make.If(makeNonNullCheck(resource),
1661 closeIfStatement,
1662 null)));
1663 }
1665 private JCStatement makeResourceCloseInvocation(JCExpression resource) {
1666 // convert to AutoCloseable if needed
1667 if (types.asSuper(resource.type, syms.autoCloseableType.tsym) == null) {
1668 resource = (JCExpression) convert(resource, syms.autoCloseableType);
1669 }
1671 // create resource.close() method invocation
1672 JCExpression resourceClose = makeCall(resource,
1673 names.close,
1674 List.<JCExpression>nil());
1675 return make.Exec(resourceClose);
1676 }
1678 private JCExpression makeNonNullCheck(JCExpression expression) {
1679 return makeBinary(NE, expression, makeNull());
1680 }
1682 /** Construct a tree that represents the outer instance
1683 * {@code C.this}. Never pick the current `this'.
1684 * @param pos The source code position to be used for the tree.
1685 * @param c The qualifier class.
1686 */
1687 JCExpression makeOuterThis(DiagnosticPosition pos, TypeSymbol c) {
1688 List<VarSymbol> ots = outerThisStack;
1689 if (ots.isEmpty()) {
1690 log.error(pos, "no.encl.instance.of.type.in.scope", c);
1691 Assert.error();
1692 return makeNull();
1693 }
1694 VarSymbol ot = ots.head;
1695 JCExpression tree = access(make.at(pos).Ident(ot));
1696 TypeSymbol otc = ot.type.tsym;
1697 while (otc != c) {
1698 do {
1699 ots = ots.tail;
1700 if (ots.isEmpty()) {
1701 log.error(pos,
1702 "no.encl.instance.of.type.in.scope",
1703 c);
1704 Assert.error(); // should have been caught in Attr
1705 return tree;
1706 }
1707 ot = ots.head;
1708 } while (ot.owner != otc);
1709 if (otc.owner.kind != PCK && !otc.hasOuterInstance()) {
1710 chk.earlyRefError(pos, c);
1711 Assert.error(); // should have been caught in Attr
1712 return makeNull();
1713 }
1714 tree = access(make.at(pos).Select(tree, ot));
1715 otc = ot.type.tsym;
1716 }
1717 return tree;
1718 }
1720 /** Construct a tree that represents the closest outer instance
1721 * {@code C.this} such that the given symbol is a member of C.
1722 * @param pos The source code position to be used for the tree.
1723 * @param sym The accessed symbol.
1724 * @param preciseMatch should we accept a type that is a subtype of
1725 * sym's owner, even if it doesn't contain sym
1726 * due to hiding, overriding, or non-inheritance
1727 * due to protection?
1728 */
1729 JCExpression makeOwnerThis(DiagnosticPosition pos, Symbol sym, boolean preciseMatch) {
1730 Symbol c = sym.owner;
1731 if (preciseMatch ? sym.isMemberOf(currentClass, types)
1732 : currentClass.isSubClass(sym.owner, types)) {
1733 // in this case, `this' works fine
1734 return make.at(pos).This(c.erasure(types));
1735 } else {
1736 // need to go via this$n
1737 return makeOwnerThisN(pos, sym, preciseMatch);
1738 }
1739 }
1741 /**
1742 * Similar to makeOwnerThis but will never pick "this".
1743 */
1744 JCExpression makeOwnerThisN(DiagnosticPosition pos, Symbol sym, boolean preciseMatch) {
1745 Symbol c = sym.owner;
1746 List<VarSymbol> ots = outerThisStack;
1747 if (ots.isEmpty()) {
1748 log.error(pos, "no.encl.instance.of.type.in.scope", c);
1749 Assert.error();
1750 return makeNull();
1751 }
1752 VarSymbol ot = ots.head;
1753 JCExpression tree = access(make.at(pos).Ident(ot));
1754 TypeSymbol otc = ot.type.tsym;
1755 while (!(preciseMatch ? sym.isMemberOf(otc, types) : otc.isSubClass(sym.owner, types))) {
1756 do {
1757 ots = ots.tail;
1758 if (ots.isEmpty()) {
1759 log.error(pos,
1760 "no.encl.instance.of.type.in.scope",
1761 c);
1762 Assert.error();
1763 return tree;
1764 }
1765 ot = ots.head;
1766 } while (ot.owner != otc);
1767 tree = access(make.at(pos).Select(tree, ot));
1768 otc = ot.type.tsym;
1769 }
1770 return tree;
1771 }
1773 /** Return tree simulating the assignment {@code this.name = name}, where
1774 * name is the name of a free variable.
1775 */
1776 JCStatement initField(int pos, Name name) {
1777 Scope.Entry e = proxies.lookup(name);
1778 Symbol rhs = e.sym;
1779 Assert.check(rhs.owner.kind == MTH);
1780 Symbol lhs = e.next().sym;
1781 Assert.check(rhs.owner.owner == lhs.owner);
1782 make.at(pos);
1783 return
1784 make.Exec(
1785 make.Assign(
1786 make.Select(make.This(lhs.owner.erasure(types)), lhs),
1787 make.Ident(rhs)).setType(lhs.erasure(types)));
1788 }
1790 /** Return tree simulating the assignment {@code this.this$n = this$n}.
1791 */
1792 JCStatement initOuterThis(int pos) {
1793 VarSymbol rhs = outerThisStack.head;
1794 Assert.check(rhs.owner.kind == MTH);
1795 VarSymbol lhs = outerThisStack.tail.head;
1796 Assert.check(rhs.owner.owner == lhs.owner);
1797 make.at(pos);
1798 return
1799 make.Exec(
1800 make.Assign(
1801 make.Select(make.This(lhs.owner.erasure(types)), lhs),
1802 make.Ident(rhs)).setType(lhs.erasure(types)));
1803 }
1805 /**************************************************************************
1806 * Code for .class
1807 *************************************************************************/
1809 /** Return the symbol of a class to contain a cache of
1810 * compiler-generated statics such as class$ and the
1811 * $assertionsDisabled flag. We create an anonymous nested class
1812 * (unless one already exists) and return its symbol. However,
1813 * for backward compatibility in 1.4 and earlier we use the
1814 * top-level class itself.
1815 */
1816 private ClassSymbol outerCacheClass() {
1817 ClassSymbol clazz = outermostClassDef.sym;
1818 if ((clazz.flags() & INTERFACE) == 0 &&
1819 !target.useInnerCacheClass()) return clazz;
1820 Scope s = clazz.members();
1821 for (Scope.Entry e = s.elems; e != null; e = e.sibling)
1822 if (e.sym.kind == TYP &&
1823 e.sym.name == names.empty &&
1824 (e.sym.flags() & INTERFACE) == 0) return (ClassSymbol) e.sym;
1825 return makeEmptyClass(STATIC | SYNTHETIC, clazz).sym;
1826 }
1828 /** Return symbol for "class$" method. If there is no method definition
1829 * for class$, construct one as follows:
1830 *
1831 * class class$(String x0) {
1832 * try {
1833 * return Class.forName(x0);
1834 * } catch (ClassNotFoundException x1) {
1835 * throw new NoClassDefFoundError(x1.getMessage());
1836 * }
1837 * }
1838 */
1839 private MethodSymbol classDollarSym(DiagnosticPosition pos) {
1840 ClassSymbol outerCacheClass = outerCacheClass();
1841 MethodSymbol classDollarSym =
1842 (MethodSymbol)lookupSynthetic(classDollar,
1843 outerCacheClass.members());
1844 if (classDollarSym == null) {
1845 classDollarSym = new MethodSymbol(
1846 STATIC | SYNTHETIC,
1847 classDollar,
1848 new MethodType(
1849 List.of(syms.stringType),
1850 types.erasure(syms.classType),
1851 List.<Type>nil(),
1852 syms.methodClass),
1853 outerCacheClass);
1854 enterSynthetic(pos, classDollarSym, outerCacheClass.members());
1856 JCMethodDecl md = make.MethodDef(classDollarSym, null);
1857 try {
1858 md.body = classDollarSymBody(pos, md);
1859 } catch (CompletionFailure ex) {
1860 md.body = make.Block(0, List.<JCStatement>nil());
1861 chk.completionError(pos, ex);
1862 }
1863 JCClassDecl outerCacheClassDef = classDef(outerCacheClass);
1864 outerCacheClassDef.defs = outerCacheClassDef.defs.prepend(md);
1865 }
1866 return classDollarSym;
1867 }
1869 /** Generate code for class$(String name). */
1870 JCBlock classDollarSymBody(DiagnosticPosition pos, JCMethodDecl md) {
1871 MethodSymbol classDollarSym = md.sym;
1872 ClassSymbol outerCacheClass = (ClassSymbol)classDollarSym.owner;
1874 JCBlock returnResult;
1876 // in 1.4.2 and above, we use
1877 // Class.forName(String name, boolean init, ClassLoader loader);
1878 // which requires we cache the current loader in cl$
1879 if (target.classLiteralsNoInit()) {
1880 // clsym = "private static ClassLoader cl$"
1881 VarSymbol clsym = new VarSymbol(STATIC|SYNTHETIC,
1882 names.fromString("cl" + target.syntheticNameChar()),
1883 syms.classLoaderType,
1884 outerCacheClass);
1885 enterSynthetic(pos, clsym, outerCacheClass.members());
1887 // emit "private static ClassLoader cl$;"
1888 JCVariableDecl cldef = make.VarDef(clsym, null);
1889 JCClassDecl outerCacheClassDef = classDef(outerCacheClass);
1890 outerCacheClassDef.defs = outerCacheClassDef.defs.prepend(cldef);
1892 // newcache := "new cache$1[0]"
1893 JCNewArray newcache = make.
1894 NewArray(make.Type(outerCacheClass.type),
1895 List.<JCExpression>of(make.Literal(INT, 0).setType(syms.intType)),
1896 null);
1897 newcache.type = new ArrayType(types.erasure(outerCacheClass.type),
1898 syms.arrayClass);
1900 // forNameSym := java.lang.Class.forName(
1901 // String s,boolean init,ClassLoader loader)
1902 Symbol forNameSym = lookupMethod(make_pos, names.forName,
1903 types.erasure(syms.classType),
1904 List.of(syms.stringType,
1905 syms.booleanType,
1906 syms.classLoaderType));
1907 // clvalue := "(cl$ == null) ?
1908 // $newcache.getClass().getComponentType().getClassLoader() : cl$"
1909 JCExpression clvalue =
1910 make.Conditional(
1911 makeBinary(EQ, make.Ident(clsym), makeNull()),
1912 make.Assign(
1913 make.Ident(clsym),
1914 makeCall(
1915 makeCall(makeCall(newcache,
1916 names.getClass,
1917 List.<JCExpression>nil()),
1918 names.getComponentType,
1919 List.<JCExpression>nil()),
1920 names.getClassLoader,
1921 List.<JCExpression>nil())).setType(syms.classLoaderType),
1922 make.Ident(clsym)).setType(syms.classLoaderType);
1924 // returnResult := "{ return Class.forName(param1, false, cl$); }"
1925 List<JCExpression> args = List.of(make.Ident(md.params.head.sym),
1926 makeLit(syms.booleanType, 0),
1927 clvalue);
1928 returnResult = make.
1929 Block(0, List.<JCStatement>of(make.
1930 Call(make. // return
1931 App(make.
1932 Ident(forNameSym), args))));
1933 } else {
1934 // forNameSym := java.lang.Class.forName(String s)
1935 Symbol forNameSym = lookupMethod(make_pos,
1936 names.forName,
1937 types.erasure(syms.classType),
1938 List.of(syms.stringType));
1939 // returnResult := "{ return Class.forName(param1); }"
1940 returnResult = make.
1941 Block(0, List.of(make.
1942 Call(make. // return
1943 App(make.
1944 QualIdent(forNameSym),
1945 List.<JCExpression>of(make.
1946 Ident(md.params.
1947 head.sym))))));
1948 }
1950 // catchParam := ClassNotFoundException e1
1951 VarSymbol catchParam =
1952 new VarSymbol(0, make.paramName(1),
1953 syms.classNotFoundExceptionType,
1954 classDollarSym);
1956 JCStatement rethrow;
1957 if (target.hasInitCause()) {
1958 // rethrow = "throw new NoClassDefFoundError().initCause(e);
1959 JCTree throwExpr =
1960 makeCall(makeNewClass(syms.noClassDefFoundErrorType,
1961 List.<JCExpression>nil()),
1962 names.initCause,
1963 List.<JCExpression>of(make.Ident(catchParam)));
1964 rethrow = make.Throw(throwExpr);
1965 } else {
1966 // getMessageSym := ClassNotFoundException.getMessage()
1967 Symbol getMessageSym = lookupMethod(make_pos,
1968 names.getMessage,
1969 syms.classNotFoundExceptionType,
1970 List.<Type>nil());
1971 // rethrow = "throw new NoClassDefFoundError(e.getMessage());"
1972 rethrow = make.
1973 Throw(makeNewClass(syms.noClassDefFoundErrorType,
1974 List.<JCExpression>of(make.App(make.Select(make.Ident(catchParam),
1975 getMessageSym),
1976 List.<JCExpression>nil()))));
1977 }
1979 // rethrowStmt := "( $rethrow )"
1980 JCBlock rethrowStmt = make.Block(0, List.of(rethrow));
1982 // catchBlock := "catch ($catchParam) $rethrowStmt"
1983 JCCatch catchBlock = make.Catch(make.VarDef(catchParam, null),
1984 rethrowStmt);
1986 // tryCatch := "try $returnResult $catchBlock"
1987 JCStatement tryCatch = make.Try(returnResult,
1988 List.of(catchBlock), null);
1990 return make.Block(0, List.of(tryCatch));
1991 }
1992 // where
1993 /** Create an attributed tree of the form left.name(). */
1994 private JCMethodInvocation makeCall(JCExpression left, Name name, List<JCExpression> args) {
1995 Assert.checkNonNull(left.type);
1996 Symbol funcsym = lookupMethod(make_pos, name, left.type,
1997 TreeInfo.types(args));
1998 return make.App(make.Select(left, funcsym), args);
1999 }
2001 /** The Name Of The variable to cache T.class values.
2002 * @param sig The signature of type T.
2003 */
2004 private Name cacheName(String sig) {
2005 StringBuilder buf = new StringBuilder();
2006 if (sig.startsWith("[")) {
2007 buf = buf.append("array");
2008 while (sig.startsWith("[")) {
2009 buf = buf.append(target.syntheticNameChar());
2010 sig = sig.substring(1);
2011 }
2012 if (sig.startsWith("L")) {
2013 sig = sig.substring(0, sig.length() - 1);
2014 }
2015 } else {
2016 buf = buf.append("class" + target.syntheticNameChar());
2017 }
2018 buf = buf.append(sig.replace('.', target.syntheticNameChar()));
2019 return names.fromString(buf.toString());
2020 }
2022 /** The variable symbol that caches T.class values.
2023 * If none exists yet, create a definition.
2024 * @param sig The signature of type T.
2025 * @param pos The position to report diagnostics, if any.
2026 */
2027 private VarSymbol cacheSym(DiagnosticPosition pos, String sig) {
2028 ClassSymbol outerCacheClass = outerCacheClass();
2029 Name cname = cacheName(sig);
2030 VarSymbol cacheSym =
2031 (VarSymbol)lookupSynthetic(cname, outerCacheClass.members());
2032 if (cacheSym == null) {
2033 cacheSym = new VarSymbol(
2034 STATIC | SYNTHETIC, cname, types.erasure(syms.classType), outerCacheClass);
2035 enterSynthetic(pos, cacheSym, outerCacheClass.members());
2037 JCVariableDecl cacheDef = make.VarDef(cacheSym, null);
2038 JCClassDecl outerCacheClassDef = classDef(outerCacheClass);
2039 outerCacheClassDef.defs = outerCacheClassDef.defs.prepend(cacheDef);
2040 }
2041 return cacheSym;
2042 }
2044 /** The tree simulating a T.class expression.
2045 * @param clazz The tree identifying type T.
2046 */
2047 private JCExpression classOf(JCTree clazz) {
2048 return classOfType(clazz.type, clazz.pos());
2049 }
2051 private JCExpression classOfType(Type type, DiagnosticPosition pos) {
2052 switch (type.getTag()) {
2053 case BYTE: case SHORT: case CHAR: case INT: case LONG: case FLOAT:
2054 case DOUBLE: case BOOLEAN: case VOID:
2055 // replace with <BoxedClass>.TYPE
2056 ClassSymbol c = types.boxedClass(type);
2057 Symbol typeSym =
2058 rs.accessBase(
2059 rs.findIdentInType(attrEnv, c.type, names.TYPE, VAR),
2060 pos, c.type, names.TYPE, true);
2061 if (typeSym.kind == VAR)
2062 ((VarSymbol)typeSym).getConstValue(); // ensure initializer is evaluated
2063 return make.QualIdent(typeSym);
2064 case CLASS: case ARRAY:
2065 if (target.hasClassLiterals()) {
2066 VarSymbol sym = new VarSymbol(
2067 STATIC | PUBLIC | FINAL, names._class,
2068 syms.classType, type.tsym);
2069 return make_at(pos).Select(make.Type(type), sym);
2070 }
2071 // replace with <cache == null ? cache = class$(tsig) : cache>
2072 // where
2073 // - <tsig> is the type signature of T,
2074 // - <cache> is the cache variable for tsig.
2075 String sig =
2076 writer.xClassName(type).toString().replace('/', '.');
2077 Symbol cs = cacheSym(pos, sig);
2078 return make_at(pos).Conditional(
2079 makeBinary(EQ, make.Ident(cs), makeNull()),
2080 make.Assign(
2081 make.Ident(cs),
2082 make.App(
2083 make.Ident(classDollarSym(pos)),
2084 List.<JCExpression>of(make.Literal(CLASS, sig)
2085 .setType(syms.stringType))))
2086 .setType(types.erasure(syms.classType)),
2087 make.Ident(cs)).setType(types.erasure(syms.classType));
2088 default:
2089 throw new AssertionError();
2090 }
2091 }
2093 /**************************************************************************
2094 * Code for enabling/disabling assertions.
2095 *************************************************************************/
2097 // This code is not particularly robust if the user has
2098 // previously declared a member named '$assertionsDisabled'.
2099 // The same faulty idiom also appears in the translation of
2100 // class literals above. We should report an error if a
2101 // previous declaration is not synthetic.
2103 private JCExpression assertFlagTest(DiagnosticPosition pos) {
2104 // Outermost class may be either true class or an interface.
2105 ClassSymbol outermostClass = outermostClassDef.sym;
2107 // note that this is a class, as an interface can't contain a statement.
2108 ClassSymbol container = currentClass;
2110 VarSymbol assertDisabledSym =
2111 (VarSymbol)lookupSynthetic(dollarAssertionsDisabled,
2112 container.members());
2113 if (assertDisabledSym == null) {
2114 assertDisabledSym =
2115 new VarSymbol(STATIC | FINAL | SYNTHETIC,
2116 dollarAssertionsDisabled,
2117 syms.booleanType,
2118 container);
2119 enterSynthetic(pos, assertDisabledSym, container.members());
2120 Symbol desiredAssertionStatusSym = lookupMethod(pos,
2121 names.desiredAssertionStatus,
2122 types.erasure(syms.classType),
2123 List.<Type>nil());
2124 JCClassDecl containerDef = classDef(container);
2125 make_at(containerDef.pos());
2126 JCExpression notStatus = makeUnary(NOT, make.App(make.Select(
2127 classOfType(types.erasure(outermostClass.type),
2128 containerDef.pos()),
2129 desiredAssertionStatusSym)));
2130 JCVariableDecl assertDisabledDef = make.VarDef(assertDisabledSym,
2131 notStatus);
2132 containerDef.defs = containerDef.defs.prepend(assertDisabledDef);
2133 }
2134 make_at(pos);
2135 return makeUnary(NOT, make.Ident(assertDisabledSym));
2136 }
2139 /**************************************************************************
2140 * Building blocks for let expressions
2141 *************************************************************************/
2143 interface TreeBuilder {
2144 JCTree build(JCTree arg);
2145 }
2147 /** Construct an expression using the builder, with the given rval
2148 * expression as an argument to the builder. However, the rval
2149 * expression must be computed only once, even if used multiple
2150 * times in the result of the builder. We do that by
2151 * constructing a "let" expression that saves the rvalue into a
2152 * temporary variable and then uses the temporary variable in
2153 * place of the expression built by the builder. The complete
2154 * resulting expression is of the form
2155 * <pre>
2156 * (let <b>TYPE</b> <b>TEMP</b> = <b>RVAL</b>;
2157 * in (<b>BUILDER</b>(<b>TEMP</b>)))
2158 * </pre>
2159 * where <code><b>TEMP</b></code> is a newly declared variable
2160 * in the let expression.
2161 */
2162 JCTree abstractRval(JCTree rval, Type type, TreeBuilder builder) {
2163 rval = TreeInfo.skipParens(rval);
2164 switch (rval.getTag()) {
2165 case LITERAL:
2166 return builder.build(rval);
2167 case IDENT:
2168 JCIdent id = (JCIdent) rval;
2169 if ((id.sym.flags() & FINAL) != 0 && id.sym.owner.kind == MTH)
2170 return builder.build(rval);
2171 }
2172 VarSymbol var =
2173 new VarSymbol(FINAL|SYNTHETIC,
2174 names.fromString(
2175 target.syntheticNameChar()
2176 + "" + rval.hashCode()),
2177 type,
2178 currentMethodSym);
2179 rval = convert(rval,type);
2180 JCVariableDecl def = make.VarDef(var, (JCExpression)rval); // XXX cast
2181 JCTree built = builder.build(make.Ident(var));
2182 JCTree res = make.LetExpr(def, built);
2183 res.type = built.type;
2184 return res;
2185 }
2187 // same as above, with the type of the temporary variable computed
2188 JCTree abstractRval(JCTree rval, TreeBuilder builder) {
2189 return abstractRval(rval, rval.type, builder);
2190 }
2192 // same as above, but for an expression that may be used as either
2193 // an rvalue or an lvalue. This requires special handling for
2194 // Select expressions, where we place the left-hand-side of the
2195 // select in a temporary, and for Indexed expressions, where we
2196 // place both the indexed expression and the index value in temps.
2197 JCTree abstractLval(JCTree lval, final TreeBuilder builder) {
2198 lval = TreeInfo.skipParens(lval);
2199 switch (lval.getTag()) {
2200 case IDENT:
2201 return builder.build(lval);
2202 case SELECT: {
2203 final JCFieldAccess s = (JCFieldAccess)lval;
2204 JCTree selected = TreeInfo.skipParens(s.selected);
2205 Symbol lid = TreeInfo.symbol(s.selected);
2206 if (lid != null && lid.kind == TYP) return builder.build(lval);
2207 return abstractRval(s.selected, new TreeBuilder() {
2208 public JCTree build(final JCTree selected) {
2209 return builder.build(make.Select((JCExpression)selected, s.sym));
2210 }
2211 });
2212 }
2213 case INDEXED: {
2214 final JCArrayAccess i = (JCArrayAccess)lval;
2215 return abstractRval(i.indexed, new TreeBuilder() {
2216 public JCTree build(final JCTree indexed) {
2217 return abstractRval(i.index, syms.intType, new TreeBuilder() {
2218 public JCTree build(final JCTree index) {
2219 JCTree newLval = make.Indexed((JCExpression)indexed,
2220 (JCExpression)index);
2221 newLval.setType(i.type);
2222 return builder.build(newLval);
2223 }
2224 });
2225 }
2226 });
2227 }
2228 case TYPECAST: {
2229 return abstractLval(((JCTypeCast)lval).expr, builder);
2230 }
2231 }
2232 throw new AssertionError(lval);
2233 }
2235 // evaluate and discard the first expression, then evaluate the second.
2236 JCTree makeComma(final JCTree expr1, final JCTree expr2) {
2237 return abstractRval(expr1, new TreeBuilder() {
2238 public JCTree build(final JCTree discarded) {
2239 return expr2;
2240 }
2241 });
2242 }
2244 /**************************************************************************
2245 * Translation methods
2246 *************************************************************************/
2248 /** Visitor argument: enclosing operator node.
2249 */
2250 private JCExpression enclOp;
2252 /** Visitor method: Translate a single node.
2253 * Attach the source position from the old tree to its replacement tree.
2254 */
2255 public <T extends JCTree> T translate(T tree) {
2256 if (tree == null) {
2257 return null;
2258 } else {
2259 make_at(tree.pos());
2260 T result = super.translate(tree);
2261 if (endPosTable != null && result != tree) {
2262 endPosTable.replaceTree(tree, result);
2263 }
2264 return result;
2265 }
2266 }
2268 /** Visitor method: Translate a single node, boxing or unboxing if needed.
2269 */
2270 public <T extends JCTree> T translate(T tree, Type type) {
2271 return (tree == null) ? null : boxIfNeeded(translate(tree), type);
2272 }
2274 /** Visitor method: Translate tree.
2275 */
2276 public <T extends JCTree> T translate(T tree, JCExpression enclOp) {
2277 JCExpression prevEnclOp = this.enclOp;
2278 this.enclOp = enclOp;
2279 T res = translate(tree);
2280 this.enclOp = prevEnclOp;
2281 return res;
2282 }
2284 /** Visitor method: Translate list of trees.
2285 */
2286 public <T extends JCTree> List<T> translate(List<T> trees, JCExpression enclOp) {
2287 JCExpression prevEnclOp = this.enclOp;
2288 this.enclOp = enclOp;
2289 List<T> res = translate(trees);
2290 this.enclOp = prevEnclOp;
2291 return res;
2292 }
2294 /** Visitor method: Translate list of trees.
2295 */
2296 public <T extends JCTree> List<T> translate(List<T> trees, Type type) {
2297 if (trees == null) return null;
2298 for (List<T> l = trees; l.nonEmpty(); l = l.tail)
2299 l.head = translate(l.head, type);
2300 return trees;
2301 }
2303 public void visitTopLevel(JCCompilationUnit tree) {
2304 if (needPackageInfoClass(tree)) {
2305 Name name = names.package_info;
2306 long flags = Flags.ABSTRACT | Flags.INTERFACE;
2307 if (target.isPackageInfoSynthetic())
2308 // package-info is marked SYNTHETIC in JDK 1.6 and later releases
2309 flags = flags | Flags.SYNTHETIC;
2310 JCClassDecl packageAnnotationsClass
2311 = make.ClassDef(make.Modifiers(flags,
2312 tree.packageAnnotations),
2313 name, List.<JCTypeParameter>nil(),
2314 null, List.<JCExpression>nil(), List.<JCTree>nil());
2315 ClassSymbol c = tree.packge.package_info;
2316 c.flags_field |= flags;
2317 c.annotations.setAttributes(tree.packge.annotations);
2318 ClassType ctype = (ClassType) c.type;
2319 ctype.supertype_field = syms.objectType;
2320 ctype.interfaces_field = List.nil();
2321 packageAnnotationsClass.sym = c;
2323 translated.append(packageAnnotationsClass);
2324 }
2325 }
2326 // where
2327 private boolean needPackageInfoClass(JCCompilationUnit tree) {
2328 switch (pkginfoOpt) {
2329 case ALWAYS:
2330 return true;
2331 case LEGACY:
2332 return tree.packageAnnotations.nonEmpty();
2333 case NONEMPTY:
2334 for (Attribute.Compound a :
2335 tree.packge.annotations.getDeclarationAttributes()) {
2336 Attribute.RetentionPolicy p = types.getRetention(a);
2337 if (p != Attribute.RetentionPolicy.SOURCE)
2338 return true;
2339 }
2340 return false;
2341 }
2342 throw new AssertionError();
2343 }
2345 public void visitClassDef(JCClassDecl tree) {
2346 ClassSymbol currentClassPrev = currentClass;
2347 MethodSymbol currentMethodSymPrev = currentMethodSym;
2348 currentClass = tree.sym;
2349 currentMethodSym = null;
2350 classdefs.put(currentClass, tree);
2352 proxies = proxies.dup(currentClass);
2353 List<VarSymbol> prevOuterThisStack = outerThisStack;
2355 // If this is an enum definition
2356 if ((tree.mods.flags & ENUM) != 0 &&
2357 (types.supertype(currentClass.type).tsym.flags() & ENUM) == 0)
2358 visitEnumDef(tree);
2360 // If this is a nested class, define a this$n field for
2361 // it and add to proxies.
2362 JCVariableDecl otdef = null;
2363 if (currentClass.hasOuterInstance())
2364 otdef = outerThisDef(tree.pos, currentClass);
2366 // If this is a local class, define proxies for all its free variables.
2367 List<JCVariableDecl> fvdefs = freevarDefs(
2368 tree.pos, freevars(currentClass), currentClass);
2370 // Recursively translate superclass, interfaces.
2371 tree.extending = translate(tree.extending);
2372 tree.implementing = translate(tree.implementing);
2374 if (currentClass.isLocal()) {
2375 ClassSymbol encl = currentClass.owner.enclClass();
2376 if (encl.trans_local == null) {
2377 encl.trans_local = List.nil();
2378 }
2379 encl.trans_local = encl.trans_local.prepend(currentClass);
2380 }
2382 // Recursively translate members, taking into account that new members
2383 // might be created during the translation and prepended to the member
2384 // list `tree.defs'.
2385 List<JCTree> seen = List.nil();
2386 while (tree.defs != seen) {
2387 List<JCTree> unseen = tree.defs;
2388 for (List<JCTree> l = unseen; l.nonEmpty() && l != seen; l = l.tail) {
2389 JCTree outermostMemberDefPrev = outermostMemberDef;
2390 if (outermostMemberDefPrev == null) outermostMemberDef = l.head;
2391 l.head = translate(l.head);
2392 outermostMemberDef = outermostMemberDefPrev;
2393 }
2394 seen = unseen;
2395 }
2397 // Convert a protected modifier to public, mask static modifier.
2398 if ((tree.mods.flags & PROTECTED) != 0) tree.mods.flags |= PUBLIC;
2399 tree.mods.flags &= ClassFlags;
2401 // Convert name to flat representation, replacing '.' by '$'.
2402 tree.name = Convert.shortName(currentClass.flatName());
2404 // Add this$n and free variables proxy definitions to class.
2405 for (List<JCVariableDecl> l = fvdefs; l.nonEmpty(); l = l.tail) {
2406 tree.defs = tree.defs.prepend(l.head);
2407 enterSynthetic(tree.pos(), l.head.sym, currentClass.members());
2408 }
2409 if (currentClass.hasOuterInstance()) {
2410 tree.defs = tree.defs.prepend(otdef);
2411 enterSynthetic(tree.pos(), otdef.sym, currentClass.members());
2412 }
2414 proxies = proxies.leave();
2415 outerThisStack = prevOuterThisStack;
2417 // Append translated tree to `translated' queue.
2418 translated.append(tree);
2420 currentClass = currentClassPrev;
2421 currentMethodSym = currentMethodSymPrev;
2423 // Return empty block {} as a placeholder for an inner class.
2424 result = make_at(tree.pos()).Block(0, List.<JCStatement>nil());
2425 }
2427 /** Translate an enum class. */
2428 private void visitEnumDef(JCClassDecl tree) {
2429 make_at(tree.pos());
2431 // add the supertype, if needed
2432 if (tree.extending == null)
2433 tree.extending = make.Type(types.supertype(tree.type));
2435 // classOfType adds a cache field to tree.defs unless
2436 // target.hasClassLiterals().
2437 JCExpression e_class = classOfType(tree.sym.type, tree.pos()).
2438 setType(types.erasure(syms.classType));
2440 // process each enumeration constant, adding implicit constructor parameters
2441 int nextOrdinal = 0;
2442 ListBuffer<JCExpression> values = new ListBuffer<JCExpression>();
2443 ListBuffer<JCTree> enumDefs = new ListBuffer<JCTree>();
2444 ListBuffer<JCTree> otherDefs = new ListBuffer<JCTree>();
2445 for (List<JCTree> defs = tree.defs;
2446 defs.nonEmpty();
2447 defs=defs.tail) {
2448 if (defs.head.hasTag(VARDEF) && (((JCVariableDecl) defs.head).mods.flags & ENUM) != 0) {
2449 JCVariableDecl var = (JCVariableDecl)defs.head;
2450 visitEnumConstantDef(var, nextOrdinal++);
2451 values.append(make.QualIdent(var.sym));
2452 enumDefs.append(var);
2453 } else {
2454 otherDefs.append(defs.head);
2455 }
2456 }
2458 // private static final T[] #VALUES = { a, b, c };
2459 Name valuesName = names.fromString(target.syntheticNameChar() + "VALUES");
2460 while (tree.sym.members().lookup(valuesName).scope != null) // avoid name clash
2461 valuesName = names.fromString(valuesName + "" + target.syntheticNameChar());
2462 Type arrayType = new ArrayType(types.erasure(tree.type), syms.arrayClass);
2463 VarSymbol valuesVar = new VarSymbol(PRIVATE|FINAL|STATIC|SYNTHETIC,
2464 valuesName,
2465 arrayType,
2466 tree.type.tsym);
2467 JCNewArray newArray = make.NewArray(make.Type(types.erasure(tree.type)),
2468 List.<JCExpression>nil(),
2469 values.toList());
2470 newArray.type = arrayType;
2471 enumDefs.append(make.VarDef(valuesVar, newArray));
2472 tree.sym.members().enter(valuesVar);
2474 Symbol valuesSym = lookupMethod(tree.pos(), names.values,
2475 tree.type, List.<Type>nil());
2476 List<JCStatement> valuesBody;
2477 if (useClone()) {
2478 // return (T[]) $VALUES.clone();
2479 JCTypeCast valuesResult =
2480 make.TypeCast(valuesSym.type.getReturnType(),
2481 make.App(make.Select(make.Ident(valuesVar),
2482 syms.arrayCloneMethod)));
2483 valuesBody = List.<JCStatement>of(make.Return(valuesResult));
2484 } else {
2485 // template: T[] $result = new T[$values.length];
2486 Name resultName = names.fromString(target.syntheticNameChar() + "result");
2487 while (tree.sym.members().lookup(resultName).scope != null) // avoid name clash
2488 resultName = names.fromString(resultName + "" + target.syntheticNameChar());
2489 VarSymbol resultVar = new VarSymbol(FINAL|SYNTHETIC,
2490 resultName,
2491 arrayType,
2492 valuesSym);
2493 JCNewArray resultArray = make.NewArray(make.Type(types.erasure(tree.type)),
2494 List.of(make.Select(make.Ident(valuesVar), syms.lengthVar)),
2495 null);
2496 resultArray.type = arrayType;
2497 JCVariableDecl decl = make.VarDef(resultVar, resultArray);
2499 // template: System.arraycopy($VALUES, 0, $result, 0, $VALUES.length);
2500 if (systemArraycopyMethod == null) {
2501 systemArraycopyMethod =
2502 new MethodSymbol(PUBLIC | STATIC,
2503 names.fromString("arraycopy"),
2504 new MethodType(List.<Type>of(syms.objectType,
2505 syms.intType,
2506 syms.objectType,
2507 syms.intType,
2508 syms.intType),
2509 syms.voidType,
2510 List.<Type>nil(),
2511 syms.methodClass),
2512 syms.systemType.tsym);
2513 }
2514 JCStatement copy =
2515 make.Exec(make.App(make.Select(make.Ident(syms.systemType.tsym),
2516 systemArraycopyMethod),
2517 List.of(make.Ident(valuesVar), make.Literal(0),
2518 make.Ident(resultVar), make.Literal(0),
2519 make.Select(make.Ident(valuesVar), syms.lengthVar))));
2521 // template: return $result;
2522 JCStatement ret = make.Return(make.Ident(resultVar));
2523 valuesBody = List.<JCStatement>of(decl, copy, ret);
2524 }
2526 JCMethodDecl valuesDef =
2527 make.MethodDef((MethodSymbol)valuesSym, make.Block(0, valuesBody));
2529 enumDefs.append(valuesDef);
2531 if (debugLower)
2532 System.err.println(tree.sym + ".valuesDef = " + valuesDef);
2534 /** The template for the following code is:
2535 *
2536 * public static E valueOf(String name) {
2537 * return (E)Enum.valueOf(E.class, name);
2538 * }
2539 *
2540 * where E is tree.sym
2541 */
2542 MethodSymbol valueOfSym = lookupMethod(tree.pos(),
2543 names.valueOf,
2544 tree.sym.type,
2545 List.of(syms.stringType));
2546 Assert.check((valueOfSym.flags() & STATIC) != 0);
2547 VarSymbol nameArgSym = valueOfSym.params.head;
2548 JCIdent nameVal = make.Ident(nameArgSym);
2549 JCStatement enum_ValueOf =
2550 make.Return(make.TypeCast(tree.sym.type,
2551 makeCall(make.Ident(syms.enumSym),
2552 names.valueOf,
2553 List.of(e_class, nameVal))));
2554 JCMethodDecl valueOf = make.MethodDef(valueOfSym,
2555 make.Block(0, List.of(enum_ValueOf)));
2556 nameVal.sym = valueOf.params.head.sym;
2557 if (debugLower)
2558 System.err.println(tree.sym + ".valueOf = " + valueOf);
2559 enumDefs.append(valueOf);
2561 enumDefs.appendList(otherDefs.toList());
2562 tree.defs = enumDefs.toList();
2564 // Add the necessary members for the EnumCompatibleMode
2565 if (target.compilerBootstrap(tree.sym)) {
2566 addEnumCompatibleMembers(tree);
2567 }
2568 }
2569 // where
2570 private MethodSymbol systemArraycopyMethod;
2571 private boolean useClone() {
2572 try {
2573 Scope.Entry e = syms.objectType.tsym.members().lookup(names.clone);
2574 return (e.sym != null);
2575 }
2576 catch (CompletionFailure e) {
2577 return false;
2578 }
2579 }
2581 /** Translate an enumeration constant and its initializer. */
2582 private void visitEnumConstantDef(JCVariableDecl var, int ordinal) {
2583 JCNewClass varDef = (JCNewClass)var.init;
2584 varDef.args = varDef.args.
2585 prepend(makeLit(syms.intType, ordinal)).
2586 prepend(makeLit(syms.stringType, var.name.toString()));
2587 }
2589 public void visitMethodDef(JCMethodDecl tree) {
2590 if (tree.name == names.init && (currentClass.flags_field&ENUM) != 0) {
2591 // Add "String $enum$name, int $enum$ordinal" to the beginning of the
2592 // argument list for each constructor of an enum.
2593 JCVariableDecl nameParam = make_at(tree.pos()).
2594 Param(names.fromString(target.syntheticNameChar() +
2595 "enum" + target.syntheticNameChar() + "name"),
2596 syms.stringType, tree.sym);
2597 nameParam.mods.flags |= SYNTHETIC; nameParam.sym.flags_field |= SYNTHETIC;
2598 JCVariableDecl ordParam = make.
2599 Param(names.fromString(target.syntheticNameChar() +
2600 "enum" + target.syntheticNameChar() +
2601 "ordinal"),
2602 syms.intType, tree.sym);
2603 ordParam.mods.flags |= SYNTHETIC; ordParam.sym.flags_field |= SYNTHETIC;
2605 tree.params = tree.params.prepend(ordParam).prepend(nameParam);
2607 MethodSymbol m = tree.sym;
2608 m.extraParams = m.extraParams.prepend(ordParam.sym);
2609 m.extraParams = m.extraParams.prepend(nameParam.sym);
2610 Type olderasure = m.erasure(types);
2611 m.erasure_field = new MethodType(
2612 olderasure.getParameterTypes().prepend(syms.intType).prepend(syms.stringType),
2613 olderasure.getReturnType(),
2614 olderasure.getThrownTypes(),
2615 syms.methodClass);
2617 if (target.compilerBootstrap(m.owner)) {
2618 // Initialize synthetic name field
2619 Symbol nameVarSym = lookupSynthetic(names.fromString("$name"),
2620 tree.sym.owner.members());
2621 JCIdent nameIdent = make.Ident(nameParam.sym);
2622 JCIdent id1 = make.Ident(nameVarSym);
2623 JCAssign newAssign = make.Assign(id1, nameIdent);
2624 newAssign.type = id1.type;
2625 JCExpressionStatement nameAssign = make.Exec(newAssign);
2626 nameAssign.type = id1.type;
2627 tree.body.stats = tree.body.stats.prepend(nameAssign);
2629 // Initialize synthetic ordinal field
2630 Symbol ordinalVarSym = lookupSynthetic(names.fromString("$ordinal"),
2631 tree.sym.owner.members());
2632 JCIdent ordIdent = make.Ident(ordParam.sym);
2633 id1 = make.Ident(ordinalVarSym);
2634 newAssign = make.Assign(id1, ordIdent);
2635 newAssign.type = id1.type;
2636 JCExpressionStatement ordinalAssign = make.Exec(newAssign);
2637 ordinalAssign.type = id1.type;
2638 tree.body.stats = tree.body.stats.prepend(ordinalAssign);
2639 }
2640 }
2642 JCMethodDecl prevMethodDef = currentMethodDef;
2643 MethodSymbol prevMethodSym = currentMethodSym;
2644 try {
2645 currentMethodDef = tree;
2646 currentMethodSym = tree.sym;
2647 visitMethodDefInternal(tree);
2648 } finally {
2649 currentMethodDef = prevMethodDef;
2650 currentMethodSym = prevMethodSym;
2651 }
2652 }
2653 //where
2654 private void visitMethodDefInternal(JCMethodDecl tree) {
2655 if (tree.name == names.init &&
2656 (currentClass.isInner() ||
2657 (currentClass.owner.kind & (VAR | MTH)) != 0)) {
2658 // We are seeing a constructor of an inner class.
2659 MethodSymbol m = tree.sym;
2661 // Push a new proxy scope for constructor parameters.
2662 // and create definitions for any this$n and proxy parameters.
2663 proxies = proxies.dup(m);
2664 List<VarSymbol> prevOuterThisStack = outerThisStack;
2665 List<VarSymbol> fvs = freevars(currentClass);
2666 JCVariableDecl otdef = null;
2667 if (currentClass.hasOuterInstance())
2668 otdef = outerThisDef(tree.pos, m);
2669 List<JCVariableDecl> fvdefs = freevarDefs(tree.pos, fvs, m);
2671 // Recursively translate result type, parameters and thrown list.
2672 tree.restype = translate(tree.restype);
2673 tree.params = translateVarDefs(tree.params);
2674 tree.thrown = translate(tree.thrown);
2676 // when compiling stubs, don't process body
2677 if (tree.body == null) {
2678 result = tree;
2679 return;
2680 }
2682 // Add this$n (if needed) in front of and free variables behind
2683 // constructor parameter list.
2684 tree.params = tree.params.appendList(fvdefs);
2685 if (currentClass.hasOuterInstance())
2686 tree.params = tree.params.prepend(otdef);
2688 // If this is an initial constructor, i.e., it does not start with
2689 // this(...), insert initializers for this$n and proxies
2690 // before (pre-1.4, after) the call to superclass constructor.
2691 JCStatement selfCall = translate(tree.body.stats.head);
2693 List<JCStatement> added = List.nil();
2694 if (fvs.nonEmpty()) {
2695 List<Type> addedargtypes = List.nil();
2696 for (List<VarSymbol> l = fvs; l.nonEmpty(); l = l.tail) {
2697 if (TreeInfo.isInitialConstructor(tree))
2698 added = added.prepend(
2699 initField(tree.body.pos, proxyName(l.head.name)));
2700 addedargtypes = addedargtypes.prepend(l.head.erasure(types));
2701 }
2702 Type olderasure = m.erasure(types);
2703 m.erasure_field = new MethodType(
2704 olderasure.getParameterTypes().appendList(addedargtypes),
2705 olderasure.getReturnType(),
2706 olderasure.getThrownTypes(),
2707 syms.methodClass);
2708 }
2709 if (currentClass.hasOuterInstance() &&
2710 TreeInfo.isInitialConstructor(tree))
2711 {
2712 added = added.prepend(initOuterThis(tree.body.pos));
2713 }
2715 // pop local variables from proxy stack
2716 proxies = proxies.leave();
2718 // recursively translate following local statements and
2719 // combine with this- or super-call
2720 List<JCStatement> stats = translate(tree.body.stats.tail);
2721 if (target.initializeFieldsBeforeSuper())
2722 tree.body.stats = stats.prepend(selfCall).prependList(added);
2723 else
2724 tree.body.stats = stats.prependList(added).prepend(selfCall);
2726 outerThisStack = prevOuterThisStack;
2727 } else {
2728 super.visitMethodDef(tree);
2729 }
2730 result = tree;
2731 }
2733 public void visitAnnotatedType(JCAnnotatedType tree) {
2734 // No need to retain type annotations any longer.
2735 // tree.annotations = translate(tree.annotations);
2736 tree.underlyingType = translate(tree.underlyingType);
2737 result = tree.underlyingType;
2738 }
2740 public void visitTypeCast(JCTypeCast tree) {
2741 tree.clazz = translate(tree.clazz);
2742 if (tree.type.isPrimitive() != tree.expr.type.isPrimitive())
2743 tree.expr = translate(tree.expr, tree.type);
2744 else
2745 tree.expr = translate(tree.expr);
2746 result = tree;
2747 }
2749 public void visitNewClass(JCNewClass tree) {
2750 ClassSymbol c = (ClassSymbol)tree.constructor.owner;
2752 // Box arguments, if necessary
2753 boolean isEnum = (tree.constructor.owner.flags() & ENUM) != 0;
2754 List<Type> argTypes = tree.constructor.type.getParameterTypes();
2755 if (isEnum) argTypes = argTypes.prepend(syms.intType).prepend(syms.stringType);
2756 tree.args = boxArgs(argTypes, tree.args, tree.varargsElement);
2757 tree.varargsElement = null;
2759 // If created class is local, add free variables after
2760 // explicit constructor arguments.
2761 if ((c.owner.kind & (VAR | MTH)) != 0) {
2762 tree.args = tree.args.appendList(loadFreevars(tree.pos(), freevars(c)));
2763 }
2765 // If an access constructor is used, append null as a last argument.
2766 Symbol constructor = accessConstructor(tree.pos(), tree.constructor);
2767 if (constructor != tree.constructor) {
2768 tree.args = tree.args.append(makeNull());
2769 tree.constructor = constructor;
2770 }
2772 // If created class has an outer instance, and new is qualified, pass
2773 // qualifier as first argument. If new is not qualified, pass the
2774 // correct outer instance as first argument.
2775 if (c.hasOuterInstance()) {
2776 JCExpression thisArg;
2777 if (tree.encl != null) {
2778 thisArg = attr.makeNullCheck(translate(tree.encl));
2779 thisArg.type = tree.encl.type;
2780 } else if ((c.owner.kind & (MTH | VAR)) != 0) {
2781 // local class
2782 thisArg = makeThis(tree.pos(), c.type.getEnclosingType().tsym);
2783 } else {
2784 // nested class
2785 thisArg = makeOwnerThis(tree.pos(), c, false);
2786 }
2787 tree.args = tree.args.prepend(thisArg);
2788 }
2789 tree.encl = null;
2791 // If we have an anonymous class, create its flat version, rather
2792 // than the class or interface following new.
2793 if (tree.def != null) {
2794 translate(tree.def);
2795 tree.clazz = access(make_at(tree.clazz.pos()).Ident(tree.def.sym));
2796 tree.def = null;
2797 } else {
2798 tree.clazz = access(c, tree.clazz, enclOp, false);
2799 }
2800 result = tree;
2801 }
2803 // Simplify conditionals with known constant controlling expressions.
2804 // This allows us to avoid generating supporting declarations for
2805 // the dead code, which will not be eliminated during code generation.
2806 // Note that Flow.isFalse and Flow.isTrue only return true
2807 // for constant expressions in the sense of JLS 15.27, which
2808 // are guaranteed to have no side-effects. More aggressive
2809 // constant propagation would require that we take care to
2810 // preserve possible side-effects in the condition expression.
2812 /** Visitor method for conditional expressions.
2813 */
2814 @Override
2815 public void visitConditional(JCConditional tree) {
2816 JCTree cond = tree.cond = translate(tree.cond, syms.booleanType);
2817 if (cond.type.isTrue()) {
2818 result = convert(translate(tree.truepart, tree.type), tree.type);
2819 addPrunedInfo(cond);
2820 } else if (cond.type.isFalse()) {
2821 result = convert(translate(tree.falsepart, tree.type), tree.type);
2822 addPrunedInfo(cond);
2823 } else {
2824 // Condition is not a compile-time constant.
2825 tree.truepart = translate(tree.truepart, tree.type);
2826 tree.falsepart = translate(tree.falsepart, tree.type);
2827 result = tree;
2828 }
2829 }
2830 //where
2831 private JCTree convert(JCTree tree, Type pt) {
2832 if (tree.type == pt || tree.type.hasTag(BOT))
2833 return tree;
2834 JCTree result = make_at(tree.pos()).TypeCast(make.Type(pt), (JCExpression)tree);
2835 result.type = (tree.type.constValue() != null) ? cfolder.coerce(tree.type, pt)
2836 : pt;
2837 return result;
2838 }
2840 /** Visitor method for if statements.
2841 */
2842 public void visitIf(JCIf tree) {
2843 JCTree cond = tree.cond = translate(tree.cond, syms.booleanType);
2844 if (cond.type.isTrue()) {
2845 result = translate(tree.thenpart);
2846 addPrunedInfo(cond);
2847 } else if (cond.type.isFalse()) {
2848 if (tree.elsepart != null) {
2849 result = translate(tree.elsepart);
2850 } else {
2851 result = make.Skip();
2852 }
2853 addPrunedInfo(cond);
2854 } else {
2855 // Condition is not a compile-time constant.
2856 tree.thenpart = translate(tree.thenpart);
2857 tree.elsepart = translate(tree.elsepart);
2858 result = tree;
2859 }
2860 }
2862 /** Visitor method for assert statements. Translate them away.
2863 */
2864 public void visitAssert(JCAssert tree) {
2865 DiagnosticPosition detailPos = (tree.detail == null) ? tree.pos() : tree.detail.pos();
2866 tree.cond = translate(tree.cond, syms.booleanType);
2867 if (!tree.cond.type.isTrue()) {
2868 JCExpression cond = assertFlagTest(tree.pos());
2869 List<JCExpression> exnArgs = (tree.detail == null) ?
2870 List.<JCExpression>nil() : List.of(translate(tree.detail));
2871 if (!tree.cond.type.isFalse()) {
2872 cond = makeBinary
2873 (AND,
2874 cond,
2875 makeUnary(NOT, tree.cond));
2876 }
2877 result =
2878 make.If(cond,
2879 make_at(detailPos).
2880 Throw(makeNewClass(syms.assertionErrorType, exnArgs)),
2881 null);
2882 } else {
2883 result = make.Skip();
2884 }
2885 }
2887 public void visitApply(JCMethodInvocation tree) {
2888 Symbol meth = TreeInfo.symbol(tree.meth);
2889 List<Type> argtypes = meth.type.getParameterTypes();
2890 if (allowEnums &&
2891 meth.name==names.init &&
2892 meth.owner == syms.enumSym)
2893 argtypes = argtypes.tail.tail;
2894 tree.args = boxArgs(argtypes, tree.args, tree.varargsElement);
2895 tree.varargsElement = null;
2896 Name methName = TreeInfo.name(tree.meth);
2897 if (meth.name==names.init) {
2898 // We are seeing a this(...) or super(...) constructor call.
2899 // If an access constructor is used, append null as a last argument.
2900 Symbol constructor = accessConstructor(tree.pos(), meth);
2901 if (constructor != meth) {
2902 tree.args = tree.args.append(makeNull());
2903 TreeInfo.setSymbol(tree.meth, constructor);
2904 }
2906 // If we are calling a constructor of a local class, add
2907 // free variables after explicit constructor arguments.
2908 ClassSymbol c = (ClassSymbol)constructor.owner;
2909 if ((c.owner.kind & (VAR | MTH)) != 0) {
2910 tree.args = tree.args.appendList(loadFreevars(tree.pos(), freevars(c)));
2911 }
2913 // If we are calling a constructor of an enum class, pass
2914 // along the name and ordinal arguments
2915 if ((c.flags_field&ENUM) != 0 || c.getQualifiedName() == names.java_lang_Enum) {
2916 List<JCVariableDecl> params = currentMethodDef.params;
2917 if (currentMethodSym.owner.hasOuterInstance())
2918 params = params.tail; // drop this$n
2919 tree.args = tree.args
2920 .prepend(make_at(tree.pos()).Ident(params.tail.head.sym)) // ordinal
2921 .prepend(make.Ident(params.head.sym)); // name
2922 }
2924 // If we are calling a constructor of a class with an outer
2925 // instance, and the call
2926 // is qualified, pass qualifier as first argument in front of
2927 // the explicit constructor arguments. If the call
2928 // is not qualified, pass the correct outer instance as
2929 // first argument.
2930 if (c.hasOuterInstance()) {
2931 JCExpression thisArg;
2932 if (tree.meth.hasTag(SELECT)) {
2933 thisArg = attr.
2934 makeNullCheck(translate(((JCFieldAccess) tree.meth).selected));
2935 tree.meth = make.Ident(constructor);
2936 ((JCIdent) tree.meth).name = methName;
2937 } else if ((c.owner.kind & (MTH | VAR)) != 0 || methName == names._this){
2938 // local class or this() call
2939 thisArg = makeThis(tree.meth.pos(), c.type.getEnclosingType().tsym);
2940 } else {
2941 // super() call of nested class - never pick 'this'
2942 thisArg = makeOwnerThisN(tree.meth.pos(), c, false);
2943 }
2944 tree.args = tree.args.prepend(thisArg);
2945 }
2946 } else {
2947 // We are seeing a normal method invocation; translate this as usual.
2948 tree.meth = translate(tree.meth);
2950 // If the translated method itself is an Apply tree, we are
2951 // seeing an access method invocation. In this case, append
2952 // the method arguments to the arguments of the access method.
2953 if (tree.meth.hasTag(APPLY)) {
2954 JCMethodInvocation app = (JCMethodInvocation)tree.meth;
2955 app.args = tree.args.prependList(app.args);
2956 result = app;
2957 return;
2958 }
2959 }
2960 result = tree;
2961 }
2963 List<JCExpression> boxArgs(List<Type> parameters, List<JCExpression> _args, Type varargsElement) {
2964 List<JCExpression> args = _args;
2965 if (parameters.isEmpty()) return args;
2966 boolean anyChanges = false;
2967 ListBuffer<JCExpression> result = new ListBuffer<JCExpression>();
2968 while (parameters.tail.nonEmpty()) {
2969 JCExpression arg = translate(args.head, parameters.head);
2970 anyChanges |= (arg != args.head);
2971 result.append(arg);
2972 args = args.tail;
2973 parameters = parameters.tail;
2974 }
2975 Type parameter = parameters.head;
2976 if (varargsElement != null) {
2977 anyChanges = true;
2978 ListBuffer<JCExpression> elems = new ListBuffer<JCExpression>();
2979 while (args.nonEmpty()) {
2980 JCExpression arg = translate(args.head, varargsElement);
2981 elems.append(arg);
2982 args = args.tail;
2983 }
2984 JCNewArray boxedArgs = make.NewArray(make.Type(varargsElement),
2985 List.<JCExpression>nil(),
2986 elems.toList());
2987 boxedArgs.type = new ArrayType(varargsElement, syms.arrayClass);
2988 result.append(boxedArgs);
2989 } else {
2990 if (args.length() != 1) throw new AssertionError(args);
2991 JCExpression arg = translate(args.head, parameter);
2992 anyChanges |= (arg != args.head);
2993 result.append(arg);
2994 if (!anyChanges) return _args;
2995 }
2996 return result.toList();
2997 }
2999 /** Expand a boxing or unboxing conversion if needed. */
3000 @SuppressWarnings("unchecked") // XXX unchecked
3001 <T extends JCTree> T boxIfNeeded(T tree, Type type) {
3002 boolean havePrimitive = tree.type.isPrimitive();
3003 if (havePrimitive == type.isPrimitive())
3004 return tree;
3005 if (havePrimitive) {
3006 Type unboxedTarget = types.unboxedType(type);
3007 if (!unboxedTarget.hasTag(NONE)) {
3008 if (!types.isSubtype(tree.type, unboxedTarget)) //e.g. Character c = 89;
3009 tree.type = unboxedTarget.constType(tree.type.constValue());
3010 return (T)boxPrimitive((JCExpression)tree, type);
3011 } else {
3012 tree = (T)boxPrimitive((JCExpression)tree);
3013 }
3014 } else {
3015 tree = (T)unbox((JCExpression)tree, type);
3016 }
3017 return tree;
3018 }
3020 /** Box up a single primitive expression. */
3021 JCExpression boxPrimitive(JCExpression tree) {
3022 return boxPrimitive(tree, types.boxedClass(tree.type).type);
3023 }
3025 /** Box up a single primitive expression. */
3026 JCExpression boxPrimitive(JCExpression tree, Type box) {
3027 make_at(tree.pos());
3028 if (target.boxWithConstructors()) {
3029 Symbol ctor = lookupConstructor(tree.pos(),
3030 box,
3031 List.<Type>nil()
3032 .prepend(tree.type));
3033 return make.Create(ctor, List.of(tree));
3034 } else {
3035 Symbol valueOfSym = lookupMethod(tree.pos(),
3036 names.valueOf,
3037 box,
3038 List.<Type>nil()
3039 .prepend(tree.type));
3040 return make.App(make.QualIdent(valueOfSym), List.of(tree));
3041 }
3042 }
3044 /** Unbox an object to a primitive value. */
3045 JCExpression unbox(JCExpression tree, Type primitive) {
3046 Type unboxedType = types.unboxedType(tree.type);
3047 if (unboxedType.hasTag(NONE)) {
3048 unboxedType = primitive;
3049 if (!unboxedType.isPrimitive())
3050 throw new AssertionError(unboxedType);
3051 make_at(tree.pos());
3052 tree = make.TypeCast(types.boxedClass(unboxedType).type, tree);
3053 } else {
3054 // There must be a conversion from unboxedType to primitive.
3055 if (!types.isSubtype(unboxedType, primitive))
3056 throw new AssertionError(tree);
3057 }
3058 make_at(tree.pos());
3059 Symbol valueSym = lookupMethod(tree.pos(),
3060 unboxedType.tsym.name.append(names.Value), // x.intValue()
3061 tree.type,
3062 List.<Type>nil());
3063 return make.App(make.Select(tree, valueSym));
3064 }
3066 /** Visitor method for parenthesized expressions.
3067 * If the subexpression has changed, omit the parens.
3068 */
3069 public void visitParens(JCParens tree) {
3070 JCTree expr = translate(tree.expr);
3071 result = ((expr == tree.expr) ? tree : expr);
3072 }
3074 public void visitIndexed(JCArrayAccess tree) {
3075 tree.indexed = translate(tree.indexed);
3076 tree.index = translate(tree.index, syms.intType);
3077 result = tree;
3078 }
3080 public void visitAssign(JCAssign tree) {
3081 tree.lhs = translate(tree.lhs, tree);
3082 tree.rhs = translate(tree.rhs, tree.lhs.type);
3084 // If translated left hand side is an Apply, we are
3085 // seeing an access method invocation. In this case, append
3086 // right hand side as last argument of the access method.
3087 if (tree.lhs.hasTag(APPLY)) {
3088 JCMethodInvocation app = (JCMethodInvocation)tree.lhs;
3089 app.args = List.of(tree.rhs).prependList(app.args);
3090 result = app;
3091 } else {
3092 result = tree;
3093 }
3094 }
3096 public void visitAssignop(final JCAssignOp tree) {
3097 final boolean boxingReq = !tree.lhs.type.isPrimitive() &&
3098 tree.operator.type.getReturnType().isPrimitive();
3100 // boxing required; need to rewrite as x = (unbox typeof x)(x op y);
3101 // or if x == (typeof x)z then z = (unbox typeof x)((typeof x)z op y)
3102 // (but without recomputing x)
3103 JCTree newTree = abstractLval(tree.lhs, new TreeBuilder() {
3104 public JCTree build(final JCTree lhs) {
3105 JCTree.Tag newTag = tree.getTag().noAssignOp();
3106 // Erasure (TransTypes) can change the type of
3107 // tree.lhs. However, we can still get the
3108 // unerased type of tree.lhs as it is stored
3109 // in tree.type in Attr.
3110 Symbol newOperator = rs.resolveBinaryOperator(tree.pos(),
3111 newTag,
3112 attrEnv,
3113 tree.type,
3114 tree.rhs.type);
3115 JCExpression expr = (JCExpression)lhs;
3116 if (expr.type != tree.type)
3117 expr = make.TypeCast(tree.type, expr);
3118 JCBinary opResult = make.Binary(newTag, expr, tree.rhs);
3119 opResult.operator = newOperator;
3120 opResult.type = newOperator.type.getReturnType();
3121 JCExpression newRhs = boxingReq ?
3122 make.TypeCast(types.unboxedType(tree.type),
3123 opResult) :
3124 opResult;
3125 return make.Assign((JCExpression)lhs, newRhs).setType(tree.type);
3126 }
3127 });
3128 result = translate(newTree);
3129 }
3131 /** Lower a tree of the form e++ or e-- where e is an object type */
3132 JCTree lowerBoxedPostop(final JCUnary tree) {
3133 // translate to tmp1=lval(e); tmp2=tmp1; tmp1 OP 1; tmp2
3134 // or
3135 // translate to tmp1=lval(e); tmp2=tmp1; (typeof tree)tmp1 OP 1; tmp2
3136 // where OP is += or -=
3137 final boolean cast = TreeInfo.skipParens(tree.arg).hasTag(TYPECAST);
3138 return abstractLval(tree.arg, new TreeBuilder() {
3139 public JCTree build(final JCTree tmp1) {
3140 return abstractRval(tmp1, tree.arg.type, new TreeBuilder() {
3141 public JCTree build(final JCTree tmp2) {
3142 JCTree.Tag opcode = (tree.hasTag(POSTINC))
3143 ? PLUS_ASG : MINUS_ASG;
3144 JCTree lhs = cast
3145 ? make.TypeCast(tree.arg.type, (JCExpression)tmp1)
3146 : tmp1;
3147 JCTree update = makeAssignop(opcode,
3148 lhs,
3149 make.Literal(1));
3150 return makeComma(update, tmp2);
3151 }
3152 });
3153 }
3154 });
3155 }
3157 public void visitUnary(JCUnary tree) {
3158 boolean isUpdateOperator = tree.getTag().isIncOrDecUnaryOp();
3159 if (isUpdateOperator && !tree.arg.type.isPrimitive()) {
3160 switch(tree.getTag()) {
3161 case PREINC: // ++ e
3162 // translate to e += 1
3163 case PREDEC: // -- e
3164 // translate to e -= 1
3165 {
3166 JCTree.Tag opcode = (tree.hasTag(PREINC))
3167 ? PLUS_ASG : MINUS_ASG;
3168 JCAssignOp newTree = makeAssignop(opcode,
3169 tree.arg,
3170 make.Literal(1));
3171 result = translate(newTree, tree.type);
3172 return;
3173 }
3174 case POSTINC: // e ++
3175 case POSTDEC: // e --
3176 {
3177 result = translate(lowerBoxedPostop(tree), tree.type);
3178 return;
3179 }
3180 }
3181 throw new AssertionError(tree);
3182 }
3184 tree.arg = boxIfNeeded(translate(tree.arg, tree), tree.type);
3186 if (tree.hasTag(NOT) && tree.arg.type.constValue() != null) {
3187 tree.type = cfolder.fold1(bool_not, tree.arg.type);
3188 }
3190 // If translated left hand side is an Apply, we are
3191 // seeing an access method invocation. In this case, return
3192 // that access method invocation as result.
3193 if (isUpdateOperator && tree.arg.hasTag(APPLY)) {
3194 result = tree.arg;
3195 } else {
3196 result = tree;
3197 }
3198 }
3200 public void visitBinary(JCBinary tree) {
3201 List<Type> formals = tree.operator.type.getParameterTypes();
3202 JCTree lhs = tree.lhs = translate(tree.lhs, formals.head);
3203 switch (tree.getTag()) {
3204 case OR:
3205 if (lhs.type.isTrue()) {
3206 result = lhs;
3207 return;
3208 }
3209 if (lhs.type.isFalse()) {
3210 result = translate(tree.rhs, formals.tail.head);
3211 return;
3212 }
3213 break;
3214 case AND:
3215 if (lhs.type.isFalse()) {
3216 result = lhs;
3217 return;
3218 }
3219 if (lhs.type.isTrue()) {
3220 result = translate(tree.rhs, formals.tail.head);
3221 return;
3222 }
3223 break;
3224 }
3225 tree.rhs = translate(tree.rhs, formals.tail.head);
3226 result = tree;
3227 }
3229 public void visitIdent(JCIdent tree) {
3230 result = access(tree.sym, tree, enclOp, false);
3231 }
3233 /** Translate away the foreach loop. */
3234 public void visitForeachLoop(JCEnhancedForLoop tree) {
3235 if (types.elemtype(tree.expr.type) == null)
3236 visitIterableForeachLoop(tree);
3237 else
3238 visitArrayForeachLoop(tree);
3239 }
3240 // where
3241 /**
3242 * A statement of the form
3243 *
3244 * <pre>
3245 * for ( T v : arrayexpr ) stmt;
3246 * </pre>
3247 *
3248 * (where arrayexpr is of an array type) gets translated to
3249 *
3250 * <pre>{@code
3251 * for ( { arraytype #arr = arrayexpr;
3252 * int #len = array.length;
3253 * int #i = 0; };
3254 * #i < #len; i$++ ) {
3255 * T v = arr$[#i];
3256 * stmt;
3257 * }
3258 * }</pre>
3259 *
3260 * where #arr, #len, and #i are freshly named synthetic local variables.
3261 */
3262 private void visitArrayForeachLoop(JCEnhancedForLoop tree) {
3263 make_at(tree.expr.pos());
3264 VarSymbol arraycache = new VarSymbol(0,
3265 names.fromString("arr" + target.syntheticNameChar()),
3266 tree.expr.type,
3267 currentMethodSym);
3268 JCStatement arraycachedef = make.VarDef(arraycache, tree.expr);
3269 VarSymbol lencache = new VarSymbol(0,
3270 names.fromString("len" + target.syntheticNameChar()),
3271 syms.intType,
3272 currentMethodSym);
3273 JCStatement lencachedef = make.
3274 VarDef(lencache, make.Select(make.Ident(arraycache), syms.lengthVar));
3275 VarSymbol index = new VarSymbol(0,
3276 names.fromString("i" + target.syntheticNameChar()),
3277 syms.intType,
3278 currentMethodSym);
3280 JCVariableDecl indexdef = make.VarDef(index, make.Literal(INT, 0));
3281 indexdef.init.type = indexdef.type = syms.intType.constType(0);
3283 List<JCStatement> loopinit = List.of(arraycachedef, lencachedef, indexdef);
3284 JCBinary cond = makeBinary(LT, make.Ident(index), make.Ident(lencache));
3286 JCExpressionStatement step = make.Exec(makeUnary(PREINC, make.Ident(index)));
3288 Type elemtype = types.elemtype(tree.expr.type);
3289 JCExpression loopvarinit = make.Indexed(make.Ident(arraycache),
3290 make.Ident(index)).setType(elemtype);
3291 JCVariableDecl loopvardef = (JCVariableDecl)make.VarDef(tree.var.mods,
3292 tree.var.name,
3293 tree.var.vartype,
3294 loopvarinit).setType(tree.var.type);
3295 loopvardef.sym = tree.var.sym;
3296 JCBlock body = make.
3297 Block(0, List.of(loopvardef, tree.body));
3299 result = translate(make.
3300 ForLoop(loopinit,
3301 cond,
3302 List.of(step),
3303 body));
3304 patchTargets(body, tree, result);
3305 }
3306 /** Patch up break and continue targets. */
3307 private void patchTargets(JCTree body, final JCTree src, final JCTree dest) {
3308 class Patcher extends TreeScanner {
3309 public void visitBreak(JCBreak tree) {
3310 if (tree.target == src)
3311 tree.target = dest;
3312 }
3313 public void visitContinue(JCContinue tree) {
3314 if (tree.target == src)
3315 tree.target = dest;
3316 }
3317 public void visitClassDef(JCClassDecl tree) {}
3318 }
3319 new Patcher().scan(body);
3320 }
3321 /**
3322 * A statement of the form
3323 *
3324 * <pre>
3325 * for ( T v : coll ) stmt ;
3326 * </pre>
3327 *
3328 * (where coll implements {@code Iterable<? extends T>}) gets translated to
3329 *
3330 * <pre>{@code
3331 * for ( Iterator<? extends T> #i = coll.iterator(); #i.hasNext(); ) {
3332 * T v = (T) #i.next();
3333 * stmt;
3334 * }
3335 * }</pre>
3336 *
3337 * where #i is a freshly named synthetic local variable.
3338 */
3339 private void visitIterableForeachLoop(JCEnhancedForLoop tree) {
3340 make_at(tree.expr.pos());
3341 Type iteratorTarget = syms.objectType;
3342 Type iterableType = types.asSuper(types.upperBound(tree.expr.type),
3343 syms.iterableType.tsym);
3344 if (iterableType.getTypeArguments().nonEmpty())
3345 iteratorTarget = types.erasure(iterableType.getTypeArguments().head);
3346 Type eType = tree.expr.type;
3347 tree.expr.type = types.erasure(eType);
3348 if (eType.hasTag(TYPEVAR) && eType.getUpperBound().isCompound())
3349 tree.expr = make.TypeCast(types.erasure(iterableType), tree.expr);
3350 Symbol iterator = lookupMethod(tree.expr.pos(),
3351 names.iterator,
3352 types.erasure(syms.iterableType),
3353 List.<Type>nil());
3354 VarSymbol itvar = new VarSymbol(0, names.fromString("i" + target.syntheticNameChar()),
3355 types.erasure(iterator.type.getReturnType()),
3356 currentMethodSym);
3357 JCStatement init = make.
3358 VarDef(itvar,
3359 make.App(make.Select(tree.expr, iterator)));
3360 Symbol hasNext = lookupMethod(tree.expr.pos(),
3361 names.hasNext,
3362 itvar.type,
3363 List.<Type>nil());
3364 JCMethodInvocation cond = make.App(make.Select(make.Ident(itvar), hasNext));
3365 Symbol next = lookupMethod(tree.expr.pos(),
3366 names.next,
3367 itvar.type,
3368 List.<Type>nil());
3369 JCExpression vardefinit = make.App(make.Select(make.Ident(itvar), next));
3370 if (tree.var.type.isPrimitive())
3371 vardefinit = make.TypeCast(types.upperBound(iteratorTarget), vardefinit);
3372 else
3373 vardefinit = make.TypeCast(tree.var.type, vardefinit);
3374 JCVariableDecl indexDef = (JCVariableDecl)make.VarDef(tree.var.mods,
3375 tree.var.name,
3376 tree.var.vartype,
3377 vardefinit).setType(tree.var.type);
3378 indexDef.sym = tree.var.sym;
3379 JCBlock body = make.Block(0, List.of(indexDef, tree.body));
3380 body.endpos = TreeInfo.endPos(tree.body);
3381 result = translate(make.
3382 ForLoop(List.of(init),
3383 cond,
3384 List.<JCExpressionStatement>nil(),
3385 body));
3386 patchTargets(body, tree, result);
3387 }
3389 public void visitVarDef(JCVariableDecl tree) {
3390 MethodSymbol oldMethodSym = currentMethodSym;
3391 tree.mods = translate(tree.mods);
3392 tree.vartype = translate(tree.vartype);
3393 if (currentMethodSym == null) {
3394 // A class or instance field initializer.
3395 currentMethodSym =
3396 new MethodSymbol((tree.mods.flags&STATIC) | BLOCK,
3397 names.empty, null,
3398 currentClass);
3399 }
3400 if (tree.init != null) tree.init = translate(tree.init, tree.type);
3401 result = tree;
3402 currentMethodSym = oldMethodSym;
3403 }
3405 public void visitBlock(JCBlock tree) {
3406 MethodSymbol oldMethodSym = currentMethodSym;
3407 if (currentMethodSym == null) {
3408 // Block is a static or instance initializer.
3409 currentMethodSym =
3410 new MethodSymbol(tree.flags | BLOCK,
3411 names.empty, null,
3412 currentClass);
3413 }
3414 super.visitBlock(tree);
3415 currentMethodSym = oldMethodSym;
3416 }
3418 public void visitDoLoop(JCDoWhileLoop tree) {
3419 tree.body = translate(tree.body);
3420 tree.cond = translate(tree.cond, syms.booleanType);
3421 result = tree;
3422 }
3424 public void visitWhileLoop(JCWhileLoop tree) {
3425 tree.cond = translate(tree.cond, syms.booleanType);
3426 tree.body = translate(tree.body);
3427 result = tree;
3428 }
3430 public void visitForLoop(JCForLoop tree) {
3431 tree.init = translate(tree.init);
3432 if (tree.cond != null)
3433 tree.cond = translate(tree.cond, syms.booleanType);
3434 tree.step = translate(tree.step);
3435 tree.body = translate(tree.body);
3436 result = tree;
3437 }
3439 public void visitReturn(JCReturn tree) {
3440 if (tree.expr != null)
3441 tree.expr = translate(tree.expr,
3442 types.erasure(currentMethodDef
3443 .restype.type));
3444 result = tree;
3445 }
3447 public void visitSwitch(JCSwitch tree) {
3448 Type selsuper = types.supertype(tree.selector.type);
3449 boolean enumSwitch = selsuper != null &&
3450 (tree.selector.type.tsym.flags() & ENUM) != 0;
3451 boolean stringSwitch = selsuper != null &&
3452 types.isSameType(tree.selector.type, syms.stringType);
3453 Type target = enumSwitch ? tree.selector.type :
3454 (stringSwitch? syms.stringType : syms.intType);
3455 tree.selector = translate(tree.selector, target);
3456 tree.cases = translateCases(tree.cases);
3457 if (enumSwitch) {
3458 result = visitEnumSwitch(tree);
3459 } else if (stringSwitch) {
3460 result = visitStringSwitch(tree);
3461 } else {
3462 result = tree;
3463 }
3464 }
3466 public JCTree visitEnumSwitch(JCSwitch tree) {
3467 TypeSymbol enumSym = tree.selector.type.tsym;
3468 EnumMapping map = mapForEnum(tree.pos(), enumSym);
3469 make_at(tree.pos());
3470 Symbol ordinalMethod = lookupMethod(tree.pos(),
3471 names.ordinal,
3472 tree.selector.type,
3473 List.<Type>nil());
3474 JCArrayAccess selector = make.Indexed(map.mapVar,
3475 make.App(make.Select(tree.selector,
3476 ordinalMethod)));
3477 ListBuffer<JCCase> cases = new ListBuffer<JCCase>();
3478 for (JCCase c : tree.cases) {
3479 if (c.pat != null) {
3480 VarSymbol label = (VarSymbol)TreeInfo.symbol(c.pat);
3481 JCLiteral pat = map.forConstant(label);
3482 cases.append(make.Case(pat, c.stats));
3483 } else {
3484 cases.append(c);
3485 }
3486 }
3487 JCSwitch enumSwitch = make.Switch(selector, cases.toList());
3488 patchTargets(enumSwitch, tree, enumSwitch);
3489 return enumSwitch;
3490 }
3492 public JCTree visitStringSwitch(JCSwitch tree) {
3493 List<JCCase> caseList = tree.getCases();
3494 int alternatives = caseList.size();
3496 if (alternatives == 0) { // Strange but legal possibility
3497 return make.at(tree.pos()).Exec(attr.makeNullCheck(tree.getExpression()));
3498 } else {
3499 /*
3500 * The general approach used is to translate a single
3501 * string switch statement into a series of two chained
3502 * switch statements: the first a synthesized statement
3503 * switching on the argument string's hash value and
3504 * computing a string's position in the list of original
3505 * case labels, if any, followed by a second switch on the
3506 * computed integer value. The second switch has the same
3507 * code structure as the original string switch statement
3508 * except that the string case labels are replaced with
3509 * positional integer constants starting at 0.
3510 *
3511 * The first switch statement can be thought of as an
3512 * inlined map from strings to their position in the case
3513 * label list. An alternate implementation would use an
3514 * actual Map for this purpose, as done for enum switches.
3515 *
3516 * With some additional effort, it would be possible to
3517 * use a single switch statement on the hash code of the
3518 * argument, but care would need to be taken to preserve
3519 * the proper control flow in the presence of hash
3520 * collisions and other complications, such as
3521 * fallthroughs. Switch statements with one or two
3522 * alternatives could also be specially translated into
3523 * if-then statements to omit the computation of the hash
3524 * code.
3525 *
3526 * The generated code assumes that the hashing algorithm
3527 * of String is the same in the compilation environment as
3528 * in the environment the code will run in. The string
3529 * hashing algorithm in the SE JDK has been unchanged
3530 * since at least JDK 1.2. Since the algorithm has been
3531 * specified since that release as well, it is very
3532 * unlikely to be changed in the future.
3533 *
3534 * Different hashing algorithms, such as the length of the
3535 * strings or a perfect hashing algorithm over the
3536 * particular set of case labels, could potentially be
3537 * used instead of String.hashCode.
3538 */
3540 ListBuffer<JCStatement> stmtList = new ListBuffer<JCStatement>();
3542 // Map from String case labels to their original position in
3543 // the list of case labels.
3544 Map<String, Integer> caseLabelToPosition =
3545 new LinkedHashMap<String, Integer>(alternatives + 1, 1.0f);
3547 // Map of hash codes to the string case labels having that hashCode.
3548 Map<Integer, Set<String>> hashToString =
3549 new LinkedHashMap<Integer, Set<String>>(alternatives + 1, 1.0f);
3551 int casePosition = 0;
3552 for(JCCase oneCase : caseList) {
3553 JCExpression expression = oneCase.getExpression();
3555 if (expression != null) { // expression for a "default" case is null
3556 String labelExpr = (String) expression.type.constValue();
3557 Integer mapping = caseLabelToPosition.put(labelExpr, casePosition);
3558 Assert.checkNull(mapping);
3559 int hashCode = labelExpr.hashCode();
3561 Set<String> stringSet = hashToString.get(hashCode);
3562 if (stringSet == null) {
3563 stringSet = new LinkedHashSet<String>(1, 1.0f);
3564 stringSet.add(labelExpr);
3565 hashToString.put(hashCode, stringSet);
3566 } else {
3567 boolean added = stringSet.add(labelExpr);
3568 Assert.check(added);
3569 }
3570 }
3571 casePosition++;
3572 }
3574 // Synthesize a switch statement that has the effect of
3575 // mapping from a string to the integer position of that
3576 // string in the list of case labels. This is done by
3577 // switching on the hashCode of the string followed by an
3578 // if-then-else chain comparing the input for equality
3579 // with all the case labels having that hash value.
3581 /*
3582 * s$ = top of stack;
3583 * tmp$ = -1;
3584 * switch($s.hashCode()) {
3585 * case caseLabel.hashCode:
3586 * if (s$.equals("caseLabel_1")
3587 * tmp$ = caseLabelToPosition("caseLabel_1");
3588 * else if (s$.equals("caseLabel_2"))
3589 * tmp$ = caseLabelToPosition("caseLabel_2");
3590 * ...
3591 * break;
3592 * ...
3593 * }
3594 */
3596 VarSymbol dollar_s = new VarSymbol(FINAL|SYNTHETIC,
3597 names.fromString("s" + tree.pos + target.syntheticNameChar()),
3598 syms.stringType,
3599 currentMethodSym);
3600 stmtList.append(make.at(tree.pos()).VarDef(dollar_s, tree.getExpression()).setType(dollar_s.type));
3602 VarSymbol dollar_tmp = new VarSymbol(SYNTHETIC,
3603 names.fromString("tmp" + tree.pos + target.syntheticNameChar()),
3604 syms.intType,
3605 currentMethodSym);
3606 JCVariableDecl dollar_tmp_def =
3607 (JCVariableDecl)make.VarDef(dollar_tmp, make.Literal(INT, -1)).setType(dollar_tmp.type);
3608 dollar_tmp_def.init.type = dollar_tmp.type = syms.intType;
3609 stmtList.append(dollar_tmp_def);
3610 ListBuffer<JCCase> caseBuffer = ListBuffer.lb();
3611 // hashCode will trigger nullcheck on original switch expression
3612 JCMethodInvocation hashCodeCall = makeCall(make.Ident(dollar_s),
3613 names.hashCode,
3614 List.<JCExpression>nil()).setType(syms.intType);
3615 JCSwitch switch1 = make.Switch(hashCodeCall,
3616 caseBuffer.toList());
3617 for(Map.Entry<Integer, Set<String>> entry : hashToString.entrySet()) {
3618 int hashCode = entry.getKey();
3619 Set<String> stringsWithHashCode = entry.getValue();
3620 Assert.check(stringsWithHashCode.size() >= 1);
3622 JCStatement elsepart = null;
3623 for(String caseLabel : stringsWithHashCode ) {
3624 JCMethodInvocation stringEqualsCall = makeCall(make.Ident(dollar_s),
3625 names.equals,
3626 List.<JCExpression>of(make.Literal(caseLabel)));
3627 elsepart = make.If(stringEqualsCall,
3628 make.Exec(make.Assign(make.Ident(dollar_tmp),
3629 make.Literal(caseLabelToPosition.get(caseLabel))).
3630 setType(dollar_tmp.type)),
3631 elsepart);
3632 }
3634 ListBuffer<JCStatement> lb = ListBuffer.lb();
3635 JCBreak breakStmt = make.Break(null);
3636 breakStmt.target = switch1;
3637 lb.append(elsepart).append(breakStmt);
3639 caseBuffer.append(make.Case(make.Literal(hashCode), lb.toList()));
3640 }
3642 switch1.cases = caseBuffer.toList();
3643 stmtList.append(switch1);
3645 // Make isomorphic switch tree replacing string labels
3646 // with corresponding integer ones from the label to
3647 // position map.
3649 ListBuffer<JCCase> lb = ListBuffer.lb();
3650 JCSwitch switch2 = make.Switch(make.Ident(dollar_tmp), lb.toList());
3651 for(JCCase oneCase : caseList ) {
3652 // Rewire up old unlabeled break statements to the
3653 // replacement switch being created.
3654 patchTargets(oneCase, tree, switch2);
3656 boolean isDefault = (oneCase.getExpression() == null);
3657 JCExpression caseExpr;
3658 if (isDefault)
3659 caseExpr = null;
3660 else {
3661 caseExpr = make.Literal(caseLabelToPosition.get((String)TreeInfo.skipParens(oneCase.
3662 getExpression()).
3663 type.constValue()));
3664 }
3666 lb.append(make.Case(caseExpr,
3667 oneCase.getStatements()));
3668 }
3670 switch2.cases = lb.toList();
3671 stmtList.append(switch2);
3673 return make.Block(0L, stmtList.toList());
3674 }
3675 }
3677 public void visitNewArray(JCNewArray tree) {
3678 tree.elemtype = translate(tree.elemtype);
3679 for (List<JCExpression> t = tree.dims; t.tail != null; t = t.tail)
3680 if (t.head != null) t.head = translate(t.head, syms.intType);
3681 tree.elems = translate(tree.elems, types.elemtype(tree.type));
3682 result = tree;
3683 }
3685 public void visitSelect(JCFieldAccess tree) {
3686 // need to special case-access of the form C.super.x
3687 // these will always need an access method, unless C
3688 // is a default interface subclassed by the current class.
3689 boolean qualifiedSuperAccess =
3690 tree.selected.hasTag(SELECT) &&
3691 TreeInfo.name(tree.selected) == names._super &&
3692 !types.isDirectSuperInterface(((JCFieldAccess)tree.selected).selected.type.tsym, currentClass);
3693 tree.selected = translate(tree.selected);
3694 if (tree.name == names._class) {
3695 result = classOf(tree.selected);
3696 }
3697 else if (tree.name == names._super &&
3698 types.isDirectSuperInterface(tree.selected.type.tsym, currentClass)) {
3699 //default super call!! Not a classic qualified super call
3700 TypeSymbol supSym = tree.selected.type.tsym;
3701 Assert.checkNonNull(types.asSuper(currentClass.type, supSym));
3702 result = tree;
3703 }
3704 else if (tree.name == names._this || tree.name == names._super) {
3705 result = makeThis(tree.pos(), tree.selected.type.tsym);
3706 }
3707 else
3708 result = access(tree.sym, tree, enclOp, qualifiedSuperAccess);
3709 }
3711 public void visitLetExpr(LetExpr tree) {
3712 tree.defs = translateVarDefs(tree.defs);
3713 tree.expr = translate(tree.expr, tree.type);
3714 result = tree;
3715 }
3717 // There ought to be nothing to rewrite here;
3718 // we don't generate code.
3719 public void visitAnnotation(JCAnnotation tree) {
3720 result = tree;
3721 }
3723 @Override
3724 public void visitTry(JCTry tree) {
3725 if (tree.resources.isEmpty()) {
3726 super.visitTry(tree);
3727 } else {
3728 result = makeTwrTry(tree);
3729 }
3730 }
3732 /**************************************************************************
3733 * main method
3734 *************************************************************************/
3736 /** Translate a toplevel class and return a list consisting of
3737 * the translated class and translated versions of all inner classes.
3738 * @param env The attribution environment current at the class definition.
3739 * We need this for resolving some additional symbols.
3740 * @param cdef The tree representing the class definition.
3741 */
3742 public List<JCTree> translateTopLevelClass(Env<AttrContext> env, JCTree cdef, TreeMaker make) {
3743 ListBuffer<JCTree> translated = null;
3744 try {
3745 attrEnv = env;
3746 this.make = make;
3747 endPosTable = env.toplevel.endPositions;
3748 currentClass = null;
3749 currentMethodDef = null;
3750 outermostClassDef = (cdef.hasTag(CLASSDEF)) ? (JCClassDecl)cdef : null;
3751 outermostMemberDef = null;
3752 this.translated = new ListBuffer<JCTree>();
3753 classdefs = new HashMap<ClassSymbol,JCClassDecl>();
3754 actualSymbols = new HashMap<Symbol,Symbol>();
3755 freevarCache = new HashMap<ClassSymbol,List<VarSymbol>>();
3756 proxies = new Scope(syms.noSymbol);
3757 twrVars = new Scope(syms.noSymbol);
3758 outerThisStack = List.nil();
3759 accessNums = new HashMap<Symbol,Integer>();
3760 accessSyms = new HashMap<Symbol,MethodSymbol[]>();
3761 accessConstrs = new HashMap<Symbol,MethodSymbol>();
3762 accessConstrTags = List.nil();
3763 accessed = new ListBuffer<Symbol>();
3764 translate(cdef, (JCExpression)null);
3765 for (List<Symbol> l = accessed.toList(); l.nonEmpty(); l = l.tail)
3766 makeAccessible(l.head);
3767 for (EnumMapping map : enumSwitchMap.values())
3768 map.translate();
3769 checkConflicts(this.translated.toList());
3770 checkAccessConstructorTags();
3771 translated = this.translated;
3772 } finally {
3773 // note that recursive invocations of this method fail hard
3774 attrEnv = null;
3775 this.make = null;
3776 endPosTable = null;
3777 currentClass = null;
3778 currentMethodDef = null;
3779 outermostClassDef = null;
3780 outermostMemberDef = null;
3781 this.translated = null;
3782 classdefs = null;
3783 actualSymbols = null;
3784 freevarCache = null;
3785 proxies = null;
3786 outerThisStack = null;
3787 accessNums = null;
3788 accessSyms = null;
3789 accessConstrs = null;
3790 accessConstrTags = null;
3791 accessed = null;
3792 enumSwitchMap.clear();
3793 }
3794 return translated.toList();
3795 }
3797 //////////////////////////////////////////////////////////////
3798 // The following contributed by Borland for bootstrapping purposes
3799 //////////////////////////////////////////////////////////////
3800 private void addEnumCompatibleMembers(JCClassDecl cdef) {
3801 make_at(null);
3803 // Add the special enum fields
3804 VarSymbol ordinalFieldSym = addEnumOrdinalField(cdef);
3805 VarSymbol nameFieldSym = addEnumNameField(cdef);
3807 // Add the accessor methods for name and ordinal
3808 MethodSymbol ordinalMethodSym = addEnumFieldOrdinalMethod(cdef, ordinalFieldSym);
3809 MethodSymbol nameMethodSym = addEnumFieldNameMethod(cdef, nameFieldSym);
3811 // Add the toString method
3812 addEnumToString(cdef, nameFieldSym);
3814 // Add the compareTo method
3815 addEnumCompareTo(cdef, ordinalFieldSym);
3816 }
3818 private VarSymbol addEnumOrdinalField(JCClassDecl cdef) {
3819 VarSymbol ordinal = new VarSymbol(PRIVATE|FINAL|SYNTHETIC,
3820 names.fromString("$ordinal"),
3821 syms.intType,
3822 cdef.sym);
3823 cdef.sym.members().enter(ordinal);
3824 cdef.defs = cdef.defs.prepend(make.VarDef(ordinal, null));
3825 return ordinal;
3826 }
3828 private VarSymbol addEnumNameField(JCClassDecl cdef) {
3829 VarSymbol name = new VarSymbol(PRIVATE|FINAL|SYNTHETIC,
3830 names.fromString("$name"),
3831 syms.stringType,
3832 cdef.sym);
3833 cdef.sym.members().enter(name);
3834 cdef.defs = cdef.defs.prepend(make.VarDef(name, null));
3835 return name;
3836 }
3838 private MethodSymbol addEnumFieldOrdinalMethod(JCClassDecl cdef, VarSymbol ordinalSymbol) {
3839 // Add the accessor methods for ordinal
3840 Symbol ordinalSym = lookupMethod(cdef.pos(),
3841 names.ordinal,
3842 cdef.type,
3843 List.<Type>nil());
3845 Assert.check(ordinalSym instanceof MethodSymbol);
3847 JCStatement ret = make.Return(make.Ident(ordinalSymbol));
3848 cdef.defs = cdef.defs.append(make.MethodDef((MethodSymbol)ordinalSym,
3849 make.Block(0L, List.of(ret))));
3851 return (MethodSymbol)ordinalSym;
3852 }
3854 private MethodSymbol addEnumFieldNameMethod(JCClassDecl cdef, VarSymbol nameSymbol) {
3855 // Add the accessor methods for name
3856 Symbol nameSym = lookupMethod(cdef.pos(),
3857 names._name,
3858 cdef.type,
3859 List.<Type>nil());
3861 Assert.check(nameSym instanceof MethodSymbol);
3863 JCStatement ret = make.Return(make.Ident(nameSymbol));
3865 cdef.defs = cdef.defs.append(make.MethodDef((MethodSymbol)nameSym,
3866 make.Block(0L, List.of(ret))));
3868 return (MethodSymbol)nameSym;
3869 }
3871 private MethodSymbol addEnumToString(JCClassDecl cdef,
3872 VarSymbol nameSymbol) {
3873 Symbol toStringSym = lookupMethod(cdef.pos(),
3874 names.toString,
3875 cdef.type,
3876 List.<Type>nil());
3878 JCTree toStringDecl = null;
3879 if (toStringSym != null)
3880 toStringDecl = TreeInfo.declarationFor(toStringSym, cdef);
3882 if (toStringDecl != null)
3883 return (MethodSymbol)toStringSym;
3885 JCStatement ret = make.Return(make.Ident(nameSymbol));
3887 JCTree resTypeTree = make.Type(syms.stringType);
3889 MethodType toStringType = new MethodType(List.<Type>nil(),
3890 syms.stringType,
3891 List.<Type>nil(),
3892 cdef.sym);
3893 toStringSym = new MethodSymbol(PUBLIC,
3894 names.toString,
3895 toStringType,
3896 cdef.type.tsym);
3897 toStringDecl = make.MethodDef((MethodSymbol)toStringSym,
3898 make.Block(0L, List.of(ret)));
3900 cdef.defs = cdef.defs.prepend(toStringDecl);
3901 cdef.sym.members().enter(toStringSym);
3903 return (MethodSymbol)toStringSym;
3904 }
3906 private MethodSymbol addEnumCompareTo(JCClassDecl cdef, VarSymbol ordinalSymbol) {
3907 Symbol compareToSym = lookupMethod(cdef.pos(),
3908 names.compareTo,
3909 cdef.type,
3910 List.of(cdef.sym.type));
3912 Assert.check(compareToSym instanceof MethodSymbol);
3914 JCMethodDecl compareToDecl = (JCMethodDecl) TreeInfo.declarationFor(compareToSym, cdef);
3916 ListBuffer<JCStatement> blockStatements = new ListBuffer<JCStatement>();
3918 JCModifiers mod1 = make.Modifiers(0L);
3919 Name oName = names.fromString("o");
3920 JCVariableDecl par1 = make.Param(oName, cdef.type, compareToSym);
3922 JCIdent paramId1 = make.Ident(names.java_lang_Object);
3923 paramId1.type = cdef.type;
3924 paramId1.sym = par1.sym;
3926 ((MethodSymbol)compareToSym).params = List.of(par1.sym);
3928 JCIdent par1UsageId = make.Ident(par1.sym);
3929 JCIdent castTargetIdent = make.Ident(cdef.sym);
3930 JCTypeCast cast = make.TypeCast(castTargetIdent, par1UsageId);
3931 cast.setType(castTargetIdent.type);
3933 Name otherName = names.fromString("other");
3935 VarSymbol otherVarSym = new VarSymbol(mod1.flags,
3936 otherName,
3937 cdef.type,
3938 compareToSym);
3939 JCVariableDecl otherVar = make.VarDef(otherVarSym, cast);
3940 blockStatements.append(otherVar);
3942 JCIdent id1 = make.Ident(ordinalSymbol);
3944 JCIdent fLocUsageId = make.Ident(otherVarSym);
3945 JCExpression sel = make.Select(fLocUsageId, ordinalSymbol);
3946 JCBinary bin = makeBinary(MINUS, id1, sel);
3947 JCReturn ret = make.Return(bin);
3948 blockStatements.append(ret);
3949 JCMethodDecl compareToMethod = make.MethodDef((MethodSymbol)compareToSym,
3950 make.Block(0L,
3951 blockStatements.toList()));
3952 compareToMethod.params = List.of(par1);
3953 cdef.defs = cdef.defs.append(compareToMethod);
3955 return (MethodSymbol)compareToSym;
3956 }
3957 //////////////////////////////////////////////////////////////
3958 // The above contributed by Borland for bootstrapping purposes
3959 //////////////////////////////////////////////////////////////
3960 }