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