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