Issue #271310 - NullPointerException at com.sun.tools.javac.comp.Attr.enclosingInitEnv - fixed.
2 * Copyright (c) 1999, 2017, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
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.
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).
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.
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
26 package com.sun.tools.javac.comp;
30 import javax.lang.model.element.ElementKind;
31 import javax.tools.JavaFileObject;
33 import com.sun.source.tree.IdentifierTree;
34 import com.sun.source.tree.MemberReferenceTree.ReferenceMode;
35 import com.sun.source.tree.MemberSelectTree;
36 import com.sun.source.tree.TreeVisitor;
37 import com.sun.source.util.SimpleTreeVisitor;
38 import com.sun.tools.javac.code.*;
39 import com.sun.tools.javac.code.Lint.LintCategory;
40 import com.sun.tools.javac.code.Scope.WriteableScope;
41 import com.sun.tools.javac.code.Symbol.*;
42 import com.sun.tools.javac.code.Type.*;
43 import com.sun.tools.javac.code.TypeMetadata.Annotations;
44 import com.sun.tools.javac.code.Types.FunctionDescriptorLookupError;
45 import com.sun.tools.javac.comp.ArgumentAttr.LocalCacheContext;
46 import com.sun.tools.javac.comp.Check.CheckContext;
47 import com.sun.tools.javac.comp.DeferredAttr.AttrMode;
48 import com.sun.tools.javac.jvm.*;
49 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.Diamond;
50 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.DiamondInvalidArg;
51 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.DiamondInvalidArgs;
52 import com.sun.tools.javac.resources.CompilerProperties.Errors;
53 import com.sun.tools.javac.resources.CompilerProperties.Fragments;
54 import com.sun.tools.javac.tree.*;
55 import com.sun.tools.javac.tree.JCTree.*;
56 import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*;
57 import com.sun.tools.javac.util.*;
58 import com.sun.tools.javac.util.DefinedBy.Api;
59 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
60 import com.sun.tools.javac.util.JCDiagnostic.Fragment;
61 import com.sun.tools.javac.util.List;
63 import static com.sun.tools.javac.code.Flags.*;
64 import static com.sun.tools.javac.code.Flags.ANNOTATION;
65 import static com.sun.tools.javac.code.Flags.BLOCK;
66 import static com.sun.tools.javac.code.Kinds.*;
67 import static com.sun.tools.javac.code.Kinds.Kind.*;
68 import static com.sun.tools.javac.code.TypeTag.*;
69 import static com.sun.tools.javac.code.TypeTag.WILDCARD;
70 import static com.sun.tools.javac.tree.JCTree.Tag.*;
71 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
73 /** This is the main context-dependent analysis phase in GJC. It
74 * encompasses name resolution, type checking and constant folding as
75 * subtasks. Some subtasks involve auxiliary classes.
81 * <p><b>This is NOT part of any supported API.
82 * If you write code that depends on this, you do so at your own risk.
83 * This code and its internal interfaces are subject to change or
84 * deletion without notice.</b>
86 public class Attr extends JCTree.Visitor {
87 protected static final Context.Key<Attr> attrKey = new Context.Key<>();
93 final Operators operators;
95 final Analyzer analyzer;
96 final DeferredAttr deferredAttr;
99 final MemberEnter memberEnter;
100 final TypeEnter typeEnter;
101 final TreeMaker make;
102 final ConstFold cfolder;
106 final JCDiagnostic.Factory diags;
107 final TypeAnnotations typeAnnotations;
108 final DeferredLintHandler deferredLintHandler;
109 final TypeEnvs typeEnvs;
110 final Dependencies dependencies;
111 final Annotate annotate;
112 final ArgumentAttr argumentAttr;
113 private final boolean isBackgroundCompilation;
115 public static Attr instance(Context context) {
116 Attr instance = context.get(attrKey);
117 if (instance == null)
118 instance = new Attr(context);
122 protected Attr(Context context) {
123 context.put(attrKey, this);
125 names = Names.instance(context);
126 log = Log.instance(context);
127 syms = Symtab.instance(context);
128 rs = Resolve.instance(context);
129 operators = Operators.instance(context);
130 chk = Check.instance(context);
131 flow = Flow.instance(context);
132 memberEnter = MemberEnter.instance(context);
133 typeEnter = TypeEnter.instance(context);
134 make = TreeMaker.instance(context);
135 enter = Enter.instance(context);
136 infer = Infer.instance(context);
137 analyzer = Analyzer.instance(context);
138 deferredAttr = DeferredAttr.instance(context);
139 cfolder = ConstFold.instance(context);
140 target = Target.instance(context);
141 types = Types.instance(context);
142 diags = JCDiagnostic.Factory.instance(context);
143 annotate = Annotate.instance(context);
144 typeAnnotations = TypeAnnotations.instance(context);
145 deferredLintHandler = DeferredLintHandler.instance(context);
146 typeEnvs = TypeEnvs.instance(context);
147 dependencies = Dependencies.instance(context);
148 argumentAttr = ArgumentAttr.instance(context);
150 Options options = Options.instance(context);
152 Source source = Source.instance(context);
153 allowStringsInSwitch = source.allowStringsInSwitch();
154 allowPoly = source.allowPoly();
155 allowTypeAnnos = source.allowTypeAnnotations();
156 allowLambda = source.allowLambda();
157 allowDefaultMethods = source.allowDefaultMethods();
158 allowStaticInterfaceMethods = source.allowStaticInterfaceMethods();
159 sourceName = source.name;
160 useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
162 statInfo = new ResultInfo(KindSelector.NIL, Type.noType);
163 varAssignmentInfo = new ResultInfo(KindSelector.ASG, Type.noType);
164 unknownExprInfo = new ResultInfo(KindSelector.VAL, Type.noType);
165 methodAttrInfo = new MethodAttrInfo();
166 unknownTypeInfo = new ResultInfo(KindSelector.TYP, Type.noType);
167 unknownTypeExprInfo = new ResultInfo(KindSelector.VAL_TYP, Type.noType);
168 recoveryInfo = new RecoveryInfo(deferredAttr.emptyDeferredAttrContext);
170 isBackgroundCompilation = options.get("backgroundCompilation") != null; //NOI18N
173 /** Switch: support target-typing inference
177 /** Switch: support type annotations.
179 boolean allowTypeAnnos;
181 /** Switch: support lambda expressions ?
185 /** Switch: support default methods ?
187 boolean allowDefaultMethods;
189 /** Switch: static interface methods enabled?
191 boolean allowStaticInterfaceMethods;
194 * Switch: warn about use of variable before declaration?
197 boolean useBeforeDeclarationWarning;
200 * Switch: allow strings in switch?
202 boolean allowStringsInSwitch;
205 * Switch: name of source level; used for error reporting.
209 /** Check kind and type of given tree against protokind and prototype.
210 * If check succeeds, store type in tree and return it.
211 * If check fails, store errType in tree and return it.
212 * No checks are performed if the prototype is a method type.
213 * It is not necessary in this case since we know that kind and type
216 * @param tree The tree whose kind and type is checked
217 * @param found The computed type of the tree
218 * @param ownkind The computed kind of the tree
219 * @param resultInfo The expected result of the tree
221 Type check(final JCTree tree,
223 final KindSelector ownkind,
224 final ResultInfo resultInfo) {
225 InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
227 boolean shouldCheck = !found.hasTag(ERROR) &&
228 !resultInfo.pt.hasTag(METHOD) &&
229 !resultInfo.pt.hasTag(FORALL);
230 if (shouldCheck && !ownkind.subset(resultInfo.pkind)) {
231 log.error(tree.pos(), "unexpected.type",
232 resultInfo.pkind.kindNames(),
233 ownkind.kindNames());
234 owntype = types.createErrorType(found);
235 } else if (allowPoly && inferenceContext.free(found)) {
236 //delay the check if there are inference variables in the found type
237 //this means we are dealing with a partially inferred poly expression
238 owntype = shouldCheck ? resultInfo.pt : found;
239 if (resultInfo.checkMode.installPostInferenceHook()) {
240 inferenceContext.addFreeTypeListener(List.of(found),
241 instantiatedContext -> {
242 ResultInfo pendingResult =
243 resultInfo.dup(inferenceContext.asInstType(resultInfo.pt));
244 check(tree, inferenceContext.asInstType(found), ownkind, pendingResult);
248 owntype = shouldCheck ?
249 resultInfo.check(tree, found) :
252 if (resultInfo.checkMode.updateTreeType()) {
258 /** Is given blank final variable assignable, i.e. in a scope where it
259 * may be assigned to even though it is final?
260 * @param v The blank final variable.
261 * @param env The current environment.
263 boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
264 Symbol owner = env.info.scope.owner;
265 // owner refers to the innermost variable, method or
266 // initializer block declaration at this point.
270 ((owner.name == names.init || // i.e. we are in a constructor
271 owner.kind == VAR || // i.e. we are in a variable initializer
272 (owner.flags() & BLOCK) != 0) // i.e. we are in an initializer block
274 v.owner == owner.owner
276 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
279 /** Check that variable can be assigned to.
280 * @param pos The current source code position.
281 * @param v The assigned variable
282 * @param base If the variable is referred to in a Select, the part
283 * to the left of the `.', null otherwise.
284 * @param env The current environment.
286 void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
287 if (v.name == names._this) {
288 log.error(pos, Errors.CantAssignValToThis);
289 } else if ((v.flags() & FINAL) != 0 &&
290 ((v.flags() & HASINIT) != 0
293 (base.hasTag(IDENT) && TreeInfo.name(base) == names._this)) &&
294 isAssignableAsBlankFinal(v, env)))) {
295 if (v.isResourceVariable()) { //TWR resource
296 log.error(pos, "try.resource.may.not.be.assigned", v);
298 log.error(pos, "cant.assign.val.to.final.var", v);
303 /** Does tree represent a static reference to an identifier?
304 * It is assumed that tree is either a SELECT or an IDENT.
305 * We have to weed out selects from non-type names here.
306 * @param tree The candidate tree.
308 boolean isStaticReference(JCTree tree) {
309 if (tree.hasTag(SELECT)) {
310 Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
311 if (lsym == null || lsym.kind != TYP) {
318 /** Is this symbol a type?
320 static boolean isType(Symbol sym) {
321 return sym != null && sym.kind == TYP;
324 /** The current `this' symbol.
325 * @param env The current environment.
327 Symbol thisSym(DiagnosticPosition pos, Env<AttrContext> env) {
328 return rs.resolveSelf(pos, env, env.enclClass.sym, names._this);
331 /** Attribute a parsed identifier.
332 * @param tree Parsed identifier name
333 * @param topLevel The toplevel to use
335 public Symbol attribIdent(JCTree tree, JCCompilationUnit topLevel) {
336 Env<AttrContext> localEnv = enter.topLevelEnv(topLevel);
337 localEnv.enclClass = make.ClassDef(make.Modifiers(0),
339 null, null, null, null);
340 localEnv.enclClass.sym = syms.errSymbol;
341 return attribIdent(tree, localEnv);
344 /** Attribute a parsed identifier.
345 * @param tree Parsed identifier name
346 * @param env The env to use
348 public Symbol attribIdent(JCTree tree, Env<AttrContext> env) {
349 return tree.accept(identAttributer, env);
352 private TreeVisitor<Symbol,Env<AttrContext>> identAttributer = new IdentAttributer();
353 private class IdentAttributer extends SimpleTreeVisitor<Symbol,Env<AttrContext>> {
354 @Override @DefinedBy(Api.COMPILER_TREE)
355 public Symbol visitMemberSelect(MemberSelectTree node, Env<AttrContext> env) {
356 Symbol site = visit(node.getExpression(), env);
357 if (!site.kind.isValid())
359 Name name = (Name)node.getIdentifier();
360 if (site.kind == PCK) {
361 env.toplevel.packge = (PackageSymbol)site;
362 return rs.findIdentInPackage(env, (TypeSymbol)site, name,
363 KindSelector.TYP_PCK);
365 env.enclClass.sym = (ClassSymbol)site;
366 return rs.findMemberType(env, site.asType(), name, (TypeSymbol)site);
370 @Override @DefinedBy(Api.COMPILER_TREE)
371 public Symbol visitIdentifier(IdentifierTree node, Env<AttrContext> env) {
372 return rs.findIdent(env, (Name)node.getName(), KindSelector.TYP_PCK);
376 public Type coerce(Type etype, Type ttype) {
377 return cfolder.coerce(etype, ttype);
380 public Type attribType(JCTree node, TypeSymbol sym) {
381 Env<AttrContext> env = typeEnvs.get(sym);
382 Env<AttrContext> localEnv = env.dup(node, env.info.dup());
383 return attribTree(node, localEnv, unknownTypeInfo);
386 public Type attribImportQualifier(JCImport tree, Env<AttrContext> env) {
387 // Attribute qualifying package or class.
388 JCFieldAccess s = (JCFieldAccess)tree.qualid;
389 return attribTree(s.selected, env,
390 new ResultInfo(tree.staticImport ?
391 KindSelector.TYP : KindSelector.TYP_PCK,
395 public Env<AttrContext> attribExprToTree(JCTree expr, Env<AttrContext> env, JCTree tree) {
396 Env<AttrContext> localEnv = env.dup(env.tree, env.info.dup(env.info.scope.dupUnshared()));
399 attribExpr(expr, localEnv);
400 } catch (BreakAttr b) {
402 } catch (AssertionError ae) {
403 if (ae.getCause() instanceof BreakAttr) {
404 return ((BreakAttr)(ae.getCause())).env;
414 public Env<AttrContext> attribStatToTree(JCTree stmt, Env<AttrContext> env, JCTree tree) {
415 Env<AttrContext> localEnv = env.dup(env.tree, env.info.dup(env.info.scope.dupUnshared()));
418 attribStat(stmt, localEnv);
419 } catch (BreakAttr b) {
421 } catch (AssertionError ae) {
422 if (ae.getCause() instanceof BreakAttr) {
423 return ((BreakAttr)(ae.getCause())).env;
433 private JCTree breakTree = null;
435 public static class BreakAttr extends RuntimeException {
436 static final long serialVersionUID = -6924771130405446405L;
437 private final Env<AttrContext> env;
438 private final Type result;
439 private BreakAttr(Env<AttrContext> env, Type result) {
441 this.result = result;
446 * Mode controlling behavior of Attr.Check
453 * Mode signalling 'fake check' - skip tree update. A side-effect of this mode is
454 * that the captured var cache in {@code InferenceContext} will be used in read-only
455 * mode when performing inference checks.
459 public boolean updateTreeType() {
464 * Mode signalling that caller will manage free types in tree decorations.
468 public boolean installPostInferenceHook() {
473 public boolean updateTreeType() {
476 public boolean installPostInferenceHook() {
483 final KindSelector pkind;
485 final CheckContext checkContext;
486 final CheckMode checkMode;
488 ResultInfo(KindSelector pkind, Type pt) {
489 this(pkind, pt, chk.basicHandler, CheckMode.NORMAL);
492 ResultInfo(KindSelector pkind, Type pt, CheckMode checkMode) {
493 this(pkind, pt, chk.basicHandler, checkMode);
496 protected ResultInfo(KindSelector pkind,
497 Type pt, CheckContext checkContext) {
498 this(pkind, pt, checkContext, CheckMode.NORMAL);
501 protected ResultInfo(KindSelector pkind,
502 Type pt, CheckContext checkContext, CheckMode checkMode) {
505 this.checkContext = checkContext;
506 this.checkMode = checkMode;
510 * Should {@link Attr#attribTree} use the {@ArgumentAttr} visitor instead of this one?
511 * @param tree The tree to be type-checked.
512 * @return true if {@ArgumentAttr} should be used.
514 protected boolean needsArgumentAttr(JCTree tree) { return false; }
516 protected Type check(final DiagnosticPosition pos, final Type found) {
517 return chk.checkType(pos, found, pt, checkContext);
520 protected ResultInfo dup(Type newPt) {
521 return new ResultInfo(pkind, newPt, checkContext, checkMode);
524 protected ResultInfo dup(CheckContext newContext) {
525 return new ResultInfo(pkind, pt, newContext, checkMode);
528 protected ResultInfo dup(Type newPt, CheckContext newContext) {
529 return new ResultInfo(pkind, newPt, newContext, checkMode);
532 protected ResultInfo dup(Type newPt, CheckContext newContext, CheckMode newMode) {
533 return new ResultInfo(pkind, newPt, newContext, newMode);
536 protected ResultInfo dup(CheckMode newMode) {
537 return new ResultInfo(pkind, pt, checkContext, newMode);
541 public String toString() {
543 return pt.toString();
550 class MethodAttrInfo extends ResultInfo {
551 public MethodAttrInfo() {
552 this(chk.basicHandler);
555 public MethodAttrInfo(CheckContext checkContext) {
556 super(KindSelector.VAL, Infer.anyPoly, checkContext);
560 protected boolean needsArgumentAttr(JCTree tree) {
564 protected ResultInfo dup(Type newPt) {
565 throw new IllegalStateException();
568 protected ResultInfo dup(CheckContext newContext) {
569 return new MethodAttrInfo(newContext);
572 protected ResultInfo dup(Type newPt, CheckContext newContext) {
573 throw new IllegalStateException();
576 protected ResultInfo dup(Type newPt, CheckContext newContext, CheckMode newMode) {
577 throw new IllegalStateException();
580 protected ResultInfo dup(CheckMode newMode) {
581 throw new IllegalStateException();
585 class RecoveryInfo extends ResultInfo {
587 public RecoveryInfo(final DeferredAttr.DeferredAttrContext deferredAttrContext) {
588 this(deferredAttrContext, Type.recoveryType);
591 public RecoveryInfo(final DeferredAttr.DeferredAttrContext deferredAttrContext, final Type pt) {
592 super(KindSelector.VAL, pt, new Check.NestedCheckContext(chk.basicHandler) {
594 public DeferredAttr.DeferredAttrContext deferredAttrContext() {
595 return deferredAttrContext;
598 public boolean compatible(Type found, Type req, Warner warn) {
602 public void report(DiagnosticPosition pos, JCDiagnostic details) {
603 chk.basicHandler.report(pos, details);
609 final ResultInfo statInfo;
610 final ResultInfo varAssignmentInfo;
611 final ResultInfo methodAttrInfo;
612 final ResultInfo unknownExprInfo;
613 final ResultInfo unknownTypeInfo;
614 final ResultInfo unknownTypeExprInfo;
615 final ResultInfo recoveryInfo;
618 return resultInfo.pt;
621 KindSelector pkind() {
622 return resultInfo.pkind;
625 /* ************************************************************************
627 *************************************************************************/
629 /** Visitor argument: the current environment.
631 Env<AttrContext> env;
633 /** Visitor argument: the currently expected attribution result.
635 ResultInfo resultInfo;
637 /** Visitor result: the computed type.
641 /** Visitor method: attribute a tree, catching any completion failure
642 * exceptions. Return the tree's type.
644 * @param tree The tree to be visited.
645 * @param env The environment visitor argument.
646 * @param resultInfo The result info visitor argument.
648 Type attribTree(JCTree tree, Env<AttrContext> env, ResultInfo resultInfo) {
649 Env<AttrContext> prevEnv = this.env;
650 ResultInfo prevResult = this.resultInfo;
653 this.resultInfo = resultInfo;
655 if (resultInfo.needsArgumentAttr(tree)) {
656 result = argumentAttr.attribArg(tree, env);
660 } catch (Resolve.InapplicableMethodException ime) {
661 if (tree != breakTree ||
662 resultInfo.checkContext.deferredAttrContext().mode != AttrMode.CHECK) {
666 if (tree == breakTree &&
667 resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
668 throw new BreakAttr(copyEnv(env), result);
671 } catch (CompletionFailure ex) {
672 tree.type = syms.errType;
673 return chk.completionError(tree.pos(), ex);
676 this.resultInfo = prevResult;
680 Env<AttrContext> copyEnv(Env<AttrContext> env) {
681 Env<AttrContext> newEnv =
682 env.dup(env.tree, env.info.dup(copyScope(env.info.scope)));
683 if (newEnv.outer != null) {
684 newEnv.outer = copyEnv(newEnv.outer);
689 WriteableScope copyScope(WriteableScope sc) {
690 WriteableScope newScope = WriteableScope.create(sc.owner);
691 List<Symbol> elemsList = List.nil();
692 for (Symbol sym : sc.getSymbols()) {
693 elemsList = elemsList.prepend(sym);
695 for (Symbol s : elemsList) {
701 /** Derived visitor method: attribute an expression tree.
703 public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) {
704 return attribTree(tree, env, new ResultInfo(KindSelector.VAL, pt != null && !pt.hasTag(ERROR) ? pt : Type.noType));
707 /** Derived visitor method: attribute an expression tree with
708 * no constraints on the computed type.
710 public Type attribExpr(JCTree tree, Env<AttrContext> env) {
711 return attribTree(tree, env, unknownExprInfo);
714 /** Derived visitor method: attribute a type tree.
716 public Type attribType(JCTree tree, Env<AttrContext> env) {
717 Type result = attribType(tree, env, Type.noType);
721 /** Derived visitor method: attribute a type tree.
723 Type attribType(JCTree tree, Env<AttrContext> env, Type pt) {
724 Type result = attribTree(tree, env, new ResultInfo(KindSelector.TYP, pt));
728 /** Derived visitor method: attribute a statement or definition tree.
730 public Type attribStat(JCTree tree, Env<AttrContext> env) {
731 Env<AttrContext> analyzeEnv = analyzer.copyEnvIfNeeded(tree, env);
732 boolean baCatched = false;
734 return attribTree(tree, env, statInfo);
735 } catch (BreakAttr ba) {
740 analyzer.analyzeIfNeeded(tree, analyzeEnv);
745 /** Attribute a list of expressions, returning a list of types.
747 List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) {
748 ListBuffer<Type> ts = new ListBuffer<>();
749 for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
750 ts.append(attribExpr(l.head, env, pt));
754 /** Attribute a list of statements, returning nothing.
756 <T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) {
757 for (List<T> l = trees; l.nonEmpty(); l = l.tail)
758 attribStat(l.head, env);
761 /** Attribute the arguments in a method call, returning the method kind.
763 KindSelector attribArgs(KindSelector initialKind, List<JCExpression> trees, Env<AttrContext> env, ListBuffer<Type> argtypes) {
764 KindSelector kind = initialKind;
765 for (JCExpression arg : trees) {
767 Type argtype = chk.checkNonVoid(arg, attribTree(arg, env, allowPoly ? methodAttrInfo : unknownExprInfo));
768 if (argtype.hasTag(DEFERRED)) {
769 kind = KindSelector.of(KindSelector.POLY, kind);
771 argtypes.append(argtype);
772 } catch (BreakAttr ba) {
773 if (ba.result != null && !ba.result.hasTag(PACKAGE) && !ba.result.hasTag(METHOD) && env.tree == ba.env.tree) {
774 argtypes.append(chk.checkNonVoid(arg, ba.result));
782 /** Attribute a type argument list, returning a list of types.
783 * Caller is responsible for calling checkRefTypes.
785 List<Type> attribAnyTypes(List<JCExpression> trees, Env<AttrContext> env) {
786 ListBuffer<Type> argtypes = new ListBuffer<>();
787 for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
788 argtypes.append(attribType(l.head, env));
789 return argtypes.toList();
792 /** Attribute a type argument list, returning a list of types.
793 * Check that all the types are references.
795 List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
796 List<Type> types = attribAnyTypes(trees, env);
797 return chk.checkRefTypes(trees, types);
801 * Attribute type variables (of generic classes or methods).
802 * Compound types are attributed later in attribBounds.
803 * @param typarams the type variables to enter
804 * @param env the current environment
806 void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env) {
807 for (JCTypeParameter tvar : typarams) {
808 TypeVar a = (TypeVar)tvar.type;
809 a.tsym.flags_field |= UNATTRIBUTED;
810 a.bound = Type.noType;
811 if (!tvar.bounds.isEmpty()) {
812 List<Type> bounds = List.of(attribType(tvar.bounds.head, env));
813 for (JCExpression bound : tvar.bounds.tail)
814 bounds = bounds.prepend(attribType(bound, env));
815 types.setBounds(a, bounds.reverse());
817 // if no bounds are given, assume a single bound of
819 types.setBounds(a, List.of(syms.objectType));
821 a.tsym.flags_field &= ~UNATTRIBUTED;
823 for (JCTypeParameter tvar : typarams) {
824 chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
829 * Attribute the type references in a list of annotations.
831 void attribAnnotationTypes(List<JCAnnotation> annotations,
832 Env<AttrContext> env) {
833 for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
834 JCAnnotation a = al.head;
835 attribType(a.annotationType, env);
840 * Attribute a "lazy constant value".
841 * @param env The env for the const value
842 * @param variable The initializer for the const value
843 * @param type The expected type, or null
844 * @see VarSymbol#setLazyConstValue
846 public Object attribLazyConstantValue(Env<AttrContext> env,
847 JCVariableDecl variable,
850 DiagnosticPosition prevLintPos
851 = deferredLintHandler.setPos(variable.pos());
853 final JavaFileObject prevSource = log.useSource(env.toplevel.sourcefile);
855 if (variable.init == null) {
858 Type itype = attribExpr(variable.init, env, type);
859 if (itype.constValue() != null) {
860 return coerce(itype, type).constValue();
865 log.useSource(prevSource);
866 deferredLintHandler.setPos(prevLintPos);
870 /** Attribute type reference in an `extends' or `implements' clause.
871 * Supertypes of anonymous inner classes are usually already attributed.
873 * @param tree The tree making up the type reference.
874 * @param env The environment current at the reference.
875 * @param classExpected true if only a class is expected here.
876 * @param interfaceExpected true if only an interface is expected here.
878 Type attribBase(JCTree tree,
879 Env<AttrContext> env,
880 boolean classExpected,
881 boolean interfaceExpected,
882 boolean checkExtensible) {
883 Type t = tree.type != null ?
885 attribType(tree, env);
886 return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible);
888 Type checkBase(Type t,
890 Env<AttrContext> env,
891 boolean classExpected,
892 boolean interfaceExpected,
893 boolean checkExtensible) {
894 final DiagnosticPosition pos = tree.hasTag(TYPEAPPLY) ?
895 (((JCTypeApply) tree).clazz).pos() : tree.pos();
896 if (t.tsym.isAnonymous()) {
897 log.error(pos, "cant.inherit.from.anon");
898 return types.createErrorType(t);
902 if (t.hasTag(TYPEVAR) && !classExpected && !interfaceExpected) {
903 // check that type variable is already visible
904 if (t.getUpperBound() == null) {
905 log.error(pos, "illegal.forward.ref");
906 return types.createErrorType(t);
909 t = chk.checkClassType(pos, t, checkExtensible);
911 if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) {
912 log.error(pos, "intf.expected.here");
913 // return errType is necessary since otherwise there might
914 // be undetected cycles which cause attribution to loop
915 return types.createErrorType(t);
916 } else if (checkExtensible &&
918 (t.tsym.flags() & INTERFACE) != 0) {
919 log.error(pos, "no.intf.expected.here");
920 return types.createErrorType(t);
922 if (checkExtensible &&
923 ((t.tsym.flags() & FINAL) != 0)) {
925 "cant.inherit.from.final", t.tsym);
927 chk.checkNonCyclic(pos, t);
931 Type attribIdentAsEnumType(Env<AttrContext> env, JCIdent id) {
932 Assert.check((env.enclClass.sym.flags() & ENUM) != 0 || env.enclClass.sym.kind == ERR);
933 id.type = env.info.scope.owner.enclClass().type;
934 id.sym = env.info.scope.owner.enclClass();
938 public void visitClassDef(JCClassDecl tree) {
939 Optional<ArgumentAttr.LocalCacheContext> localCacheContext =
940 Optional.ofNullable(env.info.isSpeculative ?
941 argumentAttr.withLocalCacheContext() : null);
943 // Local and anonymous classes have not been entered yet, so we need to
945 if (env.info.scope.owner.kind.matches(KindSelector.VAL_MTH)
946 && (env.info.scope.owner.kind != ERR || tree.sym == null)) {
947 enter.classEnter(tree, env);
949 // If this class declaration is part of a class level annotation,
950 // as in @MyAnno(new Object() {}) class MyClass {}, enter it in
951 // order to simplify later steps and allow for sensible error
953 if (env.tree.hasTag(NEWCLASS) && TreeInfo.isInAnnotation(env, tree))
954 enter.classEnter(tree, env);
957 ClassSymbol c = tree.sym;
959 // exit in case something drastic went wrong during enter.
962 // make sure class has been completed:
965 // If this class appears as an anonymous class
966 // in a superclass constructor call
967 // disable implicit outer instance from being passed.
968 // (This would be an illegal access to "this before super").
969 if (env.info.isSelfCall &&
970 env.tree.hasTag(NEWCLASS)) {
971 c.flags_field |= NOOUTERTHIS;
973 attribClass(tree.pos(), c);
974 result = tree.type = c.type;
977 localCacheContext.ifPresent(LocalCacheContext::leave);
981 public void visitMethodDef(JCMethodDecl tree) {
982 MethodSymbol m = tree.sym;
984 // exit in case something drastic went wrong during enter.
988 boolean isDefaultMethod = (m.flags() & DEFAULT) != 0;
990 Lint lint = env.info.lint.augment(m);
991 Lint prevLint = chk.setLint(lint);
992 MethodSymbol prevMethod = chk.setMethod(m);
994 deferredLintHandler.flush(tree.pos());
995 chk.checkDeprecatedAnnotation(tree.pos(), m);
998 // Create a new environment with local scope
999 // for attributing the method.
1000 Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
1001 localEnv.info.lint = lint;
1003 attribStats(tree.typarams, localEnv);
1005 // If we override any other methods, check that we do so properly.
1008 chk.checkHideClashes(tree.pos(), env.enclClass.type, m);
1010 chk.checkOverrideClashes(tree.pos(), env.enclClass.type, m);
1012 chk.checkOverride(env, tree, m);
1014 if (isDefaultMethod && types.overridesObjectMethod(m.enclClass(), m)) {
1015 log.error(tree, "default.overrides.object.member", m.name, Kinds.kindName(m.location()), m.location());
1018 // Enter all type parameters into the local method scope.
1019 for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
1020 localEnv.info.scope.enterIfAbsent(l.head.type.tsym);
1022 ClassSymbol owner = env.enclClass.sym;
1023 if ((owner.flags() & ANNOTATION) != 0 &&
1024 (tree.params.nonEmpty() ||
1025 tree.recvparam != null))
1026 log.error(tree.params.nonEmpty() ?
1027 tree.params.head.pos() :
1028 tree.recvparam.pos(),
1029 "intf.annotation.members.cant.have.params");
1031 // Attribute all value parameters.
1032 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
1033 attribStat(l.head, localEnv);
1036 chk.checkVarargsMethodDecl(localEnv, tree);
1038 // Check that type parameters are well-formed.
1039 chk.validate(tree.typarams, localEnv);
1041 // Check that result type is well-formed.
1042 if (tree.restype != null && !tree.restype.type.hasTag(VOID))
1043 chk.validate(tree.restype, localEnv);
1045 // Check that receiver type is well-formed.
1046 if (tree.recvparam != null) {
1047 // Use a new environment to check the receiver parameter.
1048 // Otherwise I get "might not have been initialized" errors.
1049 // Is there a better way?
1050 Env<AttrContext> newEnv = memberEnter.methodEnv(tree, env);
1051 attribType(tree.recvparam, newEnv);
1052 chk.validate(tree.recvparam, newEnv);
1055 // annotation method checks
1056 if ((owner.flags() & ANNOTATION) != 0) {
1057 // annotation method cannot have throws clause
1058 if (tree.thrown.nonEmpty()) {
1059 log.error(tree.thrown.head.pos(),
1060 "throws.not.allowed.in.intf.annotation");
1062 // annotation method cannot declare type-parameters
1063 if (tree.typarams.nonEmpty()) {
1064 log.error(tree.typarams.head.pos(),
1065 "intf.annotation.members.cant.have.type.params");
1067 // validate annotation method's return type (could be an annotation type)
1068 chk.validateAnnotationType(tree.restype);
1069 // ensure that annotation method does not clash with members of Object/Annotation
1070 chk.validateAnnotationMethod(tree.pos(), m);
1073 for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
1074 chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
1076 if (tree.body == null) {
1077 // Empty bodies are only allowed for
1078 // abstract, native, or interface methods, or for methods
1079 // in a retrofit signature class.
1080 if (tree.defaultValue != null) {
1081 if ((owner.flags() & ANNOTATION) == 0)
1082 log.error(tree.pos(),
1083 "default.allowed.in.intf.annotation.member");
1085 if (isDefaultMethod || (tree.sym.flags() & (ABSTRACT | NATIVE)) == 0)
1086 log.error(tree.pos(), "missing.meth.body.or.decl.abstract");
1088 if ((tree.sym.flags() & (ABSTRACT|DEFAULT|PRIVATE)) == ABSTRACT) {
1089 if ((owner.flags() & INTERFACE) != 0) {
1090 log.error(tree.body.pos(), "intf.meth.cant.have.body");
1092 log.error(tree.pos(), "abstract.meth.cant.have.body");
1094 } else if ((tree.mods.flags & NATIVE) != 0) {
1095 log.error(tree.pos(), "native.meth.cant.have.body");
1097 // Add an implicit super() call unless an explicit call to
1098 // super(...) or this(...) is given
1099 // or we are compiling class java.lang.Object.
1100 if (tree.name == names.init && !owner.type.isErroneous() && owner.type != syms.objectType) {
1101 JCBlock body = tree.body;
1102 if (body.stats.isEmpty() ||
1103 !TreeInfo.isSelfCall(body.stats.head)) {
1104 body.stats = body.stats.
1105 prepend(typeEnter.SuperCall(make.at(body.pos),
1109 } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
1110 (tree.mods.flags & GENERATEDCONSTR) == 0 &&
1111 TreeInfo.isSuperCall(body.stats.head)) {
1112 // enum constructors are not allowed to call super
1113 // directly, so make sure there aren't any super calls
1114 // in enum constructors, except in the compiler
1116 log.error(tree.body.stats.head.pos(),
1117 "call.to.super.not.allowed.in.enum.ctor",
1122 if (!isBackgroundCompilation) {
1123 tree.localEnv = dupLocalEnv(localEnv);
1126 // Attribute all type annotations in the body
1127 annotate.queueScanTreeAndTypeAnnotate(tree.body, localEnv, m, null);
1130 // Attribute method body.
1131 attribStat(tree.body, localEnv);
1134 localEnv.info.scope.leave();
1135 result = tree.type = m.type;
1137 chk.setLint(prevLint);
1138 chk.setMethod(prevMethod);
1142 public void visitVarDef(JCVariableDecl tree) {
1143 // Local variables have not been entered yet, so we need to do it now:
1144 if (env.info.scope.owner.kind == MTH) {
1145 if (tree.sym != null) {
1146 // parameters have already been entered
1147 env.info.scope.enter(tree.sym);
1150 annotate.blockAnnotations();
1151 memberEnter.memberEnter(tree, env);
1153 annotate.unblockAnnotations();
1157 if (tree.init != null) {
1158 // Field initializer expression need to be entered.
1159 annotate.queueScanTreeAndTypeAnnotate(tree.init, env, tree.sym, tree.pos());
1164 VarSymbol v = tree.sym;
1166 // exit in case something drastic went wrong during enter.
1170 Lint lint = env.info.lint.augment(v);
1171 Lint prevLint = chk.setLint(lint);
1173 // Check that the variable's declared type is well-formed.
1174 boolean isImplicitLambdaParameter = env.tree.hasTag(LAMBDA) &&
1175 ((JCLambda)env.tree).paramKind == JCLambda.ParameterKind.IMPLICIT &&
1176 (tree.sym.flags() & PARAMETER) != 0;
1177 chk.validate(tree.vartype, env, !isImplicitLambdaParameter);
1180 v.getConstValue(); // ensure compile-time constant initializer is evaluated
1181 deferredLintHandler.flush(tree.pos());
1182 chk.checkDeprecatedAnnotation(tree.pos(), v);
1184 if (tree.init != null) {
1185 if ((v.flags_field & FINAL) == 0 ||
1186 !memberEnter.needsLazyConstValue(tree.init)) {
1187 // Not a compile-time constant
1188 // Attribute initializer in a new environment
1189 // with the declared variable as owner.
1190 // Check that initializer conforms to variable's declared type.
1191 Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
1192 initEnv.info.lint = lint;
1193 // In order to catch self-references, we set the variable's
1194 // declaration position to maximal possible value, effectively
1195 // marking the variable as undefined.
1196 initEnv.info.enclVar = v;
1197 attribExpr(tree.init, initEnv, v.type);
1200 result = tree.type = v.type;
1203 chk.setLint(prevLint);
1207 public void visitSkip(JCSkip tree) {
1211 public void visitBlock(JCBlock tree) {
1212 if (env.info.scope != null && env.info.scope.owner != null && (env.info.scope.owner.kind == TYP || env.info.scope.owner.kind == ERR)) {
1213 // Block is a static or instance initializer;
1214 // let the owner of the environment be a freshly
1215 // created BLOCK-method.
1217 new MethodSymbol(tree.flags | BLOCK |
1218 env.info.scope.owner.flags() & STRICTFP, names.empty, null,
1219 env.info.scope.owner);
1220 final Env<AttrContext> localEnv =
1221 env.dup(tree, env.info.dup(env.info.scope.dupUnshared(fakeOwner)));
1223 if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
1224 // Attribute all type annotations in the block
1225 annotate.queueScanTreeAndTypeAnnotate(tree, localEnv, localEnv.info.scope.owner, null);
1227 attribStats(tree.stats, localEnv);
1230 // Store init and clinit type annotations with the ClassSymbol
1231 // to allow output in Gen.normalizeDefs.
1232 ClassSymbol cs = (ClassSymbol)env.info.scope.owner;
1233 List<Attribute.TypeCompound> tas = localEnv.info.scope.owner.getRawTypeAttributes();
1234 if ((tree.flags & STATIC) != 0) {
1235 cs.appendClassInitTypeAttributes(tas);
1237 cs.appendInitTypeAttributes(tas);
1241 // Create a new local environment with a local scope.
1242 Env<AttrContext> localEnv =
1243 env.dup(tree, env.info.dup((env.info.scope != null ? env.info.scope : WriteableScope.create(syms.noSymbol)).dup()));
1245 attribStats(tree.stats, localEnv);
1247 localEnv.info.scope.leave();
1253 public void visitDoLoop(JCDoWhileLoop tree) {
1254 attribStat(tree.body, env.dup(tree));
1255 attribExpr(tree.cond, env, syms.booleanType);
1259 public void visitWhileLoop(JCWhileLoop tree) {
1260 attribExpr(tree.cond, env, syms.booleanType);
1261 attribStat(tree.body, env.dup(tree));
1265 public void visitForLoop(JCForLoop tree) {
1266 Env<AttrContext> loopEnv =
1267 env.dup(env.tree, env.info.dup(env.info.scope.dup()));
1269 attribStats(tree.init, loopEnv);
1270 if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType);
1271 loopEnv.tree = tree; // before, we were not in loop!
1272 attribStats(tree.step, loopEnv);
1273 attribStat(tree.body, loopEnv);
1277 loopEnv.info.scope.leave();
1281 public void visitForeachLoop(JCEnhancedForLoop tree) {
1282 Env<AttrContext> loopEnv =
1283 env.dup(env.tree, env.info.dup(env.info.scope.dup()));
1285 //the Formal Parameter of a for-each loop is not in the scope when
1286 //attributing the for-each expression; we mimick this by attributing
1287 //the for-each expression first (against original scope).
1288 Type exprType = types.cvarUpperBound(attribExpr(tree.expr, loopEnv));
1289 attribStat(tree.var, loopEnv);
1290 chk.checkNonVoid(tree.pos(), exprType);
1291 Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
1292 if (elemtype == null) {
1293 // or perhaps expr implements Iterable<T>?
1294 Type base = types.asSuper(exprType, syms.iterableType.tsym);
1296 log.error(tree.expr.pos(),
1297 "foreach.not.applicable.to.type",
1299 diags.fragment("type.req.array.or.iterable"));
1300 elemtype = types.createErrorType(exprType);
1302 List<Type> iterableParams = base.allparams();
1303 elemtype = iterableParams.isEmpty()
1305 : types.wildUpperBound(iterableParams.head);
1308 if (tree.var.sym != null)
1309 chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
1310 loopEnv.tree = tree; // before, we were not in loop!
1311 attribStat(tree.body, loopEnv);
1315 loopEnv.info.scope.leave();
1319 public void visitLabelled(JCLabeledStatement tree) {
1320 // Check that label is not used in an enclosing statement
1321 Env<AttrContext> env1 = env;
1322 while (env1 != null && !env1.tree.hasTag(CLASSDEF)) {
1323 if (env1.tree.hasTag(LABELLED) &&
1324 ((JCLabeledStatement) env1.tree).label == tree.label) {
1325 log.error(tree.pos(), "label.already.in.use",
1332 attribStat(tree.body, env.dup(tree));
1336 public void visitSwitch(JCSwitch tree) {
1337 Type seltype = attribExpr(tree.selector, env);
1339 Env<AttrContext> switchEnv =
1340 env.dup(tree, env.info.dup(env.info.scope.dup()));
1344 boolean enumSwitch = seltype.tsym != null && (seltype.tsym.flags() & Flags.ENUM) != 0;
1345 boolean stringSwitch = types.isSameType(seltype, syms.stringType);
1346 if (stringSwitch && !allowStringsInSwitch) {
1347 log.error(DiagnosticFlag.SOURCE_LEVEL, tree.selector.pos(), "string.switch.not.supported.in.source", sourceName);
1349 if (!enumSwitch && !stringSwitch)
1350 seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType);
1352 // Attribute all cases and
1353 // check that there are no duplicate case labels or default clauses.
1354 Set<Object> labels = new HashSet<>(); // The set of case labels.
1355 boolean hasDefault = false; // Is there a default label?
1356 for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
1358 if (c.pat != null) {
1360 Symbol sym = enumConstant(c.pat, seltype);
1362 log.error(c.pat.pos(), "enum.label.must.be.unqualified.enum");
1363 } else if (!labels.add(sym)) {
1364 log.error(c.pos(), "duplicate.case.label");
1367 Type pattype = attribExpr(c.pat, switchEnv, seltype);
1368 if (!pattype.hasTag(ERROR)) {
1369 if (pattype.constValue() == null) {
1370 log.error(c.pat.pos(),
1371 (stringSwitch ? "string.const.req" : "const.expr.req"));
1372 } else if (!labels.add(pattype.constValue())) {
1373 log.error(c.pos(), "duplicate.case.label");
1377 } else if (hasDefault) {
1378 log.error(c.pos(), "duplicate.default.label");
1382 if (c == breakTree &&
1383 resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK)
1384 throw new BreakAttr(env, null);
1385 Env<AttrContext> caseEnv =
1386 switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup()));
1387 boolean baCatched = false;
1389 attribStats(c.stats, caseEnv);
1390 } catch (BreakAttr ba) {
1394 caseEnv.info.scope.leave();
1396 addVars(c.stats, switchEnv.info.scope);
1404 switchEnv.info.scope.leave();
1408 /** Add any variables defined in stats to the switch scope. */
1409 private static void addVars(List<JCStatement> stats, WriteableScope switchScope) {
1410 for (;stats.nonEmpty(); stats = stats.tail) {
1411 JCTree stat = stats.head;
1412 if (stat.hasTag(VARDEF) && ((JCVariableDecl) stat).sym != null)
1413 switchScope.enter(((JCVariableDecl) stat).sym);
1417 /** Return the selected enumeration constant symbol, or null. */
1418 private Symbol enumConstant(JCTree tree, Type enumType) {
1419 if (tree.hasTag(IDENT)) {
1420 JCIdent ident = (JCIdent)tree;
1421 Name name = ident.name;
1422 for (Symbol sym : enumType.tsym.members().getSymbolsByName(name)) {
1423 if (sym.kind == VAR) {
1424 Symbol s = ident.sym = sym;
1425 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
1426 ident.type = s.type;
1427 return ((s.flags_field & Flags.ENUM) == 0)
1435 public void visitSynchronized(JCSynchronized tree) {
1436 chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
1437 attribStat(tree.body, env);
1441 public void visitTry(JCTry tree) {
1442 // Create a new local environment with a local
1443 Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
1445 boolean isTryWithResource = tree.resources.nonEmpty();
1446 // Create a nested environment for attributing the try block if needed
1447 Env<AttrContext> tryEnv = isTryWithResource ?
1448 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
1451 // Attribute resource declarations
1452 for (JCTree resource : tree.resources) {
1453 CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) {
1455 public void report(DiagnosticPosition pos, JCDiagnostic details) {
1456 chk.basicHandler.report(pos, diags.fragment("try.not.applicable.to.type", details));
1459 ResultInfo twrResult =
1460 new ResultInfo(KindSelector.VAR,
1461 syms.autoCloseableType,
1463 if (resource.hasTag(VARDEF)) {
1464 attribStat(resource, tryEnv);
1465 twrResult.check(resource, resource.type);
1467 //check that resource type cannot throw InterruptedException
1468 checkAutoCloseable(resource.pos(), localEnv, resource.type);
1470 VarSymbol var = ((JCVariableDecl) resource).sym;
1471 var.setData(ElementKind.RESOURCE_VARIABLE);
1473 attribTree(resource, tryEnv, twrResult);
1477 attribStat(tree.body, tryEnv);
1479 if (isTryWithResource)
1480 tryEnv.info.scope.leave();
1483 // Attribute catch clauses
1484 for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
1486 Env<AttrContext> catchEnv =
1487 localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup()));
1489 Type ctype = attribStat(c.param, catchEnv);
1490 if (TreeInfo.isMultiCatch(c)) {
1491 //multi-catch parameter is implicitly marked as final
1492 c.param.sym.flags_field |= FINAL | UNION;
1494 if (c.param.sym.kind == VAR) {
1495 c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
1497 chk.checkType(c.param.vartype.pos(),
1498 chk.checkClassType(c.param.vartype.pos(), ctype),
1499 syms.throwableType);
1500 attribStat(c.body, catchEnv);
1502 catchEnv.info.scope.leave();
1506 // Attribute finalizer
1507 if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
1511 localEnv.info.scope.leave();
1515 void checkAutoCloseable(DiagnosticPosition pos, Env<AttrContext> env, Type resource) {
1516 if (!resource.isErroneous() &&
1517 types.asSuper(resource, syms.autoCloseableType.tsym) != null &&
1518 !types.isSameType(resource, syms.autoCloseableType)) { // Don't emit warning for AutoCloseable itself
1519 Symbol close = syms.noSymbol;
1520 Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log);
1522 close = rs.resolveQualifiedMethod(pos,
1524 types.skipTypeVars(resource, false),
1530 log.popDiagnosticHandler(discardHandler);
1532 if (close.kind == MTH &&
1533 close.overrides(syms.autoCloseableClose, resource.tsym, types, true) &&
1534 chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes()) &&
1535 env.info.lint.isEnabled(LintCategory.TRY)) {
1536 log.warning(LintCategory.TRY, pos, "try.resource.throws.interrupted.exc", resource);
1541 public void visitConditional(JCConditional tree) {
1542 Type condtype = attribExpr(tree.cond, env, syms.booleanType);
1544 tree.polyKind = (!allowPoly ||
1545 pt().hasTag(NONE) && pt() != Type.recoveryType && pt() != Infer.anyPoly ||
1546 isBooleanOrNumeric(env, tree)) ?
1547 PolyKind.STANDALONE : PolyKind.POLY;
1549 if (tree.polyKind == PolyKind.POLY && resultInfo.pt.hasTag(VOID)) {
1550 //this means we are returning a poly conditional from void-compatible lambda expression
1551 resultInfo.checkContext.report(tree, diags.fragment("conditional.target.cant.be.void"));
1552 tree.polyKind = PolyKind.STANDALONE;
1555 ResultInfo condInfo = tree.polyKind == PolyKind.STANDALONE ?
1557 resultInfo.dup(conditionalContext(resultInfo.checkContext));
1559 Type truetype = attribTree(tree.truepart, env, condInfo);
1560 Type falsetype = attribTree(tree.falsepart, env, condInfo);
1562 Type owntype = (tree.polyKind == PolyKind.STANDALONE) ? condType(tree, truetype, falsetype) : pt();
1563 if (condtype.constValue() != null &&
1564 truetype.constValue() != null &&
1565 falsetype.constValue() != null &&
1566 !owntype.hasTag(NONE)) {
1568 owntype = cfolder.coerce(condtype.isTrue() ? truetype : falsetype, owntype);
1570 result = check(tree, owntype, KindSelector.VAL, resultInfo);
1573 private boolean isBooleanOrNumeric(Env<AttrContext> env, JCExpression tree) {
1574 switch (tree.getTag()) {
1575 case LITERAL: return ((JCLiteral)tree).typetag.isSubRangeOf(DOUBLE) ||
1576 ((JCLiteral)tree).typetag == BOOLEAN ||
1577 ((JCLiteral)tree).typetag == BOT;
1578 case LAMBDA: case REFERENCE: return false;
1579 case PARENS: return isBooleanOrNumeric(env, ((JCParens)tree).expr);
1581 JCConditional condTree = (JCConditional)tree;
1582 return isBooleanOrNumeric(env, condTree.truepart) &&
1583 isBooleanOrNumeric(env, condTree.falsepart);
1585 JCMethodInvocation speculativeMethodTree =
1586 (JCMethodInvocation)deferredAttr.attribSpeculative(
1587 tree, env, unknownExprInfo,
1588 argumentAttr.withLocalCacheContext());
1589 Symbol msym = TreeInfo.symbol(speculativeMethodTree.meth);
1590 Type receiverType = speculativeMethodTree.meth.hasTag(IDENT) ?
1591 env.enclClass.type :
1592 ((JCFieldAccess)speculativeMethodTree.meth).selected.type;
1593 Type owntype = types.memberType(receiverType, msym).getReturnType();
1594 return primitiveOrBoxed(owntype);
1596 JCExpression className =
1597 removeClassParams.translate(((JCNewClass)tree).clazz);
1598 JCExpression speculativeNewClassTree =
1599 (JCExpression)deferredAttr.attribSpeculative(
1600 className, env, unknownTypeInfo,
1601 argumentAttr.withLocalCacheContext());
1602 return primitiveOrBoxed(speculativeNewClassTree.type);
1604 Type speculativeType = deferredAttr.attribSpeculative(tree, env, unknownExprInfo,
1605 argumentAttr.withLocalCacheContext()).type;
1606 return primitiveOrBoxed(speculativeType);
1610 boolean primitiveOrBoxed(Type t) {
1611 return (!t.hasTag(TYPEVAR) && types.unboxedTypeOrType(t).isPrimitive());
1614 TreeTranslator removeClassParams = new TreeTranslator() {
1616 public void visitTypeApply(JCTypeApply tree) {
1617 result = translate(tree.clazz);
1621 CheckContext conditionalContext(CheckContext checkContext) {
1622 return new Check.NestedCheckContext(checkContext) {
1623 //this will use enclosing check context to check compatibility of
1624 //subexpression against target type; if we are in a method check context,
1625 //depending on whether boxing is allowed, we could have incompatibilities
1627 public void report(DiagnosticPosition pos, JCDiagnostic details) {
1628 enclosingContext.report(pos, diags.fragment("incompatible.type.in.conditional", details));
1633 /** Compute the type of a conditional expression, after
1634 * checking that it exists. See JLS 15.25. Does not take into
1635 * account the special case where condition and both arms
1638 * @param pos The source position to be used for error
1640 * @param thentype The type of the expression's then-part.
1641 * @param elsetype The type of the expression's else-part.
1643 Type condType(DiagnosticPosition pos,
1644 Type thentype, Type elsetype) {
1645 // If same type, that is the result
1646 if (types.isSameType(thentype, elsetype))
1647 return thentype.baseType();
1649 Type thenUnboxed = (thentype.isPrimitive())
1650 ? thentype : types.unboxedType(thentype);
1651 Type elseUnboxed = (elsetype.isPrimitive())
1652 ? elsetype : types.unboxedType(elsetype);
1654 // Otherwise, if both arms can be converted to a numeric
1655 // type, return the least numeric type that fits both arms
1656 // (i.e. return larger of the two, or return int if one
1657 // arm is short, the other is char).
1658 if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) {
1659 // If one arm has an integer subrange type (i.e., byte,
1660 // short, or char), and the other is an integer constant
1661 // that fits into the subrange, return the subrange type.
1662 if (thenUnboxed.getTag().isStrictSubRangeOf(INT) &&
1663 elseUnboxed.hasTag(INT) &&
1664 types.isAssignable(elseUnboxed, thenUnboxed)) {
1665 return thenUnboxed.baseType();
1667 if (elseUnboxed.getTag().isStrictSubRangeOf(INT) &&
1668 thenUnboxed.hasTag(INT) &&
1669 types.isAssignable(thenUnboxed, elseUnboxed)) {
1670 return elseUnboxed.baseType();
1673 for (TypeTag tag : primitiveTags) {
1674 Type candidate = syms.typeOfTag[tag.ordinal()];
1675 if (types.isSubtype(thenUnboxed, candidate) &&
1676 types.isSubtype(elseUnboxed, candidate)) {
1682 // Those were all the cases that could result in a primitive
1683 if (thentype.isPrimitive())
1684 thentype = types.boxedClass(thentype).type;
1685 if (elsetype.isPrimitive())
1686 elsetype = types.boxedClass(elsetype).type;
1688 if (types.isSubtype(thentype, elsetype))
1689 return elsetype.baseType();
1690 if (types.isSubtype(elsetype, thentype))
1691 return thentype.baseType();
1693 if (thentype.hasTag(VOID) || elsetype.hasTag(VOID)) {
1694 log.error(pos, "neither.conditional.subtype",
1695 thentype, elsetype);
1696 return thentype.baseType();
1699 // both are known to be reference types. The result is
1700 // lub(thentype,elsetype). This cannot fail, as it will
1701 // always be possible to infer "Object" if nothing better.
1702 return types.lub(thentype.baseType(), elsetype.baseType());
1705 final static TypeTag[] primitiveTags = new TypeTag[]{
1716 public void visitIf(JCIf tree) {
1717 attribExpr(tree.cond, env, syms.booleanType);
1718 attribStat(tree.thenpart, env);
1719 if (tree.elsepart != null)
1720 attribStat(tree.elsepart, env);
1721 chk.checkEmptyIf(tree);
1725 public void visitExec(JCExpressionStatement tree) {
1726 //a fresh environment is required for 292 inference to work properly ---
1727 //see Infer.instantiatePolymorphicSignatureInstance()
1728 Env<AttrContext> localEnv = env.dup(tree);
1729 attribExpr(tree.expr, localEnv);
1733 public void visitBreak(JCBreak tree) {
1734 tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
1738 public void visitContinue(JCContinue tree) {
1739 tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
1743 /** Return the target of a break or continue statement, if it exists,
1744 * report an error if not.
1745 * Note: The target of a labelled break or continue is the
1746 * (non-labelled) statement tree referred to by the label,
1747 * not the tree representing the labelled statement itself.
1749 * @param pos The position to be used for error diagnostics
1750 * @param tag The tag of the jump statement. This is either
1751 * Tree.BREAK or Tree.CONTINUE.
1752 * @param label The label of the jump statement, or null if no
1754 * @param env The environment current at the jump statement.
1756 private JCTree findJumpTarget(DiagnosticPosition pos,
1759 Env<AttrContext> env) {
1760 // Search environments outwards from the point of jump.
1761 Env<AttrContext> env1 = env;
1763 while (env1 != null) {
1764 switch (env1.tree.getTag()) {
1766 JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
1767 if (label == labelled.label) {
1768 // If jump is a continue, check that target is a loop.
1769 if (tag == CONTINUE) {
1770 if (!labelled.body.hasTag(DOLOOP) &&
1771 !labelled.body.hasTag(WHILELOOP) &&
1772 !labelled.body.hasTag(FORLOOP) &&
1773 !labelled.body.hasTag(FOREACHLOOP))
1774 log.error(pos, "not.loop.label", label);
1775 // Found labelled statement target, now go inwards
1776 // to next non-labelled tree.
1777 return TreeInfo.referencedStatement(labelled);
1787 if (label == null) return env1.tree;
1790 if (label == null && tag == BREAK) return env1.tree;
1801 log.error(pos, "undef.label", label);
1802 else if (tag == CONTINUE)
1803 log.error(pos, "cont.outside.loop");
1805 log.error(pos, "break.outside.switch.loop");
1809 public void visitReturn(JCReturn tree) {
1810 // Check that there is an enclosing method which is
1811 // nested within than the enclosing class.
1812 if (env.info.returnResult == null) {
1813 log.error(tree.pos(), "ret.outside.meth");
1815 // Attribute return expression, if it exists, and check that
1816 // it conforms to result type of enclosing method.
1817 if (tree.expr != null) {
1818 if (env.info.returnResult.pt.hasTag(VOID)) {
1819 env.info.returnResult.checkContext.report(tree.expr.pos(),
1820 diags.fragment("unexpected.ret.val"));
1822 attribTree(tree.expr, env, env.info.returnResult);
1823 } else if (!env.info.returnResult.pt.hasTag(VOID) &&
1824 !env.info.returnResult.pt.hasTag(NONE)) {
1825 env.info.returnResult.checkContext.report(tree.pos(),
1826 diags.fragment("missing.ret.val"));
1832 public void visitThrow(JCThrow tree) {
1833 Type owntype = attribExpr(tree.expr, env, allowPoly ? Type.noType : syms.throwableType);
1835 chk.checkType(tree, owntype, syms.throwableType);
1840 public void visitAssert(JCAssert tree) {
1841 attribExpr(tree.cond, env, syms.booleanType);
1842 if (tree.detail != null) {
1843 chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
1848 /** Visitor method for method invocations.
1849 * NOTE: The method part of an application will have in its type field
1850 * the return type of the method, not the method's type itself!
1852 public void visitApply(JCMethodInvocation tree) {
1853 // The local environment of a method application is
1854 // a new environment nested in the current one.
1855 Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
1857 // The types of the actual method arguments.
1858 List<Type> argtypes = null;
1860 // The types of the actual method type arguments.
1861 List<Type> typeargtypes = null;
1863 Name methName = TreeInfo.name(tree.meth);
1865 boolean isConstructorCall =
1866 methName == names._this || methName == names._super;
1868 ListBuffer<Type> argtypesBuf = new ListBuffer<>();
1869 if (isConstructorCall) {
1870 // We are seeing a ...this(...) or ...super(...) call.
1871 // Check that this is the first statement in a constructor.
1872 checkFirstConstructorStat(tree, env);
1875 // that this is a constructor call (using isSelfCall).
1876 localEnv.info.isSelfCall = true;
1878 // Attribute arguments, yielding list of argument types.
1879 KindSelector kind = attribArgs(KindSelector.MTH, tree.args, localEnv, argtypesBuf);
1880 argtypes = argtypesBuf.toList();
1881 typeargtypes = attribTypes(tree.typeargs, localEnv);
1883 // Variable `site' points to the class in which the called
1884 // constructor is defined.
1885 Type site = env.enclClass.sym.type;
1886 if (methName == names._super) {
1887 if (site == syms.objectType) {
1888 log.error(tree.meth.pos(), "no.superclass", site);
1889 site = types.createErrorType(syms.objectType);
1891 site = types.supertype(site);
1895 if (site.hasTag(CLASS) || site.hasTag(ERROR)) {
1896 Type encl = site.getEnclosingType();
1897 while (encl != null && encl.hasTag(TYPEVAR))
1898 encl = encl.getUpperBound();
1899 if (encl.hasTag(CLASS)) {
1900 // we are calling a nested class
1902 if (tree.meth.hasTag(SELECT)) {
1903 JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
1905 // We are seeing a prefixed call, of the form
1906 // <expr>.super(...).
1907 // Check that the prefix expression conforms
1908 // to the outer instance type of the class.
1909 chk.checkRefType(qualifier.pos(),
1910 attribExpr(qualifier, localEnv,
1912 } else if (methName == names._super) {
1913 // qualifier omitted; check for existence
1914 // of an appropriate implicit qualifier.
1915 rs.resolveImplicitThis(tree.meth.pos(),
1916 localEnv, site, true);
1918 } else if (tree.meth.hasTag(SELECT)) {
1919 log.error(tree.meth.pos(), "illegal.qual.not.icls",
1923 // if we're calling a java.lang.Enum constructor,
1924 // prefix the implicit String and int parameters
1925 if (site.tsym == syms.enumSym)
1926 argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
1928 // Resolve the called constructor under the assumption
1929 // that we are referring to a superclass instance of the
1930 // current instance (JLS ???).
1931 boolean selectSuperPrev = localEnv.info.selectSuper;
1932 localEnv.info.selectSuper = true;
1933 localEnv.info.pendingResolutionPhase = null;
1934 Symbol sym = rs.resolveConstructor(
1935 tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
1936 localEnv.info.selectSuper = selectSuperPrev;
1938 // Set method symbol to resolved constructor...
1939 TreeInfo.setSymbol(tree.meth, sym);
1941 // ...and check that it is legal in the current context.
1942 // (this will also set the tree's type)
1943 Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
1944 checkId(tree.meth, site, sym, localEnv,
1945 new ResultInfo(kind, mpt));
1947 result = tree.type = syms.voidType;
1949 // Otherwise, we are seeing a regular method call.
1950 // Attribute the arguments, yielding list of argument types, ...
1953 kind = attribArgs(KindSelector.VAL, tree.args, localEnv, argtypesBuf);
1954 } catch (BreakAttr bae) {
1955 argtypes = argtypesBuf.toList();
1956 typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
1957 Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
1958 localEnv.info.pendingResolutionPhase = null;
1959 attribTree(tree.meth, localEnv, new ResultInfo(KindSelector.VAL_POLY, mpt, resultInfo.checkContext));
1962 argtypes = argtypesBuf.toList();
1963 typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
1965 // ... and attribute the method using as a prototype a methodtype
1966 // whose formal argument types is exactly the list of actual
1967 // arguments (this will also set the method symbol).
1968 Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
1969 localEnv.info.pendingResolutionPhase = null;
1970 Type mtype = attribTree(tree.meth, localEnv, new ResultInfo(kind, mpt, resultInfo.checkContext));
1972 // Compute the result type.
1973 Type restype = mtype.getReturnType();
1974 if (restype.hasTag(WILDCARD))
1975 throw new AssertionError(mtype);
1977 Type qualifier = (tree.meth.hasTag(SELECT))
1978 ? ((JCFieldAccess) tree.meth).selected.type
1979 : env.enclClass.sym.type;
1980 Symbol msym = TreeInfo.symbol(tree.meth);
1981 restype = adjustMethodReturnType(msym, qualifier, methName, argtypes, restype);
1983 chk.checkRefTypes(tree.typeargs, typeargtypes);
1985 // Check that value of resulting type is admissible in the
1986 // current context. Also, capture the return type
1987 Type capturedRes = resultInfo.checkContext.inferenceContext().cachedCapture(tree, restype, true);
1988 result = check(tree, capturedRes, KindSelector.VAL, resultInfo);
1990 chk.validate(tree.typeargs, localEnv);
1993 Type adjustMethodReturnType(Symbol msym, Type qualifierType, Name methodName, List<Type> argtypes, Type restype) {
1995 msym.owner == syms.objectType.tsym &&
1996 methodName == names.getClass &&
1997 argtypes.isEmpty()) {
1998 // as a special case, x.getClass() has type Class<? extends |X|>
1999 return new ClassType(restype.getEnclosingType(),
2000 List.of(new WildcardType(types.erasure(qualifierType),
2004 restype.getMetadata());
2005 } else if (msym != null &&
2006 msym.owner == syms.arrayClass &&
2007 methodName == names.clone &&
2008 types.isArray(qualifierType)) {
2009 // as a special case, array.clone() has a result that is
2010 // the same as static type of the array being cloned
2011 return qualifierType;
2017 /** Check that given application node appears as first statement
2018 * in a constructor call.
2019 * @param tree The application node
2020 * @param env The environment current at the application.
2022 boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) {
2023 JCMethodDecl enclMethod = env.enclMethod;
2024 if (enclMethod != null && enclMethod.name == names.init) {
2025 JCBlock body = enclMethod.body;
2026 if (body.stats.head.hasTag(EXEC) &&
2027 ((JCExpressionStatement) body.stats.head).expr == tree)
2030 log.error(tree.pos(),"call.must.be.first.stmt.in.ctor",
2031 TreeInfo.name(tree.meth));
2035 /** Obtain a method type with given argument types.
2037 Type newMethodTemplate(Type restype, List<Type> argtypes, List<Type> typeargtypes) {
2038 MethodType mt = new MethodType(argtypes, restype, List.nil(), syms.methodClass);
2039 return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
2042 public void visitNewClass(final JCNewClass tree) {
2043 Type owntype = types.createErrorType(tree.type);
2045 // The local environment of a class creation is
2046 // a new environment nested in the current one.
2047 Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
2049 // The anonymous inner class definition of the new expression,
2050 // if one is defined by it.
2051 JCClassDecl cdef = tree.def;
2053 // If enclosing class is given, attribute it, and
2054 // complete class name to be fully qualified
2055 JCExpression clazz = tree.clazz; // Class field following new
2056 JCExpression clazzid; // Identifier in class field
2057 JCAnnotatedType annoclazzid; // Annotated type enclosing clazzid
2060 if (clazz.hasTag(TYPEAPPLY)) {
2061 clazzid = ((JCTypeApply) clazz).clazz;
2062 if (clazzid.hasTag(ANNOTATED_TYPE)) {
2063 annoclazzid = (JCAnnotatedType) clazzid;
2064 clazzid = annoclazzid.underlyingType;
2067 if (clazz.hasTag(ANNOTATED_TYPE)) {
2068 annoclazzid = (JCAnnotatedType) clazz;
2069 clazzid = annoclazzid.underlyingType;
2075 JCExpression clazzid1 = clazzid; // The same in fully qualified form
2077 if (tree.encl != null) {
2078 // We are seeing a qualified new, of the form
2079 // <expr>.new C <...> (...) ...
2080 // In this case, we let clazz stand for the name of the
2081 // allocated class C prefixed with the type of the qualifier
2082 // expression, so that we can
2083 // resolve it with standard techniques later. I.e., if
2084 // <expr> has type T, then <expr>.new C <...> (...)
2085 // yields a clazz T.C.
2086 Type encltype = chk.checkRefType(tree.encl.pos(),
2087 attribExpr(tree.encl, env));
2088 // TODO 308: in <expr>.new C, do we also want to add the type annotations
2089 // from expr to the combined type, or not? Yes, do this.
2090 clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
2091 ((JCIdent) clazzid).name);
2093 EndPosTable endPosTable = this.env.toplevel.endPositions;
2094 endPosTable.storeEnd(clazzid1, tree.getEndPosition(endPosTable));
2095 if (clazz.hasTag(ANNOTATED_TYPE)) {
2096 JCAnnotatedType annoType = (JCAnnotatedType) clazz;
2097 List<JCAnnotation> annos = annoType.annotations;
2099 if (annoType.underlyingType.hasTag(TYPEAPPLY)) {
2100 clazzid1 = make.at(tree.pos).
2102 ((JCTypeApply) clazz).arguments);
2105 clazzid1 = make.at(tree.pos).
2106 AnnotatedType(annos, clazzid1);
2107 } else if (clazz.hasTag(TYPEAPPLY)) {
2108 clazzid1 = make.at(tree.pos).
2110 ((JCTypeApply) clazz).arguments);
2116 // Attribute clazz expression and store
2117 // symbol + type back into the attributed tree.
2121 env.info.isNewClass = true;
2122 clazztype = TreeInfo.isEnumInit(env.tree) ?
2123 attribIdentAsEnumType(env, (JCIdent)clazz) :
2124 attribType(clazz, env);
2126 env.info.isNewClass = false;
2129 clazztype = chk.checkDiamond(tree, clazztype);
2130 chk.validate(clazz, localEnv);
2131 if (tree.encl != null) {
2132 // We have to work in this case to store
2133 // symbol + type back into the attributed tree.
2134 tree.clazz.type = clazztype;
2135 TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
2136 clazzid.type = ((JCIdent) clazzid).sym.type;
2137 if (annoclazzid != null) {
2138 annoclazzid.type = clazzid.type;
2140 if (!clazztype.isErroneous()) {
2141 if (cdef != null && clazztype.tsym.isInterface()) {
2142 log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new");
2143 } else if (clazztype.tsym.isStatic()) {
2144 log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym);
2147 } else if (!clazztype.tsym.isInterface() &&
2148 clazztype.getEnclosingType().hasTag(CLASS)) {
2149 // Check for the existence of an apropos outer instance
2150 rs.resolveImplicitThis(tree.pos(), env, clazztype);
2153 // Attribute constructor arguments.
2154 ListBuffer<Type> argtypesBuf = new ListBuffer<>();
2155 final KindSelector pkind =
2156 attribArgs(KindSelector.VAL, tree.args, localEnv, argtypesBuf);
2157 List<Type> argtypes = argtypesBuf.toList();
2158 List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
2160 // If we have made no mistakes in the class type...
2161 boolean wasError = clazztype.hasTag(ERROR);
2162 if (clazztype.hasTag(CLASS) || wasError) {
2163 // Enums may not be instantiated except implicitly
2164 if ((clazztype.tsym.flags_field & Flags.ENUM) != 0 &&
2165 (!env.tree.hasTag(VARDEF) ||
2166 (((JCVariableDecl) env.tree).mods.flags & Flags.ENUM) == 0 ||
2167 ((JCVariableDecl) env.tree).init != tree))
2168 log.error(tree.pos(), "enum.cant.be.instantiated");
2170 boolean isSpeculativeDiamondInferenceRound = TreeInfo.isDiamond(tree) &&
2171 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
2172 boolean skipNonDiamondPath = false;
2173 // Check that class is not abstract
2174 if (cdef == null && !isSpeculativeDiamondInferenceRound && // class body may be nulled out in speculative tree copy
2175 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
2176 log.error(tree.pos(), "abstract.cant.be.instantiated",
2178 skipNonDiamondPath = true;
2179 } else if (cdef != null && clazztype.tsym.isInterface()) {
2180 // Check that no constructor arguments are given to
2181 // anonymous classes implementing an interface
2182 if (!argtypes.isEmpty())
2183 log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args");
2185 if (!typeargtypes.isEmpty())
2186 log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs");
2188 // Error recovery: pretend no arguments were supplied.
2189 argtypes = List.nil();
2190 typeargtypes = List.nil();
2191 skipNonDiamondPath = true;
2193 if (TreeInfo.isDiamond(tree) && !wasError) {
2194 ClassType site = new ClassType(clazztype.getEnclosingType(),
2195 clazztype.tsym.type.getTypeArguments(),
2197 clazztype.getMetadata());
2199 Env<AttrContext> diamondEnv = localEnv.dup(tree);
2200 diamondEnv.info.selectSuper = cdef != null;
2201 diamondEnv.info.pendingResolutionPhase = null;
2203 //if the type of the instance creation expression is a class type
2204 //apply method resolution inference (JLS 15.12.2.7). The return type
2205 //of the resolved constructor will be a partially instantiated type
2206 Symbol constructor = rs.resolveDiamond(tree.pos(),
2211 tree.constructor = constructor.baseSymbol();
2213 final TypeSymbol csym = clazztype.tsym;
2214 ResultInfo diamondResult = new ResultInfo(pkind, newMethodTemplate(resultInfo.pt, argtypes, typeargtypes),
2215 diamondContext(tree, csym, resultInfo.checkContext), CheckMode.NO_TREE_UPDATE);
2216 Type constructorType = tree.constructorType = types.createErrorType(clazztype);
2217 constructorType = checkId(tree, site,
2222 tree.clazz.type = types.createErrorType(clazztype);
2223 if (!constructorType.isErroneous()) {
2224 tree.clazz.type = clazz.type = constructorType.getReturnType();
2225 tree.constructorType = types.createMethodTypeWithReturn(constructorType, syms.voidType);
2226 } else if (errArgs(tree.args)) {
2228 for (Symbol sym : site.tsym.members().getSymbolsByName(names.init)) {
2229 if (s == null || sym.asType().getParameterTypes().isEmpty())
2233 List<Type> atypes = s.asType().getParameterTypes();
2234 constructor = rs.resolveDiamond(tree.pos(),
2239 diamondResult = new ResultInfo(KindSelector.MTH, newMethodTemplate(resultInfo.pt, atypes, typeargtypes), new Check.NestedCheckContext(resultInfo.checkContext) {
2241 public void report(DiagnosticPosition _unused, JCDiagnostic details) {
2244 constructorType = checkId(tree, site,
2248 if (!constructorType.isErroneous())
2249 tree.clazz.type = constructorType.getReturnType();
2252 clazztype = chk.checkClassType(tree.clazz, tree.clazz.type, true);
2255 // Resolve the called constructor under the assumption
2256 // that we are referring to a superclass instance of the
2257 // current instance (JLS ???).
2258 else if (!skipNonDiamondPath) {
2259 //the following code alters some of the fields in the current
2260 //AttrContext - hence, the current context must be dup'ed in
2261 //order to avoid downstream failures
2262 Env<AttrContext> rsEnv = localEnv.dup(tree);
2263 rsEnv.info.selectSuper = cdef != null;
2264 rsEnv.info.pendingResolutionPhase = null;
2265 tree.constructor = rs.resolveConstructor(
2266 tree.pos(), rsEnv, clazztype, argtypes, typeargtypes);
2267 if (cdef == null) { //do not check twice!
2268 tree.constructorType = checkId(tree,
2272 new ResultInfo(pkind, newMethodTemplate(syms.voidType, argtypes, typeargtypes), CheckMode.NO_TREE_UPDATE));
2273 if (rsEnv.info.lastResolveVarargs())
2274 Assert.check(tree.constructorType.isErroneous() || tree.varargsElement != null);
2275 Env<AttrContext> enclosing;
2276 if (tree.constructor.kind == MTH && tree.constructor.type.isErroneous() && ((enclosing = enter.getEnv(tree.constructor.enclClass())) == null || enclosing.toplevel != env.toplevel)) {
2277 log.error(tree, "type.error", tree.constructor);
2283 visitAnonymousClassDefinition(tree, clazz, clazztype, cdef, localEnv, argtypes, typeargtypes, pkind);
2287 if (tree.constructor != null && tree.constructor.kind == MTH)
2288 owntype = wasError ? types.createErrorType(clazztype) : clazztype;
2290 result = check(tree, owntype, KindSelector.VAL, resultInfo);
2291 InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
2292 if (tree.constructorType != null && inferenceContext.free(tree.constructorType)) {
2293 //we need to wait for inference to finish and then replace inference vars in the constructor type
2294 inferenceContext.addFreeTypeListener(List.of(tree.constructorType),
2295 instantiatedContext -> {
2296 tree.constructorType = instantiatedContext.asInstType(tree.constructorType);
2299 chk.validate(tree.typeargs, localEnv);
2302 private boolean errArgs(List<JCExpression> args) {
2303 for (JCExpression arg : args) {
2304 if (arg.hasTag(Tag.ERRONEOUS))
2311 private void visitAnonymousClassDefinition(JCNewClass tree, JCExpression clazz, Type clazztype,
2312 JCClassDecl cdef, Env<AttrContext> localEnv,
2313 List<Type> argtypes, List<Type> typeargtypes,
2314 KindSelector pkind) {
2315 // We are seeing an anonymous class instance creation.
2316 // In this case, the class instance creation
2319 // E.new <typeargs1>C<typargs2>(args) { ... }
2321 // is represented internally as
2323 // E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } ) .
2325 // This expression is then *transformed* as follows:
2327 // (1) add an extends or implements clause
2328 // (2) add a constructor.
2330 // For instance, if C is a class, and ET is the type of E,
2333 // E.new <typeargs1>C<typargs2>(args) { ... }
2335 // is translated to (where X is a fresh name and typarams is the
2336 // parameter list of the super constructor):
2338 // new <typeargs1>X(<*nullchk*>E, args) where
2339 // X extends C<typargs2> {
2340 // <typarams> X(ET e, args) {
2341 // e.<typeargs1>super(args)
2345 InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
2346 final boolean isDiamond = TreeInfo.isDiamond(tree);
2348 && ((tree.constructorType != null && inferenceContext.free(tree.constructorType))
2349 || (tree.clazz.type != null && inferenceContext.free(tree.clazz.type)))) {
2350 final ResultInfo resultInfoForClassDefinition = this.resultInfo;
2351 inferenceContext.addFreeTypeListener(List.of(tree.constructorType, tree.clazz.type),
2352 instantiatedContext -> {
2353 tree.constructorType = instantiatedContext.asInstType(tree.constructorType);
2354 tree.clazz.type = clazz.type = instantiatedContext.asInstType(clazz.type);
2355 ResultInfo prevResult = this.resultInfo;
2357 this.resultInfo = resultInfoForClassDefinition;
2358 visitAnonymousClassDefinition(tree, clazz, clazz.type, cdef,
2359 localEnv, argtypes, typeargtypes, pkind);
2361 this.resultInfo = prevResult;
2365 if (isDiamond && clazztype.hasTag(CLASS)) {
2366 List<Type> invalidDiamondArgs = chk.checkDiamondDenotable((ClassType)clazztype);
2367 if (!clazztype.isErroneous() && invalidDiamondArgs.nonEmpty()) {
2368 // One or more types inferred in the previous steps is non-denotable.
2369 Fragment fragment = Diamond(clazztype.tsym);
2370 log.error(tree.clazz.pos(),
2371 Errors.CantApplyDiamond1(
2373 invalidDiamondArgs.size() > 1 ?
2374 DiamondInvalidArgs(invalidDiamondArgs, fragment) :
2375 DiamondInvalidArg(invalidDiamondArgs, fragment)));
2377 // For <>(){}, inferred types must also be accessible.
2378 for (Type t : clazztype.getTypeArguments()) {
2379 rs.checkAccessibleType(env, t);
2383 // If we already errored, be careful to avoid a further avalanche. ErrorType answers
2384 // false for isInterface call even when the original type is an interface.
2385 boolean implementing = clazztype.tsym.isInterface() ||
2386 clazztype.isErroneous() && !clazztype.getOriginalType().hasTag(NONE) && clazztype.getOriginalType().tsym.isInterface();
2389 cdef.implementing = List.of(clazz);
2391 cdef.extending = clazz;
2394 if (resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
2395 isSerializable(clazztype)) {
2396 localEnv.info.isSerializable = true;
2399 attribStat(cdef, localEnv);
2401 JCExpression clazzCopy = new TreeCopier<JCTree>(make) {
2403 public <T extends JCTree> T copy(T tree, JCTree p) {
2404 T t = super.copy(tree, p);
2406 t.pos = Position.NOPOS;
2412 @Override public JCTree visitIdentifier(IdentifierTree node, JCTree p) {
2413 JCIdent result = (JCIdent) super.visitIdentifier(node, p);
2415 result.sym = ((JCIdent) node).sym;
2420 @Override public JCTree visitMemberSelect(MemberSelectTree node, JCTree p) {
2421 JCFieldAccess result = (JCFieldAccess) super.visitMemberSelect(node, p);
2423 result.sym = ((JCFieldAccess) node).sym;
2428 if (clazztype.tsym.isInterface()) {
2429 cdef.implementing = List.of(clazzCopy);
2431 cdef.extending = clazzCopy;
2434 List<Type> finalargtypes;
2435 // If an outer instance is given,
2436 // prefix it to the constructor arguments
2437 // "encl" will be cleared in TransTypes
2438 if (tree.encl != null && !clazztype.tsym.isInterface()) {
2439 tree.args = tree.args.prepend(makeNullCheck(tree.encl));
2440 finalargtypes = argtypes.prepend(tree.encl.type);
2442 finalargtypes = argtypes;
2445 // Reassign clazztype and recompute constructor. As this necessarily involves
2446 // another attribution pass for deferred types in the case of <>, replicate
2447 // them. Original arguments have right decorations already.
2448 if (isDiamond && pkind.contains(KindSelector.POLY)) {
2449 finalargtypes = finalargtypes.map(deferredAttr.deferredCopier);
2452 clazztype = cdef.sym.type;
2453 Symbol sym = tree.constructor = rs.resolveConstructor(
2454 tree.pos(), localEnv, clazztype, finalargtypes, typeargtypes);
2455 Assert.check(!sym.kind.isResolutionError());
2456 tree.constructor = sym;
2457 tree.constructorType = checkId(tree,
2461 new ResultInfo(pkind, newMethodTemplate(syms.voidType, finalargtypes, typeargtypes), CheckMode.NO_TREE_UPDATE));
2463 Type owntype = (tree.constructor != null && tree.constructor.kind == MTH) ?
2464 clazztype : types.createErrorType(tree.type);
2465 result = check(tree, owntype, KindSelector.VAL, resultInfo.dup(CheckMode.NO_INFERENCE_HOOK));
2466 chk.validate(tree.typeargs, localEnv);
2469 CheckContext diamondContext(JCNewClass clazz, TypeSymbol tsym, CheckContext checkContext) {
2470 return new Check.NestedCheckContext(checkContext) {
2472 public void report(DiagnosticPosition _unused, JCDiagnostic details) {
2473 enclosingContext.report(clazz.clazz,
2474 diags.fragment("cant.apply.diamond.1", diags.fragment("diamond", tsym), details));
2479 /** Make an attributed null check tree.
2481 public JCExpression makeNullCheck(JCExpression arg) {
2482 // optimization: new Outer() can never be null; skip null check
2483 if (arg.getTag() == NEWCLASS)
2485 // optimization: X.this is never null; skip null check
2486 Name name = TreeInfo.name(arg);
2487 if (name == names._this || name == names._super) return arg;
2489 JCTree.Tag optag = NULLCHK;
2490 JCUnary tree = make.at(Position.NOPOS).Unary(optag, arg);
2491 tree.operator = operators.resolveUnary(arg, optag, arg.type);
2492 tree.type = arg.type;
2496 public void visitNewArray(JCNewArray tree) {
2497 Type owntype = types.createErrorType(tree.type);
2498 Env<AttrContext> localEnv = env.dup(tree);
2500 if (tree.elemtype != null) {
2501 elemtype = attribType(tree.elemtype, localEnv);
2502 chk.validate(tree.elemtype, localEnv);
2504 for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
2505 attribExpr(l.head, localEnv, syms.intType);
2506 owntype = new ArrayType(owntype, syms.arrayClass);
2509 // we are seeing an untyped aggregate { ... }
2510 // this is allowed only if the prototype is an array
2511 if (pt().hasTag(ARRAY)) {
2512 elemtype = types.elemtype(pt());
2514 if (!pt().hasTag(ERROR)) {
2515 log.error(tree.pos(), "illegal.initializer.for.type",
2518 elemtype = types.createErrorType(pt());
2521 if (tree.elems != null) {
2522 attribExprs(tree.elems, localEnv, elemtype);
2523 owntype = new ArrayType(elemtype, syms.arrayClass);
2525 if (!types.isReifiable(elemtype))
2526 log.error(tree.pos(), "generic.array.creation");
2527 result = check(tree, owntype, KindSelector.VAL, resultInfo);
2531 * A lambda expression can only be attributed when a target-type is available.
2532 * In addition, if the target-type is that of a functional interface whose
2533 * descriptor contains inference variables in argument position the lambda expression
2534 * is 'stuck' (see DeferredAttr).
2537 public void visitLambda(final JCLambda that) {
2538 if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
2539 if (pt().hasTag(NONE)) {
2540 //lambda only allowed in assignment or method invocation/cast context
2541 log.error(that.pos(), "unexpected.lambda");
2544 //create an environment for attribution of the lambda expression
2545 final Env<AttrContext> localEnv = lambdaEnv(that, env);
2546 boolean needsRecovery = resultInfo != recoveryInfo &&
2547 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK;
2548 Type currentTarget = null;
2550 if (needsRecovery && isSerializable(pt())) {
2551 localEnv.info.isSerializable = true;
2552 localEnv.info.isLambda = true;
2554 List<Type> explicitParamTypes = null;
2555 if (that.paramKind == JCLambda.ParameterKind.EXPLICIT) {
2556 //attribute lambda parameters
2557 attribStats(that.params, localEnv);
2558 explicitParamTypes = TreeInfo.types(that.params);
2561 if (pt().hasTag(NONE) && pt() != Type.recoveryType) {
2562 resultInfo = recoveryInfo;
2564 TargetInfo targetInfo = getTargetInfo(that, resultInfo, explicitParamTypes);
2565 currentTarget = targetInfo.target;
2566 Type lambdaType = targetInfo.descriptor;
2568 if (currentTarget.isErroneous()) {
2569 result = that.type = currentTarget;
2573 setFunctionalInfo(localEnv, that, pt(), lambdaType, currentTarget, resultInfo.checkContext);
2575 if (lambdaType.hasTag(FORALL)) {
2576 //lambda expression target desc cannot be a generic method
2577 resultInfo.checkContext.report(that, diags.fragment("invalid.generic.lambda.target",
2578 lambdaType, kindName(currentTarget.tsym), currentTarget.tsym));
2579 result = that.type = types.createErrorType(pt());
2583 if (that.paramKind == JCLambda.ParameterKind.IMPLICIT) {
2584 //add param type info in the AST
2585 List<Type> actuals = lambdaType.getParameterTypes();
2586 List<JCVariableDecl> params = that.params;
2588 boolean arityMismatch = false;
2590 while (params.nonEmpty()) {
2591 if (actuals.isEmpty()) {
2592 //not enough actuals to perform lambda parameter inference
2593 arityMismatch = true;
2595 //reset previously set info
2596 Type argType = arityMismatch ?
2599 params.head.vartype = make.at(Position.NOPOS).Type(argType);
2600 params.head.sym = null;
2601 actuals = actuals.isEmpty() ?
2604 params = params.tail;
2607 //attribute lambda parameters
2608 attribStats(that.params, localEnv);
2610 if (arityMismatch) {
2611 resultInfo.checkContext.report(that, diags.fragment("incompatible.arg.types.in.lambda"));
2612 result = that.type = types.createErrorType(currentTarget);
2617 //from this point on, no recovery is needed; if we are in assignment context
2618 //we will be able to attribute the whole lambda body, regardless of errors;
2619 //if we are in a 'check' method context, and the lambda is not compatible
2620 //with the target-type, it will be recovered anyway in Attr.checkId
2621 needsRecovery = false;
2623 ResultInfo bodyResultInfo = localEnv.info.returnResult =
2624 lambdaBodyResult(that, lambdaType, resultInfo);
2626 if (that.getBodyKind() == JCLambda.BodyKind.EXPRESSION) {
2627 attribTree(that.getBody(), localEnv, bodyResultInfo);
2629 JCBlock body = (JCBlock)that.body;
2630 if (body == breakTree &&
2631 resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
2632 throw new BreakAttr(copyEnv(localEnv), null);
2634 attribStats(body.stats, localEnv);
2637 result = check(that, currentTarget, KindSelector.VAL, resultInfo);
2639 boolean isSpeculativeRound =
2640 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
2643 flow.analyzeLambda(env, that, make, isSpeculativeRound);
2645 that.type = currentTarget; //avoids recovery at this stage
2646 checkLambdaCompatible(that, lambdaType, resultInfo.checkContext);
2648 if (!isSpeculativeRound) {
2649 //add thrown types as bounds to the thrown types free variables if needed:
2650 if (resultInfo.checkContext.inferenceContext().free(lambdaType.getThrownTypes())) {
2651 List<Type> inferredThrownTypes = flow.analyzeLambdaThrownTypes(env, that, make);
2652 List<Type> thrownTypes = resultInfo.checkContext.inferenceContext().asUndetVars(lambdaType.getThrownTypes());
2654 chk.unhandled(inferredThrownTypes, thrownTypes);
2656 //18.2.5: "In addition, for all j (1 <= j <= n), the constraint reduces to the bound throws Ej"
2657 thrownTypes.stream()
2658 .filter(t -> t.hasTag(UNDETVAR))
2659 .forEach(t -> ((UndetVar)t).setThrow());
2662 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), lambdaType, currentTarget);
2664 result = check(that, currentTarget, KindSelector.VAL, resultInfo);
2665 } catch (Types.FunctionDescriptorLookupError ex) {
2666 JCDiagnostic cause = ex.getDiagnostic();
2667 resultInfo.checkContext.report(that, cause);
2668 result = that.type = types.createErrorType(pt());
2670 } catch (BreakAttr ba) {
2671 if (currentTarget != null) {
2672 check(that, currentTarget, KindSelector.VAL, resultInfo);
2674 needsRecovery = false;
2676 } catch (Throwable t) {
2677 //when an unexpected exception happens, avoid attempts to attribute the same tree again
2678 //as that would likely cause the same exception again.
2679 needsRecovery = false;
2682 localEnv.info.scope.leave();
2683 if (needsRecovery) {
2684 attribTree(that, env, recoveryInfo);
2693 public TargetInfo(Type target, Type descriptor) {
2694 this.target = target;
2695 this.descriptor = descriptor;
2699 TargetInfo getTargetInfo(JCPolyExpression that, ResultInfo resultInfo, List<Type> explicitParamTypes) {
2701 Type currentTarget = resultInfo.pt;
2702 if (resultInfo.pt != Type.recoveryType) {
2703 /* We need to adjust the target. If the target is an
2704 * intersection type, for example: SAM & I1 & I2 ...
2705 * the target will be updated to SAM
2707 currentTarget = targetChecker.visit(currentTarget, that);
2708 if (explicitParamTypes != null) {
2709 currentTarget = infer.instantiateFunctionalInterface(that,
2710 currentTarget, explicitParamTypes, resultInfo.checkContext);
2712 currentTarget = types.removeWildcards(currentTarget);
2713 lambdaType = types.findDescriptorType(currentTarget);
2715 currentTarget = Type.recoveryType;
2716 lambdaType = fallbackDescriptorType(that);
2718 if (that.hasTag(LAMBDA) && lambdaType.hasTag(FORALL)) {
2719 //lambda expression target desc cannot be a generic method
2720 resultInfo.checkContext.report(that, diags.fragment("invalid.generic.lambda.target",
2721 lambdaType, kindName(currentTarget.tsym), currentTarget.tsym));
2722 currentTarget = types.createErrorType(pt());
2724 return new TargetInfo(currentTarget, lambdaType);
2727 void preFlow(JCLambda tree) {
2728 new PostAttrAnalyzer() {
2730 public void scan(JCTree tree) {
2732 (tree.type != null &&
2733 tree.type == Type.stuckType)) {
2734 //don't touch stuck expressions!
2742 Types.MapVisitor<DiagnosticPosition> targetChecker = new Types.MapVisitor<DiagnosticPosition>() {
2745 public Type visitClassType(ClassType t, DiagnosticPosition pos) {
2746 return t.isIntersection() ?
2747 visitIntersectionClassType((IntersectionClassType)t, pos) : t;
2750 public Type visitIntersectionClassType(IntersectionClassType ict, DiagnosticPosition pos) {
2751 Symbol desc = types.findDescriptorSymbol(makeNotionalInterface(ict));
2753 for (Type bound : ict.getExplicitComponents()) {
2754 TypeSymbol boundSym = bound.tsym;
2755 if (types.isFunctionalInterface(boundSym) &&
2756 types.findDescriptorSymbol(boundSym) == desc) {
2758 } else if (!boundSym.isInterface() || (boundSym.flags() & ANNOTATION) != 0) {
2759 //bound must be an interface
2760 reportIntersectionError(pos, "not.an.intf.component", boundSym);
2763 return target != null ?
2765 ict.getExplicitComponents().head; //error recovery
2768 private TypeSymbol makeNotionalInterface(IntersectionClassType ict) {
2769 ListBuffer<Type> targs = new ListBuffer<>();
2770 ListBuffer<Type> supertypes = new ListBuffer<>();
2771 for (Type i : ict.interfaces_field) {
2772 if (i.isParameterized()) {
2773 targs.appendList(i.tsym.type.allparams());
2775 supertypes.append(i.tsym.type);
2777 IntersectionClassType notionalIntf = types.makeIntersectionType(supertypes.toList());
2778 notionalIntf.allparams_field = targs.toList();
2779 notionalIntf.tsym.flags_field |= INTERFACE;
2780 return notionalIntf.tsym;
2783 private void reportIntersectionError(DiagnosticPosition pos, String key, Object... args) {
2784 resultInfo.checkContext.report(pos, diags.fragment("bad.intersection.target.for.functional.expr",
2785 diags.fragment(key, args)));
2789 private Type fallbackDescriptorType(JCExpression tree) {
2790 switch (tree.getTag()) {
2792 JCLambda lambda = (JCLambda)tree;
2793 List<Type> argtypes = List.nil();
2794 for (JCVariableDecl param : lambda.params) {
2795 argtypes = param.vartype != null ?
2796 argtypes.append(param.vartype.type) :
2797 argtypes.append(syms.errType);
2799 return new MethodType(argtypes, Type.recoveryType,
2800 List.of(syms.throwableType), syms.methodClass);
2802 return new MethodType(List.nil(), Type.recoveryType,
2803 List.of(syms.throwableType), syms.methodClass);
2805 Assert.error("Cannot get here!");
2810 private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
2811 final InferenceContext inferenceContext, final Type... ts) {
2812 checkAccessibleTypes(pos, env, inferenceContext, List.from(ts));
2815 private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
2816 final InferenceContext inferenceContext, final List<Type> ts) {
2817 if (inferenceContext.free(ts)) {
2818 inferenceContext.addFreeTypeListener(ts,
2819 solvedContext -> checkAccessibleTypes(pos, env, solvedContext, solvedContext.asInstTypes(ts)));
2822 rs.checkAccessibleType(env, t);
2828 * Lambda/method reference have a special check context that ensures
2829 * that i.e. a lambda return type is compatible with the expected
2830 * type according to both the inherited context and the assignment
2833 class FunctionalReturnContext extends Check.NestedCheckContext {
2835 FunctionalReturnContext(CheckContext enclosingContext) {
2836 super(enclosingContext);
2840 public boolean compatible(Type found, Type req, Warner warn) {
2841 //return type must be compatible in both current context and assignment context
2842 return chk.basicHandler.compatible(inferenceContext().asUndetVar(found), inferenceContext().asUndetVar(req), warn);
2846 public void report(DiagnosticPosition pos, JCDiagnostic details) {
2847 enclosingContext.report(pos, diags.fragment("incompatible.ret.type.in.lambda", details));
2851 class ExpressionLambdaReturnContext extends FunctionalReturnContext {
2854 boolean expStmtExpected;
2856 ExpressionLambdaReturnContext(JCExpression expr, CheckContext enclosingContext) {
2857 super(enclosingContext);
2862 public void report(DiagnosticPosition pos, JCDiagnostic details) {
2863 if (expStmtExpected) {
2864 enclosingContext.report(pos, diags.fragment(Fragments.StatExprExpected));
2866 super.report(pos, details);
2871 public boolean compatible(Type found, Type req, Warner warn) {
2872 //a void return is compatible with an expression statement lambda
2873 if (req.hasTag(VOID)) {
2874 expStmtExpected = true;
2875 return TreeInfo.isExpressionStatement(expr, names);
2877 return super.compatible(found, req, warn);
2882 ResultInfo lambdaBodyResult(JCLambda that, Type descriptor, ResultInfo resultInfo) {
2883 FunctionalReturnContext funcContext = that.getBodyKind() == JCLambda.BodyKind.EXPRESSION ?
2884 new ExpressionLambdaReturnContext((JCExpression)that.getBody(), resultInfo.checkContext) :
2885 new FunctionalReturnContext(resultInfo.checkContext);
2887 return descriptor.getReturnType() == Type.recoveryType ?
2889 new ResultInfo(KindSelector.VAL,
2890 descriptor.getReturnType(), funcContext);
2894 * Lambda compatibility. Check that given return types, thrown types, parameter types
2895 * are compatible with the expected functional interface descriptor. This means that:
2896 * (i) parameter types must be identical to those of the target descriptor; (ii) return
2897 * types must be compatible with the return type of the expected descriptor.
2899 void checkLambdaCompatible(JCLambda tree, Type descriptor, CheckContext checkContext) {
2900 Type returnType = checkContext.inferenceContext().asUndetVar(descriptor.getReturnType());
2902 //return values have already been checked - but if lambda has no return
2903 //values, we must ensure that void/value compatibility is correct;
2904 //this amounts at checking that, if a lambda body can complete normally,
2905 //the descriptor's return type must be void
2906 if (tree.getBodyKind() == JCLambda.BodyKind.STATEMENT && tree.canCompleteNormally &&
2907 !returnType.hasTag(VOID) && returnType != Type.recoveryType) {
2908 checkContext.report(tree, diags.fragment("incompatible.ret.type.in.lambda",
2909 diags.fragment("missing.ret.val", returnType)));
2912 List<Type> argTypes = checkContext.inferenceContext().asUndetVars(descriptor.getParameterTypes());
2913 if (!types.isSameTypes(argTypes, TreeInfo.types(tree.params))) {
2914 checkContext.report(tree, diags.fragment("incompatible.arg.types.in.lambda"));
2918 /* Map to hold 'fake' clinit methods. If a lambda is used to initialize a
2919 * static field and that lambda has type annotations, these annotations will
2920 * also be stored at these fake clinit methods.
2922 * LambdaToMethod also use fake clinit methods so they can be reused.
2923 * Also as LTM is a phase subsequent to attribution, the methods from
2924 * clinits can be safely removed by LTM to save memory.
2926 private Map<ClassSymbol, MethodSymbol> clinits = new HashMap<>();
2928 public MethodSymbol removeClinit(ClassSymbol sym) {
2929 return clinits.remove(sym);
2932 /* This method returns an environment to be used to attribute a lambda
2935 * The owner of this environment is a method symbol. If the current owner
2936 * is not a method, for example if the lambda is used to initialize
2937 * a field, then if the field is:
2939 * - an instance field, we use the first constructor.
2940 * - a static field, we create a fake clinit method.
2942 public Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) {
2943 Env<AttrContext> lambdaEnv;
2944 Symbol owner = env.info.scope.owner;
2945 if (owner.kind == VAR && owner.owner.kind == TYP) {
2947 ClassSymbol enclClass = owner.enclClass();
2948 Symbol newScopeOwner = env.info.scope.owner;
2949 /* if the field isn't static, then we can get the first constructor
2950 * and use it as the owner of the environment. This is what
2951 * LTM code is doing to look for type annotations so we are fine.
2953 if ((owner.flags() & STATIC) == 0) {
2954 for (Symbol s : enclClass.members_field.getSymbolsByName(names.init)) {
2959 /* if the field is static then we need to create a fake clinit
2960 * method, this method can later be reused by LTM.
2962 MethodSymbol clinit = clinits.get(enclClass);
2963 if (clinit == null) {
2964 Type clinitType = new MethodType(List.nil(),
2965 syms.voidType, List.nil(), syms.methodClass);
2966 clinit = new MethodSymbol(STATIC | SYNTHETIC | PRIVATE,
2967 names.clinit, clinitType, enclClass);
2968 clinit.params = List.nil();
2969 clinits.put(enclClass, clinit);
2971 newScopeOwner = clinit;
2973 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared(newScopeOwner)));
2975 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dup()));
2981 public void visitReference(final JCMemberReference that) {
2982 if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
2983 if (pt().hasTag(NONE)) {
2984 //method reference only allowed in assignment or method invocation/cast context
2985 log.error(that.pos(), "unexpected.mref");
2987 result = that.type = types.createErrorType(pt());
2990 final Env<AttrContext> localEnv = env.dup(that);
2992 //attribute member reference qualifier - if this is a constructor
2993 //reference, the expected kind must be a type
2994 Type exprType = attribTree(that.expr, env, memberReferenceQualifierResult(that));
2996 if (that.getMode() == JCMemberReference.ReferenceMode.NEW) {
2997 exprType = chk.checkConstructorRefType(that.expr, exprType);
2998 if (!exprType.isErroneous() &&
3000 that.typeargs != null) {
3001 log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
3002 diags.fragment("mref.infer.and.explicit.params"));
3003 exprType = types.createErrorType(exprType);
3007 if (exprType.isErroneous()) {
3008 //if the qualifier expression contains problems,
3009 //give up attribution of method reference
3010 result = that.type = exprType;
3014 if (TreeInfo.isStaticSelector(that.expr, names)) {
3015 //if the qualifier is a type, validate it; raw warning check is
3016 //omitted as we don't know at this stage as to whether this is a
3017 //raw selector (because of inference)
3018 chk.validate(that.expr, env, false);
3020 Symbol lhsSym = TreeInfo.symbol(that.expr);
3021 localEnv.info.selectSuper = lhsSym != null && lhsSym.name == names._super;
3023 //attrib type-arguments
3024 List<Type> typeargtypes = List.nil();
3025 if (that.typeargs != null) {
3026 typeargtypes = attribTypes(that.typeargs, localEnv);
3029 boolean isTargetSerializable =
3030 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
3031 isSerializable(pt());
3032 TargetInfo targetInfo = getTargetInfo(that, resultInfo, null);
3033 Type currentTarget = targetInfo.target;
3034 Type desc = targetInfo.descriptor;
3036 setFunctionalInfo(localEnv, that, pt(), desc, currentTarget, resultInfo.checkContext);
3037 List<Type> argtypes = desc.getParameterTypes();
3038 Resolve.MethodCheck referenceCheck = rs.resolveMethodCheck;
3040 if (resultInfo.checkContext.inferenceContext().free(argtypes)) {
3041 referenceCheck = rs.new MethodReferenceCheck(resultInfo.checkContext.inferenceContext());
3044 Pair<Symbol, Resolve.ReferenceLookupHelper> refResult = null;
3045 List<Type> saved_undet = resultInfo.checkContext.inferenceContext().save();
3047 refResult = rs.resolveMemberReference(localEnv, that, that.expr.type,
3048 that.name, argtypes, typeargtypes, referenceCheck,
3049 resultInfo.checkContext.inferenceContext(), rs.basicReferenceChooser);
3051 resultInfo.checkContext.inferenceContext().rollback(saved_undet);
3054 Symbol refSym = refResult.fst;
3055 Resolve.ReferenceLookupHelper lookupHelper = refResult.snd;
3057 /** this switch will need to go away and be replaced by the new RESOLUTION_TARGET testing
3060 if (refSym.kind != MTH) {
3061 boolean targetError;
3062 switch (refSym.kind) {
3065 targetError = false;
3075 Assert.error("unexpected result kind " + refSym.kind);
3076 targetError = false;
3079 JCDiagnostic detailsDiag = ((Resolve.ResolveError)refSym.baseSymbol()).getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT,
3080 that, exprType.tsym, exprType, that.name, argtypes, typeargtypes);
3082 JCDiagnostic.DiagnosticType diagKind = targetError ?
3083 JCDiagnostic.DiagnosticType.FRAGMENT : JCDiagnostic.DiagnosticType.ERROR;
3085 JCDiagnostic diag = diags.create(diagKind, log.currentSource(), that,
3086 "invalid.mref", Kinds.kindName(that.getMode()), detailsDiag);
3088 if (targetError && currentTarget == Type.recoveryType) {
3089 //a target error doesn't make sense during recovery stage
3090 //as we don't know what actual parameter types are
3091 result = that.type = currentTarget;
3095 resultInfo.checkContext.report(that, diag);
3099 result = that.type = types.createErrorType(currentTarget);
3104 that.sym = refSym.baseSymbol();
3105 that.kind = lookupHelper.referenceKind(that.sym);
3106 that.ownerAccessible = rs.isAccessible(localEnv, that.sym.enclClass());
3108 if (desc.getReturnType() == Type.recoveryType) {
3110 result = that.type = currentTarget;
3114 if (!env.info.isSpeculative && that.getMode() == JCMemberReference.ReferenceMode.NEW) {
3115 Type enclosingType = exprType.getEnclosingType();
3116 if (enclosingType != null && enclosingType.hasTag(CLASS)) {
3117 // Check for the existence of an apropriate outer instance
3118 rs.resolveImplicitThis(that.pos(), env, exprType);
3122 if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
3124 if (that.getMode() == ReferenceMode.INVOKE &&
3125 TreeInfo.isStaticSelector(that.expr, names) &&
3126 that.kind.isUnbound() &&
3127 !desc.getParameterTypes().head.isParameterized()) {
3128 chk.checkRaw(that.expr, localEnv);
3131 if (that.sym.isStatic() && TreeInfo.isStaticSelector(that.expr, names) &&
3132 exprType.getTypeArguments().nonEmpty()) {
3133 //static ref with class type-args
3134 log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
3135 diags.fragment("static.mref.with.targs"));
3136 result = that.type = types.createErrorType(currentTarget);
3140 if (!refSym.isStatic() && that.kind == JCMemberReference.ReferenceKind.SUPER) {
3141 // Check that super-qualified symbols are not abstract (JLS)
3142 rs.checkNonAbstract(that.pos(), that.sym);
3145 if (isTargetSerializable) {
3146 chk.checkAccessFromSerializableElement(that, true);
3150 ResultInfo checkInfo =
3151 resultInfo.dup(newMethodTemplate(
3152 desc.getReturnType().hasTag(VOID) ? Type.noType : desc.getReturnType(),
3153 that.kind.isUnbound() ? argtypes.tail : argtypes, typeargtypes),
3154 new FunctionalReturnContext(resultInfo.checkContext), CheckMode.NO_TREE_UPDATE);
3156 Type refType = checkId(that, lookupHelper.site, refSym, localEnv, checkInfo);
3158 if (that.kind.isUnbound() &&
3159 resultInfo.checkContext.inferenceContext().free(argtypes.head)) {
3160 //re-generate inference constraints for unbound receiver
3161 if (!types.isSubtype(resultInfo.checkContext.inferenceContext().asUndetVar(argtypes.head), exprType)) {
3162 //cannot happen as this has already been checked - we just need
3163 //to regenerate the inference constraints, as that has been lost
3164 //as a result of the call to inferenceContext.save()
3165 Assert.error("Can't get here");
3169 if (!refType.isErroneous()) {
3170 refType = types.createMethodTypeWithReturn(refType,
3171 adjustMethodReturnType(refSym, lookupHelper.site, that.name, checkInfo.pt.getParameterTypes(), refType.getReturnType()));
3174 //go ahead with standard method reference compatibility check - note that param check
3175 //is a no-op (as this has been taken care during method applicability)
3176 boolean isSpeculativeRound =
3177 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
3179 that.type = currentTarget; //avoids recovery at this stage
3180 checkReferenceCompatible(that, desc, refType, resultInfo.checkContext, isSpeculativeRound);
3181 if (!isSpeculativeRound) {
3182 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), desc, currentTarget);
3184 result = check(that, currentTarget, KindSelector.VAL, resultInfo);
3185 } catch (Types.FunctionDescriptorLookupError ex) {
3186 JCDiagnostic cause = ex.getDiagnostic();
3187 resultInfo.checkContext.report(that, cause);
3188 result = that.type = types.createErrorType(pt());
3193 ResultInfo memberReferenceQualifierResult(JCMemberReference tree) {
3194 //if this is a constructor reference, the expected kind must be a type
3195 return new ResultInfo(tree.getMode() == ReferenceMode.INVOKE ?
3196 KindSelector.VAL_TYP : KindSelector.TYP,
3201 @SuppressWarnings("fallthrough")
3202 void checkReferenceCompatible(JCMemberReference tree, Type descriptor, Type refType, CheckContext checkContext, boolean speculativeAttr) {
3203 InferenceContext inferenceContext = checkContext.inferenceContext();
3204 Type returnType = inferenceContext.asUndetVar(descriptor.getReturnType());
3207 switch (tree.getMode()) {
3209 if (!tree.expr.type.isRaw()) {
3210 resType = tree.expr.type;
3214 resType = refType.getReturnType();
3217 Type incompatibleReturnType = resType;
3219 if (returnType.hasTag(VOID)) {
3220 incompatibleReturnType = null;
3223 if (!returnType.hasTag(VOID) && !resType.hasTag(VOID)) {
3224 if (resType.isErroneous() ||
3225 new FunctionalReturnContext(checkContext).compatible(resType, returnType,
3226 checkContext.checkWarner(tree, resType, returnType))) {
3227 incompatibleReturnType = null;
3231 if (incompatibleReturnType != null) {
3232 checkContext.report(tree, diags.fragment("incompatible.ret.type.in.mref",
3233 diags.fragment("inconvertible.types", resType, descriptor.getReturnType())));
3235 if (inferenceContext.free(refType)) {
3236 // we need to wait for inference to finish and then replace inference vars in the referent type
3237 inferenceContext.addFreeTypeListener(List.of(refType),
3238 instantiatedContext -> {
3239 tree.referentType = instantiatedContext.asInstType(refType);
3242 tree.referentType = refType;
3246 if (!speculativeAttr) {
3247 List<Type> thrownTypes = inferenceContext.asUndetVars(descriptor.getThrownTypes());
3248 if (chk.unhandled(refType.getThrownTypes(), thrownTypes).nonEmpty()) {
3249 log.error(tree, "incompatible.thrown.types.in.mref", refType.getThrownTypes());
3251 //18.2.5: "In addition, for all j (1 <= j <= n), the constraint reduces to the bound throws Ej"
3252 thrownTypes.stream()
3253 .filter(t -> t.hasTag(UNDETVAR))
3254 .forEach(t -> ((UndetVar)t).setThrow());
3259 * Set functional type info on the underlying AST. Note: as the target descriptor
3260 * might contain inference variables, we might need to register an hook in the
3261 * current inference context.
3263 private void setFunctionalInfo(final Env<AttrContext> env, final JCFunctionalExpression fExpr,
3264 final Type pt, final Type descriptorType, final Type primaryTarget, final CheckContext checkContext) {
3265 if (checkContext.inferenceContext().free(descriptorType)) {
3266 checkContext.inferenceContext().addFreeTypeListener(List.of(pt, descriptorType),
3267 inferenceContext -> setFunctionalInfo(env, fExpr, pt, inferenceContext.asInstType(descriptorType),
3268 inferenceContext.asInstType(primaryTarget), checkContext));
3270 ListBuffer<Type> targets = new ListBuffer<>();
3271 if (pt.hasTag(CLASS)) {
3272 if (pt.isCompound()) {
3273 targets.append(types.removeWildcards(primaryTarget)); //this goes first
3274 for (Type t : ((IntersectionClassType)pt()).interfaces_field) {
3275 if (t != primaryTarget) {
3276 targets.append(types.removeWildcards(t));
3280 targets.append(types.removeWildcards(primaryTarget));
3283 fExpr.targets = targets.toList();
3284 if (checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
3285 pt != Type.recoveryType) {
3286 //check that functional interface class is well-formed
3288 /* Types.makeFunctionalInterfaceClass() may throw an exception
3289 * when it's executed post-inference. See the listener code
3292 ClassSymbol csym = types.makeFunctionalInterfaceClass(env,
3293 names.empty, List.of(fExpr.targets.head), ABSTRACT);
3295 chk.checkImplementations(env.tree, csym, csym);
3297 //perform an additional functional interface check on the synthetic class,
3298 //as there may be spurious errors for raw targets - because of existing issues
3299 //with membership and inheritance (see JDK-8074570).
3300 csym.flags_field |= INTERFACE;
3301 types.findDescriptorType(csym.type);
3302 } catch (FunctionDescriptorLookupError err) {
3303 resultInfo.checkContext.report(fExpr,
3304 diags.fragment(Fragments.NoSuitableFunctionalIntfInst(fExpr.targets.head)));
3307 } catch (Types.FunctionDescriptorLookupError ex) {
3308 JCDiagnostic cause = ex.getDiagnostic();
3309 resultInfo.checkContext.report(env.tree, cause);
3315 public void visitParens(JCParens tree) {
3316 Type owntype = attribTree(tree.expr, env, resultInfo);
3317 result = check(tree, owntype, pkind(), resultInfo);
3318 Symbol sym = TreeInfo.symbol(tree);
3319 if (sym != null && sym.kind.matches(KindSelector.TYP_PCK))
3320 log.error(tree.pos(), "illegal.start.of.type");
3323 public void visitAssign(JCAssign tree) {
3324 Type owntype = attribTree(tree.lhs, env.dup(tree), varAssignmentInfo);
3325 Type capturedType = capture(owntype);
3326 attribExpr(tree.rhs, env, owntype);
3327 result = check(tree, capturedType, KindSelector.VAL, resultInfo);
3330 public void visitAssignop(JCAssignOp tree) {
3331 // Attribute arguments.
3332 Type owntype = attribTree(tree.lhs, env, varAssignmentInfo);
3333 Type operand = attribExpr(tree.rhs, env);
3335 Symbol operator = tree.operator = operators.resolveBinary(tree, tree.getTag().noAssignOp(), owntype, operand);
3336 if (operator != operators.noOpSymbol &&
3337 !owntype.isErroneous() &&
3338 !operand.isErroneous()) {
3339 chk.checkDivZero(tree.rhs.pos(), operator, operand);
3340 chk.checkCastable(tree.rhs.pos(),
3341 operator.type.getReturnType(),
3344 result = check(tree, owntype, KindSelector.VAL, resultInfo);
3347 public void visitUnary(JCUnary tree) {
3348 // Attribute arguments.
3349 Type argtype = (tree.getTag().isIncOrDecUnaryOp())
3350 ? attribTree(tree.arg, env, varAssignmentInfo)
3351 : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
3354 Symbol operator = tree.operator = operators.resolveUnary(tree, tree.getTag(), argtype);
3355 Type owntype = types.createErrorType(tree.type);
3356 if (operator != operators.noOpSymbol &&
3357 !argtype.isErroneous()) {
3358 owntype = (tree.getTag().isIncOrDecUnaryOp())
3360 : operator.type.getReturnType();
3361 int opc = ((OperatorSymbol)operator).opcode;
3363 // If the argument is constant, fold it.
3364 if (argtype.constValue() != null) {
3365 Type ctype = cfolder.fold1(opc, argtype);
3366 if (ctype != null) {
3367 owntype = cfolder.coerce(ctype, owntype);
3371 result = check(tree, owntype, KindSelector.VAL, resultInfo);
3374 public void visitBinary(JCBinary tree) {
3375 boolean baCatched = false;
3377 // Attribute arguments.
3378 Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
3379 Type right = chk.checkNonVoid(tree.rhs.pos(), attribExpr(tree.rhs, env));
3381 Symbol operator = tree.operator = operators.resolveBinary(tree, tree.getTag(), left, right);
3382 Type owntype = types.createErrorType(tree.type);
3383 if (operator != operators.noOpSymbol &&
3384 !left.isErroneous() &&
3385 !right.isErroneous()) {
3386 owntype = operator.type.getReturnType();
3387 int opc = ((OperatorSymbol)operator).opcode;
3388 // If both arguments are constants, fold them.
3389 if (left.constValue() != null && right.constValue() != null) {
3390 Type ctype = cfolder.fold2(opc, left, right);
3391 if (ctype != null) {
3392 owntype = cfolder.coerce(ctype, owntype);
3396 // Check that argument types of a reference ==, != are
3397 // castable to each other, (JLS 15.21). Note: unboxing
3398 // comparisons will not have an acmp* opc at this point.
3399 if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
3400 if (!types.isCastable(left, right, new Warner(tree.pos()))) {
3401 log.error(tree.pos(), "incomparable.types", left, right);
3405 chk.checkDivZero(tree.rhs.pos(), operator, right);
3407 result = check(tree, owntype, KindSelector.VAL, resultInfo);
3408 } catch (BreakAttr ba) {
3412 if ((baCatched || result.isErroneous()) && tree.hasTag(BITAND)) {
3414 TreeScanner treeCleaner = new TreeScanner() {
3415 public void scan(JCTree node) {
3420 public void visitClassDef(JCClassDecl node) {
3422 super.visitClassDef(node);
3424 public void visitMethodDef(JCMethodDecl node) {
3426 super.visitMethodDef(node);
3428 public void visitVarDef(JCVariableDecl node) {
3430 super.visitVarDef(node);
3432 public void visitNewClass(JCNewClass node) {
3433 node.constructor = null;
3434 super.visitNewClass(node);
3436 public void visitAssignop(JCAssignOp node) {
3437 node.operator = null;
3438 super.visitAssignop(node);
3440 public void visitUnary(JCUnary node) {
3441 node.operator = null;
3442 super.visitUnary(node);
3444 public void visitBinary(JCBinary node) {
3445 node.operator = null;
3446 super.visitBinary(node);
3448 public void visitSelect(JCFieldAccess node) {
3450 super.visitSelect(node);
3452 public void visitIdent(JCIdent node) {
3454 super.visitIdent(node);
3456 public void visitAnnotation(JCAnnotation node) {
3457 node.attribute = null;
3458 super.visitAnnotation(node);
3461 // attribTree will change the 'result', save it:
3462 Type saveResult = this.result;
3463 treeCleaner.scan(tree.lhs);
3464 attribTree(tree.lhs, env, new ResultInfo(KindSelector.VAL_TYP , Type.noType));
3465 treeCleaner.scan(tree.rhs);
3466 attribTree(tree.rhs, env, new ResultInfo(KindSelector.VAL_TYP , Type.noType));
3467 this.result = saveResult;
3468 List<JCExpression> bounds = collectIntersectionBounds(tree);
3469 if (bounds != null) {
3470 Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log);
3472 Type owntype = checkIntersection(tree, bounds);
3473 if (!owntype.isErroneous()) {
3474 tree.type = result = owntype;
3477 log.popDiagnosticHandler(discardHandler);
3484 private List<JCExpression> collectIntersectionBounds(JCTree tree) {
3485 if (tree.hasTag(BITAND)) {
3486 List<JCExpression> left = collectIntersectionBounds(((JCBinary)tree).lhs);
3488 List<JCExpression> right = collectIntersectionBounds(((JCBinary)tree).rhs);
3489 if (right != null) {
3490 return left.appendList(right);
3493 } else if (tree instanceof JCExpression && tree.type != null) {
3494 return List.of((JCExpression)tree);
3499 public void visitTypeCast(final JCTypeCast tree) {
3500 Type clazztype = attribType(tree.clazz, env);
3501 chk.validate(tree.clazz, env, false);
3502 //a fresh environment is required for 292 inference to work properly ---
3503 //see Infer.instantiatePolymorphicSignatureInstance()
3504 Env<AttrContext> localEnv = env.dup(tree);
3505 //should we propagate the target type?
3506 final ResultInfo castInfo;
3507 JCExpression expr = TreeInfo.skipParens(tree.expr);
3508 boolean isPoly = expr.hasTag(LAMBDA) || expr.hasTag(REFERENCE);
3510 //expression is a poly - we need to propagate target type info
3511 castInfo = new ResultInfo(KindSelector.VAL, clazztype,
3512 new Check.NestedCheckContext(resultInfo.checkContext) {
3514 public boolean compatible(Type found, Type req, Warner warn) {
3515 return types.isCastable(found, req, warn);
3519 //standalone cast - target-type info is not propagated
3520 castInfo = unknownExprInfo;
3522 Type exprtype = attribTree(tree.expr, localEnv, castInfo);
3523 Type owntype = isPoly ? clazztype : chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
3524 if (exprtype.constValue() != null)
3525 owntype = cfolder.coerce(exprtype, owntype);
3526 result = check(tree, capture(owntype), KindSelector.VAL, resultInfo);
3528 chk.checkRedundantCast(localEnv, tree);
3531 public void visitTypeTest(JCInstanceOf tree) {
3532 Type exprtype = chk.checkNullOrRefType(
3533 tree.expr.pos(), attribExpr(tree.expr, env));
3534 Type clazztype = attribType(tree.clazz, env);
3535 if (!clazztype.hasTag(TYPEVAR)) {
3536 clazztype = chk.checkClassOrArrayType(tree.clazz.pos(), clazztype);
3538 if (!clazztype.isErroneous() && !types.isReifiable(clazztype)) {
3539 log.error(tree.clazz.pos(), "illegal.generic.type.for.instof");
3540 clazztype = types.createErrorType(clazztype);
3542 chk.validate(tree.clazz, env, false);
3543 chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
3544 result = check(tree, syms.booleanType, KindSelector.VAL, resultInfo);
3547 public void visitIndexed(JCArrayAccess tree) {
3548 Type owntype = types.createErrorType(tree.type);
3549 Type atype = attribExpr(tree.indexed, env);
3550 attribExpr(tree.index, env, syms.intType);
3551 if (types.isArray(atype))
3552 owntype = types.elemtype(atype);
3553 else if (!atype.hasTag(ERROR))
3554 log.error(tree.pos(), "array.req.but.found", atype);
3555 if (!pkind().contains(KindSelector.VAL))
3556 owntype = capture(owntype);
3557 result = check(tree, owntype, KindSelector.VAR, resultInfo);
3560 public void visitIdent(JCIdent tree) {
3564 if (pt().hasTag(METHOD) || pt().hasTag(FORALL)) {
3565 // If we are looking for a method, the prototype `pt' will be a
3566 // method type with the type of the call's arguments as parameters.
3567 env.info.pendingResolutionPhase = null;
3568 sym = rs.resolveMethod(tree.pos(), env, tree.name, pt().getParameterTypes(), pt().getTypeArguments());
3569 } else if (tree.sym != null && tree.sym.kind != VAR) {
3572 sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind());
3576 // (1) Also find the environment current for the class where
3577 // sym is defined (`symEnv').
3578 // Only for pre-tiger versions (1.4 and earlier):
3579 // (2) Also determine whether we access symbol out of an anonymous
3580 // class in a this or super call. This is illegal for instance
3581 // members since such classes don't carry a this$n link.
3582 // (`noOuterThisPath').
3583 Env<AttrContext> symEnv = env;
3584 boolean noOuterThisPath = false;
3585 if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
3586 sym.kind.matches(KindSelector.VAL_MTH) &&
3587 sym.owner.kind == TYP &&
3588 tree.name != names._this && tree.name != names._super) {
3590 // Find environment in which identifier is defined.
3591 while (symEnv.outer != null &&
3592 !sym.isMemberOf(symEnv.enclClass.sym, types)) {
3593 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
3594 noOuterThisPath = false;
3595 symEnv = symEnv.outer;
3599 // If symbol is a variable, ...
3600 if (sym.kind == VAR) {
3601 VarSymbol v = (VarSymbol)sym;
3603 // ..., evaluate its initializer, if it has one, and check for
3604 // illegal forward reference.
3605 checkInit(tree, env, v, false);
3607 // If we are expecting a variable (as opposed to a value), check
3608 // that the variable is assignable in the current environment.
3609 if (KindSelector.ASG.subset(pkind()))
3610 checkAssignable(tree.pos(), v, null, env);
3613 // In a constructor body,
3614 // if symbol is a field or instance method, check that it is
3615 // not accessed before the supertype constructor is called.
3616 if ((symEnv.info.isSelfCall || noOuterThisPath) &&
3617 sym.kind.matches(KindSelector.VAL_MTH) &&
3618 sym.owner.kind == TYP &&
3619 (sym.flags() & STATIC) == 0) {
3620 chk.earlyRefError(tree.pos(), sym.kind == VAR ?
3621 sym : thisSym(tree.pos(), env));
3623 Env<AttrContext> env1 = env;
3624 if (sym.kind != ERR && sym.kind != TYP &&
3625 sym.owner != null && sym.owner != env1.enclClass.sym) {
3626 // If the found symbol is inaccessible, then it is
3627 // accessed through an enclosing instance. Locate this
3628 // enclosing instance:
3629 while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
3633 if (env.info.isSerializable) {
3634 chk.checkAccessFromSerializableElement(tree, env.info.isLambda);
3637 result = checkId(tree, env1.enclClass.sym.type, sym, env, resultInfo);
3640 public void visitSelect(JCFieldAccess tree) {
3641 // Determine the expected kind of the qualifier expression.
3642 KindSelector skind = KindSelector.NIL;
3643 if (tree.name == names._this || tree.name == names._super ||
3644 tree.name == names._class)
3646 skind = KindSelector.TYP;
3647 } else if (tree.name == names.error) {
3648 skind = KindSelector.ERR;
3650 if (pkind().contains(KindSelector.PCK))
3651 skind = KindSelector.of(skind, KindSelector.PCK);
3652 if (pkind().contains(KindSelector.TYP))
3653 skind = KindSelector.of(skind, KindSelector.TYP, KindSelector.PCK);
3654 if (pkind().contains(KindSelector.VAL_MTH))
3655 skind = KindSelector.of(skind, KindSelector.VAL, KindSelector.TYP);
3658 // Attribute the qualifier expression, and determine its symbol (if any).
3659 Type site = attribTree(tree.selected, env, new ResultInfo(skind, Type.noType));
3660 if (!pkind().contains(KindSelector.TYP_PCK))
3661 site = capture(site); // Capture field access
3663 // don't allow T.class T[].class, etc
3664 if (skind == KindSelector.TYP) {
3666 while (elt.hasTag(ARRAY))
3667 elt = ((ArrayType)elt).elemtype;
3668 if (elt.hasTag(TYPEVAR)) {
3669 log.error(tree.pos(), "type.var.cant.be.deref");
3670 result = tree.type = types.createErrorType(tree.name, site.tsym, site);
3671 tree.sym = tree.type.tsym;
3676 // If qualifier symbol is a type or `super', assert `selectSuper'
3677 // for the selection. This is relevant for determining whether
3678 // protected symbols are accessible.
3679 Symbol sitesym = TreeInfo.symbol(tree.selected);
3680 boolean selectSuperPrev = env.info.selectSuper;
3681 env.info.selectSuper =
3683 sitesym.name == names._super;
3685 // Determine the symbol represented by the selection.
3686 env.info.pendingResolutionPhase = null;
3687 Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
3688 if (sym.kind == VAR && sym.name != names._super && env.info.defaultSuperCallSite != null) {
3689 log.error(tree.selected.pos(), "not.encl.class", site.tsym);
3690 sym = syms.errSymbol;
3692 if (sym.exists() && !isType(sym) && pkind().contains(KindSelector.TYP_PCK)) {
3693 site = capture(site);
3694 sym = selectSym(tree, sitesym, site, env, resultInfo);
3696 boolean varArgs = env.info.lastResolveVarargs();
3699 if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) {
3700 site = types.skipTypeVars(site, true);
3703 // If that symbol is a variable, ...
3704 if (sym.kind == VAR) {
3705 VarSymbol v = (VarSymbol)sym;
3707 // ..., evaluate its initializer, if it has one, and check for
3708 // illegal forward reference.
3709 checkInit(tree, env, v, true);
3711 // If we are expecting a variable (as opposed to a value), check
3712 // that the variable is assignable in the current environment.
3713 if (KindSelector.ASG.subset(pkind()))
3714 checkAssignable(tree.pos(), v, tree.selected, env);
3717 if (sitesym != null &&
3718 sitesym.kind == VAR &&
3719 ((VarSymbol)sitesym).isResourceVariable() &&
3721 sym.name.equals(names.close) &&
3722 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) &&
3723 env.info.lint.isEnabled(LintCategory.TRY)) {
3724 log.warning(LintCategory.TRY, tree, "try.explicit.close.call");
3727 // Disallow selecting a type from an expression
3728 if (isType(sym) && (sitesym == null || !sitesym.kind.matches(KindSelector.TYP_PCK))) {
3729 tree.type = check(tree.selected, pt(),
3731 KindSelector.VAL : sitesym.kind.toSelector(),
3732 new ResultInfo(KindSelector.TYP_PCK, pt()));
3735 if (isType(sitesym)) {
3736 if (sym.name == names._this) {
3737 // If `C' is the currently compiled class, check that
3738 // C.this' does not appear in a call to a super(...)
3739 if (env.info.isSelfCall &&
3740 site.tsym == env.enclClass.sym) {
3741 chk.earlyRefError(tree.pos(), sym);
3744 // Check if type-qualified fields or methods are static (JLS)
3745 if ((sym.flags() & STATIC) == 0 &&
3746 sym.name != names._super &&
3747 (sym.kind == VAR || sym.kind == MTH)) {
3748 rs.accessBase(rs.new StaticError(sym),
3749 tree.pos(), site, sym.name, true);
3752 if (!allowStaticInterfaceMethods && sitesym.isInterface() &&
3753 sym.isStatic() && sym.kind == MTH) {
3754 log.error(DiagnosticFlag.SOURCE_LEVEL, tree.pos(), "static.intf.method.invoke.not.supported.in.source", sourceName);
3756 } else if (sym.kind != ERR &&
3757 (sym.flags() & STATIC) != 0 &&
3758 sym.name != names._class) {
3759 // If the qualified item is not a type and the selected item is static, report
3760 // a warning. Make allowance for the class of an array type e.g. Object[].class)
3761 chk.warnStatic(tree, "static.not.qualified.by.type",
3762 sym.kind.kindName(), sym.owner);
3765 // If we are selecting an instance member via a `super', ...
3766 if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
3768 // Check that super-qualified symbols are not abstract (JLS)
3769 rs.checkNonAbstract(tree.pos(), sym);
3772 // Determine argument types for site.
3773 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
3774 if (site1 != null) site = site1;
3778 if (env.info.isSerializable) {
3779 chk.checkAccessFromSerializableElement(tree, env.info.isLambda);
3782 env.info.selectSuper = selectSuperPrev;
3783 result = checkId(tree, site, sym, env, resultInfo);
3786 /** Determine symbol referenced by a Select expression,
3788 * @param tree The select tree.
3789 * @param site The type of the selected expression,
3790 * @param env The current environment.
3791 * @param resultInfo The current result.
3793 private Symbol selectSym(JCFieldAccess tree,
3796 Env<AttrContext> env,
3797 ResultInfo resultInfo) {
3798 DiagnosticPosition pos = tree.pos();
3799 Name name = tree.name;
3800 switch (site.getTag()) {
3802 return rs.accessBase(
3803 rs.findIdentInPackage(env, site.tsym, name, resultInfo.pkind),
3804 pos, location, site, name, true);
3807 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) {
3808 return rs.resolveQualifiedMethod(
3809 pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
3810 } else if (name == names._this || name == names._super) {
3811 return rs.resolveSelf(pos, env, site.tsym, name);
3812 } else if (name == names._class) {
3813 // In this case, we have already made sure in
3814 // visitSelect that qualifier expression is a type.
3815 Type t = syms.classType;
3816 List<Type> typeargs = List.of(types.erasure(site));
3817 t = new ClassType(t.getEnclosingType(), typeargs, t.tsym);
3818 return new VarSymbol(
3819 STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
3821 // We are seeing a plain identifier as selector.
3822 Symbol sym = rs.findIdentInType(env, site, name, resultInfo.pkind);
3823 sym = rs.accessBase(sym, pos, location, site, name, true);
3827 throw new AssertionError(tree);
3829 // Normally, site.getUpperBound() shouldn't be null.
3830 // It should only happen during memberEnter/attribBase
3831 // when determining the super type which *must* beac
3832 // done before attributing the type variables. In
3833 // other words, we are seeing this illegal program:
3834 // class B<T> extends A<T.foo> {}
3835 Symbol sym = (site.getUpperBound() != null)
3836 ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
3839 log.error(pos, "type.var.cant.be.deref");
3840 return syms.errSymbol;
3842 Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
3843 rs.new AccessError(env, site, sym) :
3845 rs.accessBase(sym2, pos, location, site, name, true);
3849 // preserve identifier names through errors
3850 return types.createErrorType(name, site.tsym, site).tsym;
3852 // The qualifier expression is of a primitive type -- only
3853 // .class is allowed for these.
3854 if (name == names._class) {
3855 // In this case, we have already made sure in Select that
3856 // qualifier expression is a type.
3857 Type t = syms.classType;
3858 Type arg = types.boxedClass(site).type;
3859 t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym);
3860 return new VarSymbol(
3861 STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
3863 log.error(pos, "cant.deref", site);
3864 return syms.errSymbol;
3869 /** Determine type of identifier or select expression and check that
3870 * (1) the referenced symbol is not deprecated
3871 * (2) the symbol's type is safe (@see checkSafe)
3872 * (3) if symbol is a variable, check that its type and kind are
3873 * compatible with the prototype and protokind.
3874 * (4) if symbol is an instance field of a raw type,
3875 * which is being assigned to, issue an unchecked warning if its
3876 * type changes under erasure.
3877 * (5) if symbol is an instance method of a raw type, issue an
3878 * unchecked warning if its argument types change under erasure.
3879 * If checks succeed:
3880 * If symbol is a constant, return its constant type
3881 * else if symbol is a method, return its result type
3882 * otherwise return its type.
3883 * Otherwise return errType.
3885 * @param tree The syntax tree representing the identifier
3886 * @param site If this is a select, the type of the selected
3887 * expression, otherwise the type of the current class.
3888 * @param sym The symbol representing the identifier.
3889 * @param env The current environment.
3890 * @param resultInfo The expected result
3892 Type checkId(JCTree tree,
3895 Env<AttrContext> env,
3896 ResultInfo resultInfo) {
3897 return (resultInfo.pt.hasTag(FORALL) || resultInfo.pt.hasTag(METHOD)) ?
3898 checkMethodId(tree, site, sym, env, resultInfo) :
3899 checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
3902 Type checkMethodId(JCTree tree,
3905 Env<AttrContext> env,
3906 ResultInfo resultInfo) {
3907 boolean isPolymorhicSignature =
3908 (sym.baseSymbol().flags() & SIGNATURE_POLYMORPHIC) != 0;
3909 return isPolymorhicSignature ?
3910 checkSigPolyMethodId(tree, site, sym, env, resultInfo) :
3911 checkMethodIdInternal(tree, site, sym, env, resultInfo);
3914 Type checkSigPolyMethodId(JCTree tree,
3917 Env<AttrContext> env,
3918 ResultInfo resultInfo) {
3919 //recover original symbol for signature polymorphic methods
3920 checkMethodIdInternal(tree, site, sym.baseSymbol(), env, resultInfo);
3921 env.info.pendingResolutionPhase = Resolve.MethodResolutionPhase.BASIC;
3925 Type checkMethodIdInternal(JCTree tree,
3928 Env<AttrContext> env,
3929 ResultInfo resultInfo) {
3930 if (resultInfo.pkind.contains(KindSelector.POLY)) {
3931 Type pt = resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, sym, env.info.pendingResolutionPhase));
3932 Type owntype = checkIdInternal(tree, site, sym, pt, env, resultInfo);
3933 resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
3936 return checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
3940 Type checkIdInternal(JCTree tree,
3944 Env<AttrContext> env,
3945 ResultInfo resultInfo) {
3946 if (pt.isErroneous()) {
3947 return tree.type = types.createErrorType(site);
3949 Type owntype; // The computed type of this identifier occurrence.
3952 // For types, the computed type equals the symbol's type,
3953 // except for two situations:
3955 if (owntype.hasTag(CLASS)) {
3956 chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym);
3957 Type ownOuter = owntype.getEnclosingType();
3959 // (a) If the symbol's type is parameterized, erase it
3960 // because no type parameters were given.
3961 // We recover generic outer type later in visitTypeApply.
3962 if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
3963 owntype = types.erasure(owntype);
3966 // (b) If the symbol's type is an inner class, then
3967 // we have to interpret its outer type as a superclass
3968 // of the site type. Example:
3970 // class Tree<A> { class Visitor { ... } }
3971 // class PointTree extends Tree<Point> { ... }
3972 // ...PointTree.Visitor...
3974 // Then the type of the last expression above is
3975 // Tree<Point>.Visitor.
3976 else if (ownOuter != null && ownOuter.hasTag(CLASS) && site != ownOuter) {
3977 Type normOuter = site;
3978 if (normOuter.hasTag(CLASS)) {
3979 normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
3981 if (normOuter == null) // perhaps from an import
3982 normOuter = types.erasure(ownOuter);
3983 if (normOuter != ownOuter)
3984 owntype = new ClassType(
3985 normOuter, List.nil(), owntype.tsym,
3986 owntype.getMetadata());
3991 VarSymbol v = (VarSymbol)sym;
3992 // Test (4): if symbol is an instance field of a raw type,
3993 // which is being assigned to, issue an unchecked warning if
3994 // its type changes under erasure.
3995 if (KindSelector.ASG.subset(pkind()) &&
3996 v.owner.kind == TYP &&
3997 (v.flags() & STATIC) == 0 &&
3998 (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
3999 Type s = types.asOuterSuper(site, v.owner);
4002 !types.isSameType(v.type, v.erasure(types))) {
4003 chk.warnUnchecked(tree.pos(),
4004 "unchecked.assign.to.var",
4008 // The computed type of a variable is the type of the
4009 // variable symbol, taken as a member of the site type.
4010 owntype = (sym.owner.kind == TYP &&
4011 sym.name != names._this && sym.name != names._super)
4012 ? types.memberType(site, sym)
4015 // If the variable is a constant, record constant value in
4017 if (v.getConstValue() != null && isStaticReference(tree))
4018 owntype = owntype.constType(v.getConstValue());
4020 if (resultInfo.pkind == KindSelector.VAL) {
4021 owntype = capture(owntype); // capture "names as expressions"
4025 owntype = checkMethod(site, sym,
4026 new ResultInfo(resultInfo.pkind, resultInfo.pt.getReturnType(), resultInfo.checkContext, resultInfo.checkMode),
4027 env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(),
4028 resultInfo.pt.getTypeArguments());
4035 throw new AssertionError("unexpected kind: " + sym.kind +
4036 " in tree " + tree);
4039 // Emit a `deprecation' warning if symbol is deprecated.
4040 // (for constructors (but not for constructor references), the error
4041 // was given when the constructor was resolved)
4043 if (sym.name != names.init || tree.hasTag(REFERENCE)) {
4044 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym);
4045 chk.checkSunAPI(tree.pos(), sym);
4046 chk.checkProfile(tree.pos(), sym);
4049 Env<AttrContext> enclosing;
4050 if (owntype.isErroneous() && (sym.kind == MTH || sym.kind == VAR) && ((enclosing = enter.getEnv(sym.enclClass())) == null || enclosing.toplevel != env.toplevel)) {
4051 log.error(tree, "type.error", sym);
4054 // If symbol is a variable, check that its type and
4055 // kind are compatible with the prototype and protokind.
4056 return check(tree, owntype, sym.kind.toSelector(), resultInfo);
4059 /** Check that variable is initialized and evaluate the variable's
4060 * initializer, if not yet done. Also check that variable is not
4061 * referenced before it is defined.
4062 * @param tree The tree making up the variable reference.
4063 * @param env The current environment.
4064 * @param v The variable's symbol.
4066 private void checkInit(JCTree tree,
4067 Env<AttrContext> env,
4069 boolean onlyWarning) {
4070 // A forward reference is diagnosed if the declaration position
4071 // of the variable is greater than the current tree position
4072 // and the tree and variable definition occur in the same class
4073 // definition. Note that writes don't count as references.
4074 // This check applies only to class and instance
4075 // variables. Local variables follow different scope rules,
4076 // and are subject to definite assignment checking.
4077 Env<AttrContext> initEnv = enclosingInitEnv(env);
4078 if (initEnv != null &&
4079 (initEnv.info.enclVar == v || v.pos > tree.pos) &&
4080 v.owner.kind == TYP &&
4081 v.owner == env.info.scope.owner.enclClass() &&
4082 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
4083 (!env.tree.hasTag(ASSIGN) ||
4084 TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
4085 String suffix = (initEnv.info.enclVar == v) ?
4086 "self.ref" : "forward.ref";
4087 if (!onlyWarning || isStaticEnumField(v)) {
4088 log.error(tree.pos(), "illegal." + suffix);
4089 } else if (useBeforeDeclarationWarning) {
4090 log.warning(tree.pos(), suffix, v);
4094 v.getConstValue(); // ensure initializer is evaluated
4096 checkEnumInitializer(tree, env, v);
4100 * Returns the enclosing init environment associated with this env (if any). An init env
4101 * can be either a field declaration env or a static/instance initializer env.
4103 Env<AttrContext> enclosingInitEnv(Env<AttrContext> env) {
4105 switch (env.tree.getTag()) {
4107 JCVariableDecl vdecl = (JCVariableDecl)env.tree;
4108 if (vdecl.sym != null && vdecl.sym.owner != null && vdecl.sym.owner.kind == TYP) {
4114 if (env.next.tree.hasTag(CLASSDEF)) {
4115 //instance/static initializer
4124 Assert.checkNonNull(env.next);
4130 * Check for illegal references to static members of enum. In
4131 * an enum type, constructors and initializers may not
4132 * reference its static members unless they are constant.
4134 * @param tree The tree making up the variable reference.
4135 * @param env The current environment.
4136 * @param v The variable's symbol.
4137 * @jls section 8.9 Enums
4139 private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
4142 // "It is a compile-time error to reference a static field
4143 // of an enum type that is not a compile-time constant
4144 // (15.28) from constructors, instance initializer blocks,
4145 // or instance variable initializer expressions of that
4146 // type. It is a compile-time error for the constructors,
4147 // instance initializer blocks, or instance variable
4148 // initializer expressions of an enum constant e to refer
4149 // to itself or to an enum constant of the same type that
4150 // is declared to the right of e."
4151 if (isStaticEnumField(v)) {
4152 ClassSymbol enclClass = env.info.scope.owner.enclClass();
4154 if (enclClass == null || enclClass.owner == null)
4157 // See if the enclosing class is the enum (or a
4158 // subclass thereof) declaring v. If not, this
4160 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
4163 // If the reference isn't from an initializer, then
4164 // the reference is OK.
4165 if (!Resolve.isInitializer(env))
4168 log.error(tree.pos(), "illegal.enum.static.ref");
4172 /** Is the given symbol a static, non-constant field of an Enum?
4173 * Note: enum literals should not be regarded as such
4175 private boolean isStaticEnumField(VarSymbol v) {
4176 return Flags.isEnum(v.owner) &&
4177 Flags.isStatic(v) &&
4178 !Flags.isConstant(v) &&
4179 v.name != names._class;
4183 * Check that method arguments conform to its instantiation.
4185 public Type checkMethod(Type site,
4187 ResultInfo resultInfo,
4188 Env<AttrContext> env,
4189 final List<JCExpression> argtrees,
4190 List<Type> argtypes,
4191 List<Type> typeargtypes) {
4192 // Test (5): if symbol is an instance method of a raw type, issue
4193 // an unchecked warning if its argument types change under erasure.
4194 if ((sym.flags() & STATIC) == 0 &&
4195 (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
4196 Type s = types.asOuterSuper(site, sym.owner);
4197 if (s != null && s.isRaw() &&
4198 !types.isSameTypes(sym.type.getParameterTypes(),
4199 sym.erasure(types).getParameterTypes())) {
4200 chk.warnUnchecked(env.tree.pos(),
4201 "unchecked.call.mbr.of.raw.type",
4206 if (env.info.defaultSuperCallSite != null) {
4207 for (Type sup : types.interfaces(env.enclClass.sym.type).prepend(types.supertype((env.enclClass.sym.type)))) {
4208 if (!sup.tsym.isSubClass(sym.enclClass(), types) ||
4209 types.isSameType(sup, env.info.defaultSuperCallSite)) continue;
4210 List<MethodSymbol> icand_sup =
4211 types.interfaceCandidates(sup, (MethodSymbol)sym);
4212 if (icand_sup.nonEmpty() &&
4213 icand_sup.head != sym &&
4214 icand_sup.head.overrides(sym, icand_sup.head.enclClass(), types, true)) {
4215 log.error(env.tree.pos(), "illegal.default.super.call", env.info.defaultSuperCallSite,
4216 diags.fragment("overridden.default", sym, sup));
4220 env.info.defaultSuperCallSite = null;
4223 if (sym.isStatic() && site.isInterface() && env.tree.hasTag(APPLY)) {
4224 JCMethodInvocation app = (JCMethodInvocation)env.tree;
4225 if (app.meth.hasTag(SELECT) &&
4226 !TreeInfo.isStaticSelector(((JCFieldAccess)app.meth).selected, names)) {
4227 log.error(env.tree.pos(), "illegal.static.intf.meth.call", site);
4231 // Compute the identifier's instantiated type.
4232 // For methods, we need to compute the instance type by
4233 // Resolve.instantiate from the symbol's type as well as
4234 // any type arguments and value arguments.
4235 Warner noteWarner = new Warner();
4237 Type owntype = rs.checkMethod(
4246 DeferredAttr.DeferredTypeMap checkDeferredMap =
4247 deferredAttr.new DeferredTypeMap(DeferredAttr.AttrMode.CHECK, sym, env.info.pendingResolutionPhase);
4249 argtypes = argtypes.map(checkDeferredMap);
4251 if (noteWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
4252 chk.warnUnchecked(env.tree.pos(),
4253 "unchecked.meth.invocation.applied",
4256 rs.methodArguments(sym.type.getParameterTypes()),
4257 rs.methodArguments(argtypes.map(checkDeferredMap)),
4258 kindName(sym.location()),
4260 if (resultInfo.pt != Infer.anyPoly ||
4261 !owntype.hasTag(METHOD) ||
4262 !owntype.isPartial()) {
4263 //if this is not a partially inferred method type, erase return type. Otherwise,
4264 //erasure is carried out in PartiallyInferredMethodType.check().
4265 owntype = new MethodType(owntype.getParameterTypes(),
4266 types.erasure(owntype.getReturnType()),
4267 types.erasure(owntype.getThrownTypes()),
4272 PolyKind pkind = (sym.type.hasTag(FORALL) &&
4273 sym.type.getReturnType().containsAny(((ForAll)sym.type).tvars)) ?
4274 PolyKind.POLY : PolyKind.STANDALONE;
4275 TreeInfo.setPolyKind(env.tree, pkind);
4277 return (resultInfo.pt == Infer.anyPoly) ?
4279 chk.checkMethod(owntype, sym, env, argtrees, argtypes, env.info.lastResolveVarargs(),
4280 resultInfo.checkContext.inferenceContext());
4281 } catch (Infer.InferenceException ex) {
4282 //invalid target type - propagate exception outwards or report error
4283 //depending on the current check context
4284 resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic());
4285 return types.createErrorType(sym.type);
4286 } catch (Resolve.InapplicableMethodException ex) {
4287 final JCDiagnostic diag = ex.getDiagnostic();
4288 Resolve.InapplicableSymbolError errSym = rs.new InapplicableSymbolError(null) {
4290 protected Pair<Symbol, JCDiagnostic> errCandidate() {
4291 return new Pair<>(sym, diag);
4294 List<Type> argtypes2 = argtypes.map(
4295 rs.new ResolveDeferredRecoveryMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
4296 JCDiagnostic errDiag = errSym.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
4297 env.tree, sym, site, sym.name, argtypes2, typeargtypes);
4298 log.report(errDiag);
4299 return types.createErrorType(site);
4303 public void visitLiteral(JCLiteral tree) {
4304 result = check(tree, litType(tree.typetag).constType(tree.value),
4305 KindSelector.VAL, resultInfo);
4308 /** Return the type of a literal with given type tag.
4310 Type litType(TypeTag tag) {
4311 return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()];
4314 public void visitTypeIdent(JCPrimitiveTypeTree tree) {
4315 result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], KindSelector.TYP, resultInfo);
4318 public void visitTypeArray(JCArrayTypeTree tree) {
4319 Type etype = attribType(tree.elemtype, env);
4320 Type type = new ArrayType(etype, syms.arrayClass);
4321 result = check(tree, type, KindSelector.TYP, resultInfo);
4324 /** Visitor method for parameterized types.
4325 * Bound checking is left until later, since types are attributed
4326 * before supertype structure is completely known
4328 public void visitTypeApply(JCTypeApply tree) {
4329 Type owntype = types.createErrorType(tree.type);
4331 // Attribute functor part of application and make sure it's a class.
4332 Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
4334 // Attribute type parameters
4335 List<Type> actuals = attribTypes(tree.arguments, env);
4337 if (clazztype.hasTag(CLASS)) {
4338 List<Type> formals = clazztype.tsym.type.getTypeArguments();
4339 if (actuals.isEmpty()) //diamond
4342 if (actuals.length() == formals.length()) {
4343 List<Type> a = actuals;
4344 List<Type> f = formals;
4345 while (a.nonEmpty()) {
4346 a.head = a.head.withTypeVar(f.head);
4350 // Compute the proper generic outer
4351 Type clazzOuter = clazztype.getEnclosingType();
4352 if (clazzOuter.hasTag(CLASS)) {
4354 JCExpression clazz = TreeInfo.typeIn(tree.clazz);
4355 if (clazz.hasTag(IDENT)) {
4356 site = env.enclClass.sym.type;
4357 } else if (clazz.hasTag(SELECT)) {
4358 site = ((JCFieldAccess) clazz).selected.type;
4359 } else throw new AssertionError(""+tree);
4360 if (clazzOuter.hasTag(CLASS) && site != clazzOuter) {
4361 if (site.hasTag(CLASS))
4362 site = types.asOuterSuper(site, clazzOuter.tsym);
4364 site = types.erasure(clazzOuter);
4368 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym,
4369 clazztype.getMetadata());
4371 if (formals.length() != 0) {
4372 log.error(tree.pos(), "wrong.number.type.args",
4373 Integer.toString(formals.length()));
4375 log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym);
4377 owntype = types.createErrorType(tree.type);
4380 result = check(tree, owntype, KindSelector.TYP, resultInfo);
4383 public void visitTypeUnion(JCTypeUnion tree) {
4384 ListBuffer<Type> multicatchTypes = new ListBuffer<>();
4385 ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
4386 for (JCExpression typeTree : tree.alternatives) {
4387 Type ctype = attribType(typeTree, env);
4388 ctype = chk.checkType(typeTree.pos(),
4389 chk.checkClassType(typeTree.pos(), ctype),
4390 syms.throwableType);
4391 if (!ctype.isErroneous()) {
4392 //check that alternatives of a union type are pairwise
4393 //unrelated w.r.t. subtyping
4394 if (chk.intersects(ctype, multicatchTypes.toList())) {
4395 for (Type t : multicatchTypes) {
4396 boolean sub = types.isSubtype(ctype, t);
4397 boolean sup = types.isSubtype(t, ctype);
4400 Type a = sub ? ctype : t;
4401 Type b = sub ? t : ctype;
4402 log.error(typeTree.pos(), "multicatch.types.must.be.disjoint", a, b);
4406 multicatchTypes.append(ctype);
4407 if (all_multicatchTypes != null)
4408 all_multicatchTypes.append(ctype);
4410 if (all_multicatchTypes == null) {
4411 all_multicatchTypes = new ListBuffer<>();
4412 all_multicatchTypes.appendList(multicatchTypes);
4414 all_multicatchTypes.append(ctype);
4417 Type t = check(tree, types.lub(multicatchTypes.toList()),
4418 KindSelector.TYP, resultInfo.dup(CheckMode.NO_TREE_UPDATE));
4419 if (t.hasTag(CLASS)) {
4420 List<Type> alternatives =
4421 ((all_multicatchTypes == null) ? multicatchTypes : all_multicatchTypes).toList();
4422 t = new UnionClassType((ClassType) t, alternatives);
4424 tree.type = result = t;
4427 public void visitTypeIntersection(JCTypeIntersection tree) {
4428 attribTypes(tree.bounds, env);
4429 tree.type = result = checkIntersection(tree, tree.bounds);
4432 public void visitTypeParameter(JCTypeParameter tree) {
4433 TypeVar typeVar = (TypeVar) tree.type;
4435 if (tree.annotations != null && tree.annotations.nonEmpty()) {
4436 annotate.annotateTypeParameterSecondStage(tree, tree.annotations);
4439 if (!typeVar.bound.isErroneous()) {
4440 //fixup type-parameter bound computed in 'attribTypeVariables'
4441 typeVar.bound = checkIntersection(tree, tree.bounds);
4445 Type checkIntersection(JCTree tree, List<JCExpression> bounds) {
4446 Set<Type> boundSet = new HashSet<>();
4447 if (bounds.nonEmpty()) {
4448 // accept class or interface or typevar as first bound.
4449 bounds.head.type = checkBase(bounds.head.type, bounds.head, env, false, false, false);
4450 boundSet.add(types.erasure(bounds.head.type));
4451 if (bounds.head.type.isErroneous()) {
4452 return bounds.head.type;
4454 else if (bounds.head.type.hasTag(TYPEVAR)) {
4455 // if first bound was a typevar, do not accept further bounds.
4456 if (bounds.tail.nonEmpty()) {
4457 log.error(bounds.tail.head.pos(),
4458 "type.var.may.not.be.followed.by.other.bounds");
4459 return bounds.head.type;
4462 // if first bound was a class or interface, accept only interfaces
4463 // as further bounds.
4464 for (JCExpression bound : bounds.tail) {
4465 bound.type = checkBase(bound.type, bound, env, false, true, false);
4466 if (bound.type.isErroneous()) {
4467 bounds = List.of(bound);
4469 else if (bound.type.hasTag(CLASS)) {
4470 chk.checkNotRepeated(bound.pos(), types.erasure(bound.type), boundSet);
4476 if (bounds.length() == 0) {
4477 return syms.objectType;
4478 } else if (bounds.length() == 1) {
4479 return bounds.head.type;
4481 Type owntype = types.makeIntersectionType(TreeInfo.types(bounds));
4482 // ... the variable's bound is a class type flagged COMPOUND
4483 // (see comment for TypeVar.bound).
4484 // In this case, generate a class tree that represents the
4486 JCExpression extending;
4487 List<JCExpression> implementing;
4488 if (!bounds.head.type.isInterface()) {
4489 extending = bounds.head;
4490 implementing = bounds.tail;
4493 implementing = bounds;
4495 JCClassDecl cd = make.at(tree).ClassDef(
4496 make.Modifiers(PUBLIC | ABSTRACT),
4497 names.empty, List.nil(),
4498 extending, implementing, List.nil());
4500 ClassSymbol c = (ClassSymbol)owntype.tsym;
4501 Assert.check((c.flags() & COMPOUND) != 0);
4503 c.sourcefile = env.toplevel.sourcefile;
4505 // ... and attribute the bound class
4506 c.flags_field |= UNATTRIBUTED;
4507 Env<AttrContext> cenv = enter.classEnv(cd, env);
4508 typeEnvs.put(c, cenv);
4514 public void visitWildcard(JCWildcard tree) {
4515 //- System.err.println("visitWildcard("+tree+");");//DEBUG
4516 Type type = (tree.kind.kind == BoundKind.UNBOUND)
4518 : attribType(tree.inner, env);
4519 result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
4522 KindSelector.TYP, resultInfo);
4525 public void visitAnnotation(JCAnnotation tree) {
4526 Assert.error("should be handled in annotate");
4529 public void visitAnnotatedType(JCAnnotatedType tree) {
4530 attribAnnotationTypes(tree.annotations, env);
4531 Type underlyingType = attribType(tree.underlyingType, env);
4532 Type annotatedType = underlyingType.annotatedType(Annotations.TO_BE_SET);
4534 if (!env.info.isNewClass)
4535 annotate.annotateTypeSecondStage(tree, tree.annotations, annotatedType);
4536 result = tree.type = annotatedType;
4539 public void visitErroneous(JCErroneous tree) {
4540 if (tree.errs != null)
4541 for (JCTree err : tree.errs) {
4543 attribTree(err, env, new ResultInfo(KindSelector.ERR, pt()));
4544 } catch (AssertionError ae) {
4548 result = tree.type = syms.errType;
4551 /** Default visitor method for all other trees.
4553 public void visitTree(JCTree tree) {
4554 throw new AssertionError();
4558 * Attribute an env for either a top level tree or class or module declaration.
4560 public void attrib(Env<AttrContext> env) {
4561 switch (env.tree.getTag()) {
4563 attribModule(env.tree.pos(), ((JCModuleDecl)env.tree).sym);
4566 attribTopLevel(env);
4569 attribPackage(env.tree.pos(), ((JCPackageDecl) env.tree).packge);
4572 attribClass(env.tree.pos(), env.enclClass.sym);
4577 * Attribute a top level tree. These trees are encountered when the
4578 * package declaration has annotations.
4580 public void attribTopLevel(Env<AttrContext> env) {
4581 JCCompilationUnit toplevel = env.toplevel;
4584 } catch (CompletionFailure ex) {
4585 chk.completionError(toplevel.pos(), ex);
4589 public void attribPackage(DiagnosticPosition pos, PackageSymbol p) {
4593 } catch (CompletionFailure ex) {
4594 chk.completionError(pos, ex);
4598 void attribPackage(PackageSymbol p) {
4599 Env<AttrContext> env = typeEnvs.get(p);
4600 chk.checkDeprecatedAnnotation(((JCPackageDecl) env.tree).pid.pos(), p);
4603 public void attribModule(DiagnosticPosition pos, ModuleSymbol m) {
4607 } catch (CompletionFailure ex) {
4608 chk.completionError(pos, ex);
4612 void attribModule(ModuleSymbol m) {
4613 // Get environment current at the point of module definition.
4614 Env<AttrContext> env = enter.typeEnvs.get(m);
4615 attribStat(env.tree, env);
4618 /** Main method: attribute class definition associated with given class symbol.
4619 * reporting completion failures at the given position.
4620 * @param pos The source position at which completion errors are to be
4622 * @param c The class symbol whose definition will be attributed.
4624 public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
4628 } catch (CompletionFailure ex) {
4629 chk.completionError(pos, ex);
4633 /** Attribute class definition associated with given class symbol.
4634 * @param c The class symbol whose definition will be attributed.
4636 void attribClass(ClassSymbol c) throws CompletionFailure {
4637 // Check for cycles in the inheritance graph, which can arise from
4638 // ill-formed class files.
4639 chk.checkNonCyclic(null, c.type);
4641 Type st = types.supertype(c.type);
4642 if ((c.flags_field & Flags.COMPOUND) == 0) {
4643 // First, attribute superclass.
4644 if (st.hasTag(CLASS))
4645 attribClass((ClassSymbol)st.tsym);
4647 // Next attribute owner, if it is a class.
4648 if (c.owner.kind == TYP && c.owner.type.hasTag(CLASS))
4649 attribClass((ClassSymbol)c.owner);
4652 // The previous operations might have attributed the current class
4653 // if there was a cycle. So we test first whether the class is still
4655 if ((c.flags_field & UNATTRIBUTED) != 0) {
4656 c.flags_field &= ~UNATTRIBUTED;
4658 // Get environment current at the point of class definition.
4659 Env<AttrContext> env = typeEnvs.get(c);
4664 // The info.lint field in the envs stored in typeEnvs is deliberately uninitialized,
4665 // because the annotations were not available at the time the env was created. Therefore,
4666 // we look up the environment chain for the first enclosing environment for which the
4667 // lint value is set. Typically, this is the parent env, but might be further if there
4668 // are any envs created as a result of TypeParameter nodes.
4669 Env<AttrContext> lintEnv = env;
4670 while (lintEnv.info.lint == null)
4671 lintEnv = lintEnv.next;
4673 // Having found the enclosing lint value, we can initialize the lint value for this class
4674 env.info.lint = lintEnv.info.lint.augment(c);
4676 Lint prevLint = chk.setLint(env.info.lint);
4677 JavaFileObject prev = log.useSource(c.sourcefile);
4678 ResultInfo prevReturnRes = env.info.returnResult;
4681 deferredLintHandler.flush(env.tree);
4682 env.info.returnResult = null;
4683 // java.lang.Enum may not be subclassed by a non-enum
4684 if (st.tsym == syms.enumSym &&
4685 ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
4686 log.error(env.tree.pos(), "enum.no.subclassing");
4688 // Enums may not be extended by source-level classes
4689 if (st.tsym != null &&
4690 ((st.tsym.flags_field & Flags.ENUM) != 0) &&
4691 ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
4692 log.error(env.tree.pos(), "enum.types.not.extensible");
4695 if (isSerializable(c.type)) {
4696 env.info.isSerializable = true;
4699 attribClassBody(env, c);
4701 deferredLintHandler.flush(env.tree.pos());
4702 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
4703 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
4704 chk.checkFunctionalInterface((JCClassDecl) env.tree, c);
4705 chk.checkLeaksNotAccessible(env, (JCClassDecl) env.tree);
4707 env.info.returnResult = prevReturnRes;
4708 log.useSource(prev);
4709 chk.setLint(prevLint);
4715 public void visitImport(JCImport tree) {
4719 public void visitModuleDef(JCModuleDecl tree) {
4720 tree.sym.completeUsesProvides();
4721 ModuleSymbol msym = tree.sym;
4722 Lint lint = env.outer.info.lint = env.outer.info.lint.augment(msym);
4723 Lint prevLint = chk.setLint(lint);
4724 chk.checkModuleName(tree);
4725 chk.checkDeprecatedAnnotation(tree, msym);
4728 deferredLintHandler.flush(tree.pos());
4730 chk.setLint(prevLint);
4734 /** Finish the attribution of a class. */
4735 private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
4736 JCClassDecl tree = (JCClassDecl)env.tree;
4739 Assert.error("c = " + c + " tree.sym = " + tree.sym + " tree = " + tree);
4741 // Validate type parameters, supertype and interfaces.
4742 attribStats(tree.typarams, env);
4743 if (!c.isAnonymous()) {
4744 //already checked if anonymous
4745 chk.validate(tree.typarams, env);
4746 chk.validate(tree.extending, env);
4747 chk.validate(tree.implementing, env);
4750 c.markAbstractIfNeeded(types);
4752 // If this is a non-abstract class, check that it has no abstract
4753 // methods or unimplemented methods of an implemented interface.
4754 if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
4755 chk.checkAllDefined(tree.pos(), c);
4758 if ((c.flags() & ANNOTATION) != 0) {
4759 if (tree.implementing.nonEmpty())
4760 log.error(tree.implementing.head.pos(),
4761 "cant.extend.intf.annotation");
4762 if (tree.typarams.nonEmpty())
4763 log.error(tree.typarams.head.pos(),
4764 "intf.annotation.cant.have.type.params");
4766 // If this annotation type has a @Repeatable, validate
4767 Attribute.Compound repeatable = c.getAnnotationTypeMetadata().getRepeatable();
4768 // If this annotation type has a @Repeatable, validate
4769 if (repeatable != null) {
4770 // get diagnostic position for error reporting
4771 DiagnosticPosition cbPos = getDiagnosticPosition(tree, repeatable.type);
4772 Assert.checkNonNull(cbPos);
4774 chk.validateRepeatable(c, repeatable, cbPos);
4777 // Check that all extended classes and interfaces
4778 // are compatible (i.e. no two define methods with same arguments
4779 // yet different return types). (JLS 8.4.6.3)
4780 chk.checkCompatibleSupertypes(tree.pos(), c.type);
4781 if (allowDefaultMethods) {
4782 chk.checkDefaultMethodClashes(tree.pos(), c.type);
4786 // Check that class does not import the same parameterized interface
4787 // with two different argument lists.
4788 chk.checkClassBounds(tree.pos(), c.type);
4792 for (List<JCTypeParameter> l = tree.typarams;
4793 l.nonEmpty(); l = l.tail) {
4794 Assert.checkNonNull(env.info.scope.findFirst(l.head.name));
4797 // Check that a generic class doesn't extend Throwable
4798 if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
4799 log.error(tree.extending.pos(), "generic.throwable");
4801 // Check that all methods which implement some
4802 // method conform to the method they implement.
4803 DiagnosticPosition prevPos = deferredLintHandler.setPos(tree.pos());
4805 chk.checkImplementations(tree);
4807 deferredLintHandler.setPos(prevPos);
4810 //check that a resource implementing AutoCloseable cannot throw InterruptedException
4811 checkAutoCloseable(tree.pos(), env, c.type);
4813 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
4814 // Attribute declaration
4815 attribStat(l.head, env);
4816 // Check that declarations in inner classes are not static (JLS 8.1.2)
4817 // Make an exception for static constants.
4818 if (c.owner.kind != PCK &&
4819 ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
4820 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
4822 if (l.head.hasTag(VARDEF)) sym = ((JCVariableDecl) l.head).sym;
4825 ((VarSymbol) sym).getConstValue() == null) {
4826 // Check that enum type is not local. If so, 'Enum types must not be local' is already reported
4827 // and there is no need for reporting static declaration in an inner class
4828 if (c.owner.kind != MTH || (c.flags() & ENUM) == 0)
4829 log.error(l.head.pos(), "icls.cant.have.static.decl", c);
4834 // Check for cycles among non-initial constructors.
4835 chk.checkCyclicConstructors(tree);
4837 // Check for cycles among annotation elements.
4838 chk.checkNonCyclicElements(tree);
4840 // Check for proper use of serialVersionUID
4841 if (env.info.lint.isEnabled(LintCategory.SERIAL)
4842 && isSerializable(c.type)
4843 && (c.flags() & Flags.ENUM) == 0
4845 && checkForSerial(c)) {
4846 checkSerialVersionUID(tree, c);
4848 if (allowTypeAnnos) {
4849 // Correctly organize the postions of the type annotations
4850 typeAnnotations.organizeTypeAnnotationsBodies(tree);
4852 // Check type annotations applicability rules
4853 validateTypeAnnotations(tree, false);
4857 boolean checkForSerial(ClassSymbol c) {
4858 if ((c.flags() & ABSTRACT) == 0) {
4861 return c.members().anyMatch(anyNonAbstractOrDefaultMethod);
4865 public static final Filter<Symbol> anyNonAbstractOrDefaultMethod = s ->
4866 s.kind == MTH && (s.flags() & (DEFAULT | ABSTRACT)) != ABSTRACT;
4868 /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
4869 private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
4870 for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
4871 if (types.isSameType(al.head.annotationType.type, t))
4872 return al.head.pos();
4878 /** check if a type is a subtype of Serializable, if that is available. */
4879 boolean isSerializable(Type t) {
4881 syms.serializableType.complete();
4883 catch (CompletionFailure e) {
4886 return types.isSubtype(t, syms.serializableType);
4889 /** Check that an appropriate serialVersionUID member is defined. */
4890 private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
4892 // check for presence of serialVersionUID
4893 VarSymbol svuid = null;
4894 for (Symbol sym : c.members().getSymbolsByName(names.serialVersionUID)) {
4895 if (sym.kind == VAR) {
4896 svuid = (VarSymbol)sym;
4901 if (svuid == null) {
4902 log.warning(LintCategory.SERIAL,
4903 tree.pos(), "missing.SVUID", c);
4907 // check that it is static final
4908 if ((svuid.flags() & (STATIC | FINAL)) !=
4910 log.warning(LintCategory.SERIAL,
4911 TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c);
4913 // check that it is long
4914 else if (!svuid.type.hasTag(LONG))
4915 log.warning(LintCategory.SERIAL,
4916 TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c);
4919 else if (svuid.getConstValue() == null)
4920 log.warning(LintCategory.SERIAL,
4921 TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c);
4924 private Type capture(Type type) {
4925 return types.capture(type);
4928 public void validateTypeAnnotations(JCTree tree, boolean sigOnly) {
4929 tree.accept(new TypeAnnotationsValidator(sigOnly));
4932 private final class TypeAnnotationsValidator extends TreeScanner {
4934 private final boolean sigOnly;
4935 public TypeAnnotationsValidator(boolean sigOnly) {
4936 this.sigOnly = sigOnly;
4939 public void visitAnnotation(JCAnnotation tree) {
4940 chk.validateTypeAnnotation(tree, false);
4941 super.visitAnnotation(tree);
4943 public void visitAnnotatedType(JCAnnotatedType tree) {
4944 if (!tree.underlyingType.type.isErroneous()) {
4945 super.visitAnnotatedType(tree);
4948 public void visitTypeParameter(JCTypeParameter tree) {
4949 chk.validateTypeAnnotations(tree.annotations, true);
4951 // Don't call super.
4952 // This is needed because above we call validateTypeAnnotation with
4953 // false, which would forbid annotations on type parameters.
4954 // super.visitTypeParameter(tree);
4956 public void visitMethodDef(JCMethodDecl tree) {
4957 if (tree.recvparam != null &&
4958 !tree.recvparam.vartype.type.isErroneous()) {
4959 checkForDeclarationAnnotations(tree.recvparam.mods.annotations,
4960 tree.recvparam.vartype.type.tsym);
4962 if (tree.restype != null && tree.restype.type != null) {
4963 validateAnnotatedType(tree.restype, tree.restype.type);
4968 scan(tree.typarams);
4969 scan(tree.recvparam);
4973 scan(tree.defaultValue);
4977 public void visitVarDef(final JCVariableDecl tree) {
4978 //System.err.println("validateTypeAnnotations.visitVarDef " + tree);
4979 if (tree.sym != null && tree.sym.type != null && !tree.sym.type.isErroneous())
4980 validateAnnotatedType(tree.vartype, tree.sym.type);
4987 public void visitTypeCast(JCTypeCast tree) {
4988 if (tree.clazz != null && tree.clazz.type != null)
4989 validateAnnotatedType(tree.clazz, tree.clazz.type);
4990 super.visitTypeCast(tree);
4992 public void visitTypeTest(JCInstanceOf tree) {
4993 if (tree.clazz != null && tree.clazz.type != null)
4994 validateAnnotatedType(tree.clazz, tree.clazz.type);
4995 super.visitTypeTest(tree);
4997 public void visitNewClass(JCNewClass tree) {
4998 if (tree.clazz != null && tree.clazz.type != null) {
4999 if (tree.clazz.hasTag(ANNOTATED_TYPE)) {
5000 checkForDeclarationAnnotations(((JCAnnotatedType) tree.clazz).annotations,
5001 tree.clazz.type.tsym);
5003 if (tree.def != null) {
5004 checkForDeclarationAnnotations(tree.def.mods.annotations, tree.clazz.type.tsym);
5007 validateAnnotatedType(tree.clazz, tree.clazz.type);
5009 super.visitNewClass(tree);
5011 public void visitNewArray(JCNewArray tree) {
5012 if (tree.elemtype != null && tree.elemtype.type != null) {
5013 if (tree.elemtype.hasTag(ANNOTATED_TYPE)) {
5014 checkForDeclarationAnnotations(((JCAnnotatedType) tree.elemtype).annotations,
5015 tree.elemtype.type.tsym);
5017 validateAnnotatedType(tree.elemtype, tree.elemtype.type);
5019 super.visitNewArray(tree);
5021 public void visitClassDef(JCClassDecl tree) {
5022 //System.err.println("validateTypeAnnotations.visitClassDef " + tree);
5025 scan(tree.typarams);
5026 scan(tree.extending);
5027 scan(tree.implementing);
5029 for (JCTree member : tree.defs) {
5030 if (member.hasTag(Tag.CLASSDEF)) {
5036 public void visitBlock(JCBlock tree) {
5042 /* I would want to model this after
5043 * com.sun.tools.javac.comp.Check.Validator.visitSelectInternal(JCFieldAccess)
5044 * and override visitSelect and visitTypeApply.
5045 * However, we only set the annotated type in the top-level type
5047 * Therefore, we need to override each individual location where a type
5050 private void validateAnnotatedType(final JCTree errtree, final Type type) {
5051 //System.err.println("Attr.validateAnnotatedType: " + errtree + " type: " + type);
5053 if (type.isPrimitiveOrVoid() || type.isErroneous()) {
5057 JCTree enclTr = errtree;
5060 boolean repeat = true;
5062 if (enclTr == null) {
5063 Assert.error("Unexpected null tree within: "+ errtree + " with kind: " + errtree.getKind());
5065 if (enclTr.hasTag(TYPEAPPLY)) {
5066 List<Type> tyargs = enclTy.getTypeArguments();
5067 List<JCExpression> trargs = ((JCTypeApply)enclTr).getTypeArguments();
5068 if (trargs.length() > 0) {
5069 // Nothing to do for diamonds
5070 if (tyargs.length() == trargs.length()) {
5071 for (int i = 0; i < tyargs.length(); ++i) {
5072 validateAnnotatedType(trargs.get(i), tyargs.get(i));
5075 // If the lengths don't match, it's either a diamond
5076 // or some nested type that redundantly provides
5077 // type arguments in the tree.
5080 // Look at the clazz part of a generic type
5081 enclTr = ((JCTree.JCTypeApply)enclTr).clazz;
5084 if (enclTr.hasTag(SELECT)) {
5085 enclTr = ((JCTree.JCFieldAccess)enclTr).getExpression();
5086 if (enclTy != null &&
5087 !enclTy.hasTag(NONE)) {
5088 enclTy = enclTy.getEnclosingType();
5090 } else if (enclTr.hasTag(ANNOTATED_TYPE)) {
5091 JCAnnotatedType at = (JCTree.JCAnnotatedType) enclTr;
5092 if (enclTy == null || enclTy.hasTag(NONE)) {
5093 if (at.getAnnotations().size() == 1) {
5094 log.error(at.underlyingType.pos(), "cant.type.annotate.scoping.1", at.getAnnotations().head.attribute);
5096 ListBuffer<Attribute.Compound> comps = new ListBuffer<>();
5097 for (JCAnnotation an : at.getAnnotations()) {
5098 comps.add(an.attribute);
5100 log.error(at.underlyingType.pos(), "cant.type.annotate.scoping", comps.toList());
5104 enclTr = at.underlyingType;
5105 // enclTy doesn't need to be changed
5106 } else if (enclTr.hasTag(IDENT)) {
5108 } else if (enclTr.hasTag(JCTree.Tag.WILDCARD)) {
5109 JCWildcard wc = (JCWildcard) enclTr;
5110 if (wc.getKind() == JCTree.Kind.EXTENDS_WILDCARD) {
5111 validateAnnotatedType(wc.getBound(), ((WildcardType)enclTy).getExtendsBound());
5112 } else if (wc.getKind() == JCTree.Kind.SUPER_WILDCARD) {
5113 validateAnnotatedType(wc.getBound(), ((WildcardType)enclTy).getSuperBound());
5115 // Nothing to do for UNBOUND
5118 } else if (enclTr.hasTag(TYPEARRAY)) {
5119 JCArrayTypeTree art = (JCArrayTypeTree) enclTr;
5120 validateAnnotatedType(art.getType(), ((ArrayType)enclTy).getComponentType());
5122 } else if (enclTr.hasTag(TYPEUNION)) {
5123 JCTypeUnion ut = (JCTypeUnion) enclTr;
5124 for (JCTree t : ut.getTypeAlternatives()) {
5125 validateAnnotatedType(t, t.type);
5128 } else if (enclTr.hasTag(TYPEINTERSECTION)) {
5129 JCTypeIntersection it = (JCTypeIntersection) enclTr;
5130 for (JCTree t : it.getBounds()) {
5131 validateAnnotatedType(t, t.type);
5134 } else if (enclTr.getKind() == JCTree.Kind.PRIMITIVE_TYPE ||
5135 enclTr.getKind() == JCTree.Kind.ERRONEOUS) {
5137 } else if (enclTr.getKind() == JCTree.Kind.ERRONEOUS) {
5140 Assert.error("Unexpected tree: " + enclTr + " with kind: " + enclTr.getKind() +
5141 " within: "+ errtree + " with kind: " + errtree.getKind());
5146 private void checkForDeclarationAnnotations(List<? extends JCAnnotation> annotations,
5148 // Ensure that no declaration annotations are present.
5149 // Note that a tree type might be an AnnotatedType with
5150 // empty annotations, if only declaration annotations were given.
5151 // This method will raise an error for such a type.
5152 for (JCAnnotation ai : annotations) {
5153 if (!ai.type.isErroneous() &&
5154 typeAnnotations.annotationTargetType(ai.attribute, sym) == TypeAnnotations.AnnotationType.DECLARATION) {
5155 log.error(ai.pos(), Errors.AnnotationTypeNotApplicableToType(ai.type));
5161 public Env<AttrContext> dupLocalEnv(Env<AttrContext> localEnv) {
5162 return localEnv.dup(localEnv.tree, localEnv.info.dup(localEnv.info.scope.dupUnshared()));
5165 // <editor-fold desc="post-attribution visitor">
5168 * Handle missing types/symbols in an AST. This routine is useful when
5169 * the compiler has encountered some errors (which might have ended up
5170 * terminating attribution abruptly); if the compiler is used in fail-over
5171 * mode (e.g. by an IDE) and the AST contains semantic errors, this routine
5172 * prevents NPE to be progagated during subsequent compilation steps.
5174 public void postAttr(JCTree tree) {
5175 new PostAttrAnalyzer().scan(tree);
5178 class PostAttrAnalyzer extends TreeScanner {
5180 private void initTypeIfNeeded(JCTree that) {
5181 if (that.type == null) {
5182 if (that.hasTag(METHODDEF)) {
5183 that.type = dummyMethodType((JCMethodDecl)that);
5185 that.type = syms.unknownType;
5190 /* Construct a dummy method type. If we have a method declaration,
5191 * and the declared return type is void, then use that return type
5192 * instead of UNKNOWN to avoid spurious error messages in lambda
5193 * bodies (see:JDK-8041704).
5195 private Type dummyMethodType(JCMethodDecl md) {
5196 Type restype = syms.unknownType;
5197 if (md != null && md.restype != null && md.restype.hasTag(TYPEIDENT)) {
5198 JCPrimitiveTypeTree prim = (JCPrimitiveTypeTree)md.restype;
5199 if (prim.typetag == VOID)
5200 restype = syms.voidType;
5202 return new MethodType(List.nil(), restype,
5203 List.nil(), syms.methodClass);
5205 private Type dummyMethodType() {
5206 return dummyMethodType(null);
5210 public void scan(JCTree tree) {
5211 if (tree == null) return;
5212 if (tree instanceof JCExpression) {
5213 initTypeIfNeeded(tree);
5219 public void visitIdent(JCIdent that) {
5220 if (that.sym == null) {
5221 that.sym = syms.unknownSymbol;
5226 public void visitSelect(JCFieldAccess that) {
5227 if (that.sym == null) {
5228 that.sym = syms.unknownSymbol;
5230 super.visitSelect(that);
5234 public void visitClassDef(JCClassDecl that) {
5235 initTypeIfNeeded(that);
5236 if (that.sym == null) {
5237 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol);
5239 super.visitClassDef(that);
5242 private boolean inMethodParams = false;
5245 public void visitMethodDef(JCMethodDecl that) {
5246 initTypeIfNeeded(that);
5247 if (that.sym == null) {
5248 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol);
5252 scan(that.typarams);
5254 inMethodParams = true;
5255 scan(that.recvparam);
5258 inMethodParams = false;
5261 scan(that.defaultValue);
5266 public void visitVarDef(JCVariableDecl that) {
5267 initTypeIfNeeded(that);
5268 if (that.sym == null) {
5269 that.sym = new VarSymbol(inMethodParams ? Flags.PARAMETER : 0, that.name, that.type, syms.noSymbol);
5272 if (that.vartype == null) {
5273 that.vartype = make.Erroneous();
5275 super.visitVarDef(that);
5279 public void visitNewClass(JCNewClass that) {
5280 if (that.constructor == null) {
5281 that.constructor = new MethodSymbol(0, names.init,
5282 dummyMethodType(), syms.noSymbol);
5284 if (that.constructorType == null) {
5285 that.constructorType = syms.unknownType;
5287 super.visitNewClass(that);
5291 public void visitAssignop(JCAssignOp that) {
5292 if (that.operator == null) {
5293 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
5296 super.visitAssignop(that);
5300 public void visitBinary(JCBinary that) {
5301 if (that.operator == null) {
5302 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
5305 super.visitBinary(that);
5309 public void visitUnary(JCUnary that) {
5310 if (that.operator == null) {
5311 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
5314 super.visitUnary(that);
5318 public void visitLambda(JCLambda that) {
5319 super.visitLambda(that);
5320 if (that.targets == null) {
5321 that.targets = List.nil();
5326 public void visitReference(JCMemberReference that) {
5327 super.visitReference(that);
5328 if (that.sym == null) {
5329 that.sym = new MethodSymbol(0, names.empty, dummyMethodType(),
5332 if (that.targets == null) {
5333 that.targets = List.nil();
5338 public void visitErroneous(JCErroneous tree) {
5344 public void setPackageSymbols(JCExpression pid, Symbol pkg) {
5346 Symbol packge = pkg;
5348 public void visitIdent(JCIdent that) {
5353 public void visitSelect(JCFieldAccess that) {
5355 packge = packge.owner;
5356 super.visitSelect(that);