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