Attr.java revision 2778:6a927a9114c1
1/*
2 * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26package com.sun.tools.javac.comp;
27
28import java.util.*;
29
30import javax.lang.model.element.ElementKind;
31import javax.tools.JavaFileObject;
32
33import com.sun.source.tree.IdentifierTree;
34import com.sun.source.tree.MemberReferenceTree.ReferenceMode;
35import com.sun.source.tree.MemberSelectTree;
36import com.sun.source.tree.TreeVisitor;
37import com.sun.source.util.SimpleTreeVisitor;
38import com.sun.tools.javac.code.*;
39import com.sun.tools.javac.code.Lint.LintCategory;
40import com.sun.tools.javac.code.Scope.WriteableScope;
41import com.sun.tools.javac.code.Symbol.*;
42import com.sun.tools.javac.code.Type.*;
43import com.sun.tools.javac.comp.Check.CheckContext;
44import com.sun.tools.javac.comp.DeferredAttr.AttrMode;
45import com.sun.tools.javac.comp.Infer.InferenceContext;
46import com.sun.tools.javac.comp.Infer.FreeTypeListener;
47import com.sun.tools.javac.jvm.*;
48import com.sun.tools.javac.tree.*;
49import com.sun.tools.javac.tree.JCTree.*;
50import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*;
51import com.sun.tools.javac.util.*;
52import com.sun.tools.javac.util.DefinedBy.Api;
53import com.sun.tools.javac.util.Dependencies.AttributionKind;
54import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
55import com.sun.tools.javac.util.List;
56import static com.sun.tools.javac.code.Flags.*;
57import static com.sun.tools.javac.code.Flags.ANNOTATION;
58import static com.sun.tools.javac.code.Flags.BLOCK;
59import static com.sun.tools.javac.code.Kinds.*;
60import static com.sun.tools.javac.code.Kinds.Kind.*;
61import static com.sun.tools.javac.code.TypeTag.*;
62import static com.sun.tools.javac.code.TypeTag.WILDCARD;
63import static com.sun.tools.javac.tree.JCTree.Tag.*;
64
65/** This is the main context-dependent analysis phase in GJC. It
66 *  encompasses name resolution, type checking and constant folding as
67 *  subtasks. Some subtasks involve auxiliary classes.
68 *  @see Check
69 *  @see Resolve
70 *  @see ConstFold
71 *  @see Infer
72 *
73 *  <p><b>This is NOT part of any supported API.
74 *  If you write code that depends on this, you do so at your own risk.
75 *  This code and its internal interfaces are subject to change or
76 *  deletion without notice.</b>
77 */
78public class Attr extends JCTree.Visitor {
79    protected static final Context.Key<Attr> attrKey = new Context.Key<>();
80
81    final Names names;
82    final Log log;
83    final Symtab syms;
84    final Resolve rs;
85    final Infer infer;
86    final Analyzer analyzer;
87    final DeferredAttr deferredAttr;
88    final Check chk;
89    final Flow flow;
90    final MemberEnter memberEnter;
91    final TypeEnter typeEnter;
92    final TreeMaker make;
93    final ConstFold cfolder;
94    final Enter enter;
95    final Target target;
96    final Types types;
97    final JCDiagnostic.Factory diags;
98    final Annotate annotate;
99    final TypeAnnotations typeAnnotations;
100    final DeferredLintHandler deferredLintHandler;
101    final TypeEnvs typeEnvs;
102    final Dependencies dependencies;
103
104    public static Attr instance(Context context) {
105        Attr instance = context.get(attrKey);
106        if (instance == null)
107            instance = new Attr(context);
108        return instance;
109    }
110
111    protected Attr(Context context) {
112        context.put(attrKey, this);
113
114        names = Names.instance(context);
115        log = Log.instance(context);
116        syms = Symtab.instance(context);
117        rs = Resolve.instance(context);
118        chk = Check.instance(context);
119        flow = Flow.instance(context);
120        memberEnter = MemberEnter.instance(context);
121        typeEnter = TypeEnter.instance(context);
122        make = TreeMaker.instance(context);
123        enter = Enter.instance(context);
124        infer = Infer.instance(context);
125        analyzer = Analyzer.instance(context);
126        deferredAttr = DeferredAttr.instance(context);
127        cfolder = ConstFold.instance(context);
128        target = Target.instance(context);
129        types = Types.instance(context);
130        diags = JCDiagnostic.Factory.instance(context);
131        annotate = Annotate.instance(context);
132        typeAnnotations = TypeAnnotations.instance(context);
133        deferredLintHandler = DeferredLintHandler.instance(context);
134        typeEnvs = TypeEnvs.instance(context);
135        dependencies = Dependencies.instance(context);
136
137        Options options = Options.instance(context);
138
139        Source source = Source.instance(context);
140        allowStringsInSwitch = source.allowStringsInSwitch();
141        allowPoly = source.allowPoly();
142        allowTypeAnnos = source.allowTypeAnnotations();
143        allowLambda = source.allowLambda();
144        allowDefaultMethods = source.allowDefaultMethods();
145        allowStaticInterfaceMethods = source.allowStaticInterfaceMethods();
146        sourceName = source.name;
147        relax = (options.isSet("-retrofit") ||
148                options.isSet("-relax"));
149        useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
150
151        statInfo = new ResultInfo(KindSelector.NIL, Type.noType);
152        varAssignmentInfo = new ResultInfo(KindSelector.ASG, Type.noType);
153        unknownExprInfo = new ResultInfo(KindSelector.VAL, Type.noType);
154        unknownAnyPolyInfo = new ResultInfo(KindSelector.VAL, Infer.anyPoly);
155        unknownTypeInfo = new ResultInfo(KindSelector.TYP, Type.noType);
156        unknownTypeExprInfo = new ResultInfo(KindSelector.VAL_TYP, Type.noType);
157        recoveryInfo = new RecoveryInfo(deferredAttr.emptyDeferredAttrContext);
158
159        noCheckTree = make.at(-1).Skip();
160    }
161
162    /** Switch: relax some constraints for retrofit mode.
163     */
164    boolean relax;
165
166    /** Switch: support target-typing inference
167     */
168    boolean allowPoly;
169
170    /** Switch: support type annotations.
171     */
172    boolean allowTypeAnnos;
173
174    /** Switch: support lambda expressions ?
175     */
176    boolean allowLambda;
177
178    /** Switch: support default methods ?
179     */
180    boolean allowDefaultMethods;
181
182    /** Switch: static interface methods enabled?
183     */
184    boolean allowStaticInterfaceMethods;
185
186    /**
187     * Switch: warn about use of variable before declaration?
188     * RFE: 6425594
189     */
190    boolean useBeforeDeclarationWarning;
191
192    /**
193     * Switch: allow strings in switch?
194     */
195    boolean allowStringsInSwitch;
196
197    /**
198     * Switch: name of source level; used for error reporting.
199     */
200    String sourceName;
201
202    /** Check kind and type of given tree against protokind and prototype.
203     *  If check succeeds, store type in tree and return it.
204     *  If check fails, store errType in tree and return it.
205     *  No checks are performed if the prototype is a method type.
206     *  It is not necessary in this case since we know that kind and type
207     *  are correct.
208     *
209     *  @param tree     The tree whose kind and type is checked
210     *  @param found    The computed type of the tree
211     *  @param ownkind  The computed kind of the tree
212     *  @param resultInfo  The expected result of the tree
213     */
214    Type check(final JCTree tree,
215               final Type found,
216               final KindSelector ownkind,
217               final ResultInfo resultInfo) {
218        InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
219        Type owntype;
220        boolean shouldCheck = !found.hasTag(ERROR) &&
221                !resultInfo.pt.hasTag(METHOD) &&
222                !resultInfo.pt.hasTag(FORALL);
223        if (shouldCheck && !ownkind.subset(resultInfo.pkind)) {
224            log.error(tree.pos(), "unexpected.type",
225            resultInfo.pkind.kindNames(),
226            ownkind.kindNames());
227            owntype = types.createErrorType(found);
228        } else if (allowPoly && inferenceContext.free(found)) {
229            //delay the check if there are inference variables in the found type
230            //this means we are dealing with a partially inferred poly expression
231            owntype = shouldCheck ? resultInfo.pt : found;
232            inferenceContext.addFreeTypeListener(List.of(found, resultInfo.pt),
233                    instantiatedContext -> {
234                        ResultInfo pendingResult =
235                                resultInfo.dup(inferenceContext.asInstType(resultInfo.pt));
236                        check(tree, inferenceContext.asInstType(found), ownkind, pendingResult);
237                    });
238        } else {
239            owntype = shouldCheck ?
240            resultInfo.check(tree, found) :
241            found;
242        }
243        if (tree != noCheckTree) {
244            tree.type = owntype;
245        }
246        return owntype;
247    }
248
249    /** Is given blank final variable assignable, i.e. in a scope where it
250     *  may be assigned to even though it is final?
251     *  @param v      The blank final variable.
252     *  @param env    The current environment.
253     */
254    boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
255        Symbol owner = env.info.scope.owner;
256           // owner refers to the innermost variable, method or
257           // initializer block declaration at this point.
258        return
259            v.owner == owner
260            ||
261            ((owner.name == names.init ||    // i.e. we are in a constructor
262              owner.kind == VAR ||           // i.e. we are in a variable initializer
263              (owner.flags() & BLOCK) != 0)  // i.e. we are in an initializer block
264             &&
265             v.owner == owner.owner
266             &&
267             ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
268    }
269
270    /** Check that variable can be assigned to.
271     *  @param pos    The current source code position.
272     *  @param v      The assigned varaible
273     *  @param base   If the variable is referred to in a Select, the part
274     *                to the left of the `.', null otherwise.
275     *  @param env    The current environment.
276     */
277    void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
278        if ((v.flags() & FINAL) != 0 &&
279            ((v.flags() & HASINIT) != 0
280             ||
281             !((base == null ||
282               (base.hasTag(IDENT) && TreeInfo.name(base) == names._this)) &&
283               isAssignableAsBlankFinal(v, env)))) {
284            if (v.isResourceVariable()) { //TWR resource
285                log.error(pos, "try.resource.may.not.be.assigned", v);
286            } else {
287                log.error(pos, "cant.assign.val.to.final.var", v);
288            }
289        }
290    }
291
292    /** Does tree represent a static reference to an identifier?
293     *  It is assumed that tree is either a SELECT or an IDENT.
294     *  We have to weed out selects from non-type names here.
295     *  @param tree    The candidate tree.
296     */
297    boolean isStaticReference(JCTree tree) {
298        if (tree.hasTag(SELECT)) {
299            Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
300            if (lsym == null || lsym.kind != TYP) {
301                return false;
302            }
303        }
304        return true;
305    }
306
307    /** Is this symbol a type?
308     */
309    static boolean isType(Symbol sym) {
310        return sym != null && sym.kind == TYP;
311    }
312
313    /** The current `this' symbol.
314     *  @param env    The current environment.
315     */
316    Symbol thisSym(DiagnosticPosition pos, Env<AttrContext> env) {
317        return rs.resolveSelf(pos, env, env.enclClass.sym, names._this);
318    }
319
320    /** Attribute a parsed identifier.
321     * @param tree Parsed identifier name
322     * @param topLevel The toplevel to use
323     */
324    public Symbol attribIdent(JCTree tree, JCCompilationUnit topLevel) {
325        Env<AttrContext> localEnv = enter.topLevelEnv(topLevel);
326        localEnv.enclClass = make.ClassDef(make.Modifiers(0),
327                                           syms.errSymbol.name,
328                                           null, null, null, null);
329        localEnv.enclClass.sym = syms.errSymbol;
330        return tree.accept(identAttributer, localEnv);
331    }
332    // where
333        private TreeVisitor<Symbol,Env<AttrContext>> identAttributer = new IdentAttributer();
334        private class IdentAttributer extends SimpleTreeVisitor<Symbol,Env<AttrContext>> {
335            @Override @DefinedBy(Api.COMPILER_TREE)
336            public Symbol visitMemberSelect(MemberSelectTree node, Env<AttrContext> env) {
337                Symbol site = visit(node.getExpression(), env);
338                if (site.kind == ERR || site.kind == ABSENT_TYP)
339                    return site;
340                Name name = (Name)node.getIdentifier();
341                if (site.kind == PCK) {
342                    env.toplevel.packge = (PackageSymbol)site;
343                    return rs.findIdentInPackage(env, (TypeSymbol)site, name,
344                            KindSelector.TYP_PCK);
345                } else {
346                    env.enclClass.sym = (ClassSymbol)site;
347                    return rs.findMemberType(env, site.asType(), name, (TypeSymbol)site);
348                }
349            }
350
351            @Override @DefinedBy(Api.COMPILER_TREE)
352            public Symbol visitIdentifier(IdentifierTree node, Env<AttrContext> env) {
353                return rs.findIdent(env, (Name)node.getName(), KindSelector.TYP_PCK);
354            }
355        }
356
357    public Type coerce(Type etype, Type ttype) {
358        return cfolder.coerce(etype, ttype);
359    }
360
361    public Type attribType(JCTree node, TypeSymbol sym) {
362        Env<AttrContext> env = typeEnvs.get(sym);
363        Env<AttrContext> localEnv = env.dup(node, env.info.dup());
364        return attribTree(node, localEnv, unknownTypeInfo);
365    }
366
367    public Type attribImportQualifier(JCImport tree, Env<AttrContext> env) {
368        // Attribute qualifying package or class.
369        JCFieldAccess s = (JCFieldAccess)tree.qualid;
370        return attribTree(s.selected, env,
371                          new ResultInfo(tree.staticImport ?
372                                         KindSelector.TYP : KindSelector.TYP_PCK,
373                       Type.noType));
374    }
375
376    public Env<AttrContext> attribExprToTree(JCTree expr, Env<AttrContext> env, JCTree tree) {
377        breakTree = tree;
378        JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
379        try {
380            attribExpr(expr, env);
381        } catch (BreakAttr b) {
382            return b.env;
383        } catch (AssertionError ae) {
384            if (ae.getCause() instanceof BreakAttr) {
385                return ((BreakAttr)(ae.getCause())).env;
386            } else {
387                throw ae;
388            }
389        } finally {
390            breakTree = null;
391            log.useSource(prev);
392        }
393        return env;
394    }
395
396    public Env<AttrContext> attribStatToTree(JCTree stmt, Env<AttrContext> env, JCTree tree) {
397        breakTree = tree;
398        JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
399        try {
400            attribStat(stmt, env);
401        } catch (BreakAttr b) {
402            return b.env;
403        } catch (AssertionError ae) {
404            if (ae.getCause() instanceof BreakAttr) {
405                return ((BreakAttr)(ae.getCause())).env;
406            } else {
407                throw ae;
408            }
409        } finally {
410            breakTree = null;
411            log.useSource(prev);
412        }
413        return env;
414    }
415
416    private JCTree breakTree = null;
417
418    private static class BreakAttr extends RuntimeException {
419        static final long serialVersionUID = -6924771130405446405L;
420        private Env<AttrContext> env;
421        private BreakAttr(Env<AttrContext> env) {
422            this.env = env;
423        }
424    }
425
426    class ResultInfo {
427        final KindSelector pkind;
428        final Type pt;
429        final CheckContext checkContext;
430
431        ResultInfo(KindSelector pkind, Type pt) {
432            this(pkind, pt, chk.basicHandler);
433        }
434
435        protected ResultInfo(KindSelector pkind,
436                             Type pt, CheckContext checkContext) {
437            this.pkind = pkind;
438            this.pt = pt;
439            this.checkContext = checkContext;
440        }
441
442        protected Type check(final DiagnosticPosition pos, final Type found) {
443            return chk.checkType(pos, found, pt, checkContext);
444        }
445
446        protected ResultInfo dup(Type newPt) {
447            return new ResultInfo(pkind, newPt, checkContext);
448        }
449
450        protected ResultInfo dup(CheckContext newContext) {
451            return new ResultInfo(pkind, pt, newContext);
452        }
453
454        protected ResultInfo dup(Type newPt, CheckContext newContext) {
455            return new ResultInfo(pkind, newPt, newContext);
456        }
457
458        @Override
459        public String toString() {
460            if (pt != null) {
461                return pt.toString();
462            } else {
463                return "";
464            }
465        }
466    }
467
468    class RecoveryInfo extends ResultInfo {
469
470        public RecoveryInfo(final DeferredAttr.DeferredAttrContext deferredAttrContext) {
471            super(KindSelector.VAL, Type.recoveryType,
472                  new Check.NestedCheckContext(chk.basicHandler) {
473                @Override
474                public DeferredAttr.DeferredAttrContext deferredAttrContext() {
475                    return deferredAttrContext;
476                }
477                @Override
478                public boolean compatible(Type found, Type req, Warner warn) {
479                    return true;
480                }
481                @Override
482                public void report(DiagnosticPosition pos, JCDiagnostic details) {
483                    chk.basicHandler.report(pos, details);
484                }
485            });
486        }
487    }
488
489    final ResultInfo statInfo;
490    final ResultInfo varAssignmentInfo;
491    final ResultInfo unknownAnyPolyInfo;
492    final ResultInfo unknownExprInfo;
493    final ResultInfo unknownTypeInfo;
494    final ResultInfo unknownTypeExprInfo;
495    final ResultInfo recoveryInfo;
496
497    Type pt() {
498        return resultInfo.pt;
499    }
500
501    KindSelector pkind() {
502        return resultInfo.pkind;
503    }
504
505/* ************************************************************************
506 * Visitor methods
507 *************************************************************************/
508
509    /** Visitor argument: the current environment.
510     */
511    Env<AttrContext> env;
512
513    /** Visitor argument: the currently expected attribution result.
514     */
515    ResultInfo resultInfo;
516
517    /** Visitor result: the computed type.
518     */
519    Type result;
520
521    /** Synthetic tree to be used during 'fake' checks.
522     */
523    JCTree noCheckTree;
524
525    /** Visitor method: attribute a tree, catching any completion failure
526     *  exceptions. Return the tree's type.
527     *
528     *  @param tree    The tree to be visited.
529     *  @param env     The environment visitor argument.
530     *  @param resultInfo   The result info visitor argument.
531     */
532    Type attribTree(JCTree tree, Env<AttrContext> env, ResultInfo resultInfo) {
533        Env<AttrContext> prevEnv = this.env;
534        ResultInfo prevResult = this.resultInfo;
535        try {
536            this.env = env;
537            this.resultInfo = resultInfo;
538            tree.accept(this);
539            if (tree == breakTree &&
540                    resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
541                throw new BreakAttr(copyEnv(env));
542            }
543            return result;
544        } catch (CompletionFailure ex) {
545            tree.type = syms.errType;
546            return chk.completionError(tree.pos(), ex);
547        } finally {
548            this.env = prevEnv;
549            this.resultInfo = prevResult;
550        }
551    }
552
553    Env<AttrContext> copyEnv(Env<AttrContext> env) {
554        Env<AttrContext> newEnv =
555                env.dup(env.tree, env.info.dup(copyScope(env.info.scope)));
556        if (newEnv.outer != null) {
557            newEnv.outer = copyEnv(newEnv.outer);
558        }
559        return newEnv;
560    }
561
562    WriteableScope copyScope(WriteableScope sc) {
563        WriteableScope newScope = WriteableScope.create(sc.owner);
564        List<Symbol> elemsList = List.nil();
565        for (Symbol sym : sc.getSymbols()) {
566            elemsList = elemsList.prepend(sym);
567        }
568        for (Symbol s : elemsList) {
569            newScope.enter(s);
570        }
571        return newScope;
572    }
573
574    /** Derived visitor method: attribute an expression tree.
575     */
576    public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) {
577        return attribTree(tree, env, new ResultInfo(KindSelector.VAL, !pt.hasTag(ERROR) ? pt : Type.noType));
578    }
579
580    /** Derived visitor method: attribute an expression tree with
581     *  no constraints on the computed type.
582     */
583    public Type attribExpr(JCTree tree, Env<AttrContext> env) {
584        return attribTree(tree, env, unknownExprInfo);
585    }
586
587    /** Derived visitor method: attribute a type tree.
588     */
589    public Type attribType(JCTree tree, Env<AttrContext> env) {
590        Type result = attribType(tree, env, Type.noType);
591        return result;
592    }
593
594    /** Derived visitor method: attribute a type tree.
595     */
596    Type attribType(JCTree tree, Env<AttrContext> env, Type pt) {
597        Type result = attribTree(tree, env, new ResultInfo(KindSelector.TYP, pt));
598        return result;
599    }
600
601    /** Derived visitor method: attribute a statement or definition tree.
602     */
603    public Type attribStat(JCTree tree, Env<AttrContext> env) {
604        Env<AttrContext> analyzeEnv =
605                env.dup(tree, env.info.dup(env.info.scope.dupUnshared(env.info.scope.owner)));
606        try {
607            return attribTree(tree, env, statInfo);
608        } finally {
609            analyzer.analyzeIfNeeded(tree, analyzeEnv);
610        }
611    }
612
613    /** Attribute a list of expressions, returning a list of types.
614     */
615    List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) {
616        ListBuffer<Type> ts = new ListBuffer<>();
617        for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
618            ts.append(attribExpr(l.head, env, pt));
619        return ts.toList();
620    }
621
622    /** Attribute a list of statements, returning nothing.
623     */
624    <T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) {
625        for (List<T> l = trees; l.nonEmpty(); l = l.tail)
626            attribStat(l.head, env);
627    }
628
629    /** Attribute the arguments in a method call, returning the method kind.
630     */
631    KindSelector attribArgs(KindSelector initialKind, List<JCExpression> trees, Env<AttrContext> env, ListBuffer<Type> argtypes) {
632        KindSelector kind = initialKind;
633        for (JCExpression arg : trees) {
634            Type argtype;
635            if (allowPoly && deferredAttr.isDeferred(env, arg)) {
636                argtype = deferredAttr.new DeferredType(arg, env);
637                kind = KindSelector.of(KindSelector.POLY, kind);
638            } else {
639                argtype = chk.checkNonVoid(arg, attribTree(arg, env, unknownAnyPolyInfo));
640            }
641            argtypes.append(argtype);
642        }
643        return kind;
644    }
645
646    /** Attribute a type argument list, returning a list of types.
647     *  Caller is responsible for calling checkRefTypes.
648     */
649    List<Type> attribAnyTypes(List<JCExpression> trees, Env<AttrContext> env) {
650        ListBuffer<Type> argtypes = new ListBuffer<>();
651        for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
652            argtypes.append(attribType(l.head, env));
653        return argtypes.toList();
654    }
655
656    /** Attribute a type argument list, returning a list of types.
657     *  Check that all the types are references.
658     */
659    List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
660        List<Type> types = attribAnyTypes(trees, env);
661        return chk.checkRefTypes(trees, types);
662    }
663
664    /**
665     * Attribute type variables (of generic classes or methods).
666     * Compound types are attributed later in attribBounds.
667     * @param typarams the type variables to enter
668     * @param env      the current environment
669     */
670    void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env) {
671        for (JCTypeParameter tvar : typarams) {
672            dependencies.push(AttributionKind.TVAR, tvar);
673            TypeVar a = (TypeVar)tvar.type;
674            a.tsym.flags_field |= UNATTRIBUTED;
675            a.bound = Type.noType;
676            if (!tvar.bounds.isEmpty()) {
677                List<Type> bounds = List.of(attribType(tvar.bounds.head, env));
678                for (JCExpression bound : tvar.bounds.tail)
679                    bounds = bounds.prepend(attribType(bound, env));
680                types.setBounds(a, bounds.reverse());
681            } else {
682                // if no bounds are given, assume a single bound of
683                // java.lang.Object.
684                types.setBounds(a, List.of(syms.objectType));
685            }
686            a.tsym.flags_field &= ~UNATTRIBUTED;
687            dependencies.pop();
688        }
689        for (JCTypeParameter tvar : typarams) {
690            chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
691        }
692    }
693
694    /**
695     * Attribute the type references in a list of annotations.
696     */
697    void attribAnnotationTypes(List<JCAnnotation> annotations,
698                               Env<AttrContext> env) {
699        for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
700            JCAnnotation a = al.head;
701            attribType(a.annotationType, env);
702        }
703    }
704
705    /**
706     * Attribute a "lazy constant value".
707     *  @param env         The env for the const value
708     *  @param initializer The initializer for the const value
709     *  @param type        The expected type, or null
710     *  @see VarSymbol#setLazyConstValue
711     */
712    public Object attribLazyConstantValue(Env<AttrContext> env,
713                                      JCVariableDecl variable,
714                                      Type type) {
715
716        DiagnosticPosition prevLintPos
717                = deferredLintHandler.setPos(variable.pos());
718
719        try {
720            Type itype = attribExpr(variable.init, env, type);
721            if (itype.constValue() != null) {
722                return coerce(itype, type).constValue();
723            } else {
724                return null;
725            }
726        } finally {
727            deferredLintHandler.setPos(prevLintPos);
728        }
729    }
730
731    /** Attribute type reference in an `extends' or `implements' clause.
732     *  Supertypes of anonymous inner classes are usually already attributed.
733     *
734     *  @param tree              The tree making up the type reference.
735     *  @param env               The environment current at the reference.
736     *  @param classExpected     true if only a class is expected here.
737     *  @param interfaceExpected true if only an interface is expected here.
738     */
739    Type attribBase(JCTree tree,
740                    Env<AttrContext> env,
741                    boolean classExpected,
742                    boolean interfaceExpected,
743                    boolean checkExtensible) {
744        Type t = tree.type != null ?
745            tree.type :
746            attribType(tree, env);
747        return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible);
748    }
749    Type checkBase(Type t,
750                   JCTree tree,
751                   Env<AttrContext> env,
752                   boolean classExpected,
753                   boolean interfaceExpected,
754                   boolean checkExtensible) {
755        if (t.tsym.isAnonymous()) {
756            log.error(tree.pos(), "cant.inherit.from.anon");
757            return types.createErrorType(t);
758        }
759        if (t.isErroneous())
760            return t;
761        if (t.hasTag(TYPEVAR) && !classExpected && !interfaceExpected) {
762            // check that type variable is already visible
763            if (t.getUpperBound() == null) {
764                log.error(tree.pos(), "illegal.forward.ref");
765                return types.createErrorType(t);
766            }
767        } else {
768            t = chk.checkClassType(tree.pos(), t, checkExtensible);
769        }
770        if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) {
771            log.error(tree.pos(), "intf.expected.here");
772            // return errType is necessary since otherwise there might
773            // be undetected cycles which cause attribution to loop
774            return types.createErrorType(t);
775        } else if (checkExtensible &&
776                   classExpected &&
777                   (t.tsym.flags() & INTERFACE) != 0) {
778            log.error(tree.pos(), "no.intf.expected.here");
779            return types.createErrorType(t);
780        }
781        if (checkExtensible &&
782            ((t.tsym.flags() & FINAL) != 0)) {
783            log.error(tree.pos(),
784                      "cant.inherit.from.final", t.tsym);
785        }
786        chk.checkNonCyclic(tree.pos(), t);
787        return t;
788    }
789
790    Type attribIdentAsEnumType(Env<AttrContext> env, JCIdent id) {
791        Assert.check((env.enclClass.sym.flags() & ENUM) != 0);
792        id.type = env.info.scope.owner.enclClass().type;
793        id.sym = env.info.scope.owner.enclClass();
794        return id.type;
795    }
796
797    public void visitClassDef(JCClassDecl tree) {
798        // Local and anonymous classes have not been entered yet, so we need to
799        // do it now.
800        if (env.info.scope.owner.kind.matches(KindSelector.VAL_MTH)) {
801            enter.classEnter(tree, env);
802        } else {
803            // If this class declaration is part of a class level annotation,
804            // as in @MyAnno(new Object() {}) class MyClass {}, enter it in
805            // order to simplify later steps and allow for sensible error
806            // messages.
807            if (env.tree.hasTag(NEWCLASS) && TreeInfo.isInAnnotation(env, tree))
808                enter.classEnter(tree, env);
809        }
810
811        ClassSymbol c = tree.sym;
812        if (c == null) {
813            // exit in case something drastic went wrong during enter.
814            result = null;
815        } else {
816            // make sure class has been completed:
817            c.complete();
818
819            // If this class appears as an anonymous class
820            // in a superclass constructor call where
821            // no explicit outer instance is given,
822            // disable implicit outer instance from being passed.
823            // (This would be an illegal access to "this before super").
824            if (env.info.isSelfCall &&
825                env.tree.hasTag(NEWCLASS) &&
826                ((JCNewClass) env.tree).encl == null)
827            {
828                c.flags_field |= NOOUTERTHIS;
829            }
830            attribClass(tree.pos(), c);
831            result = tree.type = c.type;
832        }
833    }
834
835    public void visitMethodDef(JCMethodDecl tree) {
836        MethodSymbol m = tree.sym;
837        boolean isDefaultMethod = (m.flags() & DEFAULT) != 0;
838
839        Lint lint = env.info.lint.augment(m);
840        Lint prevLint = chk.setLint(lint);
841        MethodSymbol prevMethod = chk.setMethod(m);
842        try {
843            deferredLintHandler.flush(tree.pos());
844            chk.checkDeprecatedAnnotation(tree.pos(), m);
845
846
847            // Create a new environment with local scope
848            // for attributing the method.
849            Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
850            localEnv.info.lint = lint;
851
852            attribStats(tree.typarams, localEnv);
853
854            // If we override any other methods, check that we do so properly.
855            // JLS ???
856            if (m.isStatic()) {
857                chk.checkHideClashes(tree.pos(), env.enclClass.type, m);
858            } else {
859                chk.checkOverrideClashes(tree.pos(), env.enclClass.type, m);
860            }
861            chk.checkOverride(tree, m);
862
863            if (isDefaultMethod && types.overridesObjectMethod(m.enclClass(), m)) {
864                log.error(tree, "default.overrides.object.member", m.name, Kinds.kindName(m.location()), m.location());
865            }
866
867            // Enter all type parameters into the local method scope.
868            for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
869                localEnv.info.scope.enterIfAbsent(l.head.type.tsym);
870
871            ClassSymbol owner = env.enclClass.sym;
872            if ((owner.flags() & ANNOTATION) != 0 &&
873                    tree.params.nonEmpty())
874                log.error(tree.params.head.pos(),
875                        "intf.annotation.members.cant.have.params");
876
877            // Attribute all value parameters.
878            for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
879                attribStat(l.head, localEnv);
880            }
881
882            chk.checkVarargsMethodDecl(localEnv, tree);
883
884            // Check that type parameters are well-formed.
885            chk.validate(tree.typarams, localEnv);
886
887            // Check that result type is well-formed.
888            if (tree.restype != null && !tree.restype.type.hasTag(VOID))
889                chk.validate(tree.restype, localEnv);
890
891            // Check that receiver type is well-formed.
892            if (tree.recvparam != null) {
893                // Use a new environment to check the receiver parameter.
894                // Otherwise I get "might not have been initialized" errors.
895                // Is there a better way?
896                Env<AttrContext> newEnv = memberEnter.methodEnv(tree, env);
897                attribType(tree.recvparam, newEnv);
898                chk.validate(tree.recvparam, newEnv);
899            }
900
901            // annotation method checks
902            if ((owner.flags() & ANNOTATION) != 0) {
903                // annotation method cannot have throws clause
904                if (tree.thrown.nonEmpty()) {
905                    log.error(tree.thrown.head.pos(),
906                            "throws.not.allowed.in.intf.annotation");
907                }
908                // annotation method cannot declare type-parameters
909                if (tree.typarams.nonEmpty()) {
910                    log.error(tree.typarams.head.pos(),
911                            "intf.annotation.members.cant.have.type.params");
912                }
913                // validate annotation method's return type (could be an annotation type)
914                chk.validateAnnotationType(tree.restype);
915                // ensure that annotation method does not clash with members of Object/Annotation
916                chk.validateAnnotationMethod(tree.pos(), m);
917            }
918
919            for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
920                chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
921
922            if (tree.body == null) {
923                // Empty bodies are only allowed for
924                // abstract, native, or interface methods, or for methods
925                // in a retrofit signature class.
926                if (tree.defaultValue != null) {
927                    if ((owner.flags() & ANNOTATION) == 0)
928                        log.error(tree.pos(),
929                                  "default.allowed.in.intf.annotation.member");
930                }
931                if (isDefaultMethod || (tree.sym.flags() & (ABSTRACT | NATIVE)) == 0 &&
932                    !relax)
933                    log.error(tree.pos(), "missing.meth.body.or.decl.abstract");
934            } else if ((tree.sym.flags() & ABSTRACT) != 0 && !isDefaultMethod) {
935                if ((owner.flags() & INTERFACE) != 0) {
936                    log.error(tree.body.pos(), "intf.meth.cant.have.body");
937                } else {
938                    log.error(tree.pos(), "abstract.meth.cant.have.body");
939                }
940            } else if ((tree.mods.flags & NATIVE) != 0) {
941                log.error(tree.pos(), "native.meth.cant.have.body");
942            } else {
943                // Add an implicit super() call unless an explicit call to
944                // super(...) or this(...) is given
945                // or we are compiling class java.lang.Object.
946                if (tree.name == names.init && owner.type != syms.objectType) {
947                    JCBlock body = tree.body;
948                    if (body.stats.isEmpty() ||
949                            !TreeInfo.isSelfCall(body.stats.head)) {
950                        body.stats = body.stats.
951                                prepend(typeEnter.SuperCall(make.at(body.pos),
952                                        List.<Type>nil(),
953                                        List.<JCVariableDecl>nil(),
954                                        false));
955                    } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
956                            (tree.mods.flags & GENERATEDCONSTR) == 0 &&
957                            TreeInfo.isSuperCall(body.stats.head)) {
958                        // enum constructors are not allowed to call super
959                        // directly, so make sure there aren't any super calls
960                        // in enum constructors, except in the compiler
961                        // generated one.
962                        log.error(tree.body.stats.head.pos(),
963                                "call.to.super.not.allowed.in.enum.ctor",
964                                env.enclClass.sym);
965                    }
966                }
967
968                // Attribute all type annotations in the body
969                annotate.annotateTypeLater(tree.body, localEnv, m, null);
970                annotate.flush();
971
972                // Attribute method body.
973                attribStat(tree.body, localEnv);
974            }
975
976            localEnv.info.scope.leave();
977            result = tree.type = m.type;
978        } finally {
979            chk.setLint(prevLint);
980            chk.setMethod(prevMethod);
981        }
982    }
983
984    public void visitVarDef(JCVariableDecl tree) {
985        // Local variables have not been entered yet, so we need to do it now:
986        if (env.info.scope.owner.kind == MTH) {
987            if (tree.sym != null) {
988                // parameters have already been entered
989                env.info.scope.enter(tree.sym);
990            } else {
991                try {
992                    annotate.enterStart();
993                    memberEnter.memberEnter(tree, env);
994                } finally {
995                    annotate.enterDone();
996                }
997            }
998        } else {
999            if (tree.init != null) {
1000                // Field initializer expression need to be entered.
1001                annotate.annotateTypeLater(tree.init, env, tree.sym, tree.pos());
1002                annotate.flush();
1003            }
1004        }
1005
1006        VarSymbol v = tree.sym;
1007        Lint lint = env.info.lint.augment(v);
1008        Lint prevLint = chk.setLint(lint);
1009
1010        // Check that the variable's declared type is well-formed.
1011        boolean isImplicitLambdaParameter = env.tree.hasTag(LAMBDA) &&
1012                ((JCLambda)env.tree).paramKind == JCLambda.ParameterKind.IMPLICIT &&
1013                (tree.sym.flags() & PARAMETER) != 0;
1014        chk.validate(tree.vartype, env, !isImplicitLambdaParameter);
1015
1016        try {
1017            v.getConstValue(); // ensure compile-time constant initializer is evaluated
1018            deferredLintHandler.flush(tree.pos());
1019            chk.checkDeprecatedAnnotation(tree.pos(), v);
1020
1021            if (tree.init != null) {
1022                if ((v.flags_field & FINAL) == 0 ||
1023                    !memberEnter.needsLazyConstValue(tree.init)) {
1024                    // Not a compile-time constant
1025                    // Attribute initializer in a new environment
1026                    // with the declared variable as owner.
1027                    // Check that initializer conforms to variable's declared type.
1028                    Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
1029                    initEnv.info.lint = lint;
1030                    // In order to catch self-references, we set the variable's
1031                    // declaration position to maximal possible value, effectively
1032                    // marking the variable as undefined.
1033                    initEnv.info.enclVar = v;
1034                    attribExpr(tree.init, initEnv, v.type);
1035                }
1036            }
1037            result = tree.type = v.type;
1038        }
1039        finally {
1040            chk.setLint(prevLint);
1041        }
1042    }
1043
1044    public void visitSkip(JCSkip tree) {
1045        result = null;
1046    }
1047
1048    public void visitBlock(JCBlock tree) {
1049        if (env.info.scope.owner.kind == TYP) {
1050            // Block is a static or instance initializer;
1051            // let the owner of the environment be a freshly
1052            // created BLOCK-method.
1053            Symbol fakeOwner =
1054                new MethodSymbol(tree.flags | BLOCK |
1055                    env.info.scope.owner.flags() & STRICTFP, names.empty, null,
1056                    env.info.scope.owner);
1057            final Env<AttrContext> localEnv =
1058                env.dup(tree, env.info.dup(env.info.scope.dupUnshared(fakeOwner)));
1059
1060            if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
1061            // Attribute all type annotations in the block
1062            annotate.annotateTypeLater(tree, localEnv, localEnv.info.scope.owner, null);
1063            annotate.flush();
1064            attribStats(tree.stats, localEnv);
1065
1066            {
1067                // Store init and clinit type annotations with the ClassSymbol
1068                // to allow output in Gen.normalizeDefs.
1069                ClassSymbol cs = (ClassSymbol)env.info.scope.owner;
1070                List<Attribute.TypeCompound> tas = localEnv.info.scope.owner.getRawTypeAttributes();
1071                if ((tree.flags & STATIC) != 0) {
1072                    cs.appendClassInitTypeAttributes(tas);
1073                } else {
1074                    cs.appendInitTypeAttributes(tas);
1075                }
1076            }
1077        } else {
1078            // Create a new local environment with a local scope.
1079            Env<AttrContext> localEnv =
1080                env.dup(tree, env.info.dup(env.info.scope.dup()));
1081            try {
1082                attribStats(tree.stats, localEnv);
1083            } finally {
1084                localEnv.info.scope.leave();
1085            }
1086        }
1087        result = null;
1088    }
1089
1090    public void visitDoLoop(JCDoWhileLoop tree) {
1091        attribStat(tree.body, env.dup(tree));
1092        attribExpr(tree.cond, env, syms.booleanType);
1093        result = null;
1094    }
1095
1096    public void visitWhileLoop(JCWhileLoop tree) {
1097        attribExpr(tree.cond, env, syms.booleanType);
1098        attribStat(tree.body, env.dup(tree));
1099        result = null;
1100    }
1101
1102    public void visitForLoop(JCForLoop tree) {
1103        Env<AttrContext> loopEnv =
1104            env.dup(env.tree, env.info.dup(env.info.scope.dup()));
1105        try {
1106            attribStats(tree.init, loopEnv);
1107            if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType);
1108            loopEnv.tree = tree; // before, we were not in loop!
1109            attribStats(tree.step, loopEnv);
1110            attribStat(tree.body, loopEnv);
1111            result = null;
1112        }
1113        finally {
1114            loopEnv.info.scope.leave();
1115        }
1116    }
1117
1118    public void visitForeachLoop(JCEnhancedForLoop tree) {
1119        Env<AttrContext> loopEnv =
1120            env.dup(env.tree, env.info.dup(env.info.scope.dup()));
1121        try {
1122            //the Formal Parameter of a for-each loop is not in the scope when
1123            //attributing the for-each expression; we mimick this by attributing
1124            //the for-each expression first (against original scope).
1125            Type exprType = types.cvarUpperBound(attribExpr(tree.expr, loopEnv));
1126            attribStat(tree.var, loopEnv);
1127            chk.checkNonVoid(tree.pos(), exprType);
1128            Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
1129            if (elemtype == null) {
1130                // or perhaps expr implements Iterable<T>?
1131                Type base = types.asSuper(exprType, syms.iterableType.tsym);
1132                if (base == null) {
1133                    log.error(tree.expr.pos(),
1134                            "foreach.not.applicable.to.type",
1135                            exprType,
1136                            diags.fragment("type.req.array.or.iterable"));
1137                    elemtype = types.createErrorType(exprType);
1138                } else {
1139                    List<Type> iterableParams = base.allparams();
1140                    elemtype = iterableParams.isEmpty()
1141                        ? syms.objectType
1142                        : types.wildUpperBound(iterableParams.head);
1143                }
1144            }
1145            chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
1146            loopEnv.tree = tree; // before, we were not in loop!
1147            attribStat(tree.body, loopEnv);
1148            result = null;
1149        }
1150        finally {
1151            loopEnv.info.scope.leave();
1152        }
1153    }
1154
1155    public void visitLabelled(JCLabeledStatement tree) {
1156        // Check that label is not used in an enclosing statement
1157        Env<AttrContext> env1 = env;
1158        while (env1 != null && !env1.tree.hasTag(CLASSDEF)) {
1159            if (env1.tree.hasTag(LABELLED) &&
1160                ((JCLabeledStatement) env1.tree).label == tree.label) {
1161                log.error(tree.pos(), "label.already.in.use",
1162                          tree.label);
1163                break;
1164            }
1165            env1 = env1.next;
1166        }
1167
1168        attribStat(tree.body, env.dup(tree));
1169        result = null;
1170    }
1171
1172    public void visitSwitch(JCSwitch tree) {
1173        Type seltype = attribExpr(tree.selector, env);
1174
1175        Env<AttrContext> switchEnv =
1176            env.dup(tree, env.info.dup(env.info.scope.dup()));
1177
1178        try {
1179
1180            boolean enumSwitch = (seltype.tsym.flags() & Flags.ENUM) != 0;
1181            boolean stringSwitch = false;
1182            if (types.isSameType(seltype, syms.stringType)) {
1183                if (allowStringsInSwitch) {
1184                    stringSwitch = true;
1185                } else {
1186                    log.error(tree.selector.pos(), "string.switch.not.supported.in.source", sourceName);
1187                }
1188            }
1189            if (!enumSwitch && !stringSwitch)
1190                seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType);
1191
1192            // Attribute all cases and
1193            // check that there are no duplicate case labels or default clauses.
1194            Set<Object> labels = new HashSet<>(); // The set of case labels.
1195            boolean hasDefault = false;      // Is there a default label?
1196            for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
1197                JCCase c = l.head;
1198                if (c.pat != null) {
1199                    if (enumSwitch) {
1200                        Symbol sym = enumConstant(c.pat, seltype);
1201                        if (sym == null) {
1202                            log.error(c.pat.pos(), "enum.label.must.be.unqualified.enum");
1203                        } else if (!labels.add(sym)) {
1204                            log.error(c.pos(), "duplicate.case.label");
1205                        }
1206                    } else {
1207                        Type pattype = attribExpr(c.pat, switchEnv, seltype);
1208                        if (!pattype.hasTag(ERROR)) {
1209                            if (pattype.constValue() == null) {
1210                                log.error(c.pat.pos(),
1211                                          (stringSwitch ? "string.const.req" : "const.expr.req"));
1212                            } else if (labels.contains(pattype.constValue())) {
1213                                log.error(c.pos(), "duplicate.case.label");
1214                            } else {
1215                                labels.add(pattype.constValue());
1216                            }
1217                        }
1218                    }
1219                } else if (hasDefault) {
1220                    log.error(c.pos(), "duplicate.default.label");
1221                } else {
1222                    hasDefault = true;
1223                }
1224                Env<AttrContext> caseEnv =
1225                    switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup()));
1226                try {
1227                    attribStats(c.stats, caseEnv);
1228                } finally {
1229                    caseEnv.info.scope.leave();
1230                    addVars(c.stats, switchEnv.info.scope);
1231                }
1232            }
1233
1234            result = null;
1235        }
1236        finally {
1237            switchEnv.info.scope.leave();
1238        }
1239    }
1240    // where
1241        /** Add any variables defined in stats to the switch scope. */
1242        private static void addVars(List<JCStatement> stats, WriteableScope switchScope) {
1243            for (;stats.nonEmpty(); stats = stats.tail) {
1244                JCTree stat = stats.head;
1245                if (stat.hasTag(VARDEF))
1246                    switchScope.enter(((JCVariableDecl) stat).sym);
1247            }
1248        }
1249    // where
1250    /** Return the selected enumeration constant symbol, or null. */
1251    private Symbol enumConstant(JCTree tree, Type enumType) {
1252        if (!tree.hasTag(IDENT)) {
1253            log.error(tree.pos(), "enum.label.must.be.unqualified.enum");
1254            return syms.errSymbol;
1255        }
1256        JCIdent ident = (JCIdent)tree;
1257        Name name = ident.name;
1258        for (Symbol sym : enumType.tsym.members().getSymbolsByName(name)) {
1259            if (sym.kind == VAR) {
1260                Symbol s = ident.sym = sym;
1261                ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
1262                ident.type = s.type;
1263                return ((s.flags_field & Flags.ENUM) == 0)
1264                    ? null : s;
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        private 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.isOverloadError());
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 = syms.nullcheck;
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.isCompound() ?
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 =
2388                        (IntersectionClassType)types.makeCompoundType(supertypes.toList());
2389                notionalIntf.allparams_field = targs.toList();
2390                notionalIntf.tsym.flags_field |= INTERFACE;
2391                return notionalIntf.tsym;
2392            }
2393
2394            private void reportIntersectionError(DiagnosticPosition pos, String key, Object... args) {
2395                resultInfo.checkContext.report(pos, diags.fragment("bad.intersection.target.for.functional.expr",
2396                        diags.fragment(key, args)));
2397            }
2398        };
2399
2400        private Type fallbackDescriptorType(JCExpression tree) {
2401            switch (tree.getTag()) {
2402                case LAMBDA:
2403                    JCLambda lambda = (JCLambda)tree;
2404                    List<Type> argtypes = List.nil();
2405                    for (JCVariableDecl param : lambda.params) {
2406                        argtypes = param.vartype != null ?
2407                                argtypes.append(param.vartype.type) :
2408                                argtypes.append(syms.errType);
2409                    }
2410                    return new MethodType(argtypes, Type.recoveryType,
2411                            List.of(syms.throwableType), syms.methodClass);
2412                case REFERENCE:
2413                    return new MethodType(List.<Type>nil(), Type.recoveryType,
2414                            List.of(syms.throwableType), syms.methodClass);
2415                default:
2416                    Assert.error("Cannot get here!");
2417            }
2418            return null;
2419        }
2420
2421        private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
2422                final InferenceContext inferenceContext, final Type... ts) {
2423            checkAccessibleTypes(pos, env, inferenceContext, List.from(ts));
2424        }
2425
2426        private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
2427                final InferenceContext inferenceContext, final List<Type> ts) {
2428            if (inferenceContext.free(ts)) {
2429                inferenceContext.addFreeTypeListener(ts, new FreeTypeListener() {
2430                    @Override
2431                    public void typesInferred(InferenceContext inferenceContext) {
2432                        checkAccessibleTypes(pos, env, inferenceContext, inferenceContext.asInstTypes(ts));
2433                    }
2434                });
2435            } else {
2436                for (Type t : ts) {
2437                    rs.checkAccessibleType(env, t);
2438                }
2439            }
2440        }
2441
2442        /**
2443         * Lambda/method reference have a special check context that ensures
2444         * that i.e. a lambda return type is compatible with the expected
2445         * type according to both the inherited context and the assignment
2446         * context.
2447         */
2448        class FunctionalReturnContext extends Check.NestedCheckContext {
2449
2450            FunctionalReturnContext(CheckContext enclosingContext) {
2451                super(enclosingContext);
2452            }
2453
2454            @Override
2455            public boolean compatible(Type found, Type req, Warner warn) {
2456                //return type must be compatible in both current context and assignment context
2457                return chk.basicHandler.compatible(found, inferenceContext().asUndetVar(req), warn);
2458            }
2459
2460            @Override
2461            public void report(DiagnosticPosition pos, JCDiagnostic details) {
2462                enclosingContext.report(pos, diags.fragment("incompatible.ret.type.in.lambda", details));
2463            }
2464        }
2465
2466        class ExpressionLambdaReturnContext extends FunctionalReturnContext {
2467
2468            JCExpression expr;
2469
2470            ExpressionLambdaReturnContext(JCExpression expr, CheckContext enclosingContext) {
2471                super(enclosingContext);
2472                this.expr = expr;
2473            }
2474
2475            @Override
2476            public boolean compatible(Type found, Type req, Warner warn) {
2477                //a void return is compatible with an expression statement lambda
2478                return TreeInfo.isExpressionStatement(expr) && req.hasTag(VOID) ||
2479                        super.compatible(found, req, warn);
2480            }
2481        }
2482
2483        /**
2484        * Lambda compatibility. Check that given return types, thrown types, parameter types
2485        * are compatible with the expected functional interface descriptor. This means that:
2486        * (i) parameter types must be identical to those of the target descriptor; (ii) return
2487        * types must be compatible with the return type of the expected descriptor.
2488        */
2489        private void checkLambdaCompatible(JCLambda tree, Type descriptor, CheckContext checkContext) {
2490            Type returnType = checkContext.inferenceContext().asUndetVar(descriptor.getReturnType());
2491
2492            //return values have already been checked - but if lambda has no return
2493            //values, we must ensure that void/value compatibility is correct;
2494            //this amounts at checking that, if a lambda body can complete normally,
2495            //the descriptor's return type must be void
2496            if (tree.getBodyKind() == JCLambda.BodyKind.STATEMENT && tree.canCompleteNormally &&
2497                    !returnType.hasTag(VOID) && returnType != Type.recoveryType) {
2498                checkContext.report(tree, diags.fragment("incompatible.ret.type.in.lambda",
2499                        diags.fragment("missing.ret.val", returnType)));
2500            }
2501
2502            List<Type> argTypes = checkContext.inferenceContext().asUndetVars(descriptor.getParameterTypes());
2503            if (!types.isSameTypes(argTypes, TreeInfo.types(tree.params))) {
2504                checkContext.report(tree, diags.fragment("incompatible.arg.types.in.lambda"));
2505            }
2506        }
2507
2508        /* Map to hold 'fake' clinit methods. If a lambda is used to initialize a
2509         * static field and that lambda has type annotations, these annotations will
2510         * also be stored at these fake clinit methods.
2511         *
2512         * LambdaToMethod also use fake clinit methods so they can be reused.
2513         * Also as LTM is a phase subsequent to attribution, the methods from
2514         * clinits can be safely removed by LTM to save memory.
2515         */
2516        private Map<ClassSymbol, MethodSymbol> clinits = new HashMap<>();
2517
2518        public MethodSymbol removeClinit(ClassSymbol sym) {
2519            return clinits.remove(sym);
2520        }
2521
2522        /* This method returns an environment to be used to attribute a lambda
2523         * expression.
2524         *
2525         * The owner of this environment is a method symbol. If the current owner
2526         * is not a method, for example if the lambda is used to initialize
2527         * a field, then if the field is:
2528         *
2529         * - an instance field, we use the first constructor.
2530         * - a static field, we create a fake clinit method.
2531         */
2532        public Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) {
2533            Env<AttrContext> lambdaEnv;
2534            Symbol owner = env.info.scope.owner;
2535            if (owner.kind == VAR && owner.owner.kind == TYP) {
2536                //field initializer
2537                ClassSymbol enclClass = owner.enclClass();
2538                Symbol newScopeOwner = env.info.scope.owner;
2539                /* if the field isn't static, then we can get the first constructor
2540                 * and use it as the owner of the environment. This is what
2541                 * LTM code is doing to look for type annotations so we are fine.
2542                 */
2543                if ((owner.flags() & STATIC) == 0) {
2544                    for (Symbol s : enclClass.members_field.getSymbolsByName(names.init)) {
2545                        newScopeOwner = s;
2546                        break;
2547                    }
2548                } else {
2549                    /* if the field is static then we need to create a fake clinit
2550                     * method, this method can later be reused by LTM.
2551                     */
2552                    MethodSymbol clinit = clinits.get(enclClass);
2553                    if (clinit == null) {
2554                        Type clinitType = new MethodType(List.<Type>nil(),
2555                                syms.voidType, List.<Type>nil(), syms.methodClass);
2556                        clinit = new MethodSymbol(STATIC | SYNTHETIC | PRIVATE,
2557                                names.clinit, clinitType, enclClass);
2558                        clinit.params = List.<VarSymbol>nil();
2559                        clinits.put(enclClass, clinit);
2560                    }
2561                    newScopeOwner = clinit;
2562                }
2563                lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared(newScopeOwner)));
2564            } else {
2565                lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dup()));
2566            }
2567            return lambdaEnv;
2568        }
2569
2570    @Override
2571    public void visitReference(final JCMemberReference that) {
2572        if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
2573            if (pt().hasTag(NONE)) {
2574                //method reference only allowed in assignment or method invocation/cast context
2575                log.error(that.pos(), "unexpected.mref");
2576            }
2577            result = that.type = types.createErrorType(pt());
2578            return;
2579        }
2580        final Env<AttrContext> localEnv = env.dup(that);
2581        try {
2582            //attribute member reference qualifier - if this is a constructor
2583            //reference, the expected kind must be a type
2584            Type exprType = attribTree(that.expr, env, memberReferenceQualifierResult(that));
2585
2586            if (that.getMode() == JCMemberReference.ReferenceMode.NEW) {
2587                exprType = chk.checkConstructorRefType(that.expr, exprType);
2588                if (!exprType.isErroneous() &&
2589                    exprType.isRaw() &&
2590                    that.typeargs != null) {
2591                    log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
2592                        diags.fragment("mref.infer.and.explicit.params"));
2593                    exprType = types.createErrorType(exprType);
2594                }
2595            }
2596
2597            if (exprType.isErroneous()) {
2598                //if the qualifier expression contains problems,
2599                //give up attribution of method reference
2600                result = that.type = exprType;
2601                return;
2602            }
2603
2604            if (TreeInfo.isStaticSelector(that.expr, names)) {
2605                //if the qualifier is a type, validate it; raw warning check is
2606                //omitted as we don't know at this stage as to whether this is a
2607                //raw selector (because of inference)
2608                chk.validate(that.expr, env, false);
2609            }
2610
2611            //attrib type-arguments
2612            List<Type> typeargtypes = List.nil();
2613            if (that.typeargs != null) {
2614                typeargtypes = attribTypes(that.typeargs, localEnv);
2615            }
2616
2617            Type desc;
2618            Type currentTarget = pt();
2619            boolean isTargetSerializable =
2620                    resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
2621                    isSerializable(currentTarget);
2622            if (currentTarget != Type.recoveryType) {
2623                currentTarget = types.removeWildcards(targetChecker.visit(currentTarget, that));
2624                desc = types.findDescriptorType(currentTarget);
2625            } else {
2626                currentTarget = Type.recoveryType;
2627                desc = fallbackDescriptorType(that);
2628            }
2629
2630            setFunctionalInfo(localEnv, that, pt(), desc, currentTarget, resultInfo.checkContext);
2631            List<Type> argtypes = desc.getParameterTypes();
2632            Resolve.MethodCheck referenceCheck = rs.resolveMethodCheck;
2633
2634            if (resultInfo.checkContext.inferenceContext().free(argtypes)) {
2635                referenceCheck = rs.new MethodReferenceCheck(resultInfo.checkContext.inferenceContext());
2636            }
2637
2638            Pair<Symbol, Resolve.ReferenceLookupHelper> refResult = null;
2639            List<Type> saved_undet = resultInfo.checkContext.inferenceContext().save();
2640            try {
2641                refResult = rs.resolveMemberReference(localEnv, that, that.expr.type,
2642                        that.name, argtypes, typeargtypes, referenceCheck,
2643                        resultInfo.checkContext.inferenceContext(),
2644                        resultInfo.checkContext.deferredAttrContext().mode);
2645            } finally {
2646                resultInfo.checkContext.inferenceContext().rollback(saved_undet);
2647            }
2648
2649            Symbol refSym = refResult.fst;
2650            Resolve.ReferenceLookupHelper lookupHelper = refResult.snd;
2651
2652            if (refSym.kind != MTH) {
2653                boolean targetError;
2654                switch (refSym.kind) {
2655                    case ABSENT_MTH:
2656                        targetError = false;
2657                        break;
2658                    case WRONG_MTH:
2659                    case WRONG_MTHS:
2660                    case AMBIGUOUS:
2661                    case HIDDEN:
2662                    case STATICERR:
2663                    case MISSING_ENCL:
2664                    case WRONG_STATICNESS:
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 (that.sym.isStatic() && !TreeInfo.isStaticSelector(that.expr, names) &&
2726                        !that.kind.isUnbound()) {
2727                    //no static bound mrefs
2728                    log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
2729                            diags.fragment("static.bound.mref"));
2730                    result = that.type = types.createErrorType(currentTarget);
2731                    return;
2732                }
2733
2734                if (!refSym.isStatic() && that.kind == JCMemberReference.ReferenceKind.SUPER) {
2735                    // Check that super-qualified symbols are not abstract (JLS)
2736                    rs.checkNonAbstract(that.pos(), that.sym);
2737                }
2738
2739                if (isTargetSerializable) {
2740                    chk.checkElemAccessFromSerializableLambda(that);
2741                }
2742            }
2743
2744            ResultInfo checkInfo =
2745                    resultInfo.dup(newMethodTemplate(
2746                        desc.getReturnType().hasTag(VOID) ? Type.noType : desc.getReturnType(),
2747                        that.kind.isUnbound() ? argtypes.tail : argtypes, typeargtypes),
2748                        new FunctionalReturnContext(resultInfo.checkContext));
2749
2750            Type refType = checkId(noCheckTree, lookupHelper.site, refSym, localEnv, checkInfo);
2751
2752            if (that.kind.isUnbound() &&
2753                    resultInfo.checkContext.inferenceContext().free(argtypes.head)) {
2754                //re-generate inference constraints for unbound receiver
2755                if (!types.isSubtype(resultInfo.checkContext.inferenceContext().asUndetVar(argtypes.head), exprType)) {
2756                    //cannot happen as this has already been checked - we just need
2757                    //to regenerate the inference constraints, as that has been lost
2758                    //as a result of the call to inferenceContext.save()
2759                    Assert.error("Can't get here");
2760                }
2761            }
2762
2763            if (!refType.isErroneous()) {
2764                refType = types.createMethodTypeWithReturn(refType,
2765                        adjustMethodReturnType(lookupHelper.site, that.name, checkInfo.pt.getParameterTypes(), refType.getReturnType()));
2766            }
2767
2768            //go ahead with standard method reference compatibility check - note that param check
2769            //is a no-op (as this has been taken care during method applicability)
2770            boolean isSpeculativeRound =
2771                    resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
2772
2773            that.type = currentTarget; //avoids recovery at this stage
2774            checkReferenceCompatible(that, desc, refType, resultInfo.checkContext, isSpeculativeRound);
2775            if (!isSpeculativeRound) {
2776                checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), desc, currentTarget);
2777            }
2778            result = check(that, currentTarget, KindSelector.VAL, resultInfo);
2779        } catch (Types.FunctionDescriptorLookupError ex) {
2780            JCDiagnostic cause = ex.getDiagnostic();
2781            resultInfo.checkContext.report(that, cause);
2782            result = that.type = types.createErrorType(pt());
2783            return;
2784        }
2785    }
2786    //where
2787        ResultInfo memberReferenceQualifierResult(JCMemberReference tree) {
2788            //if this is a constructor reference, the expected kind must be a type
2789            return new ResultInfo(tree.getMode() == ReferenceMode.INVOKE ?
2790                                  KindSelector.VAL_TYP : KindSelector.TYP,
2791                                  Type.noType);
2792        }
2793
2794
2795    @SuppressWarnings("fallthrough")
2796    void checkReferenceCompatible(JCMemberReference tree, Type descriptor, Type refType, CheckContext checkContext, boolean speculativeAttr) {
2797        Type returnType = checkContext.inferenceContext().asUndetVar(descriptor.getReturnType());
2798
2799        Type resType;
2800        switch (tree.getMode()) {
2801            case NEW:
2802                if (!tree.expr.type.isRaw()) {
2803                    resType = tree.expr.type;
2804                    break;
2805                }
2806            default:
2807                resType = refType.getReturnType();
2808        }
2809
2810        Type incompatibleReturnType = resType;
2811
2812        if (returnType.hasTag(VOID)) {
2813            incompatibleReturnType = null;
2814        }
2815
2816        if (!returnType.hasTag(VOID) && !resType.hasTag(VOID)) {
2817            if (resType.isErroneous() ||
2818                    new FunctionalReturnContext(checkContext).compatible(resType, returnType, types.noWarnings)) {
2819                incompatibleReturnType = null;
2820            }
2821        }
2822
2823        if (incompatibleReturnType != null) {
2824            checkContext.report(tree, diags.fragment("incompatible.ret.type.in.mref",
2825                    diags.fragment("inconvertible.types", resType, descriptor.getReturnType())));
2826        }
2827
2828        if (!speculativeAttr) {
2829            List<Type> thrownTypes = checkContext.inferenceContext().asUndetVars(descriptor.getThrownTypes());
2830            if (chk.unhandled(refType.getThrownTypes(), thrownTypes).nonEmpty()) {
2831                log.error(tree, "incompatible.thrown.types.in.mref", refType.getThrownTypes());
2832            }
2833        }
2834    }
2835
2836    /**
2837     * Set functional type info on the underlying AST. Note: as the target descriptor
2838     * might contain inference variables, we might need to register an hook in the
2839     * current inference context.
2840     */
2841    private void setFunctionalInfo(final Env<AttrContext> env, final JCFunctionalExpression fExpr,
2842            final Type pt, final Type descriptorType, final Type primaryTarget, final CheckContext checkContext) {
2843        if (checkContext.inferenceContext().free(descriptorType)) {
2844            checkContext.inferenceContext().addFreeTypeListener(List.of(pt, descriptorType), new FreeTypeListener() {
2845                public void typesInferred(InferenceContext inferenceContext) {
2846                    setFunctionalInfo(env, fExpr, pt, inferenceContext.asInstType(descriptorType),
2847                            inferenceContext.asInstType(primaryTarget), checkContext);
2848                }
2849            });
2850        } else {
2851            ListBuffer<Type> targets = new ListBuffer<>();
2852            if (pt.hasTag(CLASS)) {
2853                if (pt.isCompound()) {
2854                    targets.append(types.removeWildcards(primaryTarget)); //this goes first
2855                    for (Type t : ((IntersectionClassType)pt()).interfaces_field) {
2856                        if (t != primaryTarget) {
2857                            targets.append(types.removeWildcards(t));
2858                        }
2859                    }
2860                } else {
2861                    targets.append(types.removeWildcards(primaryTarget));
2862                }
2863            }
2864            fExpr.targets = targets.toList();
2865            if (checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
2866                    pt != Type.recoveryType) {
2867                //check that functional interface class is well-formed
2868                try {
2869                    /* Types.makeFunctionalInterfaceClass() may throw an exception
2870                     * when it's executed post-inference. See the listener code
2871                     * above.
2872                     */
2873                    ClassSymbol csym = types.makeFunctionalInterfaceClass(env,
2874                            names.empty, List.of(fExpr.targets.head), ABSTRACT);
2875                    if (csym != null) {
2876                        chk.checkImplementations(env.tree, csym, csym);
2877                    }
2878                } catch (Types.FunctionDescriptorLookupError ex) {
2879                    JCDiagnostic cause = ex.getDiagnostic();
2880                    resultInfo.checkContext.report(env.tree, cause);
2881                }
2882            }
2883        }
2884    }
2885
2886    public void visitParens(JCParens tree) {
2887        Type owntype = attribTree(tree.expr, env, resultInfo);
2888        result = check(tree, owntype, pkind(), resultInfo);
2889        Symbol sym = TreeInfo.symbol(tree);
2890        if (sym != null && sym.kind.matches(KindSelector.TYP_PCK))
2891            log.error(tree.pos(), "illegal.start.of.type");
2892    }
2893
2894    public void visitAssign(JCAssign tree) {
2895        Type owntype = attribTree(tree.lhs, env.dup(tree), varAssignmentInfo);
2896        Type capturedType = capture(owntype);
2897        attribExpr(tree.rhs, env, owntype);
2898        result = check(tree, capturedType, KindSelector.VAL, resultInfo);
2899    }
2900
2901    public void visitAssignop(JCAssignOp tree) {
2902        // Attribute arguments.
2903        Type owntype = attribTree(tree.lhs, env, varAssignmentInfo);
2904        Type operand = attribExpr(tree.rhs, env);
2905        // Find operator.
2906        Symbol operator = tree.operator = rs.resolveBinaryOperator(
2907            tree.pos(), tree.getTag().noAssignOp(), env,
2908            owntype, operand);
2909
2910        if (operator.kind == MTH &&
2911                !owntype.isErroneous() &&
2912                !operand.isErroneous()) {
2913            chk.checkOperator(tree.pos(),
2914                              (OperatorSymbol)operator,
2915                              tree.getTag().noAssignOp(),
2916                              owntype,
2917                              operand);
2918            chk.checkDivZero(tree.rhs.pos(), operator, operand);
2919            chk.checkCastable(tree.rhs.pos(),
2920                              operator.type.getReturnType(),
2921                              owntype);
2922        }
2923        result = check(tree, owntype, KindSelector.VAL, resultInfo);
2924    }
2925
2926    public void visitUnary(JCUnary tree) {
2927        // Attribute arguments.
2928        Type argtype = (tree.getTag().isIncOrDecUnaryOp())
2929            ? attribTree(tree.arg, env, varAssignmentInfo)
2930            : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
2931
2932        // Find operator.
2933        Symbol operator = tree.operator =
2934            rs.resolveUnaryOperator(tree.pos(), tree.getTag(), env, argtype);
2935
2936        Type owntype = types.createErrorType(tree.type);
2937        if (operator.kind == MTH &&
2938                !argtype.isErroneous()) {
2939            owntype = (tree.getTag().isIncOrDecUnaryOp())
2940                ? tree.arg.type
2941                : operator.type.getReturnType();
2942            int opc = ((OperatorSymbol)operator).opcode;
2943
2944            // If the argument is constant, fold it.
2945            if (argtype.constValue() != null) {
2946                Type ctype = cfolder.fold1(opc, argtype);
2947                if (ctype != null) {
2948                    owntype = cfolder.coerce(ctype, owntype);
2949                }
2950            }
2951        }
2952        result = check(tree, owntype, KindSelector.VAL, resultInfo);
2953    }
2954
2955    public void visitBinary(JCBinary tree) {
2956        // Attribute arguments.
2957        Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
2958        Type right = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.rhs, env));
2959        // Find operator.
2960        Symbol operator = tree.operator =
2961            rs.resolveBinaryOperator(tree.pos(), tree.getTag(), env, left, right);
2962
2963        Type owntype = types.createErrorType(tree.type);
2964        if (operator.kind == MTH &&
2965                !left.isErroneous() &&
2966                !right.isErroneous()) {
2967            owntype = operator.type.getReturnType();
2968            // This will figure out when unboxing can happen and
2969            // choose the right comparison operator.
2970            int opc = chk.checkOperator(tree.lhs.pos(),
2971                                        (OperatorSymbol)operator,
2972                                        tree.getTag(),
2973                                        left,
2974                                        right);
2975
2976            // If both arguments are constants, fold them.
2977            if (left.constValue() != null && right.constValue() != null) {
2978                Type ctype = cfolder.fold2(opc, left, right);
2979                if (ctype != null) {
2980                    owntype = cfolder.coerce(ctype, owntype);
2981                }
2982            }
2983
2984            // Check that argument types of a reference ==, != are
2985            // castable to each other, (JLS 15.21).  Note: unboxing
2986            // comparisons will not have an acmp* opc at this point.
2987            if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
2988                if (!types.isEqualityComparable(left, right,
2989                                                new Warner(tree.pos()))) {
2990                    log.error(tree.pos(), "incomparable.types", left, right);
2991                }
2992            }
2993
2994            chk.checkDivZero(tree.rhs.pos(), operator, right);
2995        }
2996        result = check(tree, owntype, KindSelector.VAL, resultInfo);
2997    }
2998
2999    public void visitTypeCast(final JCTypeCast tree) {
3000        Type clazztype = attribType(tree.clazz, env);
3001        chk.validate(tree.clazz, env, false);
3002        //a fresh environment is required for 292 inference to work properly ---
3003        //see Infer.instantiatePolymorphicSignatureInstance()
3004        Env<AttrContext> localEnv = env.dup(tree);
3005        //should we propagate the target type?
3006        final ResultInfo castInfo;
3007        JCExpression expr = TreeInfo.skipParens(tree.expr);
3008        boolean isPoly = allowPoly && (expr.hasTag(LAMBDA) || expr.hasTag(REFERENCE));
3009        if (isPoly) {
3010            //expression is a poly - we need to propagate target type info
3011            castInfo = new ResultInfo(KindSelector.VAL, clazztype,
3012                                      new Check.NestedCheckContext(resultInfo.checkContext) {
3013                @Override
3014                public boolean compatible(Type found, Type req, Warner warn) {
3015                    return types.isCastable(found, req, warn);
3016                }
3017            });
3018        } else {
3019            //standalone cast - target-type info is not propagated
3020            castInfo = unknownExprInfo;
3021        }
3022        Type exprtype = attribTree(tree.expr, localEnv, castInfo);
3023        Type owntype = isPoly ? clazztype : chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
3024        if (exprtype.constValue() != null)
3025            owntype = cfolder.coerce(exprtype, owntype);
3026        result = check(tree, capture(owntype), KindSelector.VAL, resultInfo);
3027        if (!isPoly)
3028            chk.checkRedundantCast(localEnv, tree);
3029    }
3030
3031    public void visitTypeTest(JCInstanceOf tree) {
3032        Type exprtype = chk.checkNullOrRefType(
3033                tree.expr.pos(), attribExpr(tree.expr, env));
3034        Type clazztype = attribType(tree.clazz, env);
3035        if (!clazztype.hasTag(TYPEVAR)) {
3036            clazztype = chk.checkClassOrArrayType(tree.clazz.pos(), clazztype);
3037        }
3038        if (!clazztype.isErroneous() && !types.isReifiable(clazztype)) {
3039            log.error(tree.clazz.pos(), "illegal.generic.type.for.instof");
3040            clazztype = types.createErrorType(clazztype);
3041        }
3042        chk.validate(tree.clazz, env, false);
3043        chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
3044        result = check(tree, syms.booleanType, KindSelector.VAL, resultInfo);
3045    }
3046
3047    public void visitIndexed(JCArrayAccess tree) {
3048        Type owntype = types.createErrorType(tree.type);
3049        Type atype = attribExpr(tree.indexed, env);
3050        attribExpr(tree.index, env, syms.intType);
3051        if (types.isArray(atype))
3052            owntype = types.elemtype(atype);
3053        else if (!atype.hasTag(ERROR))
3054            log.error(tree.pos(), "array.req.but.found", atype);
3055        if (!pkind().contains(KindSelector.VAL))
3056            owntype = capture(owntype);
3057        result = check(tree, owntype, KindSelector.VAR, resultInfo);
3058    }
3059
3060    public void visitIdent(JCIdent tree) {
3061        Symbol sym;
3062
3063        // Find symbol
3064        if (pt().hasTag(METHOD) || pt().hasTag(FORALL)) {
3065            // If we are looking for a method, the prototype `pt' will be a
3066            // method type with the type of the call's arguments as parameters.
3067            env.info.pendingResolutionPhase = null;
3068            sym = rs.resolveMethod(tree.pos(), env, tree.name, pt().getParameterTypes(), pt().getTypeArguments());
3069        } else if (tree.sym != null && tree.sym.kind != VAR) {
3070            sym = tree.sym;
3071        } else {
3072            sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind());
3073        }
3074        tree.sym = sym;
3075
3076        // (1) Also find the environment current for the class where
3077        //     sym is defined (`symEnv').
3078        // Only for pre-tiger versions (1.4 and earlier):
3079        // (2) Also determine whether we access symbol out of an anonymous
3080        //     class in a this or super call.  This is illegal for instance
3081        //     members since such classes don't carry a this$n link.
3082        //     (`noOuterThisPath').
3083        Env<AttrContext> symEnv = env;
3084        boolean noOuterThisPath = false;
3085        if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
3086            sym.kind.matches(KindSelector.VAL_MTH) &&
3087            sym.owner.kind == TYP &&
3088            tree.name != names._this && tree.name != names._super) {
3089
3090            // Find environment in which identifier is defined.
3091            while (symEnv.outer != null &&
3092                   !sym.isMemberOf(symEnv.enclClass.sym, types)) {
3093                if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
3094                    noOuterThisPath = false;
3095                symEnv = symEnv.outer;
3096            }
3097        }
3098
3099        // If symbol is a variable, ...
3100        if (sym.kind == VAR) {
3101            VarSymbol v = (VarSymbol)sym;
3102
3103            // ..., evaluate its initializer, if it has one, and check for
3104            // illegal forward reference.
3105            checkInit(tree, env, v, false);
3106
3107            // If we are expecting a variable (as opposed to a value), check
3108            // that the variable is assignable in the current environment.
3109            if (KindSelector.ASG.subset(pkind()))
3110                checkAssignable(tree.pos(), v, null, env);
3111        }
3112
3113        // In a constructor body,
3114        // if symbol is a field or instance method, check that it is
3115        // not accessed before the supertype constructor is called.
3116        if ((symEnv.info.isSelfCall || noOuterThisPath) &&
3117            sym.kind.matches(KindSelector.VAL_MTH) &&
3118            sym.owner.kind == TYP &&
3119            (sym.flags() & STATIC) == 0) {
3120            chk.earlyRefError(tree.pos(), sym.kind == VAR ?
3121                                          sym : thisSym(tree.pos(), env));
3122        }
3123        Env<AttrContext> env1 = env;
3124        if (sym.kind != ERR && sym.kind != TYP &&
3125            sym.owner != null && sym.owner != env1.enclClass.sym) {
3126            // If the found symbol is inaccessible, then it is
3127            // accessed through an enclosing instance.  Locate this
3128            // enclosing instance:
3129            while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
3130                env1 = env1.outer;
3131        }
3132
3133        if (env.info.isSerializable) {
3134            chk.checkElemAccessFromSerializableLambda(tree);
3135        }
3136
3137        result = checkId(tree, env1.enclClass.sym.type, sym, env, resultInfo);
3138    }
3139
3140    public void visitSelect(JCFieldAccess tree) {
3141        // Determine the expected kind of the qualifier expression.
3142        KindSelector skind = KindSelector.NIL;
3143        if (tree.name == names._this || tree.name == names._super ||
3144                tree.name == names._class)
3145        {
3146            skind = KindSelector.TYP;
3147        } else {
3148            if (pkind().contains(KindSelector.PCK))
3149                skind = KindSelector.of(skind, KindSelector.PCK);
3150            if (pkind().contains(KindSelector.TYP))
3151                skind = KindSelector.of(skind, KindSelector.TYP, KindSelector.PCK);
3152            if (pkind().contains(KindSelector.VAL_MTH))
3153                skind = KindSelector.of(skind, KindSelector.VAL, KindSelector.TYP);
3154        }
3155
3156        // Attribute the qualifier expression, and determine its symbol (if any).
3157        Type site = attribTree(tree.selected, env, new ResultInfo(skind, Infer.anyPoly));
3158        if (!pkind().contains(KindSelector.TYP_PCK))
3159            site = capture(site); // Capture field access
3160
3161        // don't allow T.class T[].class, etc
3162        if (skind == KindSelector.TYP) {
3163            Type elt = site;
3164            while (elt.hasTag(ARRAY))
3165                elt = ((ArrayType)elt).elemtype;
3166            if (elt.hasTag(TYPEVAR)) {
3167                log.error(tree.pos(), "type.var.cant.be.deref");
3168                result = tree.type = types.createErrorType(tree.name, site.tsym, site);
3169                tree.sym = tree.type.tsym;
3170                return ;
3171            }
3172        }
3173
3174        // If qualifier symbol is a type or `super', assert `selectSuper'
3175        // for the selection. This is relevant for determining whether
3176        // protected symbols are accessible.
3177        Symbol sitesym = TreeInfo.symbol(tree.selected);
3178        boolean selectSuperPrev = env.info.selectSuper;
3179        env.info.selectSuper =
3180            sitesym != null &&
3181            sitesym.name == names._super;
3182
3183        // Determine the symbol represented by the selection.
3184        env.info.pendingResolutionPhase = null;
3185        Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
3186        if (sym.kind == VAR && sym.name != names._super && env.info.defaultSuperCallSite != null) {
3187            log.error(tree.selected.pos(), "not.encl.class", site.tsym);
3188            sym = syms.errSymbol;
3189        }
3190        if (sym.exists() && !isType(sym) && pkind().contains(KindSelector.TYP_PCK)) {
3191            site = capture(site);
3192            sym = selectSym(tree, sitesym, site, env, resultInfo);
3193        }
3194        boolean varArgs = env.info.lastResolveVarargs();
3195        tree.sym = sym;
3196
3197        if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) {
3198            while (site.hasTag(TYPEVAR)) site = site.getUpperBound();
3199            site = capture(site);
3200        }
3201
3202        // If that symbol is a variable, ...
3203        if (sym.kind == VAR) {
3204            VarSymbol v = (VarSymbol)sym;
3205
3206            // ..., evaluate its initializer, if it has one, and check for
3207            // illegal forward reference.
3208            checkInit(tree, env, v, true);
3209
3210            // If we are expecting a variable (as opposed to a value), check
3211            // that the variable is assignable in the current environment.
3212            if (KindSelector.ASG.subset(pkind()))
3213                checkAssignable(tree.pos(), v, tree.selected, env);
3214        }
3215
3216        if (sitesym != null &&
3217                sitesym.kind == VAR &&
3218                ((VarSymbol)sitesym).isResourceVariable() &&
3219                sym.kind == MTH &&
3220                sym.name.equals(names.close) &&
3221                sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) &&
3222                env.info.lint.isEnabled(LintCategory.TRY)) {
3223            log.warning(LintCategory.TRY, tree, "try.explicit.close.call");
3224        }
3225
3226        // Disallow selecting a type from an expression
3227        if (isType(sym) && (sitesym == null || !sitesym.kind.matches(KindSelector.TYP_PCK))) {
3228            tree.type = check(tree.selected, pt(),
3229                              sitesym == null ?
3230                                      KindSelector.VAL : sitesym.kind.toSelector(),
3231                              new ResultInfo(KindSelector.TYP_PCK, pt()));
3232        }
3233
3234        if (isType(sitesym)) {
3235            if (sym.name == names._this) {
3236                // If `C' is the currently compiled class, check that
3237                // C.this' does not appear in a call to a super(...)
3238                if (env.info.isSelfCall &&
3239                    site.tsym == env.enclClass.sym) {
3240                    chk.earlyRefError(tree.pos(), sym);
3241                }
3242            } else {
3243                // Check if type-qualified fields or methods are static (JLS)
3244                if ((sym.flags() & STATIC) == 0 &&
3245                    !env.next.tree.hasTag(REFERENCE) &&
3246                    sym.name != names._super &&
3247                    (sym.kind == VAR || sym.kind == MTH)) {
3248                    rs.accessBase(rs.new StaticError(sym),
3249                              tree.pos(), site, sym.name, true);
3250                }
3251            }
3252            if (!allowStaticInterfaceMethods && sitesym.isInterface() &&
3253                    sym.isStatic() && sym.kind == MTH) {
3254                log.error(tree.pos(), "static.intf.method.invoke.not.supported.in.source", sourceName);
3255            }
3256        } else if (sym.kind != ERR &&
3257                   (sym.flags() & STATIC) != 0 &&
3258                   sym.name != names._class) {
3259            // If the qualified item is not a type and the selected item is static, report
3260            // a warning. Make allowance for the class of an array type e.g. Object[].class)
3261            chk.warnStatic(tree, "static.not.qualified.by.type",
3262                           sym.kind.kindName(), sym.owner);
3263        }
3264
3265        // If we are selecting an instance member via a `super', ...
3266        if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
3267
3268            // Check that super-qualified symbols are not abstract (JLS)
3269            rs.checkNonAbstract(tree.pos(), sym);
3270
3271            if (site.isRaw()) {
3272                // Determine argument types for site.
3273                Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
3274                if (site1 != null) site = site1;
3275            }
3276        }
3277
3278        if (env.info.isSerializable) {
3279            chk.checkElemAccessFromSerializableLambda(tree);
3280        }
3281
3282        env.info.selectSuper = selectSuperPrev;
3283        result = checkId(tree, site, sym, env, resultInfo);
3284    }
3285    //where
3286        /** Determine symbol referenced by a Select expression,
3287         *
3288         *  @param tree   The select tree.
3289         *  @param site   The type of the selected expression,
3290         *  @param env    The current environment.
3291         *  @param resultInfo The current result.
3292         */
3293        private Symbol selectSym(JCFieldAccess tree,
3294                                 Symbol location,
3295                                 Type site,
3296                                 Env<AttrContext> env,
3297                                 ResultInfo resultInfo) {
3298            DiagnosticPosition pos = tree.pos();
3299            Name name = tree.name;
3300            switch (site.getTag()) {
3301            case PACKAGE:
3302                return rs.accessBase(
3303                    rs.findIdentInPackage(env, site.tsym, name, resultInfo.pkind),
3304                    pos, location, site, name, true);
3305            case ARRAY:
3306            case CLASS:
3307                if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) {
3308                    return rs.resolveQualifiedMethod(
3309                        pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
3310                } else if (name == names._this || name == names._super) {
3311                    return rs.resolveSelf(pos, env, site.tsym, name);
3312                } else if (name == names._class) {
3313                    // In this case, we have already made sure in
3314                    // visitSelect that qualifier expression is a type.
3315                    Type t = syms.classType;
3316                    List<Type> typeargs = List.of(types.erasure(site));
3317                    t = new ClassType(t.getEnclosingType(), typeargs, t.tsym);
3318                    return new VarSymbol(
3319                        STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
3320                } else {
3321                    // We are seeing a plain identifier as selector.
3322                    Symbol sym = rs.findIdentInType(env, site, name, resultInfo.pkind);
3323                        sym = rs.accessBase(sym, pos, location, site, name, true);
3324                    return sym;
3325                }
3326            case WILDCARD:
3327                throw new AssertionError(tree);
3328            case TYPEVAR:
3329                // Normally, site.getUpperBound() shouldn't be null.
3330                // It should only happen during memberEnter/attribBase
3331                // when determining the super type which *must* beac
3332                // done before attributing the type variables.  In
3333                // other words, we are seeing this illegal program:
3334                // class B<T> extends A<T.foo> {}
3335                Symbol sym = (site.getUpperBound() != null)
3336                    ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
3337                    : null;
3338                if (sym == null) {
3339                    log.error(pos, "type.var.cant.be.deref");
3340                    return syms.errSymbol;
3341                } else {
3342                    Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
3343                        rs.new AccessError(env, site, sym) :
3344                                sym;
3345                    rs.accessBase(sym2, pos, location, site, name, true);
3346                    return sym;
3347                }
3348            case ERROR:
3349                // preserve identifier names through errors
3350                return types.createErrorType(name, site.tsym, site).tsym;
3351            default:
3352                // The qualifier expression is of a primitive type -- only
3353                // .class is allowed for these.
3354                if (name == names._class) {
3355                    // In this case, we have already made sure in Select that
3356                    // qualifier expression is a type.
3357                    Type t = syms.classType;
3358                    Type arg = types.boxedClass(site).type;
3359                    t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym);
3360                    return new VarSymbol(
3361                        STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
3362                } else {
3363                    log.error(pos, "cant.deref", site);
3364                    return syms.errSymbol;
3365                }
3366            }
3367        }
3368
3369        /** Determine type of identifier or select expression and check that
3370         *  (1) the referenced symbol is not deprecated
3371         *  (2) the symbol's type is safe (@see checkSafe)
3372         *  (3) if symbol is a variable, check that its type and kind are
3373         *      compatible with the prototype and protokind.
3374         *  (4) if symbol is an instance field of a raw type,
3375         *      which is being assigned to, issue an unchecked warning if its
3376         *      type changes under erasure.
3377         *  (5) if symbol is an instance method of a raw type, issue an
3378         *      unchecked warning if its argument types change under erasure.
3379         *  If checks succeed:
3380         *    If symbol is a constant, return its constant type
3381         *    else if symbol is a method, return its result type
3382         *    otherwise return its type.
3383         *  Otherwise return errType.
3384         *
3385         *  @param tree       The syntax tree representing the identifier
3386         *  @param site       If this is a select, the type of the selected
3387         *                    expression, otherwise the type of the current class.
3388         *  @param sym        The symbol representing the identifier.
3389         *  @param env        The current environment.
3390         *  @param resultInfo    The expected result
3391         */
3392        Type checkId(JCTree tree,
3393                     Type site,
3394                     Symbol sym,
3395                     Env<AttrContext> env,
3396                     ResultInfo resultInfo) {
3397            return (resultInfo.pt.hasTag(FORALL) || resultInfo.pt.hasTag(METHOD)) ?
3398                    checkMethodId(tree, site, sym, env, resultInfo) :
3399                    checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
3400        }
3401
3402        Type checkMethodId(JCTree tree,
3403                     Type site,
3404                     Symbol sym,
3405                     Env<AttrContext> env,
3406                     ResultInfo resultInfo) {
3407            boolean isPolymorhicSignature =
3408                (sym.baseSymbol().flags() & SIGNATURE_POLYMORPHIC) != 0;
3409            return isPolymorhicSignature ?
3410                    checkSigPolyMethodId(tree, site, sym, env, resultInfo) :
3411                    checkMethodIdInternal(tree, site, sym, env, resultInfo);
3412        }
3413
3414        Type checkSigPolyMethodId(JCTree tree,
3415                     Type site,
3416                     Symbol sym,
3417                     Env<AttrContext> env,
3418                     ResultInfo resultInfo) {
3419            //recover original symbol for signature polymorphic methods
3420            checkMethodIdInternal(tree, site, sym.baseSymbol(), env, resultInfo);
3421            env.info.pendingResolutionPhase = Resolve.MethodResolutionPhase.BASIC;
3422            return sym.type;
3423        }
3424
3425        Type checkMethodIdInternal(JCTree tree,
3426                     Type site,
3427                     Symbol sym,
3428                     Env<AttrContext> env,
3429                     ResultInfo resultInfo) {
3430            if (resultInfo.pkind.contains(KindSelector.POLY)) {
3431                Type pt = resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, sym, env.info.pendingResolutionPhase));
3432                Type owntype = checkIdInternal(tree, site, sym, pt, env, resultInfo);
3433                resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
3434                return owntype;
3435            } else {
3436                return checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
3437            }
3438        }
3439
3440        Type checkIdInternal(JCTree tree,
3441                     Type site,
3442                     Symbol sym,
3443                     Type pt,
3444                     Env<AttrContext> env,
3445                     ResultInfo resultInfo) {
3446            if (pt.isErroneous()) {
3447                return types.createErrorType(site);
3448            }
3449            Type owntype; // The computed type of this identifier occurrence.
3450            switch (sym.kind) {
3451            case TYP:
3452                // For types, the computed type equals the symbol's type,
3453                // except for two situations:
3454                owntype = sym.type;
3455                if (owntype.hasTag(CLASS)) {
3456                    chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym);
3457                    Type ownOuter = owntype.getEnclosingType();
3458
3459                    // (a) If the symbol's type is parameterized, erase it
3460                    // because no type parameters were given.
3461                    // We recover generic outer type later in visitTypeApply.
3462                    if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
3463                        owntype = types.erasure(owntype);
3464                    }
3465
3466                    // (b) If the symbol's type is an inner class, then
3467                    // we have to interpret its outer type as a superclass
3468                    // of the site type. Example:
3469                    //
3470                    // class Tree<A> { class Visitor { ... } }
3471                    // class PointTree extends Tree<Point> { ... }
3472                    // ...PointTree.Visitor...
3473                    //
3474                    // Then the type of the last expression above is
3475                    // Tree<Point>.Visitor.
3476                    else if (ownOuter.hasTag(CLASS) && site != ownOuter) {
3477                        Type normOuter = site;
3478                        if (normOuter.hasTag(CLASS)) {
3479                            normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
3480                        }
3481                        if (normOuter == null) // perhaps from an import
3482                            normOuter = types.erasure(ownOuter);
3483                        if (normOuter != ownOuter)
3484                            owntype = new ClassType(
3485                                normOuter, List.<Type>nil(), owntype.tsym,
3486                                owntype.getMetadata());
3487                    }
3488                }
3489                break;
3490            case VAR:
3491                VarSymbol v = (VarSymbol)sym;
3492                // Test (4): if symbol is an instance field of a raw type,
3493                // which is being assigned to, issue an unchecked warning if
3494                // its type changes under erasure.
3495                if (KindSelector.ASG.subset(pkind()) &&
3496                    v.owner.kind == TYP &&
3497                    (v.flags() & STATIC) == 0 &&
3498                    (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
3499                    Type s = types.asOuterSuper(site, v.owner);
3500                    if (s != null &&
3501                        s.isRaw() &&
3502                        !types.isSameType(v.type, v.erasure(types))) {
3503                        chk.warnUnchecked(tree.pos(),
3504                                          "unchecked.assign.to.var",
3505                                          v, s);
3506                    }
3507                }
3508                // The computed type of a variable is the type of the
3509                // variable symbol, taken as a member of the site type.
3510                owntype = (sym.owner.kind == TYP &&
3511                           sym.name != names._this && sym.name != names._super)
3512                    ? types.memberType(site, sym)
3513                    : sym.type;
3514
3515                // If the variable is a constant, record constant value in
3516                // computed type.
3517                if (v.getConstValue() != null && isStaticReference(tree))
3518                    owntype = owntype.constType(v.getConstValue());
3519
3520                if (resultInfo.pkind == KindSelector.VAL) {
3521                    owntype = capture(owntype); // capture "names as expressions"
3522                }
3523                break;
3524            case MTH: {
3525                owntype = checkMethod(site, sym,
3526                        new ResultInfo(resultInfo.pkind, resultInfo.pt.getReturnType(), resultInfo.checkContext),
3527                        env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(),
3528                        resultInfo.pt.getTypeArguments());
3529                break;
3530            }
3531            case PCK: case ERR:
3532                owntype = sym.type;
3533                break;
3534            default:
3535                throw new AssertionError("unexpected kind: " + sym.kind +
3536                                         " in tree " + tree);
3537            }
3538
3539            // Test (1): emit a `deprecation' warning if symbol is deprecated.
3540            // (for constructors, the error was given when the constructor was
3541            // resolved)
3542
3543            if (sym.name != names.init) {
3544                chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym);
3545                chk.checkSunAPI(tree.pos(), sym);
3546                chk.checkProfile(tree.pos(), sym);
3547            }
3548
3549            // Test (3): if symbol is a variable, check that its type and
3550            // kind are compatible with the prototype and protokind.
3551            return check(tree, owntype, sym.kind.toSelector(), resultInfo);
3552        }
3553
3554        /** Check that variable is initialized and evaluate the variable's
3555         *  initializer, if not yet done. Also check that variable is not
3556         *  referenced before it is defined.
3557         *  @param tree    The tree making up the variable reference.
3558         *  @param env     The current environment.
3559         *  @param v       The variable's symbol.
3560         */
3561        private void checkInit(JCTree tree,
3562                               Env<AttrContext> env,
3563                               VarSymbol v,
3564                               boolean onlyWarning) {
3565//          System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " +
3566//                             tree.pos + " " + v.pos + " " +
3567//                             Resolve.isStatic(env));//DEBUG
3568
3569            // A forward reference is diagnosed if the declaration position
3570            // of the variable is greater than the current tree position
3571            // and the tree and variable definition occur in the same class
3572            // definition.  Note that writes don't count as references.
3573            // This check applies only to class and instance
3574            // variables.  Local variables follow different scope rules,
3575            // and are subject to definite assignment checking.
3576            if ((env.info.enclVar == v || v.pos > tree.pos) &&
3577                v.owner.kind == TYP &&
3578                enclosingInitEnv(env) != null &&
3579                v.owner == env.info.scope.owner.enclClass() &&
3580                ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
3581                (!env.tree.hasTag(ASSIGN) ||
3582                 TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
3583                String suffix = (env.info.enclVar == v) ?
3584                                "self.ref" : "forward.ref";
3585                if (!onlyWarning || isStaticEnumField(v)) {
3586                    log.error(tree.pos(), "illegal." + suffix);
3587                } else if (useBeforeDeclarationWarning) {
3588                    log.warning(tree.pos(), suffix, v);
3589                }
3590            }
3591
3592            v.getConstValue(); // ensure initializer is evaluated
3593
3594            checkEnumInitializer(tree, env, v);
3595        }
3596
3597        /**
3598         * Returns the enclosing init environment associated with this env (if any). An init env
3599         * can be either a field declaration env or a static/instance initializer env.
3600         */
3601        Env<AttrContext> enclosingInitEnv(Env<AttrContext> env) {
3602            while (true) {
3603                switch (env.tree.getTag()) {
3604                    case VARDEF:
3605                        JCVariableDecl vdecl = (JCVariableDecl)env.tree;
3606                        if (vdecl.sym.owner.kind == TYP) {
3607                            //field
3608                            return env;
3609                        }
3610                        break;
3611                    case BLOCK:
3612                        if (env.next.tree.hasTag(CLASSDEF)) {
3613                            //instance/static initializer
3614                            return env;
3615                        }
3616                        break;
3617                    case METHODDEF:
3618                    case CLASSDEF:
3619                    case TOPLEVEL:
3620                        return null;
3621                }
3622                Assert.checkNonNull(env.next);
3623                env = env.next;
3624            }
3625        }
3626
3627        /**
3628         * Check for illegal references to static members of enum.  In
3629         * an enum type, constructors and initializers may not
3630         * reference its static members unless they are constant.
3631         *
3632         * @param tree    The tree making up the variable reference.
3633         * @param env     The current environment.
3634         * @param v       The variable's symbol.
3635         * @jls  section 8.9 Enums
3636         */
3637        private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
3638            // JLS:
3639            //
3640            // "It is a compile-time error to reference a static field
3641            // of an enum type that is not a compile-time constant
3642            // (15.28) from constructors, instance initializer blocks,
3643            // or instance variable initializer expressions of that
3644            // type. It is a compile-time error for the constructors,
3645            // instance initializer blocks, or instance variable
3646            // initializer expressions of an enum constant e to refer
3647            // to itself or to an enum constant of the same type that
3648            // is declared to the right of e."
3649            if (isStaticEnumField(v)) {
3650                ClassSymbol enclClass = env.info.scope.owner.enclClass();
3651
3652                if (enclClass == null || enclClass.owner == null)
3653                    return;
3654
3655                // See if the enclosing class is the enum (or a
3656                // subclass thereof) declaring v.  If not, this
3657                // reference is OK.
3658                if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
3659                    return;
3660
3661                // If the reference isn't from an initializer, then
3662                // the reference is OK.
3663                if (!Resolve.isInitializer(env))
3664                    return;
3665
3666                log.error(tree.pos(), "illegal.enum.static.ref");
3667            }
3668        }
3669
3670        /** Is the given symbol a static, non-constant field of an Enum?
3671         *  Note: enum literals should not be regarded as such
3672         */
3673        private boolean isStaticEnumField(VarSymbol v) {
3674            return Flags.isEnum(v.owner) &&
3675                   Flags.isStatic(v) &&
3676                   !Flags.isConstant(v) &&
3677                   v.name != names._class;
3678        }
3679
3680    Warner noteWarner = new Warner();
3681
3682    /**
3683     * Check that method arguments conform to its instantiation.
3684     **/
3685    public Type checkMethod(Type site,
3686                            final Symbol sym,
3687                            ResultInfo resultInfo,
3688                            Env<AttrContext> env,
3689                            final List<JCExpression> argtrees,
3690                            List<Type> argtypes,
3691                            List<Type> typeargtypes) {
3692        // Test (5): if symbol is an instance method of a raw type, issue
3693        // an unchecked warning if its argument types change under erasure.
3694        if ((sym.flags() & STATIC) == 0 &&
3695            (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
3696            Type s = types.asOuterSuper(site, sym.owner);
3697            if (s != null && s.isRaw() &&
3698                !types.isSameTypes(sym.type.getParameterTypes(),
3699                                   sym.erasure(types).getParameterTypes())) {
3700                chk.warnUnchecked(env.tree.pos(),
3701                                  "unchecked.call.mbr.of.raw.type",
3702                                  sym, s);
3703            }
3704        }
3705
3706        if (env.info.defaultSuperCallSite != null) {
3707            for (Type sup : types.interfaces(env.enclClass.type).prepend(types.supertype((env.enclClass.type)))) {
3708                if (!sup.tsym.isSubClass(sym.enclClass(), types) ||
3709                        types.isSameType(sup, env.info.defaultSuperCallSite)) continue;
3710                List<MethodSymbol> icand_sup =
3711                        types.interfaceCandidates(sup, (MethodSymbol)sym);
3712                if (icand_sup.nonEmpty() &&
3713                        icand_sup.head != sym &&
3714                        icand_sup.head.overrides(sym, icand_sup.head.enclClass(), types, true)) {
3715                    log.error(env.tree.pos(), "illegal.default.super.call", env.info.defaultSuperCallSite,
3716                        diags.fragment("overridden.default", sym, sup));
3717                    break;
3718                }
3719            }
3720            env.info.defaultSuperCallSite = null;
3721        }
3722
3723        if (sym.isStatic() && site.isInterface() && env.tree.hasTag(APPLY)) {
3724            JCMethodInvocation app = (JCMethodInvocation)env.tree;
3725            if (app.meth.hasTag(SELECT) &&
3726                    !TreeInfo.isStaticSelector(((JCFieldAccess)app.meth).selected, names)) {
3727                log.error(env.tree.pos(), "illegal.static.intf.meth.call", site);
3728            }
3729        }
3730
3731        // Compute the identifier's instantiated type.
3732        // For methods, we need to compute the instance type by
3733        // Resolve.instantiate from the symbol's type as well as
3734        // any type arguments and value arguments.
3735        noteWarner.clear();
3736        try {
3737            Type owntype = rs.checkMethod(
3738                    env,
3739                    site,
3740                    sym,
3741                    resultInfo,
3742                    argtypes,
3743                    typeargtypes,
3744                    noteWarner);
3745
3746            DeferredAttr.DeferredTypeMap checkDeferredMap =
3747                deferredAttr.new DeferredTypeMap(DeferredAttr.AttrMode.CHECK, sym, env.info.pendingResolutionPhase);
3748
3749            argtypes = Type.map(argtypes, checkDeferredMap);
3750
3751            if (noteWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
3752                chk.warnUnchecked(env.tree.pos(),
3753                        "unchecked.meth.invocation.applied",
3754                        kindName(sym),
3755                        sym.name,
3756                        rs.methodArguments(sym.type.getParameterTypes()),
3757                        rs.methodArguments(Type.map(argtypes, checkDeferredMap)),
3758                        kindName(sym.location()),
3759                        sym.location());
3760               owntype = new MethodType(owntype.getParameterTypes(),
3761                       types.erasure(owntype.getReturnType()),
3762                       types.erasure(owntype.getThrownTypes()),
3763                       syms.methodClass);
3764            }
3765
3766            return chk.checkMethod(owntype, sym, env, argtrees, argtypes, env.info.lastResolveVarargs(),
3767                    resultInfo.checkContext.inferenceContext());
3768        } catch (Infer.InferenceException ex) {
3769            //invalid target type - propagate exception outwards or report error
3770            //depending on the current check context
3771            resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic());
3772            return types.createErrorType(site);
3773        } catch (Resolve.InapplicableMethodException ex) {
3774            final JCDiagnostic diag = ex.getDiagnostic();
3775            Resolve.InapplicableSymbolError errSym = rs.new InapplicableSymbolError(null) {
3776                @Override
3777                protected Pair<Symbol, JCDiagnostic> errCandidate() {
3778                    return new Pair<>(sym, diag);
3779                }
3780            };
3781            List<Type> argtypes2 = Type.map(argtypes,
3782                    rs.new ResolveDeferredRecoveryMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
3783            JCDiagnostic errDiag = errSym.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
3784                    env.tree, sym, site, sym.name, argtypes2, typeargtypes);
3785            log.report(errDiag);
3786            return types.createErrorType(site);
3787        }
3788    }
3789
3790    public void visitLiteral(JCLiteral tree) {
3791        result = check(tree, litType(tree.typetag).constType(tree.value),
3792                KindSelector.VAL, resultInfo);
3793    }
3794    //where
3795    /** Return the type of a literal with given type tag.
3796     */
3797    Type litType(TypeTag tag) {
3798        return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()];
3799    }
3800
3801    public void visitTypeIdent(JCPrimitiveTypeTree tree) {
3802        result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], KindSelector.TYP, resultInfo);
3803    }
3804
3805    public void visitTypeArray(JCArrayTypeTree tree) {
3806        Type etype = attribType(tree.elemtype, env);
3807        Type type = new ArrayType(etype, syms.arrayClass);
3808        result = check(tree, type, KindSelector.TYP, resultInfo);
3809    }
3810
3811    /** Visitor method for parameterized types.
3812     *  Bound checking is left until later, since types are attributed
3813     *  before supertype structure is completely known
3814     */
3815    public void visitTypeApply(JCTypeApply tree) {
3816        Type owntype = types.createErrorType(tree.type);
3817
3818        // Attribute functor part of application and make sure it's a class.
3819        Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
3820
3821        // Attribute type parameters
3822        List<Type> actuals = attribTypes(tree.arguments, env);
3823
3824        if (clazztype.hasTag(CLASS)) {
3825            List<Type> formals = clazztype.tsym.type.getTypeArguments();
3826            if (actuals.isEmpty()) //diamond
3827                actuals = formals;
3828
3829            if (actuals.length() == formals.length()) {
3830                List<Type> a = actuals;
3831                List<Type> f = formals;
3832                while (a.nonEmpty()) {
3833                    a.head = a.head.withTypeVar(f.head);
3834                    a = a.tail;
3835                    f = f.tail;
3836                }
3837                // Compute the proper generic outer
3838                Type clazzOuter = clazztype.getEnclosingType();
3839                if (clazzOuter.hasTag(CLASS)) {
3840                    Type site;
3841                    JCExpression clazz = TreeInfo.typeIn(tree.clazz);
3842                    if (clazz.hasTag(IDENT)) {
3843                        site = env.enclClass.sym.type;
3844                    } else if (clazz.hasTag(SELECT)) {
3845                        site = ((JCFieldAccess) clazz).selected.type;
3846                    } else throw new AssertionError(""+tree);
3847                    if (clazzOuter.hasTag(CLASS) && site != clazzOuter) {
3848                        if (site.hasTag(CLASS))
3849                            site = types.asOuterSuper(site, clazzOuter.tsym);
3850                        if (site == null)
3851                            site = types.erasure(clazzOuter);
3852                        clazzOuter = site;
3853                    }
3854                }
3855                owntype = new ClassType(clazzOuter, actuals, clazztype.tsym,
3856                                        clazztype.getMetadata());
3857            } else {
3858                if (formals.length() != 0) {
3859                    log.error(tree.pos(), "wrong.number.type.args",
3860                              Integer.toString(formals.length()));
3861                } else {
3862                    log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym);
3863                }
3864                owntype = types.createErrorType(tree.type);
3865            }
3866        }
3867        result = check(tree, owntype, KindSelector.TYP, resultInfo);
3868    }
3869
3870    public void visitTypeUnion(JCTypeUnion tree) {
3871        ListBuffer<Type> multicatchTypes = new ListBuffer<>();
3872        ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
3873        for (JCExpression typeTree : tree.alternatives) {
3874            Type ctype = attribType(typeTree, env);
3875            ctype = chk.checkType(typeTree.pos(),
3876                          chk.checkClassType(typeTree.pos(), ctype),
3877                          syms.throwableType);
3878            if (!ctype.isErroneous()) {
3879                //check that alternatives of a union type are pairwise
3880                //unrelated w.r.t. subtyping
3881                if (chk.intersects(ctype,  multicatchTypes.toList())) {
3882                    for (Type t : multicatchTypes) {
3883                        boolean sub = types.isSubtype(ctype, t);
3884                        boolean sup = types.isSubtype(t, ctype);
3885                        if (sub || sup) {
3886                            //assume 'a' <: 'b'
3887                            Type a = sub ? ctype : t;
3888                            Type b = sub ? t : ctype;
3889                            log.error(typeTree.pos(), "multicatch.types.must.be.disjoint", a, b);
3890                        }
3891                    }
3892                }
3893                multicatchTypes.append(ctype);
3894                if (all_multicatchTypes != null)
3895                    all_multicatchTypes.append(ctype);
3896            } else {
3897                if (all_multicatchTypes == null) {
3898                    all_multicatchTypes = new ListBuffer<>();
3899                    all_multicatchTypes.appendList(multicatchTypes);
3900                }
3901                all_multicatchTypes.append(ctype);
3902            }
3903        }
3904        Type t = check(noCheckTree, types.lub(multicatchTypes.toList()),
3905                KindSelector.TYP, resultInfo);
3906        if (t.hasTag(CLASS)) {
3907            List<Type> alternatives =
3908                ((all_multicatchTypes == null) ? multicatchTypes : all_multicatchTypes).toList();
3909            t = new UnionClassType((ClassType) t, alternatives);
3910        }
3911        tree.type = result = t;
3912    }
3913
3914    public void visitTypeIntersection(JCTypeIntersection tree) {
3915        attribTypes(tree.bounds, env);
3916        tree.type = result = checkIntersection(tree, tree.bounds);
3917    }
3918
3919    public void visitTypeParameter(JCTypeParameter tree) {
3920        TypeVar typeVar = (TypeVar) tree.type;
3921
3922        if (tree.annotations != null && tree.annotations.nonEmpty()) {
3923            annotateType(tree, tree.annotations);
3924        }
3925
3926        if (!typeVar.bound.isErroneous()) {
3927            //fixup type-parameter bound computed in 'attribTypeVariables'
3928            typeVar.bound = checkIntersection(tree, tree.bounds);
3929        }
3930    }
3931
3932    Type checkIntersection(JCTree tree, List<JCExpression> bounds) {
3933        Set<Type> boundSet = new HashSet<>();
3934        if (bounds.nonEmpty()) {
3935            // accept class or interface or typevar as first bound.
3936            bounds.head.type = checkBase(bounds.head.type, bounds.head, env, false, false, false);
3937            boundSet.add(types.erasure(bounds.head.type));
3938            if (bounds.head.type.isErroneous()) {
3939                return bounds.head.type;
3940            }
3941            else if (bounds.head.type.hasTag(TYPEVAR)) {
3942                // if first bound was a typevar, do not accept further bounds.
3943                if (bounds.tail.nonEmpty()) {
3944                    log.error(bounds.tail.head.pos(),
3945                              "type.var.may.not.be.followed.by.other.bounds");
3946                    return bounds.head.type;
3947                }
3948            } else {
3949                // if first bound was a class or interface, accept only interfaces
3950                // as further bounds.
3951                for (JCExpression bound : bounds.tail) {
3952                    bound.type = checkBase(bound.type, bound, env, false, true, false);
3953                    if (bound.type.isErroneous()) {
3954                        bounds = List.of(bound);
3955                    }
3956                    else if (bound.type.hasTag(CLASS)) {
3957                        chk.checkNotRepeated(bound.pos(), types.erasure(bound.type), boundSet);
3958                    }
3959                }
3960            }
3961        }
3962
3963        if (bounds.length() == 0) {
3964            return syms.objectType;
3965        } else if (bounds.length() == 1) {
3966            return bounds.head.type;
3967        } else {
3968            Type owntype = types.makeCompoundType(TreeInfo.types(bounds));
3969            // ... the variable's bound is a class type flagged COMPOUND
3970            // (see comment for TypeVar.bound).
3971            // In this case, generate a class tree that represents the
3972            // bound class, ...
3973            JCExpression extending;
3974            List<JCExpression> implementing;
3975            if (!bounds.head.type.isInterface()) {
3976                extending = bounds.head;
3977                implementing = bounds.tail;
3978            } else {
3979                extending = null;
3980                implementing = bounds;
3981            }
3982            JCClassDecl cd = make.at(tree).ClassDef(
3983                make.Modifiers(PUBLIC | ABSTRACT),
3984                names.empty, List.<JCTypeParameter>nil(),
3985                extending, implementing, List.<JCTree>nil());
3986
3987            ClassSymbol c = (ClassSymbol)owntype.tsym;
3988            Assert.check((c.flags() & COMPOUND) != 0);
3989            cd.sym = c;
3990            c.sourcefile = env.toplevel.sourcefile;
3991
3992            // ... and attribute the bound class
3993            c.flags_field |= UNATTRIBUTED;
3994            Env<AttrContext> cenv = enter.classEnv(cd, env);
3995            typeEnvs.put(c, cenv);
3996            attribClass(c);
3997            return owntype;
3998        }
3999    }
4000
4001    public void visitWildcard(JCWildcard tree) {
4002        //- System.err.println("visitWildcard("+tree+");");//DEBUG
4003        Type type = (tree.kind.kind == BoundKind.UNBOUND)
4004            ? syms.objectType
4005            : attribType(tree.inner, env);
4006        result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
4007                                              tree.kind.kind,
4008                                              syms.boundClass),
4009                KindSelector.TYP, resultInfo);
4010    }
4011
4012    public void visitAnnotation(JCAnnotation tree) {
4013        Assert.error("should be handled in Annotate");
4014    }
4015
4016    public void visitAnnotatedType(JCAnnotatedType tree) {
4017        Type underlyingType = attribType(tree.getUnderlyingType(), env);
4018        this.attribAnnotationTypes(tree.annotations, env);
4019        annotateType(tree, tree.annotations);
4020        result = tree.type = underlyingType;
4021    }
4022
4023    /**
4024     * Apply the annotations to the particular type.
4025     */
4026    public void annotateType(final JCTree tree, final List<JCAnnotation> annotations) {
4027        annotate.typeAnnotation(new Annotate.Worker() {
4028            @Override
4029            public String toString() {
4030                return "annotate " + annotations + " onto " + tree;
4031            }
4032            @Override
4033            public void run() {
4034                List<Attribute.TypeCompound> compounds = fromAnnotations(annotations);
4035                Assert.check(annotations.size() == compounds.size());
4036                tree.type = tree.type.annotatedType(compounds);
4037                }
4038        });
4039    }
4040
4041    private static List<Attribute.TypeCompound> fromAnnotations(List<JCAnnotation> annotations) {
4042        if (annotations.isEmpty()) {
4043            return List.nil();
4044        }
4045
4046        ListBuffer<Attribute.TypeCompound> buf = new ListBuffer<>();
4047        for (JCAnnotation anno : annotations) {
4048            Assert.checkNonNull(anno.attribute);
4049            buf.append((Attribute.TypeCompound) anno.attribute);
4050        }
4051        return buf.toList();
4052    }
4053
4054    public void visitErroneous(JCErroneous tree) {
4055        if (tree.errs != null)
4056            for (JCTree err : tree.errs)
4057                attribTree(err, env, new ResultInfo(KindSelector.ERR, pt()));
4058        result = tree.type = syms.errType;
4059    }
4060
4061    /** Default visitor method for all other trees.
4062     */
4063    public void visitTree(JCTree tree) {
4064        throw new AssertionError();
4065    }
4066
4067    /**
4068     * Attribute an env for either a top level tree or class declaration.
4069     */
4070    public void attrib(Env<AttrContext> env) {
4071        if (env.tree.hasTag(TOPLEVEL))
4072            attribTopLevel(env);
4073        else
4074            attribClass(env.tree.pos(), env.enclClass.sym);
4075    }
4076
4077    /**
4078     * Attribute a top level tree. These trees are encountered when the
4079     * package declaration has annotations.
4080     */
4081    public void attribTopLevel(Env<AttrContext> env) {
4082        JCCompilationUnit toplevel = env.toplevel;
4083        try {
4084            annotate.flush();
4085        } catch (CompletionFailure ex) {
4086            chk.completionError(toplevel.pos(), ex);
4087        }
4088    }
4089
4090    /** Main method: attribute class definition associated with given class symbol.
4091     *  reporting completion failures at the given position.
4092     *  @param pos The source position at which completion errors are to be
4093     *             reported.
4094     *  @param c   The class symbol whose definition will be attributed.
4095     */
4096    public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
4097        try {
4098            annotate.flush();
4099            attribClass(c);
4100        } catch (CompletionFailure ex) {
4101            chk.completionError(pos, ex);
4102        }
4103    }
4104
4105    /** Attribute class definition associated with given class symbol.
4106     *  @param c   The class symbol whose definition will be attributed.
4107     */
4108    void attribClass(ClassSymbol c) throws CompletionFailure {
4109        if (c.type.hasTag(ERROR)) return;
4110
4111        // Check for cycles in the inheritance graph, which can arise from
4112        // ill-formed class files.
4113        chk.checkNonCyclic(null, c.type);
4114
4115        Type st = types.supertype(c.type);
4116        if ((c.flags_field & Flags.COMPOUND) == 0) {
4117            // First, attribute superclass.
4118            if (st.hasTag(CLASS))
4119                attribClass((ClassSymbol)st.tsym);
4120
4121            // Next attribute owner, if it is a class.
4122            if (c.owner.kind == TYP && c.owner.type.hasTag(CLASS))
4123                attribClass((ClassSymbol)c.owner);
4124        }
4125
4126        // The previous operations might have attributed the current class
4127        // if there was a cycle. So we test first whether the class is still
4128        // UNATTRIBUTED.
4129        if ((c.flags_field & UNATTRIBUTED) != 0) {
4130            c.flags_field &= ~UNATTRIBUTED;
4131
4132            // Get environment current at the point of class definition.
4133            Env<AttrContext> env = typeEnvs.get(c);
4134
4135            // The info.lint field in the envs stored in typeEnvs is deliberately uninitialized,
4136            // because the annotations were not available at the time the env was created. Therefore,
4137            // we look up the environment chain for the first enclosing environment for which the
4138            // lint value is set. Typically, this is the parent env, but might be further if there
4139            // are any envs created as a result of TypeParameter nodes.
4140            Env<AttrContext> lintEnv = env;
4141            while (lintEnv.info.lint == null)
4142                lintEnv = lintEnv.next;
4143
4144            // Having found the enclosing lint value, we can initialize the lint value for this class
4145            env.info.lint = lintEnv.info.lint.augment(c);
4146
4147            Lint prevLint = chk.setLint(env.info.lint);
4148            JavaFileObject prev = log.useSource(c.sourcefile);
4149            ResultInfo prevReturnRes = env.info.returnResult;
4150
4151            try {
4152                deferredLintHandler.flush(env.tree);
4153                env.info.returnResult = null;
4154                // java.lang.Enum may not be subclassed by a non-enum
4155                if (st.tsym == syms.enumSym &&
4156                    ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
4157                    log.error(env.tree.pos(), "enum.no.subclassing");
4158
4159                // Enums may not be extended by source-level classes
4160                if (st.tsym != null &&
4161                    ((st.tsym.flags_field & Flags.ENUM) != 0) &&
4162                    ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
4163                    log.error(env.tree.pos(), "enum.types.not.extensible");
4164                }
4165
4166                if (isSerializable(c.type)) {
4167                    env.info.isSerializable = true;
4168                }
4169
4170                attribClassBody(env, c);
4171
4172                chk.checkDeprecatedAnnotation(env.tree.pos(), c);
4173                chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
4174                chk.checkFunctionalInterface((JCClassDecl) env.tree, c);
4175            } finally {
4176                env.info.returnResult = prevReturnRes;
4177                log.useSource(prev);
4178                chk.setLint(prevLint);
4179            }
4180
4181        }
4182    }
4183
4184    public void visitImport(JCImport tree) {
4185        // nothing to do
4186    }
4187
4188    /** Finish the attribution of a class. */
4189    private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
4190        JCClassDecl tree = (JCClassDecl)env.tree;
4191        Assert.check(c == tree.sym);
4192
4193        // Validate type parameters, supertype and interfaces.
4194        attribStats(tree.typarams, env);
4195        if (!c.isAnonymous()) {
4196            //already checked if anonymous
4197            chk.validate(tree.typarams, env);
4198            chk.validate(tree.extending, env);
4199            chk.validate(tree.implementing, env);
4200        }
4201
4202        // If this is a non-abstract class, check that it has no abstract
4203        // methods or unimplemented methods of an implemented interface.
4204        if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
4205            if (!relax)
4206                chk.checkAllDefined(tree.pos(), c);
4207        }
4208
4209        if ((c.flags() & ANNOTATION) != 0) {
4210            if (tree.implementing.nonEmpty())
4211                log.error(tree.implementing.head.pos(),
4212                          "cant.extend.intf.annotation");
4213            if (tree.typarams.nonEmpty())
4214                log.error(tree.typarams.head.pos(),
4215                          "intf.annotation.cant.have.type.params");
4216
4217            // If this annotation has a @Repeatable, validate
4218            Attribute.Compound repeatable = c.attribute(syms.repeatableType.tsym);
4219            if (repeatable != null) {
4220                // get diagnostic position for error reporting
4221                DiagnosticPosition cbPos = getDiagnosticPosition(tree, repeatable.type);
4222                Assert.checkNonNull(cbPos);
4223
4224                chk.validateRepeatable(c, repeatable, cbPos);
4225            }
4226        } else {
4227            // Check that all extended classes and interfaces
4228            // are compatible (i.e. no two define methods with same arguments
4229            // yet different return types).  (JLS 8.4.6.3)
4230            chk.checkCompatibleSupertypes(tree.pos(), c.type);
4231            if (allowDefaultMethods) {
4232                chk.checkDefaultMethodClashes(tree.pos(), c.type);
4233            }
4234        }
4235
4236        // Check that class does not import the same parameterized interface
4237        // with two different argument lists.
4238        chk.checkClassBounds(tree.pos(), c.type);
4239
4240        tree.type = c.type;
4241
4242        for (List<JCTypeParameter> l = tree.typarams;
4243             l.nonEmpty(); l = l.tail) {
4244             Assert.checkNonNull(env.info.scope.findFirst(l.head.name));
4245        }
4246
4247        // Check that a generic class doesn't extend Throwable
4248        if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
4249            log.error(tree.extending.pos(), "generic.throwable");
4250
4251        // Check that all methods which implement some
4252        // method conform to the method they implement.
4253        chk.checkImplementations(tree);
4254
4255        //check that a resource implementing AutoCloseable cannot throw InterruptedException
4256        checkAutoCloseable(tree.pos(), env, c.type);
4257
4258        for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
4259            // Attribute declaration
4260            attribStat(l.head, env);
4261            // Check that declarations in inner classes are not static (JLS 8.1.2)
4262            // Make an exception for static constants.
4263            if (c.owner.kind != PCK &&
4264                ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
4265                (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
4266                Symbol sym = null;
4267                if (l.head.hasTag(VARDEF)) sym = ((JCVariableDecl) l.head).sym;
4268                if (sym == null ||
4269                    sym.kind != VAR ||
4270                    ((VarSymbol) sym).getConstValue() == null)
4271                    log.error(l.head.pos(), "icls.cant.have.static.decl", c);
4272            }
4273        }
4274
4275        // Check for cycles among non-initial constructors.
4276        chk.checkCyclicConstructors(tree);
4277
4278        // Check for cycles among annotation elements.
4279        chk.checkNonCyclicElements(tree);
4280
4281        // Check for proper use of serialVersionUID
4282        if (env.info.lint.isEnabled(LintCategory.SERIAL) &&
4283            isSerializable(c.type) &&
4284            (c.flags() & Flags.ENUM) == 0 &&
4285            checkForSerial(c)) {
4286            checkSerialVersionUID(tree, c);
4287        }
4288        if (allowTypeAnnos) {
4289            // Correctly organize the postions of the type annotations
4290            typeAnnotations.organizeTypeAnnotationsBodies(tree);
4291
4292            // Check type annotations applicability rules
4293            validateTypeAnnotations(tree, false);
4294        }
4295    }
4296        // where
4297        boolean checkForSerial(ClassSymbol c) {
4298            if ((c.flags() & ABSTRACT) == 0) {
4299                return true;
4300            } else {
4301                return c.members().anyMatch(anyNonAbstractOrDefaultMethod);
4302            }
4303        }
4304
4305        public static final Filter<Symbol> anyNonAbstractOrDefaultMethod = new Filter<Symbol>() {
4306            @Override
4307            public boolean accepts(Symbol s) {
4308                return s.kind == MTH &&
4309                       (s.flags() & (DEFAULT | ABSTRACT)) != ABSTRACT;
4310            }
4311        };
4312
4313        /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
4314        private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
4315            for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
4316                if (types.isSameType(al.head.annotationType.type, t))
4317                    return al.head.pos();
4318            }
4319
4320            return null;
4321        }
4322
4323        /** check if a type is a subtype of Serializable, if that is available. */
4324        boolean isSerializable(Type t) {
4325            try {
4326                syms.serializableType.complete();
4327            }
4328            catch (CompletionFailure e) {
4329                return false;
4330            }
4331            return types.isSubtype(t, syms.serializableType);
4332        }
4333
4334        /** Check that an appropriate serialVersionUID member is defined. */
4335        private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
4336
4337            // check for presence of serialVersionUID
4338            VarSymbol svuid = null;
4339            for (Symbol sym : c.members().getSymbolsByName(names.serialVersionUID)) {
4340                if (sym.kind == VAR) {
4341                    svuid = (VarSymbol)sym;
4342                    break;
4343                }
4344            }
4345
4346            if (svuid == null) {
4347                log.warning(LintCategory.SERIAL,
4348                        tree.pos(), "missing.SVUID", c);
4349                return;
4350            }
4351
4352            // check that it is static final
4353            if ((svuid.flags() & (STATIC | FINAL)) !=
4354                (STATIC | FINAL))
4355                log.warning(LintCategory.SERIAL,
4356                        TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c);
4357
4358            // check that it is long
4359            else if (!svuid.type.hasTag(LONG))
4360                log.warning(LintCategory.SERIAL,
4361                        TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c);
4362
4363            // check constant
4364            else if (svuid.getConstValue() == null)
4365                log.warning(LintCategory.SERIAL,
4366                        TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c);
4367        }
4368
4369    private Type capture(Type type) {
4370        return types.capture(type);
4371    }
4372
4373    public void validateTypeAnnotations(JCTree tree, boolean sigOnly) {
4374        tree.accept(new TypeAnnotationsValidator(sigOnly));
4375    }
4376    //where
4377    private final class TypeAnnotationsValidator extends TreeScanner {
4378
4379        private final boolean sigOnly;
4380        public TypeAnnotationsValidator(boolean sigOnly) {
4381            this.sigOnly = sigOnly;
4382        }
4383
4384        public void visitAnnotation(JCAnnotation tree) {
4385            chk.validateTypeAnnotation(tree, false);
4386            super.visitAnnotation(tree);
4387        }
4388        public void visitAnnotatedType(JCAnnotatedType tree) {
4389            if (!tree.underlyingType.type.isErroneous()) {
4390                super.visitAnnotatedType(tree);
4391            }
4392        }
4393        public void visitTypeParameter(JCTypeParameter tree) {
4394            chk.validateTypeAnnotations(tree.annotations, true);
4395            scan(tree.bounds);
4396            // Don't call super.
4397            // This is needed because above we call validateTypeAnnotation with
4398            // false, which would forbid annotations on type parameters.
4399            // super.visitTypeParameter(tree);
4400        }
4401        public void visitMethodDef(JCMethodDecl tree) {
4402            if (tree.recvparam != null &&
4403                    !tree.recvparam.vartype.type.isErroneous()) {
4404                checkForDeclarationAnnotations(tree.recvparam.mods.annotations,
4405                        tree.recvparam.vartype.type.tsym);
4406            }
4407            if (tree.restype != null && tree.restype.type != null) {
4408                validateAnnotatedType(tree.restype, tree.restype.type);
4409            }
4410            if (sigOnly) {
4411                scan(tree.mods);
4412                scan(tree.restype);
4413                scan(tree.typarams);
4414                scan(tree.recvparam);
4415                scan(tree.params);
4416                scan(tree.thrown);
4417            } else {
4418                scan(tree.defaultValue);
4419                scan(tree.body);
4420            }
4421        }
4422        public void visitVarDef(final JCVariableDecl tree) {
4423            //System.err.println("validateTypeAnnotations.visitVarDef " + tree);
4424            if (tree.sym != null && tree.sym.type != null)
4425                validateAnnotatedType(tree.vartype, tree.sym.type);
4426            scan(tree.mods);
4427            scan(tree.vartype);
4428            if (!sigOnly) {
4429                scan(tree.init);
4430            }
4431        }
4432        public void visitTypeCast(JCTypeCast tree) {
4433            if (tree.clazz != null && tree.clazz.type != null)
4434                validateAnnotatedType(tree.clazz, tree.clazz.type);
4435            super.visitTypeCast(tree);
4436        }
4437        public void visitTypeTest(JCInstanceOf tree) {
4438            if (tree.clazz != null && tree.clazz.type != null)
4439                validateAnnotatedType(tree.clazz, tree.clazz.type);
4440            super.visitTypeTest(tree);
4441        }
4442        public void visitNewClass(JCNewClass tree) {
4443            if (tree.clazz != null && tree.clazz.type != null) {
4444                if (tree.clazz.hasTag(ANNOTATED_TYPE)) {
4445                    checkForDeclarationAnnotations(((JCAnnotatedType) tree.clazz).annotations,
4446                            tree.clazz.type.tsym);
4447                }
4448                if (tree.def != null) {
4449                    checkForDeclarationAnnotations(tree.def.mods.annotations, tree.clazz.type.tsym);
4450                }
4451
4452                validateAnnotatedType(tree.clazz, tree.clazz.type);
4453            }
4454            super.visitNewClass(tree);
4455        }
4456        public void visitNewArray(JCNewArray tree) {
4457            if (tree.elemtype != null && tree.elemtype.type != null) {
4458                if (tree.elemtype.hasTag(ANNOTATED_TYPE)) {
4459                    checkForDeclarationAnnotations(((JCAnnotatedType) tree.elemtype).annotations,
4460                            tree.elemtype.type.tsym);
4461                }
4462                validateAnnotatedType(tree.elemtype, tree.elemtype.type);
4463            }
4464            super.visitNewArray(tree);
4465        }
4466        public void visitClassDef(JCClassDecl tree) {
4467            //System.err.println("validateTypeAnnotations.visitClassDef " + tree);
4468            if (sigOnly) {
4469                scan(tree.mods);
4470                scan(tree.typarams);
4471                scan(tree.extending);
4472                scan(tree.implementing);
4473            }
4474            for (JCTree member : tree.defs) {
4475                if (member.hasTag(Tag.CLASSDEF)) {
4476                    continue;
4477                }
4478                scan(member);
4479            }
4480        }
4481        public void visitBlock(JCBlock tree) {
4482            if (!sigOnly) {
4483                scan(tree.stats);
4484            }
4485        }
4486
4487        /* I would want to model this after
4488         * com.sun.tools.javac.comp.Check.Validator.visitSelectInternal(JCFieldAccess)
4489         * and override visitSelect and visitTypeApply.
4490         * However, we only set the annotated type in the top-level type
4491         * of the symbol.
4492         * Therefore, we need to override each individual location where a type
4493         * can occur.
4494         */
4495        private void validateAnnotatedType(final JCTree errtree, final Type type) {
4496            //System.err.println("Attr.validateAnnotatedType: " + errtree + " type: " + type);
4497
4498            if (type.isPrimitiveOrVoid()) {
4499                return;
4500            }
4501
4502            JCTree enclTr = errtree;
4503            Type enclTy = type;
4504
4505            boolean repeat = true;
4506            while (repeat) {
4507                if (enclTr.hasTag(TYPEAPPLY)) {
4508                    List<Type> tyargs = enclTy.getTypeArguments();
4509                    List<JCExpression> trargs = ((JCTypeApply)enclTr).getTypeArguments();
4510                    if (trargs.length() > 0) {
4511                        // Nothing to do for diamonds
4512                        if (tyargs.length() == trargs.length()) {
4513                            for (int i = 0; i < tyargs.length(); ++i) {
4514                                validateAnnotatedType(trargs.get(i), tyargs.get(i));
4515                            }
4516                        }
4517                        // If the lengths don't match, it's either a diamond
4518                        // or some nested type that redundantly provides
4519                        // type arguments in the tree.
4520                    }
4521
4522                    // Look at the clazz part of a generic type
4523                    enclTr = ((JCTree.JCTypeApply)enclTr).clazz;
4524                }
4525
4526                if (enclTr.hasTag(SELECT)) {
4527                    enclTr = ((JCTree.JCFieldAccess)enclTr).getExpression();
4528                    if (enclTy != null &&
4529                            !enclTy.hasTag(NONE)) {
4530                        enclTy = enclTy.getEnclosingType();
4531                    }
4532                } else if (enclTr.hasTag(ANNOTATED_TYPE)) {
4533                    JCAnnotatedType at = (JCTree.JCAnnotatedType) enclTr;
4534                    if (enclTy == null || enclTy.hasTag(NONE)) {
4535                        if (at.getAnnotations().size() == 1) {
4536                            log.error(at.underlyingType.pos(), "cant.type.annotate.scoping.1", at.getAnnotations().head.attribute);
4537                        } else {
4538                            ListBuffer<Attribute.Compound> comps = new ListBuffer<>();
4539                            for (JCAnnotation an : at.getAnnotations()) {
4540                                comps.add(an.attribute);
4541                            }
4542                            log.error(at.underlyingType.pos(), "cant.type.annotate.scoping", comps.toList());
4543                        }
4544                        repeat = false;
4545                    }
4546                    enclTr = at.underlyingType;
4547                    // enclTy doesn't need to be changed
4548                } else if (enclTr.hasTag(IDENT)) {
4549                    repeat = false;
4550                } else if (enclTr.hasTag(JCTree.Tag.WILDCARD)) {
4551                    JCWildcard wc = (JCWildcard) enclTr;
4552                    if (wc.getKind() == JCTree.Kind.EXTENDS_WILDCARD) {
4553                        validateAnnotatedType(wc.getBound(), ((WildcardType)enclTy).getExtendsBound());
4554                    } else if (wc.getKind() == JCTree.Kind.SUPER_WILDCARD) {
4555                        validateAnnotatedType(wc.getBound(), ((WildcardType)enclTy).getSuperBound());
4556                    } else {
4557                        // Nothing to do for UNBOUND
4558                    }
4559                    repeat = false;
4560                } else if (enclTr.hasTag(TYPEARRAY)) {
4561                    JCArrayTypeTree art = (JCArrayTypeTree) enclTr;
4562                    validateAnnotatedType(art.getType(), ((ArrayType)enclTy).getComponentType());
4563                    repeat = false;
4564                } else if (enclTr.hasTag(TYPEUNION)) {
4565                    JCTypeUnion ut = (JCTypeUnion) enclTr;
4566                    for (JCTree t : ut.getTypeAlternatives()) {
4567                        validateAnnotatedType(t, t.type);
4568                    }
4569                    repeat = false;
4570                } else if (enclTr.hasTag(TYPEINTERSECTION)) {
4571                    JCTypeIntersection it = (JCTypeIntersection) enclTr;
4572                    for (JCTree t : it.getBounds()) {
4573                        validateAnnotatedType(t, t.type);
4574                    }
4575                    repeat = false;
4576                } else if (enclTr.getKind() == JCTree.Kind.PRIMITIVE_TYPE ||
4577                           enclTr.getKind() == JCTree.Kind.ERRONEOUS) {
4578                    repeat = false;
4579                } else {
4580                    Assert.error("Unexpected tree: " + enclTr + " with kind: " + enclTr.getKind() +
4581                            " within: "+ errtree + " with kind: " + errtree.getKind());
4582                }
4583            }
4584        }
4585
4586        private void checkForDeclarationAnnotations(List<? extends JCAnnotation> annotations,
4587                Symbol sym) {
4588            // Ensure that no declaration annotations are present.
4589            // Note that a tree type might be an AnnotatedType with
4590            // empty annotations, if only declaration annotations were given.
4591            // This method will raise an error for such a type.
4592            for (JCAnnotation ai : annotations) {
4593                if (!ai.type.isErroneous() &&
4594                        typeAnnotations.annotationType(ai.attribute, sym) == TypeAnnotations.AnnotationType.DECLARATION) {
4595                    log.error(ai.pos(), "annotation.type.not.applicable");
4596                }
4597            }
4598        }
4599    }
4600
4601    // <editor-fold desc="post-attribution visitor">
4602
4603    /**
4604     * Handle missing types/symbols in an AST. This routine is useful when
4605     * the compiler has encountered some errors (which might have ended up
4606     * terminating attribution abruptly); if the compiler is used in fail-over
4607     * mode (e.g. by an IDE) and the AST contains semantic errors, this routine
4608     * prevents NPE to be progagated during subsequent compilation steps.
4609     */
4610    public void postAttr(JCTree tree) {
4611        new PostAttrAnalyzer().scan(tree);
4612    }
4613
4614    class PostAttrAnalyzer extends TreeScanner {
4615
4616        private void initTypeIfNeeded(JCTree that) {
4617            if (that.type == null) {
4618                if (that.hasTag(METHODDEF)) {
4619                    that.type = dummyMethodType((JCMethodDecl)that);
4620                } else {
4621                    that.type = syms.unknownType;
4622                }
4623            }
4624        }
4625
4626        /* Construct a dummy method type. If we have a method declaration,
4627         * and the declared return type is void, then use that return type
4628         * instead of UNKNOWN to avoid spurious error messages in lambda
4629         * bodies (see:JDK-8041704).
4630         */
4631        private Type dummyMethodType(JCMethodDecl md) {
4632            Type restype = syms.unknownType;
4633            if (md != null && md.restype.hasTag(TYPEIDENT)) {
4634                JCPrimitiveTypeTree prim = (JCPrimitiveTypeTree)md.restype;
4635                if (prim.typetag == VOID)
4636                    restype = syms.voidType;
4637            }
4638            return new MethodType(List.<Type>nil(), restype,
4639                                  List.<Type>nil(), syms.methodClass);
4640        }
4641        private Type dummyMethodType() {
4642            return dummyMethodType(null);
4643        }
4644
4645        @Override
4646        public void scan(JCTree tree) {
4647            if (tree == null) return;
4648            if (tree instanceof JCExpression) {
4649                initTypeIfNeeded(tree);
4650            }
4651            super.scan(tree);
4652        }
4653
4654        @Override
4655        public void visitIdent(JCIdent that) {
4656            if (that.sym == null) {
4657                that.sym = syms.unknownSymbol;
4658            }
4659        }
4660
4661        @Override
4662        public void visitSelect(JCFieldAccess that) {
4663            if (that.sym == null) {
4664                that.sym = syms.unknownSymbol;
4665            }
4666            super.visitSelect(that);
4667        }
4668
4669        @Override
4670        public void visitClassDef(JCClassDecl that) {
4671            initTypeIfNeeded(that);
4672            if (that.sym == null) {
4673                that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol);
4674            }
4675            super.visitClassDef(that);
4676        }
4677
4678        @Override
4679        public void visitMethodDef(JCMethodDecl that) {
4680            initTypeIfNeeded(that);
4681            if (that.sym == null) {
4682                that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol);
4683            }
4684            super.visitMethodDef(that);
4685        }
4686
4687        @Override
4688        public void visitVarDef(JCVariableDecl that) {
4689            initTypeIfNeeded(that);
4690            if (that.sym == null) {
4691                that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol);
4692                that.sym.adr = 0;
4693            }
4694            super.visitVarDef(that);
4695        }
4696
4697        @Override
4698        public void visitNewClass(JCNewClass that) {
4699            if (that.constructor == null) {
4700                that.constructor = new MethodSymbol(0, names.init,
4701                        dummyMethodType(), syms.noSymbol);
4702            }
4703            if (that.constructorType == null) {
4704                that.constructorType = syms.unknownType;
4705            }
4706            super.visitNewClass(that);
4707        }
4708
4709        @Override
4710        public void visitAssignop(JCAssignOp that) {
4711            if (that.operator == null) {
4712                that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
4713                        -1, syms.noSymbol);
4714            }
4715            super.visitAssignop(that);
4716        }
4717
4718        @Override
4719        public void visitBinary(JCBinary that) {
4720            if (that.operator == null) {
4721                that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
4722                        -1, syms.noSymbol);
4723            }
4724            super.visitBinary(that);
4725        }
4726
4727        @Override
4728        public void visitUnary(JCUnary that) {
4729            if (that.operator == null) {
4730                that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
4731                        -1, syms.noSymbol);
4732            }
4733            super.visitUnary(that);
4734        }
4735
4736        @Override
4737        public void visitLambda(JCLambda that) {
4738            super.visitLambda(that);
4739            if (that.targets == null) {
4740                that.targets = List.nil();
4741            }
4742        }
4743
4744        @Override
4745        public void visitReference(JCMemberReference that) {
4746            super.visitReference(that);
4747            if (that.sym == null) {
4748                that.sym = new MethodSymbol(0, names.empty, dummyMethodType(),
4749                        syms.noSymbol);
4750            }
4751            if (that.targets == null) {
4752                that.targets = List.nil();
4753            }
4754        }
4755    }
4756    // </editor-fold>
4757}
4758