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

Tue, 08 Nov 2011 11:51:05 -0800

author
jjg
date
Tue, 08 Nov 2011 11:51:05 -0800
changeset 1127
ca49d50318dc
parent 1086
f595d8bc0599
child 1138
7375d4979bd3
permissions
-rw-r--r--

6921494: provide way to print javac tree tag values
Reviewed-by: jjg, mcimadamore
Contributed-by: vicenterz@yahoo.es

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

mercurial