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

Sun, 03 Feb 2013 02:31:30 +0000

author
vromero
date
Sun, 03 Feb 2013 02:31:30 +0000
changeset 1542
a51a8dac0a2f
parent 1521
71f35e4b93a5
child 1557
017e8bdd440f
permissions
-rw-r--r--

7199823: javac generates inner class that can't be verified
Reviewed-by: jjg, mcimadamore

     1 /*
     2  * Copyright (c) 1999, 2013, 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     JCClassDecl makeEmptyClass(long flags, ClassSymbol owner) {
   574         return makeEmptyClass(flags, owner, null, true);
   575     }
   577     JCClassDecl makeEmptyClass(long flags, ClassSymbol owner, Name flatname,
   578             boolean addToDefs) {
   579         // Create class symbol.
   580         ClassSymbol c = reader.defineClass(names.empty, owner);
   581         if (flatname != null) {
   582             c.flatname = flatname;
   583         } else {
   584             c.flatname = chk.localClassName(c);
   585         }
   586         c.sourcefile = owner.sourcefile;
   587         c.completer = null;
   588         c.members_field = new Scope(c);
   589         c.flags_field = flags;
   590         ClassType ctype = (ClassType) c.type;
   591         ctype.supertype_field = syms.objectType;
   592         ctype.interfaces_field = List.nil();
   594         JCClassDecl odef = classDef(owner);
   596         // Enter class symbol in owner scope and compiled table.
   597         enterSynthetic(odef.pos(), c, owner.members());
   598         chk.compiled.put(c.flatname, c);
   600         // Create class definition tree.
   601         JCClassDecl cdef = make.ClassDef(
   602             make.Modifiers(flags), names.empty,
   603             List.<JCTypeParameter>nil(),
   604             null, List.<JCExpression>nil(), List.<JCTree>nil());
   605         cdef.sym = c;
   606         cdef.type = c.type;
   608         // Append class definition tree to owner's definitions.
   609         if (addToDefs) odef.defs = odef.defs.prepend(cdef);
   610         return cdef;
   611     }
   613 /**************************************************************************
   614  * Symbol manipulation utilities
   615  *************************************************************************/
   617     /** Enter a synthetic symbol in a given scope, but complain if there was already one there.
   618      *  @param pos           Position for error reporting.
   619      *  @param sym           The symbol.
   620      *  @param s             The scope.
   621      */
   622     private void enterSynthetic(DiagnosticPosition pos, Symbol sym, Scope s) {
   623         s.enter(sym);
   624     }
   626     /** Create a fresh synthetic name within a given scope - the unique name is
   627      *  obtained by appending '$' chars at the end of the name until no match
   628      *  is found.
   629      *
   630      * @param name base name
   631      * @param s scope in which the name has to be unique
   632      * @return fresh synthetic name
   633      */
   634     private Name makeSyntheticName(Name name, Scope s) {
   635         do {
   636             name = name.append(
   637                     target.syntheticNameChar(),
   638                     names.empty);
   639         } while (lookupSynthetic(name, s) != null);
   640         return name;
   641     }
   643     /** Check whether synthetic symbols generated during lowering conflict
   644      *  with user-defined symbols.
   645      *
   646      *  @param translatedTrees lowered class trees
   647      */
   648     void checkConflicts(List<JCTree> translatedTrees) {
   649         for (JCTree t : translatedTrees) {
   650             t.accept(conflictsChecker);
   651         }
   652     }
   654     JCTree.Visitor conflictsChecker = new TreeScanner() {
   656         TypeSymbol currentClass;
   658         @Override
   659         public void visitMethodDef(JCMethodDecl that) {
   660             chk.checkConflicts(that.pos(), that.sym, currentClass);
   661             super.visitMethodDef(that);
   662         }
   664         @Override
   665         public void visitVarDef(JCVariableDecl that) {
   666             if (that.sym.owner.kind == TYP) {
   667                 chk.checkConflicts(that.pos(), that.sym, currentClass);
   668             }
   669             super.visitVarDef(that);
   670         }
   672         @Override
   673         public void visitClassDef(JCClassDecl that) {
   674             TypeSymbol prevCurrentClass = currentClass;
   675             currentClass = that.sym;
   676             try {
   677                 super.visitClassDef(that);
   678             }
   679             finally {
   680                 currentClass = prevCurrentClass;
   681             }
   682         }
   683     };
   685     /** Look up a synthetic name in a given scope.
   686      *  @param s            The scope.
   687      *  @param name         The name.
   688      */
   689     private Symbol lookupSynthetic(Name name, Scope s) {
   690         Symbol sym = s.lookup(name).sym;
   691         return (sym==null || (sym.flags()&SYNTHETIC)==0) ? null : sym;
   692     }
   694     /** Look up a method in a given scope.
   695      */
   696     private MethodSymbol lookupMethod(DiagnosticPosition pos, Name name, Type qual, List<Type> args) {
   697         return rs.resolveInternalMethod(pos, attrEnv, qual, name, args, List.<Type>nil());
   698     }
   700     /** Look up a constructor.
   701      */
   702     private MethodSymbol lookupConstructor(DiagnosticPosition pos, Type qual, List<Type> args) {
   703         return rs.resolveInternalConstructor(pos, attrEnv, qual, args, null);
   704     }
   706     /** Look up a field.
   707      */
   708     private VarSymbol lookupField(DiagnosticPosition pos, Type qual, Name name) {
   709         return rs.resolveInternalField(pos, attrEnv, qual, name);
   710     }
   712     /** Anon inner classes are used as access constructor tags.
   713      * accessConstructorTag will use an existing anon class if one is available,
   714      * and synthethise a class (with makeEmptyClass) if one is not available.
   715      * However, there is a small possibility that an existing class will not
   716      * be generated as expected if it is inside a conditional with a constant
   717      * expression. If that is found to be the case, create an empty class tree here.
   718      */
   719     private void checkAccessConstructorTags() {
   720         for (List<ClassSymbol> l = accessConstrTags; l.nonEmpty(); l = l.tail) {
   721             ClassSymbol c = l.head;
   722             if (isTranslatedClassAvailable(c))
   723                 continue;
   724             // Create class definition tree.
   725             JCClassDecl cdec = makeEmptyClass(STATIC | SYNTHETIC,
   726                     c.outermostClass(), c.flatname, false);
   727             swapAccessConstructorTag(c, cdec.sym);
   728             translated.append(cdec);
   729         }
   730     }
   731     // where
   732     private boolean isTranslatedClassAvailable(ClassSymbol c) {
   733         for (JCTree tree: translated) {
   734             if (tree.hasTag(CLASSDEF)
   735                     && ((JCClassDecl) tree).sym == c) {
   736                 return true;
   737             }
   738         }
   739         return false;
   740     }
   742     void swapAccessConstructorTag(ClassSymbol oldCTag, ClassSymbol newCTag) {
   743         for (MethodSymbol methodSymbol : accessConstrs.values()) {
   744             Assert.check(methodSymbol.type.hasTag(METHOD));
   745             MethodType oldMethodType =
   746                     (MethodType)methodSymbol.type;
   747             if (oldMethodType.argtypes.head.tsym == oldCTag)
   748                 methodSymbol.type =
   749                     types.createMethodTypeWithParameters(oldMethodType,
   750                         oldMethodType.getParameterTypes().tail
   751                             .prepend(newCTag.erasure(types)));
   752         }
   753     }
   755 /**************************************************************************
   756  * Access methods
   757  *************************************************************************/
   759     /** Access codes for dereferencing, assignment,
   760      *  and pre/post increment/decrement.
   761      *  Access codes for assignment operations are determined by method accessCode
   762      *  below.
   763      *
   764      *  All access codes for accesses to the current class are even.
   765      *  If a member of the superclass should be accessed instead (because
   766      *  access was via a qualified super), add one to the corresponding code
   767      *  for the current class, making the number odd.
   768      *  This numbering scheme is used by the backend to decide whether
   769      *  to issue an invokevirtual or invokespecial call.
   770      *
   771      *  @see Gen#visitSelect(JCFieldAccess tree)
   772      */
   773     private static final int
   774         DEREFcode = 0,
   775         ASSIGNcode = 2,
   776         PREINCcode = 4,
   777         PREDECcode = 6,
   778         POSTINCcode = 8,
   779         POSTDECcode = 10,
   780         FIRSTASGOPcode = 12;
   782     /** Number of access codes
   783      */
   784     private static final int NCODES = accessCode(ByteCodes.lushrl) + 2;
   786     /** A mapping from symbols to their access numbers.
   787      */
   788     private Map<Symbol,Integer> accessNums;
   790     /** A mapping from symbols to an array of access symbols, indexed by
   791      *  access code.
   792      */
   793     private Map<Symbol,MethodSymbol[]> accessSyms;
   795     /** A mapping from (constructor) symbols to access constructor symbols.
   796      */
   797     private Map<Symbol,MethodSymbol> accessConstrs;
   799     /** A list of all class symbols used for access constructor tags.
   800      */
   801     private List<ClassSymbol> accessConstrTags;
   803     /** A queue for all accessed symbols.
   804      */
   805     private ListBuffer<Symbol> accessed;
   807     /** Map bytecode of binary operation to access code of corresponding
   808      *  assignment operation. This is always an even number.
   809      */
   810     private static int accessCode(int bytecode) {
   811         if (ByteCodes.iadd <= bytecode && bytecode <= ByteCodes.lxor)
   812             return (bytecode - iadd) * 2 + FIRSTASGOPcode;
   813         else if (bytecode == ByteCodes.string_add)
   814             return (ByteCodes.lxor + 1 - iadd) * 2 + FIRSTASGOPcode;
   815         else if (ByteCodes.ishll <= bytecode && bytecode <= ByteCodes.lushrl)
   816             return (bytecode - ishll + ByteCodes.lxor + 2 - iadd) * 2 + FIRSTASGOPcode;
   817         else
   818             return -1;
   819     }
   821     /** return access code for identifier,
   822      *  @param tree     The tree representing the identifier use.
   823      *  @param enclOp   The closest enclosing operation node of tree,
   824      *                  null if tree is not a subtree of an operation.
   825      */
   826     private static int accessCode(JCTree tree, JCTree enclOp) {
   827         if (enclOp == null)
   828             return DEREFcode;
   829         else if (enclOp.hasTag(ASSIGN) &&
   830                  tree == TreeInfo.skipParens(((JCAssign) enclOp).lhs))
   831             return ASSIGNcode;
   832         else if (enclOp.getTag().isIncOrDecUnaryOp() &&
   833                  tree == TreeInfo.skipParens(((JCUnary) enclOp).arg))
   834             return mapTagToUnaryOpCode(enclOp.getTag());
   835         else if (enclOp.getTag().isAssignop() &&
   836                  tree == TreeInfo.skipParens(((JCAssignOp) enclOp).lhs))
   837             return accessCode(((OperatorSymbol) ((JCAssignOp) enclOp).operator).opcode);
   838         else
   839             return DEREFcode;
   840     }
   842     /** Return binary operator that corresponds to given access code.
   843      */
   844     private OperatorSymbol binaryAccessOperator(int acode) {
   845         for (Scope.Entry e = syms.predefClass.members().elems;
   846              e != null;
   847              e = e.sibling) {
   848             if (e.sym instanceof OperatorSymbol) {
   849                 OperatorSymbol op = (OperatorSymbol)e.sym;
   850                 if (accessCode(op.opcode) == acode) return op;
   851             }
   852         }
   853         return null;
   854     }
   856     /** Return tree tag for assignment operation corresponding
   857      *  to given binary operator.
   858      */
   859     private static JCTree.Tag treeTag(OperatorSymbol operator) {
   860         switch (operator.opcode) {
   861         case ByteCodes.ior: case ByteCodes.lor:
   862             return BITOR_ASG;
   863         case ByteCodes.ixor: case ByteCodes.lxor:
   864             return BITXOR_ASG;
   865         case ByteCodes.iand: case ByteCodes.land:
   866             return BITAND_ASG;
   867         case ByteCodes.ishl: case ByteCodes.lshl:
   868         case ByteCodes.ishll: case ByteCodes.lshll:
   869             return SL_ASG;
   870         case ByteCodes.ishr: case ByteCodes.lshr:
   871         case ByteCodes.ishrl: case ByteCodes.lshrl:
   872             return SR_ASG;
   873         case ByteCodes.iushr: case ByteCodes.lushr:
   874         case ByteCodes.iushrl: case ByteCodes.lushrl:
   875             return USR_ASG;
   876         case ByteCodes.iadd: case ByteCodes.ladd:
   877         case ByteCodes.fadd: case ByteCodes.dadd:
   878         case ByteCodes.string_add:
   879             return PLUS_ASG;
   880         case ByteCodes.isub: case ByteCodes.lsub:
   881         case ByteCodes.fsub: case ByteCodes.dsub:
   882             return MINUS_ASG;
   883         case ByteCodes.imul: case ByteCodes.lmul:
   884         case ByteCodes.fmul: case ByteCodes.dmul:
   885             return MUL_ASG;
   886         case ByteCodes.idiv: case ByteCodes.ldiv:
   887         case ByteCodes.fdiv: case ByteCodes.ddiv:
   888             return DIV_ASG;
   889         case ByteCodes.imod: case ByteCodes.lmod:
   890         case ByteCodes.fmod: case ByteCodes.dmod:
   891             return MOD_ASG;
   892         default:
   893             throw new AssertionError();
   894         }
   895     }
   897     /** The name of the access method with number `anum' and access code `acode'.
   898      */
   899     Name accessName(int anum, int acode) {
   900         return names.fromString(
   901             "access" + target.syntheticNameChar() + anum + acode / 10 + acode % 10);
   902     }
   904     /** Return access symbol for a private or protected symbol from an inner class.
   905      *  @param sym        The accessed private symbol.
   906      *  @param tree       The accessing tree.
   907      *  @param enclOp     The closest enclosing operation node of tree,
   908      *                    null if tree is not a subtree of an operation.
   909      *  @param protAccess Is access to a protected symbol in another
   910      *                    package?
   911      *  @param refSuper   Is access via a (qualified) C.super?
   912      */
   913     MethodSymbol accessSymbol(Symbol sym, JCTree tree, JCTree enclOp,
   914                               boolean protAccess, boolean refSuper) {
   915         ClassSymbol accOwner = refSuper && protAccess
   916             // For access via qualified super (T.super.x), place the
   917             // access symbol on T.
   918             ? (ClassSymbol)((JCFieldAccess) tree).selected.type.tsym
   919             // Otherwise pretend that the owner of an accessed
   920             // protected symbol is the enclosing class of the current
   921             // class which is a subclass of the symbol's owner.
   922             : accessClass(sym, protAccess, tree);
   924         Symbol vsym = sym;
   925         if (sym.owner != accOwner) {
   926             vsym = sym.clone(accOwner);
   927             actualSymbols.put(vsym, sym);
   928         }
   930         Integer anum              // The access number of the access method.
   931             = accessNums.get(vsym);
   932         if (anum == null) {
   933             anum = accessed.length();
   934             accessNums.put(vsym, anum);
   935             accessSyms.put(vsym, new MethodSymbol[NCODES]);
   936             accessed.append(vsym);
   937             // System.out.println("accessing " + vsym + " in " + vsym.location());
   938         }
   940         int acode;                // The access code of the access method.
   941         List<Type> argtypes;      // The argument types of the access method.
   942         Type restype;             // The result type of the access method.
   943         List<Type> thrown;        // The thrown exceptions of the access method.
   944         switch (vsym.kind) {
   945         case VAR:
   946             acode = accessCode(tree, enclOp);
   947             if (acode >= FIRSTASGOPcode) {
   948                 OperatorSymbol operator = binaryAccessOperator(acode);
   949                 if (operator.opcode == string_add)
   950                     argtypes = List.of(syms.objectType);
   951                 else
   952                     argtypes = operator.type.getParameterTypes().tail;
   953             } else if (acode == ASSIGNcode)
   954                 argtypes = List.of(vsym.erasure(types));
   955             else
   956                 argtypes = List.nil();
   957             restype = vsym.erasure(types);
   958             thrown = List.nil();
   959             break;
   960         case MTH:
   961             acode = DEREFcode;
   962             argtypes = vsym.erasure(types).getParameterTypes();
   963             restype = vsym.erasure(types).getReturnType();
   964             thrown = vsym.type.getThrownTypes();
   965             break;
   966         default:
   967             throw new AssertionError();
   968         }
   970         // For references via qualified super, increment acode by one,
   971         // making it odd.
   972         if (protAccess && refSuper) acode++;
   974         // Instance access methods get instance as first parameter.
   975         // For protected symbols this needs to be the instance as a member
   976         // of the type containing the accessed symbol, not the class
   977         // containing the access method.
   978         if ((vsym.flags() & STATIC) == 0) {
   979             argtypes = argtypes.prepend(vsym.owner.erasure(types));
   980         }
   981         MethodSymbol[] accessors = accessSyms.get(vsym);
   982         MethodSymbol accessor = accessors[acode];
   983         if (accessor == null) {
   984             accessor = new MethodSymbol(
   985                 STATIC | SYNTHETIC,
   986                 accessName(anum.intValue(), acode),
   987                 new MethodType(argtypes, restype, thrown, syms.methodClass),
   988                 accOwner);
   989             enterSynthetic(tree.pos(), accessor, accOwner.members());
   990             accessors[acode] = accessor;
   991         }
   992         return accessor;
   993     }
   995     /** The qualifier to be used for accessing a symbol in an outer class.
   996      *  This is either C.sym or C.this.sym, depending on whether or not
   997      *  sym is static.
   998      *  @param sym   The accessed symbol.
   999      */
  1000     JCExpression accessBase(DiagnosticPosition pos, Symbol sym) {
  1001         return (sym.flags() & STATIC) != 0
  1002             ? access(make.at(pos.getStartPosition()).QualIdent(sym.owner))
  1003             : makeOwnerThis(pos, sym, true);
  1006     /** Do we need an access method to reference private symbol?
  1007      */
  1008     boolean needsPrivateAccess(Symbol sym) {
  1009         if ((sym.flags() & PRIVATE) == 0 || sym.owner == currentClass) {
  1010             return false;
  1011         } else if (sym.name == names.init && (sym.owner.owner.kind & (VAR | MTH)) != 0) {
  1012             // private constructor in local class: relax protection
  1013             sym.flags_field &= ~PRIVATE;
  1014             return false;
  1015         } else {
  1016             return true;
  1020     /** Do we need an access method to reference symbol in other package?
  1021      */
  1022     boolean needsProtectedAccess(Symbol sym, JCTree tree) {
  1023         if ((sym.flags() & PROTECTED) == 0 ||
  1024             sym.owner.owner == currentClass.owner || // fast special case
  1025             sym.packge() == currentClass.packge())
  1026             return false;
  1027         if (!currentClass.isSubClass(sym.owner, types))
  1028             return true;
  1029         if ((sym.flags() & STATIC) != 0 ||
  1030             !tree.hasTag(SELECT) ||
  1031             TreeInfo.name(((JCFieldAccess) tree).selected) == names._super)
  1032             return false;
  1033         return !((JCFieldAccess) tree).selected.type.tsym.isSubClass(currentClass, types);
  1036     /** The class in which an access method for given symbol goes.
  1037      *  @param sym        The access symbol
  1038      *  @param protAccess Is access to a protected symbol in another
  1039      *                    package?
  1040      */
  1041     ClassSymbol accessClass(Symbol sym, boolean protAccess, JCTree tree) {
  1042         if (protAccess) {
  1043             Symbol qualifier = null;
  1044             ClassSymbol c = currentClass;
  1045             if (tree.hasTag(SELECT) && (sym.flags() & STATIC) == 0) {
  1046                 qualifier = ((JCFieldAccess) tree).selected.type.tsym;
  1047                 while (!qualifier.isSubClass(c, types)) {
  1048                     c = c.owner.enclClass();
  1050                 return c;
  1051             } else {
  1052                 while (!c.isSubClass(sym.owner, types)) {
  1053                     c = c.owner.enclClass();
  1056             return c;
  1057         } else {
  1058             // the symbol is private
  1059             return sym.owner.enclClass();
  1063     private void addPrunedInfo(JCTree tree) {
  1064         List<JCTree> infoList = prunedTree.get(currentClass);
  1065         infoList = (infoList == null) ? List.of(tree) : infoList.prepend(tree);
  1066         prunedTree.put(currentClass, infoList);
  1069     /** Ensure that identifier is accessible, return tree accessing the identifier.
  1070      *  @param sym      The accessed symbol.
  1071      *  @param tree     The tree referring to the symbol.
  1072      *  @param enclOp   The closest enclosing operation node of tree,
  1073      *                  null if tree is not a subtree of an operation.
  1074      *  @param refSuper Is access via a (qualified) C.super?
  1075      */
  1076     JCExpression access(Symbol sym, JCExpression tree, JCExpression enclOp, boolean refSuper) {
  1077         // Access a free variable via its proxy, or its proxy's proxy
  1078         while (sym.kind == VAR && sym.owner.kind == MTH &&
  1079             sym.owner.enclClass() != currentClass) {
  1080             // A constant is replaced by its constant value.
  1081             Object cv = ((VarSymbol)sym).getConstValue();
  1082             if (cv != null) {
  1083                 make.at(tree.pos);
  1084                 return makeLit(sym.type, cv);
  1086             // Otherwise replace the variable by its proxy.
  1087             sym = proxies.lookup(proxyName(sym.name)).sym;
  1088             Assert.check(sym != null && (sym.flags_field & FINAL) != 0);
  1089             tree = make.at(tree.pos).Ident(sym);
  1091         JCExpression base = (tree.hasTag(SELECT)) ? ((JCFieldAccess) tree).selected : null;
  1092         switch (sym.kind) {
  1093         case TYP:
  1094             if (sym.owner.kind != PCK) {
  1095                 // Convert type idents to
  1096                 // <flat name> or <package name> . <flat name>
  1097                 Name flatname = Convert.shortName(sym.flatName());
  1098                 while (base != null &&
  1099                        TreeInfo.symbol(base) != null &&
  1100                        TreeInfo.symbol(base).kind != PCK) {
  1101                     base = (base.hasTag(SELECT))
  1102                         ? ((JCFieldAccess) base).selected
  1103                         : null;
  1105                 if (tree.hasTag(IDENT)) {
  1106                     ((JCIdent) tree).name = flatname;
  1107                 } else if (base == null) {
  1108                     tree = make.at(tree.pos).Ident(sym);
  1109                     ((JCIdent) tree).name = flatname;
  1110                 } else {
  1111                     ((JCFieldAccess) tree).selected = base;
  1112                     ((JCFieldAccess) tree).name = flatname;
  1115             break;
  1116         case MTH: case VAR:
  1117             if (sym.owner.kind == TYP) {
  1119                 // Access methods are required for
  1120                 //  - private members,
  1121                 //  - protected members in a superclass of an
  1122                 //    enclosing class contained in another package.
  1123                 //  - all non-private members accessed via a qualified super.
  1124                 boolean protAccess = refSuper && !needsPrivateAccess(sym)
  1125                     || needsProtectedAccess(sym, tree);
  1126                 boolean accReq = protAccess || needsPrivateAccess(sym);
  1128                 // A base has to be supplied for
  1129                 //  - simple identifiers accessing variables in outer classes.
  1130                 boolean baseReq =
  1131                     base == null &&
  1132                     sym.owner != syms.predefClass &&
  1133                     !sym.isMemberOf(currentClass, types);
  1135                 if (accReq || baseReq) {
  1136                     make.at(tree.pos);
  1138                     // Constants are replaced by their constant value.
  1139                     if (sym.kind == VAR) {
  1140                         Object cv = ((VarSymbol)sym).getConstValue();
  1141                         if (cv != null) {
  1142                             addPrunedInfo(tree);
  1143                             return makeLit(sym.type, cv);
  1147                     // Private variables and methods are replaced by calls
  1148                     // to their access methods.
  1149                     if (accReq) {
  1150                         List<JCExpression> args = List.nil();
  1151                         if ((sym.flags() & STATIC) == 0) {
  1152                             // Instance access methods get instance
  1153                             // as first parameter.
  1154                             if (base == null)
  1155                                 base = makeOwnerThis(tree.pos(), sym, true);
  1156                             args = args.prepend(base);
  1157                             base = null;   // so we don't duplicate code
  1159                         Symbol access = accessSymbol(sym, tree,
  1160                                                      enclOp, protAccess,
  1161                                                      refSuper);
  1162                         JCExpression receiver = make.Select(
  1163                             base != null ? base : make.QualIdent(access.owner),
  1164                             access);
  1165                         return make.App(receiver, args);
  1167                     // Other accesses to members of outer classes get a
  1168                     // qualifier.
  1169                     } else if (baseReq) {
  1170                         return make.at(tree.pos).Select(
  1171                             accessBase(tree.pos(), sym), sym).setType(tree.type);
  1176         return tree;
  1179     /** Ensure that identifier is accessible, return tree accessing the identifier.
  1180      *  @param tree     The identifier tree.
  1181      */
  1182     JCExpression access(JCExpression tree) {
  1183         Symbol sym = TreeInfo.symbol(tree);
  1184         return sym == null ? tree : access(sym, tree, null, false);
  1187     /** Return access constructor for a private constructor,
  1188      *  or the constructor itself, if no access constructor is needed.
  1189      *  @param pos       The position to report diagnostics, if any.
  1190      *  @param constr    The private constructor.
  1191      */
  1192     Symbol accessConstructor(DiagnosticPosition pos, Symbol constr) {
  1193         if (needsPrivateAccess(constr)) {
  1194             ClassSymbol accOwner = constr.owner.enclClass();
  1195             MethodSymbol aconstr = accessConstrs.get(constr);
  1196             if (aconstr == null) {
  1197                 List<Type> argtypes = constr.type.getParameterTypes();
  1198                 if ((accOwner.flags_field & ENUM) != 0)
  1199                     argtypes = argtypes
  1200                         .prepend(syms.intType)
  1201                         .prepend(syms.stringType);
  1202                 aconstr = new MethodSymbol(
  1203                     SYNTHETIC,
  1204                     names.init,
  1205                     new MethodType(
  1206                         argtypes.append(
  1207                             accessConstructorTag().erasure(types)),
  1208                         constr.type.getReturnType(),
  1209                         constr.type.getThrownTypes(),
  1210                         syms.methodClass),
  1211                     accOwner);
  1212                 enterSynthetic(pos, aconstr, accOwner.members());
  1213                 accessConstrs.put(constr, aconstr);
  1214                 accessed.append(constr);
  1216             return aconstr;
  1217         } else {
  1218             return constr;
  1222     /** Return an anonymous class nested in this toplevel class.
  1223      */
  1224     ClassSymbol accessConstructorTag() {
  1225         ClassSymbol topClass = currentClass.outermostClass();
  1226         Name flatname = names.fromString("" + topClass.getQualifiedName() +
  1227                                          target.syntheticNameChar() +
  1228                                          "1");
  1229         ClassSymbol ctag = chk.compiled.get(flatname);
  1230         if (ctag == null)
  1231             ctag = makeEmptyClass(STATIC | SYNTHETIC, topClass).sym;
  1232         // keep a record of all tags, to verify that all are generated as required
  1233         accessConstrTags = accessConstrTags.prepend(ctag);
  1234         return ctag;
  1237     /** Add all required access methods for a private symbol to enclosing class.
  1238      *  @param sym       The symbol.
  1239      */
  1240     void makeAccessible(Symbol sym) {
  1241         JCClassDecl cdef = classDef(sym.owner.enclClass());
  1242         if (cdef == null) Assert.error("class def not found: " + sym + " in " + sym.owner);
  1243         if (sym.name == names.init) {
  1244             cdef.defs = cdef.defs.prepend(
  1245                 accessConstructorDef(cdef.pos, sym, accessConstrs.get(sym)));
  1246         } else {
  1247             MethodSymbol[] accessors = accessSyms.get(sym);
  1248             for (int i = 0; i < NCODES; i++) {
  1249                 if (accessors[i] != null)
  1250                     cdef.defs = cdef.defs.prepend(
  1251                         accessDef(cdef.pos, sym, accessors[i], i));
  1256     /** Maps unary operator integer codes to JCTree.Tag objects
  1257      *  @param unaryOpCode the unary operator code
  1258      */
  1259     private static Tag mapUnaryOpCodeToTag(int unaryOpCode){
  1260         switch (unaryOpCode){
  1261             case PREINCcode:
  1262                 return PREINC;
  1263             case PREDECcode:
  1264                 return PREDEC;
  1265             case POSTINCcode:
  1266                 return POSTINC;
  1267             case POSTDECcode:
  1268                 return POSTDEC;
  1269             default:
  1270                 return NO_TAG;
  1274     /** Maps JCTree.Tag objects to unary operator integer codes
  1275      *  @param tag the JCTree.Tag
  1276      */
  1277     private static int mapTagToUnaryOpCode(Tag tag){
  1278         switch (tag){
  1279             case PREINC:
  1280                 return PREINCcode;
  1281             case PREDEC:
  1282                 return PREDECcode;
  1283             case POSTINC:
  1284                 return POSTINCcode;
  1285             case POSTDEC:
  1286                 return POSTDECcode;
  1287             default:
  1288                 return -1;
  1292     /** Construct definition of an access method.
  1293      *  @param pos        The source code position of the definition.
  1294      *  @param vsym       The private or protected symbol.
  1295      *  @param accessor   The access method for the symbol.
  1296      *  @param acode      The access code.
  1297      */
  1298     JCTree accessDef(int pos, Symbol vsym, MethodSymbol accessor, int acode) {
  1299 //      System.err.println("access " + vsym + " with " + accessor);//DEBUG
  1300         currentClass = vsym.owner.enclClass();
  1301         make.at(pos);
  1302         JCMethodDecl md = make.MethodDef(accessor, null);
  1304         // Find actual symbol
  1305         Symbol sym = actualSymbols.get(vsym);
  1306         if (sym == null) sym = vsym;
  1308         JCExpression ref;           // The tree referencing the private symbol.
  1309         List<JCExpression> args;    // Any additional arguments to be passed along.
  1310         if ((sym.flags() & STATIC) != 0) {
  1311             ref = make.Ident(sym);
  1312             args = make.Idents(md.params);
  1313         } else {
  1314             ref = make.Select(make.Ident(md.params.head), sym);
  1315             args = make.Idents(md.params.tail);
  1317         JCStatement stat;          // The statement accessing the private symbol.
  1318         if (sym.kind == VAR) {
  1319             // Normalize out all odd access codes by taking floor modulo 2:
  1320             int acode1 = acode - (acode & 1);
  1322             JCExpression expr;      // The access method's return value.
  1323             switch (acode1) {
  1324             case DEREFcode:
  1325                 expr = ref;
  1326                 break;
  1327             case ASSIGNcode:
  1328                 expr = make.Assign(ref, args.head);
  1329                 break;
  1330             case PREINCcode: case POSTINCcode: case PREDECcode: case POSTDECcode:
  1331                 expr = makeUnary(mapUnaryOpCodeToTag(acode1), ref);
  1332                 break;
  1333             default:
  1334                 expr = make.Assignop(
  1335                     treeTag(binaryAccessOperator(acode1)), ref, args.head);
  1336                 ((JCAssignOp) expr).operator = binaryAccessOperator(acode1);
  1338             stat = make.Return(expr.setType(sym.type));
  1339         } else {
  1340             stat = make.Call(make.App(ref, args));
  1342         md.body = make.Block(0, List.of(stat));
  1344         // Make sure all parameters, result types and thrown exceptions
  1345         // are accessible.
  1346         for (List<JCVariableDecl> l = md.params; l.nonEmpty(); l = l.tail)
  1347             l.head.vartype = access(l.head.vartype);
  1348         md.restype = access(md.restype);
  1349         for (List<JCExpression> l = md.thrown; l.nonEmpty(); l = l.tail)
  1350             l.head = access(l.head);
  1352         return md;
  1355     /** Construct definition of an access constructor.
  1356      *  @param pos        The source code position of the definition.
  1357      *  @param constr     The private constructor.
  1358      *  @param accessor   The access method for the constructor.
  1359      */
  1360     JCTree accessConstructorDef(int pos, Symbol constr, MethodSymbol accessor) {
  1361         make.at(pos);
  1362         JCMethodDecl md = make.MethodDef(accessor,
  1363                                       accessor.externalType(types),
  1364                                       null);
  1365         JCIdent callee = make.Ident(names._this);
  1366         callee.sym = constr;
  1367         callee.type = constr.type;
  1368         md.body =
  1369             make.Block(0, List.<JCStatement>of(
  1370                 make.Call(
  1371                     make.App(
  1372                         callee,
  1373                         make.Idents(md.params.reverse().tail.reverse())))));
  1374         return md;
  1377 /**************************************************************************
  1378  * Free variables proxies and this$n
  1379  *************************************************************************/
  1381     /** A scope containing all free variable proxies for currently translated
  1382      *  class, as well as its this$n symbol (if needed).
  1383      *  Proxy scopes are nested in the same way classes are.
  1384      *  Inside a constructor, proxies and any this$n symbol are duplicated
  1385      *  in an additional innermost scope, where they represent the constructor
  1386      *  parameters.
  1387      */
  1388     Scope proxies;
  1390     /** A scope containing all unnamed resource variables/saved
  1391      *  exception variables for translated TWR blocks
  1392      */
  1393     Scope twrVars;
  1395     /** A stack containing the this$n field of the currently translated
  1396      *  classes (if needed) in innermost first order.
  1397      *  Inside a constructor, proxies and any this$n symbol are duplicated
  1398      *  in an additional innermost scope, where they represent the constructor
  1399      *  parameters.
  1400      */
  1401     List<VarSymbol> outerThisStack;
  1403     /** The name of a free variable proxy.
  1404      */
  1405     Name proxyName(Name name) {
  1406         return names.fromString("val" + target.syntheticNameChar() + name);
  1409     /** Proxy definitions for all free variables in given list, in reverse order.
  1410      *  @param pos        The source code position of the definition.
  1411      *  @param freevars   The free variables.
  1412      *  @param owner      The class in which the definitions go.
  1413      */
  1414     List<JCVariableDecl> freevarDefs(int pos, List<VarSymbol> freevars, Symbol owner) {
  1415         long flags = FINAL | SYNTHETIC;
  1416         if (owner.kind == TYP &&
  1417             target.usePrivateSyntheticFields())
  1418             flags |= PRIVATE;
  1419         List<JCVariableDecl> defs = List.nil();
  1420         for (List<VarSymbol> l = freevars; l.nonEmpty(); l = l.tail) {
  1421             VarSymbol v = l.head;
  1422             VarSymbol proxy = new VarSymbol(
  1423                 flags, proxyName(v.name), v.erasure(types), owner);
  1424             proxies.enter(proxy);
  1425             JCVariableDecl vd = make.at(pos).VarDef(proxy, null);
  1426             vd.vartype = access(vd.vartype);
  1427             defs = defs.prepend(vd);
  1429         return defs;
  1432     /** The name of a this$n field
  1433      *  @param type   The class referenced by the this$n field
  1434      */
  1435     Name outerThisName(Type type, Symbol owner) {
  1436         Type t = type.getEnclosingType();
  1437         int nestingLevel = 0;
  1438         while (t.hasTag(CLASS)) {
  1439             t = t.getEnclosingType();
  1440             nestingLevel++;
  1442         Name result = names.fromString("this" + target.syntheticNameChar() + nestingLevel);
  1443         while (owner.kind == TYP && ((ClassSymbol)owner).members().lookup(result).scope != null)
  1444             result = names.fromString(result.toString() + target.syntheticNameChar());
  1445         return result;
  1448     /** Definition for this$n field.
  1449      *  @param pos        The source code position of the definition.
  1450      *  @param owner      The class in which the definition goes.
  1451      */
  1452     JCVariableDecl outerThisDef(int pos, Symbol owner) {
  1453         long flags = FINAL | SYNTHETIC;
  1454         if (owner.kind == TYP &&
  1455             target.usePrivateSyntheticFields())
  1456             flags |= PRIVATE;
  1457         Type target = types.erasure(owner.enclClass().type.getEnclosingType());
  1458         VarSymbol outerThis = new VarSymbol(
  1459             flags, outerThisName(target, owner), target, owner);
  1460         outerThisStack = outerThisStack.prepend(outerThis);
  1461         JCVariableDecl vd = make.at(pos).VarDef(outerThis, null);
  1462         vd.vartype = access(vd.vartype);
  1463         return vd;
  1466     /** Return a list of trees that load the free variables in given list,
  1467      *  in reverse order.
  1468      *  @param pos          The source code position to be used for the trees.
  1469      *  @param freevars     The list of free variables.
  1470      */
  1471     List<JCExpression> loadFreevars(DiagnosticPosition pos, List<VarSymbol> freevars) {
  1472         List<JCExpression> args = List.nil();
  1473         for (List<VarSymbol> l = freevars; l.nonEmpty(); l = l.tail)
  1474             args = args.prepend(loadFreevar(pos, l.head));
  1475         return args;
  1477 //where
  1478         JCExpression loadFreevar(DiagnosticPosition pos, VarSymbol v) {
  1479             return access(v, make.at(pos).Ident(v), null, false);
  1482     /** Construct a tree simulating the expression {@code C.this}.
  1483      *  @param pos           The source code position to be used for the tree.
  1484      *  @param c             The qualifier class.
  1485      */
  1486     JCExpression makeThis(DiagnosticPosition pos, TypeSymbol c) {
  1487         if (currentClass == c) {
  1488             // in this case, `this' works fine
  1489             return make.at(pos).This(c.erasure(types));
  1490         } else {
  1491             // need to go via this$n
  1492             return makeOuterThis(pos, c);
  1496     /**
  1497      * Optionally replace a try statement with the desugaring of a
  1498      * try-with-resources statement.  The canonical desugaring of
  1500      * try ResourceSpecification
  1501      *   Block
  1503      * is
  1505      * {
  1506      *   final VariableModifiers_minus_final R #resource = Expression;
  1507      *   Throwable #primaryException = null;
  1509      *   try ResourceSpecificationtail
  1510      *     Block
  1511      *   catch (Throwable #t) {
  1512      *     #primaryException = t;
  1513      *     throw #t;
  1514      *   } finally {
  1515      *     if (#resource != null) {
  1516      *       if (#primaryException != null) {
  1517      *         try {
  1518      *           #resource.close();
  1519      *         } catch(Throwable #suppressedException) {
  1520      *           #primaryException.addSuppressed(#suppressedException);
  1521      *         }
  1522      *       } else {
  1523      *         #resource.close();
  1524      *       }
  1525      *     }
  1526      *   }
  1528      * @param tree  The try statement to inspect.
  1529      * @return A a desugared try-with-resources tree, or the original
  1530      * try block if there are no resources to manage.
  1531      */
  1532     JCTree makeTwrTry(JCTry tree) {
  1533         make_at(tree.pos());
  1534         twrVars = twrVars.dup();
  1535         JCBlock twrBlock = makeTwrBlock(tree.resources, tree.body, 0);
  1536         if (tree.catchers.isEmpty() && tree.finalizer == null)
  1537             result = translate(twrBlock);
  1538         else
  1539             result = translate(make.Try(twrBlock, tree.catchers, tree.finalizer));
  1540         twrVars = twrVars.leave();
  1541         return result;
  1544     private JCBlock makeTwrBlock(List<JCTree> resources, JCBlock block, int depth) {
  1545         if (resources.isEmpty())
  1546             return block;
  1548         // Add resource declaration or expression to block statements
  1549         ListBuffer<JCStatement> stats = new ListBuffer<JCStatement>();
  1550         JCTree resource = resources.head;
  1551         JCExpression expr = null;
  1552         if (resource instanceof JCVariableDecl) {
  1553             JCVariableDecl var = (JCVariableDecl) resource;
  1554             expr = make.Ident(var.sym).setType(resource.type);
  1555             stats.add(var);
  1556         } else {
  1557             Assert.check(resource instanceof JCExpression);
  1558             VarSymbol syntheticTwrVar =
  1559             new VarSymbol(SYNTHETIC | FINAL,
  1560                           makeSyntheticName(names.fromString("twrVar" +
  1561                                            depth), twrVars),
  1562                           (resource.type.hasTag(BOT)) ?
  1563                           syms.autoCloseableType : resource.type,
  1564                           currentMethodSym);
  1565             twrVars.enter(syntheticTwrVar);
  1566             JCVariableDecl syntheticTwrVarDecl =
  1567                 make.VarDef(syntheticTwrVar, (JCExpression)resource);
  1568             expr = (JCExpression)make.Ident(syntheticTwrVar);
  1569             stats.add(syntheticTwrVarDecl);
  1572         // Add primaryException declaration
  1573         VarSymbol primaryException =
  1574             new VarSymbol(SYNTHETIC,
  1575                           makeSyntheticName(names.fromString("primaryException" +
  1576                           depth), twrVars),
  1577                           syms.throwableType,
  1578                           currentMethodSym);
  1579         twrVars.enter(primaryException);
  1580         JCVariableDecl primaryExceptionTreeDecl = make.VarDef(primaryException, makeNull());
  1581         stats.add(primaryExceptionTreeDecl);
  1583         // Create catch clause that saves exception and then rethrows it
  1584         VarSymbol param =
  1585             new VarSymbol(FINAL|SYNTHETIC,
  1586                           names.fromString("t" +
  1587                                            target.syntheticNameChar()),
  1588                           syms.throwableType,
  1589                           currentMethodSym);
  1590         JCVariableDecl paramTree = make.VarDef(param, null);
  1591         JCStatement assign = make.Assignment(primaryException, make.Ident(param));
  1592         JCStatement rethrowStat = make.Throw(make.Ident(param));
  1593         JCBlock catchBlock = make.Block(0L, List.<JCStatement>of(assign, rethrowStat));
  1594         JCCatch catchClause = make.Catch(paramTree, catchBlock);
  1596         int oldPos = make.pos;
  1597         make.at(TreeInfo.endPos(block));
  1598         JCBlock finallyClause = makeTwrFinallyClause(primaryException, expr);
  1599         make.at(oldPos);
  1600         JCTry outerTry = make.Try(makeTwrBlock(resources.tail, block, depth + 1),
  1601                                   List.<JCCatch>of(catchClause),
  1602                                   finallyClause);
  1603         stats.add(outerTry);
  1604         return make.Block(0L, stats.toList());
  1607     private JCBlock makeTwrFinallyClause(Symbol primaryException, JCExpression resource) {
  1608         // primaryException.addSuppressed(catchException);
  1609         VarSymbol catchException =
  1610             new VarSymbol(0, make.paramName(2),
  1611                           syms.throwableType,
  1612                           currentMethodSym);
  1613         JCStatement addSuppressionStatement =
  1614             make.Exec(makeCall(make.Ident(primaryException),
  1615                                names.addSuppressed,
  1616                                List.<JCExpression>of(make.Ident(catchException))));
  1618         // try { resource.close(); } catch (e) { primaryException.addSuppressed(e); }
  1619         JCBlock tryBlock =
  1620             make.Block(0L, List.<JCStatement>of(makeResourceCloseInvocation(resource)));
  1621         JCVariableDecl catchExceptionDecl = make.VarDef(catchException, null);
  1622         JCBlock catchBlock = make.Block(0L, List.<JCStatement>of(addSuppressionStatement));
  1623         List<JCCatch> catchClauses = List.<JCCatch>of(make.Catch(catchExceptionDecl, catchBlock));
  1624         JCTry tryTree = make.Try(tryBlock, catchClauses, null);
  1626         // if (primaryException != null) {try...} else resourceClose;
  1627         JCIf closeIfStatement = make.If(makeNonNullCheck(make.Ident(primaryException)),
  1628                                         tryTree,
  1629                                         makeResourceCloseInvocation(resource));
  1631         // if (#resource != null) { if (primaryException ...  }
  1632         return make.Block(0L,
  1633                           List.<JCStatement>of(make.If(makeNonNullCheck(resource),
  1634                                                        closeIfStatement,
  1635                                                        null)));
  1638     private JCStatement makeResourceCloseInvocation(JCExpression resource) {
  1639         // convert to AutoCloseable if needed
  1640         if (types.asSuper(resource.type, syms.autoCloseableType.tsym) == null) {
  1641             resource = (JCExpression) convert(resource, syms.autoCloseableType);
  1644         // create resource.close() method invocation
  1645         JCExpression resourceClose = makeCall(resource,
  1646                                               names.close,
  1647                                               List.<JCExpression>nil());
  1648         return make.Exec(resourceClose);
  1651     private JCExpression makeNonNullCheck(JCExpression expression) {
  1652         return makeBinary(NE, expression, makeNull());
  1655     /** Construct a tree that represents the outer instance
  1656      *  {@code C.this}. Never pick the current `this'.
  1657      *  @param pos           The source code position to be used for the tree.
  1658      *  @param c             The qualifier class.
  1659      */
  1660     JCExpression makeOuterThis(DiagnosticPosition pos, TypeSymbol c) {
  1661         List<VarSymbol> ots = outerThisStack;
  1662         if (ots.isEmpty()) {
  1663             log.error(pos, "no.encl.instance.of.type.in.scope", c);
  1664             Assert.error();
  1665             return makeNull();
  1667         VarSymbol ot = ots.head;
  1668         JCExpression tree = access(make.at(pos).Ident(ot));
  1669         TypeSymbol otc = ot.type.tsym;
  1670         while (otc != c) {
  1671             do {
  1672                 ots = ots.tail;
  1673                 if (ots.isEmpty()) {
  1674                     log.error(pos,
  1675                               "no.encl.instance.of.type.in.scope",
  1676                               c);
  1677                     Assert.error(); // should have been caught in Attr
  1678                     return tree;
  1680                 ot = ots.head;
  1681             } while (ot.owner != otc);
  1682             if (otc.owner.kind != PCK && !otc.hasOuterInstance()) {
  1683                 chk.earlyRefError(pos, c);
  1684                 Assert.error(); // should have been caught in Attr
  1685                 return makeNull();
  1687             tree = access(make.at(pos).Select(tree, ot));
  1688             otc = ot.type.tsym;
  1690         return tree;
  1693     /** Construct a tree that represents the closest outer instance
  1694      *  {@code C.this} such that the given symbol is a member of C.
  1695      *  @param pos           The source code position to be used for the tree.
  1696      *  @param sym           The accessed symbol.
  1697      *  @param preciseMatch  should we accept a type that is a subtype of
  1698      *                       sym's owner, even if it doesn't contain sym
  1699      *                       due to hiding, overriding, or non-inheritance
  1700      *                       due to protection?
  1701      */
  1702     JCExpression makeOwnerThis(DiagnosticPosition pos, Symbol sym, boolean preciseMatch) {
  1703         Symbol c = sym.owner;
  1704         if (preciseMatch ? sym.isMemberOf(currentClass, types)
  1705                          : currentClass.isSubClass(sym.owner, types)) {
  1706             // in this case, `this' works fine
  1707             return make.at(pos).This(c.erasure(types));
  1708         } else {
  1709             // need to go via this$n
  1710             return makeOwnerThisN(pos, sym, preciseMatch);
  1714     /**
  1715      * Similar to makeOwnerThis but will never pick "this".
  1716      */
  1717     JCExpression makeOwnerThisN(DiagnosticPosition pos, Symbol sym, boolean preciseMatch) {
  1718         Symbol c = sym.owner;
  1719         List<VarSymbol> ots = outerThisStack;
  1720         if (ots.isEmpty()) {
  1721             log.error(pos, "no.encl.instance.of.type.in.scope", c);
  1722             Assert.error();
  1723             return makeNull();
  1725         VarSymbol ot = ots.head;
  1726         JCExpression tree = access(make.at(pos).Ident(ot));
  1727         TypeSymbol otc = ot.type.tsym;
  1728         while (!(preciseMatch ? sym.isMemberOf(otc, types) : otc.isSubClass(sym.owner, types))) {
  1729             do {
  1730                 ots = ots.tail;
  1731                 if (ots.isEmpty()) {
  1732                     log.error(pos,
  1733                         "no.encl.instance.of.type.in.scope",
  1734                         c);
  1735                     Assert.error();
  1736                     return tree;
  1738                 ot = ots.head;
  1739             } while (ot.owner != otc);
  1740             tree = access(make.at(pos).Select(tree, ot));
  1741             otc = ot.type.tsym;
  1743         return tree;
  1746     /** Return tree simulating the assignment {@code this.name = name}, where
  1747      *  name is the name of a free variable.
  1748      */
  1749     JCStatement initField(int pos, Name name) {
  1750         Scope.Entry e = proxies.lookup(name);
  1751         Symbol rhs = e.sym;
  1752         Assert.check(rhs.owner.kind == MTH);
  1753         Symbol lhs = e.next().sym;
  1754         Assert.check(rhs.owner.owner == lhs.owner);
  1755         make.at(pos);
  1756         return
  1757             make.Exec(
  1758                 make.Assign(
  1759                     make.Select(make.This(lhs.owner.erasure(types)), lhs),
  1760                     make.Ident(rhs)).setType(lhs.erasure(types)));
  1763     /** Return tree simulating the assignment {@code this.this$n = this$n}.
  1764      */
  1765     JCStatement initOuterThis(int pos) {
  1766         VarSymbol rhs = outerThisStack.head;
  1767         Assert.check(rhs.owner.kind == MTH);
  1768         VarSymbol lhs = outerThisStack.tail.head;
  1769         Assert.check(rhs.owner.owner == lhs.owner);
  1770         make.at(pos);
  1771         return
  1772             make.Exec(
  1773                 make.Assign(
  1774                     make.Select(make.This(lhs.owner.erasure(types)), lhs),
  1775                     make.Ident(rhs)).setType(lhs.erasure(types)));
  1778 /**************************************************************************
  1779  * Code for .class
  1780  *************************************************************************/
  1782     /** Return the symbol of a class to contain a cache of
  1783      *  compiler-generated statics such as class$ and the
  1784      *  $assertionsDisabled flag.  We create an anonymous nested class
  1785      *  (unless one already exists) and return its symbol.  However,
  1786      *  for backward compatibility in 1.4 and earlier we use the
  1787      *  top-level class itself.
  1788      */
  1789     private ClassSymbol outerCacheClass() {
  1790         ClassSymbol clazz = outermostClassDef.sym;
  1791         if ((clazz.flags() & INTERFACE) == 0 &&
  1792             !target.useInnerCacheClass()) return clazz;
  1793         Scope s = clazz.members();
  1794         for (Scope.Entry e = s.elems; e != null; e = e.sibling)
  1795             if (e.sym.kind == TYP &&
  1796                 e.sym.name == names.empty &&
  1797                 (e.sym.flags() & INTERFACE) == 0) return (ClassSymbol) e.sym;
  1798         return makeEmptyClass(STATIC | SYNTHETIC, clazz).sym;
  1801     /** Return symbol for "class$" method. If there is no method definition
  1802      *  for class$, construct one as follows:
  1804      *    class class$(String x0) {
  1805      *      try {
  1806      *        return Class.forName(x0);
  1807      *      } catch (ClassNotFoundException x1) {
  1808      *        throw new NoClassDefFoundError(x1.getMessage());
  1809      *      }
  1810      *    }
  1811      */
  1812     private MethodSymbol classDollarSym(DiagnosticPosition pos) {
  1813         ClassSymbol outerCacheClass = outerCacheClass();
  1814         MethodSymbol classDollarSym =
  1815             (MethodSymbol)lookupSynthetic(classDollar,
  1816                                           outerCacheClass.members());
  1817         if (classDollarSym == null) {
  1818             classDollarSym = new MethodSymbol(
  1819                 STATIC | SYNTHETIC,
  1820                 classDollar,
  1821                 new MethodType(
  1822                     List.of(syms.stringType),
  1823                     types.erasure(syms.classType),
  1824                     List.<Type>nil(),
  1825                     syms.methodClass),
  1826                 outerCacheClass);
  1827             enterSynthetic(pos, classDollarSym, outerCacheClass.members());
  1829             JCMethodDecl md = make.MethodDef(classDollarSym, null);
  1830             try {
  1831                 md.body = classDollarSymBody(pos, md);
  1832             } catch (CompletionFailure ex) {
  1833                 md.body = make.Block(0, List.<JCStatement>nil());
  1834                 chk.completionError(pos, ex);
  1836             JCClassDecl outerCacheClassDef = classDef(outerCacheClass);
  1837             outerCacheClassDef.defs = outerCacheClassDef.defs.prepend(md);
  1839         return classDollarSym;
  1842     /** Generate code for class$(String name). */
  1843     JCBlock classDollarSymBody(DiagnosticPosition pos, JCMethodDecl md) {
  1844         MethodSymbol classDollarSym = md.sym;
  1845         ClassSymbol outerCacheClass = (ClassSymbol)classDollarSym.owner;
  1847         JCBlock returnResult;
  1849         // in 1.4.2 and above, we use
  1850         // Class.forName(String name, boolean init, ClassLoader loader);
  1851         // which requires we cache the current loader in cl$
  1852         if (target.classLiteralsNoInit()) {
  1853             // clsym = "private static ClassLoader cl$"
  1854             VarSymbol clsym = new VarSymbol(STATIC|SYNTHETIC,
  1855                                             names.fromString("cl" + target.syntheticNameChar()),
  1856                                             syms.classLoaderType,
  1857                                             outerCacheClass);
  1858             enterSynthetic(pos, clsym, outerCacheClass.members());
  1860             // emit "private static ClassLoader cl$;"
  1861             JCVariableDecl cldef = make.VarDef(clsym, null);
  1862             JCClassDecl outerCacheClassDef = classDef(outerCacheClass);
  1863             outerCacheClassDef.defs = outerCacheClassDef.defs.prepend(cldef);
  1865             // newcache := "new cache$1[0]"
  1866             JCNewArray newcache = make.
  1867                 NewArray(make.Type(outerCacheClass.type),
  1868                          List.<JCExpression>of(make.Literal(INT, 0).setType(syms.intType)),
  1869                          null);
  1870             newcache.type = new ArrayType(types.erasure(outerCacheClass.type),
  1871                                           syms.arrayClass);
  1873             // forNameSym := java.lang.Class.forName(
  1874             //     String s,boolean init,ClassLoader loader)
  1875             Symbol forNameSym = lookupMethod(make_pos, names.forName,
  1876                                              types.erasure(syms.classType),
  1877                                              List.of(syms.stringType,
  1878                                                      syms.booleanType,
  1879                                                      syms.classLoaderType));
  1880             // clvalue := "(cl$ == null) ?
  1881             // $newcache.getClass().getComponentType().getClassLoader() : cl$"
  1882             JCExpression clvalue =
  1883                 make.Conditional(
  1884                     makeBinary(EQ, make.Ident(clsym), makeNull()),
  1885                     make.Assign(
  1886                         make.Ident(clsym),
  1887                         makeCall(
  1888                             makeCall(makeCall(newcache,
  1889                                               names.getClass,
  1890                                               List.<JCExpression>nil()),
  1891                                      names.getComponentType,
  1892                                      List.<JCExpression>nil()),
  1893                             names.getClassLoader,
  1894                             List.<JCExpression>nil())).setType(syms.classLoaderType),
  1895                     make.Ident(clsym)).setType(syms.classLoaderType);
  1897             // returnResult := "{ return Class.forName(param1, false, cl$); }"
  1898             List<JCExpression> args = List.of(make.Ident(md.params.head.sym),
  1899                                               makeLit(syms.booleanType, 0),
  1900                                               clvalue);
  1901             returnResult = make.
  1902                 Block(0, List.<JCStatement>of(make.
  1903                               Call(make. // return
  1904                                    App(make.
  1905                                        Ident(forNameSym), args))));
  1906         } else {
  1907             // forNameSym := java.lang.Class.forName(String s)
  1908             Symbol forNameSym = lookupMethod(make_pos,
  1909                                              names.forName,
  1910                                              types.erasure(syms.classType),
  1911                                              List.of(syms.stringType));
  1912             // returnResult := "{ return Class.forName(param1); }"
  1913             returnResult = make.
  1914                 Block(0, List.of(make.
  1915                           Call(make. // return
  1916                               App(make.
  1917                                   QualIdent(forNameSym),
  1918                                   List.<JCExpression>of(make.
  1919                                                         Ident(md.params.
  1920                                                               head.sym))))));
  1923         // catchParam := ClassNotFoundException e1
  1924         VarSymbol catchParam =
  1925             new VarSymbol(0, make.paramName(1),
  1926                           syms.classNotFoundExceptionType,
  1927                           classDollarSym);
  1929         JCStatement rethrow;
  1930         if (target.hasInitCause()) {
  1931             // rethrow = "throw new NoClassDefFoundError().initCause(e);
  1932             JCTree throwExpr =
  1933                 makeCall(makeNewClass(syms.noClassDefFoundErrorType,
  1934                                       List.<JCExpression>nil()),
  1935                          names.initCause,
  1936                          List.<JCExpression>of(make.Ident(catchParam)));
  1937             rethrow = make.Throw(throwExpr);
  1938         } else {
  1939             // getMessageSym := ClassNotFoundException.getMessage()
  1940             Symbol getMessageSym = lookupMethod(make_pos,
  1941                                                 names.getMessage,
  1942                                                 syms.classNotFoundExceptionType,
  1943                                                 List.<Type>nil());
  1944             // rethrow = "throw new NoClassDefFoundError(e.getMessage());"
  1945             rethrow = make.
  1946                 Throw(makeNewClass(syms.noClassDefFoundErrorType,
  1947                           List.<JCExpression>of(make.App(make.Select(make.Ident(catchParam),
  1948                                                                      getMessageSym),
  1949                                                          List.<JCExpression>nil()))));
  1952         // rethrowStmt := "( $rethrow )"
  1953         JCBlock rethrowStmt = make.Block(0, List.of(rethrow));
  1955         // catchBlock := "catch ($catchParam) $rethrowStmt"
  1956         JCCatch catchBlock = make.Catch(make.VarDef(catchParam, null),
  1957                                       rethrowStmt);
  1959         // tryCatch := "try $returnResult $catchBlock"
  1960         JCStatement tryCatch = make.Try(returnResult,
  1961                                         List.of(catchBlock), null);
  1963         return make.Block(0, List.of(tryCatch));
  1965     // where
  1966         /** Create an attributed tree of the form left.name(). */
  1967         private JCMethodInvocation makeCall(JCExpression left, Name name, List<JCExpression> args) {
  1968             Assert.checkNonNull(left.type);
  1969             Symbol funcsym = lookupMethod(make_pos, name, left.type,
  1970                                           TreeInfo.types(args));
  1971             return make.App(make.Select(left, funcsym), args);
  1974     /** The Name Of The variable to cache T.class values.
  1975      *  @param sig      The signature of type T.
  1976      */
  1977     private Name cacheName(String sig) {
  1978         StringBuilder buf = new StringBuilder();
  1979         if (sig.startsWith("[")) {
  1980             buf = buf.append("array");
  1981             while (sig.startsWith("[")) {
  1982                 buf = buf.append(target.syntheticNameChar());
  1983                 sig = sig.substring(1);
  1985             if (sig.startsWith("L")) {
  1986                 sig = sig.substring(0, sig.length() - 1);
  1988         } else {
  1989             buf = buf.append("class" + target.syntheticNameChar());
  1991         buf = buf.append(sig.replace('.', target.syntheticNameChar()));
  1992         return names.fromString(buf.toString());
  1995     /** The variable symbol that caches T.class values.
  1996      *  If none exists yet, create a definition.
  1997      *  @param sig      The signature of type T.
  1998      *  @param pos      The position to report diagnostics, if any.
  1999      */
  2000     private VarSymbol cacheSym(DiagnosticPosition pos, String sig) {
  2001         ClassSymbol outerCacheClass = outerCacheClass();
  2002         Name cname = cacheName(sig);
  2003         VarSymbol cacheSym =
  2004             (VarSymbol)lookupSynthetic(cname, outerCacheClass.members());
  2005         if (cacheSym == null) {
  2006             cacheSym = new VarSymbol(
  2007                 STATIC | SYNTHETIC, cname, types.erasure(syms.classType), outerCacheClass);
  2008             enterSynthetic(pos, cacheSym, outerCacheClass.members());
  2010             JCVariableDecl cacheDef = make.VarDef(cacheSym, null);
  2011             JCClassDecl outerCacheClassDef = classDef(outerCacheClass);
  2012             outerCacheClassDef.defs = outerCacheClassDef.defs.prepend(cacheDef);
  2014         return cacheSym;
  2017     /** The tree simulating a T.class expression.
  2018      *  @param clazz      The tree identifying type T.
  2019      */
  2020     private JCExpression classOf(JCTree clazz) {
  2021         return classOfType(clazz.type, clazz.pos());
  2024     private JCExpression classOfType(Type type, DiagnosticPosition pos) {
  2025         switch (type.getTag()) {
  2026         case BYTE: case SHORT: case CHAR: case INT: case LONG: case FLOAT:
  2027         case DOUBLE: case BOOLEAN: case VOID:
  2028             // replace with <BoxedClass>.TYPE
  2029             ClassSymbol c = types.boxedClass(type);
  2030             Symbol typeSym =
  2031                 rs.accessBase(
  2032                     rs.findIdentInType(attrEnv, c.type, names.TYPE, VAR),
  2033                     pos, c.type, names.TYPE, true);
  2034             if (typeSym.kind == VAR)
  2035                 ((VarSymbol)typeSym).getConstValue(); // ensure initializer is evaluated
  2036             return make.QualIdent(typeSym);
  2037         case CLASS: case ARRAY:
  2038             if (target.hasClassLiterals()) {
  2039                 VarSymbol sym = new VarSymbol(
  2040                         STATIC | PUBLIC | FINAL, names._class,
  2041                         syms.classType, type.tsym);
  2042                 return make_at(pos).Select(make.Type(type), sym);
  2044             // replace with <cache == null ? cache = class$(tsig) : cache>
  2045             // where
  2046             //  - <tsig>  is the type signature of T,
  2047             //  - <cache> is the cache variable for tsig.
  2048             String sig =
  2049                 writer.xClassName(type).toString().replace('/', '.');
  2050             Symbol cs = cacheSym(pos, sig);
  2051             return make_at(pos).Conditional(
  2052                 makeBinary(EQ, make.Ident(cs), makeNull()),
  2053                 make.Assign(
  2054                     make.Ident(cs),
  2055                     make.App(
  2056                         make.Ident(classDollarSym(pos)),
  2057                         List.<JCExpression>of(make.Literal(CLASS, sig)
  2058                                               .setType(syms.stringType))))
  2059                 .setType(types.erasure(syms.classType)),
  2060                 make.Ident(cs)).setType(types.erasure(syms.classType));
  2061         default:
  2062             throw new AssertionError();
  2066 /**************************************************************************
  2067  * Code for enabling/disabling assertions.
  2068  *************************************************************************/
  2070     // This code is not particularly robust if the user has
  2071     // previously declared a member named '$assertionsDisabled'.
  2072     // The same faulty idiom also appears in the translation of
  2073     // class literals above.  We should report an error if a
  2074     // previous declaration is not synthetic.
  2076     private JCExpression assertFlagTest(DiagnosticPosition pos) {
  2077         // Outermost class may be either true class or an interface.
  2078         ClassSymbol outermostClass = outermostClassDef.sym;
  2080         // note that this is a class, as an interface can't contain a statement.
  2081         ClassSymbol container = currentClass;
  2083         VarSymbol assertDisabledSym =
  2084             (VarSymbol)lookupSynthetic(dollarAssertionsDisabled,
  2085                                        container.members());
  2086         if (assertDisabledSym == null) {
  2087             assertDisabledSym =
  2088                 new VarSymbol(STATIC | FINAL | SYNTHETIC,
  2089                               dollarAssertionsDisabled,
  2090                               syms.booleanType,
  2091                               container);
  2092             enterSynthetic(pos, assertDisabledSym, container.members());
  2093             Symbol desiredAssertionStatusSym = lookupMethod(pos,
  2094                                                             names.desiredAssertionStatus,
  2095                                                             types.erasure(syms.classType),
  2096                                                             List.<Type>nil());
  2097             JCClassDecl containerDef = classDef(container);
  2098             make_at(containerDef.pos());
  2099             JCExpression notStatus = makeUnary(NOT, make.App(make.Select(
  2100                     classOfType(types.erasure(outermostClass.type),
  2101                                 containerDef.pos()),
  2102                     desiredAssertionStatusSym)));
  2103             JCVariableDecl assertDisabledDef = make.VarDef(assertDisabledSym,
  2104                                                    notStatus);
  2105             containerDef.defs = containerDef.defs.prepend(assertDisabledDef);
  2107         make_at(pos);
  2108         return makeUnary(NOT, make.Ident(assertDisabledSym));
  2112 /**************************************************************************
  2113  * Building blocks for let expressions
  2114  *************************************************************************/
  2116     interface TreeBuilder {
  2117         JCTree build(JCTree arg);
  2120     /** Construct an expression using the builder, with the given rval
  2121      *  expression as an argument to the builder.  However, the rval
  2122      *  expression must be computed only once, even if used multiple
  2123      *  times in the result of the builder.  We do that by
  2124      *  constructing a "let" expression that saves the rvalue into a
  2125      *  temporary variable and then uses the temporary variable in
  2126      *  place of the expression built by the builder.  The complete
  2127      *  resulting expression is of the form
  2128      *  <pre>
  2129      *    (let <b>TYPE</b> <b>TEMP</b> = <b>RVAL</b>;
  2130      *     in (<b>BUILDER</b>(<b>TEMP</b>)))
  2131      *  </pre>
  2132      *  where <code><b>TEMP</b></code> is a newly declared variable
  2133      *  in the let expression.
  2134      */
  2135     JCTree abstractRval(JCTree rval, Type type, TreeBuilder builder) {
  2136         rval = TreeInfo.skipParens(rval);
  2137         switch (rval.getTag()) {
  2138         case LITERAL:
  2139             return builder.build(rval);
  2140         case IDENT:
  2141             JCIdent id = (JCIdent) rval;
  2142             if ((id.sym.flags() & FINAL) != 0 && id.sym.owner.kind == MTH)
  2143                 return builder.build(rval);
  2145         VarSymbol var =
  2146             new VarSymbol(FINAL|SYNTHETIC,
  2147                           names.fromString(
  2148                                           target.syntheticNameChar()
  2149                                           + "" + rval.hashCode()),
  2150                                       type,
  2151                                       currentMethodSym);
  2152         rval = convert(rval,type);
  2153         JCVariableDecl def = make.VarDef(var, (JCExpression)rval); // XXX cast
  2154         JCTree built = builder.build(make.Ident(var));
  2155         JCTree res = make.LetExpr(def, built);
  2156         res.type = built.type;
  2157         return res;
  2160     // same as above, with the type of the temporary variable computed
  2161     JCTree abstractRval(JCTree rval, TreeBuilder builder) {
  2162         return abstractRval(rval, rval.type, builder);
  2165     // same as above, but for an expression that may be used as either
  2166     // an rvalue or an lvalue.  This requires special handling for
  2167     // Select expressions, where we place the left-hand-side of the
  2168     // select in a temporary, and for Indexed expressions, where we
  2169     // place both the indexed expression and the index value in temps.
  2170     JCTree abstractLval(JCTree lval, final TreeBuilder builder) {
  2171         lval = TreeInfo.skipParens(lval);
  2172         switch (lval.getTag()) {
  2173         case IDENT:
  2174             return builder.build(lval);
  2175         case SELECT: {
  2176             final JCFieldAccess s = (JCFieldAccess)lval;
  2177             JCTree selected = TreeInfo.skipParens(s.selected);
  2178             Symbol lid = TreeInfo.symbol(s.selected);
  2179             if (lid != null && lid.kind == TYP) return builder.build(lval);
  2180             return abstractRval(s.selected, new TreeBuilder() {
  2181                     public JCTree build(final JCTree selected) {
  2182                         return builder.build(make.Select((JCExpression)selected, s.sym));
  2184                 });
  2186         case INDEXED: {
  2187             final JCArrayAccess i = (JCArrayAccess)lval;
  2188             return abstractRval(i.indexed, new TreeBuilder() {
  2189                     public JCTree build(final JCTree indexed) {
  2190                         return abstractRval(i.index, syms.intType, new TreeBuilder() {
  2191                                 public JCTree build(final JCTree index) {
  2192                                     JCTree newLval = make.Indexed((JCExpression)indexed,
  2193                                                                 (JCExpression)index);
  2194                                     newLval.setType(i.type);
  2195                                     return builder.build(newLval);
  2197                             });
  2199                 });
  2201         case TYPECAST: {
  2202             return abstractLval(((JCTypeCast)lval).expr, builder);
  2205         throw new AssertionError(lval);
  2208     // evaluate and discard the first expression, then evaluate the second.
  2209     JCTree makeComma(final JCTree expr1, final JCTree expr2) {
  2210         return abstractRval(expr1, new TreeBuilder() {
  2211                 public JCTree build(final JCTree discarded) {
  2212                     return expr2;
  2214             });
  2217 /**************************************************************************
  2218  * Translation methods
  2219  *************************************************************************/
  2221     /** Visitor argument: enclosing operator node.
  2222      */
  2223     private JCExpression enclOp;
  2225     /** Visitor method: Translate a single node.
  2226      *  Attach the source position from the old tree to its replacement tree.
  2227      */
  2228     public <T extends JCTree> T translate(T tree) {
  2229         if (tree == null) {
  2230             return null;
  2231         } else {
  2232             make_at(tree.pos());
  2233             T result = super.translate(tree);
  2234             if (endPosTable != null && result != tree) {
  2235                 endPosTable.replaceTree(tree, result);
  2237             return result;
  2241     /** Visitor method: Translate a single node, boxing or unboxing if needed.
  2242      */
  2243     public <T extends JCTree> T translate(T tree, Type type) {
  2244         return (tree == null) ? null : boxIfNeeded(translate(tree), type);
  2247     /** Visitor method: Translate tree.
  2248      */
  2249     public <T extends JCTree> T translate(T tree, JCExpression enclOp) {
  2250         JCExpression prevEnclOp = this.enclOp;
  2251         this.enclOp = enclOp;
  2252         T res = translate(tree);
  2253         this.enclOp = prevEnclOp;
  2254         return res;
  2257     /** Visitor method: Translate list of trees.
  2258      */
  2259     public <T extends JCTree> List<T> translate(List<T> trees, JCExpression enclOp) {
  2260         JCExpression prevEnclOp = this.enclOp;
  2261         this.enclOp = enclOp;
  2262         List<T> res = translate(trees);
  2263         this.enclOp = prevEnclOp;
  2264         return res;
  2267     /** Visitor method: Translate list of trees.
  2268      */
  2269     public <T extends JCTree> List<T> translate(List<T> trees, Type type) {
  2270         if (trees == null) return null;
  2271         for (List<T> l = trees; l.nonEmpty(); l = l.tail)
  2272             l.head = translate(l.head, type);
  2273         return trees;
  2276     public void visitTopLevel(JCCompilationUnit tree) {
  2277         if (needPackageInfoClass(tree)) {
  2278             Name name = names.package_info;
  2279             long flags = Flags.ABSTRACT | Flags.INTERFACE;
  2280             if (target.isPackageInfoSynthetic())
  2281                 // package-info is marked SYNTHETIC in JDK 1.6 and later releases
  2282                 flags = flags | Flags.SYNTHETIC;
  2283             JCClassDecl packageAnnotationsClass
  2284                 = make.ClassDef(make.Modifiers(flags,
  2285                                                tree.packageAnnotations),
  2286                                 name, List.<JCTypeParameter>nil(),
  2287                                 null, List.<JCExpression>nil(), List.<JCTree>nil());
  2288             ClassSymbol c = tree.packge.package_info;
  2289             c.flags_field |= flags;
  2290             c.annotations.setAttributes(tree.packge.annotations);
  2291             ClassType ctype = (ClassType) c.type;
  2292             ctype.supertype_field = syms.objectType;
  2293             ctype.interfaces_field = List.nil();
  2294             packageAnnotationsClass.sym = c;
  2296             translated.append(packageAnnotationsClass);
  2299     // where
  2300     private boolean needPackageInfoClass(JCCompilationUnit tree) {
  2301         switch (pkginfoOpt) {
  2302             case ALWAYS:
  2303                 return true;
  2304             case LEGACY:
  2305                 return tree.packageAnnotations.nonEmpty();
  2306             case NONEMPTY:
  2307                 for (Attribute.Compound a :
  2308                          tree.packge.annotations.getDeclarationAttributes()) {
  2309                     Attribute.RetentionPolicy p = types.getRetention(a);
  2310                     if (p != Attribute.RetentionPolicy.SOURCE)
  2311                         return true;
  2313                 return false;
  2315         throw new AssertionError();
  2318     public void visitClassDef(JCClassDecl tree) {
  2319         ClassSymbol currentClassPrev = currentClass;
  2320         MethodSymbol currentMethodSymPrev = currentMethodSym;
  2321         currentClass = tree.sym;
  2322         currentMethodSym = null;
  2323         classdefs.put(currentClass, tree);
  2325         proxies = proxies.dup(currentClass);
  2326         List<VarSymbol> prevOuterThisStack = outerThisStack;
  2328         // If this is an enum definition
  2329         if ((tree.mods.flags & ENUM) != 0 &&
  2330             (types.supertype(currentClass.type).tsym.flags() & ENUM) == 0)
  2331             visitEnumDef(tree);
  2333         // If this is a nested class, define a this$n field for
  2334         // it and add to proxies.
  2335         JCVariableDecl otdef = null;
  2336         if (currentClass.hasOuterInstance())
  2337             otdef = outerThisDef(tree.pos, currentClass);
  2339         // If this is a local class, define proxies for all its free variables.
  2340         List<JCVariableDecl> fvdefs = freevarDefs(
  2341             tree.pos, freevars(currentClass), currentClass);
  2343         // Recursively translate superclass, interfaces.
  2344         tree.extending = translate(tree.extending);
  2345         tree.implementing = translate(tree.implementing);
  2347         if (currentClass.isLocal()) {
  2348             ClassSymbol encl = currentClass.owner.enclClass();
  2349             if (encl.trans_local == null) {
  2350                 encl.trans_local = List.nil();
  2352             encl.trans_local = encl.trans_local.prepend(currentClass);
  2355         // Recursively translate members, taking into account that new members
  2356         // might be created during the translation and prepended to the member
  2357         // list `tree.defs'.
  2358         List<JCTree> seen = List.nil();
  2359         while (tree.defs != seen) {
  2360             List<JCTree> unseen = tree.defs;
  2361             for (List<JCTree> l = unseen; l.nonEmpty() && l != seen; l = l.tail) {
  2362                 JCTree outermostMemberDefPrev = outermostMemberDef;
  2363                 if (outermostMemberDefPrev == null) outermostMemberDef = l.head;
  2364                 l.head = translate(l.head);
  2365                 outermostMemberDef = outermostMemberDefPrev;
  2367             seen = unseen;
  2370         // Convert a protected modifier to public, mask static modifier.
  2371         if ((tree.mods.flags & PROTECTED) != 0) tree.mods.flags |= PUBLIC;
  2372         tree.mods.flags &= ClassFlags;
  2374         // Convert name to flat representation, replacing '.' by '$'.
  2375         tree.name = Convert.shortName(currentClass.flatName());
  2377         // Add this$n and free variables proxy definitions to class.
  2378         for (List<JCVariableDecl> l = fvdefs; l.nonEmpty(); l = l.tail) {
  2379             tree.defs = tree.defs.prepend(l.head);
  2380             enterSynthetic(tree.pos(), l.head.sym, currentClass.members());
  2382         if (currentClass.hasOuterInstance()) {
  2383             tree.defs = tree.defs.prepend(otdef);
  2384             enterSynthetic(tree.pos(), otdef.sym, currentClass.members());
  2387         proxies = proxies.leave();
  2388         outerThisStack = prevOuterThisStack;
  2390         // Append translated tree to `translated' queue.
  2391         translated.append(tree);
  2393         currentClass = currentClassPrev;
  2394         currentMethodSym = currentMethodSymPrev;
  2396         // Return empty block {} as a placeholder for an inner class.
  2397         result = make_at(tree.pos()).Block(0, List.<JCStatement>nil());
  2400     /** Translate an enum class. */
  2401     private void visitEnumDef(JCClassDecl tree) {
  2402         make_at(tree.pos());
  2404         // add the supertype, if needed
  2405         if (tree.extending == null)
  2406             tree.extending = make.Type(types.supertype(tree.type));
  2408         // classOfType adds a cache field to tree.defs unless
  2409         // target.hasClassLiterals().
  2410         JCExpression e_class = classOfType(tree.sym.type, tree.pos()).
  2411             setType(types.erasure(syms.classType));
  2413         // process each enumeration constant, adding implicit constructor parameters
  2414         int nextOrdinal = 0;
  2415         ListBuffer<JCExpression> values = new ListBuffer<JCExpression>();
  2416         ListBuffer<JCTree> enumDefs = new ListBuffer<JCTree>();
  2417         ListBuffer<JCTree> otherDefs = new ListBuffer<JCTree>();
  2418         for (List<JCTree> defs = tree.defs;
  2419              defs.nonEmpty();
  2420              defs=defs.tail) {
  2421             if (defs.head.hasTag(VARDEF) && (((JCVariableDecl) defs.head).mods.flags & ENUM) != 0) {
  2422                 JCVariableDecl var = (JCVariableDecl)defs.head;
  2423                 visitEnumConstantDef(var, nextOrdinal++);
  2424                 values.append(make.QualIdent(var.sym));
  2425                 enumDefs.append(var);
  2426             } else {
  2427                 otherDefs.append(defs.head);
  2431         // private static final T[] #VALUES = { a, b, c };
  2432         Name valuesName = names.fromString(target.syntheticNameChar() + "VALUES");
  2433         while (tree.sym.members().lookup(valuesName).scope != null) // avoid name clash
  2434             valuesName = names.fromString(valuesName + "" + target.syntheticNameChar());
  2435         Type arrayType = new ArrayType(types.erasure(tree.type), syms.arrayClass);
  2436         VarSymbol valuesVar = new VarSymbol(PRIVATE|FINAL|STATIC|SYNTHETIC,
  2437                                             valuesName,
  2438                                             arrayType,
  2439                                             tree.type.tsym);
  2440         JCNewArray newArray = make.NewArray(make.Type(types.erasure(tree.type)),
  2441                                           List.<JCExpression>nil(),
  2442                                           values.toList());
  2443         newArray.type = arrayType;
  2444         enumDefs.append(make.VarDef(valuesVar, newArray));
  2445         tree.sym.members().enter(valuesVar);
  2447         Symbol valuesSym = lookupMethod(tree.pos(), names.values,
  2448                                         tree.type, List.<Type>nil());
  2449         List<JCStatement> valuesBody;
  2450         if (useClone()) {
  2451             // return (T[]) $VALUES.clone();
  2452             JCTypeCast valuesResult =
  2453                 make.TypeCast(valuesSym.type.getReturnType(),
  2454                               make.App(make.Select(make.Ident(valuesVar),
  2455                                                    syms.arrayCloneMethod)));
  2456             valuesBody = List.<JCStatement>of(make.Return(valuesResult));
  2457         } else {
  2458             // template: T[] $result = new T[$values.length];
  2459             Name resultName = names.fromString(target.syntheticNameChar() + "result");
  2460             while (tree.sym.members().lookup(resultName).scope != null) // avoid name clash
  2461                 resultName = names.fromString(resultName + "" + target.syntheticNameChar());
  2462             VarSymbol resultVar = new VarSymbol(FINAL|SYNTHETIC,
  2463                                                 resultName,
  2464                                                 arrayType,
  2465                                                 valuesSym);
  2466             JCNewArray resultArray = make.NewArray(make.Type(types.erasure(tree.type)),
  2467                                   List.of(make.Select(make.Ident(valuesVar), syms.lengthVar)),
  2468                                   null);
  2469             resultArray.type = arrayType;
  2470             JCVariableDecl decl = make.VarDef(resultVar, resultArray);
  2472             // template: System.arraycopy($VALUES, 0, $result, 0, $VALUES.length);
  2473             if (systemArraycopyMethod == null) {
  2474                 systemArraycopyMethod =
  2475                     new MethodSymbol(PUBLIC | STATIC,
  2476                                      names.fromString("arraycopy"),
  2477                                      new MethodType(List.<Type>of(syms.objectType,
  2478                                                             syms.intType,
  2479                                                             syms.objectType,
  2480                                                             syms.intType,
  2481                                                             syms.intType),
  2482                                                     syms.voidType,
  2483                                                     List.<Type>nil(),
  2484                                                     syms.methodClass),
  2485                                      syms.systemType.tsym);
  2487             JCStatement copy =
  2488                 make.Exec(make.App(make.Select(make.Ident(syms.systemType.tsym),
  2489                                                systemArraycopyMethod),
  2490                           List.of(make.Ident(valuesVar), make.Literal(0),
  2491                                   make.Ident(resultVar), make.Literal(0),
  2492                                   make.Select(make.Ident(valuesVar), syms.lengthVar))));
  2494             // template: return $result;
  2495             JCStatement ret = make.Return(make.Ident(resultVar));
  2496             valuesBody = List.<JCStatement>of(decl, copy, ret);
  2499         JCMethodDecl valuesDef =
  2500              make.MethodDef((MethodSymbol)valuesSym, make.Block(0, valuesBody));
  2502         enumDefs.append(valuesDef);
  2504         if (debugLower)
  2505             System.err.println(tree.sym + ".valuesDef = " + valuesDef);
  2507         /** The template for the following code is:
  2509          *     public static E valueOf(String name) {
  2510          *         return (E)Enum.valueOf(E.class, name);
  2511          *     }
  2513          *  where E is tree.sym
  2514          */
  2515         MethodSymbol valueOfSym = lookupMethod(tree.pos(),
  2516                          names.valueOf,
  2517                          tree.sym.type,
  2518                          List.of(syms.stringType));
  2519         Assert.check((valueOfSym.flags() & STATIC) != 0);
  2520         VarSymbol nameArgSym = valueOfSym.params.head;
  2521         JCIdent nameVal = make.Ident(nameArgSym);
  2522         JCStatement enum_ValueOf =
  2523             make.Return(make.TypeCast(tree.sym.type,
  2524                                       makeCall(make.Ident(syms.enumSym),
  2525                                                names.valueOf,
  2526                                                List.of(e_class, nameVal))));
  2527         JCMethodDecl valueOf = make.MethodDef(valueOfSym,
  2528                                            make.Block(0, List.of(enum_ValueOf)));
  2529         nameVal.sym = valueOf.params.head.sym;
  2530         if (debugLower)
  2531             System.err.println(tree.sym + ".valueOf = " + valueOf);
  2532         enumDefs.append(valueOf);
  2534         enumDefs.appendList(otherDefs.toList());
  2535         tree.defs = enumDefs.toList();
  2537         // Add the necessary members for the EnumCompatibleMode
  2538         if (target.compilerBootstrap(tree.sym)) {
  2539             addEnumCompatibleMembers(tree);
  2542         // where
  2543         private MethodSymbol systemArraycopyMethod;
  2544         private boolean useClone() {
  2545             try {
  2546                 Scope.Entry e = syms.objectType.tsym.members().lookup(names.clone);
  2547                 return (e.sym != null);
  2549             catch (CompletionFailure e) {
  2550                 return false;
  2554     /** Translate an enumeration constant and its initializer. */
  2555     private void visitEnumConstantDef(JCVariableDecl var, int ordinal) {
  2556         JCNewClass varDef = (JCNewClass)var.init;
  2557         varDef.args = varDef.args.
  2558             prepend(makeLit(syms.intType, ordinal)).
  2559             prepend(makeLit(syms.stringType, var.name.toString()));
  2562     public void visitMethodDef(JCMethodDecl tree) {
  2563         if (tree.name == names.init && (currentClass.flags_field&ENUM) != 0) {
  2564             // Add "String $enum$name, int $enum$ordinal" to the beginning of the
  2565             // argument list for each constructor of an enum.
  2566             JCVariableDecl nameParam = make_at(tree.pos()).
  2567                 Param(names.fromString(target.syntheticNameChar() +
  2568                                        "enum" + target.syntheticNameChar() + "name"),
  2569                       syms.stringType, tree.sym);
  2570             nameParam.mods.flags |= SYNTHETIC; nameParam.sym.flags_field |= SYNTHETIC;
  2572             JCVariableDecl ordParam = make.
  2573                 Param(names.fromString(target.syntheticNameChar() +
  2574                                        "enum" + target.syntheticNameChar() +
  2575                                        "ordinal"),
  2576                       syms.intType, tree.sym);
  2577             ordParam.mods.flags |= SYNTHETIC; ordParam.sym.flags_field |= SYNTHETIC;
  2579             tree.params = tree.params.prepend(ordParam).prepend(nameParam);
  2581             MethodSymbol m = tree.sym;
  2582             Type olderasure = m.erasure(types);
  2583             m.erasure_field = new MethodType(
  2584                 olderasure.getParameterTypes().prepend(syms.intType).prepend(syms.stringType),
  2585                 olderasure.getReturnType(),
  2586                 olderasure.getThrownTypes(),
  2587                 syms.methodClass);
  2589             if (target.compilerBootstrap(m.owner)) {
  2590                 // Initialize synthetic name field
  2591                 Symbol nameVarSym = lookupSynthetic(names.fromString("$name"),
  2592                                                     tree.sym.owner.members());
  2593                 JCIdent nameIdent = make.Ident(nameParam.sym);
  2594                 JCIdent id1 = make.Ident(nameVarSym);
  2595                 JCAssign newAssign = make.Assign(id1, nameIdent);
  2596                 newAssign.type = id1.type;
  2597                 JCExpressionStatement nameAssign = make.Exec(newAssign);
  2598                 nameAssign.type = id1.type;
  2599                 tree.body.stats = tree.body.stats.prepend(nameAssign);
  2601                 // Initialize synthetic ordinal field
  2602                 Symbol ordinalVarSym = lookupSynthetic(names.fromString("$ordinal"),
  2603                                                        tree.sym.owner.members());
  2604                 JCIdent ordIdent = make.Ident(ordParam.sym);
  2605                 id1 = make.Ident(ordinalVarSym);
  2606                 newAssign = make.Assign(id1, ordIdent);
  2607                 newAssign.type = id1.type;
  2608                 JCExpressionStatement ordinalAssign = make.Exec(newAssign);
  2609                 ordinalAssign.type = id1.type;
  2610                 tree.body.stats = tree.body.stats.prepend(ordinalAssign);
  2614         JCMethodDecl prevMethodDef = currentMethodDef;
  2615         MethodSymbol prevMethodSym = currentMethodSym;
  2616         try {
  2617             currentMethodDef = tree;
  2618             currentMethodSym = tree.sym;
  2619             visitMethodDefInternal(tree);
  2620         } finally {
  2621             currentMethodDef = prevMethodDef;
  2622             currentMethodSym = prevMethodSym;
  2625     //where
  2626     private void visitMethodDefInternal(JCMethodDecl tree) {
  2627         if (tree.name == names.init &&
  2628             (currentClass.isInner() ||
  2629              (currentClass.owner.kind & (VAR | MTH)) != 0)) {
  2630             // We are seeing a constructor of an inner class.
  2631             MethodSymbol m = tree.sym;
  2633             // Push a new proxy scope for constructor parameters.
  2634             // and create definitions for any this$n and proxy parameters.
  2635             proxies = proxies.dup(m);
  2636             List<VarSymbol> prevOuterThisStack = outerThisStack;
  2637             List<VarSymbol> fvs = freevars(currentClass);
  2638             JCVariableDecl otdef = null;
  2639             if (currentClass.hasOuterInstance())
  2640                 otdef = outerThisDef(tree.pos, m);
  2641             List<JCVariableDecl> fvdefs = freevarDefs(tree.pos, fvs, m);
  2643             // Recursively translate result type, parameters and thrown list.
  2644             tree.restype = translate(tree.restype);
  2645             tree.params = translateVarDefs(tree.params);
  2646             tree.thrown = translate(tree.thrown);
  2648             // when compiling stubs, don't process body
  2649             if (tree.body == null) {
  2650                 result = tree;
  2651                 return;
  2654             // Add this$n (if needed) in front of and free variables behind
  2655             // constructor parameter list.
  2656             tree.params = tree.params.appendList(fvdefs);
  2657             if (currentClass.hasOuterInstance())
  2658                 tree.params = tree.params.prepend(otdef);
  2660             // If this is an initial constructor, i.e., it does not start with
  2661             // this(...), insert initializers for this$n and proxies
  2662             // before (pre-1.4, after) the call to superclass constructor.
  2663             JCStatement selfCall = translate(tree.body.stats.head);
  2665             List<JCStatement> added = List.nil();
  2666             if (fvs.nonEmpty()) {
  2667                 List<Type> addedargtypes = List.nil();
  2668                 for (List<VarSymbol> l = fvs; l.nonEmpty(); l = l.tail) {
  2669                     if (TreeInfo.isInitialConstructor(tree))
  2670                         added = added.prepend(
  2671                             initField(tree.body.pos, proxyName(l.head.name)));
  2672                     addedargtypes = addedargtypes.prepend(l.head.erasure(types));
  2674                 Type olderasure = m.erasure(types);
  2675                 m.erasure_field = new MethodType(
  2676                     olderasure.getParameterTypes().appendList(addedargtypes),
  2677                     olderasure.getReturnType(),
  2678                     olderasure.getThrownTypes(),
  2679                     syms.methodClass);
  2681             if (currentClass.hasOuterInstance() &&
  2682                 TreeInfo.isInitialConstructor(tree))
  2684                 added = added.prepend(initOuterThis(tree.body.pos));
  2687             // pop local variables from proxy stack
  2688             proxies = proxies.leave();
  2690             // recursively translate following local statements and
  2691             // combine with this- or super-call
  2692             List<JCStatement> stats = translate(tree.body.stats.tail);
  2693             if (target.initializeFieldsBeforeSuper())
  2694                 tree.body.stats = stats.prepend(selfCall).prependList(added);
  2695             else
  2696                 tree.body.stats = stats.prependList(added).prepend(selfCall);
  2698             outerThisStack = prevOuterThisStack;
  2699         } else {
  2700             super.visitMethodDef(tree);
  2702         result = tree;
  2705     public void visitAnnotatedType(JCAnnotatedType tree) {
  2706         // No need to retain type annotations any longer.
  2707         // tree.annotations = translate(tree.annotations);
  2708         tree.underlyingType = translate(tree.underlyingType);
  2709         result = tree.underlyingType;
  2712     public void visitTypeCast(JCTypeCast tree) {
  2713         tree.clazz = translate(tree.clazz);
  2714         if (tree.type.isPrimitive() != tree.expr.type.isPrimitive())
  2715             tree.expr = translate(tree.expr, tree.type);
  2716         else
  2717             tree.expr = translate(tree.expr);
  2718         result = tree;
  2721     public void visitNewClass(JCNewClass tree) {
  2722         ClassSymbol c = (ClassSymbol)tree.constructor.owner;
  2724         // Box arguments, if necessary
  2725         boolean isEnum = (tree.constructor.owner.flags() & ENUM) != 0;
  2726         List<Type> argTypes = tree.constructor.type.getParameterTypes();
  2727         if (isEnum) argTypes = argTypes.prepend(syms.intType).prepend(syms.stringType);
  2728         tree.args = boxArgs(argTypes, tree.args, tree.varargsElement);
  2729         tree.varargsElement = null;
  2731         // If created class is local, add free variables after
  2732         // explicit constructor arguments.
  2733         if ((c.owner.kind & (VAR | MTH)) != 0) {
  2734             tree.args = tree.args.appendList(loadFreevars(tree.pos(), freevars(c)));
  2737         // If an access constructor is used, append null as a last argument.
  2738         Symbol constructor = accessConstructor(tree.pos(), tree.constructor);
  2739         if (constructor != tree.constructor) {
  2740             tree.args = tree.args.append(makeNull());
  2741             tree.constructor = constructor;
  2744         // If created class has an outer instance, and new is qualified, pass
  2745         // qualifier as first argument. If new is not qualified, pass the
  2746         // correct outer instance as first argument.
  2747         if (c.hasOuterInstance()) {
  2748             JCExpression thisArg;
  2749             if (tree.encl != null) {
  2750                 thisArg = attr.makeNullCheck(translate(tree.encl));
  2751                 thisArg.type = tree.encl.type;
  2752             } else if ((c.owner.kind & (MTH | VAR)) != 0) {
  2753                 // local class
  2754                 thisArg = makeThis(tree.pos(), c.type.getEnclosingType().tsym);
  2755             } else {
  2756                 // nested class
  2757                 thisArg = makeOwnerThis(tree.pos(), c, false);
  2759             tree.args = tree.args.prepend(thisArg);
  2761         tree.encl = null;
  2763         // If we have an anonymous class, create its flat version, rather
  2764         // than the class or interface following new.
  2765         if (tree.def != null) {
  2766             translate(tree.def);
  2767             tree.clazz = access(make_at(tree.clazz.pos()).Ident(tree.def.sym));
  2768             tree.def = null;
  2769         } else {
  2770             tree.clazz = access(c, tree.clazz, enclOp, false);
  2772         result = tree;
  2775     // Simplify conditionals with known constant controlling expressions.
  2776     // This allows us to avoid generating supporting declarations for
  2777     // the dead code, which will not be eliminated during code generation.
  2778     // Note that Flow.isFalse and Flow.isTrue only return true
  2779     // for constant expressions in the sense of JLS 15.27, which
  2780     // are guaranteed to have no side-effects.  More aggressive
  2781     // constant propagation would require that we take care to
  2782     // preserve possible side-effects in the condition expression.
  2784     /** Visitor method for conditional expressions.
  2785      */
  2786     @Override
  2787     public void visitConditional(JCConditional tree) {
  2788         JCTree cond = tree.cond = translate(tree.cond, syms.booleanType);
  2789         if (cond.type.isTrue()) {
  2790             result = convert(translate(tree.truepart, tree.type), tree.type);
  2791             addPrunedInfo(cond);
  2792         } else if (cond.type.isFalse()) {
  2793             result = convert(translate(tree.falsepart, tree.type), tree.type);
  2794             addPrunedInfo(cond);
  2795         } else {
  2796             // Condition is not a compile-time constant.
  2797             tree.truepart = translate(tree.truepart, tree.type);
  2798             tree.falsepart = translate(tree.falsepart, tree.type);
  2799             result = tree;
  2802 //where
  2803     private JCTree convert(JCTree tree, Type pt) {
  2804         if (tree.type == pt || tree.type.hasTag(BOT))
  2805             return tree;
  2806         JCTree result = make_at(tree.pos()).TypeCast(make.Type(pt), (JCExpression)tree);
  2807         result.type = (tree.type.constValue() != null) ? cfolder.coerce(tree.type, pt)
  2808                                                        : pt;
  2809         return result;
  2812     /** Visitor method for if statements.
  2813      */
  2814     public void visitIf(JCIf tree) {
  2815         JCTree cond = tree.cond = translate(tree.cond, syms.booleanType);
  2816         if (cond.type.isTrue()) {
  2817             result = translate(tree.thenpart);
  2818             addPrunedInfo(cond);
  2819         } else if (cond.type.isFalse()) {
  2820             if (tree.elsepart != null) {
  2821                 result = translate(tree.elsepart);
  2822             } else {
  2823                 result = make.Skip();
  2825             addPrunedInfo(cond);
  2826         } else {
  2827             // Condition is not a compile-time constant.
  2828             tree.thenpart = translate(tree.thenpart);
  2829             tree.elsepart = translate(tree.elsepart);
  2830             result = tree;
  2834     /** Visitor method for assert statements. Translate them away.
  2835      */
  2836     public void visitAssert(JCAssert tree) {
  2837         DiagnosticPosition detailPos = (tree.detail == null) ? tree.pos() : tree.detail.pos();
  2838         tree.cond = translate(tree.cond, syms.booleanType);
  2839         if (!tree.cond.type.isTrue()) {
  2840             JCExpression cond = assertFlagTest(tree.pos());
  2841             List<JCExpression> exnArgs = (tree.detail == null) ?
  2842                 List.<JCExpression>nil() : List.of(translate(tree.detail));
  2843             if (!tree.cond.type.isFalse()) {
  2844                 cond = makeBinary
  2845                     (AND,
  2846                      cond,
  2847                      makeUnary(NOT, tree.cond));
  2849             result =
  2850                 make.If(cond,
  2851                         make_at(detailPos).
  2852                            Throw(makeNewClass(syms.assertionErrorType, exnArgs)),
  2853                         null);
  2854         } else {
  2855             result = make.Skip();
  2859     public void visitApply(JCMethodInvocation tree) {
  2860         Symbol meth = TreeInfo.symbol(tree.meth);
  2861         List<Type> argtypes = meth.type.getParameterTypes();
  2862         if (allowEnums &&
  2863             meth.name==names.init &&
  2864             meth.owner == syms.enumSym)
  2865             argtypes = argtypes.tail.tail;
  2866         tree.args = boxArgs(argtypes, tree.args, tree.varargsElement);
  2867         tree.varargsElement = null;
  2868         Name methName = TreeInfo.name(tree.meth);
  2869         if (meth.name==names.init) {
  2870             // We are seeing a this(...) or super(...) constructor call.
  2871             // If an access constructor is used, append null as a last argument.
  2872             Symbol constructor = accessConstructor(tree.pos(), meth);
  2873             if (constructor != meth) {
  2874                 tree.args = tree.args.append(makeNull());
  2875                 TreeInfo.setSymbol(tree.meth, constructor);
  2878             // If we are calling a constructor of a local class, add
  2879             // free variables after explicit constructor arguments.
  2880             ClassSymbol c = (ClassSymbol)constructor.owner;
  2881             if ((c.owner.kind & (VAR | MTH)) != 0) {
  2882                 tree.args = tree.args.appendList(loadFreevars(tree.pos(), freevars(c)));
  2885             // If we are calling a constructor of an enum class, pass
  2886             // along the name and ordinal arguments
  2887             if ((c.flags_field&ENUM) != 0 || c.getQualifiedName() == names.java_lang_Enum) {
  2888                 List<JCVariableDecl> params = currentMethodDef.params;
  2889                 if (currentMethodSym.owner.hasOuterInstance())
  2890                     params = params.tail; // drop this$n
  2891                 tree.args = tree.args
  2892                     .prepend(make_at(tree.pos()).Ident(params.tail.head.sym)) // ordinal
  2893                     .prepend(make.Ident(params.head.sym)); // name
  2896             // If we are calling a constructor of a class with an outer
  2897             // instance, and the call
  2898             // is qualified, pass qualifier as first argument in front of
  2899             // the explicit constructor arguments. If the call
  2900             // is not qualified, pass the correct outer instance as
  2901             // first argument.
  2902             if (c.hasOuterInstance()) {
  2903                 JCExpression thisArg;
  2904                 if (tree.meth.hasTag(SELECT)) {
  2905                     thisArg = attr.
  2906                         makeNullCheck(translate(((JCFieldAccess) tree.meth).selected));
  2907                     tree.meth = make.Ident(constructor);
  2908                     ((JCIdent) tree.meth).name = methName;
  2909                 } else if ((c.owner.kind & (MTH | VAR)) != 0 || methName == names._this){
  2910                     // local class or this() call
  2911                     thisArg = makeThis(tree.meth.pos(), c.type.getEnclosingType().tsym);
  2912                 } else {
  2913                     // super() call of nested class - never pick 'this'
  2914                     thisArg = makeOwnerThisN(tree.meth.pos(), c, false);
  2916                 tree.args = tree.args.prepend(thisArg);
  2918         } else {
  2919             // We are seeing a normal method invocation; translate this as usual.
  2920             tree.meth = translate(tree.meth);
  2922             // If the translated method itself is an Apply tree, we are
  2923             // seeing an access method invocation. In this case, append
  2924             // the method arguments to the arguments of the access method.
  2925             if (tree.meth.hasTag(APPLY)) {
  2926                 JCMethodInvocation app = (JCMethodInvocation)tree.meth;
  2927                 app.args = tree.args.prependList(app.args);
  2928                 result = app;
  2929                 return;
  2932         result = tree;
  2935     List<JCExpression> boxArgs(List<Type> parameters, List<JCExpression> _args, Type varargsElement) {
  2936         List<JCExpression> args = _args;
  2937         if (parameters.isEmpty()) return args;
  2938         boolean anyChanges = false;
  2939         ListBuffer<JCExpression> result = new ListBuffer<JCExpression>();
  2940         while (parameters.tail.nonEmpty()) {
  2941             JCExpression arg = translate(args.head, parameters.head);
  2942             anyChanges |= (arg != args.head);
  2943             result.append(arg);
  2944             args = args.tail;
  2945             parameters = parameters.tail;
  2947         Type parameter = parameters.head;
  2948         if (varargsElement != null) {
  2949             anyChanges = true;
  2950             ListBuffer<JCExpression> elems = new ListBuffer<JCExpression>();
  2951             while (args.nonEmpty()) {
  2952                 JCExpression arg = translate(args.head, varargsElement);
  2953                 elems.append(arg);
  2954                 args = args.tail;
  2956             JCNewArray boxedArgs = make.NewArray(make.Type(varargsElement),
  2957                                                List.<JCExpression>nil(),
  2958                                                elems.toList());
  2959             boxedArgs.type = new ArrayType(varargsElement, syms.arrayClass);
  2960             result.append(boxedArgs);
  2961         } else {
  2962             if (args.length() != 1) throw new AssertionError(args);
  2963             JCExpression arg = translate(args.head, parameter);
  2964             anyChanges |= (arg != args.head);
  2965             result.append(arg);
  2966             if (!anyChanges) return _args;
  2968         return result.toList();
  2971     /** Expand a boxing or unboxing conversion if needed. */
  2972     @SuppressWarnings("unchecked") // XXX unchecked
  2973     <T extends JCTree> T boxIfNeeded(T tree, Type type) {
  2974         boolean havePrimitive = tree.type.isPrimitive();
  2975         if (havePrimitive == type.isPrimitive())
  2976             return tree;
  2977         if (havePrimitive) {
  2978             Type unboxedTarget = types.unboxedType(type);
  2979             if (!unboxedTarget.hasTag(NONE)) {
  2980                 if (!types.isSubtype(tree.type, unboxedTarget)) //e.g. Character c = 89;
  2981                     tree.type = unboxedTarget.constType(tree.type.constValue());
  2982                 return (T)boxPrimitive((JCExpression)tree, type);
  2983             } else {
  2984                 tree = (T)boxPrimitive((JCExpression)tree);
  2986         } else {
  2987             tree = (T)unbox((JCExpression)tree, type);
  2989         return tree;
  2992     /** Box up a single primitive expression. */
  2993     JCExpression boxPrimitive(JCExpression tree) {
  2994         return boxPrimitive(tree, types.boxedClass(tree.type).type);
  2997     /** Box up a single primitive expression. */
  2998     JCExpression boxPrimitive(JCExpression tree, Type box) {
  2999         make_at(tree.pos());
  3000         if (target.boxWithConstructors()) {
  3001             Symbol ctor = lookupConstructor(tree.pos(),
  3002                                             box,
  3003                                             List.<Type>nil()
  3004                                             .prepend(tree.type));
  3005             return make.Create(ctor, List.of(tree));
  3006         } else {
  3007             Symbol valueOfSym = lookupMethod(tree.pos(),
  3008                                              names.valueOf,
  3009                                              box,
  3010                                              List.<Type>nil()
  3011                                              .prepend(tree.type));
  3012             return make.App(make.QualIdent(valueOfSym), List.of(tree));
  3016     /** Unbox an object to a primitive value. */
  3017     JCExpression unbox(JCExpression tree, Type primitive) {
  3018         Type unboxedType = types.unboxedType(tree.type);
  3019         if (unboxedType.hasTag(NONE)) {
  3020             unboxedType = primitive;
  3021             if (!unboxedType.isPrimitive())
  3022                 throw new AssertionError(unboxedType);
  3023             make_at(tree.pos());
  3024             tree = make.TypeCast(types.boxedClass(unboxedType).type, tree);
  3025         } else {
  3026             // There must be a conversion from unboxedType to primitive.
  3027             if (!types.isSubtype(unboxedType, primitive))
  3028                 throw new AssertionError(tree);
  3030         make_at(tree.pos());
  3031         Symbol valueSym = lookupMethod(tree.pos(),
  3032                                        unboxedType.tsym.name.append(names.Value), // x.intValue()
  3033                                        tree.type,
  3034                                        List.<Type>nil());
  3035         return make.App(make.Select(tree, valueSym));
  3038     /** Visitor method for parenthesized expressions.
  3039      *  If the subexpression has changed, omit the parens.
  3040      */
  3041     public void visitParens(JCParens tree) {
  3042         JCTree expr = translate(tree.expr);
  3043         result = ((expr == tree.expr) ? tree : expr);
  3046     public void visitIndexed(JCArrayAccess tree) {
  3047         tree.indexed = translate(tree.indexed);
  3048         tree.index = translate(tree.index, syms.intType);
  3049         result = tree;
  3052     public void visitAssign(JCAssign tree) {
  3053         tree.lhs = translate(tree.lhs, tree);
  3054         tree.rhs = translate(tree.rhs, tree.lhs.type);
  3056         // If translated left hand side is an Apply, we are
  3057         // seeing an access method invocation. In this case, append
  3058         // right hand side as last argument of the access method.
  3059         if (tree.lhs.hasTag(APPLY)) {
  3060             JCMethodInvocation app = (JCMethodInvocation)tree.lhs;
  3061             app.args = List.of(tree.rhs).prependList(app.args);
  3062             result = app;
  3063         } else {
  3064             result = tree;
  3068     public void visitAssignop(final JCAssignOp tree) {
  3069         if (!tree.lhs.type.isPrimitive() &&
  3070             tree.operator.type.getReturnType().isPrimitive()) {
  3071             // boxing required; need to rewrite as x = (unbox typeof x)(x op y);
  3072             // or if x == (typeof x)z then z = (unbox typeof x)((typeof x)z op y)
  3073             // (but without recomputing x)
  3074             JCTree newTree = abstractLval(tree.lhs, new TreeBuilder() {
  3075                     public JCTree build(final JCTree lhs) {
  3076                         JCTree.Tag newTag = tree.getTag().noAssignOp();
  3077                         // Erasure (TransTypes) can change the type of
  3078                         // tree.lhs.  However, we can still get the
  3079                         // unerased type of tree.lhs as it is stored
  3080                         // in tree.type in Attr.
  3081                         Symbol newOperator = rs.resolveBinaryOperator(tree.pos(),
  3082                                                                       newTag,
  3083                                                                       attrEnv,
  3084                                                                       tree.type,
  3085                                                                       tree.rhs.type);
  3086                         JCExpression expr = (JCExpression)lhs;
  3087                         if (expr.type != tree.type)
  3088                             expr = make.TypeCast(tree.type, expr);
  3089                         JCBinary opResult = make.Binary(newTag, expr, tree.rhs);
  3090                         opResult.operator = newOperator;
  3091                         opResult.type = newOperator.type.getReturnType();
  3092                         JCTypeCast newRhs = make.TypeCast(types.unboxedType(tree.type),
  3093                                                           opResult);
  3094                         return make.Assign((JCExpression)lhs, newRhs).setType(tree.type);
  3096                 });
  3097             result = translate(newTree);
  3098             return;
  3100         tree.lhs = translate(tree.lhs, tree);
  3101         tree.rhs = translate(tree.rhs, tree.operator.type.getParameterTypes().tail.head);
  3103         // If translated left hand side is an Apply, we are
  3104         // seeing an access method invocation. In this case, append
  3105         // right hand side as last argument of the access method.
  3106         if (tree.lhs.hasTag(APPLY)) {
  3107             JCMethodInvocation app = (JCMethodInvocation)tree.lhs;
  3108             // if operation is a += on strings,
  3109             // make sure to convert argument to string
  3110             JCExpression rhs = (((OperatorSymbol)tree.operator).opcode == string_add)
  3111               ? makeString(tree.rhs)
  3112               : tree.rhs;
  3113             app.args = List.of(rhs).prependList(app.args);
  3114             result = app;
  3115         } else {
  3116             result = tree;
  3120     /** Lower a tree of the form e++ or e-- where e is an object type */
  3121     JCTree lowerBoxedPostop(final JCUnary tree) {
  3122         // translate to tmp1=lval(e); tmp2=tmp1; tmp1 OP 1; tmp2
  3123         // or
  3124         // translate to tmp1=lval(e); tmp2=tmp1; (typeof tree)tmp1 OP 1; tmp2
  3125         // where OP is += or -=
  3126         final boolean cast = TreeInfo.skipParens(tree.arg).hasTag(TYPECAST);
  3127         return abstractLval(tree.arg, new TreeBuilder() {
  3128                 public JCTree build(final JCTree tmp1) {
  3129                     return abstractRval(tmp1, tree.arg.type, new TreeBuilder() {
  3130                             public JCTree build(final JCTree tmp2) {
  3131                                 JCTree.Tag opcode = (tree.hasTag(POSTINC))
  3132                                     ? PLUS_ASG : MINUS_ASG;
  3133                                 JCTree lhs = cast
  3134                                     ? make.TypeCast(tree.arg.type, (JCExpression)tmp1)
  3135                                     : tmp1;
  3136                                 JCTree update = makeAssignop(opcode,
  3137                                                              lhs,
  3138                                                              make.Literal(1));
  3139                                 return makeComma(update, tmp2);
  3141                         });
  3143             });
  3146     public void visitUnary(JCUnary tree) {
  3147         boolean isUpdateOperator = tree.getTag().isIncOrDecUnaryOp();
  3148         if (isUpdateOperator && !tree.arg.type.isPrimitive()) {
  3149             switch(tree.getTag()) {
  3150             case PREINC:            // ++ e
  3151                     // translate to e += 1
  3152             case PREDEC:            // -- e
  3153                     // translate to e -= 1
  3155                     JCTree.Tag opcode = (tree.hasTag(PREINC))
  3156                         ? PLUS_ASG : MINUS_ASG;
  3157                     JCAssignOp newTree = makeAssignop(opcode,
  3158                                                     tree.arg,
  3159                                                     make.Literal(1));
  3160                     result = translate(newTree, tree.type);
  3161                     return;
  3163             case POSTINC:           // e ++
  3164             case POSTDEC:           // e --
  3166                     result = translate(lowerBoxedPostop(tree), tree.type);
  3167                     return;
  3170             throw new AssertionError(tree);
  3173         tree.arg = boxIfNeeded(translate(tree.arg, tree), tree.type);
  3175         if (tree.hasTag(NOT) && tree.arg.type.constValue() != null) {
  3176             tree.type = cfolder.fold1(bool_not, tree.arg.type);
  3179         // If translated left hand side is an Apply, we are
  3180         // seeing an access method invocation. In this case, return
  3181         // that access method invocation as result.
  3182         if (isUpdateOperator && tree.arg.hasTag(APPLY)) {
  3183             result = tree.arg;
  3184         } else {
  3185             result = tree;
  3189     public void visitBinary(JCBinary tree) {
  3190         List<Type> formals = tree.operator.type.getParameterTypes();
  3191         JCTree lhs = tree.lhs = translate(tree.lhs, formals.head);
  3192         switch (tree.getTag()) {
  3193         case OR:
  3194             if (lhs.type.isTrue()) {
  3195                 result = lhs;
  3196                 return;
  3198             if (lhs.type.isFalse()) {
  3199                 result = translate(tree.rhs, formals.tail.head);
  3200                 return;
  3202             break;
  3203         case AND:
  3204             if (lhs.type.isFalse()) {
  3205                 result = lhs;
  3206                 return;
  3208             if (lhs.type.isTrue()) {
  3209                 result = translate(tree.rhs, formals.tail.head);
  3210                 return;
  3212             break;
  3214         tree.rhs = translate(tree.rhs, formals.tail.head);
  3215         result = tree;
  3218     public void visitIdent(JCIdent tree) {
  3219         result = access(tree.sym, tree, enclOp, false);
  3222     /** Translate away the foreach loop.  */
  3223     public void visitForeachLoop(JCEnhancedForLoop tree) {
  3224         if (types.elemtype(tree.expr.type) == null)
  3225             visitIterableForeachLoop(tree);
  3226         else
  3227             visitArrayForeachLoop(tree);
  3229         // where
  3230         /**
  3231          * A statement of the form
  3233          * <pre>
  3234          *     for ( T v : arrayexpr ) stmt;
  3235          * </pre>
  3237          * (where arrayexpr is of an array type) gets translated to
  3239          * <pre>{@code
  3240          *     for ( { arraytype #arr = arrayexpr;
  3241          *             int #len = array.length;
  3242          *             int #i = 0; };
  3243          *           #i < #len; i$++ ) {
  3244          *         T v = arr$[#i];
  3245          *         stmt;
  3246          *     }
  3247          * }</pre>
  3249          * where #arr, #len, and #i are freshly named synthetic local variables.
  3250          */
  3251         private void visitArrayForeachLoop(JCEnhancedForLoop tree) {
  3252             make_at(tree.expr.pos());
  3253             VarSymbol arraycache = new VarSymbol(0,
  3254                                                  names.fromString("arr" + target.syntheticNameChar()),
  3255                                                  tree.expr.type,
  3256                                                  currentMethodSym);
  3257             JCStatement arraycachedef = make.VarDef(arraycache, tree.expr);
  3258             VarSymbol lencache = new VarSymbol(0,
  3259                                                names.fromString("len" + target.syntheticNameChar()),
  3260                                                syms.intType,
  3261                                                currentMethodSym);
  3262             JCStatement lencachedef = make.
  3263                 VarDef(lencache, make.Select(make.Ident(arraycache), syms.lengthVar));
  3264             VarSymbol index = new VarSymbol(0,
  3265                                             names.fromString("i" + target.syntheticNameChar()),
  3266                                             syms.intType,
  3267                                             currentMethodSym);
  3269             JCVariableDecl indexdef = make.VarDef(index, make.Literal(INT, 0));
  3270             indexdef.init.type = indexdef.type = syms.intType.constType(0);
  3272             List<JCStatement> loopinit = List.of(arraycachedef, lencachedef, indexdef);
  3273             JCBinary cond = makeBinary(LT, make.Ident(index), make.Ident(lencache));
  3275             JCExpressionStatement step = make.Exec(makeUnary(PREINC, make.Ident(index)));
  3277             Type elemtype = types.elemtype(tree.expr.type);
  3278             JCExpression loopvarinit = make.Indexed(make.Ident(arraycache),
  3279                                                     make.Ident(index)).setType(elemtype);
  3280             JCVariableDecl loopvardef = (JCVariableDecl)make.VarDef(tree.var.mods,
  3281                                                   tree.var.name,
  3282                                                   tree.var.vartype,
  3283                                                   loopvarinit).setType(tree.var.type);
  3284             loopvardef.sym = tree.var.sym;
  3285             JCBlock body = make.
  3286                 Block(0, List.of(loopvardef, tree.body));
  3288             result = translate(make.
  3289                                ForLoop(loopinit,
  3290                                        cond,
  3291                                        List.of(step),
  3292                                        body));
  3293             patchTargets(body, tree, result);
  3295         /** Patch up break and continue targets. */
  3296         private void patchTargets(JCTree body, final JCTree src, final JCTree dest) {
  3297             class Patcher extends TreeScanner {
  3298                 public void visitBreak(JCBreak tree) {
  3299                     if (tree.target == src)
  3300                         tree.target = dest;
  3302                 public void visitContinue(JCContinue tree) {
  3303                     if (tree.target == src)
  3304                         tree.target = dest;
  3306                 public void visitClassDef(JCClassDecl tree) {}
  3308             new Patcher().scan(body);
  3310         /**
  3311          * A statement of the form
  3313          * <pre>
  3314          *     for ( T v : coll ) stmt ;
  3315          * </pre>
  3317          * (where coll implements {@code Iterable<? extends T>}) gets translated to
  3319          * <pre>{@code
  3320          *     for ( Iterator<? extends T> #i = coll.iterator(); #i.hasNext(); ) {
  3321          *         T v = (T) #i.next();
  3322          *         stmt;
  3323          *     }
  3324          * }</pre>
  3326          * where #i is a freshly named synthetic local variable.
  3327          */
  3328         private void visitIterableForeachLoop(JCEnhancedForLoop tree) {
  3329             make_at(tree.expr.pos());
  3330             Type iteratorTarget = syms.objectType;
  3331             Type iterableType = types.asSuper(types.upperBound(tree.expr.type),
  3332                                               syms.iterableType.tsym);
  3333             if (iterableType.getTypeArguments().nonEmpty())
  3334                 iteratorTarget = types.erasure(iterableType.getTypeArguments().head);
  3335             Type eType = tree.expr.type;
  3336             tree.expr.type = types.erasure(eType);
  3337             if (eType.hasTag(TYPEVAR) && eType.getUpperBound().isCompound())
  3338                 tree.expr = make.TypeCast(types.erasure(iterableType), tree.expr);
  3339             Symbol iterator = lookupMethod(tree.expr.pos(),
  3340                                            names.iterator,
  3341                                            types.erasure(syms.iterableType),
  3342                                            List.<Type>nil());
  3343             VarSymbol itvar = new VarSymbol(0, names.fromString("i" + target.syntheticNameChar()),
  3344                                             types.erasure(iterator.type.getReturnType()),
  3345                                             currentMethodSym);
  3346             JCStatement init = make.
  3347                 VarDef(itvar,
  3348                        make.App(make.Select(tree.expr, iterator)));
  3349             Symbol hasNext = lookupMethod(tree.expr.pos(),
  3350                                           names.hasNext,
  3351                                           itvar.type,
  3352                                           List.<Type>nil());
  3353             JCMethodInvocation cond = make.App(make.Select(make.Ident(itvar), hasNext));
  3354             Symbol next = lookupMethod(tree.expr.pos(),
  3355                                        names.next,
  3356                                        itvar.type,
  3357                                        List.<Type>nil());
  3358             JCExpression vardefinit = make.App(make.Select(make.Ident(itvar), next));
  3359             if (tree.var.type.isPrimitive())
  3360                 vardefinit = make.TypeCast(types.upperBound(iteratorTarget), vardefinit);
  3361             else
  3362                 vardefinit = make.TypeCast(tree.var.type, vardefinit);
  3363             JCVariableDecl indexDef = (JCVariableDecl)make.VarDef(tree.var.mods,
  3364                                                   tree.var.name,
  3365                                                   tree.var.vartype,
  3366                                                   vardefinit).setType(tree.var.type);
  3367             indexDef.sym = tree.var.sym;
  3368             JCBlock body = make.Block(0, List.of(indexDef, tree.body));
  3369             body.endpos = TreeInfo.endPos(tree.body);
  3370             result = translate(make.
  3371                 ForLoop(List.of(init),
  3372                         cond,
  3373                         List.<JCExpressionStatement>nil(),
  3374                         body));
  3375             patchTargets(body, tree, result);
  3378     public void visitVarDef(JCVariableDecl tree) {
  3379         MethodSymbol oldMethodSym = currentMethodSym;
  3380         tree.mods = translate(tree.mods);
  3381         tree.vartype = translate(tree.vartype);
  3382         if (currentMethodSym == null) {
  3383             // A class or instance field initializer.
  3384             currentMethodSym =
  3385                 new MethodSymbol((tree.mods.flags&STATIC) | BLOCK,
  3386                                  names.empty, null,
  3387                                  currentClass);
  3389         if (tree.init != null) tree.init = translate(tree.init, tree.type);
  3390         result = tree;
  3391         currentMethodSym = oldMethodSym;
  3394     public void visitBlock(JCBlock tree) {
  3395         MethodSymbol oldMethodSym = currentMethodSym;
  3396         if (currentMethodSym == null) {
  3397             // Block is a static or instance initializer.
  3398             currentMethodSym =
  3399                 new MethodSymbol(tree.flags | BLOCK,
  3400                                  names.empty, null,
  3401                                  currentClass);
  3403         super.visitBlock(tree);
  3404         currentMethodSym = oldMethodSym;
  3407     public void visitDoLoop(JCDoWhileLoop tree) {
  3408         tree.body = translate(tree.body);
  3409         tree.cond = translate(tree.cond, syms.booleanType);
  3410         result = tree;
  3413     public void visitWhileLoop(JCWhileLoop tree) {
  3414         tree.cond = translate(tree.cond, syms.booleanType);
  3415         tree.body = translate(tree.body);
  3416         result = tree;
  3419     public void visitForLoop(JCForLoop tree) {
  3420         tree.init = translate(tree.init);
  3421         if (tree.cond != null)
  3422             tree.cond = translate(tree.cond, syms.booleanType);
  3423         tree.step = translate(tree.step);
  3424         tree.body = translate(tree.body);
  3425         result = tree;
  3428     public void visitReturn(JCReturn tree) {
  3429         if (tree.expr != null)
  3430             tree.expr = translate(tree.expr,
  3431                                   types.erasure(currentMethodDef
  3432                                                 .restype.type));
  3433         result = tree;
  3436     public void visitSwitch(JCSwitch tree) {
  3437         Type selsuper = types.supertype(tree.selector.type);
  3438         boolean enumSwitch = selsuper != null &&
  3439             (tree.selector.type.tsym.flags() & ENUM) != 0;
  3440         boolean stringSwitch = selsuper != null &&
  3441             types.isSameType(tree.selector.type, syms.stringType);
  3442         Type target = enumSwitch ? tree.selector.type :
  3443             (stringSwitch? syms.stringType : syms.intType);
  3444         tree.selector = translate(tree.selector, target);
  3445         tree.cases = translateCases(tree.cases);
  3446         if (enumSwitch) {
  3447             result = visitEnumSwitch(tree);
  3448         } else if (stringSwitch) {
  3449             result = visitStringSwitch(tree);
  3450         } else {
  3451             result = tree;
  3455     public JCTree visitEnumSwitch(JCSwitch tree) {
  3456         TypeSymbol enumSym = tree.selector.type.tsym;
  3457         EnumMapping map = mapForEnum(tree.pos(), enumSym);
  3458         make_at(tree.pos());
  3459         Symbol ordinalMethod = lookupMethod(tree.pos(),
  3460                                             names.ordinal,
  3461                                             tree.selector.type,
  3462                                             List.<Type>nil());
  3463         JCArrayAccess selector = make.Indexed(map.mapVar,
  3464                                         make.App(make.Select(tree.selector,
  3465                                                              ordinalMethod)));
  3466         ListBuffer<JCCase> cases = new ListBuffer<JCCase>();
  3467         for (JCCase c : tree.cases) {
  3468             if (c.pat != null) {
  3469                 VarSymbol label = (VarSymbol)TreeInfo.symbol(c.pat);
  3470                 JCLiteral pat = map.forConstant(label);
  3471                 cases.append(make.Case(pat, c.stats));
  3472             } else {
  3473                 cases.append(c);
  3476         JCSwitch enumSwitch = make.Switch(selector, cases.toList());
  3477         patchTargets(enumSwitch, tree, enumSwitch);
  3478         return enumSwitch;
  3481     public JCTree visitStringSwitch(JCSwitch tree) {
  3482         List<JCCase> caseList = tree.getCases();
  3483         int alternatives = caseList.size();
  3485         if (alternatives == 0) { // Strange but legal possibility
  3486             return make.at(tree.pos()).Exec(attr.makeNullCheck(tree.getExpression()));
  3487         } else {
  3488             /*
  3489              * The general approach used is to translate a single
  3490              * string switch statement into a series of two chained
  3491              * switch statements: the first a synthesized statement
  3492              * switching on the argument string's hash value and
  3493              * computing a string's position in the list of original
  3494              * case labels, if any, followed by a second switch on the
  3495              * computed integer value.  The second switch has the same
  3496              * code structure as the original string switch statement
  3497              * except that the string case labels are replaced with
  3498              * positional integer constants starting at 0.
  3500              * The first switch statement can be thought of as an
  3501              * inlined map from strings to their position in the case
  3502              * label list.  An alternate implementation would use an
  3503              * actual Map for this purpose, as done for enum switches.
  3505              * With some additional effort, it would be possible to
  3506              * use a single switch statement on the hash code of the
  3507              * argument, but care would need to be taken to preserve
  3508              * the proper control flow in the presence of hash
  3509              * collisions and other complications, such as
  3510              * fallthroughs.  Switch statements with one or two
  3511              * alternatives could also be specially translated into
  3512              * if-then statements to omit the computation of the hash
  3513              * code.
  3515              * The generated code assumes that the hashing algorithm
  3516              * of String is the same in the compilation environment as
  3517              * in the environment the code will run in.  The string
  3518              * hashing algorithm in the SE JDK has been unchanged
  3519              * since at least JDK 1.2.  Since the algorithm has been
  3520              * specified since that release as well, it is very
  3521              * unlikely to be changed in the future.
  3523              * Different hashing algorithms, such as the length of the
  3524              * strings or a perfect hashing algorithm over the
  3525              * particular set of case labels, could potentially be
  3526              * used instead of String.hashCode.
  3527              */
  3529             ListBuffer<JCStatement> stmtList = new ListBuffer<JCStatement>();
  3531             // Map from String case labels to their original position in
  3532             // the list of case labels.
  3533             Map<String, Integer> caseLabelToPosition =
  3534                 new LinkedHashMap<String, Integer>(alternatives + 1, 1.0f);
  3536             // Map of hash codes to the string case labels having that hashCode.
  3537             Map<Integer, Set<String>> hashToString =
  3538                 new LinkedHashMap<Integer, Set<String>>(alternatives + 1, 1.0f);
  3540             int casePosition = 0;
  3541             for(JCCase oneCase : caseList) {
  3542                 JCExpression expression = oneCase.getExpression();
  3544                 if (expression != null) { // expression for a "default" case is null
  3545                     String labelExpr = (String) expression.type.constValue();
  3546                     Integer mapping = caseLabelToPosition.put(labelExpr, casePosition);
  3547                     Assert.checkNull(mapping);
  3548                     int hashCode = labelExpr.hashCode();
  3550                     Set<String> stringSet = hashToString.get(hashCode);
  3551                     if (stringSet == null) {
  3552                         stringSet = new LinkedHashSet<String>(1, 1.0f);
  3553                         stringSet.add(labelExpr);
  3554                         hashToString.put(hashCode, stringSet);
  3555                     } else {
  3556                         boolean added = stringSet.add(labelExpr);
  3557                         Assert.check(added);
  3560                 casePosition++;
  3563             // Synthesize a switch statement that has the effect of
  3564             // mapping from a string to the integer position of that
  3565             // string in the list of case labels.  This is done by
  3566             // switching on the hashCode of the string followed by an
  3567             // if-then-else chain comparing the input for equality
  3568             // with all the case labels having that hash value.
  3570             /*
  3571              * s$ = top of stack;
  3572              * tmp$ = -1;
  3573              * switch($s.hashCode()) {
  3574              *     case caseLabel.hashCode:
  3575              *         if (s$.equals("caseLabel_1")
  3576              *           tmp$ = caseLabelToPosition("caseLabel_1");
  3577              *         else if (s$.equals("caseLabel_2"))
  3578              *           tmp$ = caseLabelToPosition("caseLabel_2");
  3579              *         ...
  3580              *         break;
  3581              * ...
  3582              * }
  3583              */
  3585             VarSymbol dollar_s = new VarSymbol(FINAL|SYNTHETIC,
  3586                                                names.fromString("s" + tree.pos + target.syntheticNameChar()),
  3587                                                syms.stringType,
  3588                                                currentMethodSym);
  3589             stmtList.append(make.at(tree.pos()).VarDef(dollar_s, tree.getExpression()).setType(dollar_s.type));
  3591             VarSymbol dollar_tmp = new VarSymbol(SYNTHETIC,
  3592                                                  names.fromString("tmp" + tree.pos + target.syntheticNameChar()),
  3593                                                  syms.intType,
  3594                                                  currentMethodSym);
  3595             JCVariableDecl dollar_tmp_def =
  3596                 (JCVariableDecl)make.VarDef(dollar_tmp, make.Literal(INT, -1)).setType(dollar_tmp.type);
  3597             dollar_tmp_def.init.type = dollar_tmp.type = syms.intType;
  3598             stmtList.append(dollar_tmp_def);
  3599             ListBuffer<JCCase> caseBuffer = ListBuffer.lb();
  3600             // hashCode will trigger nullcheck on original switch expression
  3601             JCMethodInvocation hashCodeCall = makeCall(make.Ident(dollar_s),
  3602                                                        names.hashCode,
  3603                                                        List.<JCExpression>nil()).setType(syms.intType);
  3604             JCSwitch switch1 = make.Switch(hashCodeCall,
  3605                                         caseBuffer.toList());
  3606             for(Map.Entry<Integer, Set<String>> entry : hashToString.entrySet()) {
  3607                 int hashCode = entry.getKey();
  3608                 Set<String> stringsWithHashCode = entry.getValue();
  3609                 Assert.check(stringsWithHashCode.size() >= 1);
  3611                 JCStatement elsepart = null;
  3612                 for(String caseLabel : stringsWithHashCode ) {
  3613                     JCMethodInvocation stringEqualsCall = makeCall(make.Ident(dollar_s),
  3614                                                                    names.equals,
  3615                                                                    List.<JCExpression>of(make.Literal(caseLabel)));
  3616                     elsepart = make.If(stringEqualsCall,
  3617                                        make.Exec(make.Assign(make.Ident(dollar_tmp),
  3618                                                              make.Literal(caseLabelToPosition.get(caseLabel))).
  3619                                                  setType(dollar_tmp.type)),
  3620                                        elsepart);
  3623                 ListBuffer<JCStatement> lb = ListBuffer.lb();
  3624                 JCBreak breakStmt = make.Break(null);
  3625                 breakStmt.target = switch1;
  3626                 lb.append(elsepart).append(breakStmt);
  3628                 caseBuffer.append(make.Case(make.Literal(hashCode), lb.toList()));
  3631             switch1.cases = caseBuffer.toList();
  3632             stmtList.append(switch1);
  3634             // Make isomorphic switch tree replacing string labels
  3635             // with corresponding integer ones from the label to
  3636             // position map.
  3638             ListBuffer<JCCase> lb = ListBuffer.lb();
  3639             JCSwitch switch2 = make.Switch(make.Ident(dollar_tmp), lb.toList());
  3640             for(JCCase oneCase : caseList ) {
  3641                 // Rewire up old unlabeled break statements to the
  3642                 // replacement switch being created.
  3643                 patchTargets(oneCase, tree, switch2);
  3645                 boolean isDefault = (oneCase.getExpression() == null);
  3646                 JCExpression caseExpr;
  3647                 if (isDefault)
  3648                     caseExpr = null;
  3649                 else {
  3650                     caseExpr = make.Literal(caseLabelToPosition.get((String)TreeInfo.skipParens(oneCase.
  3651                                                                                                 getExpression()).
  3652                                                                     type.constValue()));
  3655                 lb.append(make.Case(caseExpr,
  3656                                     oneCase.getStatements()));
  3659             switch2.cases = lb.toList();
  3660             stmtList.append(switch2);
  3662             return make.Block(0L, stmtList.toList());
  3666     public void visitNewArray(JCNewArray tree) {
  3667         tree.elemtype = translate(tree.elemtype);
  3668         for (List<JCExpression> t = tree.dims; t.tail != null; t = t.tail)
  3669             if (t.head != null) t.head = translate(t.head, syms.intType);
  3670         tree.elems = translate(tree.elems, types.elemtype(tree.type));
  3671         result = tree;
  3674     public void visitSelect(JCFieldAccess tree) {
  3675         // need to special case-access of the form C.super.x
  3676         // these will always need an access method, unless C
  3677         // is a default interface subclassed by the current class.
  3678         boolean qualifiedSuperAccess =
  3679             tree.selected.hasTag(SELECT) &&
  3680             TreeInfo.name(tree.selected) == names._super &&
  3681             !types.isDirectSuperInterface(((JCFieldAccess)tree.selected).selected.type.tsym, currentClass);
  3682         tree.selected = translate(tree.selected);
  3683         if (tree.name == names._class) {
  3684             result = classOf(tree.selected);
  3686         else if (tree.name == names._super &&
  3687                 types.isDirectSuperInterface(tree.selected.type.tsym, currentClass)) {
  3688             //default super call!! Not a classic qualified super call
  3689             TypeSymbol supSym = tree.selected.type.tsym;
  3690             Assert.checkNonNull(types.asSuper(currentClass.type, supSym));
  3691             result = tree;
  3693         else if (tree.name == names._this || tree.name == names._super) {
  3694             result = makeThis(tree.pos(), tree.selected.type.tsym);
  3696         else
  3697             result = access(tree.sym, tree, enclOp, qualifiedSuperAccess);
  3700     public void visitLetExpr(LetExpr tree) {
  3701         tree.defs = translateVarDefs(tree.defs);
  3702         tree.expr = translate(tree.expr, tree.type);
  3703         result = tree;
  3706     // There ought to be nothing to rewrite here;
  3707     // we don't generate code.
  3708     public void visitAnnotation(JCAnnotation tree) {
  3709         result = tree;
  3712     @Override
  3713     public void visitTry(JCTry tree) {
  3714         if (tree.resources.isEmpty()) {
  3715             super.visitTry(tree);
  3716         } else {
  3717             result = makeTwrTry(tree);
  3721 /**************************************************************************
  3722  * main method
  3723  *************************************************************************/
  3725     /** Translate a toplevel class and return a list consisting of
  3726      *  the translated class and translated versions of all inner classes.
  3727      *  @param env   The attribution environment current at the class definition.
  3728      *               We need this for resolving some additional symbols.
  3729      *  @param cdef  The tree representing the class definition.
  3730      */
  3731     public List<JCTree> translateTopLevelClass(Env<AttrContext> env, JCTree cdef, TreeMaker make) {
  3732         ListBuffer<JCTree> translated = null;
  3733         try {
  3734             attrEnv = env;
  3735             this.make = make;
  3736             endPosTable = env.toplevel.endPositions;
  3737             currentClass = null;
  3738             currentMethodDef = null;
  3739             outermostClassDef = (cdef.hasTag(CLASSDEF)) ? (JCClassDecl)cdef : null;
  3740             outermostMemberDef = null;
  3741             this.translated = new ListBuffer<JCTree>();
  3742             classdefs = new HashMap<ClassSymbol,JCClassDecl>();
  3743             actualSymbols = new HashMap<Symbol,Symbol>();
  3744             freevarCache = new HashMap<ClassSymbol,List<VarSymbol>>();
  3745             proxies = new Scope(syms.noSymbol);
  3746             twrVars = new Scope(syms.noSymbol);
  3747             outerThisStack = List.nil();
  3748             accessNums = new HashMap<Symbol,Integer>();
  3749             accessSyms = new HashMap<Symbol,MethodSymbol[]>();
  3750             accessConstrs = new HashMap<Symbol,MethodSymbol>();
  3751             accessConstrTags = List.nil();
  3752             accessed = new ListBuffer<Symbol>();
  3753             translate(cdef, (JCExpression)null);
  3754             for (List<Symbol> l = accessed.toList(); l.nonEmpty(); l = l.tail)
  3755                 makeAccessible(l.head);
  3756             for (EnumMapping map : enumSwitchMap.values())
  3757                 map.translate();
  3758             checkConflicts(this.translated.toList());
  3759             checkAccessConstructorTags();
  3760             translated = this.translated;
  3761         } finally {
  3762             // note that recursive invocations of this method fail hard
  3763             attrEnv = null;
  3764             this.make = null;
  3765             endPosTable = null;
  3766             currentClass = null;
  3767             currentMethodDef = null;
  3768             outermostClassDef = null;
  3769             outermostMemberDef = null;
  3770             this.translated = null;
  3771             classdefs = null;
  3772             actualSymbols = null;
  3773             freevarCache = null;
  3774             proxies = null;
  3775             outerThisStack = null;
  3776             accessNums = null;
  3777             accessSyms = null;
  3778             accessConstrs = null;
  3779             accessConstrTags = null;
  3780             accessed = null;
  3781             enumSwitchMap.clear();
  3783         return translated.toList();
  3786     //////////////////////////////////////////////////////////////
  3787     // The following contributed by Borland for bootstrapping purposes
  3788     //////////////////////////////////////////////////////////////
  3789     private void addEnumCompatibleMembers(JCClassDecl cdef) {
  3790         make_at(null);
  3792         // Add the special enum fields
  3793         VarSymbol ordinalFieldSym = addEnumOrdinalField(cdef);
  3794         VarSymbol nameFieldSym = addEnumNameField(cdef);
  3796         // Add the accessor methods for name and ordinal
  3797         MethodSymbol ordinalMethodSym = addEnumFieldOrdinalMethod(cdef, ordinalFieldSym);
  3798         MethodSymbol nameMethodSym = addEnumFieldNameMethod(cdef, nameFieldSym);
  3800         // Add the toString method
  3801         addEnumToString(cdef, nameFieldSym);
  3803         // Add the compareTo method
  3804         addEnumCompareTo(cdef, ordinalFieldSym);
  3807     private VarSymbol addEnumOrdinalField(JCClassDecl cdef) {
  3808         VarSymbol ordinal = new VarSymbol(PRIVATE|FINAL|SYNTHETIC,
  3809                                           names.fromString("$ordinal"),
  3810                                           syms.intType,
  3811                                           cdef.sym);
  3812         cdef.sym.members().enter(ordinal);
  3813         cdef.defs = cdef.defs.prepend(make.VarDef(ordinal, null));
  3814         return ordinal;
  3817     private VarSymbol addEnumNameField(JCClassDecl cdef) {
  3818         VarSymbol name = new VarSymbol(PRIVATE|FINAL|SYNTHETIC,
  3819                                           names.fromString("$name"),
  3820                                           syms.stringType,
  3821                                           cdef.sym);
  3822         cdef.sym.members().enter(name);
  3823         cdef.defs = cdef.defs.prepend(make.VarDef(name, null));
  3824         return name;
  3827     private MethodSymbol addEnumFieldOrdinalMethod(JCClassDecl cdef, VarSymbol ordinalSymbol) {
  3828         // Add the accessor methods for ordinal
  3829         Symbol ordinalSym = lookupMethod(cdef.pos(),
  3830                                          names.ordinal,
  3831                                          cdef.type,
  3832                                          List.<Type>nil());
  3834         Assert.check(ordinalSym instanceof MethodSymbol);
  3836         JCStatement ret = make.Return(make.Ident(ordinalSymbol));
  3837         cdef.defs = cdef.defs.append(make.MethodDef((MethodSymbol)ordinalSym,
  3838                                                     make.Block(0L, List.of(ret))));
  3840         return (MethodSymbol)ordinalSym;
  3843     private MethodSymbol addEnumFieldNameMethod(JCClassDecl cdef, VarSymbol nameSymbol) {
  3844         // Add the accessor methods for name
  3845         Symbol nameSym = lookupMethod(cdef.pos(),
  3846                                    names._name,
  3847                                    cdef.type,
  3848                                    List.<Type>nil());
  3850         Assert.check(nameSym instanceof MethodSymbol);
  3852         JCStatement ret = make.Return(make.Ident(nameSymbol));
  3854         cdef.defs = cdef.defs.append(make.MethodDef((MethodSymbol)nameSym,
  3855                                                     make.Block(0L, List.of(ret))));
  3857         return (MethodSymbol)nameSym;
  3860     private MethodSymbol addEnumToString(JCClassDecl cdef,
  3861                                          VarSymbol nameSymbol) {
  3862         Symbol toStringSym = lookupMethod(cdef.pos(),
  3863                                           names.toString,
  3864                                           cdef.type,
  3865                                           List.<Type>nil());
  3867         JCTree toStringDecl = null;
  3868         if (toStringSym != null)
  3869             toStringDecl = TreeInfo.declarationFor(toStringSym, cdef);
  3871         if (toStringDecl != null)
  3872             return (MethodSymbol)toStringSym;
  3874         JCStatement ret = make.Return(make.Ident(nameSymbol));
  3876         JCTree resTypeTree = make.Type(syms.stringType);
  3878         MethodType toStringType = new MethodType(List.<Type>nil(),
  3879                                                  syms.stringType,
  3880                                                  List.<Type>nil(),
  3881                                                  cdef.sym);
  3882         toStringSym = new MethodSymbol(PUBLIC,
  3883                                        names.toString,
  3884                                        toStringType,
  3885                                        cdef.type.tsym);
  3886         toStringDecl = make.MethodDef((MethodSymbol)toStringSym,
  3887                                       make.Block(0L, List.of(ret)));
  3889         cdef.defs = cdef.defs.prepend(toStringDecl);
  3890         cdef.sym.members().enter(toStringSym);
  3892         return (MethodSymbol)toStringSym;
  3895     private MethodSymbol addEnumCompareTo(JCClassDecl cdef, VarSymbol ordinalSymbol) {
  3896         Symbol compareToSym = lookupMethod(cdef.pos(),
  3897                                    names.compareTo,
  3898                                    cdef.type,
  3899                                    List.of(cdef.sym.type));
  3901         Assert.check(compareToSym instanceof MethodSymbol);
  3903         JCMethodDecl compareToDecl = (JCMethodDecl) TreeInfo.declarationFor(compareToSym, cdef);
  3905         ListBuffer<JCStatement> blockStatements = new ListBuffer<JCStatement>();
  3907         JCModifiers mod1 = make.Modifiers(0L);
  3908         Name oName = names.fromString("o");
  3909         JCVariableDecl par1 = make.Param(oName, cdef.type, compareToSym);
  3911         JCIdent paramId1 = make.Ident(names.java_lang_Object);
  3912         paramId1.type = cdef.type;
  3913         paramId1.sym = par1.sym;
  3915         ((MethodSymbol)compareToSym).params = List.of(par1.sym);
  3917         JCIdent par1UsageId = make.Ident(par1.sym);
  3918         JCIdent castTargetIdent = make.Ident(cdef.sym);
  3919         JCTypeCast cast = make.TypeCast(castTargetIdent, par1UsageId);
  3920         cast.setType(castTargetIdent.type);
  3922         Name otherName = names.fromString("other");
  3924         VarSymbol otherVarSym = new VarSymbol(mod1.flags,
  3925                                               otherName,
  3926                                               cdef.type,
  3927                                               compareToSym);
  3928         JCVariableDecl otherVar = make.VarDef(otherVarSym, cast);
  3929         blockStatements.append(otherVar);
  3931         JCIdent id1 = make.Ident(ordinalSymbol);
  3933         JCIdent fLocUsageId = make.Ident(otherVarSym);
  3934         JCExpression sel = make.Select(fLocUsageId, ordinalSymbol);
  3935         JCBinary bin = makeBinary(MINUS, id1, sel);
  3936         JCReturn ret = make.Return(bin);
  3937         blockStatements.append(ret);
  3938         JCMethodDecl compareToMethod = make.MethodDef((MethodSymbol)compareToSym,
  3939                                                    make.Block(0L,
  3940                                                               blockStatements.toList()));
  3941         compareToMethod.params = List.of(par1);
  3942         cdef.defs = cdef.defs.append(compareToMethod);
  3944         return (MethodSymbol)compareToSym;
  3946     //////////////////////////////////////////////////////////////
  3947     // The above contributed by Borland for bootstrapping purposes
  3948     //////////////////////////////////////////////////////////////

mercurial