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