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