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