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