Tue, 28 Jul 2009 12:12:59 -0700
6862919: Update copyright year
Summary: Update copyright for files that have been modified in 2009, up to 07/09
Reviewed-by: tbell, ohair
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 auxilliary table intialized 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 /** Report a conflict between a user symbol and a synthetic symbol.
600 */
601 private void duplicateError(DiagnosticPosition pos, Symbol sym) {
602 if (!sym.type.isErroneous()) {
603 log.error(pos, "synthetic.name.conflict", sym, sym.location());
604 }
605 }
607 /** Enter a synthetic symbol in a given scope, but complain if there was already one there.
608 * @param pos Position for error reporting.
609 * @param sym The symbol.
610 * @param s The scope.
611 */
612 private void enterSynthetic(DiagnosticPosition pos, Symbol sym, Scope s) {
613 if (sym.name != names.error && sym.name != names.empty) {
614 for (Scope.Entry e = s.lookup(sym.name); e.scope == s; e = e.next()) {
615 if (sym != e.sym && sym.kind == e.sym.kind) {
616 // VM allows methods and variables with differing types
617 if ((sym.kind & (MTH|VAR)) != 0 &&
618 !types.erasure(sym.type).equals(types.erasure(e.sym.type)))
619 continue;
620 duplicateError(pos, e.sym);
621 break;
622 }
623 }
624 }
625 s.enter(sym);
626 }
628 /** Look up a synthetic name in a given scope.
629 * @param scope The scope.
630 * @param name The name.
631 */
632 private Symbol lookupSynthetic(Name name, Scope s) {
633 Symbol sym = s.lookup(name).sym;
634 return (sym==null || (sym.flags()&SYNTHETIC)==0) ? null : sym;
635 }
637 /** Look up a method in a given scope.
638 */
639 private MethodSymbol lookupMethod(DiagnosticPosition pos, Name name, Type qual, List<Type> args) {
640 return rs.resolveInternalMethod(pos, attrEnv, qual, name, args, null);
641 }
643 /** Look up a constructor.
644 */
645 private MethodSymbol lookupConstructor(DiagnosticPosition pos, Type qual, List<Type> args) {
646 return rs.resolveInternalConstructor(pos, attrEnv, qual, args, null);
647 }
649 /** Look up a field.
650 */
651 private VarSymbol lookupField(DiagnosticPosition pos, Type qual, Name name) {
652 return rs.resolveInternalField(pos, attrEnv, qual, name);
653 }
655 /**************************************************************************
656 * Access methods
657 *************************************************************************/
659 /** Access codes for dereferencing, assignment,
660 * and pre/post increment/decrement.
661 * Access codes for assignment operations are determined by method accessCode
662 * below.
663 *
664 * All access codes for accesses to the current class are even.
665 * If a member of the superclass should be accessed instead (because
666 * access was via a qualified super), add one to the corresponding code
667 * for the current class, making the number odd.
668 * This numbering scheme is used by the backend to decide whether
669 * to issue an invokevirtual or invokespecial call.
670 *
671 * @see Gen.visitSelect(Select tree)
672 */
673 private static final int
674 DEREFcode = 0,
675 ASSIGNcode = 2,
676 PREINCcode = 4,
677 PREDECcode = 6,
678 POSTINCcode = 8,
679 POSTDECcode = 10,
680 FIRSTASGOPcode = 12;
682 /** Number of access codes
683 */
684 private static final int NCODES = accessCode(ByteCodes.lushrl) + 2;
686 /** A mapping from symbols to their access numbers.
687 */
688 private Map<Symbol,Integer> accessNums;
690 /** A mapping from symbols to an array of access symbols, indexed by
691 * access code.
692 */
693 private Map<Symbol,MethodSymbol[]> accessSyms;
695 /** A mapping from (constructor) symbols to access constructor symbols.
696 */
697 private Map<Symbol,MethodSymbol> accessConstrs;
699 /** A queue for all accessed symbols.
700 */
701 private ListBuffer<Symbol> accessed;
703 /** Map bytecode of binary operation to access code of corresponding
704 * assignment operation. This is always an even number.
705 */
706 private static int accessCode(int bytecode) {
707 if (ByteCodes.iadd <= bytecode && bytecode <= ByteCodes.lxor)
708 return (bytecode - iadd) * 2 + FIRSTASGOPcode;
709 else if (bytecode == ByteCodes.string_add)
710 return (ByteCodes.lxor + 1 - iadd) * 2 + FIRSTASGOPcode;
711 else if (ByteCodes.ishll <= bytecode && bytecode <= ByteCodes.lushrl)
712 return (bytecode - ishll + ByteCodes.lxor + 2 - iadd) * 2 + FIRSTASGOPcode;
713 else
714 return -1;
715 }
717 /** return access code for identifier,
718 * @param tree The tree representing the identifier use.
719 * @param enclOp The closest enclosing operation node of tree,
720 * null if tree is not a subtree of an operation.
721 */
722 private static int accessCode(JCTree tree, JCTree enclOp) {
723 if (enclOp == null)
724 return DEREFcode;
725 else if (enclOp.getTag() == JCTree.ASSIGN &&
726 tree == TreeInfo.skipParens(((JCAssign) enclOp).lhs))
727 return ASSIGNcode;
728 else if (JCTree.PREINC <= enclOp.getTag() && enclOp.getTag() <= JCTree.POSTDEC &&
729 tree == TreeInfo.skipParens(((JCUnary) enclOp).arg))
730 return (enclOp.getTag() - JCTree.PREINC) * 2 + PREINCcode;
731 else if (JCTree.BITOR_ASG <= enclOp.getTag() && enclOp.getTag() <= JCTree.MOD_ASG &&
732 tree == TreeInfo.skipParens(((JCAssignOp) enclOp).lhs))
733 return accessCode(((OperatorSymbol) ((JCAssignOp) enclOp).operator).opcode);
734 else
735 return DEREFcode;
736 }
738 /** Return binary operator that corresponds to given access code.
739 */
740 private OperatorSymbol binaryAccessOperator(int acode) {
741 for (Scope.Entry e = syms.predefClass.members().elems;
742 e != null;
743 e = e.sibling) {
744 if (e.sym instanceof OperatorSymbol) {
745 OperatorSymbol op = (OperatorSymbol)e.sym;
746 if (accessCode(op.opcode) == acode) return op;
747 }
748 }
749 return null;
750 }
752 /** Return tree tag for assignment operation corresponding
753 * to given binary operator.
754 */
755 private static int treeTag(OperatorSymbol operator) {
756 switch (operator.opcode) {
757 case ByteCodes.ior: case ByteCodes.lor:
758 return JCTree.BITOR_ASG;
759 case ByteCodes.ixor: case ByteCodes.lxor:
760 return JCTree.BITXOR_ASG;
761 case ByteCodes.iand: case ByteCodes.land:
762 return JCTree.BITAND_ASG;
763 case ByteCodes.ishl: case ByteCodes.lshl:
764 case ByteCodes.ishll: case ByteCodes.lshll:
765 return JCTree.SL_ASG;
766 case ByteCodes.ishr: case ByteCodes.lshr:
767 case ByteCodes.ishrl: case ByteCodes.lshrl:
768 return JCTree.SR_ASG;
769 case ByteCodes.iushr: case ByteCodes.lushr:
770 case ByteCodes.iushrl: case ByteCodes.lushrl:
771 return JCTree.USR_ASG;
772 case ByteCodes.iadd: case ByteCodes.ladd:
773 case ByteCodes.fadd: case ByteCodes.dadd:
774 case ByteCodes.string_add:
775 return JCTree.PLUS_ASG;
776 case ByteCodes.isub: case ByteCodes.lsub:
777 case ByteCodes.fsub: case ByteCodes.dsub:
778 return JCTree.MINUS_ASG;
779 case ByteCodes.imul: case ByteCodes.lmul:
780 case ByteCodes.fmul: case ByteCodes.dmul:
781 return JCTree.MUL_ASG;
782 case ByteCodes.idiv: case ByteCodes.ldiv:
783 case ByteCodes.fdiv: case ByteCodes.ddiv:
784 return JCTree.DIV_ASG;
785 case ByteCodes.imod: case ByteCodes.lmod:
786 case ByteCodes.fmod: case ByteCodes.dmod:
787 return JCTree.MOD_ASG;
788 default:
789 throw new AssertionError();
790 }
791 }
793 /** The name of the access method with number `anum' and access code `acode'.
794 */
795 Name accessName(int anum, int acode) {
796 return names.fromString(
797 "access" + target.syntheticNameChar() + anum + acode / 10 + acode % 10);
798 }
800 /** Return access symbol for a private or protected symbol from an inner class.
801 * @param sym The accessed private symbol.
802 * @param tree The accessing tree.
803 * @param enclOp The closest enclosing operation node of tree,
804 * null if tree is not a subtree of an operation.
805 * @param protAccess Is access to a protected symbol in another
806 * package?
807 * @param refSuper Is access via a (qualified) C.super?
808 */
809 MethodSymbol accessSymbol(Symbol sym, JCTree tree, JCTree enclOp,
810 boolean protAccess, boolean refSuper) {
811 ClassSymbol accOwner = refSuper && protAccess
812 // For access via qualified super (T.super.x), place the
813 // access symbol on T.
814 ? (ClassSymbol)((JCFieldAccess) tree).selected.type.tsym
815 // Otherwise pretend that the owner of an accessed
816 // protected symbol is the enclosing class of the current
817 // class which is a subclass of the symbol's owner.
818 : accessClass(sym, protAccess, tree);
820 Symbol vsym = sym;
821 if (sym.owner != accOwner) {
822 vsym = sym.clone(accOwner);
823 actualSymbols.put(vsym, sym);
824 }
826 Integer anum // The access number of the access method.
827 = accessNums.get(vsym);
828 if (anum == null) {
829 anum = accessed.length();
830 accessNums.put(vsym, anum);
831 accessSyms.put(vsym, new MethodSymbol[NCODES]);
832 accessed.append(vsym);
833 // System.out.println("accessing " + vsym + " in " + vsym.location());
834 }
836 int acode; // The access code of the access method.
837 List<Type> argtypes; // The argument types of the access method.
838 Type restype; // The result type of the access method.
839 List<Type> thrown; // The thrown execeptions of the access method.
840 switch (vsym.kind) {
841 case VAR:
842 acode = accessCode(tree, enclOp);
843 if (acode >= FIRSTASGOPcode) {
844 OperatorSymbol operator = binaryAccessOperator(acode);
845 if (operator.opcode == string_add)
846 argtypes = List.of(syms.objectType);
847 else
848 argtypes = operator.type.getParameterTypes().tail;
849 } else if (acode == ASSIGNcode)
850 argtypes = List.of(vsym.erasure(types));
851 else
852 argtypes = List.nil();
853 restype = vsym.erasure(types);
854 thrown = List.nil();
855 break;
856 case MTH:
857 acode = DEREFcode;
858 argtypes = vsym.erasure(types).getParameterTypes();
859 restype = vsym.erasure(types).getReturnType();
860 thrown = vsym.type.getThrownTypes();
861 break;
862 default:
863 throw new AssertionError();
864 }
866 // For references via qualified super, increment acode by one,
867 // making it odd.
868 if (protAccess && refSuper) acode++;
870 // Instance access methods get instance as first parameter.
871 // For protected symbols this needs to be the instance as a member
872 // of the type containing the accessed symbol, not the class
873 // containing the access method.
874 if ((vsym.flags() & STATIC) == 0) {
875 argtypes = argtypes.prepend(vsym.owner.erasure(types));
876 }
877 MethodSymbol[] accessors = accessSyms.get(vsym);
878 MethodSymbol accessor = accessors[acode];
879 if (accessor == null) {
880 accessor = new MethodSymbol(
881 STATIC | SYNTHETIC,
882 accessName(anum.intValue(), acode),
883 new MethodType(argtypes, restype, thrown, syms.methodClass),
884 accOwner);
885 enterSynthetic(tree.pos(), accessor, accOwner.members());
886 accessors[acode] = accessor;
887 }
888 return accessor;
889 }
891 /** The qualifier to be used for accessing a symbol in an outer class.
892 * This is either C.sym or C.this.sym, depending on whether or not
893 * sym is static.
894 * @param sym The accessed symbol.
895 */
896 JCExpression accessBase(DiagnosticPosition pos, Symbol sym) {
897 return (sym.flags() & STATIC) != 0
898 ? access(make.at(pos.getStartPosition()).QualIdent(sym.owner))
899 : makeOwnerThis(pos, sym, true);
900 }
902 /** Do we need an access method to reference private symbol?
903 */
904 boolean needsPrivateAccess(Symbol sym) {
905 if ((sym.flags() & PRIVATE) == 0 || sym.owner == currentClass) {
906 return false;
907 } else if (sym.name == names.init && (sym.owner.owner.kind & (VAR | MTH)) != 0) {
908 // private constructor in local class: relax protection
909 sym.flags_field &= ~PRIVATE;
910 return false;
911 } else {
912 return true;
913 }
914 }
916 /** Do we need an access method to reference symbol in other package?
917 */
918 boolean needsProtectedAccess(Symbol sym, JCTree tree) {
919 if ((sym.flags() & PROTECTED) == 0 ||
920 sym.owner.owner == currentClass.owner || // fast special case
921 sym.packge() == currentClass.packge())
922 return false;
923 if (!currentClass.isSubClass(sym.owner, types))
924 return true;
925 if ((sym.flags() & STATIC) != 0 ||
926 tree.getTag() != JCTree.SELECT ||
927 TreeInfo.name(((JCFieldAccess) tree).selected) == names._super)
928 return false;
929 return !((JCFieldAccess) tree).selected.type.tsym.isSubClass(currentClass, types);
930 }
932 /** The class in which an access method for given symbol goes.
933 * @param sym The access symbol
934 * @param protAccess Is access to a protected symbol in another
935 * package?
936 */
937 ClassSymbol accessClass(Symbol sym, boolean protAccess, JCTree tree) {
938 if (protAccess) {
939 Symbol qualifier = null;
940 ClassSymbol c = currentClass;
941 if (tree.getTag() == JCTree.SELECT && (sym.flags() & STATIC) == 0) {
942 qualifier = ((JCFieldAccess) tree).selected.type.tsym;
943 while (!qualifier.isSubClass(c, types)) {
944 c = c.owner.enclClass();
945 }
946 return c;
947 } else {
948 while (!c.isSubClass(sym.owner, types)) {
949 c = c.owner.enclClass();
950 }
951 }
952 return c;
953 } else {
954 // the symbol is private
955 return sym.owner.enclClass();
956 }
957 }
959 /** Ensure that identifier is accessible, return tree accessing the identifier.
960 * @param sym The accessed symbol.
961 * @param tree The tree referring to the symbol.
962 * @param enclOp The closest enclosing operation node of tree,
963 * null if tree is not a subtree of an operation.
964 * @param refSuper Is access via a (qualified) C.super?
965 */
966 JCExpression access(Symbol sym, JCExpression tree, JCExpression enclOp, boolean refSuper) {
967 // Access a free variable via its proxy, or its proxy's proxy
968 while (sym.kind == VAR && sym.owner.kind == MTH &&
969 sym.owner.enclClass() != currentClass) {
970 // A constant is replaced by its constant value.
971 Object cv = ((VarSymbol)sym).getConstValue();
972 if (cv != null) {
973 make.at(tree.pos);
974 return makeLit(sym.type, cv);
975 }
976 // Otherwise replace the variable by its proxy.
977 sym = proxies.lookup(proxyName(sym.name)).sym;
978 assert sym != null && (sym.flags_field & FINAL) != 0;
979 tree = make.at(tree.pos).Ident(sym);
980 }
981 JCExpression base = (tree.getTag() == JCTree.SELECT) ? ((JCFieldAccess) tree).selected : null;
982 switch (sym.kind) {
983 case TYP:
984 if (sym.owner.kind != PCK) {
985 // Convert type idents to
986 // <flat name> or <package name> . <flat name>
987 Name flatname = Convert.shortName(sym.flatName());
988 while (base != null &&
989 TreeInfo.symbol(base) != null &&
990 TreeInfo.symbol(base).kind != PCK) {
991 base = (base.getTag() == JCTree.SELECT)
992 ? ((JCFieldAccess) base).selected
993 : null;
994 }
995 if (tree.getTag() == JCTree.IDENT) {
996 ((JCIdent) tree).name = flatname;
997 } else if (base == null) {
998 tree = make.at(tree.pos).Ident(sym);
999 ((JCIdent) tree).name = flatname;
1000 } else {
1001 ((JCFieldAccess) tree).selected = base;
1002 ((JCFieldAccess) tree).name = flatname;
1003 }
1004 }
1005 break;
1006 case MTH: case VAR:
1007 if (sym.owner.kind == TYP) {
1009 // Access methods are required for
1010 // - private members,
1011 // - protected members in a superclass of an
1012 // enclosing class contained in another package.
1013 // - all non-private members accessed via a qualified super.
1014 boolean protAccess = refSuper && !needsPrivateAccess(sym)
1015 || needsProtectedAccess(sym, tree);
1016 boolean accReq = protAccess || needsPrivateAccess(sym);
1018 // A base has to be supplied for
1019 // - simple identifiers accessing variables in outer classes.
1020 boolean baseReq =
1021 base == null &&
1022 sym.owner != syms.predefClass &&
1023 !sym.isMemberOf(currentClass, types);
1025 if (accReq || baseReq) {
1026 make.at(tree.pos);
1028 // Constants are replaced by their constant value.
1029 if (sym.kind == VAR) {
1030 Object cv = ((VarSymbol)sym).getConstValue();
1031 if (cv != null) return makeLit(sym.type, cv);
1032 }
1034 // Private variables and methods are replaced by calls
1035 // to their access methods.
1036 if (accReq) {
1037 List<JCExpression> args = List.nil();
1038 if ((sym.flags() & STATIC) == 0) {
1039 // Instance access methods get instance
1040 // as first parameter.
1041 if (base == null)
1042 base = makeOwnerThis(tree.pos(), sym, true);
1043 args = args.prepend(base);
1044 base = null; // so we don't duplicate code
1045 }
1046 Symbol access = accessSymbol(sym, tree,
1047 enclOp, protAccess,
1048 refSuper);
1049 JCExpression receiver = make.Select(
1050 base != null ? base : make.QualIdent(access.owner),
1051 access);
1052 return make.App(receiver, args);
1054 // Other accesses to members of outer classes get a
1055 // qualifier.
1056 } else if (baseReq) {
1057 return make.at(tree.pos).Select(
1058 accessBase(tree.pos(), sym), sym).setType(tree.type);
1059 }
1060 }
1061 }
1062 }
1063 return tree;
1064 }
1066 /** Ensure that identifier is accessible, return tree accessing the identifier.
1067 * @param tree The identifier tree.
1068 */
1069 JCExpression access(JCExpression tree) {
1070 Symbol sym = TreeInfo.symbol(tree);
1071 return sym == null ? tree : access(sym, tree, null, false);
1072 }
1074 /** Return access constructor for a private constructor,
1075 * or the constructor itself, if no access constructor is needed.
1076 * @param pos The position to report diagnostics, if any.
1077 * @param constr The private constructor.
1078 */
1079 Symbol accessConstructor(DiagnosticPosition pos, Symbol constr) {
1080 if (needsPrivateAccess(constr)) {
1081 ClassSymbol accOwner = constr.owner.enclClass();
1082 MethodSymbol aconstr = accessConstrs.get(constr);
1083 if (aconstr == null) {
1084 List<Type> argtypes = constr.type.getParameterTypes();
1085 if ((accOwner.flags_field & ENUM) != 0)
1086 argtypes = argtypes
1087 .prepend(syms.intType)
1088 .prepend(syms.stringType);
1089 aconstr = new MethodSymbol(
1090 SYNTHETIC,
1091 names.init,
1092 new MethodType(
1093 argtypes.append(
1094 accessConstructorTag().erasure(types)),
1095 constr.type.getReturnType(),
1096 constr.type.getThrownTypes(),
1097 syms.methodClass),
1098 accOwner);
1099 enterSynthetic(pos, aconstr, accOwner.members());
1100 accessConstrs.put(constr, aconstr);
1101 accessed.append(constr);
1102 }
1103 return aconstr;
1104 } else {
1105 return constr;
1106 }
1107 }
1109 /** Return an anonymous class nested in this toplevel class.
1110 */
1111 ClassSymbol accessConstructorTag() {
1112 ClassSymbol topClass = currentClass.outermostClass();
1113 Name flatname = names.fromString("" + topClass.getQualifiedName() +
1114 target.syntheticNameChar() +
1115 "1");
1116 ClassSymbol ctag = chk.compiled.get(flatname);
1117 if (ctag == null)
1118 ctag = makeEmptyClass(STATIC | SYNTHETIC, topClass);
1119 return ctag;
1120 }
1122 /** Add all required access methods for a private symbol to enclosing class.
1123 * @param sym The symbol.
1124 */
1125 void makeAccessible(Symbol sym) {
1126 JCClassDecl cdef = classDef(sym.owner.enclClass());
1127 assert cdef != null : "class def not found: " + sym + " in " + sym.owner;
1128 if (sym.name == names.init) {
1129 cdef.defs = cdef.defs.prepend(
1130 accessConstructorDef(cdef.pos, sym, accessConstrs.get(sym)));
1131 } else {
1132 MethodSymbol[] accessors = accessSyms.get(sym);
1133 for (int i = 0; i < NCODES; i++) {
1134 if (accessors[i] != null)
1135 cdef.defs = cdef.defs.prepend(
1136 accessDef(cdef.pos, sym, accessors[i], i));
1137 }
1138 }
1139 }
1141 /** Construct definition of an access method.
1142 * @param pos The source code position of the definition.
1143 * @param vsym The private or protected symbol.
1144 * @param accessor The access method for the symbol.
1145 * @param acode The access code.
1146 */
1147 JCTree accessDef(int pos, Symbol vsym, MethodSymbol accessor, int acode) {
1148 // System.err.println("access " + vsym + " with " + accessor);//DEBUG
1149 currentClass = vsym.owner.enclClass();
1150 make.at(pos);
1151 JCMethodDecl md = make.MethodDef(accessor, null);
1153 // Find actual symbol
1154 Symbol sym = actualSymbols.get(vsym);
1155 if (sym == null) sym = vsym;
1157 JCExpression ref; // The tree referencing the private symbol.
1158 List<JCExpression> args; // Any additional arguments to be passed along.
1159 if ((sym.flags() & STATIC) != 0) {
1160 ref = make.Ident(sym);
1161 args = make.Idents(md.params);
1162 } else {
1163 ref = make.Select(make.Ident(md.params.head), sym);
1164 args = make.Idents(md.params.tail);
1165 }
1166 JCStatement stat; // The statement accessing the private symbol.
1167 if (sym.kind == VAR) {
1168 // Normalize out all odd access codes by taking floor modulo 2:
1169 int acode1 = acode - (acode & 1);
1171 JCExpression expr; // The access method's return value.
1172 switch (acode1) {
1173 case DEREFcode:
1174 expr = ref;
1175 break;
1176 case ASSIGNcode:
1177 expr = make.Assign(ref, args.head);
1178 break;
1179 case PREINCcode: case POSTINCcode: case PREDECcode: case POSTDECcode:
1180 expr = makeUnary(
1181 ((acode1 - PREINCcode) >> 1) + JCTree.PREINC, ref);
1182 break;
1183 default:
1184 expr = make.Assignop(
1185 treeTag(binaryAccessOperator(acode1)), ref, args.head);
1186 ((JCAssignOp) expr).operator = binaryAccessOperator(acode1);
1187 }
1188 stat = make.Return(expr.setType(sym.type));
1189 } else {
1190 stat = make.Call(make.App(ref, args));
1191 }
1192 md.body = make.Block(0, List.of(stat));
1194 // Make sure all parameters, result types and thrown exceptions
1195 // are accessible.
1196 for (List<JCVariableDecl> l = md.params; l.nonEmpty(); l = l.tail)
1197 l.head.vartype = access(l.head.vartype);
1198 md.restype = access(md.restype);
1199 for (List<JCExpression> l = md.thrown; l.nonEmpty(); l = l.tail)
1200 l.head = access(l.head);
1202 return md;
1203 }
1205 /** Construct definition of an access constructor.
1206 * @param pos The source code position of the definition.
1207 * @param constr The private constructor.
1208 * @param accessor The access method for the constructor.
1209 */
1210 JCTree accessConstructorDef(int pos, Symbol constr, MethodSymbol accessor) {
1211 make.at(pos);
1212 JCMethodDecl md = make.MethodDef(accessor,
1213 accessor.externalType(types),
1214 null);
1215 JCIdent callee = make.Ident(names._this);
1216 callee.sym = constr;
1217 callee.type = constr.type;
1218 md.body =
1219 make.Block(0, List.<JCStatement>of(
1220 make.Call(
1221 make.App(
1222 callee,
1223 make.Idents(md.params.reverse().tail.reverse())))));
1224 return md;
1225 }
1227 /**************************************************************************
1228 * Free variables proxies and this$n
1229 *************************************************************************/
1231 /** A scope containing all free variable proxies for currently translated
1232 * class, as well as its this$n symbol (if needed).
1233 * Proxy scopes are nested in the same way classes are.
1234 * Inside a constructor, proxies and any this$n symbol are duplicated
1235 * in an additional innermost scope, where they represent the constructor
1236 * parameters.
1237 */
1238 Scope proxies;
1240 /** A stack containing the this$n field of the currently translated
1241 * classes (if needed) in innermost first order.
1242 * Inside a constructor, proxies and any this$n symbol are duplicated
1243 * in an additional innermost scope, where they represent the constructor
1244 * parameters.
1245 */
1246 List<VarSymbol> outerThisStack;
1248 /** The name of a free variable proxy.
1249 */
1250 Name proxyName(Name name) {
1251 return names.fromString("val" + target.syntheticNameChar() + name);
1252 }
1254 /** Proxy definitions for all free variables in given list, in reverse order.
1255 * @param pos The source code position of the definition.
1256 * @param freevars The free variables.
1257 * @param owner The class in which the definitions go.
1258 */
1259 List<JCVariableDecl> freevarDefs(int pos, List<VarSymbol> freevars, Symbol owner) {
1260 long flags = FINAL | SYNTHETIC;
1261 if (owner.kind == TYP &&
1262 target.usePrivateSyntheticFields())
1263 flags |= PRIVATE;
1264 List<JCVariableDecl> defs = List.nil();
1265 for (List<VarSymbol> l = freevars; l.nonEmpty(); l = l.tail) {
1266 VarSymbol v = l.head;
1267 VarSymbol proxy = new VarSymbol(
1268 flags, proxyName(v.name), v.erasure(types), owner);
1269 proxies.enter(proxy);
1270 JCVariableDecl vd = make.at(pos).VarDef(proxy, null);
1271 vd.vartype = access(vd.vartype);
1272 defs = defs.prepend(vd);
1273 }
1274 return defs;
1275 }
1277 /** The name of a this$n field
1278 * @param type The class referenced by the this$n field
1279 */
1280 Name outerThisName(Type type, Symbol owner) {
1281 Type t = type.getEnclosingType();
1282 int nestingLevel = 0;
1283 while (t.tag == CLASS) {
1284 t = t.getEnclosingType();
1285 nestingLevel++;
1286 }
1287 Name result = names.fromString("this" + target.syntheticNameChar() + nestingLevel);
1288 while (owner.kind == TYP && ((ClassSymbol)owner).members().lookup(result).scope != null)
1289 result = names.fromString(result.toString() + target.syntheticNameChar());
1290 return result;
1291 }
1293 /** Definition for this$n field.
1294 * @param pos The source code position of the definition.
1295 * @param owner The class in which the definition goes.
1296 */
1297 JCVariableDecl outerThisDef(int pos, Symbol owner) {
1298 long flags = FINAL | SYNTHETIC;
1299 if (owner.kind == TYP &&
1300 target.usePrivateSyntheticFields())
1301 flags |= PRIVATE;
1302 Type target = types.erasure(owner.enclClass().type.getEnclosingType());
1303 VarSymbol outerThis = new VarSymbol(
1304 flags, outerThisName(target, owner), target, owner);
1305 outerThisStack = outerThisStack.prepend(outerThis);
1306 JCVariableDecl vd = make.at(pos).VarDef(outerThis, null);
1307 vd.vartype = access(vd.vartype);
1308 return vd;
1309 }
1311 /** Return a list of trees that load the free variables in given list,
1312 * in reverse order.
1313 * @param pos The source code position to be used for the trees.
1314 * @param freevars The list of free variables.
1315 */
1316 List<JCExpression> loadFreevars(DiagnosticPosition pos, List<VarSymbol> freevars) {
1317 List<JCExpression> args = List.nil();
1318 for (List<VarSymbol> l = freevars; l.nonEmpty(); l = l.tail)
1319 args = args.prepend(loadFreevar(pos, l.head));
1320 return args;
1321 }
1322 //where
1323 JCExpression loadFreevar(DiagnosticPosition pos, VarSymbol v) {
1324 return access(v, make.at(pos).Ident(v), null, false);
1325 }
1327 /** Construct a tree simulating the expression <C.this>.
1328 * @param pos The source code position to be used for the tree.
1329 * @param c The qualifier class.
1330 */
1331 JCExpression makeThis(DiagnosticPosition pos, TypeSymbol c) {
1332 if (currentClass == c) {
1333 // in this case, `this' works fine
1334 return make.at(pos).This(c.erasure(types));
1335 } else {
1336 // need to go via this$n
1337 return makeOuterThis(pos, c);
1338 }
1339 }
1341 /** Construct a tree that represents the outer instance
1342 * <C.this>. Never pick the current `this'.
1343 * @param pos The source code position to be used for the tree.
1344 * @param c The qualifier class.
1345 */
1346 JCExpression makeOuterThis(DiagnosticPosition pos, TypeSymbol c) {
1347 List<VarSymbol> ots = outerThisStack;
1348 if (ots.isEmpty()) {
1349 log.error(pos, "no.encl.instance.of.type.in.scope", c);
1350 assert false;
1351 return makeNull();
1352 }
1353 VarSymbol ot = ots.head;
1354 JCExpression tree = access(make.at(pos).Ident(ot));
1355 TypeSymbol otc = ot.type.tsym;
1356 while (otc != c) {
1357 do {
1358 ots = ots.tail;
1359 if (ots.isEmpty()) {
1360 log.error(pos,
1361 "no.encl.instance.of.type.in.scope",
1362 c);
1363 assert false; // should have been caught in Attr
1364 return tree;
1365 }
1366 ot = ots.head;
1367 } while (ot.owner != otc);
1368 if (otc.owner.kind != PCK && !otc.hasOuterInstance()) {
1369 chk.earlyRefError(pos, c);
1370 assert false; // should have been caught in Attr
1371 return makeNull();
1372 }
1373 tree = access(make.at(pos).Select(tree, ot));
1374 otc = ot.type.tsym;
1375 }
1376 return tree;
1377 }
1379 /** Construct a tree that represents the closest outer instance
1380 * <C.this> such that the given symbol is a member of C.
1381 * @param pos The source code position to be used for the tree.
1382 * @param sym The accessed symbol.
1383 * @param preciseMatch should we accept a type that is a subtype of
1384 * sym's owner, even if it doesn't contain sym
1385 * due to hiding, overriding, or non-inheritance
1386 * due to protection?
1387 */
1388 JCExpression makeOwnerThis(DiagnosticPosition pos, Symbol sym, boolean preciseMatch) {
1389 Symbol c = sym.owner;
1390 if (preciseMatch ? sym.isMemberOf(currentClass, types)
1391 : currentClass.isSubClass(sym.owner, types)) {
1392 // in this case, `this' works fine
1393 return make.at(pos).This(c.erasure(types));
1394 } else {
1395 // need to go via this$n
1396 return makeOwnerThisN(pos, sym, preciseMatch);
1397 }
1398 }
1400 /**
1401 * Similar to makeOwnerThis but will never pick "this".
1402 */
1403 JCExpression makeOwnerThisN(DiagnosticPosition pos, Symbol sym, boolean preciseMatch) {
1404 Symbol c = sym.owner;
1405 List<VarSymbol> ots = outerThisStack;
1406 if (ots.isEmpty()) {
1407 log.error(pos, "no.encl.instance.of.type.in.scope", c);
1408 assert false;
1409 return makeNull();
1410 }
1411 VarSymbol ot = ots.head;
1412 JCExpression tree = access(make.at(pos).Ident(ot));
1413 TypeSymbol otc = ot.type.tsym;
1414 while (!(preciseMatch ? sym.isMemberOf(otc, types) : otc.isSubClass(sym.owner, types))) {
1415 do {
1416 ots = ots.tail;
1417 if (ots.isEmpty()) {
1418 log.error(pos,
1419 "no.encl.instance.of.type.in.scope",
1420 c);
1421 assert false;
1422 return tree;
1423 }
1424 ot = ots.head;
1425 } while (ot.owner != otc);
1426 tree = access(make.at(pos).Select(tree, ot));
1427 otc = ot.type.tsym;
1428 }
1429 return tree;
1430 }
1432 /** Return tree simulating the assignment <this.name = name>, where
1433 * name is the name of a free variable.
1434 */
1435 JCStatement initField(int pos, Name name) {
1436 Scope.Entry e = proxies.lookup(name);
1437 Symbol rhs = e.sym;
1438 assert rhs.owner.kind == MTH;
1439 Symbol lhs = e.next().sym;
1440 assert rhs.owner.owner == lhs.owner;
1441 make.at(pos);
1442 return
1443 make.Exec(
1444 make.Assign(
1445 make.Select(make.This(lhs.owner.erasure(types)), lhs),
1446 make.Ident(rhs)).setType(lhs.erasure(types)));
1447 }
1449 /** Return tree simulating the assignment <this.this$n = this$n>.
1450 */
1451 JCStatement initOuterThis(int pos) {
1452 VarSymbol rhs = outerThisStack.head;
1453 assert rhs.owner.kind == MTH;
1454 VarSymbol lhs = outerThisStack.tail.head;
1455 assert rhs.owner.owner == lhs.owner;
1456 make.at(pos);
1457 return
1458 make.Exec(
1459 make.Assign(
1460 make.Select(make.This(lhs.owner.erasure(types)), lhs),
1461 make.Ident(rhs)).setType(lhs.erasure(types)));
1462 }
1464 /**************************************************************************
1465 * Code for .class
1466 *************************************************************************/
1468 /** Return the symbol of a class to contain a cache of
1469 * compiler-generated statics such as class$ and the
1470 * $assertionsDisabled flag. We create an anonymous nested class
1471 * (unless one already exists) and return its symbol. However,
1472 * for backward compatibility in 1.4 and earlier we use the
1473 * top-level class itself.
1474 */
1475 private ClassSymbol outerCacheClass() {
1476 ClassSymbol clazz = outermostClassDef.sym;
1477 if ((clazz.flags() & INTERFACE) == 0 &&
1478 !target.useInnerCacheClass()) return clazz;
1479 Scope s = clazz.members();
1480 for (Scope.Entry e = s.elems; e != null; e = e.sibling)
1481 if (e.sym.kind == TYP &&
1482 e.sym.name == names.empty &&
1483 (e.sym.flags() & INTERFACE) == 0) return (ClassSymbol) e.sym;
1484 return makeEmptyClass(STATIC | SYNTHETIC, clazz);
1485 }
1487 /** Return symbol for "class$" method. If there is no method definition
1488 * for class$, construct one as follows:
1489 *
1490 * class class$(String x0) {
1491 * try {
1492 * return Class.forName(x0);
1493 * } catch (ClassNotFoundException x1) {
1494 * throw new NoClassDefFoundError(x1.getMessage());
1495 * }
1496 * }
1497 */
1498 private MethodSymbol classDollarSym(DiagnosticPosition pos) {
1499 ClassSymbol outerCacheClass = outerCacheClass();
1500 MethodSymbol classDollarSym =
1501 (MethodSymbol)lookupSynthetic(classDollar,
1502 outerCacheClass.members());
1503 if (classDollarSym == null) {
1504 classDollarSym = new MethodSymbol(
1505 STATIC | SYNTHETIC,
1506 classDollar,
1507 new MethodType(
1508 List.of(syms.stringType),
1509 types.erasure(syms.classType),
1510 List.<Type>nil(),
1511 syms.methodClass),
1512 outerCacheClass);
1513 enterSynthetic(pos, classDollarSym, outerCacheClass.members());
1515 JCMethodDecl md = make.MethodDef(classDollarSym, null);
1516 try {
1517 md.body = classDollarSymBody(pos, md);
1518 } catch (CompletionFailure ex) {
1519 md.body = make.Block(0, List.<JCStatement>nil());
1520 chk.completionError(pos, ex);
1521 }
1522 JCClassDecl outerCacheClassDef = classDef(outerCacheClass);
1523 outerCacheClassDef.defs = outerCacheClassDef.defs.prepend(md);
1524 }
1525 return classDollarSym;
1526 }
1528 /** Generate code for class$(String name). */
1529 JCBlock classDollarSymBody(DiagnosticPosition pos, JCMethodDecl md) {
1530 MethodSymbol classDollarSym = md.sym;
1531 ClassSymbol outerCacheClass = (ClassSymbol)classDollarSym.owner;
1533 JCBlock returnResult;
1535 // in 1.4.2 and above, we use
1536 // Class.forName(String name, boolean init, ClassLoader loader);
1537 // which requires we cache the current loader in cl$
1538 if (target.classLiteralsNoInit()) {
1539 // clsym = "private static ClassLoader cl$"
1540 VarSymbol clsym = new VarSymbol(STATIC|SYNTHETIC,
1541 names.fromString("cl" + target.syntheticNameChar()),
1542 syms.classLoaderType,
1543 outerCacheClass);
1544 enterSynthetic(pos, clsym, outerCacheClass.members());
1546 // emit "private static ClassLoader cl$;"
1547 JCVariableDecl cldef = make.VarDef(clsym, null);
1548 JCClassDecl outerCacheClassDef = classDef(outerCacheClass);
1549 outerCacheClassDef.defs = outerCacheClassDef.defs.prepend(cldef);
1551 // newcache := "new cache$1[0]"
1552 JCNewArray newcache = make.
1553 NewArray(make.Type(outerCacheClass.type),
1554 List.<JCExpression>of(make.Literal(INT, 0).setType(syms.intType)),
1555 null);
1556 newcache.type = new ArrayType(types.erasure(outerCacheClass.type),
1557 syms.arrayClass);
1559 // forNameSym := java.lang.Class.forName(
1560 // String s,boolean init,ClassLoader loader)
1561 Symbol forNameSym = lookupMethod(make_pos, names.forName,
1562 types.erasure(syms.classType),
1563 List.of(syms.stringType,
1564 syms.booleanType,
1565 syms.classLoaderType));
1566 // clvalue := "(cl$ == null) ?
1567 // $newcache.getClass().getComponentType().getClassLoader() : cl$"
1568 JCExpression clvalue =
1569 make.Conditional(
1570 makeBinary(JCTree.EQ, make.Ident(clsym), makeNull()),
1571 make.Assign(
1572 make.Ident(clsym),
1573 makeCall(
1574 makeCall(makeCall(newcache,
1575 names.getClass,
1576 List.<JCExpression>nil()),
1577 names.getComponentType,
1578 List.<JCExpression>nil()),
1579 names.getClassLoader,
1580 List.<JCExpression>nil())).setType(syms.classLoaderType),
1581 make.Ident(clsym)).setType(syms.classLoaderType);
1583 // returnResult := "{ return Class.forName(param1, false, cl$); }"
1584 List<JCExpression> args = List.of(make.Ident(md.params.head.sym),
1585 makeLit(syms.booleanType, 0),
1586 clvalue);
1587 returnResult = make.
1588 Block(0, List.<JCStatement>of(make.
1589 Call(make. // return
1590 App(make.
1591 Ident(forNameSym), args))));
1592 } else {
1593 // forNameSym := java.lang.Class.forName(String s)
1594 Symbol forNameSym = lookupMethod(make_pos,
1595 names.forName,
1596 types.erasure(syms.classType),
1597 List.of(syms.stringType));
1598 // returnResult := "{ return Class.forName(param1); }"
1599 returnResult = make.
1600 Block(0, List.of(make.
1601 Call(make. // return
1602 App(make.
1603 QualIdent(forNameSym),
1604 List.<JCExpression>of(make.
1605 Ident(md.params.
1606 head.sym))))));
1607 }
1609 // catchParam := ClassNotFoundException e1
1610 VarSymbol catchParam =
1611 new VarSymbol(0, make.paramName(1),
1612 syms.classNotFoundExceptionType,
1613 classDollarSym);
1615 JCStatement rethrow;
1616 if (target.hasInitCause()) {
1617 // rethrow = "throw new NoClassDefFoundError().initCause(e);
1618 JCTree throwExpr =
1619 makeCall(makeNewClass(syms.noClassDefFoundErrorType,
1620 List.<JCExpression>nil()),
1621 names.initCause,
1622 List.<JCExpression>of(make.Ident(catchParam)));
1623 rethrow = make.Throw(throwExpr);
1624 } else {
1625 // getMessageSym := ClassNotFoundException.getMessage()
1626 Symbol getMessageSym = lookupMethod(make_pos,
1627 names.getMessage,
1628 syms.classNotFoundExceptionType,
1629 List.<Type>nil());
1630 // rethrow = "throw new NoClassDefFoundError(e.getMessage());"
1631 rethrow = make.
1632 Throw(makeNewClass(syms.noClassDefFoundErrorType,
1633 List.<JCExpression>of(make.App(make.Select(make.Ident(catchParam),
1634 getMessageSym),
1635 List.<JCExpression>nil()))));
1636 }
1638 // rethrowStmt := "( $rethrow )"
1639 JCBlock rethrowStmt = make.Block(0, List.of(rethrow));
1641 // catchBlock := "catch ($catchParam) $rethrowStmt"
1642 JCCatch catchBlock = make.Catch(make.VarDef(catchParam, null),
1643 rethrowStmt);
1645 // tryCatch := "try $returnResult $catchBlock"
1646 JCStatement tryCatch = make.Try(returnResult,
1647 List.of(catchBlock), null);
1649 return make.Block(0, List.of(tryCatch));
1650 }
1651 // where
1652 /** Create an attributed tree of the form left.name(). */
1653 private JCMethodInvocation makeCall(JCExpression left, Name name, List<JCExpression> args) {
1654 assert left.type != null;
1655 Symbol funcsym = lookupMethod(make_pos, name, left.type,
1656 TreeInfo.types(args));
1657 return make.App(make.Select(left, funcsym), args);
1658 }
1660 /** The Name Of The variable to cache T.class values.
1661 * @param sig The signature of type T.
1662 */
1663 private Name cacheName(String sig) {
1664 StringBuffer buf = new StringBuffer();
1665 if (sig.startsWith("[")) {
1666 buf = buf.append("array");
1667 while (sig.startsWith("[")) {
1668 buf = buf.append(target.syntheticNameChar());
1669 sig = sig.substring(1);
1670 }
1671 if (sig.startsWith("L")) {
1672 sig = sig.substring(0, sig.length() - 1);
1673 }
1674 } else {
1675 buf = buf.append("class" + target.syntheticNameChar());
1676 }
1677 buf = buf.append(sig.replace('.', target.syntheticNameChar()));
1678 return names.fromString(buf.toString());
1679 }
1681 /** The variable symbol that caches T.class values.
1682 * If none exists yet, create a definition.
1683 * @param sig The signature of type T.
1684 * @param pos The position to report diagnostics, if any.
1685 */
1686 private VarSymbol cacheSym(DiagnosticPosition pos, String sig) {
1687 ClassSymbol outerCacheClass = outerCacheClass();
1688 Name cname = cacheName(sig);
1689 VarSymbol cacheSym =
1690 (VarSymbol)lookupSynthetic(cname, outerCacheClass.members());
1691 if (cacheSym == null) {
1692 cacheSym = new VarSymbol(
1693 STATIC | SYNTHETIC, cname, types.erasure(syms.classType), outerCacheClass);
1694 enterSynthetic(pos, cacheSym, outerCacheClass.members());
1696 JCVariableDecl cacheDef = make.VarDef(cacheSym, null);
1697 JCClassDecl outerCacheClassDef = classDef(outerCacheClass);
1698 outerCacheClassDef.defs = outerCacheClassDef.defs.prepend(cacheDef);
1699 }
1700 return cacheSym;
1701 }
1703 /** The tree simulating a T.class expression.
1704 * @param clazz The tree identifying type T.
1705 */
1706 private JCExpression classOf(JCTree clazz) {
1707 return classOfType(clazz.type, clazz.pos());
1708 }
1710 private JCExpression classOfType(Type type, DiagnosticPosition pos) {
1711 switch (type.tag) {
1712 case BYTE: case SHORT: case CHAR: case INT: case LONG: case FLOAT:
1713 case DOUBLE: case BOOLEAN: case VOID:
1714 // replace with <BoxedClass>.TYPE
1715 ClassSymbol c = types.boxedClass(type);
1716 Symbol typeSym =
1717 rs.access(
1718 rs.findIdentInType(attrEnv, c.type, names.TYPE, VAR),
1719 pos, c.type, names.TYPE, true);
1720 if (typeSym.kind == VAR)
1721 ((VarSymbol)typeSym).getConstValue(); // ensure initializer is evaluated
1722 return make.QualIdent(typeSym);
1723 case CLASS: case ARRAY:
1724 if (target.hasClassLiterals()) {
1725 VarSymbol sym = new VarSymbol(
1726 STATIC | PUBLIC | FINAL, names._class,
1727 syms.classType, type.tsym);
1728 return make_at(pos).Select(make.Type(type), sym);
1729 }
1730 // replace with <cache == null ? cache = class$(tsig) : cache>
1731 // where
1732 // - <tsig> is the type signature of T,
1733 // - <cache> is the cache variable for tsig.
1734 String sig =
1735 writer.xClassName(type).toString().replace('/', '.');
1736 Symbol cs = cacheSym(pos, sig);
1737 return make_at(pos).Conditional(
1738 makeBinary(JCTree.EQ, make.Ident(cs), makeNull()),
1739 make.Assign(
1740 make.Ident(cs),
1741 make.App(
1742 make.Ident(classDollarSym(pos)),
1743 List.<JCExpression>of(make.Literal(CLASS, sig)
1744 .setType(syms.stringType))))
1745 .setType(types.erasure(syms.classType)),
1746 make.Ident(cs)).setType(types.erasure(syms.classType));
1747 default:
1748 throw new AssertionError();
1749 }
1750 }
1752 /**************************************************************************
1753 * Code for enabling/disabling assertions.
1754 *************************************************************************/
1756 // This code is not particularly robust if the user has
1757 // previously declared a member named '$assertionsDisabled'.
1758 // The same faulty idiom also appears in the translation of
1759 // class literals above. We should report an error if a
1760 // previous declaration is not synthetic.
1762 private JCExpression assertFlagTest(DiagnosticPosition pos) {
1763 // Outermost class may be either true class or an interface.
1764 ClassSymbol outermostClass = outermostClassDef.sym;
1766 // note that this is a class, as an interface can't contain a statement.
1767 ClassSymbol container = currentClass;
1769 VarSymbol assertDisabledSym =
1770 (VarSymbol)lookupSynthetic(dollarAssertionsDisabled,
1771 container.members());
1772 if (assertDisabledSym == null) {
1773 assertDisabledSym =
1774 new VarSymbol(STATIC | FINAL | SYNTHETIC,
1775 dollarAssertionsDisabled,
1776 syms.booleanType,
1777 container);
1778 enterSynthetic(pos, assertDisabledSym, container.members());
1779 Symbol desiredAssertionStatusSym = lookupMethod(pos,
1780 names.desiredAssertionStatus,
1781 types.erasure(syms.classType),
1782 List.<Type>nil());
1783 JCClassDecl containerDef = classDef(container);
1784 make_at(containerDef.pos());
1785 JCExpression notStatus = makeUnary(JCTree.NOT, make.App(make.Select(
1786 classOfType(types.erasure(outermostClass.type),
1787 containerDef.pos()),
1788 desiredAssertionStatusSym)));
1789 JCVariableDecl assertDisabledDef = make.VarDef(assertDisabledSym,
1790 notStatus);
1791 containerDef.defs = containerDef.defs.prepend(assertDisabledDef);
1792 }
1793 make_at(pos);
1794 return makeUnary(JCTree.NOT, make.Ident(assertDisabledSym));
1795 }
1798 /**************************************************************************
1799 * Building blocks for let expressions
1800 *************************************************************************/
1802 interface TreeBuilder {
1803 JCTree build(JCTree arg);
1804 }
1806 /** Construct an expression using the builder, with the given rval
1807 * expression as an argument to the builder. However, the rval
1808 * expression must be computed only once, even if used multiple
1809 * times in the result of the builder. We do that by
1810 * constructing a "let" expression that saves the rvalue into a
1811 * temporary variable and then uses the temporary variable in
1812 * place of the expression built by the builder. The complete
1813 * resulting expression is of the form
1814 * <pre>
1815 * (let <b>TYPE</b> <b>TEMP</b> = <b>RVAL</b>;
1816 * in (<b>BUILDER</b>(<b>TEMP</b>)))
1817 * </pre>
1818 * where <code><b>TEMP</b></code> is a newly declared variable
1819 * in the let expression.
1820 */
1821 JCTree abstractRval(JCTree rval, Type type, TreeBuilder builder) {
1822 rval = TreeInfo.skipParens(rval);
1823 switch (rval.getTag()) {
1824 case JCTree.LITERAL:
1825 return builder.build(rval);
1826 case JCTree.IDENT:
1827 JCIdent id = (JCIdent) rval;
1828 if ((id.sym.flags() & FINAL) != 0 && id.sym.owner.kind == MTH)
1829 return builder.build(rval);
1830 }
1831 VarSymbol var =
1832 new VarSymbol(FINAL|SYNTHETIC,
1833 names.fromString(
1834 target.syntheticNameChar()
1835 + "" + rval.hashCode()),
1836 type,
1837 currentMethodSym);
1838 rval = convert(rval,type);
1839 JCVariableDecl def = make.VarDef(var, (JCExpression)rval); // XXX cast
1840 JCTree built = builder.build(make.Ident(var));
1841 JCTree res = make.LetExpr(def, built);
1842 res.type = built.type;
1843 return res;
1844 }
1846 // same as above, with the type of the temporary variable computed
1847 JCTree abstractRval(JCTree rval, TreeBuilder builder) {
1848 return abstractRval(rval, rval.type, builder);
1849 }
1851 // same as above, but for an expression that may be used as either
1852 // an rvalue or an lvalue. This requires special handling for
1853 // Select expressions, where we place the left-hand-side of the
1854 // select in a temporary, and for Indexed expressions, where we
1855 // place both the indexed expression and the index value in temps.
1856 JCTree abstractLval(JCTree lval, final TreeBuilder builder) {
1857 lval = TreeInfo.skipParens(lval);
1858 switch (lval.getTag()) {
1859 case JCTree.IDENT:
1860 return builder.build(lval);
1861 case JCTree.SELECT: {
1862 final JCFieldAccess s = (JCFieldAccess)lval;
1863 JCTree selected = TreeInfo.skipParens(s.selected);
1864 Symbol lid = TreeInfo.symbol(s.selected);
1865 if (lid != null && lid.kind == TYP) return builder.build(lval);
1866 return abstractRval(s.selected, new TreeBuilder() {
1867 public JCTree build(final JCTree selected) {
1868 return builder.build(make.Select((JCExpression)selected, s.sym));
1869 }
1870 });
1871 }
1872 case JCTree.INDEXED: {
1873 final JCArrayAccess i = (JCArrayAccess)lval;
1874 return abstractRval(i.indexed, new TreeBuilder() {
1875 public JCTree build(final JCTree indexed) {
1876 return abstractRval(i.index, syms.intType, new TreeBuilder() {
1877 public JCTree build(final JCTree index) {
1878 JCTree newLval = make.Indexed((JCExpression)indexed,
1879 (JCExpression)index);
1880 newLval.setType(i.type);
1881 return builder.build(newLval);
1882 }
1883 });
1884 }
1885 });
1886 }
1887 case JCTree.TYPECAST: {
1888 return abstractLval(((JCTypeCast)lval).expr, builder);
1889 }
1890 }
1891 throw new AssertionError(lval);
1892 }
1894 // evaluate and discard the first expression, then evaluate the second.
1895 JCTree makeComma(final JCTree expr1, final JCTree expr2) {
1896 return abstractRval(expr1, new TreeBuilder() {
1897 public JCTree build(final JCTree discarded) {
1898 return expr2;
1899 }
1900 });
1901 }
1903 /**************************************************************************
1904 * Translation methods
1905 *************************************************************************/
1907 /** Visitor argument: enclosing operator node.
1908 */
1909 private JCExpression enclOp;
1911 /** Visitor method: Translate a single node.
1912 * Attach the source position from the old tree to its replacement tree.
1913 */
1914 public <T extends JCTree> T translate(T tree) {
1915 if (tree == null) {
1916 return null;
1917 } else {
1918 make_at(tree.pos());
1919 T result = super.translate(tree);
1920 if (endPositions != null && result != tree) {
1921 Integer endPos = endPositions.remove(tree);
1922 if (endPos != null) endPositions.put(result, endPos);
1923 }
1924 return result;
1925 }
1926 }
1928 /** Visitor method: Translate a single node, boxing or unboxing if needed.
1929 */
1930 public <T extends JCTree> T translate(T tree, Type type) {
1931 return (tree == null) ? null : boxIfNeeded(translate(tree), type);
1932 }
1934 /** Visitor method: Translate tree.
1935 */
1936 public <T extends JCTree> T translate(T tree, JCExpression enclOp) {
1937 JCExpression prevEnclOp = this.enclOp;
1938 this.enclOp = enclOp;
1939 T res = translate(tree);
1940 this.enclOp = prevEnclOp;
1941 return res;
1942 }
1944 /** Visitor method: Translate list of trees.
1945 */
1946 public <T extends JCTree> List<T> translate(List<T> trees, JCExpression enclOp) {
1947 JCExpression prevEnclOp = this.enclOp;
1948 this.enclOp = enclOp;
1949 List<T> res = translate(trees);
1950 this.enclOp = prevEnclOp;
1951 return res;
1952 }
1954 /** Visitor method: Translate list of trees.
1955 */
1956 public <T extends JCTree> List<T> translate(List<T> trees, Type type) {
1957 if (trees == null) return null;
1958 for (List<T> l = trees; l.nonEmpty(); l = l.tail)
1959 l.head = translate(l.head, type);
1960 return trees;
1961 }
1963 public void visitTopLevel(JCCompilationUnit tree) {
1964 if (tree.packageAnnotations.nonEmpty()) {
1965 Name name = names.package_info;
1966 long flags = Flags.ABSTRACT | Flags.INTERFACE;
1967 if (target.isPackageInfoSynthetic())
1968 // package-info is marked SYNTHETIC in JDK 1.6 and later releases
1969 flags = flags | Flags.SYNTHETIC;
1970 JCClassDecl packageAnnotationsClass
1971 = make.ClassDef(make.Modifiers(flags,
1972 tree.packageAnnotations),
1973 name, List.<JCTypeParameter>nil(),
1974 null, List.<JCExpression>nil(), List.<JCTree>nil());
1975 ClassSymbol c = reader.enterClass(name, tree.packge);
1976 c.flatname = names.fromString(tree.packge + "." + name);
1977 c.sourcefile = tree.sourcefile;
1978 c.completer = null;
1979 c.members_field = new Scope(c);
1980 c.flags_field = flags;
1981 c.attributes_field = tree.packge.attributes_field;
1982 ClassType ctype = (ClassType) c.type;
1983 ctype.supertype_field = syms.objectType;
1984 ctype.interfaces_field = List.nil();
1985 packageAnnotationsClass.sym = c;
1988 translated.append(packageAnnotationsClass);
1989 }
1990 }
1992 public void visitClassDef(JCClassDecl tree) {
1993 ClassSymbol currentClassPrev = currentClass;
1994 MethodSymbol currentMethodSymPrev = currentMethodSym;
1995 currentClass = tree.sym;
1996 currentMethodSym = null;
1997 classdefs.put(currentClass, tree);
1999 proxies = proxies.dup(currentClass);
2000 List<VarSymbol> prevOuterThisStack = outerThisStack;
2002 // If this is an enum definition
2003 if ((tree.mods.flags & ENUM) != 0 &&
2004 (types.supertype(currentClass.type).tsym.flags() & ENUM) == 0)
2005 visitEnumDef(tree);
2007 // If this is a nested class, define a this$n field for
2008 // it and add to proxies.
2009 JCVariableDecl otdef = null;
2010 if (currentClass.hasOuterInstance())
2011 otdef = outerThisDef(tree.pos, currentClass);
2013 // If this is a local class, define proxies for all its free variables.
2014 List<JCVariableDecl> fvdefs = freevarDefs(
2015 tree.pos, freevars(currentClass), currentClass);
2017 // Recursively translate superclass, interfaces.
2018 tree.extending = translate(tree.extending);
2019 tree.implementing = translate(tree.implementing);
2021 // Recursively translate members, taking into account that new members
2022 // might be created during the translation and prepended to the member
2023 // list `tree.defs'.
2024 List<JCTree> seen = List.nil();
2025 while (tree.defs != seen) {
2026 List<JCTree> unseen = tree.defs;
2027 for (List<JCTree> l = unseen; l.nonEmpty() && l != seen; l = l.tail) {
2028 JCTree outermostMemberDefPrev = outermostMemberDef;
2029 if (outermostMemberDefPrev == null) outermostMemberDef = l.head;
2030 l.head = translate(l.head);
2031 outermostMemberDef = outermostMemberDefPrev;
2032 }
2033 seen = unseen;
2034 }
2036 // Convert a protected modifier to public, mask static modifier.
2037 if ((tree.mods.flags & PROTECTED) != 0) tree.mods.flags |= PUBLIC;
2038 tree.mods.flags &= ClassFlags;
2040 // Convert name to flat representation, replacing '.' by '$'.
2041 tree.name = Convert.shortName(currentClass.flatName());
2043 // Add this$n and free variables proxy definitions to class.
2044 for (List<JCVariableDecl> l = fvdefs; l.nonEmpty(); l = l.tail) {
2045 tree.defs = tree.defs.prepend(l.head);
2046 enterSynthetic(tree.pos(), l.head.sym, currentClass.members());
2047 }
2048 if (currentClass.hasOuterInstance()) {
2049 tree.defs = tree.defs.prepend(otdef);
2050 enterSynthetic(tree.pos(), otdef.sym, currentClass.members());
2051 }
2053 proxies = proxies.leave();
2054 outerThisStack = prevOuterThisStack;
2056 // Append translated tree to `translated' queue.
2057 translated.append(tree);
2059 currentClass = currentClassPrev;
2060 currentMethodSym = currentMethodSymPrev;
2062 // Return empty block {} as a placeholder for an inner class.
2063 result = make_at(tree.pos()).Block(0, List.<JCStatement>nil());
2064 }
2066 /** Translate an enum class. */
2067 private void visitEnumDef(JCClassDecl tree) {
2068 make_at(tree.pos());
2070 // add the supertype, if needed
2071 if (tree.extending == null)
2072 tree.extending = make.Type(types.supertype(tree.type));
2074 // classOfType adds a cache field to tree.defs unless
2075 // target.hasClassLiterals().
2076 JCExpression e_class = classOfType(tree.sym.type, tree.pos()).
2077 setType(types.erasure(syms.classType));
2079 // process each enumeration constant, adding implicit constructor parameters
2080 int nextOrdinal = 0;
2081 ListBuffer<JCExpression> values = new ListBuffer<JCExpression>();
2082 ListBuffer<JCTree> enumDefs = new ListBuffer<JCTree>();
2083 ListBuffer<JCTree> otherDefs = new ListBuffer<JCTree>();
2084 for (List<JCTree> defs = tree.defs;
2085 defs.nonEmpty();
2086 defs=defs.tail) {
2087 if (defs.head.getTag() == JCTree.VARDEF && (((JCVariableDecl) defs.head).mods.flags & ENUM) != 0) {
2088 JCVariableDecl var = (JCVariableDecl)defs.head;
2089 visitEnumConstantDef(var, nextOrdinal++);
2090 values.append(make.QualIdent(var.sym));
2091 enumDefs.append(var);
2092 } else {
2093 otherDefs.append(defs.head);
2094 }
2095 }
2097 // private static final T[] #VALUES = { a, b, c };
2098 Name valuesName = names.fromString(target.syntheticNameChar() + "VALUES");
2099 while (tree.sym.members().lookup(valuesName).scope != null) // avoid name clash
2100 valuesName = names.fromString(valuesName + "" + target.syntheticNameChar());
2101 Type arrayType = new ArrayType(types.erasure(tree.type), syms.arrayClass);
2102 VarSymbol valuesVar = new VarSymbol(PRIVATE|FINAL|STATIC|SYNTHETIC,
2103 valuesName,
2104 arrayType,
2105 tree.type.tsym);
2106 JCNewArray newArray = make.NewArray(make.Type(types.erasure(tree.type)),
2107 List.<JCExpression>nil(),
2108 values.toList());
2109 newArray.type = arrayType;
2110 enumDefs.append(make.VarDef(valuesVar, newArray));
2111 tree.sym.members().enter(valuesVar);
2113 Symbol valuesSym = lookupMethod(tree.pos(), names.values,
2114 tree.type, List.<Type>nil());
2115 List<JCStatement> valuesBody;
2116 if (useClone()) {
2117 // return (T[]) $VALUES.clone();
2118 JCTypeCast valuesResult =
2119 make.TypeCast(valuesSym.type.getReturnType(),
2120 make.App(make.Select(make.Ident(valuesVar),
2121 syms.arrayCloneMethod)));
2122 valuesBody = List.<JCStatement>of(make.Return(valuesResult));
2123 } else {
2124 // template: T[] $result = new T[$values.length];
2125 Name resultName = names.fromString(target.syntheticNameChar() + "result");
2126 while (tree.sym.members().lookup(resultName).scope != null) // avoid name clash
2127 resultName = names.fromString(resultName + "" + target.syntheticNameChar());
2128 VarSymbol resultVar = new VarSymbol(FINAL|SYNTHETIC,
2129 resultName,
2130 arrayType,
2131 valuesSym);
2132 JCNewArray resultArray = make.NewArray(make.Type(types.erasure(tree.type)),
2133 List.of(make.Select(make.Ident(valuesVar), syms.lengthVar)),
2134 null);
2135 resultArray.type = arrayType;
2136 JCVariableDecl decl = make.VarDef(resultVar, resultArray);
2138 // template: System.arraycopy($VALUES, 0, $result, 0, $VALUES.length);
2139 if (systemArraycopyMethod == null) {
2140 systemArraycopyMethod =
2141 new MethodSymbol(PUBLIC | STATIC,
2142 names.fromString("arraycopy"),
2143 new MethodType(List.<Type>of(syms.objectType,
2144 syms.intType,
2145 syms.objectType,
2146 syms.intType,
2147 syms.intType),
2148 syms.voidType,
2149 List.<Type>nil(),
2150 syms.methodClass),
2151 syms.systemType.tsym);
2152 }
2153 JCStatement copy =
2154 make.Exec(make.App(make.Select(make.Ident(syms.systemType.tsym),
2155 systemArraycopyMethod),
2156 List.of(make.Ident(valuesVar), make.Literal(0),
2157 make.Ident(resultVar), make.Literal(0),
2158 make.Select(make.Ident(valuesVar), syms.lengthVar))));
2160 // template: return $result;
2161 JCStatement ret = make.Return(make.Ident(resultVar));
2162 valuesBody = List.<JCStatement>of(decl, copy, ret);
2163 }
2165 JCMethodDecl valuesDef =
2166 make.MethodDef((MethodSymbol)valuesSym, make.Block(0, valuesBody));
2168 enumDefs.append(valuesDef);
2170 if (debugLower)
2171 System.err.println(tree.sym + ".valuesDef = " + valuesDef);
2173 /** The template for the following code is:
2174 *
2175 * public static E valueOf(String name) {
2176 * return (E)Enum.valueOf(E.class, name);
2177 * }
2178 *
2179 * where E is tree.sym
2180 */
2181 MethodSymbol valueOfSym = lookupMethod(tree.pos(),
2182 names.valueOf,
2183 tree.sym.type,
2184 List.of(syms.stringType));
2185 assert (valueOfSym.flags() & STATIC) != 0;
2186 VarSymbol nameArgSym = valueOfSym.params.head;
2187 JCIdent nameVal = make.Ident(nameArgSym);
2188 JCStatement enum_ValueOf =
2189 make.Return(make.TypeCast(tree.sym.type,
2190 makeCall(make.Ident(syms.enumSym),
2191 names.valueOf,
2192 List.of(e_class, nameVal))));
2193 JCMethodDecl valueOf = make.MethodDef(valueOfSym,
2194 make.Block(0, List.of(enum_ValueOf)));
2195 nameVal.sym = valueOf.params.head.sym;
2196 if (debugLower)
2197 System.err.println(tree.sym + ".valueOf = " + valueOf);
2198 enumDefs.append(valueOf);
2200 enumDefs.appendList(otherDefs.toList());
2201 tree.defs = enumDefs.toList();
2203 // Add the necessary members for the EnumCompatibleMode
2204 if (target.compilerBootstrap(tree.sym)) {
2205 addEnumCompatibleMembers(tree);
2206 }
2207 }
2208 // where
2209 private MethodSymbol systemArraycopyMethod;
2210 private boolean useClone() {
2211 try {
2212 Scope.Entry e = syms.objectType.tsym.members().lookup(names.clone);
2213 return (e.sym != null);
2214 }
2215 catch (CompletionFailure e) {
2216 return false;
2217 }
2218 }
2220 /** Translate an enumeration constant and its initializer. */
2221 private void visitEnumConstantDef(JCVariableDecl var, int ordinal) {
2222 JCNewClass varDef = (JCNewClass)var.init;
2223 varDef.args = varDef.args.
2224 prepend(makeLit(syms.intType, ordinal)).
2225 prepend(makeLit(syms.stringType, var.name.toString()));
2226 }
2228 public void visitMethodDef(JCMethodDecl tree) {
2229 if (tree.name == names.init && (currentClass.flags_field&ENUM) != 0) {
2230 // Add "String $enum$name, int $enum$ordinal" to the beginning of the
2231 // argument list for each constructor of an enum.
2232 JCVariableDecl nameParam = make_at(tree.pos()).
2233 Param(names.fromString(target.syntheticNameChar() +
2234 "enum" + target.syntheticNameChar() + "name"),
2235 syms.stringType, tree.sym);
2236 nameParam.mods.flags |= SYNTHETIC; nameParam.sym.flags_field |= SYNTHETIC;
2238 JCVariableDecl ordParam = make.
2239 Param(names.fromString(target.syntheticNameChar() +
2240 "enum" + target.syntheticNameChar() +
2241 "ordinal"),
2242 syms.intType, tree.sym);
2243 ordParam.mods.flags |= SYNTHETIC; ordParam.sym.flags_field |= SYNTHETIC;
2245 tree.params = tree.params.prepend(ordParam).prepend(nameParam);
2247 MethodSymbol m = tree.sym;
2248 Type olderasure = m.erasure(types);
2249 m.erasure_field = new MethodType(
2250 olderasure.getParameterTypes().prepend(syms.intType).prepend(syms.stringType),
2251 olderasure.getReturnType(),
2252 olderasure.getThrownTypes(),
2253 syms.methodClass);
2255 if (target.compilerBootstrap(m.owner)) {
2256 // Initialize synthetic name field
2257 Symbol nameVarSym = lookupSynthetic(names.fromString("$name"),
2258 tree.sym.owner.members());
2259 JCIdent nameIdent = make.Ident(nameParam.sym);
2260 JCIdent id1 = make.Ident(nameVarSym);
2261 JCAssign newAssign = make.Assign(id1, nameIdent);
2262 newAssign.type = id1.type;
2263 JCExpressionStatement nameAssign = make.Exec(newAssign);
2264 nameAssign.type = id1.type;
2265 tree.body.stats = tree.body.stats.prepend(nameAssign);
2267 // Initialize synthetic ordinal field
2268 Symbol ordinalVarSym = lookupSynthetic(names.fromString("$ordinal"),
2269 tree.sym.owner.members());
2270 JCIdent ordIdent = make.Ident(ordParam.sym);
2271 id1 = make.Ident(ordinalVarSym);
2272 newAssign = make.Assign(id1, ordIdent);
2273 newAssign.type = id1.type;
2274 JCExpressionStatement ordinalAssign = make.Exec(newAssign);
2275 ordinalAssign.type = id1.type;
2276 tree.body.stats = tree.body.stats.prepend(ordinalAssign);
2277 }
2278 }
2280 JCMethodDecl prevMethodDef = currentMethodDef;
2281 MethodSymbol prevMethodSym = currentMethodSym;
2282 try {
2283 currentMethodDef = tree;
2284 currentMethodSym = tree.sym;
2285 visitMethodDefInternal(tree);
2286 } finally {
2287 currentMethodDef = prevMethodDef;
2288 currentMethodSym = prevMethodSym;
2289 }
2290 }
2291 //where
2292 private void visitMethodDefInternal(JCMethodDecl tree) {
2293 if (tree.name == names.init &&
2294 (currentClass.isInner() ||
2295 (currentClass.owner.kind & (VAR | MTH)) != 0)) {
2296 // We are seeing a constructor of an inner class.
2297 MethodSymbol m = tree.sym;
2299 // Push a new proxy scope for constructor parameters.
2300 // and create definitions for any this$n and proxy parameters.
2301 proxies = proxies.dup(m);
2302 List<VarSymbol> prevOuterThisStack = outerThisStack;
2303 List<VarSymbol> fvs = freevars(currentClass);
2304 JCVariableDecl otdef = null;
2305 if (currentClass.hasOuterInstance())
2306 otdef = outerThisDef(tree.pos, m);
2307 List<JCVariableDecl> fvdefs = freevarDefs(tree.pos, fvs, m);
2309 // Recursively translate result type, parameters and thrown list.
2310 tree.restype = translate(tree.restype);
2311 tree.params = translateVarDefs(tree.params);
2312 tree.thrown = translate(tree.thrown);
2314 // when compiling stubs, don't process body
2315 if (tree.body == null) {
2316 result = tree;
2317 return;
2318 }
2320 // Add this$n (if needed) in front of and free variables behind
2321 // constructor parameter list.
2322 tree.params = tree.params.appendList(fvdefs);
2323 if (currentClass.hasOuterInstance())
2324 tree.params = tree.params.prepend(otdef);
2326 // If this is an initial constructor, i.e., it does not start with
2327 // this(...), insert initializers for this$n and proxies
2328 // before (pre-1.4, after) the call to superclass constructor.
2329 JCStatement selfCall = translate(tree.body.stats.head);
2331 List<JCStatement> added = List.nil();
2332 if (fvs.nonEmpty()) {
2333 List<Type> addedargtypes = List.nil();
2334 for (List<VarSymbol> l = fvs; l.nonEmpty(); l = l.tail) {
2335 if (TreeInfo.isInitialConstructor(tree))
2336 added = added.prepend(
2337 initField(tree.body.pos, proxyName(l.head.name)));
2338 addedargtypes = addedargtypes.prepend(l.head.erasure(types));
2339 }
2340 Type olderasure = m.erasure(types);
2341 m.erasure_field = new MethodType(
2342 olderasure.getParameterTypes().appendList(addedargtypes),
2343 olderasure.getReturnType(),
2344 olderasure.getThrownTypes(),
2345 syms.methodClass);
2346 }
2347 if (currentClass.hasOuterInstance() &&
2348 TreeInfo.isInitialConstructor(tree))
2349 {
2350 added = added.prepend(initOuterThis(tree.body.pos));
2351 }
2353 // pop local variables from proxy stack
2354 proxies = proxies.leave();
2356 // recursively translate following local statements and
2357 // combine with this- or super-call
2358 List<JCStatement> stats = translate(tree.body.stats.tail);
2359 if (target.initializeFieldsBeforeSuper())
2360 tree.body.stats = stats.prepend(selfCall).prependList(added);
2361 else
2362 tree.body.stats = stats.prependList(added).prepend(selfCall);
2364 outerThisStack = prevOuterThisStack;
2365 } else {
2366 super.visitMethodDef(tree);
2367 }
2368 result = tree;
2369 }
2371 public void visitAnnotatedType(JCAnnotatedType tree) {
2372 tree.underlyingType = translate(tree.underlyingType);
2373 result = tree.underlyingType;
2374 }
2376 public void visitTypeCast(JCTypeCast tree) {
2377 tree.clazz = translate(tree.clazz);
2378 if (tree.type.isPrimitive() != tree.expr.type.isPrimitive())
2379 tree.expr = translate(tree.expr, tree.type);
2380 else
2381 tree.expr = translate(tree.expr);
2382 result = tree;
2383 }
2385 public void visitNewClass(JCNewClass tree) {
2386 ClassSymbol c = (ClassSymbol)tree.constructor.owner;
2388 // Box arguments, if necessary
2389 boolean isEnum = (tree.constructor.owner.flags() & ENUM) != 0;
2390 List<Type> argTypes = tree.constructor.type.getParameterTypes();
2391 if (isEnum) argTypes = argTypes.prepend(syms.intType).prepend(syms.stringType);
2392 tree.args = boxArgs(argTypes, tree.args, tree.varargsElement);
2393 tree.varargsElement = null;
2395 // If created class is local, add free variables after
2396 // explicit constructor arguments.
2397 if ((c.owner.kind & (VAR | MTH)) != 0) {
2398 tree.args = tree.args.appendList(loadFreevars(tree.pos(), freevars(c)));
2399 }
2401 // If an access constructor is used, append null as a last argument.
2402 Symbol constructor = accessConstructor(tree.pos(), tree.constructor);
2403 if (constructor != tree.constructor) {
2404 tree.args = tree.args.append(makeNull());
2405 tree.constructor = constructor;
2406 }
2408 // If created class has an outer instance, and new is qualified, pass
2409 // qualifier as first argument. If new is not qualified, pass the
2410 // correct outer instance as first argument.
2411 if (c.hasOuterInstance()) {
2412 JCExpression thisArg;
2413 if (tree.encl != null) {
2414 thisArg = attr.makeNullCheck(translate(tree.encl));
2415 thisArg.type = tree.encl.type;
2416 } else if ((c.owner.kind & (MTH | VAR)) != 0) {
2417 // local class
2418 thisArg = makeThis(tree.pos(), c.type.getEnclosingType().tsym);
2419 } else {
2420 // nested class
2421 thisArg = makeOwnerThis(tree.pos(), c, false);
2422 }
2423 tree.args = tree.args.prepend(thisArg);
2424 }
2425 tree.encl = null;
2427 // If we have an anonymous class, create its flat version, rather
2428 // than the class or interface following new.
2429 if (tree.def != null) {
2430 translate(tree.def);
2431 tree.clazz = access(make_at(tree.clazz.pos()).Ident(tree.def.sym));
2432 tree.def = null;
2433 } else {
2434 tree.clazz = access(c, tree.clazz, enclOp, false);
2435 }
2436 result = tree;
2437 }
2439 // Simplify conditionals with known constant controlling expressions.
2440 // This allows us to avoid generating supporting declarations for
2441 // the dead code, which will not be eliminated during code generation.
2442 // Note that Flow.isFalse and Flow.isTrue only return true
2443 // for constant expressions in the sense of JLS 15.27, which
2444 // are guaranteed to have no side-effects. More agressive
2445 // constant propagation would require that we take care to
2446 // preserve possible side-effects in the condition expression.
2448 /** Visitor method for conditional expressions.
2449 */
2450 public void visitConditional(JCConditional tree) {
2451 JCTree cond = tree.cond = translate(tree.cond, syms.booleanType);
2452 if (cond.type.isTrue()) {
2453 result = convert(translate(tree.truepart, tree.type), tree.type);
2454 } else if (cond.type.isFalse()) {
2455 result = convert(translate(tree.falsepart, tree.type), tree.type);
2456 } else {
2457 // Condition is not a compile-time constant.
2458 tree.truepart = translate(tree.truepart, tree.type);
2459 tree.falsepart = translate(tree.falsepart, tree.type);
2460 result = tree;
2461 }
2462 }
2463 //where
2464 private JCTree convert(JCTree tree, Type pt) {
2465 if (tree.type == pt) return tree;
2466 JCTree result = make_at(tree.pos()).TypeCast(make.Type(pt), (JCExpression)tree);
2467 result.type = (tree.type.constValue() != null) ? cfolder.coerce(tree.type, pt)
2468 : pt;
2469 return result;
2470 }
2472 /** Visitor method for if statements.
2473 */
2474 public void visitIf(JCIf tree) {
2475 JCTree cond = tree.cond = translate(tree.cond, syms.booleanType);
2476 if (cond.type.isTrue()) {
2477 result = translate(tree.thenpart);
2478 } else if (cond.type.isFalse()) {
2479 if (tree.elsepart != null) {
2480 result = translate(tree.elsepart);
2481 } else {
2482 result = make.Skip();
2483 }
2484 } else {
2485 // Condition is not a compile-time constant.
2486 tree.thenpart = translate(tree.thenpart);
2487 tree.elsepart = translate(tree.elsepart);
2488 result = tree;
2489 }
2490 }
2492 /** Visitor method for assert statements. Translate them away.
2493 */
2494 public void visitAssert(JCAssert tree) {
2495 DiagnosticPosition detailPos = (tree.detail == null) ? tree.pos() : tree.detail.pos();
2496 tree.cond = translate(tree.cond, syms.booleanType);
2497 if (!tree.cond.type.isTrue()) {
2498 JCExpression cond = assertFlagTest(tree.pos());
2499 List<JCExpression> exnArgs = (tree.detail == null) ?
2500 List.<JCExpression>nil() : List.of(translate(tree.detail));
2501 if (!tree.cond.type.isFalse()) {
2502 cond = makeBinary
2503 (JCTree.AND,
2504 cond,
2505 makeUnary(JCTree.NOT, tree.cond));
2506 }
2507 result =
2508 make.If(cond,
2509 make_at(detailPos).
2510 Throw(makeNewClass(syms.assertionErrorType, exnArgs)),
2511 null);
2512 } else {
2513 result = make.Skip();
2514 }
2515 }
2517 public void visitApply(JCMethodInvocation tree) {
2518 Symbol meth = TreeInfo.symbol(tree.meth);
2519 List<Type> argtypes = meth.type.getParameterTypes();
2520 if (allowEnums &&
2521 meth.name==names.init &&
2522 meth.owner == syms.enumSym)
2523 argtypes = argtypes.tail.tail;
2524 tree.args = boxArgs(argtypes, tree.args, tree.varargsElement);
2525 tree.varargsElement = null;
2526 Name methName = TreeInfo.name(tree.meth);
2527 if (meth.name==names.init) {
2528 // We are seeing a this(...) or super(...) constructor call.
2529 // If an access constructor is used, append null as a last argument.
2530 Symbol constructor = accessConstructor(tree.pos(), meth);
2531 if (constructor != meth) {
2532 tree.args = tree.args.append(makeNull());
2533 TreeInfo.setSymbol(tree.meth, constructor);
2534 }
2536 // If we are calling a constructor of a local class, add
2537 // free variables after explicit constructor arguments.
2538 ClassSymbol c = (ClassSymbol)constructor.owner;
2539 if ((c.owner.kind & (VAR | MTH)) != 0) {
2540 tree.args = tree.args.appendList(loadFreevars(tree.pos(), freevars(c)));
2541 }
2543 // If we are calling a constructor of an enum class, pass
2544 // along the name and ordinal arguments
2545 if ((c.flags_field&ENUM) != 0 || c.getQualifiedName() == names.java_lang_Enum) {
2546 List<JCVariableDecl> params = currentMethodDef.params;
2547 if (currentMethodSym.owner.hasOuterInstance())
2548 params = params.tail; // drop this$n
2549 tree.args = tree.args
2550 .prepend(make_at(tree.pos()).Ident(params.tail.head.sym)) // ordinal
2551 .prepend(make.Ident(params.head.sym)); // name
2552 }
2554 // If we are calling a constructor of a class with an outer
2555 // instance, and the call
2556 // is qualified, pass qualifier as first argument in front of
2557 // the explicit constructor arguments. If the call
2558 // is not qualified, pass the correct outer instance as
2559 // first argument.
2560 if (c.hasOuterInstance()) {
2561 JCExpression thisArg;
2562 if (tree.meth.getTag() == JCTree.SELECT) {
2563 thisArg = attr.
2564 makeNullCheck(translate(((JCFieldAccess) tree.meth).selected));
2565 tree.meth = make.Ident(constructor);
2566 ((JCIdent) tree.meth).name = methName;
2567 } else if ((c.owner.kind & (MTH | VAR)) != 0 || methName == names._this){
2568 // local class or this() call
2569 thisArg = makeThis(tree.meth.pos(), c.type.getEnclosingType().tsym);
2570 } else {
2571 // super() call of nested class
2572 thisArg = makeOwnerThis(tree.meth.pos(), c, false);
2573 }
2574 tree.args = tree.args.prepend(thisArg);
2575 }
2576 } else {
2577 // We are seeing a normal method invocation; translate this as usual.
2578 tree.meth = translate(tree.meth);
2580 // If the translated method itself is an Apply tree, we are
2581 // seeing an access method invocation. In this case, append
2582 // the method arguments to the arguments of the access method.
2583 if (tree.meth.getTag() == JCTree.APPLY) {
2584 JCMethodInvocation app = (JCMethodInvocation)tree.meth;
2585 app.args = tree.args.prependList(app.args);
2586 result = app;
2587 return;
2588 }
2589 }
2590 result = tree;
2591 }
2593 List<JCExpression> boxArgs(List<Type> parameters, List<JCExpression> _args, Type varargsElement) {
2594 List<JCExpression> args = _args;
2595 if (parameters.isEmpty()) return args;
2596 boolean anyChanges = false;
2597 ListBuffer<JCExpression> result = new ListBuffer<JCExpression>();
2598 while (parameters.tail.nonEmpty()) {
2599 JCExpression arg = translate(args.head, parameters.head);
2600 anyChanges |= (arg != args.head);
2601 result.append(arg);
2602 args = args.tail;
2603 parameters = parameters.tail;
2604 }
2605 Type parameter = parameters.head;
2606 if (varargsElement != null) {
2607 anyChanges = true;
2608 ListBuffer<JCExpression> elems = new ListBuffer<JCExpression>();
2609 while (args.nonEmpty()) {
2610 JCExpression arg = translate(args.head, varargsElement);
2611 elems.append(arg);
2612 args = args.tail;
2613 }
2614 JCNewArray boxedArgs = make.NewArray(make.Type(varargsElement),
2615 List.<JCExpression>nil(),
2616 elems.toList());
2617 boxedArgs.type = new ArrayType(varargsElement, syms.arrayClass);
2618 result.append(boxedArgs);
2619 } else {
2620 if (args.length() != 1) throw new AssertionError(args);
2621 JCExpression arg = translate(args.head, parameter);
2622 anyChanges |= (arg != args.head);
2623 result.append(arg);
2624 if (!anyChanges) return _args;
2625 }
2626 return result.toList();
2627 }
2629 /** Expand a boxing or unboxing conversion if needed. */
2630 @SuppressWarnings("unchecked") // XXX unchecked
2631 <T extends JCTree> T boxIfNeeded(T tree, Type type) {
2632 boolean havePrimitive = tree.type.isPrimitive();
2633 if (havePrimitive == type.isPrimitive())
2634 return tree;
2635 if (havePrimitive) {
2636 Type unboxedTarget = types.unboxedType(type);
2637 if (unboxedTarget.tag != NONE) {
2638 if (!types.isSubtype(tree.type, unboxedTarget)) //e.g. Character c = 89;
2639 tree.type = unboxedTarget.constType(tree.type.constValue());
2640 return (T)boxPrimitive((JCExpression)tree, type);
2641 } else {
2642 tree = (T)boxPrimitive((JCExpression)tree);
2643 }
2644 } else {
2645 tree = (T)unbox((JCExpression)tree, type);
2646 }
2647 return tree;
2648 }
2650 /** Box up a single primitive expression. */
2651 JCExpression boxPrimitive(JCExpression tree) {
2652 return boxPrimitive(tree, types.boxedClass(tree.type).type);
2653 }
2655 /** Box up a single primitive expression. */
2656 JCExpression boxPrimitive(JCExpression tree, Type box) {
2657 make_at(tree.pos());
2658 if (target.boxWithConstructors()) {
2659 Symbol ctor = lookupConstructor(tree.pos(),
2660 box,
2661 List.<Type>nil()
2662 .prepend(tree.type));
2663 return make.Create(ctor, List.of(tree));
2664 } else {
2665 Symbol valueOfSym = lookupMethod(tree.pos(),
2666 names.valueOf,
2667 box,
2668 List.<Type>nil()
2669 .prepend(tree.type));
2670 return make.App(make.QualIdent(valueOfSym), List.of(tree));
2671 }
2672 }
2674 /** Unbox an object to a primitive value. */
2675 JCExpression unbox(JCExpression tree, Type primitive) {
2676 Type unboxedType = types.unboxedType(tree.type);
2677 // note: the "primitive" parameter is not used. There muse be
2678 // a conversion from unboxedType to primitive.
2679 make_at(tree.pos());
2680 Symbol valueSym = lookupMethod(tree.pos(),
2681 unboxedType.tsym.name.append(names.Value), // x.intValue()
2682 tree.type,
2683 List.<Type>nil());
2684 return make.App(make.Select(tree, valueSym));
2685 }
2687 /** Visitor method for parenthesized expressions.
2688 * If the subexpression has changed, omit the parens.
2689 */
2690 public void visitParens(JCParens tree) {
2691 JCTree expr = translate(tree.expr);
2692 result = ((expr == tree.expr) ? tree : expr);
2693 }
2695 public void visitIndexed(JCArrayAccess tree) {
2696 tree.indexed = translate(tree.indexed);
2697 tree.index = translate(tree.index, syms.intType);
2698 result = tree;
2699 }
2701 public void visitAssign(JCAssign tree) {
2702 tree.lhs = translate(tree.lhs, tree);
2703 tree.rhs = translate(tree.rhs, tree.lhs.type);
2705 // If translated left hand side is an Apply, we are
2706 // seeing an access method invocation. In this case, append
2707 // right hand side as last argument of the access method.
2708 if (tree.lhs.getTag() == JCTree.APPLY) {
2709 JCMethodInvocation app = (JCMethodInvocation)tree.lhs;
2710 app.args = List.of(tree.rhs).prependList(app.args);
2711 result = app;
2712 } else {
2713 result = tree;
2714 }
2715 }
2717 public void visitAssignop(final JCAssignOp tree) {
2718 if (!tree.lhs.type.isPrimitive() &&
2719 tree.operator.type.getReturnType().isPrimitive()) {
2720 // boxing required; need to rewrite as x = (unbox typeof x)(x op y);
2721 // or if x == (typeof x)z then z = (unbox typeof x)((typeof x)z op y)
2722 // (but without recomputing x)
2723 JCTree newTree = abstractLval(tree.lhs, new TreeBuilder() {
2724 public JCTree build(final JCTree lhs) {
2725 int newTag = tree.getTag() - JCTree.ASGOffset;
2726 // Erasure (TransTypes) can change the type of
2727 // tree.lhs. However, we can still get the
2728 // unerased type of tree.lhs as it is stored
2729 // in tree.type in Attr.
2730 Symbol newOperator = rs.resolveBinaryOperator(tree.pos(),
2731 newTag,
2732 attrEnv,
2733 tree.type,
2734 tree.rhs.type);
2735 JCExpression expr = (JCExpression)lhs;
2736 if (expr.type != tree.type)
2737 expr = make.TypeCast(tree.type, expr);
2738 JCBinary opResult = make.Binary(newTag, expr, tree.rhs);
2739 opResult.operator = newOperator;
2740 opResult.type = newOperator.type.getReturnType();
2741 JCTypeCast newRhs = make.TypeCast(types.unboxedType(tree.type),
2742 opResult);
2743 return make.Assign((JCExpression)lhs, newRhs).setType(tree.type);
2744 }
2745 });
2746 result = translate(newTree);
2747 return;
2748 }
2749 tree.lhs = translate(tree.lhs, tree);
2750 tree.rhs = translate(tree.rhs, tree.operator.type.getParameterTypes().tail.head);
2752 // If translated left hand side is an Apply, we are
2753 // seeing an access method invocation. In this case, append
2754 // right hand side as last argument of the access method.
2755 if (tree.lhs.getTag() == JCTree.APPLY) {
2756 JCMethodInvocation app = (JCMethodInvocation)tree.lhs;
2757 // if operation is a += on strings,
2758 // make sure to convert argument to string
2759 JCExpression rhs = (((OperatorSymbol)tree.operator).opcode == string_add)
2760 ? makeString(tree.rhs)
2761 : tree.rhs;
2762 app.args = List.of(rhs).prependList(app.args);
2763 result = app;
2764 } else {
2765 result = tree;
2766 }
2767 }
2769 /** Lower a tree of the form e++ or e-- where e is an object type */
2770 JCTree lowerBoxedPostop(final JCUnary tree) {
2771 // translate to tmp1=lval(e); tmp2=tmp1; tmp1 OP 1; tmp2
2772 // or
2773 // translate to tmp1=lval(e); tmp2=tmp1; (typeof tree)tmp1 OP 1; tmp2
2774 // where OP is += or -=
2775 final boolean cast = TreeInfo.skipParens(tree.arg).getTag() == JCTree.TYPECAST;
2776 return abstractLval(tree.arg, new TreeBuilder() {
2777 public JCTree build(final JCTree tmp1) {
2778 return abstractRval(tmp1, tree.arg.type, new TreeBuilder() {
2779 public JCTree build(final JCTree tmp2) {
2780 int opcode = (tree.getTag() == JCTree.POSTINC)
2781 ? JCTree.PLUS_ASG : JCTree.MINUS_ASG;
2782 JCTree lhs = cast
2783 ? make.TypeCast(tree.arg.type, (JCExpression)tmp1)
2784 : tmp1;
2785 JCTree update = makeAssignop(opcode,
2786 lhs,
2787 make.Literal(1));
2788 return makeComma(update, tmp2);
2789 }
2790 });
2791 }
2792 });
2793 }
2795 public void visitUnary(JCUnary tree) {
2796 boolean isUpdateOperator =
2797 JCTree.PREINC <= tree.getTag() && tree.getTag() <= JCTree.POSTDEC;
2798 if (isUpdateOperator && !tree.arg.type.isPrimitive()) {
2799 switch(tree.getTag()) {
2800 case JCTree.PREINC: // ++ e
2801 // translate to e += 1
2802 case JCTree.PREDEC: // -- e
2803 // translate to e -= 1
2804 {
2805 int opcode = (tree.getTag() == JCTree.PREINC)
2806 ? JCTree.PLUS_ASG : JCTree.MINUS_ASG;
2807 JCAssignOp newTree = makeAssignop(opcode,
2808 tree.arg,
2809 make.Literal(1));
2810 result = translate(newTree, tree.type);
2811 return;
2812 }
2813 case JCTree.POSTINC: // e ++
2814 case JCTree.POSTDEC: // e --
2815 {
2816 result = translate(lowerBoxedPostop(tree), tree.type);
2817 return;
2818 }
2819 }
2820 throw new AssertionError(tree);
2821 }
2823 tree.arg = boxIfNeeded(translate(tree.arg, tree), tree.type);
2825 if (tree.getTag() == JCTree.NOT && tree.arg.type.constValue() != null) {
2826 tree.type = cfolder.fold1(bool_not, tree.arg.type);
2827 }
2829 // If translated left hand side is an Apply, we are
2830 // seeing an access method invocation. In this case, return
2831 // that access method invokation as result.
2832 if (isUpdateOperator && tree.arg.getTag() == JCTree.APPLY) {
2833 result = tree.arg;
2834 } else {
2835 result = tree;
2836 }
2837 }
2839 public void visitBinary(JCBinary tree) {
2840 List<Type> formals = tree.operator.type.getParameterTypes();
2841 JCTree lhs = tree.lhs = translate(tree.lhs, formals.head);
2842 switch (tree.getTag()) {
2843 case JCTree.OR:
2844 if (lhs.type.isTrue()) {
2845 result = lhs;
2846 return;
2847 }
2848 if (lhs.type.isFalse()) {
2849 result = translate(tree.rhs, formals.tail.head);
2850 return;
2851 }
2852 break;
2853 case JCTree.AND:
2854 if (lhs.type.isFalse()) {
2855 result = lhs;
2856 return;
2857 }
2858 if (lhs.type.isTrue()) {
2859 result = translate(tree.rhs, formals.tail.head);
2860 return;
2861 }
2862 break;
2863 }
2864 tree.rhs = translate(tree.rhs, formals.tail.head);
2865 result = tree;
2866 }
2868 public void visitIdent(JCIdent tree) {
2869 result = access(tree.sym, tree, enclOp, false);
2870 }
2872 /** Translate away the foreach loop. */
2873 public void visitForeachLoop(JCEnhancedForLoop tree) {
2874 if (types.elemtype(tree.expr.type) == null)
2875 visitIterableForeachLoop(tree);
2876 else
2877 visitArrayForeachLoop(tree);
2878 }
2879 // where
2880 /**
2881 * A statment of the form
2882 *
2883 * <pre>
2884 * for ( T v : arrayexpr ) stmt;
2885 * </pre>
2886 *
2887 * (where arrayexpr is of an array type) gets translated to
2888 *
2889 * <pre>
2890 * for ( { arraytype #arr = arrayexpr;
2891 * int #len = array.length;
2892 * int #i = 0; };
2893 * #i < #len; i$++ ) {
2894 * T v = arr$[#i];
2895 * stmt;
2896 * }
2897 * </pre>
2898 *
2899 * where #arr, #len, and #i are freshly named synthetic local variables.
2900 */
2901 private void visitArrayForeachLoop(JCEnhancedForLoop tree) {
2902 make_at(tree.expr.pos());
2903 VarSymbol arraycache = new VarSymbol(0,
2904 names.fromString("arr" + target.syntheticNameChar()),
2905 tree.expr.type,
2906 currentMethodSym);
2907 JCStatement arraycachedef = make.VarDef(arraycache, tree.expr);
2908 VarSymbol lencache = new VarSymbol(0,
2909 names.fromString("len" + target.syntheticNameChar()),
2910 syms.intType,
2911 currentMethodSym);
2912 JCStatement lencachedef = make.
2913 VarDef(lencache, make.Select(make.Ident(arraycache), syms.lengthVar));
2914 VarSymbol index = new VarSymbol(0,
2915 names.fromString("i" + target.syntheticNameChar()),
2916 syms.intType,
2917 currentMethodSym);
2919 JCVariableDecl indexdef = make.VarDef(index, make.Literal(INT, 0));
2920 indexdef.init.type = indexdef.type = syms.intType.constType(0);
2922 List<JCStatement> loopinit = List.of(arraycachedef, lencachedef, indexdef);
2923 JCBinary cond = makeBinary(JCTree.LT, make.Ident(index), make.Ident(lencache));
2925 JCExpressionStatement step = make.Exec(makeUnary(JCTree.PREINC, make.Ident(index)));
2927 Type elemtype = types.elemtype(tree.expr.type);
2928 JCExpression loopvarinit = make.Indexed(make.Ident(arraycache),
2929 make.Ident(index)).setType(elemtype);
2930 JCVariableDecl loopvardef = (JCVariableDecl)make.VarDef(tree.var.mods,
2931 tree.var.name,
2932 tree.var.vartype,
2933 loopvarinit).setType(tree.var.type);
2934 loopvardef.sym = tree.var.sym;
2935 JCBlock body = make.
2936 Block(0, List.of(loopvardef, tree.body));
2938 result = translate(make.
2939 ForLoop(loopinit,
2940 cond,
2941 List.of(step),
2942 body));
2943 patchTargets(body, tree, result);
2944 }
2945 /** Patch up break and continue targets. */
2946 private void patchTargets(JCTree body, final JCTree src, final JCTree dest) {
2947 class Patcher extends TreeScanner {
2948 public void visitBreak(JCBreak tree) {
2949 if (tree.target == src)
2950 tree.target = dest;
2951 }
2952 public void visitContinue(JCContinue tree) {
2953 if (tree.target == src)
2954 tree.target = dest;
2955 }
2956 public void visitClassDef(JCClassDecl tree) {}
2957 }
2958 new Patcher().scan(body);
2959 }
2960 /**
2961 * A statement of the form
2962 *
2963 * <pre>
2964 * for ( T v : coll ) stmt ;
2965 * </pre>
2966 *
2967 * (where coll implements Iterable<? extends T>) gets translated to
2968 *
2969 * <pre>
2970 * for ( Iterator<? extends T> #i = coll.iterator(); #i.hasNext(); ) {
2971 * T v = (T) #i.next();
2972 * stmt;
2973 * }
2974 * </pre>
2975 *
2976 * where #i is a freshly named synthetic local variable.
2977 */
2978 private void visitIterableForeachLoop(JCEnhancedForLoop tree) {
2979 make_at(tree.expr.pos());
2980 Type iteratorTarget = syms.objectType;
2981 Type iterableType = types.asSuper(types.upperBound(tree.expr.type),
2982 syms.iterableType.tsym);
2983 if (iterableType.getTypeArguments().nonEmpty())
2984 iteratorTarget = types.erasure(iterableType.getTypeArguments().head);
2985 Type eType = tree.expr.type;
2986 tree.expr.type = types.erasure(eType);
2987 if (eType.tag == TYPEVAR && eType.getUpperBound().isCompound())
2988 tree.expr = make.TypeCast(types.erasure(iterableType), tree.expr);
2989 Symbol iterator = lookupMethod(tree.expr.pos(),
2990 names.iterator,
2991 types.erasure(syms.iterableType),
2992 List.<Type>nil());
2993 VarSymbol itvar = new VarSymbol(0, names.fromString("i" + target.syntheticNameChar()),
2994 types.erasure(iterator.type.getReturnType()),
2995 currentMethodSym);
2996 JCStatement init = make.
2997 VarDef(itvar,
2998 make.App(make.Select(tree.expr, iterator)));
2999 Symbol hasNext = lookupMethod(tree.expr.pos(),
3000 names.hasNext,
3001 itvar.type,
3002 List.<Type>nil());
3003 JCMethodInvocation cond = make.App(make.Select(make.Ident(itvar), hasNext));
3004 Symbol next = lookupMethod(tree.expr.pos(),
3005 names.next,
3006 itvar.type,
3007 List.<Type>nil());
3008 JCExpression vardefinit = make.App(make.Select(make.Ident(itvar), next));
3009 if (tree.var.type.isPrimitive())
3010 vardefinit = make.TypeCast(types.upperBound(iteratorTarget), vardefinit);
3011 else
3012 vardefinit = make.TypeCast(tree.var.type, vardefinit);
3013 JCVariableDecl indexDef = (JCVariableDecl)make.VarDef(tree.var.mods,
3014 tree.var.name,
3015 tree.var.vartype,
3016 vardefinit).setType(tree.var.type);
3017 indexDef.sym = tree.var.sym;
3018 JCBlock body = make.Block(0, List.of(indexDef, tree.body));
3019 body.endpos = TreeInfo.endPos(tree.body);
3020 result = translate(make.
3021 ForLoop(List.of(init),
3022 cond,
3023 List.<JCExpressionStatement>nil(),
3024 body));
3025 patchTargets(body, tree, result);
3026 }
3028 public void visitVarDef(JCVariableDecl tree) {
3029 MethodSymbol oldMethodSym = currentMethodSym;
3030 tree.mods = translate(tree.mods);
3031 tree.vartype = translate(tree.vartype);
3032 if (currentMethodSym == null) {
3033 // A class or instance field initializer.
3034 currentMethodSym =
3035 new MethodSymbol((tree.mods.flags&STATIC) | BLOCK,
3036 names.empty, null,
3037 currentClass);
3038 }
3039 if (tree.init != null) tree.init = translate(tree.init, tree.type);
3040 result = tree;
3041 currentMethodSym = oldMethodSym;
3042 }
3044 public void visitBlock(JCBlock tree) {
3045 MethodSymbol oldMethodSym = currentMethodSym;
3046 if (currentMethodSym == null) {
3047 // Block is a static or instance initializer.
3048 currentMethodSym =
3049 new MethodSymbol(tree.flags | BLOCK,
3050 names.empty, null,
3051 currentClass);
3052 }
3053 super.visitBlock(tree);
3054 currentMethodSym = oldMethodSym;
3055 }
3057 public void visitDoLoop(JCDoWhileLoop tree) {
3058 tree.body = translate(tree.body);
3059 tree.cond = translate(tree.cond, syms.booleanType);
3060 result = tree;
3061 }
3063 public void visitWhileLoop(JCWhileLoop tree) {
3064 tree.cond = translate(tree.cond, syms.booleanType);
3065 tree.body = translate(tree.body);
3066 result = tree;
3067 }
3069 public void visitForLoop(JCForLoop tree) {
3070 tree.init = translate(tree.init);
3071 if (tree.cond != null)
3072 tree.cond = translate(tree.cond, syms.booleanType);
3073 tree.step = translate(tree.step);
3074 tree.body = translate(tree.body);
3075 result = tree;
3076 }
3078 public void visitReturn(JCReturn tree) {
3079 if (tree.expr != null)
3080 tree.expr = translate(tree.expr,
3081 types.erasure(currentMethodDef
3082 .restype.type));
3083 result = tree;
3084 }
3086 public void visitSwitch(JCSwitch tree) {
3087 Type selsuper = types.supertype(tree.selector.type);
3088 boolean enumSwitch = selsuper != null &&
3089 (tree.selector.type.tsym.flags() & ENUM) != 0;
3090 Type target = enumSwitch ? tree.selector.type : syms.intType;
3091 tree.selector = translate(tree.selector, target);
3092 tree.cases = translateCases(tree.cases);
3093 if (enumSwitch) {
3094 result = visitEnumSwitch(tree);
3095 patchTargets(result, tree, result);
3096 } else {
3097 result = tree;
3098 }
3099 }
3101 public JCTree visitEnumSwitch(JCSwitch tree) {
3102 TypeSymbol enumSym = tree.selector.type.tsym;
3103 EnumMapping map = mapForEnum(tree.pos(), enumSym);
3104 make_at(tree.pos());
3105 Symbol ordinalMethod = lookupMethod(tree.pos(),
3106 names.ordinal,
3107 tree.selector.type,
3108 List.<Type>nil());
3109 JCArrayAccess selector = make.Indexed(map.mapVar,
3110 make.App(make.Select(tree.selector,
3111 ordinalMethod)));
3112 ListBuffer<JCCase> cases = new ListBuffer<JCCase>();
3113 for (JCCase c : tree.cases) {
3114 if (c.pat != null) {
3115 VarSymbol label = (VarSymbol)TreeInfo.symbol(c.pat);
3116 JCLiteral pat = map.forConstant(label);
3117 cases.append(make.Case(pat, c.stats));
3118 } else {
3119 cases.append(c);
3120 }
3121 }
3122 return make.Switch(selector, cases.toList());
3123 }
3125 public void visitNewArray(JCNewArray tree) {
3126 tree.elemtype = translate(tree.elemtype);
3127 for (List<JCExpression> t = tree.dims; t.tail != null; t = t.tail)
3128 if (t.head != null) t.head = translate(t.head, syms.intType);
3129 tree.elems = translate(tree.elems, types.elemtype(tree.type));
3130 result = tree;
3131 }
3133 public void visitSelect(JCFieldAccess tree) {
3134 // need to special case-access of the form C.super.x
3135 // these will always need an access method.
3136 boolean qualifiedSuperAccess =
3137 tree.selected.getTag() == JCTree.SELECT &&
3138 TreeInfo.name(tree.selected) == names._super;
3139 tree.selected = translate(tree.selected);
3140 if (tree.name == names._class)
3141 result = classOf(tree.selected);
3142 else if (tree.name == names._this || tree.name == names._super)
3143 result = makeThis(tree.pos(), tree.selected.type.tsym);
3144 else
3145 result = access(tree.sym, tree, enclOp, qualifiedSuperAccess);
3146 }
3148 public void visitLetExpr(LetExpr tree) {
3149 tree.defs = translateVarDefs(tree.defs);
3150 tree.expr = translate(tree.expr, tree.type);
3151 result = tree;
3152 }
3154 // There ought to be nothing to rewrite here;
3155 // we don't generate code.
3156 public void visitAnnotation(JCAnnotation tree) {
3157 result = tree;
3158 }
3160 /**************************************************************************
3161 * main method
3162 *************************************************************************/
3164 /** Translate a toplevel class and return a list consisting of
3165 * the translated class and translated versions of all inner classes.
3166 * @param env The attribution environment current at the class definition.
3167 * We need this for resolving some additional symbols.
3168 * @param cdef The tree representing the class definition.
3169 */
3170 public List<JCTree> translateTopLevelClass(Env<AttrContext> env, JCTree cdef, TreeMaker make) {
3171 ListBuffer<JCTree> translated = null;
3172 try {
3173 attrEnv = env;
3174 this.make = make;
3175 endPositions = env.toplevel.endPositions;
3176 currentClass = null;
3177 currentMethodDef = null;
3178 outermostClassDef = (cdef.getTag() == JCTree.CLASSDEF) ? (JCClassDecl)cdef : null;
3179 outermostMemberDef = null;
3180 this.translated = new ListBuffer<JCTree>();
3181 classdefs = new HashMap<ClassSymbol,JCClassDecl>();
3182 actualSymbols = new HashMap<Symbol,Symbol>();
3183 freevarCache = new HashMap<ClassSymbol,List<VarSymbol>>();
3184 proxies = new Scope(syms.noSymbol);
3185 outerThisStack = List.nil();
3186 accessNums = new HashMap<Symbol,Integer>();
3187 accessSyms = new HashMap<Symbol,MethodSymbol[]>();
3188 accessConstrs = new HashMap<Symbol,MethodSymbol>();
3189 accessed = new ListBuffer<Symbol>();
3190 translate(cdef, (JCExpression)null);
3191 for (List<Symbol> l = accessed.toList(); l.nonEmpty(); l = l.tail)
3192 makeAccessible(l.head);
3193 for (EnumMapping map : enumSwitchMap.values())
3194 map.translate();
3195 translated = this.translated;
3196 } finally {
3197 // note that recursive invocations of this method fail hard
3198 attrEnv = null;
3199 this.make = null;
3200 endPositions = null;
3201 currentClass = null;
3202 currentMethodDef = null;
3203 outermostClassDef = null;
3204 outermostMemberDef = null;
3205 this.translated = null;
3206 classdefs = null;
3207 actualSymbols = null;
3208 freevarCache = null;
3209 proxies = null;
3210 outerThisStack = null;
3211 accessNums = null;
3212 accessSyms = null;
3213 accessConstrs = null;
3214 accessed = null;
3215 enumSwitchMap.clear();
3216 }
3217 return translated.toList();
3218 }
3220 //////////////////////////////////////////////////////////////
3221 // The following contributed by Borland for bootstrapping purposes
3222 //////////////////////////////////////////////////////////////
3223 private void addEnumCompatibleMembers(JCClassDecl cdef) {
3224 make_at(null);
3226 // Add the special enum fields
3227 VarSymbol ordinalFieldSym = addEnumOrdinalField(cdef);
3228 VarSymbol nameFieldSym = addEnumNameField(cdef);
3230 // Add the accessor methods for name and ordinal
3231 MethodSymbol ordinalMethodSym = addEnumFieldOrdinalMethod(cdef, ordinalFieldSym);
3232 MethodSymbol nameMethodSym = addEnumFieldNameMethod(cdef, nameFieldSym);
3234 // Add the toString method
3235 addEnumToString(cdef, nameFieldSym);
3237 // Add the compareTo method
3238 addEnumCompareTo(cdef, ordinalFieldSym);
3239 }
3241 private VarSymbol addEnumOrdinalField(JCClassDecl cdef) {
3242 VarSymbol ordinal = new VarSymbol(PRIVATE|FINAL|SYNTHETIC,
3243 names.fromString("$ordinal"),
3244 syms.intType,
3245 cdef.sym);
3246 cdef.sym.members().enter(ordinal);
3247 cdef.defs = cdef.defs.prepend(make.VarDef(ordinal, null));
3248 return ordinal;
3249 }
3251 private VarSymbol addEnumNameField(JCClassDecl cdef) {
3252 VarSymbol name = new VarSymbol(PRIVATE|FINAL|SYNTHETIC,
3253 names.fromString("$name"),
3254 syms.stringType,
3255 cdef.sym);
3256 cdef.sym.members().enter(name);
3257 cdef.defs = cdef.defs.prepend(make.VarDef(name, null));
3258 return name;
3259 }
3261 private MethodSymbol addEnumFieldOrdinalMethod(JCClassDecl cdef, VarSymbol ordinalSymbol) {
3262 // Add the accessor methods for ordinal
3263 Symbol ordinalSym = lookupMethod(cdef.pos(),
3264 names.ordinal,
3265 cdef.type,
3266 List.<Type>nil());
3268 assert(ordinalSym != null);
3269 assert(ordinalSym instanceof MethodSymbol);
3271 JCStatement ret = make.Return(make.Ident(ordinalSymbol));
3272 cdef.defs = cdef.defs.append(make.MethodDef((MethodSymbol)ordinalSym,
3273 make.Block(0L, List.of(ret))));
3275 return (MethodSymbol)ordinalSym;
3276 }
3278 private MethodSymbol addEnumFieldNameMethod(JCClassDecl cdef, VarSymbol nameSymbol) {
3279 // Add the accessor methods for name
3280 Symbol nameSym = lookupMethod(cdef.pos(),
3281 names._name,
3282 cdef.type,
3283 List.<Type>nil());
3285 assert(nameSym != null);
3286 assert(nameSym instanceof MethodSymbol);
3288 JCStatement ret = make.Return(make.Ident(nameSymbol));
3290 cdef.defs = cdef.defs.append(make.MethodDef((MethodSymbol)nameSym,
3291 make.Block(0L, List.of(ret))));
3293 return (MethodSymbol)nameSym;
3294 }
3296 private MethodSymbol addEnumToString(JCClassDecl cdef,
3297 VarSymbol nameSymbol) {
3298 Symbol toStringSym = lookupMethod(cdef.pos(),
3299 names.toString,
3300 cdef.type,
3301 List.<Type>nil());
3303 JCTree toStringDecl = null;
3304 if (toStringSym != null)
3305 toStringDecl = TreeInfo.declarationFor(toStringSym, cdef);
3307 if (toStringDecl != null)
3308 return (MethodSymbol)toStringSym;
3310 JCStatement ret = make.Return(make.Ident(nameSymbol));
3312 JCTree resTypeTree = make.Type(syms.stringType);
3314 MethodType toStringType = new MethodType(List.<Type>nil(),
3315 syms.stringType,
3316 List.<Type>nil(),
3317 cdef.sym);
3318 toStringSym = new MethodSymbol(PUBLIC,
3319 names.toString,
3320 toStringType,
3321 cdef.type.tsym);
3322 toStringDecl = make.MethodDef((MethodSymbol)toStringSym,
3323 make.Block(0L, List.of(ret)));
3325 cdef.defs = cdef.defs.prepend(toStringDecl);
3326 cdef.sym.members().enter(toStringSym);
3328 return (MethodSymbol)toStringSym;
3329 }
3331 private MethodSymbol addEnumCompareTo(JCClassDecl cdef, VarSymbol ordinalSymbol) {
3332 Symbol compareToSym = lookupMethod(cdef.pos(),
3333 names.compareTo,
3334 cdef.type,
3335 List.of(cdef.sym.type));
3337 assert(compareToSym != null);
3338 assert(compareToSym instanceof MethodSymbol);
3340 JCMethodDecl compareToDecl = (JCMethodDecl) TreeInfo.declarationFor(compareToSym, cdef);
3342 ListBuffer<JCStatement> blockStatements = new ListBuffer<JCStatement>();
3344 JCModifiers mod1 = make.Modifiers(0L);
3345 Name oName = names.fromString("o");
3346 JCVariableDecl par1 = make.Param(oName, cdef.type, compareToSym);
3348 JCIdent paramId1 = make.Ident(names.java_lang_Object);
3349 paramId1.type = cdef.type;
3350 paramId1.sym = par1.sym;
3352 ((MethodSymbol)compareToSym).params = List.of(par1.sym);
3354 JCIdent par1UsageId = make.Ident(par1.sym);
3355 JCIdent castTargetIdent = make.Ident(cdef.sym);
3356 JCTypeCast cast = make.TypeCast(castTargetIdent, par1UsageId);
3357 cast.setType(castTargetIdent.type);
3359 Name otherName = names.fromString("other");
3361 VarSymbol otherVarSym = new VarSymbol(mod1.flags,
3362 otherName,
3363 cdef.type,
3364 compareToSym);
3365 JCVariableDecl otherVar = make.VarDef(otherVarSym, cast);
3366 blockStatements.append(otherVar);
3368 JCIdent id1 = make.Ident(ordinalSymbol);
3370 JCIdent fLocUsageId = make.Ident(otherVarSym);
3371 JCExpression sel = make.Select(fLocUsageId, ordinalSymbol);
3372 JCBinary bin = makeBinary(JCTree.MINUS, id1, sel);
3373 JCReturn ret = make.Return(bin);
3374 blockStatements.append(ret);
3375 JCMethodDecl compareToMethod = make.MethodDef((MethodSymbol)compareToSym,
3376 make.Block(0L,
3377 blockStatements.toList()));
3378 compareToMethod.params = List.of(par1);
3379 cdef.defs = cdef.defs.append(compareToMethod);
3381 return (MethodSymbol)compareToSym;
3382 }
3383 //////////////////////////////////////////////////////////////
3384 // The above contributed by Borland for bootstrapping purposes
3385 //////////////////////////////////////////////////////////////
3386 }