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