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

Tue, 15 Oct 2013 15:57:13 -0700

author
jjg
date
Tue, 15 Oct 2013 15:57:13 -0700
changeset 2134
b0c086cd4520
parent 2098
0be3f1820e8b
child 2183
75c8cde12ab6
permissions
-rw-r--r--

8026564: import changes from type-annotations forest
Reviewed-by: jjg
Contributed-by: wdietl@gmail.com, steve.sides@oracle.com

     1 /*
     2  * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    26 package com.sun.tools.javac.comp;
    28 import java.util.*;
    30 import com.sun.tools.javac.code.*;
    31 import com.sun.tools.javac.code.Type.AnnotatedType;
    32 import com.sun.tools.javac.jvm.*;
    33 import com.sun.tools.javac.main.Option.PkgInfo;
    34 import com.sun.tools.javac.tree.*;
    35 import com.sun.tools.javac.util.*;
    36 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    37 import com.sun.tools.javac.util.List;
    39 import com.sun.tools.javac.code.Symbol.*;
    40 import com.sun.tools.javac.tree.JCTree.*;
    41 import com.sun.tools.javac.code.Type.*;
    43 import com.sun.tools.javac.jvm.Target;
    44 import com.sun.tools.javac.tree.EndPosTable;
    46 import static com.sun.tools.javac.code.Flags.*;
    47 import static com.sun.tools.javac.code.Flags.BLOCK;
    48 import static com.sun.tools.javac.code.Kinds.*;
    49 import static com.sun.tools.javac.code.TypeTag.*;
    50 import static com.sun.tools.javac.jvm.ByteCodes.*;
    51 import static com.sun.tools.javac.tree.JCTree.Tag.*;
    53 /** This pass translates away some syntactic sugar: inner classes,
    54  *  class literals, assertions, foreach loops, etc.
    55  *
    56  *  <p><b>This is NOT part of any supported API.
    57  *  If you write code that depends on this, you do so at your own risk.
    58  *  This code and its internal interfaces are subject to change or
    59  *  deletion without notice.</b>
    60  */
    61 public class Lower extends TreeTranslator {
    62     protected static final Context.Key<Lower> lowerKey =
    63         new Context.Key<Lower>();
    65     public static Lower instance(Context context) {
    66         Lower instance = context.get(lowerKey);
    67         if (instance == null)
    68             instance = new Lower(context);
    69         return instance;
    70     }
    72     private Names names;
    73     private Log log;
    74     private Symtab syms;
    75     private Resolve rs;
    76     private Check chk;
    77     private Attr attr;
    78     private TreeMaker make;
    79     private DiagnosticPosition make_pos;
    80     private ClassWriter writer;
    81     private ClassReader reader;
    82     private ConstFold cfolder;
    83     private Target target;
    84     private Source source;
    85     private boolean allowEnums;
    86     private final Name dollarAssertionsDisabled;
    87     private final Name classDollar;
    88     private Types types;
    89     private boolean debugLower;
    90     private PkgInfo pkginfoOpt;
    92     protected Lower(Context context) {
    93         context.put(lowerKey, this);
    94         names = Names.instance(context);
    95         log = Log.instance(context);
    96         syms = Symtab.instance(context);
    97         rs = Resolve.instance(context);
    98         chk = Check.instance(context);
    99         attr = Attr.instance(context);
   100         make = TreeMaker.instance(context);
   101         writer = ClassWriter.instance(context);
   102         reader = ClassReader.instance(context);
   103         cfolder = ConstFold.instance(context);
   104         target = Target.instance(context);
   105         source = Source.instance(context);
   106         allowEnums = source.allowEnums();
   107         dollarAssertionsDisabled = names.
   108             fromString(target.syntheticNameChar() + "assertionsDisabled");
   109         classDollar = names.
   110             fromString("class" + target.syntheticNameChar());
   112         types = Types.instance(context);
   113         Options options = Options.instance(context);
   114         debugLower = options.isSet("debuglower");
   115         pkginfoOpt = PkgInfo.get(options);
   116     }
   118     /** The currently enclosing class.
   119      */
   120     ClassSymbol currentClass;
   122     /** A queue of all translated classes.
   123      */
   124     ListBuffer<JCTree> translated;
   126     /** Environment for symbol lookup, set by translateTopLevelClass.
   127      */
   128     Env<AttrContext> attrEnv;
   130     /** A hash table mapping syntax trees to their ending source positions.
   131      */
   132     EndPosTable endPosTable;
   134 /**************************************************************************
   135  * Global mappings
   136  *************************************************************************/
   138     /** A hash table mapping local classes to their definitions.
   139      */
   140     Map<ClassSymbol, JCClassDecl> classdefs;
   142     /** A hash table mapping local classes to a list of pruned trees.
   143      */
   144     public Map<ClassSymbol, List<JCTree>> prunedTree = new WeakHashMap<ClassSymbol, List<JCTree>>();
   146     /** A hash table mapping virtual accessed symbols in outer subclasses
   147      *  to the actually referred symbol in superclasses.
   148      */
   149     Map<Symbol,Symbol> actualSymbols;
   151     /** The current method definition.
   152      */
   153     JCMethodDecl currentMethodDef;
   155     /** The current method symbol.
   156      */
   157     MethodSymbol currentMethodSym;
   159     /** The currently enclosing outermost class definition.
   160      */
   161     JCClassDecl outermostClassDef;
   163     /** The currently enclosing outermost member definition.
   164      */
   165     JCTree outermostMemberDef;
   167     /** A map from local variable symbols to their translation (as per LambdaToMethod).
   168      * This is required when a capturing local class is created from a lambda (in which
   169      * case the captured symbols should be replaced with the translated lambda symbols).
   170      */
   171     Map<Symbol, Symbol> lambdaTranslationMap = null;
   173     /** A navigator class for assembling a mapping from local class symbols
   174      *  to class definition trees.
   175      *  There is only one case; all other cases simply traverse down the tree.
   176      */
   177     class ClassMap extends TreeScanner {
   179         /** All encountered class defs are entered into classdefs table.
   180          */
   181         public void visitClassDef(JCClassDecl tree) {
   182             classdefs.put(tree.sym, tree);
   183             super.visitClassDef(tree);
   184         }
   185     }
   186     ClassMap classMap = new ClassMap();
   188     /** Map a class symbol to its definition.
   189      *  @param c    The class symbol of which we want to determine the definition.
   190      */
   191     JCClassDecl classDef(ClassSymbol c) {
   192         // First lookup the class in the classdefs table.
   193         JCClassDecl def = classdefs.get(c);
   194         if (def == null && outermostMemberDef != null) {
   195             // If this fails, traverse outermost member definition, entering all
   196             // local classes into classdefs, and try again.
   197             classMap.scan(outermostMemberDef);
   198             def = classdefs.get(c);
   199         }
   200         if (def == null) {
   201             // If this fails, traverse outermost class definition, entering all
   202             // local classes into classdefs, and try again.
   203             classMap.scan(outermostClassDef);
   204             def = classdefs.get(c);
   205         }
   206         return def;
   207     }
   209     /** A hash table mapping class symbols to lists of free variables.
   210      *  accessed by them. Only free variables of the method immediately containing
   211      *  a class are associated with that class.
   212      */
   213     Map<ClassSymbol,List<VarSymbol>> freevarCache;
   215     /** A navigator class for collecting the free variables accessed
   216      *  from a local class. There is only one case; all other cases simply
   217      *  traverse down the tree. This class doesn't deal with the specific
   218      *  of Lower - it's an abstract visitor that is meant to be reused in
   219      *  order to share the local variable capture logic.
   220      */
   221     abstract class BasicFreeVarCollector extends TreeScanner {
   223         /** Add all free variables of class c to fvs list
   224          *  unless they are already there.
   225          */
   226         abstract void addFreeVars(ClassSymbol c);
   228         /** If tree refers to a variable in owner of local class, add it to
   229          *  free variables list.
   230          */
   231         public void visitIdent(JCIdent tree) {
   232             visitSymbol(tree.sym);
   233         }
   234         // where
   235         abstract void visitSymbol(Symbol _sym);
   237         /** If tree refers to a class instance creation expression
   238          *  add all free variables of the freshly created class.
   239          */
   240         public void visitNewClass(JCNewClass tree) {
   241             ClassSymbol c = (ClassSymbol)tree.constructor.owner;
   242             addFreeVars(c);
   243             super.visitNewClass(tree);
   244         }
   246         /** If tree refers to a superclass constructor call,
   247          *  add all free variables of the superclass.
   248          */
   249         public void visitApply(JCMethodInvocation tree) {
   250             if (TreeInfo.name(tree.meth) == names._super) {
   251                 addFreeVars((ClassSymbol) TreeInfo.symbol(tree.meth).owner);
   252             }
   253             super.visitApply(tree);
   254         }
   255     }
   257     /**
   258      * Lower-specific subclass of {@code BasicFreeVarCollector}.
   259      */
   260     class FreeVarCollector extends BasicFreeVarCollector {
   262         /** The owner of the local class.
   263          */
   264         Symbol owner;
   266         /** The local class.
   267          */
   268         ClassSymbol clazz;
   270         /** The list of owner's variables accessed from within the local class,
   271          *  without any duplicates.
   272          */
   273         List<VarSymbol> fvs;
   275         FreeVarCollector(ClassSymbol clazz) {
   276             this.clazz = clazz;
   277             this.owner = clazz.owner;
   278             this.fvs = List.nil();
   279         }
   281         /** Add free variable to fvs list unless it is already there.
   282          */
   283         private void addFreeVar(VarSymbol v) {
   284             for (List<VarSymbol> l = fvs; l.nonEmpty(); l = l.tail)
   285                 if (l.head == v) return;
   286             fvs = fvs.prepend(v);
   287         }
   289         @Override
   290         void addFreeVars(ClassSymbol c) {
   291             List<VarSymbol> fvs = freevarCache.get(c);
   292             if (fvs != null) {
   293                 for (List<VarSymbol> l = fvs; l.nonEmpty(); l = l.tail) {
   294                     addFreeVar(l.head);
   295                 }
   296             }
   297         }
   299         @Override
   300         void visitSymbol(Symbol _sym) {
   301             Symbol sym = _sym;
   302             if (sym.kind == VAR || sym.kind == MTH) {
   303                 while (sym != null && sym.owner != owner)
   304                     sym = proxies.lookup(proxyName(sym.name)).sym;
   305                 if (sym != null && sym.owner == owner) {
   306                     VarSymbol v = (VarSymbol)sym;
   307                     if (v.getConstValue() == null) {
   308                         addFreeVar(v);
   309                     }
   310                 } else {
   311                     if (outerThisStack.head != null &&
   312                         outerThisStack.head != _sym)
   313                         visitSymbol(outerThisStack.head);
   314                 }
   315             }
   316         }
   318         /** If tree refers to a class instance creation expression
   319          *  add all free variables of the freshly created class.
   320          */
   321         public void visitNewClass(JCNewClass tree) {
   322             ClassSymbol c = (ClassSymbol)tree.constructor.owner;
   323             if (tree.encl == null &&
   324                 c.hasOuterInstance() &&
   325                 outerThisStack.head != null)
   326                 visitSymbol(outerThisStack.head);
   327             super.visitNewClass(tree);
   328         }
   330         /** If tree refers to a qualified this or super expression
   331          *  for anything but the current class, add the outer this
   332          *  stack as a free variable.
   333          */
   334         public void visitSelect(JCFieldAccess tree) {
   335             if ((tree.name == names._this || tree.name == names._super) &&
   336                 tree.selected.type.tsym != clazz &&
   337                 outerThisStack.head != null)
   338                 visitSymbol(outerThisStack.head);
   339             super.visitSelect(tree);
   340         }
   342         /** If tree refers to a superclass constructor call,
   343          *  add all free variables of the superclass.
   344          */
   345         public void visitApply(JCMethodInvocation tree) {
   346             if (TreeInfo.name(tree.meth) == names._super) {
   347                 Symbol constructor = TreeInfo.symbol(tree.meth);
   348                 ClassSymbol c = (ClassSymbol)constructor.owner;
   349                 if (c.hasOuterInstance() &&
   350                     !tree.meth.hasTag(SELECT) &&
   351                     outerThisStack.head != null)
   352                     visitSymbol(outerThisStack.head);
   353             }
   354             super.visitApply(tree);
   355         }
   356     }
   358     ClassSymbol ownerToCopyFreeVarsFrom(ClassSymbol c) {
   359         if (!c.isLocal()) {
   360             return null;
   361         }
   362         Symbol currentOwner = c.owner;
   363         while ((currentOwner.owner.kind & TYP) != 0 && currentOwner.isLocal()) {
   364             currentOwner = currentOwner.owner;
   365         }
   366         if ((currentOwner.owner.kind & (VAR | MTH)) != 0 && c.isSubClass(currentOwner, types)) {
   367             return (ClassSymbol)currentOwner;
   368         }
   369         return null;
   370     }
   372     /** Return the variables accessed from within a local class, which
   373      *  are declared in the local class' owner.
   374      *  (in reverse order of first access).
   375      */
   376     List<VarSymbol> freevars(ClassSymbol c)  {
   377         List<VarSymbol> fvs = freevarCache.get(c);
   378         if (fvs != null) {
   379             return fvs;
   380         }
   381         if ((c.owner.kind & (VAR | MTH)) != 0) {
   382             FreeVarCollector collector = new FreeVarCollector(c);
   383             collector.scan(classDef(c));
   384             fvs = collector.fvs;
   385             freevarCache.put(c, fvs);
   386             return fvs;
   387         } else {
   388             ClassSymbol owner = ownerToCopyFreeVarsFrom(c);
   389             if (owner != null) {
   390                 fvs = freevarCache.get(owner);
   391                 freevarCache.put(c, fvs);
   392                 return fvs;
   393             } else {
   394                 return List.nil();
   395             }
   396         }
   397     }
   399     Map<TypeSymbol,EnumMapping> enumSwitchMap = new LinkedHashMap<TypeSymbol,EnumMapping>();
   401     EnumMapping mapForEnum(DiagnosticPosition pos, TypeSymbol enumClass) {
   402         EnumMapping map = enumSwitchMap.get(enumClass);
   403         if (map == null)
   404             enumSwitchMap.put(enumClass, map = new EnumMapping(pos, enumClass));
   405         return map;
   406     }
   408     /** This map gives a translation table to be used for enum
   409      *  switches.
   410      *
   411      *  <p>For each enum that appears as the type of a switch
   412      *  expression, we maintain an EnumMapping to assist in the
   413      *  translation, as exemplified by the following example:
   414      *
   415      *  <p>we translate
   416      *  <pre>
   417      *          switch(colorExpression) {
   418      *          case red: stmt1;
   419      *          case green: stmt2;
   420      *          }
   421      *  </pre>
   422      *  into
   423      *  <pre>
   424      *          switch(Outer$0.$EnumMap$Color[colorExpression.ordinal()]) {
   425      *          case 1: stmt1;
   426      *          case 2: stmt2
   427      *          }
   428      *  </pre>
   429      *  with the auxiliary table initialized as follows:
   430      *  <pre>
   431      *          class Outer$0 {
   432      *              synthetic final int[] $EnumMap$Color = new int[Color.values().length];
   433      *              static {
   434      *                  try { $EnumMap$Color[red.ordinal()] = 1; } catch (NoSuchFieldError ex) {}
   435      *                  try { $EnumMap$Color[green.ordinal()] = 2; } catch (NoSuchFieldError ex) {}
   436      *              }
   437      *          }
   438      *  </pre>
   439      *  class EnumMapping provides mapping data and support methods for this translation.
   440      */
   441     class EnumMapping {
   442         EnumMapping(DiagnosticPosition pos, TypeSymbol forEnum) {
   443             this.forEnum = forEnum;
   444             this.values = new LinkedHashMap<VarSymbol,Integer>();
   445             this.pos = pos;
   446             Name varName = names
   447                 .fromString(target.syntheticNameChar() +
   448                             "SwitchMap" +
   449                             target.syntheticNameChar() +
   450                             writer.xClassName(forEnum.type).toString()
   451                             .replace('/', '.')
   452                             .replace('.', target.syntheticNameChar()));
   453             ClassSymbol outerCacheClass = outerCacheClass();
   454             this.mapVar = new VarSymbol(STATIC | SYNTHETIC | FINAL,
   455                                         varName,
   456                                         new ArrayType(syms.intType, syms.arrayClass),
   457                                         outerCacheClass);
   458             enterSynthetic(pos, mapVar, outerCacheClass.members());
   459         }
   461         DiagnosticPosition pos = null;
   463         // the next value to use
   464         int next = 1; // 0 (unused map elements) go to the default label
   466         // the enum for which this is a map
   467         final TypeSymbol forEnum;
   469         // the field containing the map
   470         final VarSymbol mapVar;
   472         // the mapped values
   473         final Map<VarSymbol,Integer> values;
   475         JCLiteral forConstant(VarSymbol v) {
   476             Integer result = values.get(v);
   477             if (result == null)
   478                 values.put(v, result = next++);
   479             return make.Literal(result);
   480         }
   482         // generate the field initializer for the map
   483         void translate() {
   484             make.at(pos.getStartPosition());
   485             JCClassDecl owner = classDef((ClassSymbol)mapVar.owner);
   487             // synthetic static final int[] $SwitchMap$Color = new int[Color.values().length];
   488             MethodSymbol valuesMethod = lookupMethod(pos,
   489                                                      names.values,
   490                                                      forEnum.type,
   491                                                      List.<Type>nil());
   492             JCExpression size = make // Color.values().length
   493                 .Select(make.App(make.QualIdent(valuesMethod)),
   494                         syms.lengthVar);
   495             JCExpression mapVarInit = make
   496                 .NewArray(make.Type(syms.intType), List.of(size), null)
   497                 .setType(new ArrayType(syms.intType, syms.arrayClass));
   499             // try { $SwitchMap$Color[red.ordinal()] = 1; } catch (java.lang.NoSuchFieldError ex) {}
   500             ListBuffer<JCStatement> stmts = new ListBuffer<JCStatement>();
   501             Symbol ordinalMethod = lookupMethod(pos,
   502                                                 names.ordinal,
   503                                                 forEnum.type,
   504                                                 List.<Type>nil());
   505             List<JCCatch> catcher = List.<JCCatch>nil()
   506                 .prepend(make.Catch(make.VarDef(new VarSymbol(PARAMETER, names.ex,
   507                                                               syms.noSuchFieldErrorType,
   508                                                               syms.noSymbol),
   509                                                 null),
   510                                     make.Block(0, List.<JCStatement>nil())));
   511             for (Map.Entry<VarSymbol,Integer> e : values.entrySet()) {
   512                 VarSymbol enumerator = e.getKey();
   513                 Integer mappedValue = e.getValue();
   514                 JCExpression assign = make
   515                     .Assign(make.Indexed(mapVar,
   516                                          make.App(make.Select(make.QualIdent(enumerator),
   517                                                               ordinalMethod))),
   518                             make.Literal(mappedValue))
   519                     .setType(syms.intType);
   520                 JCStatement exec = make.Exec(assign);
   521                 JCStatement _try = make.Try(make.Block(0, List.of(exec)), catcher, null);
   522                 stmts.append(_try);
   523             }
   525             owner.defs = owner.defs
   526                 .prepend(make.Block(STATIC, stmts.toList()))
   527                 .prepend(make.VarDef(mapVar, mapVarInit));
   528         }
   529     }
   532 /**************************************************************************
   533  * Tree building blocks
   534  *************************************************************************/
   536     /** Equivalent to make.at(pos.getStartPosition()) with side effect of caching
   537      *  pos as make_pos, for use in diagnostics.
   538      **/
   539     TreeMaker make_at(DiagnosticPosition pos) {
   540         make_pos = pos;
   541         return make.at(pos);
   542     }
   544     /** Make an attributed tree representing a literal. This will be an
   545      *  Ident node in the case of boolean literals, a Literal node in all
   546      *  other cases.
   547      *  @param type       The literal's type.
   548      *  @param value      The literal's value.
   549      */
   550     JCExpression makeLit(Type type, Object value) {
   551         return make.Literal(type.getTag(), value).setType(type.constType(value));
   552     }
   554     /** Make an attributed tree representing null.
   555      */
   556     JCExpression makeNull() {
   557         return makeLit(syms.botType, null);
   558     }
   560     /** Make an attributed class instance creation expression.
   561      *  @param ctype    The class type.
   562      *  @param args     The constructor arguments.
   563      */
   564     JCNewClass makeNewClass(Type ctype, List<JCExpression> args) {
   565         JCNewClass tree = make.NewClass(null,
   566             null, make.QualIdent(ctype.tsym), args, null);
   567         tree.constructor = rs.resolveConstructor(
   568             make_pos, attrEnv, ctype, TreeInfo.types(args), List.<Type>nil());
   569         tree.type = ctype;
   570         return tree;
   571     }
   573     /** Make an attributed unary expression.
   574      *  @param optag    The operators tree tag.
   575      *  @param arg      The operator's argument.
   576      */
   577     JCUnary makeUnary(JCTree.Tag optag, JCExpression arg) {
   578         JCUnary tree = make.Unary(optag, arg);
   579         tree.operator = rs.resolveUnaryOperator(
   580             make_pos, optag, attrEnv, arg.type);
   581         tree.type = tree.operator.type.getReturnType();
   582         return tree;
   583     }
   585     /** Make an attributed binary expression.
   586      *  @param optag    The operators tree tag.
   587      *  @param lhs      The operator's left argument.
   588      *  @param rhs      The operator's right argument.
   589      */
   590     JCBinary makeBinary(JCTree.Tag optag, JCExpression lhs, JCExpression rhs) {
   591         JCBinary tree = make.Binary(optag, lhs, rhs);
   592         tree.operator = rs.resolveBinaryOperator(
   593             make_pos, optag, attrEnv, lhs.type, rhs.type);
   594         tree.type = tree.operator.type.getReturnType();
   595         return tree;
   596     }
   598     /** Make an attributed assignop expression.
   599      *  @param optag    The operators tree tag.
   600      *  @param lhs      The operator's left argument.
   601      *  @param rhs      The operator's right argument.
   602      */
   603     JCAssignOp makeAssignop(JCTree.Tag optag, JCTree lhs, JCTree rhs) {
   604         JCAssignOp tree = make.Assignop(optag, lhs, rhs);
   605         tree.operator = rs.resolveBinaryOperator(
   606             make_pos, tree.getTag().noAssignOp(), attrEnv, lhs.type, rhs.type);
   607         tree.type = lhs.type;
   608         return tree;
   609     }
   611     /** Convert tree into string object, unless it has already a
   612      *  reference type..
   613      */
   614     JCExpression makeString(JCExpression tree) {
   615         if (!tree.type.isPrimitiveOrVoid()) {
   616             return tree;
   617         } else {
   618             Symbol valueOfSym = lookupMethod(tree.pos(),
   619                                              names.valueOf,
   620                                              syms.stringType,
   621                                              List.of(tree.type));
   622             return make.App(make.QualIdent(valueOfSym), List.of(tree));
   623         }
   624     }
   626     /** Create an empty anonymous class definition and enter and complete
   627      *  its symbol. Return the class definition's symbol.
   628      *  and create
   629      *  @param flags    The class symbol's flags
   630      *  @param owner    The class symbol's owner
   631      */
   632     JCClassDecl makeEmptyClass(long flags, ClassSymbol owner) {
   633         return makeEmptyClass(flags, owner, null, true);
   634     }
   636     JCClassDecl makeEmptyClass(long flags, ClassSymbol owner, Name flatname,
   637             boolean addToDefs) {
   638         // Create class symbol.
   639         ClassSymbol c = reader.defineClass(names.empty, owner);
   640         if (flatname != null) {
   641             c.flatname = flatname;
   642         } else {
   643             c.flatname = chk.localClassName(c);
   644         }
   645         c.sourcefile = owner.sourcefile;
   646         c.completer = null;
   647         c.members_field = new Scope(c);
   648         c.flags_field = flags;
   649         ClassType ctype = (ClassType) c.type;
   650         ctype.supertype_field = syms.objectType;
   651         ctype.interfaces_field = List.nil();
   653         JCClassDecl odef = classDef(owner);
   655         // Enter class symbol in owner scope and compiled table.
   656         enterSynthetic(odef.pos(), c, owner.members());
   657         chk.compiled.put(c.flatname, c);
   659         // Create class definition tree.
   660         JCClassDecl cdef = make.ClassDef(
   661             make.Modifiers(flags), names.empty,
   662             List.<JCTypeParameter>nil(),
   663             null, List.<JCExpression>nil(), List.<JCTree>nil());
   664         cdef.sym = c;
   665         cdef.type = c.type;
   667         // Append class definition tree to owner's definitions.
   668         if (addToDefs) odef.defs = odef.defs.prepend(cdef);
   669         return cdef;
   670     }
   672 /**************************************************************************
   673  * Symbol manipulation utilities
   674  *************************************************************************/
   676     /** Enter a synthetic symbol in a given scope, but complain if there was already one there.
   677      *  @param pos           Position for error reporting.
   678      *  @param sym           The symbol.
   679      *  @param s             The scope.
   680      */
   681     private void enterSynthetic(DiagnosticPosition pos, Symbol sym, Scope s) {
   682         s.enter(sym);
   683     }
   685     /** Create a fresh synthetic name within a given scope - the unique name is
   686      *  obtained by appending '$' chars at the end of the name until no match
   687      *  is found.
   688      *
   689      * @param name base name
   690      * @param s scope in which the name has to be unique
   691      * @return fresh synthetic name
   692      */
   693     private Name makeSyntheticName(Name name, Scope s) {
   694         do {
   695             name = name.append(
   696                     target.syntheticNameChar(),
   697                     names.empty);
   698         } while (lookupSynthetic(name, s) != null);
   699         return name;
   700     }
   702     /** Check whether synthetic symbols generated during lowering conflict
   703      *  with user-defined symbols.
   704      *
   705      *  @param translatedTrees lowered class trees
   706      */
   707     void checkConflicts(List<JCTree> translatedTrees) {
   708         for (JCTree t : translatedTrees) {
   709             t.accept(conflictsChecker);
   710         }
   711     }
   713     JCTree.Visitor conflictsChecker = new TreeScanner() {
   715         TypeSymbol currentClass;
   717         @Override
   718         public void visitMethodDef(JCMethodDecl that) {
   719             chk.checkConflicts(that.pos(), that.sym, currentClass);
   720             super.visitMethodDef(that);
   721         }
   723         @Override
   724         public void visitVarDef(JCVariableDecl that) {
   725             if (that.sym.owner.kind == TYP) {
   726                 chk.checkConflicts(that.pos(), that.sym, currentClass);
   727             }
   728             super.visitVarDef(that);
   729         }
   731         @Override
   732         public void visitClassDef(JCClassDecl that) {
   733             TypeSymbol prevCurrentClass = currentClass;
   734             currentClass = that.sym;
   735             try {
   736                 super.visitClassDef(that);
   737             }
   738             finally {
   739                 currentClass = prevCurrentClass;
   740             }
   741         }
   742     };
   744     /** Look up a synthetic name in a given scope.
   745      *  @param s            The scope.
   746      *  @param name         The name.
   747      */
   748     private Symbol lookupSynthetic(Name name, Scope s) {
   749         Symbol sym = s.lookup(name).sym;
   750         return (sym==null || (sym.flags()&SYNTHETIC)==0) ? null : sym;
   751     }
   753     /** Look up a method in a given scope.
   754      */
   755     private MethodSymbol lookupMethod(DiagnosticPosition pos, Name name, Type qual, List<Type> args) {
   756         return rs.resolveInternalMethod(pos, attrEnv, qual, name, args, List.<Type>nil());
   757     }
   759     /** Look up a constructor.
   760      */
   761     private MethodSymbol lookupConstructor(DiagnosticPosition pos, Type qual, List<Type> args) {
   762         return rs.resolveInternalConstructor(pos, attrEnv, qual, args, null);
   763     }
   765     /** Look up a field.
   766      */
   767     private VarSymbol lookupField(DiagnosticPosition pos, Type qual, Name name) {
   768         return rs.resolveInternalField(pos, attrEnv, qual, name);
   769     }
   771     /** Anon inner classes are used as access constructor tags.
   772      * accessConstructorTag will use an existing anon class if one is available,
   773      * and synthethise a class (with makeEmptyClass) if one is not available.
   774      * However, there is a small possibility that an existing class will not
   775      * be generated as expected if it is inside a conditional with a constant
   776      * expression. If that is found to be the case, create an empty class tree here.
   777      */
   778     private void checkAccessConstructorTags() {
   779         for (List<ClassSymbol> l = accessConstrTags; l.nonEmpty(); l = l.tail) {
   780             ClassSymbol c = l.head;
   781             if (isTranslatedClassAvailable(c))
   782                 continue;
   783             // Create class definition tree.
   784             JCClassDecl cdec = makeEmptyClass(STATIC | SYNTHETIC,
   785                     c.outermostClass(), c.flatname, false);
   786             swapAccessConstructorTag(c, cdec.sym);
   787             translated.append(cdec);
   788         }
   789     }
   790     // where
   791     private boolean isTranslatedClassAvailable(ClassSymbol c) {
   792         for (JCTree tree: translated) {
   793             if (tree.hasTag(CLASSDEF)
   794                     && ((JCClassDecl) tree).sym == c) {
   795                 return true;
   796             }
   797         }
   798         return false;
   799     }
   801     void swapAccessConstructorTag(ClassSymbol oldCTag, ClassSymbol newCTag) {
   802         for (MethodSymbol methodSymbol : accessConstrs.values()) {
   803             Assert.check(methodSymbol.type.hasTag(METHOD));
   804             MethodType oldMethodType =
   805                     (MethodType)methodSymbol.type;
   806             if (oldMethodType.argtypes.head.tsym == oldCTag)
   807                 methodSymbol.type =
   808                     types.createMethodTypeWithParameters(oldMethodType,
   809                         oldMethodType.getParameterTypes().tail
   810                             .prepend(newCTag.erasure(types)));
   811         }
   812     }
   814 /**************************************************************************
   815  * Access methods
   816  *************************************************************************/
   818     /** Access codes for dereferencing, assignment,
   819      *  and pre/post increment/decrement.
   820      *  Access codes for assignment operations are determined by method accessCode
   821      *  below.
   822      *
   823      *  All access codes for accesses to the current class are even.
   824      *  If a member of the superclass should be accessed instead (because
   825      *  access was via a qualified super), add one to the corresponding code
   826      *  for the current class, making the number odd.
   827      *  This numbering scheme is used by the backend to decide whether
   828      *  to issue an invokevirtual or invokespecial call.
   829      *
   830      *  @see Gen#visitSelect(JCFieldAccess tree)
   831      */
   832     private static final int
   833         DEREFcode = 0,
   834         ASSIGNcode = 2,
   835         PREINCcode = 4,
   836         PREDECcode = 6,
   837         POSTINCcode = 8,
   838         POSTDECcode = 10,
   839         FIRSTASGOPcode = 12;
   841     /** Number of access codes
   842      */
   843     private static final int NCODES = accessCode(ByteCodes.lushrl) + 2;
   845     /** A mapping from symbols to their access numbers.
   846      */
   847     private Map<Symbol,Integer> accessNums;
   849     /** A mapping from symbols to an array of access symbols, indexed by
   850      *  access code.
   851      */
   852     private Map<Symbol,MethodSymbol[]> accessSyms;
   854     /** A mapping from (constructor) symbols to access constructor symbols.
   855      */
   856     private Map<Symbol,MethodSymbol> accessConstrs;
   858     /** A list of all class symbols used for access constructor tags.
   859      */
   860     private List<ClassSymbol> accessConstrTags;
   862     /** A queue for all accessed symbols.
   863      */
   864     private ListBuffer<Symbol> accessed;
   866     /** Map bytecode of binary operation to access code of corresponding
   867      *  assignment operation. This is always an even number.
   868      */
   869     private static int accessCode(int bytecode) {
   870         if (ByteCodes.iadd <= bytecode && bytecode <= ByteCodes.lxor)
   871             return (bytecode - iadd) * 2 + FIRSTASGOPcode;
   872         else if (bytecode == ByteCodes.string_add)
   873             return (ByteCodes.lxor + 1 - iadd) * 2 + FIRSTASGOPcode;
   874         else if (ByteCodes.ishll <= bytecode && bytecode <= ByteCodes.lushrl)
   875             return (bytecode - ishll + ByteCodes.lxor + 2 - iadd) * 2 + FIRSTASGOPcode;
   876         else
   877             return -1;
   878     }
   880     /** return access code for identifier,
   881      *  @param tree     The tree representing the identifier use.
   882      *  @param enclOp   The closest enclosing operation node of tree,
   883      *                  null if tree is not a subtree of an operation.
   884      */
   885     private static int accessCode(JCTree tree, JCTree enclOp) {
   886         if (enclOp == null)
   887             return DEREFcode;
   888         else if (enclOp.hasTag(ASSIGN) &&
   889                  tree == TreeInfo.skipParens(((JCAssign) enclOp).lhs))
   890             return ASSIGNcode;
   891         else if (enclOp.getTag().isIncOrDecUnaryOp() &&
   892                  tree == TreeInfo.skipParens(((JCUnary) enclOp).arg))
   893             return mapTagToUnaryOpCode(enclOp.getTag());
   894         else if (enclOp.getTag().isAssignop() &&
   895                  tree == TreeInfo.skipParens(((JCAssignOp) enclOp).lhs))
   896             return accessCode(((OperatorSymbol) ((JCAssignOp) enclOp).operator).opcode);
   897         else
   898             return DEREFcode;
   899     }
   901     /** Return binary operator that corresponds to given access code.
   902      */
   903     private OperatorSymbol binaryAccessOperator(int acode) {
   904         for (Scope.Entry e = syms.predefClass.members().elems;
   905              e != null;
   906              e = e.sibling) {
   907             if (e.sym instanceof OperatorSymbol) {
   908                 OperatorSymbol op = (OperatorSymbol)e.sym;
   909                 if (accessCode(op.opcode) == acode) return op;
   910             }
   911         }
   912         return null;
   913     }
   915     /** Return tree tag for assignment operation corresponding
   916      *  to given binary operator.
   917      */
   918     private static JCTree.Tag treeTag(OperatorSymbol operator) {
   919         switch (operator.opcode) {
   920         case ByteCodes.ior: case ByteCodes.lor:
   921             return BITOR_ASG;
   922         case ByteCodes.ixor: case ByteCodes.lxor:
   923             return BITXOR_ASG;
   924         case ByteCodes.iand: case ByteCodes.land:
   925             return BITAND_ASG;
   926         case ByteCodes.ishl: case ByteCodes.lshl:
   927         case ByteCodes.ishll: case ByteCodes.lshll:
   928             return SL_ASG;
   929         case ByteCodes.ishr: case ByteCodes.lshr:
   930         case ByteCodes.ishrl: case ByteCodes.lshrl:
   931             return SR_ASG;
   932         case ByteCodes.iushr: case ByteCodes.lushr:
   933         case ByteCodes.iushrl: case ByteCodes.lushrl:
   934             return USR_ASG;
   935         case ByteCodes.iadd: case ByteCodes.ladd:
   936         case ByteCodes.fadd: case ByteCodes.dadd:
   937         case ByteCodes.string_add:
   938             return PLUS_ASG;
   939         case ByteCodes.isub: case ByteCodes.lsub:
   940         case ByteCodes.fsub: case ByteCodes.dsub:
   941             return MINUS_ASG;
   942         case ByteCodes.imul: case ByteCodes.lmul:
   943         case ByteCodes.fmul: case ByteCodes.dmul:
   944             return MUL_ASG;
   945         case ByteCodes.idiv: case ByteCodes.ldiv:
   946         case ByteCodes.fdiv: case ByteCodes.ddiv:
   947             return DIV_ASG;
   948         case ByteCodes.imod: case ByteCodes.lmod:
   949         case ByteCodes.fmod: case ByteCodes.dmod:
   950             return MOD_ASG;
   951         default:
   952             throw new AssertionError();
   953         }
   954     }
   956     /** The name of the access method with number `anum' and access code `acode'.
   957      */
   958     Name accessName(int anum, int acode) {
   959         return names.fromString(
   960             "access" + target.syntheticNameChar() + anum + acode / 10 + acode % 10);
   961     }
   963     /** Return access symbol for a private or protected symbol from an inner class.
   964      *  @param sym        The accessed private symbol.
   965      *  @param tree       The accessing tree.
   966      *  @param enclOp     The closest enclosing operation node of tree,
   967      *                    null if tree is not a subtree of an operation.
   968      *  @param protAccess Is access to a protected symbol in another
   969      *                    package?
   970      *  @param refSuper   Is access via a (qualified) C.super?
   971      */
   972     MethodSymbol accessSymbol(Symbol sym, JCTree tree, JCTree enclOp,
   973                               boolean protAccess, boolean refSuper) {
   974         ClassSymbol accOwner = refSuper && protAccess
   975             // For access via qualified super (T.super.x), place the
   976             // access symbol on T.
   977             ? (ClassSymbol)((JCFieldAccess) tree).selected.type.tsym
   978             // Otherwise pretend that the owner of an accessed
   979             // protected symbol is the enclosing class of the current
   980             // class which is a subclass of the symbol's owner.
   981             : accessClass(sym, protAccess, tree);
   983         Symbol vsym = sym;
   984         if (sym.owner != accOwner) {
   985             vsym = sym.clone(accOwner);
   986             actualSymbols.put(vsym, sym);
   987         }
   989         Integer anum              // The access number of the access method.
   990             = accessNums.get(vsym);
   991         if (anum == null) {
   992             anum = accessed.length();
   993             accessNums.put(vsym, anum);
   994             accessSyms.put(vsym, new MethodSymbol[NCODES]);
   995             accessed.append(vsym);
   996             // System.out.println("accessing " + vsym + " in " + vsym.location());
   997         }
   999         int acode;                // The access code of the access method.
  1000         List<Type> argtypes;      // The argument types of the access method.
  1001         Type restype;             // The result type of the access method.
  1002         List<Type> thrown;        // The thrown exceptions of the access method.
  1003         switch (vsym.kind) {
  1004         case VAR:
  1005             acode = accessCode(tree, enclOp);
  1006             if (acode >= FIRSTASGOPcode) {
  1007                 OperatorSymbol operator = binaryAccessOperator(acode);
  1008                 if (operator.opcode == string_add)
  1009                     argtypes = List.of(syms.objectType);
  1010                 else
  1011                     argtypes = operator.type.getParameterTypes().tail;
  1012             } else if (acode == ASSIGNcode)
  1013                 argtypes = List.of(vsym.erasure(types));
  1014             else
  1015                 argtypes = List.nil();
  1016             restype = vsym.erasure(types);
  1017             thrown = List.nil();
  1018             break;
  1019         case MTH:
  1020             acode = DEREFcode;
  1021             argtypes = vsym.erasure(types).getParameterTypes();
  1022             restype = vsym.erasure(types).getReturnType();
  1023             thrown = vsym.type.getThrownTypes();
  1024             break;
  1025         default:
  1026             throw new AssertionError();
  1029         // For references via qualified super, increment acode by one,
  1030         // making it odd.
  1031         if (protAccess && refSuper) acode++;
  1033         // Instance access methods get instance as first parameter.
  1034         // For protected symbols this needs to be the instance as a member
  1035         // of the type containing the accessed symbol, not the class
  1036         // containing the access method.
  1037         if ((vsym.flags() & STATIC) == 0) {
  1038             argtypes = argtypes.prepend(vsym.owner.erasure(types));
  1040         MethodSymbol[] accessors = accessSyms.get(vsym);
  1041         MethodSymbol accessor = accessors[acode];
  1042         if (accessor == null) {
  1043             accessor = new MethodSymbol(
  1044                 STATIC | SYNTHETIC,
  1045                 accessName(anum.intValue(), acode),
  1046                 new MethodType(argtypes, restype, thrown, syms.methodClass),
  1047                 accOwner);
  1048             enterSynthetic(tree.pos(), accessor, accOwner.members());
  1049             accessors[acode] = accessor;
  1051         return accessor;
  1054     /** The qualifier to be used for accessing a symbol in an outer class.
  1055      *  This is either C.sym or C.this.sym, depending on whether or not
  1056      *  sym is static.
  1057      *  @param sym   The accessed symbol.
  1058      */
  1059     JCExpression accessBase(DiagnosticPosition pos, Symbol sym) {
  1060         return (sym.flags() & STATIC) != 0
  1061             ? access(make.at(pos.getStartPosition()).QualIdent(sym.owner))
  1062             : makeOwnerThis(pos, sym, true);
  1065     /** Do we need an access method to reference private symbol?
  1066      */
  1067     boolean needsPrivateAccess(Symbol sym) {
  1068         if ((sym.flags() & PRIVATE) == 0 || sym.owner == currentClass) {
  1069             return false;
  1070         } else if (sym.name == names.init && sym.owner.isLocal()) {
  1071             // private constructor in local class: relax protection
  1072             sym.flags_field &= ~PRIVATE;
  1073             return false;
  1074         } else {
  1075             return true;
  1079     /** Do we need an access method to reference symbol in other package?
  1080      */
  1081     boolean needsProtectedAccess(Symbol sym, JCTree tree) {
  1082         if ((sym.flags() & PROTECTED) == 0 ||
  1083             sym.owner.owner == currentClass.owner || // fast special case
  1084             sym.packge() == currentClass.packge())
  1085             return false;
  1086         if (!currentClass.isSubClass(sym.owner, types))
  1087             return true;
  1088         if ((sym.flags() & STATIC) != 0 ||
  1089             !tree.hasTag(SELECT) ||
  1090             TreeInfo.name(((JCFieldAccess) tree).selected) == names._super)
  1091             return false;
  1092         return !((JCFieldAccess) tree).selected.type.tsym.isSubClass(currentClass, types);
  1095     /** The class in which an access method for given symbol goes.
  1096      *  @param sym        The access symbol
  1097      *  @param protAccess Is access to a protected symbol in another
  1098      *                    package?
  1099      */
  1100     ClassSymbol accessClass(Symbol sym, boolean protAccess, JCTree tree) {
  1101         if (protAccess) {
  1102             Symbol qualifier = null;
  1103             ClassSymbol c = currentClass;
  1104             if (tree.hasTag(SELECT) && (sym.flags() & STATIC) == 0) {
  1105                 qualifier = ((JCFieldAccess) tree).selected.type.tsym;
  1106                 while (!qualifier.isSubClass(c, types)) {
  1107                     c = c.owner.enclClass();
  1109                 return c;
  1110             } else {
  1111                 while (!c.isSubClass(sym.owner, types)) {
  1112                     c = c.owner.enclClass();
  1115             return c;
  1116         } else {
  1117             // the symbol is private
  1118             return sym.owner.enclClass();
  1122     private void addPrunedInfo(JCTree tree) {
  1123         List<JCTree> infoList = prunedTree.get(currentClass);
  1124         infoList = (infoList == null) ? List.of(tree) : infoList.prepend(tree);
  1125         prunedTree.put(currentClass, infoList);
  1128     /** Ensure that identifier is accessible, return tree accessing the identifier.
  1129      *  @param sym      The accessed symbol.
  1130      *  @param tree     The tree referring to the symbol.
  1131      *  @param enclOp   The closest enclosing operation node of tree,
  1132      *                  null if tree is not a subtree of an operation.
  1133      *  @param refSuper Is access via a (qualified) C.super?
  1134      */
  1135     JCExpression access(Symbol sym, JCExpression tree, JCExpression enclOp, boolean refSuper) {
  1136         // Access a free variable via its proxy, or its proxy's proxy
  1137         while (sym.kind == VAR && sym.owner.kind == MTH &&
  1138             sym.owner.enclClass() != currentClass) {
  1139             // A constant is replaced by its constant value.
  1140             Object cv = ((VarSymbol)sym).getConstValue();
  1141             if (cv != null) {
  1142                 make.at(tree.pos);
  1143                 return makeLit(sym.type, cv);
  1145             // Otherwise replace the variable by its proxy.
  1146             sym = proxies.lookup(proxyName(sym.name)).sym;
  1147             Assert.check(sym != null && (sym.flags_field & FINAL) != 0);
  1148             tree = make.at(tree.pos).Ident(sym);
  1150         JCExpression base = (tree.hasTag(SELECT)) ? ((JCFieldAccess) tree).selected : null;
  1151         switch (sym.kind) {
  1152         case TYP:
  1153             if (sym.owner.kind != PCK) {
  1154                 // Convert type idents to
  1155                 // <flat name> or <package name> . <flat name>
  1156                 Name flatname = Convert.shortName(sym.flatName());
  1157                 while (base != null &&
  1158                        TreeInfo.symbol(base) != null &&
  1159                        TreeInfo.symbol(base).kind != PCK) {
  1160                     base = (base.hasTag(SELECT))
  1161                         ? ((JCFieldAccess) base).selected
  1162                         : null;
  1164                 if (tree.hasTag(IDENT)) {
  1165                     ((JCIdent) tree).name = flatname;
  1166                 } else if (base == null) {
  1167                     tree = make.at(tree.pos).Ident(sym);
  1168                     ((JCIdent) tree).name = flatname;
  1169                 } else {
  1170                     ((JCFieldAccess) tree).selected = base;
  1171                     ((JCFieldAccess) tree).name = flatname;
  1174             break;
  1175         case MTH: case VAR:
  1176             if (sym.owner.kind == TYP) {
  1178                 // Access methods are required for
  1179                 //  - private members,
  1180                 //  - protected members in a superclass of an
  1181                 //    enclosing class contained in another package.
  1182                 //  - all non-private members accessed via a qualified super.
  1183                 boolean protAccess = refSuper && !needsPrivateAccess(sym)
  1184                     || needsProtectedAccess(sym, tree);
  1185                 boolean accReq = protAccess || needsPrivateAccess(sym);
  1187                 // A base has to be supplied for
  1188                 //  - simple identifiers accessing variables in outer classes.
  1189                 boolean baseReq =
  1190                     base == null &&
  1191                     sym.owner != syms.predefClass &&
  1192                     !sym.isMemberOf(currentClass, types);
  1194                 if (accReq || baseReq) {
  1195                     make.at(tree.pos);
  1197                     // Constants are replaced by their constant value.
  1198                     if (sym.kind == VAR) {
  1199                         Object cv = ((VarSymbol)sym).getConstValue();
  1200                         if (cv != null) {
  1201                             addPrunedInfo(tree);
  1202                             return makeLit(sym.type, cv);
  1206                     // Private variables and methods are replaced by calls
  1207                     // to their access methods.
  1208                     if (accReq) {
  1209                         List<JCExpression> args = List.nil();
  1210                         if ((sym.flags() & STATIC) == 0) {
  1211                             // Instance access methods get instance
  1212                             // as first parameter.
  1213                             if (base == null)
  1214                                 base = makeOwnerThis(tree.pos(), sym, true);
  1215                             args = args.prepend(base);
  1216                             base = null;   // so we don't duplicate code
  1218                         Symbol access = accessSymbol(sym, tree,
  1219                                                      enclOp, protAccess,
  1220                                                      refSuper);
  1221                         JCExpression receiver = make.Select(
  1222                             base != null ? base : make.QualIdent(access.owner),
  1223                             access);
  1224                         return make.App(receiver, args);
  1226                     // Other accesses to members of outer classes get a
  1227                     // qualifier.
  1228                     } else if (baseReq) {
  1229                         return make.at(tree.pos).Select(
  1230                             accessBase(tree.pos(), sym), sym).setType(tree.type);
  1233             } else if (sym.owner.kind == MTH && lambdaTranslationMap != null) {
  1234                 //sym is a local variable - check the lambda translation map to
  1235                 //see if sym has been translated to something else in the current
  1236                 //scope (by LambdaToMethod)
  1237                 Symbol translatedSym = lambdaTranslationMap.get(sym);
  1238                 if (translatedSym != null) {
  1239                     tree = make.at(tree.pos).Ident(translatedSym);
  1243         return tree;
  1246     /** Ensure that identifier is accessible, return tree accessing the identifier.
  1247      *  @param tree     The identifier tree.
  1248      */
  1249     JCExpression access(JCExpression tree) {
  1250         Symbol sym = TreeInfo.symbol(tree);
  1251         return sym == null ? tree : access(sym, tree, null, false);
  1254     /** Return access constructor for a private constructor,
  1255      *  or the constructor itself, if no access constructor is needed.
  1256      *  @param pos       The position to report diagnostics, if any.
  1257      *  @param constr    The private constructor.
  1258      */
  1259     Symbol accessConstructor(DiagnosticPosition pos, Symbol constr) {
  1260         if (needsPrivateAccess(constr)) {
  1261             ClassSymbol accOwner = constr.owner.enclClass();
  1262             MethodSymbol aconstr = accessConstrs.get(constr);
  1263             if (aconstr == null) {
  1264                 List<Type> argtypes = constr.type.getParameterTypes();
  1265                 if ((accOwner.flags_field & ENUM) != 0)
  1266                     argtypes = argtypes
  1267                         .prepend(syms.intType)
  1268                         .prepend(syms.stringType);
  1269                 aconstr = new MethodSymbol(
  1270                     SYNTHETIC,
  1271                     names.init,
  1272                     new MethodType(
  1273                         argtypes.append(
  1274                             accessConstructorTag().erasure(types)),
  1275                         constr.type.getReturnType(),
  1276                         constr.type.getThrownTypes(),
  1277                         syms.methodClass),
  1278                     accOwner);
  1279                 enterSynthetic(pos, aconstr, accOwner.members());
  1280                 accessConstrs.put(constr, aconstr);
  1281                 accessed.append(constr);
  1283             return aconstr;
  1284         } else {
  1285             return constr;
  1289     /** Return an anonymous class nested in this toplevel class.
  1290      */
  1291     ClassSymbol accessConstructorTag() {
  1292         ClassSymbol topClass = currentClass.outermostClass();
  1293         Name flatname = names.fromString("" + topClass.getQualifiedName() +
  1294                                          target.syntheticNameChar() +
  1295                                          "1");
  1296         ClassSymbol ctag = chk.compiled.get(flatname);
  1297         if (ctag == null)
  1298             ctag = makeEmptyClass(STATIC | SYNTHETIC, topClass).sym;
  1299         // keep a record of all tags, to verify that all are generated as required
  1300         accessConstrTags = accessConstrTags.prepend(ctag);
  1301         return ctag;
  1304     /** Add all required access methods for a private symbol to enclosing class.
  1305      *  @param sym       The symbol.
  1306      */
  1307     void makeAccessible(Symbol sym) {
  1308         JCClassDecl cdef = classDef(sym.owner.enclClass());
  1309         if (cdef == null) Assert.error("class def not found: " + sym + " in " + sym.owner);
  1310         if (sym.name == names.init) {
  1311             cdef.defs = cdef.defs.prepend(
  1312                 accessConstructorDef(cdef.pos, sym, accessConstrs.get(sym)));
  1313         } else {
  1314             MethodSymbol[] accessors = accessSyms.get(sym);
  1315             for (int i = 0; i < NCODES; i++) {
  1316                 if (accessors[i] != null)
  1317                     cdef.defs = cdef.defs.prepend(
  1318                         accessDef(cdef.pos, sym, accessors[i], i));
  1323     /** Maps unary operator integer codes to JCTree.Tag objects
  1324      *  @param unaryOpCode the unary operator code
  1325      */
  1326     private static Tag mapUnaryOpCodeToTag(int unaryOpCode){
  1327         switch (unaryOpCode){
  1328             case PREINCcode:
  1329                 return PREINC;
  1330             case PREDECcode:
  1331                 return PREDEC;
  1332             case POSTINCcode:
  1333                 return POSTINC;
  1334             case POSTDECcode:
  1335                 return POSTDEC;
  1336             default:
  1337                 return NO_TAG;
  1341     /** Maps JCTree.Tag objects to unary operator integer codes
  1342      *  @param tag the JCTree.Tag
  1343      */
  1344     private static int mapTagToUnaryOpCode(Tag tag){
  1345         switch (tag){
  1346             case PREINC:
  1347                 return PREINCcode;
  1348             case PREDEC:
  1349                 return PREDECcode;
  1350             case POSTINC:
  1351                 return POSTINCcode;
  1352             case POSTDEC:
  1353                 return POSTDECcode;
  1354             default:
  1355                 return -1;
  1359     /** Construct definition of an access method.
  1360      *  @param pos        The source code position of the definition.
  1361      *  @param vsym       The private or protected symbol.
  1362      *  @param accessor   The access method for the symbol.
  1363      *  @param acode      The access code.
  1364      */
  1365     JCTree accessDef(int pos, Symbol vsym, MethodSymbol accessor, int acode) {
  1366 //      System.err.println("access " + vsym + " with " + accessor);//DEBUG
  1367         currentClass = vsym.owner.enclClass();
  1368         make.at(pos);
  1369         JCMethodDecl md = make.MethodDef(accessor, null);
  1371         // Find actual symbol
  1372         Symbol sym = actualSymbols.get(vsym);
  1373         if (sym == null) sym = vsym;
  1375         JCExpression ref;           // The tree referencing the private symbol.
  1376         List<JCExpression> args;    // Any additional arguments to be passed along.
  1377         if ((sym.flags() & STATIC) != 0) {
  1378             ref = make.Ident(sym);
  1379             args = make.Idents(md.params);
  1380         } else {
  1381             ref = make.Select(make.Ident(md.params.head), sym);
  1382             args = make.Idents(md.params.tail);
  1384         JCStatement stat;          // The statement accessing the private symbol.
  1385         if (sym.kind == VAR) {
  1386             // Normalize out all odd access codes by taking floor modulo 2:
  1387             int acode1 = acode - (acode & 1);
  1389             JCExpression expr;      // The access method's return value.
  1390             switch (acode1) {
  1391             case DEREFcode:
  1392                 expr = ref;
  1393                 break;
  1394             case ASSIGNcode:
  1395                 expr = make.Assign(ref, args.head);
  1396                 break;
  1397             case PREINCcode: case POSTINCcode: case PREDECcode: case POSTDECcode:
  1398                 expr = makeUnary(mapUnaryOpCodeToTag(acode1), ref);
  1399                 break;
  1400             default:
  1401                 expr = make.Assignop(
  1402                     treeTag(binaryAccessOperator(acode1)), ref, args.head);
  1403                 ((JCAssignOp) expr).operator = binaryAccessOperator(acode1);
  1405             stat = make.Return(expr.setType(sym.type));
  1406         } else {
  1407             stat = make.Call(make.App(ref, args));
  1409         md.body = make.Block(0, List.of(stat));
  1411         // Make sure all parameters, result types and thrown exceptions
  1412         // are accessible.
  1413         for (List<JCVariableDecl> l = md.params; l.nonEmpty(); l = l.tail)
  1414             l.head.vartype = access(l.head.vartype);
  1415         md.restype = access(md.restype);
  1416         for (List<JCExpression> l = md.thrown; l.nonEmpty(); l = l.tail)
  1417             l.head = access(l.head);
  1419         return md;
  1422     /** Construct definition of an access constructor.
  1423      *  @param pos        The source code position of the definition.
  1424      *  @param constr     The private constructor.
  1425      *  @param accessor   The access method for the constructor.
  1426      */
  1427     JCTree accessConstructorDef(int pos, Symbol constr, MethodSymbol accessor) {
  1428         make.at(pos);
  1429         JCMethodDecl md = make.MethodDef(accessor,
  1430                                       accessor.externalType(types),
  1431                                       null);
  1432         JCIdent callee = make.Ident(names._this);
  1433         callee.sym = constr;
  1434         callee.type = constr.type;
  1435         md.body =
  1436             make.Block(0, List.<JCStatement>of(
  1437                 make.Call(
  1438                     make.App(
  1439                         callee,
  1440                         make.Idents(md.params.reverse().tail.reverse())))));
  1441         return md;
  1444 /**************************************************************************
  1445  * Free variables proxies and this$n
  1446  *************************************************************************/
  1448     /** A scope containing all free variable proxies for currently translated
  1449      *  class, as well as its this$n symbol (if needed).
  1450      *  Proxy scopes are nested in the same way classes are.
  1451      *  Inside a constructor, proxies and any this$n symbol are duplicated
  1452      *  in an additional innermost scope, where they represent the constructor
  1453      *  parameters.
  1454      */
  1455     Scope proxies;
  1457     /** A scope containing all unnamed resource variables/saved
  1458      *  exception variables for translated TWR blocks
  1459      */
  1460     Scope twrVars;
  1462     /** A stack containing the this$n field of the currently translated
  1463      *  classes (if needed) in innermost first order.
  1464      *  Inside a constructor, proxies and any this$n symbol are duplicated
  1465      *  in an additional innermost scope, where they represent the constructor
  1466      *  parameters.
  1467      */
  1468     List<VarSymbol> outerThisStack;
  1470     /** The name of a free variable proxy.
  1471      */
  1472     Name proxyName(Name name) {
  1473         return names.fromString("val" + target.syntheticNameChar() + name);
  1476     /** Proxy definitions for all free variables in given list, in reverse order.
  1477      *  @param pos        The source code position of the definition.
  1478      *  @param freevars   The free variables.
  1479      *  @param owner      The class in which the definitions go.
  1480      */
  1481     List<JCVariableDecl> freevarDefs(int pos, List<VarSymbol> freevars, Symbol owner) {
  1482         return freevarDefs(pos, freevars, owner, 0);
  1485     List<JCVariableDecl> freevarDefs(int pos, List<VarSymbol> freevars, Symbol owner,
  1486             long additionalFlags) {
  1487         long flags = FINAL | SYNTHETIC | additionalFlags;
  1488         if (owner.kind == TYP &&
  1489             target.usePrivateSyntheticFields())
  1490             flags |= PRIVATE;
  1491         List<JCVariableDecl> defs = List.nil();
  1492         for (List<VarSymbol> l = freevars; l.nonEmpty(); l = l.tail) {
  1493             VarSymbol v = l.head;
  1494             VarSymbol proxy = new VarSymbol(
  1495                 flags, proxyName(v.name), v.erasure(types), owner);
  1496             proxies.enter(proxy);
  1497             JCVariableDecl vd = make.at(pos).VarDef(proxy, null);
  1498             vd.vartype = access(vd.vartype);
  1499             defs = defs.prepend(vd);
  1501         return defs;
  1504     /** The name of a this$n field
  1505      *  @param type   The class referenced by the this$n field
  1506      */
  1507     Name outerThisName(Type type, Symbol owner) {
  1508         Type t = type.getEnclosingType();
  1509         int nestingLevel = 0;
  1510         while (t.hasTag(CLASS)) {
  1511             t = t.getEnclosingType();
  1512             nestingLevel++;
  1514         Name result = names.fromString("this" + target.syntheticNameChar() + nestingLevel);
  1515         while (owner.kind == TYP && ((ClassSymbol)owner).members().lookup(result).scope != null)
  1516             result = names.fromString(result.toString() + target.syntheticNameChar());
  1517         return result;
  1520     private VarSymbol makeOuterThisVarSymbol(Symbol owner, long flags) {
  1521         if (owner.kind == TYP &&
  1522             target.usePrivateSyntheticFields())
  1523             flags |= PRIVATE;
  1524         Type target = types.erasure(owner.enclClass().type.getEnclosingType());
  1525         VarSymbol outerThis =
  1526             new VarSymbol(flags, outerThisName(target, owner), target, owner);
  1527         outerThisStack = outerThisStack.prepend(outerThis);
  1528         return outerThis;
  1531     private JCVariableDecl makeOuterThisVarDecl(int pos, VarSymbol sym) {
  1532         JCVariableDecl vd = make.at(pos).VarDef(sym, null);
  1533         vd.vartype = access(vd.vartype);
  1534         return vd;
  1537     /** Definition for this$n field.
  1538      *  @param pos        The source code position of the definition.
  1539      *  @param owner      The method in which the definition goes.
  1540      */
  1541     JCVariableDecl outerThisDef(int pos, MethodSymbol owner) {
  1542         ClassSymbol c = owner.enclClass();
  1543         boolean isMandated =
  1544             // Anonymous constructors
  1545             (owner.isConstructor() && owner.isAnonymous()) ||
  1546             // Constructors of non-private inner member classes
  1547             (owner.isConstructor() && c.isInner() &&
  1548              !c.isPrivate() && !c.isStatic());
  1549         long flags =
  1550             FINAL | (isMandated ? MANDATED : SYNTHETIC) | PARAMETER;
  1551         VarSymbol outerThis = makeOuterThisVarSymbol(owner, flags);
  1552         owner.extraParams = owner.extraParams.prepend(outerThis);
  1553         return makeOuterThisVarDecl(pos, outerThis);
  1556     /** Definition for this$n field.
  1557      *  @param pos        The source code position of the definition.
  1558      *  @param owner      The class in which the definition goes.
  1559      */
  1560     JCVariableDecl outerThisDef(int pos, ClassSymbol owner) {
  1561         VarSymbol outerThis = makeOuterThisVarSymbol(owner, FINAL | SYNTHETIC);
  1562         return makeOuterThisVarDecl(pos, outerThis);
  1565     /** Return a list of trees that load the free variables in given list,
  1566      *  in reverse order.
  1567      *  @param pos          The source code position to be used for the trees.
  1568      *  @param freevars     The list of free variables.
  1569      */
  1570     List<JCExpression> loadFreevars(DiagnosticPosition pos, List<VarSymbol> freevars) {
  1571         List<JCExpression> args = List.nil();
  1572         for (List<VarSymbol> l = freevars; l.nonEmpty(); l = l.tail)
  1573             args = args.prepend(loadFreevar(pos, l.head));
  1574         return args;
  1576 //where
  1577         JCExpression loadFreevar(DiagnosticPosition pos, VarSymbol v) {
  1578             return access(v, make.at(pos).Ident(v), null, false);
  1581     /** Construct a tree simulating the expression {@code C.this}.
  1582      *  @param pos           The source code position to be used for the tree.
  1583      *  @param c             The qualifier class.
  1584      */
  1585     JCExpression makeThis(DiagnosticPosition pos, TypeSymbol c) {
  1586         if (currentClass == c) {
  1587             // in this case, `this' works fine
  1588             return make.at(pos).This(c.erasure(types));
  1589         } else {
  1590             // need to go via this$n
  1591             return makeOuterThis(pos, c);
  1595     /**
  1596      * Optionally replace a try statement with the desugaring of a
  1597      * try-with-resources statement.  The canonical desugaring of
  1599      * try ResourceSpecification
  1600      *   Block
  1602      * is
  1604      * {
  1605      *   final VariableModifiers_minus_final R #resource = Expression;
  1606      *   Throwable #primaryException = null;
  1608      *   try ResourceSpecificationtail
  1609      *     Block
  1610      *   catch (Throwable #t) {
  1611      *     #primaryException = t;
  1612      *     throw #t;
  1613      *   } finally {
  1614      *     if (#resource != null) {
  1615      *       if (#primaryException != null) {
  1616      *         try {
  1617      *           #resource.close();
  1618      *         } catch(Throwable #suppressedException) {
  1619      *           #primaryException.addSuppressed(#suppressedException);
  1620      *         }
  1621      *       } else {
  1622      *         #resource.close();
  1623      *       }
  1624      *     }
  1625      *   }
  1627      * @param tree  The try statement to inspect.
  1628      * @return A a desugared try-with-resources tree, or the original
  1629      * try block if there are no resources to manage.
  1630      */
  1631     JCTree makeTwrTry(JCTry tree) {
  1632         make_at(tree.pos());
  1633         twrVars = twrVars.dup();
  1634         JCBlock twrBlock = makeTwrBlock(tree.resources, tree.body,
  1635                 tree.finallyCanCompleteNormally, 0);
  1636         if (tree.catchers.isEmpty() && tree.finalizer == null)
  1637             result = translate(twrBlock);
  1638         else
  1639             result = translate(make.Try(twrBlock, tree.catchers, tree.finalizer));
  1640         twrVars = twrVars.leave();
  1641         return result;
  1644     private JCBlock makeTwrBlock(List<JCTree> resources, JCBlock block,
  1645             boolean finallyCanCompleteNormally, int depth) {
  1646         if (resources.isEmpty())
  1647             return block;
  1649         // Add resource declaration or expression to block statements
  1650         ListBuffer<JCStatement> stats = new ListBuffer<JCStatement>();
  1651         JCTree resource = resources.head;
  1652         JCExpression expr = null;
  1653         if (resource instanceof JCVariableDecl) {
  1654             JCVariableDecl var = (JCVariableDecl) resource;
  1655             expr = make.Ident(var.sym).setType(resource.type);
  1656             stats.add(var);
  1657         } else {
  1658             Assert.check(resource instanceof JCExpression);
  1659             VarSymbol syntheticTwrVar =
  1660             new VarSymbol(SYNTHETIC | FINAL,
  1661                           makeSyntheticName(names.fromString("twrVar" +
  1662                                            depth), twrVars),
  1663                           (resource.type.hasTag(BOT)) ?
  1664                           syms.autoCloseableType : resource.type,
  1665                           currentMethodSym);
  1666             twrVars.enter(syntheticTwrVar);
  1667             JCVariableDecl syntheticTwrVarDecl =
  1668                 make.VarDef(syntheticTwrVar, (JCExpression)resource);
  1669             expr = (JCExpression)make.Ident(syntheticTwrVar);
  1670             stats.add(syntheticTwrVarDecl);
  1673         // Add primaryException declaration
  1674         VarSymbol primaryException =
  1675             new VarSymbol(SYNTHETIC,
  1676                           makeSyntheticName(names.fromString("primaryException" +
  1677                           depth), twrVars),
  1678                           syms.throwableType,
  1679                           currentMethodSym);
  1680         twrVars.enter(primaryException);
  1681         JCVariableDecl primaryExceptionTreeDecl = make.VarDef(primaryException, makeNull());
  1682         stats.add(primaryExceptionTreeDecl);
  1684         // Create catch clause that saves exception and then rethrows it
  1685         VarSymbol param =
  1686             new VarSymbol(FINAL|SYNTHETIC,
  1687                           names.fromString("t" +
  1688                                            target.syntheticNameChar()),
  1689                           syms.throwableType,
  1690                           currentMethodSym);
  1691         JCVariableDecl paramTree = make.VarDef(param, null);
  1692         JCStatement assign = make.Assignment(primaryException, make.Ident(param));
  1693         JCStatement rethrowStat = make.Throw(make.Ident(param));
  1694         JCBlock catchBlock = make.Block(0L, List.<JCStatement>of(assign, rethrowStat));
  1695         JCCatch catchClause = make.Catch(paramTree, catchBlock);
  1697         int oldPos = make.pos;
  1698         make.at(TreeInfo.endPos(block));
  1699         JCBlock finallyClause = makeTwrFinallyClause(primaryException, expr);
  1700         make.at(oldPos);
  1701         JCTry outerTry = make.Try(makeTwrBlock(resources.tail, block,
  1702                                     finallyCanCompleteNormally, depth + 1),
  1703                                   List.<JCCatch>of(catchClause),
  1704                                   finallyClause);
  1705         outerTry.finallyCanCompleteNormally = finallyCanCompleteNormally;
  1706         stats.add(outerTry);
  1707         JCBlock newBlock = make.Block(0L, stats.toList());
  1708         return newBlock;
  1711     private JCBlock makeTwrFinallyClause(Symbol primaryException, JCExpression resource) {
  1712         // primaryException.addSuppressed(catchException);
  1713         VarSymbol catchException =
  1714             new VarSymbol(SYNTHETIC, make.paramName(2),
  1715                           syms.throwableType,
  1716                           currentMethodSym);
  1717         JCStatement addSuppressionStatement =
  1718             make.Exec(makeCall(make.Ident(primaryException),
  1719                                names.addSuppressed,
  1720                                List.<JCExpression>of(make.Ident(catchException))));
  1722         // try { resource.close(); } catch (e) { primaryException.addSuppressed(e); }
  1723         JCBlock tryBlock =
  1724             make.Block(0L, List.<JCStatement>of(makeResourceCloseInvocation(resource)));
  1725         JCVariableDecl catchExceptionDecl = make.VarDef(catchException, null);
  1726         JCBlock catchBlock = make.Block(0L, List.<JCStatement>of(addSuppressionStatement));
  1727         List<JCCatch> catchClauses = List.<JCCatch>of(make.Catch(catchExceptionDecl, catchBlock));
  1728         JCTry tryTree = make.Try(tryBlock, catchClauses, null);
  1729         tryTree.finallyCanCompleteNormally = true;
  1731         // if (primaryException != null) {try...} else resourceClose;
  1732         JCIf closeIfStatement = make.If(makeNonNullCheck(make.Ident(primaryException)),
  1733                                         tryTree,
  1734                                         makeResourceCloseInvocation(resource));
  1736         // if (#resource != null) { if (primaryException ...  }
  1737         return make.Block(0L,
  1738                           List.<JCStatement>of(make.If(makeNonNullCheck(resource),
  1739                                                        closeIfStatement,
  1740                                                        null)));
  1743     private JCStatement makeResourceCloseInvocation(JCExpression resource) {
  1744         // convert to AutoCloseable if needed
  1745         if (types.asSuper(resource.type, syms.autoCloseableType.tsym) == null) {
  1746             resource = (JCExpression) convert(resource, syms.autoCloseableType);
  1749         // create resource.close() method invocation
  1750         JCExpression resourceClose = makeCall(resource,
  1751                                               names.close,
  1752                                               List.<JCExpression>nil());
  1753         return make.Exec(resourceClose);
  1756     private JCExpression makeNonNullCheck(JCExpression expression) {
  1757         return makeBinary(NE, expression, makeNull());
  1760     /** Construct a tree that represents the outer instance
  1761      *  {@code C.this}. Never pick the current `this'.
  1762      *  @param pos           The source code position to be used for the tree.
  1763      *  @param c             The qualifier class.
  1764      */
  1765     JCExpression makeOuterThis(DiagnosticPosition pos, TypeSymbol c) {
  1766         List<VarSymbol> ots = outerThisStack;
  1767         if (ots.isEmpty()) {
  1768             log.error(pos, "no.encl.instance.of.type.in.scope", c);
  1769             Assert.error();
  1770             return makeNull();
  1772         VarSymbol ot = ots.head;
  1773         JCExpression tree = access(make.at(pos).Ident(ot));
  1774         TypeSymbol otc = ot.type.tsym;
  1775         while (otc != c) {
  1776             do {
  1777                 ots = ots.tail;
  1778                 if (ots.isEmpty()) {
  1779                     log.error(pos,
  1780                               "no.encl.instance.of.type.in.scope",
  1781                               c);
  1782                     Assert.error(); // should have been caught in Attr
  1783                     return tree;
  1785                 ot = ots.head;
  1786             } while (ot.owner != otc);
  1787             if (otc.owner.kind != PCK && !otc.hasOuterInstance()) {
  1788                 chk.earlyRefError(pos, c);
  1789                 Assert.error(); // should have been caught in Attr
  1790                 return makeNull();
  1792             tree = access(make.at(pos).Select(tree, ot));
  1793             otc = ot.type.tsym;
  1795         return tree;
  1798     /** Construct a tree that represents the closest outer instance
  1799      *  {@code C.this} such that the given symbol is a member of C.
  1800      *  @param pos           The source code position to be used for the tree.
  1801      *  @param sym           The accessed symbol.
  1802      *  @param preciseMatch  should we accept a type that is a subtype of
  1803      *                       sym's owner, even if it doesn't contain sym
  1804      *                       due to hiding, overriding, or non-inheritance
  1805      *                       due to protection?
  1806      */
  1807     JCExpression makeOwnerThis(DiagnosticPosition pos, Symbol sym, boolean preciseMatch) {
  1808         Symbol c = sym.owner;
  1809         if (preciseMatch ? sym.isMemberOf(currentClass, types)
  1810                          : currentClass.isSubClass(sym.owner, types)) {
  1811             // in this case, `this' works fine
  1812             return make.at(pos).This(c.erasure(types));
  1813         } else {
  1814             // need to go via this$n
  1815             return makeOwnerThisN(pos, sym, preciseMatch);
  1819     /**
  1820      * Similar to makeOwnerThis but will never pick "this".
  1821      */
  1822     JCExpression makeOwnerThisN(DiagnosticPosition pos, Symbol sym, boolean preciseMatch) {
  1823         Symbol c = sym.owner;
  1824         List<VarSymbol> ots = outerThisStack;
  1825         if (ots.isEmpty()) {
  1826             log.error(pos, "no.encl.instance.of.type.in.scope", c);
  1827             Assert.error();
  1828             return makeNull();
  1830         VarSymbol ot = ots.head;
  1831         JCExpression tree = access(make.at(pos).Ident(ot));
  1832         TypeSymbol otc = ot.type.tsym;
  1833         while (!(preciseMatch ? sym.isMemberOf(otc, types) : otc.isSubClass(sym.owner, types))) {
  1834             do {
  1835                 ots = ots.tail;
  1836                 if (ots.isEmpty()) {
  1837                     log.error(pos,
  1838                         "no.encl.instance.of.type.in.scope",
  1839                         c);
  1840                     Assert.error();
  1841                     return tree;
  1843                 ot = ots.head;
  1844             } while (ot.owner != otc);
  1845             tree = access(make.at(pos).Select(tree, ot));
  1846             otc = ot.type.tsym;
  1848         return tree;
  1851     /** Return tree simulating the assignment {@code this.name = name}, where
  1852      *  name is the name of a free variable.
  1853      */
  1854     JCStatement initField(int pos, Name name) {
  1855         Scope.Entry e = proxies.lookup(name);
  1856         Symbol rhs = e.sym;
  1857         Assert.check(rhs.owner.kind == MTH);
  1858         Symbol lhs = e.next().sym;
  1859         Assert.check(rhs.owner.owner == lhs.owner);
  1860         make.at(pos);
  1861         return
  1862             make.Exec(
  1863                 make.Assign(
  1864                     make.Select(make.This(lhs.owner.erasure(types)), lhs),
  1865                     make.Ident(rhs)).setType(lhs.erasure(types)));
  1868     /** Return tree simulating the assignment {@code this.this$n = this$n}.
  1869      */
  1870     JCStatement initOuterThis(int pos) {
  1871         VarSymbol rhs = outerThisStack.head;
  1872         Assert.check(rhs.owner.kind == MTH);
  1873         VarSymbol lhs = outerThisStack.tail.head;
  1874         Assert.check(rhs.owner.owner == lhs.owner);
  1875         make.at(pos);
  1876         return
  1877             make.Exec(
  1878                 make.Assign(
  1879                     make.Select(make.This(lhs.owner.erasure(types)), lhs),
  1880                     make.Ident(rhs)).setType(lhs.erasure(types)));
  1883 /**************************************************************************
  1884  * Code for .class
  1885  *************************************************************************/
  1887     /** Return the symbol of a class to contain a cache of
  1888      *  compiler-generated statics such as class$ and the
  1889      *  $assertionsDisabled flag.  We create an anonymous nested class
  1890      *  (unless one already exists) and return its symbol.  However,
  1891      *  for backward compatibility in 1.4 and earlier we use the
  1892      *  top-level class itself.
  1893      */
  1894     private ClassSymbol outerCacheClass() {
  1895         ClassSymbol clazz = outermostClassDef.sym;
  1896         if ((clazz.flags() & INTERFACE) == 0 &&
  1897             !target.useInnerCacheClass()) return clazz;
  1898         Scope s = clazz.members();
  1899         for (Scope.Entry e = s.elems; e != null; e = e.sibling)
  1900             if (e.sym.kind == TYP &&
  1901                 e.sym.name == names.empty &&
  1902                 (e.sym.flags() & INTERFACE) == 0) return (ClassSymbol) e.sym;
  1903         return makeEmptyClass(STATIC | SYNTHETIC, clazz).sym;
  1906     /** Return symbol for "class$" method. If there is no method definition
  1907      *  for class$, construct one as follows:
  1909      *    class class$(String x0) {
  1910      *      try {
  1911      *        return Class.forName(x0);
  1912      *      } catch (ClassNotFoundException x1) {
  1913      *        throw new NoClassDefFoundError(x1.getMessage());
  1914      *      }
  1915      *    }
  1916      */
  1917     private MethodSymbol classDollarSym(DiagnosticPosition pos) {
  1918         ClassSymbol outerCacheClass = outerCacheClass();
  1919         MethodSymbol classDollarSym =
  1920             (MethodSymbol)lookupSynthetic(classDollar,
  1921                                           outerCacheClass.members());
  1922         if (classDollarSym == null) {
  1923             classDollarSym = new MethodSymbol(
  1924                 STATIC | SYNTHETIC,
  1925                 classDollar,
  1926                 new MethodType(
  1927                     List.of(syms.stringType),
  1928                     types.erasure(syms.classType),
  1929                     List.<Type>nil(),
  1930                     syms.methodClass),
  1931                 outerCacheClass);
  1932             enterSynthetic(pos, classDollarSym, outerCacheClass.members());
  1934             JCMethodDecl md = make.MethodDef(classDollarSym, null);
  1935             try {
  1936                 md.body = classDollarSymBody(pos, md);
  1937             } catch (CompletionFailure ex) {
  1938                 md.body = make.Block(0, List.<JCStatement>nil());
  1939                 chk.completionError(pos, ex);
  1941             JCClassDecl outerCacheClassDef = classDef(outerCacheClass);
  1942             outerCacheClassDef.defs = outerCacheClassDef.defs.prepend(md);
  1944         return classDollarSym;
  1947     /** Generate code for class$(String name). */
  1948     JCBlock classDollarSymBody(DiagnosticPosition pos, JCMethodDecl md) {
  1949         MethodSymbol classDollarSym = md.sym;
  1950         ClassSymbol outerCacheClass = (ClassSymbol)classDollarSym.owner;
  1952         JCBlock returnResult;
  1954         // in 1.4.2 and above, we use
  1955         // Class.forName(String name, boolean init, ClassLoader loader);
  1956         // which requires we cache the current loader in cl$
  1957         if (target.classLiteralsNoInit()) {
  1958             // clsym = "private static ClassLoader cl$"
  1959             VarSymbol clsym = new VarSymbol(STATIC|SYNTHETIC,
  1960                                             names.fromString("cl" + target.syntheticNameChar()),
  1961                                             syms.classLoaderType,
  1962                                             outerCacheClass);
  1963             enterSynthetic(pos, clsym, outerCacheClass.members());
  1965             // emit "private static ClassLoader cl$;"
  1966             JCVariableDecl cldef = make.VarDef(clsym, null);
  1967             JCClassDecl outerCacheClassDef = classDef(outerCacheClass);
  1968             outerCacheClassDef.defs = outerCacheClassDef.defs.prepend(cldef);
  1970             // newcache := "new cache$1[0]"
  1971             JCNewArray newcache = make.
  1972                 NewArray(make.Type(outerCacheClass.type),
  1973                          List.<JCExpression>of(make.Literal(INT, 0).setType(syms.intType)),
  1974                          null);
  1975             newcache.type = new ArrayType(types.erasure(outerCacheClass.type),
  1976                                           syms.arrayClass);
  1978             // forNameSym := java.lang.Class.forName(
  1979             //     String s,boolean init,ClassLoader loader)
  1980             Symbol forNameSym = lookupMethod(make_pos, names.forName,
  1981                                              types.erasure(syms.classType),
  1982                                              List.of(syms.stringType,
  1983                                                      syms.booleanType,
  1984                                                      syms.classLoaderType));
  1985             // clvalue := "(cl$ == null) ?
  1986             // $newcache.getClass().getComponentType().getClassLoader() : cl$"
  1987             JCExpression clvalue =
  1988                 make.Conditional(
  1989                     makeBinary(EQ, make.Ident(clsym), makeNull()),
  1990                     make.Assign(
  1991                         make.Ident(clsym),
  1992                         makeCall(
  1993                             makeCall(makeCall(newcache,
  1994                                               names.getClass,
  1995                                               List.<JCExpression>nil()),
  1996                                      names.getComponentType,
  1997                                      List.<JCExpression>nil()),
  1998                             names.getClassLoader,
  1999                             List.<JCExpression>nil())).setType(syms.classLoaderType),
  2000                     make.Ident(clsym)).setType(syms.classLoaderType);
  2002             // returnResult := "{ return Class.forName(param1, false, cl$); }"
  2003             List<JCExpression> args = List.of(make.Ident(md.params.head.sym),
  2004                                               makeLit(syms.booleanType, 0),
  2005                                               clvalue);
  2006             returnResult = make.
  2007                 Block(0, List.<JCStatement>of(make.
  2008                               Call(make. // return
  2009                                    App(make.
  2010                                        Ident(forNameSym), args))));
  2011         } else {
  2012             // forNameSym := java.lang.Class.forName(String s)
  2013             Symbol forNameSym = lookupMethod(make_pos,
  2014                                              names.forName,
  2015                                              types.erasure(syms.classType),
  2016                                              List.of(syms.stringType));
  2017             // returnResult := "{ return Class.forName(param1); }"
  2018             returnResult = make.
  2019                 Block(0, List.of(make.
  2020                           Call(make. // return
  2021                               App(make.
  2022                                   QualIdent(forNameSym),
  2023                                   List.<JCExpression>of(make.
  2024                                                         Ident(md.params.
  2025                                                               head.sym))))));
  2028         // catchParam := ClassNotFoundException e1
  2029         VarSymbol catchParam =
  2030             new VarSymbol(SYNTHETIC, make.paramName(1),
  2031                           syms.classNotFoundExceptionType,
  2032                           classDollarSym);
  2034         JCStatement rethrow;
  2035         if (target.hasInitCause()) {
  2036             // rethrow = "throw new NoClassDefFoundError().initCause(e);
  2037             JCExpression throwExpr =
  2038                 makeCall(makeNewClass(syms.noClassDefFoundErrorType,
  2039                                       List.<JCExpression>nil()),
  2040                          names.initCause,
  2041                          List.<JCExpression>of(make.Ident(catchParam)));
  2042             rethrow = make.Throw(throwExpr);
  2043         } else {
  2044             // getMessageSym := ClassNotFoundException.getMessage()
  2045             Symbol getMessageSym = lookupMethod(make_pos,
  2046                                                 names.getMessage,
  2047                                                 syms.classNotFoundExceptionType,
  2048                                                 List.<Type>nil());
  2049             // rethrow = "throw new NoClassDefFoundError(e.getMessage());"
  2050             rethrow = make.
  2051                 Throw(makeNewClass(syms.noClassDefFoundErrorType,
  2052                           List.<JCExpression>of(make.App(make.Select(make.Ident(catchParam),
  2053                                                                      getMessageSym),
  2054                                                          List.<JCExpression>nil()))));
  2057         // rethrowStmt := "( $rethrow )"
  2058         JCBlock rethrowStmt = make.Block(0, List.of(rethrow));
  2060         // catchBlock := "catch ($catchParam) $rethrowStmt"
  2061         JCCatch catchBlock = make.Catch(make.VarDef(catchParam, null),
  2062                                       rethrowStmt);
  2064         // tryCatch := "try $returnResult $catchBlock"
  2065         JCStatement tryCatch = make.Try(returnResult,
  2066                                         List.of(catchBlock), null);
  2068         return make.Block(0, List.of(tryCatch));
  2070     // where
  2071         /** Create an attributed tree of the form left.name(). */
  2072         private JCMethodInvocation makeCall(JCExpression left, Name name, List<JCExpression> args) {
  2073             Assert.checkNonNull(left.type);
  2074             Symbol funcsym = lookupMethod(make_pos, name, left.type,
  2075                                           TreeInfo.types(args));
  2076             return make.App(make.Select(left, funcsym), args);
  2079     /** The Name Of The variable to cache T.class values.
  2080      *  @param sig      The signature of type T.
  2081      */
  2082     private Name cacheName(String sig) {
  2083         StringBuilder buf = new StringBuilder();
  2084         if (sig.startsWith("[")) {
  2085             buf = buf.append("array");
  2086             while (sig.startsWith("[")) {
  2087                 buf = buf.append(target.syntheticNameChar());
  2088                 sig = sig.substring(1);
  2090             if (sig.startsWith("L")) {
  2091                 sig = sig.substring(0, sig.length() - 1);
  2093         } else {
  2094             buf = buf.append("class" + target.syntheticNameChar());
  2096         buf = buf.append(sig.replace('.', target.syntheticNameChar()));
  2097         return names.fromString(buf.toString());
  2100     /** The variable symbol that caches T.class values.
  2101      *  If none exists yet, create a definition.
  2102      *  @param sig      The signature of type T.
  2103      *  @param pos      The position to report diagnostics, if any.
  2104      */
  2105     private VarSymbol cacheSym(DiagnosticPosition pos, String sig) {
  2106         ClassSymbol outerCacheClass = outerCacheClass();
  2107         Name cname = cacheName(sig);
  2108         VarSymbol cacheSym =
  2109             (VarSymbol)lookupSynthetic(cname, outerCacheClass.members());
  2110         if (cacheSym == null) {
  2111             cacheSym = new VarSymbol(
  2112                 STATIC | SYNTHETIC, cname, types.erasure(syms.classType), outerCacheClass);
  2113             enterSynthetic(pos, cacheSym, outerCacheClass.members());
  2115             JCVariableDecl cacheDef = make.VarDef(cacheSym, null);
  2116             JCClassDecl outerCacheClassDef = classDef(outerCacheClass);
  2117             outerCacheClassDef.defs = outerCacheClassDef.defs.prepend(cacheDef);
  2119         return cacheSym;
  2122     /** The tree simulating a T.class expression.
  2123      *  @param clazz      The tree identifying type T.
  2124      */
  2125     private JCExpression classOf(JCTree clazz) {
  2126         return classOfType(clazz.type, clazz.pos());
  2129     private JCExpression classOfType(Type type, DiagnosticPosition pos) {
  2130         switch (type.getTag()) {
  2131         case BYTE: case SHORT: case CHAR: case INT: case LONG: case FLOAT:
  2132         case DOUBLE: case BOOLEAN: case VOID:
  2133             // replace with <BoxedClass>.TYPE
  2134             ClassSymbol c = types.boxedClass(type);
  2135             Symbol typeSym =
  2136                 rs.accessBase(
  2137                     rs.findIdentInType(attrEnv, c.type, names.TYPE, VAR),
  2138                     pos, c.type, names.TYPE, true);
  2139             if (typeSym.kind == VAR)
  2140                 ((VarSymbol)typeSym).getConstValue(); // ensure initializer is evaluated
  2141             return make.QualIdent(typeSym);
  2142         case CLASS: case ARRAY:
  2143             if (target.hasClassLiterals()) {
  2144                 VarSymbol sym = new VarSymbol(
  2145                         STATIC | PUBLIC | FINAL, names._class,
  2146                         syms.classType, type.tsym);
  2147                 return make_at(pos).Select(make.Type(type), sym);
  2149             // replace with <cache == null ? cache = class$(tsig) : cache>
  2150             // where
  2151             //  - <tsig>  is the type signature of T,
  2152             //  - <cache> is the cache variable for tsig.
  2153             String sig =
  2154                 writer.xClassName(type).toString().replace('/', '.');
  2155             Symbol cs = cacheSym(pos, sig);
  2156             return make_at(pos).Conditional(
  2157                 makeBinary(EQ, make.Ident(cs), makeNull()),
  2158                 make.Assign(
  2159                     make.Ident(cs),
  2160                     make.App(
  2161                         make.Ident(classDollarSym(pos)),
  2162                         List.<JCExpression>of(make.Literal(CLASS, sig)
  2163                                               .setType(syms.stringType))))
  2164                 .setType(types.erasure(syms.classType)),
  2165                 make.Ident(cs)).setType(types.erasure(syms.classType));
  2166         default:
  2167             throw new AssertionError();
  2171 /**************************************************************************
  2172  * Code for enabling/disabling assertions.
  2173  *************************************************************************/
  2175     private ClassSymbol assertionsDisabledClassCache;
  2177     /**Used to create an auxiliary class to hold $assertionsDisabled for interfaces.
  2178      */
  2179     private ClassSymbol assertionsDisabledClass() {
  2180         if (assertionsDisabledClassCache != null) return assertionsDisabledClassCache;
  2182         assertionsDisabledClassCache = makeEmptyClass(STATIC | SYNTHETIC, outermostClassDef.sym).sym;
  2184         return assertionsDisabledClassCache;
  2187     // This code is not particularly robust if the user has
  2188     // previously declared a member named '$assertionsDisabled'.
  2189     // The same faulty idiom also appears in the translation of
  2190     // class literals above.  We should report an error if a
  2191     // previous declaration is not synthetic.
  2193     private JCExpression assertFlagTest(DiagnosticPosition pos) {
  2194         // Outermost class may be either true class or an interface.
  2195         ClassSymbol outermostClass = outermostClassDef.sym;
  2197         //only classes can hold a non-public field, look for a usable one:
  2198         ClassSymbol container = !currentClass.isInterface() ? currentClass :
  2199                 assertionsDisabledClass();
  2201         VarSymbol assertDisabledSym =
  2202             (VarSymbol)lookupSynthetic(dollarAssertionsDisabled,
  2203                                        container.members());
  2204         if (assertDisabledSym == null) {
  2205             assertDisabledSym =
  2206                 new VarSymbol(STATIC | FINAL | SYNTHETIC,
  2207                               dollarAssertionsDisabled,
  2208                               syms.booleanType,
  2209                               container);
  2210             enterSynthetic(pos, assertDisabledSym, container.members());
  2211             Symbol desiredAssertionStatusSym = lookupMethod(pos,
  2212                                                             names.desiredAssertionStatus,
  2213                                                             types.erasure(syms.classType),
  2214                                                             List.<Type>nil());
  2215             JCClassDecl containerDef = classDef(container);
  2216             make_at(containerDef.pos());
  2217             JCExpression notStatus = makeUnary(NOT, make.App(make.Select(
  2218                     classOfType(types.erasure(outermostClass.type),
  2219                                 containerDef.pos()),
  2220                     desiredAssertionStatusSym)));
  2221             JCVariableDecl assertDisabledDef = make.VarDef(assertDisabledSym,
  2222                                                    notStatus);
  2223             containerDef.defs = containerDef.defs.prepend(assertDisabledDef);
  2225             if (currentClass.isInterface()) {
  2226                 //need to load the assertions enabled/disabled state while
  2227                 //initializing the interface:
  2228                 JCClassDecl currentClassDef = classDef(currentClass);
  2229                 make_at(currentClassDef.pos());
  2230                 JCStatement dummy = make.If(make.QualIdent(assertDisabledSym), make.Skip(), null);
  2231                 JCBlock clinit = make.Block(STATIC, List.<JCStatement>of(dummy));
  2232                 currentClassDef.defs = currentClassDef.defs.prepend(clinit);
  2235         make_at(pos);
  2236         return makeUnary(NOT, make.Ident(assertDisabledSym));
  2240 /**************************************************************************
  2241  * Building blocks for let expressions
  2242  *************************************************************************/
  2244     interface TreeBuilder {
  2245         JCTree build(JCTree arg);
  2248     /** Construct an expression using the builder, with the given rval
  2249      *  expression as an argument to the builder.  However, the rval
  2250      *  expression must be computed only once, even if used multiple
  2251      *  times in the result of the builder.  We do that by
  2252      *  constructing a "let" expression that saves the rvalue into a
  2253      *  temporary variable and then uses the temporary variable in
  2254      *  place of the expression built by the builder.  The complete
  2255      *  resulting expression is of the form
  2256      *  <pre>
  2257      *    (let <b>TYPE</b> <b>TEMP</b> = <b>RVAL</b>;
  2258      *     in (<b>BUILDER</b>(<b>TEMP</b>)))
  2259      *  </pre>
  2260      *  where <code><b>TEMP</b></code> is a newly declared variable
  2261      *  in the let expression.
  2262      */
  2263     JCTree abstractRval(JCTree rval, Type type, TreeBuilder builder) {
  2264         rval = TreeInfo.skipParens(rval);
  2265         switch (rval.getTag()) {
  2266         case LITERAL:
  2267             return builder.build(rval);
  2268         case IDENT:
  2269             JCIdent id = (JCIdent) rval;
  2270             if ((id.sym.flags() & FINAL) != 0 && id.sym.owner.kind == MTH)
  2271                 return builder.build(rval);
  2273         VarSymbol var =
  2274             new VarSymbol(FINAL|SYNTHETIC,
  2275                           names.fromString(
  2276                                           target.syntheticNameChar()
  2277                                           + "" + rval.hashCode()),
  2278                                       type,
  2279                                       currentMethodSym);
  2280         rval = convert(rval,type);
  2281         JCVariableDecl def = make.VarDef(var, (JCExpression)rval); // XXX cast
  2282         JCTree built = builder.build(make.Ident(var));
  2283         JCTree res = make.LetExpr(def, built);
  2284         res.type = built.type;
  2285         return res;
  2288     // same as above, with the type of the temporary variable computed
  2289     JCTree abstractRval(JCTree rval, TreeBuilder builder) {
  2290         return abstractRval(rval, rval.type, builder);
  2293     // same as above, but for an expression that may be used as either
  2294     // an rvalue or an lvalue.  This requires special handling for
  2295     // Select expressions, where we place the left-hand-side of the
  2296     // select in a temporary, and for Indexed expressions, where we
  2297     // place both the indexed expression and the index value in temps.
  2298     JCTree abstractLval(JCTree lval, final TreeBuilder builder) {
  2299         lval = TreeInfo.skipParens(lval);
  2300         switch (lval.getTag()) {
  2301         case IDENT:
  2302             return builder.build(lval);
  2303         case SELECT: {
  2304             final JCFieldAccess s = (JCFieldAccess)lval;
  2305             JCTree selected = TreeInfo.skipParens(s.selected);
  2306             Symbol lid = TreeInfo.symbol(s.selected);
  2307             if (lid != null && lid.kind == TYP) return builder.build(lval);
  2308             return abstractRval(s.selected, new TreeBuilder() {
  2309                     public JCTree build(final JCTree selected) {
  2310                         return builder.build(make.Select((JCExpression)selected, s.sym));
  2312                 });
  2314         case INDEXED: {
  2315             final JCArrayAccess i = (JCArrayAccess)lval;
  2316             return abstractRval(i.indexed, new TreeBuilder() {
  2317                     public JCTree build(final JCTree indexed) {
  2318                         return abstractRval(i.index, syms.intType, new TreeBuilder() {
  2319                                 public JCTree build(final JCTree index) {
  2320                                     JCTree newLval = make.Indexed((JCExpression)indexed,
  2321                                                                 (JCExpression)index);
  2322                                     newLval.setType(i.type);
  2323                                     return builder.build(newLval);
  2325                             });
  2327                 });
  2329         case TYPECAST: {
  2330             return abstractLval(((JCTypeCast)lval).expr, builder);
  2333         throw new AssertionError(lval);
  2336     // evaluate and discard the first expression, then evaluate the second.
  2337     JCTree makeComma(final JCTree expr1, final JCTree expr2) {
  2338         return abstractRval(expr1, new TreeBuilder() {
  2339                 public JCTree build(final JCTree discarded) {
  2340                     return expr2;
  2342             });
  2345 /**************************************************************************
  2346  * Translation methods
  2347  *************************************************************************/
  2349     /** Visitor argument: enclosing operator node.
  2350      */
  2351     private JCExpression enclOp;
  2353     /** Visitor method: Translate a single node.
  2354      *  Attach the source position from the old tree to its replacement tree.
  2355      */
  2356     public <T extends JCTree> T translate(T tree) {
  2357         if (tree == null) {
  2358             return null;
  2359         } else {
  2360             make_at(tree.pos());
  2361             T result = super.translate(tree);
  2362             if (endPosTable != null && result != tree) {
  2363                 endPosTable.replaceTree(tree, result);
  2365             return result;
  2369     /** Visitor method: Translate a single node, boxing or unboxing if needed.
  2370      */
  2371     public <T extends JCTree> T translate(T tree, Type type) {
  2372         return (tree == null) ? null : boxIfNeeded(translate(tree), type);
  2375     /** Visitor method: Translate tree.
  2376      */
  2377     public <T extends JCTree> T translate(T tree, JCExpression enclOp) {
  2378         JCExpression prevEnclOp = this.enclOp;
  2379         this.enclOp = enclOp;
  2380         T res = translate(tree);
  2381         this.enclOp = prevEnclOp;
  2382         return res;
  2385     /** Visitor method: Translate list of trees.
  2386      */
  2387     public <T extends JCTree> List<T> translate(List<T> trees, JCExpression enclOp) {
  2388         JCExpression prevEnclOp = this.enclOp;
  2389         this.enclOp = enclOp;
  2390         List<T> res = translate(trees);
  2391         this.enclOp = prevEnclOp;
  2392         return res;
  2395     /** Visitor method: Translate list of trees.
  2396      */
  2397     public <T extends JCTree> List<T> translate(List<T> trees, Type type) {
  2398         if (trees == null) return null;
  2399         for (List<T> l = trees; l.nonEmpty(); l = l.tail)
  2400             l.head = translate(l.head, type);
  2401         return trees;
  2404     public void visitTopLevel(JCCompilationUnit tree) {
  2405         if (needPackageInfoClass(tree)) {
  2406             Name name = names.package_info;
  2407             long flags = Flags.ABSTRACT | Flags.INTERFACE;
  2408             if (target.isPackageInfoSynthetic())
  2409                 // package-info is marked SYNTHETIC in JDK 1.6 and later releases
  2410                 flags = flags | Flags.SYNTHETIC;
  2411             JCClassDecl packageAnnotationsClass
  2412                 = make.ClassDef(make.Modifiers(flags,
  2413                                                tree.packageAnnotations),
  2414                                 name, List.<JCTypeParameter>nil(),
  2415                                 null, List.<JCExpression>nil(), List.<JCTree>nil());
  2416             ClassSymbol c = tree.packge.package_info;
  2417             c.flags_field |= flags;
  2418             c.setAttributes(tree.packge);
  2419             ClassType ctype = (ClassType) c.type;
  2420             ctype.supertype_field = syms.objectType;
  2421             ctype.interfaces_field = List.nil();
  2422             packageAnnotationsClass.sym = c;
  2424             translated.append(packageAnnotationsClass);
  2427     // where
  2428     private boolean needPackageInfoClass(JCCompilationUnit tree) {
  2429         switch (pkginfoOpt) {
  2430             case ALWAYS:
  2431                 return true;
  2432             case LEGACY:
  2433                 return tree.packageAnnotations.nonEmpty();
  2434             case NONEMPTY:
  2435                 for (Attribute.Compound a :
  2436                          tree.packge.getDeclarationAttributes()) {
  2437                     Attribute.RetentionPolicy p = types.getRetention(a);
  2438                     if (p != Attribute.RetentionPolicy.SOURCE)
  2439                         return true;
  2441                 return false;
  2443         throw new AssertionError();
  2446     public void visitClassDef(JCClassDecl tree) {
  2447         ClassSymbol currentClassPrev = currentClass;
  2448         MethodSymbol currentMethodSymPrev = currentMethodSym;
  2449         currentClass = tree.sym;
  2450         currentMethodSym = null;
  2451         classdefs.put(currentClass, tree);
  2453         proxies = proxies.dup(currentClass);
  2454         List<VarSymbol> prevOuterThisStack = outerThisStack;
  2456         // If this is an enum definition
  2457         if ((tree.mods.flags & ENUM) != 0 &&
  2458             (types.supertype(currentClass.type).tsym.flags() & ENUM) == 0)
  2459             visitEnumDef(tree);
  2461         // If this is a nested class, define a this$n field for
  2462         // it and add to proxies.
  2463         JCVariableDecl otdef = null;
  2464         if (currentClass.hasOuterInstance())
  2465             otdef = outerThisDef(tree.pos, currentClass);
  2467         // If this is a local class, define proxies for all its free variables.
  2468         List<JCVariableDecl> fvdefs = freevarDefs(
  2469             tree.pos, freevars(currentClass), currentClass);
  2471         // Recursively translate superclass, interfaces.
  2472         tree.extending = translate(tree.extending);
  2473         tree.implementing = translate(tree.implementing);
  2475         if (currentClass.isLocal()) {
  2476             ClassSymbol encl = currentClass.owner.enclClass();
  2477             if (encl.trans_local == null) {
  2478                 encl.trans_local = List.nil();
  2480             encl.trans_local = encl.trans_local.prepend(currentClass);
  2483         // Recursively translate members, taking into account that new members
  2484         // might be created during the translation and prepended to the member
  2485         // list `tree.defs'.
  2486         List<JCTree> seen = List.nil();
  2487         while (tree.defs != seen) {
  2488             List<JCTree> unseen = tree.defs;
  2489             for (List<JCTree> l = unseen; l.nonEmpty() && l != seen; l = l.tail) {
  2490                 JCTree outermostMemberDefPrev = outermostMemberDef;
  2491                 if (outermostMemberDefPrev == null) outermostMemberDef = l.head;
  2492                 l.head = translate(l.head);
  2493                 outermostMemberDef = outermostMemberDefPrev;
  2495             seen = unseen;
  2498         // Convert a protected modifier to public, mask static modifier.
  2499         if ((tree.mods.flags & PROTECTED) != 0) tree.mods.flags |= PUBLIC;
  2500         tree.mods.flags &= ClassFlags;
  2502         // Convert name to flat representation, replacing '.' by '$'.
  2503         tree.name = Convert.shortName(currentClass.flatName());
  2505         // Add this$n and free variables proxy definitions to class.
  2507         for (List<JCVariableDecl> l = fvdefs; l.nonEmpty(); l = l.tail) {
  2508             tree.defs = tree.defs.prepend(l.head);
  2509             enterSynthetic(tree.pos(), l.head.sym, currentClass.members());
  2511         if (currentClass.hasOuterInstance()) {
  2512             tree.defs = tree.defs.prepend(otdef);
  2513             enterSynthetic(tree.pos(), otdef.sym, currentClass.members());
  2516         proxies = proxies.leave();
  2517         outerThisStack = prevOuterThisStack;
  2519         // Append translated tree to `translated' queue.
  2520         translated.append(tree);
  2522         currentClass = currentClassPrev;
  2523         currentMethodSym = currentMethodSymPrev;
  2525         // Return empty block {} as a placeholder for an inner class.
  2526         result = make_at(tree.pos()).Block(0, List.<JCStatement>nil());
  2529     /** Translate an enum class. */
  2530     private void visitEnumDef(JCClassDecl tree) {
  2531         make_at(tree.pos());
  2533         // add the supertype, if needed
  2534         if (tree.extending == null)
  2535             tree.extending = make.Type(types.supertype(tree.type));
  2537         // classOfType adds a cache field to tree.defs unless
  2538         // target.hasClassLiterals().
  2539         JCExpression e_class = classOfType(tree.sym.type, tree.pos()).
  2540             setType(types.erasure(syms.classType));
  2542         // process each enumeration constant, adding implicit constructor parameters
  2543         int nextOrdinal = 0;
  2544         ListBuffer<JCExpression> values = new ListBuffer<JCExpression>();
  2545         ListBuffer<JCTree> enumDefs = new ListBuffer<JCTree>();
  2546         ListBuffer<JCTree> otherDefs = new ListBuffer<JCTree>();
  2547         for (List<JCTree> defs = tree.defs;
  2548              defs.nonEmpty();
  2549              defs=defs.tail) {
  2550             if (defs.head.hasTag(VARDEF) && (((JCVariableDecl) defs.head).mods.flags & ENUM) != 0) {
  2551                 JCVariableDecl var = (JCVariableDecl)defs.head;
  2552                 visitEnumConstantDef(var, nextOrdinal++);
  2553                 values.append(make.QualIdent(var.sym));
  2554                 enumDefs.append(var);
  2555             } else {
  2556                 otherDefs.append(defs.head);
  2560         // private static final T[] #VALUES = { a, b, c };
  2561         Name valuesName = names.fromString(target.syntheticNameChar() + "VALUES");
  2562         while (tree.sym.members().lookup(valuesName).scope != null) // avoid name clash
  2563             valuesName = names.fromString(valuesName + "" + target.syntheticNameChar());
  2564         Type arrayType = new ArrayType(types.erasure(tree.type), syms.arrayClass);
  2565         VarSymbol valuesVar = new VarSymbol(PRIVATE|FINAL|STATIC|SYNTHETIC,
  2566                                             valuesName,
  2567                                             arrayType,
  2568                                             tree.type.tsym);
  2569         JCNewArray newArray = make.NewArray(make.Type(types.erasure(tree.type)),
  2570                                           List.<JCExpression>nil(),
  2571                                           values.toList());
  2572         newArray.type = arrayType;
  2573         enumDefs.append(make.VarDef(valuesVar, newArray));
  2574         tree.sym.members().enter(valuesVar);
  2576         Symbol valuesSym = lookupMethod(tree.pos(), names.values,
  2577                                         tree.type, List.<Type>nil());
  2578         List<JCStatement> valuesBody;
  2579         if (useClone()) {
  2580             // return (T[]) $VALUES.clone();
  2581             JCTypeCast valuesResult =
  2582                 make.TypeCast(valuesSym.type.getReturnType(),
  2583                               make.App(make.Select(make.Ident(valuesVar),
  2584                                                    syms.arrayCloneMethod)));
  2585             valuesBody = List.<JCStatement>of(make.Return(valuesResult));
  2586         } else {
  2587             // template: T[] $result = new T[$values.length];
  2588             Name resultName = names.fromString(target.syntheticNameChar() + "result");
  2589             while (tree.sym.members().lookup(resultName).scope != null) // avoid name clash
  2590                 resultName = names.fromString(resultName + "" + target.syntheticNameChar());
  2591             VarSymbol resultVar = new VarSymbol(FINAL|SYNTHETIC,
  2592                                                 resultName,
  2593                                                 arrayType,
  2594                                                 valuesSym);
  2595             JCNewArray resultArray = make.NewArray(make.Type(types.erasure(tree.type)),
  2596                                   List.of(make.Select(make.Ident(valuesVar), syms.lengthVar)),
  2597                                   null);
  2598             resultArray.type = arrayType;
  2599             JCVariableDecl decl = make.VarDef(resultVar, resultArray);
  2601             // template: System.arraycopy($VALUES, 0, $result, 0, $VALUES.length);
  2602             if (systemArraycopyMethod == null) {
  2603                 systemArraycopyMethod =
  2604                     new MethodSymbol(PUBLIC | STATIC,
  2605                                      names.fromString("arraycopy"),
  2606                                      new MethodType(List.<Type>of(syms.objectType,
  2607                                                             syms.intType,
  2608                                                             syms.objectType,
  2609                                                             syms.intType,
  2610                                                             syms.intType),
  2611                                                     syms.voidType,
  2612                                                     List.<Type>nil(),
  2613                                                     syms.methodClass),
  2614                                      syms.systemType.tsym);
  2616             JCStatement copy =
  2617                 make.Exec(make.App(make.Select(make.Ident(syms.systemType.tsym),
  2618                                                systemArraycopyMethod),
  2619                           List.of(make.Ident(valuesVar), make.Literal(0),
  2620                                   make.Ident(resultVar), make.Literal(0),
  2621                                   make.Select(make.Ident(valuesVar), syms.lengthVar))));
  2623             // template: return $result;
  2624             JCStatement ret = make.Return(make.Ident(resultVar));
  2625             valuesBody = List.<JCStatement>of(decl, copy, ret);
  2628         JCMethodDecl valuesDef =
  2629              make.MethodDef((MethodSymbol)valuesSym, make.Block(0, valuesBody));
  2631         enumDefs.append(valuesDef);
  2633         if (debugLower)
  2634             System.err.println(tree.sym + ".valuesDef = " + valuesDef);
  2636         /** The template for the following code is:
  2638          *     public static E valueOf(String name) {
  2639          *         return (E)Enum.valueOf(E.class, name);
  2640          *     }
  2642          *  where E is tree.sym
  2643          */
  2644         MethodSymbol valueOfSym = lookupMethod(tree.pos(),
  2645                          names.valueOf,
  2646                          tree.sym.type,
  2647                          List.of(syms.stringType));
  2648         Assert.check((valueOfSym.flags() & STATIC) != 0);
  2649         VarSymbol nameArgSym = valueOfSym.params.head;
  2650         JCIdent nameVal = make.Ident(nameArgSym);
  2651         JCStatement enum_ValueOf =
  2652             make.Return(make.TypeCast(tree.sym.type,
  2653                                       makeCall(make.Ident(syms.enumSym),
  2654                                                names.valueOf,
  2655                                                List.of(e_class, nameVal))));
  2656         JCMethodDecl valueOf = make.MethodDef(valueOfSym,
  2657                                            make.Block(0, List.of(enum_ValueOf)));
  2658         nameVal.sym = valueOf.params.head.sym;
  2659         if (debugLower)
  2660             System.err.println(tree.sym + ".valueOf = " + valueOf);
  2661         enumDefs.append(valueOf);
  2663         enumDefs.appendList(otherDefs.toList());
  2664         tree.defs = enumDefs.toList();
  2666         // where
  2667         private MethodSymbol systemArraycopyMethod;
  2668         private boolean useClone() {
  2669             try {
  2670                 Scope.Entry e = syms.objectType.tsym.members().lookup(names.clone);
  2671                 return (e.sym != null);
  2673             catch (CompletionFailure e) {
  2674                 return false;
  2678     /** Translate an enumeration constant and its initializer. */
  2679     private void visitEnumConstantDef(JCVariableDecl var, int ordinal) {
  2680         JCNewClass varDef = (JCNewClass)var.init;
  2681         varDef.args = varDef.args.
  2682             prepend(makeLit(syms.intType, ordinal)).
  2683             prepend(makeLit(syms.stringType, var.name.toString()));
  2686     public void visitMethodDef(JCMethodDecl tree) {
  2687         if (tree.name == names.init && (currentClass.flags_field&ENUM) != 0) {
  2688             // Add "String $enum$name, int $enum$ordinal" to the beginning of the
  2689             // argument list for each constructor of an enum.
  2690             JCVariableDecl nameParam = make_at(tree.pos()).
  2691                 Param(names.fromString(target.syntheticNameChar() +
  2692                                        "enum" + target.syntheticNameChar() + "name"),
  2693                       syms.stringType, tree.sym);
  2694             nameParam.mods.flags |= SYNTHETIC; nameParam.sym.flags_field |= SYNTHETIC;
  2695             JCVariableDecl ordParam = make.
  2696                 Param(names.fromString(target.syntheticNameChar() +
  2697                                        "enum" + target.syntheticNameChar() +
  2698                                        "ordinal"),
  2699                       syms.intType, tree.sym);
  2700             ordParam.mods.flags |= SYNTHETIC; ordParam.sym.flags_field |= SYNTHETIC;
  2702             tree.params = tree.params.prepend(ordParam).prepend(nameParam);
  2704             MethodSymbol m = tree.sym;
  2705             m.extraParams = m.extraParams.prepend(ordParam.sym);
  2706             m.extraParams = m.extraParams.prepend(nameParam.sym);
  2707             Type olderasure = m.erasure(types);
  2708             m.erasure_field = new MethodType(
  2709                 olderasure.getParameterTypes().prepend(syms.intType).prepend(syms.stringType),
  2710                 olderasure.getReturnType(),
  2711                 olderasure.getThrownTypes(),
  2712                 syms.methodClass);
  2715         JCMethodDecl prevMethodDef = currentMethodDef;
  2716         MethodSymbol prevMethodSym = currentMethodSym;
  2717         try {
  2718             currentMethodDef = tree;
  2719             currentMethodSym = tree.sym;
  2720             visitMethodDefInternal(tree);
  2721         } finally {
  2722             currentMethodDef = prevMethodDef;
  2723             currentMethodSym = prevMethodSym;
  2726     //where
  2727     private void visitMethodDefInternal(JCMethodDecl tree) {
  2728         if (tree.name == names.init &&
  2729             (currentClass.isInner() || currentClass.isLocal())) {
  2730             // We are seeing a constructor of an inner class.
  2731             MethodSymbol m = tree.sym;
  2733             // Push a new proxy scope for constructor parameters.
  2734             // and create definitions for any this$n and proxy parameters.
  2735             proxies = proxies.dup(m);
  2736             List<VarSymbol> prevOuterThisStack = outerThisStack;
  2737             List<VarSymbol> fvs = freevars(currentClass);
  2738             JCVariableDecl otdef = null;
  2739             if (currentClass.hasOuterInstance())
  2740                 otdef = outerThisDef(tree.pos, m);
  2741             List<JCVariableDecl> fvdefs = freevarDefs(tree.pos, fvs, m, PARAMETER);
  2743             // Recursively translate result type, parameters and thrown list.
  2744             tree.restype = translate(tree.restype);
  2745             tree.params = translateVarDefs(tree.params);
  2746             tree.thrown = translate(tree.thrown);
  2748             // when compiling stubs, don't process body
  2749             if (tree.body == null) {
  2750                 result = tree;
  2751                 return;
  2754             // Add this$n (if needed) in front of and free variables behind
  2755             // constructor parameter list.
  2756             tree.params = tree.params.appendList(fvdefs);
  2757             if (currentClass.hasOuterInstance())
  2758                 tree.params = tree.params.prepend(otdef);
  2760             // If this is an initial constructor, i.e., it does not start with
  2761             // this(...), insert initializers for this$n and proxies
  2762             // before (pre-1.4, after) the call to superclass constructor.
  2763             JCStatement selfCall = translate(tree.body.stats.head);
  2765             List<JCStatement> added = List.nil();
  2766             if (fvs.nonEmpty()) {
  2767                 List<Type> addedargtypes = List.nil();
  2768                 for (List<VarSymbol> l = fvs; l.nonEmpty(); l = l.tail) {
  2769                     if (TreeInfo.isInitialConstructor(tree)) {
  2770                         final Name pName = proxyName(l.head.name);
  2771                         m.capturedLocals =
  2772                             m.capturedLocals.append((VarSymbol)
  2773                                                     (proxies.lookup(pName).sym));
  2774                         added = added.prepend(
  2775                           initField(tree.body.pos, pName));
  2777                     addedargtypes = addedargtypes.prepend(l.head.erasure(types));
  2779                 Type olderasure = m.erasure(types);
  2780                 m.erasure_field = new MethodType(
  2781                     olderasure.getParameterTypes().appendList(addedargtypes),
  2782                     olderasure.getReturnType(),
  2783                     olderasure.getThrownTypes(),
  2784                     syms.methodClass);
  2786             if (currentClass.hasOuterInstance() &&
  2787                 TreeInfo.isInitialConstructor(tree))
  2789                 added = added.prepend(initOuterThis(tree.body.pos));
  2792             // pop local variables from proxy stack
  2793             proxies = proxies.leave();
  2795             // recursively translate following local statements and
  2796             // combine with this- or super-call
  2797             List<JCStatement> stats = translate(tree.body.stats.tail);
  2798             if (target.initializeFieldsBeforeSuper())
  2799                 tree.body.stats = stats.prepend(selfCall).prependList(added);
  2800             else
  2801                 tree.body.stats = stats.prependList(added).prepend(selfCall);
  2803             outerThisStack = prevOuterThisStack;
  2804         } else {
  2805             Map<Symbol, Symbol> prevLambdaTranslationMap =
  2806                     lambdaTranslationMap;
  2807             try {
  2808                 lambdaTranslationMap = (tree.sym.flags() & SYNTHETIC) != 0 &&
  2809                         tree.sym.name.startsWith(names.lambda) ?
  2810                         makeTranslationMap(tree) : null;
  2811                 super.visitMethodDef(tree);
  2812             } finally {
  2813                 lambdaTranslationMap = prevLambdaTranslationMap;
  2816         result = tree;
  2818     //where
  2819         private Map<Symbol, Symbol> makeTranslationMap(JCMethodDecl tree) {
  2820             Map<Symbol, Symbol> translationMap = new HashMap<Symbol,Symbol>();
  2821             for (JCVariableDecl vd : tree.params) {
  2822                 Symbol p = vd.sym;
  2823                 if (p != p.baseSymbol()) {
  2824                     translationMap.put(p.baseSymbol(), p);
  2827             return translationMap;
  2830     public void visitAnnotatedType(JCAnnotatedType tree) {
  2831         // No need to retain type annotations in the tree
  2832         // tree.annotations = translate(tree.annotations);
  2833         tree.annotations = List.nil();
  2834         tree.underlyingType = translate(tree.underlyingType);
  2835         // but maintain type annotations in the type.
  2836         if (tree.type.isAnnotated()) {
  2837             tree.type = tree.underlyingType.type.unannotatedType().annotatedType(tree.type.getAnnotationMirrors());
  2838         } else if (tree.underlyingType.type.isAnnotated()) {
  2839             tree.type = tree.underlyingType.type;
  2841         result = tree;
  2844     public void visitTypeCast(JCTypeCast tree) {
  2845         tree.clazz = translate(tree.clazz);
  2846         if (tree.type.isPrimitive() != tree.expr.type.isPrimitive())
  2847             tree.expr = translate(tree.expr, tree.type);
  2848         else
  2849             tree.expr = translate(tree.expr);
  2850         result = tree;
  2853     public void visitNewClass(JCNewClass tree) {
  2854         ClassSymbol c = (ClassSymbol)tree.constructor.owner;
  2856         // Box arguments, if necessary
  2857         boolean isEnum = (tree.constructor.owner.flags() & ENUM) != 0;
  2858         List<Type> argTypes = tree.constructor.type.getParameterTypes();
  2859         if (isEnum) argTypes = argTypes.prepend(syms.intType).prepend(syms.stringType);
  2860         tree.args = boxArgs(argTypes, tree.args, tree.varargsElement);
  2861         tree.varargsElement = null;
  2863         // If created class is local, add free variables after
  2864         // explicit constructor arguments.
  2865         if (c.isLocal()) {
  2866             tree.args = tree.args.appendList(loadFreevars(tree.pos(), freevars(c)));
  2869         // If an access constructor is used, append null as a last argument.
  2870         Symbol constructor = accessConstructor(tree.pos(), tree.constructor);
  2871         if (constructor != tree.constructor) {
  2872             tree.args = tree.args.append(makeNull());
  2873             tree.constructor = constructor;
  2876         // If created class has an outer instance, and new is qualified, pass
  2877         // qualifier as first argument. If new is not qualified, pass the
  2878         // correct outer instance as first argument.
  2879         if (c.hasOuterInstance()) {
  2880             JCExpression thisArg;
  2881             if (tree.encl != null) {
  2882                 thisArg = attr.makeNullCheck(translate(tree.encl));
  2883                 thisArg.type = tree.encl.type;
  2884             } else if (c.isLocal()) {
  2885                 // local class
  2886                 thisArg = makeThis(tree.pos(), c.type.getEnclosingType().tsym);
  2887             } else {
  2888                 // nested class
  2889                 thisArg = makeOwnerThis(tree.pos(), c, false);
  2891             tree.args = tree.args.prepend(thisArg);
  2893         tree.encl = null;
  2895         // If we have an anonymous class, create its flat version, rather
  2896         // than the class or interface following new.
  2897         if (tree.def != null) {
  2898             translate(tree.def);
  2899             tree.clazz = access(make_at(tree.clazz.pos()).Ident(tree.def.sym));
  2900             tree.def = null;
  2901         } else {
  2902             tree.clazz = access(c, tree.clazz, enclOp, false);
  2904         result = tree;
  2907     // Simplify conditionals with known constant controlling expressions.
  2908     // This allows us to avoid generating supporting declarations for
  2909     // the dead code, which will not be eliminated during code generation.
  2910     // Note that Flow.isFalse and Flow.isTrue only return true
  2911     // for constant expressions in the sense of JLS 15.27, which
  2912     // are guaranteed to have no side-effects.  More aggressive
  2913     // constant propagation would require that we take care to
  2914     // preserve possible side-effects in the condition expression.
  2916     /** Visitor method for conditional expressions.
  2917      */
  2918     @Override
  2919     public void visitConditional(JCConditional tree) {
  2920         JCTree cond = tree.cond = translate(tree.cond, syms.booleanType);
  2921         if (cond.type.isTrue()) {
  2922             result = convert(translate(tree.truepart, tree.type), tree.type);
  2923             addPrunedInfo(cond);
  2924         } else if (cond.type.isFalse()) {
  2925             result = convert(translate(tree.falsepart, tree.type), tree.type);
  2926             addPrunedInfo(cond);
  2927         } else {
  2928             // Condition is not a compile-time constant.
  2929             tree.truepart = translate(tree.truepart, tree.type);
  2930             tree.falsepart = translate(tree.falsepart, tree.type);
  2931             result = tree;
  2934 //where
  2935     private JCTree convert(JCTree tree, Type pt) {
  2936         if (tree.type == pt || tree.type.hasTag(BOT))
  2937             return tree;
  2938         JCTree result = make_at(tree.pos()).TypeCast(make.Type(pt), (JCExpression)tree);
  2939         result.type = (tree.type.constValue() != null) ? cfolder.coerce(tree.type, pt)
  2940                                                        : pt;
  2941         return result;
  2944     /** Visitor method for if statements.
  2945      */
  2946     public void visitIf(JCIf tree) {
  2947         JCTree cond = tree.cond = translate(tree.cond, syms.booleanType);
  2948         if (cond.type.isTrue()) {
  2949             result = translate(tree.thenpart);
  2950             addPrunedInfo(cond);
  2951         } else if (cond.type.isFalse()) {
  2952             if (tree.elsepart != null) {
  2953                 result = translate(tree.elsepart);
  2954             } else {
  2955                 result = make.Skip();
  2957             addPrunedInfo(cond);
  2958         } else {
  2959             // Condition is not a compile-time constant.
  2960             tree.thenpart = translate(tree.thenpart);
  2961             tree.elsepart = translate(tree.elsepart);
  2962             result = tree;
  2966     /** Visitor method for assert statements. Translate them away.
  2967      */
  2968     public void visitAssert(JCAssert tree) {
  2969         DiagnosticPosition detailPos = (tree.detail == null) ? tree.pos() : tree.detail.pos();
  2970         tree.cond = translate(tree.cond, syms.booleanType);
  2971         if (!tree.cond.type.isTrue()) {
  2972             JCExpression cond = assertFlagTest(tree.pos());
  2973             List<JCExpression> exnArgs = (tree.detail == null) ?
  2974                 List.<JCExpression>nil() : List.of(translate(tree.detail));
  2975             if (!tree.cond.type.isFalse()) {
  2976                 cond = makeBinary
  2977                     (AND,
  2978                      cond,
  2979                      makeUnary(NOT, tree.cond));
  2981             result =
  2982                 make.If(cond,
  2983                         make_at(tree).
  2984                            Throw(makeNewClass(syms.assertionErrorType, exnArgs)),
  2985                         null);
  2986         } else {
  2987             result = make.Skip();
  2991     public void visitApply(JCMethodInvocation tree) {
  2992         Symbol meth = TreeInfo.symbol(tree.meth);
  2993         List<Type> argtypes = meth.type.getParameterTypes();
  2994         if (allowEnums &&
  2995             meth.name==names.init &&
  2996             meth.owner == syms.enumSym)
  2997             argtypes = argtypes.tail.tail;
  2998         tree.args = boxArgs(argtypes, tree.args, tree.varargsElement);
  2999         tree.varargsElement = null;
  3000         Name methName = TreeInfo.name(tree.meth);
  3001         if (meth.name==names.init) {
  3002             // We are seeing a this(...) or super(...) constructor call.
  3003             // If an access constructor is used, append null as a last argument.
  3004             Symbol constructor = accessConstructor(tree.pos(), meth);
  3005             if (constructor != meth) {
  3006                 tree.args = tree.args.append(makeNull());
  3007                 TreeInfo.setSymbol(tree.meth, constructor);
  3010             // If we are calling a constructor of a local class, add
  3011             // free variables after explicit constructor arguments.
  3012             ClassSymbol c = (ClassSymbol)constructor.owner;
  3013             if (c.isLocal()) {
  3014                 tree.args = tree.args.appendList(loadFreevars(tree.pos(), freevars(c)));
  3017             // If we are calling a constructor of an enum class, pass
  3018             // along the name and ordinal arguments
  3019             if ((c.flags_field&ENUM) != 0 || c.getQualifiedName() == names.java_lang_Enum) {
  3020                 List<JCVariableDecl> params = currentMethodDef.params;
  3021                 if (currentMethodSym.owner.hasOuterInstance())
  3022                     params = params.tail; // drop this$n
  3023                 tree.args = tree.args
  3024                     .prepend(make_at(tree.pos()).Ident(params.tail.head.sym)) // ordinal
  3025                     .prepend(make.Ident(params.head.sym)); // name
  3028             // If we are calling a constructor of a class with an outer
  3029             // instance, and the call
  3030             // is qualified, pass qualifier as first argument in front of
  3031             // the explicit constructor arguments. If the call
  3032             // is not qualified, pass the correct outer instance as
  3033             // first argument.
  3034             if (c.hasOuterInstance()) {
  3035                 JCExpression thisArg;
  3036                 if (tree.meth.hasTag(SELECT)) {
  3037                     thisArg = attr.
  3038                         makeNullCheck(translate(((JCFieldAccess) tree.meth).selected));
  3039                     tree.meth = make.Ident(constructor);
  3040                     ((JCIdent) tree.meth).name = methName;
  3041                 } else if (c.isLocal() || methName == names._this){
  3042                     // local class or this() call
  3043                     thisArg = makeThis(tree.meth.pos(), c.type.getEnclosingType().tsym);
  3044                 } else {
  3045                     // super() call of nested class - never pick 'this'
  3046                     thisArg = makeOwnerThisN(tree.meth.pos(), c, false);
  3048                 tree.args = tree.args.prepend(thisArg);
  3050         } else {
  3051             // We are seeing a normal method invocation; translate this as usual.
  3052             tree.meth = translate(tree.meth);
  3054             // If the translated method itself is an Apply tree, we are
  3055             // seeing an access method invocation. In this case, append
  3056             // the method arguments to the arguments of the access method.
  3057             if (tree.meth.hasTag(APPLY)) {
  3058                 JCMethodInvocation app = (JCMethodInvocation)tree.meth;
  3059                 app.args = tree.args.prependList(app.args);
  3060                 result = app;
  3061                 return;
  3064         result = tree;
  3067     List<JCExpression> boxArgs(List<Type> parameters, List<JCExpression> _args, Type varargsElement) {
  3068         List<JCExpression> args = _args;
  3069         if (parameters.isEmpty()) return args;
  3070         boolean anyChanges = false;
  3071         ListBuffer<JCExpression> result = new ListBuffer<JCExpression>();
  3072         while (parameters.tail.nonEmpty()) {
  3073             JCExpression arg = translate(args.head, parameters.head);
  3074             anyChanges |= (arg != args.head);
  3075             result.append(arg);
  3076             args = args.tail;
  3077             parameters = parameters.tail;
  3079         Type parameter = parameters.head;
  3080         if (varargsElement != null) {
  3081             anyChanges = true;
  3082             ListBuffer<JCExpression> elems = new ListBuffer<JCExpression>();
  3083             while (args.nonEmpty()) {
  3084                 JCExpression arg = translate(args.head, varargsElement);
  3085                 elems.append(arg);
  3086                 args = args.tail;
  3088             JCNewArray boxedArgs = make.NewArray(make.Type(varargsElement),
  3089                                                List.<JCExpression>nil(),
  3090                                                elems.toList());
  3091             boxedArgs.type = new ArrayType(varargsElement, syms.arrayClass);
  3092             result.append(boxedArgs);
  3093         } else {
  3094             if (args.length() != 1) throw new AssertionError(args);
  3095             JCExpression arg = translate(args.head, parameter);
  3096             anyChanges |= (arg != args.head);
  3097             result.append(arg);
  3098             if (!anyChanges) return _args;
  3100         return result.toList();
  3103     /** Expand a boxing or unboxing conversion if needed. */
  3104     @SuppressWarnings("unchecked") // XXX unchecked
  3105     <T extends JCTree> T boxIfNeeded(T tree, Type type) {
  3106         boolean havePrimitive = tree.type.isPrimitive();
  3107         if (havePrimitive == type.isPrimitive())
  3108             return tree;
  3109         if (havePrimitive) {
  3110             Type unboxedTarget = types.unboxedType(type);
  3111             if (!unboxedTarget.hasTag(NONE)) {
  3112                 if (!types.isSubtype(tree.type, unboxedTarget)) //e.g. Character c = 89;
  3113                     tree.type = unboxedTarget.constType(tree.type.constValue());
  3114                 return (T)boxPrimitive((JCExpression)tree, type);
  3115             } else {
  3116                 tree = (T)boxPrimitive((JCExpression)tree);
  3118         } else {
  3119             tree = (T)unbox((JCExpression)tree, type);
  3121         return tree;
  3124     /** Box up a single primitive expression. */
  3125     JCExpression boxPrimitive(JCExpression tree) {
  3126         return boxPrimitive(tree, types.boxedClass(tree.type).type);
  3129     /** Box up a single primitive expression. */
  3130     JCExpression boxPrimitive(JCExpression tree, Type box) {
  3131         make_at(tree.pos());
  3132         if (target.boxWithConstructors()) {
  3133             Symbol ctor = lookupConstructor(tree.pos(),
  3134                                             box,
  3135                                             List.<Type>nil()
  3136                                             .prepend(tree.type));
  3137             return make.Create(ctor, List.of(tree));
  3138         } else {
  3139             Symbol valueOfSym = lookupMethod(tree.pos(),
  3140                                              names.valueOf,
  3141                                              box,
  3142                                              List.<Type>nil()
  3143                                              .prepend(tree.type));
  3144             return make.App(make.QualIdent(valueOfSym), List.of(tree));
  3148     /** Unbox an object to a primitive value. */
  3149     JCExpression unbox(JCExpression tree, Type primitive) {
  3150         Type unboxedType = types.unboxedType(tree.type);
  3151         if (unboxedType.hasTag(NONE)) {
  3152             unboxedType = primitive;
  3153             if (!unboxedType.isPrimitive())
  3154                 throw new AssertionError(unboxedType);
  3155             make_at(tree.pos());
  3156             tree = make.TypeCast(types.boxedClass(unboxedType).type, tree);
  3157         } else {
  3158             // There must be a conversion from unboxedType to primitive.
  3159             if (!types.isSubtype(unboxedType, primitive))
  3160                 throw new AssertionError(tree);
  3162         make_at(tree.pos());
  3163         Symbol valueSym = lookupMethod(tree.pos(),
  3164                                        unboxedType.tsym.name.append(names.Value), // x.intValue()
  3165                                        tree.type,
  3166                                        List.<Type>nil());
  3167         return make.App(make.Select(tree, valueSym));
  3170     /** Visitor method for parenthesized expressions.
  3171      *  If the subexpression has changed, omit the parens.
  3172      */
  3173     public void visitParens(JCParens tree) {
  3174         JCTree expr = translate(tree.expr);
  3175         result = ((expr == tree.expr) ? tree : expr);
  3178     public void visitIndexed(JCArrayAccess tree) {
  3179         tree.indexed = translate(tree.indexed);
  3180         tree.index = translate(tree.index, syms.intType);
  3181         result = tree;
  3184     public void visitAssign(JCAssign tree) {
  3185         tree.lhs = translate(tree.lhs, tree);
  3186         tree.rhs = translate(tree.rhs, tree.lhs.type);
  3188         // If translated left hand side is an Apply, we are
  3189         // seeing an access method invocation. In this case, append
  3190         // right hand side as last argument of the access method.
  3191         if (tree.lhs.hasTag(APPLY)) {
  3192             JCMethodInvocation app = (JCMethodInvocation)tree.lhs;
  3193             app.args = List.of(tree.rhs).prependList(app.args);
  3194             result = app;
  3195         } else {
  3196             result = tree;
  3200     public void visitAssignop(final JCAssignOp tree) {
  3201         JCTree lhsAccess = access(TreeInfo.skipParens(tree.lhs));
  3202         final boolean boxingReq = !tree.lhs.type.isPrimitive() &&
  3203             tree.operator.type.getReturnType().isPrimitive();
  3205         if (boxingReq || lhsAccess.hasTag(APPLY)) {
  3206             // boxing required; need to rewrite as x = (unbox typeof x)(x op y);
  3207             // or if x == (typeof x)z then z = (unbox typeof x)((typeof x)z op y)
  3208             // (but without recomputing x)
  3209             JCTree newTree = abstractLval(tree.lhs, new TreeBuilder() {
  3210                     public JCTree build(final JCTree lhs) {
  3211                         JCTree.Tag newTag = tree.getTag().noAssignOp();
  3212                         // Erasure (TransTypes) can change the type of
  3213                         // tree.lhs.  However, we can still get the
  3214                         // unerased type of tree.lhs as it is stored
  3215                         // in tree.type in Attr.
  3216                         Symbol newOperator = rs.resolveBinaryOperator(tree.pos(),
  3217                                                                       newTag,
  3218                                                                       attrEnv,
  3219                                                                       tree.type,
  3220                                                                       tree.rhs.type);
  3221                         JCExpression expr = (JCExpression)lhs;
  3222                         if (expr.type != tree.type)
  3223                             expr = make.TypeCast(tree.type, expr);
  3224                         JCBinary opResult = make.Binary(newTag, expr, tree.rhs);
  3225                         opResult.operator = newOperator;
  3226                         opResult.type = newOperator.type.getReturnType();
  3227                         JCExpression newRhs = boxingReq ?
  3228                             make.TypeCast(types.unboxedType(tree.type), opResult) :
  3229                             opResult;
  3230                         return make.Assign((JCExpression)lhs, newRhs).setType(tree.type);
  3232                 });
  3233             result = translate(newTree);
  3234             return;
  3236         tree.lhs = translate(tree.lhs, tree);
  3237         tree.rhs = translate(tree.rhs, tree.operator.type.getParameterTypes().tail.head);
  3239         // If translated left hand side is an Apply, we are
  3240         // seeing an access method invocation. In this case, append
  3241         // right hand side as last argument of the access method.
  3242         if (tree.lhs.hasTag(APPLY)) {
  3243             JCMethodInvocation app = (JCMethodInvocation)tree.lhs;
  3244             // if operation is a += on strings,
  3245             // make sure to convert argument to string
  3246             JCExpression rhs = (((OperatorSymbol)tree.operator).opcode == string_add)
  3247               ? makeString(tree.rhs)
  3248               : tree.rhs;
  3249             app.args = List.of(rhs).prependList(app.args);
  3250             result = app;
  3251         } else {
  3252             result = tree;
  3256     /** Lower a tree of the form e++ or e-- where e is an object type */
  3257     JCTree lowerBoxedPostop(final JCUnary tree) {
  3258         // translate to tmp1=lval(e); tmp2=tmp1; tmp1 OP 1; tmp2
  3259         // or
  3260         // translate to tmp1=lval(e); tmp2=tmp1; (typeof tree)tmp1 OP 1; tmp2
  3261         // where OP is += or -=
  3262         final boolean cast = TreeInfo.skipParens(tree.arg).hasTag(TYPECAST);
  3263         return abstractLval(tree.arg, new TreeBuilder() {
  3264                 public JCTree build(final JCTree tmp1) {
  3265                     return abstractRval(tmp1, tree.arg.type, new TreeBuilder() {
  3266                             public JCTree build(final JCTree tmp2) {
  3267                                 JCTree.Tag opcode = (tree.hasTag(POSTINC))
  3268                                     ? PLUS_ASG : MINUS_ASG;
  3269                                 JCTree lhs = cast
  3270                                     ? make.TypeCast(tree.arg.type, (JCExpression)tmp1)
  3271                                     : tmp1;
  3272                                 JCTree update = makeAssignop(opcode,
  3273                                                              lhs,
  3274                                                              make.Literal(1));
  3275                                 return makeComma(update, tmp2);
  3277                         });
  3279             });
  3282     public void visitUnary(JCUnary tree) {
  3283         boolean isUpdateOperator = tree.getTag().isIncOrDecUnaryOp();
  3284         if (isUpdateOperator && !tree.arg.type.isPrimitive()) {
  3285             switch(tree.getTag()) {
  3286             case PREINC:            // ++ e
  3287                     // translate to e += 1
  3288             case PREDEC:            // -- e
  3289                     // translate to e -= 1
  3291                     JCTree.Tag opcode = (tree.hasTag(PREINC))
  3292                         ? PLUS_ASG : MINUS_ASG;
  3293                     JCAssignOp newTree = makeAssignop(opcode,
  3294                                                     tree.arg,
  3295                                                     make.Literal(1));
  3296                     result = translate(newTree, tree.type);
  3297                     return;
  3299             case POSTINC:           // e ++
  3300             case POSTDEC:           // e --
  3302                     result = translate(lowerBoxedPostop(tree), tree.type);
  3303                     return;
  3306             throw new AssertionError(tree);
  3309         tree.arg = boxIfNeeded(translate(tree.arg, tree), tree.type);
  3311         if (tree.hasTag(NOT) && tree.arg.type.constValue() != null) {
  3312             tree.type = cfolder.fold1(bool_not, tree.arg.type);
  3315         // If translated left hand side is an Apply, we are
  3316         // seeing an access method invocation. In this case, return
  3317         // that access method invocation as result.
  3318         if (isUpdateOperator && tree.arg.hasTag(APPLY)) {
  3319             result = tree.arg;
  3320         } else {
  3321             result = tree;
  3325     public void visitBinary(JCBinary tree) {
  3326         List<Type> formals = tree.operator.type.getParameterTypes();
  3327         JCTree lhs = tree.lhs = translate(tree.lhs, formals.head);
  3328         switch (tree.getTag()) {
  3329         case OR:
  3330             if (lhs.type.isTrue()) {
  3331                 result = lhs;
  3332                 return;
  3334             if (lhs.type.isFalse()) {
  3335                 result = translate(tree.rhs, formals.tail.head);
  3336                 return;
  3338             break;
  3339         case AND:
  3340             if (lhs.type.isFalse()) {
  3341                 result = lhs;
  3342                 return;
  3344             if (lhs.type.isTrue()) {
  3345                 result = translate(tree.rhs, formals.tail.head);
  3346                 return;
  3348             break;
  3350         tree.rhs = translate(tree.rhs, formals.tail.head);
  3351         result = tree;
  3354     public void visitIdent(JCIdent tree) {
  3355         result = access(tree.sym, tree, enclOp, false);
  3358     /** Translate away the foreach loop.  */
  3359     public void visitForeachLoop(JCEnhancedForLoop tree) {
  3360         if (types.elemtype(tree.expr.type) == null)
  3361             visitIterableForeachLoop(tree);
  3362         else
  3363             visitArrayForeachLoop(tree);
  3365         // where
  3366         /**
  3367          * A statement of the form
  3369          * <pre>
  3370          *     for ( T v : arrayexpr ) stmt;
  3371          * </pre>
  3373          * (where arrayexpr is of an array type) gets translated to
  3375          * <pre>{@code
  3376          *     for ( { arraytype #arr = arrayexpr;
  3377          *             int #len = array.length;
  3378          *             int #i = 0; };
  3379          *           #i < #len; i$++ ) {
  3380          *         T v = arr$[#i];
  3381          *         stmt;
  3382          *     }
  3383          * }</pre>
  3385          * where #arr, #len, and #i are freshly named synthetic local variables.
  3386          */
  3387         private void visitArrayForeachLoop(JCEnhancedForLoop tree) {
  3388             make_at(tree.expr.pos());
  3389             VarSymbol arraycache = new VarSymbol(SYNTHETIC,
  3390                                                  names.fromString("arr" + target.syntheticNameChar()),
  3391                                                  tree.expr.type,
  3392                                                  currentMethodSym);
  3393             JCStatement arraycachedef = make.VarDef(arraycache, tree.expr);
  3394             VarSymbol lencache = new VarSymbol(SYNTHETIC,
  3395                                                names.fromString("len" + target.syntheticNameChar()),
  3396                                                syms.intType,
  3397                                                currentMethodSym);
  3398             JCStatement lencachedef = make.
  3399                 VarDef(lencache, make.Select(make.Ident(arraycache), syms.lengthVar));
  3400             VarSymbol index = new VarSymbol(SYNTHETIC,
  3401                                             names.fromString("i" + target.syntheticNameChar()),
  3402                                             syms.intType,
  3403                                             currentMethodSym);
  3405             JCVariableDecl indexdef = make.VarDef(index, make.Literal(INT, 0));
  3406             indexdef.init.type = indexdef.type = syms.intType.constType(0);
  3408             List<JCStatement> loopinit = List.of(arraycachedef, lencachedef, indexdef);
  3409             JCBinary cond = makeBinary(LT, make.Ident(index), make.Ident(lencache));
  3411             JCExpressionStatement step = make.Exec(makeUnary(PREINC, make.Ident(index)));
  3413             Type elemtype = types.elemtype(tree.expr.type);
  3414             JCExpression loopvarinit = make.Indexed(make.Ident(arraycache),
  3415                                                     make.Ident(index)).setType(elemtype);
  3416             JCVariableDecl loopvardef = (JCVariableDecl)make.VarDef(tree.var.mods,
  3417                                                   tree.var.name,
  3418                                                   tree.var.vartype,
  3419                                                   loopvarinit).setType(tree.var.type);
  3420             loopvardef.sym = tree.var.sym;
  3421             JCBlock body = make.
  3422                 Block(0, List.of(loopvardef, tree.body));
  3424             result = translate(make.
  3425                                ForLoop(loopinit,
  3426                                        cond,
  3427                                        List.of(step),
  3428                                        body));
  3429             patchTargets(body, tree, result);
  3431         /** Patch up break and continue targets. */
  3432         private void patchTargets(JCTree body, final JCTree src, final JCTree dest) {
  3433             class Patcher extends TreeScanner {
  3434                 public void visitBreak(JCBreak tree) {
  3435                     if (tree.target == src)
  3436                         tree.target = dest;
  3438                 public void visitContinue(JCContinue tree) {
  3439                     if (tree.target == src)
  3440                         tree.target = dest;
  3442                 public void visitClassDef(JCClassDecl tree) {}
  3444             new Patcher().scan(body);
  3446         /**
  3447          * A statement of the form
  3449          * <pre>
  3450          *     for ( T v : coll ) stmt ;
  3451          * </pre>
  3453          * (where coll implements {@code Iterable<? extends T>}) gets translated to
  3455          * <pre>{@code
  3456          *     for ( Iterator<? extends T> #i = coll.iterator(); #i.hasNext(); ) {
  3457          *         T v = (T) #i.next();
  3458          *         stmt;
  3459          *     }
  3460          * }</pre>
  3462          * where #i is a freshly named synthetic local variable.
  3463          */
  3464         private void visitIterableForeachLoop(JCEnhancedForLoop tree) {
  3465             make_at(tree.expr.pos());
  3466             Type iteratorTarget = syms.objectType;
  3467             Type iterableType = types.asSuper(types.upperBound(tree.expr.type),
  3468                                               syms.iterableType.tsym);
  3469             if (iterableType.getTypeArguments().nonEmpty())
  3470                 iteratorTarget = types.erasure(iterableType.getTypeArguments().head);
  3471             Type eType = tree.expr.type;
  3472             while (eType.hasTag(TYPEVAR)) {
  3473                 eType = eType.getUpperBound();
  3475             tree.expr.type = types.erasure(eType);
  3476             if (eType.isCompound())
  3477                 tree.expr = make.TypeCast(types.erasure(iterableType), tree.expr);
  3478             Symbol iterator = lookupMethod(tree.expr.pos(),
  3479                                            names.iterator,
  3480                                            eType,
  3481                                            List.<Type>nil());
  3482             VarSymbol itvar = new VarSymbol(SYNTHETIC, names.fromString("i" + target.syntheticNameChar()),
  3483                                             types.erasure(types.asSuper(iterator.type.getReturnType(), syms.iteratorType.tsym)),
  3484                                             currentMethodSym);
  3486              JCStatement init = make.
  3487                 VarDef(itvar, make.App(make.Select(tree.expr, iterator)
  3488                      .setType(types.erasure(iterator.type))));
  3490             Symbol hasNext = lookupMethod(tree.expr.pos(),
  3491                                           names.hasNext,
  3492                                           itvar.type,
  3493                                           List.<Type>nil());
  3494             JCMethodInvocation cond = make.App(make.Select(make.Ident(itvar), hasNext));
  3495             Symbol next = lookupMethod(tree.expr.pos(),
  3496                                        names.next,
  3497                                        itvar.type,
  3498                                        List.<Type>nil());
  3499             JCExpression vardefinit = make.App(make.Select(make.Ident(itvar), next));
  3500             if (tree.var.type.isPrimitive())
  3501                 vardefinit = make.TypeCast(types.upperBound(iteratorTarget), vardefinit);
  3502             else
  3503                 vardefinit = make.TypeCast(tree.var.type, vardefinit);
  3504             JCVariableDecl indexDef = (JCVariableDecl)make.VarDef(tree.var.mods,
  3505                                                   tree.var.name,
  3506                                                   tree.var.vartype,
  3507                                                   vardefinit).setType(tree.var.type);
  3508             indexDef.sym = tree.var.sym;
  3509             JCBlock body = make.Block(0, List.of(indexDef, tree.body));
  3510             body.endpos = TreeInfo.endPos(tree.body);
  3511             result = translate(make.
  3512                 ForLoop(List.of(init),
  3513                         cond,
  3514                         List.<JCExpressionStatement>nil(),
  3515                         body));
  3516             patchTargets(body, tree, result);
  3519     public void visitVarDef(JCVariableDecl tree) {
  3520         MethodSymbol oldMethodSym = currentMethodSym;
  3521         tree.mods = translate(tree.mods);
  3522         tree.vartype = translate(tree.vartype);
  3523         if (currentMethodSym == null) {
  3524             // A class or instance field initializer.
  3525             currentMethodSym =
  3526                 new MethodSymbol((tree.mods.flags&STATIC) | BLOCK,
  3527                                  names.empty, null,
  3528                                  currentClass);
  3530         if (tree.init != null) tree.init = translate(tree.init, tree.type);
  3531         result = tree;
  3532         currentMethodSym = oldMethodSym;
  3535     public void visitBlock(JCBlock tree) {
  3536         MethodSymbol oldMethodSym = currentMethodSym;
  3537         if (currentMethodSym == null) {
  3538             // Block is a static or instance initializer.
  3539             currentMethodSym =
  3540                 new MethodSymbol(tree.flags | BLOCK,
  3541                                  names.empty, null,
  3542                                  currentClass);
  3544         super.visitBlock(tree);
  3545         currentMethodSym = oldMethodSym;
  3548     public void visitDoLoop(JCDoWhileLoop tree) {
  3549         tree.body = translate(tree.body);
  3550         tree.cond = translate(tree.cond, syms.booleanType);
  3551         result = tree;
  3554     public void visitWhileLoop(JCWhileLoop tree) {
  3555         tree.cond = translate(tree.cond, syms.booleanType);
  3556         tree.body = translate(tree.body);
  3557         result = tree;
  3560     public void visitForLoop(JCForLoop tree) {
  3561         tree.init = translate(tree.init);
  3562         if (tree.cond != null)
  3563             tree.cond = translate(tree.cond, syms.booleanType);
  3564         tree.step = translate(tree.step);
  3565         tree.body = translate(tree.body);
  3566         result = tree;
  3569     public void visitReturn(JCReturn tree) {
  3570         if (tree.expr != null)
  3571             tree.expr = translate(tree.expr,
  3572                                   types.erasure(currentMethodDef
  3573                                                 .restype.type));
  3574         result = tree;
  3577     public void visitSwitch(JCSwitch tree) {
  3578         Type selsuper = types.supertype(tree.selector.type);
  3579         boolean enumSwitch = selsuper != null &&
  3580             (tree.selector.type.tsym.flags() & ENUM) != 0;
  3581         boolean stringSwitch = selsuper != null &&
  3582             types.isSameType(tree.selector.type, syms.stringType);
  3583         Type target = enumSwitch ? tree.selector.type :
  3584             (stringSwitch? syms.stringType : syms.intType);
  3585         tree.selector = translate(tree.selector, target);
  3586         tree.cases = translateCases(tree.cases);
  3587         if (enumSwitch) {
  3588             result = visitEnumSwitch(tree);
  3589         } else if (stringSwitch) {
  3590             result = visitStringSwitch(tree);
  3591         } else {
  3592             result = tree;
  3596     public JCTree visitEnumSwitch(JCSwitch tree) {
  3597         TypeSymbol enumSym = tree.selector.type.tsym;
  3598         EnumMapping map = mapForEnum(tree.pos(), enumSym);
  3599         make_at(tree.pos());
  3600         Symbol ordinalMethod = lookupMethod(tree.pos(),
  3601                                             names.ordinal,
  3602                                             tree.selector.type,
  3603                                             List.<Type>nil());
  3604         JCArrayAccess selector = make.Indexed(map.mapVar,
  3605                                         make.App(make.Select(tree.selector,
  3606                                                              ordinalMethod)));
  3607         ListBuffer<JCCase> cases = new ListBuffer<JCCase>();
  3608         for (JCCase c : tree.cases) {
  3609             if (c.pat != null) {
  3610                 VarSymbol label = (VarSymbol)TreeInfo.symbol(c.pat);
  3611                 JCLiteral pat = map.forConstant(label);
  3612                 cases.append(make.Case(pat, c.stats));
  3613             } else {
  3614                 cases.append(c);
  3617         JCSwitch enumSwitch = make.Switch(selector, cases.toList());
  3618         patchTargets(enumSwitch, tree, enumSwitch);
  3619         return enumSwitch;
  3622     public JCTree visitStringSwitch(JCSwitch tree) {
  3623         List<JCCase> caseList = tree.getCases();
  3624         int alternatives = caseList.size();
  3626         if (alternatives == 0) { // Strange but legal possibility
  3627             return make.at(tree.pos()).Exec(attr.makeNullCheck(tree.getExpression()));
  3628         } else {
  3629             /*
  3630              * The general approach used is to translate a single
  3631              * string switch statement into a series of two chained
  3632              * switch statements: the first a synthesized statement
  3633              * switching on the argument string's hash value and
  3634              * computing a string's position in the list of original
  3635              * case labels, if any, followed by a second switch on the
  3636              * computed integer value.  The second switch has the same
  3637              * code structure as the original string switch statement
  3638              * except that the string case labels are replaced with
  3639              * positional integer constants starting at 0.
  3641              * The first switch statement can be thought of as an
  3642              * inlined map from strings to their position in the case
  3643              * label list.  An alternate implementation would use an
  3644              * actual Map for this purpose, as done for enum switches.
  3646              * With some additional effort, it would be possible to
  3647              * use a single switch statement on the hash code of the
  3648              * argument, but care would need to be taken to preserve
  3649              * the proper control flow in the presence of hash
  3650              * collisions and other complications, such as
  3651              * fallthroughs.  Switch statements with one or two
  3652              * alternatives could also be specially translated into
  3653              * if-then statements to omit the computation of the hash
  3654              * code.
  3656              * The generated code assumes that the hashing algorithm
  3657              * of String is the same in the compilation environment as
  3658              * in the environment the code will run in.  The string
  3659              * hashing algorithm in the SE JDK has been unchanged
  3660              * since at least JDK 1.2.  Since the algorithm has been
  3661              * specified since that release as well, it is very
  3662              * unlikely to be changed in the future.
  3664              * Different hashing algorithms, such as the length of the
  3665              * strings or a perfect hashing algorithm over the
  3666              * particular set of case labels, could potentially be
  3667              * used instead of String.hashCode.
  3668              */
  3670             ListBuffer<JCStatement> stmtList = new ListBuffer<JCStatement>();
  3672             // Map from String case labels to their original position in
  3673             // the list of case labels.
  3674             Map<String, Integer> caseLabelToPosition =
  3675                 new LinkedHashMap<String, Integer>(alternatives + 1, 1.0f);
  3677             // Map of hash codes to the string case labels having that hashCode.
  3678             Map<Integer, Set<String>> hashToString =
  3679                 new LinkedHashMap<Integer, Set<String>>(alternatives + 1, 1.0f);
  3681             int casePosition = 0;
  3682             for(JCCase oneCase : caseList) {
  3683                 JCExpression expression = oneCase.getExpression();
  3685                 if (expression != null) { // expression for a "default" case is null
  3686                     String labelExpr = (String) expression.type.constValue();
  3687                     Integer mapping = caseLabelToPosition.put(labelExpr, casePosition);
  3688                     Assert.checkNull(mapping);
  3689                     int hashCode = labelExpr.hashCode();
  3691                     Set<String> stringSet = hashToString.get(hashCode);
  3692                     if (stringSet == null) {
  3693                         stringSet = new LinkedHashSet<String>(1, 1.0f);
  3694                         stringSet.add(labelExpr);
  3695                         hashToString.put(hashCode, stringSet);
  3696                     } else {
  3697                         boolean added = stringSet.add(labelExpr);
  3698                         Assert.check(added);
  3701                 casePosition++;
  3704             // Synthesize a switch statement that has the effect of
  3705             // mapping from a string to the integer position of that
  3706             // string in the list of case labels.  This is done by
  3707             // switching on the hashCode of the string followed by an
  3708             // if-then-else chain comparing the input for equality
  3709             // with all the case labels having that hash value.
  3711             /*
  3712              * s$ = top of stack;
  3713              * tmp$ = -1;
  3714              * switch($s.hashCode()) {
  3715              *     case caseLabel.hashCode:
  3716              *         if (s$.equals("caseLabel_1")
  3717              *           tmp$ = caseLabelToPosition("caseLabel_1");
  3718              *         else if (s$.equals("caseLabel_2"))
  3719              *           tmp$ = caseLabelToPosition("caseLabel_2");
  3720              *         ...
  3721              *         break;
  3722              * ...
  3723              * }
  3724              */
  3726             VarSymbol dollar_s = new VarSymbol(FINAL|SYNTHETIC,
  3727                                                names.fromString("s" + tree.pos + target.syntheticNameChar()),
  3728                                                syms.stringType,
  3729                                                currentMethodSym);
  3730             stmtList.append(make.at(tree.pos()).VarDef(dollar_s, tree.getExpression()).setType(dollar_s.type));
  3732             VarSymbol dollar_tmp = new VarSymbol(SYNTHETIC,
  3733                                                  names.fromString("tmp" + tree.pos + target.syntheticNameChar()),
  3734                                                  syms.intType,
  3735                                                  currentMethodSym);
  3736             JCVariableDecl dollar_tmp_def =
  3737                 (JCVariableDecl)make.VarDef(dollar_tmp, make.Literal(INT, -1)).setType(dollar_tmp.type);
  3738             dollar_tmp_def.init.type = dollar_tmp.type = syms.intType;
  3739             stmtList.append(dollar_tmp_def);
  3740             ListBuffer<JCCase> caseBuffer = new ListBuffer<>();
  3741             // hashCode will trigger nullcheck on original switch expression
  3742             JCMethodInvocation hashCodeCall = makeCall(make.Ident(dollar_s),
  3743                                                        names.hashCode,
  3744                                                        List.<JCExpression>nil()).setType(syms.intType);
  3745             JCSwitch switch1 = make.Switch(hashCodeCall,
  3746                                         caseBuffer.toList());
  3747             for(Map.Entry<Integer, Set<String>> entry : hashToString.entrySet()) {
  3748                 int hashCode = entry.getKey();
  3749                 Set<String> stringsWithHashCode = entry.getValue();
  3750                 Assert.check(stringsWithHashCode.size() >= 1);
  3752                 JCStatement elsepart = null;
  3753                 for(String caseLabel : stringsWithHashCode ) {
  3754                     JCMethodInvocation stringEqualsCall = makeCall(make.Ident(dollar_s),
  3755                                                                    names.equals,
  3756                                                                    List.<JCExpression>of(make.Literal(caseLabel)));
  3757                     elsepart = make.If(stringEqualsCall,
  3758                                        make.Exec(make.Assign(make.Ident(dollar_tmp),
  3759                                                              make.Literal(caseLabelToPosition.get(caseLabel))).
  3760                                                  setType(dollar_tmp.type)),
  3761                                        elsepart);
  3764                 ListBuffer<JCStatement> lb = new ListBuffer<>();
  3765                 JCBreak breakStmt = make.Break(null);
  3766                 breakStmt.target = switch1;
  3767                 lb.append(elsepart).append(breakStmt);
  3769                 caseBuffer.append(make.Case(make.Literal(hashCode), lb.toList()));
  3772             switch1.cases = caseBuffer.toList();
  3773             stmtList.append(switch1);
  3775             // Make isomorphic switch tree replacing string labels
  3776             // with corresponding integer ones from the label to
  3777             // position map.
  3779             ListBuffer<JCCase> lb = new ListBuffer<>();
  3780             JCSwitch switch2 = make.Switch(make.Ident(dollar_tmp), lb.toList());
  3781             for(JCCase oneCase : caseList ) {
  3782                 // Rewire up old unlabeled break statements to the
  3783                 // replacement switch being created.
  3784                 patchTargets(oneCase, tree, switch2);
  3786                 boolean isDefault = (oneCase.getExpression() == null);
  3787                 JCExpression caseExpr;
  3788                 if (isDefault)
  3789                     caseExpr = null;
  3790                 else {
  3791                     caseExpr = make.Literal(caseLabelToPosition.get((String)TreeInfo.skipParens(oneCase.
  3792                                                                                                 getExpression()).
  3793                                                                     type.constValue()));
  3796                 lb.append(make.Case(caseExpr,
  3797                                     oneCase.getStatements()));
  3800             switch2.cases = lb.toList();
  3801             stmtList.append(switch2);
  3803             return make.Block(0L, stmtList.toList());
  3807     public void visitNewArray(JCNewArray tree) {
  3808         tree.elemtype = translate(tree.elemtype);
  3809         for (List<JCExpression> t = tree.dims; t.tail != null; t = t.tail)
  3810             if (t.head != null) t.head = translate(t.head, syms.intType);
  3811         tree.elems = translate(tree.elems, types.elemtype(tree.type));
  3812         result = tree;
  3815     public void visitSelect(JCFieldAccess tree) {
  3816         // need to special case-access of the form C.super.x
  3817         // these will always need an access method, unless C
  3818         // is a default interface subclassed by the current class.
  3819         boolean qualifiedSuperAccess =
  3820             tree.selected.hasTag(SELECT) &&
  3821             TreeInfo.name(tree.selected) == names._super &&
  3822             !types.isDirectSuperInterface(((JCFieldAccess)tree.selected).selected.type.tsym, currentClass);
  3823         tree.selected = translate(tree.selected);
  3824         if (tree.name == names._class) {
  3825             result = classOf(tree.selected);
  3827         else if (tree.name == names._super &&
  3828                 types.isDirectSuperInterface(tree.selected.type.tsym, currentClass)) {
  3829             //default super call!! Not a classic qualified super call
  3830             TypeSymbol supSym = tree.selected.type.tsym;
  3831             Assert.checkNonNull(types.asSuper(currentClass.type, supSym));
  3832             result = tree;
  3834         else if (tree.name == names._this || tree.name == names._super) {
  3835             result = makeThis(tree.pos(), tree.selected.type.tsym);
  3837         else
  3838             result = access(tree.sym, tree, enclOp, qualifiedSuperAccess);
  3841     public void visitLetExpr(LetExpr tree) {
  3842         tree.defs = translateVarDefs(tree.defs);
  3843         tree.expr = translate(tree.expr, tree.type);
  3844         result = tree;
  3847     // There ought to be nothing to rewrite here;
  3848     // we don't generate code.
  3849     public void visitAnnotation(JCAnnotation tree) {
  3850         result = tree;
  3853     @Override
  3854     public void visitTry(JCTry tree) {
  3855         if (tree.resources.nonEmpty()) {
  3856             result = makeTwrTry(tree);
  3857             return;
  3860         boolean hasBody = tree.body.getStatements().nonEmpty();
  3861         boolean hasCatchers = tree.catchers.nonEmpty();
  3862         boolean hasFinally = tree.finalizer != null &&
  3863                 tree.finalizer.getStatements().nonEmpty();
  3865         if (!hasCatchers && !hasFinally) {
  3866             result = translate(tree.body);
  3867             return;
  3870         if (!hasBody) {
  3871             if (hasFinally) {
  3872                 result = translate(tree.finalizer);
  3873             } else {
  3874                 result = translate(tree.body);
  3876             return;
  3879         // no optimizations possible
  3880         super.visitTry(tree);
  3883 /**************************************************************************
  3884  * main method
  3885  *************************************************************************/
  3887     /** Translate a toplevel class and return a list consisting of
  3888      *  the translated class and translated versions of all inner classes.
  3889      *  @param env   The attribution environment current at the class definition.
  3890      *               We need this for resolving some additional symbols.
  3891      *  @param cdef  The tree representing the class definition.
  3892      */
  3893     public List<JCTree> translateTopLevelClass(Env<AttrContext> env, JCTree cdef, TreeMaker make) {
  3894         ListBuffer<JCTree> translated = null;
  3895         try {
  3896             attrEnv = env;
  3897             this.make = make;
  3898             endPosTable = env.toplevel.endPositions;
  3899             currentClass = null;
  3900             currentMethodDef = null;
  3901             outermostClassDef = (cdef.hasTag(CLASSDEF)) ? (JCClassDecl)cdef : null;
  3902             outermostMemberDef = null;
  3903             this.translated = new ListBuffer<JCTree>();
  3904             classdefs = new HashMap<ClassSymbol,JCClassDecl>();
  3905             actualSymbols = new HashMap<Symbol,Symbol>();
  3906             freevarCache = new HashMap<ClassSymbol,List<VarSymbol>>();
  3907             proxies = new Scope(syms.noSymbol);
  3908             twrVars = new Scope(syms.noSymbol);
  3909             outerThisStack = List.nil();
  3910             accessNums = new HashMap<Symbol,Integer>();
  3911             accessSyms = new HashMap<Symbol,MethodSymbol[]>();
  3912             accessConstrs = new HashMap<Symbol,MethodSymbol>();
  3913             accessConstrTags = List.nil();
  3914             accessed = new ListBuffer<Symbol>();
  3915             translate(cdef, (JCExpression)null);
  3916             for (List<Symbol> l = accessed.toList(); l.nonEmpty(); l = l.tail)
  3917                 makeAccessible(l.head);
  3918             for (EnumMapping map : enumSwitchMap.values())
  3919                 map.translate();
  3920             checkConflicts(this.translated.toList());
  3921             checkAccessConstructorTags();
  3922             translated = this.translated;
  3923         } finally {
  3924             // note that recursive invocations of this method fail hard
  3925             attrEnv = null;
  3926             this.make = null;
  3927             endPosTable = null;
  3928             currentClass = null;
  3929             currentMethodDef = null;
  3930             outermostClassDef = null;
  3931             outermostMemberDef = null;
  3932             this.translated = null;
  3933             classdefs = null;
  3934             actualSymbols = null;
  3935             freevarCache = null;
  3936             proxies = null;
  3937             outerThisStack = null;
  3938             accessNums = null;
  3939             accessSyms = null;
  3940             accessConstrs = null;
  3941             accessConstrTags = null;
  3942             accessed = null;
  3943             enumSwitchMap.clear();
  3944             assertionsDisabledClassCache = null;
  3946         return translated.toList();

mercurial