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