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