Thu, 02 Aug 2012 18:24:01 +0100
7187104: Inference cleanup: remove redundant exception classes in Infer.java
Summary: Remove unused exception classes in Infer.java
Reviewed-by: jjg
1 /*
2 * Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
26 package com.sun.tools.javac.comp;
28 import java.util.*;
30 import com.sun.tools.javac.code.*;
31 import com.sun.tools.javac.jvm.*;
32 import com.sun.tools.javac.main.Option.PkgInfo;
33 import com.sun.tools.javac.tree.*;
34 import com.sun.tools.javac.util.*;
35 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
36 import com.sun.tools.javac.util.List;
38 import com.sun.tools.javac.code.Symbol.*;
39 import com.sun.tools.javac.tree.JCTree.*;
40 import com.sun.tools.javac.code.Type.*;
42 import com.sun.tools.javac.jvm.Target;
43 import com.sun.tools.javac.tree.EndPosTable;
45 import static com.sun.tools.javac.code.Flags.*;
46 import static com.sun.tools.javac.code.Flags.BLOCK;
47 import static com.sun.tools.javac.code.Kinds.*;
48 import static com.sun.tools.javac.code.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 // convert to AutoCloseable if needed
1610 if (types.asSuper(resource.type, syms.autoCloseableType.tsym) == null) {
1611 resource = (JCExpression) convert(resource, syms.autoCloseableType);
1612 }
1614 // create resource.close() method invocation
1615 JCExpression resourceClose = makeCall(resource,
1616 names.close,
1617 List.<JCExpression>nil());
1618 return make.Exec(resourceClose);
1619 }
1621 private JCExpression makeNonNullCheck(JCExpression expression) {
1622 return makeBinary(NE, expression, makeNull());
1623 }
1625 /** Construct a tree that represents the outer instance
1626 * <C.this>. Never pick the current `this'.
1627 * @param pos The source code position to be used for the tree.
1628 * @param c The qualifier class.
1629 */
1630 JCExpression makeOuterThis(DiagnosticPosition pos, TypeSymbol c) {
1631 List<VarSymbol> ots = outerThisStack;
1632 if (ots.isEmpty()) {
1633 log.error(pos, "no.encl.instance.of.type.in.scope", c);
1634 Assert.error();
1635 return makeNull();
1636 }
1637 VarSymbol ot = ots.head;
1638 JCExpression tree = access(make.at(pos).Ident(ot));
1639 TypeSymbol otc = ot.type.tsym;
1640 while (otc != c) {
1641 do {
1642 ots = ots.tail;
1643 if (ots.isEmpty()) {
1644 log.error(pos,
1645 "no.encl.instance.of.type.in.scope",
1646 c);
1647 Assert.error(); // should have been caught in Attr
1648 return tree;
1649 }
1650 ot = ots.head;
1651 } while (ot.owner != otc);
1652 if (otc.owner.kind != PCK && !otc.hasOuterInstance()) {
1653 chk.earlyRefError(pos, c);
1654 Assert.error(); // should have been caught in Attr
1655 return makeNull();
1656 }
1657 tree = access(make.at(pos).Select(tree, ot));
1658 otc = ot.type.tsym;
1659 }
1660 return tree;
1661 }
1663 /** Construct a tree that represents the closest outer instance
1664 * <C.this> such that the given symbol is a member of C.
1665 * @param pos The source code position to be used for the tree.
1666 * @param sym The accessed symbol.
1667 * @param preciseMatch should we accept a type that is a subtype of
1668 * sym's owner, even if it doesn't contain sym
1669 * due to hiding, overriding, or non-inheritance
1670 * due to protection?
1671 */
1672 JCExpression makeOwnerThis(DiagnosticPosition pos, Symbol sym, boolean preciseMatch) {
1673 Symbol c = sym.owner;
1674 if (preciseMatch ? sym.isMemberOf(currentClass, types)
1675 : currentClass.isSubClass(sym.owner, types)) {
1676 // in this case, `this' works fine
1677 return make.at(pos).This(c.erasure(types));
1678 } else {
1679 // need to go via this$n
1680 return makeOwnerThisN(pos, sym, preciseMatch);
1681 }
1682 }
1684 /**
1685 * Similar to makeOwnerThis but will never pick "this".
1686 */
1687 JCExpression makeOwnerThisN(DiagnosticPosition pos, Symbol sym, boolean preciseMatch) {
1688 Symbol c = sym.owner;
1689 List<VarSymbol> ots = outerThisStack;
1690 if (ots.isEmpty()) {
1691 log.error(pos, "no.encl.instance.of.type.in.scope", c);
1692 Assert.error();
1693 return makeNull();
1694 }
1695 VarSymbol ot = ots.head;
1696 JCExpression tree = access(make.at(pos).Ident(ot));
1697 TypeSymbol otc = ot.type.tsym;
1698 while (!(preciseMatch ? sym.isMemberOf(otc, types) : otc.isSubClass(sym.owner, types))) {
1699 do {
1700 ots = ots.tail;
1701 if (ots.isEmpty()) {
1702 log.error(pos,
1703 "no.encl.instance.of.type.in.scope",
1704 c);
1705 Assert.error();
1706 return tree;
1707 }
1708 ot = ots.head;
1709 } while (ot.owner != otc);
1710 tree = access(make.at(pos).Select(tree, ot));
1711 otc = ot.type.tsym;
1712 }
1713 return tree;
1714 }
1716 /** Return tree simulating the assignment <this.name = name>, where
1717 * name is the name of a free variable.
1718 */
1719 JCStatement initField(int pos, Name name) {
1720 Scope.Entry e = proxies.lookup(name);
1721 Symbol rhs = e.sym;
1722 Assert.check(rhs.owner.kind == MTH);
1723 Symbol lhs = e.next().sym;
1724 Assert.check(rhs.owner.owner == lhs.owner);
1725 make.at(pos);
1726 return
1727 make.Exec(
1728 make.Assign(
1729 make.Select(make.This(lhs.owner.erasure(types)), lhs),
1730 make.Ident(rhs)).setType(lhs.erasure(types)));
1731 }
1733 /** Return tree simulating the assignment <this.this$n = this$n>.
1734 */
1735 JCStatement initOuterThis(int pos) {
1736 VarSymbol rhs = outerThisStack.head;
1737 Assert.check(rhs.owner.kind == MTH);
1738 VarSymbol lhs = outerThisStack.tail.head;
1739 Assert.check(rhs.owner.owner == lhs.owner);
1740 make.at(pos);
1741 return
1742 make.Exec(
1743 make.Assign(
1744 make.Select(make.This(lhs.owner.erasure(types)), lhs),
1745 make.Ident(rhs)).setType(lhs.erasure(types)));
1746 }
1748 /**************************************************************************
1749 * Code for .class
1750 *************************************************************************/
1752 /** Return the symbol of a class to contain a cache of
1753 * compiler-generated statics such as class$ and the
1754 * $assertionsDisabled flag. We create an anonymous nested class
1755 * (unless one already exists) and return its symbol. However,
1756 * for backward compatibility in 1.4 and earlier we use the
1757 * top-level class itself.
1758 */
1759 private ClassSymbol outerCacheClass() {
1760 ClassSymbol clazz = outermostClassDef.sym;
1761 if ((clazz.flags() & INTERFACE) == 0 &&
1762 !target.useInnerCacheClass()) return clazz;
1763 Scope s = clazz.members();
1764 for (Scope.Entry e = s.elems; e != null; e = e.sibling)
1765 if (e.sym.kind == TYP &&
1766 e.sym.name == names.empty &&
1767 (e.sym.flags() & INTERFACE) == 0) return (ClassSymbol) e.sym;
1768 return makeEmptyClass(STATIC | SYNTHETIC, clazz);
1769 }
1771 /** Return symbol for "class$" method. If there is no method definition
1772 * for class$, construct one as follows:
1773 *
1774 * class class$(String x0) {
1775 * try {
1776 * return Class.forName(x0);
1777 * } catch (ClassNotFoundException x1) {
1778 * throw new NoClassDefFoundError(x1.getMessage());
1779 * }
1780 * }
1781 */
1782 private MethodSymbol classDollarSym(DiagnosticPosition pos) {
1783 ClassSymbol outerCacheClass = outerCacheClass();
1784 MethodSymbol classDollarSym =
1785 (MethodSymbol)lookupSynthetic(classDollar,
1786 outerCacheClass.members());
1787 if (classDollarSym == null) {
1788 classDollarSym = new MethodSymbol(
1789 STATIC | SYNTHETIC,
1790 classDollar,
1791 new MethodType(
1792 List.of(syms.stringType),
1793 types.erasure(syms.classType),
1794 List.<Type>nil(),
1795 syms.methodClass),
1796 outerCacheClass);
1797 enterSynthetic(pos, classDollarSym, outerCacheClass.members());
1799 JCMethodDecl md = make.MethodDef(classDollarSym, null);
1800 try {
1801 md.body = classDollarSymBody(pos, md);
1802 } catch (CompletionFailure ex) {
1803 md.body = make.Block(0, List.<JCStatement>nil());
1804 chk.completionError(pos, ex);
1805 }
1806 JCClassDecl outerCacheClassDef = classDef(outerCacheClass);
1807 outerCacheClassDef.defs = outerCacheClassDef.defs.prepend(md);
1808 }
1809 return classDollarSym;
1810 }
1812 /** Generate code for class$(String name). */
1813 JCBlock classDollarSymBody(DiagnosticPosition pos, JCMethodDecl md) {
1814 MethodSymbol classDollarSym = md.sym;
1815 ClassSymbol outerCacheClass = (ClassSymbol)classDollarSym.owner;
1817 JCBlock returnResult;
1819 // in 1.4.2 and above, we use
1820 // Class.forName(String name, boolean init, ClassLoader loader);
1821 // which requires we cache the current loader in cl$
1822 if (target.classLiteralsNoInit()) {
1823 // clsym = "private static ClassLoader cl$"
1824 VarSymbol clsym = new VarSymbol(STATIC|SYNTHETIC,
1825 names.fromString("cl" + target.syntheticNameChar()),
1826 syms.classLoaderType,
1827 outerCacheClass);
1828 enterSynthetic(pos, clsym, outerCacheClass.members());
1830 // emit "private static ClassLoader cl$;"
1831 JCVariableDecl cldef = make.VarDef(clsym, null);
1832 JCClassDecl outerCacheClassDef = classDef(outerCacheClass);
1833 outerCacheClassDef.defs = outerCacheClassDef.defs.prepend(cldef);
1835 // newcache := "new cache$1[0]"
1836 JCNewArray newcache = make.
1837 NewArray(make.Type(outerCacheClass.type),
1838 List.<JCExpression>of(make.Literal(INT, 0).setType(syms.intType)),
1839 null);
1840 newcache.type = new ArrayType(types.erasure(outerCacheClass.type),
1841 syms.arrayClass);
1843 // forNameSym := java.lang.Class.forName(
1844 // String s,boolean init,ClassLoader loader)
1845 Symbol forNameSym = lookupMethod(make_pos, names.forName,
1846 types.erasure(syms.classType),
1847 List.of(syms.stringType,
1848 syms.booleanType,
1849 syms.classLoaderType));
1850 // clvalue := "(cl$ == null) ?
1851 // $newcache.getClass().getComponentType().getClassLoader() : cl$"
1852 JCExpression clvalue =
1853 make.Conditional(
1854 makeBinary(EQ, make.Ident(clsym), makeNull()),
1855 make.Assign(
1856 make.Ident(clsym),
1857 makeCall(
1858 makeCall(makeCall(newcache,
1859 names.getClass,
1860 List.<JCExpression>nil()),
1861 names.getComponentType,
1862 List.<JCExpression>nil()),
1863 names.getClassLoader,
1864 List.<JCExpression>nil())).setType(syms.classLoaderType),
1865 make.Ident(clsym)).setType(syms.classLoaderType);
1867 // returnResult := "{ return Class.forName(param1, false, cl$); }"
1868 List<JCExpression> args = List.of(make.Ident(md.params.head.sym),
1869 makeLit(syms.booleanType, 0),
1870 clvalue);
1871 returnResult = make.
1872 Block(0, List.<JCStatement>of(make.
1873 Call(make. // return
1874 App(make.
1875 Ident(forNameSym), args))));
1876 } else {
1877 // forNameSym := java.lang.Class.forName(String s)
1878 Symbol forNameSym = lookupMethod(make_pos,
1879 names.forName,
1880 types.erasure(syms.classType),
1881 List.of(syms.stringType));
1882 // returnResult := "{ return Class.forName(param1); }"
1883 returnResult = make.
1884 Block(0, List.of(make.
1885 Call(make. // return
1886 App(make.
1887 QualIdent(forNameSym),
1888 List.<JCExpression>of(make.
1889 Ident(md.params.
1890 head.sym))))));
1891 }
1893 // catchParam := ClassNotFoundException e1
1894 VarSymbol catchParam =
1895 new VarSymbol(0, make.paramName(1),
1896 syms.classNotFoundExceptionType,
1897 classDollarSym);
1899 JCStatement rethrow;
1900 if (target.hasInitCause()) {
1901 // rethrow = "throw new NoClassDefFoundError().initCause(e);
1902 JCTree throwExpr =
1903 makeCall(makeNewClass(syms.noClassDefFoundErrorType,
1904 List.<JCExpression>nil()),
1905 names.initCause,
1906 List.<JCExpression>of(make.Ident(catchParam)));
1907 rethrow = make.Throw(throwExpr);
1908 } else {
1909 // getMessageSym := ClassNotFoundException.getMessage()
1910 Symbol getMessageSym = lookupMethod(make_pos,
1911 names.getMessage,
1912 syms.classNotFoundExceptionType,
1913 List.<Type>nil());
1914 // rethrow = "throw new NoClassDefFoundError(e.getMessage());"
1915 rethrow = make.
1916 Throw(makeNewClass(syms.noClassDefFoundErrorType,
1917 List.<JCExpression>of(make.App(make.Select(make.Ident(catchParam),
1918 getMessageSym),
1919 List.<JCExpression>nil()))));
1920 }
1922 // rethrowStmt := "( $rethrow )"
1923 JCBlock rethrowStmt = make.Block(0, List.of(rethrow));
1925 // catchBlock := "catch ($catchParam) $rethrowStmt"
1926 JCCatch catchBlock = make.Catch(make.VarDef(catchParam, null),
1927 rethrowStmt);
1929 // tryCatch := "try $returnResult $catchBlock"
1930 JCStatement tryCatch = make.Try(returnResult,
1931 List.of(catchBlock), null);
1933 return make.Block(0, List.of(tryCatch));
1934 }
1935 // where
1936 /** Create an attributed tree of the form left.name(). */
1937 private JCMethodInvocation makeCall(JCExpression left, Name name, List<JCExpression> args) {
1938 Assert.checkNonNull(left.type);
1939 Symbol funcsym = lookupMethod(make_pos, name, left.type,
1940 TreeInfo.types(args));
1941 return make.App(make.Select(left, funcsym), args);
1942 }
1944 /** The Name Of The variable to cache T.class values.
1945 * @param sig The signature of type T.
1946 */
1947 private Name cacheName(String sig) {
1948 StringBuffer buf = new StringBuffer();
1949 if (sig.startsWith("[")) {
1950 buf = buf.append("array");
1951 while (sig.startsWith("[")) {
1952 buf = buf.append(target.syntheticNameChar());
1953 sig = sig.substring(1);
1954 }
1955 if (sig.startsWith("L")) {
1956 sig = sig.substring(0, sig.length() - 1);
1957 }
1958 } else {
1959 buf = buf.append("class" + target.syntheticNameChar());
1960 }
1961 buf = buf.append(sig.replace('.', target.syntheticNameChar()));
1962 return names.fromString(buf.toString());
1963 }
1965 /** The variable symbol that caches T.class values.
1966 * If none exists yet, create a definition.
1967 * @param sig The signature of type T.
1968 * @param pos The position to report diagnostics, if any.
1969 */
1970 private VarSymbol cacheSym(DiagnosticPosition pos, String sig) {
1971 ClassSymbol outerCacheClass = outerCacheClass();
1972 Name cname = cacheName(sig);
1973 VarSymbol cacheSym =
1974 (VarSymbol)lookupSynthetic(cname, outerCacheClass.members());
1975 if (cacheSym == null) {
1976 cacheSym = new VarSymbol(
1977 STATIC | SYNTHETIC, cname, types.erasure(syms.classType), outerCacheClass);
1978 enterSynthetic(pos, cacheSym, outerCacheClass.members());
1980 JCVariableDecl cacheDef = make.VarDef(cacheSym, null);
1981 JCClassDecl outerCacheClassDef = classDef(outerCacheClass);
1982 outerCacheClassDef.defs = outerCacheClassDef.defs.prepend(cacheDef);
1983 }
1984 return cacheSym;
1985 }
1987 /** The tree simulating a T.class expression.
1988 * @param clazz The tree identifying type T.
1989 */
1990 private JCExpression classOf(JCTree clazz) {
1991 return classOfType(clazz.type, clazz.pos());
1992 }
1994 private JCExpression classOfType(Type type, DiagnosticPosition pos) {
1995 switch (type.tag) {
1996 case BYTE: case SHORT: case CHAR: case INT: case LONG: case FLOAT:
1997 case DOUBLE: case BOOLEAN: case VOID:
1998 // replace with <BoxedClass>.TYPE
1999 ClassSymbol c = types.boxedClass(type);
2000 Symbol typeSym =
2001 rs.access(
2002 rs.findIdentInType(attrEnv, c.type, names.TYPE, VAR),
2003 pos, c.type, names.TYPE, true);
2004 if (typeSym.kind == VAR)
2005 ((VarSymbol)typeSym).getConstValue(); // ensure initializer is evaluated
2006 return make.QualIdent(typeSym);
2007 case CLASS: case ARRAY:
2008 if (target.hasClassLiterals()) {
2009 VarSymbol sym = new VarSymbol(
2010 STATIC | PUBLIC | FINAL, names._class,
2011 syms.classType, type.tsym);
2012 return make_at(pos).Select(make.Type(type), sym);
2013 }
2014 // replace with <cache == null ? cache = class$(tsig) : cache>
2015 // where
2016 // - <tsig> is the type signature of T,
2017 // - <cache> is the cache variable for tsig.
2018 String sig =
2019 writer.xClassName(type).toString().replace('/', '.');
2020 Symbol cs = cacheSym(pos, sig);
2021 return make_at(pos).Conditional(
2022 makeBinary(EQ, make.Ident(cs), makeNull()),
2023 make.Assign(
2024 make.Ident(cs),
2025 make.App(
2026 make.Ident(classDollarSym(pos)),
2027 List.<JCExpression>of(make.Literal(CLASS, sig)
2028 .setType(syms.stringType))))
2029 .setType(types.erasure(syms.classType)),
2030 make.Ident(cs)).setType(types.erasure(syms.classType));
2031 default:
2032 throw new AssertionError();
2033 }
2034 }
2036 /**************************************************************************
2037 * Code for enabling/disabling assertions.
2038 *************************************************************************/
2040 // This code is not particularly robust if the user has
2041 // previously declared a member named '$assertionsDisabled'.
2042 // The same faulty idiom also appears in the translation of
2043 // class literals above. We should report an error if a
2044 // previous declaration is not synthetic.
2046 private JCExpression assertFlagTest(DiagnosticPosition pos) {
2047 // Outermost class may be either true class or an interface.
2048 ClassSymbol outermostClass = outermostClassDef.sym;
2050 // note that this is a class, as an interface can't contain a statement.
2051 ClassSymbol container = currentClass;
2053 VarSymbol assertDisabledSym =
2054 (VarSymbol)lookupSynthetic(dollarAssertionsDisabled,
2055 container.members());
2056 if (assertDisabledSym == null) {
2057 assertDisabledSym =
2058 new VarSymbol(STATIC | FINAL | SYNTHETIC,
2059 dollarAssertionsDisabled,
2060 syms.booleanType,
2061 container);
2062 enterSynthetic(pos, assertDisabledSym, container.members());
2063 Symbol desiredAssertionStatusSym = lookupMethod(pos,
2064 names.desiredAssertionStatus,
2065 types.erasure(syms.classType),
2066 List.<Type>nil());
2067 JCClassDecl containerDef = classDef(container);
2068 make_at(containerDef.pos());
2069 JCExpression notStatus = makeUnary(NOT, make.App(make.Select(
2070 classOfType(types.erasure(outermostClass.type),
2071 containerDef.pos()),
2072 desiredAssertionStatusSym)));
2073 JCVariableDecl assertDisabledDef = make.VarDef(assertDisabledSym,
2074 notStatus);
2075 containerDef.defs = containerDef.defs.prepend(assertDisabledDef);
2076 }
2077 make_at(pos);
2078 return makeUnary(NOT, make.Ident(assertDisabledSym));
2079 }
2082 /**************************************************************************
2083 * Building blocks for let expressions
2084 *************************************************************************/
2086 interface TreeBuilder {
2087 JCTree build(JCTree arg);
2088 }
2090 /** Construct an expression using the builder, with the given rval
2091 * expression as an argument to the builder. However, the rval
2092 * expression must be computed only once, even if used multiple
2093 * times in the result of the builder. We do that by
2094 * constructing a "let" expression that saves the rvalue into a
2095 * temporary variable and then uses the temporary variable in
2096 * place of the expression built by the builder. The complete
2097 * resulting expression is of the form
2098 * <pre>
2099 * (let <b>TYPE</b> <b>TEMP</b> = <b>RVAL</b>;
2100 * in (<b>BUILDER</b>(<b>TEMP</b>)))
2101 * </pre>
2102 * where <code><b>TEMP</b></code> is a newly declared variable
2103 * in the let expression.
2104 */
2105 JCTree abstractRval(JCTree rval, Type type, TreeBuilder builder) {
2106 rval = TreeInfo.skipParens(rval);
2107 switch (rval.getTag()) {
2108 case LITERAL:
2109 return builder.build(rval);
2110 case IDENT:
2111 JCIdent id = (JCIdent) rval;
2112 if ((id.sym.flags() & FINAL) != 0 && id.sym.owner.kind == MTH)
2113 return builder.build(rval);
2114 }
2115 VarSymbol var =
2116 new VarSymbol(FINAL|SYNTHETIC,
2117 names.fromString(
2118 target.syntheticNameChar()
2119 + "" + rval.hashCode()),
2120 type,
2121 currentMethodSym);
2122 rval = convert(rval,type);
2123 JCVariableDecl def = make.VarDef(var, (JCExpression)rval); // XXX cast
2124 JCTree built = builder.build(make.Ident(var));
2125 JCTree res = make.LetExpr(def, built);
2126 res.type = built.type;
2127 return res;
2128 }
2130 // same as above, with the type of the temporary variable computed
2131 JCTree abstractRval(JCTree rval, TreeBuilder builder) {
2132 return abstractRval(rval, rval.type, builder);
2133 }
2135 // same as above, but for an expression that may be used as either
2136 // an rvalue or an lvalue. This requires special handling for
2137 // Select expressions, where we place the left-hand-side of the
2138 // select in a temporary, and for Indexed expressions, where we
2139 // place both the indexed expression and the index value in temps.
2140 JCTree abstractLval(JCTree lval, final TreeBuilder builder) {
2141 lval = TreeInfo.skipParens(lval);
2142 switch (lval.getTag()) {
2143 case IDENT:
2144 return builder.build(lval);
2145 case SELECT: {
2146 final JCFieldAccess s = (JCFieldAccess)lval;
2147 JCTree selected = TreeInfo.skipParens(s.selected);
2148 Symbol lid = TreeInfo.symbol(s.selected);
2149 if (lid != null && lid.kind == TYP) return builder.build(lval);
2150 return abstractRval(s.selected, new TreeBuilder() {
2151 public JCTree build(final JCTree selected) {
2152 return builder.build(make.Select((JCExpression)selected, s.sym));
2153 }
2154 });
2155 }
2156 case INDEXED: {
2157 final JCArrayAccess i = (JCArrayAccess)lval;
2158 return abstractRval(i.indexed, new TreeBuilder() {
2159 public JCTree build(final JCTree indexed) {
2160 return abstractRval(i.index, syms.intType, new TreeBuilder() {
2161 public JCTree build(final JCTree index) {
2162 JCTree newLval = make.Indexed((JCExpression)indexed,
2163 (JCExpression)index);
2164 newLval.setType(i.type);
2165 return builder.build(newLval);
2166 }
2167 });
2168 }
2169 });
2170 }
2171 case TYPECAST: {
2172 return abstractLval(((JCTypeCast)lval).expr, builder);
2173 }
2174 }
2175 throw new AssertionError(lval);
2176 }
2178 // evaluate and discard the first expression, then evaluate the second.
2179 JCTree makeComma(final JCTree expr1, final JCTree expr2) {
2180 return abstractRval(expr1, new TreeBuilder() {
2181 public JCTree build(final JCTree discarded) {
2182 return expr2;
2183 }
2184 });
2185 }
2187 /**************************************************************************
2188 * Translation methods
2189 *************************************************************************/
2191 /** Visitor argument: enclosing operator node.
2192 */
2193 private JCExpression enclOp;
2195 /** Visitor method: Translate a single node.
2196 * Attach the source position from the old tree to its replacement tree.
2197 */
2198 public <T extends JCTree> T translate(T tree) {
2199 if (tree == null) {
2200 return null;
2201 } else {
2202 make_at(tree.pos());
2203 T result = super.translate(tree);
2204 if (endPosTable != null && result != tree) {
2205 endPosTable.replaceTree(tree, result);
2206 }
2207 return result;
2208 }
2209 }
2211 /** Visitor method: Translate a single node, boxing or unboxing if needed.
2212 */
2213 public <T extends JCTree> T translate(T tree, Type type) {
2214 return (tree == null) ? null : boxIfNeeded(translate(tree), type);
2215 }
2217 /** Visitor method: Translate tree.
2218 */
2219 public <T extends JCTree> T translate(T tree, JCExpression enclOp) {
2220 JCExpression prevEnclOp = this.enclOp;
2221 this.enclOp = enclOp;
2222 T res = translate(tree);
2223 this.enclOp = prevEnclOp;
2224 return res;
2225 }
2227 /** Visitor method: Translate list of trees.
2228 */
2229 public <T extends JCTree> List<T> translate(List<T> trees, JCExpression enclOp) {
2230 JCExpression prevEnclOp = this.enclOp;
2231 this.enclOp = enclOp;
2232 List<T> res = translate(trees);
2233 this.enclOp = prevEnclOp;
2234 return res;
2235 }
2237 /** Visitor method: Translate list of trees.
2238 */
2239 public <T extends JCTree> List<T> translate(List<T> trees, Type type) {
2240 if (trees == null) return null;
2241 for (List<T> l = trees; l.nonEmpty(); l = l.tail)
2242 l.head = translate(l.head, type);
2243 return trees;
2244 }
2246 public void visitTopLevel(JCCompilationUnit tree) {
2247 if (needPackageInfoClass(tree)) {
2248 Name name = names.package_info;
2249 long flags = Flags.ABSTRACT | Flags.INTERFACE;
2250 if (target.isPackageInfoSynthetic())
2251 // package-info is marked SYNTHETIC in JDK 1.6 and later releases
2252 flags = flags | Flags.SYNTHETIC;
2253 JCClassDecl packageAnnotationsClass
2254 = make.ClassDef(make.Modifiers(flags,
2255 tree.packageAnnotations),
2256 name, List.<JCTypeParameter>nil(),
2257 null, List.<JCExpression>nil(), List.<JCTree>nil());
2258 ClassSymbol c = tree.packge.package_info;
2259 c.flags_field |= flags;
2260 c.attributes_field = tree.packge.attributes_field;
2261 ClassType ctype = (ClassType) c.type;
2262 ctype.supertype_field = syms.objectType;
2263 ctype.interfaces_field = List.nil();
2264 packageAnnotationsClass.sym = c;
2266 translated.append(packageAnnotationsClass);
2267 }
2268 }
2269 // where
2270 private boolean needPackageInfoClass(JCCompilationUnit tree) {
2271 switch (pkginfoOpt) {
2272 case ALWAYS:
2273 return true;
2274 case LEGACY:
2275 return tree.packageAnnotations.nonEmpty();
2276 case NONEMPTY:
2277 for (Attribute.Compound a: tree.packge.attributes_field) {
2278 Attribute.RetentionPolicy p = types.getRetention(a);
2279 if (p != Attribute.RetentionPolicy.SOURCE)
2280 return true;
2281 }
2282 return false;
2283 }
2284 throw new AssertionError();
2285 }
2287 public void visitClassDef(JCClassDecl tree) {
2288 ClassSymbol currentClassPrev = currentClass;
2289 MethodSymbol currentMethodSymPrev = currentMethodSym;
2290 currentClass = tree.sym;
2291 currentMethodSym = null;
2292 classdefs.put(currentClass, tree);
2294 proxies = proxies.dup(currentClass);
2295 List<VarSymbol> prevOuterThisStack = outerThisStack;
2297 // If this is an enum definition
2298 if ((tree.mods.flags & ENUM) != 0 &&
2299 (types.supertype(currentClass.type).tsym.flags() & ENUM) == 0)
2300 visitEnumDef(tree);
2302 // If this is a nested class, define a this$n field for
2303 // it and add to proxies.
2304 JCVariableDecl otdef = null;
2305 if (currentClass.hasOuterInstance())
2306 otdef = outerThisDef(tree.pos, currentClass);
2308 // If this is a local class, define proxies for all its free variables.
2309 List<JCVariableDecl> fvdefs = freevarDefs(
2310 tree.pos, freevars(currentClass), currentClass);
2312 // Recursively translate superclass, interfaces.
2313 tree.extending = translate(tree.extending);
2314 tree.implementing = translate(tree.implementing);
2316 if (currentClass.isLocal()) {
2317 ClassSymbol encl = currentClass.owner.enclClass();
2318 if (encl.trans_local == null) {
2319 encl.trans_local = List.nil();
2320 }
2321 encl.trans_local = encl.trans_local.prepend(currentClass);
2322 }
2324 // Recursively translate members, taking into account that new members
2325 // might be created during the translation and prepended to the member
2326 // list `tree.defs'.
2327 List<JCTree> seen = List.nil();
2328 while (tree.defs != seen) {
2329 List<JCTree> unseen = tree.defs;
2330 for (List<JCTree> l = unseen; l.nonEmpty() && l != seen; l = l.tail) {
2331 JCTree outermostMemberDefPrev = outermostMemberDef;
2332 if (outermostMemberDefPrev == null) outermostMemberDef = l.head;
2333 l.head = translate(l.head);
2334 outermostMemberDef = outermostMemberDefPrev;
2335 }
2336 seen = unseen;
2337 }
2339 // Convert a protected modifier to public, mask static modifier.
2340 if ((tree.mods.flags & PROTECTED) != 0) tree.mods.flags |= PUBLIC;
2341 tree.mods.flags &= ClassFlags;
2343 // Convert name to flat representation, replacing '.' by '$'.
2344 tree.name = Convert.shortName(currentClass.flatName());
2346 // Add this$n and free variables proxy definitions to class.
2347 for (List<JCVariableDecl> l = fvdefs; l.nonEmpty(); l = l.tail) {
2348 tree.defs = tree.defs.prepend(l.head);
2349 enterSynthetic(tree.pos(), l.head.sym, currentClass.members());
2350 }
2351 if (currentClass.hasOuterInstance()) {
2352 tree.defs = tree.defs.prepend(otdef);
2353 enterSynthetic(tree.pos(), otdef.sym, currentClass.members());
2354 }
2356 proxies = proxies.leave();
2357 outerThisStack = prevOuterThisStack;
2359 // Append translated tree to `translated' queue.
2360 translated.append(tree);
2362 currentClass = currentClassPrev;
2363 currentMethodSym = currentMethodSymPrev;
2365 // Return empty block {} as a placeholder for an inner class.
2366 result = make_at(tree.pos()).Block(0, List.<JCStatement>nil());
2367 }
2369 /** Translate an enum class. */
2370 private void visitEnumDef(JCClassDecl tree) {
2371 make_at(tree.pos());
2373 // add the supertype, if needed
2374 if (tree.extending == null)
2375 tree.extending = make.Type(types.supertype(tree.type));
2377 // classOfType adds a cache field to tree.defs unless
2378 // target.hasClassLiterals().
2379 JCExpression e_class = classOfType(tree.sym.type, tree.pos()).
2380 setType(types.erasure(syms.classType));
2382 // process each enumeration constant, adding implicit constructor parameters
2383 int nextOrdinal = 0;
2384 ListBuffer<JCExpression> values = new ListBuffer<JCExpression>();
2385 ListBuffer<JCTree> enumDefs = new ListBuffer<JCTree>();
2386 ListBuffer<JCTree> otherDefs = new ListBuffer<JCTree>();
2387 for (List<JCTree> defs = tree.defs;
2388 defs.nonEmpty();
2389 defs=defs.tail) {
2390 if (defs.head.hasTag(VARDEF) && (((JCVariableDecl) defs.head).mods.flags & ENUM) != 0) {
2391 JCVariableDecl var = (JCVariableDecl)defs.head;
2392 visitEnumConstantDef(var, nextOrdinal++);
2393 values.append(make.QualIdent(var.sym));
2394 enumDefs.append(var);
2395 } else {
2396 otherDefs.append(defs.head);
2397 }
2398 }
2400 // private static final T[] #VALUES = { a, b, c };
2401 Name valuesName = names.fromString(target.syntheticNameChar() + "VALUES");
2402 while (tree.sym.members().lookup(valuesName).scope != null) // avoid name clash
2403 valuesName = names.fromString(valuesName + "" + target.syntheticNameChar());
2404 Type arrayType = new ArrayType(types.erasure(tree.type), syms.arrayClass);
2405 VarSymbol valuesVar = new VarSymbol(PRIVATE|FINAL|STATIC|SYNTHETIC,
2406 valuesName,
2407 arrayType,
2408 tree.type.tsym);
2409 JCNewArray newArray = make.NewArray(make.Type(types.erasure(tree.type)),
2410 List.<JCExpression>nil(),
2411 values.toList());
2412 newArray.type = arrayType;
2413 enumDefs.append(make.VarDef(valuesVar, newArray));
2414 tree.sym.members().enter(valuesVar);
2416 Symbol valuesSym = lookupMethod(tree.pos(), names.values,
2417 tree.type, List.<Type>nil());
2418 List<JCStatement> valuesBody;
2419 if (useClone()) {
2420 // return (T[]) $VALUES.clone();
2421 JCTypeCast valuesResult =
2422 make.TypeCast(valuesSym.type.getReturnType(),
2423 make.App(make.Select(make.Ident(valuesVar),
2424 syms.arrayCloneMethod)));
2425 valuesBody = List.<JCStatement>of(make.Return(valuesResult));
2426 } else {
2427 // template: T[] $result = new T[$values.length];
2428 Name resultName = names.fromString(target.syntheticNameChar() + "result");
2429 while (tree.sym.members().lookup(resultName).scope != null) // avoid name clash
2430 resultName = names.fromString(resultName + "" + target.syntheticNameChar());
2431 VarSymbol resultVar = new VarSymbol(FINAL|SYNTHETIC,
2432 resultName,
2433 arrayType,
2434 valuesSym);
2435 JCNewArray resultArray = make.NewArray(make.Type(types.erasure(tree.type)),
2436 List.of(make.Select(make.Ident(valuesVar), syms.lengthVar)),
2437 null);
2438 resultArray.type = arrayType;
2439 JCVariableDecl decl = make.VarDef(resultVar, resultArray);
2441 // template: System.arraycopy($VALUES, 0, $result, 0, $VALUES.length);
2442 if (systemArraycopyMethod == null) {
2443 systemArraycopyMethod =
2444 new MethodSymbol(PUBLIC | STATIC,
2445 names.fromString("arraycopy"),
2446 new MethodType(List.<Type>of(syms.objectType,
2447 syms.intType,
2448 syms.objectType,
2449 syms.intType,
2450 syms.intType),
2451 syms.voidType,
2452 List.<Type>nil(),
2453 syms.methodClass),
2454 syms.systemType.tsym);
2455 }
2456 JCStatement copy =
2457 make.Exec(make.App(make.Select(make.Ident(syms.systemType.tsym),
2458 systemArraycopyMethod),
2459 List.of(make.Ident(valuesVar), make.Literal(0),
2460 make.Ident(resultVar), make.Literal(0),
2461 make.Select(make.Ident(valuesVar), syms.lengthVar))));
2463 // template: return $result;
2464 JCStatement ret = make.Return(make.Ident(resultVar));
2465 valuesBody = List.<JCStatement>of(decl, copy, ret);
2466 }
2468 JCMethodDecl valuesDef =
2469 make.MethodDef((MethodSymbol)valuesSym, make.Block(0, valuesBody));
2471 enumDefs.append(valuesDef);
2473 if (debugLower)
2474 System.err.println(tree.sym + ".valuesDef = " + valuesDef);
2476 /** The template for the following code is:
2477 *
2478 * public static E valueOf(String name) {
2479 * return (E)Enum.valueOf(E.class, name);
2480 * }
2481 *
2482 * where E is tree.sym
2483 */
2484 MethodSymbol valueOfSym = lookupMethod(tree.pos(),
2485 names.valueOf,
2486 tree.sym.type,
2487 List.of(syms.stringType));
2488 Assert.check((valueOfSym.flags() & STATIC) != 0);
2489 VarSymbol nameArgSym = valueOfSym.params.head;
2490 JCIdent nameVal = make.Ident(nameArgSym);
2491 JCStatement enum_ValueOf =
2492 make.Return(make.TypeCast(tree.sym.type,
2493 makeCall(make.Ident(syms.enumSym),
2494 names.valueOf,
2495 List.of(e_class, nameVal))));
2496 JCMethodDecl valueOf = make.MethodDef(valueOfSym,
2497 make.Block(0, List.of(enum_ValueOf)));
2498 nameVal.sym = valueOf.params.head.sym;
2499 if (debugLower)
2500 System.err.println(tree.sym + ".valueOf = " + valueOf);
2501 enumDefs.append(valueOf);
2503 enumDefs.appendList(otherDefs.toList());
2504 tree.defs = enumDefs.toList();
2506 // Add the necessary members for the EnumCompatibleMode
2507 if (target.compilerBootstrap(tree.sym)) {
2508 addEnumCompatibleMembers(tree);
2509 }
2510 }
2511 // where
2512 private MethodSymbol systemArraycopyMethod;
2513 private boolean useClone() {
2514 try {
2515 Scope.Entry e = syms.objectType.tsym.members().lookup(names.clone);
2516 return (e.sym != null);
2517 }
2518 catch (CompletionFailure e) {
2519 return false;
2520 }
2521 }
2523 /** Translate an enumeration constant and its initializer. */
2524 private void visitEnumConstantDef(JCVariableDecl var, int ordinal) {
2525 JCNewClass varDef = (JCNewClass)var.init;
2526 varDef.args = varDef.args.
2527 prepend(makeLit(syms.intType, ordinal)).
2528 prepend(makeLit(syms.stringType, var.name.toString()));
2529 }
2531 public void visitMethodDef(JCMethodDecl tree) {
2532 if (tree.name == names.init && (currentClass.flags_field&ENUM) != 0) {
2533 // Add "String $enum$name, int $enum$ordinal" to the beginning of the
2534 // argument list for each constructor of an enum.
2535 JCVariableDecl nameParam = make_at(tree.pos()).
2536 Param(names.fromString(target.syntheticNameChar() +
2537 "enum" + target.syntheticNameChar() + "name"),
2538 syms.stringType, tree.sym);
2539 nameParam.mods.flags |= SYNTHETIC; nameParam.sym.flags_field |= SYNTHETIC;
2541 JCVariableDecl ordParam = make.
2542 Param(names.fromString(target.syntheticNameChar() +
2543 "enum" + target.syntheticNameChar() +
2544 "ordinal"),
2545 syms.intType, tree.sym);
2546 ordParam.mods.flags |= SYNTHETIC; ordParam.sym.flags_field |= SYNTHETIC;
2548 tree.params = tree.params.prepend(ordParam).prepend(nameParam);
2550 MethodSymbol m = tree.sym;
2551 Type olderasure = m.erasure(types);
2552 m.erasure_field = new MethodType(
2553 olderasure.getParameterTypes().prepend(syms.intType).prepend(syms.stringType),
2554 olderasure.getReturnType(),
2555 olderasure.getThrownTypes(),
2556 syms.methodClass);
2558 if (target.compilerBootstrap(m.owner)) {
2559 // Initialize synthetic name field
2560 Symbol nameVarSym = lookupSynthetic(names.fromString("$name"),
2561 tree.sym.owner.members());
2562 JCIdent nameIdent = make.Ident(nameParam.sym);
2563 JCIdent id1 = make.Ident(nameVarSym);
2564 JCAssign newAssign = make.Assign(id1, nameIdent);
2565 newAssign.type = id1.type;
2566 JCExpressionStatement nameAssign = make.Exec(newAssign);
2567 nameAssign.type = id1.type;
2568 tree.body.stats = tree.body.stats.prepend(nameAssign);
2570 // Initialize synthetic ordinal field
2571 Symbol ordinalVarSym = lookupSynthetic(names.fromString("$ordinal"),
2572 tree.sym.owner.members());
2573 JCIdent ordIdent = make.Ident(ordParam.sym);
2574 id1 = make.Ident(ordinalVarSym);
2575 newAssign = make.Assign(id1, ordIdent);
2576 newAssign.type = id1.type;
2577 JCExpressionStatement ordinalAssign = make.Exec(newAssign);
2578 ordinalAssign.type = id1.type;
2579 tree.body.stats = tree.body.stats.prepend(ordinalAssign);
2580 }
2581 }
2583 JCMethodDecl prevMethodDef = currentMethodDef;
2584 MethodSymbol prevMethodSym = currentMethodSym;
2585 try {
2586 currentMethodDef = tree;
2587 currentMethodSym = tree.sym;
2588 visitMethodDefInternal(tree);
2589 } finally {
2590 currentMethodDef = prevMethodDef;
2591 currentMethodSym = prevMethodSym;
2592 }
2593 }
2594 //where
2595 private void visitMethodDefInternal(JCMethodDecl tree) {
2596 if (tree.name == names.init &&
2597 (currentClass.isInner() ||
2598 (currentClass.owner.kind & (VAR | MTH)) != 0)) {
2599 // We are seeing a constructor of an inner class.
2600 MethodSymbol m = tree.sym;
2602 // Push a new proxy scope for constructor parameters.
2603 // and create definitions for any this$n and proxy parameters.
2604 proxies = proxies.dup(m);
2605 List<VarSymbol> prevOuterThisStack = outerThisStack;
2606 List<VarSymbol> fvs = freevars(currentClass);
2607 JCVariableDecl otdef = null;
2608 if (currentClass.hasOuterInstance())
2609 otdef = outerThisDef(tree.pos, m);
2610 List<JCVariableDecl> fvdefs = freevarDefs(tree.pos, fvs, m);
2612 // Recursively translate result type, parameters and thrown list.
2613 tree.restype = translate(tree.restype);
2614 tree.params = translateVarDefs(tree.params);
2615 tree.thrown = translate(tree.thrown);
2617 // when compiling stubs, don't process body
2618 if (tree.body == null) {
2619 result = tree;
2620 return;
2621 }
2623 // Add this$n (if needed) in front of and free variables behind
2624 // constructor parameter list.
2625 tree.params = tree.params.appendList(fvdefs);
2626 if (currentClass.hasOuterInstance())
2627 tree.params = tree.params.prepend(otdef);
2629 // If this is an initial constructor, i.e., it does not start with
2630 // this(...), insert initializers for this$n and proxies
2631 // before (pre-1.4, after) the call to superclass constructor.
2632 JCStatement selfCall = translate(tree.body.stats.head);
2634 List<JCStatement> added = List.nil();
2635 if (fvs.nonEmpty()) {
2636 List<Type> addedargtypes = List.nil();
2637 for (List<VarSymbol> l = fvs; l.nonEmpty(); l = l.tail) {
2638 if (TreeInfo.isInitialConstructor(tree))
2639 added = added.prepend(
2640 initField(tree.body.pos, proxyName(l.head.name)));
2641 addedargtypes = addedargtypes.prepend(l.head.erasure(types));
2642 }
2643 Type olderasure = m.erasure(types);
2644 m.erasure_field = new MethodType(
2645 olderasure.getParameterTypes().appendList(addedargtypes),
2646 olderasure.getReturnType(),
2647 olderasure.getThrownTypes(),
2648 syms.methodClass);
2649 }
2650 if (currentClass.hasOuterInstance() &&
2651 TreeInfo.isInitialConstructor(tree))
2652 {
2653 added = added.prepend(initOuterThis(tree.body.pos));
2654 }
2656 // pop local variables from proxy stack
2657 proxies = proxies.leave();
2659 // recursively translate following local statements and
2660 // combine with this- or super-call
2661 List<JCStatement> stats = translate(tree.body.stats.tail);
2662 if (target.initializeFieldsBeforeSuper())
2663 tree.body.stats = stats.prepend(selfCall).prependList(added);
2664 else
2665 tree.body.stats = stats.prependList(added).prepend(selfCall);
2667 outerThisStack = prevOuterThisStack;
2668 } else {
2669 super.visitMethodDef(tree);
2670 }
2671 result = tree;
2672 }
2674 public void visitTypeCast(JCTypeCast tree) {
2675 tree.clazz = translate(tree.clazz);
2676 if (tree.type.isPrimitive() != tree.expr.type.isPrimitive())
2677 tree.expr = translate(tree.expr, tree.type);
2678 else
2679 tree.expr = translate(tree.expr);
2680 result = tree;
2681 }
2683 public void visitNewClass(JCNewClass tree) {
2684 ClassSymbol c = (ClassSymbol)tree.constructor.owner;
2686 // Box arguments, if necessary
2687 boolean isEnum = (tree.constructor.owner.flags() & ENUM) != 0;
2688 List<Type> argTypes = tree.constructor.type.getParameterTypes();
2689 if (isEnum) argTypes = argTypes.prepend(syms.intType).prepend(syms.stringType);
2690 tree.args = boxArgs(argTypes, tree.args, tree.varargsElement);
2691 tree.varargsElement = null;
2693 // If created class is local, add free variables after
2694 // explicit constructor arguments.
2695 if ((c.owner.kind & (VAR | MTH)) != 0) {
2696 tree.args = tree.args.appendList(loadFreevars(tree.pos(), freevars(c)));
2697 }
2699 // If an access constructor is used, append null as a last argument.
2700 Symbol constructor = accessConstructor(tree.pos(), tree.constructor);
2701 if (constructor != tree.constructor) {
2702 tree.args = tree.args.append(makeNull());
2703 tree.constructor = constructor;
2704 }
2706 // If created class has an outer instance, and new is qualified, pass
2707 // qualifier as first argument. If new is not qualified, pass the
2708 // correct outer instance as first argument.
2709 if (c.hasOuterInstance()) {
2710 JCExpression thisArg;
2711 if (tree.encl != null) {
2712 thisArg = attr.makeNullCheck(translate(tree.encl));
2713 thisArg.type = tree.encl.type;
2714 } else if ((c.owner.kind & (MTH | VAR)) != 0) {
2715 // local class
2716 thisArg = makeThis(tree.pos(), c.type.getEnclosingType().tsym);
2717 } else {
2718 // nested class
2719 thisArg = makeOwnerThis(tree.pos(), c, false);
2720 }
2721 tree.args = tree.args.prepend(thisArg);
2722 }
2723 tree.encl = null;
2725 // If we have an anonymous class, create its flat version, rather
2726 // than the class or interface following new.
2727 if (tree.def != null) {
2728 translate(tree.def);
2729 tree.clazz = access(make_at(tree.clazz.pos()).Ident(tree.def.sym));
2730 tree.def = null;
2731 } else {
2732 tree.clazz = access(c, tree.clazz, enclOp, false);
2733 }
2734 result = tree;
2735 }
2737 // Simplify conditionals with known constant controlling expressions.
2738 // This allows us to avoid generating supporting declarations for
2739 // the dead code, which will not be eliminated during code generation.
2740 // Note that Flow.isFalse and Flow.isTrue only return true
2741 // for constant expressions in the sense of JLS 15.27, which
2742 // are guaranteed to have no side-effects. More aggressive
2743 // constant propagation would require that we take care to
2744 // preserve possible side-effects in the condition expression.
2746 /** Visitor method for conditional expressions.
2747 */
2748 public void visitConditional(JCConditional tree) {
2749 JCTree cond = tree.cond = translate(tree.cond, syms.booleanType);
2750 if (cond.type.isTrue()) {
2751 result = convert(translate(tree.truepart, tree.type), tree.type);
2752 } else if (cond.type.isFalse()) {
2753 result = convert(translate(tree.falsepart, tree.type), tree.type);
2754 } else {
2755 // Condition is not a compile-time constant.
2756 tree.truepart = translate(tree.truepart, tree.type);
2757 tree.falsepart = translate(tree.falsepart, tree.type);
2758 result = tree;
2759 }
2760 }
2761 //where
2762 private JCTree convert(JCTree tree, Type pt) {
2763 if (tree.type == pt || tree.type.tag == TypeTags.BOT)
2764 return tree;
2765 JCTree result = make_at(tree.pos()).TypeCast(make.Type(pt), (JCExpression)tree);
2766 result.type = (tree.type.constValue() != null) ? cfolder.coerce(tree.type, pt)
2767 : pt;
2768 return result;
2769 }
2771 /** Visitor method for if statements.
2772 */
2773 public void visitIf(JCIf tree) {
2774 JCTree cond = tree.cond = translate(tree.cond, syms.booleanType);
2775 if (cond.type.isTrue()) {
2776 result = translate(tree.thenpart);
2777 } else if (cond.type.isFalse()) {
2778 if (tree.elsepart != null) {
2779 result = translate(tree.elsepart);
2780 } else {
2781 result = make.Skip();
2782 }
2783 } else {
2784 // Condition is not a compile-time constant.
2785 tree.thenpart = translate(tree.thenpart);
2786 tree.elsepart = translate(tree.elsepart);
2787 result = tree;
2788 }
2789 }
2791 /** Visitor method for assert statements. Translate them away.
2792 */
2793 public void visitAssert(JCAssert tree) {
2794 DiagnosticPosition detailPos = (tree.detail == null) ? tree.pos() : tree.detail.pos();
2795 tree.cond = translate(tree.cond, syms.booleanType);
2796 if (!tree.cond.type.isTrue()) {
2797 JCExpression cond = assertFlagTest(tree.pos());
2798 List<JCExpression> exnArgs = (tree.detail == null) ?
2799 List.<JCExpression>nil() : List.of(translate(tree.detail));
2800 if (!tree.cond.type.isFalse()) {
2801 cond = makeBinary
2802 (AND,
2803 cond,
2804 makeUnary(NOT, tree.cond));
2805 }
2806 result =
2807 make.If(cond,
2808 make_at(detailPos).
2809 Throw(makeNewClass(syms.assertionErrorType, exnArgs)),
2810 null);
2811 } else {
2812 result = make.Skip();
2813 }
2814 }
2816 public void visitApply(JCMethodInvocation tree) {
2817 Symbol meth = TreeInfo.symbol(tree.meth);
2818 List<Type> argtypes = meth.type.getParameterTypes();
2819 if (allowEnums &&
2820 meth.name==names.init &&
2821 meth.owner == syms.enumSym)
2822 argtypes = argtypes.tail.tail;
2823 tree.args = boxArgs(argtypes, tree.args, tree.varargsElement);
2824 tree.varargsElement = null;
2825 Name methName = TreeInfo.name(tree.meth);
2826 if (meth.name==names.init) {
2827 // We are seeing a this(...) or super(...) constructor call.
2828 // If an access constructor is used, append null as a last argument.
2829 Symbol constructor = accessConstructor(tree.pos(), meth);
2830 if (constructor != meth) {
2831 tree.args = tree.args.append(makeNull());
2832 TreeInfo.setSymbol(tree.meth, constructor);
2833 }
2835 // If we are calling a constructor of a local class, add
2836 // free variables after explicit constructor arguments.
2837 ClassSymbol c = (ClassSymbol)constructor.owner;
2838 if ((c.owner.kind & (VAR | MTH)) != 0) {
2839 tree.args = tree.args.appendList(loadFreevars(tree.pos(), freevars(c)));
2840 }
2842 // If we are calling a constructor of an enum class, pass
2843 // along the name and ordinal arguments
2844 if ((c.flags_field&ENUM) != 0 || c.getQualifiedName() == names.java_lang_Enum) {
2845 List<JCVariableDecl> params = currentMethodDef.params;
2846 if (currentMethodSym.owner.hasOuterInstance())
2847 params = params.tail; // drop this$n
2848 tree.args = tree.args
2849 .prepend(make_at(tree.pos()).Ident(params.tail.head.sym)) // ordinal
2850 .prepend(make.Ident(params.head.sym)); // name
2851 }
2853 // If we are calling a constructor of a class with an outer
2854 // instance, and the call
2855 // is qualified, pass qualifier as first argument in front of
2856 // the explicit constructor arguments. If the call
2857 // is not qualified, pass the correct outer instance as
2858 // first argument.
2859 if (c.hasOuterInstance()) {
2860 JCExpression thisArg;
2861 if (tree.meth.hasTag(SELECT)) {
2862 thisArg = attr.
2863 makeNullCheck(translate(((JCFieldAccess) tree.meth).selected));
2864 tree.meth = make.Ident(constructor);
2865 ((JCIdent) tree.meth).name = methName;
2866 } else if ((c.owner.kind & (MTH | VAR)) != 0 || methName == names._this){
2867 // local class or this() call
2868 thisArg = makeThis(tree.meth.pos(), c.type.getEnclosingType().tsym);
2869 } else {
2870 // super() call of nested class - never pick 'this'
2871 thisArg = makeOwnerThisN(tree.meth.pos(), c, false);
2872 }
2873 tree.args = tree.args.prepend(thisArg);
2874 }
2875 } else {
2876 // We are seeing a normal method invocation; translate this as usual.
2877 tree.meth = translate(tree.meth);
2879 // If the translated method itself is an Apply tree, we are
2880 // seeing an access method invocation. In this case, append
2881 // the method arguments to the arguments of the access method.
2882 if (tree.meth.hasTag(APPLY)) {
2883 JCMethodInvocation app = (JCMethodInvocation)tree.meth;
2884 app.args = tree.args.prependList(app.args);
2885 result = app;
2886 return;
2887 }
2888 }
2889 result = tree;
2890 }
2892 List<JCExpression> boxArgs(List<Type> parameters, List<JCExpression> _args, Type varargsElement) {
2893 List<JCExpression> args = _args;
2894 if (parameters.isEmpty()) return args;
2895 boolean anyChanges = false;
2896 ListBuffer<JCExpression> result = new ListBuffer<JCExpression>();
2897 while (parameters.tail.nonEmpty()) {
2898 JCExpression arg = translate(args.head, parameters.head);
2899 anyChanges |= (arg != args.head);
2900 result.append(arg);
2901 args = args.tail;
2902 parameters = parameters.tail;
2903 }
2904 Type parameter = parameters.head;
2905 if (varargsElement != null) {
2906 anyChanges = true;
2907 ListBuffer<JCExpression> elems = new ListBuffer<JCExpression>();
2908 while (args.nonEmpty()) {
2909 JCExpression arg = translate(args.head, varargsElement);
2910 elems.append(arg);
2911 args = args.tail;
2912 }
2913 JCNewArray boxedArgs = make.NewArray(make.Type(varargsElement),
2914 List.<JCExpression>nil(),
2915 elems.toList());
2916 boxedArgs.type = new ArrayType(varargsElement, syms.arrayClass);
2917 result.append(boxedArgs);
2918 } else {
2919 if (args.length() != 1) throw new AssertionError(args);
2920 JCExpression arg = translate(args.head, parameter);
2921 anyChanges |= (arg != args.head);
2922 result.append(arg);
2923 if (!anyChanges) return _args;
2924 }
2925 return result.toList();
2926 }
2928 /** Expand a boxing or unboxing conversion if needed. */
2929 @SuppressWarnings("unchecked") // XXX unchecked
2930 <T extends JCTree> T boxIfNeeded(T tree, Type type) {
2931 boolean havePrimitive = tree.type.isPrimitive();
2932 if (havePrimitive == type.isPrimitive())
2933 return tree;
2934 if (havePrimitive) {
2935 Type unboxedTarget = types.unboxedType(type);
2936 if (unboxedTarget.tag != NONE) {
2937 if (!types.isSubtype(tree.type, unboxedTarget)) //e.g. Character c = 89;
2938 tree.type = unboxedTarget.constType(tree.type.constValue());
2939 return (T)boxPrimitive((JCExpression)tree, type);
2940 } else {
2941 tree = (T)boxPrimitive((JCExpression)tree);
2942 }
2943 } else {
2944 tree = (T)unbox((JCExpression)tree, type);
2945 }
2946 return tree;
2947 }
2949 /** Box up a single primitive expression. */
2950 JCExpression boxPrimitive(JCExpression tree) {
2951 return boxPrimitive(tree, types.boxedClass(tree.type).type);
2952 }
2954 /** Box up a single primitive expression. */
2955 JCExpression boxPrimitive(JCExpression tree, Type box) {
2956 make_at(tree.pos());
2957 if (target.boxWithConstructors()) {
2958 Symbol ctor = lookupConstructor(tree.pos(),
2959 box,
2960 List.<Type>nil()
2961 .prepend(tree.type));
2962 return make.Create(ctor, List.of(tree));
2963 } else {
2964 Symbol valueOfSym = lookupMethod(tree.pos(),
2965 names.valueOf,
2966 box,
2967 List.<Type>nil()
2968 .prepend(tree.type));
2969 return make.App(make.QualIdent(valueOfSym), List.of(tree));
2970 }
2971 }
2973 /** Unbox an object to a primitive value. */
2974 JCExpression unbox(JCExpression tree, Type primitive) {
2975 Type unboxedType = types.unboxedType(tree.type);
2976 if (unboxedType.tag == NONE) {
2977 unboxedType = primitive;
2978 if (!unboxedType.isPrimitive())
2979 throw new AssertionError(unboxedType);
2980 make_at(tree.pos());
2981 tree = make.TypeCast(types.boxedClass(unboxedType).type, tree);
2982 } else {
2983 // There must be a conversion from unboxedType to primitive.
2984 if (!types.isSubtype(unboxedType, primitive))
2985 throw new AssertionError(tree);
2986 }
2987 make_at(tree.pos());
2988 Symbol valueSym = lookupMethod(tree.pos(),
2989 unboxedType.tsym.name.append(names.Value), // x.intValue()
2990 tree.type,
2991 List.<Type>nil());
2992 return make.App(make.Select(tree, valueSym));
2993 }
2995 /** Visitor method for parenthesized expressions.
2996 * If the subexpression has changed, omit the parens.
2997 */
2998 public void visitParens(JCParens tree) {
2999 JCTree expr = translate(tree.expr);
3000 result = ((expr == tree.expr) ? tree : expr);
3001 }
3003 public void visitIndexed(JCArrayAccess tree) {
3004 tree.indexed = translate(tree.indexed);
3005 tree.index = translate(tree.index, syms.intType);
3006 result = tree;
3007 }
3009 public void visitAssign(JCAssign tree) {
3010 tree.lhs = translate(tree.lhs, tree);
3011 tree.rhs = translate(tree.rhs, tree.lhs.type);
3013 // If translated left hand side is an Apply, we are
3014 // seeing an access method invocation. In this case, append
3015 // right hand side as last argument of the access method.
3016 if (tree.lhs.hasTag(APPLY)) {
3017 JCMethodInvocation app = (JCMethodInvocation)tree.lhs;
3018 app.args = List.of(tree.rhs).prependList(app.args);
3019 result = app;
3020 } else {
3021 result = tree;
3022 }
3023 }
3025 public void visitAssignop(final JCAssignOp tree) {
3026 if (!tree.lhs.type.isPrimitive() &&
3027 tree.operator.type.getReturnType().isPrimitive()) {
3028 // boxing required; need to rewrite as x = (unbox typeof x)(x op y);
3029 // or if x == (typeof x)z then z = (unbox typeof x)((typeof x)z op y)
3030 // (but without recomputing x)
3031 JCTree newTree = abstractLval(tree.lhs, new TreeBuilder() {
3032 public JCTree build(final JCTree lhs) {
3033 JCTree.Tag newTag = tree.getTag().noAssignOp();
3034 // Erasure (TransTypes) can change the type of
3035 // tree.lhs. However, we can still get the
3036 // unerased type of tree.lhs as it is stored
3037 // in tree.type in Attr.
3038 Symbol newOperator = rs.resolveBinaryOperator(tree.pos(),
3039 newTag,
3040 attrEnv,
3041 tree.type,
3042 tree.rhs.type);
3043 JCExpression expr = (JCExpression)lhs;
3044 if (expr.type != tree.type)
3045 expr = make.TypeCast(tree.type, expr);
3046 JCBinary opResult = make.Binary(newTag, expr, tree.rhs);
3047 opResult.operator = newOperator;
3048 opResult.type = newOperator.type.getReturnType();
3049 JCTypeCast newRhs = make.TypeCast(types.unboxedType(tree.type),
3050 opResult);
3051 return make.Assign((JCExpression)lhs, newRhs).setType(tree.type);
3052 }
3053 });
3054 result = translate(newTree);
3055 return;
3056 }
3057 tree.lhs = translate(tree.lhs, tree);
3058 tree.rhs = translate(tree.rhs, tree.operator.type.getParameterTypes().tail.head);
3060 // If translated left hand side is an Apply, we are
3061 // seeing an access method invocation. In this case, append
3062 // right hand side as last argument of the access method.
3063 if (tree.lhs.hasTag(APPLY)) {
3064 JCMethodInvocation app = (JCMethodInvocation)tree.lhs;
3065 // if operation is a += on strings,
3066 // make sure to convert argument to string
3067 JCExpression rhs = (((OperatorSymbol)tree.operator).opcode == string_add)
3068 ? makeString(tree.rhs)
3069 : tree.rhs;
3070 app.args = List.of(rhs).prependList(app.args);
3071 result = app;
3072 } else {
3073 result = tree;
3074 }
3075 }
3077 /** Lower a tree of the form e++ or e-- where e is an object type */
3078 JCTree lowerBoxedPostop(final JCUnary tree) {
3079 // translate to tmp1=lval(e); tmp2=tmp1; tmp1 OP 1; tmp2
3080 // or
3081 // translate to tmp1=lval(e); tmp2=tmp1; (typeof tree)tmp1 OP 1; tmp2
3082 // where OP is += or -=
3083 final boolean cast = TreeInfo.skipParens(tree.arg).hasTag(TYPECAST);
3084 return abstractLval(tree.arg, new TreeBuilder() {
3085 public JCTree build(final JCTree tmp1) {
3086 return abstractRval(tmp1, tree.arg.type, new TreeBuilder() {
3087 public JCTree build(final JCTree tmp2) {
3088 JCTree.Tag opcode = (tree.hasTag(POSTINC))
3089 ? PLUS_ASG : MINUS_ASG;
3090 JCTree lhs = cast
3091 ? make.TypeCast(tree.arg.type, (JCExpression)tmp1)
3092 : tmp1;
3093 JCTree update = makeAssignop(opcode,
3094 lhs,
3095 make.Literal(1));
3096 return makeComma(update, tmp2);
3097 }
3098 });
3099 }
3100 });
3101 }
3103 public void visitUnary(JCUnary tree) {
3104 boolean isUpdateOperator = tree.getTag().isIncOrDecUnaryOp();
3105 if (isUpdateOperator && !tree.arg.type.isPrimitive()) {
3106 switch(tree.getTag()) {
3107 case PREINC: // ++ e
3108 // translate to e += 1
3109 case PREDEC: // -- e
3110 // translate to e -= 1
3111 {
3112 JCTree.Tag opcode = (tree.hasTag(PREINC))
3113 ? PLUS_ASG : MINUS_ASG;
3114 JCAssignOp newTree = makeAssignop(opcode,
3115 tree.arg,
3116 make.Literal(1));
3117 result = translate(newTree, tree.type);
3118 return;
3119 }
3120 case POSTINC: // e ++
3121 case POSTDEC: // e --
3122 {
3123 result = translate(lowerBoxedPostop(tree), tree.type);
3124 return;
3125 }
3126 }
3127 throw new AssertionError(tree);
3128 }
3130 tree.arg = boxIfNeeded(translate(tree.arg, tree), tree.type);
3132 if (tree.hasTag(NOT) && tree.arg.type.constValue() != null) {
3133 tree.type = cfolder.fold1(bool_not, tree.arg.type);
3134 }
3136 // If translated left hand side is an Apply, we are
3137 // seeing an access method invocation. In this case, return
3138 // that access method invocation as result.
3139 if (isUpdateOperator && tree.arg.hasTag(APPLY)) {
3140 result = tree.arg;
3141 } else {
3142 result = tree;
3143 }
3144 }
3146 public void visitBinary(JCBinary tree) {
3147 List<Type> formals = tree.operator.type.getParameterTypes();
3148 JCTree lhs = tree.lhs = translate(tree.lhs, formals.head);
3149 switch (tree.getTag()) {
3150 case OR:
3151 if (lhs.type.isTrue()) {
3152 result = lhs;
3153 return;
3154 }
3155 if (lhs.type.isFalse()) {
3156 result = translate(tree.rhs, formals.tail.head);
3157 return;
3158 }
3159 break;
3160 case AND:
3161 if (lhs.type.isFalse()) {
3162 result = lhs;
3163 return;
3164 }
3165 if (lhs.type.isTrue()) {
3166 result = translate(tree.rhs, formals.tail.head);
3167 return;
3168 }
3169 break;
3170 }
3171 tree.rhs = translate(tree.rhs, formals.tail.head);
3172 result = tree;
3173 }
3175 public void visitIdent(JCIdent tree) {
3176 result = access(tree.sym, tree, enclOp, false);
3177 }
3179 /** Translate away the foreach loop. */
3180 public void visitForeachLoop(JCEnhancedForLoop tree) {
3181 if (types.elemtype(tree.expr.type) == null)
3182 visitIterableForeachLoop(tree);
3183 else
3184 visitArrayForeachLoop(tree);
3185 }
3186 // where
3187 /**
3188 * A statement of the form
3189 *
3190 * <pre>
3191 * for ( T v : arrayexpr ) stmt;
3192 * </pre>
3193 *
3194 * (where arrayexpr is of an array type) gets translated to
3195 *
3196 * <pre>
3197 * for ( { arraytype #arr = arrayexpr;
3198 * int #len = array.length;
3199 * int #i = 0; };
3200 * #i < #len; i$++ ) {
3201 * T v = arr$[#i];
3202 * stmt;
3203 * }
3204 * </pre>
3205 *
3206 * where #arr, #len, and #i are freshly named synthetic local variables.
3207 */
3208 private void visitArrayForeachLoop(JCEnhancedForLoop tree) {
3209 make_at(tree.expr.pos());
3210 VarSymbol arraycache = new VarSymbol(0,
3211 names.fromString("arr" + target.syntheticNameChar()),
3212 tree.expr.type,
3213 currentMethodSym);
3214 JCStatement arraycachedef = make.VarDef(arraycache, tree.expr);
3215 VarSymbol lencache = new VarSymbol(0,
3216 names.fromString("len" + target.syntheticNameChar()),
3217 syms.intType,
3218 currentMethodSym);
3219 JCStatement lencachedef = make.
3220 VarDef(lencache, make.Select(make.Ident(arraycache), syms.lengthVar));
3221 VarSymbol index = new VarSymbol(0,
3222 names.fromString("i" + target.syntheticNameChar()),
3223 syms.intType,
3224 currentMethodSym);
3226 JCVariableDecl indexdef = make.VarDef(index, make.Literal(INT, 0));
3227 indexdef.init.type = indexdef.type = syms.intType.constType(0);
3229 List<JCStatement> loopinit = List.of(arraycachedef, lencachedef, indexdef);
3230 JCBinary cond = makeBinary(LT, make.Ident(index), make.Ident(lencache));
3232 JCExpressionStatement step = make.Exec(makeUnary(PREINC, make.Ident(index)));
3234 Type elemtype = types.elemtype(tree.expr.type);
3235 JCExpression loopvarinit = make.Indexed(make.Ident(arraycache),
3236 make.Ident(index)).setType(elemtype);
3237 JCVariableDecl loopvardef = (JCVariableDecl)make.VarDef(tree.var.mods,
3238 tree.var.name,
3239 tree.var.vartype,
3240 loopvarinit).setType(tree.var.type);
3241 loopvardef.sym = tree.var.sym;
3242 JCBlock body = make.
3243 Block(0, List.of(loopvardef, tree.body));
3245 result = translate(make.
3246 ForLoop(loopinit,
3247 cond,
3248 List.of(step),
3249 body));
3250 patchTargets(body, tree, result);
3251 }
3252 /** Patch up break and continue targets. */
3253 private void patchTargets(JCTree body, final JCTree src, final JCTree dest) {
3254 class Patcher extends TreeScanner {
3255 public void visitBreak(JCBreak tree) {
3256 if (tree.target == src)
3257 tree.target = dest;
3258 }
3259 public void visitContinue(JCContinue tree) {
3260 if (tree.target == src)
3261 tree.target = dest;
3262 }
3263 public void visitClassDef(JCClassDecl tree) {}
3264 }
3265 new Patcher().scan(body);
3266 }
3267 /**
3268 * A statement of the form
3269 *
3270 * <pre>
3271 * for ( T v : coll ) stmt ;
3272 * </pre>
3273 *
3274 * (where coll implements Iterable<? extends T>) gets translated to
3275 *
3276 * <pre>
3277 * for ( Iterator<? extends T> #i = coll.iterator(); #i.hasNext(); ) {
3278 * T v = (T) #i.next();
3279 * stmt;
3280 * }
3281 * </pre>
3282 *
3283 * where #i is a freshly named synthetic local variable.
3284 */
3285 private void visitIterableForeachLoop(JCEnhancedForLoop tree) {
3286 make_at(tree.expr.pos());
3287 Type iteratorTarget = syms.objectType;
3288 Type iterableType = types.asSuper(types.upperBound(tree.expr.type),
3289 syms.iterableType.tsym);
3290 if (iterableType.getTypeArguments().nonEmpty())
3291 iteratorTarget = types.erasure(iterableType.getTypeArguments().head);
3292 Type eType = tree.expr.type;
3293 tree.expr.type = types.erasure(eType);
3294 if (eType.tag == TYPEVAR && eType.getUpperBound().isCompound())
3295 tree.expr = make.TypeCast(types.erasure(iterableType), tree.expr);
3296 Symbol iterator = lookupMethod(tree.expr.pos(),
3297 names.iterator,
3298 types.erasure(syms.iterableType),
3299 List.<Type>nil());
3300 VarSymbol itvar = new VarSymbol(0, names.fromString("i" + target.syntheticNameChar()),
3301 types.erasure(iterator.type.getReturnType()),
3302 currentMethodSym);
3303 JCStatement init = make.
3304 VarDef(itvar,
3305 make.App(make.Select(tree.expr, iterator)));
3306 Symbol hasNext = lookupMethod(tree.expr.pos(),
3307 names.hasNext,
3308 itvar.type,
3309 List.<Type>nil());
3310 JCMethodInvocation cond = make.App(make.Select(make.Ident(itvar), hasNext));
3311 Symbol next = lookupMethod(tree.expr.pos(),
3312 names.next,
3313 itvar.type,
3314 List.<Type>nil());
3315 JCExpression vardefinit = make.App(make.Select(make.Ident(itvar), next));
3316 if (tree.var.type.isPrimitive())
3317 vardefinit = make.TypeCast(types.upperBound(iteratorTarget), vardefinit);
3318 else
3319 vardefinit = make.TypeCast(tree.var.type, vardefinit);
3320 JCVariableDecl indexDef = (JCVariableDecl)make.VarDef(tree.var.mods,
3321 tree.var.name,
3322 tree.var.vartype,
3323 vardefinit).setType(tree.var.type);
3324 indexDef.sym = tree.var.sym;
3325 JCBlock body = make.Block(0, List.of(indexDef, tree.body));
3326 body.endpos = TreeInfo.endPos(tree.body);
3327 result = translate(make.
3328 ForLoop(List.of(init),
3329 cond,
3330 List.<JCExpressionStatement>nil(),
3331 body));
3332 patchTargets(body, tree, result);
3333 }
3335 public void visitVarDef(JCVariableDecl tree) {
3336 MethodSymbol oldMethodSym = currentMethodSym;
3337 tree.mods = translate(tree.mods);
3338 tree.vartype = translate(tree.vartype);
3339 if (currentMethodSym == null) {
3340 // A class or instance field initializer.
3341 currentMethodSym =
3342 new MethodSymbol((tree.mods.flags&STATIC) | BLOCK,
3343 names.empty, null,
3344 currentClass);
3345 }
3346 if (tree.init != null) tree.init = translate(tree.init, tree.type);
3347 result = tree;
3348 currentMethodSym = oldMethodSym;
3349 }
3351 public void visitBlock(JCBlock tree) {
3352 MethodSymbol oldMethodSym = currentMethodSym;
3353 if (currentMethodSym == null) {
3354 // Block is a static or instance initializer.
3355 currentMethodSym =
3356 new MethodSymbol(tree.flags | BLOCK,
3357 names.empty, null,
3358 currentClass);
3359 }
3360 super.visitBlock(tree);
3361 currentMethodSym = oldMethodSym;
3362 }
3364 public void visitDoLoop(JCDoWhileLoop tree) {
3365 tree.body = translate(tree.body);
3366 tree.cond = translate(tree.cond, syms.booleanType);
3367 result = tree;
3368 }
3370 public void visitWhileLoop(JCWhileLoop tree) {
3371 tree.cond = translate(tree.cond, syms.booleanType);
3372 tree.body = translate(tree.body);
3373 result = tree;
3374 }
3376 public void visitForLoop(JCForLoop tree) {
3377 tree.init = translate(tree.init);
3378 if (tree.cond != null)
3379 tree.cond = translate(tree.cond, syms.booleanType);
3380 tree.step = translate(tree.step);
3381 tree.body = translate(tree.body);
3382 result = tree;
3383 }
3385 public void visitReturn(JCReturn tree) {
3386 if (tree.expr != null)
3387 tree.expr = translate(tree.expr,
3388 types.erasure(currentMethodDef
3389 .restype.type));
3390 result = tree;
3391 }
3393 public void visitSwitch(JCSwitch tree) {
3394 Type selsuper = types.supertype(tree.selector.type);
3395 boolean enumSwitch = selsuper != null &&
3396 (tree.selector.type.tsym.flags() & ENUM) != 0;
3397 boolean stringSwitch = selsuper != null &&
3398 types.isSameType(tree.selector.type, syms.stringType);
3399 Type target = enumSwitch ? tree.selector.type :
3400 (stringSwitch? syms.stringType : syms.intType);
3401 tree.selector = translate(tree.selector, target);
3402 tree.cases = translateCases(tree.cases);
3403 if (enumSwitch) {
3404 result = visitEnumSwitch(tree);
3405 } else if (stringSwitch) {
3406 result = visitStringSwitch(tree);
3407 } else {
3408 result = tree;
3409 }
3410 }
3412 public JCTree visitEnumSwitch(JCSwitch tree) {
3413 TypeSymbol enumSym = tree.selector.type.tsym;
3414 EnumMapping map = mapForEnum(tree.pos(), enumSym);
3415 make_at(tree.pos());
3416 Symbol ordinalMethod = lookupMethod(tree.pos(),
3417 names.ordinal,
3418 tree.selector.type,
3419 List.<Type>nil());
3420 JCArrayAccess selector = make.Indexed(map.mapVar,
3421 make.App(make.Select(tree.selector,
3422 ordinalMethod)));
3423 ListBuffer<JCCase> cases = new ListBuffer<JCCase>();
3424 for (JCCase c : tree.cases) {
3425 if (c.pat != null) {
3426 VarSymbol label = (VarSymbol)TreeInfo.symbol(c.pat);
3427 JCLiteral pat = map.forConstant(label);
3428 cases.append(make.Case(pat, c.stats));
3429 } else {
3430 cases.append(c);
3431 }
3432 }
3433 JCSwitch enumSwitch = make.Switch(selector, cases.toList());
3434 patchTargets(enumSwitch, tree, enumSwitch);
3435 return enumSwitch;
3436 }
3438 public JCTree visitStringSwitch(JCSwitch tree) {
3439 List<JCCase> caseList = tree.getCases();
3440 int alternatives = caseList.size();
3442 if (alternatives == 0) { // Strange but legal possibility
3443 return make.at(tree.pos()).Exec(attr.makeNullCheck(tree.getExpression()));
3444 } else {
3445 /*
3446 * The general approach used is to translate a single
3447 * string switch statement into a series of two chained
3448 * switch statements: the first a synthesized statement
3449 * switching on the argument string's hash value and
3450 * computing a string's position in the list of original
3451 * case labels, if any, followed by a second switch on the
3452 * computed integer value. The second switch has the same
3453 * code structure as the original string switch statement
3454 * except that the string case labels are replaced with
3455 * positional integer constants starting at 0.
3456 *
3457 * The first switch statement can be thought of as an
3458 * inlined map from strings to their position in the case
3459 * label list. An alternate implementation would use an
3460 * actual Map for this purpose, as done for enum switches.
3461 *
3462 * With some additional effort, it would be possible to
3463 * use a single switch statement on the hash code of the
3464 * argument, but care would need to be taken to preserve
3465 * the proper control flow in the presence of hash
3466 * collisions and other complications, such as
3467 * fallthroughs. Switch statements with one or two
3468 * alternatives could also be specially translated into
3469 * if-then statements to omit the computation of the hash
3470 * code.
3471 *
3472 * The generated code assumes that the hashing algorithm
3473 * of String is the same in the compilation environment as
3474 * in the environment the code will run in. The string
3475 * hashing algorithm in the SE JDK has been unchanged
3476 * since at least JDK 1.2. Since the algorithm has been
3477 * specified since that release as well, it is very
3478 * unlikely to be changed in the future.
3479 *
3480 * Different hashing algorithms, such as the length of the
3481 * strings or a perfect hashing algorithm over the
3482 * particular set of case labels, could potentially be
3483 * used instead of String.hashCode.
3484 */
3486 ListBuffer<JCStatement> stmtList = new ListBuffer<JCStatement>();
3488 // Map from String case labels to their original position in
3489 // the list of case labels.
3490 Map<String, Integer> caseLabelToPosition =
3491 new LinkedHashMap<String, Integer>(alternatives + 1, 1.0f);
3493 // Map of hash codes to the string case labels having that hashCode.
3494 Map<Integer, Set<String>> hashToString =
3495 new LinkedHashMap<Integer, Set<String>>(alternatives + 1, 1.0f);
3497 int casePosition = 0;
3498 for(JCCase oneCase : caseList) {
3499 JCExpression expression = oneCase.getExpression();
3501 if (expression != null) { // expression for a "default" case is null
3502 expression = TreeInfo.skipParens(expression);
3503 String labelExpr = (String) expression.type.constValue();
3504 Integer mapping = caseLabelToPosition.put(labelExpr, casePosition);
3505 Assert.checkNull(mapping);
3506 int hashCode = labelExpr.hashCode();
3508 Set<String> stringSet = hashToString.get(hashCode);
3509 if (stringSet == null) {
3510 stringSet = new LinkedHashSet<String>(1, 1.0f);
3511 stringSet.add(labelExpr);
3512 hashToString.put(hashCode, stringSet);
3513 } else {
3514 boolean added = stringSet.add(labelExpr);
3515 Assert.check(added);
3516 }
3517 }
3518 casePosition++;
3519 }
3521 // Synthesize a switch statement that has the effect of
3522 // mapping from a string to the integer position of that
3523 // string in the list of case labels. This is done by
3524 // switching on the hashCode of the string followed by an
3525 // if-then-else chain comparing the input for equality
3526 // with all the case labels having that hash value.
3528 /*
3529 * s$ = top of stack;
3530 * tmp$ = -1;
3531 * switch($s.hashCode()) {
3532 * case caseLabel.hashCode:
3533 * if (s$.equals("caseLabel_1")
3534 * tmp$ = caseLabelToPosition("caseLabel_1");
3535 * else if (s$.equals("caseLabel_2"))
3536 * tmp$ = caseLabelToPosition("caseLabel_2");
3537 * ...
3538 * break;
3539 * ...
3540 * }
3541 */
3543 VarSymbol dollar_s = new VarSymbol(FINAL|SYNTHETIC,
3544 names.fromString("s" + tree.pos + target.syntheticNameChar()),
3545 syms.stringType,
3546 currentMethodSym);
3547 stmtList.append(make.at(tree.pos()).VarDef(dollar_s, tree.getExpression()).setType(dollar_s.type));
3549 VarSymbol dollar_tmp = new VarSymbol(SYNTHETIC,
3550 names.fromString("tmp" + tree.pos + target.syntheticNameChar()),
3551 syms.intType,
3552 currentMethodSym);
3553 JCVariableDecl dollar_tmp_def =
3554 (JCVariableDecl)make.VarDef(dollar_tmp, make.Literal(INT, -1)).setType(dollar_tmp.type);
3555 dollar_tmp_def.init.type = dollar_tmp.type = syms.intType;
3556 stmtList.append(dollar_tmp_def);
3557 ListBuffer<JCCase> caseBuffer = ListBuffer.lb();
3558 // hashCode will trigger nullcheck on original switch expression
3559 JCMethodInvocation hashCodeCall = makeCall(make.Ident(dollar_s),
3560 names.hashCode,
3561 List.<JCExpression>nil()).setType(syms.intType);
3562 JCSwitch switch1 = make.Switch(hashCodeCall,
3563 caseBuffer.toList());
3564 for(Map.Entry<Integer, Set<String>> entry : hashToString.entrySet()) {
3565 int hashCode = entry.getKey();
3566 Set<String> stringsWithHashCode = entry.getValue();
3567 Assert.check(stringsWithHashCode.size() >= 1);
3569 JCStatement elsepart = null;
3570 for(String caseLabel : stringsWithHashCode ) {
3571 JCMethodInvocation stringEqualsCall = makeCall(make.Ident(dollar_s),
3572 names.equals,
3573 List.<JCExpression>of(make.Literal(caseLabel)));
3574 elsepart = make.If(stringEqualsCall,
3575 make.Exec(make.Assign(make.Ident(dollar_tmp),
3576 make.Literal(caseLabelToPosition.get(caseLabel))).
3577 setType(dollar_tmp.type)),
3578 elsepart);
3579 }
3581 ListBuffer<JCStatement> lb = ListBuffer.lb();
3582 JCBreak breakStmt = make.Break(null);
3583 breakStmt.target = switch1;
3584 lb.append(elsepart).append(breakStmt);
3586 caseBuffer.append(make.Case(make.Literal(hashCode), lb.toList()));
3587 }
3589 switch1.cases = caseBuffer.toList();
3590 stmtList.append(switch1);
3592 // Make isomorphic switch tree replacing string labels
3593 // with corresponding integer ones from the label to
3594 // position map.
3596 ListBuffer<JCCase> lb = ListBuffer.lb();
3597 JCSwitch switch2 = make.Switch(make.Ident(dollar_tmp), lb.toList());
3598 for(JCCase oneCase : caseList ) {
3599 // Rewire up old unlabeled break statements to the
3600 // replacement switch being created.
3601 patchTargets(oneCase, tree, switch2);
3603 boolean isDefault = (oneCase.getExpression() == null);
3604 JCExpression caseExpr;
3605 if (isDefault)
3606 caseExpr = null;
3607 else {
3608 caseExpr = make.Literal(caseLabelToPosition.get((String)TreeInfo.skipParens(oneCase.
3609 getExpression()).
3610 type.constValue()));
3611 }
3613 lb.append(make.Case(caseExpr,
3614 oneCase.getStatements()));
3615 }
3617 switch2.cases = lb.toList();
3618 stmtList.append(switch2);
3620 return make.Block(0L, stmtList.toList());
3621 }
3622 }
3624 public void visitNewArray(JCNewArray tree) {
3625 tree.elemtype = translate(tree.elemtype);
3626 for (List<JCExpression> t = tree.dims; t.tail != null; t = t.tail)
3627 if (t.head != null) t.head = translate(t.head, syms.intType);
3628 tree.elems = translate(tree.elems, types.elemtype(tree.type));
3629 result = tree;
3630 }
3632 public void visitSelect(JCFieldAccess tree) {
3633 // need to special case-access of the form C.super.x
3634 // these will always need an access method.
3635 boolean qualifiedSuperAccess =
3636 tree.selected.hasTag(SELECT) &&
3637 TreeInfo.name(tree.selected) == names._super;
3638 tree.selected = translate(tree.selected);
3639 if (tree.name == names._class)
3640 result = classOf(tree.selected);
3641 else if (tree.name == names._this || tree.name == names._super)
3642 result = makeThis(tree.pos(), tree.selected.type.tsym);
3643 else
3644 result = access(tree.sym, tree, enclOp, qualifiedSuperAccess);
3645 }
3647 public void visitLetExpr(LetExpr tree) {
3648 tree.defs = translateVarDefs(tree.defs);
3649 tree.expr = translate(tree.expr, tree.type);
3650 result = tree;
3651 }
3653 // There ought to be nothing to rewrite here;
3654 // we don't generate code.
3655 public void visitAnnotation(JCAnnotation tree) {
3656 result = tree;
3657 }
3659 @Override
3660 public void visitTry(JCTry tree) {
3661 if (tree.resources.isEmpty()) {
3662 super.visitTry(tree);
3663 } else {
3664 result = makeTwrTry(tree);
3665 }
3666 }
3668 /**************************************************************************
3669 * main method
3670 *************************************************************************/
3672 /** Translate a toplevel class and return a list consisting of
3673 * the translated class and translated versions of all inner classes.
3674 * @param env The attribution environment current at the class definition.
3675 * We need this for resolving some additional symbols.
3676 * @param cdef The tree representing the class definition.
3677 */
3678 public List<JCTree> translateTopLevelClass(Env<AttrContext> env, JCTree cdef, TreeMaker make) {
3679 ListBuffer<JCTree> translated = null;
3680 try {
3681 attrEnv = env;
3682 this.make = make;
3683 endPosTable = env.toplevel.endPositions;
3684 currentClass = null;
3685 currentMethodDef = null;
3686 outermostClassDef = (cdef.hasTag(CLASSDEF)) ? (JCClassDecl)cdef : null;
3687 outermostMemberDef = null;
3688 this.translated = new ListBuffer<JCTree>();
3689 classdefs = new HashMap<ClassSymbol,JCClassDecl>();
3690 actualSymbols = new HashMap<Symbol,Symbol>();
3691 freevarCache = new HashMap<ClassSymbol,List<VarSymbol>>();
3692 proxies = new Scope(syms.noSymbol);
3693 twrVars = new Scope(syms.noSymbol);
3694 outerThisStack = List.nil();
3695 accessNums = new HashMap<Symbol,Integer>();
3696 accessSyms = new HashMap<Symbol,MethodSymbol[]>();
3697 accessConstrs = new HashMap<Symbol,MethodSymbol>();
3698 accessConstrTags = List.nil();
3699 accessed = new ListBuffer<Symbol>();
3700 translate(cdef, (JCExpression)null);
3701 for (List<Symbol> l = accessed.toList(); l.nonEmpty(); l = l.tail)
3702 makeAccessible(l.head);
3703 for (EnumMapping map : enumSwitchMap.values())
3704 map.translate();
3705 checkConflicts(this.translated.toList());
3706 checkAccessConstructorTags();
3707 translated = this.translated;
3708 } finally {
3709 // note that recursive invocations of this method fail hard
3710 attrEnv = null;
3711 this.make = null;
3712 endPosTable = null;
3713 currentClass = null;
3714 currentMethodDef = null;
3715 outermostClassDef = null;
3716 outermostMemberDef = null;
3717 this.translated = null;
3718 classdefs = null;
3719 actualSymbols = null;
3720 freevarCache = null;
3721 proxies = null;
3722 outerThisStack = null;
3723 accessNums = null;
3724 accessSyms = null;
3725 accessConstrs = null;
3726 accessConstrTags = null;
3727 accessed = null;
3728 enumSwitchMap.clear();
3729 }
3730 return translated.toList();
3731 }
3733 //////////////////////////////////////////////////////////////
3734 // The following contributed by Borland for bootstrapping purposes
3735 //////////////////////////////////////////////////////////////
3736 private void addEnumCompatibleMembers(JCClassDecl cdef) {
3737 make_at(null);
3739 // Add the special enum fields
3740 VarSymbol ordinalFieldSym = addEnumOrdinalField(cdef);
3741 VarSymbol nameFieldSym = addEnumNameField(cdef);
3743 // Add the accessor methods for name and ordinal
3744 MethodSymbol ordinalMethodSym = addEnumFieldOrdinalMethod(cdef, ordinalFieldSym);
3745 MethodSymbol nameMethodSym = addEnumFieldNameMethod(cdef, nameFieldSym);
3747 // Add the toString method
3748 addEnumToString(cdef, nameFieldSym);
3750 // Add the compareTo method
3751 addEnumCompareTo(cdef, ordinalFieldSym);
3752 }
3754 private VarSymbol addEnumOrdinalField(JCClassDecl cdef) {
3755 VarSymbol ordinal = new VarSymbol(PRIVATE|FINAL|SYNTHETIC,
3756 names.fromString("$ordinal"),
3757 syms.intType,
3758 cdef.sym);
3759 cdef.sym.members().enter(ordinal);
3760 cdef.defs = cdef.defs.prepend(make.VarDef(ordinal, null));
3761 return ordinal;
3762 }
3764 private VarSymbol addEnumNameField(JCClassDecl cdef) {
3765 VarSymbol name = new VarSymbol(PRIVATE|FINAL|SYNTHETIC,
3766 names.fromString("$name"),
3767 syms.stringType,
3768 cdef.sym);
3769 cdef.sym.members().enter(name);
3770 cdef.defs = cdef.defs.prepend(make.VarDef(name, null));
3771 return name;
3772 }
3774 private MethodSymbol addEnumFieldOrdinalMethod(JCClassDecl cdef, VarSymbol ordinalSymbol) {
3775 // Add the accessor methods for ordinal
3776 Symbol ordinalSym = lookupMethod(cdef.pos(),
3777 names.ordinal,
3778 cdef.type,
3779 List.<Type>nil());
3781 Assert.check(ordinalSym instanceof MethodSymbol);
3783 JCStatement ret = make.Return(make.Ident(ordinalSymbol));
3784 cdef.defs = cdef.defs.append(make.MethodDef((MethodSymbol)ordinalSym,
3785 make.Block(0L, List.of(ret))));
3787 return (MethodSymbol)ordinalSym;
3788 }
3790 private MethodSymbol addEnumFieldNameMethod(JCClassDecl cdef, VarSymbol nameSymbol) {
3791 // Add the accessor methods for name
3792 Symbol nameSym = lookupMethod(cdef.pos(),
3793 names._name,
3794 cdef.type,
3795 List.<Type>nil());
3797 Assert.check(nameSym instanceof MethodSymbol);
3799 JCStatement ret = make.Return(make.Ident(nameSymbol));
3801 cdef.defs = cdef.defs.append(make.MethodDef((MethodSymbol)nameSym,
3802 make.Block(0L, List.of(ret))));
3804 return (MethodSymbol)nameSym;
3805 }
3807 private MethodSymbol addEnumToString(JCClassDecl cdef,
3808 VarSymbol nameSymbol) {
3809 Symbol toStringSym = lookupMethod(cdef.pos(),
3810 names.toString,
3811 cdef.type,
3812 List.<Type>nil());
3814 JCTree toStringDecl = null;
3815 if (toStringSym != null)
3816 toStringDecl = TreeInfo.declarationFor(toStringSym, cdef);
3818 if (toStringDecl != null)
3819 return (MethodSymbol)toStringSym;
3821 JCStatement ret = make.Return(make.Ident(nameSymbol));
3823 JCTree resTypeTree = make.Type(syms.stringType);
3825 MethodType toStringType = new MethodType(List.<Type>nil(),
3826 syms.stringType,
3827 List.<Type>nil(),
3828 cdef.sym);
3829 toStringSym = new MethodSymbol(PUBLIC,
3830 names.toString,
3831 toStringType,
3832 cdef.type.tsym);
3833 toStringDecl = make.MethodDef((MethodSymbol)toStringSym,
3834 make.Block(0L, List.of(ret)));
3836 cdef.defs = cdef.defs.prepend(toStringDecl);
3837 cdef.sym.members().enter(toStringSym);
3839 return (MethodSymbol)toStringSym;
3840 }
3842 private MethodSymbol addEnumCompareTo(JCClassDecl cdef, VarSymbol ordinalSymbol) {
3843 Symbol compareToSym = lookupMethod(cdef.pos(),
3844 names.compareTo,
3845 cdef.type,
3846 List.of(cdef.sym.type));
3848 Assert.check(compareToSym instanceof MethodSymbol);
3850 JCMethodDecl compareToDecl = (JCMethodDecl) TreeInfo.declarationFor(compareToSym, cdef);
3852 ListBuffer<JCStatement> blockStatements = new ListBuffer<JCStatement>();
3854 JCModifiers mod1 = make.Modifiers(0L);
3855 Name oName = names.fromString("o");
3856 JCVariableDecl par1 = make.Param(oName, cdef.type, compareToSym);
3858 JCIdent paramId1 = make.Ident(names.java_lang_Object);
3859 paramId1.type = cdef.type;
3860 paramId1.sym = par1.sym;
3862 ((MethodSymbol)compareToSym).params = List.of(par1.sym);
3864 JCIdent par1UsageId = make.Ident(par1.sym);
3865 JCIdent castTargetIdent = make.Ident(cdef.sym);
3866 JCTypeCast cast = make.TypeCast(castTargetIdent, par1UsageId);
3867 cast.setType(castTargetIdent.type);
3869 Name otherName = names.fromString("other");
3871 VarSymbol otherVarSym = new VarSymbol(mod1.flags,
3872 otherName,
3873 cdef.type,
3874 compareToSym);
3875 JCVariableDecl otherVar = make.VarDef(otherVarSym, cast);
3876 blockStatements.append(otherVar);
3878 JCIdent id1 = make.Ident(ordinalSymbol);
3880 JCIdent fLocUsageId = make.Ident(otherVarSym);
3881 JCExpression sel = make.Select(fLocUsageId, ordinalSymbol);
3882 JCBinary bin = makeBinary(MINUS, id1, sel);
3883 JCReturn ret = make.Return(bin);
3884 blockStatements.append(ret);
3885 JCMethodDecl compareToMethod = make.MethodDef((MethodSymbol)compareToSym,
3886 make.Block(0L,
3887 blockStatements.toList()));
3888 compareToMethod.params = List.of(par1);
3889 cdef.defs = cdef.defs.append(compareToMethod);
3891 return (MethodSymbol)compareToSym;
3892 }
3893 //////////////////////////////////////////////////////////////
3894 // The above contributed by Borland for bootstrapping purposes
3895 //////////////////////////////////////////////////////////////
3896 }