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