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

Wed, 16 Jan 2013 17:40:28 +0000

author
mcimadamore
date
Wed, 16 Jan 2013 17:40:28 +0000
changeset 1498
1afdf1f1472b
parent 1432
969c96b980b7
child 1521
71f35e4b93a5
permissions
-rw-r--r--

8005964: Regression: difference in error recovery after ambiguity causes JCK test failure
Summary: Wrong implementation of ResolveError.access in AmbiguityError
Reviewed-by: jjh

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

mercurial