Attr.java revision 3212:b2b1e27e324c
1/*
2 * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26package com.sun.tools.javac.comp;
27
28import java.util.*;
29
30import javax.lang.model.element.ElementKind;
31import javax.tools.JavaFileObject;
32
33import com.sun.source.tree.IdentifierTree;
34import com.sun.source.tree.MemberReferenceTree.ReferenceMode;
35import com.sun.source.tree.MemberSelectTree;
36import com.sun.source.tree.TreeVisitor;
37import com.sun.source.util.SimpleTreeVisitor;
38import com.sun.tools.javac.code.*;
39import com.sun.tools.javac.code.Lint.LintCategory;
40import com.sun.tools.javac.code.Scope.WriteableScope;
41import com.sun.tools.javac.code.Symbol.*;
42import com.sun.tools.javac.code.Type.*;
43import com.sun.tools.javac.code.TypeMetadata.Annotations;
44import com.sun.tools.javac.code.Types.FunctionDescriptorLookupError;
45import com.sun.tools.javac.comp.Check.CheckContext;
46import com.sun.tools.javac.comp.DeferredAttr.AttrMode;
47import com.sun.tools.javac.comp.Infer.FreeTypeListener;
48import com.sun.tools.javac.jvm.*;
49import static com.sun.tools.javac.resources.CompilerProperties.Fragments.Diamond;
50import static com.sun.tools.javac.resources.CompilerProperties.Fragments.DiamondInvalidArg;
51import static com.sun.tools.javac.resources.CompilerProperties.Fragments.DiamondInvalidArgs;
52import com.sun.tools.javac.resources.CompilerProperties.Errors;
53import com.sun.tools.javac.resources.CompilerProperties.Fragments;
54import com.sun.tools.javac.tree.*;
55import com.sun.tools.javac.tree.JCTree.*;
56import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*;
57import com.sun.tools.javac.util.*;
58import com.sun.tools.javac.util.DefinedBy.Api;
59import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
60import com.sun.tools.javac.util.JCDiagnostic.Fragment;
61import com.sun.tools.javac.util.List;
62import static com.sun.tools.javac.code.Flags.*;
63import static com.sun.tools.javac.code.Flags.ANNOTATION;
64import static com.sun.tools.javac.code.Flags.BLOCK;
65import static com.sun.tools.javac.code.Kinds.*;
66import static com.sun.tools.javac.code.Kinds.Kind.*;
67import static com.sun.tools.javac.code.TypeTag.*;
68import static com.sun.tools.javac.code.TypeTag.WILDCARD;
69import static com.sun.tools.javac.tree.JCTree.Tag.*;
70
71/** This is the main context-dependent analysis phase in GJC. It
72 *  encompasses name resolution, type checking and constant folding as
73 *  subtasks. Some subtasks involve auxiliary classes.
74 *  @see Check
75 *  @see Resolve
76 *  @see ConstFold
77 *  @see Infer
78 *
79 *  <p><b>This is NOT part of any supported API.
80 *  If you write code that depends on this, you do so at your own risk.
81 *  This code and its internal interfaces are subject to change or
82 *  deletion without notice.</b>
83 */
84public class Attr extends JCTree.Visitor {
85    protected static final Context.Key<Attr> attrKey = new Context.Key<>();
86
87    final Names names;
88    final Log log;
89    final Symtab syms;
90    final Resolve rs;
91    final Operators operators;
92    final Infer infer;
93    final Analyzer analyzer;
94    final DeferredAttr deferredAttr;
95    final Check chk;
96    final Flow flow;
97    final MemberEnter memberEnter;
98    final TypeEnter typeEnter;
99    final TreeMaker make;
100    final ConstFold cfolder;
101    final Enter enter;
102    final Target target;
103    final Types types;
104    final JCDiagnostic.Factory diags;
105    final TypeAnnotations typeAnnotations;
106    final DeferredLintHandler deferredLintHandler;
107    final TypeEnvs typeEnvs;
108    final Dependencies dependencies;
109    final Annotate annotate;
110    final ArgumentAttr argumentAttr;
111
112    public static Attr instance(Context context) {
113        Attr instance = context.get(attrKey);
114        if (instance == null)
115            instance = new Attr(context);
116        return instance;
117    }
118
119    protected Attr(Context context) {
120        context.put(attrKey, this);
121
122        names = Names.instance(context);
123        log = Log.instance(context);
124        syms = Symtab.instance(context);
125        rs = Resolve.instance(context);
126        operators = Operators.instance(context);
127        chk = Check.instance(context);
128        flow = Flow.instance(context);
129        memberEnter = MemberEnter.instance(context);
130        typeEnter = TypeEnter.instance(context);
131        make = TreeMaker.instance(context);
132        enter = Enter.instance(context);
133        infer = Infer.instance(context);
134        analyzer = Analyzer.instance(context);
135        deferredAttr = DeferredAttr.instance(context);
136        cfolder = ConstFold.instance(context);
137        target = Target.instance(context);
138        types = Types.instance(context);
139        diags = JCDiagnostic.Factory.instance(context);
140        annotate = Annotate.instance(context);
141        typeAnnotations = TypeAnnotations.instance(context);
142        deferredLintHandler = DeferredLintHandler.instance(context);
143        typeEnvs = TypeEnvs.instance(context);
144        dependencies = Dependencies.instance(context);
145        argumentAttr = ArgumentAttr.instance(context);
146
147        Options options = Options.instance(context);
148
149        Source source = Source.instance(context);
150        allowStringsInSwitch = source.allowStringsInSwitch();
151        allowPoly = source.allowPoly();
152        allowTypeAnnos = source.allowTypeAnnotations();
153        allowLambda = source.allowLambda();
154        allowDefaultMethods = source.allowDefaultMethods();
155        allowStaticInterfaceMethods = source.allowStaticInterfaceMethods();
156        sourceName = source.name;
157        relax = (options.isSet("-retrofit") ||
158                options.isSet("-relax"));
159        useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
160
161        statInfo = new ResultInfo(KindSelector.NIL, Type.noType);
162        varAssignmentInfo = new ResultInfo(KindSelector.ASG, Type.noType);
163        unknownExprInfo = new ResultInfo(KindSelector.VAL, Type.noType);
164        methodAttrInfo = new MethodAttrInfo();
165        unknownTypeInfo = new ResultInfo(KindSelector.TYP, Type.noType);
166        unknownTypeExprInfo = new ResultInfo(KindSelector.VAL_TYP, Type.noType);
167        recoveryInfo = new RecoveryInfo(deferredAttr.emptyDeferredAttrContext);
168    }
169
170    /** Switch: relax some constraints for retrofit mode.
171     */
172    boolean relax;
173
174    /** Switch: support target-typing inference
175     */
176    boolean allowPoly;
177
178    /** Switch: support type annotations.
179     */
180    boolean allowTypeAnnos;
181
182    /** Switch: support lambda expressions ?
183     */
184    boolean allowLambda;
185
186    /** Switch: support default methods ?
187     */
188    boolean allowDefaultMethods;
189
190    /** Switch: static interface methods enabled?
191     */
192    boolean allowStaticInterfaceMethods;
193
194    /**
195     * Switch: warn about use of variable before declaration?
196     * RFE: 6425594
197     */
198    boolean useBeforeDeclarationWarning;
199
200    /**
201     * Switch: allow strings in switch?
202     */
203    boolean allowStringsInSwitch;
204
205    /**
206     * Switch: name of source level; used for error reporting.
207     */
208    String sourceName;
209
210    /** Check kind and type of given tree against protokind and prototype.
211     *  If check succeeds, store type in tree and return it.
212     *  If check fails, store errType in tree and return it.
213     *  No checks are performed if the prototype is a method type.
214     *  It is not necessary in this case since we know that kind and type
215     *  are correct.
216     *
217     *  @param tree     The tree whose kind and type is checked
218     *  @param found    The computed type of the tree
219     *  @param ownkind  The computed kind of the tree
220     *  @param resultInfo  The expected result of the tree
221     */
222    Type check(final JCTree tree,
223               final Type found,
224               final KindSelector ownkind,
225               final ResultInfo resultInfo) {
226        InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
227        Type owntype;
228        boolean shouldCheck = !found.hasTag(ERROR) &&
229                !resultInfo.pt.hasTag(METHOD) &&
230                !resultInfo.pt.hasTag(FORALL);
231        if (shouldCheck && !ownkind.subset(resultInfo.pkind)) {
232            log.error(tree.pos(), "unexpected.type",
233            resultInfo.pkind.kindNames(),
234            ownkind.kindNames());
235            owntype = types.createErrorType(found);
236        } else if (allowPoly && inferenceContext.free(found)) {
237            //delay the check if there are inference variables in the found type
238            //this means we are dealing with a partially inferred poly expression
239            owntype = shouldCheck ? resultInfo.pt : found;
240            if (resultInfo.checkMode.installPostInferenceHook()) {
241                inferenceContext.addFreeTypeListener(List.of(found, resultInfo.pt),
242                        instantiatedContext -> {
243                            ResultInfo pendingResult =
244                                    resultInfo.dup(inferenceContext.asInstType(resultInfo.pt));
245                            check(tree, inferenceContext.asInstType(found), ownkind, pendingResult);
246                        });
247            }
248        } else {
249            owntype = shouldCheck ?
250            resultInfo.check(tree, found) :
251            found;
252        }
253        if (resultInfo.checkMode.updateTreeType()) {
254            tree.type = owntype;
255        }
256        return owntype;
257    }
258
259    /** Is given blank final variable assignable, i.e. in a scope where it
260     *  may be assigned to even though it is final?
261     *  @param v      The blank final variable.
262     *  @param env    The current environment.
263     */
264    boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
265        Symbol owner = env.info.scope.owner;
266           // owner refers to the innermost variable, method or
267           // initializer block declaration at this point.
268        return
269            v.owner == owner
270            ||
271            ((owner.name == names.init ||    // i.e. we are in a constructor
272              owner.kind == VAR ||           // i.e. we are in a variable initializer
273              (owner.flags() & BLOCK) != 0)  // i.e. we are in an initializer block
274             &&
275             v.owner == owner.owner
276             &&
277             ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
278    }
279
280    /** Check that variable can be assigned to.
281     *  @param pos    The current source code position.
282     *  @param v      The assigned variable
283     *  @param base   If the variable is referred to in a Select, the part
284     *                to the left of the `.', null otherwise.
285     *  @param env    The current environment.
286     */
287    void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
288        if ((v.flags() & FINAL) != 0 &&
289            ((v.flags() & HASINIT) != 0
290             ||
291             !((base == null ||
292               (base.hasTag(IDENT) && TreeInfo.name(base) == names._this)) &&
293               isAssignableAsBlankFinal(v, env)))) {
294            if (v.isResourceVariable()) { //TWR resource
295                log.error(pos, "try.resource.may.not.be.assigned", v);
296            } else {
297                log.error(pos, "cant.assign.val.to.final.var", v);
298            }
299        }
300    }
301
302    /** Does tree represent a static reference to an identifier?
303     *  It is assumed that tree is either a SELECT or an IDENT.
304     *  We have to weed out selects from non-type names here.
305     *  @param tree    The candidate tree.
306     */
307    boolean isStaticReference(JCTree tree) {
308        if (tree.hasTag(SELECT)) {
309            Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
310            if (lsym == null || lsym.kind != TYP) {
311                return false;
312            }
313        }
314        return true;
315    }
316
317    /** Is this symbol a type?
318     */
319    static boolean isType(Symbol sym) {
320        return sym != null && sym.kind == TYP;
321    }
322
323    /** The current `this' symbol.
324     *  @param env    The current environment.
325     */
326    Symbol thisSym(DiagnosticPosition pos, Env<AttrContext> env) {
327        return rs.resolveSelf(pos, env, env.enclClass.sym, names._this);
328    }
329
330    /** Attribute a parsed identifier.
331     * @param tree Parsed identifier name
332     * @param topLevel The toplevel to use
333     */
334    public Symbol attribIdent(JCTree tree, JCCompilationUnit topLevel) {
335        Env<AttrContext> localEnv = enter.topLevelEnv(topLevel);
336        localEnv.enclClass = make.ClassDef(make.Modifiers(0),
337                                           syms.errSymbol.name,
338                                           null, null, null, null);
339        localEnv.enclClass.sym = syms.errSymbol;
340        return tree.accept(identAttributer, localEnv);
341    }
342    // where
343        private TreeVisitor<Symbol,Env<AttrContext>> identAttributer = new IdentAttributer();
344        private class IdentAttributer extends SimpleTreeVisitor<Symbol,Env<AttrContext>> {
345            @Override @DefinedBy(Api.COMPILER_TREE)
346            public Symbol visitMemberSelect(MemberSelectTree node, Env<AttrContext> env) {
347                Symbol site = visit(node.getExpression(), env);
348                if (site.kind == ERR || site.kind == ABSENT_TYP)
349                    return site;
350                Name name = (Name)node.getIdentifier();
351                if (site.kind == PCK) {
352                    env.toplevel.packge = (PackageSymbol)site;
353                    return rs.findIdentInPackage(env, (TypeSymbol)site, name,
354                            KindSelector.TYP_PCK);
355                } else {
356                    env.enclClass.sym = (ClassSymbol)site;
357                    return rs.findMemberType(env, site.asType(), name, (TypeSymbol)site);
358                }
359            }
360
361            @Override @DefinedBy(Api.COMPILER_TREE)
362            public Symbol visitIdentifier(IdentifierTree node, Env<AttrContext> env) {
363                return rs.findIdent(env, (Name)node.getName(), KindSelector.TYP_PCK);
364            }
365        }
366
367    public Type coerce(Type etype, Type ttype) {
368        return cfolder.coerce(etype, ttype);
369    }
370
371    public Type attribType(JCTree node, TypeSymbol sym) {
372        Env<AttrContext> env = typeEnvs.get(sym);
373        Env<AttrContext> localEnv = env.dup(node, env.info.dup());
374        return attribTree(node, localEnv, unknownTypeInfo);
375    }
376
377    public Type attribImportQualifier(JCImport tree, Env<AttrContext> env) {
378        // Attribute qualifying package or class.
379        JCFieldAccess s = (JCFieldAccess)tree.qualid;
380        return attribTree(s.selected, env,
381                          new ResultInfo(tree.staticImport ?
382                                         KindSelector.TYP : KindSelector.TYP_PCK,
383                       Type.noType));
384    }
385
386    public Env<AttrContext> attribExprToTree(JCTree expr, Env<AttrContext> env, JCTree tree) {
387        breakTree = tree;
388        JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
389        try {
390            attribExpr(expr, env);
391        } catch (BreakAttr b) {
392            return b.env;
393        } catch (AssertionError ae) {
394            if (ae.getCause() instanceof BreakAttr) {
395                return ((BreakAttr)(ae.getCause())).env;
396            } else {
397                throw ae;
398            }
399        } finally {
400            breakTree = null;
401            log.useSource(prev);
402        }
403        return env;
404    }
405
406    public Env<AttrContext> attribStatToTree(JCTree stmt, Env<AttrContext> env, JCTree tree) {
407        breakTree = tree;
408        JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
409        try {
410            attribStat(stmt, env);
411        } catch (BreakAttr b) {
412            return b.env;
413        } catch (AssertionError ae) {
414            if (ae.getCause() instanceof BreakAttr) {
415                return ((BreakAttr)(ae.getCause())).env;
416            } else {
417                throw ae;
418            }
419        } finally {
420            breakTree = null;
421            log.useSource(prev);
422        }
423        return env;
424    }
425
426    private JCTree breakTree = null;
427
428    private static class BreakAttr extends RuntimeException {
429        static final long serialVersionUID = -6924771130405446405L;
430        private Env<AttrContext> env;
431        private BreakAttr(Env<AttrContext> env) {
432            this.env = env;
433        }
434    }
435
436    /**
437     * Mode controlling behavior of Attr.Check
438     */
439    enum CheckMode {
440
441        NORMAL,
442
443        NO_TREE_UPDATE {     // Mode signalling 'fake check' - skip tree update
444            @Override
445            public boolean updateTreeType() {
446                return false;
447            }
448        },
449        NO_INFERENCE_HOOK { // Mode signalling that caller will manage free types in tree decorations.
450            @Override
451            public boolean installPostInferenceHook() {
452                return false;
453            }
454        };
455
456        public boolean updateTreeType() {
457            return true;
458        }
459        public boolean installPostInferenceHook() {
460            return true;
461        }
462    }
463
464
465    class ResultInfo {
466        final KindSelector pkind;
467        final Type pt;
468        final CheckContext checkContext;
469        final CheckMode checkMode;
470
471        ResultInfo(KindSelector pkind, Type pt) {
472            this(pkind, pt, chk.basicHandler, CheckMode.NORMAL);
473        }
474
475        ResultInfo(KindSelector pkind, Type pt, CheckMode checkMode) {
476            this(pkind, pt, chk.basicHandler, checkMode);
477        }
478
479        protected ResultInfo(KindSelector pkind,
480                             Type pt, CheckContext checkContext) {
481            this(pkind, pt, checkContext, CheckMode.NORMAL);
482        }
483
484        protected ResultInfo(KindSelector pkind,
485                             Type pt, CheckContext checkContext, CheckMode checkMode) {
486            this.pkind = pkind;
487            this.pt = pt;
488            this.checkContext = checkContext;
489            this.checkMode = checkMode;
490        }
491
492        protected void attr(JCTree tree, Env<AttrContext> env) {
493            tree.accept(Attr.this);
494        }
495
496        protected Type check(final DiagnosticPosition pos, final Type found) {
497            return chk.checkType(pos, found, pt, checkContext);
498        }
499
500        protected ResultInfo dup(Type newPt) {
501            return new ResultInfo(pkind, newPt, checkContext, checkMode);
502        }
503
504        protected ResultInfo dup(CheckContext newContext) {
505            return new ResultInfo(pkind, pt, newContext, checkMode);
506        }
507
508        protected ResultInfo dup(Type newPt, CheckContext newContext) {
509            return new ResultInfo(pkind, newPt, newContext, checkMode);
510        }
511
512        protected ResultInfo dup(Type newPt, CheckContext newContext, CheckMode newMode) {
513            return new ResultInfo(pkind, newPt, newContext, newMode);
514        }
515
516        protected ResultInfo dup(CheckMode newMode) {
517            return new ResultInfo(pkind, pt, checkContext, newMode);
518        }
519
520        @Override
521        public String toString() {
522            if (pt != null) {
523                return pt.toString();
524            } else {
525                return "";
526            }
527        }
528    }
529
530    class MethodAttrInfo extends ResultInfo {
531        public MethodAttrInfo() {
532            this(chk.basicHandler);
533        }
534
535        public MethodAttrInfo(CheckContext checkContext) {
536            super(KindSelector.VAL, Infer.anyPoly, checkContext);
537        }
538
539        @Override
540        protected void attr(JCTree tree, Env<AttrContext> env) {
541            result = argumentAttr.attribArg(tree, env);
542        }
543
544        protected ResultInfo dup(Type newPt) {
545            throw new IllegalStateException();
546        }
547
548        protected ResultInfo dup(CheckContext newContext) {
549            return new MethodAttrInfo(newContext);
550        }
551
552        protected ResultInfo dup(Type newPt, CheckContext newContext) {
553            throw new IllegalStateException();
554        }
555
556        protected ResultInfo dup(Type newPt, CheckContext newContext, CheckMode newMode) {
557            throw new IllegalStateException();
558        }
559
560        protected ResultInfo dup(CheckMode newMode) {
561            throw new IllegalStateException();
562        }
563    }
564
565    class RecoveryInfo extends ResultInfo {
566
567        public RecoveryInfo(final DeferredAttr.DeferredAttrContext deferredAttrContext) {
568            super(KindSelector.VAL, Type.recoveryType,
569                  new Check.NestedCheckContext(chk.basicHandler) {
570                @Override
571                public DeferredAttr.DeferredAttrContext deferredAttrContext() {
572                    return deferredAttrContext;
573                }
574                @Override
575                public boolean compatible(Type found, Type req, Warner warn) {
576                    return true;
577                }
578                @Override
579                public void report(DiagnosticPosition pos, JCDiagnostic details) {
580                    chk.basicHandler.report(pos, details);
581                }
582            });
583        }
584    }
585
586    final ResultInfo statInfo;
587    final ResultInfo varAssignmentInfo;
588    final ResultInfo methodAttrInfo;
589    final ResultInfo unknownExprInfo;
590    final ResultInfo unknownTypeInfo;
591    final ResultInfo unknownTypeExprInfo;
592    final ResultInfo recoveryInfo;
593
594    Type pt() {
595        return resultInfo.pt;
596    }
597
598    KindSelector pkind() {
599        return resultInfo.pkind;
600    }
601
602/* ************************************************************************
603 * Visitor methods
604 *************************************************************************/
605
606    /** Visitor argument: the current environment.
607     */
608    Env<AttrContext> env;
609
610    /** Visitor argument: the currently expected attribution result.
611     */
612    ResultInfo resultInfo;
613
614    /** Visitor result: the computed type.
615     */
616    Type result;
617
618    /** Visitor method: attribute a tree, catching any completion failure
619     *  exceptions. Return the tree's type.
620     *
621     *  @param tree    The tree to be visited.
622     *  @param env     The environment visitor argument.
623     *  @param resultInfo   The result info visitor argument.
624     */
625    Type attribTree(JCTree tree, Env<AttrContext> env, ResultInfo resultInfo) {
626        Env<AttrContext> prevEnv = this.env;
627        ResultInfo prevResult = this.resultInfo;
628        try {
629            this.env = env;
630            this.resultInfo = resultInfo;
631            resultInfo.attr(tree, env);
632            if (tree == breakTree &&
633                    resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
634                throw new BreakAttr(copyEnv(env));
635            }
636            return result;
637        } catch (CompletionFailure ex) {
638            tree.type = syms.errType;
639            return chk.completionError(tree.pos(), ex);
640        } finally {
641            this.env = prevEnv;
642            this.resultInfo = prevResult;
643        }
644    }
645
646    Env<AttrContext> copyEnv(Env<AttrContext> env) {
647        Env<AttrContext> newEnv =
648                env.dup(env.tree, env.info.dup(copyScope(env.info.scope)));
649        if (newEnv.outer != null) {
650            newEnv.outer = copyEnv(newEnv.outer);
651        }
652        return newEnv;
653    }
654
655    WriteableScope copyScope(WriteableScope sc) {
656        WriteableScope newScope = WriteableScope.create(sc.owner);
657        List<Symbol> elemsList = List.nil();
658        for (Symbol sym : sc.getSymbols()) {
659            elemsList = elemsList.prepend(sym);
660        }
661        for (Symbol s : elemsList) {
662            newScope.enter(s);
663        }
664        return newScope;
665    }
666
667    /** Derived visitor method: attribute an expression tree.
668     */
669    public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) {
670        return attribTree(tree, env, new ResultInfo(KindSelector.VAL, !pt.hasTag(ERROR) ? pt : Type.noType));
671    }
672
673    /** Derived visitor method: attribute an expression tree with
674     *  no constraints on the computed type.
675     */
676    public Type attribExpr(JCTree tree, Env<AttrContext> env) {
677        return attribTree(tree, env, unknownExprInfo);
678    }
679
680    /** Derived visitor method: attribute a type tree.
681     */
682    public Type attribType(JCTree tree, Env<AttrContext> env) {
683        Type result = attribType(tree, env, Type.noType);
684        return result;
685    }
686
687    /** Derived visitor method: attribute a type tree.
688     */
689    Type attribType(JCTree tree, Env<AttrContext> env, Type pt) {
690        Type result = attribTree(tree, env, new ResultInfo(KindSelector.TYP, pt));
691        return result;
692    }
693
694    /** Derived visitor method: attribute a statement or definition tree.
695     */
696    public Type attribStat(JCTree tree, Env<AttrContext> env) {
697        Env<AttrContext> analyzeEnv =
698                env.dup(tree, env.info.dup(env.info.scope.dupUnshared(env.info.scope.owner)));
699        try {
700            return attribTree(tree, env, statInfo);
701        } finally {
702            analyzer.analyzeIfNeeded(tree, analyzeEnv);
703        }
704    }
705
706    /** Attribute a list of expressions, returning a list of types.
707     */
708    List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) {
709        ListBuffer<Type> ts = new ListBuffer<>();
710        for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
711            ts.append(attribExpr(l.head, env, pt));
712        return ts.toList();
713    }
714
715    /** Attribute a list of statements, returning nothing.
716     */
717    <T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) {
718        for (List<T> l = trees; l.nonEmpty(); l = l.tail)
719            attribStat(l.head, env);
720    }
721
722    /** Attribute the arguments in a method call, returning the method kind.
723     */
724    KindSelector attribArgs(KindSelector initialKind, List<JCExpression> trees, Env<AttrContext> env, ListBuffer<Type> argtypes) {
725        KindSelector kind = initialKind;
726        for (JCExpression arg : trees) {
727            Type argtype = chk.checkNonVoid(arg, attribTree(arg, env, allowPoly ? methodAttrInfo : unknownExprInfo));
728            if (argtype.hasTag(DEFERRED)) {
729                kind = KindSelector.of(KindSelector.POLY, kind);
730            }
731            argtypes.append(argtype);
732        }
733        return kind;
734    }
735
736    /** Attribute a type argument list, returning a list of types.
737     *  Caller is responsible for calling checkRefTypes.
738     */
739    List<Type> attribAnyTypes(List<JCExpression> trees, Env<AttrContext> env) {
740        ListBuffer<Type> argtypes = new ListBuffer<>();
741        for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
742            argtypes.append(attribType(l.head, env));
743        return argtypes.toList();
744    }
745
746    /** Attribute a type argument list, returning a list of types.
747     *  Check that all the types are references.
748     */
749    List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
750        List<Type> types = attribAnyTypes(trees, env);
751        return chk.checkRefTypes(trees, types);
752    }
753
754    /**
755     * Attribute type variables (of generic classes or methods).
756     * Compound types are attributed later in attribBounds.
757     * @param typarams the type variables to enter
758     * @param env      the current environment
759     */
760    void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env) {
761        for (JCTypeParameter tvar : typarams) {
762            TypeVar a = (TypeVar)tvar.type;
763            a.tsym.flags_field |= UNATTRIBUTED;
764            a.bound = Type.noType;
765            if (!tvar.bounds.isEmpty()) {
766                List<Type> bounds = List.of(attribType(tvar.bounds.head, env));
767                for (JCExpression bound : tvar.bounds.tail)
768                    bounds = bounds.prepend(attribType(bound, env));
769                types.setBounds(a, bounds.reverse());
770            } else {
771                // if no bounds are given, assume a single bound of
772                // java.lang.Object.
773                types.setBounds(a, List.of(syms.objectType));
774            }
775            a.tsym.flags_field &= ~UNATTRIBUTED;
776        }
777        for (JCTypeParameter tvar : typarams) {
778            chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
779        }
780    }
781
782    /**
783     * Attribute the type references in a list of annotations.
784     */
785    void attribAnnotationTypes(List<JCAnnotation> annotations,
786                               Env<AttrContext> env) {
787        for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
788            JCAnnotation a = al.head;
789            attribType(a.annotationType, env);
790        }
791    }
792
793    /**
794     * Attribute a "lazy constant value".
795     *  @param env         The env for the const value
796     *  @param variable    The initializer for the const value
797     *  @param type        The expected type, or null
798     *  @see VarSymbol#setLazyConstValue
799     */
800    public Object attribLazyConstantValue(Env<AttrContext> env,
801                                      JCVariableDecl variable,
802                                      Type type) {
803
804        DiagnosticPosition prevLintPos
805                = deferredLintHandler.setPos(variable.pos());
806
807        try {
808            Type itype = attribExpr(variable.init, env, type);
809            if (itype.constValue() != null) {
810                return coerce(itype, type).constValue();
811            } else {
812                return null;
813            }
814        } finally {
815            deferredLintHandler.setPos(prevLintPos);
816        }
817    }
818
819    /** Attribute type reference in an `extends' or `implements' clause.
820     *  Supertypes of anonymous inner classes are usually already attributed.
821     *
822     *  @param tree              The tree making up the type reference.
823     *  @param env               The environment current at the reference.
824     *  @param classExpected     true if only a class is expected here.
825     *  @param interfaceExpected true if only an interface is expected here.
826     */
827    Type attribBase(JCTree tree,
828                    Env<AttrContext> env,
829                    boolean classExpected,
830                    boolean interfaceExpected,
831                    boolean checkExtensible) {
832        Type t = tree.type != null ?
833            tree.type :
834            attribType(tree, env);
835        return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible);
836    }
837    Type checkBase(Type t,
838                   JCTree tree,
839                   Env<AttrContext> env,
840                   boolean classExpected,
841                   boolean interfaceExpected,
842                   boolean checkExtensible) {
843        final DiagnosticPosition pos = tree.hasTag(TYPEAPPLY) ?
844                (((JCTypeApply) tree).clazz).pos() : tree.pos();
845        if (t.tsym.isAnonymous()) {
846            log.error(pos, "cant.inherit.from.anon");
847            return types.createErrorType(t);
848        }
849        if (t.isErroneous())
850            return t;
851        if (t.hasTag(TYPEVAR) && !classExpected && !interfaceExpected) {
852            // check that type variable is already visible
853            if (t.getUpperBound() == null) {
854                log.error(pos, "illegal.forward.ref");
855                return types.createErrorType(t);
856            }
857        } else {
858            t = chk.checkClassType(pos, t, checkExtensible);
859        }
860        if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) {
861            log.error(pos, "intf.expected.here");
862            // return errType is necessary since otherwise there might
863            // be undetected cycles which cause attribution to loop
864            return types.createErrorType(t);
865        } else if (checkExtensible &&
866                   classExpected &&
867                   (t.tsym.flags() & INTERFACE) != 0) {
868            log.error(pos, "no.intf.expected.here");
869            return types.createErrorType(t);
870        }
871        if (checkExtensible &&
872            ((t.tsym.flags() & FINAL) != 0)) {
873            log.error(pos,
874                      "cant.inherit.from.final", t.tsym);
875        }
876        chk.checkNonCyclic(pos, t);
877        return t;
878    }
879
880    Type attribIdentAsEnumType(Env<AttrContext> env, JCIdent id) {
881        Assert.check((env.enclClass.sym.flags() & ENUM) != 0);
882        id.type = env.info.scope.owner.enclClass().type;
883        id.sym = env.info.scope.owner.enclClass();
884        return id.type;
885    }
886
887    public void visitClassDef(JCClassDecl tree) {
888        // Local and anonymous classes have not been entered yet, so we need to
889        // do it now.
890        if (env.info.scope.owner.kind.matches(KindSelector.VAL_MTH)) {
891            enter.classEnter(tree, env);
892        } else {
893            // If this class declaration is part of a class level annotation,
894            // as in @MyAnno(new Object() {}) class MyClass {}, enter it in
895            // order to simplify later steps and allow for sensible error
896            // messages.
897            if (env.tree.hasTag(NEWCLASS) && TreeInfo.isInAnnotation(env, tree))
898                enter.classEnter(tree, env);
899        }
900
901        ClassSymbol c = tree.sym;
902        if (c == null) {
903            // exit in case something drastic went wrong during enter.
904            result = null;
905        } else {
906            // make sure class has been completed:
907            c.complete();
908
909            // If this class appears as an anonymous class
910            // in a superclass constructor call where
911            // no explicit outer instance is given,
912            // disable implicit outer instance from being passed.
913            // (This would be an illegal access to "this before super").
914            if (env.info.isSelfCall &&
915                env.tree.hasTag(NEWCLASS) &&
916                ((JCNewClass) env.tree).encl == null)
917            {
918                c.flags_field |= NOOUTERTHIS;
919            }
920            attribClass(tree.pos(), c);
921            result = tree.type = c.type;
922        }
923    }
924
925    public void visitMethodDef(JCMethodDecl tree) {
926        MethodSymbol m = tree.sym;
927        boolean isDefaultMethod = (m.flags() & DEFAULT) != 0;
928
929        Lint lint = env.info.lint.augment(m);
930        Lint prevLint = chk.setLint(lint);
931        MethodSymbol prevMethod = chk.setMethod(m);
932        try {
933            deferredLintHandler.flush(tree.pos());
934            chk.checkDeprecatedAnnotation(tree.pos(), m);
935
936
937            // Create a new environment with local scope
938            // for attributing the method.
939            Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
940            localEnv.info.lint = lint;
941
942            attribStats(tree.typarams, localEnv);
943
944            // If we override any other methods, check that we do so properly.
945            // JLS ???
946            if (m.isStatic()) {
947                chk.checkHideClashes(tree.pos(), env.enclClass.type, m);
948            } else {
949                chk.checkOverrideClashes(tree.pos(), env.enclClass.type, m);
950            }
951            chk.checkOverride(env, tree, m);
952
953            if (isDefaultMethod && types.overridesObjectMethod(m.enclClass(), m)) {
954                log.error(tree, "default.overrides.object.member", m.name, Kinds.kindName(m.location()), m.location());
955            }
956
957            // Enter all type parameters into the local method scope.
958            for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
959                localEnv.info.scope.enterIfAbsent(l.head.type.tsym);
960
961            ClassSymbol owner = env.enclClass.sym;
962            if ((owner.flags() & ANNOTATION) != 0 &&
963                    tree.params.nonEmpty())
964                log.error(tree.params.head.pos(),
965                        "intf.annotation.members.cant.have.params");
966
967            // Attribute all value parameters.
968            for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
969                attribStat(l.head, localEnv);
970            }
971
972            chk.checkVarargsMethodDecl(localEnv, tree);
973
974            // Check that type parameters are well-formed.
975            chk.validate(tree.typarams, localEnv);
976
977            // Check that result type is well-formed.
978            if (tree.restype != null && !tree.restype.type.hasTag(VOID))
979                chk.validate(tree.restype, localEnv);
980
981            // Check that receiver type is well-formed.
982            if (tree.recvparam != null) {
983                // Use a new environment to check the receiver parameter.
984                // Otherwise I get "might not have been initialized" errors.
985                // Is there a better way?
986                Env<AttrContext> newEnv = memberEnter.methodEnv(tree, env);
987                attribType(tree.recvparam, newEnv);
988                chk.validate(tree.recvparam, newEnv);
989            }
990
991            // annotation method checks
992            if ((owner.flags() & ANNOTATION) != 0) {
993                // annotation method cannot have throws clause
994                if (tree.thrown.nonEmpty()) {
995                    log.error(tree.thrown.head.pos(),
996                            "throws.not.allowed.in.intf.annotation");
997                }
998                // annotation method cannot declare type-parameters
999                if (tree.typarams.nonEmpty()) {
1000                    log.error(tree.typarams.head.pos(),
1001                            "intf.annotation.members.cant.have.type.params");
1002                }
1003                // validate annotation method's return type (could be an annotation type)
1004                chk.validateAnnotationType(tree.restype);
1005                // ensure that annotation method does not clash with members of Object/Annotation
1006                chk.validateAnnotationMethod(tree.pos(), m);
1007            }
1008
1009            for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
1010                chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
1011
1012            if (tree.body == null) {
1013                // Empty bodies are only allowed for
1014                // abstract, native, or interface methods, or for methods
1015                // in a retrofit signature class.
1016                if (tree.defaultValue != null) {
1017                    if ((owner.flags() & ANNOTATION) == 0)
1018                        log.error(tree.pos(),
1019                                  "default.allowed.in.intf.annotation.member");
1020                }
1021                if (isDefaultMethod || (tree.sym.flags() & (ABSTRACT | NATIVE)) == 0 &&
1022                    !relax)
1023                    log.error(tree.pos(), "missing.meth.body.or.decl.abstract");
1024            } else if ((tree.sym.flags() & (ABSTRACT|DEFAULT|PRIVATE)) == ABSTRACT) {
1025                if ((owner.flags() & INTERFACE) != 0) {
1026                    log.error(tree.body.pos(), "intf.meth.cant.have.body");
1027                } else {
1028                    log.error(tree.pos(), "abstract.meth.cant.have.body");
1029                }
1030            } else if ((tree.mods.flags & NATIVE) != 0) {
1031                log.error(tree.pos(), "native.meth.cant.have.body");
1032            } else {
1033                // Add an implicit super() call unless an explicit call to
1034                // super(...) or this(...) is given
1035                // or we are compiling class java.lang.Object.
1036                if (tree.name == names.init && owner.type != syms.objectType) {
1037                    JCBlock body = tree.body;
1038                    if (body.stats.isEmpty() ||
1039                            !TreeInfo.isSelfCall(body.stats.head)) {
1040                        body.stats = body.stats.
1041                                prepend(typeEnter.SuperCall(make.at(body.pos),
1042                                        List.<Type>nil(),
1043                                        List.<JCVariableDecl>nil(),
1044                                        false));
1045                    } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
1046                            (tree.mods.flags & GENERATEDCONSTR) == 0 &&
1047                            TreeInfo.isSuperCall(body.stats.head)) {
1048                        // enum constructors are not allowed to call super
1049                        // directly, so make sure there aren't any super calls
1050                        // in enum constructors, except in the compiler
1051                        // generated one.
1052                        log.error(tree.body.stats.head.pos(),
1053                                "call.to.super.not.allowed.in.enum.ctor",
1054                                env.enclClass.sym);
1055                    }
1056                }
1057
1058                // Attribute all type annotations in the body
1059                annotate.queueScanTreeAndTypeAnnotate(tree.body, localEnv, m, null);
1060                annotate.flush();
1061
1062                // Attribute method body.
1063                attribStat(tree.body, localEnv);
1064            }
1065
1066            localEnv.info.scope.leave();
1067            result = tree.type = m.type;
1068        } finally {
1069            chk.setLint(prevLint);
1070            chk.setMethod(prevMethod);
1071        }
1072    }
1073
1074    public void visitVarDef(JCVariableDecl tree) {
1075        // Local variables have not been entered yet, so we need to do it now:
1076        if (env.info.scope.owner.kind == MTH) {
1077            if (tree.sym != null) {
1078                // parameters have already been entered
1079                env.info.scope.enter(tree.sym);
1080            } else {
1081                try {
1082                    annotate.blockAnnotations();
1083                    memberEnter.memberEnter(tree, env);
1084                } finally {
1085                    annotate.unblockAnnotations();
1086                }
1087            }
1088        } else {
1089            if (tree.init != null) {
1090                // Field initializer expression need to be entered.
1091                annotate.queueScanTreeAndTypeAnnotate(tree.init, env, tree.sym, tree.pos());
1092                annotate.flush();
1093            }
1094        }
1095
1096        VarSymbol v = tree.sym;
1097        Lint lint = env.info.lint.augment(v);
1098        Lint prevLint = chk.setLint(lint);
1099
1100        // Check that the variable's declared type is well-formed.
1101        boolean isImplicitLambdaParameter = env.tree.hasTag(LAMBDA) &&
1102                ((JCLambda)env.tree).paramKind == JCLambda.ParameterKind.IMPLICIT &&
1103                (tree.sym.flags() & PARAMETER) != 0;
1104        chk.validate(tree.vartype, env, !isImplicitLambdaParameter);
1105
1106        try {
1107            v.getConstValue(); // ensure compile-time constant initializer is evaluated
1108            deferredLintHandler.flush(tree.pos());
1109            chk.checkDeprecatedAnnotation(tree.pos(), v);
1110
1111            if (tree.init != null) {
1112                if ((v.flags_field & FINAL) == 0 ||
1113                    !memberEnter.needsLazyConstValue(tree.init)) {
1114                    // Not a compile-time constant
1115                    // Attribute initializer in a new environment
1116                    // with the declared variable as owner.
1117                    // Check that initializer conforms to variable's declared type.
1118                    Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
1119                    initEnv.info.lint = lint;
1120                    // In order to catch self-references, we set the variable's
1121                    // declaration position to maximal possible value, effectively
1122                    // marking the variable as undefined.
1123                    initEnv.info.enclVar = v;
1124                    attribExpr(tree.init, initEnv, v.type);
1125                }
1126            }
1127            result = tree.type = v.type;
1128        }
1129        finally {
1130            chk.setLint(prevLint);
1131        }
1132    }
1133
1134    public void visitSkip(JCSkip tree) {
1135        result = null;
1136    }
1137
1138    public void visitBlock(JCBlock tree) {
1139        if (env.info.scope.owner.kind == TYP) {
1140            // Block is a static or instance initializer;
1141            // let the owner of the environment be a freshly
1142            // created BLOCK-method.
1143            Symbol fakeOwner =
1144                new MethodSymbol(tree.flags | BLOCK |
1145                    env.info.scope.owner.flags() & STRICTFP, names.empty, null,
1146                    env.info.scope.owner);
1147            final Env<AttrContext> localEnv =
1148                env.dup(tree, env.info.dup(env.info.scope.dupUnshared(fakeOwner)));
1149
1150            if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
1151            // Attribute all type annotations in the block
1152            annotate.queueScanTreeAndTypeAnnotate(tree, localEnv, localEnv.info.scope.owner, null);
1153            annotate.flush();
1154            attribStats(tree.stats, localEnv);
1155
1156            {
1157                // Store init and clinit type annotations with the ClassSymbol
1158                // to allow output in Gen.normalizeDefs.
1159                ClassSymbol cs = (ClassSymbol)env.info.scope.owner;
1160                List<Attribute.TypeCompound> tas = localEnv.info.scope.owner.getRawTypeAttributes();
1161                if ((tree.flags & STATIC) != 0) {
1162                    cs.appendClassInitTypeAttributes(tas);
1163                } else {
1164                    cs.appendInitTypeAttributes(tas);
1165                }
1166            }
1167        } else {
1168            // Create a new local environment with a local scope.
1169            Env<AttrContext> localEnv =
1170                env.dup(tree, env.info.dup(env.info.scope.dup()));
1171            try {
1172                attribStats(tree.stats, localEnv);
1173            } finally {
1174                localEnv.info.scope.leave();
1175            }
1176        }
1177        result = null;
1178    }
1179
1180    public void visitDoLoop(JCDoWhileLoop tree) {
1181        attribStat(tree.body, env.dup(tree));
1182        attribExpr(tree.cond, env, syms.booleanType);
1183        result = null;
1184    }
1185
1186    public void visitWhileLoop(JCWhileLoop tree) {
1187        attribExpr(tree.cond, env, syms.booleanType);
1188        attribStat(tree.body, env.dup(tree));
1189        result = null;
1190    }
1191
1192    public void visitForLoop(JCForLoop tree) {
1193        Env<AttrContext> loopEnv =
1194            env.dup(env.tree, env.info.dup(env.info.scope.dup()));
1195        try {
1196            attribStats(tree.init, loopEnv);
1197            if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType);
1198            loopEnv.tree = tree; // before, we were not in loop!
1199            attribStats(tree.step, loopEnv);
1200            attribStat(tree.body, loopEnv);
1201            result = null;
1202        }
1203        finally {
1204            loopEnv.info.scope.leave();
1205        }
1206    }
1207
1208    public void visitForeachLoop(JCEnhancedForLoop tree) {
1209        Env<AttrContext> loopEnv =
1210            env.dup(env.tree, env.info.dup(env.info.scope.dup()));
1211        try {
1212            //the Formal Parameter of a for-each loop is not in the scope when
1213            //attributing the for-each expression; we mimick this by attributing
1214            //the for-each expression first (against original scope).
1215            Type exprType = types.cvarUpperBound(attribExpr(tree.expr, loopEnv));
1216            attribStat(tree.var, loopEnv);
1217            chk.checkNonVoid(tree.pos(), exprType);
1218            Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
1219            if (elemtype == null) {
1220                // or perhaps expr implements Iterable<T>?
1221                Type base = types.asSuper(exprType, syms.iterableType.tsym);
1222                if (base == null) {
1223                    log.error(tree.expr.pos(),
1224                            "foreach.not.applicable.to.type",
1225                            exprType,
1226                            diags.fragment("type.req.array.or.iterable"));
1227                    elemtype = types.createErrorType(exprType);
1228                } else {
1229                    List<Type> iterableParams = base.allparams();
1230                    elemtype = iterableParams.isEmpty()
1231                        ? syms.objectType
1232                        : types.wildUpperBound(iterableParams.head);
1233                }
1234            }
1235            chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
1236            loopEnv.tree = tree; // before, we were not in loop!
1237            attribStat(tree.body, loopEnv);
1238            result = null;
1239        }
1240        finally {
1241            loopEnv.info.scope.leave();
1242        }
1243    }
1244
1245    public void visitLabelled(JCLabeledStatement tree) {
1246        // Check that label is not used in an enclosing statement
1247        Env<AttrContext> env1 = env;
1248        while (env1 != null && !env1.tree.hasTag(CLASSDEF)) {
1249            if (env1.tree.hasTag(LABELLED) &&
1250                ((JCLabeledStatement) env1.tree).label == tree.label) {
1251                log.error(tree.pos(), "label.already.in.use",
1252                          tree.label);
1253                break;
1254            }
1255            env1 = env1.next;
1256        }
1257
1258        attribStat(tree.body, env.dup(tree));
1259        result = null;
1260    }
1261
1262    public void visitSwitch(JCSwitch tree) {
1263        Type seltype = attribExpr(tree.selector, env);
1264
1265        Env<AttrContext> switchEnv =
1266            env.dup(tree, env.info.dup(env.info.scope.dup()));
1267
1268        try {
1269
1270            boolean enumSwitch = (seltype.tsym.flags() & Flags.ENUM) != 0;
1271            boolean stringSwitch = false;
1272            if (types.isSameType(seltype, syms.stringType)) {
1273                if (allowStringsInSwitch) {
1274                    stringSwitch = true;
1275                } else {
1276                    log.error(tree.selector.pos(), "string.switch.not.supported.in.source", sourceName);
1277                }
1278            }
1279            if (!enumSwitch && !stringSwitch)
1280                seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType);
1281
1282            // Attribute all cases and
1283            // check that there are no duplicate case labels or default clauses.
1284            Set<Object> labels = new HashSet<>(); // The set of case labels.
1285            boolean hasDefault = false;      // Is there a default label?
1286            for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
1287                JCCase c = l.head;
1288                if (c.pat != null) {
1289                    if (enumSwitch) {
1290                        Symbol sym = enumConstant(c.pat, seltype);
1291                        if (sym == null) {
1292                            log.error(c.pat.pos(), "enum.label.must.be.unqualified.enum");
1293                        } else if (!labels.add(sym)) {
1294                            log.error(c.pos(), "duplicate.case.label");
1295                        }
1296                    } else {
1297                        Type pattype = attribExpr(c.pat, switchEnv, seltype);
1298                        if (!pattype.hasTag(ERROR)) {
1299                            if (pattype.constValue() == null) {
1300                                log.error(c.pat.pos(),
1301                                          (stringSwitch ? "string.const.req" : "const.expr.req"));
1302                            } else if (!labels.add(pattype.constValue())) {
1303                                log.error(c.pos(), "duplicate.case.label");
1304                            }
1305                        }
1306                    }
1307                } else if (hasDefault) {
1308                    log.error(c.pos(), "duplicate.default.label");
1309                } else {
1310                    hasDefault = true;
1311                }
1312                Env<AttrContext> caseEnv =
1313                    switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup()));
1314                try {
1315                    attribStats(c.stats, caseEnv);
1316                } finally {
1317                    caseEnv.info.scope.leave();
1318                    addVars(c.stats, switchEnv.info.scope);
1319                }
1320            }
1321
1322            result = null;
1323        }
1324        finally {
1325            switchEnv.info.scope.leave();
1326        }
1327    }
1328    // where
1329        /** Add any variables defined in stats to the switch scope. */
1330        private static void addVars(List<JCStatement> stats, WriteableScope switchScope) {
1331            for (;stats.nonEmpty(); stats = stats.tail) {
1332                JCTree stat = stats.head;
1333                if (stat.hasTag(VARDEF))
1334                    switchScope.enter(((JCVariableDecl) stat).sym);
1335            }
1336        }
1337    // where
1338    /** Return the selected enumeration constant symbol, or null. */
1339    private Symbol enumConstant(JCTree tree, Type enumType) {
1340        if (tree.hasTag(IDENT)) {
1341            JCIdent ident = (JCIdent)tree;
1342            Name name = ident.name;
1343            for (Symbol sym : enumType.tsym.members().getSymbolsByName(name)) {
1344                if (sym.kind == VAR) {
1345                    Symbol s = ident.sym = sym;
1346                    ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
1347                    ident.type = s.type;
1348                    return ((s.flags_field & Flags.ENUM) == 0)
1349                        ? null : s;
1350                }
1351            }
1352        }
1353        return null;
1354    }
1355
1356    public void visitSynchronized(JCSynchronized tree) {
1357        chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
1358        attribStat(tree.body, env);
1359        result = null;
1360    }
1361
1362    public void visitTry(JCTry tree) {
1363        // Create a new local environment with a local
1364        Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
1365        try {
1366            boolean isTryWithResource = tree.resources.nonEmpty();
1367            // Create a nested environment for attributing the try block if needed
1368            Env<AttrContext> tryEnv = isTryWithResource ?
1369                env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
1370                localEnv;
1371            try {
1372                // Attribute resource declarations
1373                for (JCTree resource : tree.resources) {
1374                    CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) {
1375                        @Override
1376                        public void report(DiagnosticPosition pos, JCDiagnostic details) {
1377                            chk.basicHandler.report(pos, diags.fragment("try.not.applicable.to.type", details));
1378                        }
1379                    };
1380                    ResultInfo twrResult =
1381                        new ResultInfo(KindSelector.VAR,
1382                                       syms.autoCloseableType,
1383                                       twrContext);
1384                    if (resource.hasTag(VARDEF)) {
1385                        attribStat(resource, tryEnv);
1386                        twrResult.check(resource, resource.type);
1387
1388                        //check that resource type cannot throw InterruptedException
1389                        checkAutoCloseable(resource.pos(), localEnv, resource.type);
1390
1391                        VarSymbol var = ((JCVariableDecl) resource).sym;
1392                        var.setData(ElementKind.RESOURCE_VARIABLE);
1393                    } else {
1394                        attribTree(resource, tryEnv, twrResult);
1395                    }
1396                }
1397                // Attribute body
1398                attribStat(tree.body, tryEnv);
1399            } finally {
1400                if (isTryWithResource)
1401                    tryEnv.info.scope.leave();
1402            }
1403
1404            // Attribute catch clauses
1405            for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
1406                JCCatch c = l.head;
1407                Env<AttrContext> catchEnv =
1408                    localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup()));
1409                try {
1410                    Type ctype = attribStat(c.param, catchEnv);
1411                    if (TreeInfo.isMultiCatch(c)) {
1412                        //multi-catch parameter is implicitly marked as final
1413                        c.param.sym.flags_field |= FINAL | UNION;
1414                    }
1415                    if (c.param.sym.kind == VAR) {
1416                        c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
1417                    }
1418                    chk.checkType(c.param.vartype.pos(),
1419                                  chk.checkClassType(c.param.vartype.pos(), ctype),
1420                                  syms.throwableType);
1421                    attribStat(c.body, catchEnv);
1422                } finally {
1423                    catchEnv.info.scope.leave();
1424                }
1425            }
1426
1427            // Attribute finalizer
1428            if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
1429            result = null;
1430        }
1431        finally {
1432            localEnv.info.scope.leave();
1433        }
1434    }
1435
1436    void checkAutoCloseable(DiagnosticPosition pos, Env<AttrContext> env, Type resource) {
1437        if (!resource.isErroneous() &&
1438            types.asSuper(resource, syms.autoCloseableType.tsym) != null &&
1439            !types.isSameType(resource, syms.autoCloseableType)) { // Don't emit warning for AutoCloseable itself
1440            Symbol close = syms.noSymbol;
1441            Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log);
1442            try {
1443                close = rs.resolveQualifiedMethod(pos,
1444                        env,
1445                        resource,
1446                        names.close,
1447                        List.<Type>nil(),
1448                        List.<Type>nil());
1449            }
1450            finally {
1451                log.popDiagnosticHandler(discardHandler);
1452            }
1453            if (close.kind == MTH &&
1454                    close.overrides(syms.autoCloseableClose, resource.tsym, types, true) &&
1455                    chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes()) &&
1456                    env.info.lint.isEnabled(LintCategory.TRY)) {
1457                log.warning(LintCategory.TRY, pos, "try.resource.throws.interrupted.exc", resource);
1458            }
1459        }
1460    }
1461
1462    public void visitConditional(JCConditional tree) {
1463        Type condtype = attribExpr(tree.cond, env, syms.booleanType);
1464
1465        tree.polyKind = (!allowPoly ||
1466                pt().hasTag(NONE) && pt() != Type.recoveryType && pt() != Infer.anyPoly ||
1467                isBooleanOrNumeric(env, tree)) ?
1468                PolyKind.STANDALONE : PolyKind.POLY;
1469
1470        if (tree.polyKind == PolyKind.POLY && resultInfo.pt.hasTag(VOID)) {
1471            //this means we are returning a poly conditional from void-compatible lambda expression
1472            resultInfo.checkContext.report(tree, diags.fragment("conditional.target.cant.be.void"));
1473            result = tree.type = types.createErrorType(resultInfo.pt);
1474            return;
1475        }
1476
1477        ResultInfo condInfo = tree.polyKind == PolyKind.STANDALONE ?
1478                unknownExprInfo :
1479                resultInfo.dup(conditionalContext(resultInfo.checkContext));
1480
1481        Type truetype = attribTree(tree.truepart, env, condInfo);
1482        Type falsetype = attribTree(tree.falsepart, env, condInfo);
1483
1484        Type owntype = (tree.polyKind == PolyKind.STANDALONE) ? condType(tree, truetype, falsetype) : pt();
1485        if (condtype.constValue() != null &&
1486                truetype.constValue() != null &&
1487                falsetype.constValue() != null &&
1488                !owntype.hasTag(NONE)) {
1489            //constant folding
1490            owntype = cfolder.coerce(condtype.isTrue() ? truetype : falsetype, owntype);
1491        }
1492        result = check(tree, owntype, KindSelector.VAL, resultInfo);
1493    }
1494    //where
1495        private boolean isBooleanOrNumeric(Env<AttrContext> env, JCExpression tree) {
1496            switch (tree.getTag()) {
1497                case LITERAL: return ((JCLiteral)tree).typetag.isSubRangeOf(DOUBLE) ||
1498                              ((JCLiteral)tree).typetag == BOOLEAN ||
1499                              ((JCLiteral)tree).typetag == BOT;
1500                case LAMBDA: case REFERENCE: return false;
1501                case PARENS: return isBooleanOrNumeric(env, ((JCParens)tree).expr);
1502                case CONDEXPR:
1503                    JCConditional condTree = (JCConditional)tree;
1504                    return isBooleanOrNumeric(env, condTree.truepart) &&
1505                            isBooleanOrNumeric(env, condTree.falsepart);
1506                case APPLY:
1507                    JCMethodInvocation speculativeMethodTree =
1508                            (JCMethodInvocation)deferredAttr.attribSpeculative(tree, env, unknownExprInfo);
1509                    Symbol msym = TreeInfo.symbol(speculativeMethodTree.meth);
1510                    Type receiverType = speculativeMethodTree.meth.hasTag(IDENT) ?
1511                            env.enclClass.type :
1512                            ((JCFieldAccess)speculativeMethodTree.meth).selected.type;
1513                    Type owntype = types.memberType(receiverType, msym).getReturnType();
1514                    return primitiveOrBoxed(owntype);
1515                case NEWCLASS:
1516                    JCExpression className =
1517                            removeClassParams.translate(((JCNewClass)tree).clazz);
1518                    JCExpression speculativeNewClassTree =
1519                            (JCExpression)deferredAttr.attribSpeculative(className, env, unknownTypeInfo);
1520                    return primitiveOrBoxed(speculativeNewClassTree.type);
1521                default:
1522                    Type speculativeType = deferredAttr.attribSpeculative(tree, env, unknownExprInfo).type;
1523                    return primitiveOrBoxed(speculativeType);
1524            }
1525        }
1526        //where
1527            boolean primitiveOrBoxed(Type t) {
1528                return (!t.hasTag(TYPEVAR) && types.unboxedTypeOrType(t).isPrimitive());
1529            }
1530
1531            TreeTranslator removeClassParams = new TreeTranslator() {
1532                @Override
1533                public void visitTypeApply(JCTypeApply tree) {
1534                    result = translate(tree.clazz);
1535                }
1536            };
1537
1538        CheckContext conditionalContext(CheckContext checkContext) {
1539            return new Check.NestedCheckContext(checkContext) {
1540                //this will use enclosing check context to check compatibility of
1541                //subexpression against target type; if we are in a method check context,
1542                //depending on whether boxing is allowed, we could have incompatibilities
1543                @Override
1544                public void report(DiagnosticPosition pos, JCDiagnostic details) {
1545                    enclosingContext.report(pos, diags.fragment("incompatible.type.in.conditional", details));
1546                }
1547            };
1548        }
1549
1550        /** Compute the type of a conditional expression, after
1551         *  checking that it exists.  See JLS 15.25. Does not take into
1552         *  account the special case where condition and both arms
1553         *  are constants.
1554         *
1555         *  @param pos      The source position to be used for error
1556         *                  diagnostics.
1557         *  @param thentype The type of the expression's then-part.
1558         *  @param elsetype The type of the expression's else-part.
1559         */
1560        Type condType(DiagnosticPosition pos,
1561                               Type thentype, Type elsetype) {
1562            // If same type, that is the result
1563            if (types.isSameType(thentype, elsetype))
1564                return thentype.baseType();
1565
1566            Type thenUnboxed = (thentype.isPrimitive())
1567                ? thentype : types.unboxedType(thentype);
1568            Type elseUnboxed = (elsetype.isPrimitive())
1569                ? elsetype : types.unboxedType(elsetype);
1570
1571            // Otherwise, if both arms can be converted to a numeric
1572            // type, return the least numeric type that fits both arms
1573            // (i.e. return larger of the two, or return int if one
1574            // arm is short, the other is char).
1575            if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) {
1576                // If one arm has an integer subrange type (i.e., byte,
1577                // short, or char), and the other is an integer constant
1578                // that fits into the subrange, return the subrange type.
1579                if (thenUnboxed.getTag().isStrictSubRangeOf(INT) &&
1580                    elseUnboxed.hasTag(INT) &&
1581                    types.isAssignable(elseUnboxed, thenUnboxed)) {
1582                    return thenUnboxed.baseType();
1583                }
1584                if (elseUnboxed.getTag().isStrictSubRangeOf(INT) &&
1585                    thenUnboxed.hasTag(INT) &&
1586                    types.isAssignable(thenUnboxed, elseUnboxed)) {
1587                    return elseUnboxed.baseType();
1588                }
1589
1590                for (TypeTag tag : primitiveTags) {
1591                    Type candidate = syms.typeOfTag[tag.ordinal()];
1592                    if (types.isSubtype(thenUnboxed, candidate) &&
1593                        types.isSubtype(elseUnboxed, candidate)) {
1594                        return candidate;
1595                    }
1596                }
1597            }
1598
1599            // Those were all the cases that could result in a primitive
1600            if (thentype.isPrimitive())
1601                thentype = types.boxedClass(thentype).type;
1602            if (elsetype.isPrimitive())
1603                elsetype = types.boxedClass(elsetype).type;
1604
1605            if (types.isSubtype(thentype, elsetype))
1606                return elsetype.baseType();
1607            if (types.isSubtype(elsetype, thentype))
1608                return thentype.baseType();
1609
1610            if (thentype.hasTag(VOID) || elsetype.hasTag(VOID)) {
1611                log.error(pos, "neither.conditional.subtype",
1612                          thentype, elsetype);
1613                return thentype.baseType();
1614            }
1615
1616            // both are known to be reference types.  The result is
1617            // lub(thentype,elsetype). This cannot fail, as it will
1618            // always be possible to infer "Object" if nothing better.
1619            return types.lub(thentype.baseType(), elsetype.baseType());
1620        }
1621
1622    final static TypeTag[] primitiveTags = new TypeTag[]{
1623        BYTE,
1624        CHAR,
1625        SHORT,
1626        INT,
1627        LONG,
1628        FLOAT,
1629        DOUBLE,
1630        BOOLEAN,
1631    };
1632
1633    public void visitIf(JCIf tree) {
1634        attribExpr(tree.cond, env, syms.booleanType);
1635        attribStat(tree.thenpart, env);
1636        if (tree.elsepart != null)
1637            attribStat(tree.elsepart, env);
1638        chk.checkEmptyIf(tree);
1639        result = null;
1640    }
1641
1642    public void visitExec(JCExpressionStatement tree) {
1643        //a fresh environment is required for 292 inference to work properly ---
1644        //see Infer.instantiatePolymorphicSignatureInstance()
1645        Env<AttrContext> localEnv = env.dup(tree);
1646        attribExpr(tree.expr, localEnv);
1647        result = null;
1648    }
1649
1650    public void visitBreak(JCBreak tree) {
1651        tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
1652        result = null;
1653    }
1654
1655    public void visitContinue(JCContinue tree) {
1656        tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
1657        result = null;
1658    }
1659    //where
1660        /** Return the target of a break or continue statement, if it exists,
1661         *  report an error if not.
1662         *  Note: The target of a labelled break or continue is the
1663         *  (non-labelled) statement tree referred to by the label,
1664         *  not the tree representing the labelled statement itself.
1665         *
1666         *  @param pos     The position to be used for error diagnostics
1667         *  @param tag     The tag of the jump statement. This is either
1668         *                 Tree.BREAK or Tree.CONTINUE.
1669         *  @param label   The label of the jump statement, or null if no
1670         *                 label is given.
1671         *  @param env     The environment current at the jump statement.
1672         */
1673        private JCTree findJumpTarget(DiagnosticPosition pos,
1674                                    JCTree.Tag tag,
1675                                    Name label,
1676                                    Env<AttrContext> env) {
1677            // Search environments outwards from the point of jump.
1678            Env<AttrContext> env1 = env;
1679            LOOP:
1680            while (env1 != null) {
1681                switch (env1.tree.getTag()) {
1682                    case LABELLED:
1683                        JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
1684                        if (label == labelled.label) {
1685                            // If jump is a continue, check that target is a loop.
1686                            if (tag == CONTINUE) {
1687                                if (!labelled.body.hasTag(DOLOOP) &&
1688                                        !labelled.body.hasTag(WHILELOOP) &&
1689                                        !labelled.body.hasTag(FORLOOP) &&
1690                                        !labelled.body.hasTag(FOREACHLOOP))
1691                                    log.error(pos, "not.loop.label", label);
1692                                // Found labelled statement target, now go inwards
1693                                // to next non-labelled tree.
1694                                return TreeInfo.referencedStatement(labelled);
1695                            } else {
1696                                return labelled;
1697                            }
1698                        }
1699                        break;
1700                    case DOLOOP:
1701                    case WHILELOOP:
1702                    case FORLOOP:
1703                    case FOREACHLOOP:
1704                        if (label == null) return env1.tree;
1705                        break;
1706                    case SWITCH:
1707                        if (label == null && tag == BREAK) return env1.tree;
1708                        break;
1709                    case LAMBDA:
1710                    case METHODDEF:
1711                    case CLASSDEF:
1712                        break LOOP;
1713                    default:
1714                }
1715                env1 = env1.next;
1716            }
1717            if (label != null)
1718                log.error(pos, "undef.label", label);
1719            else if (tag == CONTINUE)
1720                log.error(pos, "cont.outside.loop");
1721            else
1722                log.error(pos, "break.outside.switch.loop");
1723            return null;
1724        }
1725
1726    public void visitReturn(JCReturn tree) {
1727        // Check that there is an enclosing method which is
1728        // nested within than the enclosing class.
1729        if (env.info.returnResult == null) {
1730            log.error(tree.pos(), "ret.outside.meth");
1731        } else {
1732            // Attribute return expression, if it exists, and check that
1733            // it conforms to result type of enclosing method.
1734            if (tree.expr != null) {
1735                if (env.info.returnResult.pt.hasTag(VOID)) {
1736                    env.info.returnResult.checkContext.report(tree.expr.pos(),
1737                              diags.fragment("unexpected.ret.val"));
1738                }
1739                attribTree(tree.expr, env, env.info.returnResult);
1740            } else if (!env.info.returnResult.pt.hasTag(VOID) &&
1741                    !env.info.returnResult.pt.hasTag(NONE)) {
1742                env.info.returnResult.checkContext.report(tree.pos(),
1743                              diags.fragment("missing.ret.val"));
1744            }
1745        }
1746        result = null;
1747    }
1748
1749    public void visitThrow(JCThrow tree) {
1750        Type owntype = attribExpr(tree.expr, env, allowPoly ? Type.noType : syms.throwableType);
1751        if (allowPoly) {
1752            chk.checkType(tree, owntype, syms.throwableType);
1753        }
1754        result = null;
1755    }
1756
1757    public void visitAssert(JCAssert tree) {
1758        attribExpr(tree.cond, env, syms.booleanType);
1759        if (tree.detail != null) {
1760            chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
1761        }
1762        result = null;
1763    }
1764
1765     /** Visitor method for method invocations.
1766     *  NOTE: The method part of an application will have in its type field
1767     *        the return type of the method, not the method's type itself!
1768     */
1769    public void visitApply(JCMethodInvocation tree) {
1770        // The local environment of a method application is
1771        // a new environment nested in the current one.
1772        Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
1773
1774        // The types of the actual method arguments.
1775        List<Type> argtypes;
1776
1777        // The types of the actual method type arguments.
1778        List<Type> typeargtypes = null;
1779
1780        Name methName = TreeInfo.name(tree.meth);
1781
1782        boolean isConstructorCall =
1783            methName == names._this || methName == names._super;
1784
1785        ListBuffer<Type> argtypesBuf = new ListBuffer<>();
1786        if (isConstructorCall) {
1787            // We are seeing a ...this(...) or ...super(...) call.
1788            // Check that this is the first statement in a constructor.
1789            if (checkFirstConstructorStat(tree, env)) {
1790
1791                // Record the fact
1792                // that this is a constructor call (using isSelfCall).
1793                localEnv.info.isSelfCall = true;
1794
1795                // Attribute arguments, yielding list of argument types.
1796                KindSelector kind = attribArgs(KindSelector.MTH, tree.args, localEnv, argtypesBuf);
1797                argtypes = argtypesBuf.toList();
1798                typeargtypes = attribTypes(tree.typeargs, localEnv);
1799
1800                // Variable `site' points to the class in which the called
1801                // constructor is defined.
1802                Type site = env.enclClass.sym.type;
1803                if (methName == names._super) {
1804                    if (site == syms.objectType) {
1805                        log.error(tree.meth.pos(), "no.superclass", site);
1806                        site = types.createErrorType(syms.objectType);
1807                    } else {
1808                        site = types.supertype(site);
1809                    }
1810                }
1811
1812                if (site.hasTag(CLASS)) {
1813                    Type encl = site.getEnclosingType();
1814                    while (encl != null && encl.hasTag(TYPEVAR))
1815                        encl = encl.getUpperBound();
1816                    if (encl.hasTag(CLASS)) {
1817                        // we are calling a nested class
1818
1819                        if (tree.meth.hasTag(SELECT)) {
1820                            JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
1821
1822                            // We are seeing a prefixed call, of the form
1823                            //     <expr>.super(...).
1824                            // Check that the prefix expression conforms
1825                            // to the outer instance type of the class.
1826                            chk.checkRefType(qualifier.pos(),
1827                                             attribExpr(qualifier, localEnv,
1828                                                        encl));
1829                        } else if (methName == names._super) {
1830                            // qualifier omitted; check for existence
1831                            // of an appropriate implicit qualifier.
1832                            rs.resolveImplicitThis(tree.meth.pos(),
1833                                                   localEnv, site, true);
1834                        }
1835                    } else if (tree.meth.hasTag(SELECT)) {
1836                        log.error(tree.meth.pos(), "illegal.qual.not.icls",
1837                                  site.tsym);
1838                    }
1839
1840                    // if we're calling a java.lang.Enum constructor,
1841                    // prefix the implicit String and int parameters
1842                    if (site.tsym == syms.enumSym)
1843                        argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
1844
1845                    // Resolve the called constructor under the assumption
1846                    // that we are referring to a superclass instance of the
1847                    // current instance (JLS ???).
1848                    boolean selectSuperPrev = localEnv.info.selectSuper;
1849                    localEnv.info.selectSuper = true;
1850                    localEnv.info.pendingResolutionPhase = null;
1851                    Symbol sym = rs.resolveConstructor(
1852                        tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
1853                    localEnv.info.selectSuper = selectSuperPrev;
1854
1855                    // Set method symbol to resolved constructor...
1856                    TreeInfo.setSymbol(tree.meth, sym);
1857
1858                    // ...and check that it is legal in the current context.
1859                    // (this will also set the tree's type)
1860                    Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
1861                    checkId(tree.meth, site, sym, localEnv,
1862                            new ResultInfo(kind, mpt));
1863                }
1864                // Otherwise, `site' is an error type and we do nothing
1865            }
1866            result = tree.type = syms.voidType;
1867        } else {
1868            // Otherwise, we are seeing a regular method call.
1869            // Attribute the arguments, yielding list of argument types, ...
1870            KindSelector kind = attribArgs(KindSelector.VAL, tree.args, localEnv, argtypesBuf);
1871            argtypes = argtypesBuf.toList();
1872            typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
1873
1874            // ... and attribute the method using as a prototype a methodtype
1875            // whose formal argument types is exactly the list of actual
1876            // arguments (this will also set the method symbol).
1877            Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
1878            localEnv.info.pendingResolutionPhase = null;
1879            Type mtype = attribTree(tree.meth, localEnv, new ResultInfo(kind, mpt, resultInfo.checkContext));
1880
1881            // Compute the result type.
1882            Type restype = mtype.getReturnType();
1883            if (restype.hasTag(WILDCARD))
1884                throw new AssertionError(mtype);
1885
1886            Type qualifier = (tree.meth.hasTag(SELECT))
1887                    ? ((JCFieldAccess) tree.meth).selected.type
1888                    : env.enclClass.sym.type;
1889            restype = adjustMethodReturnType(qualifier, methName, argtypes, restype);
1890
1891            chk.checkRefTypes(tree.typeargs, typeargtypes);
1892
1893            // Check that value of resulting type is admissible in the
1894            // current context.  Also, capture the return type
1895            Type capturedRes = resultInfo.checkContext.inferenceContext().cachedCapture(tree, restype, true);
1896            result = check(tree, capturedRes, 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            } else {
2821                Symbol lhsSym = TreeInfo.symbol(that.expr);
2822                localEnv.info.selectSuper = lhsSym != null && lhsSym.name == names._super;
2823            }
2824            //attrib type-arguments
2825            List<Type> typeargtypes = List.nil();
2826            if (that.typeargs != null) {
2827                typeargtypes = attribTypes(that.typeargs, localEnv);
2828            }
2829
2830            boolean isTargetSerializable =
2831                    resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
2832                    isSerializable(pt());
2833            TargetInfo targetInfo = getTargetInfo(that, resultInfo, null);
2834            Type currentTarget = targetInfo.target;
2835            Type desc = targetInfo.descriptor;
2836
2837            setFunctionalInfo(localEnv, that, pt(), desc, currentTarget, resultInfo.checkContext);
2838            List<Type> argtypes = desc.getParameterTypes();
2839            Resolve.MethodCheck referenceCheck = rs.resolveMethodCheck;
2840
2841            if (resultInfo.checkContext.inferenceContext().free(argtypes)) {
2842                referenceCheck = rs.new MethodReferenceCheck(resultInfo.checkContext.inferenceContext());
2843            }
2844
2845            Pair<Symbol, Resolve.ReferenceLookupHelper> refResult = null;
2846            List<Type> saved_undet = resultInfo.checkContext.inferenceContext().save();
2847            try {
2848                refResult = rs.resolveMemberReference(localEnv, that, that.expr.type,
2849                        that.name, argtypes, typeargtypes, referenceCheck,
2850                        resultInfo.checkContext.inferenceContext(), rs.basicReferenceChooser);
2851            } finally {
2852                resultInfo.checkContext.inferenceContext().rollback(saved_undet);
2853            }
2854
2855            Symbol refSym = refResult.fst;
2856            Resolve.ReferenceLookupHelper lookupHelper = refResult.snd;
2857
2858            /** this switch will need to go away and be replaced by the new RESOLUTION_TARGET testing
2859             *  JDK-8075541
2860             */
2861            if (refSym.kind != MTH) {
2862                boolean targetError;
2863                switch (refSym.kind) {
2864                    case ABSENT_MTH:
2865                    case MISSING_ENCL:
2866                        targetError = false;
2867                        break;
2868                    case WRONG_MTH:
2869                    case WRONG_MTHS:
2870                    case AMBIGUOUS:
2871                    case HIDDEN:
2872                    case STATICERR:
2873                        targetError = true;
2874                        break;
2875                    default:
2876                        Assert.error("unexpected result kind " + refSym.kind);
2877                        targetError = false;
2878                }
2879
2880                JCDiagnostic detailsDiag = ((Resolve.ResolveError)refSym.baseSymbol()).getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT,
2881                                that, exprType.tsym, exprType, that.name, argtypes, typeargtypes);
2882
2883                JCDiagnostic.DiagnosticType diagKind = targetError ?
2884                        JCDiagnostic.DiagnosticType.FRAGMENT : JCDiagnostic.DiagnosticType.ERROR;
2885
2886                JCDiagnostic diag = diags.create(diagKind, log.currentSource(), that,
2887                        "invalid.mref", Kinds.kindName(that.getMode()), detailsDiag);
2888
2889                if (targetError && currentTarget == Type.recoveryType) {
2890                    //a target error doesn't make sense during recovery stage
2891                    //as we don't know what actual parameter types are
2892                    result = that.type = currentTarget;
2893                    return;
2894                } else {
2895                    if (targetError) {
2896                        resultInfo.checkContext.report(that, diag);
2897                    } else {
2898                        log.report(diag);
2899                    }
2900                    result = that.type = types.createErrorType(currentTarget);
2901                    return;
2902                }
2903            }
2904
2905            that.sym = refSym.baseSymbol();
2906            that.kind = lookupHelper.referenceKind(that.sym);
2907            that.ownerAccessible = rs.isAccessible(localEnv, that.sym.enclClass());
2908
2909            if (desc.getReturnType() == Type.recoveryType) {
2910                // stop here
2911                result = that.type = currentTarget;
2912                return;
2913            }
2914
2915            if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
2916
2917                if (that.getMode() == ReferenceMode.INVOKE &&
2918                        TreeInfo.isStaticSelector(that.expr, names) &&
2919                        that.kind.isUnbound() &&
2920                        !desc.getParameterTypes().head.isParameterized()) {
2921                    chk.checkRaw(that.expr, localEnv);
2922                }
2923
2924                if (that.sym.isStatic() && TreeInfo.isStaticSelector(that.expr, names) &&
2925                        exprType.getTypeArguments().nonEmpty()) {
2926                    //static ref with class type-args
2927                    log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
2928                            diags.fragment("static.mref.with.targs"));
2929                    result = that.type = types.createErrorType(currentTarget);
2930                    return;
2931                }
2932
2933                if (!refSym.isStatic() && that.kind == JCMemberReference.ReferenceKind.SUPER) {
2934                    // Check that super-qualified symbols are not abstract (JLS)
2935                    rs.checkNonAbstract(that.pos(), that.sym);
2936                }
2937
2938                if (isTargetSerializable) {
2939                    chk.checkElemAccessFromSerializableLambda(that);
2940                }
2941            }
2942
2943            ResultInfo checkInfo =
2944                    resultInfo.dup(newMethodTemplate(
2945                        desc.getReturnType().hasTag(VOID) ? Type.noType : desc.getReturnType(),
2946                        that.kind.isUnbound() ? argtypes.tail : argtypes, typeargtypes),
2947                        new FunctionalReturnContext(resultInfo.checkContext), CheckMode.NO_TREE_UPDATE);
2948
2949            Type refType = checkId(that, lookupHelper.site, refSym, localEnv, checkInfo);
2950
2951            if (that.kind.isUnbound() &&
2952                    resultInfo.checkContext.inferenceContext().free(argtypes.head)) {
2953                //re-generate inference constraints for unbound receiver
2954                if (!types.isSubtype(resultInfo.checkContext.inferenceContext().asUndetVar(argtypes.head), exprType)) {
2955                    //cannot happen as this has already been checked - we just need
2956                    //to regenerate the inference constraints, as that has been lost
2957                    //as a result of the call to inferenceContext.save()
2958                    Assert.error("Can't get here");
2959                }
2960            }
2961
2962            if (!refType.isErroneous()) {
2963                refType = types.createMethodTypeWithReturn(refType,
2964                        adjustMethodReturnType(lookupHelper.site, that.name, checkInfo.pt.getParameterTypes(), refType.getReturnType()));
2965            }
2966
2967            //go ahead with standard method reference compatibility check - note that param check
2968            //is a no-op (as this has been taken care during method applicability)
2969            boolean isSpeculativeRound =
2970                    resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
2971
2972            that.type = currentTarget; //avoids recovery at this stage
2973            checkReferenceCompatible(that, desc, refType, resultInfo.checkContext, isSpeculativeRound);
2974            if (!isSpeculativeRound) {
2975                checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), desc, currentTarget);
2976            }
2977            result = check(that, currentTarget, KindSelector.VAL, resultInfo);
2978        } catch (Types.FunctionDescriptorLookupError ex) {
2979            JCDiagnostic cause = ex.getDiagnostic();
2980            resultInfo.checkContext.report(that, cause);
2981            result = that.type = types.createErrorType(pt());
2982            return;
2983        }
2984    }
2985    //where
2986        ResultInfo memberReferenceQualifierResult(JCMemberReference tree) {
2987            //if this is a constructor reference, the expected kind must be a type
2988            return new ResultInfo(tree.getMode() == ReferenceMode.INVOKE ?
2989                                  KindSelector.VAL_TYP : KindSelector.TYP,
2990                                  Type.noType);
2991        }
2992
2993
2994    @SuppressWarnings("fallthrough")
2995    void checkReferenceCompatible(JCMemberReference tree, Type descriptor, Type refType, CheckContext checkContext, boolean speculativeAttr) {
2996        InferenceContext inferenceContext = checkContext.inferenceContext();
2997        Type returnType = inferenceContext.asUndetVar(descriptor.getReturnType());
2998
2999        Type resType;
3000        switch (tree.getMode()) {
3001            case NEW:
3002                if (!tree.expr.type.isRaw()) {
3003                    resType = tree.expr.type;
3004                    break;
3005                }
3006            default:
3007                resType = refType.getReturnType();
3008        }
3009
3010        Type incompatibleReturnType = resType;
3011
3012        if (returnType.hasTag(VOID)) {
3013            incompatibleReturnType = null;
3014        }
3015
3016        if (!returnType.hasTag(VOID) && !resType.hasTag(VOID)) {
3017            if (resType.isErroneous() ||
3018                    new FunctionalReturnContext(checkContext).compatible(resType, returnType, types.noWarnings)) {
3019                incompatibleReturnType = null;
3020            }
3021        }
3022
3023        if (incompatibleReturnType != null) {
3024            checkContext.report(tree, diags.fragment("incompatible.ret.type.in.mref",
3025                    diags.fragment("inconvertible.types", resType, descriptor.getReturnType())));
3026        } else {
3027            if (inferenceContext.free(refType)) {
3028                // we need to wait for inference to finish and then replace inference vars in the referent type
3029                inferenceContext.addFreeTypeListener(List.of(refType),
3030                        instantiatedContext -> {
3031                            tree.referentType = instantiatedContext.asInstType(refType);
3032                        });
3033            } else {
3034                tree.referentType = refType;
3035            }
3036        }
3037
3038        if (!speculativeAttr) {
3039            List<Type> thrownTypes = inferenceContext.asUndetVars(descriptor.getThrownTypes());
3040            if (chk.unhandled(refType.getThrownTypes(), thrownTypes).nonEmpty()) {
3041                log.error(tree, "incompatible.thrown.types.in.mref", refType.getThrownTypes());
3042            }
3043        }
3044    }
3045
3046    /**
3047     * Set functional type info on the underlying AST. Note: as the target descriptor
3048     * might contain inference variables, we might need to register an hook in the
3049     * current inference context.
3050     */
3051    private void setFunctionalInfo(final Env<AttrContext> env, final JCFunctionalExpression fExpr,
3052            final Type pt, final Type descriptorType, final Type primaryTarget, final CheckContext checkContext) {
3053        if (checkContext.inferenceContext().free(descriptorType)) {
3054            checkContext.inferenceContext().addFreeTypeListener(List.of(pt, descriptorType), new FreeTypeListener() {
3055                public void typesInferred(InferenceContext inferenceContext) {
3056                    setFunctionalInfo(env, fExpr, pt, inferenceContext.asInstType(descriptorType),
3057                            inferenceContext.asInstType(primaryTarget), checkContext);
3058                }
3059            });
3060        } else {
3061            ListBuffer<Type> targets = new ListBuffer<>();
3062            if (pt.hasTag(CLASS)) {
3063                if (pt.isCompound()) {
3064                    targets.append(types.removeWildcards(primaryTarget)); //this goes first
3065                    for (Type t : ((IntersectionClassType)pt()).interfaces_field) {
3066                        if (t != primaryTarget) {
3067                            targets.append(types.removeWildcards(t));
3068                        }
3069                    }
3070                } else {
3071                    targets.append(types.removeWildcards(primaryTarget));
3072                }
3073            }
3074            fExpr.targets = targets.toList();
3075            if (checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
3076                    pt != Type.recoveryType) {
3077                //check that functional interface class is well-formed
3078                try {
3079                    /* Types.makeFunctionalInterfaceClass() may throw an exception
3080                     * when it's executed post-inference. See the listener code
3081                     * above.
3082                     */
3083                    ClassSymbol csym = types.makeFunctionalInterfaceClass(env,
3084                            names.empty, List.of(fExpr.targets.head), ABSTRACT);
3085                    if (csym != null) {
3086                        chk.checkImplementations(env.tree, csym, csym);
3087                        try {
3088                            //perform an additional functional interface check on the synthetic class,
3089                            //as there may be spurious errors for raw targets - because of existing issues
3090                            //with membership and inheritance (see JDK-8074570).
3091                            csym.flags_field |= INTERFACE;
3092                            types.findDescriptorType(csym.type);
3093                        } catch (FunctionDescriptorLookupError err) {
3094                            resultInfo.checkContext.report(fExpr,
3095                                    diags.fragment(Fragments.NoSuitableFunctionalIntfInst(fExpr.targets.head)));
3096                        }
3097                    }
3098                } catch (Types.FunctionDescriptorLookupError ex) {
3099                    JCDiagnostic cause = ex.getDiagnostic();
3100                    resultInfo.checkContext.report(env.tree, cause);
3101                }
3102            }
3103        }
3104    }
3105
3106    public void visitParens(JCParens tree) {
3107        Type owntype = attribTree(tree.expr, env, resultInfo);
3108        result = check(tree, owntype, pkind(), resultInfo);
3109        Symbol sym = TreeInfo.symbol(tree);
3110        if (sym != null && sym.kind.matches(KindSelector.TYP_PCK))
3111            log.error(tree.pos(), "illegal.start.of.type");
3112    }
3113
3114    public void visitAssign(JCAssign tree) {
3115        Type owntype = attribTree(tree.lhs, env.dup(tree), varAssignmentInfo);
3116        Type capturedType = capture(owntype);
3117        attribExpr(tree.rhs, env, owntype);
3118        result = check(tree, capturedType, KindSelector.VAL, resultInfo);
3119    }
3120
3121    public void visitAssignop(JCAssignOp tree) {
3122        // Attribute arguments.
3123        Type owntype = attribTree(tree.lhs, env, varAssignmentInfo);
3124        Type operand = attribExpr(tree.rhs, env);
3125        // Find operator.
3126        Symbol operator = tree.operator = operators.resolveBinary(tree, tree.getTag().noAssignOp(), owntype, operand);
3127        if (operator.kind == MTH &&
3128                !owntype.isErroneous() &&
3129                !operand.isErroneous()) {
3130            chk.checkDivZero(tree.rhs.pos(), operator, operand);
3131            chk.checkCastable(tree.rhs.pos(),
3132                              operator.type.getReturnType(),
3133                              owntype);
3134        }
3135        result = check(tree, owntype, KindSelector.VAL, resultInfo);
3136    }
3137
3138    public void visitUnary(JCUnary tree) {
3139        // Attribute arguments.
3140        Type argtype = (tree.getTag().isIncOrDecUnaryOp())
3141            ? attribTree(tree.arg, env, varAssignmentInfo)
3142            : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
3143
3144        // Find operator.
3145        Symbol operator = tree.operator = operators.resolveUnary(tree, tree.getTag(), argtype);
3146        Type owntype = types.createErrorType(tree.type);
3147        if (operator.kind == MTH &&
3148                !argtype.isErroneous()) {
3149            owntype = (tree.getTag().isIncOrDecUnaryOp())
3150                ? tree.arg.type
3151                : operator.type.getReturnType();
3152            int opc = ((OperatorSymbol)operator).opcode;
3153
3154            // If the argument is constant, fold it.
3155            if (argtype.constValue() != null) {
3156                Type ctype = cfolder.fold1(opc, argtype);
3157                if (ctype != null) {
3158                    owntype = cfolder.coerce(ctype, owntype);
3159                }
3160            }
3161        }
3162        result = check(tree, owntype, KindSelector.VAL, resultInfo);
3163    }
3164
3165    public void visitBinary(JCBinary tree) {
3166        // Attribute arguments.
3167        Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
3168        Type right = chk.checkNonVoid(tree.rhs.pos(), attribExpr(tree.rhs, env));
3169        // Find operator.
3170        Symbol operator = tree.operator = operators.resolveBinary(tree, tree.getTag(), left, right);
3171        Type owntype = types.createErrorType(tree.type);
3172        if (operator.kind == MTH &&
3173                !left.isErroneous() &&
3174                !right.isErroneous()) {
3175            owntype = operator.type.getReturnType();
3176            int opc = ((OperatorSymbol)operator).opcode;
3177            // If both arguments are constants, fold them.
3178            if (left.constValue() != null && right.constValue() != null) {
3179                Type ctype = cfolder.fold2(opc, left, right);
3180                if (ctype != null) {
3181                    owntype = cfolder.coerce(ctype, owntype);
3182                }
3183            }
3184
3185            // Check that argument types of a reference ==, != are
3186            // castable to each other, (JLS 15.21).  Note: unboxing
3187            // comparisons will not have an acmp* opc at this point.
3188            if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
3189                if (!types.isCastable(left, right, new Warner(tree.pos()))) {
3190                    log.error(tree.pos(), "incomparable.types", left, right);
3191                }
3192            }
3193
3194            chk.checkDivZero(tree.rhs.pos(), operator, right);
3195        }
3196        result = check(tree, owntype, KindSelector.VAL, resultInfo);
3197    }
3198
3199    public void visitTypeCast(final JCTypeCast tree) {
3200        Type clazztype = attribType(tree.clazz, env);
3201        chk.validate(tree.clazz, env, false);
3202        //a fresh environment is required for 292 inference to work properly ---
3203        //see Infer.instantiatePolymorphicSignatureInstance()
3204        Env<AttrContext> localEnv = env.dup(tree);
3205        //should we propagate the target type?
3206        final ResultInfo castInfo;
3207        JCExpression expr = TreeInfo.skipParens(tree.expr);
3208        boolean isPoly = allowPoly && (expr.hasTag(LAMBDA) || expr.hasTag(REFERENCE));
3209        if (isPoly) {
3210            //expression is a poly - we need to propagate target type info
3211            castInfo = new ResultInfo(KindSelector.VAL, clazztype,
3212                                      new Check.NestedCheckContext(resultInfo.checkContext) {
3213                @Override
3214                public boolean compatible(Type found, Type req, Warner warn) {
3215                    return types.isCastable(found, req, warn);
3216                }
3217            });
3218        } else {
3219            //standalone cast - target-type info is not propagated
3220            castInfo = unknownExprInfo;
3221        }
3222        Type exprtype = attribTree(tree.expr, localEnv, castInfo);
3223        Type owntype = isPoly ? clazztype : chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
3224        if (exprtype.constValue() != null)
3225            owntype = cfolder.coerce(exprtype, owntype);
3226        result = check(tree, capture(owntype), KindSelector.VAL, resultInfo);
3227        if (!isPoly)
3228            chk.checkRedundantCast(localEnv, tree);
3229    }
3230
3231    public void visitTypeTest(JCInstanceOf tree) {
3232        Type exprtype = chk.checkNullOrRefType(
3233                tree.expr.pos(), attribExpr(tree.expr, env));
3234        Type clazztype = attribType(tree.clazz, env);
3235        if (!clazztype.hasTag(TYPEVAR)) {
3236            clazztype = chk.checkClassOrArrayType(tree.clazz.pos(), clazztype);
3237        }
3238        if (!clazztype.isErroneous() && !types.isReifiable(clazztype)) {
3239            log.error(tree.clazz.pos(), "illegal.generic.type.for.instof");
3240            clazztype = types.createErrorType(clazztype);
3241        }
3242        chk.validate(tree.clazz, env, false);
3243        chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
3244        result = check(tree, syms.booleanType, KindSelector.VAL, resultInfo);
3245    }
3246
3247    public void visitIndexed(JCArrayAccess tree) {
3248        Type owntype = types.createErrorType(tree.type);
3249        Type atype = attribExpr(tree.indexed, env);
3250        attribExpr(tree.index, env, syms.intType);
3251        if (types.isArray(atype))
3252            owntype = types.elemtype(atype);
3253        else if (!atype.hasTag(ERROR))
3254            log.error(tree.pos(), "array.req.but.found", atype);
3255        if (!pkind().contains(KindSelector.VAL))
3256            owntype = capture(owntype);
3257        result = check(tree, owntype, KindSelector.VAR, resultInfo);
3258    }
3259
3260    public void visitIdent(JCIdent tree) {
3261        Symbol sym;
3262
3263        // Find symbol
3264        if (pt().hasTag(METHOD) || pt().hasTag(FORALL)) {
3265            // If we are looking for a method, the prototype `pt' will be a
3266            // method type with the type of the call's arguments as parameters.
3267            env.info.pendingResolutionPhase = null;
3268            sym = rs.resolveMethod(tree.pos(), env, tree.name, pt().getParameterTypes(), pt().getTypeArguments());
3269        } else if (tree.sym != null && tree.sym.kind != VAR) {
3270            sym = tree.sym;
3271        } else {
3272            sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind());
3273        }
3274        tree.sym = sym;
3275
3276        // (1) Also find the environment current for the class where
3277        //     sym is defined (`symEnv').
3278        // Only for pre-tiger versions (1.4 and earlier):
3279        // (2) Also determine whether we access symbol out of an anonymous
3280        //     class in a this or super call.  This is illegal for instance
3281        //     members since such classes don't carry a this$n link.
3282        //     (`noOuterThisPath').
3283        Env<AttrContext> symEnv = env;
3284        boolean noOuterThisPath = false;
3285        if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
3286            sym.kind.matches(KindSelector.VAL_MTH) &&
3287            sym.owner.kind == TYP &&
3288            tree.name != names._this && tree.name != names._super) {
3289
3290            // Find environment in which identifier is defined.
3291            while (symEnv.outer != null &&
3292                   !sym.isMemberOf(symEnv.enclClass.sym, types)) {
3293                if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
3294                    noOuterThisPath = false;
3295                symEnv = symEnv.outer;
3296            }
3297        }
3298
3299        // If symbol is a variable, ...
3300        if (sym.kind == VAR) {
3301            VarSymbol v = (VarSymbol)sym;
3302
3303            // ..., evaluate its initializer, if it has one, and check for
3304            // illegal forward reference.
3305            checkInit(tree, env, v, false);
3306
3307            // If we are expecting a variable (as opposed to a value), check
3308            // that the variable is assignable in the current environment.
3309            if (KindSelector.ASG.subset(pkind()))
3310                checkAssignable(tree.pos(), v, null, env);
3311        }
3312
3313        // In a constructor body,
3314        // if symbol is a field or instance method, check that it is
3315        // not accessed before the supertype constructor is called.
3316        if ((symEnv.info.isSelfCall || noOuterThisPath) &&
3317            sym.kind.matches(KindSelector.VAL_MTH) &&
3318            sym.owner.kind == TYP &&
3319            (sym.flags() & STATIC) == 0) {
3320            chk.earlyRefError(tree.pos(), sym.kind == VAR ?
3321                                          sym : thisSym(tree.pos(), env));
3322        }
3323        Env<AttrContext> env1 = env;
3324        if (sym.kind != ERR && sym.kind != TYP &&
3325            sym.owner != null && sym.owner != env1.enclClass.sym) {
3326            // If the found symbol is inaccessible, then it is
3327            // accessed through an enclosing instance.  Locate this
3328            // enclosing instance:
3329            while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
3330                env1 = env1.outer;
3331        }
3332
3333        if (env.info.isSerializable) {
3334            chk.checkElemAccessFromSerializableLambda(tree);
3335        }
3336
3337        result = checkId(tree, env1.enclClass.sym.type, sym, env, resultInfo);
3338    }
3339
3340    public void visitSelect(JCFieldAccess tree) {
3341        // Determine the expected kind of the qualifier expression.
3342        KindSelector skind = KindSelector.NIL;
3343        if (tree.name == names._this || tree.name == names._super ||
3344                tree.name == names._class)
3345        {
3346            skind = KindSelector.TYP;
3347        } else {
3348            if (pkind().contains(KindSelector.PCK))
3349                skind = KindSelector.of(skind, KindSelector.PCK);
3350            if (pkind().contains(KindSelector.TYP))
3351                skind = KindSelector.of(skind, KindSelector.TYP, KindSelector.PCK);
3352            if (pkind().contains(KindSelector.VAL_MTH))
3353                skind = KindSelector.of(skind, KindSelector.VAL, KindSelector.TYP);
3354        }
3355
3356        // Attribute the qualifier expression, and determine its symbol (if any).
3357        Type site = attribTree(tree.selected, env, new ResultInfo(skind, Type.noType));
3358        if (!pkind().contains(KindSelector.TYP_PCK))
3359            site = capture(site); // Capture field access
3360
3361        // don't allow T.class T[].class, etc
3362        if (skind == KindSelector.TYP) {
3363            Type elt = site;
3364            while (elt.hasTag(ARRAY))
3365                elt = ((ArrayType)elt).elemtype;
3366            if (elt.hasTag(TYPEVAR)) {
3367                log.error(tree.pos(), "type.var.cant.be.deref");
3368                result = tree.type = types.createErrorType(tree.name, site.tsym, site);
3369                tree.sym = tree.type.tsym;
3370                return ;
3371            }
3372        }
3373
3374        // If qualifier symbol is a type or `super', assert `selectSuper'
3375        // for the selection. This is relevant for determining whether
3376        // protected symbols are accessible.
3377        Symbol sitesym = TreeInfo.symbol(tree.selected);
3378        boolean selectSuperPrev = env.info.selectSuper;
3379        env.info.selectSuper =
3380            sitesym != null &&
3381            sitesym.name == names._super;
3382
3383        // Determine the symbol represented by the selection.
3384        env.info.pendingResolutionPhase = null;
3385        Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
3386        if (sym.kind == VAR && sym.name != names._super && env.info.defaultSuperCallSite != null) {
3387            log.error(tree.selected.pos(), "not.encl.class", site.tsym);
3388            sym = syms.errSymbol;
3389        }
3390        if (sym.exists() && !isType(sym) && pkind().contains(KindSelector.TYP_PCK)) {
3391            site = capture(site);
3392            sym = selectSym(tree, sitesym, site, env, resultInfo);
3393        }
3394        boolean varArgs = env.info.lastResolveVarargs();
3395        tree.sym = sym;
3396
3397        if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) {
3398            site = types.skipTypeVars(site, true);
3399        }
3400
3401        // If that symbol is a variable, ...
3402        if (sym.kind == VAR) {
3403            VarSymbol v = (VarSymbol)sym;
3404
3405            // ..., evaluate its initializer, if it has one, and check for
3406            // illegal forward reference.
3407            checkInit(tree, env, v, true);
3408
3409            // If we are expecting a variable (as opposed to a value), check
3410            // that the variable is assignable in the current environment.
3411            if (KindSelector.ASG.subset(pkind()))
3412                checkAssignable(tree.pos(), v, tree.selected, env);
3413        }
3414
3415        if (sitesym != null &&
3416                sitesym.kind == VAR &&
3417                ((VarSymbol)sitesym).isResourceVariable() &&
3418                sym.kind == MTH &&
3419                sym.name.equals(names.close) &&
3420                sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) &&
3421                env.info.lint.isEnabled(LintCategory.TRY)) {
3422            log.warning(LintCategory.TRY, tree, "try.explicit.close.call");
3423        }
3424
3425        // Disallow selecting a type from an expression
3426        if (isType(sym) && (sitesym == null || !sitesym.kind.matches(KindSelector.TYP_PCK))) {
3427            tree.type = check(tree.selected, pt(),
3428                              sitesym == null ?
3429                                      KindSelector.VAL : sitesym.kind.toSelector(),
3430                              new ResultInfo(KindSelector.TYP_PCK, pt()));
3431        }
3432
3433        if (isType(sitesym)) {
3434            if (sym.name == names._this) {
3435                // If `C' is the currently compiled class, check that
3436                // C.this' does not appear in a call to a super(...)
3437                if (env.info.isSelfCall &&
3438                    site.tsym == env.enclClass.sym) {
3439                    chk.earlyRefError(tree.pos(), sym);
3440                }
3441            } else {
3442                // Check if type-qualified fields or methods are static (JLS)
3443                if ((sym.flags() & STATIC) == 0 &&
3444                    !env.next.tree.hasTag(REFERENCE) &&
3445                    sym.name != names._super &&
3446                    (sym.kind == VAR || sym.kind == MTH)) {
3447                    rs.accessBase(rs.new StaticError(sym),
3448                              tree.pos(), site, sym.name, true);
3449                }
3450            }
3451            if (!allowStaticInterfaceMethods && sitesym.isInterface() &&
3452                    sym.isStatic() && sym.kind == MTH) {
3453                log.error(tree.pos(), "static.intf.method.invoke.not.supported.in.source", sourceName);
3454            }
3455        } else if (sym.kind != ERR &&
3456                   (sym.flags() & STATIC) != 0 &&
3457                   sym.name != names._class) {
3458            // If the qualified item is not a type and the selected item is static, report
3459            // a warning. Make allowance for the class of an array type e.g. Object[].class)
3460            chk.warnStatic(tree, "static.not.qualified.by.type",
3461                           sym.kind.kindName(), sym.owner);
3462        }
3463
3464        // If we are selecting an instance member via a `super', ...
3465        if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
3466
3467            // Check that super-qualified symbols are not abstract (JLS)
3468            rs.checkNonAbstract(tree.pos(), sym);
3469
3470            if (site.isRaw()) {
3471                // Determine argument types for site.
3472                Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
3473                if (site1 != null) site = site1;
3474            }
3475        }
3476
3477        if (env.info.isSerializable) {
3478            chk.checkElemAccessFromSerializableLambda(tree);
3479        }
3480
3481        env.info.selectSuper = selectSuperPrev;
3482        result = checkId(tree, site, sym, env, resultInfo);
3483    }
3484    //where
3485        /** Determine symbol referenced by a Select expression,
3486         *
3487         *  @param tree   The select tree.
3488         *  @param site   The type of the selected expression,
3489         *  @param env    The current environment.
3490         *  @param resultInfo The current result.
3491         */
3492        private Symbol selectSym(JCFieldAccess tree,
3493                                 Symbol location,
3494                                 Type site,
3495                                 Env<AttrContext> env,
3496                                 ResultInfo resultInfo) {
3497            DiagnosticPosition pos = tree.pos();
3498            Name name = tree.name;
3499            switch (site.getTag()) {
3500            case PACKAGE:
3501                return rs.accessBase(
3502                    rs.findIdentInPackage(env, site.tsym, name, resultInfo.pkind),
3503                    pos, location, site, name, true);
3504            case ARRAY:
3505            case CLASS:
3506                if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) {
3507                    return rs.resolveQualifiedMethod(
3508                        pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
3509                } else if (name == names._this || name == names._super) {
3510                    return rs.resolveSelf(pos, env, site.tsym, name);
3511                } else if (name == names._class) {
3512                    // In this case, we have already made sure in
3513                    // visitSelect that qualifier expression is a type.
3514                    Type t = syms.classType;
3515                    List<Type> typeargs = List.of(types.erasure(site));
3516                    t = new ClassType(t.getEnclosingType(), typeargs, t.tsym);
3517                    return new VarSymbol(
3518                        STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
3519                } else {
3520                    // We are seeing a plain identifier as selector.
3521                    Symbol sym = rs.findIdentInType(env, site, name, resultInfo.pkind);
3522                        sym = rs.accessBase(sym, pos, location, site, name, true);
3523                    return sym;
3524                }
3525            case WILDCARD:
3526                throw new AssertionError(tree);
3527            case TYPEVAR:
3528                // Normally, site.getUpperBound() shouldn't be null.
3529                // It should only happen during memberEnter/attribBase
3530                // when determining the super type which *must* beac
3531                // done before attributing the type variables.  In
3532                // other words, we are seeing this illegal program:
3533                // class B<T> extends A<T.foo> {}
3534                Symbol sym = (site.getUpperBound() != null)
3535                    ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
3536                    : null;
3537                if (sym == null) {
3538                    log.error(pos, "type.var.cant.be.deref");
3539                    return syms.errSymbol;
3540                } else {
3541                    Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
3542                        rs.new AccessError(env, site, sym) :
3543                                sym;
3544                    rs.accessBase(sym2, pos, location, site, name, true);
3545                    return sym;
3546                }
3547            case ERROR:
3548                // preserve identifier names through errors
3549                return types.createErrorType(name, site.tsym, site).tsym;
3550            default:
3551                // The qualifier expression is of a primitive type -- only
3552                // .class is allowed for these.
3553                if (name == names._class) {
3554                    // In this case, we have already made sure in Select that
3555                    // qualifier expression is a type.
3556                    Type t = syms.classType;
3557                    Type arg = types.boxedClass(site).type;
3558                    t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym);
3559                    return new VarSymbol(
3560                        STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
3561                } else {
3562                    log.error(pos, "cant.deref", site);
3563                    return syms.errSymbol;
3564                }
3565            }
3566        }
3567
3568        /** Determine type of identifier or select expression and check that
3569         *  (1) the referenced symbol is not deprecated
3570         *  (2) the symbol's type is safe (@see checkSafe)
3571         *  (3) if symbol is a variable, check that its type and kind are
3572         *      compatible with the prototype and protokind.
3573         *  (4) if symbol is an instance field of a raw type,
3574         *      which is being assigned to, issue an unchecked warning if its
3575         *      type changes under erasure.
3576         *  (5) if symbol is an instance method of a raw type, issue an
3577         *      unchecked warning if its argument types change under erasure.
3578         *  If checks succeed:
3579         *    If symbol is a constant, return its constant type
3580         *    else if symbol is a method, return its result type
3581         *    otherwise return its type.
3582         *  Otherwise return errType.
3583         *
3584         *  @param tree       The syntax tree representing the identifier
3585         *  @param site       If this is a select, the type of the selected
3586         *                    expression, otherwise the type of the current class.
3587         *  @param sym        The symbol representing the identifier.
3588         *  @param env        The current environment.
3589         *  @param resultInfo    The expected result
3590         */
3591        Type checkId(JCTree tree,
3592                     Type site,
3593                     Symbol sym,
3594                     Env<AttrContext> env,
3595                     ResultInfo resultInfo) {
3596            return (resultInfo.pt.hasTag(FORALL) || resultInfo.pt.hasTag(METHOD)) ?
3597                    checkMethodId(tree, site, sym, env, resultInfo) :
3598                    checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
3599        }
3600
3601        Type checkMethodId(JCTree tree,
3602                     Type site,
3603                     Symbol sym,
3604                     Env<AttrContext> env,
3605                     ResultInfo resultInfo) {
3606            boolean isPolymorhicSignature =
3607                (sym.baseSymbol().flags() & SIGNATURE_POLYMORPHIC) != 0;
3608            return isPolymorhicSignature ?
3609                    checkSigPolyMethodId(tree, site, sym, env, resultInfo) :
3610                    checkMethodIdInternal(tree, site, sym, env, resultInfo);
3611        }
3612
3613        Type checkSigPolyMethodId(JCTree tree,
3614                     Type site,
3615                     Symbol sym,
3616                     Env<AttrContext> env,
3617                     ResultInfo resultInfo) {
3618            //recover original symbol for signature polymorphic methods
3619            checkMethodIdInternal(tree, site, sym.baseSymbol(), env, resultInfo);
3620            env.info.pendingResolutionPhase = Resolve.MethodResolutionPhase.BASIC;
3621            return sym.type;
3622        }
3623
3624        Type checkMethodIdInternal(JCTree tree,
3625                     Type site,
3626                     Symbol sym,
3627                     Env<AttrContext> env,
3628                     ResultInfo resultInfo) {
3629            if (resultInfo.pkind.contains(KindSelector.POLY)) {
3630                Type pt = resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, sym, env.info.pendingResolutionPhase));
3631                Type owntype = checkIdInternal(tree, site, sym, pt, env, resultInfo);
3632                resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
3633                return owntype;
3634            } else {
3635                return checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
3636            }
3637        }
3638
3639        Type checkIdInternal(JCTree tree,
3640                     Type site,
3641                     Symbol sym,
3642                     Type pt,
3643                     Env<AttrContext> env,
3644                     ResultInfo resultInfo) {
3645            if (pt.isErroneous()) {
3646                return types.createErrorType(site);
3647            }
3648            Type owntype; // The computed type of this identifier occurrence.
3649            switch (sym.kind) {
3650            case TYP:
3651                // For types, the computed type equals the symbol's type,
3652                // except for two situations:
3653                owntype = sym.type;
3654                if (owntype.hasTag(CLASS)) {
3655                    chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym);
3656                    Type ownOuter = owntype.getEnclosingType();
3657
3658                    // (a) If the symbol's type is parameterized, erase it
3659                    // because no type parameters were given.
3660                    // We recover generic outer type later in visitTypeApply.
3661                    if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
3662                        owntype = types.erasure(owntype);
3663                    }
3664
3665                    // (b) If the symbol's type is an inner class, then
3666                    // we have to interpret its outer type as a superclass
3667                    // of the site type. Example:
3668                    //
3669                    // class Tree<A> { class Visitor { ... } }
3670                    // class PointTree extends Tree<Point> { ... }
3671                    // ...PointTree.Visitor...
3672                    //
3673                    // Then the type of the last expression above is
3674                    // Tree<Point>.Visitor.
3675                    else if (ownOuter.hasTag(CLASS) && site != ownOuter) {
3676                        Type normOuter = site;
3677                        if (normOuter.hasTag(CLASS)) {
3678                            normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
3679                        }
3680                        if (normOuter == null) // perhaps from an import
3681                            normOuter = types.erasure(ownOuter);
3682                        if (normOuter != ownOuter)
3683                            owntype = new ClassType(
3684                                normOuter, List.<Type>nil(), owntype.tsym,
3685                                owntype.getMetadata());
3686                    }
3687                }
3688                break;
3689            case VAR:
3690                VarSymbol v = (VarSymbol)sym;
3691                // Test (4): if symbol is an instance field of a raw type,
3692                // which is being assigned to, issue an unchecked warning if
3693                // its type changes under erasure.
3694                if (KindSelector.ASG.subset(pkind()) &&
3695                    v.owner.kind == TYP &&
3696                    (v.flags() & STATIC) == 0 &&
3697                    (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
3698                    Type s = types.asOuterSuper(site, v.owner);
3699                    if (s != null &&
3700                        s.isRaw() &&
3701                        !types.isSameType(v.type, v.erasure(types))) {
3702                        chk.warnUnchecked(tree.pos(),
3703                                          "unchecked.assign.to.var",
3704                                          v, s);
3705                    }
3706                }
3707                // The computed type of a variable is the type of the
3708                // variable symbol, taken as a member of the site type.
3709                owntype = (sym.owner.kind == TYP &&
3710                           sym.name != names._this && sym.name != names._super)
3711                    ? types.memberType(site, sym)
3712                    : sym.type;
3713
3714                // If the variable is a constant, record constant value in
3715                // computed type.
3716                if (v.getConstValue() != null && isStaticReference(tree))
3717                    owntype = owntype.constType(v.getConstValue());
3718
3719                if (resultInfo.pkind == KindSelector.VAL) {
3720                    owntype = capture(owntype); // capture "names as expressions"
3721                }
3722                break;
3723            case MTH: {
3724                owntype = checkMethod(site, sym,
3725                        new ResultInfo(resultInfo.pkind, resultInfo.pt.getReturnType(), resultInfo.checkContext),
3726                        env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(),
3727                        resultInfo.pt.getTypeArguments());
3728                break;
3729            }
3730            case PCK: case ERR:
3731                owntype = sym.type;
3732                break;
3733            default:
3734                throw new AssertionError("unexpected kind: " + sym.kind +
3735                                         " in tree " + tree);
3736            }
3737
3738            // Emit a `deprecation' warning if symbol is deprecated.
3739            // (for constructors (but not for constructor references), the error
3740            // was given when the constructor was resolved)
3741
3742            if (sym.name != names.init || tree.hasTag(REFERENCE)) {
3743                chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym);
3744                chk.checkSunAPI(tree.pos(), sym);
3745                chk.checkProfile(tree.pos(), sym);
3746            }
3747
3748            // If symbol is a variable, check that its type and
3749            // kind are compatible with the prototype and protokind.
3750            return check(tree, owntype, sym.kind.toSelector(), resultInfo);
3751        }
3752
3753        /** Check that variable is initialized and evaluate the variable's
3754         *  initializer, if not yet done. Also check that variable is not
3755         *  referenced before it is defined.
3756         *  @param tree    The tree making up the variable reference.
3757         *  @param env     The current environment.
3758         *  @param v       The variable's symbol.
3759         */
3760        private void checkInit(JCTree tree,
3761                               Env<AttrContext> env,
3762                               VarSymbol v,
3763                               boolean onlyWarning) {
3764            // A forward reference is diagnosed if the declaration position
3765            // of the variable is greater than the current tree position
3766            // and the tree and variable definition occur in the same class
3767            // definition.  Note that writes don't count as references.
3768            // This check applies only to class and instance
3769            // variables.  Local variables follow different scope rules,
3770            // and are subject to definite assignment checking.
3771            Env<AttrContext> initEnv = enclosingInitEnv(env);
3772            if (initEnv != null &&
3773                (initEnv.info.enclVar == v || v.pos > tree.pos) &&
3774                v.owner.kind == TYP &&
3775                v.owner == env.info.scope.owner.enclClass() &&
3776                ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
3777                (!env.tree.hasTag(ASSIGN) ||
3778                 TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
3779                String suffix = (initEnv.info.enclVar == v) ?
3780                                "self.ref" : "forward.ref";
3781                if (!onlyWarning || isStaticEnumField(v)) {
3782                    log.error(tree.pos(), "illegal." + suffix);
3783                } else if (useBeforeDeclarationWarning) {
3784                    log.warning(tree.pos(), suffix, v);
3785                }
3786            }
3787
3788            v.getConstValue(); // ensure initializer is evaluated
3789
3790            checkEnumInitializer(tree, env, v);
3791        }
3792
3793        /**
3794         * Returns the enclosing init environment associated with this env (if any). An init env
3795         * can be either a field declaration env or a static/instance initializer env.
3796         */
3797        Env<AttrContext> enclosingInitEnv(Env<AttrContext> env) {
3798            while (true) {
3799                switch (env.tree.getTag()) {
3800                    case VARDEF:
3801                        JCVariableDecl vdecl = (JCVariableDecl)env.tree;
3802                        if (vdecl.sym.owner.kind == TYP) {
3803                            //field
3804                            return env;
3805                        }
3806                        break;
3807                    case BLOCK:
3808                        if (env.next.tree.hasTag(CLASSDEF)) {
3809                            //instance/static initializer
3810                            return env;
3811                        }
3812                        break;
3813                    case METHODDEF:
3814                    case CLASSDEF:
3815                    case TOPLEVEL:
3816                        return null;
3817                }
3818                Assert.checkNonNull(env.next);
3819                env = env.next;
3820            }
3821        }
3822
3823        /**
3824         * Check for illegal references to static members of enum.  In
3825         * an enum type, constructors and initializers may not
3826         * reference its static members unless they are constant.
3827         *
3828         * @param tree    The tree making up the variable reference.
3829         * @param env     The current environment.
3830         * @param v       The variable's symbol.
3831         * @jls  section 8.9 Enums
3832         */
3833        private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
3834            // JLS:
3835            //
3836            // "It is a compile-time error to reference a static field
3837            // of an enum type that is not a compile-time constant
3838            // (15.28) from constructors, instance initializer blocks,
3839            // or instance variable initializer expressions of that
3840            // type. It is a compile-time error for the constructors,
3841            // instance initializer blocks, or instance variable
3842            // initializer expressions of an enum constant e to refer
3843            // to itself or to an enum constant of the same type that
3844            // is declared to the right of e."
3845            if (isStaticEnumField(v)) {
3846                ClassSymbol enclClass = env.info.scope.owner.enclClass();
3847
3848                if (enclClass == null || enclClass.owner == null)
3849                    return;
3850
3851                // See if the enclosing class is the enum (or a
3852                // subclass thereof) declaring v.  If not, this
3853                // reference is OK.
3854                if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
3855                    return;
3856
3857                // If the reference isn't from an initializer, then
3858                // the reference is OK.
3859                if (!Resolve.isInitializer(env))
3860                    return;
3861
3862                log.error(tree.pos(), "illegal.enum.static.ref");
3863            }
3864        }
3865
3866        /** Is the given symbol a static, non-constant field of an Enum?
3867         *  Note: enum literals should not be regarded as such
3868         */
3869        private boolean isStaticEnumField(VarSymbol v) {
3870            return Flags.isEnum(v.owner) &&
3871                   Flags.isStatic(v) &&
3872                   !Flags.isConstant(v) &&
3873                   v.name != names._class;
3874        }
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        Warner noteWarner = new Warner();
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