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