Attr.java revision 3066:820841f0e8bd
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            result = check(tree, capture(restype), KindSelector.VAL, resultInfo);
1894        }
1895        chk.validate(tree.typeargs, localEnv);
1896    }
1897    //where
1898        Type adjustMethodReturnType(Type qualifierType, Name methodName, List<Type> argtypes, Type restype) {
1899            if (methodName == names.clone && types.isArray(qualifierType)) {
1900                // as a special case, array.clone() has a result that is
1901                // the same as static type of the array being cloned
1902                return qualifierType;
1903            } else if (methodName == names.getClass && argtypes.isEmpty()) {
1904                // as a special case, x.getClass() has type Class<? extends |X|>
1905                return new ClassType(restype.getEnclosingType(),
1906                              List.<Type>of(new WildcardType(types.erasure(qualifierType),
1907                                                               BoundKind.EXTENDS,
1908                                                             syms.boundClass)),
1909                                     restype.tsym,
1910                                     restype.getMetadata());
1911            } else {
1912                return restype;
1913            }
1914        }
1915
1916        /** Check that given application node appears as first statement
1917         *  in a constructor call.
1918         *  @param tree   The application node
1919         *  @param env    The environment current at the application.
1920         */
1921        boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) {
1922            JCMethodDecl enclMethod = env.enclMethod;
1923            if (enclMethod != null && enclMethod.name == names.init) {
1924                JCBlock body = enclMethod.body;
1925                if (body.stats.head.hasTag(EXEC) &&
1926                    ((JCExpressionStatement) body.stats.head).expr == tree)
1927                    return true;
1928            }
1929            log.error(tree.pos(),"call.must.be.first.stmt.in.ctor",
1930                      TreeInfo.name(tree.meth));
1931            return false;
1932        }
1933
1934        /** Obtain a method type with given argument types.
1935         */
1936        Type newMethodTemplate(Type restype, List<Type> argtypes, List<Type> typeargtypes) {
1937            MethodType mt = new MethodType(argtypes, restype, List.<Type>nil(), syms.methodClass);
1938            return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
1939        }
1940
1941    public void visitNewClass(final JCNewClass tree) {
1942        Type owntype = types.createErrorType(tree.type);
1943
1944        // The local environment of a class creation is
1945        // a new environment nested in the current one.
1946        Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
1947
1948        // The anonymous inner class definition of the new expression,
1949        // if one is defined by it.
1950        JCClassDecl cdef = tree.def;
1951
1952        // If enclosing class is given, attribute it, and
1953        // complete class name to be fully qualified
1954        JCExpression clazz = tree.clazz; // Class field following new
1955        JCExpression clazzid;            // Identifier in class field
1956        JCAnnotatedType annoclazzid;     // Annotated type enclosing clazzid
1957        annoclazzid = null;
1958
1959        if (clazz.hasTag(TYPEAPPLY)) {
1960            clazzid = ((JCTypeApply) clazz).clazz;
1961            if (clazzid.hasTag(ANNOTATED_TYPE)) {
1962                annoclazzid = (JCAnnotatedType) clazzid;
1963                clazzid = annoclazzid.underlyingType;
1964            }
1965        } else {
1966            if (clazz.hasTag(ANNOTATED_TYPE)) {
1967                annoclazzid = (JCAnnotatedType) clazz;
1968                clazzid = annoclazzid.underlyingType;
1969            } else {
1970                clazzid = clazz;
1971            }
1972        }
1973
1974        JCExpression clazzid1 = clazzid; // The same in fully qualified form
1975
1976        if (tree.encl != null) {
1977            // We are seeing a qualified new, of the form
1978            //    <expr>.new C <...> (...) ...
1979            // In this case, we let clazz stand for the name of the
1980            // allocated class C prefixed with the type of the qualifier
1981            // expression, so that we can
1982            // resolve it with standard techniques later. I.e., if
1983            // <expr> has type T, then <expr>.new C <...> (...)
1984            // yields a clazz T.C.
1985            Type encltype = chk.checkRefType(tree.encl.pos(),
1986                                             attribExpr(tree.encl, env));
1987            // TODO 308: in <expr>.new C, do we also want to add the type annotations
1988            // from expr to the combined type, or not? Yes, do this.
1989            clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
1990                                                 ((JCIdent) clazzid).name);
1991
1992            EndPosTable endPosTable = this.env.toplevel.endPositions;
1993            endPosTable.storeEnd(clazzid1, tree.getEndPosition(endPosTable));
1994            if (clazz.hasTag(ANNOTATED_TYPE)) {
1995                JCAnnotatedType annoType = (JCAnnotatedType) clazz;
1996                List<JCAnnotation> annos = annoType.annotations;
1997
1998                if (annoType.underlyingType.hasTag(TYPEAPPLY)) {
1999                    clazzid1 = make.at(tree.pos).
2000                        TypeApply(clazzid1,
2001                                  ((JCTypeApply) clazz).arguments);
2002                }
2003
2004                clazzid1 = make.at(tree.pos).
2005                    AnnotatedType(annos, clazzid1);
2006            } else if (clazz.hasTag(TYPEAPPLY)) {
2007                clazzid1 = make.at(tree.pos).
2008                    TypeApply(clazzid1,
2009                              ((JCTypeApply) clazz).arguments);
2010            }
2011
2012            clazz = clazzid1;
2013        }
2014
2015        // Attribute clazz expression and store
2016        // symbol + type back into the attributed tree.
2017        Type clazztype;
2018
2019        try {
2020            env.info.isNewClass = true;
2021            clazztype = TreeInfo.isEnumInit(env.tree) ?
2022                attribIdentAsEnumType(env, (JCIdent)clazz) :
2023                attribType(clazz, env);
2024        } finally {
2025            env.info.isNewClass = false;
2026        }
2027
2028        clazztype = chk.checkDiamond(tree, clazztype);
2029        chk.validate(clazz, localEnv);
2030        if (tree.encl != null) {
2031            // We have to work in this case to store
2032            // symbol + type back into the attributed tree.
2033            tree.clazz.type = clazztype;
2034            TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
2035            clazzid.type = ((JCIdent) clazzid).sym.type;
2036            if (annoclazzid != null) {
2037                annoclazzid.type = clazzid.type;
2038            }
2039            if (!clazztype.isErroneous()) {
2040                if (cdef != null && clazztype.tsym.isInterface()) {
2041                    log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new");
2042                } else if (clazztype.tsym.isStatic()) {
2043                    log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym);
2044                }
2045            }
2046        } else if (!clazztype.tsym.isInterface() &&
2047                   clazztype.getEnclosingType().hasTag(CLASS)) {
2048            // Check for the existence of an apropos outer instance
2049            rs.resolveImplicitThis(tree.pos(), env, clazztype);
2050        }
2051
2052        // Attribute constructor arguments.
2053        ListBuffer<Type> argtypesBuf = new ListBuffer<>();
2054        final KindSelector pkind =
2055            attribArgs(KindSelector.VAL, tree.args, localEnv, argtypesBuf);
2056        List<Type> argtypes = argtypesBuf.toList();
2057        List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
2058
2059        // If we have made no mistakes in the class type...
2060        if (clazztype.hasTag(CLASS)) {
2061            // Enums may not be instantiated except implicitly
2062            if ((clazztype.tsym.flags_field & Flags.ENUM) != 0 &&
2063                (!env.tree.hasTag(VARDEF) ||
2064                 (((JCVariableDecl) env.tree).mods.flags & Flags.ENUM) == 0 ||
2065                 ((JCVariableDecl) env.tree).init != tree))
2066                log.error(tree.pos(), "enum.cant.be.instantiated");
2067
2068            boolean isSpeculativeDiamondInferenceRound = TreeInfo.isDiamond(tree) &&
2069                    resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
2070            boolean skipNonDiamondPath = false;
2071            // Check that class is not abstract
2072            if (cdef == null && !isSpeculativeDiamondInferenceRound && // class body may be nulled out in speculative tree copy
2073                (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
2074                log.error(tree.pos(), "abstract.cant.be.instantiated",
2075                          clazztype.tsym);
2076                skipNonDiamondPath = true;
2077            } else if (cdef != null && clazztype.tsym.isInterface()) {
2078                // Check that no constructor arguments are given to
2079                // anonymous classes implementing an interface
2080                if (!argtypes.isEmpty())
2081                    log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args");
2082
2083                if (!typeargtypes.isEmpty())
2084                    log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs");
2085
2086                // Error recovery: pretend no arguments were supplied.
2087                argtypes = List.nil();
2088                typeargtypes = List.nil();
2089                skipNonDiamondPath = true;
2090            }
2091            if (TreeInfo.isDiamond(tree)) {
2092                ClassType site = new ClassType(clazztype.getEnclosingType(),
2093                            clazztype.tsym.type.getTypeArguments(),
2094                                               clazztype.tsym,
2095                                               clazztype.getMetadata());
2096
2097                Env<AttrContext> diamondEnv = localEnv.dup(tree);
2098                diamondEnv.info.selectSuper = cdef != null;
2099                diamondEnv.info.pendingResolutionPhase = null;
2100
2101                //if the type of the instance creation expression is a class type
2102                //apply method resolution inference (JLS 15.12.2.7). The return type
2103                //of the resolved constructor will be a partially instantiated type
2104                Symbol constructor = rs.resolveDiamond(tree.pos(),
2105                            diamondEnv,
2106                            site,
2107                            argtypes,
2108                            typeargtypes);
2109                tree.constructor = constructor.baseSymbol();
2110
2111                final TypeSymbol csym = clazztype.tsym;
2112                ResultInfo diamondResult = new ResultInfo(pkind, newMethodTemplate(resultInfo.pt, argtypes, typeargtypes),
2113                        diamondContext(tree, csym, resultInfo.checkContext), CheckMode.NO_TREE_UPDATE);
2114                Type constructorType = tree.constructorType = types.createErrorType(clazztype);
2115                constructorType = checkId(tree, site,
2116                        constructor,
2117                        diamondEnv,
2118                        diamondResult);
2119
2120                tree.clazz.type = types.createErrorType(clazztype);
2121                if (!constructorType.isErroneous()) {
2122                    tree.clazz.type = clazz.type = constructorType.getReturnType();
2123                    tree.constructorType = types.createMethodTypeWithReturn(constructorType, syms.voidType);
2124                }
2125                clazztype = chk.checkClassType(tree.clazz, tree.clazz.type, true);
2126            }
2127
2128            // Resolve the called constructor under the assumption
2129            // that we are referring to a superclass instance of the
2130            // current instance (JLS ???).
2131            else if (!skipNonDiamondPath) {
2132                //the following code alters some of the fields in the current
2133                //AttrContext - hence, the current context must be dup'ed in
2134                //order to avoid downstream failures
2135                Env<AttrContext> rsEnv = localEnv.dup(tree);
2136                rsEnv.info.selectSuper = cdef != null;
2137                rsEnv.info.pendingResolutionPhase = null;
2138                tree.constructor = rs.resolveConstructor(
2139                    tree.pos(), rsEnv, clazztype, argtypes, typeargtypes);
2140                if (cdef == null) { //do not check twice!
2141                    tree.constructorType = checkId(tree,
2142                            clazztype,
2143                            tree.constructor,
2144                            rsEnv,
2145                            new ResultInfo(pkind, newMethodTemplate(syms.voidType, argtypes, typeargtypes), CheckMode.NO_TREE_UPDATE));
2146                    if (rsEnv.info.lastResolveVarargs())
2147                        Assert.check(tree.constructorType.isErroneous() || tree.varargsElement != null);
2148                }
2149            }
2150
2151            if (cdef != null) {
2152                visitAnonymousClassDefinition(tree, clazz, clazztype, cdef, localEnv, argtypes, typeargtypes, pkind);
2153                return;
2154            }
2155
2156            if (tree.constructor != null && tree.constructor.kind == MTH)
2157                owntype = clazztype;
2158        }
2159        result = check(tree, owntype, KindSelector.VAL, resultInfo);
2160        InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
2161        if (tree.constructorType != null && inferenceContext.free(tree.constructorType)) {
2162            //we need to wait for inference to finish and then replace inference vars in the constructor type
2163            inferenceContext.addFreeTypeListener(List.of(tree.constructorType),
2164                    instantiatedContext -> {
2165                        tree.constructorType = instantiatedContext.asInstType(tree.constructorType);
2166                    });
2167        }
2168        chk.validate(tree.typeargs, localEnv);
2169    }
2170
2171        // where
2172        private void visitAnonymousClassDefinition(JCNewClass tree, JCExpression clazz, Type clazztype,
2173                                                   JCClassDecl cdef, Env<AttrContext> localEnv,
2174                                                   List<Type> argtypes, List<Type> typeargtypes,
2175                                                   KindSelector pkind) {
2176            // We are seeing an anonymous class instance creation.
2177            // In this case, the class instance creation
2178            // expression
2179            //
2180            //    E.new <typeargs1>C<typargs2>(args) { ... }
2181            //
2182            // is represented internally as
2183            //
2184            //    E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } )  .
2185            //
2186            // This expression is then *transformed* as follows:
2187            //
2188            // (1) add an extends or implements clause
2189            // (2) add a constructor.
2190            //
2191            // For instance, if C is a class, and ET is the type of E,
2192            // the expression
2193            //
2194            //    E.new <typeargs1>C<typargs2>(args) { ... }
2195            //
2196            // is translated to (where X is a fresh name and typarams is the
2197            // parameter list of the super constructor):
2198            //
2199            //   new <typeargs1>X(<*nullchk*>E, args) where
2200            //     X extends C<typargs2> {
2201            //       <typarams> X(ET e, args) {
2202            //         e.<typeargs1>super(args)
2203            //       }
2204            //       ...
2205            //     }
2206            InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
2207            final boolean isDiamond = TreeInfo.isDiamond(tree);
2208            if (isDiamond
2209                    && ((tree.constructorType != null && inferenceContext.free(tree.constructorType))
2210                    || (tree.clazz.type != null && inferenceContext.free(tree.clazz.type)))) {
2211                final ResultInfo resultInfoForClassDefinition = this.resultInfo;
2212                inferenceContext.addFreeTypeListener(List.of(tree.constructorType, tree.clazz.type),
2213                        instantiatedContext -> {
2214                            tree.constructorType = instantiatedContext.asInstType(tree.constructorType);
2215                            tree.clazz.type = clazz.type = instantiatedContext.asInstType(clazz.type);
2216                            ResultInfo prevResult = this.resultInfo;
2217                            try {
2218                                this.resultInfo = resultInfoForClassDefinition;
2219                                visitAnonymousClassDefinition(tree, clazz, clazz.type, cdef,
2220                                                            localEnv, argtypes, typeargtypes, pkind);
2221                            } finally {
2222                                this.resultInfo = prevResult;
2223                            }
2224                        });
2225            } else {
2226                if (isDiamond && clazztype.hasTag(CLASS)) {
2227                    List<Type> invalidDiamondArgs = chk.checkDiamondDenotable((ClassType)clazztype);
2228                    if (!clazztype.isErroneous() && invalidDiamondArgs.nonEmpty()) {
2229                        // One or more types inferred in the previous steps is non-denotable.
2230                        Fragment fragment = Diamond(clazztype.tsym);
2231                        log.error(tree.clazz.pos(),
2232                                Errors.CantApplyDiamond1(
2233                                        fragment,
2234                                        invalidDiamondArgs.size() > 1 ?
2235                                                DiamondInvalidArgs(invalidDiamondArgs, fragment) :
2236                                                DiamondInvalidArg(invalidDiamondArgs, fragment)));
2237                    }
2238                    // For <>(){}, inferred types must also be accessible.
2239                    for (Type t : clazztype.getTypeArguments()) {
2240                        rs.checkAccessibleType(env, t);
2241                    }
2242                }
2243
2244                // If we already errored, be careful to avoid a further avalanche. ErrorType answers
2245                // false for isInterface call even when the original type is an interface.
2246                boolean implementing = clazztype.tsym.isInterface() ||
2247                        clazztype.isErroneous() && clazztype.getOriginalType().tsym.isInterface();
2248
2249                if (implementing) {
2250                    cdef.implementing = List.of(clazz);
2251                } else {
2252                    cdef.extending = clazz;
2253                }
2254
2255                if (resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
2256                    isSerializable(clazztype)) {
2257                    localEnv.info.isSerializable = true;
2258                }
2259
2260                attribStat(cdef, localEnv);
2261
2262                List<Type> finalargtypes;
2263                // If an outer instance is given,
2264                // prefix it to the constructor arguments
2265                // and delete it from the new expression
2266                if (tree.encl != null && !clazztype.tsym.isInterface()) {
2267                    tree.args = tree.args.prepend(makeNullCheck(tree.encl));
2268                    finalargtypes = argtypes.prepend(tree.encl.type);
2269                    tree.encl = null;
2270                } else {
2271                    finalargtypes = argtypes;
2272                }
2273
2274                // Reassign clazztype and recompute constructor. As this necessarily involves
2275                // another attribution pass for deferred types in the case of <>, replicate
2276                // them. Original arguments have right decorations already.
2277                if (isDiamond && pkind.contains(KindSelector.POLY)) {
2278                    finalargtypes = finalargtypes.map(deferredAttr.deferredCopier);
2279                }
2280
2281                clazztype = cdef.sym.type;
2282                Symbol sym = tree.constructor = rs.resolveConstructor(
2283                        tree.pos(), localEnv, clazztype, finalargtypes, typeargtypes);
2284                Assert.check(!sym.kind.isResolutionError());
2285                tree.constructor = sym;
2286                tree.constructorType = checkId(tree,
2287                        clazztype,
2288                        tree.constructor,
2289                        localEnv,
2290                        new ResultInfo(pkind, newMethodTemplate(syms.voidType, finalargtypes, typeargtypes), CheckMode.NO_TREE_UPDATE));
2291            }
2292            Type owntype = (tree.constructor != null && tree.constructor.kind == MTH) ?
2293                                clazztype : types.createErrorType(tree.type);
2294            result = check(tree, owntype, KindSelector.VAL, resultInfo.dup(CheckMode.NO_INFERENCE_HOOK));
2295            chk.validate(tree.typeargs, localEnv);
2296        }
2297
2298        CheckContext diamondContext(JCNewClass clazz, TypeSymbol tsym, CheckContext checkContext) {
2299            return new Check.NestedCheckContext(checkContext) {
2300                @Override
2301                public void report(DiagnosticPosition _unused, JCDiagnostic details) {
2302                    enclosingContext.report(clazz.clazz,
2303                            diags.fragment("cant.apply.diamond.1", diags.fragment("diamond", tsym), details));
2304                }
2305            };
2306        }
2307
2308    /** Make an attributed null check tree.
2309     */
2310    public JCExpression makeNullCheck(JCExpression arg) {
2311        // optimization: X.this is never null; skip null check
2312        Name name = TreeInfo.name(arg);
2313        if (name == names._this || name == names._super) return arg;
2314
2315        JCTree.Tag optag = NULLCHK;
2316        JCUnary tree = make.at(arg.pos).Unary(optag, arg);
2317        tree.operator = operators.resolveUnary(arg, optag, arg.type);
2318        tree.type = arg.type;
2319        return tree;
2320    }
2321
2322    public void visitNewArray(JCNewArray tree) {
2323        Type owntype = types.createErrorType(tree.type);
2324        Env<AttrContext> localEnv = env.dup(tree);
2325        Type elemtype;
2326        if (tree.elemtype != null) {
2327            elemtype = attribType(tree.elemtype, localEnv);
2328            chk.validate(tree.elemtype, localEnv);
2329            owntype = elemtype;
2330            for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
2331                attribExpr(l.head, localEnv, syms.intType);
2332                owntype = new ArrayType(owntype, syms.arrayClass);
2333            }
2334        } else {
2335            // we are seeing an untyped aggregate { ... }
2336            // this is allowed only if the prototype is an array
2337            if (pt().hasTag(ARRAY)) {
2338                elemtype = types.elemtype(pt());
2339            } else {
2340                if (!pt().hasTag(ERROR)) {
2341                    log.error(tree.pos(), "illegal.initializer.for.type",
2342                              pt());
2343                }
2344                elemtype = types.createErrorType(pt());
2345            }
2346        }
2347        if (tree.elems != null) {
2348            attribExprs(tree.elems, localEnv, elemtype);
2349            owntype = new ArrayType(elemtype, syms.arrayClass);
2350        }
2351        if (!types.isReifiable(elemtype))
2352            log.error(tree.pos(), "generic.array.creation");
2353        result = check(tree, owntype, KindSelector.VAL, resultInfo);
2354    }
2355
2356    /*
2357     * A lambda expression can only be attributed when a target-type is available.
2358     * In addition, if the target-type is that of a functional interface whose
2359     * descriptor contains inference variables in argument position the lambda expression
2360     * is 'stuck' (see DeferredAttr).
2361     */
2362    @Override
2363    public void visitLambda(final JCLambda that) {
2364        if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
2365            if (pt().hasTag(NONE)) {
2366                //lambda only allowed in assignment or method invocation/cast context
2367                log.error(that.pos(), "unexpected.lambda");
2368            }
2369            result = that.type = types.createErrorType(pt());
2370            return;
2371        }
2372        //create an environment for attribution of the lambda expression
2373        final Env<AttrContext> localEnv = lambdaEnv(that, env);
2374        boolean needsRecovery =
2375                resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK;
2376        try {
2377            if (needsRecovery && isSerializable(pt())) {
2378                localEnv.info.isSerializable = true;
2379            }
2380            List<Type> explicitParamTypes = null;
2381            if (that.paramKind == JCLambda.ParameterKind.EXPLICIT) {
2382                //attribute lambda parameters
2383                attribStats(that.params, localEnv);
2384                explicitParamTypes = TreeInfo.types(that.params);
2385            }
2386
2387            TargetInfo targetInfo = getTargetInfo(that, resultInfo, explicitParamTypes);
2388            Type currentTarget = targetInfo.target;
2389            Type lambdaType = targetInfo.descriptor;
2390
2391            if (currentTarget.isErroneous()) {
2392                result = that.type = currentTarget;
2393                return;
2394            }
2395
2396            setFunctionalInfo(localEnv, that, pt(), lambdaType, currentTarget, resultInfo.checkContext);
2397
2398            if (lambdaType.hasTag(FORALL)) {
2399                //lambda expression target desc cannot be a generic method
2400                resultInfo.checkContext.report(that, diags.fragment("invalid.generic.lambda.target",
2401                        lambdaType, kindName(currentTarget.tsym), currentTarget.tsym));
2402                result = that.type = types.createErrorType(pt());
2403                return;
2404            }
2405
2406            if (that.paramKind == JCLambda.ParameterKind.IMPLICIT) {
2407                //add param type info in the AST
2408                List<Type> actuals = lambdaType.getParameterTypes();
2409                List<JCVariableDecl> params = that.params;
2410
2411                boolean arityMismatch = false;
2412
2413                while (params.nonEmpty()) {
2414                    if (actuals.isEmpty()) {
2415                        //not enough actuals to perform lambda parameter inference
2416                        arityMismatch = true;
2417                    }
2418                    //reset previously set info
2419                    Type argType = arityMismatch ?
2420                            syms.errType :
2421                            actuals.head;
2422                    params.head.vartype = make.at(params.head).Type(argType);
2423                    params.head.sym = null;
2424                    actuals = actuals.isEmpty() ?
2425                            actuals :
2426                            actuals.tail;
2427                    params = params.tail;
2428                }
2429
2430                //attribute lambda parameters
2431                attribStats(that.params, localEnv);
2432
2433                if (arityMismatch) {
2434                    resultInfo.checkContext.report(that, diags.fragment("incompatible.arg.types.in.lambda"));
2435                        result = that.type = types.createErrorType(currentTarget);
2436                        return;
2437                }
2438            }
2439
2440            //from this point on, no recovery is needed; if we are in assignment context
2441            //we will be able to attribute the whole lambda body, regardless of errors;
2442            //if we are in a 'check' method context, and the lambda is not compatible
2443            //with the target-type, it will be recovered anyway in Attr.checkId
2444            needsRecovery = false;
2445
2446            ResultInfo bodyResultInfo = localEnv.info.returnResult =
2447                    lambdaBodyResult(that, lambdaType, resultInfo);
2448
2449            if (that.getBodyKind() == JCLambda.BodyKind.EXPRESSION) {
2450                attribTree(that.getBody(), localEnv, bodyResultInfo);
2451            } else {
2452                JCBlock body = (JCBlock)that.body;
2453                attribStats(body.stats, localEnv);
2454            }
2455
2456            result = check(that, currentTarget, KindSelector.VAL, resultInfo);
2457
2458            boolean isSpeculativeRound =
2459                    resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
2460
2461            preFlow(that);
2462            flow.analyzeLambda(env, that, make, isSpeculativeRound);
2463
2464            that.type = currentTarget; //avoids recovery at this stage
2465            checkLambdaCompatible(that, lambdaType, resultInfo.checkContext);
2466
2467            if (!isSpeculativeRound) {
2468                //add thrown types as bounds to the thrown types free variables if needed:
2469                if (resultInfo.checkContext.inferenceContext().free(lambdaType.getThrownTypes())) {
2470                    List<Type> inferredThrownTypes = flow.analyzeLambdaThrownTypes(env, that, make);
2471                    List<Type> thrownTypes = resultInfo.checkContext.inferenceContext().asUndetVars(lambdaType.getThrownTypes());
2472
2473                    chk.unhandled(inferredThrownTypes, thrownTypes);
2474                }
2475
2476                checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), lambdaType, currentTarget);
2477            }
2478            result = check(that, currentTarget, KindSelector.VAL, resultInfo);
2479        } catch (Types.FunctionDescriptorLookupError ex) {
2480            JCDiagnostic cause = ex.getDiagnostic();
2481            resultInfo.checkContext.report(that, cause);
2482            result = that.type = types.createErrorType(pt());
2483            return;
2484        } catch (Throwable t) {
2485            //when an unexpected exception happens, avoid attempts to attribute the same tree again
2486            //as that would likely cause the same exception again.
2487            needsRecovery = false;
2488            throw t;
2489        } finally {
2490            localEnv.info.scope.leave();
2491            if (needsRecovery) {
2492                attribTree(that, env, recoveryInfo);
2493            }
2494        }
2495    }
2496    //where
2497        class TargetInfo {
2498            Type target;
2499            Type descriptor;
2500
2501            public TargetInfo(Type target, Type descriptor) {
2502                this.target = target;
2503                this.descriptor = descriptor;
2504            }
2505        }
2506
2507        TargetInfo getTargetInfo(JCPolyExpression that, ResultInfo resultInfo, List<Type> explicitParamTypes) {
2508            Type lambdaType;
2509            Type currentTarget = resultInfo.pt;
2510            if (resultInfo.pt != Type.recoveryType) {
2511                /* We need to adjust the target. If the target is an
2512                 * intersection type, for example: SAM & I1 & I2 ...
2513                 * the target will be updated to SAM
2514                 */
2515                currentTarget = targetChecker.visit(currentTarget, that);
2516                if (explicitParamTypes != null) {
2517                    currentTarget = infer.instantiateFunctionalInterface(that,
2518                            currentTarget, explicitParamTypes, resultInfo.checkContext);
2519                }
2520                currentTarget = types.removeWildcards(currentTarget);
2521                lambdaType = types.findDescriptorType(currentTarget);
2522            } else {
2523                currentTarget = Type.recoveryType;
2524                lambdaType = fallbackDescriptorType(that);
2525            }
2526            if (that.hasTag(LAMBDA) && lambdaType.hasTag(FORALL)) {
2527                //lambda expression target desc cannot be a generic method
2528                resultInfo.checkContext.report(that, diags.fragment("invalid.generic.lambda.target",
2529                        lambdaType, kindName(currentTarget.tsym), currentTarget.tsym));
2530                currentTarget = types.createErrorType(pt());
2531            }
2532            return new TargetInfo(currentTarget, lambdaType);
2533        }
2534
2535        void preFlow(JCLambda tree) {
2536            new PostAttrAnalyzer() {
2537                @Override
2538                public void scan(JCTree tree) {
2539                    if (tree == null ||
2540                            (tree.type != null &&
2541                            tree.type == Type.stuckType)) {
2542                        //don't touch stuck expressions!
2543                        return;
2544                    }
2545                    super.scan(tree);
2546                }
2547            }.scan(tree);
2548        }
2549
2550        Types.MapVisitor<DiagnosticPosition> targetChecker = new Types.MapVisitor<DiagnosticPosition>() {
2551
2552            @Override
2553            public Type visitClassType(ClassType t, DiagnosticPosition pos) {
2554                return t.isIntersection() ?
2555                        visitIntersectionClassType((IntersectionClassType)t, pos) : t;
2556            }
2557
2558            public Type visitIntersectionClassType(IntersectionClassType ict, DiagnosticPosition pos) {
2559                Symbol desc = types.findDescriptorSymbol(makeNotionalInterface(ict));
2560                Type target = null;
2561                for (Type bound : ict.getExplicitComponents()) {
2562                    TypeSymbol boundSym = bound.tsym;
2563                    if (types.isFunctionalInterface(boundSym) &&
2564                            types.findDescriptorSymbol(boundSym) == desc) {
2565                        target = bound;
2566                    } else if (!boundSym.isInterface() || (boundSym.flags() & ANNOTATION) != 0) {
2567                        //bound must be an interface
2568                        reportIntersectionError(pos, "not.an.intf.component", boundSym);
2569                    }
2570                }
2571                return target != null ?
2572                        target :
2573                        ict.getExplicitComponents().head; //error recovery
2574            }
2575
2576            private TypeSymbol makeNotionalInterface(IntersectionClassType ict) {
2577                ListBuffer<Type> targs = new ListBuffer<>();
2578                ListBuffer<Type> supertypes = new ListBuffer<>();
2579                for (Type i : ict.interfaces_field) {
2580                    if (i.isParameterized()) {
2581                        targs.appendList(i.tsym.type.allparams());
2582                    }
2583                    supertypes.append(i.tsym.type);
2584                }
2585                IntersectionClassType notionalIntf = types.makeIntersectionType(supertypes.toList());
2586                notionalIntf.allparams_field = targs.toList();
2587                notionalIntf.tsym.flags_field |= INTERFACE;
2588                return notionalIntf.tsym;
2589            }
2590
2591            private void reportIntersectionError(DiagnosticPosition pos, String key, Object... args) {
2592                resultInfo.checkContext.report(pos, diags.fragment("bad.intersection.target.for.functional.expr",
2593                        diags.fragment(key, args)));
2594            }
2595        };
2596
2597        private Type fallbackDescriptorType(JCExpression tree) {
2598            switch (tree.getTag()) {
2599                case LAMBDA:
2600                    JCLambda lambda = (JCLambda)tree;
2601                    List<Type> argtypes = List.nil();
2602                    for (JCVariableDecl param : lambda.params) {
2603                        argtypes = param.vartype != null ?
2604                                argtypes.append(param.vartype.type) :
2605                                argtypes.append(syms.errType);
2606                    }
2607                    return new MethodType(argtypes, Type.recoveryType,
2608                            List.of(syms.throwableType), syms.methodClass);
2609                case REFERENCE:
2610                    return new MethodType(List.<Type>nil(), Type.recoveryType,
2611                            List.of(syms.throwableType), syms.methodClass);
2612                default:
2613                    Assert.error("Cannot get here!");
2614            }
2615            return null;
2616        }
2617
2618        private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
2619                final InferenceContext inferenceContext, final Type... ts) {
2620            checkAccessibleTypes(pos, env, inferenceContext, List.from(ts));
2621        }
2622
2623        private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
2624                final InferenceContext inferenceContext, final List<Type> ts) {
2625            if (inferenceContext.free(ts)) {
2626                inferenceContext.addFreeTypeListener(ts, new FreeTypeListener() {
2627                    @Override
2628                    public void typesInferred(InferenceContext inferenceContext) {
2629                        checkAccessibleTypes(pos, env, inferenceContext, inferenceContext.asInstTypes(ts));
2630                    }
2631                });
2632            } else {
2633                for (Type t : ts) {
2634                    rs.checkAccessibleType(env, t);
2635                }
2636            }
2637        }
2638
2639        /**
2640         * Lambda/method reference have a special check context that ensures
2641         * that i.e. a lambda return type is compatible with the expected
2642         * type according to both the inherited context and the assignment
2643         * context.
2644         */
2645        class FunctionalReturnContext extends Check.NestedCheckContext {
2646
2647            FunctionalReturnContext(CheckContext enclosingContext) {
2648                super(enclosingContext);
2649            }
2650
2651            @Override
2652            public boolean compatible(Type found, Type req, Warner warn) {
2653                //return type must be compatible in both current context and assignment context
2654                return chk.basicHandler.compatible(found, inferenceContext().asUndetVar(req), warn);
2655            }
2656
2657            @Override
2658            public void report(DiagnosticPosition pos, JCDiagnostic details) {
2659                enclosingContext.report(pos, diags.fragment("incompatible.ret.type.in.lambda", details));
2660            }
2661        }
2662
2663        class ExpressionLambdaReturnContext extends FunctionalReturnContext {
2664
2665            JCExpression expr;
2666
2667            ExpressionLambdaReturnContext(JCExpression expr, CheckContext enclosingContext) {
2668                super(enclosingContext);
2669                this.expr = expr;
2670            }
2671
2672            @Override
2673            public boolean compatible(Type found, Type req, Warner warn) {
2674                //a void return is compatible with an expression statement lambda
2675                return TreeInfo.isExpressionStatement(expr) && req.hasTag(VOID) ||
2676                        super.compatible(found, req, warn);
2677            }
2678        }
2679
2680        ResultInfo lambdaBodyResult(JCLambda that, Type descriptor, ResultInfo resultInfo) {
2681            FunctionalReturnContext funcContext = that.getBodyKind() == JCLambda.BodyKind.EXPRESSION ?
2682                    new ExpressionLambdaReturnContext((JCExpression)that.getBody(), resultInfo.checkContext) :
2683                    new FunctionalReturnContext(resultInfo.checkContext);
2684
2685            return descriptor.getReturnType() == Type.recoveryType ?
2686                    recoveryInfo :
2687                    new ResultInfo(KindSelector.VAL,
2688                            descriptor.getReturnType(), funcContext);
2689        }
2690
2691        /**
2692        * Lambda compatibility. Check that given return types, thrown types, parameter types
2693        * are compatible with the expected functional interface descriptor. This means that:
2694        * (i) parameter types must be identical to those of the target descriptor; (ii) return
2695        * types must be compatible with the return type of the expected descriptor.
2696        */
2697        void checkLambdaCompatible(JCLambda tree, Type descriptor, CheckContext checkContext) {
2698            Type returnType = checkContext.inferenceContext().asUndetVar(descriptor.getReturnType());
2699
2700            //return values have already been checked - but if lambda has no return
2701            //values, we must ensure that void/value compatibility is correct;
2702            //this amounts at checking that, if a lambda body can complete normally,
2703            //the descriptor's return type must be void
2704            if (tree.getBodyKind() == JCLambda.BodyKind.STATEMENT && tree.canCompleteNormally &&
2705                    !returnType.hasTag(VOID) && returnType != Type.recoveryType) {
2706                checkContext.report(tree, diags.fragment("incompatible.ret.type.in.lambda",
2707                        diags.fragment("missing.ret.val", returnType)));
2708            }
2709
2710            List<Type> argTypes = checkContext.inferenceContext().asUndetVars(descriptor.getParameterTypes());
2711            if (!types.isSameTypes(argTypes, TreeInfo.types(tree.params))) {
2712                checkContext.report(tree, diags.fragment("incompatible.arg.types.in.lambda"));
2713            }
2714        }
2715
2716        /* Map to hold 'fake' clinit methods. If a lambda is used to initialize a
2717         * static field and that lambda has type annotations, these annotations will
2718         * also be stored at these fake clinit methods.
2719         *
2720         * LambdaToMethod also use fake clinit methods so they can be reused.
2721         * Also as LTM is a phase subsequent to attribution, the methods from
2722         * clinits can be safely removed by LTM to save memory.
2723         */
2724        private Map<ClassSymbol, MethodSymbol> clinits = new HashMap<>();
2725
2726        public MethodSymbol removeClinit(ClassSymbol sym) {
2727            return clinits.remove(sym);
2728        }
2729
2730        /* This method returns an environment to be used to attribute a lambda
2731         * expression.
2732         *
2733         * The owner of this environment is a method symbol. If the current owner
2734         * is not a method, for example if the lambda is used to initialize
2735         * a field, then if the field is:
2736         *
2737         * - an instance field, we use the first constructor.
2738         * - a static field, we create a fake clinit method.
2739         */
2740        public Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) {
2741            Env<AttrContext> lambdaEnv;
2742            Symbol owner = env.info.scope.owner;
2743            if (owner.kind == VAR && owner.owner.kind == TYP) {
2744                //field initializer
2745                ClassSymbol enclClass = owner.enclClass();
2746                Symbol newScopeOwner = env.info.scope.owner;
2747                /* if the field isn't static, then we can get the first constructor
2748                 * and use it as the owner of the environment. This is what
2749                 * LTM code is doing to look for type annotations so we are fine.
2750                 */
2751                if ((owner.flags() & STATIC) == 0) {
2752                    for (Symbol s : enclClass.members_field.getSymbolsByName(names.init)) {
2753                        newScopeOwner = s;
2754                        break;
2755                    }
2756                } else {
2757                    /* if the field is static then we need to create a fake clinit
2758                     * method, this method can later be reused by LTM.
2759                     */
2760                    MethodSymbol clinit = clinits.get(enclClass);
2761                    if (clinit == null) {
2762                        Type clinitType = new MethodType(List.<Type>nil(),
2763                                syms.voidType, List.<Type>nil(), syms.methodClass);
2764                        clinit = new MethodSymbol(STATIC | SYNTHETIC | PRIVATE,
2765                                names.clinit, clinitType, enclClass);
2766                        clinit.params = List.<VarSymbol>nil();
2767                        clinits.put(enclClass, clinit);
2768                    }
2769                    newScopeOwner = clinit;
2770                }
2771                lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared(newScopeOwner)));
2772            } else {
2773                lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dup()));
2774            }
2775            return lambdaEnv;
2776        }
2777
2778    @Override
2779    public void visitReference(final JCMemberReference that) {
2780        if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
2781            if (pt().hasTag(NONE)) {
2782                //method reference only allowed in assignment or method invocation/cast context
2783                log.error(that.pos(), "unexpected.mref");
2784            }
2785            result = that.type = types.createErrorType(pt());
2786            return;
2787        }
2788        final Env<AttrContext> localEnv = env.dup(that);
2789        try {
2790            //attribute member reference qualifier - if this is a constructor
2791            //reference, the expected kind must be a type
2792            Type exprType = attribTree(that.expr, env, memberReferenceQualifierResult(that));
2793
2794            if (that.getMode() == JCMemberReference.ReferenceMode.NEW) {
2795                exprType = chk.checkConstructorRefType(that.expr, exprType);
2796                if (!exprType.isErroneous() &&
2797                    exprType.isRaw() &&
2798                    that.typeargs != null) {
2799                    log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
2800                        diags.fragment("mref.infer.and.explicit.params"));
2801                    exprType = types.createErrorType(exprType);
2802                }
2803            }
2804
2805            if (exprType.isErroneous()) {
2806                //if the qualifier expression contains problems,
2807                //give up attribution of method reference
2808                result = that.type = exprType;
2809                return;
2810            }
2811
2812            if (TreeInfo.isStaticSelector(that.expr, names)) {
2813                //if the qualifier is a type, validate it; raw warning check is
2814                //omitted as we don't know at this stage as to whether this is a
2815                //raw selector (because of inference)
2816                chk.validate(that.expr, env, false);
2817            } else {
2818                Symbol lhsSym = TreeInfo.symbol(that.expr);
2819                localEnv.info.selectSuper = lhsSym != null && lhsSym.name == names._super;
2820            }
2821            //attrib type-arguments
2822            List<Type> typeargtypes = List.nil();
2823            if (that.typeargs != null) {
2824                typeargtypes = attribTypes(that.typeargs, localEnv);
2825            }
2826
2827            boolean isTargetSerializable =
2828                    resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
2829                    isSerializable(pt());
2830            TargetInfo targetInfo = getTargetInfo(that, resultInfo, null);
2831            Type currentTarget = targetInfo.target;
2832            Type desc = targetInfo.descriptor;
2833
2834            setFunctionalInfo(localEnv, that, pt(), desc, currentTarget, resultInfo.checkContext);
2835            List<Type> argtypes = desc.getParameterTypes();
2836            Resolve.MethodCheck referenceCheck = rs.resolveMethodCheck;
2837
2838            if (resultInfo.checkContext.inferenceContext().free(argtypes)) {
2839                referenceCheck = rs.new MethodReferenceCheck(resultInfo.checkContext.inferenceContext());
2840            }
2841
2842            Pair<Symbol, Resolve.ReferenceLookupHelper> refResult = null;
2843            List<Type> saved_undet = resultInfo.checkContext.inferenceContext().save();
2844            try {
2845                refResult = rs.resolveMemberReference(localEnv, that, that.expr.type,
2846                        that.name, argtypes, typeargtypes, referenceCheck,
2847                        resultInfo.checkContext.inferenceContext(), rs.basicReferenceChooser);
2848            } finally {
2849                resultInfo.checkContext.inferenceContext().rollback(saved_undet);
2850            }
2851
2852            Symbol refSym = refResult.fst;
2853            Resolve.ReferenceLookupHelper lookupHelper = refResult.snd;
2854
2855            /** this switch will need to go away and be replaced by the new RESOLUTION_TARGET testing
2856             *  JDK-8075541
2857             */
2858            if (refSym.kind != MTH) {
2859                boolean targetError;
2860                switch (refSym.kind) {
2861                    case ABSENT_MTH:
2862                    case MISSING_ENCL:
2863                        targetError = false;
2864                        break;
2865                    case WRONG_MTH:
2866                    case WRONG_MTHS:
2867                    case AMBIGUOUS:
2868                    case HIDDEN:
2869                    case STATICERR:
2870                        targetError = true;
2871                        break;
2872                    default:
2873                        Assert.error("unexpected result kind " + refSym.kind);
2874                        targetError = false;
2875                }
2876
2877                JCDiagnostic detailsDiag = ((Resolve.ResolveError)refSym.baseSymbol()).getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT,
2878                                that, exprType.tsym, exprType, that.name, argtypes, typeargtypes);
2879
2880                JCDiagnostic.DiagnosticType diagKind = targetError ?
2881                        JCDiagnostic.DiagnosticType.FRAGMENT : JCDiagnostic.DiagnosticType.ERROR;
2882
2883                JCDiagnostic diag = diags.create(diagKind, log.currentSource(), that,
2884                        "invalid.mref", Kinds.kindName(that.getMode()), detailsDiag);
2885
2886                if (targetError && currentTarget == Type.recoveryType) {
2887                    //a target error doesn't make sense during recovery stage
2888                    //as we don't know what actual parameter types are
2889                    result = that.type = currentTarget;
2890                    return;
2891                } else {
2892                    if (targetError) {
2893                        resultInfo.checkContext.report(that, diag);
2894                    } else {
2895                        log.report(diag);
2896                    }
2897                    result = that.type = types.createErrorType(currentTarget);
2898                    return;
2899                }
2900            }
2901
2902            that.sym = refSym.baseSymbol();
2903            that.kind = lookupHelper.referenceKind(that.sym);
2904            that.ownerAccessible = rs.isAccessible(localEnv, that.sym.enclClass());
2905
2906            if (desc.getReturnType() == Type.recoveryType) {
2907                // stop here
2908                result = that.type = currentTarget;
2909                return;
2910            }
2911
2912            if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
2913
2914                if (that.getMode() == ReferenceMode.INVOKE &&
2915                        TreeInfo.isStaticSelector(that.expr, names) &&
2916                        that.kind.isUnbound() &&
2917                        !desc.getParameterTypes().head.isParameterized()) {
2918                    chk.checkRaw(that.expr, localEnv);
2919                }
2920
2921                if (that.sym.isStatic() && TreeInfo.isStaticSelector(that.expr, names) &&
2922                        exprType.getTypeArguments().nonEmpty()) {
2923                    //static ref with class type-args
2924                    log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
2925                            diags.fragment("static.mref.with.targs"));
2926                    result = that.type = types.createErrorType(currentTarget);
2927                    return;
2928                }
2929
2930                if (!refSym.isStatic() && that.kind == JCMemberReference.ReferenceKind.SUPER) {
2931                    // Check that super-qualified symbols are not abstract (JLS)
2932                    rs.checkNonAbstract(that.pos(), that.sym);
2933                }
2934
2935                if (isTargetSerializable) {
2936                    chk.checkElemAccessFromSerializableLambda(that);
2937                }
2938            }
2939
2940            ResultInfo checkInfo =
2941                    resultInfo.dup(newMethodTemplate(
2942                        desc.getReturnType().hasTag(VOID) ? Type.noType : desc.getReturnType(),
2943                        that.kind.isUnbound() ? argtypes.tail : argtypes, typeargtypes),
2944                        new FunctionalReturnContext(resultInfo.checkContext), CheckMode.NO_TREE_UPDATE);
2945
2946            Type refType = checkId(that, lookupHelper.site, refSym, localEnv, checkInfo);
2947
2948            if (that.kind.isUnbound() &&
2949                    resultInfo.checkContext.inferenceContext().free(argtypes.head)) {
2950                //re-generate inference constraints for unbound receiver
2951                if (!types.isSubtype(resultInfo.checkContext.inferenceContext().asUndetVar(argtypes.head), exprType)) {
2952                    //cannot happen as this has already been checked - we just need
2953                    //to regenerate the inference constraints, as that has been lost
2954                    //as a result of the call to inferenceContext.save()
2955                    Assert.error("Can't get here");
2956                }
2957            }
2958
2959            if (!refType.isErroneous()) {
2960                refType = types.createMethodTypeWithReturn(refType,
2961                        adjustMethodReturnType(lookupHelper.site, that.name, checkInfo.pt.getParameterTypes(), refType.getReturnType()));
2962            }
2963
2964            //go ahead with standard method reference compatibility check - note that param check
2965            //is a no-op (as this has been taken care during method applicability)
2966            boolean isSpeculativeRound =
2967                    resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
2968
2969            that.type = currentTarget; //avoids recovery at this stage
2970            checkReferenceCompatible(that, desc, refType, resultInfo.checkContext, isSpeculativeRound);
2971            if (!isSpeculativeRound) {
2972                checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), desc, currentTarget);
2973            }
2974            result = check(that, currentTarget, KindSelector.VAL, resultInfo);
2975        } catch (Types.FunctionDescriptorLookupError ex) {
2976            JCDiagnostic cause = ex.getDiagnostic();
2977            resultInfo.checkContext.report(that, cause);
2978            result = that.type = types.createErrorType(pt());
2979            return;
2980        }
2981    }
2982    //where
2983        ResultInfo memberReferenceQualifierResult(JCMemberReference tree) {
2984            //if this is a constructor reference, the expected kind must be a type
2985            return new ResultInfo(tree.getMode() == ReferenceMode.INVOKE ?
2986                                  KindSelector.VAL_TYP : KindSelector.TYP,
2987                                  Type.noType);
2988        }
2989
2990
2991    @SuppressWarnings("fallthrough")
2992    void checkReferenceCompatible(JCMemberReference tree, Type descriptor, Type refType, CheckContext checkContext, boolean speculativeAttr) {
2993        InferenceContext inferenceContext = checkContext.inferenceContext();
2994        Type returnType = inferenceContext.asUndetVar(descriptor.getReturnType());
2995
2996        Type resType;
2997        switch (tree.getMode()) {
2998            case NEW:
2999                if (!tree.expr.type.isRaw()) {
3000                    resType = tree.expr.type;
3001                    break;
3002                }
3003            default:
3004                resType = refType.getReturnType();
3005        }
3006
3007        Type incompatibleReturnType = resType;
3008
3009        if (returnType.hasTag(VOID)) {
3010            incompatibleReturnType = null;
3011        }
3012
3013        if (!returnType.hasTag(VOID) && !resType.hasTag(VOID)) {
3014            if (resType.isErroneous() ||
3015                    new FunctionalReturnContext(checkContext).compatible(resType, returnType, types.noWarnings)) {
3016                incompatibleReturnType = null;
3017            }
3018        }
3019
3020        if (incompatibleReturnType != null) {
3021            checkContext.report(tree, diags.fragment("incompatible.ret.type.in.mref",
3022                    diags.fragment("inconvertible.types", resType, descriptor.getReturnType())));
3023        } else {
3024            if (inferenceContext.free(refType)) {
3025                // we need to wait for inference to finish and then replace inference vars in the referent type
3026                inferenceContext.addFreeTypeListener(List.of(refType),
3027                        instantiatedContext -> {
3028                            tree.referentType = instantiatedContext.asInstType(refType);
3029                        });
3030            } else {
3031                tree.referentType = refType;
3032            }
3033        }
3034
3035        if (!speculativeAttr) {
3036            List<Type> thrownTypes = inferenceContext.asUndetVars(descriptor.getThrownTypes());
3037            if (chk.unhandled(refType.getThrownTypes(), thrownTypes).nonEmpty()) {
3038                log.error(tree, "incompatible.thrown.types.in.mref", refType.getThrownTypes());
3039            }
3040        }
3041    }
3042
3043    /**
3044     * Set functional type info on the underlying AST. Note: as the target descriptor
3045     * might contain inference variables, we might need to register an hook in the
3046     * current inference context.
3047     */
3048    private void setFunctionalInfo(final Env<AttrContext> env, final JCFunctionalExpression fExpr,
3049            final Type pt, final Type descriptorType, final Type primaryTarget, final CheckContext checkContext) {
3050        if (checkContext.inferenceContext().free(descriptorType)) {
3051            checkContext.inferenceContext().addFreeTypeListener(List.of(pt, descriptorType), new FreeTypeListener() {
3052                public void typesInferred(InferenceContext inferenceContext) {
3053                    setFunctionalInfo(env, fExpr, pt, inferenceContext.asInstType(descriptorType),
3054                            inferenceContext.asInstType(primaryTarget), checkContext);
3055                }
3056            });
3057        } else {
3058            ListBuffer<Type> targets = new ListBuffer<>();
3059            if (pt.hasTag(CLASS)) {
3060                if (pt.isCompound()) {
3061                    targets.append(types.removeWildcards(primaryTarget)); //this goes first
3062                    for (Type t : ((IntersectionClassType)pt()).interfaces_field) {
3063                        if (t != primaryTarget) {
3064                            targets.append(types.removeWildcards(t));
3065                        }
3066                    }
3067                } else {
3068                    targets.append(types.removeWildcards(primaryTarget));
3069                }
3070            }
3071            fExpr.targets = targets.toList();
3072            if (checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
3073                    pt != Type.recoveryType) {
3074                //check that functional interface class is well-formed
3075                try {
3076                    /* Types.makeFunctionalInterfaceClass() may throw an exception
3077                     * when it's executed post-inference. See the listener code
3078                     * above.
3079                     */
3080                    ClassSymbol csym = types.makeFunctionalInterfaceClass(env,
3081                            names.empty, List.of(fExpr.targets.head), ABSTRACT);
3082                    if (csym != null) {
3083                        chk.checkImplementations(env.tree, csym, csym);
3084                        try {
3085                            //perform an additional functional interface check on the synthetic class,
3086                            //as there may be spurious errors for raw targets - because of existing issues
3087                            //with membership and inheritance (see JDK-8074570).
3088                            csym.flags_field |= INTERFACE;
3089                            types.findDescriptorType(csym.type);
3090                        } catch (FunctionDescriptorLookupError err) {
3091                            resultInfo.checkContext.report(fExpr,
3092                                    diags.fragment(Fragments.NoSuitableFunctionalIntfInst(fExpr.targets.head)));
3093                        }
3094                    }
3095                } catch (Types.FunctionDescriptorLookupError ex) {
3096                    JCDiagnostic cause = ex.getDiagnostic();
3097                    resultInfo.checkContext.report(env.tree, cause);
3098                }
3099            }
3100        }
3101    }
3102
3103    public void visitParens(JCParens tree) {
3104        Type owntype = attribTree(tree.expr, env, resultInfo);
3105        result = check(tree, owntype, pkind(), resultInfo);
3106        Symbol sym = TreeInfo.symbol(tree);
3107        if (sym != null && sym.kind.matches(KindSelector.TYP_PCK))
3108            log.error(tree.pos(), "illegal.start.of.type");
3109    }
3110
3111    public void visitAssign(JCAssign tree) {
3112        Type owntype = attribTree(tree.lhs, env.dup(tree), varAssignmentInfo);
3113        Type capturedType = capture(owntype);
3114        attribExpr(tree.rhs, env, owntype);
3115        result = check(tree, capturedType, KindSelector.VAL, resultInfo);
3116    }
3117
3118    public void visitAssignop(JCAssignOp tree) {
3119        // Attribute arguments.
3120        Type owntype = attribTree(tree.lhs, env, varAssignmentInfo);
3121        Type operand = attribExpr(tree.rhs, env);
3122        // Find operator.
3123        Symbol operator = tree.operator = operators.resolveBinary(tree, tree.getTag().noAssignOp(), owntype, operand);
3124        if (operator.kind == MTH &&
3125                !owntype.isErroneous() &&
3126                !operand.isErroneous()) {
3127            chk.checkDivZero(tree.rhs.pos(), operator, operand);
3128            chk.checkCastable(tree.rhs.pos(),
3129                              operator.type.getReturnType(),
3130                              owntype);
3131        }
3132        result = check(tree, owntype, KindSelector.VAL, resultInfo);
3133    }
3134
3135    public void visitUnary(JCUnary tree) {
3136        // Attribute arguments.
3137        Type argtype = (tree.getTag().isIncOrDecUnaryOp())
3138            ? attribTree(tree.arg, env, varAssignmentInfo)
3139            : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
3140
3141        // Find operator.
3142        Symbol operator = tree.operator = operators.resolveUnary(tree, tree.getTag(), argtype);
3143        Type owntype = types.createErrorType(tree.type);
3144        if (operator.kind == MTH &&
3145                !argtype.isErroneous()) {
3146            owntype = (tree.getTag().isIncOrDecUnaryOp())
3147                ? tree.arg.type
3148                : operator.type.getReturnType();
3149            int opc = ((OperatorSymbol)operator).opcode;
3150
3151            // If the argument is constant, fold it.
3152            if (argtype.constValue() != null) {
3153                Type ctype = cfolder.fold1(opc, argtype);
3154                if (ctype != null) {
3155                    owntype = cfolder.coerce(ctype, owntype);
3156                }
3157            }
3158        }
3159        result = check(tree, owntype, KindSelector.VAL, resultInfo);
3160    }
3161
3162    public void visitBinary(JCBinary tree) {
3163        // Attribute arguments.
3164        Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
3165        Type right = chk.checkNonVoid(tree.rhs.pos(), attribExpr(tree.rhs, env));
3166        // Find operator.
3167        Symbol operator = tree.operator = operators.resolveBinary(tree, tree.getTag(), left, right);
3168        Type owntype = types.createErrorType(tree.type);
3169        if (operator.kind == MTH &&
3170                !left.isErroneous() &&
3171                !right.isErroneous()) {
3172            owntype = operator.type.getReturnType();
3173            int opc = ((OperatorSymbol)operator).opcode;
3174            // If both arguments are constants, fold them.
3175            if (left.constValue() != null && right.constValue() != null) {
3176                Type ctype = cfolder.fold2(opc, left, right);
3177                if (ctype != null) {
3178                    owntype = cfolder.coerce(ctype, owntype);
3179                }
3180            }
3181
3182            // Check that argument types of a reference ==, != are
3183            // castable to each other, (JLS 15.21).  Note: unboxing
3184            // comparisons will not have an acmp* opc at this point.
3185            if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
3186                if (!types.isCastable(left, right, new Warner(tree.pos()))) {
3187                    log.error(tree.pos(), "incomparable.types", left, right);
3188                }
3189            }
3190
3191            chk.checkDivZero(tree.rhs.pos(), operator, right);
3192        }
3193        result = check(tree, owntype, KindSelector.VAL, resultInfo);
3194    }
3195
3196    public void visitTypeCast(final JCTypeCast tree) {
3197        Type clazztype = attribType(tree.clazz, env);
3198        chk.validate(tree.clazz, env, false);
3199        //a fresh environment is required for 292 inference to work properly ---
3200        //see Infer.instantiatePolymorphicSignatureInstance()
3201        Env<AttrContext> localEnv = env.dup(tree);
3202        //should we propagate the target type?
3203        final ResultInfo castInfo;
3204        JCExpression expr = TreeInfo.skipParens(tree.expr);
3205        boolean isPoly = allowPoly && (expr.hasTag(LAMBDA) || expr.hasTag(REFERENCE));
3206        if (isPoly) {
3207            //expression is a poly - we need to propagate target type info
3208            castInfo = new ResultInfo(KindSelector.VAL, clazztype,
3209                                      new Check.NestedCheckContext(resultInfo.checkContext) {
3210                @Override
3211                public boolean compatible(Type found, Type req, Warner warn) {
3212                    return types.isCastable(found, req, warn);
3213                }
3214            });
3215        } else {
3216            //standalone cast - target-type info is not propagated
3217            castInfo = unknownExprInfo;
3218        }
3219        Type exprtype = attribTree(tree.expr, localEnv, castInfo);
3220        Type owntype = isPoly ? clazztype : chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
3221        if (exprtype.constValue() != null)
3222            owntype = cfolder.coerce(exprtype, owntype);
3223        result = check(tree, capture(owntype), KindSelector.VAL, resultInfo);
3224        if (!isPoly)
3225            chk.checkRedundantCast(localEnv, tree);
3226    }
3227
3228    public void visitTypeTest(JCInstanceOf tree) {
3229        Type exprtype = chk.checkNullOrRefType(
3230                tree.expr.pos(), attribExpr(tree.expr, env));
3231        Type clazztype = attribType(tree.clazz, env);
3232        if (!clazztype.hasTag(TYPEVAR)) {
3233            clazztype = chk.checkClassOrArrayType(tree.clazz.pos(), clazztype);
3234        }
3235        if (!clazztype.isErroneous() && !types.isReifiable(clazztype)) {
3236            log.error(tree.clazz.pos(), "illegal.generic.type.for.instof");
3237            clazztype = types.createErrorType(clazztype);
3238        }
3239        chk.validate(tree.clazz, env, false);
3240        chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
3241        result = check(tree, syms.booleanType, KindSelector.VAL, resultInfo);
3242    }
3243
3244    public void visitIndexed(JCArrayAccess tree) {
3245        Type owntype = types.createErrorType(tree.type);
3246        Type atype = attribExpr(tree.indexed, env);
3247        attribExpr(tree.index, env, syms.intType);
3248        if (types.isArray(atype))
3249            owntype = types.elemtype(atype);
3250        else if (!atype.hasTag(ERROR))
3251            log.error(tree.pos(), "array.req.but.found", atype);
3252        if (!pkind().contains(KindSelector.VAL))
3253            owntype = capture(owntype);
3254        result = check(tree, owntype, KindSelector.VAR, resultInfo);
3255    }
3256
3257    public void visitIdent(JCIdent tree) {
3258        Symbol sym;
3259
3260        // Find symbol
3261        if (pt().hasTag(METHOD) || pt().hasTag(FORALL)) {
3262            // If we are looking for a method, the prototype `pt' will be a
3263            // method type with the type of the call's arguments as parameters.
3264            env.info.pendingResolutionPhase = null;
3265            sym = rs.resolveMethod(tree.pos(), env, tree.name, pt().getParameterTypes(), pt().getTypeArguments());
3266        } else if (tree.sym != null && tree.sym.kind != VAR) {
3267            sym = tree.sym;
3268        } else {
3269            sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind());
3270        }
3271        tree.sym = sym;
3272
3273        // (1) Also find the environment current for the class where
3274        //     sym is defined (`symEnv').
3275        // Only for pre-tiger versions (1.4 and earlier):
3276        // (2) Also determine whether we access symbol out of an anonymous
3277        //     class in a this or super call.  This is illegal for instance
3278        //     members since such classes don't carry a this$n link.
3279        //     (`noOuterThisPath').
3280        Env<AttrContext> symEnv = env;
3281        boolean noOuterThisPath = false;
3282        if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
3283            sym.kind.matches(KindSelector.VAL_MTH) &&
3284            sym.owner.kind == TYP &&
3285            tree.name != names._this && tree.name != names._super) {
3286
3287            // Find environment in which identifier is defined.
3288            while (symEnv.outer != null &&
3289                   !sym.isMemberOf(symEnv.enclClass.sym, types)) {
3290                if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
3291                    noOuterThisPath = false;
3292                symEnv = symEnv.outer;
3293            }
3294        }
3295
3296        // If symbol is a variable, ...
3297        if (sym.kind == VAR) {
3298            VarSymbol v = (VarSymbol)sym;
3299
3300            // ..., evaluate its initializer, if it has one, and check for
3301            // illegal forward reference.
3302            checkInit(tree, env, v, false);
3303
3304            // If we are expecting a variable (as opposed to a value), check
3305            // that the variable is assignable in the current environment.
3306            if (KindSelector.ASG.subset(pkind()))
3307                checkAssignable(tree.pos(), v, null, env);
3308        }
3309
3310        // In a constructor body,
3311        // if symbol is a field or instance method, check that it is
3312        // not accessed before the supertype constructor is called.
3313        if ((symEnv.info.isSelfCall || noOuterThisPath) &&
3314            sym.kind.matches(KindSelector.VAL_MTH) &&
3315            sym.owner.kind == TYP &&
3316            (sym.flags() & STATIC) == 0) {
3317            chk.earlyRefError(tree.pos(), sym.kind == VAR ?
3318                                          sym : thisSym(tree.pos(), env));
3319        }
3320        Env<AttrContext> env1 = env;
3321        if (sym.kind != ERR && sym.kind != TYP &&
3322            sym.owner != null && sym.owner != env1.enclClass.sym) {
3323            // If the found symbol is inaccessible, then it is
3324            // accessed through an enclosing instance.  Locate this
3325            // enclosing instance:
3326            while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
3327                env1 = env1.outer;
3328        }
3329
3330        if (env.info.isSerializable) {
3331            chk.checkElemAccessFromSerializableLambda(tree);
3332        }
3333
3334        result = checkId(tree, env1.enclClass.sym.type, sym, env, resultInfo);
3335    }
3336
3337    public void visitSelect(JCFieldAccess tree) {
3338        // Determine the expected kind of the qualifier expression.
3339        KindSelector skind = KindSelector.NIL;
3340        if (tree.name == names._this || tree.name == names._super ||
3341                tree.name == names._class)
3342        {
3343            skind = KindSelector.TYP;
3344        } else {
3345            if (pkind().contains(KindSelector.PCK))
3346                skind = KindSelector.of(skind, KindSelector.PCK);
3347            if (pkind().contains(KindSelector.TYP))
3348                skind = KindSelector.of(skind, KindSelector.TYP, KindSelector.PCK);
3349            if (pkind().contains(KindSelector.VAL_MTH))
3350                skind = KindSelector.of(skind, KindSelector.VAL, KindSelector.TYP);
3351        }
3352
3353        // Attribute the qualifier expression, and determine its symbol (if any).
3354        Type site = attribTree(tree.selected, env, new ResultInfo(skind, Type.noType));
3355        if (!pkind().contains(KindSelector.TYP_PCK))
3356            site = capture(site); // Capture field access
3357
3358        // don't allow T.class T[].class, etc
3359        if (skind == KindSelector.TYP) {
3360            Type elt = site;
3361            while (elt.hasTag(ARRAY))
3362                elt = ((ArrayType)elt).elemtype;
3363            if (elt.hasTag(TYPEVAR)) {
3364                log.error(tree.pos(), "type.var.cant.be.deref");
3365                result = tree.type = types.createErrorType(tree.name, site.tsym, site);
3366                tree.sym = tree.type.tsym;
3367                return ;
3368            }
3369        }
3370
3371        // If qualifier symbol is a type or `super', assert `selectSuper'
3372        // for the selection. This is relevant for determining whether
3373        // protected symbols are accessible.
3374        Symbol sitesym = TreeInfo.symbol(tree.selected);
3375        boolean selectSuperPrev = env.info.selectSuper;
3376        env.info.selectSuper =
3377            sitesym != null &&
3378            sitesym.name == names._super;
3379
3380        // Determine the symbol represented by the selection.
3381        env.info.pendingResolutionPhase = null;
3382        Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
3383        if (sym.kind == VAR && sym.name != names._super && env.info.defaultSuperCallSite != null) {
3384            log.error(tree.selected.pos(), "not.encl.class", site.tsym);
3385            sym = syms.errSymbol;
3386        }
3387        if (sym.exists() && !isType(sym) && pkind().contains(KindSelector.TYP_PCK)) {
3388            site = capture(site);
3389            sym = selectSym(tree, sitesym, site, env, resultInfo);
3390        }
3391        boolean varArgs = env.info.lastResolveVarargs();
3392        tree.sym = sym;
3393
3394        if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) {
3395            site = types.skipTypeVars(site, true);
3396        }
3397
3398        // If that symbol is a variable, ...
3399        if (sym.kind == VAR) {
3400            VarSymbol v = (VarSymbol)sym;
3401
3402            // ..., evaluate its initializer, if it has one, and check for
3403            // illegal forward reference.
3404            checkInit(tree, env, v, true);
3405
3406            // If we are expecting a variable (as opposed to a value), check
3407            // that the variable is assignable in the current environment.
3408            if (KindSelector.ASG.subset(pkind()))
3409                checkAssignable(tree.pos(), v, tree.selected, env);
3410        }
3411
3412        if (sitesym != null &&
3413                sitesym.kind == VAR &&
3414                ((VarSymbol)sitesym).isResourceVariable() &&
3415                sym.kind == MTH &&
3416                sym.name.equals(names.close) &&
3417                sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) &&
3418                env.info.lint.isEnabled(LintCategory.TRY)) {
3419            log.warning(LintCategory.TRY, tree, "try.explicit.close.call");
3420        }
3421
3422        // Disallow selecting a type from an expression
3423        if (isType(sym) && (sitesym == null || !sitesym.kind.matches(KindSelector.TYP_PCK))) {
3424            tree.type = check(tree.selected, pt(),
3425                              sitesym == null ?
3426                                      KindSelector.VAL : sitesym.kind.toSelector(),
3427                              new ResultInfo(KindSelector.TYP_PCK, pt()));
3428        }
3429
3430        if (isType(sitesym)) {
3431            if (sym.name == names._this) {
3432                // If `C' is the currently compiled class, check that
3433                // C.this' does not appear in a call to a super(...)
3434                if (env.info.isSelfCall &&
3435                    site.tsym == env.enclClass.sym) {
3436                    chk.earlyRefError(tree.pos(), sym);
3437                }
3438            } else {
3439                // Check if type-qualified fields or methods are static (JLS)
3440                if ((sym.flags() & STATIC) == 0 &&
3441                    !env.next.tree.hasTag(REFERENCE) &&
3442                    sym.name != names._super &&
3443                    (sym.kind == VAR || sym.kind == MTH)) {
3444                    rs.accessBase(rs.new StaticError(sym),
3445                              tree.pos(), site, sym.name, true);
3446                }
3447            }
3448            if (!allowStaticInterfaceMethods && sitesym.isInterface() &&
3449                    sym.isStatic() && sym.kind == MTH) {
3450                log.error(tree.pos(), "static.intf.method.invoke.not.supported.in.source", sourceName);
3451            }
3452        } else if (sym.kind != ERR &&
3453                   (sym.flags() & STATIC) != 0 &&
3454                   sym.name != names._class) {
3455            // If the qualified item is not a type and the selected item is static, report
3456            // a warning. Make allowance for the class of an array type e.g. Object[].class)
3457            chk.warnStatic(tree, "static.not.qualified.by.type",
3458                           sym.kind.kindName(), sym.owner);
3459        }
3460
3461        // If we are selecting an instance member via a `super', ...
3462        if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
3463
3464            // Check that super-qualified symbols are not abstract (JLS)
3465            rs.checkNonAbstract(tree.pos(), sym);
3466
3467            if (site.isRaw()) {
3468                // Determine argument types for site.
3469                Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
3470                if (site1 != null) site = site1;
3471            }
3472        }
3473
3474        if (env.info.isSerializable) {
3475            chk.checkElemAccessFromSerializableLambda(tree);
3476        }
3477
3478        env.info.selectSuper = selectSuperPrev;
3479        result = checkId(tree, site, sym, env, resultInfo);
3480    }
3481    //where
3482        /** Determine symbol referenced by a Select expression,
3483         *
3484         *  @param tree   The select tree.
3485         *  @param site   The type of the selected expression,
3486         *  @param env    The current environment.
3487         *  @param resultInfo The current result.
3488         */
3489        private Symbol selectSym(JCFieldAccess tree,
3490                                 Symbol location,
3491                                 Type site,
3492                                 Env<AttrContext> env,
3493                                 ResultInfo resultInfo) {
3494            DiagnosticPosition pos = tree.pos();
3495            Name name = tree.name;
3496            switch (site.getTag()) {
3497            case PACKAGE:
3498                return rs.accessBase(
3499                    rs.findIdentInPackage(env, site.tsym, name, resultInfo.pkind),
3500                    pos, location, site, name, true);
3501            case ARRAY:
3502            case CLASS:
3503                if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) {
3504                    return rs.resolveQualifiedMethod(
3505                        pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
3506                } else if (name == names._this || name == names._super) {
3507                    return rs.resolveSelf(pos, env, site.tsym, name);
3508                } else if (name == names._class) {
3509                    // In this case, we have already made sure in
3510                    // visitSelect that qualifier expression is a type.
3511                    Type t = syms.classType;
3512                    List<Type> typeargs = List.of(types.erasure(site));
3513                    t = new ClassType(t.getEnclosingType(), typeargs, t.tsym);
3514                    return new VarSymbol(
3515                        STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
3516                } else {
3517                    // We are seeing a plain identifier as selector.
3518                    Symbol sym = rs.findIdentInType(env, site, name, resultInfo.pkind);
3519                        sym = rs.accessBase(sym, pos, location, site, name, true);
3520                    return sym;
3521                }
3522            case WILDCARD:
3523                throw new AssertionError(tree);
3524            case TYPEVAR:
3525                // Normally, site.getUpperBound() shouldn't be null.
3526                // It should only happen during memberEnter/attribBase
3527                // when determining the super type which *must* beac
3528                // done before attributing the type variables.  In
3529                // other words, we are seeing this illegal program:
3530                // class B<T> extends A<T.foo> {}
3531                Symbol sym = (site.getUpperBound() != null)
3532                    ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
3533                    : null;
3534                if (sym == null) {
3535                    log.error(pos, "type.var.cant.be.deref");
3536                    return syms.errSymbol;
3537                } else {
3538                    Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
3539                        rs.new AccessError(env, site, sym) :
3540                                sym;
3541                    rs.accessBase(sym2, pos, location, site, name, true);
3542                    return sym;
3543                }
3544            case ERROR:
3545                // preserve identifier names through errors
3546                return types.createErrorType(name, site.tsym, site).tsym;
3547            default:
3548                // The qualifier expression is of a primitive type -- only
3549                // .class is allowed for these.
3550                if (name == names._class) {
3551                    // In this case, we have already made sure in Select that
3552                    // qualifier expression is a type.
3553                    Type t = syms.classType;
3554                    Type arg = types.boxedClass(site).type;
3555                    t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym);
3556                    return new VarSymbol(
3557                        STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
3558                } else {
3559                    log.error(pos, "cant.deref", site);
3560                    return syms.errSymbol;
3561                }
3562            }
3563        }
3564
3565        /** Determine type of identifier or select expression and check that
3566         *  (1) the referenced symbol is not deprecated
3567         *  (2) the symbol's type is safe (@see checkSafe)
3568         *  (3) if symbol is a variable, check that its type and kind are
3569         *      compatible with the prototype and protokind.
3570         *  (4) if symbol is an instance field of a raw type,
3571         *      which is being assigned to, issue an unchecked warning if its
3572         *      type changes under erasure.
3573         *  (5) if symbol is an instance method of a raw type, issue an
3574         *      unchecked warning if its argument types change under erasure.
3575         *  If checks succeed:
3576         *    If symbol is a constant, return its constant type
3577         *    else if symbol is a method, return its result type
3578         *    otherwise return its type.
3579         *  Otherwise return errType.
3580         *
3581         *  @param tree       The syntax tree representing the identifier
3582         *  @param site       If this is a select, the type of the selected
3583         *                    expression, otherwise the type of the current class.
3584         *  @param sym        The symbol representing the identifier.
3585         *  @param env        The current environment.
3586         *  @param resultInfo    The expected result
3587         */
3588        Type checkId(JCTree tree,
3589                     Type site,
3590                     Symbol sym,
3591                     Env<AttrContext> env,
3592                     ResultInfo resultInfo) {
3593            return (resultInfo.pt.hasTag(FORALL) || resultInfo.pt.hasTag(METHOD)) ?
3594                    checkMethodId(tree, site, sym, env, resultInfo) :
3595                    checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
3596        }
3597
3598        Type checkMethodId(JCTree tree,
3599                     Type site,
3600                     Symbol sym,
3601                     Env<AttrContext> env,
3602                     ResultInfo resultInfo) {
3603            boolean isPolymorhicSignature =
3604                (sym.baseSymbol().flags() & SIGNATURE_POLYMORPHIC) != 0;
3605            return isPolymorhicSignature ?
3606                    checkSigPolyMethodId(tree, site, sym, env, resultInfo) :
3607                    checkMethodIdInternal(tree, site, sym, env, resultInfo);
3608        }
3609
3610        Type checkSigPolyMethodId(JCTree tree,
3611                     Type site,
3612                     Symbol sym,
3613                     Env<AttrContext> env,
3614                     ResultInfo resultInfo) {
3615            //recover original symbol for signature polymorphic methods
3616            checkMethodIdInternal(tree, site, sym.baseSymbol(), env, resultInfo);
3617            env.info.pendingResolutionPhase = Resolve.MethodResolutionPhase.BASIC;
3618            return sym.type;
3619        }
3620
3621        Type checkMethodIdInternal(JCTree tree,
3622                     Type site,
3623                     Symbol sym,
3624                     Env<AttrContext> env,
3625                     ResultInfo resultInfo) {
3626            if (resultInfo.pkind.contains(KindSelector.POLY)) {
3627                Type pt = resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, sym, env.info.pendingResolutionPhase));
3628                Type owntype = checkIdInternal(tree, site, sym, pt, env, resultInfo);
3629                resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
3630                return owntype;
3631            } else {
3632                return checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
3633            }
3634        }
3635
3636        Type checkIdInternal(JCTree tree,
3637                     Type site,
3638                     Symbol sym,
3639                     Type pt,
3640                     Env<AttrContext> env,
3641                     ResultInfo resultInfo) {
3642            if (pt.isErroneous()) {
3643                return types.createErrorType(site);
3644            }
3645            Type owntype; // The computed type of this identifier occurrence.
3646            switch (sym.kind) {
3647            case TYP:
3648                // For types, the computed type equals the symbol's type,
3649                // except for two situations:
3650                owntype = sym.type;
3651                if (owntype.hasTag(CLASS)) {
3652                    chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym);
3653                    Type ownOuter = owntype.getEnclosingType();
3654
3655                    // (a) If the symbol's type is parameterized, erase it
3656                    // because no type parameters were given.
3657                    // We recover generic outer type later in visitTypeApply.
3658                    if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
3659                        owntype = types.erasure(owntype);
3660                    }
3661
3662                    // (b) If the symbol's type is an inner class, then
3663                    // we have to interpret its outer type as a superclass
3664                    // of the site type. Example:
3665                    //
3666                    // class Tree<A> { class Visitor { ... } }
3667                    // class PointTree extends Tree<Point> { ... }
3668                    // ...PointTree.Visitor...
3669                    //
3670                    // Then the type of the last expression above is
3671                    // Tree<Point>.Visitor.
3672                    else if (ownOuter.hasTag(CLASS) && site != ownOuter) {
3673                        Type normOuter = site;
3674                        if (normOuter.hasTag(CLASS)) {
3675                            normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
3676                        }
3677                        if (normOuter == null) // perhaps from an import
3678                            normOuter = types.erasure(ownOuter);
3679                        if (normOuter != ownOuter)
3680                            owntype = new ClassType(
3681                                normOuter, List.<Type>nil(), owntype.tsym,
3682                                owntype.getMetadata());
3683                    }
3684                }
3685                break;
3686            case VAR:
3687                VarSymbol v = (VarSymbol)sym;
3688                // Test (4): if symbol is an instance field of a raw type,
3689                // which is being assigned to, issue an unchecked warning if
3690                // its type changes under erasure.
3691                if (KindSelector.ASG.subset(pkind()) &&
3692                    v.owner.kind == TYP &&
3693                    (v.flags() & STATIC) == 0 &&
3694                    (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
3695                    Type s = types.asOuterSuper(site, v.owner);
3696                    if (s != null &&
3697                        s.isRaw() &&
3698                        !types.isSameType(v.type, v.erasure(types))) {
3699                        chk.warnUnchecked(tree.pos(),
3700                                          "unchecked.assign.to.var",
3701                                          v, s);
3702                    }
3703                }
3704                // The computed type of a variable is the type of the
3705                // variable symbol, taken as a member of the site type.
3706                owntype = (sym.owner.kind == TYP &&
3707                           sym.name != names._this && sym.name != names._super)
3708                    ? types.memberType(site, sym)
3709                    : sym.type;
3710
3711                // If the variable is a constant, record constant value in
3712                // computed type.
3713                if (v.getConstValue() != null && isStaticReference(tree))
3714                    owntype = owntype.constType(v.getConstValue());
3715
3716                if (resultInfo.pkind == KindSelector.VAL) {
3717                    owntype = capture(owntype); // capture "names as expressions"
3718                }
3719                break;
3720            case MTH: {
3721                owntype = checkMethod(site, sym,
3722                        new ResultInfo(resultInfo.pkind, resultInfo.pt.getReturnType(), resultInfo.checkContext),
3723                        env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(),
3724                        resultInfo.pt.getTypeArguments());
3725                break;
3726            }
3727            case PCK: case ERR:
3728                owntype = sym.type;
3729                break;
3730            default:
3731                throw new AssertionError("unexpected kind: " + sym.kind +
3732                                         " in tree " + tree);
3733            }
3734
3735            // Emit a `deprecation' warning if symbol is deprecated.
3736            // (for constructors (but not for constructor references), the error
3737            // was given when the constructor was resolved)
3738
3739            if (sym.name != names.init || tree.hasTag(REFERENCE)) {
3740                chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym);
3741                chk.checkSunAPI(tree.pos(), sym);
3742                chk.checkProfile(tree.pos(), sym);
3743            }
3744
3745            // If symbol is a variable, check that its type and
3746            // kind are compatible with the prototype and protokind.
3747            return check(tree, owntype, sym.kind.toSelector(), resultInfo);
3748        }
3749
3750        /** Check that variable is initialized and evaluate the variable's
3751         *  initializer, if not yet done. Also check that variable is not
3752         *  referenced before it is defined.
3753         *  @param tree    The tree making up the variable reference.
3754         *  @param env     The current environment.
3755         *  @param v       The variable's symbol.
3756         */
3757        private void checkInit(JCTree tree,
3758                               Env<AttrContext> env,
3759                               VarSymbol v,
3760                               boolean onlyWarning) {
3761            // A forward reference is diagnosed if the declaration position
3762            // of the variable is greater than the current tree position
3763            // and the tree and variable definition occur in the same class
3764            // definition.  Note that writes don't count as references.
3765            // This check applies only to class and instance
3766            // variables.  Local variables follow different scope rules,
3767            // and are subject to definite assignment checking.
3768            Env<AttrContext> initEnv = enclosingInitEnv(env);
3769            if (initEnv != null &&
3770                (initEnv.info.enclVar == v || v.pos > tree.pos) &&
3771                v.owner.kind == TYP &&
3772                v.owner == env.info.scope.owner.enclClass() &&
3773                ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
3774                (!env.tree.hasTag(ASSIGN) ||
3775                 TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
3776                String suffix = (initEnv.info.enclVar == v) ?
3777                                "self.ref" : "forward.ref";
3778                if (!onlyWarning || isStaticEnumField(v)) {
3779                    log.error(tree.pos(), "illegal." + suffix);
3780                } else if (useBeforeDeclarationWarning) {
3781                    log.warning(tree.pos(), suffix, v);
3782                }
3783            }
3784
3785            v.getConstValue(); // ensure initializer is evaluated
3786
3787            checkEnumInitializer(tree, env, v);
3788        }
3789
3790        /**
3791         * Returns the enclosing init environment associated with this env (if any). An init env
3792         * can be either a field declaration env or a static/instance initializer env.
3793         */
3794        Env<AttrContext> enclosingInitEnv(Env<AttrContext> env) {
3795            while (true) {
3796                switch (env.tree.getTag()) {
3797                    case VARDEF:
3798                        JCVariableDecl vdecl = (JCVariableDecl)env.tree;
3799                        if (vdecl.sym.owner.kind == TYP) {
3800                            //field
3801                            return env;
3802                        }
3803                        break;
3804                    case BLOCK:
3805                        if (env.next.tree.hasTag(CLASSDEF)) {
3806                            //instance/static initializer
3807                            return env;
3808                        }
3809                        break;
3810                    case METHODDEF:
3811                    case CLASSDEF:
3812                    case TOPLEVEL:
3813                        return null;
3814                }
3815                Assert.checkNonNull(env.next);
3816                env = env.next;
3817            }
3818        }
3819
3820        /**
3821         * Check for illegal references to static members of enum.  In
3822         * an enum type, constructors and initializers may not
3823         * reference its static members unless they are constant.
3824         *
3825         * @param tree    The tree making up the variable reference.
3826         * @param env     The current environment.
3827         * @param v       The variable's symbol.
3828         * @jls  section 8.9 Enums
3829         */
3830        private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
3831            // JLS:
3832            //
3833            // "It is a compile-time error to reference a static field
3834            // of an enum type that is not a compile-time constant
3835            // (15.28) from constructors, instance initializer blocks,
3836            // or instance variable initializer expressions of that
3837            // type. It is a compile-time error for the constructors,
3838            // instance initializer blocks, or instance variable
3839            // initializer expressions of an enum constant e to refer
3840            // to itself or to an enum constant of the same type that
3841            // is declared to the right of e."
3842            if (isStaticEnumField(v)) {
3843                ClassSymbol enclClass = env.info.scope.owner.enclClass();
3844
3845                if (enclClass == null || enclClass.owner == null)
3846                    return;
3847
3848                // See if the enclosing class is the enum (or a
3849                // subclass thereof) declaring v.  If not, this
3850                // reference is OK.
3851                if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
3852                    return;
3853
3854                // If the reference isn't from an initializer, then
3855                // the reference is OK.
3856                if (!Resolve.isInitializer(env))
3857                    return;
3858
3859                log.error(tree.pos(), "illegal.enum.static.ref");
3860            }
3861        }
3862
3863        /** Is the given symbol a static, non-constant field of an Enum?
3864         *  Note: enum literals should not be regarded as such
3865         */
3866        private boolean isStaticEnumField(VarSymbol v) {
3867            return Flags.isEnum(v.owner) &&
3868                   Flags.isStatic(v) &&
3869                   !Flags.isConstant(v) &&
3870                   v.name != names._class;
3871        }
3872
3873    Warner noteWarner = new Warner();
3874
3875    /**
3876     * Check that method arguments conform to its instantiation.
3877     **/
3878    public Type checkMethod(Type site,
3879                            final Symbol sym,
3880                            ResultInfo resultInfo,
3881                            Env<AttrContext> env,
3882                            final List<JCExpression> argtrees,
3883                            List<Type> argtypes,
3884                            List<Type> typeargtypes) {
3885        // Test (5): if symbol is an instance method of a raw type, issue
3886        // an unchecked warning if its argument types change under erasure.
3887        if ((sym.flags() & STATIC) == 0 &&
3888            (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
3889            Type s = types.asOuterSuper(site, sym.owner);
3890            if (s != null && s.isRaw() &&
3891                !types.isSameTypes(sym.type.getParameterTypes(),
3892                                   sym.erasure(types).getParameterTypes())) {
3893                chk.warnUnchecked(env.tree.pos(),
3894                                  "unchecked.call.mbr.of.raw.type",
3895                                  sym, s);
3896            }
3897        }
3898
3899        if (env.info.defaultSuperCallSite != null) {
3900            for (Type sup : types.interfaces(env.enclClass.type).prepend(types.supertype((env.enclClass.type)))) {
3901                if (!sup.tsym.isSubClass(sym.enclClass(), types) ||
3902                        types.isSameType(sup, env.info.defaultSuperCallSite)) continue;
3903                List<MethodSymbol> icand_sup =
3904                        types.interfaceCandidates(sup, (MethodSymbol)sym);
3905                if (icand_sup.nonEmpty() &&
3906                        icand_sup.head != sym &&
3907                        icand_sup.head.overrides(sym, icand_sup.head.enclClass(), types, true)) {
3908                    log.error(env.tree.pos(), "illegal.default.super.call", env.info.defaultSuperCallSite,
3909                        diags.fragment("overridden.default", sym, sup));
3910                    break;
3911                }
3912            }
3913            env.info.defaultSuperCallSite = null;
3914        }
3915
3916        if (sym.isStatic() && site.isInterface() && env.tree.hasTag(APPLY)) {
3917            JCMethodInvocation app = (JCMethodInvocation)env.tree;
3918            if (app.meth.hasTag(SELECT) &&
3919                    !TreeInfo.isStaticSelector(((JCFieldAccess)app.meth).selected, names)) {
3920                log.error(env.tree.pos(), "illegal.static.intf.meth.call", site);
3921            }
3922        }
3923
3924        // Compute the identifier's instantiated type.
3925        // For methods, we need to compute the instance type by
3926        // Resolve.instantiate from the symbol's type as well as
3927        // any type arguments and value arguments.
3928        noteWarner.clear();
3929        try {
3930            Type owntype = rs.checkMethod(
3931                    env,
3932                    site,
3933                    sym,
3934                    resultInfo,
3935                    argtypes,
3936                    typeargtypes,
3937                    noteWarner);
3938
3939            DeferredAttr.DeferredTypeMap checkDeferredMap =
3940                deferredAttr.new DeferredTypeMap(DeferredAttr.AttrMode.CHECK, sym, env.info.pendingResolutionPhase);
3941
3942            argtypes = argtypes.map(checkDeferredMap);
3943
3944            if (noteWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
3945                chk.warnUnchecked(env.tree.pos(),
3946                        "unchecked.meth.invocation.applied",
3947                        kindName(sym),
3948                        sym.name,
3949                        rs.methodArguments(sym.type.getParameterTypes()),
3950                        rs.methodArguments(argtypes.map(checkDeferredMap)),
3951                        kindName(sym.location()),
3952                        sym.location());
3953               owntype = new MethodType(owntype.getParameterTypes(),
3954                       types.erasure(owntype.getReturnType()),
3955                       types.erasure(owntype.getThrownTypes()),
3956                       syms.methodClass);
3957            }
3958
3959            PolyKind pkind = (sym.type.hasTag(FORALL) &&
3960                 sym.type.getReturnType().containsAny(((ForAll)sym.type).tvars)) ?
3961                 PolyKind.POLY : PolyKind.STANDALONE;
3962            TreeInfo.setPolyKind(env.tree, pkind);
3963
3964            return (resultInfo.pt == Infer.anyPoly) ?
3965                    owntype :
3966                    chk.checkMethod(owntype, sym, env, argtrees, argtypes, env.info.lastResolveVarargs(),
3967                            resultInfo.checkContext.inferenceContext());
3968        } catch (Infer.InferenceException ex) {
3969            //invalid target type - propagate exception outwards or report error
3970            //depending on the current check context
3971            resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic());
3972            return types.createErrorType(site);
3973        } catch (Resolve.InapplicableMethodException ex) {
3974            final JCDiagnostic diag = ex.getDiagnostic();
3975            Resolve.InapplicableSymbolError errSym = rs.new InapplicableSymbolError(null) {
3976                @Override
3977                protected Pair<Symbol, JCDiagnostic> errCandidate() {
3978                    return new Pair<>(sym, diag);
3979                }
3980            };
3981            List<Type> argtypes2 = argtypes.map(
3982                    rs.new ResolveDeferredRecoveryMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
3983            JCDiagnostic errDiag = errSym.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
3984                    env.tree, sym, site, sym.name, argtypes2, typeargtypes);
3985            log.report(errDiag);
3986            return types.createErrorType(site);
3987        }
3988    }
3989
3990    public void visitLiteral(JCLiteral tree) {
3991        result = check(tree, litType(tree.typetag).constType(tree.value),
3992                KindSelector.VAL, resultInfo);
3993    }
3994    //where
3995    /** Return the type of a literal with given type tag.
3996     */
3997    Type litType(TypeTag tag) {
3998        return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()];
3999    }
4000
4001    public void visitTypeIdent(JCPrimitiveTypeTree tree) {
4002        result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], KindSelector.TYP, resultInfo);
4003    }
4004
4005    public void visitTypeArray(JCArrayTypeTree tree) {
4006        Type etype = attribType(tree.elemtype, env);
4007        Type type = new ArrayType(etype, syms.arrayClass);
4008        result = check(tree, type, KindSelector.TYP, resultInfo);
4009    }
4010
4011    /** Visitor method for parameterized types.
4012     *  Bound checking is left until later, since types are attributed
4013     *  before supertype structure is completely known
4014     */
4015    public void visitTypeApply(JCTypeApply tree) {
4016        Type owntype = types.createErrorType(tree.type);
4017
4018        // Attribute functor part of application and make sure it's a class.
4019        Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
4020
4021        // Attribute type parameters
4022        List<Type> actuals = attribTypes(tree.arguments, env);
4023
4024        if (clazztype.hasTag(CLASS)) {
4025            List<Type> formals = clazztype.tsym.type.getTypeArguments();
4026            if (actuals.isEmpty()) //diamond
4027                actuals = formals;
4028
4029            if (actuals.length() == formals.length()) {
4030                List<Type> a = actuals;
4031                List<Type> f = formals;
4032                while (a.nonEmpty()) {
4033                    a.head = a.head.withTypeVar(f.head);
4034                    a = a.tail;
4035                    f = f.tail;
4036                }
4037                // Compute the proper generic outer
4038                Type clazzOuter = clazztype.getEnclosingType();
4039                if (clazzOuter.hasTag(CLASS)) {
4040                    Type site;
4041                    JCExpression clazz = TreeInfo.typeIn(tree.clazz);
4042                    if (clazz.hasTag(IDENT)) {
4043                        site = env.enclClass.sym.type;
4044                    } else if (clazz.hasTag(SELECT)) {
4045                        site = ((JCFieldAccess) clazz).selected.type;
4046                    } else throw new AssertionError(""+tree);
4047                    if (clazzOuter.hasTag(CLASS) && site != clazzOuter) {
4048                        if (site.hasTag(CLASS))
4049                            site = types.asOuterSuper(site, clazzOuter.tsym);
4050                        if (site == null)
4051                            site = types.erasure(clazzOuter);
4052                        clazzOuter = site;
4053                    }
4054                }
4055                owntype = new ClassType(clazzOuter, actuals, clazztype.tsym,
4056                                        clazztype.getMetadata());
4057            } else {
4058                if (formals.length() != 0) {
4059                    log.error(tree.pos(), "wrong.number.type.args",
4060                              Integer.toString(formals.length()));
4061                } else {
4062                    log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym);
4063                }
4064                owntype = types.createErrorType(tree.type);
4065            }
4066        }
4067        result = check(tree, owntype, KindSelector.TYP, resultInfo);
4068    }
4069
4070    public void visitTypeUnion(JCTypeUnion tree) {
4071        ListBuffer<Type> multicatchTypes = new ListBuffer<>();
4072        ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
4073        for (JCExpression typeTree : tree.alternatives) {
4074            Type ctype = attribType(typeTree, env);
4075            ctype = chk.checkType(typeTree.pos(),
4076                          chk.checkClassType(typeTree.pos(), ctype),
4077                          syms.throwableType);
4078            if (!ctype.isErroneous()) {
4079                //check that alternatives of a union type are pairwise
4080                //unrelated w.r.t. subtyping
4081                if (chk.intersects(ctype,  multicatchTypes.toList())) {
4082                    for (Type t : multicatchTypes) {
4083                        boolean sub = types.isSubtype(ctype, t);
4084                        boolean sup = types.isSubtype(t, ctype);
4085                        if (sub || sup) {
4086                            //assume 'a' <: 'b'
4087                            Type a = sub ? ctype : t;
4088                            Type b = sub ? t : ctype;
4089                            log.error(typeTree.pos(), "multicatch.types.must.be.disjoint", a, b);
4090                        }
4091                    }
4092                }
4093                multicatchTypes.append(ctype);
4094                if (all_multicatchTypes != null)
4095                    all_multicatchTypes.append(ctype);
4096            } else {
4097                if (all_multicatchTypes == null) {
4098                    all_multicatchTypes = new ListBuffer<>();
4099                    all_multicatchTypes.appendList(multicatchTypes);
4100                }
4101                all_multicatchTypes.append(ctype);
4102            }
4103        }
4104        Type t = check(tree, types.lub(multicatchTypes.toList()),
4105                KindSelector.TYP, resultInfo.dup(CheckMode.NO_TREE_UPDATE));
4106        if (t.hasTag(CLASS)) {
4107            List<Type> alternatives =
4108                ((all_multicatchTypes == null) ? multicatchTypes : all_multicatchTypes).toList();
4109            t = new UnionClassType((ClassType) t, alternatives);
4110        }
4111        tree.type = result = t;
4112    }
4113
4114    public void visitTypeIntersection(JCTypeIntersection tree) {
4115        attribTypes(tree.bounds, env);
4116        tree.type = result = checkIntersection(tree, tree.bounds);
4117    }
4118
4119    public void visitTypeParameter(JCTypeParameter tree) {
4120        TypeVar typeVar = (TypeVar) tree.type;
4121
4122        if (tree.annotations != null && tree.annotations.nonEmpty()) {
4123            annotate.annotateTypeParameterSecondStage(tree, tree.annotations);
4124        }
4125
4126        if (!typeVar.bound.isErroneous()) {
4127            //fixup type-parameter bound computed in 'attribTypeVariables'
4128            typeVar.bound = checkIntersection(tree, tree.bounds);
4129        }
4130    }
4131
4132    Type checkIntersection(JCTree tree, List<JCExpression> bounds) {
4133        Set<Type> boundSet = new HashSet<>();
4134        if (bounds.nonEmpty()) {
4135            // accept class or interface or typevar as first bound.
4136            bounds.head.type = checkBase(bounds.head.type, bounds.head, env, false, false, false);
4137            boundSet.add(types.erasure(bounds.head.type));
4138            if (bounds.head.type.isErroneous()) {
4139                return bounds.head.type;
4140            }
4141            else if (bounds.head.type.hasTag(TYPEVAR)) {
4142                // if first bound was a typevar, do not accept further bounds.
4143                if (bounds.tail.nonEmpty()) {
4144                    log.error(bounds.tail.head.pos(),
4145                              "type.var.may.not.be.followed.by.other.bounds");
4146                    return bounds.head.type;
4147                }
4148            } else {
4149                // if first bound was a class or interface, accept only interfaces
4150                // as further bounds.
4151                for (JCExpression bound : bounds.tail) {
4152                    bound.type = checkBase(bound.type, bound, env, false, true, false);
4153                    if (bound.type.isErroneous()) {
4154                        bounds = List.of(bound);
4155                    }
4156                    else if (bound.type.hasTag(CLASS)) {
4157                        chk.checkNotRepeated(bound.pos(), types.erasure(bound.type), boundSet);
4158                    }
4159                }
4160            }
4161        }
4162
4163        if (bounds.length() == 0) {
4164            return syms.objectType;
4165        } else if (bounds.length() == 1) {
4166            return bounds.head.type;
4167        } else {
4168            Type owntype = types.makeIntersectionType(TreeInfo.types(bounds));
4169            // ... the variable's bound is a class type flagged COMPOUND
4170            // (see comment for TypeVar.bound).
4171            // In this case, generate a class tree that represents the
4172            // bound class, ...
4173            JCExpression extending;
4174            List<JCExpression> implementing;
4175            if (!bounds.head.type.isInterface()) {
4176                extending = bounds.head;
4177                implementing = bounds.tail;
4178            } else {
4179                extending = null;
4180                implementing = bounds;
4181            }
4182            JCClassDecl cd = make.at(tree).ClassDef(
4183                make.Modifiers(PUBLIC | ABSTRACT),
4184                names.empty, List.<JCTypeParameter>nil(),
4185                extending, implementing, List.<JCTree>nil());
4186
4187            ClassSymbol c = (ClassSymbol)owntype.tsym;
4188            Assert.check((c.flags() & COMPOUND) != 0);
4189            cd.sym = c;
4190            c.sourcefile = env.toplevel.sourcefile;
4191
4192            // ... and attribute the bound class
4193            c.flags_field |= UNATTRIBUTED;
4194            Env<AttrContext> cenv = enter.classEnv(cd, env);
4195            typeEnvs.put(c, cenv);
4196            attribClass(c);
4197            return owntype;
4198        }
4199    }
4200
4201    public void visitWildcard(JCWildcard tree) {
4202        //- System.err.println("visitWildcard("+tree+");");//DEBUG
4203        Type type = (tree.kind.kind == BoundKind.UNBOUND)
4204            ? syms.objectType
4205            : attribType(tree.inner, env);
4206        result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
4207                                              tree.kind.kind,
4208                                              syms.boundClass),
4209                KindSelector.TYP, resultInfo);
4210    }
4211
4212    public void visitAnnotation(JCAnnotation tree) {
4213        Assert.error("should be handled in annotate");
4214    }
4215
4216    public void visitAnnotatedType(JCAnnotatedType tree) {
4217        attribAnnotationTypes(tree.annotations, env);
4218        Type underlyingType = attribType(tree.underlyingType, env);
4219        Type annotatedType = underlyingType.annotatedType(Annotations.TO_BE_SET);
4220
4221        if (!env.info.isNewClass)
4222            annotate.annotateTypeSecondStage(tree, tree.annotations, annotatedType);
4223        result = tree.type = annotatedType;
4224    }
4225
4226    public void visitErroneous(JCErroneous tree) {
4227        if (tree.errs != null)
4228            for (JCTree err : tree.errs)
4229                attribTree(err, env, new ResultInfo(KindSelector.ERR, pt()));
4230        result = tree.type = syms.errType;
4231    }
4232
4233    /** Default visitor method for all other trees.
4234     */
4235    public void visitTree(JCTree tree) {
4236        throw new AssertionError();
4237    }
4238
4239    /**
4240     * Attribute an env for either a top level tree or class declaration.
4241     */
4242    public void attrib(Env<AttrContext> env) {
4243        if (env.tree.hasTag(TOPLEVEL))
4244            attribTopLevel(env);
4245        else
4246            attribClass(env.tree.pos(), env.enclClass.sym);
4247    }
4248
4249    /**
4250     * Attribute a top level tree. These trees are encountered when the
4251     * package declaration has annotations.
4252     */
4253    public void attribTopLevel(Env<AttrContext> env) {
4254        JCCompilationUnit toplevel = env.toplevel;
4255        try {
4256            annotate.flush();
4257        } catch (CompletionFailure ex) {
4258            chk.completionError(toplevel.pos(), ex);
4259        }
4260    }
4261
4262    /** Main method: attribute class definition associated with given class symbol.
4263     *  reporting completion failures at the given position.
4264     *  @param pos The source position at which completion errors are to be
4265     *             reported.
4266     *  @param c   The class symbol whose definition will be attributed.
4267     */
4268    public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
4269        try {
4270            annotate.flush();
4271            attribClass(c);
4272        } catch (CompletionFailure ex) {
4273            chk.completionError(pos, ex);
4274        }
4275    }
4276
4277    /** Attribute class definition associated with given class symbol.
4278     *  @param c   The class symbol whose definition will be attributed.
4279     */
4280    void attribClass(ClassSymbol c) throws CompletionFailure {
4281        if (c.type.hasTag(ERROR)) return;
4282
4283        // Check for cycles in the inheritance graph, which can arise from
4284        // ill-formed class files.
4285        chk.checkNonCyclic(null, c.type);
4286
4287        Type st = types.supertype(c.type);
4288        if ((c.flags_field & Flags.COMPOUND) == 0) {
4289            // First, attribute superclass.
4290            if (st.hasTag(CLASS))
4291                attribClass((ClassSymbol)st.tsym);
4292
4293            // Next attribute owner, if it is a class.
4294            if (c.owner.kind == TYP && c.owner.type.hasTag(CLASS))
4295                attribClass((ClassSymbol)c.owner);
4296        }
4297
4298        // The previous operations might have attributed the current class
4299        // if there was a cycle. So we test first whether the class is still
4300        // UNATTRIBUTED.
4301        if ((c.flags_field & UNATTRIBUTED) != 0) {
4302            c.flags_field &= ~UNATTRIBUTED;
4303
4304            // Get environment current at the point of class definition.
4305            Env<AttrContext> env = typeEnvs.get(c);
4306
4307            // The info.lint field in the envs stored in typeEnvs is deliberately uninitialized,
4308            // because the annotations were not available at the time the env was created. Therefore,
4309            // we look up the environment chain for the first enclosing environment for which the
4310            // lint value is set. Typically, this is the parent env, but might be further if there
4311            // are any envs created as a result of TypeParameter nodes.
4312            Env<AttrContext> lintEnv = env;
4313            while (lintEnv.info.lint == null)
4314                lintEnv = lintEnv.next;
4315
4316            // Having found the enclosing lint value, we can initialize the lint value for this class
4317            env.info.lint = lintEnv.info.lint.augment(c);
4318
4319            Lint prevLint = chk.setLint(env.info.lint);
4320            JavaFileObject prev = log.useSource(c.sourcefile);
4321            ResultInfo prevReturnRes = env.info.returnResult;
4322
4323            try {
4324                deferredLintHandler.flush(env.tree);
4325                env.info.returnResult = null;
4326                // java.lang.Enum may not be subclassed by a non-enum
4327                if (st.tsym == syms.enumSym &&
4328                    ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
4329                    log.error(env.tree.pos(), "enum.no.subclassing");
4330
4331                // Enums may not be extended by source-level classes
4332                if (st.tsym != null &&
4333                    ((st.tsym.flags_field & Flags.ENUM) != 0) &&
4334                    ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
4335                    log.error(env.tree.pos(), "enum.types.not.extensible");
4336                }
4337
4338                if (isSerializable(c.type)) {
4339                    env.info.isSerializable = true;
4340                }
4341
4342                attribClassBody(env, c);
4343
4344                chk.checkDeprecatedAnnotation(env.tree.pos(), c);
4345                chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
4346                chk.checkFunctionalInterface((JCClassDecl) env.tree, c);
4347            } finally {
4348                env.info.returnResult = prevReturnRes;
4349                log.useSource(prev);
4350                chk.setLint(prevLint);
4351            }
4352
4353        }
4354    }
4355
4356    public void visitImport(JCImport tree) {
4357        // nothing to do
4358    }
4359
4360    /** Finish the attribution of a class. */
4361    private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
4362        JCClassDecl tree = (JCClassDecl)env.tree;
4363        Assert.check(c == tree.sym);
4364
4365        // Validate type parameters, supertype and interfaces.
4366        attribStats(tree.typarams, env);
4367        if (!c.isAnonymous()) {
4368            //already checked if anonymous
4369            chk.validate(tree.typarams, env);
4370            chk.validate(tree.extending, env);
4371            chk.validate(tree.implementing, env);
4372        }
4373
4374        c.markAbstractIfNeeded(types);
4375
4376        // If this is a non-abstract class, check that it has no abstract
4377        // methods or unimplemented methods of an implemented interface.
4378        if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
4379            if (!relax)
4380                chk.checkAllDefined(tree.pos(), c);
4381        }
4382
4383        if ((c.flags() & ANNOTATION) != 0) {
4384            if (tree.implementing.nonEmpty())
4385                log.error(tree.implementing.head.pos(),
4386                          "cant.extend.intf.annotation");
4387            if (tree.typarams.nonEmpty())
4388                log.error(tree.typarams.head.pos(),
4389                          "intf.annotation.cant.have.type.params");
4390
4391            // If this annotation type has a @Repeatable, validate
4392            Attribute.Compound repeatable = c.getAnnotationTypeMetadata().getRepeatable();
4393            // If this annotation type has a @Repeatable, validate
4394            if (repeatable != null) {
4395                // get diagnostic position for error reporting
4396                DiagnosticPosition cbPos = getDiagnosticPosition(tree, repeatable.type);
4397                Assert.checkNonNull(cbPos);
4398
4399                chk.validateRepeatable(c, repeatable, cbPos);
4400            }
4401        } else {
4402            // Check that all extended classes and interfaces
4403            // are compatible (i.e. no two define methods with same arguments
4404            // yet different return types).  (JLS 8.4.6.3)
4405            chk.checkCompatibleSupertypes(tree.pos(), c.type);
4406            if (allowDefaultMethods) {
4407                chk.checkDefaultMethodClashes(tree.pos(), c.type);
4408            }
4409        }
4410
4411        // Check that class does not import the same parameterized interface
4412        // with two different argument lists.
4413        chk.checkClassBounds(tree.pos(), c.type);
4414
4415        tree.type = c.type;
4416
4417        for (List<JCTypeParameter> l = tree.typarams;
4418             l.nonEmpty(); l = l.tail) {
4419             Assert.checkNonNull(env.info.scope.findFirst(l.head.name));
4420        }
4421
4422        // Check that a generic class doesn't extend Throwable
4423        if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
4424            log.error(tree.extending.pos(), "generic.throwable");
4425
4426        // Check that all methods which implement some
4427        // method conform to the method they implement.
4428        chk.checkImplementations(tree);
4429
4430        //check that a resource implementing AutoCloseable cannot throw InterruptedException
4431        checkAutoCloseable(tree.pos(), env, c.type);
4432
4433        for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
4434            // Attribute declaration
4435            attribStat(l.head, env);
4436            // Check that declarations in inner classes are not static (JLS 8.1.2)
4437            // Make an exception for static constants.
4438            if (c.owner.kind != PCK &&
4439                ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
4440                (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
4441                Symbol sym = null;
4442                if (l.head.hasTag(VARDEF)) sym = ((JCVariableDecl) l.head).sym;
4443                if (sym == null ||
4444                    sym.kind != VAR ||
4445                    ((VarSymbol) sym).getConstValue() == null)
4446                    log.error(l.head.pos(), "icls.cant.have.static.decl", c);
4447            }
4448        }
4449
4450        // Check for cycles among non-initial constructors.
4451        chk.checkCyclicConstructors(tree);
4452
4453        // Check for cycles among annotation elements.
4454        chk.checkNonCyclicElements(tree);
4455
4456        // Check for proper use of serialVersionUID
4457        if (env.info.lint.isEnabled(LintCategory.SERIAL) &&
4458            isSerializable(c.type) &&
4459            (c.flags() & Flags.ENUM) == 0 &&
4460            checkForSerial(c)) {
4461            checkSerialVersionUID(tree, c);
4462        }
4463        if (allowTypeAnnos) {
4464            // Correctly organize the postions of the type annotations
4465            typeAnnotations.organizeTypeAnnotationsBodies(tree);
4466
4467            // Check type annotations applicability rules
4468            validateTypeAnnotations(tree, false);
4469        }
4470    }
4471        // where
4472        boolean checkForSerial(ClassSymbol c) {
4473            if ((c.flags() & ABSTRACT) == 0) {
4474                return true;
4475            } else {
4476                return c.members().anyMatch(anyNonAbstractOrDefaultMethod);
4477            }
4478        }
4479
4480        public static final Filter<Symbol> anyNonAbstractOrDefaultMethod = new Filter<Symbol>() {
4481            @Override
4482            public boolean accepts(Symbol s) {
4483                return s.kind == MTH &&
4484                       (s.flags() & (DEFAULT | ABSTRACT)) != ABSTRACT;
4485            }
4486        };
4487
4488        /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
4489        private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
4490            for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
4491                if (types.isSameType(al.head.annotationType.type, t))
4492                    return al.head.pos();
4493            }
4494
4495            return null;
4496        }
4497
4498        /** check if a type is a subtype of Serializable, if that is available. */
4499        boolean isSerializable(Type t) {
4500            try {
4501                syms.serializableType.complete();
4502            }
4503            catch (CompletionFailure e) {
4504                return false;
4505            }
4506            return types.isSubtype(t, syms.serializableType);
4507        }
4508
4509        /** Check that an appropriate serialVersionUID member is defined. */
4510        private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
4511
4512            // check for presence of serialVersionUID
4513            VarSymbol svuid = null;
4514            for (Symbol sym : c.members().getSymbolsByName(names.serialVersionUID)) {
4515                if (sym.kind == VAR) {
4516                    svuid = (VarSymbol)sym;
4517                    break;
4518                }
4519            }
4520
4521            if (svuid == null) {
4522                log.warning(LintCategory.SERIAL,
4523                        tree.pos(), "missing.SVUID", c);
4524                return;
4525            }
4526
4527            // check that it is static final
4528            if ((svuid.flags() & (STATIC | FINAL)) !=
4529                (STATIC | FINAL))
4530                log.warning(LintCategory.SERIAL,
4531                        TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c);
4532
4533            // check that it is long
4534            else if (!svuid.type.hasTag(LONG))
4535                log.warning(LintCategory.SERIAL,
4536                        TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c);
4537
4538            // check constant
4539            else if (svuid.getConstValue() == null)
4540                log.warning(LintCategory.SERIAL,
4541                        TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c);
4542        }
4543
4544    private Type capture(Type type) {
4545        return types.capture(type);
4546    }
4547
4548    public void validateTypeAnnotations(JCTree tree, boolean sigOnly) {
4549        tree.accept(new TypeAnnotationsValidator(sigOnly));
4550    }
4551    //where
4552    private final class TypeAnnotationsValidator extends TreeScanner {
4553
4554        private final boolean sigOnly;
4555        public TypeAnnotationsValidator(boolean sigOnly) {
4556            this.sigOnly = sigOnly;
4557        }
4558
4559        public void visitAnnotation(JCAnnotation tree) {
4560            chk.validateTypeAnnotation(tree, false);
4561            super.visitAnnotation(tree);
4562        }
4563        public void visitAnnotatedType(JCAnnotatedType tree) {
4564            if (!tree.underlyingType.type.isErroneous()) {
4565                super.visitAnnotatedType(tree);
4566            }
4567        }
4568        public void visitTypeParameter(JCTypeParameter tree) {
4569            chk.validateTypeAnnotations(tree.annotations, true);
4570            scan(tree.bounds);
4571            // Don't call super.
4572            // This is needed because above we call validateTypeAnnotation with
4573            // false, which would forbid annotations on type parameters.
4574            // super.visitTypeParameter(tree);
4575        }
4576        public void visitMethodDef(JCMethodDecl tree) {
4577            if (tree.recvparam != null &&
4578                    !tree.recvparam.vartype.type.isErroneous()) {
4579                checkForDeclarationAnnotations(tree.recvparam.mods.annotations,
4580                        tree.recvparam.vartype.type.tsym);
4581            }
4582            if (tree.restype != null && tree.restype.type != null) {
4583                validateAnnotatedType(tree.restype, tree.restype.type);
4584            }
4585            if (sigOnly) {
4586                scan(tree.mods);
4587                scan(tree.restype);
4588                scan(tree.typarams);
4589                scan(tree.recvparam);
4590                scan(tree.params);
4591                scan(tree.thrown);
4592            } else {
4593                scan(tree.defaultValue);
4594                scan(tree.body);
4595            }
4596        }
4597        public void visitVarDef(final JCVariableDecl tree) {
4598            //System.err.println("validateTypeAnnotations.visitVarDef " + tree);
4599            if (tree.sym != null && tree.sym.type != null)
4600                validateAnnotatedType(tree.vartype, tree.sym.type);
4601            scan(tree.mods);
4602            scan(tree.vartype);
4603            if (!sigOnly) {
4604                scan(tree.init);
4605            }
4606        }
4607        public void visitTypeCast(JCTypeCast tree) {
4608            if (tree.clazz != null && tree.clazz.type != null)
4609                validateAnnotatedType(tree.clazz, tree.clazz.type);
4610            super.visitTypeCast(tree);
4611        }
4612        public void visitTypeTest(JCInstanceOf tree) {
4613            if (tree.clazz != null && tree.clazz.type != null)
4614                validateAnnotatedType(tree.clazz, tree.clazz.type);
4615            super.visitTypeTest(tree);
4616        }
4617        public void visitNewClass(JCNewClass tree) {
4618            if (tree.clazz != null && tree.clazz.type != null) {
4619                if (tree.clazz.hasTag(ANNOTATED_TYPE)) {
4620                    checkForDeclarationAnnotations(((JCAnnotatedType) tree.clazz).annotations,
4621                            tree.clazz.type.tsym);
4622                }
4623                if (tree.def != null) {
4624                    checkForDeclarationAnnotations(tree.def.mods.annotations, tree.clazz.type.tsym);
4625                }
4626
4627                validateAnnotatedType(tree.clazz, tree.clazz.type);
4628            }
4629            super.visitNewClass(tree);
4630        }
4631        public void visitNewArray(JCNewArray tree) {
4632            if (tree.elemtype != null && tree.elemtype.type != null) {
4633                if (tree.elemtype.hasTag(ANNOTATED_TYPE)) {
4634                    checkForDeclarationAnnotations(((JCAnnotatedType) tree.elemtype).annotations,
4635                            tree.elemtype.type.tsym);
4636                }
4637                validateAnnotatedType(tree.elemtype, tree.elemtype.type);
4638            }
4639            super.visitNewArray(tree);
4640        }
4641        public void visitClassDef(JCClassDecl tree) {
4642            //System.err.println("validateTypeAnnotations.visitClassDef " + tree);
4643            if (sigOnly) {
4644                scan(tree.mods);
4645                scan(tree.typarams);
4646                scan(tree.extending);
4647                scan(tree.implementing);
4648            }
4649            for (JCTree member : tree.defs) {
4650                if (member.hasTag(Tag.CLASSDEF)) {
4651                    continue;
4652                }
4653                scan(member);
4654            }
4655        }
4656        public void visitBlock(JCBlock tree) {
4657            if (!sigOnly) {
4658                scan(tree.stats);
4659            }
4660        }
4661
4662        /* I would want to model this after
4663         * com.sun.tools.javac.comp.Check.Validator.visitSelectInternal(JCFieldAccess)
4664         * and override visitSelect and visitTypeApply.
4665         * However, we only set the annotated type in the top-level type
4666         * of the symbol.
4667         * Therefore, we need to override each individual location where a type
4668         * can occur.
4669         */
4670        private void validateAnnotatedType(final JCTree errtree, final Type type) {
4671            //System.err.println("Attr.validateAnnotatedType: " + errtree + " type: " + type);
4672
4673            if (type.isPrimitiveOrVoid()) {
4674                return;
4675            }
4676
4677            JCTree enclTr = errtree;
4678            Type enclTy = type;
4679
4680            boolean repeat = true;
4681            while (repeat) {
4682                if (enclTr.hasTag(TYPEAPPLY)) {
4683                    List<Type> tyargs = enclTy.getTypeArguments();
4684                    List<JCExpression> trargs = ((JCTypeApply)enclTr).getTypeArguments();
4685                    if (trargs.length() > 0) {
4686                        // Nothing to do for diamonds
4687                        if (tyargs.length() == trargs.length()) {
4688                            for (int i = 0; i < tyargs.length(); ++i) {
4689                                validateAnnotatedType(trargs.get(i), tyargs.get(i));
4690                            }
4691                        }
4692                        // If the lengths don't match, it's either a diamond
4693                        // or some nested type that redundantly provides
4694                        // type arguments in the tree.
4695                    }
4696
4697                    // Look at the clazz part of a generic type
4698                    enclTr = ((JCTree.JCTypeApply)enclTr).clazz;
4699                }
4700
4701                if (enclTr.hasTag(SELECT)) {
4702                    enclTr = ((JCTree.JCFieldAccess)enclTr).getExpression();
4703                    if (enclTy != null &&
4704                            !enclTy.hasTag(NONE)) {
4705                        enclTy = enclTy.getEnclosingType();
4706                    }
4707                } else if (enclTr.hasTag(ANNOTATED_TYPE)) {
4708                    JCAnnotatedType at = (JCTree.JCAnnotatedType) enclTr;
4709                    if (enclTy == null || enclTy.hasTag(NONE)) {
4710                        if (at.getAnnotations().size() == 1) {
4711                            log.error(at.underlyingType.pos(), "cant.type.annotate.scoping.1", at.getAnnotations().head.attribute);
4712                        } else {
4713                            ListBuffer<Attribute.Compound> comps = new ListBuffer<>();
4714                            for (JCAnnotation an : at.getAnnotations()) {
4715                                comps.add(an.attribute);
4716                            }
4717                            log.error(at.underlyingType.pos(), "cant.type.annotate.scoping", comps.toList());
4718                        }
4719                        repeat = false;
4720                    }
4721                    enclTr = at.underlyingType;
4722                    // enclTy doesn't need to be changed
4723                } else if (enclTr.hasTag(IDENT)) {
4724                    repeat = false;
4725                } else if (enclTr.hasTag(JCTree.Tag.WILDCARD)) {
4726                    JCWildcard wc = (JCWildcard) enclTr;
4727                    if (wc.getKind() == JCTree.Kind.EXTENDS_WILDCARD) {
4728                        validateAnnotatedType(wc.getBound(), ((WildcardType)enclTy).getExtendsBound());
4729                    } else if (wc.getKind() == JCTree.Kind.SUPER_WILDCARD) {
4730                        validateAnnotatedType(wc.getBound(), ((WildcardType)enclTy).getSuperBound());
4731                    } else {
4732                        // Nothing to do for UNBOUND
4733                    }
4734                    repeat = false;
4735                } else if (enclTr.hasTag(TYPEARRAY)) {
4736                    JCArrayTypeTree art = (JCArrayTypeTree) enclTr;
4737                    validateAnnotatedType(art.getType(), ((ArrayType)enclTy).getComponentType());
4738                    repeat = false;
4739                } else if (enclTr.hasTag(TYPEUNION)) {
4740                    JCTypeUnion ut = (JCTypeUnion) enclTr;
4741                    for (JCTree t : ut.getTypeAlternatives()) {
4742                        validateAnnotatedType(t, t.type);
4743                    }
4744                    repeat = false;
4745                } else if (enclTr.hasTag(TYPEINTERSECTION)) {
4746                    JCTypeIntersection it = (JCTypeIntersection) enclTr;
4747                    for (JCTree t : it.getBounds()) {
4748                        validateAnnotatedType(t, t.type);
4749                    }
4750                    repeat = false;
4751                } else if (enclTr.getKind() == JCTree.Kind.PRIMITIVE_TYPE ||
4752                           enclTr.getKind() == JCTree.Kind.ERRONEOUS) {
4753                    repeat = false;
4754                } else {
4755                    Assert.error("Unexpected tree: " + enclTr + " with kind: " + enclTr.getKind() +
4756                            " within: "+ errtree + " with kind: " + errtree.getKind());
4757                }
4758            }
4759        }
4760
4761        private void checkForDeclarationAnnotations(List<? extends JCAnnotation> annotations,
4762                Symbol sym) {
4763            // Ensure that no declaration annotations are present.
4764            // Note that a tree type might be an AnnotatedType with
4765            // empty annotations, if only declaration annotations were given.
4766            // This method will raise an error for such a type.
4767            for (JCAnnotation ai : annotations) {
4768                if (!ai.type.isErroneous() &&
4769                        typeAnnotations.annotationTargetType(ai.attribute, sym) == TypeAnnotations.AnnotationType.DECLARATION) {
4770                    log.error(ai.pos(), Errors.AnnotationTypeNotApplicableToType(ai.type));
4771                }
4772            }
4773        }
4774    }
4775
4776    // <editor-fold desc="post-attribution visitor">
4777
4778    /**
4779     * Handle missing types/symbols in an AST. This routine is useful when
4780     * the compiler has encountered some errors (which might have ended up
4781     * terminating attribution abruptly); if the compiler is used in fail-over
4782     * mode (e.g. by an IDE) and the AST contains semantic errors, this routine
4783     * prevents NPE to be progagated during subsequent compilation steps.
4784     */
4785    public void postAttr(JCTree tree) {
4786        new PostAttrAnalyzer().scan(tree);
4787    }
4788
4789    class PostAttrAnalyzer extends TreeScanner {
4790
4791        private void initTypeIfNeeded(JCTree that) {
4792            if (that.type == null) {
4793                if (that.hasTag(METHODDEF)) {
4794                    that.type = dummyMethodType((JCMethodDecl)that);
4795                } else {
4796                    that.type = syms.unknownType;
4797                }
4798            }
4799        }
4800
4801        /* Construct a dummy method type. If we have a method declaration,
4802         * and the declared return type is void, then use that return type
4803         * instead of UNKNOWN to avoid spurious error messages in lambda
4804         * bodies (see:JDK-8041704).
4805         */
4806        private Type dummyMethodType(JCMethodDecl md) {
4807            Type restype = syms.unknownType;
4808            if (md != null && md.restype.hasTag(TYPEIDENT)) {
4809                JCPrimitiveTypeTree prim = (JCPrimitiveTypeTree)md.restype;
4810                if (prim.typetag == VOID)
4811                    restype = syms.voidType;
4812            }
4813            return new MethodType(List.<Type>nil(), restype,
4814                                  List.<Type>nil(), syms.methodClass);
4815        }
4816        private Type dummyMethodType() {
4817            return dummyMethodType(null);
4818        }
4819
4820        @Override
4821        public void scan(JCTree tree) {
4822            if (tree == null) return;
4823            if (tree instanceof JCExpression) {
4824                initTypeIfNeeded(tree);
4825            }
4826            super.scan(tree);
4827        }
4828
4829        @Override
4830        public void visitIdent(JCIdent that) {
4831            if (that.sym == null) {
4832                that.sym = syms.unknownSymbol;
4833            }
4834        }
4835
4836        @Override
4837        public void visitSelect(JCFieldAccess that) {
4838            if (that.sym == null) {
4839                that.sym = syms.unknownSymbol;
4840            }
4841            super.visitSelect(that);
4842        }
4843
4844        @Override
4845        public void visitClassDef(JCClassDecl that) {
4846            initTypeIfNeeded(that);
4847            if (that.sym == null) {
4848                that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol);
4849            }
4850            super.visitClassDef(that);
4851        }
4852
4853        @Override
4854        public void visitMethodDef(JCMethodDecl that) {
4855            initTypeIfNeeded(that);
4856            if (that.sym == null) {
4857                that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol);
4858            }
4859            super.visitMethodDef(that);
4860        }
4861
4862        @Override
4863        public void visitVarDef(JCVariableDecl that) {
4864            initTypeIfNeeded(that);
4865            if (that.sym == null) {
4866                that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol);
4867                that.sym.adr = 0;
4868            }
4869            super.visitVarDef(that);
4870        }
4871
4872        @Override
4873        public void visitNewClass(JCNewClass that) {
4874            if (that.constructor == null) {
4875                that.constructor = new MethodSymbol(0, names.init,
4876                        dummyMethodType(), syms.noSymbol);
4877            }
4878            if (that.constructorType == null) {
4879                that.constructorType = syms.unknownType;
4880            }
4881            super.visitNewClass(that);
4882        }
4883
4884        @Override
4885        public void visitAssignop(JCAssignOp that) {
4886            if (that.operator == null) {
4887                that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
4888                        -1, syms.noSymbol);
4889            }
4890            super.visitAssignop(that);
4891        }
4892
4893        @Override
4894        public void visitBinary(JCBinary that) {
4895            if (that.operator == null) {
4896                that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
4897                        -1, syms.noSymbol);
4898            }
4899            super.visitBinary(that);
4900        }
4901
4902        @Override
4903        public void visitUnary(JCUnary that) {
4904            if (that.operator == null) {
4905                that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
4906                        -1, syms.noSymbol);
4907            }
4908            super.visitUnary(that);
4909        }
4910
4911        @Override
4912        public void visitLambda(JCLambda that) {
4913            super.visitLambda(that);
4914            if (that.targets == null) {
4915                that.targets = List.nil();
4916            }
4917        }
4918
4919        @Override
4920        public void visitReference(JCMemberReference that) {
4921            super.visitReference(that);
4922            if (that.sym == null) {
4923                that.sym = new MethodSymbol(0, names.empty, dummyMethodType(),
4924                        syms.noSymbol);
4925            }
4926            if (that.targets == null) {
4927                that.targets = List.nil();
4928            }
4929        }
4930    }
4931    // </editor-fold>
4932}
4933