Lower.java revision 3810:e5e4064d037d
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, new TreeBuilder() {
2258                    public JCExpression build(final JCExpression selected) {
2259                        return builder.build(make.Select(selected, s.sym));
2260                    }
2261                });
2262        }
2263        case INDEXED: {
2264            final JCArrayAccess i = (JCArrayAccess)lval;
2265            return abstractRval(i.indexed, new TreeBuilder() {
2266                    public JCExpression build(final JCExpression indexed) {
2267                        return abstractRval(i.index, syms.intType, new TreeBuilder() {
2268                                public JCExpression build(final JCExpression index) {
2269                                    JCExpression newLval = make.Indexed(indexed, index);
2270                                    newLval.setType(i.type);
2271                                    return builder.build(newLval);
2272                                }
2273                            });
2274                    }
2275                });
2276        }
2277        case TYPECAST: {
2278            return abstractLval(((JCTypeCast)lval).expr, builder);
2279        }
2280        }
2281        throw new AssertionError(lval);
2282    }
2283
2284    // evaluate and discard the first expression, then evaluate the second.
2285    JCExpression makeComma(final JCExpression expr1, final JCExpression expr2) {
2286        return abstractRval(expr1, new TreeBuilder() {
2287                public JCExpression build(final JCExpression discarded) {
2288                    return expr2;
2289                }
2290            });
2291    }
2292
2293/**************************************************************************
2294 * Translation methods
2295 *************************************************************************/
2296
2297    /** Visitor argument: enclosing operator node.
2298     */
2299    private JCExpression enclOp;
2300
2301    /** Visitor method: Translate a single node.
2302     *  Attach the source position from the old tree to its replacement tree.
2303     */
2304    @Override
2305    public <T extends JCTree> T translate(T tree) {
2306        if (tree == null) {
2307            return null;
2308        } else {
2309            make_at(tree.pos());
2310            T result = super.translate(tree);
2311            if (endPosTable != null && result != tree) {
2312                endPosTable.replaceTree(tree, result);
2313            }
2314            return result;
2315        }
2316    }
2317
2318    /** Visitor method: Translate a single node, boxing or unboxing if needed.
2319     */
2320    public <T extends JCExpression> T translate(T tree, Type type) {
2321        return (tree == null) ? null : boxIfNeeded(translate(tree), type);
2322    }
2323
2324    /** Visitor method: Translate tree.
2325     */
2326    public <T extends JCTree> T translate(T tree, JCExpression enclOp) {
2327        JCExpression prevEnclOp = this.enclOp;
2328        this.enclOp = enclOp;
2329        T res = translate(tree);
2330        this.enclOp = prevEnclOp;
2331        return res;
2332    }
2333
2334    /** Visitor method: Translate list of trees.
2335     */
2336    public <T extends JCTree> List<T> translate(List<T> trees, JCExpression enclOp) {
2337        JCExpression prevEnclOp = this.enclOp;
2338        this.enclOp = enclOp;
2339        List<T> res = translate(trees);
2340        this.enclOp = prevEnclOp;
2341        return res;
2342    }
2343
2344    /** Visitor method: Translate list of trees.
2345     */
2346    public <T extends JCExpression> List<T> translate(List<T> trees, Type type) {
2347        if (trees == null) return null;
2348        for (List<T> l = trees; l.nonEmpty(); l = l.tail)
2349            l.head = translate(l.head, type);
2350        return trees;
2351    }
2352
2353    public void visitPackageDef(JCPackageDecl tree) {
2354        if (!needPackageInfoClass(tree))
2355                        return;
2356
2357        long flags = Flags.ABSTRACT | Flags.INTERFACE;
2358        // package-info is marked SYNTHETIC in JDK 1.6 and later releases
2359        flags = flags | Flags.SYNTHETIC;
2360        ClassSymbol c = tree.packge.package_info;
2361        c.setAttributes(tree.packge);
2362        c.flags_field |= flags;
2363        ClassType ctype = (ClassType) c.type;
2364        ctype.supertype_field = syms.objectType;
2365        ctype.interfaces_field = List.nil();
2366        createInfoClass(tree.annotations, c);
2367    }
2368    // where
2369    private boolean needPackageInfoClass(JCPackageDecl pd) {
2370        switch (pkginfoOpt) {
2371            case ALWAYS:
2372                return true;
2373            case LEGACY:
2374                return pd.getAnnotations().nonEmpty();
2375            case NONEMPTY:
2376                for (Attribute.Compound a :
2377                         pd.packge.getDeclarationAttributes()) {
2378                    Attribute.RetentionPolicy p = types.getRetention(a);
2379                    if (p != Attribute.RetentionPolicy.SOURCE)
2380                        return true;
2381                }
2382                return false;
2383        }
2384        throw new AssertionError();
2385    }
2386
2387    public void visitModuleDef(JCModuleDecl tree) {
2388        ModuleSymbol msym = tree.sym;
2389        ClassSymbol c = msym.module_info;
2390        c.setAttributes(msym);
2391        c.flags_field |= Flags.MODULE;
2392        createInfoClass(List.<JCAnnotation>nil(), tree.sym.module_info);
2393    }
2394
2395    private void createInfoClass(List<JCAnnotation> annots, ClassSymbol c) {
2396        long flags = Flags.ABSTRACT | Flags.INTERFACE;
2397        JCClassDecl infoClass =
2398                make.ClassDef(make.Modifiers(flags, annots),
2399                    c.name, List.<JCTypeParameter>nil(),
2400                    null, List.<JCExpression>nil(), List.<JCTree>nil());
2401        infoClass.sym = c;
2402        translated.append(infoClass);
2403    }
2404
2405    public void visitClassDef(JCClassDecl tree) {
2406        Env<AttrContext> prevEnv = attrEnv;
2407        ClassSymbol currentClassPrev = currentClass;
2408        MethodSymbol currentMethodSymPrev = currentMethodSym;
2409
2410        currentClass = tree.sym;
2411        currentMethodSym = null;
2412        attrEnv = typeEnvs.remove(currentClass);
2413        if (attrEnv == null)
2414            attrEnv = prevEnv;
2415
2416        classdefs.put(currentClass, tree);
2417
2418        proxies = proxies.dup(currentClass);
2419        List<VarSymbol> prevOuterThisStack = outerThisStack;
2420
2421        // If this is an enum definition
2422        if ((tree.mods.flags & ENUM) != 0 &&
2423            (types.supertype(currentClass.type).tsym.flags() & ENUM) == 0)
2424            visitEnumDef(tree);
2425
2426        // If this is a nested class, define a this$n field for
2427        // it and add to proxies.
2428        JCVariableDecl otdef = null;
2429        if (currentClass.hasOuterInstance())
2430            otdef = outerThisDef(tree.pos, currentClass);
2431
2432        // If this is a local class, define proxies for all its free variables.
2433        List<JCVariableDecl> fvdefs = freevarDefs(
2434            tree.pos, freevars(currentClass), currentClass);
2435
2436        // Recursively translate superclass, interfaces.
2437        tree.extending = translate(tree.extending);
2438        tree.implementing = translate(tree.implementing);
2439
2440        if (currentClass.isLocal()) {
2441            ClassSymbol encl = currentClass.owner.enclClass();
2442            if (encl.trans_local == null) {
2443                encl.trans_local = List.nil();
2444            }
2445            encl.trans_local = encl.trans_local.prepend(currentClass);
2446        }
2447
2448        // Recursively translate members, taking into account that new members
2449        // might be created during the translation and prepended to the member
2450        // list `tree.defs'.
2451        List<JCTree> seen = List.nil();
2452        while (tree.defs != seen) {
2453            List<JCTree> unseen = tree.defs;
2454            for (List<JCTree> l = unseen; l.nonEmpty() && l != seen; l = l.tail) {
2455                JCTree outermostMemberDefPrev = outermostMemberDef;
2456                if (outermostMemberDefPrev == null) outermostMemberDef = l.head;
2457                l.head = translate(l.head);
2458                outermostMemberDef = outermostMemberDefPrev;
2459            }
2460            seen = unseen;
2461        }
2462
2463        // Convert a protected modifier to public, mask static modifier.
2464        if ((tree.mods.flags & PROTECTED) != 0) tree.mods.flags |= PUBLIC;
2465        tree.mods.flags &= ClassFlags;
2466
2467        // Convert name to flat representation, replacing '.' by '$'.
2468        tree.name = Convert.shortName(currentClass.flatName());
2469
2470        // Add this$n and free variables proxy definitions to class.
2471
2472        for (List<JCVariableDecl> l = fvdefs; l.nonEmpty(); l = l.tail) {
2473            tree.defs = tree.defs.prepend(l.head);
2474            enterSynthetic(tree.pos(), l.head.sym, currentClass.members());
2475        }
2476        if (currentClass.hasOuterInstance()) {
2477            tree.defs = tree.defs.prepend(otdef);
2478            enterSynthetic(tree.pos(), otdef.sym, currentClass.members());
2479        }
2480
2481        proxies = proxies.leave();
2482        outerThisStack = prevOuterThisStack;
2483
2484        // Append translated tree to `translated' queue.
2485        translated.append(tree);
2486
2487        attrEnv = prevEnv;
2488        currentClass = currentClassPrev;
2489        currentMethodSym = currentMethodSymPrev;
2490
2491        // Return empty block {} as a placeholder for an inner class.
2492        result = make_at(tree.pos()).Block(SYNTHETIC, List.<JCStatement>nil());
2493    }
2494
2495    /** Translate an enum class. */
2496    private void visitEnumDef(JCClassDecl tree) {
2497        make_at(tree.pos());
2498
2499        // add the supertype, if needed
2500        if (tree.extending == null)
2501            tree.extending = make.Type(types.supertype(tree.type));
2502
2503        // classOfType adds a cache field to tree.defs
2504        JCExpression e_class = classOfType(tree.sym.type, tree.pos()).
2505            setType(types.erasure(syms.classType));
2506
2507        // process each enumeration constant, adding implicit constructor parameters
2508        int nextOrdinal = 0;
2509        ListBuffer<JCExpression> values = new ListBuffer<>();
2510        ListBuffer<JCTree> enumDefs = new ListBuffer<>();
2511        ListBuffer<JCTree> otherDefs = new ListBuffer<>();
2512        for (List<JCTree> defs = tree.defs;
2513             defs.nonEmpty();
2514             defs=defs.tail) {
2515            if (defs.head.hasTag(VARDEF) && (((JCVariableDecl) defs.head).mods.flags & ENUM) != 0) {
2516                JCVariableDecl var = (JCVariableDecl)defs.head;
2517                visitEnumConstantDef(var, nextOrdinal++);
2518                values.append(make.QualIdent(var.sym));
2519                enumDefs.append(var);
2520            } else {
2521                otherDefs.append(defs.head);
2522            }
2523        }
2524
2525        // private static final T[] #VALUES = { a, b, c };
2526        Name valuesName = names.fromString(target.syntheticNameChar() + "VALUES");
2527        while (tree.sym.members().findFirst(valuesName) != null) // avoid name clash
2528            valuesName = names.fromString(valuesName + "" + target.syntheticNameChar());
2529        Type arrayType = new ArrayType(types.erasure(tree.type), syms.arrayClass);
2530        VarSymbol valuesVar = new VarSymbol(PRIVATE|FINAL|STATIC|SYNTHETIC,
2531                                            valuesName,
2532                                            arrayType,
2533                                            tree.type.tsym);
2534        JCNewArray newArray = make.NewArray(make.Type(types.erasure(tree.type)),
2535                                          List.<JCExpression>nil(),
2536                                          values.toList());
2537        newArray.type = arrayType;
2538        enumDefs.append(make.VarDef(valuesVar, newArray));
2539        tree.sym.members().enter(valuesVar);
2540
2541        Symbol valuesSym = lookupMethod(tree.pos(), names.values,
2542                                        tree.type, List.<Type>nil());
2543        List<JCStatement> valuesBody;
2544        if (useClone()) {
2545            // return (T[]) $VALUES.clone();
2546            JCTypeCast valuesResult =
2547                make.TypeCast(valuesSym.type.getReturnType(),
2548                              make.App(make.Select(make.Ident(valuesVar),
2549                                                   syms.arrayCloneMethod)));
2550            valuesBody = List.<JCStatement>of(make.Return(valuesResult));
2551        } else {
2552            // template: T[] $result = new T[$values.length];
2553            Name resultName = names.fromString(target.syntheticNameChar() + "result");
2554            while (tree.sym.members().findFirst(resultName) != null) // avoid name clash
2555                resultName = names.fromString(resultName + "" + target.syntheticNameChar());
2556            VarSymbol resultVar = new VarSymbol(FINAL|SYNTHETIC,
2557                                                resultName,
2558                                                arrayType,
2559                                                valuesSym);
2560            JCNewArray resultArray = make.NewArray(make.Type(types.erasure(tree.type)),
2561                                  List.of(make.Select(make.Ident(valuesVar), syms.lengthVar)),
2562                                  null);
2563            resultArray.type = arrayType;
2564            JCVariableDecl decl = make.VarDef(resultVar, resultArray);
2565
2566            // template: System.arraycopy($VALUES, 0, $result, 0, $VALUES.length);
2567            if (systemArraycopyMethod == null) {
2568                systemArraycopyMethod =
2569                    new MethodSymbol(PUBLIC | STATIC,
2570                                     names.fromString("arraycopy"),
2571                                     new MethodType(List.<Type>of(syms.objectType,
2572                                                            syms.intType,
2573                                                            syms.objectType,
2574                                                            syms.intType,
2575                                                            syms.intType),
2576                                                    syms.voidType,
2577                                                    List.<Type>nil(),
2578                                                    syms.methodClass),
2579                                     syms.systemType.tsym);
2580            }
2581            JCStatement copy =
2582                make.Exec(make.App(make.Select(make.Ident(syms.systemType.tsym),
2583                                               systemArraycopyMethod),
2584                          List.of(make.Ident(valuesVar), make.Literal(0),
2585                                  make.Ident(resultVar), make.Literal(0),
2586                                  make.Select(make.Ident(valuesVar), syms.lengthVar))));
2587
2588            // template: return $result;
2589            JCStatement ret = make.Return(make.Ident(resultVar));
2590            valuesBody = List.<JCStatement>of(decl, copy, ret);
2591        }
2592
2593        JCMethodDecl valuesDef =
2594             make.MethodDef((MethodSymbol)valuesSym, make.Block(0, valuesBody));
2595
2596        enumDefs.append(valuesDef);
2597
2598        if (debugLower)
2599            System.err.println(tree.sym + ".valuesDef = " + valuesDef);
2600
2601        /** The template for the following code is:
2602         *
2603         *     public static E valueOf(String name) {
2604         *         return (E)Enum.valueOf(E.class, name);
2605         *     }
2606         *
2607         *  where E is tree.sym
2608         */
2609        MethodSymbol valueOfSym = lookupMethod(tree.pos(),
2610                         names.valueOf,
2611                         tree.sym.type,
2612                         List.of(syms.stringType));
2613        Assert.check((valueOfSym.flags() & STATIC) != 0);
2614        VarSymbol nameArgSym = valueOfSym.params.head;
2615        JCIdent nameVal = make.Ident(nameArgSym);
2616        JCStatement enum_ValueOf =
2617            make.Return(make.TypeCast(tree.sym.type,
2618                                      makeCall(make.Ident(syms.enumSym),
2619                                               names.valueOf,
2620                                               List.of(e_class, nameVal))));
2621        JCMethodDecl valueOf = make.MethodDef(valueOfSym,
2622                                           make.Block(0, List.of(enum_ValueOf)));
2623        nameVal.sym = valueOf.params.head.sym;
2624        if (debugLower)
2625            System.err.println(tree.sym + ".valueOf = " + valueOf);
2626        enumDefs.append(valueOf);
2627
2628        enumDefs.appendList(otherDefs.toList());
2629        tree.defs = enumDefs.toList();
2630    }
2631        // where
2632        private MethodSymbol systemArraycopyMethod;
2633        private boolean useClone() {
2634            try {
2635                return syms.objectType.tsym.members().findFirst(names.clone) != null;
2636            }
2637            catch (CompletionFailure e) {
2638                return false;
2639            }
2640        }
2641
2642    /** Translate an enumeration constant and its initializer. */
2643    private void visitEnumConstantDef(JCVariableDecl var, int ordinal) {
2644        JCNewClass varDef = (JCNewClass)var.init;
2645        varDef.args = varDef.args.
2646            prepend(makeLit(syms.intType, ordinal)).
2647            prepend(makeLit(syms.stringType, var.name.toString()));
2648    }
2649
2650    public void visitMethodDef(JCMethodDecl tree) {
2651        if (tree.name == names.init && (currentClass.flags_field&ENUM) != 0) {
2652            // Add "String $enum$name, int $enum$ordinal" to the beginning of the
2653            // argument list for each constructor of an enum.
2654            JCVariableDecl nameParam = make_at(tree.pos()).
2655                Param(names.fromString(target.syntheticNameChar() +
2656                                       "enum" + target.syntheticNameChar() + "name"),
2657                      syms.stringType, tree.sym);
2658            nameParam.mods.flags |= SYNTHETIC; nameParam.sym.flags_field |= SYNTHETIC;
2659            JCVariableDecl ordParam = make.
2660                Param(names.fromString(target.syntheticNameChar() +
2661                                       "enum" + target.syntheticNameChar() +
2662                                       "ordinal"),
2663                      syms.intType, tree.sym);
2664            ordParam.mods.flags |= SYNTHETIC; ordParam.sym.flags_field |= SYNTHETIC;
2665
2666            MethodSymbol m = tree.sym;
2667            tree.params = tree.params.prepend(ordParam).prepend(nameParam);
2668
2669            m.extraParams = m.extraParams.prepend(ordParam.sym);
2670            m.extraParams = m.extraParams.prepend(nameParam.sym);
2671            Type olderasure = m.erasure(types);
2672            m.erasure_field = new MethodType(
2673                olderasure.getParameterTypes().prepend(syms.intType).prepend(syms.stringType),
2674                olderasure.getReturnType(),
2675                olderasure.getThrownTypes(),
2676                syms.methodClass);
2677        }
2678
2679        JCMethodDecl prevMethodDef = currentMethodDef;
2680        MethodSymbol prevMethodSym = currentMethodSym;
2681        try {
2682            currentMethodDef = tree;
2683            currentMethodSym = tree.sym;
2684            visitMethodDefInternal(tree);
2685        } finally {
2686            currentMethodDef = prevMethodDef;
2687            currentMethodSym = prevMethodSym;
2688        }
2689    }
2690
2691    private void visitMethodDefInternal(JCMethodDecl tree) {
2692        if (tree.name == names.init &&
2693            (currentClass.isInner() || currentClass.isLocal())) {
2694            // We are seeing a constructor of an inner class.
2695            MethodSymbol m = tree.sym;
2696
2697            // Push a new proxy scope for constructor parameters.
2698            // and create definitions for any this$n and proxy parameters.
2699            proxies = proxies.dup(m);
2700            List<VarSymbol> prevOuterThisStack = outerThisStack;
2701            List<VarSymbol> fvs = freevars(currentClass);
2702            JCVariableDecl otdef = null;
2703            if (currentClass.hasOuterInstance())
2704                otdef = outerThisDef(tree.pos, m);
2705            List<JCVariableDecl> fvdefs = freevarDefs(tree.pos, fvs, m, PARAMETER);
2706
2707            // Recursively translate result type, parameters and thrown list.
2708            tree.restype = translate(tree.restype);
2709            tree.params = translateVarDefs(tree.params);
2710            tree.thrown = translate(tree.thrown);
2711
2712            // when compiling stubs, don't process body
2713            if (tree.body == null) {
2714                result = tree;
2715                return;
2716            }
2717
2718            // Add this$n (if needed) in front of and free variables behind
2719            // constructor parameter list.
2720            tree.params = tree.params.appendList(fvdefs);
2721            if (currentClass.hasOuterInstance()) {
2722                tree.params = tree.params.prepend(otdef);
2723            }
2724
2725            // If this is an initial constructor, i.e., it does not start with
2726            // this(...), insert initializers for this$n and proxies
2727            // before (pre-1.4, after) the call to superclass constructor.
2728            JCStatement selfCall = translate(tree.body.stats.head);
2729
2730            List<JCStatement> added = List.nil();
2731            if (fvs.nonEmpty()) {
2732                List<Type> addedargtypes = List.nil();
2733                for (List<VarSymbol> l = fvs; l.nonEmpty(); l = l.tail) {
2734                    final Name pName = proxyName(l.head.name);
2735                    m.capturedLocals =
2736                        m.capturedLocals.prepend((VarSymbol)
2737                                                (proxies.findFirst(pName)));
2738                    if (TreeInfo.isInitialConstructor(tree)) {
2739                        added = added.prepend(
2740                          initField(tree.body.pos, pName));
2741                    }
2742                    addedargtypes = addedargtypes.prepend(l.head.erasure(types));
2743                }
2744                Type olderasure = m.erasure(types);
2745                m.erasure_field = new MethodType(
2746                    olderasure.getParameterTypes().appendList(addedargtypes),
2747                    olderasure.getReturnType(),
2748                    olderasure.getThrownTypes(),
2749                    syms.methodClass);
2750            }
2751            if (currentClass.hasOuterInstance() &&
2752                TreeInfo.isInitialConstructor(tree))
2753            {
2754                added = added.prepend(initOuterThis(tree.body.pos));
2755            }
2756
2757            // pop local variables from proxy stack
2758            proxies = proxies.leave();
2759
2760            // recursively translate following local statements and
2761            // combine with this- or super-call
2762            List<JCStatement> stats = translate(tree.body.stats.tail);
2763            tree.body.stats = stats.prepend(selfCall).prependList(added);
2764            outerThisStack = prevOuterThisStack;
2765        } else {
2766            Map<Symbol, Symbol> prevLambdaTranslationMap =
2767                    lambdaTranslationMap;
2768            try {
2769                lambdaTranslationMap = (tree.sym.flags() & SYNTHETIC) != 0 &&
2770                        tree.sym.name.startsWith(names.lambda) ?
2771                        makeTranslationMap(tree) : null;
2772                super.visitMethodDef(tree);
2773            } finally {
2774                lambdaTranslationMap = prevLambdaTranslationMap;
2775            }
2776        }
2777        result = tree;
2778    }
2779    //where
2780        private Map<Symbol, Symbol> makeTranslationMap(JCMethodDecl tree) {
2781            Map<Symbol, Symbol> translationMap = new HashMap<>();
2782            for (JCVariableDecl vd : tree.params) {
2783                Symbol p = vd.sym;
2784                if (p != p.baseSymbol()) {
2785                    translationMap.put(p.baseSymbol(), p);
2786                }
2787            }
2788            return translationMap;
2789        }
2790
2791    public void visitTypeCast(JCTypeCast tree) {
2792        tree.clazz = translate(tree.clazz);
2793        if (tree.type.isPrimitive() != tree.expr.type.isPrimitive())
2794            tree.expr = translate(tree.expr, tree.type);
2795        else
2796            tree.expr = translate(tree.expr);
2797        result = tree;
2798    }
2799
2800    public void visitNewClass(JCNewClass tree) {
2801        ClassSymbol c = (ClassSymbol)tree.constructor.owner;
2802
2803        // Box arguments, if necessary
2804        boolean isEnum = (tree.constructor.owner.flags() & ENUM) != 0;
2805        List<Type> argTypes = tree.constructor.type.getParameterTypes();
2806        if (isEnum) argTypes = argTypes.prepend(syms.intType).prepend(syms.stringType);
2807        tree.args = boxArgs(argTypes, tree.args, tree.varargsElement);
2808        tree.varargsElement = null;
2809
2810        // If created class is local, add free variables after
2811        // explicit constructor arguments.
2812        if (c.isLocal()) {
2813            tree.args = tree.args.appendList(loadFreevars(tree.pos(), freevars(c)));
2814        }
2815
2816        // If an access constructor is used, append null as a last argument.
2817        Symbol constructor = accessConstructor(tree.pos(), tree.constructor);
2818        if (constructor != tree.constructor) {
2819            tree.args = tree.args.append(makeNull());
2820            tree.constructor = constructor;
2821        }
2822
2823        // If created class has an outer instance, and new is qualified, pass
2824        // qualifier as first argument. If new is not qualified, pass the
2825        // correct outer instance as first argument.
2826        if (c.hasOuterInstance()) {
2827            JCExpression thisArg;
2828            if (tree.encl != null) {
2829                thisArg = attr.makeNullCheck(translate(tree.encl));
2830                thisArg.type = tree.encl.type;
2831            } else if (c.isLocal()) {
2832                // local class
2833                thisArg = makeThis(tree.pos(), c.type.getEnclosingType().tsym);
2834            } else {
2835                // nested class
2836                thisArg = makeOwnerThis(tree.pos(), c, false);
2837            }
2838            tree.args = tree.args.prepend(thisArg);
2839        }
2840        tree.encl = null;
2841
2842        // If we have an anonymous class, create its flat version, rather
2843        // than the class or interface following new.
2844        if (tree.def != null) {
2845            translate(tree.def);
2846            tree.clazz = access(make_at(tree.clazz.pos()).Ident(tree.def.sym));
2847            tree.def = null;
2848        } else {
2849            tree.clazz = access(c, tree.clazz, enclOp, false);
2850        }
2851        result = tree;
2852    }
2853
2854    // Simplify conditionals with known constant controlling expressions.
2855    // This allows us to avoid generating supporting declarations for
2856    // the dead code, which will not be eliminated during code generation.
2857    // Note that Flow.isFalse and Flow.isTrue only return true
2858    // for constant expressions in the sense of JLS 15.27, which
2859    // are guaranteed to have no side-effects.  More aggressive
2860    // constant propagation would require that we take care to
2861    // preserve possible side-effects in the condition expression.
2862
2863    // One common case is equality expressions involving a constant and null.
2864    // Since null is not a constant expression (because null cannot be
2865    // represented in the constant pool), equality checks involving null are
2866    // not captured by Flow.isTrue/isFalse.
2867    // Equality checks involving a constant and null, e.g.
2868    //     "" == null
2869    // are safe to simplify as no side-effects can occur.
2870
2871    private boolean isTrue(JCTree exp) {
2872        if (exp.type.isTrue())
2873            return true;
2874        Boolean b = expValue(exp);
2875        return b == null ? false : b;
2876    }
2877    private boolean isFalse(JCTree exp) {
2878        if (exp.type.isFalse())
2879            return true;
2880        Boolean b = expValue(exp);
2881        return b == null ? false : !b;
2882    }
2883    /* look for (in)equality relations involving null.
2884     * return true - if expression is always true
2885     *       false - if expression is always false
2886     *        null - if expression cannot be eliminated
2887     */
2888    private Boolean expValue(JCTree exp) {
2889        while (exp.hasTag(PARENS))
2890            exp = ((JCParens)exp).expr;
2891
2892        boolean eq;
2893        switch (exp.getTag()) {
2894        case EQ: eq = true;  break;
2895        case NE: eq = false; break;
2896        default:
2897            return null;
2898        }
2899
2900        // we have a JCBinary(EQ|NE)
2901        // check if we have two literals (constants or null)
2902        JCBinary b = (JCBinary)exp;
2903        if (b.lhs.type.hasTag(BOT)) return expValueIsNull(eq, b.rhs);
2904        if (b.rhs.type.hasTag(BOT)) return expValueIsNull(eq, b.lhs);
2905        return null;
2906    }
2907    private Boolean expValueIsNull(boolean eq, JCTree t) {
2908        if (t.type.hasTag(BOT)) return Boolean.valueOf(eq);
2909        if (t.hasTag(LITERAL))  return Boolean.valueOf(!eq);
2910        return null;
2911    }
2912
2913    /** Visitor method for conditional expressions.
2914     */
2915    @Override
2916    public void visitConditional(JCConditional tree) {
2917        JCTree cond = tree.cond = translate(tree.cond, syms.booleanType);
2918        if (isTrue(cond)) {
2919            result = convert(translate(tree.truepart, tree.type), tree.type);
2920            addPrunedInfo(cond);
2921        } else if (isFalse(cond)) {
2922            result = convert(translate(tree.falsepart, tree.type), tree.type);
2923            addPrunedInfo(cond);
2924        } else {
2925            // Condition is not a compile-time constant.
2926            tree.truepart = translate(tree.truepart, tree.type);
2927            tree.falsepart = translate(tree.falsepart, tree.type);
2928            result = tree;
2929        }
2930    }
2931//where
2932    private JCExpression convert(JCExpression tree, Type pt) {
2933        if (tree.type == pt || tree.type.hasTag(BOT))
2934            return tree;
2935        JCExpression result = make_at(tree.pos()).TypeCast(make.Type(pt), tree);
2936        result.type = (tree.type.constValue() != null) ? cfolder.coerce(tree.type, pt)
2937                                                       : pt;
2938        return result;
2939    }
2940
2941    /** Visitor method for if statements.
2942     */
2943    public void visitIf(JCIf tree) {
2944        JCTree cond = tree.cond = translate(tree.cond, syms.booleanType);
2945        if (isTrue(cond)) {
2946            result = translate(tree.thenpart);
2947            addPrunedInfo(cond);
2948        } else if (isFalse(cond)) {
2949            if (tree.elsepart != null) {
2950                result = translate(tree.elsepart);
2951            } else {
2952                result = make.Skip();
2953            }
2954            addPrunedInfo(cond);
2955        } else {
2956            // Condition is not a compile-time constant.
2957            tree.thenpart = translate(tree.thenpart);
2958            tree.elsepart = translate(tree.elsepart);
2959            result = tree;
2960        }
2961    }
2962
2963    /** Visitor method for assert statements. Translate them away.
2964     */
2965    public void visitAssert(JCAssert tree) {
2966        DiagnosticPosition detailPos = (tree.detail == null) ? tree.pos() : tree.detail.pos();
2967        tree.cond = translate(tree.cond, syms.booleanType);
2968        if (!tree.cond.type.isTrue()) {
2969            JCExpression cond = assertFlagTest(tree.pos());
2970            List<JCExpression> exnArgs = (tree.detail == null) ?
2971                List.<JCExpression>nil() : List.of(translate(tree.detail));
2972            if (!tree.cond.type.isFalse()) {
2973                cond = makeBinary
2974                    (AND,
2975                     cond,
2976                     makeUnary(NOT, tree.cond));
2977            }
2978            result =
2979                make.If(cond,
2980                        make_at(tree).
2981                           Throw(makeNewClass(syms.assertionErrorType, exnArgs)),
2982                        null);
2983        } else {
2984            result = make.Skip();
2985        }
2986    }
2987
2988    public void visitApply(JCMethodInvocation tree) {
2989        Symbol meth = TreeInfo.symbol(tree.meth);
2990        List<Type> argtypes = meth.type.getParameterTypes();
2991        if (meth.name == names.init && meth.owner == syms.enumSym)
2992            argtypes = argtypes.tail.tail;
2993        tree.args = boxArgs(argtypes, tree.args, tree.varargsElement);
2994        tree.varargsElement = null;
2995        Name methName = TreeInfo.name(tree.meth);
2996        if (meth.name==names.init) {
2997            // We are seeing a this(...) or super(...) constructor call.
2998            // If an access constructor is used, append null as a last argument.
2999            Symbol constructor = accessConstructor(tree.pos(), meth);
3000            if (constructor != meth) {
3001                tree.args = tree.args.append(makeNull());
3002                TreeInfo.setSymbol(tree.meth, constructor);
3003            }
3004
3005            // If we are calling a constructor of a local class, add
3006            // free variables after explicit constructor arguments.
3007            ClassSymbol c = (ClassSymbol)constructor.owner;
3008            if (c.isLocal()) {
3009                tree.args = tree.args.appendList(loadFreevars(tree.pos(), freevars(c)));
3010            }
3011
3012            // If we are calling a constructor of an enum class, pass
3013            // along the name and ordinal arguments
3014            if ((c.flags_field&ENUM) != 0 || c.getQualifiedName() == names.java_lang_Enum) {
3015                List<JCVariableDecl> params = currentMethodDef.params;
3016                if (currentMethodSym.owner.hasOuterInstance())
3017                    params = params.tail; // drop this$n
3018                tree.args = tree.args
3019                    .prepend(make_at(tree.pos()).Ident(params.tail.head.sym)) // ordinal
3020                    .prepend(make.Ident(params.head.sym)); // name
3021            }
3022
3023            // If we are calling a constructor of a class with an outer
3024            // instance, and the call
3025            // is qualified, pass qualifier as first argument in front of
3026            // the explicit constructor arguments. If the call
3027            // is not qualified, pass the correct outer instance as
3028            // first argument.
3029            if (c.hasOuterInstance()) {
3030                JCExpression thisArg;
3031                if (tree.meth.hasTag(SELECT)) {
3032                    thisArg = attr.
3033                        makeNullCheck(translate(((JCFieldAccess) tree.meth).selected));
3034                    tree.meth = make.Ident(constructor);
3035                    ((JCIdent) tree.meth).name = methName;
3036                } else if (c.isLocal() || methName == names._this){
3037                    // local class or this() call
3038                    thisArg = makeThis(tree.meth.pos(), c.type.getEnclosingType().tsym);
3039                } else {
3040                    // super() call of nested class - never pick 'this'
3041                    thisArg = makeOwnerThisN(tree.meth.pos(), c, false);
3042                }
3043                tree.args = tree.args.prepend(thisArg);
3044            }
3045        } else {
3046            // We are seeing a normal method invocation; translate this as usual.
3047            tree.meth = translate(tree.meth);
3048
3049            // If the translated method itself is an Apply tree, we are
3050            // seeing an access method invocation. In this case, append
3051            // the method arguments to the arguments of the access method.
3052            if (tree.meth.hasTag(APPLY)) {
3053                JCMethodInvocation app = (JCMethodInvocation)tree.meth;
3054                app.args = tree.args.prependList(app.args);
3055                result = app;
3056                return;
3057            }
3058        }
3059        result = tree;
3060    }
3061
3062    List<JCExpression> boxArgs(List<Type> parameters, List<JCExpression> _args, Type varargsElement) {
3063        List<JCExpression> args = _args;
3064        if (parameters.isEmpty()) return args;
3065        boolean anyChanges = false;
3066        ListBuffer<JCExpression> result = new ListBuffer<>();
3067        while (parameters.tail.nonEmpty()) {
3068            JCExpression arg = translate(args.head, parameters.head);
3069            anyChanges |= (arg != args.head);
3070            result.append(arg);
3071            args = args.tail;
3072            parameters = parameters.tail;
3073        }
3074        Type parameter = parameters.head;
3075        if (varargsElement != null) {
3076            anyChanges = true;
3077            ListBuffer<JCExpression> elems = new ListBuffer<>();
3078            while (args.nonEmpty()) {
3079                JCExpression arg = translate(args.head, varargsElement);
3080                elems.append(arg);
3081                args = args.tail;
3082            }
3083            JCNewArray boxedArgs = make.NewArray(make.Type(varargsElement),
3084                                               List.<JCExpression>nil(),
3085                                               elems.toList());
3086            boxedArgs.type = new ArrayType(varargsElement, syms.arrayClass);
3087            result.append(boxedArgs);
3088        } else {
3089            if (args.length() != 1) throw new AssertionError(args);
3090            JCExpression arg = translate(args.head, parameter);
3091            anyChanges |= (arg != args.head);
3092            result.append(arg);
3093            if (!anyChanges) return _args;
3094        }
3095        return result.toList();
3096    }
3097
3098    /** Expand a boxing or unboxing conversion if needed. */
3099    @SuppressWarnings("unchecked") // XXX unchecked
3100    <T extends JCExpression> T boxIfNeeded(T tree, Type type) {
3101        boolean havePrimitive = tree.type.isPrimitive();
3102        if (havePrimitive == type.isPrimitive())
3103            return tree;
3104        if (havePrimitive) {
3105            Type unboxedTarget = types.unboxedType(type);
3106            if (!unboxedTarget.hasTag(NONE)) {
3107                if (!types.isSubtype(tree.type, unboxedTarget)) //e.g. Character c = 89;
3108                    tree.type = unboxedTarget.constType(tree.type.constValue());
3109                return (T)boxPrimitive(tree, types.erasure(type));
3110            } else {
3111                tree = (T)boxPrimitive(tree);
3112            }
3113        } else {
3114            tree = (T)unbox(tree, type);
3115        }
3116        return tree;
3117    }
3118
3119    /** Box up a single primitive expression. */
3120    JCExpression boxPrimitive(JCExpression tree) {
3121        return boxPrimitive(tree, types.boxedClass(tree.type).type);
3122    }
3123
3124    /** Box up a single primitive expression. */
3125    JCExpression boxPrimitive(JCExpression tree, Type box) {
3126        make_at(tree.pos());
3127        Symbol valueOfSym = lookupMethod(tree.pos(),
3128                                         names.valueOf,
3129                                         box,
3130                                         List.<Type>nil()
3131                                         .prepend(tree.type));
3132        return make.App(make.QualIdent(valueOfSym), List.of(tree));
3133    }
3134
3135    /** Unbox an object to a primitive value. */
3136    JCExpression unbox(JCExpression tree, Type primitive) {
3137        Type unboxedType = types.unboxedType(tree.type);
3138        if (unboxedType.hasTag(NONE)) {
3139            unboxedType = primitive;
3140            if (!unboxedType.isPrimitive())
3141                throw new AssertionError(unboxedType);
3142            make_at(tree.pos());
3143            tree = make.TypeCast(types.boxedClass(unboxedType).type, tree);
3144        } else {
3145            // There must be a conversion from unboxedType to primitive.
3146            if (!types.isSubtype(unboxedType, primitive))
3147                throw new AssertionError(tree);
3148        }
3149        make_at(tree.pos());
3150        Symbol valueSym = lookupMethod(tree.pos(),
3151                                       unboxedType.tsym.name.append(names.Value), // x.intValue()
3152                                       tree.type,
3153                                       List.<Type>nil());
3154        return make.App(make.Select(tree, valueSym));
3155    }
3156
3157    /** Visitor method for parenthesized expressions.
3158     *  If the subexpression has changed, omit the parens.
3159     */
3160    public void visitParens(JCParens tree) {
3161        JCTree expr = translate(tree.expr);
3162        result = ((expr == tree.expr) ? tree : expr);
3163    }
3164
3165    public void visitIndexed(JCArrayAccess tree) {
3166        tree.indexed = translate(tree.indexed);
3167        tree.index = translate(tree.index, syms.intType);
3168        result = tree;
3169    }
3170
3171    public void visitAssign(JCAssign tree) {
3172        tree.lhs = translate(tree.lhs, tree);
3173        tree.rhs = translate(tree.rhs, tree.lhs.type);
3174
3175        // If translated left hand side is an Apply, we are
3176        // seeing an access method invocation. In this case, append
3177        // right hand side as last argument of the access method.
3178        if (tree.lhs.hasTag(APPLY)) {
3179            JCMethodInvocation app = (JCMethodInvocation)tree.lhs;
3180            app.args = List.of(tree.rhs).prependList(app.args);
3181            result = app;
3182        } else {
3183            result = tree;
3184        }
3185    }
3186
3187    public void visitAssignop(final JCAssignOp tree) {
3188        final boolean boxingReq = !tree.lhs.type.isPrimitive() &&
3189            tree.operator.type.getReturnType().isPrimitive();
3190
3191        AssignopDependencyScanner depScanner = new AssignopDependencyScanner(tree);
3192        depScanner.scan(tree.rhs);
3193
3194        if (boxingReq || depScanner.dependencyFound) {
3195            // boxing required; need to rewrite as x = (unbox typeof x)(x op y);
3196            // or if x == (typeof x)z then z = (unbox typeof x)((typeof x)z op y)
3197            // (but without recomputing x)
3198            JCTree newTree = abstractLval(tree.lhs, new TreeBuilder() {
3199                    public JCExpression build(final JCExpression lhs) {
3200                        JCTree.Tag newTag = tree.getTag().noAssignOp();
3201                        // Erasure (TransTypes) can change the type of
3202                        // tree.lhs.  However, we can still get the
3203                        // unerased type of tree.lhs as it is stored
3204                        // in tree.type in Attr.
3205                        OperatorSymbol newOperator = operators.resolveBinary(tree,
3206                                                                      newTag,
3207                                                                      tree.type,
3208                                                                      tree.rhs.type);
3209                        //Need to use the "lhs" at two places, once on the future left hand side
3210                        //and once in the future binary operator. But further processing may change
3211                        //the components of the tree in place (see visitSelect for e.g. <Class>.super.<ident>),
3212                        //so cloning the tree to avoid interference between the uses:
3213                        JCExpression expr = (JCExpression) lhs.clone();
3214                        if (expr.type != tree.type)
3215                            expr = make.TypeCast(tree.type, expr);
3216                        JCBinary opResult = make.Binary(newTag, expr, tree.rhs);
3217                        opResult.operator = newOperator;
3218                        opResult.type = newOperator.type.getReturnType();
3219                        JCExpression newRhs = boxingReq ?
3220                            make.TypeCast(types.unboxedType(tree.type), opResult) :
3221                            opResult;
3222                        return make.Assign(lhs, newRhs).setType(tree.type);
3223                    }
3224                });
3225            result = translate(newTree);
3226            return;
3227        }
3228        tree.lhs = translate(tree.lhs, tree);
3229        tree.rhs = translate(tree.rhs, tree.operator.type.getParameterTypes().tail.head);
3230
3231        // If translated left hand side is an Apply, we are
3232        // seeing an access method invocation. In this case, append
3233        // right hand side as last argument of the access method.
3234        if (tree.lhs.hasTag(APPLY)) {
3235            JCMethodInvocation app = (JCMethodInvocation)tree.lhs;
3236            // if operation is a += on strings,
3237            // make sure to convert argument to string
3238            JCExpression rhs = tree.operator.opcode == string_add
3239              ? makeString(tree.rhs)
3240              : tree.rhs;
3241            app.args = List.of(rhs).prependList(app.args);
3242            result = app;
3243        } else {
3244            result = tree;
3245        }
3246    }
3247
3248    class AssignopDependencyScanner extends TreeScanner {
3249
3250        Symbol sym;
3251        boolean dependencyFound = false;
3252
3253        AssignopDependencyScanner(JCAssignOp tree) {
3254            this.sym = TreeInfo.symbol(tree.lhs);
3255        }
3256
3257        @Override
3258        public void scan(JCTree tree) {
3259            if (tree != null && sym != null) {
3260                tree.accept(this);
3261            }
3262        }
3263
3264        @Override
3265        public void visitAssignop(JCAssignOp tree) {
3266            if (TreeInfo.symbol(tree.lhs) == sym) {
3267                dependencyFound = true;
3268                return;
3269            }
3270            super.visitAssignop(tree);
3271        }
3272
3273        @Override
3274        public void visitUnary(JCUnary tree) {
3275            if (TreeInfo.symbol(tree.arg) == sym) {
3276                dependencyFound = true;
3277                return;
3278            }
3279            super.visitUnary(tree);
3280        }
3281    }
3282
3283    /** Lower a tree of the form e++ or e-- where e is an object type */
3284    JCExpression lowerBoxedPostop(final JCUnary tree) {
3285        // translate to tmp1=lval(e); tmp2=tmp1; tmp1 OP 1; tmp2
3286        // or
3287        // translate to tmp1=lval(e); tmp2=tmp1; (typeof tree)tmp1 OP 1; tmp2
3288        // where OP is += or -=
3289        final boolean cast = TreeInfo.skipParens(tree.arg).hasTag(TYPECAST);
3290        return abstractLval(tree.arg, new TreeBuilder() {
3291                public JCExpression build(final JCExpression tmp1) {
3292                    return abstractRval(tmp1, tree.arg.type, new TreeBuilder() {
3293                            public JCExpression build(final JCExpression tmp2) {
3294                                JCTree.Tag opcode = (tree.hasTag(POSTINC))
3295                                    ? PLUS_ASG : MINUS_ASG;
3296                                //"tmp1" and "tmp2" may refer to the same instance
3297                                //(for e.g. <Class>.super.<ident>). But further processing may
3298                                //change the components of the tree in place (see visitSelect),
3299                                //so cloning the tree to avoid interference between the two uses:
3300                                JCExpression lhs = (JCExpression)tmp1.clone();
3301                                lhs = cast
3302                                    ? make.TypeCast(tree.arg.type, lhs)
3303                                    : lhs;
3304                                JCExpression update = makeAssignop(opcode,
3305                                                             lhs,
3306                                                             make.Literal(1));
3307                                return makeComma(update, tmp2);
3308                            }
3309                        });
3310                }
3311            });
3312    }
3313
3314    public void visitUnary(JCUnary tree) {
3315        boolean isUpdateOperator = tree.getTag().isIncOrDecUnaryOp();
3316        if (isUpdateOperator && !tree.arg.type.isPrimitive()) {
3317            switch(tree.getTag()) {
3318            case PREINC:            // ++ e
3319                    // translate to e += 1
3320            case PREDEC:            // -- e
3321                    // translate to e -= 1
3322                {
3323                    JCTree.Tag opcode = (tree.hasTag(PREINC))
3324                        ? PLUS_ASG : MINUS_ASG;
3325                    JCAssignOp newTree = makeAssignop(opcode,
3326                                                    tree.arg,
3327                                                    make.Literal(1));
3328                    result = translate(newTree, tree.type);
3329                    return;
3330                }
3331            case POSTINC:           // e ++
3332            case POSTDEC:           // e --
3333                {
3334                    result = translate(lowerBoxedPostop(tree), tree.type);
3335                    return;
3336                }
3337            }
3338            throw new AssertionError(tree);
3339        }
3340
3341        tree.arg = boxIfNeeded(translate(tree.arg, tree), tree.type);
3342
3343        if (tree.hasTag(NOT) && tree.arg.type.constValue() != null) {
3344            tree.type = cfolder.fold1(bool_not, tree.arg.type);
3345        }
3346
3347        // If translated left hand side is an Apply, we are
3348        // seeing an access method invocation. In this case, return
3349        // that access method invocation as result.
3350        if (isUpdateOperator && tree.arg.hasTag(APPLY)) {
3351            result = tree.arg;
3352        } else {
3353            result = tree;
3354        }
3355    }
3356
3357    public void visitBinary(JCBinary tree) {
3358        List<Type> formals = tree.operator.type.getParameterTypes();
3359        JCTree lhs = tree.lhs = translate(tree.lhs, formals.head);
3360        switch (tree.getTag()) {
3361        case OR:
3362            if (isTrue(lhs)) {
3363                result = lhs;
3364                return;
3365            }
3366            if (isFalse(lhs)) {
3367                result = translate(tree.rhs, formals.tail.head);
3368                return;
3369            }
3370            break;
3371        case AND:
3372            if (isFalse(lhs)) {
3373                result = lhs;
3374                return;
3375            }
3376            if (isTrue(lhs)) {
3377                result = translate(tree.rhs, formals.tail.head);
3378                return;
3379            }
3380            break;
3381        }
3382        tree.rhs = translate(tree.rhs, formals.tail.head);
3383        result = tree;
3384    }
3385
3386    public void visitIdent(JCIdent tree) {
3387        result = access(tree.sym, tree, enclOp, false);
3388    }
3389
3390    /** Translate away the foreach loop.  */
3391    public void visitForeachLoop(JCEnhancedForLoop tree) {
3392        if (types.elemtype(tree.expr.type) == null)
3393            visitIterableForeachLoop(tree);
3394        else
3395            visitArrayForeachLoop(tree);
3396    }
3397        // where
3398        /**
3399         * A statement of the form
3400         *
3401         * <pre>
3402         *     for ( T v : arrayexpr ) stmt;
3403         * </pre>
3404         *
3405         * (where arrayexpr is of an array type) gets translated to
3406         *
3407         * <pre>{@code
3408         *     for ( { arraytype #arr = arrayexpr;
3409         *             int #len = array.length;
3410         *             int #i = 0; };
3411         *           #i < #len; i$++ ) {
3412         *         T v = arr$[#i];
3413         *         stmt;
3414         *     }
3415         * }</pre>
3416         *
3417         * where #arr, #len, and #i are freshly named synthetic local variables.
3418         */
3419        private void visitArrayForeachLoop(JCEnhancedForLoop tree) {
3420            make_at(tree.expr.pos());
3421            VarSymbol arraycache = new VarSymbol(SYNTHETIC,
3422                                                 names.fromString("arr" + target.syntheticNameChar()),
3423                                                 tree.expr.type,
3424                                                 currentMethodSym);
3425            JCStatement arraycachedef = make.VarDef(arraycache, tree.expr);
3426            VarSymbol lencache = new VarSymbol(SYNTHETIC,
3427                                               names.fromString("len" + target.syntheticNameChar()),
3428                                               syms.intType,
3429                                               currentMethodSym);
3430            JCStatement lencachedef = make.
3431                VarDef(lencache, make.Select(make.Ident(arraycache), syms.lengthVar));
3432            VarSymbol index = new VarSymbol(SYNTHETIC,
3433                                            names.fromString("i" + target.syntheticNameChar()),
3434                                            syms.intType,
3435                                            currentMethodSym);
3436
3437            JCVariableDecl indexdef = make.VarDef(index, make.Literal(INT, 0));
3438            indexdef.init.type = indexdef.type = syms.intType.constType(0);
3439
3440            List<JCStatement> loopinit = List.of(arraycachedef, lencachedef, indexdef);
3441            JCBinary cond = makeBinary(LT, make.Ident(index), make.Ident(lencache));
3442
3443            JCExpressionStatement step = make.Exec(makeUnary(PREINC, make.Ident(index)));
3444
3445            Type elemtype = types.elemtype(tree.expr.type);
3446            JCExpression loopvarinit = make.Indexed(make.Ident(arraycache),
3447                                                    make.Ident(index)).setType(elemtype);
3448            JCVariableDecl loopvardef = (JCVariableDecl)make.VarDef(tree.var.mods,
3449                                                  tree.var.name,
3450                                                  tree.var.vartype,
3451                                                  loopvarinit).setType(tree.var.type);
3452            loopvardef.sym = tree.var.sym;
3453            JCBlock body = make.
3454                Block(0, List.of(loopvardef, tree.body));
3455
3456            result = translate(make.
3457                               ForLoop(loopinit,
3458                                       cond,
3459                                       List.of(step),
3460                                       body));
3461            patchTargets(body, tree, result);
3462        }
3463        /** Patch up break and continue targets. */
3464        private void patchTargets(JCTree body, final JCTree src, final JCTree dest) {
3465            class Patcher extends TreeScanner {
3466                public void visitBreak(JCBreak tree) {
3467                    if (tree.target == src)
3468                        tree.target = dest;
3469                }
3470                public void visitContinue(JCContinue tree) {
3471                    if (tree.target == src)
3472                        tree.target = dest;
3473                }
3474                public void visitClassDef(JCClassDecl tree) {}
3475            }
3476            new Patcher().scan(body);
3477        }
3478        /**
3479         * A statement of the form
3480         *
3481         * <pre>
3482         *     for ( T v : coll ) stmt ;
3483         * </pre>
3484         *
3485         * (where coll implements {@code Iterable<? extends T>}) gets translated to
3486         *
3487         * <pre>{@code
3488         *     for ( Iterator<? extends T> #i = coll.iterator(); #i.hasNext(); ) {
3489         *         T v = (T) #i.next();
3490         *         stmt;
3491         *     }
3492         * }</pre>
3493         *
3494         * where #i is a freshly named synthetic local variable.
3495         */
3496        private void visitIterableForeachLoop(JCEnhancedForLoop tree) {
3497            make_at(tree.expr.pos());
3498            Type iteratorTarget = syms.objectType;
3499            Type iterableType = types.asSuper(types.cvarUpperBound(tree.expr.type),
3500                                              syms.iterableType.tsym);
3501            if (iterableType.getTypeArguments().nonEmpty())
3502                iteratorTarget = types.erasure(iterableType.getTypeArguments().head);
3503            Type eType = types.skipTypeVars(tree.expr.type, false);
3504            tree.expr.type = types.erasure(eType);
3505            if (eType.isCompound())
3506                tree.expr = make.TypeCast(types.erasure(iterableType), tree.expr);
3507            Symbol iterator = lookupMethod(tree.expr.pos(),
3508                                           names.iterator,
3509                                           eType,
3510                                           List.<Type>nil());
3511            VarSymbol itvar = new VarSymbol(SYNTHETIC, names.fromString("i" + target.syntheticNameChar()),
3512                                            types.erasure(types.asSuper(iterator.type.getReturnType(), syms.iteratorType.tsym)),
3513                                            currentMethodSym);
3514
3515             JCStatement init = make.
3516                VarDef(itvar, make.App(make.Select(tree.expr, iterator)
3517                     .setType(types.erasure(iterator.type))));
3518
3519            Symbol hasNext = lookupMethod(tree.expr.pos(),
3520                                          names.hasNext,
3521                                          itvar.type,
3522                                          List.<Type>nil());
3523            JCMethodInvocation cond = make.App(make.Select(make.Ident(itvar), hasNext));
3524            Symbol next = lookupMethod(tree.expr.pos(),
3525                                       names.next,
3526                                       itvar.type,
3527                                       List.<Type>nil());
3528            JCExpression vardefinit = make.App(make.Select(make.Ident(itvar), next));
3529            if (tree.var.type.isPrimitive())
3530                vardefinit = make.TypeCast(types.cvarUpperBound(iteratorTarget), vardefinit);
3531            else
3532                vardefinit = make.TypeCast(tree.var.type, vardefinit);
3533            JCVariableDecl indexDef = (JCVariableDecl)make.VarDef(tree.var.mods,
3534                                                  tree.var.name,
3535                                                  tree.var.vartype,
3536                                                  vardefinit).setType(tree.var.type);
3537            indexDef.sym = tree.var.sym;
3538            JCBlock body = make.Block(0, List.of(indexDef, tree.body));
3539            body.endpos = TreeInfo.endPos(tree.body);
3540            result = translate(make.
3541                ForLoop(List.of(init),
3542                        cond,
3543                        List.<JCExpressionStatement>nil(),
3544                        body));
3545            patchTargets(body, tree, result);
3546        }
3547
3548    public void visitVarDef(JCVariableDecl tree) {
3549        MethodSymbol oldMethodSym = currentMethodSym;
3550        tree.mods = translate(tree.mods);
3551        tree.vartype = translate(tree.vartype);
3552        if (currentMethodSym == null) {
3553            // A class or instance field initializer.
3554            currentMethodSym =
3555                new MethodSymbol((tree.mods.flags&STATIC) | BLOCK,
3556                                 names.empty, null,
3557                                 currentClass);
3558        }
3559        if (tree.init != null) tree.init = translate(tree.init, tree.type);
3560        result = tree;
3561        currentMethodSym = oldMethodSym;
3562    }
3563
3564    public void visitBlock(JCBlock tree) {
3565        MethodSymbol oldMethodSym = currentMethodSym;
3566        if (currentMethodSym == null) {
3567            // Block is a static or instance initializer.
3568            currentMethodSym =
3569                new MethodSymbol(tree.flags | BLOCK,
3570                                 names.empty, null,
3571                                 currentClass);
3572        }
3573        super.visitBlock(tree);
3574        currentMethodSym = oldMethodSym;
3575    }
3576
3577    public void visitDoLoop(JCDoWhileLoop tree) {
3578        tree.body = translate(tree.body);
3579        tree.cond = translate(tree.cond, syms.booleanType);
3580        result = tree;
3581    }
3582
3583    public void visitWhileLoop(JCWhileLoop tree) {
3584        tree.cond = translate(tree.cond, syms.booleanType);
3585        tree.body = translate(tree.body);
3586        result = tree;
3587    }
3588
3589    public void visitForLoop(JCForLoop tree) {
3590        tree.init = translate(tree.init);
3591        if (tree.cond != null)
3592            tree.cond = translate(tree.cond, syms.booleanType);
3593        tree.step = translate(tree.step);
3594        tree.body = translate(tree.body);
3595        result = tree;
3596    }
3597
3598    public void visitReturn(JCReturn tree) {
3599        if (tree.expr != null)
3600            tree.expr = translate(tree.expr,
3601                                  types.erasure(currentMethodDef
3602                                                .restype.type));
3603        result = tree;
3604    }
3605
3606    public void visitSwitch(JCSwitch tree) {
3607        Type selsuper = types.supertype(tree.selector.type);
3608        boolean enumSwitch = selsuper != null &&
3609            (tree.selector.type.tsym.flags() & ENUM) != 0;
3610        boolean stringSwitch = selsuper != null &&
3611            types.isSameType(tree.selector.type, syms.stringType);
3612        Type target = enumSwitch ? tree.selector.type :
3613            (stringSwitch? syms.stringType : syms.intType);
3614        tree.selector = translate(tree.selector, target);
3615        tree.cases = translateCases(tree.cases);
3616        if (enumSwitch) {
3617            result = visitEnumSwitch(tree);
3618        } else if (stringSwitch) {
3619            result = visitStringSwitch(tree);
3620        } else {
3621            result = tree;
3622        }
3623    }
3624
3625    public JCTree visitEnumSwitch(JCSwitch tree) {
3626        TypeSymbol enumSym = tree.selector.type.tsym;
3627        EnumMapping map = mapForEnum(tree.pos(), enumSym);
3628        make_at(tree.pos());
3629        Symbol ordinalMethod = lookupMethod(tree.pos(),
3630                                            names.ordinal,
3631                                            tree.selector.type,
3632                                            List.<Type>nil());
3633        JCArrayAccess selector = make.Indexed(map.mapVar,
3634                                        make.App(make.Select(tree.selector,
3635                                                             ordinalMethod)));
3636        ListBuffer<JCCase> cases = new ListBuffer<>();
3637        for (JCCase c : tree.cases) {
3638            if (c.pat != null) {
3639                VarSymbol label = (VarSymbol)TreeInfo.symbol(c.pat);
3640                JCLiteral pat = map.forConstant(label);
3641                cases.append(make.Case(pat, c.stats));
3642            } else {
3643                cases.append(c);
3644            }
3645        }
3646        JCSwitch enumSwitch = make.Switch(selector, cases.toList());
3647        patchTargets(enumSwitch, tree, enumSwitch);
3648        return enumSwitch;
3649    }
3650
3651    public JCTree visitStringSwitch(JCSwitch tree) {
3652        List<JCCase> caseList = tree.getCases();
3653        int alternatives = caseList.size();
3654
3655        if (alternatives == 0) { // Strange but legal possibility
3656            return make.at(tree.pos()).Exec(attr.makeNullCheck(tree.getExpression()));
3657        } else {
3658            /*
3659             * The general approach used is to translate a single
3660             * string switch statement into a series of two chained
3661             * switch statements: the first a synthesized statement
3662             * switching on the argument string's hash value and
3663             * computing a string's position in the list of original
3664             * case labels, if any, followed by a second switch on the
3665             * computed integer value.  The second switch has the same
3666             * code structure as the original string switch statement
3667             * except that the string case labels are replaced with
3668             * positional integer constants starting at 0.
3669             *
3670             * The first switch statement can be thought of as an
3671             * inlined map from strings to their position in the case
3672             * label list.  An alternate implementation would use an
3673             * actual Map for this purpose, as done for enum switches.
3674             *
3675             * With some additional effort, it would be possible to
3676             * use a single switch statement on the hash code of the
3677             * argument, but care would need to be taken to preserve
3678             * the proper control flow in the presence of hash
3679             * collisions and other complications, such as
3680             * fallthroughs.  Switch statements with one or two
3681             * alternatives could also be specially translated into
3682             * if-then statements to omit the computation of the hash
3683             * code.
3684             *
3685             * The generated code assumes that the hashing algorithm
3686             * of String is the same in the compilation environment as
3687             * in the environment the code will run in.  The string
3688             * hashing algorithm in the SE JDK has been unchanged
3689             * since at least JDK 1.2.  Since the algorithm has been
3690             * specified since that release as well, it is very
3691             * unlikely to be changed in the future.
3692             *
3693             * Different hashing algorithms, such as the length of the
3694             * strings or a perfect hashing algorithm over the
3695             * particular set of case labels, could potentially be
3696             * used instead of String.hashCode.
3697             */
3698
3699            ListBuffer<JCStatement> stmtList = new ListBuffer<>();
3700
3701            // Map from String case labels to their original position in
3702            // the list of case labels.
3703            Map<String, Integer> caseLabelToPosition = new LinkedHashMap<>(alternatives + 1, 1.0f);
3704
3705            // Map of hash codes to the string case labels having that hashCode.
3706            Map<Integer, Set<String>> hashToString = new LinkedHashMap<>(alternatives + 1, 1.0f);
3707
3708            int casePosition = 0;
3709            for(JCCase oneCase : caseList) {
3710                JCExpression expression = oneCase.getExpression();
3711
3712                if (expression != null) { // expression for a "default" case is null
3713                    String labelExpr = (String) expression.type.constValue();
3714                    Integer mapping = caseLabelToPosition.put(labelExpr, casePosition);
3715                    Assert.checkNull(mapping);
3716                    int hashCode = labelExpr.hashCode();
3717
3718                    Set<String> stringSet = hashToString.get(hashCode);
3719                    if (stringSet == null) {
3720                        stringSet = new LinkedHashSet<>(1, 1.0f);
3721                        stringSet.add(labelExpr);
3722                        hashToString.put(hashCode, stringSet);
3723                    } else {
3724                        boolean added = stringSet.add(labelExpr);
3725                        Assert.check(added);
3726                    }
3727                }
3728                casePosition++;
3729            }
3730
3731            // Synthesize a switch statement that has the effect of
3732            // mapping from a string to the integer position of that
3733            // string in the list of case labels.  This is done by
3734            // switching on the hashCode of the string followed by an
3735            // if-then-else chain comparing the input for equality
3736            // with all the case labels having that hash value.
3737
3738            /*
3739             * s$ = top of stack;
3740             * tmp$ = -1;
3741             * switch($s.hashCode()) {
3742             *     case caseLabel.hashCode:
3743             *         if (s$.equals("caseLabel_1")
3744             *           tmp$ = caseLabelToPosition("caseLabel_1");
3745             *         else if (s$.equals("caseLabel_2"))
3746             *           tmp$ = caseLabelToPosition("caseLabel_2");
3747             *         ...
3748             *         break;
3749             * ...
3750             * }
3751             */
3752
3753            VarSymbol dollar_s = new VarSymbol(FINAL|SYNTHETIC,
3754                                               names.fromString("s" + tree.pos + target.syntheticNameChar()),
3755                                               syms.stringType,
3756                                               currentMethodSym);
3757            stmtList.append(make.at(tree.pos()).VarDef(dollar_s, tree.getExpression()).setType(dollar_s.type));
3758
3759            VarSymbol dollar_tmp = new VarSymbol(SYNTHETIC,
3760                                                 names.fromString("tmp" + tree.pos + target.syntheticNameChar()),
3761                                                 syms.intType,
3762                                                 currentMethodSym);
3763            JCVariableDecl dollar_tmp_def =
3764                (JCVariableDecl)make.VarDef(dollar_tmp, make.Literal(INT, -1)).setType(dollar_tmp.type);
3765            dollar_tmp_def.init.type = dollar_tmp.type = syms.intType;
3766            stmtList.append(dollar_tmp_def);
3767            ListBuffer<JCCase> caseBuffer = new ListBuffer<>();
3768            // hashCode will trigger nullcheck on original switch expression
3769            JCMethodInvocation hashCodeCall = makeCall(make.Ident(dollar_s),
3770                                                       names.hashCode,
3771                                                       List.<JCExpression>nil()).setType(syms.intType);
3772            JCSwitch switch1 = make.Switch(hashCodeCall,
3773                                        caseBuffer.toList());
3774            for(Map.Entry<Integer, Set<String>> entry : hashToString.entrySet()) {
3775                int hashCode = entry.getKey();
3776                Set<String> stringsWithHashCode = entry.getValue();
3777                Assert.check(stringsWithHashCode.size() >= 1);
3778
3779                JCStatement elsepart = null;
3780                for(String caseLabel : stringsWithHashCode ) {
3781                    JCMethodInvocation stringEqualsCall = makeCall(make.Ident(dollar_s),
3782                                                                   names.equals,
3783                                                                   List.<JCExpression>of(make.Literal(caseLabel)));
3784                    elsepart = make.If(stringEqualsCall,
3785                                       make.Exec(make.Assign(make.Ident(dollar_tmp),
3786                                                             make.Literal(caseLabelToPosition.get(caseLabel))).
3787                                                 setType(dollar_tmp.type)),
3788                                       elsepart);
3789                }
3790
3791                ListBuffer<JCStatement> lb = new ListBuffer<>();
3792                JCBreak breakStmt = make.Break(null);
3793                breakStmt.target = switch1;
3794                lb.append(elsepart).append(breakStmt);
3795
3796                caseBuffer.append(make.Case(make.Literal(hashCode), lb.toList()));
3797            }
3798
3799            switch1.cases = caseBuffer.toList();
3800            stmtList.append(switch1);
3801
3802            // Make isomorphic switch tree replacing string labels
3803            // with corresponding integer ones from the label to
3804            // position map.
3805
3806            ListBuffer<JCCase> lb = new ListBuffer<>();
3807            JCSwitch switch2 = make.Switch(make.Ident(dollar_tmp), lb.toList());
3808            for(JCCase oneCase : caseList ) {
3809                // Rewire up old unlabeled break statements to the
3810                // replacement switch being created.
3811                patchTargets(oneCase, tree, switch2);
3812
3813                boolean isDefault = (oneCase.getExpression() == null);
3814                JCExpression caseExpr;
3815                if (isDefault)
3816                    caseExpr = null;
3817                else {
3818                    caseExpr = make.Literal(caseLabelToPosition.get((String)TreeInfo.skipParens(oneCase.
3819                                                                                                getExpression()).
3820                                                                    type.constValue()));
3821                }
3822
3823                lb.append(make.Case(caseExpr,
3824                                    oneCase.getStatements()));
3825            }
3826
3827            switch2.cases = lb.toList();
3828            stmtList.append(switch2);
3829
3830            return make.Block(0L, stmtList.toList());
3831        }
3832    }
3833
3834    public void visitNewArray(JCNewArray tree) {
3835        tree.elemtype = translate(tree.elemtype);
3836        for (List<JCExpression> t = tree.dims; t.tail != null; t = t.tail)
3837            if (t.head != null) t.head = translate(t.head, syms.intType);
3838        tree.elems = translate(tree.elems, types.elemtype(tree.type));
3839        result = tree;
3840    }
3841
3842    public void visitSelect(JCFieldAccess tree) {
3843        // need to special case-access of the form C.super.x
3844        // these will always need an access method, unless C
3845        // is a default interface subclassed by the current class.
3846        boolean qualifiedSuperAccess =
3847            tree.selected.hasTag(SELECT) &&
3848            TreeInfo.name(tree.selected) == names._super &&
3849            !types.isDirectSuperInterface(((JCFieldAccess)tree.selected).selected.type.tsym, currentClass);
3850        tree.selected = translate(tree.selected);
3851        if (tree.name == names._class) {
3852            result = classOf(tree.selected);
3853        }
3854        else if (tree.name == names._super &&
3855                types.isDirectSuperInterface(tree.selected.type.tsym, currentClass)) {
3856            //default super call!! Not a classic qualified super call
3857            TypeSymbol supSym = tree.selected.type.tsym;
3858            Assert.checkNonNull(types.asSuper(currentClass.type, supSym));
3859            result = tree;
3860        }
3861        else if (tree.name == names._this || tree.name == names._super) {
3862            result = makeThis(tree.pos(), tree.selected.type.tsym);
3863        }
3864        else
3865            result = access(tree.sym, tree, enclOp, qualifiedSuperAccess);
3866    }
3867
3868    public void visitLetExpr(LetExpr tree) {
3869        tree.defs = translateVarDefs(tree.defs);
3870        tree.expr = translate(tree.expr, tree.type);
3871        result = tree;
3872    }
3873
3874    // There ought to be nothing to rewrite here;
3875    // we don't generate code.
3876    public void visitAnnotation(JCAnnotation tree) {
3877        result = tree;
3878    }
3879
3880    @Override
3881    public void visitTry(JCTry tree) {
3882        if (tree.resources.nonEmpty()) {
3883            result = makeTwrTry(tree);
3884            return;
3885        }
3886
3887        boolean hasBody = tree.body.getStatements().nonEmpty();
3888        boolean hasCatchers = tree.catchers.nonEmpty();
3889        boolean hasFinally = tree.finalizer != null &&
3890                tree.finalizer.getStatements().nonEmpty();
3891
3892        if (!hasCatchers && !hasFinally) {
3893            result = translate(tree.body);
3894            return;
3895        }
3896
3897        if (!hasBody) {
3898            if (hasFinally) {
3899                result = translate(tree.finalizer);
3900            } else {
3901                result = translate(tree.body);
3902            }
3903            return;
3904        }
3905
3906        // no optimizations possible
3907        super.visitTry(tree);
3908    }
3909
3910/**************************************************************************
3911 * main method
3912 *************************************************************************/
3913
3914    /** Translate a toplevel class and return a list consisting of
3915     *  the translated class and translated versions of all inner classes.
3916     *  @param env   The attribution environment current at the class definition.
3917     *               We need this for resolving some additional symbols.
3918     *  @param cdef  The tree representing the class definition.
3919     */
3920    public List<JCTree> translateTopLevelClass(Env<AttrContext> env, JCTree cdef, TreeMaker make) {
3921        ListBuffer<JCTree> translated = null;
3922        try {
3923            attrEnv = env;
3924            this.make = make;
3925            endPosTable = env.toplevel.endPositions;
3926            currentClass = null;
3927            currentMethodDef = null;
3928            outermostClassDef = (cdef.hasTag(CLASSDEF)) ? (JCClassDecl)cdef : null;
3929            outermostMemberDef = null;
3930            this.translated = new ListBuffer<>();
3931            classdefs = new HashMap<>();
3932            actualSymbols = new HashMap<>();
3933            freevarCache = new HashMap<>();
3934            proxies = WriteableScope.create(syms.noSymbol);
3935            twrVars = WriteableScope.create(syms.noSymbol);
3936            outerThisStack = List.nil();
3937            accessNums = new HashMap<>();
3938            accessSyms = new HashMap<>();
3939            accessConstrs = new HashMap<>();
3940            accessConstrTags = List.nil();
3941            accessed = new ListBuffer<>();
3942            translate(cdef, (JCExpression)null);
3943            for (List<Symbol> l = accessed.toList(); l.nonEmpty(); l = l.tail)
3944                makeAccessible(l.head);
3945            for (EnumMapping map : enumSwitchMap.values())
3946                map.translate();
3947            checkConflicts(this.translated.toList());
3948            checkAccessConstructorTags();
3949            translated = this.translated;
3950        } finally {
3951            // note that recursive invocations of this method fail hard
3952            attrEnv = null;
3953            this.make = null;
3954            endPosTable = null;
3955            currentClass = null;
3956            currentMethodDef = null;
3957            outermostClassDef = null;
3958            outermostMemberDef = null;
3959            this.translated = null;
3960            classdefs = null;
3961            actualSymbols = null;
3962            freevarCache = null;
3963            proxies = null;
3964            outerThisStack = null;
3965            accessNums = null;
3966            accessSyms = null;
3967            accessConstrs = null;
3968            accessConstrTags = null;
3969            accessed = null;
3970            enumSwitchMap.clear();
3971            assertionsDisabledClassCache = null;
3972        }
3973        return translated.toList();
3974    }
3975}
3976