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