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