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