Attr.java revision 2853:03939be983dd
1/*
2 * Copyright (c) 1999, 2015, 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 javax.lang.model.element.ElementKind;
31import javax.tools.JavaFileObject;
32
33import com.sun.source.tree.IdentifierTree;
34import com.sun.source.tree.MemberReferenceTree.ReferenceMode;
35import com.sun.source.tree.MemberSelectTree;
36import com.sun.source.tree.TreeVisitor;
37import com.sun.source.util.SimpleTreeVisitor;
38import com.sun.tools.javac.code.*;
39import com.sun.tools.javac.code.Lint.LintCategory;
40import com.sun.tools.javac.code.Scope.WriteableScope;
41import com.sun.tools.javac.code.Symbol.*;
42import com.sun.tools.javac.code.Type.*;
43import com.sun.tools.javac.comp.Check.CheckContext;
44import com.sun.tools.javac.comp.DeferredAttr.AttrMode;
45import com.sun.tools.javac.comp.Infer.InferenceContext;
46import com.sun.tools.javac.comp.Infer.FreeTypeListener;
47import com.sun.tools.javac.jvm.*;
48import com.sun.tools.javac.tree.*;
49import com.sun.tools.javac.tree.JCTree.*;
50import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*;
51import com.sun.tools.javac.util.*;
52import com.sun.tools.javac.util.DefinedBy.Api;
53import com.sun.tools.javac.util.Dependencies.AttributionKind;
54import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
55import com.sun.tools.javac.util.List;
56import static com.sun.tools.javac.code.Flags.*;
57import static com.sun.tools.javac.code.Flags.ANNOTATION;
58import static com.sun.tools.javac.code.Flags.BLOCK;
59import static com.sun.tools.javac.code.Kinds.*;
60import static com.sun.tools.javac.code.Kinds.Kind.*;
61import static com.sun.tools.javac.code.TypeTag.*;
62import static com.sun.tools.javac.code.TypeTag.WILDCARD;
63import static com.sun.tools.javac.tree.JCTree.Tag.*;
64
65/** This is the main context-dependent analysis phase in GJC. It
66 *  encompasses name resolution, type checking and constant folding as
67 *  subtasks. Some subtasks involve auxiliary classes.
68 *  @see Check
69 *  @see Resolve
70 *  @see ConstFold
71 *  @see Infer
72 *
73 *  <p><b>This is NOT part of any supported API.
74 *  If you write code that depends on this, you do so at your own risk.
75 *  This code and its internal interfaces are subject to change or
76 *  deletion without notice.</b>
77 */
78public class Attr extends JCTree.Visitor {
79    protected static final Context.Key<Attr> attrKey = new Context.Key<>();
80
81    final Names names;
82    final Log log;
83    final Symtab syms;
84    final Resolve rs;
85    final Operators operators;
86    final Infer infer;
87    final Analyzer analyzer;
88    final DeferredAttr deferredAttr;
89    final Check chk;
90    final Flow flow;
91    final MemberEnter memberEnter;
92    final TypeEnter typeEnter;
93    final TreeMaker make;
94    final ConstFold cfolder;
95    final Enter enter;
96    final Target target;
97    final Types types;
98    final JCDiagnostic.Factory diags;
99    final Annotate annotate;
100    final TypeAnnotations typeAnnotations;
101    final DeferredLintHandler deferredLintHandler;
102    final TypeEnvs typeEnvs;
103    final Dependencies dependencies;
104
105    public static Attr instance(Context context) {
106        Attr instance = context.get(attrKey);
107        if (instance == null)
108            instance = new Attr(context);
109        return instance;
110    }
111
112    protected Attr(Context context) {
113        context.put(attrKey, this);
114
115        names = Names.instance(context);
116        log = Log.instance(context);
117        syms = Symtab.instance(context);
118        rs = Resolve.instance(context);
119        operators = Operators.instance(context);
120        chk = Check.instance(context);
121        flow = Flow.instance(context);
122        memberEnter = MemberEnter.instance(context);
123        typeEnter = TypeEnter.instance(context);
124        make = TreeMaker.instance(context);
125        enter = Enter.instance(context);
126        infer = Infer.instance(context);
127        analyzer = Analyzer.instance(context);
128        deferredAttr = DeferredAttr.instance(context);
129        cfolder = ConstFold.instance(context);
130        target = Target.instance(context);
131        types = Types.instance(context);
132        diags = JCDiagnostic.Factory.instance(context);
133        annotate = Annotate.instance(context);
134        typeAnnotations = TypeAnnotations.instance(context);
135        deferredLintHandler = DeferredLintHandler.instance(context);
136        typeEnvs = TypeEnvs.instance(context);
137        dependencies = Dependencies.instance(context);
138
139        Options options = Options.instance(context);
140
141        Source source = Source.instance(context);
142        allowStringsInSwitch = source.allowStringsInSwitch();
143        allowPoly = source.allowPoly();
144        allowTypeAnnos = source.allowTypeAnnotations();
145        allowLambda = source.allowLambda();
146        allowDefaultMethods = source.allowDefaultMethods();
147        allowStaticInterfaceMethods = source.allowStaticInterfaceMethods();
148        sourceName = source.name;
149        relax = (options.isSet("-retrofit") ||
150                options.isSet("-relax"));
151        useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
152
153        statInfo = new ResultInfo(KindSelector.NIL, Type.noType);
154        varAssignmentInfo = new ResultInfo(KindSelector.ASG, Type.noType);
155        unknownExprInfo = new ResultInfo(KindSelector.VAL, Type.noType);
156        unknownAnyPolyInfo = new ResultInfo(KindSelector.VAL, Infer.anyPoly);
157        unknownTypeInfo = new ResultInfo(KindSelector.TYP, Type.noType);
158        unknownTypeExprInfo = new ResultInfo(KindSelector.VAL_TYP, Type.noType);
159        recoveryInfo = new RecoveryInfo(deferredAttr.emptyDeferredAttrContext);
160
161        noCheckTree = make.at(-1).Skip();
162    }
163
164    /** Switch: relax some constraints for retrofit mode.
165     */
166    boolean relax;
167
168    /** Switch: support target-typing inference
169     */
170    boolean allowPoly;
171
172    /** Switch: support type annotations.
173     */
174    boolean allowTypeAnnos;
175
176    /** Switch: support lambda expressions ?
177     */
178    boolean allowLambda;
179
180    /** Switch: support default methods ?
181     */
182    boolean allowDefaultMethods;
183
184    /** Switch: static interface methods enabled?
185     */
186    boolean allowStaticInterfaceMethods;
187
188    /**
189     * Switch: warn about use of variable before declaration?
190     * RFE: 6425594
191     */
192    boolean useBeforeDeclarationWarning;
193
194    /**
195     * Switch: allow strings in switch?
196     */
197    boolean allowStringsInSwitch;
198
199    /**
200     * Switch: name of source level; used for error reporting.
201     */
202    String sourceName;
203
204    /** Check kind and type of given tree against protokind and prototype.
205     *  If check succeeds, store type in tree and return it.
206     *  If check fails, store errType in tree and return it.
207     *  No checks are performed if the prototype is a method type.
208     *  It is not necessary in this case since we know that kind and type
209     *  are correct.
210     *
211     *  @param tree     The tree whose kind and type is checked
212     *  @param found    The computed type of the tree
213     *  @param ownkind  The computed kind of the tree
214     *  @param resultInfo  The expected result of the tree
215     */
216    Type check(final JCTree tree,
217               final Type found,
218               final KindSelector ownkind,
219               final ResultInfo resultInfo) {
220        InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
221        Type owntype;
222        boolean shouldCheck = !found.hasTag(ERROR) &&
223                !resultInfo.pt.hasTag(METHOD) &&
224                !resultInfo.pt.hasTag(FORALL);
225        if (shouldCheck && !ownkind.subset(resultInfo.pkind)) {
226            log.error(tree.pos(), "unexpected.type",
227            resultInfo.pkind.kindNames(),
228            ownkind.kindNames());
229            owntype = types.createErrorType(found);
230        } else if (allowPoly && inferenceContext.free(found)) {
231            //delay the check if there are inference variables in the found type
232            //this means we are dealing with a partially inferred poly expression
233            owntype = shouldCheck ? resultInfo.pt : found;
234            inferenceContext.addFreeTypeListener(List.of(found, resultInfo.pt),
235                    instantiatedContext -> {
236                        ResultInfo pendingResult =
237                                resultInfo.dup(inferenceContext.asInstType(resultInfo.pt));
238                        check(tree, inferenceContext.asInstType(found), ownkind, pendingResult);
239                    });
240        } else {
241            owntype = shouldCheck ?
242            resultInfo.check(tree, found) :
243            found;
244        }
245        if (tree != noCheckTree) {
246            tree.type = owntype;
247        }
248        return owntype;
249    }
250
251    /** Is given blank final variable assignable, i.e. in a scope where it
252     *  may be assigned to even though it is final?
253     *  @param v      The blank final variable.
254     *  @param env    The current environment.
255     */
256    boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
257        Symbol owner = env.info.scope.owner;
258           // owner refers to the innermost variable, method or
259           // initializer block declaration at this point.
260        return
261            v.owner == owner
262            ||
263            ((owner.name == names.init ||    // i.e. we are in a constructor
264              owner.kind == VAR ||           // i.e. we are in a variable initializer
265              (owner.flags() & BLOCK) != 0)  // i.e. we are in an initializer block
266             &&
267             v.owner == owner.owner
268             &&
269             ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
270    }
271
272    /** Check that variable can be assigned to.
273     *  @param pos    The current source code position.
274     *  @param v      The assigned varaible
275     *  @param base   If the variable is referred to in a Select, the part
276     *                to the left of the `.', null otherwise.
277     *  @param env    The current environment.
278     */
279    void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
280        if ((v.flags() & FINAL) != 0 &&
281            ((v.flags() & HASINIT) != 0
282             ||
283             !((base == null ||
284               (base.hasTag(IDENT) && TreeInfo.name(base) == names._this)) &&
285               isAssignableAsBlankFinal(v, env)))) {
286            if (v.isResourceVariable()) { //TWR resource
287                log.error(pos, "try.resource.may.not.be.assigned", v);
288            } else {
289                log.error(pos, "cant.assign.val.to.final.var", v);
290            }
291        }
292    }
293
294    /** Does tree represent a static reference to an identifier?
295     *  It is assumed that tree is either a SELECT or an IDENT.
296     *  We have to weed out selects from non-type names here.
297     *  @param tree    The candidate tree.
298     */
299    boolean isStaticReference(JCTree tree) {
300        if (tree.hasTag(SELECT)) {
301            Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
302            if (lsym == null || lsym.kind != TYP) {
303                return false;
304            }
305        }
306        return true;
307    }
308
309    /** Is this symbol a type?
310     */
311    static boolean isType(Symbol sym) {
312        return sym != null && sym.kind == TYP;
313    }
314
315    /** The current `this' symbol.
316     *  @param env    The current environment.
317     */
318    Symbol thisSym(DiagnosticPosition pos, Env<AttrContext> env) {
319        return rs.resolveSelf(pos, env, env.enclClass.sym, names._this);
320    }
321
322    /** Attribute a parsed identifier.
323     * @param tree Parsed identifier name
324     * @param topLevel The toplevel to use
325     */
326    public Symbol attribIdent(JCTree tree, JCCompilationUnit topLevel) {
327        Env<AttrContext> localEnv = enter.topLevelEnv(topLevel);
328        localEnv.enclClass = make.ClassDef(make.Modifiers(0),
329                                           syms.errSymbol.name,
330                                           null, null, null, null);
331        localEnv.enclClass.sym = syms.errSymbol;
332        return tree.accept(identAttributer, localEnv);
333    }
334    // where
335        private TreeVisitor<Symbol,Env<AttrContext>> identAttributer = new IdentAttributer();
336        private class IdentAttributer extends SimpleTreeVisitor<Symbol,Env<AttrContext>> {
337            @Override @DefinedBy(Api.COMPILER_TREE)
338            public Symbol visitMemberSelect(MemberSelectTree node, Env<AttrContext> env) {
339                Symbol site = visit(node.getExpression(), env);
340                if (site.kind == ERR || site.kind == ABSENT_TYP)
341                    return site;
342                Name name = (Name)node.getIdentifier();
343                if (site.kind == PCK) {
344                    env.toplevel.packge = (PackageSymbol)site;
345                    return rs.findIdentInPackage(env, (TypeSymbol)site, name,
346                            KindSelector.TYP_PCK);
347                } else {
348                    env.enclClass.sym = (ClassSymbol)site;
349                    return rs.findMemberType(env, site.asType(), name, (TypeSymbol)site);
350                }
351            }
352
353            @Override @DefinedBy(Api.COMPILER_TREE)
354            public Symbol visitIdentifier(IdentifierTree node, Env<AttrContext> env) {
355                return rs.findIdent(env, (Name)node.getName(), KindSelector.TYP_PCK);
356            }
357        }
358
359    public Type coerce(Type etype, Type ttype) {
360        return cfolder.coerce(etype, ttype);
361    }
362
363    public Type attribType(JCTree node, TypeSymbol sym) {
364        Env<AttrContext> env = typeEnvs.get(sym);
365        Env<AttrContext> localEnv = env.dup(node, env.info.dup());
366        return attribTree(node, localEnv, unknownTypeInfo);
367    }
368
369    public Type attribImportQualifier(JCImport tree, Env<AttrContext> env) {
370        // Attribute qualifying package or class.
371        JCFieldAccess s = (JCFieldAccess)tree.qualid;
372        return attribTree(s.selected, env,
373                          new ResultInfo(tree.staticImport ?
374                                         KindSelector.TYP : KindSelector.TYP_PCK,
375                       Type.noType));
376    }
377
378    public Env<AttrContext> attribExprToTree(JCTree expr, Env<AttrContext> env, JCTree tree) {
379        breakTree = tree;
380        JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
381        try {
382            attribExpr(expr, env);
383        } catch (BreakAttr b) {
384            return b.env;
385        } catch (AssertionError ae) {
386            if (ae.getCause() instanceof BreakAttr) {
387                return ((BreakAttr)(ae.getCause())).env;
388            } else {
389                throw ae;
390            }
391        } finally {
392            breakTree = null;
393            log.useSource(prev);
394        }
395        return env;
396    }
397
398    public Env<AttrContext> attribStatToTree(JCTree stmt, Env<AttrContext> env, JCTree tree) {
399        breakTree = tree;
400        JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
401        try {
402            attribStat(stmt, env);
403        } catch (BreakAttr b) {
404            return b.env;
405        } catch (AssertionError ae) {
406            if (ae.getCause() instanceof BreakAttr) {
407                return ((BreakAttr)(ae.getCause())).env;
408            } else {
409                throw ae;
410            }
411        } finally {
412            breakTree = null;
413            log.useSource(prev);
414        }
415        return env;
416    }
417
418    private JCTree breakTree = null;
419
420    private static class BreakAttr extends RuntimeException {
421        static final long serialVersionUID = -6924771130405446405L;
422        private Env<AttrContext> env;
423        private BreakAttr(Env<AttrContext> env) {
424            this.env = env;
425        }
426    }
427
428    class ResultInfo {
429        final KindSelector pkind;
430        final Type pt;
431        final CheckContext checkContext;
432
433        ResultInfo(KindSelector pkind, Type pt) {
434            this(pkind, pt, chk.basicHandler);
435        }
436
437        protected ResultInfo(KindSelector pkind,
438                             Type pt, CheckContext checkContext) {
439            this.pkind = pkind;
440            this.pt = pt;
441            this.checkContext = checkContext;
442        }
443
444        protected Type check(final DiagnosticPosition pos, final Type found) {
445            return chk.checkType(pos, found, pt, checkContext);
446        }
447
448        protected ResultInfo dup(Type newPt) {
449            return new ResultInfo(pkind, newPt, checkContext);
450        }
451
452        protected ResultInfo dup(CheckContext newContext) {
453            return new ResultInfo(pkind, pt, newContext);
454        }
455
456        protected ResultInfo dup(Type newPt, CheckContext newContext) {
457            return new ResultInfo(pkind, newPt, newContext);
458        }
459
460        @Override
461        public String toString() {
462            if (pt != null) {
463                return pt.toString();
464            } else {
465                return "";
466            }
467        }
468    }
469
470    class RecoveryInfo extends ResultInfo {
471
472        public RecoveryInfo(final DeferredAttr.DeferredAttrContext deferredAttrContext) {
473            super(KindSelector.VAL, Type.recoveryType,
474                  new Check.NestedCheckContext(chk.basicHandler) {
475                @Override
476                public DeferredAttr.DeferredAttrContext deferredAttrContext() {
477                    return deferredAttrContext;
478                }
479                @Override
480                public boolean compatible(Type found, Type req, Warner warn) {
481                    return true;
482                }
483                @Override
484                public void report(DiagnosticPosition pos, JCDiagnostic details) {
485                    chk.basicHandler.report(pos, details);
486                }
487            });
488        }
489    }
490
491    final ResultInfo statInfo;
492    final ResultInfo varAssignmentInfo;
493    final ResultInfo unknownAnyPolyInfo;
494    final ResultInfo unknownExprInfo;
495    final ResultInfo unknownTypeInfo;
496    final ResultInfo unknownTypeExprInfo;
497    final ResultInfo recoveryInfo;
498
499    Type pt() {
500        return resultInfo.pt;
501    }
502
503    KindSelector pkind() {
504        return resultInfo.pkind;
505    }
506
507/* ************************************************************************
508 * Visitor methods
509 *************************************************************************/
510
511    /** Visitor argument: the current environment.
512     */
513    Env<AttrContext> env;
514
515    /** Visitor argument: the currently expected attribution result.
516     */
517    ResultInfo resultInfo;
518
519    /** Visitor result: the computed type.
520     */
521    Type result;
522
523    /** Synthetic tree to be used during 'fake' checks.
524     */
525    JCTree noCheckTree;
526
527    /** Visitor method: attribute a tree, catching any completion failure
528     *  exceptions. Return the tree's type.
529     *
530     *  @param tree    The tree to be visited.
531     *  @param env     The environment visitor argument.
532     *  @param resultInfo   The result info visitor argument.
533     */
534    Type attribTree(JCTree tree, Env<AttrContext> env, ResultInfo resultInfo) {
535        Env<AttrContext> prevEnv = this.env;
536        ResultInfo prevResult = this.resultInfo;
537        try {
538            this.env = env;
539            this.resultInfo = resultInfo;
540            tree.accept(this);
541            if (tree == breakTree &&
542                    resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
543                throw new BreakAttr(copyEnv(env));
544            }
545            return result;
546        } catch (CompletionFailure ex) {
547            tree.type = syms.errType;
548            return chk.completionError(tree.pos(), ex);
549        } finally {
550            this.env = prevEnv;
551            this.resultInfo = prevResult;
552        }
553    }
554
555    Env<AttrContext> copyEnv(Env<AttrContext> env) {
556        Env<AttrContext> newEnv =
557                env.dup(env.tree, env.info.dup(copyScope(env.info.scope)));
558        if (newEnv.outer != null) {
559            newEnv.outer = copyEnv(newEnv.outer);
560        }
561        return newEnv;
562    }
563
564    WriteableScope copyScope(WriteableScope sc) {
565        WriteableScope newScope = WriteableScope.create(sc.owner);
566        List<Symbol> elemsList = List.nil();
567        for (Symbol sym : sc.getSymbols()) {
568            elemsList = elemsList.prepend(sym);
569        }
570        for (Symbol s : elemsList) {
571            newScope.enter(s);
572        }
573        return newScope;
574    }
575
576    /** Derived visitor method: attribute an expression tree.
577     */
578    public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) {
579        return attribTree(tree, env, new ResultInfo(KindSelector.VAL, !pt.hasTag(ERROR) ? pt : Type.noType));
580    }
581
582    /** Derived visitor method: attribute an expression tree with
583     *  no constraints on the computed type.
584     */
585    public Type attribExpr(JCTree tree, Env<AttrContext> env) {
586        return attribTree(tree, env, unknownExprInfo);
587    }
588
589    /** Derived visitor method: attribute a type tree.
590     */
591    public Type attribType(JCTree tree, Env<AttrContext> env) {
592        Type result = attribType(tree, env, Type.noType);
593        return result;
594    }
595
596    /** Derived visitor method: attribute a type tree.
597     */
598    Type attribType(JCTree tree, Env<AttrContext> env, Type pt) {
599        Type result = attribTree(tree, env, new ResultInfo(KindSelector.TYP, pt));
600        return result;
601    }
602
603    /** Derived visitor method: attribute a statement or definition tree.
604     */
605    public Type attribStat(JCTree tree, Env<AttrContext> env) {
606        Env<AttrContext> analyzeEnv =
607                env.dup(tree, env.info.dup(env.info.scope.dupUnshared(env.info.scope.owner)));
608        try {
609            return attribTree(tree, env, statInfo);
610        } finally {
611            analyzer.analyzeIfNeeded(tree, analyzeEnv);
612        }
613    }
614
615    /** Attribute a list of expressions, returning a list of types.
616     */
617    List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) {
618        ListBuffer<Type> ts = new ListBuffer<>();
619        for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
620            ts.append(attribExpr(l.head, env, pt));
621        return ts.toList();
622    }
623
624    /** Attribute a list of statements, returning nothing.
625     */
626    <T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) {
627        for (List<T> l = trees; l.nonEmpty(); l = l.tail)
628            attribStat(l.head, env);
629    }
630
631    /** Attribute the arguments in a method call, returning the method kind.
632     */
633    KindSelector attribArgs(KindSelector initialKind, List<JCExpression> trees, Env<AttrContext> env, ListBuffer<Type> argtypes) {
634        KindSelector kind = initialKind;
635        for (JCExpression arg : trees) {
636            Type argtype;
637            if (allowPoly && deferredAttr.isDeferred(env, arg)) {
638                argtype = deferredAttr.new DeferredType(arg, env);
639                kind = KindSelector.of(KindSelector.POLY, kind);
640            } else {
641                argtype = chk.checkNonVoid(arg, attribTree(arg, env, unknownAnyPolyInfo));
642            }
643            argtypes.append(argtype);
644        }
645        return kind;
646    }
647
648    /** Attribute a type argument list, returning a list of types.
649     *  Caller is responsible for calling checkRefTypes.
650     */
651    List<Type> attribAnyTypes(List<JCExpression> trees, Env<AttrContext> env) {
652        ListBuffer<Type> argtypes = new ListBuffer<>();
653        for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
654            argtypes.append(attribType(l.head, env));
655        return argtypes.toList();
656    }
657
658    /** Attribute a type argument list, returning a list of types.
659     *  Check that all the types are references.
660     */
661    List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
662        List<Type> types = attribAnyTypes(trees, env);
663        return chk.checkRefTypes(trees, types);
664    }
665
666    /**
667     * Attribute type variables (of generic classes or methods).
668     * Compound types are attributed later in attribBounds.
669     * @param typarams the type variables to enter
670     * @param env      the current environment
671     */
672    void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env) {
673        for (JCTypeParameter tvar : typarams) {
674            dependencies.push(AttributionKind.TVAR, tvar);
675            TypeVar a = (TypeVar)tvar.type;
676            a.tsym.flags_field |= UNATTRIBUTED;
677            a.bound = Type.noType;
678            if (!tvar.bounds.isEmpty()) {
679                List<Type> bounds = List.of(attribType(tvar.bounds.head, env));
680                for (JCExpression bound : tvar.bounds.tail)
681                    bounds = bounds.prepend(attribType(bound, env));
682                types.setBounds(a, bounds.reverse());
683            } else {
684                // if no bounds are given, assume a single bound of
685                // java.lang.Object.
686                types.setBounds(a, List.of(syms.objectType));
687            }
688            a.tsym.flags_field &= ~UNATTRIBUTED;
689            dependencies.pop();
690        }
691        for (JCTypeParameter tvar : typarams) {
692            chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
693        }
694    }
695
696    /**
697     * Attribute the type references in a list of annotations.
698     */
699    void attribAnnotationTypes(List<JCAnnotation> annotations,
700                               Env<AttrContext> env) {
701        for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
702            JCAnnotation a = al.head;
703            attribType(a.annotationType, env);
704        }
705    }
706
707    /**
708     * Attribute a "lazy constant value".
709     *  @param env         The env for the const value
710     *  @param initializer The initializer for the const value
711     *  @param type        The expected type, or null
712     *  @see VarSymbol#setLazyConstValue
713     */
714    public Object attribLazyConstantValue(Env<AttrContext> env,
715                                      JCVariableDecl variable,
716                                      Type type) {
717
718        DiagnosticPosition prevLintPos
719                = deferredLintHandler.setPos(variable.pos());
720
721        try {
722            Type itype = attribExpr(variable.init, env, type);
723            if (itype.constValue() != null) {
724                return coerce(itype, type).constValue();
725            } else {
726                return null;
727            }
728        } finally {
729            deferredLintHandler.setPos(prevLintPos);
730        }
731    }
732
733    /** Attribute type reference in an `extends' or `implements' clause.
734     *  Supertypes of anonymous inner classes are usually already attributed.
735     *
736     *  @param tree              The tree making up the type reference.
737     *  @param env               The environment current at the reference.
738     *  @param classExpected     true if only a class is expected here.
739     *  @param interfaceExpected true if only an interface is expected here.
740     */
741    Type attribBase(JCTree tree,
742                    Env<AttrContext> env,
743                    boolean classExpected,
744                    boolean interfaceExpected,
745                    boolean checkExtensible) {
746        Type t = tree.type != null ?
747            tree.type :
748            attribType(tree, env);
749        return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible);
750    }
751    Type checkBase(Type t,
752                   JCTree tree,
753                   Env<AttrContext> env,
754                   boolean classExpected,
755                   boolean interfaceExpected,
756                   boolean checkExtensible) {
757        if (t.tsym.isAnonymous()) {
758            log.error(tree.pos(), "cant.inherit.from.anon");
759            return types.createErrorType(t);
760        }
761        if (t.isErroneous())
762            return t;
763        if (t.hasTag(TYPEVAR) && !classExpected && !interfaceExpected) {
764            // check that type variable is already visible
765            if (t.getUpperBound() == null) {
766                log.error(tree.pos(), "illegal.forward.ref");
767                return types.createErrorType(t);
768            }
769        } else {
770            t = chk.checkClassType(tree.pos(), t, checkExtensible);
771        }
772        if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) {
773            log.error(tree.pos(), "intf.expected.here");
774            // return errType is necessary since otherwise there might
775            // be undetected cycles which cause attribution to loop
776            return types.createErrorType(t);
777        } else if (checkExtensible &&
778                   classExpected &&
779                   (t.tsym.flags() & INTERFACE) != 0) {
780            log.error(tree.pos(), "no.intf.expected.here");
781            return types.createErrorType(t);
782        }
783        if (checkExtensible &&
784            ((t.tsym.flags() & FINAL) != 0)) {
785            log.error(tree.pos(),
786                      "cant.inherit.from.final", t.tsym);
787        }
788        chk.checkNonCyclic(tree.pos(), t);
789        return t;
790    }
791
792    Type attribIdentAsEnumType(Env<AttrContext> env, JCIdent id) {
793        Assert.check((env.enclClass.sym.flags() & ENUM) != 0);
794        id.type = env.info.scope.owner.enclClass().type;
795        id.sym = env.info.scope.owner.enclClass();
796        return id.type;
797    }
798
799    public void visitClassDef(JCClassDecl tree) {
800        // Local and anonymous classes have not been entered yet, so we need to
801        // do it now.
802        if (env.info.scope.owner.kind.matches(KindSelector.VAL_MTH)) {
803            enter.classEnter(tree, env);
804        } else {
805            // If this class declaration is part of a class level annotation,
806            // as in @MyAnno(new Object() {}) class MyClass {}, enter it in
807            // order to simplify later steps and allow for sensible error
808            // messages.
809            if (env.tree.hasTag(NEWCLASS) && TreeInfo.isInAnnotation(env, tree))
810                enter.classEnter(tree, env);
811        }
812
813        ClassSymbol c = tree.sym;
814        if (c == null) {
815            // exit in case something drastic went wrong during enter.
816            result = null;
817        } else {
818            // make sure class has been completed:
819            c.complete();
820
821            // If this class appears as an anonymous class
822            // in a superclass constructor call where
823            // no explicit outer instance is given,
824            // disable implicit outer instance from being passed.
825            // (This would be an illegal access to "this before super").
826            if (env.info.isSelfCall &&
827                env.tree.hasTag(NEWCLASS) &&
828                ((JCNewClass) env.tree).encl == null)
829            {
830                c.flags_field |= NOOUTERTHIS;
831            }
832            attribClass(tree.pos(), c);
833            result = tree.type = c.type;
834        }
835    }
836
837    public void visitMethodDef(JCMethodDecl tree) {
838        MethodSymbol m = tree.sym;
839        boolean isDefaultMethod = (m.flags() & DEFAULT) != 0;
840
841        Lint lint = env.info.lint.augment(m);
842        Lint prevLint = chk.setLint(lint);
843        MethodSymbol prevMethod = chk.setMethod(m);
844        try {
845            deferredLintHandler.flush(tree.pos());
846            chk.checkDeprecatedAnnotation(tree.pos(), m);
847
848
849            // Create a new environment with local scope
850            // for attributing the method.
851            Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
852            localEnv.info.lint = lint;
853
854            attribStats(tree.typarams, localEnv);
855
856            // If we override any other methods, check that we do so properly.
857            // JLS ???
858            if (m.isStatic()) {
859                chk.checkHideClashes(tree.pos(), env.enclClass.type, m);
860            } else {
861                chk.checkOverrideClashes(tree.pos(), env.enclClass.type, m);
862            }
863            chk.checkOverride(tree, m);
864
865            if (isDefaultMethod && types.overridesObjectMethod(m.enclClass(), m)) {
866                log.error(tree, "default.overrides.object.member", m.name, Kinds.kindName(m.location()), m.location());
867            }
868
869            // Enter all type parameters into the local method scope.
870            for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
871                localEnv.info.scope.enterIfAbsent(l.head.type.tsym);
872
873            ClassSymbol owner = env.enclClass.sym;
874            if ((owner.flags() & ANNOTATION) != 0 &&
875                    tree.params.nonEmpty())
876                log.error(tree.params.head.pos(),
877                        "intf.annotation.members.cant.have.params");
878
879            // Attribute all value parameters.
880            for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
881                attribStat(l.head, localEnv);
882            }
883
884            chk.checkVarargsMethodDecl(localEnv, tree);
885
886            // Check that type parameters are well-formed.
887            chk.validate(tree.typarams, localEnv);
888
889            // Check that result type is well-formed.
890            if (tree.restype != null && !tree.restype.type.hasTag(VOID))
891                chk.validate(tree.restype, localEnv);
892
893            // Check that receiver type is well-formed.
894            if (tree.recvparam != null) {
895                // Use a new environment to check the receiver parameter.
896                // Otherwise I get "might not have been initialized" errors.
897                // Is there a better way?
898                Env<AttrContext> newEnv = memberEnter.methodEnv(tree, env);
899                attribType(tree.recvparam, newEnv);
900                chk.validate(tree.recvparam, newEnv);
901            }
902
903            // annotation method checks
904            if ((owner.flags() & ANNOTATION) != 0) {
905                // annotation method cannot have throws clause
906                if (tree.thrown.nonEmpty()) {
907                    log.error(tree.thrown.head.pos(),
908                            "throws.not.allowed.in.intf.annotation");
909                }
910                // annotation method cannot declare type-parameters
911                if (tree.typarams.nonEmpty()) {
912                    log.error(tree.typarams.head.pos(),
913                            "intf.annotation.members.cant.have.type.params");
914                }
915                // validate annotation method's return type (could be an annotation type)
916                chk.validateAnnotationType(tree.restype);
917                // ensure that annotation method does not clash with members of Object/Annotation
918                chk.validateAnnotationMethod(tree.pos(), m);
919            }
920
921            for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
922                chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
923
924            if (tree.body == null) {
925                // Empty bodies are only allowed for
926                // abstract, native, or interface methods, or for methods
927                // in a retrofit signature class.
928                if (tree.defaultValue != null) {
929                    if ((owner.flags() & ANNOTATION) == 0)
930                        log.error(tree.pos(),
931                                  "default.allowed.in.intf.annotation.member");
932                }
933                if (isDefaultMethod || (tree.sym.flags() & (ABSTRACT | NATIVE)) == 0 &&
934                    !relax)
935                    log.error(tree.pos(), "missing.meth.body.or.decl.abstract");
936            } else if ((tree.sym.flags() & ABSTRACT) != 0 && !isDefaultMethod) {
937                if ((owner.flags() & INTERFACE) != 0) {
938                    log.error(tree.body.pos(), "intf.meth.cant.have.body");
939                } else {
940                    log.error(tree.pos(), "abstract.meth.cant.have.body");
941                }
942            } else if ((tree.mods.flags & NATIVE) != 0) {
943                log.error(tree.pos(), "native.meth.cant.have.body");
944            } else {
945                // Add an implicit super() call unless an explicit call to
946                // super(...) or this(...) is given
947                // or we are compiling class java.lang.Object.
948                if (tree.name == names.init && owner.type != syms.objectType) {
949                    JCBlock body = tree.body;
950                    if (body.stats.isEmpty() ||
951                            !TreeInfo.isSelfCall(body.stats.head)) {
952                        body.stats = body.stats.
953                                prepend(typeEnter.SuperCall(make.at(body.pos),
954                                        List.<Type>nil(),
955                                        List.<JCVariableDecl>nil(),
956                                        false));
957                    } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
958                            (tree.mods.flags & GENERATEDCONSTR) == 0 &&
959                            TreeInfo.isSuperCall(body.stats.head)) {
960                        // enum constructors are not allowed to call super
961                        // directly, so make sure there aren't any super calls
962                        // in enum constructors, except in the compiler
963                        // generated one.
964                        log.error(tree.body.stats.head.pos(),
965                                "call.to.super.not.allowed.in.enum.ctor",
966                                env.enclClass.sym);
967                    }
968                }
969
970                // Attribute all type annotations in the body
971                annotate.annotateTypeLater(tree.body, localEnv, m, null);
972                annotate.flush();
973
974                // Attribute method body.
975                attribStat(tree.body, localEnv);
976            }
977
978            localEnv.info.scope.leave();
979            result = tree.type = m.type;
980        } finally {
981            chk.setLint(prevLint);
982            chk.setMethod(prevMethod);
983        }
984    }
985
986    public void visitVarDef(JCVariableDecl tree) {
987        // Local variables have not been entered yet, so we need to do it now:
988        if (env.info.scope.owner.kind == MTH) {
989            if (tree.sym != null) {
990                // parameters have already been entered
991                env.info.scope.enter(tree.sym);
992            } else {
993                try {
994                    annotate.enterStart();
995                    memberEnter.memberEnter(tree, env);
996                } finally {
997                    annotate.enterDone();
998                }
999            }
1000        } else {
1001            if (tree.init != null) {
1002                // Field initializer expression need to be entered.
1003                annotate.annotateTypeLater(tree.init, env, tree.sym, tree.pos());
1004                annotate.flush();
1005            }
1006        }
1007
1008        VarSymbol v = tree.sym;
1009        Lint lint = env.info.lint.augment(v);
1010        Lint prevLint = chk.setLint(lint);
1011
1012        // Check that the variable's declared type is well-formed.
1013        boolean isImplicitLambdaParameter = env.tree.hasTag(LAMBDA) &&
1014                ((JCLambda)env.tree).paramKind == JCLambda.ParameterKind.IMPLICIT &&
1015                (tree.sym.flags() & PARAMETER) != 0;
1016        chk.validate(tree.vartype, env, !isImplicitLambdaParameter);
1017
1018        try {
1019            v.getConstValue(); // ensure compile-time constant initializer is evaluated
1020            deferredLintHandler.flush(tree.pos());
1021            chk.checkDeprecatedAnnotation(tree.pos(), v);
1022
1023            if (tree.init != null) {
1024                if ((v.flags_field & FINAL) == 0 ||
1025                    !memberEnter.needsLazyConstValue(tree.init)) {
1026                    // Not a compile-time constant
1027                    // Attribute initializer in a new environment
1028                    // with the declared variable as owner.
1029                    // Check that initializer conforms to variable's declared type.
1030                    Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
1031                    initEnv.info.lint = lint;
1032                    // In order to catch self-references, we set the variable's
1033                    // declaration position to maximal possible value, effectively
1034                    // marking the variable as undefined.
1035                    initEnv.info.enclVar = v;
1036                    attribExpr(tree.init, initEnv, v.type);
1037                }
1038            }
1039            result = tree.type = v.type;
1040        }
1041        finally {
1042            chk.setLint(prevLint);
1043        }
1044    }
1045
1046    public void visitSkip(JCSkip tree) {
1047        result = null;
1048    }
1049
1050    public void visitBlock(JCBlock tree) {
1051        if (env.info.scope.owner.kind == TYP) {
1052            // Block is a static or instance initializer;
1053            // let the owner of the environment be a freshly
1054            // created BLOCK-method.
1055            Symbol fakeOwner =
1056                new MethodSymbol(tree.flags | BLOCK |
1057                    env.info.scope.owner.flags() & STRICTFP, names.empty, null,
1058                    env.info.scope.owner);
1059            final Env<AttrContext> localEnv =
1060                env.dup(tree, env.info.dup(env.info.scope.dupUnshared(fakeOwner)));
1061
1062            if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
1063            // Attribute all type annotations in the block
1064            annotate.annotateTypeLater(tree, localEnv, localEnv.info.scope.owner, null);
1065            annotate.flush();
1066            attribStats(tree.stats, localEnv);
1067
1068            {
1069                // Store init and clinit type annotations with the ClassSymbol
1070                // to allow output in Gen.normalizeDefs.
1071                ClassSymbol cs = (ClassSymbol)env.info.scope.owner;
1072                List<Attribute.TypeCompound> tas = localEnv.info.scope.owner.getRawTypeAttributes();
1073                if ((tree.flags & STATIC) != 0) {
1074                    cs.appendClassInitTypeAttributes(tas);
1075                } else {
1076                    cs.appendInitTypeAttributes(tas);
1077                }
1078            }
1079        } else {
1080            // Create a new local environment with a local scope.
1081            Env<AttrContext> localEnv =
1082                env.dup(tree, env.info.dup(env.info.scope.dup()));
1083            try {
1084                attribStats(tree.stats, localEnv);
1085            } finally {
1086                localEnv.info.scope.leave();
1087            }
1088        }
1089        result = null;
1090    }
1091
1092    public void visitDoLoop(JCDoWhileLoop tree) {
1093        attribStat(tree.body, env.dup(tree));
1094        attribExpr(tree.cond, env, syms.booleanType);
1095        result = null;
1096    }
1097
1098    public void visitWhileLoop(JCWhileLoop tree) {
1099        attribExpr(tree.cond, env, syms.booleanType);
1100        attribStat(tree.body, env.dup(tree));
1101        result = null;
1102    }
1103
1104    public void visitForLoop(JCForLoop tree) {
1105        Env<AttrContext> loopEnv =
1106            env.dup(env.tree, env.info.dup(env.info.scope.dup()));
1107        try {
1108            attribStats(tree.init, loopEnv);
1109            if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType);
1110            loopEnv.tree = tree; // before, we were not in loop!
1111            attribStats(tree.step, loopEnv);
1112            attribStat(tree.body, loopEnv);
1113            result = null;
1114        }
1115        finally {
1116            loopEnv.info.scope.leave();
1117        }
1118    }
1119
1120    public void visitForeachLoop(JCEnhancedForLoop tree) {
1121        Env<AttrContext> loopEnv =
1122            env.dup(env.tree, env.info.dup(env.info.scope.dup()));
1123        try {
1124            //the Formal Parameter of a for-each loop is not in the scope when
1125            //attributing the for-each expression; we mimick this by attributing
1126            //the for-each expression first (against original scope).
1127            Type exprType = types.cvarUpperBound(attribExpr(tree.expr, loopEnv));
1128            attribStat(tree.var, loopEnv);
1129            chk.checkNonVoid(tree.pos(), exprType);
1130            Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
1131            if (elemtype == null) {
1132                // or perhaps expr implements Iterable<T>?
1133                Type base = types.asSuper(exprType, syms.iterableType.tsym);
1134                if (base == null) {
1135                    log.error(tree.expr.pos(),
1136                            "foreach.not.applicable.to.type",
1137                            exprType,
1138                            diags.fragment("type.req.array.or.iterable"));
1139                    elemtype = types.createErrorType(exprType);
1140                } else {
1141                    List<Type> iterableParams = base.allparams();
1142                    elemtype = iterableParams.isEmpty()
1143                        ? syms.objectType
1144                        : types.wildUpperBound(iterableParams.head);
1145                }
1146            }
1147            chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
1148            loopEnv.tree = tree; // before, we were not in loop!
1149            attribStat(tree.body, loopEnv);
1150            result = null;
1151        }
1152        finally {
1153            loopEnv.info.scope.leave();
1154        }
1155    }
1156
1157    public void visitLabelled(JCLabeledStatement tree) {
1158        // Check that label is not used in an enclosing statement
1159        Env<AttrContext> env1 = env;
1160        while (env1 != null && !env1.tree.hasTag(CLASSDEF)) {
1161            if (env1.tree.hasTag(LABELLED) &&
1162                ((JCLabeledStatement) env1.tree).label == tree.label) {
1163                log.error(tree.pos(), "label.already.in.use",
1164                          tree.label);
1165                break;
1166            }
1167            env1 = env1.next;
1168        }
1169
1170        attribStat(tree.body, env.dup(tree));
1171        result = null;
1172    }
1173
1174    public void visitSwitch(JCSwitch tree) {
1175        Type seltype = attribExpr(tree.selector, env);
1176
1177        Env<AttrContext> switchEnv =
1178            env.dup(tree, env.info.dup(env.info.scope.dup()));
1179
1180        try {
1181
1182            boolean enumSwitch = (seltype.tsym.flags() & Flags.ENUM) != 0;
1183            boolean stringSwitch = false;
1184            if (types.isSameType(seltype, syms.stringType)) {
1185                if (allowStringsInSwitch) {
1186                    stringSwitch = true;
1187                } else {
1188                    log.error(tree.selector.pos(), "string.switch.not.supported.in.source", sourceName);
1189                }
1190            }
1191            if (!enumSwitch && !stringSwitch)
1192                seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType);
1193
1194            // Attribute all cases and
1195            // check that there are no duplicate case labels or default clauses.
1196            Set<Object> labels = new HashSet<>(); // The set of case labels.
1197            boolean hasDefault = false;      // Is there a default label?
1198            for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
1199                JCCase c = l.head;
1200                if (c.pat != null) {
1201                    if (enumSwitch) {
1202                        Symbol sym = enumConstant(c.pat, seltype);
1203                        if (sym == null) {
1204                            log.error(c.pat.pos(), "enum.label.must.be.unqualified.enum");
1205                        } else if (!labels.add(sym)) {
1206                            log.error(c.pos(), "duplicate.case.label");
1207                        }
1208                    } else {
1209                        Type pattype = attribExpr(c.pat, switchEnv, seltype);
1210                        if (!pattype.hasTag(ERROR)) {
1211                            if (pattype.constValue() == null) {
1212                                log.error(c.pat.pos(),
1213                                          (stringSwitch ? "string.const.req" : "const.expr.req"));
1214                            } else if (!labels.add(pattype.constValue())) {
1215                                log.error(c.pos(), "duplicate.case.label");
1216                            }
1217                        }
1218                    }
1219                } else if (hasDefault) {
1220                    log.error(c.pos(), "duplicate.default.label");
1221                } else {
1222                    hasDefault = true;
1223                }
1224                Env<AttrContext> caseEnv =
1225                    switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup()));
1226                try {
1227                    attribStats(c.stats, caseEnv);
1228                } finally {
1229                    caseEnv.info.scope.leave();
1230                    addVars(c.stats, switchEnv.info.scope);
1231                }
1232            }
1233
1234            result = null;
1235        }
1236        finally {
1237            switchEnv.info.scope.leave();
1238        }
1239    }
1240    // where
1241        /** Add any variables defined in stats to the switch scope. */
1242        private static void addVars(List<JCStatement> stats, WriteableScope switchScope) {
1243            for (;stats.nonEmpty(); stats = stats.tail) {
1244                JCTree stat = stats.head;
1245                if (stat.hasTag(VARDEF))
1246                    switchScope.enter(((JCVariableDecl) stat).sym);
1247            }
1248        }
1249    // where
1250    /** Return the selected enumeration constant symbol, or null. */
1251    private Symbol enumConstant(JCTree tree, Type enumType) {
1252        if (tree.hasTag(IDENT)) {
1253            JCIdent ident = (JCIdent)tree;
1254            Name name = ident.name;
1255            for (Symbol sym : enumType.tsym.members().getSymbolsByName(name)) {
1256                if (sym.kind == VAR) {
1257                    Symbol s = ident.sym = sym;
1258                    ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
1259                    ident.type = s.type;
1260                    return ((s.flags_field & Flags.ENUM) == 0)
1261                        ? null : s;
1262                }
1263            }
1264        }
1265        return null;
1266    }
1267
1268    public void visitSynchronized(JCSynchronized tree) {
1269        chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
1270        attribStat(tree.body, env);
1271        result = null;
1272    }
1273
1274    public void visitTry(JCTry tree) {
1275        // Create a new local environment with a local
1276        Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
1277        try {
1278            boolean isTryWithResource = tree.resources.nonEmpty();
1279            // Create a nested environment for attributing the try block if needed
1280            Env<AttrContext> tryEnv = isTryWithResource ?
1281                env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
1282                localEnv;
1283            try {
1284                // Attribute resource declarations
1285                for (JCTree resource : tree.resources) {
1286                    CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) {
1287                        @Override
1288                        public void report(DiagnosticPosition pos, JCDiagnostic details) {
1289                            chk.basicHandler.report(pos, diags.fragment("try.not.applicable.to.type", details));
1290                        }
1291                    };
1292                    ResultInfo twrResult =
1293                        new ResultInfo(KindSelector.VAR,
1294                                       syms.autoCloseableType,
1295                                       twrContext);
1296                    if (resource.hasTag(VARDEF)) {
1297                        attribStat(resource, tryEnv);
1298                        twrResult.check(resource, resource.type);
1299
1300                        //check that resource type cannot throw InterruptedException
1301                        checkAutoCloseable(resource.pos(), localEnv, resource.type);
1302
1303                        VarSymbol var = ((JCVariableDecl) resource).sym;
1304                        var.setData(ElementKind.RESOURCE_VARIABLE);
1305                    } else {
1306                        attribTree(resource, tryEnv, twrResult);
1307                    }
1308                }
1309                // Attribute body
1310                attribStat(tree.body, tryEnv);
1311            } finally {
1312                if (isTryWithResource)
1313                    tryEnv.info.scope.leave();
1314            }
1315
1316            // Attribute catch clauses
1317            for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
1318                JCCatch c = l.head;
1319                Env<AttrContext> catchEnv =
1320                    localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup()));
1321                try {
1322                    Type ctype = attribStat(c.param, catchEnv);
1323                    if (TreeInfo.isMultiCatch(c)) {
1324                        //multi-catch parameter is implicitly marked as final
1325                        c.param.sym.flags_field |= FINAL | UNION;
1326                    }
1327                    if (c.param.sym.kind == VAR) {
1328                        c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
1329                    }
1330                    chk.checkType(c.param.vartype.pos(),
1331                                  chk.checkClassType(c.param.vartype.pos(), ctype),
1332                                  syms.throwableType);
1333                    attribStat(c.body, catchEnv);
1334                } finally {
1335                    catchEnv.info.scope.leave();
1336                }
1337            }
1338
1339            // Attribute finalizer
1340            if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
1341            result = null;
1342        }
1343        finally {
1344            localEnv.info.scope.leave();
1345        }
1346    }
1347
1348    void checkAutoCloseable(DiagnosticPosition pos, Env<AttrContext> env, Type resource) {
1349        if (!resource.isErroneous() &&
1350            types.asSuper(resource, syms.autoCloseableType.tsym) != null &&
1351            !types.isSameType(resource, syms.autoCloseableType)) { // Don't emit warning for AutoCloseable itself
1352            Symbol close = syms.noSymbol;
1353            Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log);
1354            try {
1355                close = rs.resolveQualifiedMethod(pos,
1356                        env,
1357                        resource,
1358                        names.close,
1359                        List.<Type>nil(),
1360                        List.<Type>nil());
1361            }
1362            finally {
1363                log.popDiagnosticHandler(discardHandler);
1364            }
1365            if (close.kind == MTH &&
1366                    close.overrides(syms.autoCloseableClose, resource.tsym, types, true) &&
1367                    chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes()) &&
1368                    env.info.lint.isEnabled(LintCategory.TRY)) {
1369                log.warning(LintCategory.TRY, pos, "try.resource.throws.interrupted.exc", resource);
1370            }
1371        }
1372    }
1373
1374    public void visitConditional(JCConditional tree) {
1375        Type condtype = attribExpr(tree.cond, env, syms.booleanType);
1376
1377        tree.polyKind = (!allowPoly ||
1378                pt().hasTag(NONE) && pt() != Type.recoveryType ||
1379                isBooleanOrNumeric(env, tree)) ?
1380                PolyKind.STANDALONE : PolyKind.POLY;
1381
1382        if (tree.polyKind == PolyKind.POLY && resultInfo.pt.hasTag(VOID)) {
1383            //cannot get here (i.e. it means we are returning from void method - which is already an error)
1384            resultInfo.checkContext.report(tree, diags.fragment("conditional.target.cant.be.void"));
1385            result = tree.type = types.createErrorType(resultInfo.pt);
1386            return;
1387        }
1388
1389        ResultInfo condInfo = tree.polyKind == PolyKind.STANDALONE ?
1390                unknownExprInfo :
1391                resultInfo.dup(new Check.NestedCheckContext(resultInfo.checkContext) {
1392                    //this will use enclosing check context to check compatibility of
1393                    //subexpression against target type; if we are in a method check context,
1394                    //depending on whether boxing is allowed, we could have incompatibilities
1395                    @Override
1396                    public void report(DiagnosticPosition pos, JCDiagnostic details) {
1397                        enclosingContext.report(pos, diags.fragment("incompatible.type.in.conditional", details));
1398                    }
1399                });
1400
1401        Type truetype = attribTree(tree.truepart, env, condInfo);
1402        Type falsetype = attribTree(tree.falsepart, env, condInfo);
1403
1404        Type owntype = (tree.polyKind == PolyKind.STANDALONE) ? condType(tree, truetype, falsetype) : pt();
1405        if (condtype.constValue() != null &&
1406                truetype.constValue() != null &&
1407                falsetype.constValue() != null &&
1408                !owntype.hasTag(NONE)) {
1409            //constant folding
1410            owntype = cfolder.coerce(condtype.isTrue() ? truetype : falsetype, owntype);
1411        }
1412        result = check(tree, owntype, KindSelector.VAL, resultInfo);
1413    }
1414    //where
1415        private boolean isBooleanOrNumeric(Env<AttrContext> env, JCExpression tree) {
1416            switch (tree.getTag()) {
1417                case LITERAL: return ((JCLiteral)tree).typetag.isSubRangeOf(DOUBLE) ||
1418                              ((JCLiteral)tree).typetag == BOOLEAN ||
1419                              ((JCLiteral)tree).typetag == BOT;
1420                case LAMBDA: case REFERENCE: return false;
1421                case PARENS: return isBooleanOrNumeric(env, ((JCParens)tree).expr);
1422                case CONDEXPR:
1423                    JCConditional condTree = (JCConditional)tree;
1424                    return isBooleanOrNumeric(env, condTree.truepart) &&
1425                            isBooleanOrNumeric(env, condTree.falsepart);
1426                case APPLY:
1427                    JCMethodInvocation speculativeMethodTree =
1428                            (JCMethodInvocation)deferredAttr.attribSpeculative(tree, env, unknownExprInfo);
1429                    Symbol msym = TreeInfo.symbol(speculativeMethodTree.meth);
1430                    Type receiverType = speculativeMethodTree.meth.hasTag(IDENT) ?
1431                            env.enclClass.type :
1432                            ((JCFieldAccess)speculativeMethodTree.meth).selected.type;
1433                    Type owntype = types.memberType(receiverType, msym).getReturnType();
1434                    return primitiveOrBoxed(owntype);
1435                case NEWCLASS:
1436                    JCExpression className =
1437                            removeClassParams.translate(((JCNewClass)tree).clazz);
1438                    JCExpression speculativeNewClassTree =
1439                            (JCExpression)deferredAttr.attribSpeculative(className, env, unknownTypeInfo);
1440                    return primitiveOrBoxed(speculativeNewClassTree.type);
1441                default:
1442                    Type speculativeType = deferredAttr.attribSpeculative(tree, env, unknownExprInfo).type;
1443                    return primitiveOrBoxed(speculativeType);
1444            }
1445        }
1446        //where
1447            boolean primitiveOrBoxed(Type t) {
1448                return (!t.hasTag(TYPEVAR) && types.unboxedTypeOrType(t).isPrimitive());
1449            }
1450
1451            TreeTranslator removeClassParams = new TreeTranslator() {
1452                @Override
1453                public void visitTypeApply(JCTypeApply tree) {
1454                    result = translate(tree.clazz);
1455                }
1456            };
1457
1458        /** Compute the type of a conditional expression, after
1459         *  checking that it exists.  See JLS 15.25. Does not take into
1460         *  account the special case where condition and both arms
1461         *  are constants.
1462         *
1463         *  @param pos      The source position to be used for error
1464         *                  diagnostics.
1465         *  @param thentype The type of the expression's then-part.
1466         *  @param elsetype The type of the expression's else-part.
1467         */
1468        Type condType(DiagnosticPosition pos,
1469                               Type thentype, Type elsetype) {
1470            // If same type, that is the result
1471            if (types.isSameType(thentype, elsetype))
1472                return thentype.baseType();
1473
1474            Type thenUnboxed = (thentype.isPrimitive())
1475                ? thentype : types.unboxedType(thentype);
1476            Type elseUnboxed = (elsetype.isPrimitive())
1477                ? elsetype : types.unboxedType(elsetype);
1478
1479            // Otherwise, if both arms can be converted to a numeric
1480            // type, return the least numeric type that fits both arms
1481            // (i.e. return larger of the two, or return int if one
1482            // arm is short, the other is char).
1483            if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) {
1484                // If one arm has an integer subrange type (i.e., byte,
1485                // short, or char), and the other is an integer constant
1486                // that fits into the subrange, return the subrange type.
1487                if (thenUnboxed.getTag().isStrictSubRangeOf(INT) &&
1488                    elseUnboxed.hasTag(INT) &&
1489                    types.isAssignable(elseUnboxed, thenUnboxed)) {
1490                    return thenUnboxed.baseType();
1491                }
1492                if (elseUnboxed.getTag().isStrictSubRangeOf(INT) &&
1493                    thenUnboxed.hasTag(INT) &&
1494                    types.isAssignable(thenUnboxed, elseUnboxed)) {
1495                    return elseUnboxed.baseType();
1496                }
1497
1498                for (TypeTag tag : primitiveTags) {
1499                    Type candidate = syms.typeOfTag[tag.ordinal()];
1500                    if (types.isSubtype(thenUnboxed, candidate) &&
1501                        types.isSubtype(elseUnboxed, candidate)) {
1502                        return candidate;
1503                    }
1504                }
1505            }
1506
1507            // Those were all the cases that could result in a primitive
1508            if (thentype.isPrimitive())
1509                thentype = types.boxedClass(thentype).type;
1510            if (elsetype.isPrimitive())
1511                elsetype = types.boxedClass(elsetype).type;
1512
1513            if (types.isSubtype(thentype, elsetype))
1514                return elsetype.baseType();
1515            if (types.isSubtype(elsetype, thentype))
1516                return thentype.baseType();
1517
1518            if (thentype.hasTag(VOID) || elsetype.hasTag(VOID)) {
1519                log.error(pos, "neither.conditional.subtype",
1520                          thentype, elsetype);
1521                return thentype.baseType();
1522            }
1523
1524            // both are known to be reference types.  The result is
1525            // lub(thentype,elsetype). This cannot fail, as it will
1526            // always be possible to infer "Object" if nothing better.
1527            return types.lub(thentype.baseType(), elsetype.baseType());
1528        }
1529
1530    final static TypeTag[] primitiveTags = new TypeTag[]{
1531        BYTE,
1532        CHAR,
1533        SHORT,
1534        INT,
1535        LONG,
1536        FLOAT,
1537        DOUBLE,
1538        BOOLEAN,
1539    };
1540
1541    public void visitIf(JCIf tree) {
1542        attribExpr(tree.cond, env, syms.booleanType);
1543        attribStat(tree.thenpart, env);
1544        if (tree.elsepart != null)
1545            attribStat(tree.elsepart, env);
1546        chk.checkEmptyIf(tree);
1547        result = null;
1548    }
1549
1550    public void visitExec(JCExpressionStatement tree) {
1551        //a fresh environment is required for 292 inference to work properly ---
1552        //see Infer.instantiatePolymorphicSignatureInstance()
1553        Env<AttrContext> localEnv = env.dup(tree);
1554        attribExpr(tree.expr, localEnv);
1555        result = null;
1556    }
1557
1558    public void visitBreak(JCBreak tree) {
1559        tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
1560        result = null;
1561    }
1562
1563    public void visitContinue(JCContinue tree) {
1564        tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
1565        result = null;
1566    }
1567    //where
1568        /** Return the target of a break or continue statement, if it exists,
1569         *  report an error if not.
1570         *  Note: The target of a labelled break or continue is the
1571         *  (non-labelled) statement tree referred to by the label,
1572         *  not the tree representing the labelled statement itself.
1573         *
1574         *  @param pos     The position to be used for error diagnostics
1575         *  @param tag     The tag of the jump statement. This is either
1576         *                 Tree.BREAK or Tree.CONTINUE.
1577         *  @param label   The label of the jump statement, or null if no
1578         *                 label is given.
1579         *  @param env     The environment current at the jump statement.
1580         */
1581        private JCTree findJumpTarget(DiagnosticPosition pos,
1582                                    JCTree.Tag tag,
1583                                    Name label,
1584                                    Env<AttrContext> env) {
1585            // Search environments outwards from the point of jump.
1586            Env<AttrContext> env1 = env;
1587            LOOP:
1588            while (env1 != null) {
1589                switch (env1.tree.getTag()) {
1590                    case LABELLED:
1591                        JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
1592                        if (label == labelled.label) {
1593                            // If jump is a continue, check that target is a loop.
1594                            if (tag == CONTINUE) {
1595                                if (!labelled.body.hasTag(DOLOOP) &&
1596                                        !labelled.body.hasTag(WHILELOOP) &&
1597                                        !labelled.body.hasTag(FORLOOP) &&
1598                                        !labelled.body.hasTag(FOREACHLOOP))
1599                                    log.error(pos, "not.loop.label", label);
1600                                // Found labelled statement target, now go inwards
1601                                // to next non-labelled tree.
1602                                return TreeInfo.referencedStatement(labelled);
1603                            } else {
1604                                return labelled;
1605                            }
1606                        }
1607                        break;
1608                    case DOLOOP:
1609                    case WHILELOOP:
1610                    case FORLOOP:
1611                    case FOREACHLOOP:
1612                        if (label == null) return env1.tree;
1613                        break;
1614                    case SWITCH:
1615                        if (label == null && tag == BREAK) return env1.tree;
1616                        break;
1617                    case LAMBDA:
1618                    case METHODDEF:
1619                    case CLASSDEF:
1620                        break LOOP;
1621                    default:
1622                }
1623                env1 = env1.next;
1624            }
1625            if (label != null)
1626                log.error(pos, "undef.label", label);
1627            else if (tag == CONTINUE)
1628                log.error(pos, "cont.outside.loop");
1629            else
1630                log.error(pos, "break.outside.switch.loop");
1631            return null;
1632        }
1633
1634    public void visitReturn(JCReturn tree) {
1635        // Check that there is an enclosing method which is
1636        // nested within than the enclosing class.
1637        if (env.info.returnResult == null) {
1638            log.error(tree.pos(), "ret.outside.meth");
1639        } else {
1640            // Attribute return expression, if it exists, and check that
1641            // it conforms to result type of enclosing method.
1642            if (tree.expr != null) {
1643                if (env.info.returnResult.pt.hasTag(VOID)) {
1644                    env.info.returnResult.checkContext.report(tree.expr.pos(),
1645                              diags.fragment("unexpected.ret.val"));
1646                }
1647                attribTree(tree.expr, env, env.info.returnResult);
1648            } else if (!env.info.returnResult.pt.hasTag(VOID) &&
1649                    !env.info.returnResult.pt.hasTag(NONE)) {
1650                env.info.returnResult.checkContext.report(tree.pos(),
1651                              diags.fragment("missing.ret.val"));
1652            }
1653        }
1654        result = null;
1655    }
1656
1657    public void visitThrow(JCThrow tree) {
1658        Type owntype = attribExpr(tree.expr, env, allowPoly ? Type.noType : syms.throwableType);
1659        if (allowPoly) {
1660            chk.checkType(tree, owntype, syms.throwableType);
1661        }
1662        result = null;
1663    }
1664
1665    public void visitAssert(JCAssert tree) {
1666        attribExpr(tree.cond, env, syms.booleanType);
1667        if (tree.detail != null) {
1668            chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
1669        }
1670        result = null;
1671    }
1672
1673     /** Visitor method for method invocations.
1674     *  NOTE: The method part of an application will have in its type field
1675     *        the return type of the method, not the method's type itself!
1676     */
1677    public void visitApply(JCMethodInvocation tree) {
1678        // The local environment of a method application is
1679        // a new environment nested in the current one.
1680        Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
1681
1682        // The types of the actual method arguments.
1683        List<Type> argtypes;
1684
1685        // The types of the actual method type arguments.
1686        List<Type> typeargtypes = null;
1687
1688        Name methName = TreeInfo.name(tree.meth);
1689
1690        boolean isConstructorCall =
1691            methName == names._this || methName == names._super;
1692
1693        ListBuffer<Type> argtypesBuf = new ListBuffer<>();
1694        if (isConstructorCall) {
1695            // We are seeing a ...this(...) or ...super(...) call.
1696            // Check that this is the first statement in a constructor.
1697            if (checkFirstConstructorStat(tree, env)) {
1698
1699                // Record the fact
1700                // that this is a constructor call (using isSelfCall).
1701                localEnv.info.isSelfCall = true;
1702
1703                // Attribute arguments, yielding list of argument types.
1704                KindSelector kind = attribArgs(KindSelector.MTH, tree.args, localEnv, argtypesBuf);
1705                argtypes = argtypesBuf.toList();
1706                typeargtypes = attribTypes(tree.typeargs, localEnv);
1707
1708                // Variable `site' points to the class in which the called
1709                // constructor is defined.
1710                Type site = env.enclClass.sym.type;
1711                if (methName == names._super) {
1712                    if (site == syms.objectType) {
1713                        log.error(tree.meth.pos(), "no.superclass", site);
1714                        site = types.createErrorType(syms.objectType);
1715                    } else {
1716                        site = types.supertype(site);
1717                    }
1718                }
1719
1720                if (site.hasTag(CLASS)) {
1721                    Type encl = site.getEnclosingType();
1722                    while (encl != null && encl.hasTag(TYPEVAR))
1723                        encl = encl.getUpperBound();
1724                    if (encl.hasTag(CLASS)) {
1725                        // we are calling a nested class
1726
1727                        if (tree.meth.hasTag(SELECT)) {
1728                            JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
1729
1730                            // We are seeing a prefixed call, of the form
1731                            //     <expr>.super(...).
1732                            // Check that the prefix expression conforms
1733                            // to the outer instance type of the class.
1734                            chk.checkRefType(qualifier.pos(),
1735                                             attribExpr(qualifier, localEnv,
1736                                                        encl));
1737                        } else if (methName == names._super) {
1738                            // qualifier omitted; check for existence
1739                            // of an appropriate implicit qualifier.
1740                            rs.resolveImplicitThis(tree.meth.pos(),
1741                                                   localEnv, site, true);
1742                        }
1743                    } else if (tree.meth.hasTag(SELECT)) {
1744                        log.error(tree.meth.pos(), "illegal.qual.not.icls",
1745                                  site.tsym);
1746                    }
1747
1748                    // if we're calling a java.lang.Enum constructor,
1749                    // prefix the implicit String and int parameters
1750                    if (site.tsym == syms.enumSym)
1751                        argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
1752
1753                    // Resolve the called constructor under the assumption
1754                    // that we are referring to a superclass instance of the
1755                    // current instance (JLS ???).
1756                    boolean selectSuperPrev = localEnv.info.selectSuper;
1757                    localEnv.info.selectSuper = true;
1758                    localEnv.info.pendingResolutionPhase = null;
1759                    Symbol sym = rs.resolveConstructor(
1760                        tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
1761                    localEnv.info.selectSuper = selectSuperPrev;
1762
1763                    // Set method symbol to resolved constructor...
1764                    TreeInfo.setSymbol(tree.meth, sym);
1765
1766                    // ...and check that it is legal in the current context.
1767                    // (this will also set the tree's type)
1768                    Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
1769                    checkId(tree.meth, site, sym, localEnv,
1770                            new ResultInfo(kind, mpt));
1771                }
1772                // Otherwise, `site' is an error type and we do nothing
1773            }
1774            result = tree.type = syms.voidType;
1775        } else {
1776            // Otherwise, we are seeing a regular method call.
1777            // Attribute the arguments, yielding list of argument types, ...
1778            KindSelector kind = attribArgs(KindSelector.VAL, tree.args, localEnv, argtypesBuf);
1779            argtypes = argtypesBuf.toList();
1780            typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
1781
1782            // ... and attribute the method using as a prototype a methodtype
1783            // whose formal argument types is exactly the list of actual
1784            // arguments (this will also set the method symbol).
1785            Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
1786            localEnv.info.pendingResolutionPhase = null;
1787            Type mtype = attribTree(tree.meth, localEnv, new ResultInfo(kind, mpt, resultInfo.checkContext));
1788
1789            // Compute the result type.
1790            Type restype = mtype.getReturnType();
1791            if (restype.hasTag(WILDCARD))
1792                throw new AssertionError(mtype);
1793
1794            Type qualifier = (tree.meth.hasTag(SELECT))
1795                    ? ((JCFieldAccess) tree.meth).selected.type
1796                    : env.enclClass.sym.type;
1797            restype = adjustMethodReturnType(qualifier, methName, argtypes, restype);
1798
1799            chk.checkRefTypes(tree.typeargs, typeargtypes);
1800
1801            // Check that value of resulting type is admissible in the
1802            // current context.  Also, capture the return type
1803            result = check(tree, capture(restype), KindSelector.VAL, resultInfo);
1804        }
1805        chk.validate(tree.typeargs, localEnv);
1806    }
1807    //where
1808        Type adjustMethodReturnType(Type qualifierType, Name methodName, List<Type> argtypes, Type restype) {
1809            if (methodName == names.clone && types.isArray(qualifierType)) {
1810                // as a special case, array.clone() has a result that is
1811                // the same as static type of the array being cloned
1812                return qualifierType;
1813            } else if (methodName == names.getClass && argtypes.isEmpty()) {
1814                // as a special case, x.getClass() has type Class<? extends |X|>
1815                return new ClassType(restype.getEnclosingType(),
1816                              List.<Type>of(new WildcardType(types.erasure(qualifierType),
1817                                                               BoundKind.EXTENDS,
1818                                                             syms.boundClass)),
1819                                     restype.tsym,
1820                                     restype.getMetadata());
1821            } else {
1822                return restype;
1823            }
1824        }
1825
1826        /** Check that given application node appears as first statement
1827         *  in a constructor call.
1828         *  @param tree   The application node
1829         *  @param env    The environment current at the application.
1830         */
1831        boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) {
1832            JCMethodDecl enclMethod = env.enclMethod;
1833            if (enclMethod != null && enclMethod.name == names.init) {
1834                JCBlock body = enclMethod.body;
1835                if (body.stats.head.hasTag(EXEC) &&
1836                    ((JCExpressionStatement) body.stats.head).expr == tree)
1837                    return true;
1838            }
1839            log.error(tree.pos(),"call.must.be.first.stmt.in.ctor",
1840                      TreeInfo.name(tree.meth));
1841            return false;
1842        }
1843
1844        /** Obtain a method type with given argument types.
1845         */
1846        Type newMethodTemplate(Type restype, List<Type> argtypes, List<Type> typeargtypes) {
1847            MethodType mt = new MethodType(argtypes, restype, List.<Type>nil(), syms.methodClass);
1848            return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
1849        }
1850
1851    public void visitNewClass(final JCNewClass tree) {
1852        Type owntype = types.createErrorType(tree.type);
1853
1854        // The local environment of a class creation is
1855        // a new environment nested in the current one.
1856        Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
1857
1858        // The anonymous inner class definition of the new expression,
1859        // if one is defined by it.
1860        JCClassDecl cdef = tree.def;
1861
1862        // If enclosing class is given, attribute it, and
1863        // complete class name to be fully qualified
1864        JCExpression clazz = tree.clazz; // Class field following new
1865        JCExpression clazzid;            // Identifier in class field
1866        JCAnnotatedType annoclazzid;     // Annotated type enclosing clazzid
1867        annoclazzid = null;
1868
1869        if (clazz.hasTag(TYPEAPPLY)) {
1870            clazzid = ((JCTypeApply) clazz).clazz;
1871            if (clazzid.hasTag(ANNOTATED_TYPE)) {
1872                annoclazzid = (JCAnnotatedType) clazzid;
1873                clazzid = annoclazzid.underlyingType;
1874            }
1875        } else {
1876            if (clazz.hasTag(ANNOTATED_TYPE)) {
1877                annoclazzid = (JCAnnotatedType) clazz;
1878                clazzid = annoclazzid.underlyingType;
1879            } else {
1880                clazzid = clazz;
1881            }
1882        }
1883
1884        JCExpression clazzid1 = clazzid; // The same in fully qualified form
1885
1886        if (tree.encl != null) {
1887            // We are seeing a qualified new, of the form
1888            //    <expr>.new C <...> (...) ...
1889            // In this case, we let clazz stand for the name of the
1890            // allocated class C prefixed with the type of the qualifier
1891            // expression, so that we can
1892            // resolve it with standard techniques later. I.e., if
1893            // <expr> has type T, then <expr>.new C <...> (...)
1894            // yields a clazz T.C.
1895            Type encltype = chk.checkRefType(tree.encl.pos(),
1896                                             attribExpr(tree.encl, env));
1897            // TODO 308: in <expr>.new C, do we also want to add the type annotations
1898            // from expr to the combined type, or not? Yes, do this.
1899            clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
1900                                                 ((JCIdent) clazzid).name);
1901
1902            EndPosTable endPosTable = this.env.toplevel.endPositions;
1903            endPosTable.storeEnd(clazzid1, tree.getEndPosition(endPosTable));
1904            if (clazz.hasTag(ANNOTATED_TYPE)) {
1905                JCAnnotatedType annoType = (JCAnnotatedType) clazz;
1906                List<JCAnnotation> annos = annoType.annotations;
1907
1908                if (annoType.underlyingType.hasTag(TYPEAPPLY)) {
1909                    clazzid1 = make.at(tree.pos).
1910                        TypeApply(clazzid1,
1911                                  ((JCTypeApply) clazz).arguments);
1912                }
1913
1914                clazzid1 = make.at(tree.pos).
1915                    AnnotatedType(annos, clazzid1);
1916            } else if (clazz.hasTag(TYPEAPPLY)) {
1917                clazzid1 = make.at(tree.pos).
1918                    TypeApply(clazzid1,
1919                              ((JCTypeApply) clazz).arguments);
1920            }
1921
1922            clazz = clazzid1;
1923        }
1924
1925        // Attribute clazz expression and store
1926        // symbol + type back into the attributed tree.
1927        Type clazztype = TreeInfo.isEnumInit(env.tree) ?
1928            attribIdentAsEnumType(env, (JCIdent)clazz) :
1929            attribType(clazz, env);
1930
1931        clazztype = chk.checkDiamond(tree, clazztype);
1932        chk.validate(clazz, localEnv);
1933        if (tree.encl != null) {
1934            // We have to work in this case to store
1935            // symbol + type back into the attributed tree.
1936            tree.clazz.type = clazztype;
1937            TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
1938            clazzid.type = ((JCIdent) clazzid).sym.type;
1939            if (annoclazzid != null) {
1940                annoclazzid.type = clazzid.type;
1941            }
1942            if (!clazztype.isErroneous()) {
1943                if (cdef != null && clazztype.tsym.isInterface()) {
1944                    log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new");
1945                } else if (clazztype.tsym.isStatic()) {
1946                    log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym);
1947                }
1948            }
1949        } else if (!clazztype.tsym.isInterface() &&
1950                   clazztype.getEnclosingType().hasTag(CLASS)) {
1951            // Check for the existence of an apropos outer instance
1952            rs.resolveImplicitThis(tree.pos(), env, clazztype);
1953        }
1954
1955        // Attribute constructor arguments.
1956        ListBuffer<Type> argtypesBuf = new ListBuffer<>();
1957        final KindSelector pkind =
1958            attribArgs(KindSelector.VAL, tree.args, localEnv, argtypesBuf);
1959        List<Type> argtypes = argtypesBuf.toList();
1960        List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
1961
1962        // If we have made no mistakes in the class type...
1963        if (clazztype.hasTag(CLASS)) {
1964            // Enums may not be instantiated except implicitly
1965            if ((clazztype.tsym.flags_field & Flags.ENUM) != 0 &&
1966                (!env.tree.hasTag(VARDEF) ||
1967                 (((JCVariableDecl) env.tree).mods.flags & Flags.ENUM) == 0 ||
1968                 ((JCVariableDecl) env.tree).init != tree))
1969                log.error(tree.pos(), "enum.cant.be.instantiated");
1970            // Check that class is not abstract
1971            if (cdef == null &&
1972                (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
1973                log.error(tree.pos(), "abstract.cant.be.instantiated",
1974                          clazztype.tsym);
1975            } else if (cdef != null && clazztype.tsym.isInterface()) {
1976                // Check that no constructor arguments are given to
1977                // anonymous classes implementing an interface
1978                if (!argtypes.isEmpty())
1979                    log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args");
1980
1981                if (!typeargtypes.isEmpty())
1982                    log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs");
1983
1984                // Error recovery: pretend no arguments were supplied.
1985                argtypes = List.nil();
1986                typeargtypes = List.nil();
1987            } else if (TreeInfo.isDiamond(tree)) {
1988                ClassType site = new ClassType(clazztype.getEnclosingType(),
1989                            clazztype.tsym.type.getTypeArguments(),
1990                                               clazztype.tsym,
1991                                               clazztype.getMetadata());
1992
1993                Env<AttrContext> diamondEnv = localEnv.dup(tree);
1994                diamondEnv.info.selectSuper = cdef != null;
1995                diamondEnv.info.pendingResolutionPhase = null;
1996
1997                //if the type of the instance creation expression is a class type
1998                //apply method resolution inference (JLS 15.12.2.7). The return type
1999                //of the resolved constructor will be a partially instantiated type
2000                Symbol constructor = rs.resolveDiamond(tree.pos(),
2001                            diamondEnv,
2002                            site,
2003                            argtypes,
2004                            typeargtypes);
2005                tree.constructor = constructor.baseSymbol();
2006
2007                final TypeSymbol csym = clazztype.tsym;
2008                ResultInfo diamondResult = new ResultInfo(pkind, newMethodTemplate(resultInfo.pt, argtypes, typeargtypes), new Check.NestedCheckContext(resultInfo.checkContext) {
2009                    @Override
2010                    public void report(DiagnosticPosition _unused, JCDiagnostic details) {
2011                        enclosingContext.report(tree.clazz,
2012                                diags.fragment("cant.apply.diamond.1", diags.fragment("diamond", csym), details));
2013                    }
2014                });
2015                Type constructorType = tree.constructorType = types.createErrorType(clazztype);
2016                constructorType = checkId(noCheckTree, site,
2017                        constructor,
2018                        diamondEnv,
2019                        diamondResult);
2020
2021                tree.clazz.type = types.createErrorType(clazztype);
2022                if (!constructorType.isErroneous()) {
2023                    tree.clazz.type = clazztype = constructorType.getReturnType();
2024                    tree.constructorType = types.createMethodTypeWithReturn(constructorType, syms.voidType);
2025                }
2026                clazztype = chk.checkClassType(tree.clazz, tree.clazz.type, true);
2027            }
2028
2029            // Resolve the called constructor under the assumption
2030            // that we are referring to a superclass instance of the
2031            // current instance (JLS ???).
2032            else {
2033                //the following code alters some of the fields in the current
2034                //AttrContext - hence, the current context must be dup'ed in
2035                //order to avoid downstream failures
2036                Env<AttrContext> rsEnv = localEnv.dup(tree);
2037                rsEnv.info.selectSuper = cdef != null;
2038                rsEnv.info.pendingResolutionPhase = null;
2039                tree.constructor = rs.resolveConstructor(
2040                    tree.pos(), rsEnv, clazztype, argtypes, typeargtypes);
2041                if (cdef == null) { //do not check twice!
2042                    tree.constructorType = checkId(noCheckTree,
2043                            clazztype,
2044                            tree.constructor,
2045                            rsEnv,
2046                            new ResultInfo(pkind, newMethodTemplate(syms.voidType, argtypes, typeargtypes)));
2047                    if (rsEnv.info.lastResolveVarargs())
2048                        Assert.check(tree.constructorType.isErroneous() || tree.varargsElement != null);
2049                }
2050            }
2051
2052            if (cdef != null) {
2053                // We are seeing an anonymous class instance creation.
2054                // In this case, the class instance creation
2055                // expression
2056                //
2057                //    E.new <typeargs1>C<typargs2>(args) { ... }
2058                //
2059                // is represented internally as
2060                //
2061                //    E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } )  .
2062                //
2063                // This expression is then *transformed* as follows:
2064                //
2065                // (1) add an extends or implements clause
2066                // (2) add a constructor.
2067                //
2068                // For instance, if C is a class, and ET is the type of E,
2069                // the expression
2070                //
2071                //    E.new <typeargs1>C<typargs2>(args) { ... }
2072                //
2073                // is translated to (where X is a fresh name and typarams is the
2074                // parameter list of the super constructor):
2075                //
2076                //   new <typeargs1>X(<*nullchk*>E, args) where
2077                //     X extends C<typargs2> {
2078                //       <typarams> X(ET e, args) {
2079                //         e.<typeargs1>super(args)
2080                //       }
2081                //       ...
2082                //     }
2083
2084                if (clazztype.tsym.isInterface()) {
2085                    cdef.implementing = List.of(clazz);
2086                } else {
2087                    cdef.extending = clazz;
2088                }
2089
2090                if (resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
2091                    isSerializable(clazztype)) {
2092                    localEnv.info.isSerializable = true;
2093                }
2094
2095                attribStat(cdef, localEnv);
2096
2097                // If an outer instance is given,
2098                // prefix it to the constructor arguments
2099                // and delete it from the new expression
2100                if (tree.encl != null && !clazztype.tsym.isInterface()) {
2101                    tree.args = tree.args.prepend(makeNullCheck(tree.encl));
2102                    argtypes = argtypes.prepend(tree.encl.type);
2103                    tree.encl = null;
2104                }
2105
2106                // Reassign clazztype and recompute constructor.
2107                clazztype = cdef.sym.type;
2108                Symbol sym = tree.constructor = rs.resolveConstructor(
2109                    tree.pos(), localEnv, clazztype, argtypes, typeargtypes);
2110                Assert.check(!sym.kind.isOverloadError());
2111                tree.constructor = sym;
2112                tree.constructorType = checkId(noCheckTree,
2113                    clazztype,
2114                    tree.constructor,
2115                    localEnv,
2116                    new ResultInfo(pkind, newMethodTemplate(syms.voidType, argtypes, typeargtypes)));
2117            }
2118
2119            if (tree.constructor != null && tree.constructor.kind == MTH)
2120                owntype = clazztype;
2121        }
2122        result = check(tree, owntype, KindSelector.VAL, resultInfo);
2123        InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
2124        if (tree.constructorType != null && inferenceContext.free(tree.constructorType)) {
2125            //we need to wait for inference to finish and then replace inference vars in the constructor type
2126            inferenceContext.addFreeTypeListener(List.of(tree.constructorType),
2127                    instantiatedContext -> {
2128                        tree.constructorType = instantiatedContext.asInstType(tree.constructorType);
2129                    });
2130        }
2131        chk.validate(tree.typeargs, localEnv);
2132    }
2133
2134    /** Make an attributed null check tree.
2135     */
2136    public JCExpression makeNullCheck(JCExpression arg) {
2137        // optimization: X.this is never null; skip null check
2138        Name name = TreeInfo.name(arg);
2139        if (name == names._this || name == names._super) return arg;
2140
2141        JCTree.Tag optag = NULLCHK;
2142        JCUnary tree = make.at(arg.pos).Unary(optag, arg);
2143        tree.operator = operators.resolveUnary(arg, optag, arg.type);
2144        tree.type = arg.type;
2145        return tree;
2146    }
2147
2148    public void visitNewArray(JCNewArray tree) {
2149        Type owntype = types.createErrorType(tree.type);
2150        Env<AttrContext> localEnv = env.dup(tree);
2151        Type elemtype;
2152        if (tree.elemtype != null) {
2153            elemtype = attribType(tree.elemtype, localEnv);
2154            chk.validate(tree.elemtype, localEnv);
2155            owntype = elemtype;
2156            for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
2157                attribExpr(l.head, localEnv, syms.intType);
2158                owntype = new ArrayType(owntype, syms.arrayClass);
2159            }
2160        } else {
2161            // we are seeing an untyped aggregate { ... }
2162            // this is allowed only if the prototype is an array
2163            if (pt().hasTag(ARRAY)) {
2164                elemtype = types.elemtype(pt());
2165            } else {
2166                if (!pt().hasTag(ERROR)) {
2167                    log.error(tree.pos(), "illegal.initializer.for.type",
2168                              pt());
2169                }
2170                elemtype = types.createErrorType(pt());
2171            }
2172        }
2173        if (tree.elems != null) {
2174            attribExprs(tree.elems, localEnv, elemtype);
2175            owntype = new ArrayType(elemtype, syms.arrayClass);
2176        }
2177        if (!types.isReifiable(elemtype))
2178            log.error(tree.pos(), "generic.array.creation");
2179        result = check(tree, owntype, KindSelector.VAL, resultInfo);
2180    }
2181
2182    /*
2183     * A lambda expression can only be attributed when a target-type is available.
2184     * In addition, if the target-type is that of a functional interface whose
2185     * descriptor contains inference variables in argument position the lambda expression
2186     * is 'stuck' (see DeferredAttr).
2187     */
2188    @Override
2189    public void visitLambda(final JCLambda that) {
2190        if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
2191            if (pt().hasTag(NONE)) {
2192                //lambda only allowed in assignment or method invocation/cast context
2193                log.error(that.pos(), "unexpected.lambda");
2194            }
2195            result = that.type = types.createErrorType(pt());
2196            return;
2197        }
2198        //create an environment for attribution of the lambda expression
2199        final Env<AttrContext> localEnv = lambdaEnv(that, env);
2200        boolean needsRecovery =
2201                resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK;
2202        try {
2203            Type currentTarget = pt();
2204            if (needsRecovery && isSerializable(currentTarget)) {
2205                localEnv.info.isSerializable = true;
2206            }
2207            List<Type> explicitParamTypes = null;
2208            if (that.paramKind == JCLambda.ParameterKind.EXPLICIT) {
2209                //attribute lambda parameters
2210                attribStats(that.params, localEnv);
2211                explicitParamTypes = TreeInfo.types(that.params);
2212            }
2213
2214            Type lambdaType;
2215            if (pt() != Type.recoveryType) {
2216                /* We need to adjust the target. If the target is an
2217                 * intersection type, for example: SAM & I1 & I2 ...
2218                 * the target will be updated to SAM
2219                 */
2220                currentTarget = targetChecker.visit(currentTarget, that);
2221                if (explicitParamTypes != null) {
2222                    currentTarget = infer.instantiateFunctionalInterface(that,
2223                            currentTarget, explicitParamTypes, resultInfo.checkContext);
2224                }
2225                currentTarget = types.removeWildcards(currentTarget);
2226                lambdaType = types.findDescriptorType(currentTarget);
2227            } else {
2228                currentTarget = Type.recoveryType;
2229                lambdaType = fallbackDescriptorType(that);
2230            }
2231
2232            setFunctionalInfo(localEnv, that, pt(), lambdaType, currentTarget, resultInfo.checkContext);
2233
2234            if (lambdaType.hasTag(FORALL)) {
2235                //lambda expression target desc cannot be a generic method
2236                resultInfo.checkContext.report(that, diags.fragment("invalid.generic.lambda.target",
2237                        lambdaType, kindName(currentTarget.tsym), currentTarget.tsym));
2238                result = that.type = types.createErrorType(pt());
2239                return;
2240            }
2241
2242            if (that.paramKind == JCLambda.ParameterKind.IMPLICIT) {
2243                //add param type info in the AST
2244                List<Type> actuals = lambdaType.getParameterTypes();
2245                List<JCVariableDecl> params = that.params;
2246
2247                boolean arityMismatch = false;
2248
2249                while (params.nonEmpty()) {
2250                    if (actuals.isEmpty()) {
2251                        //not enough actuals to perform lambda parameter inference
2252                        arityMismatch = true;
2253                    }
2254                    //reset previously set info
2255                    Type argType = arityMismatch ?
2256                            syms.errType :
2257                            actuals.head;
2258                    params.head.vartype = make.at(params.head).Type(argType);
2259                    params.head.sym = null;
2260                    actuals = actuals.isEmpty() ?
2261                            actuals :
2262                            actuals.tail;
2263                    params = params.tail;
2264                }
2265
2266                //attribute lambda parameters
2267                attribStats(that.params, localEnv);
2268
2269                if (arityMismatch) {
2270                    resultInfo.checkContext.report(that, diags.fragment("incompatible.arg.types.in.lambda"));
2271                        result = that.type = types.createErrorType(currentTarget);
2272                        return;
2273                }
2274            }
2275
2276            //from this point on, no recovery is needed; if we are in assignment context
2277            //we will be able to attribute the whole lambda body, regardless of errors;
2278            //if we are in a 'check' method context, and the lambda is not compatible
2279            //with the target-type, it will be recovered anyway in Attr.checkId
2280            needsRecovery = false;
2281
2282            FunctionalReturnContext funcContext = that.getBodyKind() == JCLambda.BodyKind.EXPRESSION ?
2283                    new ExpressionLambdaReturnContext((JCExpression)that.getBody(), resultInfo.checkContext) :
2284                    new FunctionalReturnContext(resultInfo.checkContext);
2285
2286            ResultInfo bodyResultInfo = lambdaType.getReturnType() == Type.recoveryType ?
2287                recoveryInfo :
2288                new ResultInfo(KindSelector.VAL,
2289                               lambdaType.getReturnType(), funcContext);
2290            localEnv.info.returnResult = bodyResultInfo;
2291
2292            if (that.getBodyKind() == JCLambda.BodyKind.EXPRESSION) {
2293                attribTree(that.getBody(), localEnv, bodyResultInfo);
2294            } else {
2295                JCBlock body = (JCBlock)that.body;
2296                attribStats(body.stats, localEnv);
2297            }
2298
2299            result = check(that, currentTarget, KindSelector.VAL, resultInfo);
2300
2301            boolean isSpeculativeRound =
2302                    resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
2303
2304            preFlow(that);
2305            flow.analyzeLambda(env, that, make, isSpeculativeRound);
2306
2307            that.type = currentTarget; //avoids recovery at this stage
2308            checkLambdaCompatible(that, lambdaType, resultInfo.checkContext);
2309
2310            if (!isSpeculativeRound) {
2311                //add thrown types as bounds to the thrown types free variables if needed:
2312                if (resultInfo.checkContext.inferenceContext().free(lambdaType.getThrownTypes())) {
2313                    List<Type> inferredThrownTypes = flow.analyzeLambdaThrownTypes(env, that, make);
2314                    List<Type> thrownTypes = resultInfo.checkContext.inferenceContext().asUndetVars(lambdaType.getThrownTypes());
2315
2316                    chk.unhandled(inferredThrownTypes, thrownTypes);
2317                }
2318
2319                checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), lambdaType, currentTarget);
2320            }
2321            result = check(that, currentTarget, KindSelector.VAL, resultInfo);
2322        } catch (Types.FunctionDescriptorLookupError ex) {
2323            JCDiagnostic cause = ex.getDiagnostic();
2324            resultInfo.checkContext.report(that, cause);
2325            result = that.type = types.createErrorType(pt());
2326            return;
2327        } finally {
2328            localEnv.info.scope.leave();
2329            if (needsRecovery) {
2330                attribTree(that, env, recoveryInfo);
2331            }
2332        }
2333    }
2334    //where
2335        void preFlow(JCLambda tree) {
2336            new PostAttrAnalyzer() {
2337                @Override
2338                public void scan(JCTree tree) {
2339                    if (tree == null ||
2340                            (tree.type != null &&
2341                            tree.type == Type.stuckType)) {
2342                        //don't touch stuck expressions!
2343                        return;
2344                    }
2345                    super.scan(tree);
2346                }
2347            }.scan(tree);
2348        }
2349
2350        Types.MapVisitor<DiagnosticPosition> targetChecker = new Types.MapVisitor<DiagnosticPosition>() {
2351
2352            @Override
2353            public Type visitClassType(ClassType t, DiagnosticPosition pos) {
2354                return t.isIntersection() ?
2355                        visitIntersectionClassType((IntersectionClassType)t, pos) : t;
2356            }
2357
2358            public Type visitIntersectionClassType(IntersectionClassType ict, DiagnosticPosition pos) {
2359                Symbol desc = types.findDescriptorSymbol(makeNotionalInterface(ict));
2360                Type target = null;
2361                for (Type bound : ict.getExplicitComponents()) {
2362                    TypeSymbol boundSym = bound.tsym;
2363                    if (types.isFunctionalInterface(boundSym) &&
2364                            types.findDescriptorSymbol(boundSym) == desc) {
2365                        target = bound;
2366                    } else if (!boundSym.isInterface() || (boundSym.flags() & ANNOTATION) != 0) {
2367                        //bound must be an interface
2368                        reportIntersectionError(pos, "not.an.intf.component", boundSym);
2369                    }
2370                }
2371                return target != null ?
2372                        target :
2373                        ict.getExplicitComponents().head; //error recovery
2374            }
2375
2376            private TypeSymbol makeNotionalInterface(IntersectionClassType ict) {
2377                ListBuffer<Type> targs = new ListBuffer<>();
2378                ListBuffer<Type> supertypes = new ListBuffer<>();
2379                for (Type i : ict.interfaces_field) {
2380                    if (i.isParameterized()) {
2381                        targs.appendList(i.tsym.type.allparams());
2382                    }
2383                    supertypes.append(i.tsym.type);
2384                }
2385                IntersectionClassType notionalIntf = types.makeIntersectionType(supertypes.toList());
2386                notionalIntf.allparams_field = targs.toList();
2387                notionalIntf.tsym.flags_field |= INTERFACE;
2388                return notionalIntf.tsym;
2389            }
2390
2391            private void reportIntersectionError(DiagnosticPosition pos, String key, Object... args) {
2392                resultInfo.checkContext.report(pos, diags.fragment("bad.intersection.target.for.functional.expr",
2393                        diags.fragment(key, args)));
2394            }
2395        };
2396
2397        private Type fallbackDescriptorType(JCExpression tree) {
2398            switch (tree.getTag()) {
2399                case LAMBDA:
2400                    JCLambda lambda = (JCLambda)tree;
2401                    List<Type> argtypes = List.nil();
2402                    for (JCVariableDecl param : lambda.params) {
2403                        argtypes = param.vartype != null ?
2404                                argtypes.append(param.vartype.type) :
2405                                argtypes.append(syms.errType);
2406                    }
2407                    return new MethodType(argtypes, Type.recoveryType,
2408                            List.of(syms.throwableType), syms.methodClass);
2409                case REFERENCE:
2410                    return new MethodType(List.<Type>nil(), Type.recoveryType,
2411                            List.of(syms.throwableType), syms.methodClass);
2412                default:
2413                    Assert.error("Cannot get here!");
2414            }
2415            return null;
2416        }
2417
2418        private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
2419                final InferenceContext inferenceContext, final Type... ts) {
2420            checkAccessibleTypes(pos, env, inferenceContext, List.from(ts));
2421        }
2422
2423        private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
2424                final InferenceContext inferenceContext, final List<Type> ts) {
2425            if (inferenceContext.free(ts)) {
2426                inferenceContext.addFreeTypeListener(ts, new FreeTypeListener() {
2427                    @Override
2428                    public void typesInferred(InferenceContext inferenceContext) {
2429                        checkAccessibleTypes(pos, env, inferenceContext, inferenceContext.asInstTypes(ts));
2430                    }
2431                });
2432            } else {
2433                for (Type t : ts) {
2434                    rs.checkAccessibleType(env, t);
2435                }
2436            }
2437        }
2438
2439        /**
2440         * Lambda/method reference have a special check context that ensures
2441         * that i.e. a lambda return type is compatible with the expected
2442         * type according to both the inherited context and the assignment
2443         * context.
2444         */
2445        class FunctionalReturnContext extends Check.NestedCheckContext {
2446
2447            FunctionalReturnContext(CheckContext enclosingContext) {
2448                super(enclosingContext);
2449            }
2450
2451            @Override
2452            public boolean compatible(Type found, Type req, Warner warn) {
2453                //return type must be compatible in both current context and assignment context
2454                return chk.basicHandler.compatible(found, inferenceContext().asUndetVar(req), warn);
2455            }
2456
2457            @Override
2458            public void report(DiagnosticPosition pos, JCDiagnostic details) {
2459                enclosingContext.report(pos, diags.fragment("incompatible.ret.type.in.lambda", details));
2460            }
2461        }
2462
2463        class ExpressionLambdaReturnContext extends FunctionalReturnContext {
2464
2465            JCExpression expr;
2466
2467            ExpressionLambdaReturnContext(JCExpression expr, CheckContext enclosingContext) {
2468                super(enclosingContext);
2469                this.expr = expr;
2470            }
2471
2472            @Override
2473            public boolean compatible(Type found, Type req, Warner warn) {
2474                //a void return is compatible with an expression statement lambda
2475                return TreeInfo.isExpressionStatement(expr) && req.hasTag(VOID) ||
2476                        super.compatible(found, req, warn);
2477            }
2478        }
2479
2480        /**
2481        * Lambda compatibility. Check that given return types, thrown types, parameter types
2482        * are compatible with the expected functional interface descriptor. This means that:
2483        * (i) parameter types must be identical to those of the target descriptor; (ii) return
2484        * types must be compatible with the return type of the expected descriptor.
2485        */
2486        private void checkLambdaCompatible(JCLambda tree, Type descriptor, CheckContext checkContext) {
2487            Type returnType = checkContext.inferenceContext().asUndetVar(descriptor.getReturnType());
2488
2489            //return values have already been checked - but if lambda has no return
2490            //values, we must ensure that void/value compatibility is correct;
2491            //this amounts at checking that, if a lambda body can complete normally,
2492            //the descriptor's return type must be void
2493            if (tree.getBodyKind() == JCLambda.BodyKind.STATEMENT && tree.canCompleteNormally &&
2494                    !returnType.hasTag(VOID) && returnType != Type.recoveryType) {
2495                checkContext.report(tree, diags.fragment("incompatible.ret.type.in.lambda",
2496                        diags.fragment("missing.ret.val", returnType)));
2497            }
2498
2499            List<Type> argTypes = checkContext.inferenceContext().asUndetVars(descriptor.getParameterTypes());
2500            if (!types.isSameTypes(argTypes, TreeInfo.types(tree.params))) {
2501                checkContext.report(tree, diags.fragment("incompatible.arg.types.in.lambda"));
2502            }
2503        }
2504
2505        /* Map to hold 'fake' clinit methods. If a lambda is used to initialize a
2506         * static field and that lambda has type annotations, these annotations will
2507         * also be stored at these fake clinit methods.
2508         *
2509         * LambdaToMethod also use fake clinit methods so they can be reused.
2510         * Also as LTM is a phase subsequent to attribution, the methods from
2511         * clinits can be safely removed by LTM to save memory.
2512         */
2513        private Map<ClassSymbol, MethodSymbol> clinits = new HashMap<>();
2514
2515        public MethodSymbol removeClinit(ClassSymbol sym) {
2516            return clinits.remove(sym);
2517        }
2518
2519        /* This method returns an environment to be used to attribute a lambda
2520         * expression.
2521         *
2522         * The owner of this environment is a method symbol. If the current owner
2523         * is not a method, for example if the lambda is used to initialize
2524         * a field, then if the field is:
2525         *
2526         * - an instance field, we use the first constructor.
2527         * - a static field, we create a fake clinit method.
2528         */
2529        public Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) {
2530            Env<AttrContext> lambdaEnv;
2531            Symbol owner = env.info.scope.owner;
2532            if (owner.kind == VAR && owner.owner.kind == TYP) {
2533                //field initializer
2534                ClassSymbol enclClass = owner.enclClass();
2535                Symbol newScopeOwner = env.info.scope.owner;
2536                /* if the field isn't static, then we can get the first constructor
2537                 * and use it as the owner of the environment. This is what
2538                 * LTM code is doing to look for type annotations so we are fine.
2539                 */
2540                if ((owner.flags() & STATIC) == 0) {
2541                    for (Symbol s : enclClass.members_field.getSymbolsByName(names.init)) {
2542                        newScopeOwner = s;
2543                        break;
2544                    }
2545                } else {
2546                    /* if the field is static then we need to create a fake clinit
2547                     * method, this method can later be reused by LTM.
2548                     */
2549                    MethodSymbol clinit = clinits.get(enclClass);
2550                    if (clinit == null) {
2551                        Type clinitType = new MethodType(List.<Type>nil(),
2552                                syms.voidType, List.<Type>nil(), syms.methodClass);
2553                        clinit = new MethodSymbol(STATIC | SYNTHETIC | PRIVATE,
2554                                names.clinit, clinitType, enclClass);
2555                        clinit.params = List.<VarSymbol>nil();
2556                        clinits.put(enclClass, clinit);
2557                    }
2558                    newScopeOwner = clinit;
2559                }
2560                lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared(newScopeOwner)));
2561            } else {
2562                lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dup()));
2563            }
2564            return lambdaEnv;
2565        }
2566
2567    @Override
2568    public void visitReference(final JCMemberReference that) {
2569        if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
2570            if (pt().hasTag(NONE)) {
2571                //method reference only allowed in assignment or method invocation/cast context
2572                log.error(that.pos(), "unexpected.mref");
2573            }
2574            result = that.type = types.createErrorType(pt());
2575            return;
2576        }
2577        final Env<AttrContext> localEnv = env.dup(that);
2578        try {
2579            //attribute member reference qualifier - if this is a constructor
2580            //reference, the expected kind must be a type
2581            Type exprType = attribTree(that.expr, env, memberReferenceQualifierResult(that));
2582
2583            if (that.getMode() == JCMemberReference.ReferenceMode.NEW) {
2584                exprType = chk.checkConstructorRefType(that.expr, exprType);
2585                if (!exprType.isErroneous() &&
2586                    exprType.isRaw() &&
2587                    that.typeargs != null) {
2588                    log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
2589                        diags.fragment("mref.infer.and.explicit.params"));
2590                    exprType = types.createErrorType(exprType);
2591                }
2592            }
2593
2594            if (exprType.isErroneous()) {
2595                //if the qualifier expression contains problems,
2596                //give up attribution of method reference
2597                result = that.type = exprType;
2598                return;
2599            }
2600
2601            if (TreeInfo.isStaticSelector(that.expr, names)) {
2602                //if the qualifier is a type, validate it; raw warning check is
2603                //omitted as we don't know at this stage as to whether this is a
2604                //raw selector (because of inference)
2605                chk.validate(that.expr, env, false);
2606            }
2607
2608            //attrib type-arguments
2609            List<Type> typeargtypes = List.nil();
2610            if (that.typeargs != null) {
2611                typeargtypes = attribTypes(that.typeargs, localEnv);
2612            }
2613
2614            Type desc;
2615            Type currentTarget = pt();
2616            boolean isTargetSerializable =
2617                    resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
2618                    isSerializable(currentTarget);
2619            if (currentTarget != Type.recoveryType) {
2620                currentTarget = types.removeWildcards(targetChecker.visit(currentTarget, that));
2621                desc = types.findDescriptorType(currentTarget);
2622            } else {
2623                currentTarget = Type.recoveryType;
2624                desc = fallbackDescriptorType(that);
2625            }
2626
2627            setFunctionalInfo(localEnv, that, pt(), desc, currentTarget, resultInfo.checkContext);
2628            List<Type> argtypes = desc.getParameterTypes();
2629            Resolve.MethodCheck referenceCheck = rs.resolveMethodCheck;
2630
2631            if (resultInfo.checkContext.inferenceContext().free(argtypes)) {
2632                referenceCheck = rs.new MethodReferenceCheck(resultInfo.checkContext.inferenceContext());
2633            }
2634
2635            Pair<Symbol, Resolve.ReferenceLookupHelper> refResult = null;
2636            List<Type> saved_undet = resultInfo.checkContext.inferenceContext().save();
2637            try {
2638                refResult = rs.resolveMemberReference(localEnv, that, that.expr.type,
2639                        that.name, argtypes, typeargtypes, referenceCheck,
2640                        resultInfo.checkContext.inferenceContext(), rs.basicReferenceChooser);
2641            } finally {
2642                resultInfo.checkContext.inferenceContext().rollback(saved_undet);
2643            }
2644
2645            Symbol refSym = refResult.fst;
2646            Resolve.ReferenceLookupHelper lookupHelper = refResult.snd;
2647
2648            if (refSym.kind != MTH) {
2649                boolean targetError;
2650                switch (refSym.kind) {
2651                    case ABSENT_MTH:
2652                        targetError = false;
2653                        break;
2654                    case WRONG_MTH:
2655                    case WRONG_MTHS:
2656                    case AMBIGUOUS:
2657                    case HIDDEN:
2658                    case MISSING_ENCL:
2659                    case STATICERR:
2660                        targetError = true;
2661                        break;
2662                    default:
2663                        Assert.error("unexpected result kind " + refSym.kind);
2664                        targetError = false;
2665                }
2666
2667                JCDiagnostic detailsDiag = ((Resolve.ResolveError)refSym.baseSymbol()).getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT,
2668                                that, exprType.tsym, exprType, that.name, argtypes, typeargtypes);
2669
2670                JCDiagnostic.DiagnosticType diagKind = targetError ?
2671                        JCDiagnostic.DiagnosticType.FRAGMENT : JCDiagnostic.DiagnosticType.ERROR;
2672
2673                JCDiagnostic diag = diags.create(diagKind, log.currentSource(), that,
2674                        "invalid.mref", Kinds.kindName(that.getMode()), detailsDiag);
2675
2676                if (targetError && currentTarget == Type.recoveryType) {
2677                    //a target error doesn't make sense during recovery stage
2678                    //as we don't know what actual parameter types are
2679                    result = that.type = currentTarget;
2680                    return;
2681                } else {
2682                    if (targetError) {
2683                        resultInfo.checkContext.report(that, diag);
2684                    } else {
2685                        log.report(diag);
2686                    }
2687                    result = that.type = types.createErrorType(currentTarget);
2688                    return;
2689                }
2690            }
2691
2692            that.sym = refSym.baseSymbol();
2693            that.kind = lookupHelper.referenceKind(that.sym);
2694            that.ownerAccessible = rs.isAccessible(localEnv, that.sym.enclClass());
2695
2696            if (desc.getReturnType() == Type.recoveryType) {
2697                // stop here
2698                result = that.type = currentTarget;
2699                return;
2700            }
2701
2702            if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
2703
2704                if (that.getMode() == ReferenceMode.INVOKE &&
2705                        TreeInfo.isStaticSelector(that.expr, names) &&
2706                        that.kind.isUnbound() &&
2707                        !desc.getParameterTypes().head.isParameterized()) {
2708                    chk.checkRaw(that.expr, localEnv);
2709                }
2710
2711                if (that.sym.isStatic() && TreeInfo.isStaticSelector(that.expr, names) &&
2712                        exprType.getTypeArguments().nonEmpty()) {
2713                    //static ref with class type-args
2714                    log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
2715                            diags.fragment("static.mref.with.targs"));
2716                    result = that.type = types.createErrorType(currentTarget);
2717                    return;
2718                }
2719
2720                if (!refSym.isStatic() && that.kind == JCMemberReference.ReferenceKind.SUPER) {
2721                    // Check that super-qualified symbols are not abstract (JLS)
2722                    rs.checkNonAbstract(that.pos(), that.sym);
2723                }
2724
2725                if (isTargetSerializable) {
2726                    chk.checkElemAccessFromSerializableLambda(that);
2727                }
2728            }
2729
2730            ResultInfo checkInfo =
2731                    resultInfo.dup(newMethodTemplate(
2732                        desc.getReturnType().hasTag(VOID) ? Type.noType : desc.getReturnType(),
2733                        that.kind.isUnbound() ? argtypes.tail : argtypes, typeargtypes),
2734                        new FunctionalReturnContext(resultInfo.checkContext));
2735
2736            Type refType = checkId(noCheckTree, lookupHelper.site, refSym, localEnv, checkInfo);
2737
2738            if (that.kind.isUnbound() &&
2739                    resultInfo.checkContext.inferenceContext().free(argtypes.head)) {
2740                //re-generate inference constraints for unbound receiver
2741                if (!types.isSubtype(resultInfo.checkContext.inferenceContext().asUndetVar(argtypes.head), exprType)) {
2742                    //cannot happen as this has already been checked - we just need
2743                    //to regenerate the inference constraints, as that has been lost
2744                    //as a result of the call to inferenceContext.save()
2745                    Assert.error("Can't get here");
2746                }
2747            }
2748
2749            if (!refType.isErroneous()) {
2750                refType = types.createMethodTypeWithReturn(refType,
2751                        adjustMethodReturnType(lookupHelper.site, that.name, checkInfo.pt.getParameterTypes(), refType.getReturnType()));
2752            }
2753
2754            //go ahead with standard method reference compatibility check - note that param check
2755            //is a no-op (as this has been taken care during method applicability)
2756            boolean isSpeculativeRound =
2757                    resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
2758
2759            that.type = currentTarget; //avoids recovery at this stage
2760            checkReferenceCompatible(that, desc, refType, resultInfo.checkContext, isSpeculativeRound);
2761            if (!isSpeculativeRound) {
2762                checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), desc, currentTarget);
2763            }
2764            result = check(that, currentTarget, KindSelector.VAL, resultInfo);
2765        } catch (Types.FunctionDescriptorLookupError ex) {
2766            JCDiagnostic cause = ex.getDiagnostic();
2767            resultInfo.checkContext.report(that, cause);
2768            result = that.type = types.createErrorType(pt());
2769            return;
2770        }
2771    }
2772    //where
2773        ResultInfo memberReferenceQualifierResult(JCMemberReference tree) {
2774            //if this is a constructor reference, the expected kind must be a type
2775            return new ResultInfo(tree.getMode() == ReferenceMode.INVOKE ?
2776                                  KindSelector.VAL_TYP : KindSelector.TYP,
2777                                  Type.noType);
2778        }
2779
2780
2781    @SuppressWarnings("fallthrough")
2782    void checkReferenceCompatible(JCMemberReference tree, Type descriptor, Type refType, CheckContext checkContext, boolean speculativeAttr) {
2783        InferenceContext inferenceContext = checkContext.inferenceContext();
2784        Type returnType = inferenceContext.asUndetVar(descriptor.getReturnType());
2785
2786        Type resType;
2787        switch (tree.getMode()) {
2788            case NEW:
2789                if (!tree.expr.type.isRaw()) {
2790                    resType = tree.expr.type;
2791                    break;
2792                }
2793            default:
2794                resType = refType.getReturnType();
2795        }
2796
2797        Type incompatibleReturnType = resType;
2798
2799        if (returnType.hasTag(VOID)) {
2800            incompatibleReturnType = null;
2801        }
2802
2803        if (!returnType.hasTag(VOID) && !resType.hasTag(VOID)) {
2804            if (resType.isErroneous() ||
2805                    new FunctionalReturnContext(checkContext).compatible(resType, returnType, types.noWarnings)) {
2806                incompatibleReturnType = null;
2807            }
2808        }
2809
2810        if (incompatibleReturnType != null) {
2811            checkContext.report(tree, diags.fragment("incompatible.ret.type.in.mref",
2812                    diags.fragment("inconvertible.types", resType, descriptor.getReturnType())));
2813        } else {
2814            if (inferenceContext.free(refType)) {
2815                // we need to wait for inference to finish and then replace inference vars in the referent type
2816                inferenceContext.addFreeTypeListener(List.of(refType),
2817                        instantiatedContext -> {
2818                            tree.referentType = instantiatedContext.asInstType(refType);
2819                        });
2820            } else {
2821                tree.referentType = refType;
2822            }
2823        }
2824
2825        if (!speculativeAttr) {
2826            List<Type> thrownTypes = inferenceContext.asUndetVars(descriptor.getThrownTypes());
2827            if (chk.unhandled(refType.getThrownTypes(), thrownTypes).nonEmpty()) {
2828                log.error(tree, "incompatible.thrown.types.in.mref", refType.getThrownTypes());
2829            }
2830        }
2831    }
2832
2833    /**
2834     * Set functional type info on the underlying AST. Note: as the target descriptor
2835     * might contain inference variables, we might need to register an hook in the
2836     * current inference context.
2837     */
2838    private void setFunctionalInfo(final Env<AttrContext> env, final JCFunctionalExpression fExpr,
2839            final Type pt, final Type descriptorType, final Type primaryTarget, final CheckContext checkContext) {
2840        if (checkContext.inferenceContext().free(descriptorType)) {
2841            checkContext.inferenceContext().addFreeTypeListener(List.of(pt, descriptorType), new FreeTypeListener() {
2842                public void typesInferred(InferenceContext inferenceContext) {
2843                    setFunctionalInfo(env, fExpr, pt, inferenceContext.asInstType(descriptorType),
2844                            inferenceContext.asInstType(primaryTarget), checkContext);
2845                }
2846            });
2847        } else {
2848            ListBuffer<Type> targets = new ListBuffer<>();
2849            if (pt.hasTag(CLASS)) {
2850                if (pt.isCompound()) {
2851                    targets.append(types.removeWildcards(primaryTarget)); //this goes first
2852                    for (Type t : ((IntersectionClassType)pt()).interfaces_field) {
2853                        if (t != primaryTarget) {
2854                            targets.append(types.removeWildcards(t));
2855                        }
2856                    }
2857                } else {
2858                    targets.append(types.removeWildcards(primaryTarget));
2859                }
2860            }
2861            fExpr.targets = targets.toList();
2862            if (checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
2863                    pt != Type.recoveryType) {
2864                //check that functional interface class is well-formed
2865                try {
2866                    /* Types.makeFunctionalInterfaceClass() may throw an exception
2867                     * when it's executed post-inference. See the listener code
2868                     * above.
2869                     */
2870                    ClassSymbol csym = types.makeFunctionalInterfaceClass(env,
2871                            names.empty, List.of(fExpr.targets.head), ABSTRACT);
2872                    if (csym != null) {
2873                        chk.checkImplementations(env.tree, csym, csym);
2874                    }
2875                } catch (Types.FunctionDescriptorLookupError ex) {
2876                    JCDiagnostic cause = ex.getDiagnostic();
2877                    resultInfo.checkContext.report(env.tree, cause);
2878                }
2879            }
2880        }
2881    }
2882
2883    public void visitParens(JCParens tree) {
2884        Type owntype = attribTree(tree.expr, env, resultInfo);
2885        result = check(tree, owntype, pkind(), resultInfo);
2886        Symbol sym = TreeInfo.symbol(tree);
2887        if (sym != null && sym.kind.matches(KindSelector.TYP_PCK))
2888            log.error(tree.pos(), "illegal.start.of.type");
2889    }
2890
2891    public void visitAssign(JCAssign tree) {
2892        Type owntype = attribTree(tree.lhs, env.dup(tree), varAssignmentInfo);
2893        Type capturedType = capture(owntype);
2894        attribExpr(tree.rhs, env, owntype);
2895        result = check(tree, capturedType, KindSelector.VAL, resultInfo);
2896    }
2897
2898    public void visitAssignop(JCAssignOp tree) {
2899        // Attribute arguments.
2900        Type owntype = attribTree(tree.lhs, env, varAssignmentInfo);
2901        Type operand = attribExpr(tree.rhs, env);
2902        // Find operator.
2903        Symbol operator = tree.operator = operators.resolveBinary(tree, tree.getTag().noAssignOp(), owntype, operand);
2904        if (operator.kind == MTH &&
2905                !owntype.isErroneous() &&
2906                !operand.isErroneous()) {
2907            chk.checkDivZero(tree.rhs.pos(), operator, operand);
2908            chk.checkCastable(tree.rhs.pos(),
2909                              operator.type.getReturnType(),
2910                              owntype);
2911        }
2912        result = check(tree, owntype, KindSelector.VAL, resultInfo);
2913    }
2914
2915    public void visitUnary(JCUnary tree) {
2916        // Attribute arguments.
2917        Type argtype = (tree.getTag().isIncOrDecUnaryOp())
2918            ? attribTree(tree.arg, env, varAssignmentInfo)
2919            : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
2920
2921        // Find operator.
2922        Symbol operator = tree.operator = operators.resolveUnary(tree, tree.getTag(), argtype);
2923        Type owntype = types.createErrorType(tree.type);
2924        if (operator.kind == MTH &&
2925                !argtype.isErroneous()) {
2926            owntype = (tree.getTag().isIncOrDecUnaryOp())
2927                ? tree.arg.type
2928                : operator.type.getReturnType();
2929            int opc = ((OperatorSymbol)operator).opcode;
2930
2931            // If the argument is constant, fold it.
2932            if (argtype.constValue() != null) {
2933                Type ctype = cfolder.fold1(opc, argtype);
2934                if (ctype != null) {
2935                    owntype = cfolder.coerce(ctype, owntype);
2936                }
2937            }
2938        }
2939        result = check(tree, owntype, KindSelector.VAL, resultInfo);
2940    }
2941
2942    public void visitBinary(JCBinary tree) {
2943        // Attribute arguments.
2944        Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
2945        Type right = chk.checkNonVoid(tree.rhs.pos(), attribExpr(tree.rhs, env));
2946        // Find operator.
2947        Symbol operator = tree.operator = operators.resolveBinary(tree, tree.getTag(), left, right);
2948        Type owntype = types.createErrorType(tree.type);
2949        if (operator.kind == MTH &&
2950                !left.isErroneous() &&
2951                !right.isErroneous()) {
2952            owntype = operator.type.getReturnType();
2953            int opc = ((OperatorSymbol)operator).opcode;
2954            // If both arguments are constants, fold them.
2955            if (left.constValue() != null && right.constValue() != null) {
2956                Type ctype = cfolder.fold2(opc, left, right);
2957                if (ctype != null) {
2958                    owntype = cfolder.coerce(ctype, owntype);
2959                }
2960            }
2961
2962            // Check that argument types of a reference ==, != are
2963            // castable to each other, (JLS 15.21).  Note: unboxing
2964            // comparisons will not have an acmp* opc at this point.
2965            if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
2966                if (!types.isCastable(left, right, new Warner(tree.pos()))) {
2967                    log.error(tree.pos(), "incomparable.types", left, right);
2968                }
2969            }
2970
2971            chk.checkDivZero(tree.rhs.pos(), operator, right);
2972        }
2973        result = check(tree, owntype, KindSelector.VAL, resultInfo);
2974    }
2975
2976    public void visitTypeCast(final JCTypeCast tree) {
2977        Type clazztype = attribType(tree.clazz, env);
2978        chk.validate(tree.clazz, env, false);
2979        //a fresh environment is required for 292 inference to work properly ---
2980        //see Infer.instantiatePolymorphicSignatureInstance()
2981        Env<AttrContext> localEnv = env.dup(tree);
2982        //should we propagate the target type?
2983        final ResultInfo castInfo;
2984        JCExpression expr = TreeInfo.skipParens(tree.expr);
2985        boolean isPoly = allowPoly && (expr.hasTag(LAMBDA) || expr.hasTag(REFERENCE));
2986        if (isPoly) {
2987            //expression is a poly - we need to propagate target type info
2988            castInfo = new ResultInfo(KindSelector.VAL, clazztype,
2989                                      new Check.NestedCheckContext(resultInfo.checkContext) {
2990                @Override
2991                public boolean compatible(Type found, Type req, Warner warn) {
2992                    return types.isCastable(found, req, warn);
2993                }
2994            });
2995        } else {
2996            //standalone cast - target-type info is not propagated
2997            castInfo = unknownExprInfo;
2998        }
2999        Type exprtype = attribTree(tree.expr, localEnv, castInfo);
3000        Type owntype = isPoly ? clazztype : chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
3001        if (exprtype.constValue() != null)
3002            owntype = cfolder.coerce(exprtype, owntype);
3003        result = check(tree, capture(owntype), KindSelector.VAL, resultInfo);
3004        if (!isPoly)
3005            chk.checkRedundantCast(localEnv, tree);
3006    }
3007
3008    public void visitTypeTest(JCInstanceOf tree) {
3009        Type exprtype = chk.checkNullOrRefType(
3010                tree.expr.pos(), attribExpr(tree.expr, env));
3011        Type clazztype = attribType(tree.clazz, env);
3012        if (!clazztype.hasTag(TYPEVAR)) {
3013            clazztype = chk.checkClassOrArrayType(tree.clazz.pos(), clazztype);
3014        }
3015        if (!clazztype.isErroneous() && !types.isReifiable(clazztype)) {
3016            log.error(tree.clazz.pos(), "illegal.generic.type.for.instof");
3017            clazztype = types.createErrorType(clazztype);
3018        }
3019        chk.validate(tree.clazz, env, false);
3020        chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
3021        result = check(tree, syms.booleanType, KindSelector.VAL, resultInfo);
3022    }
3023
3024    public void visitIndexed(JCArrayAccess tree) {
3025        Type owntype = types.createErrorType(tree.type);
3026        Type atype = attribExpr(tree.indexed, env);
3027        attribExpr(tree.index, env, syms.intType);
3028        if (types.isArray(atype))
3029            owntype = types.elemtype(atype);
3030        else if (!atype.hasTag(ERROR))
3031            log.error(tree.pos(), "array.req.but.found", atype);
3032        if (!pkind().contains(KindSelector.VAL))
3033            owntype = capture(owntype);
3034        result = check(tree, owntype, KindSelector.VAR, resultInfo);
3035    }
3036
3037    public void visitIdent(JCIdent tree) {
3038        Symbol sym;
3039
3040        // Find symbol
3041        if (pt().hasTag(METHOD) || pt().hasTag(FORALL)) {
3042            // If we are looking for a method, the prototype `pt' will be a
3043            // method type with the type of the call's arguments as parameters.
3044            env.info.pendingResolutionPhase = null;
3045            sym = rs.resolveMethod(tree.pos(), env, tree.name, pt().getParameterTypes(), pt().getTypeArguments());
3046        } else if (tree.sym != null && tree.sym.kind != VAR) {
3047            sym = tree.sym;
3048        } else {
3049            sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind());
3050        }
3051        tree.sym = sym;
3052
3053        // (1) Also find the environment current for the class where
3054        //     sym is defined (`symEnv').
3055        // Only for pre-tiger versions (1.4 and earlier):
3056        // (2) Also determine whether we access symbol out of an anonymous
3057        //     class in a this or super call.  This is illegal for instance
3058        //     members since such classes don't carry a this$n link.
3059        //     (`noOuterThisPath').
3060        Env<AttrContext> symEnv = env;
3061        boolean noOuterThisPath = false;
3062        if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
3063            sym.kind.matches(KindSelector.VAL_MTH) &&
3064            sym.owner.kind == TYP &&
3065            tree.name != names._this && tree.name != names._super) {
3066
3067            // Find environment in which identifier is defined.
3068            while (symEnv.outer != null &&
3069                   !sym.isMemberOf(symEnv.enclClass.sym, types)) {
3070                if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
3071                    noOuterThisPath = false;
3072                symEnv = symEnv.outer;
3073            }
3074        }
3075
3076        // If symbol is a variable, ...
3077        if (sym.kind == VAR) {
3078            VarSymbol v = (VarSymbol)sym;
3079
3080            // ..., evaluate its initializer, if it has one, and check for
3081            // illegal forward reference.
3082            checkInit(tree, env, v, false);
3083
3084            // If we are expecting a variable (as opposed to a value), check
3085            // that the variable is assignable in the current environment.
3086            if (KindSelector.ASG.subset(pkind()))
3087                checkAssignable(tree.pos(), v, null, env);
3088        }
3089
3090        // In a constructor body,
3091        // if symbol is a field or instance method, check that it is
3092        // not accessed before the supertype constructor is called.
3093        if ((symEnv.info.isSelfCall || noOuterThisPath) &&
3094            sym.kind.matches(KindSelector.VAL_MTH) &&
3095            sym.owner.kind == TYP &&
3096            (sym.flags() & STATIC) == 0) {
3097            chk.earlyRefError(tree.pos(), sym.kind == VAR ?
3098                                          sym : thisSym(tree.pos(), env));
3099        }
3100        Env<AttrContext> env1 = env;
3101        if (sym.kind != ERR && sym.kind != TYP &&
3102            sym.owner != null && sym.owner != env1.enclClass.sym) {
3103            // If the found symbol is inaccessible, then it is
3104            // accessed through an enclosing instance.  Locate this
3105            // enclosing instance:
3106            while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
3107                env1 = env1.outer;
3108        }
3109
3110        if (env.info.isSerializable) {
3111            chk.checkElemAccessFromSerializableLambda(tree);
3112        }
3113
3114        result = checkId(tree, env1.enclClass.sym.type, sym, env, resultInfo);
3115    }
3116
3117    public void visitSelect(JCFieldAccess tree) {
3118        // Determine the expected kind of the qualifier expression.
3119        KindSelector skind = KindSelector.NIL;
3120        if (tree.name == names._this || tree.name == names._super ||
3121                tree.name == names._class)
3122        {
3123            skind = KindSelector.TYP;
3124        } else {
3125            if (pkind().contains(KindSelector.PCK))
3126                skind = KindSelector.of(skind, KindSelector.PCK);
3127            if (pkind().contains(KindSelector.TYP))
3128                skind = KindSelector.of(skind, KindSelector.TYP, KindSelector.PCK);
3129            if (pkind().contains(KindSelector.VAL_MTH))
3130                skind = KindSelector.of(skind, KindSelector.VAL, KindSelector.TYP);
3131        }
3132
3133        // Attribute the qualifier expression, and determine its symbol (if any).
3134        Type site = attribTree(tree.selected, env, new ResultInfo(skind, Infer.anyPoly));
3135        if (!pkind().contains(KindSelector.TYP_PCK))
3136            site = capture(site); // Capture field access
3137
3138        // don't allow T.class T[].class, etc
3139        if (skind == KindSelector.TYP) {
3140            Type elt = site;
3141            while (elt.hasTag(ARRAY))
3142                elt = ((ArrayType)elt).elemtype;
3143            if (elt.hasTag(TYPEVAR)) {
3144                log.error(tree.pos(), "type.var.cant.be.deref");
3145                result = tree.type = types.createErrorType(tree.name, site.tsym, site);
3146                tree.sym = tree.type.tsym;
3147                return ;
3148            }
3149        }
3150
3151        // If qualifier symbol is a type or `super', assert `selectSuper'
3152        // for the selection. This is relevant for determining whether
3153        // protected symbols are accessible.
3154        Symbol sitesym = TreeInfo.symbol(tree.selected);
3155        boolean selectSuperPrev = env.info.selectSuper;
3156        env.info.selectSuper =
3157            sitesym != null &&
3158            sitesym.name == names._super;
3159
3160        // Determine the symbol represented by the selection.
3161        env.info.pendingResolutionPhase = null;
3162        Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
3163        if (sym.kind == VAR && sym.name != names._super && env.info.defaultSuperCallSite != null) {
3164            log.error(tree.selected.pos(), "not.encl.class", site.tsym);
3165            sym = syms.errSymbol;
3166        }
3167        if (sym.exists() && !isType(sym) && pkind().contains(KindSelector.TYP_PCK)) {
3168            site = capture(site);
3169            sym = selectSym(tree, sitesym, site, env, resultInfo);
3170        }
3171        boolean varArgs = env.info.lastResolveVarargs();
3172        tree.sym = sym;
3173
3174        if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) {
3175            site = types.skipTypeVars(site, true);
3176        }
3177
3178        // If that symbol is a variable, ...
3179        if (sym.kind == VAR) {
3180            VarSymbol v = (VarSymbol)sym;
3181
3182            // ..., evaluate its initializer, if it has one, and check for
3183            // illegal forward reference.
3184            checkInit(tree, env, v, true);
3185
3186            // If we are expecting a variable (as opposed to a value), check
3187            // that the variable is assignable in the current environment.
3188            if (KindSelector.ASG.subset(pkind()))
3189                checkAssignable(tree.pos(), v, tree.selected, env);
3190        }
3191
3192        if (sitesym != null &&
3193                sitesym.kind == VAR &&
3194                ((VarSymbol)sitesym).isResourceVariable() &&
3195                sym.kind == MTH &&
3196                sym.name.equals(names.close) &&
3197                sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) &&
3198                env.info.lint.isEnabled(LintCategory.TRY)) {
3199            log.warning(LintCategory.TRY, tree, "try.explicit.close.call");
3200        }
3201
3202        // Disallow selecting a type from an expression
3203        if (isType(sym) && (sitesym == null || !sitesym.kind.matches(KindSelector.TYP_PCK))) {
3204            tree.type = check(tree.selected, pt(),
3205                              sitesym == null ?
3206                                      KindSelector.VAL : sitesym.kind.toSelector(),
3207                              new ResultInfo(KindSelector.TYP_PCK, pt()));
3208        }
3209
3210        if (isType(sitesym)) {
3211            if (sym.name == names._this) {
3212                // If `C' is the currently compiled class, check that
3213                // C.this' does not appear in a call to a super(...)
3214                if (env.info.isSelfCall &&
3215                    site.tsym == env.enclClass.sym) {
3216                    chk.earlyRefError(tree.pos(), sym);
3217                }
3218            } else {
3219                // Check if type-qualified fields or methods are static (JLS)
3220                if ((sym.flags() & STATIC) == 0 &&
3221                    !env.next.tree.hasTag(REFERENCE) &&
3222                    sym.name != names._super &&
3223                    (sym.kind == VAR || sym.kind == MTH)) {
3224                    rs.accessBase(rs.new StaticError(sym),
3225                              tree.pos(), site, sym.name, true);
3226                }
3227            }
3228            if (!allowStaticInterfaceMethods && sitesym.isInterface() &&
3229                    sym.isStatic() && sym.kind == MTH) {
3230                log.error(tree.pos(), "static.intf.method.invoke.not.supported.in.source", sourceName);
3231            }
3232        } else if (sym.kind != ERR &&
3233                   (sym.flags() & STATIC) != 0 &&
3234                   sym.name != names._class) {
3235            // If the qualified item is not a type and the selected item is static, report
3236            // a warning. Make allowance for the class of an array type e.g. Object[].class)
3237            chk.warnStatic(tree, "static.not.qualified.by.type",
3238                           sym.kind.kindName(), sym.owner);
3239        }
3240
3241        // If we are selecting an instance member via a `super', ...
3242        if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
3243
3244            // Check that super-qualified symbols are not abstract (JLS)
3245            rs.checkNonAbstract(tree.pos(), sym);
3246
3247            if (site.isRaw()) {
3248                // Determine argument types for site.
3249                Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
3250                if (site1 != null) site = site1;
3251            }
3252        }
3253
3254        if (env.info.isSerializable) {
3255            chk.checkElemAccessFromSerializableLambda(tree);
3256        }
3257
3258        env.info.selectSuper = selectSuperPrev;
3259        result = checkId(tree, site, sym, env, resultInfo);
3260    }
3261    //where
3262        /** Determine symbol referenced by a Select expression,
3263         *
3264         *  @param tree   The select tree.
3265         *  @param site   The type of the selected expression,
3266         *  @param env    The current environment.
3267         *  @param resultInfo The current result.
3268         */
3269        private Symbol selectSym(JCFieldAccess tree,
3270                                 Symbol location,
3271                                 Type site,
3272                                 Env<AttrContext> env,
3273                                 ResultInfo resultInfo) {
3274            DiagnosticPosition pos = tree.pos();
3275            Name name = tree.name;
3276            switch (site.getTag()) {
3277            case PACKAGE:
3278                return rs.accessBase(
3279                    rs.findIdentInPackage(env, site.tsym, name, resultInfo.pkind),
3280                    pos, location, site, name, true);
3281            case ARRAY:
3282            case CLASS:
3283                if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) {
3284                    return rs.resolveQualifiedMethod(
3285                        pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
3286                } else if (name == names._this || name == names._super) {
3287                    return rs.resolveSelf(pos, env, site.tsym, name);
3288                } else if (name == names._class) {
3289                    // In this case, we have already made sure in
3290                    // visitSelect that qualifier expression is a type.
3291                    Type t = syms.classType;
3292                    List<Type> typeargs = List.of(types.erasure(site));
3293                    t = new ClassType(t.getEnclosingType(), typeargs, t.tsym);
3294                    return new VarSymbol(
3295                        STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
3296                } else {
3297                    // We are seeing a plain identifier as selector.
3298                    Symbol sym = rs.findIdentInType(env, site, name, resultInfo.pkind);
3299                        sym = rs.accessBase(sym, pos, location, site, name, true);
3300                    return sym;
3301                }
3302            case WILDCARD:
3303                throw new AssertionError(tree);
3304            case TYPEVAR:
3305                // Normally, site.getUpperBound() shouldn't be null.
3306                // It should only happen during memberEnter/attribBase
3307                // when determining the super type which *must* beac
3308                // done before attributing the type variables.  In
3309                // other words, we are seeing this illegal program:
3310                // class B<T> extends A<T.foo> {}
3311                Symbol sym = (site.getUpperBound() != null)
3312                    ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
3313                    : null;
3314                if (sym == null) {
3315                    log.error(pos, "type.var.cant.be.deref");
3316                    return syms.errSymbol;
3317                } else {
3318                    Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
3319                        rs.new AccessError(env, site, sym) :
3320                                sym;
3321                    rs.accessBase(sym2, pos, location, site, name, true);
3322                    return sym;
3323                }
3324            case ERROR:
3325                // preserve identifier names through errors
3326                return types.createErrorType(name, site.tsym, site).tsym;
3327            default:
3328                // The qualifier expression is of a primitive type -- only
3329                // .class is allowed for these.
3330                if (name == names._class) {
3331                    // In this case, we have already made sure in Select that
3332                    // qualifier expression is a type.
3333                    Type t = syms.classType;
3334                    Type arg = types.boxedClass(site).type;
3335                    t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym);
3336                    return new VarSymbol(
3337                        STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
3338                } else {
3339                    log.error(pos, "cant.deref", site);
3340                    return syms.errSymbol;
3341                }
3342            }
3343        }
3344
3345        /** Determine type of identifier or select expression and check that
3346         *  (1) the referenced symbol is not deprecated
3347         *  (2) the symbol's type is safe (@see checkSafe)
3348         *  (3) if symbol is a variable, check that its type and kind are
3349         *      compatible with the prototype and protokind.
3350         *  (4) if symbol is an instance field of a raw type,
3351         *      which is being assigned to, issue an unchecked warning if its
3352         *      type changes under erasure.
3353         *  (5) if symbol is an instance method of a raw type, issue an
3354         *      unchecked warning if its argument types change under erasure.
3355         *  If checks succeed:
3356         *    If symbol is a constant, return its constant type
3357         *    else if symbol is a method, return its result type
3358         *    otherwise return its type.
3359         *  Otherwise return errType.
3360         *
3361         *  @param tree       The syntax tree representing the identifier
3362         *  @param site       If this is a select, the type of the selected
3363         *                    expression, otherwise the type of the current class.
3364         *  @param sym        The symbol representing the identifier.
3365         *  @param env        The current environment.
3366         *  @param resultInfo    The expected result
3367         */
3368        Type checkId(JCTree tree,
3369                     Type site,
3370                     Symbol sym,
3371                     Env<AttrContext> env,
3372                     ResultInfo resultInfo) {
3373            return (resultInfo.pt.hasTag(FORALL) || resultInfo.pt.hasTag(METHOD)) ?
3374                    checkMethodId(tree, site, sym, env, resultInfo) :
3375                    checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
3376        }
3377
3378        Type checkMethodId(JCTree tree,
3379                     Type site,
3380                     Symbol sym,
3381                     Env<AttrContext> env,
3382                     ResultInfo resultInfo) {
3383            boolean isPolymorhicSignature =
3384                (sym.baseSymbol().flags() & SIGNATURE_POLYMORPHIC) != 0;
3385            return isPolymorhicSignature ?
3386                    checkSigPolyMethodId(tree, site, sym, env, resultInfo) :
3387                    checkMethodIdInternal(tree, site, sym, env, resultInfo);
3388        }
3389
3390        Type checkSigPolyMethodId(JCTree tree,
3391                     Type site,
3392                     Symbol sym,
3393                     Env<AttrContext> env,
3394                     ResultInfo resultInfo) {
3395            //recover original symbol for signature polymorphic methods
3396            checkMethodIdInternal(tree, site, sym.baseSymbol(), env, resultInfo);
3397            env.info.pendingResolutionPhase = Resolve.MethodResolutionPhase.BASIC;
3398            return sym.type;
3399        }
3400
3401        Type checkMethodIdInternal(JCTree tree,
3402                     Type site,
3403                     Symbol sym,
3404                     Env<AttrContext> env,
3405                     ResultInfo resultInfo) {
3406            if (resultInfo.pkind.contains(KindSelector.POLY)) {
3407                Type pt = resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, sym, env.info.pendingResolutionPhase));
3408                Type owntype = checkIdInternal(tree, site, sym, pt, env, resultInfo);
3409                resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
3410                return owntype;
3411            } else {
3412                return checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
3413            }
3414        }
3415
3416        Type checkIdInternal(JCTree tree,
3417                     Type site,
3418                     Symbol sym,
3419                     Type pt,
3420                     Env<AttrContext> env,
3421                     ResultInfo resultInfo) {
3422            if (pt.isErroneous()) {
3423                return types.createErrorType(site);
3424            }
3425            Type owntype; // The computed type of this identifier occurrence.
3426            switch (sym.kind) {
3427            case TYP:
3428                // For types, the computed type equals the symbol's type,
3429                // except for two situations:
3430                owntype = sym.type;
3431                if (owntype.hasTag(CLASS)) {
3432                    chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym);
3433                    Type ownOuter = owntype.getEnclosingType();
3434
3435                    // (a) If the symbol's type is parameterized, erase it
3436                    // because no type parameters were given.
3437                    // We recover generic outer type later in visitTypeApply.
3438                    if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
3439                        owntype = types.erasure(owntype);
3440                    }
3441
3442                    // (b) If the symbol's type is an inner class, then
3443                    // we have to interpret its outer type as a superclass
3444                    // of the site type. Example:
3445                    //
3446                    // class Tree<A> { class Visitor { ... } }
3447                    // class PointTree extends Tree<Point> { ... }
3448                    // ...PointTree.Visitor...
3449                    //
3450                    // Then the type of the last expression above is
3451                    // Tree<Point>.Visitor.
3452                    else if (ownOuter.hasTag(CLASS) && site != ownOuter) {
3453                        Type normOuter = site;
3454                        if (normOuter.hasTag(CLASS)) {
3455                            normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
3456                        }
3457                        if (normOuter == null) // perhaps from an import
3458                            normOuter = types.erasure(ownOuter);
3459                        if (normOuter != ownOuter)
3460                            owntype = new ClassType(
3461                                normOuter, List.<Type>nil(), owntype.tsym,
3462                                owntype.getMetadata());
3463                    }
3464                }
3465                break;
3466            case VAR:
3467                VarSymbol v = (VarSymbol)sym;
3468                // Test (4): if symbol is an instance field of a raw type,
3469                // which is being assigned to, issue an unchecked warning if
3470                // its type changes under erasure.
3471                if (KindSelector.ASG.subset(pkind()) &&
3472                    v.owner.kind == TYP &&
3473                    (v.flags() & STATIC) == 0 &&
3474                    (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
3475                    Type s = types.asOuterSuper(site, v.owner);
3476                    if (s != null &&
3477                        s.isRaw() &&
3478                        !types.isSameType(v.type, v.erasure(types))) {
3479                        chk.warnUnchecked(tree.pos(),
3480                                          "unchecked.assign.to.var",
3481                                          v, s);
3482                    }
3483                }
3484                // The computed type of a variable is the type of the
3485                // variable symbol, taken as a member of the site type.
3486                owntype = (sym.owner.kind == TYP &&
3487                           sym.name != names._this && sym.name != names._super)
3488                    ? types.memberType(site, sym)
3489                    : sym.type;
3490
3491                // If the variable is a constant, record constant value in
3492                // computed type.
3493                if (v.getConstValue() != null && isStaticReference(tree))
3494                    owntype = owntype.constType(v.getConstValue());
3495
3496                if (resultInfo.pkind == KindSelector.VAL) {
3497                    owntype = capture(owntype); // capture "names as expressions"
3498                }
3499                break;
3500            case MTH: {
3501                owntype = checkMethod(site, sym,
3502                        new ResultInfo(resultInfo.pkind, resultInfo.pt.getReturnType(), resultInfo.checkContext),
3503                        env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(),
3504                        resultInfo.pt.getTypeArguments());
3505                break;
3506            }
3507            case PCK: case ERR:
3508                owntype = sym.type;
3509                break;
3510            default:
3511                throw new AssertionError("unexpected kind: " + sym.kind +
3512                                         " in tree " + tree);
3513            }
3514
3515            // Test (1): emit a `deprecation' warning if symbol is deprecated.
3516            // (for constructors, the error was given when the constructor was
3517            // resolved)
3518
3519            if (sym.name != names.init) {
3520                chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym);
3521                chk.checkSunAPI(tree.pos(), sym);
3522                chk.checkProfile(tree.pos(), sym);
3523            }
3524
3525            // Test (3): if symbol is a variable, check that its type and
3526            // kind are compatible with the prototype and protokind.
3527            return check(tree, owntype, sym.kind.toSelector(), resultInfo);
3528        }
3529
3530        /** Check that variable is initialized and evaluate the variable's
3531         *  initializer, if not yet done. Also check that variable is not
3532         *  referenced before it is defined.
3533         *  @param tree    The tree making up the variable reference.
3534         *  @param env     The current environment.
3535         *  @param v       The variable's symbol.
3536         */
3537        private void checkInit(JCTree tree,
3538                               Env<AttrContext> env,
3539                               VarSymbol v,
3540                               boolean onlyWarning) {
3541//          System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " +
3542//                             tree.pos + " " + v.pos + " " +
3543//                             Resolve.isStatic(env));//DEBUG
3544
3545            // A forward reference is diagnosed if the declaration position
3546            // of the variable is greater than the current tree position
3547            // and the tree and variable definition occur in the same class
3548            // definition.  Note that writes don't count as references.
3549            // This check applies only to class and instance
3550            // variables.  Local variables follow different scope rules,
3551            // and are subject to definite assignment checking.
3552            if ((env.info.enclVar == v || v.pos > tree.pos) &&
3553                v.owner.kind == TYP &&
3554                enclosingInitEnv(env) != null &&
3555                v.owner == env.info.scope.owner.enclClass() &&
3556                ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
3557                (!env.tree.hasTag(ASSIGN) ||
3558                 TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
3559                String suffix = (env.info.enclVar == v) ?
3560                                "self.ref" : "forward.ref";
3561                if (!onlyWarning || isStaticEnumField(v)) {
3562                    log.error(tree.pos(), "illegal." + suffix);
3563                } else if (useBeforeDeclarationWarning) {
3564                    log.warning(tree.pos(), suffix, v);
3565                }
3566            }
3567
3568            v.getConstValue(); // ensure initializer is evaluated
3569
3570            checkEnumInitializer(tree, env, v);
3571        }
3572
3573        /**
3574         * Returns the enclosing init environment associated with this env (if any). An init env
3575         * can be either a field declaration env or a static/instance initializer env.
3576         */
3577        Env<AttrContext> enclosingInitEnv(Env<AttrContext> env) {
3578            while (true) {
3579                switch (env.tree.getTag()) {
3580                    case VARDEF:
3581                        JCVariableDecl vdecl = (JCVariableDecl)env.tree;
3582                        if (vdecl.sym.owner.kind == TYP) {
3583                            //field
3584                            return env;
3585                        }
3586                        break;
3587                    case BLOCK:
3588                        if (env.next.tree.hasTag(CLASSDEF)) {
3589                            //instance/static initializer
3590                            return env;
3591                        }
3592                        break;
3593                    case METHODDEF:
3594                    case CLASSDEF:
3595                    case TOPLEVEL:
3596                        return null;
3597                }
3598                Assert.checkNonNull(env.next);
3599                env = env.next;
3600            }
3601        }
3602
3603        /**
3604         * Check for illegal references to static members of enum.  In
3605         * an enum type, constructors and initializers may not
3606         * reference its static members unless they are constant.
3607         *
3608         * @param tree    The tree making up the variable reference.
3609         * @param env     The current environment.
3610         * @param v       The variable's symbol.
3611         * @jls  section 8.9 Enums
3612         */
3613        private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
3614            // JLS:
3615            //
3616            // "It is a compile-time error to reference a static field
3617            // of an enum type that is not a compile-time constant
3618            // (15.28) from constructors, instance initializer blocks,
3619            // or instance variable initializer expressions of that
3620            // type. It is a compile-time error for the constructors,
3621            // instance initializer blocks, or instance variable
3622            // initializer expressions of an enum constant e to refer
3623            // to itself or to an enum constant of the same type that
3624            // is declared to the right of e."
3625            if (isStaticEnumField(v)) {
3626                ClassSymbol enclClass = env.info.scope.owner.enclClass();
3627
3628                if (enclClass == null || enclClass.owner == null)
3629                    return;
3630
3631                // See if the enclosing class is the enum (or a
3632                // subclass thereof) declaring v.  If not, this
3633                // reference is OK.
3634                if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
3635                    return;
3636
3637                // If the reference isn't from an initializer, then
3638                // the reference is OK.
3639                if (!Resolve.isInitializer(env))
3640                    return;
3641
3642                log.error(tree.pos(), "illegal.enum.static.ref");
3643            }
3644        }
3645
3646        /** Is the given symbol a static, non-constant field of an Enum?
3647         *  Note: enum literals should not be regarded as such
3648         */
3649        private boolean isStaticEnumField(VarSymbol v) {
3650            return Flags.isEnum(v.owner) &&
3651                   Flags.isStatic(v) &&
3652                   !Flags.isConstant(v) &&
3653                   v.name != names._class;
3654        }
3655
3656    Warner noteWarner = new Warner();
3657
3658    /**
3659     * Check that method arguments conform to its instantiation.
3660     **/
3661    public Type checkMethod(Type site,
3662                            final Symbol sym,
3663                            ResultInfo resultInfo,
3664                            Env<AttrContext> env,
3665                            final List<JCExpression> argtrees,
3666                            List<Type> argtypes,
3667                            List<Type> typeargtypes) {
3668        // Test (5): if symbol is an instance method of a raw type, issue
3669        // an unchecked warning if its argument types change under erasure.
3670        if ((sym.flags() & STATIC) == 0 &&
3671            (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
3672            Type s = types.asOuterSuper(site, sym.owner);
3673            if (s != null && s.isRaw() &&
3674                !types.isSameTypes(sym.type.getParameterTypes(),
3675                                   sym.erasure(types).getParameterTypes())) {
3676                chk.warnUnchecked(env.tree.pos(),
3677                                  "unchecked.call.mbr.of.raw.type",
3678                                  sym, s);
3679            }
3680        }
3681
3682        if (env.info.defaultSuperCallSite != null) {
3683            for (Type sup : types.interfaces(env.enclClass.type).prepend(types.supertype((env.enclClass.type)))) {
3684                if (!sup.tsym.isSubClass(sym.enclClass(), types) ||
3685                        types.isSameType(sup, env.info.defaultSuperCallSite)) continue;
3686                List<MethodSymbol> icand_sup =
3687                        types.interfaceCandidates(sup, (MethodSymbol)sym);
3688                if (icand_sup.nonEmpty() &&
3689                        icand_sup.head != sym &&
3690                        icand_sup.head.overrides(sym, icand_sup.head.enclClass(), types, true)) {
3691                    log.error(env.tree.pos(), "illegal.default.super.call", env.info.defaultSuperCallSite,
3692                        diags.fragment("overridden.default", sym, sup));
3693                    break;
3694                }
3695            }
3696            env.info.defaultSuperCallSite = null;
3697        }
3698
3699        if (sym.isStatic() && site.isInterface() && env.tree.hasTag(APPLY)) {
3700            JCMethodInvocation app = (JCMethodInvocation)env.tree;
3701            if (app.meth.hasTag(SELECT) &&
3702                    !TreeInfo.isStaticSelector(((JCFieldAccess)app.meth).selected, names)) {
3703                log.error(env.tree.pos(), "illegal.static.intf.meth.call", site);
3704            }
3705        }
3706
3707        // Compute the identifier's instantiated type.
3708        // For methods, we need to compute the instance type by
3709        // Resolve.instantiate from the symbol's type as well as
3710        // any type arguments and value arguments.
3711        noteWarner.clear();
3712        try {
3713            Type owntype = rs.checkMethod(
3714                    env,
3715                    site,
3716                    sym,
3717                    resultInfo,
3718                    argtypes,
3719                    typeargtypes,
3720                    noteWarner);
3721
3722            DeferredAttr.DeferredTypeMap checkDeferredMap =
3723                deferredAttr.new DeferredTypeMap(DeferredAttr.AttrMode.CHECK, sym, env.info.pendingResolutionPhase);
3724
3725            argtypes = Type.map(argtypes, checkDeferredMap);
3726
3727            if (noteWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
3728                chk.warnUnchecked(env.tree.pos(),
3729                        "unchecked.meth.invocation.applied",
3730                        kindName(sym),
3731                        sym.name,
3732                        rs.methodArguments(sym.type.getParameterTypes()),
3733                        rs.methodArguments(Type.map(argtypes, checkDeferredMap)),
3734                        kindName(sym.location()),
3735                        sym.location());
3736               owntype = new MethodType(owntype.getParameterTypes(),
3737                       types.erasure(owntype.getReturnType()),
3738                       types.erasure(owntype.getThrownTypes()),
3739                       syms.methodClass);
3740            }
3741
3742            return chk.checkMethod(owntype, sym, env, argtrees, argtypes, env.info.lastResolveVarargs(),
3743                    resultInfo.checkContext.inferenceContext());
3744        } catch (Infer.InferenceException ex) {
3745            //invalid target type - propagate exception outwards or report error
3746            //depending on the current check context
3747            resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic());
3748            return types.createErrorType(site);
3749        } catch (Resolve.InapplicableMethodException ex) {
3750            final JCDiagnostic diag = ex.getDiagnostic();
3751            Resolve.InapplicableSymbolError errSym = rs.new InapplicableSymbolError(null) {
3752                @Override
3753                protected Pair<Symbol, JCDiagnostic> errCandidate() {
3754                    return new Pair<>(sym, diag);
3755                }
3756            };
3757            List<Type> argtypes2 = Type.map(argtypes,
3758                    rs.new ResolveDeferredRecoveryMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
3759            JCDiagnostic errDiag = errSym.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
3760                    env.tree, sym, site, sym.name, argtypes2, typeargtypes);
3761            log.report(errDiag);
3762            return types.createErrorType(site);
3763        }
3764    }
3765
3766    public void visitLiteral(JCLiteral tree) {
3767        result = check(tree, litType(tree.typetag).constType(tree.value),
3768                KindSelector.VAL, resultInfo);
3769    }
3770    //where
3771    /** Return the type of a literal with given type tag.
3772     */
3773    Type litType(TypeTag tag) {
3774        return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()];
3775    }
3776
3777    public void visitTypeIdent(JCPrimitiveTypeTree tree) {
3778        result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], KindSelector.TYP, resultInfo);
3779    }
3780
3781    public void visitTypeArray(JCArrayTypeTree tree) {
3782        Type etype = attribType(tree.elemtype, env);
3783        Type type = new ArrayType(etype, syms.arrayClass);
3784        result = check(tree, type, KindSelector.TYP, resultInfo);
3785    }
3786
3787    /** Visitor method for parameterized types.
3788     *  Bound checking is left until later, since types are attributed
3789     *  before supertype structure is completely known
3790     */
3791    public void visitTypeApply(JCTypeApply tree) {
3792        Type owntype = types.createErrorType(tree.type);
3793
3794        // Attribute functor part of application and make sure it's a class.
3795        Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
3796
3797        // Attribute type parameters
3798        List<Type> actuals = attribTypes(tree.arguments, env);
3799
3800        if (clazztype.hasTag(CLASS)) {
3801            List<Type> formals = clazztype.tsym.type.getTypeArguments();
3802            if (actuals.isEmpty()) //diamond
3803                actuals = formals;
3804
3805            if (actuals.length() == formals.length()) {
3806                List<Type> a = actuals;
3807                List<Type> f = formals;
3808                while (a.nonEmpty()) {
3809                    a.head = a.head.withTypeVar(f.head);
3810                    a = a.tail;
3811                    f = f.tail;
3812                }
3813                // Compute the proper generic outer
3814                Type clazzOuter = clazztype.getEnclosingType();
3815                if (clazzOuter.hasTag(CLASS)) {
3816                    Type site;
3817                    JCExpression clazz = TreeInfo.typeIn(tree.clazz);
3818                    if (clazz.hasTag(IDENT)) {
3819                        site = env.enclClass.sym.type;
3820                    } else if (clazz.hasTag(SELECT)) {
3821                        site = ((JCFieldAccess) clazz).selected.type;
3822                    } else throw new AssertionError(""+tree);
3823                    if (clazzOuter.hasTag(CLASS) && site != clazzOuter) {
3824                        if (site.hasTag(CLASS))
3825                            site = types.asOuterSuper(site, clazzOuter.tsym);
3826                        if (site == null)
3827                            site = types.erasure(clazzOuter);
3828                        clazzOuter = site;
3829                    }
3830                }
3831                owntype = new ClassType(clazzOuter, actuals, clazztype.tsym,
3832                                        clazztype.getMetadata());
3833            } else {
3834                if (formals.length() != 0) {
3835                    log.error(tree.pos(), "wrong.number.type.args",
3836                              Integer.toString(formals.length()));
3837                } else {
3838                    log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym);
3839                }
3840                owntype = types.createErrorType(tree.type);
3841            }
3842        }
3843        result = check(tree, owntype, KindSelector.TYP, resultInfo);
3844    }
3845
3846    public void visitTypeUnion(JCTypeUnion tree) {
3847        ListBuffer<Type> multicatchTypes = new ListBuffer<>();
3848        ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
3849        for (JCExpression typeTree : tree.alternatives) {
3850            Type ctype = attribType(typeTree, env);
3851            ctype = chk.checkType(typeTree.pos(),
3852                          chk.checkClassType(typeTree.pos(), ctype),
3853                          syms.throwableType);
3854            if (!ctype.isErroneous()) {
3855                //check that alternatives of a union type are pairwise
3856                //unrelated w.r.t. subtyping
3857                if (chk.intersects(ctype,  multicatchTypes.toList())) {
3858                    for (Type t : multicatchTypes) {
3859                        boolean sub = types.isSubtype(ctype, t);
3860                        boolean sup = types.isSubtype(t, ctype);
3861                        if (sub || sup) {
3862                            //assume 'a' <: 'b'
3863                            Type a = sub ? ctype : t;
3864                            Type b = sub ? t : ctype;
3865                            log.error(typeTree.pos(), "multicatch.types.must.be.disjoint", a, b);
3866                        }
3867                    }
3868                }
3869                multicatchTypes.append(ctype);
3870                if (all_multicatchTypes != null)
3871                    all_multicatchTypes.append(ctype);
3872            } else {
3873                if (all_multicatchTypes == null) {
3874                    all_multicatchTypes = new ListBuffer<>();
3875                    all_multicatchTypes.appendList(multicatchTypes);
3876                }
3877                all_multicatchTypes.append(ctype);
3878            }
3879        }
3880        Type t = check(noCheckTree, types.lub(multicatchTypes.toList()),
3881                KindSelector.TYP, resultInfo);
3882        if (t.hasTag(CLASS)) {
3883            List<Type> alternatives =
3884                ((all_multicatchTypes == null) ? multicatchTypes : all_multicatchTypes).toList();
3885            t = new UnionClassType((ClassType) t, alternatives);
3886        }
3887        tree.type = result = t;
3888    }
3889
3890    public void visitTypeIntersection(JCTypeIntersection tree) {
3891        attribTypes(tree.bounds, env);
3892        tree.type = result = checkIntersection(tree, tree.bounds);
3893    }
3894
3895    public void visitTypeParameter(JCTypeParameter tree) {
3896        TypeVar typeVar = (TypeVar) tree.type;
3897
3898        if (tree.annotations != null && tree.annotations.nonEmpty()) {
3899            annotateType(tree, tree.annotations);
3900        }
3901
3902        if (!typeVar.bound.isErroneous()) {
3903            //fixup type-parameter bound computed in 'attribTypeVariables'
3904            typeVar.bound = checkIntersection(tree, tree.bounds);
3905        }
3906    }
3907
3908    Type checkIntersection(JCTree tree, List<JCExpression> bounds) {
3909        Set<Type> boundSet = new HashSet<>();
3910        if (bounds.nonEmpty()) {
3911            // accept class or interface or typevar as first bound.
3912            bounds.head.type = checkBase(bounds.head.type, bounds.head, env, false, false, false);
3913            boundSet.add(types.erasure(bounds.head.type));
3914            if (bounds.head.type.isErroneous()) {
3915                return bounds.head.type;
3916            }
3917            else if (bounds.head.type.hasTag(TYPEVAR)) {
3918                // if first bound was a typevar, do not accept further bounds.
3919                if (bounds.tail.nonEmpty()) {
3920                    log.error(bounds.tail.head.pos(),
3921                              "type.var.may.not.be.followed.by.other.bounds");
3922                    return bounds.head.type;
3923                }
3924            } else {
3925                // if first bound was a class or interface, accept only interfaces
3926                // as further bounds.
3927                for (JCExpression bound : bounds.tail) {
3928                    bound.type = checkBase(bound.type, bound, env, false, true, false);
3929                    if (bound.type.isErroneous()) {
3930                        bounds = List.of(bound);
3931                    }
3932                    else if (bound.type.hasTag(CLASS)) {
3933                        chk.checkNotRepeated(bound.pos(), types.erasure(bound.type), boundSet);
3934                    }
3935                }
3936            }
3937        }
3938
3939        if (bounds.length() == 0) {
3940            return syms.objectType;
3941        } else if (bounds.length() == 1) {
3942            return bounds.head.type;
3943        } else {
3944            Type owntype = types.makeIntersectionType(TreeInfo.types(bounds));
3945            // ... the variable's bound is a class type flagged COMPOUND
3946            // (see comment for TypeVar.bound).
3947            // In this case, generate a class tree that represents the
3948            // bound class, ...
3949            JCExpression extending;
3950            List<JCExpression> implementing;
3951            if (!bounds.head.type.isInterface()) {
3952                extending = bounds.head;
3953                implementing = bounds.tail;
3954            } else {
3955                extending = null;
3956                implementing = bounds;
3957            }
3958            JCClassDecl cd = make.at(tree).ClassDef(
3959                make.Modifiers(PUBLIC | ABSTRACT),
3960                names.empty, List.<JCTypeParameter>nil(),
3961                extending, implementing, List.<JCTree>nil());
3962
3963            ClassSymbol c = (ClassSymbol)owntype.tsym;
3964            Assert.check((c.flags() & COMPOUND) != 0);
3965            cd.sym = c;
3966            c.sourcefile = env.toplevel.sourcefile;
3967
3968            // ... and attribute the bound class
3969            c.flags_field |= UNATTRIBUTED;
3970            Env<AttrContext> cenv = enter.classEnv(cd, env);
3971            typeEnvs.put(c, cenv);
3972            attribClass(c);
3973            return owntype;
3974        }
3975    }
3976
3977    public void visitWildcard(JCWildcard tree) {
3978        //- System.err.println("visitWildcard("+tree+");");//DEBUG
3979        Type type = (tree.kind.kind == BoundKind.UNBOUND)
3980            ? syms.objectType
3981            : attribType(tree.inner, env);
3982        result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
3983                                              tree.kind.kind,
3984                                              syms.boundClass),
3985                KindSelector.TYP, resultInfo);
3986    }
3987
3988    public void visitAnnotation(JCAnnotation tree) {
3989        Assert.error("should be handled in Annotate");
3990    }
3991
3992    public void visitAnnotatedType(JCAnnotatedType tree) {
3993        Type underlyingType = attribType(tree.getUnderlyingType(), env);
3994        this.attribAnnotationTypes(tree.annotations, env);
3995        annotateType(tree, tree.annotations);
3996        result = tree.type = underlyingType;
3997    }
3998
3999    /**
4000     * Apply the annotations to the particular type.
4001     */
4002    public void annotateType(final JCTree tree, final List<JCAnnotation> annotations) {
4003        annotate.typeAnnotation(new Annotate.Worker() {
4004            @Override
4005            public String toString() {
4006                return "annotate " + annotations + " onto " + tree;
4007            }
4008            @Override
4009            public void run() {
4010                List<Attribute.TypeCompound> compounds = fromAnnotations(annotations);
4011                Assert.check(annotations.size() == compounds.size());
4012                tree.type = tree.type.annotatedType(compounds);
4013                }
4014        });
4015    }
4016
4017    private static List<Attribute.TypeCompound> fromAnnotations(List<JCAnnotation> annotations) {
4018        if (annotations.isEmpty()) {
4019            return List.nil();
4020        }
4021
4022        ListBuffer<Attribute.TypeCompound> buf = new ListBuffer<>();
4023        for (JCAnnotation anno : annotations) {
4024            Assert.checkNonNull(anno.attribute);
4025            buf.append((Attribute.TypeCompound) anno.attribute);
4026        }
4027        return buf.toList();
4028    }
4029
4030    public void visitErroneous(JCErroneous tree) {
4031        if (tree.errs != null)
4032            for (JCTree err : tree.errs)
4033                attribTree(err, env, new ResultInfo(KindSelector.ERR, pt()));
4034        result = tree.type = syms.errType;
4035    }
4036
4037    /** Default visitor method for all other trees.
4038     */
4039    public void visitTree(JCTree tree) {
4040        throw new AssertionError();
4041    }
4042
4043    /**
4044     * Attribute an env for either a top level tree or class declaration.
4045     */
4046    public void attrib(Env<AttrContext> env) {
4047        if (env.tree.hasTag(TOPLEVEL))
4048            attribTopLevel(env);
4049        else
4050            attribClass(env.tree.pos(), env.enclClass.sym);
4051    }
4052
4053    /**
4054     * Attribute a top level tree. These trees are encountered when the
4055     * package declaration has annotations.
4056     */
4057    public void attribTopLevel(Env<AttrContext> env) {
4058        JCCompilationUnit toplevel = env.toplevel;
4059        try {
4060            annotate.flush();
4061        } catch (CompletionFailure ex) {
4062            chk.completionError(toplevel.pos(), ex);
4063        }
4064    }
4065
4066    /** Main method: attribute class definition associated with given class symbol.
4067     *  reporting completion failures at the given position.
4068     *  @param pos The source position at which completion errors are to be
4069     *             reported.
4070     *  @param c   The class symbol whose definition will be attributed.
4071     */
4072    public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
4073        try {
4074            annotate.flush();
4075            attribClass(c);
4076        } catch (CompletionFailure ex) {
4077            chk.completionError(pos, ex);
4078        }
4079    }
4080
4081    /** Attribute class definition associated with given class symbol.
4082     *  @param c   The class symbol whose definition will be attributed.
4083     */
4084    void attribClass(ClassSymbol c) throws CompletionFailure {
4085        if (c.type.hasTag(ERROR)) return;
4086
4087        // Check for cycles in the inheritance graph, which can arise from
4088        // ill-formed class files.
4089        chk.checkNonCyclic(null, c.type);
4090
4091        Type st = types.supertype(c.type);
4092        if ((c.flags_field & Flags.COMPOUND) == 0) {
4093            // First, attribute superclass.
4094            if (st.hasTag(CLASS))
4095                attribClass((ClassSymbol)st.tsym);
4096
4097            // Next attribute owner, if it is a class.
4098            if (c.owner.kind == TYP && c.owner.type.hasTag(CLASS))
4099                attribClass((ClassSymbol)c.owner);
4100        }
4101
4102        // The previous operations might have attributed the current class
4103        // if there was a cycle. So we test first whether the class is still
4104        // UNATTRIBUTED.
4105        if ((c.flags_field & UNATTRIBUTED) != 0) {
4106            c.flags_field &= ~UNATTRIBUTED;
4107
4108            // Get environment current at the point of class definition.
4109            Env<AttrContext> env = typeEnvs.get(c);
4110
4111            // The info.lint field in the envs stored in typeEnvs is deliberately uninitialized,
4112            // because the annotations were not available at the time the env was created. Therefore,
4113            // we look up the environment chain for the first enclosing environment for which the
4114            // lint value is set. Typically, this is the parent env, but might be further if there
4115            // are any envs created as a result of TypeParameter nodes.
4116            Env<AttrContext> lintEnv = env;
4117            while (lintEnv.info.lint == null)
4118                lintEnv = lintEnv.next;
4119
4120            // Having found the enclosing lint value, we can initialize the lint value for this class
4121            env.info.lint = lintEnv.info.lint.augment(c);
4122
4123            Lint prevLint = chk.setLint(env.info.lint);
4124            JavaFileObject prev = log.useSource(c.sourcefile);
4125            ResultInfo prevReturnRes = env.info.returnResult;
4126
4127            try {
4128                deferredLintHandler.flush(env.tree);
4129                env.info.returnResult = null;
4130                // java.lang.Enum may not be subclassed by a non-enum
4131                if (st.tsym == syms.enumSym &&
4132                    ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
4133                    log.error(env.tree.pos(), "enum.no.subclassing");
4134
4135                // Enums may not be extended by source-level classes
4136                if (st.tsym != null &&
4137                    ((st.tsym.flags_field & Flags.ENUM) != 0) &&
4138                    ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
4139                    log.error(env.tree.pos(), "enum.types.not.extensible");
4140                }
4141
4142                if (isSerializable(c.type)) {
4143                    env.info.isSerializable = true;
4144                }
4145
4146                attribClassBody(env, c);
4147
4148                chk.checkDeprecatedAnnotation(env.tree.pos(), c);
4149                chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
4150                chk.checkFunctionalInterface((JCClassDecl) env.tree, c);
4151            } finally {
4152                env.info.returnResult = prevReturnRes;
4153                log.useSource(prev);
4154                chk.setLint(prevLint);
4155            }
4156
4157        }
4158    }
4159
4160    public void visitImport(JCImport tree) {
4161        // nothing to do
4162    }
4163
4164    /** Finish the attribution of a class. */
4165    private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
4166        JCClassDecl tree = (JCClassDecl)env.tree;
4167        Assert.check(c == tree.sym);
4168
4169        // Validate type parameters, supertype and interfaces.
4170        attribStats(tree.typarams, env);
4171        if (!c.isAnonymous()) {
4172            //already checked if anonymous
4173            chk.validate(tree.typarams, env);
4174            chk.validate(tree.extending, env);
4175            chk.validate(tree.implementing, env);
4176        }
4177
4178        c.markAbstractIfNeeded(types);
4179
4180        // If this is a non-abstract class, check that it has no abstract
4181        // methods or unimplemented methods of an implemented interface.
4182        if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
4183            if (!relax)
4184                chk.checkAllDefined(tree.pos(), c);
4185        }
4186
4187        if ((c.flags() & ANNOTATION) != 0) {
4188            if (tree.implementing.nonEmpty())
4189                log.error(tree.implementing.head.pos(),
4190                          "cant.extend.intf.annotation");
4191            if (tree.typarams.nonEmpty())
4192                log.error(tree.typarams.head.pos(),
4193                          "intf.annotation.cant.have.type.params");
4194
4195            // If this annotation has a @Repeatable, validate
4196            Attribute.Compound repeatable = c.attribute(syms.repeatableType.tsym);
4197            if (repeatable != null) {
4198                // get diagnostic position for error reporting
4199                DiagnosticPosition cbPos = getDiagnosticPosition(tree, repeatable.type);
4200                Assert.checkNonNull(cbPos);
4201
4202                chk.validateRepeatable(c, repeatable, cbPos);
4203            }
4204        } else {
4205            // Check that all extended classes and interfaces
4206            // are compatible (i.e. no two define methods with same arguments
4207            // yet different return types).  (JLS 8.4.6.3)
4208            chk.checkCompatibleSupertypes(tree.pos(), c.type);
4209            if (allowDefaultMethods) {
4210                chk.checkDefaultMethodClashes(tree.pos(), c.type);
4211            }
4212        }
4213
4214        // Check that class does not import the same parameterized interface
4215        // with two different argument lists.
4216        chk.checkClassBounds(tree.pos(), c.type);
4217
4218        tree.type = c.type;
4219
4220        for (List<JCTypeParameter> l = tree.typarams;
4221             l.nonEmpty(); l = l.tail) {
4222             Assert.checkNonNull(env.info.scope.findFirst(l.head.name));
4223        }
4224
4225        // Check that a generic class doesn't extend Throwable
4226        if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
4227            log.error(tree.extending.pos(), "generic.throwable");
4228
4229        // Check that all methods which implement some
4230        // method conform to the method they implement.
4231        chk.checkImplementations(tree);
4232
4233        //check that a resource implementing AutoCloseable cannot throw InterruptedException
4234        checkAutoCloseable(tree.pos(), env, c.type);
4235
4236        for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
4237            // Attribute declaration
4238            attribStat(l.head, env);
4239            // Check that declarations in inner classes are not static (JLS 8.1.2)
4240            // Make an exception for static constants.
4241            if (c.owner.kind != PCK &&
4242                ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
4243                (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
4244                Symbol sym = null;
4245                if (l.head.hasTag(VARDEF)) sym = ((JCVariableDecl) l.head).sym;
4246                if (sym == null ||
4247                    sym.kind != VAR ||
4248                    ((VarSymbol) sym).getConstValue() == null)
4249                    log.error(l.head.pos(), "icls.cant.have.static.decl", c);
4250            }
4251        }
4252
4253        // Check for cycles among non-initial constructors.
4254        chk.checkCyclicConstructors(tree);
4255
4256        // Check for cycles among annotation elements.
4257        chk.checkNonCyclicElements(tree);
4258
4259        // Check for proper use of serialVersionUID
4260        if (env.info.lint.isEnabled(LintCategory.SERIAL) &&
4261            isSerializable(c.type) &&
4262            (c.flags() & Flags.ENUM) == 0 &&
4263            checkForSerial(c)) {
4264            checkSerialVersionUID(tree, c);
4265        }
4266        if (allowTypeAnnos) {
4267            // Correctly organize the postions of the type annotations
4268            typeAnnotations.organizeTypeAnnotationsBodies(tree);
4269
4270            // Check type annotations applicability rules
4271            validateTypeAnnotations(tree, false);
4272        }
4273    }
4274        // where
4275        boolean checkForSerial(ClassSymbol c) {
4276            if ((c.flags() & ABSTRACT) == 0) {
4277                return true;
4278            } else {
4279                return c.members().anyMatch(anyNonAbstractOrDefaultMethod);
4280            }
4281        }
4282
4283        public static final Filter<Symbol> anyNonAbstractOrDefaultMethod = new Filter<Symbol>() {
4284            @Override
4285            public boolean accepts(Symbol s) {
4286                return s.kind == MTH &&
4287                       (s.flags() & (DEFAULT | ABSTRACT)) != ABSTRACT;
4288            }
4289        };
4290
4291        /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
4292        private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
4293            for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
4294                if (types.isSameType(al.head.annotationType.type, t))
4295                    return al.head.pos();
4296            }
4297
4298            return null;
4299        }
4300
4301        /** check if a type is a subtype of Serializable, if that is available. */
4302        boolean isSerializable(Type t) {
4303            try {
4304                syms.serializableType.complete();
4305            }
4306            catch (CompletionFailure e) {
4307                return false;
4308            }
4309            return types.isSubtype(t, syms.serializableType);
4310        }
4311
4312        /** Check that an appropriate serialVersionUID member is defined. */
4313        private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
4314
4315            // check for presence of serialVersionUID
4316            VarSymbol svuid = null;
4317            for (Symbol sym : c.members().getSymbolsByName(names.serialVersionUID)) {
4318                if (sym.kind == VAR) {
4319                    svuid = (VarSymbol)sym;
4320                    break;
4321                }
4322            }
4323
4324            if (svuid == null) {
4325                log.warning(LintCategory.SERIAL,
4326                        tree.pos(), "missing.SVUID", c);
4327                return;
4328            }
4329
4330            // check that it is static final
4331            if ((svuid.flags() & (STATIC | FINAL)) !=
4332                (STATIC | FINAL))
4333                log.warning(LintCategory.SERIAL,
4334                        TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c);
4335
4336            // check that it is long
4337            else if (!svuid.type.hasTag(LONG))
4338                log.warning(LintCategory.SERIAL,
4339                        TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c);
4340
4341            // check constant
4342            else if (svuid.getConstValue() == null)
4343                log.warning(LintCategory.SERIAL,
4344                        TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c);
4345        }
4346
4347    private Type capture(Type type) {
4348        return types.capture(type);
4349    }
4350
4351    public void validateTypeAnnotations(JCTree tree, boolean sigOnly) {
4352        tree.accept(new TypeAnnotationsValidator(sigOnly));
4353    }
4354    //where
4355    private final class TypeAnnotationsValidator extends TreeScanner {
4356
4357        private final boolean sigOnly;
4358        public TypeAnnotationsValidator(boolean sigOnly) {
4359            this.sigOnly = sigOnly;
4360        }
4361
4362        public void visitAnnotation(JCAnnotation tree) {
4363            chk.validateTypeAnnotation(tree, false);
4364            super.visitAnnotation(tree);
4365        }
4366        public void visitAnnotatedType(JCAnnotatedType tree) {
4367            if (!tree.underlyingType.type.isErroneous()) {
4368                super.visitAnnotatedType(tree);
4369            }
4370        }
4371        public void visitTypeParameter(JCTypeParameter tree) {
4372            chk.validateTypeAnnotations(tree.annotations, true);
4373            scan(tree.bounds);
4374            // Don't call super.
4375            // This is needed because above we call validateTypeAnnotation with
4376            // false, which would forbid annotations on type parameters.
4377            // super.visitTypeParameter(tree);
4378        }
4379        public void visitMethodDef(JCMethodDecl tree) {
4380            if (tree.recvparam != null &&
4381                    !tree.recvparam.vartype.type.isErroneous()) {
4382                checkForDeclarationAnnotations(tree.recvparam.mods.annotations,
4383                        tree.recvparam.vartype.type.tsym);
4384            }
4385            if (tree.restype != null && tree.restype.type != null) {
4386                validateAnnotatedType(tree.restype, tree.restype.type);
4387            }
4388            if (sigOnly) {
4389                scan(tree.mods);
4390                scan(tree.restype);
4391                scan(tree.typarams);
4392                scan(tree.recvparam);
4393                scan(tree.params);
4394                scan(tree.thrown);
4395            } else {
4396                scan(tree.defaultValue);
4397                scan(tree.body);
4398            }
4399        }
4400        public void visitVarDef(final JCVariableDecl tree) {
4401            //System.err.println("validateTypeAnnotations.visitVarDef " + tree);
4402            if (tree.sym != null && tree.sym.type != null)
4403                validateAnnotatedType(tree.vartype, tree.sym.type);
4404            scan(tree.mods);
4405            scan(tree.vartype);
4406            if (!sigOnly) {
4407                scan(tree.init);
4408            }
4409        }
4410        public void visitTypeCast(JCTypeCast tree) {
4411            if (tree.clazz != null && tree.clazz.type != null)
4412                validateAnnotatedType(tree.clazz, tree.clazz.type);
4413            super.visitTypeCast(tree);
4414        }
4415        public void visitTypeTest(JCInstanceOf tree) {
4416            if (tree.clazz != null && tree.clazz.type != null)
4417                validateAnnotatedType(tree.clazz, tree.clazz.type);
4418            super.visitTypeTest(tree);
4419        }
4420        public void visitNewClass(JCNewClass tree) {
4421            if (tree.clazz != null && tree.clazz.type != null) {
4422                if (tree.clazz.hasTag(ANNOTATED_TYPE)) {
4423                    checkForDeclarationAnnotations(((JCAnnotatedType) tree.clazz).annotations,
4424                            tree.clazz.type.tsym);
4425                }
4426                if (tree.def != null) {
4427                    checkForDeclarationAnnotations(tree.def.mods.annotations, tree.clazz.type.tsym);
4428                }
4429
4430                validateAnnotatedType(tree.clazz, tree.clazz.type);
4431            }
4432            super.visitNewClass(tree);
4433        }
4434        public void visitNewArray(JCNewArray tree) {
4435            if (tree.elemtype != null && tree.elemtype.type != null) {
4436                if (tree.elemtype.hasTag(ANNOTATED_TYPE)) {
4437                    checkForDeclarationAnnotations(((JCAnnotatedType) tree.elemtype).annotations,
4438                            tree.elemtype.type.tsym);
4439                }
4440                validateAnnotatedType(tree.elemtype, tree.elemtype.type);
4441            }
4442            super.visitNewArray(tree);
4443        }
4444        public void visitClassDef(JCClassDecl tree) {
4445            //System.err.println("validateTypeAnnotations.visitClassDef " + tree);
4446            if (sigOnly) {
4447                scan(tree.mods);
4448                scan(tree.typarams);
4449                scan(tree.extending);
4450                scan(tree.implementing);
4451            }
4452            for (JCTree member : tree.defs) {
4453                if (member.hasTag(Tag.CLASSDEF)) {
4454                    continue;
4455                }
4456                scan(member);
4457            }
4458        }
4459        public void visitBlock(JCBlock tree) {
4460            if (!sigOnly) {
4461                scan(tree.stats);
4462            }
4463        }
4464
4465        /* I would want to model this after
4466         * com.sun.tools.javac.comp.Check.Validator.visitSelectInternal(JCFieldAccess)
4467         * and override visitSelect and visitTypeApply.
4468         * However, we only set the annotated type in the top-level type
4469         * of the symbol.
4470         * Therefore, we need to override each individual location where a type
4471         * can occur.
4472         */
4473        private void validateAnnotatedType(final JCTree errtree, final Type type) {
4474            //System.err.println("Attr.validateAnnotatedType: " + errtree + " type: " + type);
4475
4476            if (type.isPrimitiveOrVoid()) {
4477                return;
4478            }
4479
4480            JCTree enclTr = errtree;
4481            Type enclTy = type;
4482
4483            boolean repeat = true;
4484            while (repeat) {
4485                if (enclTr.hasTag(TYPEAPPLY)) {
4486                    List<Type> tyargs = enclTy.getTypeArguments();
4487                    List<JCExpression> trargs = ((JCTypeApply)enclTr).getTypeArguments();
4488                    if (trargs.length() > 0) {
4489                        // Nothing to do for diamonds
4490                        if (tyargs.length() == trargs.length()) {
4491                            for (int i = 0; i < tyargs.length(); ++i) {
4492                                validateAnnotatedType(trargs.get(i), tyargs.get(i));
4493                            }
4494                        }
4495                        // If the lengths don't match, it's either a diamond
4496                        // or some nested type that redundantly provides
4497                        // type arguments in the tree.
4498                    }
4499
4500                    // Look at the clazz part of a generic type
4501                    enclTr = ((JCTree.JCTypeApply)enclTr).clazz;
4502                }
4503
4504                if (enclTr.hasTag(SELECT)) {
4505                    enclTr = ((JCTree.JCFieldAccess)enclTr).getExpression();
4506                    if (enclTy != null &&
4507                            !enclTy.hasTag(NONE)) {
4508                        enclTy = enclTy.getEnclosingType();
4509                    }
4510                } else if (enclTr.hasTag(ANNOTATED_TYPE)) {
4511                    JCAnnotatedType at = (JCTree.JCAnnotatedType) enclTr;
4512                    if (enclTy == null || enclTy.hasTag(NONE)) {
4513                        if (at.getAnnotations().size() == 1) {
4514                            log.error(at.underlyingType.pos(), "cant.type.annotate.scoping.1", at.getAnnotations().head.attribute);
4515                        } else {
4516                            ListBuffer<Attribute.Compound> comps = new ListBuffer<>();
4517                            for (JCAnnotation an : at.getAnnotations()) {
4518                                comps.add(an.attribute);
4519                            }
4520                            log.error(at.underlyingType.pos(), "cant.type.annotate.scoping", comps.toList());
4521                        }
4522                        repeat = false;
4523                    }
4524                    enclTr = at.underlyingType;
4525                    // enclTy doesn't need to be changed
4526                } else if (enclTr.hasTag(IDENT)) {
4527                    repeat = false;
4528                } else if (enclTr.hasTag(JCTree.Tag.WILDCARD)) {
4529                    JCWildcard wc = (JCWildcard) enclTr;
4530                    if (wc.getKind() == JCTree.Kind.EXTENDS_WILDCARD) {
4531                        validateAnnotatedType(wc.getBound(), ((WildcardType)enclTy).getExtendsBound());
4532                    } else if (wc.getKind() == JCTree.Kind.SUPER_WILDCARD) {
4533                        validateAnnotatedType(wc.getBound(), ((WildcardType)enclTy).getSuperBound());
4534                    } else {
4535                        // Nothing to do for UNBOUND
4536                    }
4537                    repeat = false;
4538                } else if (enclTr.hasTag(TYPEARRAY)) {
4539                    JCArrayTypeTree art = (JCArrayTypeTree) enclTr;
4540                    validateAnnotatedType(art.getType(), ((ArrayType)enclTy).getComponentType());
4541                    repeat = false;
4542                } else if (enclTr.hasTag(TYPEUNION)) {
4543                    JCTypeUnion ut = (JCTypeUnion) enclTr;
4544                    for (JCTree t : ut.getTypeAlternatives()) {
4545                        validateAnnotatedType(t, t.type);
4546                    }
4547                    repeat = false;
4548                } else if (enclTr.hasTag(TYPEINTERSECTION)) {
4549                    JCTypeIntersection it = (JCTypeIntersection) enclTr;
4550                    for (JCTree t : it.getBounds()) {
4551                        validateAnnotatedType(t, t.type);
4552                    }
4553                    repeat = false;
4554                } else if (enclTr.getKind() == JCTree.Kind.PRIMITIVE_TYPE ||
4555                           enclTr.getKind() == JCTree.Kind.ERRONEOUS) {
4556                    repeat = false;
4557                } else {
4558                    Assert.error("Unexpected tree: " + enclTr + " with kind: " + enclTr.getKind() +
4559                            " within: "+ errtree + " with kind: " + errtree.getKind());
4560                }
4561            }
4562        }
4563
4564        private void checkForDeclarationAnnotations(List<? extends JCAnnotation> annotations,
4565                Symbol sym) {
4566            // Ensure that no declaration annotations are present.
4567            // Note that a tree type might be an AnnotatedType with
4568            // empty annotations, if only declaration annotations were given.
4569            // This method will raise an error for such a type.
4570            for (JCAnnotation ai : annotations) {
4571                if (!ai.type.isErroneous() &&
4572                        typeAnnotations.annotationType(ai.attribute, sym) == TypeAnnotations.AnnotationType.DECLARATION) {
4573                    log.error(ai.pos(), "annotation.type.not.applicable");
4574                }
4575            }
4576        }
4577    }
4578
4579    // <editor-fold desc="post-attribution visitor">
4580
4581    /**
4582     * Handle missing types/symbols in an AST. This routine is useful when
4583     * the compiler has encountered some errors (which might have ended up
4584     * terminating attribution abruptly); if the compiler is used in fail-over
4585     * mode (e.g. by an IDE) and the AST contains semantic errors, this routine
4586     * prevents NPE to be progagated during subsequent compilation steps.
4587     */
4588    public void postAttr(JCTree tree) {
4589        new PostAttrAnalyzer().scan(tree);
4590    }
4591
4592    class PostAttrAnalyzer extends TreeScanner {
4593
4594        private void initTypeIfNeeded(JCTree that) {
4595            if (that.type == null) {
4596                if (that.hasTag(METHODDEF)) {
4597                    that.type = dummyMethodType((JCMethodDecl)that);
4598                } else {
4599                    that.type = syms.unknownType;
4600                }
4601            }
4602        }
4603
4604        /* Construct a dummy method type. If we have a method declaration,
4605         * and the declared return type is void, then use that return type
4606         * instead of UNKNOWN to avoid spurious error messages in lambda
4607         * bodies (see:JDK-8041704).
4608         */
4609        private Type dummyMethodType(JCMethodDecl md) {
4610            Type restype = syms.unknownType;
4611            if (md != null && md.restype.hasTag(TYPEIDENT)) {
4612                JCPrimitiveTypeTree prim = (JCPrimitiveTypeTree)md.restype;
4613                if (prim.typetag == VOID)
4614                    restype = syms.voidType;
4615            }
4616            return new MethodType(List.<Type>nil(), restype,
4617                                  List.<Type>nil(), syms.methodClass);
4618        }
4619        private Type dummyMethodType() {
4620            return dummyMethodType(null);
4621        }
4622
4623        @Override
4624        public void scan(JCTree tree) {
4625            if (tree == null) return;
4626            if (tree instanceof JCExpression) {
4627                initTypeIfNeeded(tree);
4628            }
4629            super.scan(tree);
4630        }
4631
4632        @Override
4633        public void visitIdent(JCIdent that) {
4634            if (that.sym == null) {
4635                that.sym = syms.unknownSymbol;
4636            }
4637        }
4638
4639        @Override
4640        public void visitSelect(JCFieldAccess that) {
4641            if (that.sym == null) {
4642                that.sym = syms.unknownSymbol;
4643            }
4644            super.visitSelect(that);
4645        }
4646
4647        @Override
4648        public void visitClassDef(JCClassDecl that) {
4649            initTypeIfNeeded(that);
4650            if (that.sym == null) {
4651                that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol);
4652            }
4653            super.visitClassDef(that);
4654        }
4655
4656        @Override
4657        public void visitMethodDef(JCMethodDecl that) {
4658            initTypeIfNeeded(that);
4659            if (that.sym == null) {
4660                that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol);
4661            }
4662            super.visitMethodDef(that);
4663        }
4664
4665        @Override
4666        public void visitVarDef(JCVariableDecl that) {
4667            initTypeIfNeeded(that);
4668            if (that.sym == null) {
4669                that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol);
4670                that.sym.adr = 0;
4671            }
4672            super.visitVarDef(that);
4673        }
4674
4675        @Override
4676        public void visitNewClass(JCNewClass that) {
4677            if (that.constructor == null) {
4678                that.constructor = new MethodSymbol(0, names.init,
4679                        dummyMethodType(), syms.noSymbol);
4680            }
4681            if (that.constructorType == null) {
4682                that.constructorType = syms.unknownType;
4683            }
4684            super.visitNewClass(that);
4685        }
4686
4687        @Override
4688        public void visitAssignop(JCAssignOp that) {
4689            if (that.operator == null) {
4690                that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
4691                        -1, syms.noSymbol);
4692            }
4693            super.visitAssignop(that);
4694        }
4695
4696        @Override
4697        public void visitBinary(JCBinary that) {
4698            if (that.operator == null) {
4699                that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
4700                        -1, syms.noSymbol);
4701            }
4702            super.visitBinary(that);
4703        }
4704
4705        @Override
4706        public void visitUnary(JCUnary that) {
4707            if (that.operator == null) {
4708                that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
4709                        -1, syms.noSymbol);
4710            }
4711            super.visitUnary(that);
4712        }
4713
4714        @Override
4715        public void visitLambda(JCLambda that) {
4716            super.visitLambda(that);
4717            if (that.targets == null) {
4718                that.targets = List.nil();
4719            }
4720        }
4721
4722        @Override
4723        public void visitReference(JCMemberReference that) {
4724            super.visitReference(that);
4725            if (that.sym == null) {
4726                that.sym = new MethodSymbol(0, names.empty, dummyMethodType(),
4727                        syms.noSymbol);
4728            }
4729            if (that.targets == null) {
4730                that.targets = List.nil();
4731            }
4732        }
4733    }
4734    // </editor-fold>
4735}
4736