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