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