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

Mon, 02 Nov 2009 21:36:59 -0800

author
darcy
date
Mon, 02 Nov 2009 21:36:59 -0800
changeset 430
8fb9b4be3cb1
parent 359
8227961c64d3
child 443
121e0ebf1658
permissions
-rw-r--r--

6827009: Project Coin: Strings in Switch
Reviewed-by: jjg, mcimadamore

     1 /*
     2  * Copyright 1999-2009 Sun Microsystems, Inc.  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.  Sun designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
    22  * CA 95054 USA or visit www.sun.com if you need additional information or
    23  * have any questions.
    24  */
    26 package com.sun.tools.javac.comp;
    28 import java.util.*;
    30 import com.sun.tools.javac.code.*;
    31 import com.sun.tools.javac.jvm.*;
    32 import com.sun.tools.javac.tree.*;
    33 import com.sun.tools.javac.util.*;
    34 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    35 import com.sun.tools.javac.util.List;
    37 import com.sun.tools.javac.code.Symbol.*;
    38 import com.sun.tools.javac.tree.JCTree.*;
    39 import com.sun.tools.javac.code.Type.*;
    41 import com.sun.tools.javac.jvm.Target;
    43 import static com.sun.tools.javac.code.Flags.*;
    44 import static com.sun.tools.javac.code.Kinds.*;
    45 import static com.sun.tools.javac.code.TypeTags.*;
    46 import static com.sun.tools.javac.jvm.ByteCodes.*;
    48 /** This pass translates away some syntactic sugar: inner classes,
    49  *  class literals, assertions, foreach loops, etc.
    50  *
    51  *  <p><b>This is NOT part of any API supported by Sun Microsystems.  If
    52  *  you write code that depends on this, you do so at your own risk.
    53  *  This code and its internal interfaces are subject to change or
    54  *  deletion without notice.</b>
    55  */
    56 public class Lower extends TreeTranslator {
    57     protected static final Context.Key<Lower> lowerKey =
    58         new Context.Key<Lower>();
    60     public static Lower instance(Context context) {
    61         Lower instance = context.get(lowerKey);
    62         if (instance == null)
    63             instance = new Lower(context);
    64         return instance;
    65     }
    67     private Names names;
    68     private Log log;
    69     private Symtab syms;
    70     private Resolve rs;
    71     private Check chk;
    72     private Attr attr;
    73     private TreeMaker make;
    74     private DiagnosticPosition make_pos;
    75     private ClassWriter writer;
    76     private ClassReader reader;
    77     private ConstFold cfolder;
    78     private Target target;
    79     private Source source;
    80     private boolean allowEnums;
    81     private final Name dollarAssertionsDisabled;
    82     private final Name classDollar;
    83     private Types types;
    84     private boolean debugLower;
    86     protected Lower(Context context) {
    87         context.put(lowerKey, this);
    88         names = Names.instance(context);
    89         log = Log.instance(context);
    90         syms = Symtab.instance(context);
    91         rs = Resolve.instance(context);
    92         chk = Check.instance(context);
    93         attr = Attr.instance(context);
    94         make = TreeMaker.instance(context);
    95         writer = ClassWriter.instance(context);
    96         reader = ClassReader.instance(context);
    97         cfolder = ConstFold.instance(context);
    98         target = Target.instance(context);
    99         source = Source.instance(context);
   100         allowEnums = source.allowEnums();
   101         dollarAssertionsDisabled = names.
   102             fromString(target.syntheticNameChar() + "assertionsDisabled");
   103         classDollar = names.
   104             fromString("class" + target.syntheticNameChar());
   106         types = Types.instance(context);
   107         Options options = Options.instance(context);
   108         debugLower = options.get("debuglower") != null;
   109     }
   111     /** The currently enclosing class.
   112      */
   113     ClassSymbol currentClass;
   115     /** A queue of all translated classes.
   116      */
   117     ListBuffer<JCTree> translated;
   119     /** Environment for symbol lookup, set by translateTopLevelClass.
   120      */
   121     Env<AttrContext> attrEnv;
   123     /** A hash table mapping syntax trees to their ending source positions.
   124      */
   125     Map<JCTree, Integer> endPositions;
   127 /**************************************************************************
   128  * Global mappings
   129  *************************************************************************/
   131     /** A hash table mapping local classes to their definitions.
   132      */
   133     Map<ClassSymbol, JCClassDecl> classdefs;
   135     /** A hash table mapping virtual accessed symbols in outer subclasses
   136      *  to the actually referred symbol in superclasses.
   137      */
   138     Map<Symbol,Symbol> actualSymbols;
   140     /** The current method definition.
   141      */
   142     JCMethodDecl currentMethodDef;
   144     /** The current method symbol.
   145      */
   146     MethodSymbol currentMethodSym;
   148     /** The currently enclosing outermost class definition.
   149      */
   150     JCClassDecl outermostClassDef;
   152     /** The currently enclosing outermost member definition.
   153      */
   154     JCTree outermostMemberDef;
   156     /** A navigator class for assembling a mapping from local class symbols
   157      *  to class definition trees.
   158      *  There is only one case; all other cases simply traverse down the tree.
   159      */
   160     class ClassMap extends TreeScanner {
   162         /** All encountered class defs are entered into classdefs table.
   163          */
   164         public void visitClassDef(JCClassDecl tree) {
   165             classdefs.put(tree.sym, tree);
   166             super.visitClassDef(tree);
   167         }
   168     }
   169     ClassMap classMap = new ClassMap();
   171     /** Map a class symbol to its definition.
   172      *  @param c    The class symbol of which we want to determine the definition.
   173      */
   174     JCClassDecl classDef(ClassSymbol c) {
   175         // First lookup the class in the classdefs table.
   176         JCClassDecl def = classdefs.get(c);
   177         if (def == null && outermostMemberDef != null) {
   178             // If this fails, traverse outermost member definition, entering all
   179             // local classes into classdefs, and try again.
   180             classMap.scan(outermostMemberDef);
   181             def = classdefs.get(c);
   182         }
   183         if (def == null) {
   184             // If this fails, traverse outermost class definition, entering all
   185             // local classes into classdefs, and try again.
   186             classMap.scan(outermostClassDef);
   187             def = classdefs.get(c);
   188         }
   189         return def;
   190     }
   192     /** A hash table mapping class symbols to lists of free variables.
   193      *  accessed by them. Only free variables of the method immediately containing
   194      *  a class are associated with that class.
   195      */
   196     Map<ClassSymbol,List<VarSymbol>> freevarCache;
   198     /** A navigator class for collecting the free variables accessed
   199      *  from a local class.
   200      *  There is only one case; all other cases simply traverse down the tree.
   201      */
   202     class FreeVarCollector extends TreeScanner {
   204         /** The owner of the local class.
   205          */
   206         Symbol owner;
   208         /** The local class.
   209          */
   210         ClassSymbol clazz;
   212         /** The list of owner's variables accessed from within the local class,
   213          *  without any duplicates.
   214          */
   215         List<VarSymbol> fvs;
   217         FreeVarCollector(ClassSymbol clazz) {
   218             this.clazz = clazz;
   219             this.owner = clazz.owner;
   220             this.fvs = List.nil();
   221         }
   223         /** Add free variable to fvs list unless it is already there.
   224          */
   225         private void addFreeVar(VarSymbol v) {
   226             for (List<VarSymbol> l = fvs; l.nonEmpty(); l = l.tail)
   227                 if (l.head == v) return;
   228             fvs = fvs.prepend(v);
   229         }
   231         /** Add all free variables of class c to fvs list
   232          *  unless they are already there.
   233          */
   234         private void addFreeVars(ClassSymbol c) {
   235             List<VarSymbol> fvs = freevarCache.get(c);
   236             if (fvs != null) {
   237                 for (List<VarSymbol> l = fvs; l.nonEmpty(); l = l.tail) {
   238                     addFreeVar(l.head);
   239                 }
   240             }
   241         }
   243         /** If tree refers to a variable in owner of local class, add it to
   244          *  free variables list.
   245          */
   246         public void visitIdent(JCIdent tree) {
   247             result = tree;
   248             visitSymbol(tree.sym);
   249         }
   250         // where
   251         private void visitSymbol(Symbol _sym) {
   252             Symbol sym = _sym;
   253             if (sym.kind == VAR || sym.kind == MTH) {
   254                 while (sym != null && sym.owner != owner)
   255                     sym = proxies.lookup(proxyName(sym.name)).sym;
   256                 if (sym != null && sym.owner == owner) {
   257                     VarSymbol v = (VarSymbol)sym;
   258                     if (v.getConstValue() == null) {
   259                         addFreeVar(v);
   260                     }
   261                 } else {
   262                     if (outerThisStack.head != null &&
   263                         outerThisStack.head != _sym)
   264                         visitSymbol(outerThisStack.head);
   265                 }
   266             }
   267         }
   269         /** If tree refers to a class instance creation expression
   270          *  add all free variables of the freshly created class.
   271          */
   272         public void visitNewClass(JCNewClass tree) {
   273             ClassSymbol c = (ClassSymbol)tree.constructor.owner;
   274             addFreeVars(c);
   275             if (tree.encl == null &&
   276                 c.hasOuterInstance() &&
   277                 outerThisStack.head != null)
   278                 visitSymbol(outerThisStack.head);
   279             super.visitNewClass(tree);
   280         }
   282         /** If tree refers to a qualified this or super expression
   283          *  for anything but the current class, add the outer this
   284          *  stack as a free variable.
   285          */
   286         public void visitSelect(JCFieldAccess tree) {
   287             if ((tree.name == names._this || tree.name == names._super) &&
   288                 tree.selected.type.tsym != clazz &&
   289                 outerThisStack.head != null)
   290                 visitSymbol(outerThisStack.head);
   291             super.visitSelect(tree);
   292         }
   294         /** If tree refers to a superclass constructor call,
   295          *  add all free variables of the superclass.
   296          */
   297         public void visitApply(JCMethodInvocation tree) {
   298             if (TreeInfo.name(tree.meth) == names._super) {
   299                 addFreeVars((ClassSymbol) TreeInfo.symbol(tree.meth).owner);
   300                 Symbol constructor = TreeInfo.symbol(tree.meth);
   301                 ClassSymbol c = (ClassSymbol)constructor.owner;
   302                 if (c.hasOuterInstance() &&
   303                     tree.meth.getTag() != JCTree.SELECT &&
   304                     outerThisStack.head != null)
   305                     visitSymbol(outerThisStack.head);
   306             }
   307             super.visitApply(tree);
   308         }
   309     }
   311     /** Return the variables accessed from within a local class, which
   312      *  are declared in the local class' owner.
   313      *  (in reverse order of first access).
   314      */
   315     List<VarSymbol> freevars(ClassSymbol c)  {
   316         if ((c.owner.kind & (VAR | MTH)) != 0) {
   317             List<VarSymbol> fvs = freevarCache.get(c);
   318             if (fvs == null) {
   319                 FreeVarCollector collector = new FreeVarCollector(c);
   320                 collector.scan(classDef(c));
   321                 fvs = collector.fvs;
   322                 freevarCache.put(c, fvs);
   323             }
   324             return fvs;
   325         } else {
   326             return List.nil();
   327         }
   328     }
   330     Map<TypeSymbol,EnumMapping> enumSwitchMap = new LinkedHashMap<TypeSymbol,EnumMapping>();
   332     EnumMapping mapForEnum(DiagnosticPosition pos, TypeSymbol enumClass) {
   333         EnumMapping map = enumSwitchMap.get(enumClass);
   334         if (map == null)
   335             enumSwitchMap.put(enumClass, map = new EnumMapping(pos, enumClass));
   336         return map;
   337     }
   339     /** This map gives a translation table to be used for enum
   340      *  switches.
   341      *
   342      *  <p>For each enum that appears as the type of a switch
   343      *  expression, we maintain an EnumMapping to assist in the
   344      *  translation, as exemplified by the following example:
   345      *
   346      *  <p>we translate
   347      *  <pre>
   348      *          switch(colorExpression) {
   349      *          case red: stmt1;
   350      *          case green: stmt2;
   351      *          }
   352      *  </pre>
   353      *  into
   354      *  <pre>
   355      *          switch(Outer$0.$EnumMap$Color[colorExpression.ordinal()]) {
   356      *          case 1: stmt1;
   357      *          case 2: stmt2
   358      *          }
   359      *  </pre>
   360      *  with the auxiliary table initialized as follows:
   361      *  <pre>
   362      *          class Outer$0 {
   363      *              synthetic final int[] $EnumMap$Color = new int[Color.values().length];
   364      *              static {
   365      *                  try { $EnumMap$Color[red.ordinal()] = 1; } catch (NoSuchFieldError ex) {}
   366      *                  try { $EnumMap$Color[green.ordinal()] = 2; } catch (NoSuchFieldError ex) {}
   367      *              }
   368      *          }
   369      *  </pre>
   370      *  class EnumMapping provides mapping data and support methods for this translation.
   371      */
   372     class EnumMapping {
   373         EnumMapping(DiagnosticPosition pos, TypeSymbol forEnum) {
   374             this.forEnum = forEnum;
   375             this.values = new LinkedHashMap<VarSymbol,Integer>();
   376             this.pos = pos;
   377             Name varName = names
   378                 .fromString(target.syntheticNameChar() +
   379                             "SwitchMap" +
   380                             target.syntheticNameChar() +
   381                             writer.xClassName(forEnum.type).toString()
   382                             .replace('/', '.')
   383                             .replace('.', target.syntheticNameChar()));
   384             ClassSymbol outerCacheClass = outerCacheClass();
   385             this.mapVar = new VarSymbol(STATIC | SYNTHETIC | FINAL,
   386                                         varName,
   387                                         new ArrayType(syms.intType, syms.arrayClass),
   388                                         outerCacheClass);
   389             enterSynthetic(pos, mapVar, outerCacheClass.members());
   390         }
   392         DiagnosticPosition pos = null;
   394         // the next value to use
   395         int next = 1; // 0 (unused map elements) go to the default label
   397         // the enum for which this is a map
   398         final TypeSymbol forEnum;
   400         // the field containing the map
   401         final VarSymbol mapVar;
   403         // the mapped values
   404         final Map<VarSymbol,Integer> values;
   406         JCLiteral forConstant(VarSymbol v) {
   407             Integer result = values.get(v);
   408             if (result == null)
   409                 values.put(v, result = next++);
   410             return make.Literal(result);
   411         }
   413         // generate the field initializer for the map
   414         void translate() {
   415             make.at(pos.getStartPosition());
   416             JCClassDecl owner = classDef((ClassSymbol)mapVar.owner);
   418             // synthetic static final int[] $SwitchMap$Color = new int[Color.values().length];
   419             MethodSymbol valuesMethod = lookupMethod(pos,
   420                                                      names.values,
   421                                                      forEnum.type,
   422                                                      List.<Type>nil());
   423             JCExpression size = make // Color.values().length
   424                 .Select(make.App(make.QualIdent(valuesMethod)),
   425                         syms.lengthVar);
   426             JCExpression mapVarInit = make
   427                 .NewArray(make.Type(syms.intType), List.of(size), null)
   428                 .setType(new ArrayType(syms.intType, syms.arrayClass));
   430             // try { $SwitchMap$Color[red.ordinal()] = 1; } catch (java.lang.NoSuchFieldError ex) {}
   431             ListBuffer<JCStatement> stmts = new ListBuffer<JCStatement>();
   432             Symbol ordinalMethod = lookupMethod(pos,
   433                                                 names.ordinal,
   434                                                 forEnum.type,
   435                                                 List.<Type>nil());
   436             List<JCCatch> catcher = List.<JCCatch>nil()
   437                 .prepend(make.Catch(make.VarDef(new VarSymbol(PARAMETER, names.ex,
   438                                                               syms.noSuchFieldErrorType,
   439                                                               syms.noSymbol),
   440                                                 null),
   441                                     make.Block(0, List.<JCStatement>nil())));
   442             for (Map.Entry<VarSymbol,Integer> e : values.entrySet()) {
   443                 VarSymbol enumerator = e.getKey();
   444                 Integer mappedValue = e.getValue();
   445                 JCExpression assign = make
   446                     .Assign(make.Indexed(mapVar,
   447                                          make.App(make.Select(make.QualIdent(enumerator),
   448                                                               ordinalMethod))),
   449                             make.Literal(mappedValue))
   450                     .setType(syms.intType);
   451                 JCStatement exec = make.Exec(assign);
   452                 JCStatement _try = make.Try(make.Block(0, List.of(exec)), catcher, null);
   453                 stmts.append(_try);
   454             }
   456             owner.defs = owner.defs
   457                 .prepend(make.Block(STATIC, stmts.toList()))
   458                 .prepend(make.VarDef(mapVar, mapVarInit));
   459         }
   460     }
   463 /**************************************************************************
   464  * Tree building blocks
   465  *************************************************************************/
   467     /** Equivalent to make.at(pos.getStartPosition()) with side effect of caching
   468      *  pos as make_pos, for use in diagnostics.
   469      **/
   470     TreeMaker make_at(DiagnosticPosition pos) {
   471         make_pos = pos;
   472         return make.at(pos);
   473     }
   475     /** Make an attributed tree representing a literal. This will be an
   476      *  Ident node in the case of boolean literals, a Literal node in all
   477      *  other cases.
   478      *  @param type       The literal's type.
   479      *  @param value      The literal's value.
   480      */
   481     JCExpression makeLit(Type type, Object value) {
   482         return make.Literal(type.tag, value).setType(type.constType(value));
   483     }
   485     /** Make an attributed tree representing null.
   486      */
   487     JCExpression makeNull() {
   488         return makeLit(syms.botType, null);
   489     }
   491     /** Make an attributed class instance creation expression.
   492      *  @param ctype    The class type.
   493      *  @param args     The constructor arguments.
   494      */
   495     JCNewClass makeNewClass(Type ctype, List<JCExpression> args) {
   496         JCNewClass tree = make.NewClass(null,
   497             null, make.QualIdent(ctype.tsym), args, null);
   498         tree.constructor = rs.resolveConstructor(
   499             make_pos, attrEnv, ctype, TreeInfo.types(args), null, false, false);
   500         tree.type = ctype;
   501         return tree;
   502     }
   504     /** Make an attributed unary expression.
   505      *  @param optag    The operators tree tag.
   506      *  @param arg      The operator's argument.
   507      */
   508     JCUnary makeUnary(int optag, JCExpression arg) {
   509         JCUnary tree = make.Unary(optag, arg);
   510         tree.operator = rs.resolveUnaryOperator(
   511             make_pos, optag, attrEnv, arg.type);
   512         tree.type = tree.operator.type.getReturnType();
   513         return tree;
   514     }
   516     /** Make an attributed binary expression.
   517      *  @param optag    The operators tree tag.
   518      *  @param lhs      The operator's left argument.
   519      *  @param rhs      The operator's right argument.
   520      */
   521     JCBinary makeBinary(int optag, JCExpression lhs, JCExpression rhs) {
   522         JCBinary tree = make.Binary(optag, lhs, rhs);
   523         tree.operator = rs.resolveBinaryOperator(
   524             make_pos, optag, attrEnv, lhs.type, rhs.type);
   525         tree.type = tree.operator.type.getReturnType();
   526         return tree;
   527     }
   529     /** Make an attributed assignop expression.
   530      *  @param optag    The operators tree tag.
   531      *  @param lhs      The operator's left argument.
   532      *  @param rhs      The operator's right argument.
   533      */
   534     JCAssignOp makeAssignop(int optag, JCTree lhs, JCTree rhs) {
   535         JCAssignOp tree = make.Assignop(optag, lhs, rhs);
   536         tree.operator = rs.resolveBinaryOperator(
   537             make_pos, tree.getTag() - JCTree.ASGOffset, attrEnv, lhs.type, rhs.type);
   538         tree.type = lhs.type;
   539         return tree;
   540     }
   542     /** Convert tree into string object, unless it has already a
   543      *  reference type..
   544      */
   545     JCExpression makeString(JCExpression tree) {
   546         if (tree.type.tag >= CLASS) {
   547             return tree;
   548         } else {
   549             Symbol valueOfSym = lookupMethod(tree.pos(),
   550                                              names.valueOf,
   551                                              syms.stringType,
   552                                              List.of(tree.type));
   553             return make.App(make.QualIdent(valueOfSym), List.of(tree));
   554         }
   555     }
   557     /** Create an empty anonymous class definition and enter and complete
   558      *  its symbol. Return the class definition's symbol.
   559      *  and create
   560      *  @param flags    The class symbol's flags
   561      *  @param owner    The class symbol's owner
   562      */
   563     ClassSymbol makeEmptyClass(long flags, ClassSymbol owner) {
   564         // Create class symbol.
   565         ClassSymbol c = reader.defineClass(names.empty, owner);
   566         c.flatname = chk.localClassName(c);
   567         c.sourcefile = owner.sourcefile;
   568         c.completer = null;
   569         c.members_field = new Scope(c);
   570         c.flags_field = flags;
   571         ClassType ctype = (ClassType) c.type;
   572         ctype.supertype_field = syms.objectType;
   573         ctype.interfaces_field = List.nil();
   575         JCClassDecl odef = classDef(owner);
   577         // Enter class symbol in owner scope and compiled table.
   578         enterSynthetic(odef.pos(), c, owner.members());
   579         chk.compiled.put(c.flatname, c);
   581         // Create class definition tree.
   582         JCClassDecl cdef = make.ClassDef(
   583             make.Modifiers(flags), names.empty,
   584             List.<JCTypeParameter>nil(),
   585             null, List.<JCExpression>nil(), List.<JCTree>nil());
   586         cdef.sym = c;
   587         cdef.type = c.type;
   589         // Append class definition tree to owner's definitions.
   590         odef.defs = odef.defs.prepend(cdef);
   592         return c;
   593     }
   595 /**************************************************************************
   596  * Symbol manipulation utilities
   597  *************************************************************************/
   599     /** Enter a synthetic symbol in a given scope, but complain if there was already one there.
   600      *  @param pos           Position for error reporting.
   601      *  @param sym           The symbol.
   602      *  @param s             The scope.
   603      */
   604     private void enterSynthetic(DiagnosticPosition pos, Symbol sym, Scope s) {
   605         s.enter(sym);
   606     }
   608     /** Check whether synthetic symbols generated during lowering conflict
   609      *  with user-defined symbols.
   610      *
   611      *  @param translatedTrees lowered class trees
   612      */
   613     void checkConflicts(List<JCTree> translatedTrees) {
   614         for (JCTree t : translatedTrees) {
   615             t.accept(conflictsChecker);
   616         }
   617     }
   619     JCTree.Visitor conflictsChecker = new TreeScanner() {
   621         TypeSymbol currentClass;
   623         @Override
   624         public void visitMethodDef(JCMethodDecl that) {
   625             chk.checkConflicts(that.pos(), that.sym, currentClass);
   626             super.visitMethodDef(that);
   627         }
   629         @Override
   630         public void visitVarDef(JCVariableDecl that) {
   631             if (that.sym.owner.kind == TYP) {
   632                 chk.checkConflicts(that.pos(), that.sym, currentClass);
   633             }
   634             super.visitVarDef(that);
   635         }
   637         @Override
   638         public void visitClassDef(JCClassDecl that) {
   639             TypeSymbol prevCurrentClass = currentClass;
   640             currentClass = that.sym;
   641             try {
   642                 super.visitClassDef(that);
   643             }
   644             finally {
   645                 currentClass = prevCurrentClass;
   646             }
   647         }
   648     };
   650     /** Look up a synthetic name in a given scope.
   651      *  @param scope        The scope.
   652      *  @param name         The name.
   653      */
   654     private Symbol lookupSynthetic(Name name, Scope s) {
   655         Symbol sym = s.lookup(name).sym;
   656         return (sym==null || (sym.flags()&SYNTHETIC)==0) ? null : sym;
   657     }
   659     /** Look up a method in a given scope.
   660      */
   661     private MethodSymbol lookupMethod(DiagnosticPosition pos, Name name, Type qual, List<Type> args) {
   662         return rs.resolveInternalMethod(pos, attrEnv, qual, name, args, null);
   663     }
   665     /** Look up a constructor.
   666      */
   667     private MethodSymbol lookupConstructor(DiagnosticPosition pos, Type qual, List<Type> args) {
   668         return rs.resolveInternalConstructor(pos, attrEnv, qual, args, null);
   669     }
   671     /** Look up a field.
   672      */
   673     private VarSymbol lookupField(DiagnosticPosition pos, Type qual, Name name) {
   674         return rs.resolveInternalField(pos, attrEnv, qual, name);
   675     }
   677 /**************************************************************************
   678  * Access methods
   679  *************************************************************************/
   681     /** Access codes for dereferencing, assignment,
   682      *  and pre/post increment/decrement.
   683      *  Access codes for assignment operations are determined by method accessCode
   684      *  below.
   685      *
   686      *  All access codes for accesses to the current class are even.
   687      *  If a member of the superclass should be accessed instead (because
   688      *  access was via a qualified super), add one to the corresponding code
   689      *  for the current class, making the number odd.
   690      *  This numbering scheme is used by the backend to decide whether
   691      *  to issue an invokevirtual or invokespecial call.
   692      *
   693      *  @see Gen.visitSelect(Select tree)
   694      */
   695     private static final int
   696         DEREFcode = 0,
   697         ASSIGNcode = 2,
   698         PREINCcode = 4,
   699         PREDECcode = 6,
   700         POSTINCcode = 8,
   701         POSTDECcode = 10,
   702         FIRSTASGOPcode = 12;
   704     /** Number of access codes
   705      */
   706     private static final int NCODES = accessCode(ByteCodes.lushrl) + 2;
   708     /** A mapping from symbols to their access numbers.
   709      */
   710     private Map<Symbol,Integer> accessNums;
   712     /** A mapping from symbols to an array of access symbols, indexed by
   713      *  access code.
   714      */
   715     private Map<Symbol,MethodSymbol[]> accessSyms;
   717     /** A mapping from (constructor) symbols to access constructor symbols.
   718      */
   719     private Map<Symbol,MethodSymbol> accessConstrs;
   721     /** A queue for all accessed symbols.
   722      */
   723     private ListBuffer<Symbol> accessed;
   725     /** Map bytecode of binary operation to access code of corresponding
   726      *  assignment operation. This is always an even number.
   727      */
   728     private static int accessCode(int bytecode) {
   729         if (ByteCodes.iadd <= bytecode && bytecode <= ByteCodes.lxor)
   730             return (bytecode - iadd) * 2 + FIRSTASGOPcode;
   731         else if (bytecode == ByteCodes.string_add)
   732             return (ByteCodes.lxor + 1 - iadd) * 2 + FIRSTASGOPcode;
   733         else if (ByteCodes.ishll <= bytecode && bytecode <= ByteCodes.lushrl)
   734             return (bytecode - ishll + ByteCodes.lxor + 2 - iadd) * 2 + FIRSTASGOPcode;
   735         else
   736             return -1;
   737     }
   739     /** return access code for identifier,
   740      *  @param tree     The tree representing the identifier use.
   741      *  @param enclOp   The closest enclosing operation node of tree,
   742      *                  null if tree is not a subtree of an operation.
   743      */
   744     private static int accessCode(JCTree tree, JCTree enclOp) {
   745         if (enclOp == null)
   746             return DEREFcode;
   747         else if (enclOp.getTag() == JCTree.ASSIGN &&
   748                  tree == TreeInfo.skipParens(((JCAssign) enclOp).lhs))
   749             return ASSIGNcode;
   750         else if (JCTree.PREINC <= enclOp.getTag() && enclOp.getTag() <= JCTree.POSTDEC &&
   751                  tree == TreeInfo.skipParens(((JCUnary) enclOp).arg))
   752             return (enclOp.getTag() - JCTree.PREINC) * 2 + PREINCcode;
   753         else if (JCTree.BITOR_ASG <= enclOp.getTag() && enclOp.getTag() <= JCTree.MOD_ASG &&
   754                  tree == TreeInfo.skipParens(((JCAssignOp) enclOp).lhs))
   755             return accessCode(((OperatorSymbol) ((JCAssignOp) enclOp).operator).opcode);
   756         else
   757             return DEREFcode;
   758     }
   760     /** Return binary operator that corresponds to given access code.
   761      */
   762     private OperatorSymbol binaryAccessOperator(int acode) {
   763         for (Scope.Entry e = syms.predefClass.members().elems;
   764              e != null;
   765              e = e.sibling) {
   766             if (e.sym instanceof OperatorSymbol) {
   767                 OperatorSymbol op = (OperatorSymbol)e.sym;
   768                 if (accessCode(op.opcode) == acode) return op;
   769             }
   770         }
   771         return null;
   772     }
   774     /** Return tree tag for assignment operation corresponding
   775      *  to given binary operator.
   776      */
   777     private static int treeTag(OperatorSymbol operator) {
   778         switch (operator.opcode) {
   779         case ByteCodes.ior: case ByteCodes.lor:
   780             return JCTree.BITOR_ASG;
   781         case ByteCodes.ixor: case ByteCodes.lxor:
   782             return JCTree.BITXOR_ASG;
   783         case ByteCodes.iand: case ByteCodes.land:
   784             return JCTree.BITAND_ASG;
   785         case ByteCodes.ishl: case ByteCodes.lshl:
   786         case ByteCodes.ishll: case ByteCodes.lshll:
   787             return JCTree.SL_ASG;
   788         case ByteCodes.ishr: case ByteCodes.lshr:
   789         case ByteCodes.ishrl: case ByteCodes.lshrl:
   790             return JCTree.SR_ASG;
   791         case ByteCodes.iushr: case ByteCodes.lushr:
   792         case ByteCodes.iushrl: case ByteCodes.lushrl:
   793             return JCTree.USR_ASG;
   794         case ByteCodes.iadd: case ByteCodes.ladd:
   795         case ByteCodes.fadd: case ByteCodes.dadd:
   796         case ByteCodes.string_add:
   797             return JCTree.PLUS_ASG;
   798         case ByteCodes.isub: case ByteCodes.lsub:
   799         case ByteCodes.fsub: case ByteCodes.dsub:
   800             return JCTree.MINUS_ASG;
   801         case ByteCodes.imul: case ByteCodes.lmul:
   802         case ByteCodes.fmul: case ByteCodes.dmul:
   803             return JCTree.MUL_ASG;
   804         case ByteCodes.idiv: case ByteCodes.ldiv:
   805         case ByteCodes.fdiv: case ByteCodes.ddiv:
   806             return JCTree.DIV_ASG;
   807         case ByteCodes.imod: case ByteCodes.lmod:
   808         case ByteCodes.fmod: case ByteCodes.dmod:
   809             return JCTree.MOD_ASG;
   810         default:
   811             throw new AssertionError();
   812         }
   813     }
   815     /** The name of the access method with number `anum' and access code `acode'.
   816      */
   817     Name accessName(int anum, int acode) {
   818         return names.fromString(
   819             "access" + target.syntheticNameChar() + anum + acode / 10 + acode % 10);
   820     }
   822     /** Return access symbol for a private or protected symbol from an inner class.
   823      *  @param sym        The accessed private symbol.
   824      *  @param tree       The accessing tree.
   825      *  @param enclOp     The closest enclosing operation node of tree,
   826      *                    null if tree is not a subtree of an operation.
   827      *  @param protAccess Is access to a protected symbol in another
   828      *                    package?
   829      *  @param refSuper   Is access via a (qualified) C.super?
   830      */
   831     MethodSymbol accessSymbol(Symbol sym, JCTree tree, JCTree enclOp,
   832                               boolean protAccess, boolean refSuper) {
   833         ClassSymbol accOwner = refSuper && protAccess
   834             // For access via qualified super (T.super.x), place the
   835             // access symbol on T.
   836             ? (ClassSymbol)((JCFieldAccess) tree).selected.type.tsym
   837             // Otherwise pretend that the owner of an accessed
   838             // protected symbol is the enclosing class of the current
   839             // class which is a subclass of the symbol's owner.
   840             : accessClass(sym, protAccess, tree);
   842         Symbol vsym = sym;
   843         if (sym.owner != accOwner) {
   844             vsym = sym.clone(accOwner);
   845             actualSymbols.put(vsym, sym);
   846         }
   848         Integer anum              // The access number of the access method.
   849             = accessNums.get(vsym);
   850         if (anum == null) {
   851             anum = accessed.length();
   852             accessNums.put(vsym, anum);
   853             accessSyms.put(vsym, new MethodSymbol[NCODES]);
   854             accessed.append(vsym);
   855             // System.out.println("accessing " + vsym + " in " + vsym.location());
   856         }
   858         int acode;                // The access code of the access method.
   859         List<Type> argtypes;      // The argument types of the access method.
   860         Type restype;             // The result type of the access method.
   861         List<Type> thrown;        // The thrown exceptions of the access method.
   862         switch (vsym.kind) {
   863         case VAR:
   864             acode = accessCode(tree, enclOp);
   865             if (acode >= FIRSTASGOPcode) {
   866                 OperatorSymbol operator = binaryAccessOperator(acode);
   867                 if (operator.opcode == string_add)
   868                     argtypes = List.of(syms.objectType);
   869                 else
   870                     argtypes = operator.type.getParameterTypes().tail;
   871             } else if (acode == ASSIGNcode)
   872                 argtypes = List.of(vsym.erasure(types));
   873             else
   874                 argtypes = List.nil();
   875             restype = vsym.erasure(types);
   876             thrown = List.nil();
   877             break;
   878         case MTH:
   879             acode = DEREFcode;
   880             argtypes = vsym.erasure(types).getParameterTypes();
   881             restype = vsym.erasure(types).getReturnType();
   882             thrown = vsym.type.getThrownTypes();
   883             break;
   884         default:
   885             throw new AssertionError();
   886         }
   888         // For references via qualified super, increment acode by one,
   889         // making it odd.
   890         if (protAccess && refSuper) acode++;
   892         // Instance access methods get instance as first parameter.
   893         // For protected symbols this needs to be the instance as a member
   894         // of the type containing the accessed symbol, not the class
   895         // containing the access method.
   896         if ((vsym.flags() & STATIC) == 0) {
   897             argtypes = argtypes.prepend(vsym.owner.erasure(types));
   898         }
   899         MethodSymbol[] accessors = accessSyms.get(vsym);
   900         MethodSymbol accessor = accessors[acode];
   901         if (accessor == null) {
   902             accessor = new MethodSymbol(
   903                 STATIC | SYNTHETIC,
   904                 accessName(anum.intValue(), acode),
   905                 new MethodType(argtypes, restype, thrown, syms.methodClass),
   906                 accOwner);
   907             enterSynthetic(tree.pos(), accessor, accOwner.members());
   908             accessors[acode] = accessor;
   909         }
   910         return accessor;
   911     }
   913     /** The qualifier to be used for accessing a symbol in an outer class.
   914      *  This is either C.sym or C.this.sym, depending on whether or not
   915      *  sym is static.
   916      *  @param sym   The accessed symbol.
   917      */
   918     JCExpression accessBase(DiagnosticPosition pos, Symbol sym) {
   919         return (sym.flags() & STATIC) != 0
   920             ? access(make.at(pos.getStartPosition()).QualIdent(sym.owner))
   921             : makeOwnerThis(pos, sym, true);
   922     }
   924     /** Do we need an access method to reference private symbol?
   925      */
   926     boolean needsPrivateAccess(Symbol sym) {
   927         if ((sym.flags() & PRIVATE) == 0 || sym.owner == currentClass) {
   928             return false;
   929         } else if (sym.name == names.init && (sym.owner.owner.kind & (VAR | MTH)) != 0) {
   930             // private constructor in local class: relax protection
   931             sym.flags_field &= ~PRIVATE;
   932             return false;
   933         } else {
   934             return true;
   935         }
   936     }
   938     /** Do we need an access method to reference symbol in other package?
   939      */
   940     boolean needsProtectedAccess(Symbol sym, JCTree tree) {
   941         if ((sym.flags() & PROTECTED) == 0 ||
   942             sym.owner.owner == currentClass.owner || // fast special case
   943             sym.packge() == currentClass.packge())
   944             return false;
   945         if (!currentClass.isSubClass(sym.owner, types))
   946             return true;
   947         if ((sym.flags() & STATIC) != 0 ||
   948             tree.getTag() != JCTree.SELECT ||
   949             TreeInfo.name(((JCFieldAccess) tree).selected) == names._super)
   950             return false;
   951         return !((JCFieldAccess) tree).selected.type.tsym.isSubClass(currentClass, types);
   952     }
   954     /** The class in which an access method for given symbol goes.
   955      *  @param sym        The access symbol
   956      *  @param protAccess Is access to a protected symbol in another
   957      *                    package?
   958      */
   959     ClassSymbol accessClass(Symbol sym, boolean protAccess, JCTree tree) {
   960         if (protAccess) {
   961             Symbol qualifier = null;
   962             ClassSymbol c = currentClass;
   963             if (tree.getTag() == JCTree.SELECT && (sym.flags() & STATIC) == 0) {
   964                 qualifier = ((JCFieldAccess) tree).selected.type.tsym;
   965                 while (!qualifier.isSubClass(c, types)) {
   966                     c = c.owner.enclClass();
   967                 }
   968                 return c;
   969             } else {
   970                 while (!c.isSubClass(sym.owner, types)) {
   971                     c = c.owner.enclClass();
   972                 }
   973             }
   974             return c;
   975         } else {
   976             // the symbol is private
   977             return sym.owner.enclClass();
   978         }
   979     }
   981     /** Ensure that identifier is accessible, return tree accessing the identifier.
   982      *  @param sym      The accessed symbol.
   983      *  @param tree     The tree referring to the symbol.
   984      *  @param enclOp   The closest enclosing operation node of tree,
   985      *                  null if tree is not a subtree of an operation.
   986      *  @param refSuper Is access via a (qualified) C.super?
   987      */
   988     JCExpression access(Symbol sym, JCExpression tree, JCExpression enclOp, boolean refSuper) {
   989         // Access a free variable via its proxy, or its proxy's proxy
   990         while (sym.kind == VAR && sym.owner.kind == MTH &&
   991             sym.owner.enclClass() != currentClass) {
   992             // A constant is replaced by its constant value.
   993             Object cv = ((VarSymbol)sym).getConstValue();
   994             if (cv != null) {
   995                 make.at(tree.pos);
   996                 return makeLit(sym.type, cv);
   997             }
   998             // Otherwise replace the variable by its proxy.
   999             sym = proxies.lookup(proxyName(sym.name)).sym;
  1000             assert sym != null && (sym.flags_field & FINAL) != 0;
  1001             tree = make.at(tree.pos).Ident(sym);
  1003         JCExpression base = (tree.getTag() == JCTree.SELECT) ? ((JCFieldAccess) tree).selected : null;
  1004         switch (sym.kind) {
  1005         case TYP:
  1006             if (sym.owner.kind != PCK) {
  1007                 // Convert type idents to
  1008                 // <flat name> or <package name> . <flat name>
  1009                 Name flatname = Convert.shortName(sym.flatName());
  1010                 while (base != null &&
  1011                        TreeInfo.symbol(base) != null &&
  1012                        TreeInfo.symbol(base).kind != PCK) {
  1013                     base = (base.getTag() == JCTree.SELECT)
  1014                         ? ((JCFieldAccess) base).selected
  1015                         : null;
  1017                 if (tree.getTag() == JCTree.IDENT) {
  1018                     ((JCIdent) tree).name = flatname;
  1019                 } else if (base == null) {
  1020                     tree = make.at(tree.pos).Ident(sym);
  1021                     ((JCIdent) tree).name = flatname;
  1022                 } else {
  1023                     ((JCFieldAccess) tree).selected = base;
  1024                     ((JCFieldAccess) tree).name = flatname;
  1027             break;
  1028         case MTH: case VAR:
  1029             if (sym.owner.kind == TYP) {
  1031                 // Access methods are required for
  1032                 //  - private members,
  1033                 //  - protected members in a superclass of an
  1034                 //    enclosing class contained in another package.
  1035                 //  - all non-private members accessed via a qualified super.
  1036                 boolean protAccess = refSuper && !needsPrivateAccess(sym)
  1037                     || needsProtectedAccess(sym, tree);
  1038                 boolean accReq = protAccess || needsPrivateAccess(sym);
  1040                 // A base has to be supplied for
  1041                 //  - simple identifiers accessing variables in outer classes.
  1042                 boolean baseReq =
  1043                     base == null &&
  1044                     sym.owner != syms.predefClass &&
  1045                     !sym.isMemberOf(currentClass, types);
  1047                 if (accReq || baseReq) {
  1048                     make.at(tree.pos);
  1050                     // Constants are replaced by their constant value.
  1051                     if (sym.kind == VAR) {
  1052                         Object cv = ((VarSymbol)sym).getConstValue();
  1053                         if (cv != null) return makeLit(sym.type, cv);
  1056                     // Private variables and methods are replaced by calls
  1057                     // to their access methods.
  1058                     if (accReq) {
  1059                         List<JCExpression> args = List.nil();
  1060                         if ((sym.flags() & STATIC) == 0) {
  1061                             // Instance access methods get instance
  1062                             // as first parameter.
  1063                             if (base == null)
  1064                                 base = makeOwnerThis(tree.pos(), sym, true);
  1065                             args = args.prepend(base);
  1066                             base = null;   // so we don't duplicate code
  1068                         Symbol access = accessSymbol(sym, tree,
  1069                                                      enclOp, protAccess,
  1070                                                      refSuper);
  1071                         JCExpression receiver = make.Select(
  1072                             base != null ? base : make.QualIdent(access.owner),
  1073                             access);
  1074                         return make.App(receiver, args);
  1076                     // Other accesses to members of outer classes get a
  1077                     // qualifier.
  1078                     } else if (baseReq) {
  1079                         return make.at(tree.pos).Select(
  1080                             accessBase(tree.pos(), sym), sym).setType(tree.type);
  1085         return tree;
  1088     /** Ensure that identifier is accessible, return tree accessing the identifier.
  1089      *  @param tree     The identifier tree.
  1090      */
  1091     JCExpression access(JCExpression tree) {
  1092         Symbol sym = TreeInfo.symbol(tree);
  1093         return sym == null ? tree : access(sym, tree, null, false);
  1096     /** Return access constructor for a private constructor,
  1097      *  or the constructor itself, if no access constructor is needed.
  1098      *  @param pos       The position to report diagnostics, if any.
  1099      *  @param constr    The private constructor.
  1100      */
  1101     Symbol accessConstructor(DiagnosticPosition pos, Symbol constr) {
  1102         if (needsPrivateAccess(constr)) {
  1103             ClassSymbol accOwner = constr.owner.enclClass();
  1104             MethodSymbol aconstr = accessConstrs.get(constr);
  1105             if (aconstr == null) {
  1106                 List<Type> argtypes = constr.type.getParameterTypes();
  1107                 if ((accOwner.flags_field & ENUM) != 0)
  1108                     argtypes = argtypes
  1109                         .prepend(syms.intType)
  1110                         .prepend(syms.stringType);
  1111                 aconstr = new MethodSymbol(
  1112                     SYNTHETIC,
  1113                     names.init,
  1114                     new MethodType(
  1115                         argtypes.append(
  1116                             accessConstructorTag().erasure(types)),
  1117                         constr.type.getReturnType(),
  1118                         constr.type.getThrownTypes(),
  1119                         syms.methodClass),
  1120                     accOwner);
  1121                 enterSynthetic(pos, aconstr, accOwner.members());
  1122                 accessConstrs.put(constr, aconstr);
  1123                 accessed.append(constr);
  1125             return aconstr;
  1126         } else {
  1127             return constr;
  1131     /** Return an anonymous class nested in this toplevel class.
  1132      */
  1133     ClassSymbol accessConstructorTag() {
  1134         ClassSymbol topClass = currentClass.outermostClass();
  1135         Name flatname = names.fromString("" + topClass.getQualifiedName() +
  1136                                          target.syntheticNameChar() +
  1137                                          "1");
  1138         ClassSymbol ctag = chk.compiled.get(flatname);
  1139         if (ctag == null)
  1140             ctag = makeEmptyClass(STATIC | SYNTHETIC, topClass);
  1141         return ctag;
  1144     /** Add all required access methods for a private symbol to enclosing class.
  1145      *  @param sym       The symbol.
  1146      */
  1147     void makeAccessible(Symbol sym) {
  1148         JCClassDecl cdef = classDef(sym.owner.enclClass());
  1149         assert cdef != null : "class def not found: " + sym + " in " + sym.owner;
  1150         if (sym.name == names.init) {
  1151             cdef.defs = cdef.defs.prepend(
  1152                 accessConstructorDef(cdef.pos, sym, accessConstrs.get(sym)));
  1153         } else {
  1154             MethodSymbol[] accessors = accessSyms.get(sym);
  1155             for (int i = 0; i < NCODES; i++) {
  1156                 if (accessors[i] != null)
  1157                     cdef.defs = cdef.defs.prepend(
  1158                         accessDef(cdef.pos, sym, accessors[i], i));
  1163     /** Construct definition of an access method.
  1164      *  @param pos        The source code position of the definition.
  1165      *  @param vsym       The private or protected symbol.
  1166      *  @param accessor   The access method for the symbol.
  1167      *  @param acode      The access code.
  1168      */
  1169     JCTree accessDef(int pos, Symbol vsym, MethodSymbol accessor, int acode) {
  1170 //      System.err.println("access " + vsym + " with " + accessor);//DEBUG
  1171         currentClass = vsym.owner.enclClass();
  1172         make.at(pos);
  1173         JCMethodDecl md = make.MethodDef(accessor, null);
  1175         // Find actual symbol
  1176         Symbol sym = actualSymbols.get(vsym);
  1177         if (sym == null) sym = vsym;
  1179         JCExpression ref;           // The tree referencing the private symbol.
  1180         List<JCExpression> args;    // Any additional arguments to be passed along.
  1181         if ((sym.flags() & STATIC) != 0) {
  1182             ref = make.Ident(sym);
  1183             args = make.Idents(md.params);
  1184         } else {
  1185             ref = make.Select(make.Ident(md.params.head), sym);
  1186             args = make.Idents(md.params.tail);
  1188         JCStatement stat;          // The statement accessing the private symbol.
  1189         if (sym.kind == VAR) {
  1190             // Normalize out all odd access codes by taking floor modulo 2:
  1191             int acode1 = acode - (acode & 1);
  1193             JCExpression expr;      // The access method's return value.
  1194             switch (acode1) {
  1195             case DEREFcode:
  1196                 expr = ref;
  1197                 break;
  1198             case ASSIGNcode:
  1199                 expr = make.Assign(ref, args.head);
  1200                 break;
  1201             case PREINCcode: case POSTINCcode: case PREDECcode: case POSTDECcode:
  1202                 expr = makeUnary(
  1203                     ((acode1 - PREINCcode) >> 1) + JCTree.PREINC, ref);
  1204                 break;
  1205             default:
  1206                 expr = make.Assignop(
  1207                     treeTag(binaryAccessOperator(acode1)), ref, args.head);
  1208                 ((JCAssignOp) expr).operator = binaryAccessOperator(acode1);
  1210             stat = make.Return(expr.setType(sym.type));
  1211         } else {
  1212             stat = make.Call(make.App(ref, args));
  1214         md.body = make.Block(0, List.of(stat));
  1216         // Make sure all parameters, result types and thrown exceptions
  1217         // are accessible.
  1218         for (List<JCVariableDecl> l = md.params; l.nonEmpty(); l = l.tail)
  1219             l.head.vartype = access(l.head.vartype);
  1220         md.restype = access(md.restype);
  1221         for (List<JCExpression> l = md.thrown; l.nonEmpty(); l = l.tail)
  1222             l.head = access(l.head);
  1224         return md;
  1227     /** Construct definition of an access constructor.
  1228      *  @param pos        The source code position of the definition.
  1229      *  @param constr     The private constructor.
  1230      *  @param accessor   The access method for the constructor.
  1231      */
  1232     JCTree accessConstructorDef(int pos, Symbol constr, MethodSymbol accessor) {
  1233         make.at(pos);
  1234         JCMethodDecl md = make.MethodDef(accessor,
  1235                                       accessor.externalType(types),
  1236                                       null);
  1237         JCIdent callee = make.Ident(names._this);
  1238         callee.sym = constr;
  1239         callee.type = constr.type;
  1240         md.body =
  1241             make.Block(0, List.<JCStatement>of(
  1242                 make.Call(
  1243                     make.App(
  1244                         callee,
  1245                         make.Idents(md.params.reverse().tail.reverse())))));
  1246         return md;
  1249 /**************************************************************************
  1250  * Free variables proxies and this$n
  1251  *************************************************************************/
  1253     /** A scope containing all free variable proxies for currently translated
  1254      *  class, as well as its this$n symbol (if needed).
  1255      *  Proxy scopes are nested in the same way classes are.
  1256      *  Inside a constructor, proxies and any this$n symbol are duplicated
  1257      *  in an additional innermost scope, where they represent the constructor
  1258      *  parameters.
  1259      */
  1260     Scope proxies;
  1262     /** A stack containing the this$n field of the currently translated
  1263      *  classes (if needed) in innermost first order.
  1264      *  Inside a constructor, proxies and any this$n symbol are duplicated
  1265      *  in an additional innermost scope, where they represent the constructor
  1266      *  parameters.
  1267      */
  1268     List<VarSymbol> outerThisStack;
  1270     /** The name of a free variable proxy.
  1271      */
  1272     Name proxyName(Name name) {
  1273         return names.fromString("val" + target.syntheticNameChar() + name);
  1276     /** Proxy definitions for all free variables in given list, in reverse order.
  1277      *  @param pos        The source code position of the definition.
  1278      *  @param freevars   The free variables.
  1279      *  @param owner      The class in which the definitions go.
  1280      */
  1281     List<JCVariableDecl> freevarDefs(int pos, List<VarSymbol> freevars, Symbol owner) {
  1282         long flags = FINAL | SYNTHETIC;
  1283         if (owner.kind == TYP &&
  1284             target.usePrivateSyntheticFields())
  1285             flags |= PRIVATE;
  1286         List<JCVariableDecl> defs = List.nil();
  1287         for (List<VarSymbol> l = freevars; l.nonEmpty(); l = l.tail) {
  1288             VarSymbol v = l.head;
  1289             VarSymbol proxy = new VarSymbol(
  1290                 flags, proxyName(v.name), v.erasure(types), owner);
  1291             proxies.enter(proxy);
  1292             JCVariableDecl vd = make.at(pos).VarDef(proxy, null);
  1293             vd.vartype = access(vd.vartype);
  1294             defs = defs.prepend(vd);
  1296         return defs;
  1299     /** The name of a this$n field
  1300      *  @param type   The class referenced by the this$n field
  1301      */
  1302     Name outerThisName(Type type, Symbol owner) {
  1303         Type t = type.getEnclosingType();
  1304         int nestingLevel = 0;
  1305         while (t.tag == CLASS) {
  1306             t = t.getEnclosingType();
  1307             nestingLevel++;
  1309         Name result = names.fromString("this" + target.syntheticNameChar() + nestingLevel);
  1310         while (owner.kind == TYP && ((ClassSymbol)owner).members().lookup(result).scope != null)
  1311             result = names.fromString(result.toString() + target.syntheticNameChar());
  1312         return result;
  1315     /** Definition for this$n field.
  1316      *  @param pos        The source code position of the definition.
  1317      *  @param owner      The class in which the definition goes.
  1318      */
  1319     JCVariableDecl outerThisDef(int pos, Symbol owner) {
  1320         long flags = FINAL | SYNTHETIC;
  1321         if (owner.kind == TYP &&
  1322             target.usePrivateSyntheticFields())
  1323             flags |= PRIVATE;
  1324         Type target = types.erasure(owner.enclClass().type.getEnclosingType());
  1325         VarSymbol outerThis = new VarSymbol(
  1326             flags, outerThisName(target, owner), target, owner);
  1327         outerThisStack = outerThisStack.prepend(outerThis);
  1328         JCVariableDecl vd = make.at(pos).VarDef(outerThis, null);
  1329         vd.vartype = access(vd.vartype);
  1330         return vd;
  1333     /** Return a list of trees that load the free variables in given list,
  1334      *  in reverse order.
  1335      *  @param pos          The source code position to be used for the trees.
  1336      *  @param freevars     The list of free variables.
  1337      */
  1338     List<JCExpression> loadFreevars(DiagnosticPosition pos, List<VarSymbol> freevars) {
  1339         List<JCExpression> args = List.nil();
  1340         for (List<VarSymbol> l = freevars; l.nonEmpty(); l = l.tail)
  1341             args = args.prepend(loadFreevar(pos, l.head));
  1342         return args;
  1344 //where
  1345         JCExpression loadFreevar(DiagnosticPosition pos, VarSymbol v) {
  1346             return access(v, make.at(pos).Ident(v), null, false);
  1349     /** Construct a tree simulating the expression <C.this>.
  1350      *  @param pos           The source code position to be used for the tree.
  1351      *  @param c             The qualifier class.
  1352      */
  1353     JCExpression makeThis(DiagnosticPosition pos, TypeSymbol c) {
  1354         if (currentClass == c) {
  1355             // in this case, `this' works fine
  1356             return make.at(pos).This(c.erasure(types));
  1357         } else {
  1358             // need to go via this$n
  1359             return makeOuterThis(pos, c);
  1363     /** Construct a tree that represents the outer instance
  1364      *  <C.this>. Never pick the current `this'.
  1365      *  @param pos           The source code position to be used for the tree.
  1366      *  @param c             The qualifier class.
  1367      */
  1368     JCExpression makeOuterThis(DiagnosticPosition pos, TypeSymbol c) {
  1369         List<VarSymbol> ots = outerThisStack;
  1370         if (ots.isEmpty()) {
  1371             log.error(pos, "no.encl.instance.of.type.in.scope", c);
  1372             assert false;
  1373             return makeNull();
  1375         VarSymbol ot = ots.head;
  1376         JCExpression tree = access(make.at(pos).Ident(ot));
  1377         TypeSymbol otc = ot.type.tsym;
  1378         while (otc != c) {
  1379             do {
  1380                 ots = ots.tail;
  1381                 if (ots.isEmpty()) {
  1382                     log.error(pos,
  1383                               "no.encl.instance.of.type.in.scope",
  1384                               c);
  1385                     assert false; // should have been caught in Attr
  1386                     return tree;
  1388                 ot = ots.head;
  1389             } while (ot.owner != otc);
  1390             if (otc.owner.kind != PCK && !otc.hasOuterInstance()) {
  1391                 chk.earlyRefError(pos, c);
  1392                 assert false; // should have been caught in Attr
  1393                 return makeNull();
  1395             tree = access(make.at(pos).Select(tree, ot));
  1396             otc = ot.type.tsym;
  1398         return tree;
  1401     /** Construct a tree that represents the closest outer instance
  1402      *  <C.this> such that the given symbol is a member of C.
  1403      *  @param pos           The source code position to be used for the tree.
  1404      *  @param sym           The accessed symbol.
  1405      *  @param preciseMatch  should we accept a type that is a subtype of
  1406      *                       sym's owner, even if it doesn't contain sym
  1407      *                       due to hiding, overriding, or non-inheritance
  1408      *                       due to protection?
  1409      */
  1410     JCExpression makeOwnerThis(DiagnosticPosition pos, Symbol sym, boolean preciseMatch) {
  1411         Symbol c = sym.owner;
  1412         if (preciseMatch ? sym.isMemberOf(currentClass, types)
  1413                          : currentClass.isSubClass(sym.owner, types)) {
  1414             // in this case, `this' works fine
  1415             return make.at(pos).This(c.erasure(types));
  1416         } else {
  1417             // need to go via this$n
  1418             return makeOwnerThisN(pos, sym, preciseMatch);
  1422     /**
  1423      * Similar to makeOwnerThis but will never pick "this".
  1424      */
  1425     JCExpression makeOwnerThisN(DiagnosticPosition pos, Symbol sym, boolean preciseMatch) {
  1426         Symbol c = sym.owner;
  1427         List<VarSymbol> ots = outerThisStack;
  1428         if (ots.isEmpty()) {
  1429             log.error(pos, "no.encl.instance.of.type.in.scope", c);
  1430             assert false;
  1431             return makeNull();
  1433         VarSymbol ot = ots.head;
  1434         JCExpression tree = access(make.at(pos).Ident(ot));
  1435         TypeSymbol otc = ot.type.tsym;
  1436         while (!(preciseMatch ? sym.isMemberOf(otc, types) : otc.isSubClass(sym.owner, types))) {
  1437             do {
  1438                 ots = ots.tail;
  1439                 if (ots.isEmpty()) {
  1440                     log.error(pos,
  1441                         "no.encl.instance.of.type.in.scope",
  1442                         c);
  1443                     assert false;
  1444                     return tree;
  1446                 ot = ots.head;
  1447             } while (ot.owner != otc);
  1448             tree = access(make.at(pos).Select(tree, ot));
  1449             otc = ot.type.tsym;
  1451         return tree;
  1454     /** Return tree simulating the assignment <this.name = name>, where
  1455      *  name is the name of a free variable.
  1456      */
  1457     JCStatement initField(int pos, Name name) {
  1458         Scope.Entry e = proxies.lookup(name);
  1459         Symbol rhs = e.sym;
  1460         assert rhs.owner.kind == MTH;
  1461         Symbol lhs = e.next().sym;
  1462         assert rhs.owner.owner == lhs.owner;
  1463         make.at(pos);
  1464         return
  1465             make.Exec(
  1466                 make.Assign(
  1467                     make.Select(make.This(lhs.owner.erasure(types)), lhs),
  1468                     make.Ident(rhs)).setType(lhs.erasure(types)));
  1471     /** Return tree simulating the assignment <this.this$n = this$n>.
  1472      */
  1473     JCStatement initOuterThis(int pos) {
  1474         VarSymbol rhs = outerThisStack.head;
  1475         assert rhs.owner.kind == MTH;
  1476         VarSymbol lhs = outerThisStack.tail.head;
  1477         assert rhs.owner.owner == lhs.owner;
  1478         make.at(pos);
  1479         return
  1480             make.Exec(
  1481                 make.Assign(
  1482                     make.Select(make.This(lhs.owner.erasure(types)), lhs),
  1483                     make.Ident(rhs)).setType(lhs.erasure(types)));
  1486 /**************************************************************************
  1487  * Code for .class
  1488  *************************************************************************/
  1490     /** Return the symbol of a class to contain a cache of
  1491      *  compiler-generated statics such as class$ and the
  1492      *  $assertionsDisabled flag.  We create an anonymous nested class
  1493      *  (unless one already exists) and return its symbol.  However,
  1494      *  for backward compatibility in 1.4 and earlier we use the
  1495      *  top-level class itself.
  1496      */
  1497     private ClassSymbol outerCacheClass() {
  1498         ClassSymbol clazz = outermostClassDef.sym;
  1499         if ((clazz.flags() & INTERFACE) == 0 &&
  1500             !target.useInnerCacheClass()) return clazz;
  1501         Scope s = clazz.members();
  1502         for (Scope.Entry e = s.elems; e != null; e = e.sibling)
  1503             if (e.sym.kind == TYP &&
  1504                 e.sym.name == names.empty &&
  1505                 (e.sym.flags() & INTERFACE) == 0) return (ClassSymbol) e.sym;
  1506         return makeEmptyClass(STATIC | SYNTHETIC, clazz);
  1509     /** Return symbol for "class$" method. If there is no method definition
  1510      *  for class$, construct one as follows:
  1512      *    class class$(String x0) {
  1513      *      try {
  1514      *        return Class.forName(x0);
  1515      *      } catch (ClassNotFoundException x1) {
  1516      *        throw new NoClassDefFoundError(x1.getMessage());
  1517      *      }
  1518      *    }
  1519      */
  1520     private MethodSymbol classDollarSym(DiagnosticPosition pos) {
  1521         ClassSymbol outerCacheClass = outerCacheClass();
  1522         MethodSymbol classDollarSym =
  1523             (MethodSymbol)lookupSynthetic(classDollar,
  1524                                           outerCacheClass.members());
  1525         if (classDollarSym == null) {
  1526             classDollarSym = new MethodSymbol(
  1527                 STATIC | SYNTHETIC,
  1528                 classDollar,
  1529                 new MethodType(
  1530                     List.of(syms.stringType),
  1531                     types.erasure(syms.classType),
  1532                     List.<Type>nil(),
  1533                     syms.methodClass),
  1534                 outerCacheClass);
  1535             enterSynthetic(pos, classDollarSym, outerCacheClass.members());
  1537             JCMethodDecl md = make.MethodDef(classDollarSym, null);
  1538             try {
  1539                 md.body = classDollarSymBody(pos, md);
  1540             } catch (CompletionFailure ex) {
  1541                 md.body = make.Block(0, List.<JCStatement>nil());
  1542                 chk.completionError(pos, ex);
  1544             JCClassDecl outerCacheClassDef = classDef(outerCacheClass);
  1545             outerCacheClassDef.defs = outerCacheClassDef.defs.prepend(md);
  1547         return classDollarSym;
  1550     /** Generate code for class$(String name). */
  1551     JCBlock classDollarSymBody(DiagnosticPosition pos, JCMethodDecl md) {
  1552         MethodSymbol classDollarSym = md.sym;
  1553         ClassSymbol outerCacheClass = (ClassSymbol)classDollarSym.owner;
  1555         JCBlock returnResult;
  1557         // in 1.4.2 and above, we use
  1558         // Class.forName(String name, boolean init, ClassLoader loader);
  1559         // which requires we cache the current loader in cl$
  1560         if (target.classLiteralsNoInit()) {
  1561             // clsym = "private static ClassLoader cl$"
  1562             VarSymbol clsym = new VarSymbol(STATIC|SYNTHETIC,
  1563                                             names.fromString("cl" + target.syntheticNameChar()),
  1564                                             syms.classLoaderType,
  1565                                             outerCacheClass);
  1566             enterSynthetic(pos, clsym, outerCacheClass.members());
  1568             // emit "private static ClassLoader cl$;"
  1569             JCVariableDecl cldef = make.VarDef(clsym, null);
  1570             JCClassDecl outerCacheClassDef = classDef(outerCacheClass);
  1571             outerCacheClassDef.defs = outerCacheClassDef.defs.prepend(cldef);
  1573             // newcache := "new cache$1[0]"
  1574             JCNewArray newcache = make.
  1575                 NewArray(make.Type(outerCacheClass.type),
  1576                          List.<JCExpression>of(make.Literal(INT, 0).setType(syms.intType)),
  1577                          null);
  1578             newcache.type = new ArrayType(types.erasure(outerCacheClass.type),
  1579                                           syms.arrayClass);
  1581             // forNameSym := java.lang.Class.forName(
  1582             //     String s,boolean init,ClassLoader loader)
  1583             Symbol forNameSym = lookupMethod(make_pos, names.forName,
  1584                                              types.erasure(syms.classType),
  1585                                              List.of(syms.stringType,
  1586                                                      syms.booleanType,
  1587                                                      syms.classLoaderType));
  1588             // clvalue := "(cl$ == null) ?
  1589             // $newcache.getClass().getComponentType().getClassLoader() : cl$"
  1590             JCExpression clvalue =
  1591                 make.Conditional(
  1592                     makeBinary(JCTree.EQ, make.Ident(clsym), makeNull()),
  1593                     make.Assign(
  1594                         make.Ident(clsym),
  1595                         makeCall(
  1596                             makeCall(makeCall(newcache,
  1597                                               names.getClass,
  1598                                               List.<JCExpression>nil()),
  1599                                      names.getComponentType,
  1600                                      List.<JCExpression>nil()),
  1601                             names.getClassLoader,
  1602                             List.<JCExpression>nil())).setType(syms.classLoaderType),
  1603                     make.Ident(clsym)).setType(syms.classLoaderType);
  1605             // returnResult := "{ return Class.forName(param1, false, cl$); }"
  1606             List<JCExpression> args = List.of(make.Ident(md.params.head.sym),
  1607                                               makeLit(syms.booleanType, 0),
  1608                                               clvalue);
  1609             returnResult = make.
  1610                 Block(0, List.<JCStatement>of(make.
  1611                               Call(make. // return
  1612                                    App(make.
  1613                                        Ident(forNameSym), args))));
  1614         } else {
  1615             // forNameSym := java.lang.Class.forName(String s)
  1616             Symbol forNameSym = lookupMethod(make_pos,
  1617                                              names.forName,
  1618                                              types.erasure(syms.classType),
  1619                                              List.of(syms.stringType));
  1620             // returnResult := "{ return Class.forName(param1); }"
  1621             returnResult = make.
  1622                 Block(0, List.of(make.
  1623                           Call(make. // return
  1624                               App(make.
  1625                                   QualIdent(forNameSym),
  1626                                   List.<JCExpression>of(make.
  1627                                                         Ident(md.params.
  1628                                                               head.sym))))));
  1631         // catchParam := ClassNotFoundException e1
  1632         VarSymbol catchParam =
  1633             new VarSymbol(0, make.paramName(1),
  1634                           syms.classNotFoundExceptionType,
  1635                           classDollarSym);
  1637         JCStatement rethrow;
  1638         if (target.hasInitCause()) {
  1639             // rethrow = "throw new NoClassDefFoundError().initCause(e);
  1640             JCTree throwExpr =
  1641                 makeCall(makeNewClass(syms.noClassDefFoundErrorType,
  1642                                       List.<JCExpression>nil()),
  1643                          names.initCause,
  1644                          List.<JCExpression>of(make.Ident(catchParam)));
  1645             rethrow = make.Throw(throwExpr);
  1646         } else {
  1647             // getMessageSym := ClassNotFoundException.getMessage()
  1648             Symbol getMessageSym = lookupMethod(make_pos,
  1649                                                 names.getMessage,
  1650                                                 syms.classNotFoundExceptionType,
  1651                                                 List.<Type>nil());
  1652             // rethrow = "throw new NoClassDefFoundError(e.getMessage());"
  1653             rethrow = make.
  1654                 Throw(makeNewClass(syms.noClassDefFoundErrorType,
  1655                           List.<JCExpression>of(make.App(make.Select(make.Ident(catchParam),
  1656                                                                      getMessageSym),
  1657                                                          List.<JCExpression>nil()))));
  1660         // rethrowStmt := "( $rethrow )"
  1661         JCBlock rethrowStmt = make.Block(0, List.of(rethrow));
  1663         // catchBlock := "catch ($catchParam) $rethrowStmt"
  1664         JCCatch catchBlock = make.Catch(make.VarDef(catchParam, null),
  1665                                       rethrowStmt);
  1667         // tryCatch := "try $returnResult $catchBlock"
  1668         JCStatement tryCatch = make.Try(returnResult,
  1669                                         List.of(catchBlock), null);
  1671         return make.Block(0, List.of(tryCatch));
  1673     // where
  1674         /** Create an attributed tree of the form left.name(). */
  1675         private JCMethodInvocation makeCall(JCExpression left, Name name, List<JCExpression> args) {
  1676             assert left.type != null;
  1677             Symbol funcsym = lookupMethod(make_pos, name, left.type,
  1678                                           TreeInfo.types(args));
  1679             return make.App(make.Select(left, funcsym), args);
  1682     /** The Name Of The variable to cache T.class values.
  1683      *  @param sig      The signature of type T.
  1684      */
  1685     private Name cacheName(String sig) {
  1686         StringBuffer buf = new StringBuffer();
  1687         if (sig.startsWith("[")) {
  1688             buf = buf.append("array");
  1689             while (sig.startsWith("[")) {
  1690                 buf = buf.append(target.syntheticNameChar());
  1691                 sig = sig.substring(1);
  1693             if (sig.startsWith("L")) {
  1694                 sig = sig.substring(0, sig.length() - 1);
  1696         } else {
  1697             buf = buf.append("class" + target.syntheticNameChar());
  1699         buf = buf.append(sig.replace('.', target.syntheticNameChar()));
  1700         return names.fromString(buf.toString());
  1703     /** The variable symbol that caches T.class values.
  1704      *  If none exists yet, create a definition.
  1705      *  @param sig      The signature of type T.
  1706      *  @param pos      The position to report diagnostics, if any.
  1707      */
  1708     private VarSymbol cacheSym(DiagnosticPosition pos, String sig) {
  1709         ClassSymbol outerCacheClass = outerCacheClass();
  1710         Name cname = cacheName(sig);
  1711         VarSymbol cacheSym =
  1712             (VarSymbol)lookupSynthetic(cname, outerCacheClass.members());
  1713         if (cacheSym == null) {
  1714             cacheSym = new VarSymbol(
  1715                 STATIC | SYNTHETIC, cname, types.erasure(syms.classType), outerCacheClass);
  1716             enterSynthetic(pos, cacheSym, outerCacheClass.members());
  1718             JCVariableDecl cacheDef = make.VarDef(cacheSym, null);
  1719             JCClassDecl outerCacheClassDef = classDef(outerCacheClass);
  1720             outerCacheClassDef.defs = outerCacheClassDef.defs.prepend(cacheDef);
  1722         return cacheSym;
  1725     /** The tree simulating a T.class expression.
  1726      *  @param clazz      The tree identifying type T.
  1727      */
  1728     private JCExpression classOf(JCTree clazz) {
  1729         return classOfType(clazz.type, clazz.pos());
  1732     private JCExpression classOfType(Type type, DiagnosticPosition pos) {
  1733         switch (type.tag) {
  1734         case BYTE: case SHORT: case CHAR: case INT: case LONG: case FLOAT:
  1735         case DOUBLE: case BOOLEAN: case VOID:
  1736             // replace with <BoxedClass>.TYPE
  1737             ClassSymbol c = types.boxedClass(type);
  1738             Symbol typeSym =
  1739                 rs.access(
  1740                     rs.findIdentInType(attrEnv, c.type, names.TYPE, VAR),
  1741                     pos, c.type, names.TYPE, true);
  1742             if (typeSym.kind == VAR)
  1743                 ((VarSymbol)typeSym).getConstValue(); // ensure initializer is evaluated
  1744             return make.QualIdent(typeSym);
  1745         case CLASS: case ARRAY:
  1746             if (target.hasClassLiterals()) {
  1747                 VarSymbol sym = new VarSymbol(
  1748                         STATIC | PUBLIC | FINAL, names._class,
  1749                         syms.classType, type.tsym);
  1750                 return make_at(pos).Select(make.Type(type), sym);
  1752             // replace with <cache == null ? cache = class$(tsig) : cache>
  1753             // where
  1754             //  - <tsig>  is the type signature of T,
  1755             //  - <cache> is the cache variable for tsig.
  1756             String sig =
  1757                 writer.xClassName(type).toString().replace('/', '.');
  1758             Symbol cs = cacheSym(pos, sig);
  1759             return make_at(pos).Conditional(
  1760                 makeBinary(JCTree.EQ, make.Ident(cs), makeNull()),
  1761                 make.Assign(
  1762                     make.Ident(cs),
  1763                     make.App(
  1764                         make.Ident(classDollarSym(pos)),
  1765                         List.<JCExpression>of(make.Literal(CLASS, sig)
  1766                                               .setType(syms.stringType))))
  1767                 .setType(types.erasure(syms.classType)),
  1768                 make.Ident(cs)).setType(types.erasure(syms.classType));
  1769         default:
  1770             throw new AssertionError();
  1774 /**************************************************************************
  1775  * Code for enabling/disabling assertions.
  1776  *************************************************************************/
  1778     // This code is not particularly robust if the user has
  1779     // previously declared a member named '$assertionsDisabled'.
  1780     // The same faulty idiom also appears in the translation of
  1781     // class literals above.  We should report an error if a
  1782     // previous declaration is not synthetic.
  1784     private JCExpression assertFlagTest(DiagnosticPosition pos) {
  1785         // Outermost class may be either true class or an interface.
  1786         ClassSymbol outermostClass = outermostClassDef.sym;
  1788         // note that this is a class, as an interface can't contain a statement.
  1789         ClassSymbol container = currentClass;
  1791         VarSymbol assertDisabledSym =
  1792             (VarSymbol)lookupSynthetic(dollarAssertionsDisabled,
  1793                                        container.members());
  1794         if (assertDisabledSym == null) {
  1795             assertDisabledSym =
  1796                 new VarSymbol(STATIC | FINAL | SYNTHETIC,
  1797                               dollarAssertionsDisabled,
  1798                               syms.booleanType,
  1799                               container);
  1800             enterSynthetic(pos, assertDisabledSym, container.members());
  1801             Symbol desiredAssertionStatusSym = lookupMethod(pos,
  1802                                                             names.desiredAssertionStatus,
  1803                                                             types.erasure(syms.classType),
  1804                                                             List.<Type>nil());
  1805             JCClassDecl containerDef = classDef(container);
  1806             make_at(containerDef.pos());
  1807             JCExpression notStatus = makeUnary(JCTree.NOT, make.App(make.Select(
  1808                     classOfType(types.erasure(outermostClass.type),
  1809                                 containerDef.pos()),
  1810                     desiredAssertionStatusSym)));
  1811             JCVariableDecl assertDisabledDef = make.VarDef(assertDisabledSym,
  1812                                                    notStatus);
  1813             containerDef.defs = containerDef.defs.prepend(assertDisabledDef);
  1815         make_at(pos);
  1816         return makeUnary(JCTree.NOT, make.Ident(assertDisabledSym));
  1820 /**************************************************************************
  1821  * Building blocks for let expressions
  1822  *************************************************************************/
  1824     interface TreeBuilder {
  1825         JCTree build(JCTree arg);
  1828     /** Construct an expression using the builder, with the given rval
  1829      *  expression as an argument to the builder.  However, the rval
  1830      *  expression must be computed only once, even if used multiple
  1831      *  times in the result of the builder.  We do that by
  1832      *  constructing a "let" expression that saves the rvalue into a
  1833      *  temporary variable and then uses the temporary variable in
  1834      *  place of the expression built by the builder.  The complete
  1835      *  resulting expression is of the form
  1836      *  <pre>
  1837      *    (let <b>TYPE</b> <b>TEMP</b> = <b>RVAL</b>;
  1838      *     in (<b>BUILDER</b>(<b>TEMP</b>)))
  1839      *  </pre>
  1840      *  where <code><b>TEMP</b></code> is a newly declared variable
  1841      *  in the let expression.
  1842      */
  1843     JCTree abstractRval(JCTree rval, Type type, TreeBuilder builder) {
  1844         rval = TreeInfo.skipParens(rval);
  1845         switch (rval.getTag()) {
  1846         case JCTree.LITERAL:
  1847             return builder.build(rval);
  1848         case JCTree.IDENT:
  1849             JCIdent id = (JCIdent) rval;
  1850             if ((id.sym.flags() & FINAL) != 0 && id.sym.owner.kind == MTH)
  1851                 return builder.build(rval);
  1853         VarSymbol var =
  1854             new VarSymbol(FINAL|SYNTHETIC,
  1855                           names.fromString(
  1856                                           target.syntheticNameChar()
  1857                                           + "" + rval.hashCode()),
  1858                                       type,
  1859                                       currentMethodSym);
  1860         rval = convert(rval,type);
  1861         JCVariableDecl def = make.VarDef(var, (JCExpression)rval); // XXX cast
  1862         JCTree built = builder.build(make.Ident(var));
  1863         JCTree res = make.LetExpr(def, built);
  1864         res.type = built.type;
  1865         return res;
  1868     // same as above, with the type of the temporary variable computed
  1869     JCTree abstractRval(JCTree rval, TreeBuilder builder) {
  1870         return abstractRval(rval, rval.type, builder);
  1873     // same as above, but for an expression that may be used as either
  1874     // an rvalue or an lvalue.  This requires special handling for
  1875     // Select expressions, where we place the left-hand-side of the
  1876     // select in a temporary, and for Indexed expressions, where we
  1877     // place both the indexed expression and the index value in temps.
  1878     JCTree abstractLval(JCTree lval, final TreeBuilder builder) {
  1879         lval = TreeInfo.skipParens(lval);
  1880         switch (lval.getTag()) {
  1881         case JCTree.IDENT:
  1882             return builder.build(lval);
  1883         case JCTree.SELECT: {
  1884             final JCFieldAccess s = (JCFieldAccess)lval;
  1885             JCTree selected = TreeInfo.skipParens(s.selected);
  1886             Symbol lid = TreeInfo.symbol(s.selected);
  1887             if (lid != null && lid.kind == TYP) return builder.build(lval);
  1888             return abstractRval(s.selected, new TreeBuilder() {
  1889                     public JCTree build(final JCTree selected) {
  1890                         return builder.build(make.Select((JCExpression)selected, s.sym));
  1892                 });
  1894         case JCTree.INDEXED: {
  1895             final JCArrayAccess i = (JCArrayAccess)lval;
  1896             return abstractRval(i.indexed, new TreeBuilder() {
  1897                     public JCTree build(final JCTree indexed) {
  1898                         return abstractRval(i.index, syms.intType, new TreeBuilder() {
  1899                                 public JCTree build(final JCTree index) {
  1900                                     JCTree newLval = make.Indexed((JCExpression)indexed,
  1901                                                                 (JCExpression)index);
  1902                                     newLval.setType(i.type);
  1903                                     return builder.build(newLval);
  1905                             });
  1907                 });
  1909         case JCTree.TYPECAST: {
  1910             return abstractLval(((JCTypeCast)lval).expr, builder);
  1913         throw new AssertionError(lval);
  1916     // evaluate and discard the first expression, then evaluate the second.
  1917     JCTree makeComma(final JCTree expr1, final JCTree expr2) {
  1918         return abstractRval(expr1, new TreeBuilder() {
  1919                 public JCTree build(final JCTree discarded) {
  1920                     return expr2;
  1922             });
  1925 /**************************************************************************
  1926  * Translation methods
  1927  *************************************************************************/
  1929     /** Visitor argument: enclosing operator node.
  1930      */
  1931     private JCExpression enclOp;
  1933     /** Visitor method: Translate a single node.
  1934      *  Attach the source position from the old tree to its replacement tree.
  1935      */
  1936     public <T extends JCTree> T translate(T tree) {
  1937         if (tree == null) {
  1938             return null;
  1939         } else {
  1940             make_at(tree.pos());
  1941             T result = super.translate(tree);
  1942             if (endPositions != null && result != tree) {
  1943                 Integer endPos = endPositions.remove(tree);
  1944                 if (endPos != null) endPositions.put(result, endPos);
  1946             return result;
  1950     /** Visitor method: Translate a single node, boxing or unboxing if needed.
  1951      */
  1952     public <T extends JCTree> T translate(T tree, Type type) {
  1953         return (tree == null) ? null : boxIfNeeded(translate(tree), type);
  1956     /** Visitor method: Translate tree.
  1957      */
  1958     public <T extends JCTree> T translate(T tree, JCExpression enclOp) {
  1959         JCExpression prevEnclOp = this.enclOp;
  1960         this.enclOp = enclOp;
  1961         T res = translate(tree);
  1962         this.enclOp = prevEnclOp;
  1963         return res;
  1966     /** Visitor method: Translate list of trees.
  1967      */
  1968     public <T extends JCTree> List<T> translate(List<T> trees, JCExpression enclOp) {
  1969         JCExpression prevEnclOp = this.enclOp;
  1970         this.enclOp = enclOp;
  1971         List<T> res = translate(trees);
  1972         this.enclOp = prevEnclOp;
  1973         return res;
  1976     /** Visitor method: Translate list of trees.
  1977      */
  1978     public <T extends JCTree> List<T> translate(List<T> trees, Type type) {
  1979         if (trees == null) return null;
  1980         for (List<T> l = trees; l.nonEmpty(); l = l.tail)
  1981             l.head = translate(l.head, type);
  1982         return trees;
  1985     public void visitTopLevel(JCCompilationUnit tree) {
  1986         if (tree.packageAnnotations.nonEmpty()) {
  1987             Name name = names.package_info;
  1988             long flags = Flags.ABSTRACT | Flags.INTERFACE;
  1989             if (target.isPackageInfoSynthetic())
  1990                 // package-info is marked SYNTHETIC in JDK 1.6 and later releases
  1991                 flags = flags | Flags.SYNTHETIC;
  1992             JCClassDecl packageAnnotationsClass
  1993                 = make.ClassDef(make.Modifiers(flags,
  1994                                                tree.packageAnnotations),
  1995                                 name, List.<JCTypeParameter>nil(),
  1996                                 null, List.<JCExpression>nil(), List.<JCTree>nil());
  1997             ClassSymbol c = reader.enterClass(name, tree.packge);
  1998             c.flatname = names.fromString(tree.packge + "." + name);
  1999             c.sourcefile = tree.sourcefile;
  2000             c.completer = null;
  2001             c.members_field = new Scope(c);
  2002             c.flags_field = flags;
  2003             c.attributes_field = tree.packge.attributes_field;
  2004             ClassType ctype = (ClassType) c.type;
  2005             ctype.supertype_field = syms.objectType;
  2006             ctype.interfaces_field = List.nil();
  2007             packageAnnotationsClass.sym = c;
  2010             translated.append(packageAnnotationsClass);
  2014     public void visitClassDef(JCClassDecl tree) {
  2015         ClassSymbol currentClassPrev = currentClass;
  2016         MethodSymbol currentMethodSymPrev = currentMethodSym;
  2017         currentClass = tree.sym;
  2018         currentMethodSym = null;
  2019         classdefs.put(currentClass, tree);
  2021         proxies = proxies.dup(currentClass);
  2022         List<VarSymbol> prevOuterThisStack = outerThisStack;
  2024         // If this is an enum definition
  2025         if ((tree.mods.flags & ENUM) != 0 &&
  2026             (types.supertype(currentClass.type).tsym.flags() & ENUM) == 0)
  2027             visitEnumDef(tree);
  2029         // If this is a nested class, define a this$n field for
  2030         // it and add to proxies.
  2031         JCVariableDecl otdef = null;
  2032         if (currentClass.hasOuterInstance())
  2033             otdef = outerThisDef(tree.pos, currentClass);
  2035         // If this is a local class, define proxies for all its free variables.
  2036         List<JCVariableDecl> fvdefs = freevarDefs(
  2037             tree.pos, freevars(currentClass), currentClass);
  2039         // Recursively translate superclass, interfaces.
  2040         tree.extending = translate(tree.extending);
  2041         tree.implementing = translate(tree.implementing);
  2043         // Recursively translate members, taking into account that new members
  2044         // might be created during the translation and prepended to the member
  2045         // list `tree.defs'.
  2046         List<JCTree> seen = List.nil();
  2047         while (tree.defs != seen) {
  2048             List<JCTree> unseen = tree.defs;
  2049             for (List<JCTree> l = unseen; l.nonEmpty() && l != seen; l = l.tail) {
  2050                 JCTree outermostMemberDefPrev = outermostMemberDef;
  2051                 if (outermostMemberDefPrev == null) outermostMemberDef = l.head;
  2052                 l.head = translate(l.head);
  2053                 outermostMemberDef = outermostMemberDefPrev;
  2055             seen = unseen;
  2058         // Convert a protected modifier to public, mask static modifier.
  2059         if ((tree.mods.flags & PROTECTED) != 0) tree.mods.flags |= PUBLIC;
  2060         tree.mods.flags &= ClassFlags;
  2062         // Convert name to flat representation, replacing '.' by '$'.
  2063         tree.name = Convert.shortName(currentClass.flatName());
  2065         // Add this$n and free variables proxy definitions to class.
  2066         for (List<JCVariableDecl> l = fvdefs; l.nonEmpty(); l = l.tail) {
  2067             tree.defs = tree.defs.prepend(l.head);
  2068             enterSynthetic(tree.pos(), l.head.sym, currentClass.members());
  2070         if (currentClass.hasOuterInstance()) {
  2071             tree.defs = tree.defs.prepend(otdef);
  2072             enterSynthetic(tree.pos(), otdef.sym, currentClass.members());
  2075         proxies = proxies.leave();
  2076         outerThisStack = prevOuterThisStack;
  2078         // Append translated tree to `translated' queue.
  2079         translated.append(tree);
  2081         currentClass = currentClassPrev;
  2082         currentMethodSym = currentMethodSymPrev;
  2084         // Return empty block {} as a placeholder for an inner class.
  2085         result = make_at(tree.pos()).Block(0, List.<JCStatement>nil());
  2088     /** Translate an enum class. */
  2089     private void visitEnumDef(JCClassDecl tree) {
  2090         make_at(tree.pos());
  2092         // add the supertype, if needed
  2093         if (tree.extending == null)
  2094             tree.extending = make.Type(types.supertype(tree.type));
  2096         // classOfType adds a cache field to tree.defs unless
  2097         // target.hasClassLiterals().
  2098         JCExpression e_class = classOfType(tree.sym.type, tree.pos()).
  2099             setType(types.erasure(syms.classType));
  2101         // process each enumeration constant, adding implicit constructor parameters
  2102         int nextOrdinal = 0;
  2103         ListBuffer<JCExpression> values = new ListBuffer<JCExpression>();
  2104         ListBuffer<JCTree> enumDefs = new ListBuffer<JCTree>();
  2105         ListBuffer<JCTree> otherDefs = new ListBuffer<JCTree>();
  2106         for (List<JCTree> defs = tree.defs;
  2107              defs.nonEmpty();
  2108              defs=defs.tail) {
  2109             if (defs.head.getTag() == JCTree.VARDEF && (((JCVariableDecl) defs.head).mods.flags & ENUM) != 0) {
  2110                 JCVariableDecl var = (JCVariableDecl)defs.head;
  2111                 visitEnumConstantDef(var, nextOrdinal++);
  2112                 values.append(make.QualIdent(var.sym));
  2113                 enumDefs.append(var);
  2114             } else {
  2115                 otherDefs.append(defs.head);
  2119         // private static final T[] #VALUES = { a, b, c };
  2120         Name valuesName = names.fromString(target.syntheticNameChar() + "VALUES");
  2121         while (tree.sym.members().lookup(valuesName).scope != null) // avoid name clash
  2122             valuesName = names.fromString(valuesName + "" + target.syntheticNameChar());
  2123         Type arrayType = new ArrayType(types.erasure(tree.type), syms.arrayClass);
  2124         VarSymbol valuesVar = new VarSymbol(PRIVATE|FINAL|STATIC|SYNTHETIC,
  2125                                             valuesName,
  2126                                             arrayType,
  2127                                             tree.type.tsym);
  2128         JCNewArray newArray = make.NewArray(make.Type(types.erasure(tree.type)),
  2129                                           List.<JCExpression>nil(),
  2130                                           values.toList());
  2131         newArray.type = arrayType;
  2132         enumDefs.append(make.VarDef(valuesVar, newArray));
  2133         tree.sym.members().enter(valuesVar);
  2135         Symbol valuesSym = lookupMethod(tree.pos(), names.values,
  2136                                         tree.type, List.<Type>nil());
  2137         List<JCStatement> valuesBody;
  2138         if (useClone()) {
  2139             // return (T[]) $VALUES.clone();
  2140             JCTypeCast valuesResult =
  2141                 make.TypeCast(valuesSym.type.getReturnType(),
  2142                               make.App(make.Select(make.Ident(valuesVar),
  2143                                                    syms.arrayCloneMethod)));
  2144             valuesBody = List.<JCStatement>of(make.Return(valuesResult));
  2145         } else {
  2146             // template: T[] $result = new T[$values.length];
  2147             Name resultName = names.fromString(target.syntheticNameChar() + "result");
  2148             while (tree.sym.members().lookup(resultName).scope != null) // avoid name clash
  2149                 resultName = names.fromString(resultName + "" + target.syntheticNameChar());
  2150             VarSymbol resultVar = new VarSymbol(FINAL|SYNTHETIC,
  2151                                                 resultName,
  2152                                                 arrayType,
  2153                                                 valuesSym);
  2154             JCNewArray resultArray = make.NewArray(make.Type(types.erasure(tree.type)),
  2155                                   List.of(make.Select(make.Ident(valuesVar), syms.lengthVar)),
  2156                                   null);
  2157             resultArray.type = arrayType;
  2158             JCVariableDecl decl = make.VarDef(resultVar, resultArray);
  2160             // template: System.arraycopy($VALUES, 0, $result, 0, $VALUES.length);
  2161             if (systemArraycopyMethod == null) {
  2162                 systemArraycopyMethod =
  2163                     new MethodSymbol(PUBLIC | STATIC,
  2164                                      names.fromString("arraycopy"),
  2165                                      new MethodType(List.<Type>of(syms.objectType,
  2166                                                             syms.intType,
  2167                                                             syms.objectType,
  2168                                                             syms.intType,
  2169                                                             syms.intType),
  2170                                                     syms.voidType,
  2171                                                     List.<Type>nil(),
  2172                                                     syms.methodClass),
  2173                                      syms.systemType.tsym);
  2175             JCStatement copy =
  2176                 make.Exec(make.App(make.Select(make.Ident(syms.systemType.tsym),
  2177                                                systemArraycopyMethod),
  2178                           List.of(make.Ident(valuesVar), make.Literal(0),
  2179                                   make.Ident(resultVar), make.Literal(0),
  2180                                   make.Select(make.Ident(valuesVar), syms.lengthVar))));
  2182             // template: return $result;
  2183             JCStatement ret = make.Return(make.Ident(resultVar));
  2184             valuesBody = List.<JCStatement>of(decl, copy, ret);
  2187         JCMethodDecl valuesDef =
  2188              make.MethodDef((MethodSymbol)valuesSym, make.Block(0, valuesBody));
  2190         enumDefs.append(valuesDef);
  2192         if (debugLower)
  2193             System.err.println(tree.sym + ".valuesDef = " + valuesDef);
  2195         /** The template for the following code is:
  2197          *     public static E valueOf(String name) {
  2198          *         return (E)Enum.valueOf(E.class, name);
  2199          *     }
  2201          *  where E is tree.sym
  2202          */
  2203         MethodSymbol valueOfSym = lookupMethod(tree.pos(),
  2204                          names.valueOf,
  2205                          tree.sym.type,
  2206                          List.of(syms.stringType));
  2207         assert (valueOfSym.flags() & STATIC) != 0;
  2208         VarSymbol nameArgSym = valueOfSym.params.head;
  2209         JCIdent nameVal = make.Ident(nameArgSym);
  2210         JCStatement enum_ValueOf =
  2211             make.Return(make.TypeCast(tree.sym.type,
  2212                                       makeCall(make.Ident(syms.enumSym),
  2213                                                names.valueOf,
  2214                                                List.of(e_class, nameVal))));
  2215         JCMethodDecl valueOf = make.MethodDef(valueOfSym,
  2216                                            make.Block(0, List.of(enum_ValueOf)));
  2217         nameVal.sym = valueOf.params.head.sym;
  2218         if (debugLower)
  2219             System.err.println(tree.sym + ".valueOf = " + valueOf);
  2220         enumDefs.append(valueOf);
  2222         enumDefs.appendList(otherDefs.toList());
  2223         tree.defs = enumDefs.toList();
  2225         // Add the necessary members for the EnumCompatibleMode
  2226         if (target.compilerBootstrap(tree.sym)) {
  2227             addEnumCompatibleMembers(tree);
  2230         // where
  2231         private MethodSymbol systemArraycopyMethod;
  2232         private boolean useClone() {
  2233             try {
  2234                 Scope.Entry e = syms.objectType.tsym.members().lookup(names.clone);
  2235                 return (e.sym != null);
  2237             catch (CompletionFailure e) {
  2238                 return false;
  2242     /** Translate an enumeration constant and its initializer. */
  2243     private void visitEnumConstantDef(JCVariableDecl var, int ordinal) {
  2244         JCNewClass varDef = (JCNewClass)var.init;
  2245         varDef.args = varDef.args.
  2246             prepend(makeLit(syms.intType, ordinal)).
  2247             prepend(makeLit(syms.stringType, var.name.toString()));
  2250     public void visitMethodDef(JCMethodDecl tree) {
  2251         if (tree.name == names.init && (currentClass.flags_field&ENUM) != 0) {
  2252             // Add "String $enum$name, int $enum$ordinal" to the beginning of the
  2253             // argument list for each constructor of an enum.
  2254             JCVariableDecl nameParam = make_at(tree.pos()).
  2255                 Param(names.fromString(target.syntheticNameChar() +
  2256                                        "enum" + target.syntheticNameChar() + "name"),
  2257                       syms.stringType, tree.sym);
  2258             nameParam.mods.flags |= SYNTHETIC; nameParam.sym.flags_field |= SYNTHETIC;
  2260             JCVariableDecl ordParam = make.
  2261                 Param(names.fromString(target.syntheticNameChar() +
  2262                                        "enum" + target.syntheticNameChar() +
  2263                                        "ordinal"),
  2264                       syms.intType, tree.sym);
  2265             ordParam.mods.flags |= SYNTHETIC; ordParam.sym.flags_field |= SYNTHETIC;
  2267             tree.params = tree.params.prepend(ordParam).prepend(nameParam);
  2269             MethodSymbol m = tree.sym;
  2270             Type olderasure = m.erasure(types);
  2271             m.erasure_field = new MethodType(
  2272                 olderasure.getParameterTypes().prepend(syms.intType).prepend(syms.stringType),
  2273                 olderasure.getReturnType(),
  2274                 olderasure.getThrownTypes(),
  2275                 syms.methodClass);
  2277             if (target.compilerBootstrap(m.owner)) {
  2278                 // Initialize synthetic name field
  2279                 Symbol nameVarSym = lookupSynthetic(names.fromString("$name"),
  2280                                                     tree.sym.owner.members());
  2281                 JCIdent nameIdent = make.Ident(nameParam.sym);
  2282                 JCIdent id1 = make.Ident(nameVarSym);
  2283                 JCAssign newAssign = make.Assign(id1, nameIdent);
  2284                 newAssign.type = id1.type;
  2285                 JCExpressionStatement nameAssign = make.Exec(newAssign);
  2286                 nameAssign.type = id1.type;
  2287                 tree.body.stats = tree.body.stats.prepend(nameAssign);
  2289                 // Initialize synthetic ordinal field
  2290                 Symbol ordinalVarSym = lookupSynthetic(names.fromString("$ordinal"),
  2291                                                        tree.sym.owner.members());
  2292                 JCIdent ordIdent = make.Ident(ordParam.sym);
  2293                 id1 = make.Ident(ordinalVarSym);
  2294                 newAssign = make.Assign(id1, ordIdent);
  2295                 newAssign.type = id1.type;
  2296                 JCExpressionStatement ordinalAssign = make.Exec(newAssign);
  2297                 ordinalAssign.type = id1.type;
  2298                 tree.body.stats = tree.body.stats.prepend(ordinalAssign);
  2302         JCMethodDecl prevMethodDef = currentMethodDef;
  2303         MethodSymbol prevMethodSym = currentMethodSym;
  2304         try {
  2305             currentMethodDef = tree;
  2306             currentMethodSym = tree.sym;
  2307             visitMethodDefInternal(tree);
  2308         } finally {
  2309             currentMethodDef = prevMethodDef;
  2310             currentMethodSym = prevMethodSym;
  2313     //where
  2314     private void visitMethodDefInternal(JCMethodDecl tree) {
  2315         if (tree.name == names.init &&
  2316             (currentClass.isInner() ||
  2317              (currentClass.owner.kind & (VAR | MTH)) != 0)) {
  2318             // We are seeing a constructor of an inner class.
  2319             MethodSymbol m = tree.sym;
  2321             // Push a new proxy scope for constructor parameters.
  2322             // and create definitions for any this$n and proxy parameters.
  2323             proxies = proxies.dup(m);
  2324             List<VarSymbol> prevOuterThisStack = outerThisStack;
  2325             List<VarSymbol> fvs = freevars(currentClass);
  2326             JCVariableDecl otdef = null;
  2327             if (currentClass.hasOuterInstance())
  2328                 otdef = outerThisDef(tree.pos, m);
  2329             List<JCVariableDecl> fvdefs = freevarDefs(tree.pos, fvs, m);
  2331             // Recursively translate result type, parameters and thrown list.
  2332             tree.restype = translate(tree.restype);
  2333             tree.params = translateVarDefs(tree.params);
  2334             tree.thrown = translate(tree.thrown);
  2336             // when compiling stubs, don't process body
  2337             if (tree.body == null) {
  2338                 result = tree;
  2339                 return;
  2342             // Add this$n (if needed) in front of and free variables behind
  2343             // constructor parameter list.
  2344             tree.params = tree.params.appendList(fvdefs);
  2345             if (currentClass.hasOuterInstance())
  2346                 tree.params = tree.params.prepend(otdef);
  2348             // If this is an initial constructor, i.e., it does not start with
  2349             // this(...), insert initializers for this$n and proxies
  2350             // before (pre-1.4, after) the call to superclass constructor.
  2351             JCStatement selfCall = translate(tree.body.stats.head);
  2353             List<JCStatement> added = List.nil();
  2354             if (fvs.nonEmpty()) {
  2355                 List<Type> addedargtypes = List.nil();
  2356                 for (List<VarSymbol> l = fvs; l.nonEmpty(); l = l.tail) {
  2357                     if (TreeInfo.isInitialConstructor(tree))
  2358                         added = added.prepend(
  2359                             initField(tree.body.pos, proxyName(l.head.name)));
  2360                     addedargtypes = addedargtypes.prepend(l.head.erasure(types));
  2362                 Type olderasure = m.erasure(types);
  2363                 m.erasure_field = new MethodType(
  2364                     olderasure.getParameterTypes().appendList(addedargtypes),
  2365                     olderasure.getReturnType(),
  2366                     olderasure.getThrownTypes(),
  2367                     syms.methodClass);
  2369             if (currentClass.hasOuterInstance() &&
  2370                 TreeInfo.isInitialConstructor(tree))
  2372                 added = added.prepend(initOuterThis(tree.body.pos));
  2375             // pop local variables from proxy stack
  2376             proxies = proxies.leave();
  2378             // recursively translate following local statements and
  2379             // combine with this- or super-call
  2380             List<JCStatement> stats = translate(tree.body.stats.tail);
  2381             if (target.initializeFieldsBeforeSuper())
  2382                 tree.body.stats = stats.prepend(selfCall).prependList(added);
  2383             else
  2384                 tree.body.stats = stats.prependList(added).prepend(selfCall);
  2386             outerThisStack = prevOuterThisStack;
  2387         } else {
  2388             super.visitMethodDef(tree);
  2390         result = tree;
  2393     public void visitAnnotatedType(JCAnnotatedType tree) {
  2394         tree.underlyingType = translate(tree.underlyingType);
  2395         result = tree.underlyingType;
  2398     public void visitTypeCast(JCTypeCast tree) {
  2399         tree.clazz = translate(tree.clazz);
  2400         if (tree.type.isPrimitive() != tree.expr.type.isPrimitive())
  2401             tree.expr = translate(tree.expr, tree.type);
  2402         else
  2403             tree.expr = translate(tree.expr);
  2404         result = tree;
  2407     public void visitNewClass(JCNewClass tree) {
  2408         ClassSymbol c = (ClassSymbol)tree.constructor.owner;
  2410         // Box arguments, if necessary
  2411         boolean isEnum = (tree.constructor.owner.flags() & ENUM) != 0;
  2412         List<Type> argTypes = tree.constructor.type.getParameterTypes();
  2413         if (isEnum) argTypes = argTypes.prepend(syms.intType).prepend(syms.stringType);
  2414         tree.args = boxArgs(argTypes, tree.args, tree.varargsElement);
  2415         tree.varargsElement = null;
  2417         // If created class is local, add free variables after
  2418         // explicit constructor arguments.
  2419         if ((c.owner.kind & (VAR | MTH)) != 0) {
  2420             tree.args = tree.args.appendList(loadFreevars(tree.pos(), freevars(c)));
  2423         // If an access constructor is used, append null as a last argument.
  2424         Symbol constructor = accessConstructor(tree.pos(), tree.constructor);
  2425         if (constructor != tree.constructor) {
  2426             tree.args = tree.args.append(makeNull());
  2427             tree.constructor = constructor;
  2430         // If created class has an outer instance, and new is qualified, pass
  2431         // qualifier as first argument. If new is not qualified, pass the
  2432         // correct outer instance as first argument.
  2433         if (c.hasOuterInstance()) {
  2434             JCExpression thisArg;
  2435             if (tree.encl != null) {
  2436                 thisArg = attr.makeNullCheck(translate(tree.encl));
  2437                 thisArg.type = tree.encl.type;
  2438             } else if ((c.owner.kind & (MTH | VAR)) != 0) {
  2439                 // local class
  2440                 thisArg = makeThis(tree.pos(), c.type.getEnclosingType().tsym);
  2441             } else {
  2442                 // nested class
  2443                 thisArg = makeOwnerThis(tree.pos(), c, false);
  2445             tree.args = tree.args.prepend(thisArg);
  2447         tree.encl = null;
  2449         // If we have an anonymous class, create its flat version, rather
  2450         // than the class or interface following new.
  2451         if (tree.def != null) {
  2452             translate(tree.def);
  2453             tree.clazz = access(make_at(tree.clazz.pos()).Ident(tree.def.sym));
  2454             tree.def = null;
  2455         } else {
  2456             tree.clazz = access(c, tree.clazz, enclOp, false);
  2458         result = tree;
  2461     // Simplify conditionals with known constant controlling expressions.
  2462     // This allows us to avoid generating supporting declarations for
  2463     // the dead code, which will not be eliminated during code generation.
  2464     // Note that Flow.isFalse and Flow.isTrue only return true
  2465     // for constant expressions in the sense of JLS 15.27, which
  2466     // are guaranteed to have no side-effects.  More aggressive
  2467     // constant propagation would require that we take care to
  2468     // preserve possible side-effects in the condition expression.
  2470     /** Visitor method for conditional expressions.
  2471      */
  2472     public void visitConditional(JCConditional tree) {
  2473         JCTree cond = tree.cond = translate(tree.cond, syms.booleanType);
  2474         if (cond.type.isTrue()) {
  2475             result = convert(translate(tree.truepart, tree.type), tree.type);
  2476         } else if (cond.type.isFalse()) {
  2477             result = convert(translate(tree.falsepart, tree.type), tree.type);
  2478         } else {
  2479             // Condition is not a compile-time constant.
  2480             tree.truepart = translate(tree.truepart, tree.type);
  2481             tree.falsepart = translate(tree.falsepart, tree.type);
  2482             result = tree;
  2485 //where
  2486         private JCTree convert(JCTree tree, Type pt) {
  2487             if (tree.type == pt) return tree;
  2488             JCTree result = make_at(tree.pos()).TypeCast(make.Type(pt), (JCExpression)tree);
  2489             result.type = (tree.type.constValue() != null) ? cfolder.coerce(tree.type, pt)
  2490                                                            : pt;
  2491             return result;
  2494     /** Visitor method for if statements.
  2495      */
  2496     public void visitIf(JCIf tree) {
  2497         JCTree cond = tree.cond = translate(tree.cond, syms.booleanType);
  2498         if (cond.type.isTrue()) {
  2499             result = translate(tree.thenpart);
  2500         } else if (cond.type.isFalse()) {
  2501             if (tree.elsepart != null) {
  2502                 result = translate(tree.elsepart);
  2503             } else {
  2504                 result = make.Skip();
  2506         } else {
  2507             // Condition is not a compile-time constant.
  2508             tree.thenpart = translate(tree.thenpart);
  2509             tree.elsepart = translate(tree.elsepart);
  2510             result = tree;
  2514     /** Visitor method for assert statements. Translate them away.
  2515      */
  2516     public void visitAssert(JCAssert tree) {
  2517         DiagnosticPosition detailPos = (tree.detail == null) ? tree.pos() : tree.detail.pos();
  2518         tree.cond = translate(tree.cond, syms.booleanType);
  2519         if (!tree.cond.type.isTrue()) {
  2520             JCExpression cond = assertFlagTest(tree.pos());
  2521             List<JCExpression> exnArgs = (tree.detail == null) ?
  2522                 List.<JCExpression>nil() : List.of(translate(tree.detail));
  2523             if (!tree.cond.type.isFalse()) {
  2524                 cond = makeBinary
  2525                     (JCTree.AND,
  2526                      cond,
  2527                      makeUnary(JCTree.NOT, tree.cond));
  2529             result =
  2530                 make.If(cond,
  2531                         make_at(detailPos).
  2532                            Throw(makeNewClass(syms.assertionErrorType, exnArgs)),
  2533                         null);
  2534         } else {
  2535             result = make.Skip();
  2539     public void visitApply(JCMethodInvocation tree) {
  2540         Symbol meth = TreeInfo.symbol(tree.meth);
  2541         List<Type> argtypes = meth.type.getParameterTypes();
  2542         if (allowEnums &&
  2543             meth.name==names.init &&
  2544             meth.owner == syms.enumSym)
  2545             argtypes = argtypes.tail.tail;
  2546         tree.args = boxArgs(argtypes, tree.args, tree.varargsElement);
  2547         tree.varargsElement = null;
  2548         Name methName = TreeInfo.name(tree.meth);
  2549         if (meth.name==names.init) {
  2550             // We are seeing a this(...) or super(...) constructor call.
  2551             // If an access constructor is used, append null as a last argument.
  2552             Symbol constructor = accessConstructor(tree.pos(), meth);
  2553             if (constructor != meth) {
  2554                 tree.args = tree.args.append(makeNull());
  2555                 TreeInfo.setSymbol(tree.meth, constructor);
  2558             // If we are calling a constructor of a local class, add
  2559             // free variables after explicit constructor arguments.
  2560             ClassSymbol c = (ClassSymbol)constructor.owner;
  2561             if ((c.owner.kind & (VAR | MTH)) != 0) {
  2562                 tree.args = tree.args.appendList(loadFreevars(tree.pos(), freevars(c)));
  2565             // If we are calling a constructor of an enum class, pass
  2566             // along the name and ordinal arguments
  2567             if ((c.flags_field&ENUM) != 0 || c.getQualifiedName() == names.java_lang_Enum) {
  2568                 List<JCVariableDecl> params = currentMethodDef.params;
  2569                 if (currentMethodSym.owner.hasOuterInstance())
  2570                     params = params.tail; // drop this$n
  2571                 tree.args = tree.args
  2572                     .prepend(make_at(tree.pos()).Ident(params.tail.head.sym)) // ordinal
  2573                     .prepend(make.Ident(params.head.sym)); // name
  2576             // If we are calling a constructor of a class with an outer
  2577             // instance, and the call
  2578             // is qualified, pass qualifier as first argument in front of
  2579             // the explicit constructor arguments. If the call
  2580             // is not qualified, pass the correct outer instance as
  2581             // first argument.
  2582             if (c.hasOuterInstance()) {
  2583                 JCExpression thisArg;
  2584                 if (tree.meth.getTag() == JCTree.SELECT) {
  2585                     thisArg = attr.
  2586                         makeNullCheck(translate(((JCFieldAccess) tree.meth).selected));
  2587                     tree.meth = make.Ident(constructor);
  2588                     ((JCIdent) tree.meth).name = methName;
  2589                 } else if ((c.owner.kind & (MTH | VAR)) != 0 || methName == names._this){
  2590                     // local class or this() call
  2591                     thisArg = makeThis(tree.meth.pos(), c.type.getEnclosingType().tsym);
  2592                 } else {
  2593                     // super() call of nested class
  2594                     thisArg = makeOwnerThis(tree.meth.pos(), c, false);
  2596                 tree.args = tree.args.prepend(thisArg);
  2598         } else {
  2599             // We are seeing a normal method invocation; translate this as usual.
  2600             tree.meth = translate(tree.meth);
  2602             // If the translated method itself is an Apply tree, we are
  2603             // seeing an access method invocation. In this case, append
  2604             // the method arguments to the arguments of the access method.
  2605             if (tree.meth.getTag() == JCTree.APPLY) {
  2606                 JCMethodInvocation app = (JCMethodInvocation)tree.meth;
  2607                 app.args = tree.args.prependList(app.args);
  2608                 result = app;
  2609                 return;
  2612         result = tree;
  2615     List<JCExpression> boxArgs(List<Type> parameters, List<JCExpression> _args, Type varargsElement) {
  2616         List<JCExpression> args = _args;
  2617         if (parameters.isEmpty()) return args;
  2618         boolean anyChanges = false;
  2619         ListBuffer<JCExpression> result = new ListBuffer<JCExpression>();
  2620         while (parameters.tail.nonEmpty()) {
  2621             JCExpression arg = translate(args.head, parameters.head);
  2622             anyChanges |= (arg != args.head);
  2623             result.append(arg);
  2624             args = args.tail;
  2625             parameters = parameters.tail;
  2627         Type parameter = parameters.head;
  2628         if (varargsElement != null) {
  2629             anyChanges = true;
  2630             ListBuffer<JCExpression> elems = new ListBuffer<JCExpression>();
  2631             while (args.nonEmpty()) {
  2632                 JCExpression arg = translate(args.head, varargsElement);
  2633                 elems.append(arg);
  2634                 args = args.tail;
  2636             JCNewArray boxedArgs = make.NewArray(make.Type(varargsElement),
  2637                                                List.<JCExpression>nil(),
  2638                                                elems.toList());
  2639             boxedArgs.type = new ArrayType(varargsElement, syms.arrayClass);
  2640             result.append(boxedArgs);
  2641         } else {
  2642             if (args.length() != 1) throw new AssertionError(args);
  2643             JCExpression arg = translate(args.head, parameter);
  2644             anyChanges |= (arg != args.head);
  2645             result.append(arg);
  2646             if (!anyChanges) return _args;
  2648         return result.toList();
  2651     /** Expand a boxing or unboxing conversion if needed. */
  2652     @SuppressWarnings("unchecked") // XXX unchecked
  2653     <T extends JCTree> T boxIfNeeded(T tree, Type type) {
  2654         boolean havePrimitive = tree.type.isPrimitive();
  2655         if (havePrimitive == type.isPrimitive())
  2656             return tree;
  2657         if (havePrimitive) {
  2658             Type unboxedTarget = types.unboxedType(type);
  2659             if (unboxedTarget.tag != NONE) {
  2660                 if (!types.isSubtype(tree.type, unboxedTarget)) //e.g. Character c = 89;
  2661                     tree.type = unboxedTarget.constType(tree.type.constValue());
  2662                 return (T)boxPrimitive((JCExpression)tree, type);
  2663             } else {
  2664                 tree = (T)boxPrimitive((JCExpression)tree);
  2666         } else {
  2667             tree = (T)unbox((JCExpression)tree, type);
  2669         return tree;
  2672     /** Box up a single primitive expression. */
  2673     JCExpression boxPrimitive(JCExpression tree) {
  2674         return boxPrimitive(tree, types.boxedClass(tree.type).type);
  2677     /** Box up a single primitive expression. */
  2678     JCExpression boxPrimitive(JCExpression tree, Type box) {
  2679         make_at(tree.pos());
  2680         if (target.boxWithConstructors()) {
  2681             Symbol ctor = lookupConstructor(tree.pos(),
  2682                                             box,
  2683                                             List.<Type>nil()
  2684                                             .prepend(tree.type));
  2685             return make.Create(ctor, List.of(tree));
  2686         } else {
  2687             Symbol valueOfSym = lookupMethod(tree.pos(),
  2688                                              names.valueOf,
  2689                                              box,
  2690                                              List.<Type>nil()
  2691                                              .prepend(tree.type));
  2692             return make.App(make.QualIdent(valueOfSym), List.of(tree));
  2696     /** Unbox an object to a primitive value. */
  2697     JCExpression unbox(JCExpression tree, Type primitive) {
  2698         Type unboxedType = types.unboxedType(tree.type);
  2699         // note: the "primitive" parameter is not used.  There muse be
  2700         // a conversion from unboxedType to primitive.
  2701         make_at(tree.pos());
  2702         Symbol valueSym = lookupMethod(tree.pos(),
  2703                                        unboxedType.tsym.name.append(names.Value), // x.intValue()
  2704                                        tree.type,
  2705                                        List.<Type>nil());
  2706         return make.App(make.Select(tree, valueSym));
  2709     /** Visitor method for parenthesized expressions.
  2710      *  If the subexpression has changed, omit the parens.
  2711      */
  2712     public void visitParens(JCParens tree) {
  2713         JCTree expr = translate(tree.expr);
  2714         result = ((expr == tree.expr) ? tree : expr);
  2717     public void visitIndexed(JCArrayAccess tree) {
  2718         tree.indexed = translate(tree.indexed);
  2719         tree.index = translate(tree.index, syms.intType);
  2720         result = tree;
  2723     public void visitAssign(JCAssign tree) {
  2724         tree.lhs = translate(tree.lhs, tree);
  2725         tree.rhs = translate(tree.rhs, tree.lhs.type);
  2727         // If translated left hand side is an Apply, we are
  2728         // seeing an access method invocation. In this case, append
  2729         // right hand side as last argument of the access method.
  2730         if (tree.lhs.getTag() == JCTree.APPLY) {
  2731             JCMethodInvocation app = (JCMethodInvocation)tree.lhs;
  2732             app.args = List.of(tree.rhs).prependList(app.args);
  2733             result = app;
  2734         } else {
  2735             result = tree;
  2739     public void visitAssignop(final JCAssignOp tree) {
  2740         if (!tree.lhs.type.isPrimitive() &&
  2741             tree.operator.type.getReturnType().isPrimitive()) {
  2742             // boxing required; need to rewrite as x = (unbox typeof x)(x op y);
  2743             // or if x == (typeof x)z then z = (unbox typeof x)((typeof x)z op y)
  2744             // (but without recomputing x)
  2745             JCTree newTree = abstractLval(tree.lhs, new TreeBuilder() {
  2746                     public JCTree build(final JCTree lhs) {
  2747                         int newTag = tree.getTag() - JCTree.ASGOffset;
  2748                         // Erasure (TransTypes) can change the type of
  2749                         // tree.lhs.  However, we can still get the
  2750                         // unerased type of tree.lhs as it is stored
  2751                         // in tree.type in Attr.
  2752                         Symbol newOperator = rs.resolveBinaryOperator(tree.pos(),
  2753                                                                       newTag,
  2754                                                                       attrEnv,
  2755                                                                       tree.type,
  2756                                                                       tree.rhs.type);
  2757                         JCExpression expr = (JCExpression)lhs;
  2758                         if (expr.type != tree.type)
  2759                             expr = make.TypeCast(tree.type, expr);
  2760                         JCBinary opResult = make.Binary(newTag, expr, tree.rhs);
  2761                         opResult.operator = newOperator;
  2762                         opResult.type = newOperator.type.getReturnType();
  2763                         JCTypeCast newRhs = make.TypeCast(types.unboxedType(tree.type),
  2764                                                           opResult);
  2765                         return make.Assign((JCExpression)lhs, newRhs).setType(tree.type);
  2767                 });
  2768             result = translate(newTree);
  2769             return;
  2771         tree.lhs = translate(tree.lhs, tree);
  2772         tree.rhs = translate(tree.rhs, tree.operator.type.getParameterTypes().tail.head);
  2774         // If translated left hand side is an Apply, we are
  2775         // seeing an access method invocation. In this case, append
  2776         // right hand side as last argument of the access method.
  2777         if (tree.lhs.getTag() == JCTree.APPLY) {
  2778             JCMethodInvocation app = (JCMethodInvocation)tree.lhs;
  2779             // if operation is a += on strings,
  2780             // make sure to convert argument to string
  2781             JCExpression rhs = (((OperatorSymbol)tree.operator).opcode == string_add)
  2782               ? makeString(tree.rhs)
  2783               : tree.rhs;
  2784             app.args = List.of(rhs).prependList(app.args);
  2785             result = app;
  2786         } else {
  2787             result = tree;
  2791     /** Lower a tree of the form e++ or e-- where e is an object type */
  2792     JCTree lowerBoxedPostop(final JCUnary tree) {
  2793         // translate to tmp1=lval(e); tmp2=tmp1; tmp1 OP 1; tmp2
  2794         // or
  2795         // translate to tmp1=lval(e); tmp2=tmp1; (typeof tree)tmp1 OP 1; tmp2
  2796         // where OP is += or -=
  2797         final boolean cast = TreeInfo.skipParens(tree.arg).getTag() == JCTree.TYPECAST;
  2798         return abstractLval(tree.arg, new TreeBuilder() {
  2799                 public JCTree build(final JCTree tmp1) {
  2800                     return abstractRval(tmp1, tree.arg.type, new TreeBuilder() {
  2801                             public JCTree build(final JCTree tmp2) {
  2802                                 int opcode = (tree.getTag() == JCTree.POSTINC)
  2803                                     ? JCTree.PLUS_ASG : JCTree.MINUS_ASG;
  2804                                 JCTree lhs = cast
  2805                                     ? make.TypeCast(tree.arg.type, (JCExpression)tmp1)
  2806                                     : tmp1;
  2807                                 JCTree update = makeAssignop(opcode,
  2808                                                              lhs,
  2809                                                              make.Literal(1));
  2810                                 return makeComma(update, tmp2);
  2812                         });
  2814             });
  2817     public void visitUnary(JCUnary tree) {
  2818         boolean isUpdateOperator =
  2819             JCTree.PREINC <= tree.getTag() && tree.getTag() <= JCTree.POSTDEC;
  2820         if (isUpdateOperator && !tree.arg.type.isPrimitive()) {
  2821             switch(tree.getTag()) {
  2822             case JCTree.PREINC:            // ++ e
  2823                     // translate to e += 1
  2824             case JCTree.PREDEC:            // -- e
  2825                     // translate to e -= 1
  2827                     int opcode = (tree.getTag() == JCTree.PREINC)
  2828                         ? JCTree.PLUS_ASG : JCTree.MINUS_ASG;
  2829                     JCAssignOp newTree = makeAssignop(opcode,
  2830                                                     tree.arg,
  2831                                                     make.Literal(1));
  2832                     result = translate(newTree, tree.type);
  2833                     return;
  2835             case JCTree.POSTINC:           // e ++
  2836             case JCTree.POSTDEC:           // e --
  2838                     result = translate(lowerBoxedPostop(tree), tree.type);
  2839                     return;
  2842             throw new AssertionError(tree);
  2845         tree.arg = boxIfNeeded(translate(tree.arg, tree), tree.type);
  2847         if (tree.getTag() == JCTree.NOT && tree.arg.type.constValue() != null) {
  2848             tree.type = cfolder.fold1(bool_not, tree.arg.type);
  2851         // If translated left hand side is an Apply, we are
  2852         // seeing an access method invocation. In this case, return
  2853         // that access method invocation as result.
  2854         if (isUpdateOperator && tree.arg.getTag() == JCTree.APPLY) {
  2855             result = tree.arg;
  2856         } else {
  2857             result = tree;
  2861     public void visitBinary(JCBinary tree) {
  2862         List<Type> formals = tree.operator.type.getParameterTypes();
  2863         JCTree lhs = tree.lhs = translate(tree.lhs, formals.head);
  2864         switch (tree.getTag()) {
  2865         case JCTree.OR:
  2866             if (lhs.type.isTrue()) {
  2867                 result = lhs;
  2868                 return;
  2870             if (lhs.type.isFalse()) {
  2871                 result = translate(tree.rhs, formals.tail.head);
  2872                 return;
  2874             break;
  2875         case JCTree.AND:
  2876             if (lhs.type.isFalse()) {
  2877                 result = lhs;
  2878                 return;
  2880             if (lhs.type.isTrue()) {
  2881                 result = translate(tree.rhs, formals.tail.head);
  2882                 return;
  2884             break;
  2886         tree.rhs = translate(tree.rhs, formals.tail.head);
  2887         result = tree;
  2890     public void visitIdent(JCIdent tree) {
  2891         result = access(tree.sym, tree, enclOp, false);
  2894     /** Translate away the foreach loop.  */
  2895     public void visitForeachLoop(JCEnhancedForLoop tree) {
  2896         if (types.elemtype(tree.expr.type) == null)
  2897             visitIterableForeachLoop(tree);
  2898         else
  2899             visitArrayForeachLoop(tree);
  2901         // where
  2902         /**
  2903          * A statement of the form
  2905          * <pre>
  2906          *     for ( T v : arrayexpr ) stmt;
  2907          * </pre>
  2909          * (where arrayexpr is of an array type) gets translated to
  2911          * <pre>
  2912          *     for ( { arraytype #arr = arrayexpr;
  2913          *             int #len = array.length;
  2914          *             int #i = 0; };
  2915          *           #i < #len; i$++ ) {
  2916          *         T v = arr$[#i];
  2917          *         stmt;
  2918          *     }
  2919          * </pre>
  2921          * where #arr, #len, and #i are freshly named synthetic local variables.
  2922          */
  2923         private void visitArrayForeachLoop(JCEnhancedForLoop tree) {
  2924             make_at(tree.expr.pos());
  2925             VarSymbol arraycache = new VarSymbol(0,
  2926                                                  names.fromString("arr" + target.syntheticNameChar()),
  2927                                                  tree.expr.type,
  2928                                                  currentMethodSym);
  2929             JCStatement arraycachedef = make.VarDef(arraycache, tree.expr);
  2930             VarSymbol lencache = new VarSymbol(0,
  2931                                                names.fromString("len" + target.syntheticNameChar()),
  2932                                                syms.intType,
  2933                                                currentMethodSym);
  2934             JCStatement lencachedef = make.
  2935                 VarDef(lencache, make.Select(make.Ident(arraycache), syms.lengthVar));
  2936             VarSymbol index = new VarSymbol(0,
  2937                                             names.fromString("i" + target.syntheticNameChar()),
  2938                                             syms.intType,
  2939                                             currentMethodSym);
  2941             JCVariableDecl indexdef = make.VarDef(index, make.Literal(INT, 0));
  2942             indexdef.init.type = indexdef.type = syms.intType.constType(0);
  2944             List<JCStatement> loopinit = List.of(arraycachedef, lencachedef, indexdef);
  2945             JCBinary cond = makeBinary(JCTree.LT, make.Ident(index), make.Ident(lencache));
  2947             JCExpressionStatement step = make.Exec(makeUnary(JCTree.PREINC, make.Ident(index)));
  2949             Type elemtype = types.elemtype(tree.expr.type);
  2950             JCExpression loopvarinit = make.Indexed(make.Ident(arraycache),
  2951                                                     make.Ident(index)).setType(elemtype);
  2952             JCVariableDecl loopvardef = (JCVariableDecl)make.VarDef(tree.var.mods,
  2953                                                   tree.var.name,
  2954                                                   tree.var.vartype,
  2955                                                   loopvarinit).setType(tree.var.type);
  2956             loopvardef.sym = tree.var.sym;
  2957             JCBlock body = make.
  2958                 Block(0, List.of(loopvardef, tree.body));
  2960             result = translate(make.
  2961                                ForLoop(loopinit,
  2962                                        cond,
  2963                                        List.of(step),
  2964                                        body));
  2965             patchTargets(body, tree, result);
  2967         /** Patch up break and continue targets. */
  2968         private void patchTargets(JCTree body, final JCTree src, final JCTree dest) {
  2969             class Patcher extends TreeScanner {
  2970                 public void visitBreak(JCBreak tree) {
  2971                     if (tree.target == src)
  2972                         tree.target = dest;
  2974                 public void visitContinue(JCContinue tree) {
  2975                     if (tree.target == src)
  2976                         tree.target = dest;
  2978                 public void visitClassDef(JCClassDecl tree) {}
  2980             new Patcher().scan(body);
  2982         /**
  2983          * A statement of the form
  2985          * <pre>
  2986          *     for ( T v : coll ) stmt ;
  2987          * </pre>
  2989          * (where coll implements Iterable<? extends T>) gets translated to
  2991          * <pre>
  2992          *     for ( Iterator<? extends T> #i = coll.iterator(); #i.hasNext(); ) {
  2993          *         T v = (T) #i.next();
  2994          *         stmt;
  2995          *     }
  2996          * </pre>
  2998          * where #i is a freshly named synthetic local variable.
  2999          */
  3000         private void visitIterableForeachLoop(JCEnhancedForLoop tree) {
  3001             make_at(tree.expr.pos());
  3002             Type iteratorTarget = syms.objectType;
  3003             Type iterableType = types.asSuper(types.upperBound(tree.expr.type),
  3004                                               syms.iterableType.tsym);
  3005             if (iterableType.getTypeArguments().nonEmpty())
  3006                 iteratorTarget = types.erasure(iterableType.getTypeArguments().head);
  3007             Type eType = tree.expr.type;
  3008             tree.expr.type = types.erasure(eType);
  3009             if (eType.tag == TYPEVAR && eType.getUpperBound().isCompound())
  3010                 tree.expr = make.TypeCast(types.erasure(iterableType), tree.expr);
  3011             Symbol iterator = lookupMethod(tree.expr.pos(),
  3012                                            names.iterator,
  3013                                            types.erasure(syms.iterableType),
  3014                                            List.<Type>nil());
  3015             VarSymbol itvar = new VarSymbol(0, names.fromString("i" + target.syntheticNameChar()),
  3016                                             types.erasure(iterator.type.getReturnType()),
  3017                                             currentMethodSym);
  3018             JCStatement init = make.
  3019                 VarDef(itvar,
  3020                        make.App(make.Select(tree.expr, iterator)));
  3021             Symbol hasNext = lookupMethod(tree.expr.pos(),
  3022                                           names.hasNext,
  3023                                           itvar.type,
  3024                                           List.<Type>nil());
  3025             JCMethodInvocation cond = make.App(make.Select(make.Ident(itvar), hasNext));
  3026             Symbol next = lookupMethod(tree.expr.pos(),
  3027                                        names.next,
  3028                                        itvar.type,
  3029                                        List.<Type>nil());
  3030             JCExpression vardefinit = make.App(make.Select(make.Ident(itvar), next));
  3031             if (tree.var.type.isPrimitive())
  3032                 vardefinit = make.TypeCast(types.upperBound(iteratorTarget), vardefinit);
  3033             else
  3034                 vardefinit = make.TypeCast(tree.var.type, vardefinit);
  3035             JCVariableDecl indexDef = (JCVariableDecl)make.VarDef(tree.var.mods,
  3036                                                   tree.var.name,
  3037                                                   tree.var.vartype,
  3038                                                   vardefinit).setType(tree.var.type);
  3039             indexDef.sym = tree.var.sym;
  3040             JCBlock body = make.Block(0, List.of(indexDef, tree.body));
  3041             body.endpos = TreeInfo.endPos(tree.body);
  3042             result = translate(make.
  3043                 ForLoop(List.of(init),
  3044                         cond,
  3045                         List.<JCExpressionStatement>nil(),
  3046                         body));
  3047             patchTargets(body, tree, result);
  3050     public void visitVarDef(JCVariableDecl tree) {
  3051         MethodSymbol oldMethodSym = currentMethodSym;
  3052         tree.mods = translate(tree.mods);
  3053         tree.vartype = translate(tree.vartype);
  3054         if (currentMethodSym == null) {
  3055             // A class or instance field initializer.
  3056             currentMethodSym =
  3057                 new MethodSymbol((tree.mods.flags&STATIC) | BLOCK,
  3058                                  names.empty, null,
  3059                                  currentClass);
  3061         if (tree.init != null) tree.init = translate(tree.init, tree.type);
  3062         result = tree;
  3063         currentMethodSym = oldMethodSym;
  3066     public void visitBlock(JCBlock tree) {
  3067         MethodSymbol oldMethodSym = currentMethodSym;
  3068         if (currentMethodSym == null) {
  3069             // Block is a static or instance initializer.
  3070             currentMethodSym =
  3071                 new MethodSymbol(tree.flags | BLOCK,
  3072                                  names.empty, null,
  3073                                  currentClass);
  3075         super.visitBlock(tree);
  3076         currentMethodSym = oldMethodSym;
  3079     public void visitDoLoop(JCDoWhileLoop tree) {
  3080         tree.body = translate(tree.body);
  3081         tree.cond = translate(tree.cond, syms.booleanType);
  3082         result = tree;
  3085     public void visitWhileLoop(JCWhileLoop tree) {
  3086         tree.cond = translate(tree.cond, syms.booleanType);
  3087         tree.body = translate(tree.body);
  3088         result = tree;
  3091     public void visitForLoop(JCForLoop tree) {
  3092         tree.init = translate(tree.init);
  3093         if (tree.cond != null)
  3094             tree.cond = translate(tree.cond, syms.booleanType);
  3095         tree.step = translate(tree.step);
  3096         tree.body = translate(tree.body);
  3097         result = tree;
  3100     public void visitReturn(JCReturn tree) {
  3101         if (tree.expr != null)
  3102             tree.expr = translate(tree.expr,
  3103                                   types.erasure(currentMethodDef
  3104                                                 .restype.type));
  3105         result = tree;
  3108     public void visitSwitch(JCSwitch tree) {
  3109         Type selsuper = types.supertype(tree.selector.type);
  3110         boolean enumSwitch = selsuper != null &&
  3111             (tree.selector.type.tsym.flags() & ENUM) != 0;
  3112         boolean stringSwitch = selsuper != null &&
  3113             types.isSameType(tree.selector.type, syms.stringType);
  3114         Type target = enumSwitch ? tree.selector.type :
  3115             (stringSwitch? syms.stringType : syms.intType);
  3116         tree.selector = translate(tree.selector, target);
  3117         tree.cases = translateCases(tree.cases);
  3118         if (enumSwitch) {
  3119             result = visitEnumSwitch(tree);
  3120             patchTargets(result, tree, result);
  3121         } else if (stringSwitch) {
  3122             result = visitStringSwitch(tree);
  3123         } else {
  3124             result = tree;
  3128     public JCTree visitEnumSwitch(JCSwitch tree) {
  3129         TypeSymbol enumSym = tree.selector.type.tsym;
  3130         EnumMapping map = mapForEnum(tree.pos(), enumSym);
  3131         make_at(tree.pos());
  3132         Symbol ordinalMethod = lookupMethod(tree.pos(),
  3133                                             names.ordinal,
  3134                                             tree.selector.type,
  3135                                             List.<Type>nil());
  3136         JCArrayAccess selector = make.Indexed(map.mapVar,
  3137                                         make.App(make.Select(tree.selector,
  3138                                                              ordinalMethod)));
  3139         ListBuffer<JCCase> cases = new ListBuffer<JCCase>();
  3140         for (JCCase c : tree.cases) {
  3141             if (c.pat != null) {
  3142                 VarSymbol label = (VarSymbol)TreeInfo.symbol(c.pat);
  3143                 JCLiteral pat = map.forConstant(label);
  3144                 cases.append(make.Case(pat, c.stats));
  3145             } else {
  3146                 cases.append(c);
  3149         return make.Switch(selector, cases.toList());
  3152     public JCTree visitStringSwitch(JCSwitch tree) {
  3153         List<JCCase> caseList = tree.getCases();
  3154         int alternatives = caseList.size();
  3156         if (alternatives == 0) { // Strange but legal possibility
  3157             return make.at(tree.pos()).Exec(attr.makeNullCheck(tree.getExpression()));
  3158         } else {
  3159             /*
  3160              * The general approach used is to translate a single
  3161              * string switch statement into a series of two chained
  3162              * switch statements: the first a synthesized statement
  3163              * switching on the argument string's hash value and
  3164              * computing a string's position in the list of original
  3165              * case labels, if any, followed by a second switch on the
  3166              * computed integer value.  The second switch has the same
  3167              * code structure as the original string switch statement
  3168              * except that the string case labels are replaced with
  3169              * positional integer constants starting at 0.
  3171              * The first switch statement can be thought of as an
  3172              * inlined map from strings to their position in the case
  3173              * label list.  An alternate implementation would use an
  3174              * actual Map for this purpose, as done for enum switches.
  3176              * With some additional effort, it would be possible to
  3177              * use a single switch statement on the hash code of the
  3178              * argument, but care would need to be taken to preserve
  3179              * the proper control flow in the presence of hash
  3180              * collisions and other complications, such as
  3181              * fallthroughs.  Switch statements with one or two
  3182              * alternatives could also be specially translated into
  3183              * if-then statements to omit the computation of the hash
  3184              * code.
  3186              * The generated code assumes that the hashing algorithm
  3187              * of String is the same in the compilation environment as
  3188              * in the environment the code will run in.  The string
  3189              * hashing algorithm in the SE JDK has been unchanged
  3190              * since at least JDK 1.2.
  3191              */
  3193             ListBuffer<JCStatement> stmtList = new ListBuffer<JCStatement>();
  3195             // Map from String case labels to their original position in
  3196             // the list of case labels.
  3197             Map<String, Integer> caseLabelToPosition =
  3198                 new LinkedHashMap<String, Integer>(alternatives + 1, 1.0f);
  3200             // Map of hash codes to the string case labels having that hashCode.
  3201             Map<Integer, Set<String>> hashToString =
  3202                 new LinkedHashMap<Integer, Set<String>>(alternatives + 1, 1.0f);
  3204             int casePosition = 0;
  3205             for(JCCase oneCase : caseList) {
  3206                 JCExpression expression = oneCase.getExpression();
  3208                 if (expression != null) { // expression for a "default" case is null
  3209                     String labelExpr = (String) expression.type.constValue();
  3210                     Integer mapping = caseLabelToPosition.put(labelExpr, casePosition);
  3211                     assert mapping == null;
  3212                     int hashCode = labelExpr.hashCode();
  3214                     Set<String> stringSet = hashToString.get(hashCode);
  3215                     if (stringSet == null) {
  3216                         stringSet = new LinkedHashSet<String>(1, 1.0f);
  3217                         stringSet.add(labelExpr);
  3218                         hashToString.put(hashCode, stringSet);
  3219                     } else {
  3220                         boolean added = stringSet.add(labelExpr);
  3221                         assert added;
  3224                 casePosition++;
  3227             // Synthesize a switch statement that has the effect of
  3228             // mapping from a string to the integer position of that
  3229             // string in the list of case labels.  This is done by
  3230             // switching on the hashCode of the string followed by an
  3231             // if-then-else chain comparing the input for equality
  3232             // with all the case labels having that hash value.
  3234             /*
  3235              * s$ = top of stack;
  3236              * tmp$ = -1;
  3237              * switch($s.hashCode()) {
  3238              *     case caseLabel.hashCode:
  3239              *         if (s$.equals("caseLabel_1")
  3240              *           tmp$ = caseLabelToPosition("caseLabel_1");
  3241              *         else if (s$.equals("caseLabel_2"))
  3242              *           tmp$ = caseLabelToPosition("caseLabel_2");
  3243              *         ...
  3244              *         break;
  3245              * ...
  3246              * }
  3247              */
  3249             VarSymbol dollar_s = new VarSymbol(FINAL|SYNTHETIC,
  3250                                                names.fromString("s" + tree.pos + target.syntheticNameChar()),
  3251                                                syms.stringType,
  3252                                                currentMethodSym);
  3253             stmtList.append(make.at(tree.pos()).VarDef(dollar_s, tree.getExpression()).setType(dollar_s.type));
  3255             VarSymbol dollar_tmp = new VarSymbol(SYNTHETIC,
  3256                                                  names.fromString("tmp" + tree.pos + target.syntheticNameChar()),
  3257                                                  syms.intType,
  3258                                                  currentMethodSym);
  3259             JCVariableDecl dollar_tmp_def =
  3260                 (JCVariableDecl)make.VarDef(dollar_tmp, make.Literal(INT, -1)).setType(dollar_tmp.type);
  3261             dollar_tmp_def.init.type = dollar_tmp.type = syms.intType;
  3262             stmtList.append(dollar_tmp_def);
  3263             ListBuffer<JCCase> caseBuffer = ListBuffer.lb();
  3264             // hashCode will trigger nullcheck on original switch expression
  3265             JCMethodInvocation hashCodeCall = makeCall(make.Ident(dollar_s),
  3266                                                        names.hashCode,
  3267                                                        List.<JCExpression>nil()).setType(syms.intType);
  3268             JCSwitch switch1 = make.Switch(hashCodeCall,
  3269                                         caseBuffer.toList());
  3270             for(Map.Entry<Integer, Set<String>> entry : hashToString.entrySet()) {
  3271                 int hashCode = entry.getKey();
  3272                 Set<String> stringsWithHashCode = entry.getValue();
  3273                 assert stringsWithHashCode.size() >= 1;
  3275                 JCStatement elsepart = null;
  3276                 for(String caseLabel : stringsWithHashCode ) {
  3277                     JCMethodInvocation stringEqualsCall = makeCall(make.Ident(dollar_s),
  3278                                                                    names.equals,
  3279                                                                    List.<JCExpression>of(make.Literal(caseLabel)));
  3280                     elsepart = make.If(stringEqualsCall,
  3281                                        make.Exec(make.Assign(make.Ident(dollar_tmp),
  3282                                                              make.Literal(caseLabelToPosition.get(caseLabel))).
  3283                                                  setType(dollar_tmp.type)),
  3284                                        elsepart);
  3287                 ListBuffer<JCStatement> lb = ListBuffer.lb();
  3288                 JCBreak breakStmt = make.Break(null);
  3289                 breakStmt.target = switch1;
  3290                 lb.append(elsepart).append(breakStmt);
  3292                 caseBuffer.append(make.Case(make.Literal(hashCode), lb.toList()));
  3295             switch1.cases = caseBuffer.toList();
  3296             stmtList.append(switch1);
  3298             // Make isomorphic switch tree replacing string labels
  3299             // with corresponding integer ones from the label to
  3300             // position map.
  3302             ListBuffer<JCCase> lb = ListBuffer.lb();
  3303             JCSwitch switch2 = make.Switch(make.Ident(dollar_tmp), lb.toList());
  3304             for(JCCase oneCase : caseList ) {
  3305                 // Rewire up old unlabeled break statements to the
  3306                 // replacement switch being created.
  3307                 patchTargets(oneCase, tree, switch2);
  3309                 boolean isDefault = (oneCase.getExpression() == null);
  3310                 JCExpression caseExpr;
  3311                 if (isDefault)
  3312                     caseExpr = null;
  3313                 else {
  3314                     caseExpr = make.Literal(caseLabelToPosition.get((String)oneCase.
  3315                                                                     getExpression().
  3316                                                                     type.constValue()));
  3319                 lb.append(make.Case(caseExpr,
  3320                                     oneCase.getStatements()));
  3323             switch2.cases = lb.toList();
  3324             stmtList.append(switch2);
  3326             return make.Block(0L, stmtList.toList());
  3330     public void visitNewArray(JCNewArray tree) {
  3331         tree.elemtype = translate(tree.elemtype);
  3332         for (List<JCExpression> t = tree.dims; t.tail != null; t = t.tail)
  3333             if (t.head != null) t.head = translate(t.head, syms.intType);
  3334         tree.elems = translate(tree.elems, types.elemtype(tree.type));
  3335         result = tree;
  3338     public void visitSelect(JCFieldAccess tree) {
  3339         // need to special case-access of the form C.super.x
  3340         // these will always need an access method.
  3341         boolean qualifiedSuperAccess =
  3342             tree.selected.getTag() == JCTree.SELECT &&
  3343             TreeInfo.name(tree.selected) == names._super;
  3344         tree.selected = translate(tree.selected);
  3345         if (tree.name == names._class)
  3346             result = classOf(tree.selected);
  3347         else if (tree.name == names._this || tree.name == names._super)
  3348             result = makeThis(tree.pos(), tree.selected.type.tsym);
  3349         else
  3350             result = access(tree.sym, tree, enclOp, qualifiedSuperAccess);
  3353     public void visitLetExpr(LetExpr tree) {
  3354         tree.defs = translateVarDefs(tree.defs);
  3355         tree.expr = translate(tree.expr, tree.type);
  3356         result = tree;
  3359     // There ought to be nothing to rewrite here;
  3360     // we don't generate code.
  3361     public void visitAnnotation(JCAnnotation tree) {
  3362         result = tree;
  3365 /**************************************************************************
  3366  * main method
  3367  *************************************************************************/
  3369     /** Translate a toplevel class and return a list consisting of
  3370      *  the translated class and translated versions of all inner classes.
  3371      *  @param env   The attribution environment current at the class definition.
  3372      *               We need this for resolving some additional symbols.
  3373      *  @param cdef  The tree representing the class definition.
  3374      */
  3375     public List<JCTree> translateTopLevelClass(Env<AttrContext> env, JCTree cdef, TreeMaker make) {
  3376         ListBuffer<JCTree> translated = null;
  3377         try {
  3378             attrEnv = env;
  3379             this.make = make;
  3380             endPositions = env.toplevel.endPositions;
  3381             currentClass = null;
  3382             currentMethodDef = null;
  3383             outermostClassDef = (cdef.getTag() == JCTree.CLASSDEF) ? (JCClassDecl)cdef : null;
  3384             outermostMemberDef = null;
  3385             this.translated = new ListBuffer<JCTree>();
  3386             classdefs = new HashMap<ClassSymbol,JCClassDecl>();
  3387             actualSymbols = new HashMap<Symbol,Symbol>();
  3388             freevarCache = new HashMap<ClassSymbol,List<VarSymbol>>();
  3389             proxies = new Scope(syms.noSymbol);
  3390             outerThisStack = List.nil();
  3391             accessNums = new HashMap<Symbol,Integer>();
  3392             accessSyms = new HashMap<Symbol,MethodSymbol[]>();
  3393             accessConstrs = new HashMap<Symbol,MethodSymbol>();
  3394             accessed = new ListBuffer<Symbol>();
  3395             translate(cdef, (JCExpression)null);
  3396             for (List<Symbol> l = accessed.toList(); l.nonEmpty(); l = l.tail)
  3397                 makeAccessible(l.head);
  3398             for (EnumMapping map : enumSwitchMap.values())
  3399                 map.translate();
  3400             checkConflicts(this.translated.toList());
  3401             translated = this.translated;
  3402         } finally {
  3403             // note that recursive invocations of this method fail hard
  3404             attrEnv = null;
  3405             this.make = null;
  3406             endPositions = null;
  3407             currentClass = null;
  3408             currentMethodDef = null;
  3409             outermostClassDef = null;
  3410             outermostMemberDef = null;
  3411             this.translated = null;
  3412             classdefs = null;
  3413             actualSymbols = null;
  3414             freevarCache = null;
  3415             proxies = null;
  3416             outerThisStack = null;
  3417             accessNums = null;
  3418             accessSyms = null;
  3419             accessConstrs = null;
  3420             accessed = null;
  3421             enumSwitchMap.clear();
  3423         return translated.toList();
  3426     //////////////////////////////////////////////////////////////
  3427     // The following contributed by Borland for bootstrapping purposes
  3428     //////////////////////////////////////////////////////////////
  3429     private void addEnumCompatibleMembers(JCClassDecl cdef) {
  3430         make_at(null);
  3432         // Add the special enum fields
  3433         VarSymbol ordinalFieldSym = addEnumOrdinalField(cdef);
  3434         VarSymbol nameFieldSym = addEnumNameField(cdef);
  3436         // Add the accessor methods for name and ordinal
  3437         MethodSymbol ordinalMethodSym = addEnumFieldOrdinalMethod(cdef, ordinalFieldSym);
  3438         MethodSymbol nameMethodSym = addEnumFieldNameMethod(cdef, nameFieldSym);
  3440         // Add the toString method
  3441         addEnumToString(cdef, nameFieldSym);
  3443         // Add the compareTo method
  3444         addEnumCompareTo(cdef, ordinalFieldSym);
  3447     private VarSymbol addEnumOrdinalField(JCClassDecl cdef) {
  3448         VarSymbol ordinal = new VarSymbol(PRIVATE|FINAL|SYNTHETIC,
  3449                                           names.fromString("$ordinal"),
  3450                                           syms.intType,
  3451                                           cdef.sym);
  3452         cdef.sym.members().enter(ordinal);
  3453         cdef.defs = cdef.defs.prepend(make.VarDef(ordinal, null));
  3454         return ordinal;
  3457     private VarSymbol addEnumNameField(JCClassDecl cdef) {
  3458         VarSymbol name = new VarSymbol(PRIVATE|FINAL|SYNTHETIC,
  3459                                           names.fromString("$name"),
  3460                                           syms.stringType,
  3461                                           cdef.sym);
  3462         cdef.sym.members().enter(name);
  3463         cdef.defs = cdef.defs.prepend(make.VarDef(name, null));
  3464         return name;
  3467     private MethodSymbol addEnumFieldOrdinalMethod(JCClassDecl cdef, VarSymbol ordinalSymbol) {
  3468         // Add the accessor methods for ordinal
  3469         Symbol ordinalSym = lookupMethod(cdef.pos(),
  3470                                          names.ordinal,
  3471                                          cdef.type,
  3472                                          List.<Type>nil());
  3474         assert(ordinalSym != null);
  3475         assert(ordinalSym instanceof MethodSymbol);
  3477         JCStatement ret = make.Return(make.Ident(ordinalSymbol));
  3478         cdef.defs = cdef.defs.append(make.MethodDef((MethodSymbol)ordinalSym,
  3479                                                     make.Block(0L, List.of(ret))));
  3481         return (MethodSymbol)ordinalSym;
  3484     private MethodSymbol addEnumFieldNameMethod(JCClassDecl cdef, VarSymbol nameSymbol) {
  3485         // Add the accessor methods for name
  3486         Symbol nameSym = lookupMethod(cdef.pos(),
  3487                                    names._name,
  3488                                    cdef.type,
  3489                                    List.<Type>nil());
  3491         assert(nameSym != null);
  3492         assert(nameSym instanceof MethodSymbol);
  3494         JCStatement ret = make.Return(make.Ident(nameSymbol));
  3496         cdef.defs = cdef.defs.append(make.MethodDef((MethodSymbol)nameSym,
  3497                                                     make.Block(0L, List.of(ret))));
  3499         return (MethodSymbol)nameSym;
  3502     private MethodSymbol addEnumToString(JCClassDecl cdef,
  3503                                          VarSymbol nameSymbol) {
  3504         Symbol toStringSym = lookupMethod(cdef.pos(),
  3505                                           names.toString,
  3506                                           cdef.type,
  3507                                           List.<Type>nil());
  3509         JCTree toStringDecl = null;
  3510         if (toStringSym != null)
  3511             toStringDecl = TreeInfo.declarationFor(toStringSym, cdef);
  3513         if (toStringDecl != null)
  3514             return (MethodSymbol)toStringSym;
  3516         JCStatement ret = make.Return(make.Ident(nameSymbol));
  3518         JCTree resTypeTree = make.Type(syms.stringType);
  3520         MethodType toStringType = new MethodType(List.<Type>nil(),
  3521                                                  syms.stringType,
  3522                                                  List.<Type>nil(),
  3523                                                  cdef.sym);
  3524         toStringSym = new MethodSymbol(PUBLIC,
  3525                                        names.toString,
  3526                                        toStringType,
  3527                                        cdef.type.tsym);
  3528         toStringDecl = make.MethodDef((MethodSymbol)toStringSym,
  3529                                       make.Block(0L, List.of(ret)));
  3531         cdef.defs = cdef.defs.prepend(toStringDecl);
  3532         cdef.sym.members().enter(toStringSym);
  3534         return (MethodSymbol)toStringSym;
  3537     private MethodSymbol addEnumCompareTo(JCClassDecl cdef, VarSymbol ordinalSymbol) {
  3538         Symbol compareToSym = lookupMethod(cdef.pos(),
  3539                                    names.compareTo,
  3540                                    cdef.type,
  3541                                    List.of(cdef.sym.type));
  3543         assert(compareToSym != null);
  3544         assert(compareToSym instanceof MethodSymbol);
  3546         JCMethodDecl compareToDecl = (JCMethodDecl) TreeInfo.declarationFor(compareToSym, cdef);
  3548         ListBuffer<JCStatement> blockStatements = new ListBuffer<JCStatement>();
  3550         JCModifiers mod1 = make.Modifiers(0L);
  3551         Name oName = names.fromString("o");
  3552         JCVariableDecl par1 = make.Param(oName, cdef.type, compareToSym);
  3554         JCIdent paramId1 = make.Ident(names.java_lang_Object);
  3555         paramId1.type = cdef.type;
  3556         paramId1.sym = par1.sym;
  3558         ((MethodSymbol)compareToSym).params = List.of(par1.sym);
  3560         JCIdent par1UsageId = make.Ident(par1.sym);
  3561         JCIdent castTargetIdent = make.Ident(cdef.sym);
  3562         JCTypeCast cast = make.TypeCast(castTargetIdent, par1UsageId);
  3563         cast.setType(castTargetIdent.type);
  3565         Name otherName = names.fromString("other");
  3567         VarSymbol otherVarSym = new VarSymbol(mod1.flags,
  3568                                               otherName,
  3569                                               cdef.type,
  3570                                               compareToSym);
  3571         JCVariableDecl otherVar = make.VarDef(otherVarSym, cast);
  3572         blockStatements.append(otherVar);
  3574         JCIdent id1 = make.Ident(ordinalSymbol);
  3576         JCIdent fLocUsageId = make.Ident(otherVarSym);
  3577         JCExpression sel = make.Select(fLocUsageId, ordinalSymbol);
  3578         JCBinary bin = makeBinary(JCTree.MINUS, id1, sel);
  3579         JCReturn ret = make.Return(bin);
  3580         blockStatements.append(ret);
  3581         JCMethodDecl compareToMethod = make.MethodDef((MethodSymbol)compareToSym,
  3582                                                    make.Block(0L,
  3583                                                               blockStatements.toList()));
  3584         compareToMethod.params = List.of(par1);
  3585         cdef.defs = cdef.defs.append(compareToMethod);
  3587         return (MethodSymbol)compareToSym;
  3589     //////////////////////////////////////////////////////////////
  3590     // The above contributed by Borland for bootstrapping purposes
  3591     //////////////////////////////////////////////////////////////

mercurial