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

Thu, 29 Jul 2010 15:56:25 +0100

author
mcimadamore
date
Thu, 29 Jul 2010 15:56:25 +0100
changeset 615
36c4ec4525b4
parent 609
13354e1abba7
child 657
70ebdef189c9
permissions
-rw-r--r--

6938454: Unable to determine generic type in program that compiles under Java 6
Summary: a redundant dubtyping check causes spurious inference failure
Reviewed-by: jjg

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

mercurial