src/share/classes/com/sun/tools/javac/comp/Lower.java

Thu, 09 Oct 2008 15:56:20 +0100

author
mcimadamore
date
Thu, 09 Oct 2008 15:56:20 +0100
changeset 133
c0372d1097c0
parent 113
eff38cc97183
child 237
9711a6c2db7e
permissions
-rw-r--r--

6751514: Unary post-increment with type variables crash javac during lowering
Summary: Lower.abstractRval should take into account parenthesized expressions
Reviewed-by: jjg

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

mercurial