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