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