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