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