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