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

Sat, 18 Sep 2010 09:54:51 -0700

author
mcimadamore
date
Sat, 18 Sep 2010 09:54:51 -0700
changeset 688
50f9ac2f4730
parent 665
d3ead6731a91
child 691
da7ca56d092c
permissions
-rw-r--r--

6980862: too aggressive compiler optimization causes stale results of Types.implementation()
Summary: use a scope counter in order to determine when/if the implementation cache entries are stale
Reviewed-by: jjg

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

mercurial