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