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