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