Tue, 02 Nov 2010 12:01:35 +0000
6939780: add a warning to detect diamond sites
Summary: added hidden compiler flag '-XDfindDiamond' to detect 'diamondifiable' sites
Reviewed-by: jjg
1 /*
2 * Copyright (c) 1999, 2009, 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.*;
29 import java.util.Set;
30 import javax.lang.model.element.ElementKind;
31 import javax.tools.JavaFileObject;
33 import com.sun.tools.javac.code.*;
34 import com.sun.tools.javac.jvm.*;
35 import com.sun.tools.javac.tree.*;
36 import com.sun.tools.javac.util.*;
37 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
38 import com.sun.tools.javac.util.List;
40 import com.sun.tools.javac.jvm.Target;
41 import com.sun.tools.javac.code.Symbol.*;
42 import com.sun.tools.javac.tree.JCTree.*;
43 import com.sun.tools.javac.code.Type.*;
45 import com.sun.source.tree.IdentifierTree;
46 import com.sun.source.tree.MemberSelectTree;
47 import com.sun.source.tree.TreeVisitor;
48 import com.sun.source.util.SimpleTreeVisitor;
50 import static com.sun.tools.javac.code.Flags.*;
51 import static com.sun.tools.javac.code.Kinds.*;
52 import static com.sun.tools.javac.code.TypeTags.*;
54 /** This is the main context-dependent analysis phase in GJC. It
55 * encompasses name resolution, type checking and constant folding as
56 * subtasks. Some subtasks involve auxiliary classes.
57 * @see Check
58 * @see Resolve
59 * @see ConstFold
60 * @see Infer
61 *
62 * <p><b>This is NOT part of any supported API.
63 * If you write code that depends on this, you do so at your own risk.
64 * This code and its internal interfaces are subject to change or
65 * deletion without notice.</b>
66 */
67 public class Attr extends JCTree.Visitor {
68 protected static final Context.Key<Attr> attrKey =
69 new Context.Key<Attr>();
71 final Names names;
72 final Log log;
73 final Symtab syms;
74 final Resolve rs;
75 final Infer infer;
76 final Check chk;
77 final MemberEnter memberEnter;
78 final TreeMaker make;
79 final ConstFold cfolder;
80 final Enter enter;
81 final Target target;
82 final Types types;
83 final JCDiagnostic.Factory diags;
84 final Annotate annotate;
86 public static Attr instance(Context context) {
87 Attr instance = context.get(attrKey);
88 if (instance == null)
89 instance = new Attr(context);
90 return instance;
91 }
93 protected Attr(Context context) {
94 context.put(attrKey, this);
96 names = Names.instance(context);
97 log = Log.instance(context);
98 syms = Symtab.instance(context);
99 rs = Resolve.instance(context);
100 chk = Check.instance(context);
101 memberEnter = MemberEnter.instance(context);
102 make = TreeMaker.instance(context);
103 enter = Enter.instance(context);
104 infer = Infer.instance(context);
105 cfolder = ConstFold.instance(context);
106 target = Target.instance(context);
107 types = Types.instance(context);
108 diags = JCDiagnostic.Factory.instance(context);
109 annotate = Annotate.instance(context);
111 Options options = Options.instance(context);
113 Source source = Source.instance(context);
114 allowGenerics = source.allowGenerics();
115 allowVarargs = source.allowVarargs();
116 allowEnums = source.allowEnums();
117 allowBoxing = source.allowBoxing();
118 allowCovariantReturns = source.allowCovariantReturns();
119 allowAnonOuterThis = source.allowAnonOuterThis();
120 allowStringsInSwitch = source.allowStringsInSwitch();
121 sourceName = source.name;
122 relax = (options.isSet("-retrofit") ||
123 options.isSet("-relax"));
124 findDiamonds = options.get("findDiamond") != null &&
125 source.allowDiamond();
126 useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
127 enableSunApiLintControl = options.isSet("enableSunApiLintControl");
128 }
130 /** Switch: relax some constraints for retrofit mode.
131 */
132 boolean relax;
134 /** Switch: support generics?
135 */
136 boolean allowGenerics;
138 /** Switch: allow variable-arity methods.
139 */
140 boolean allowVarargs;
142 /** Switch: support enums?
143 */
144 boolean allowEnums;
146 /** Switch: support boxing and unboxing?
147 */
148 boolean allowBoxing;
150 /** Switch: support covariant result types?
151 */
152 boolean allowCovariantReturns;
154 /** Switch: allow references to surrounding object from anonymous
155 * objects during constructor call?
156 */
157 boolean allowAnonOuterThis;
159 /** Switch: generates a warning if diamond can be safely applied
160 * to a given new expression
161 */
162 boolean findDiamonds;
164 /**
165 * Internally enables/disables diamond finder feature
166 */
167 static final boolean allowDiamondFinder = true;
169 /**
170 * Switch: warn about use of variable before declaration?
171 * RFE: 6425594
172 */
173 boolean useBeforeDeclarationWarning;
175 /**
176 * Switch: allow lint infrastructure to control proprietary
177 * API warnings.
178 */
179 boolean enableSunApiLintControl;
181 /**
182 * Switch: allow strings in switch?
183 */
184 boolean allowStringsInSwitch;
186 /**
187 * Switch: name of source level; used for error reporting.
188 */
189 String sourceName;
191 /** Check kind and type of given tree against protokind and prototype.
192 * If check succeeds, store type in tree and return it.
193 * If check fails, store errType in tree and return it.
194 * No checks are performed if the prototype is a method type.
195 * It is not necessary in this case since we know that kind and type
196 * are correct.
197 *
198 * @param tree The tree whose kind and type is checked
199 * @param owntype The computed type of the tree
200 * @param ownkind The computed kind of the tree
201 * @param pkind The expected kind (or: protokind) of the tree
202 * @param pt The expected type (or: prototype) of the tree
203 */
204 Type check(JCTree tree, Type owntype, int ownkind, int pkind, Type pt) {
205 if (owntype.tag != ERROR && pt.tag != METHOD && pt.tag != FORALL) {
206 if ((ownkind & ~pkind) == 0) {
207 owntype = chk.checkType(tree.pos(), owntype, pt, errKey);
208 } else {
209 log.error(tree.pos(), "unexpected.type",
210 kindNames(pkind),
211 kindName(ownkind));
212 owntype = types.createErrorType(owntype);
213 }
214 }
215 tree.type = owntype;
216 return owntype;
217 }
219 /** Is given blank final variable assignable, i.e. in a scope where it
220 * may be assigned to even though it is final?
221 * @param v The blank final variable.
222 * @param env The current environment.
223 */
224 boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
225 Symbol owner = env.info.scope.owner;
226 // owner refers to the innermost variable, method or
227 // initializer block declaration at this point.
228 return
229 v.owner == owner
230 ||
231 ((owner.name == names.init || // i.e. we are in a constructor
232 owner.kind == VAR || // i.e. we are in a variable initializer
233 (owner.flags() & BLOCK) != 0) // i.e. we are in an initializer block
234 &&
235 v.owner == owner.owner
236 &&
237 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
238 }
240 /** Check that variable can be assigned to.
241 * @param pos The current source code position.
242 * @param v The assigned varaible
243 * @param base If the variable is referred to in a Select, the part
244 * to the left of the `.', null otherwise.
245 * @param env The current environment.
246 */
247 void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
248 if ((v.flags() & FINAL) != 0 &&
249 ((v.flags() & HASINIT) != 0
250 ||
251 !((base == null ||
252 (base.getTag() == JCTree.IDENT && TreeInfo.name(base) == names._this)) &&
253 isAssignableAsBlankFinal(v, env)))) {
254 if (v.isResourceVariable()) { //TWR resource
255 log.error(pos, "twr.resource.may.not.be.assigned", v);
256 } else {
257 log.error(pos, "cant.assign.val.to.final.var", v);
258 }
259 }
260 }
262 /** Does tree represent a static reference to an identifier?
263 * It is assumed that tree is either a SELECT or an IDENT.
264 * We have to weed out selects from non-type names here.
265 * @param tree The candidate tree.
266 */
267 boolean isStaticReference(JCTree tree) {
268 if (tree.getTag() == JCTree.SELECT) {
269 Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
270 if (lsym == null || lsym.kind != TYP) {
271 return false;
272 }
273 }
274 return true;
275 }
277 /** Is this symbol a type?
278 */
279 static boolean isType(Symbol sym) {
280 return sym != null && sym.kind == TYP;
281 }
283 /** The current `this' symbol.
284 * @param env The current environment.
285 */
286 Symbol thisSym(DiagnosticPosition pos, Env<AttrContext> env) {
287 return rs.resolveSelf(pos, env, env.enclClass.sym, names._this);
288 }
290 /** Attribute a parsed identifier.
291 * @param tree Parsed identifier name
292 * @param topLevel The toplevel to use
293 */
294 public Symbol attribIdent(JCTree tree, JCCompilationUnit topLevel) {
295 Env<AttrContext> localEnv = enter.topLevelEnv(topLevel);
296 localEnv.enclClass = make.ClassDef(make.Modifiers(0),
297 syms.errSymbol.name,
298 null, null, null, null);
299 localEnv.enclClass.sym = syms.errSymbol;
300 return tree.accept(identAttributer, localEnv);
301 }
302 // where
303 private TreeVisitor<Symbol,Env<AttrContext>> identAttributer = new IdentAttributer();
304 private class IdentAttributer extends SimpleTreeVisitor<Symbol,Env<AttrContext>> {
305 @Override
306 public Symbol visitMemberSelect(MemberSelectTree node, Env<AttrContext> env) {
307 Symbol site = visit(node.getExpression(), env);
308 if (site.kind == ERR)
309 return site;
310 Name name = (Name)node.getIdentifier();
311 if (site.kind == PCK) {
312 env.toplevel.packge = (PackageSymbol)site;
313 return rs.findIdentInPackage(env, (TypeSymbol)site, name, TYP | PCK);
314 } else {
315 env.enclClass.sym = (ClassSymbol)site;
316 return rs.findMemberType(env, site.asType(), name, (TypeSymbol)site);
317 }
318 }
320 @Override
321 public Symbol visitIdentifier(IdentifierTree node, Env<AttrContext> env) {
322 return rs.findIdent(env, (Name)node.getName(), TYP | PCK);
323 }
324 }
326 public Type coerce(Type etype, Type ttype) {
327 return cfolder.coerce(etype, ttype);
328 }
330 public Type attribType(JCTree node, TypeSymbol sym) {
331 Env<AttrContext> env = enter.typeEnvs.get(sym);
332 Env<AttrContext> localEnv = env.dup(node, env.info.dup());
333 return attribTree(node, localEnv, Kinds.TYP, Type.noType);
334 }
336 public Env<AttrContext> attribExprToTree(JCTree expr, Env<AttrContext> env, JCTree tree) {
337 breakTree = tree;
338 JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
339 try {
340 attribExpr(expr, env);
341 } catch (BreakAttr b) {
342 return b.env;
343 } catch (AssertionError ae) {
344 if (ae.getCause() instanceof BreakAttr) {
345 return ((BreakAttr)(ae.getCause())).env;
346 } else {
347 throw ae;
348 }
349 } finally {
350 breakTree = null;
351 log.useSource(prev);
352 }
353 return env;
354 }
356 public Env<AttrContext> attribStatToTree(JCTree stmt, Env<AttrContext> env, JCTree tree) {
357 breakTree = tree;
358 JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
359 try {
360 attribStat(stmt, env);
361 } catch (BreakAttr b) {
362 return b.env;
363 } catch (AssertionError ae) {
364 if (ae.getCause() instanceof BreakAttr) {
365 return ((BreakAttr)(ae.getCause())).env;
366 } else {
367 throw ae;
368 }
369 } finally {
370 breakTree = null;
371 log.useSource(prev);
372 }
373 return env;
374 }
376 private JCTree breakTree = null;
378 private static class BreakAttr extends RuntimeException {
379 static final long serialVersionUID = -6924771130405446405L;
380 private Env<AttrContext> env;
381 private BreakAttr(Env<AttrContext> env) {
382 this.env = env;
383 }
384 }
387 /* ************************************************************************
388 * Visitor methods
389 *************************************************************************/
391 /** Visitor argument: the current environment.
392 */
393 Env<AttrContext> env;
395 /** Visitor argument: the currently expected proto-kind.
396 */
397 int pkind;
399 /** Visitor argument: the currently expected proto-type.
400 */
401 Type pt;
403 /** Visitor argument: the error key to be generated when a type error occurs
404 */
405 String errKey;
407 /** Visitor result: the computed type.
408 */
409 Type result;
411 /** Visitor method: attribute a tree, catching any completion failure
412 * exceptions. Return the tree's type.
413 *
414 * @param tree The tree to be visited.
415 * @param env The environment visitor argument.
416 * @param pkind The protokind visitor argument.
417 * @param pt The prototype visitor argument.
418 */
419 Type attribTree(JCTree tree, Env<AttrContext> env, int pkind, Type pt) {
420 return attribTree(tree, env, pkind, pt, "incompatible.types");
421 }
423 Type attribTree(JCTree tree, Env<AttrContext> env, int pkind, Type pt, String errKey) {
424 Env<AttrContext> prevEnv = this.env;
425 int prevPkind = this.pkind;
426 Type prevPt = this.pt;
427 String prevErrKey = this.errKey;
428 try {
429 this.env = env;
430 this.pkind = pkind;
431 this.pt = pt;
432 this.errKey = errKey;
433 tree.accept(this);
434 if (tree == breakTree)
435 throw new BreakAttr(env);
436 return result;
437 } catch (CompletionFailure ex) {
438 tree.type = syms.errType;
439 return chk.completionError(tree.pos(), ex);
440 } finally {
441 this.env = prevEnv;
442 this.pkind = prevPkind;
443 this.pt = prevPt;
444 this.errKey = prevErrKey;
445 }
446 }
448 /** Derived visitor method: attribute an expression tree.
449 */
450 public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) {
451 return attribTree(tree, env, VAL, pt.tag != ERROR ? pt : Type.noType);
452 }
454 public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt, String key) {
455 return attribTree(tree, env, VAL, pt.tag != ERROR ? pt : Type.noType, key);
456 }
458 /** Derived visitor method: attribute an expression tree with
459 * no constraints on the computed type.
460 */
461 Type attribExpr(JCTree tree, Env<AttrContext> env) {
462 return attribTree(tree, env, VAL, Type.noType);
463 }
465 /** Derived visitor method: attribute a type tree.
466 */
467 Type attribType(JCTree tree, Env<AttrContext> env) {
468 Type result = attribType(tree, env, Type.noType);
469 return result;
470 }
472 /** Derived visitor method: attribute a type tree.
473 */
474 Type attribType(JCTree tree, Env<AttrContext> env, Type pt) {
475 Type result = attribTree(tree, env, TYP, pt);
476 return result;
477 }
479 /** Derived visitor method: attribute a statement or definition tree.
480 */
481 public Type attribStat(JCTree tree, Env<AttrContext> env) {
482 return attribTree(tree, env, NIL, Type.noType);
483 }
485 /** Attribute a list of expressions, returning a list of types.
486 */
487 List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) {
488 ListBuffer<Type> ts = new ListBuffer<Type>();
489 for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
490 ts.append(attribExpr(l.head, env, pt));
491 return ts.toList();
492 }
494 /** Attribute a list of statements, returning nothing.
495 */
496 <T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) {
497 for (List<T> l = trees; l.nonEmpty(); l = l.tail)
498 attribStat(l.head, env);
499 }
501 /** Attribute the arguments in a method call, returning a list of types.
502 */
503 List<Type> attribArgs(List<JCExpression> trees, Env<AttrContext> env) {
504 ListBuffer<Type> argtypes = new ListBuffer<Type>();
505 for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
506 argtypes.append(chk.checkNonVoid(
507 l.head.pos(), types.upperBound(attribTree(l.head, env, VAL, Infer.anyPoly))));
508 return argtypes.toList();
509 }
511 /** Attribute a type argument list, returning a list of types.
512 * Caller is responsible for calling checkRefTypes.
513 */
514 List<Type> attribAnyTypes(List<JCExpression> trees, Env<AttrContext> env) {
515 ListBuffer<Type> argtypes = new ListBuffer<Type>();
516 for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
517 argtypes.append(attribType(l.head, env));
518 return argtypes.toList();
519 }
521 /** Attribute a type argument list, returning a list of types.
522 * Check that all the types are references.
523 */
524 List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
525 List<Type> types = attribAnyTypes(trees, env);
526 return chk.checkRefTypes(trees, types);
527 }
529 /**
530 * Attribute type variables (of generic classes or methods).
531 * Compound types are attributed later in attribBounds.
532 * @param typarams the type variables to enter
533 * @param env the current environment
534 */
535 void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env) {
536 for (JCTypeParameter tvar : typarams) {
537 TypeVar a = (TypeVar)tvar.type;
538 a.tsym.flags_field |= UNATTRIBUTED;
539 a.bound = Type.noType;
540 if (!tvar.bounds.isEmpty()) {
541 List<Type> bounds = List.of(attribType(tvar.bounds.head, env));
542 for (JCExpression bound : tvar.bounds.tail)
543 bounds = bounds.prepend(attribType(bound, env));
544 types.setBounds(a, bounds.reverse());
545 } else {
546 // if no bounds are given, assume a single bound of
547 // java.lang.Object.
548 types.setBounds(a, List.of(syms.objectType));
549 }
550 a.tsym.flags_field &= ~UNATTRIBUTED;
551 }
552 for (JCTypeParameter tvar : typarams)
553 chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
554 attribStats(typarams, env);
555 }
557 void attribBounds(List<JCTypeParameter> typarams) {
558 for (JCTypeParameter typaram : typarams) {
559 Type bound = typaram.type.getUpperBound();
560 if (bound != null && bound.tsym instanceof ClassSymbol) {
561 ClassSymbol c = (ClassSymbol)bound.tsym;
562 if ((c.flags_field & COMPOUND) != 0) {
563 assert (c.flags_field & UNATTRIBUTED) != 0 : c;
564 attribClass(typaram.pos(), c);
565 }
566 }
567 }
568 }
570 /**
571 * Attribute the type references in a list of annotations.
572 */
573 void attribAnnotationTypes(List<JCAnnotation> annotations,
574 Env<AttrContext> env) {
575 for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
576 JCAnnotation a = al.head;
577 attribType(a.annotationType, env);
578 }
579 }
581 /** Attribute type reference in an `extends' or `implements' clause.
582 * Supertypes of anonymous inner classes are usually already attributed.
583 *
584 * @param tree The tree making up the type reference.
585 * @param env The environment current at the reference.
586 * @param classExpected true if only a class is expected here.
587 * @param interfaceExpected true if only an interface is expected here.
588 */
589 Type attribBase(JCTree tree,
590 Env<AttrContext> env,
591 boolean classExpected,
592 boolean interfaceExpected,
593 boolean checkExtensible) {
594 Type t = tree.type != null ?
595 tree.type :
596 attribType(tree, env);
597 return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible);
598 }
599 Type checkBase(Type t,
600 JCTree tree,
601 Env<AttrContext> env,
602 boolean classExpected,
603 boolean interfaceExpected,
604 boolean checkExtensible) {
605 if (t.isErroneous())
606 return t;
607 if (t.tag == TYPEVAR && !classExpected && !interfaceExpected) {
608 // check that type variable is already visible
609 if (t.getUpperBound() == null) {
610 log.error(tree.pos(), "illegal.forward.ref");
611 return types.createErrorType(t);
612 }
613 } else {
614 t = chk.checkClassType(tree.pos(), t, checkExtensible|!allowGenerics);
615 }
616 if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) {
617 log.error(tree.pos(), "intf.expected.here");
618 // return errType is necessary since otherwise there might
619 // be undetected cycles which cause attribution to loop
620 return types.createErrorType(t);
621 } else if (checkExtensible &&
622 classExpected &&
623 (t.tsym.flags() & INTERFACE) != 0) {
624 log.error(tree.pos(), "no.intf.expected.here");
625 return types.createErrorType(t);
626 }
627 if (checkExtensible &&
628 ((t.tsym.flags() & FINAL) != 0)) {
629 log.error(tree.pos(),
630 "cant.inherit.from.final", t.tsym);
631 }
632 chk.checkNonCyclic(tree.pos(), t);
633 return t;
634 }
636 public void visitClassDef(JCClassDecl tree) {
637 // Local classes have not been entered yet, so we need to do it now:
638 if ((env.info.scope.owner.kind & (VAR | MTH)) != 0)
639 enter.classEnter(tree, env);
641 ClassSymbol c = tree.sym;
642 if (c == null) {
643 // exit in case something drastic went wrong during enter.
644 result = null;
645 } else {
646 // make sure class has been completed:
647 c.complete();
649 // If this class appears as an anonymous class
650 // in a superclass constructor call where
651 // no explicit outer instance is given,
652 // disable implicit outer instance from being passed.
653 // (This would be an illegal access to "this before super").
654 if (env.info.isSelfCall &&
655 env.tree.getTag() == JCTree.NEWCLASS &&
656 ((JCNewClass) env.tree).encl == null)
657 {
658 c.flags_field |= NOOUTERTHIS;
659 }
660 attribClass(tree.pos(), c);
661 result = tree.type = c.type;
662 }
663 }
665 public void visitMethodDef(JCMethodDecl tree) {
666 MethodSymbol m = tree.sym;
668 Lint lint = env.info.lint.augment(m.attributes_field, m.flags());
669 Lint prevLint = chk.setLint(lint);
670 try {
671 chk.checkDeprecatedAnnotation(tree.pos(), m);
673 attribBounds(tree.typarams);
675 // If we override any other methods, check that we do so properly.
676 // JLS ???
677 chk.checkOverride(tree, m);
679 // Create a new environment with local scope
680 // for attributing the method.
681 Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
683 localEnv.info.lint = lint;
685 // Enter all type parameters into the local method scope.
686 for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
687 localEnv.info.scope.enterIfAbsent(l.head.type.tsym);
689 ClassSymbol owner = env.enclClass.sym;
690 if ((owner.flags() & ANNOTATION) != 0 &&
691 tree.params.nonEmpty())
692 log.error(tree.params.head.pos(),
693 "intf.annotation.members.cant.have.params");
695 // Attribute all value parameters.
696 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
697 attribStat(l.head, localEnv);
698 }
700 chk.checkVarargMethodDecl(tree);
702 // Check that type parameters are well-formed.
703 chk.validate(tree.typarams, localEnv);
705 // Check that result type is well-formed.
706 chk.validate(tree.restype, localEnv);
708 // annotation method checks
709 if ((owner.flags() & ANNOTATION) != 0) {
710 // annotation method cannot have throws clause
711 if (tree.thrown.nonEmpty()) {
712 log.error(tree.thrown.head.pos(),
713 "throws.not.allowed.in.intf.annotation");
714 }
715 // annotation method cannot declare type-parameters
716 if (tree.typarams.nonEmpty()) {
717 log.error(tree.typarams.head.pos(),
718 "intf.annotation.members.cant.have.type.params");
719 }
720 // validate annotation method's return type (could be an annotation type)
721 chk.validateAnnotationType(tree.restype);
722 // ensure that annotation method does not clash with members of Object/Annotation
723 chk.validateAnnotationMethod(tree.pos(), m);
725 if (tree.defaultValue != null) {
726 // if default value is an annotation, check it is a well-formed
727 // annotation value (e.g. no duplicate values, no missing values, etc.)
728 chk.validateAnnotationTree(tree.defaultValue);
729 }
730 }
732 for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
733 chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
735 if (tree.body == null) {
736 // Empty bodies are only allowed for
737 // abstract, native, or interface methods, or for methods
738 // in a retrofit signature class.
739 if ((owner.flags() & INTERFACE) == 0 &&
740 (tree.mods.flags & (ABSTRACT | NATIVE)) == 0 &&
741 !relax)
742 log.error(tree.pos(), "missing.meth.body.or.decl.abstract");
743 if (tree.defaultValue != null) {
744 if ((owner.flags() & ANNOTATION) == 0)
745 log.error(tree.pos(),
746 "default.allowed.in.intf.annotation.member");
747 }
748 } else if ((owner.flags() & INTERFACE) != 0) {
749 log.error(tree.body.pos(), "intf.meth.cant.have.body");
750 } else if ((tree.mods.flags & ABSTRACT) != 0) {
751 log.error(tree.pos(), "abstract.meth.cant.have.body");
752 } else if ((tree.mods.flags & NATIVE) != 0) {
753 log.error(tree.pos(), "native.meth.cant.have.body");
754 } else {
755 // Add an implicit super() call unless an explicit call to
756 // super(...) or this(...) is given
757 // or we are compiling class java.lang.Object.
758 if (tree.name == names.init && owner.type != syms.objectType) {
759 JCBlock body = tree.body;
760 if (body.stats.isEmpty() ||
761 !TreeInfo.isSelfCall(body.stats.head)) {
762 body.stats = body.stats.
763 prepend(memberEnter.SuperCall(make.at(body.pos),
764 List.<Type>nil(),
765 List.<JCVariableDecl>nil(),
766 false));
767 } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
768 (tree.mods.flags & GENERATEDCONSTR) == 0 &&
769 TreeInfo.isSuperCall(body.stats.head)) {
770 // enum constructors are not allowed to call super
771 // directly, so make sure there aren't any super calls
772 // in enum constructors, except in the compiler
773 // generated one.
774 log.error(tree.body.stats.head.pos(),
775 "call.to.super.not.allowed.in.enum.ctor",
776 env.enclClass.sym);
777 }
778 }
780 // Attribute method body.
781 attribStat(tree.body, localEnv);
782 }
783 localEnv.info.scope.leave();
784 result = tree.type = m.type;
785 chk.validateAnnotations(tree.mods.annotations, m);
786 }
787 finally {
788 chk.setLint(prevLint);
789 }
790 }
792 public void visitVarDef(JCVariableDecl tree) {
793 // Local variables have not been entered yet, so we need to do it now:
794 if (env.info.scope.owner.kind == MTH) {
795 if (tree.sym != null) {
796 // parameters have already been entered
797 env.info.scope.enter(tree.sym);
798 } else {
799 memberEnter.memberEnter(tree, env);
800 annotate.flush();
801 }
802 }
804 VarSymbol v = tree.sym;
805 Lint lint = env.info.lint.augment(v.attributes_field, v.flags());
806 Lint prevLint = chk.setLint(lint);
808 // Check that the variable's declared type is well-formed.
809 chk.validate(tree.vartype, env);
811 try {
812 chk.checkDeprecatedAnnotation(tree.pos(), v);
814 if (tree.init != null) {
815 if ((v.flags_field & FINAL) != 0 && tree.init.getTag() != JCTree.NEWCLASS) {
816 // In this case, `v' is final. Ensure that it's initializer is
817 // evaluated.
818 v.getConstValue(); // ensure initializer is evaluated
819 } else {
820 // Attribute initializer in a new environment
821 // with the declared variable as owner.
822 // Check that initializer conforms to variable's declared type.
823 Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
824 initEnv.info.lint = lint;
825 // In order to catch self-references, we set the variable's
826 // declaration position to maximal possible value, effectively
827 // marking the variable as undefined.
828 initEnv.info.enclVar = v;
829 attribExpr(tree.init, initEnv, v.type);
830 }
831 }
832 result = tree.type = v.type;
833 chk.validateAnnotations(tree.mods.annotations, v);
834 }
835 finally {
836 chk.setLint(prevLint);
837 }
838 }
840 public void visitSkip(JCSkip tree) {
841 result = null;
842 }
844 public void visitBlock(JCBlock tree) {
845 if (env.info.scope.owner.kind == TYP) {
846 // Block is a static or instance initializer;
847 // let the owner of the environment be a freshly
848 // created BLOCK-method.
849 Env<AttrContext> localEnv =
850 env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
851 localEnv.info.scope.owner =
852 new MethodSymbol(tree.flags | BLOCK, names.empty, null,
853 env.info.scope.owner);
854 if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
855 attribStats(tree.stats, localEnv);
856 } else {
857 // Create a new local environment with a local scope.
858 Env<AttrContext> localEnv =
859 env.dup(tree, env.info.dup(env.info.scope.dup()));
860 attribStats(tree.stats, localEnv);
861 localEnv.info.scope.leave();
862 }
863 result = null;
864 }
866 public void visitDoLoop(JCDoWhileLoop tree) {
867 attribStat(tree.body, env.dup(tree));
868 attribExpr(tree.cond, env, syms.booleanType);
869 result = null;
870 }
872 public void visitWhileLoop(JCWhileLoop tree) {
873 attribExpr(tree.cond, env, syms.booleanType);
874 attribStat(tree.body, env.dup(tree));
875 result = null;
876 }
878 public void visitForLoop(JCForLoop tree) {
879 Env<AttrContext> loopEnv =
880 env.dup(env.tree, env.info.dup(env.info.scope.dup()));
881 attribStats(tree.init, loopEnv);
882 if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType);
883 loopEnv.tree = tree; // before, we were not in loop!
884 attribStats(tree.step, loopEnv);
885 attribStat(tree.body, loopEnv);
886 loopEnv.info.scope.leave();
887 result = null;
888 }
890 public void visitForeachLoop(JCEnhancedForLoop tree) {
891 Env<AttrContext> loopEnv =
892 env.dup(env.tree, env.info.dup(env.info.scope.dup()));
893 attribStat(tree.var, loopEnv);
894 Type exprType = types.upperBound(attribExpr(tree.expr, loopEnv));
895 chk.checkNonVoid(tree.pos(), exprType);
896 Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
897 if (elemtype == null) {
898 // or perhaps expr implements Iterable<T>?
899 Type base = types.asSuper(exprType, syms.iterableType.tsym);
900 if (base == null) {
901 log.error(tree.expr.pos(), "foreach.not.applicable.to.type");
902 elemtype = types.createErrorType(exprType);
903 } else {
904 List<Type> iterableParams = base.allparams();
905 elemtype = iterableParams.isEmpty()
906 ? syms.objectType
907 : types.upperBound(iterableParams.head);
908 }
909 }
910 chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
911 loopEnv.tree = tree; // before, we were not in loop!
912 attribStat(tree.body, loopEnv);
913 loopEnv.info.scope.leave();
914 result = null;
915 }
917 public void visitLabelled(JCLabeledStatement tree) {
918 // Check that label is not used in an enclosing statement
919 Env<AttrContext> env1 = env;
920 while (env1 != null && env1.tree.getTag() != JCTree.CLASSDEF) {
921 if (env1.tree.getTag() == JCTree.LABELLED &&
922 ((JCLabeledStatement) env1.tree).label == tree.label) {
923 log.error(tree.pos(), "label.already.in.use",
924 tree.label);
925 break;
926 }
927 env1 = env1.next;
928 }
930 attribStat(tree.body, env.dup(tree));
931 result = null;
932 }
934 public void visitSwitch(JCSwitch tree) {
935 Type seltype = attribExpr(tree.selector, env);
937 Env<AttrContext> switchEnv =
938 env.dup(tree, env.info.dup(env.info.scope.dup()));
940 boolean enumSwitch =
941 allowEnums &&
942 (seltype.tsym.flags() & Flags.ENUM) != 0;
943 boolean stringSwitch = false;
944 if (types.isSameType(seltype, syms.stringType)) {
945 if (allowStringsInSwitch) {
946 stringSwitch = true;
947 } else {
948 log.error(tree.selector.pos(), "string.switch.not.supported.in.source", sourceName);
949 }
950 }
951 if (!enumSwitch && !stringSwitch)
952 seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType);
954 // Attribute all cases and
955 // check that there are no duplicate case labels or default clauses.
956 Set<Object> labels = new HashSet<Object>(); // The set of case labels.
957 boolean hasDefault = false; // Is there a default label?
958 for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
959 JCCase c = l.head;
960 Env<AttrContext> caseEnv =
961 switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup()));
962 if (c.pat != null) {
963 if (enumSwitch) {
964 Symbol sym = enumConstant(c.pat, seltype);
965 if (sym == null) {
966 log.error(c.pat.pos(), "enum.const.req");
967 } else if (!labels.add(sym)) {
968 log.error(c.pos(), "duplicate.case.label");
969 }
970 } else {
971 Type pattype = attribExpr(c.pat, switchEnv, seltype);
972 if (pattype.tag != ERROR) {
973 if (pattype.constValue() == null) {
974 log.error(c.pat.pos(),
975 (stringSwitch ? "string.const.req" : "const.expr.req"));
976 } else if (labels.contains(pattype.constValue())) {
977 log.error(c.pos(), "duplicate.case.label");
978 } else {
979 labels.add(pattype.constValue());
980 }
981 }
982 }
983 } else if (hasDefault) {
984 log.error(c.pos(), "duplicate.default.label");
985 } else {
986 hasDefault = true;
987 }
988 attribStats(c.stats, caseEnv);
989 caseEnv.info.scope.leave();
990 addVars(c.stats, switchEnv.info.scope);
991 }
993 switchEnv.info.scope.leave();
994 result = null;
995 }
996 // where
997 /** Add any variables defined in stats to the switch scope. */
998 private static void addVars(List<JCStatement> stats, Scope switchScope) {
999 for (;stats.nonEmpty(); stats = stats.tail) {
1000 JCTree stat = stats.head;
1001 if (stat.getTag() == JCTree.VARDEF)
1002 switchScope.enter(((JCVariableDecl) stat).sym);
1003 }
1004 }
1005 // where
1006 /** Return the selected enumeration constant symbol, or null. */
1007 private Symbol enumConstant(JCTree tree, Type enumType) {
1008 if (tree.getTag() != JCTree.IDENT) {
1009 log.error(tree.pos(), "enum.label.must.be.unqualified.enum");
1010 return syms.errSymbol;
1011 }
1012 JCIdent ident = (JCIdent)tree;
1013 Name name = ident.name;
1014 for (Scope.Entry e = enumType.tsym.members().lookup(name);
1015 e.scope != null; e = e.next()) {
1016 if (e.sym.kind == VAR) {
1017 Symbol s = ident.sym = e.sym;
1018 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
1019 ident.type = s.type;
1020 return ((s.flags_field & Flags.ENUM) == 0)
1021 ? null : s;
1022 }
1023 }
1024 return null;
1025 }
1027 public void visitSynchronized(JCSynchronized tree) {
1028 chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
1029 attribStat(tree.body, env);
1030 result = null;
1031 }
1033 public void visitTry(JCTry tree) {
1034 // Create a new local environment with a local
1035 Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
1036 boolean isTryWithResource = tree.resources.nonEmpty();
1037 // Create a nested environment for attributing the try block if needed
1038 Env<AttrContext> tryEnv = isTryWithResource ?
1039 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
1040 localEnv;
1041 // Attribute resource declarations
1042 for (JCTree resource : tree.resources) {
1043 if (resource.getTag() == JCTree.VARDEF) {
1044 attribStat(resource, tryEnv);
1045 chk.checkType(resource, resource.type, syms.autoCloseableType, "twr.not.applicable.to.type");
1046 VarSymbol var = (VarSymbol)TreeInfo.symbolFor(resource);
1047 var.setData(ElementKind.RESOURCE_VARIABLE);
1048 } else {
1049 attribExpr(resource, tryEnv, syms.autoCloseableType, "twr.not.applicable.to.type");
1050 }
1051 }
1052 // Attribute body
1053 attribStat(tree.body, tryEnv);
1054 if (isTryWithResource)
1055 tryEnv.info.scope.leave();
1057 // Attribute catch clauses
1058 for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
1059 JCCatch c = l.head;
1060 Env<AttrContext> catchEnv =
1061 localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup()));
1062 Type ctype = attribStat(c.param, catchEnv);
1063 if (TreeInfo.isMultiCatch(c)) {
1064 //check that multi-catch parameter is marked as final
1065 if ((c.param.sym.flags() & FINAL) == 0) {
1066 log.error(c.param.pos(), "multicatch.param.must.be.final", c.param.sym);
1067 }
1068 c.param.sym.flags_field = c.param.sym.flags() | DISJUNCTION;
1069 }
1070 if (c.param.sym.kind == Kinds.VAR) {
1071 c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
1072 }
1073 chk.checkType(c.param.vartype.pos(),
1074 chk.checkClassType(c.param.vartype.pos(), ctype),
1075 syms.throwableType);
1076 attribStat(c.body, catchEnv);
1077 catchEnv.info.scope.leave();
1078 }
1080 // Attribute finalizer
1081 if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
1083 localEnv.info.scope.leave();
1084 result = null;
1085 }
1087 public void visitConditional(JCConditional tree) {
1088 attribExpr(tree.cond, env, syms.booleanType);
1089 attribExpr(tree.truepart, env);
1090 attribExpr(tree.falsepart, env);
1091 result = check(tree,
1092 capture(condType(tree.pos(), tree.cond.type,
1093 tree.truepart.type, tree.falsepart.type)),
1094 VAL, pkind, pt);
1095 }
1096 //where
1097 /** Compute the type of a conditional expression, after
1098 * checking that it exists. See Spec 15.25.
1099 *
1100 * @param pos The source position to be used for
1101 * error diagnostics.
1102 * @param condtype The type of the expression's condition.
1103 * @param thentype The type of the expression's then-part.
1104 * @param elsetype The type of the expression's else-part.
1105 */
1106 private Type condType(DiagnosticPosition pos,
1107 Type condtype,
1108 Type thentype,
1109 Type elsetype) {
1110 Type ctype = condType1(pos, condtype, thentype, elsetype);
1112 // If condition and both arms are numeric constants,
1113 // evaluate at compile-time.
1114 return ((condtype.constValue() != null) &&
1115 (thentype.constValue() != null) &&
1116 (elsetype.constValue() != null))
1117 ? cfolder.coerce(condtype.isTrue()?thentype:elsetype, ctype)
1118 : ctype;
1119 }
1120 /** Compute the type of a conditional expression, after
1121 * checking that it exists. Does not take into
1122 * account the special case where condition and both arms
1123 * are constants.
1124 *
1125 * @param pos The source position to be used for error
1126 * diagnostics.
1127 * @param condtype The type of the expression's condition.
1128 * @param thentype The type of the expression's then-part.
1129 * @param elsetype The type of the expression's else-part.
1130 */
1131 private Type condType1(DiagnosticPosition pos, Type condtype,
1132 Type thentype, Type elsetype) {
1133 // If same type, that is the result
1134 if (types.isSameType(thentype, elsetype))
1135 return thentype.baseType();
1137 Type thenUnboxed = (!allowBoxing || thentype.isPrimitive())
1138 ? thentype : types.unboxedType(thentype);
1139 Type elseUnboxed = (!allowBoxing || elsetype.isPrimitive())
1140 ? elsetype : types.unboxedType(elsetype);
1142 // Otherwise, if both arms can be converted to a numeric
1143 // type, return the least numeric type that fits both arms
1144 // (i.e. return larger of the two, or return int if one
1145 // arm is short, the other is char).
1146 if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) {
1147 // If one arm has an integer subrange type (i.e., byte,
1148 // short, or char), and the other is an integer constant
1149 // that fits into the subrange, return the subrange type.
1150 if (thenUnboxed.tag < INT && elseUnboxed.tag == INT &&
1151 types.isAssignable(elseUnboxed, thenUnboxed))
1152 return thenUnboxed.baseType();
1153 if (elseUnboxed.tag < INT && thenUnboxed.tag == INT &&
1154 types.isAssignable(thenUnboxed, elseUnboxed))
1155 return elseUnboxed.baseType();
1157 for (int i = BYTE; i < VOID; i++) {
1158 Type candidate = syms.typeOfTag[i];
1159 if (types.isSubtype(thenUnboxed, candidate) &&
1160 types.isSubtype(elseUnboxed, candidate))
1161 return candidate;
1162 }
1163 }
1165 // Those were all the cases that could result in a primitive
1166 if (allowBoxing) {
1167 if (thentype.isPrimitive())
1168 thentype = types.boxedClass(thentype).type;
1169 if (elsetype.isPrimitive())
1170 elsetype = types.boxedClass(elsetype).type;
1171 }
1173 if (types.isSubtype(thentype, elsetype))
1174 return elsetype.baseType();
1175 if (types.isSubtype(elsetype, thentype))
1176 return thentype.baseType();
1178 if (!allowBoxing || thentype.tag == VOID || elsetype.tag == VOID) {
1179 log.error(pos, "neither.conditional.subtype",
1180 thentype, elsetype);
1181 return thentype.baseType();
1182 }
1184 // both are known to be reference types. The result is
1185 // lub(thentype,elsetype). This cannot fail, as it will
1186 // always be possible to infer "Object" if nothing better.
1187 return types.lub(thentype.baseType(), elsetype.baseType());
1188 }
1190 public void visitIf(JCIf tree) {
1191 attribExpr(tree.cond, env, syms.booleanType);
1192 attribStat(tree.thenpart, env);
1193 if (tree.elsepart != null)
1194 attribStat(tree.elsepart, env);
1195 chk.checkEmptyIf(tree);
1196 result = null;
1197 }
1199 public void visitExec(JCExpressionStatement tree) {
1200 //a fresh environment is required for 292 inference to work properly ---
1201 //see Infer.instantiatePolymorphicSignatureInstance()
1202 Env<AttrContext> localEnv = env.dup(tree);
1203 attribExpr(tree.expr, localEnv);
1204 result = null;
1205 }
1207 public void visitBreak(JCBreak tree) {
1208 tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
1209 result = null;
1210 }
1212 public void visitContinue(JCContinue tree) {
1213 tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
1214 result = null;
1215 }
1216 //where
1217 /** Return the target of a break or continue statement, if it exists,
1218 * report an error if not.
1219 * Note: The target of a labelled break or continue is the
1220 * (non-labelled) statement tree referred to by the label,
1221 * not the tree representing the labelled statement itself.
1222 *
1223 * @param pos The position to be used for error diagnostics
1224 * @param tag The tag of the jump statement. This is either
1225 * Tree.BREAK or Tree.CONTINUE.
1226 * @param label The label of the jump statement, or null if no
1227 * label is given.
1228 * @param env The environment current at the jump statement.
1229 */
1230 private JCTree findJumpTarget(DiagnosticPosition pos,
1231 int tag,
1232 Name label,
1233 Env<AttrContext> env) {
1234 // Search environments outwards from the point of jump.
1235 Env<AttrContext> env1 = env;
1236 LOOP:
1237 while (env1 != null) {
1238 switch (env1.tree.getTag()) {
1239 case JCTree.LABELLED:
1240 JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
1241 if (label == labelled.label) {
1242 // If jump is a continue, check that target is a loop.
1243 if (tag == JCTree.CONTINUE) {
1244 if (labelled.body.getTag() != JCTree.DOLOOP &&
1245 labelled.body.getTag() != JCTree.WHILELOOP &&
1246 labelled.body.getTag() != JCTree.FORLOOP &&
1247 labelled.body.getTag() != JCTree.FOREACHLOOP)
1248 log.error(pos, "not.loop.label", label);
1249 // Found labelled statement target, now go inwards
1250 // to next non-labelled tree.
1251 return TreeInfo.referencedStatement(labelled);
1252 } else {
1253 return labelled;
1254 }
1255 }
1256 break;
1257 case JCTree.DOLOOP:
1258 case JCTree.WHILELOOP:
1259 case JCTree.FORLOOP:
1260 case JCTree.FOREACHLOOP:
1261 if (label == null) return env1.tree;
1262 break;
1263 case JCTree.SWITCH:
1264 if (label == null && tag == JCTree.BREAK) return env1.tree;
1265 break;
1266 case JCTree.METHODDEF:
1267 case JCTree.CLASSDEF:
1268 break LOOP;
1269 default:
1270 }
1271 env1 = env1.next;
1272 }
1273 if (label != null)
1274 log.error(pos, "undef.label", label);
1275 else if (tag == JCTree.CONTINUE)
1276 log.error(pos, "cont.outside.loop");
1277 else
1278 log.error(pos, "break.outside.switch.loop");
1279 return null;
1280 }
1282 public void visitReturn(JCReturn tree) {
1283 // Check that there is an enclosing method which is
1284 // nested within than the enclosing class.
1285 if (env.enclMethod == null ||
1286 env.enclMethod.sym.owner != env.enclClass.sym) {
1287 log.error(tree.pos(), "ret.outside.meth");
1289 } else {
1290 // Attribute return expression, if it exists, and check that
1291 // it conforms to result type of enclosing method.
1292 Symbol m = env.enclMethod.sym;
1293 if (m.type.getReturnType().tag == VOID) {
1294 if (tree.expr != null)
1295 log.error(tree.expr.pos(),
1296 "cant.ret.val.from.meth.decl.void");
1297 } else if (tree.expr == null) {
1298 log.error(tree.pos(), "missing.ret.val");
1299 } else {
1300 attribExpr(tree.expr, env, m.type.getReturnType());
1301 }
1302 }
1303 result = null;
1304 }
1306 public void visitThrow(JCThrow tree) {
1307 attribExpr(tree.expr, env, syms.throwableType);
1308 result = null;
1309 }
1311 public void visitAssert(JCAssert tree) {
1312 attribExpr(tree.cond, env, syms.booleanType);
1313 if (tree.detail != null) {
1314 chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
1315 }
1316 result = null;
1317 }
1319 /** Visitor method for method invocations.
1320 * NOTE: The method part of an application will have in its type field
1321 * the return type of the method, not the method's type itself!
1322 */
1323 public void visitApply(JCMethodInvocation tree) {
1324 // The local environment of a method application is
1325 // a new environment nested in the current one.
1326 Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
1328 // The types of the actual method arguments.
1329 List<Type> argtypes;
1331 // The types of the actual method type arguments.
1332 List<Type> typeargtypes = null;
1333 boolean typeargtypesNonRefOK = false;
1335 Name methName = TreeInfo.name(tree.meth);
1337 boolean isConstructorCall =
1338 methName == names._this || methName == names._super;
1340 if (isConstructorCall) {
1341 // We are seeing a ...this(...) or ...super(...) call.
1342 // Check that this is the first statement in a constructor.
1343 if (checkFirstConstructorStat(tree, env)) {
1345 // Record the fact
1346 // that this is a constructor call (using isSelfCall).
1347 localEnv.info.isSelfCall = true;
1349 // Attribute arguments, yielding list of argument types.
1350 argtypes = attribArgs(tree.args, localEnv);
1351 typeargtypes = attribTypes(tree.typeargs, localEnv);
1353 // Variable `site' points to the class in which the called
1354 // constructor is defined.
1355 Type site = env.enclClass.sym.type;
1356 if (methName == names._super) {
1357 if (site == syms.objectType) {
1358 log.error(tree.meth.pos(), "no.superclass", site);
1359 site = types.createErrorType(syms.objectType);
1360 } else {
1361 site = types.supertype(site);
1362 }
1363 }
1365 if (site.tag == CLASS) {
1366 Type encl = site.getEnclosingType();
1367 while (encl != null && encl.tag == TYPEVAR)
1368 encl = encl.getUpperBound();
1369 if (encl.tag == CLASS) {
1370 // we are calling a nested class
1372 if (tree.meth.getTag() == JCTree.SELECT) {
1373 JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
1375 // We are seeing a prefixed call, of the form
1376 // <expr>.super(...).
1377 // Check that the prefix expression conforms
1378 // to the outer instance type of the class.
1379 chk.checkRefType(qualifier.pos(),
1380 attribExpr(qualifier, localEnv,
1381 encl));
1382 } else if (methName == names._super) {
1383 // qualifier omitted; check for existence
1384 // of an appropriate implicit qualifier.
1385 rs.resolveImplicitThis(tree.meth.pos(),
1386 localEnv, site);
1387 }
1388 } else if (tree.meth.getTag() == JCTree.SELECT) {
1389 log.error(tree.meth.pos(), "illegal.qual.not.icls",
1390 site.tsym);
1391 }
1393 // if we're calling a java.lang.Enum constructor,
1394 // prefix the implicit String and int parameters
1395 if (site.tsym == syms.enumSym && allowEnums)
1396 argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
1398 // Resolve the called constructor under the assumption
1399 // that we are referring to a superclass instance of the
1400 // current instance (JLS ???).
1401 boolean selectSuperPrev = localEnv.info.selectSuper;
1402 localEnv.info.selectSuper = true;
1403 localEnv.info.varArgs = false;
1404 Symbol sym = rs.resolveConstructor(
1405 tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
1406 localEnv.info.selectSuper = selectSuperPrev;
1408 // Set method symbol to resolved constructor...
1409 TreeInfo.setSymbol(tree.meth, sym);
1411 // ...and check that it is legal in the current context.
1412 // (this will also set the tree's type)
1413 Type mpt = newMethTemplate(argtypes, typeargtypes);
1414 checkId(tree.meth, site, sym, localEnv, MTH,
1415 mpt, tree.varargsElement != null);
1416 }
1417 // Otherwise, `site' is an error type and we do nothing
1418 }
1419 result = tree.type = syms.voidType;
1420 } else {
1421 // Otherwise, we are seeing a regular method call.
1422 // Attribute the arguments, yielding list of argument types, ...
1423 argtypes = attribArgs(tree.args, localEnv);
1424 typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
1426 // ... and attribute the method using as a prototype a methodtype
1427 // whose formal argument types is exactly the list of actual
1428 // arguments (this will also set the method symbol).
1429 Type mpt = newMethTemplate(argtypes, typeargtypes);
1430 localEnv.info.varArgs = false;
1431 Type mtype = attribExpr(tree.meth, localEnv, mpt);
1432 if (localEnv.info.varArgs)
1433 assert mtype.isErroneous() || tree.varargsElement != null;
1435 // Compute the result type.
1436 Type restype = mtype.getReturnType();
1437 if (restype.tag == WILDCARD)
1438 throw new AssertionError(mtype);
1440 // as a special case, array.clone() has a result that is
1441 // the same as static type of the array being cloned
1442 if (tree.meth.getTag() == JCTree.SELECT &&
1443 allowCovariantReturns &&
1444 methName == names.clone &&
1445 types.isArray(((JCFieldAccess) tree.meth).selected.type))
1446 restype = ((JCFieldAccess) tree.meth).selected.type;
1448 // as a special case, x.getClass() has type Class<? extends |X|>
1449 if (allowGenerics &&
1450 methName == names.getClass && tree.args.isEmpty()) {
1451 Type qualifier = (tree.meth.getTag() == JCTree.SELECT)
1452 ? ((JCFieldAccess) tree.meth).selected.type
1453 : env.enclClass.sym.type;
1454 restype = new
1455 ClassType(restype.getEnclosingType(),
1456 List.<Type>of(new WildcardType(types.erasure(qualifier),
1457 BoundKind.EXTENDS,
1458 syms.boundClass)),
1459 restype.tsym);
1460 }
1462 // Special case logic for JSR 292 types.
1463 if (rs.allowTransitionalJSR292 &&
1464 tree.meth.getTag() == JCTree.SELECT &&
1465 !typeargtypes.isEmpty()) {
1466 JCFieldAccess mfield = (JCFieldAccess) tree.meth;
1467 // MethodHandle.<T>invoke(abc) and InvokeDynamic.<T>foo(abc)
1468 // has type <T>, and T can be a primitive type.
1469 if (mfield.sym != null &&
1470 mfield.sym.isPolymorphicSignatureInstance())
1471 typeargtypesNonRefOK = true;
1472 }
1474 if (!(rs.allowTransitionalJSR292 && typeargtypesNonRefOK)) {
1475 chk.checkRefTypes(tree.typeargs, typeargtypes);
1476 }
1478 // Check that value of resulting type is admissible in the
1479 // current context. Also, capture the return type
1480 result = check(tree, capture(restype), VAL, pkind, pt);
1481 }
1482 chk.validate(tree.typeargs, localEnv);
1483 }
1484 //where
1485 /** Check that given application node appears as first statement
1486 * in a constructor call.
1487 * @param tree The application node
1488 * @param env The environment current at the application.
1489 */
1490 boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) {
1491 JCMethodDecl enclMethod = env.enclMethod;
1492 if (enclMethod != null && enclMethod.name == names.init) {
1493 JCBlock body = enclMethod.body;
1494 if (body.stats.head.getTag() == JCTree.EXEC &&
1495 ((JCExpressionStatement) body.stats.head).expr == tree)
1496 return true;
1497 }
1498 log.error(tree.pos(),"call.must.be.first.stmt.in.ctor",
1499 TreeInfo.name(tree.meth));
1500 return false;
1501 }
1503 /** Obtain a method type with given argument types.
1504 */
1505 Type newMethTemplate(List<Type> argtypes, List<Type> typeargtypes) {
1506 MethodType mt = new MethodType(argtypes, null, null, syms.methodClass);
1507 return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
1508 }
1510 public void visitNewClass(JCNewClass tree) {
1511 Type owntype = types.createErrorType(tree.type);
1513 // The local environment of a class creation is
1514 // a new environment nested in the current one.
1515 Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
1517 // The anonymous inner class definition of the new expression,
1518 // if one is defined by it.
1519 JCClassDecl cdef = tree.def;
1521 // If enclosing class is given, attribute it, and
1522 // complete class name to be fully qualified
1523 JCExpression clazz = tree.clazz; // Class field following new
1524 JCExpression clazzid = // Identifier in class field
1525 (clazz.getTag() == JCTree.TYPEAPPLY)
1526 ? ((JCTypeApply) clazz).clazz
1527 : clazz;
1529 JCExpression clazzid1 = clazzid; // The same in fully qualified form
1531 if (tree.encl != null) {
1532 // We are seeing a qualified new, of the form
1533 // <expr>.new C <...> (...) ...
1534 // In this case, we let clazz stand for the name of the
1535 // allocated class C prefixed with the type of the qualifier
1536 // expression, so that we can
1537 // resolve it with standard techniques later. I.e., if
1538 // <expr> has type T, then <expr>.new C <...> (...)
1539 // yields a clazz T.C.
1540 Type encltype = chk.checkRefType(tree.encl.pos(),
1541 attribExpr(tree.encl, env));
1542 clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
1543 ((JCIdent) clazzid).name);
1544 if (clazz.getTag() == JCTree.TYPEAPPLY)
1545 clazz = make.at(tree.pos).
1546 TypeApply(clazzid1,
1547 ((JCTypeApply) clazz).arguments);
1548 else
1549 clazz = clazzid1;
1550 }
1552 // Attribute clazz expression and store
1553 // symbol + type back into the attributed tree.
1554 Type clazztype = attribType(clazz, env);
1555 Pair<Scope,Scope> mapping = getSyntheticScopeMapping(clazztype);
1556 if (!TreeInfo.isDiamond(tree)) {
1557 clazztype = chk.checkClassType(
1558 tree.clazz.pos(), clazztype, true);
1559 }
1560 chk.validate(clazz, localEnv);
1561 if (tree.encl != null) {
1562 // We have to work in this case to store
1563 // symbol + type back into the attributed tree.
1564 tree.clazz.type = clazztype;
1565 TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
1566 clazzid.type = ((JCIdent) clazzid).sym.type;
1567 if (!clazztype.isErroneous()) {
1568 if (cdef != null && clazztype.tsym.isInterface()) {
1569 log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new");
1570 } else if (clazztype.tsym.isStatic()) {
1571 log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym);
1572 }
1573 }
1574 } else if (!clazztype.tsym.isInterface() &&
1575 clazztype.getEnclosingType().tag == CLASS) {
1576 // Check for the existence of an apropos outer instance
1577 rs.resolveImplicitThis(tree.pos(), env, clazztype);
1578 }
1580 // Attribute constructor arguments.
1581 List<Type> argtypes = attribArgs(tree.args, localEnv);
1582 List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
1584 if (TreeInfo.isDiamond(tree)) {
1585 clazztype = attribDiamond(localEnv, tree, clazztype, mapping, argtypes, typeargtypes);
1586 clazz.type = clazztype;
1587 } else if (allowDiamondFinder &&
1588 clazztype.getTypeArguments().nonEmpty() &&
1589 findDiamonds) {
1590 Type inferred = attribDiamond(localEnv,
1591 tree,
1592 clazztype,
1593 mapping,
1594 argtypes,
1595 typeargtypes);
1596 if (!inferred.isErroneous() &&
1597 inferred.tag == CLASS &&
1598 types.isAssignable(inferred, pt.tag == NONE ? clazztype : pt, Warner.noWarnings) &&
1599 chk.checkDiamond((ClassType)inferred).isEmpty()) {
1600 String key = types.isSameType(clazztype, inferred) ?
1601 "diamond.redundant.args" :
1602 "diamond.redundant.args.1";
1603 log.warning(tree.clazz.pos(), key, clazztype, inferred);
1604 }
1605 }
1607 // If we have made no mistakes in the class type...
1608 if (clazztype.tag == CLASS) {
1609 // Enums may not be instantiated except implicitly
1610 if (allowEnums &&
1611 (clazztype.tsym.flags_field&Flags.ENUM) != 0 &&
1612 (env.tree.getTag() != JCTree.VARDEF ||
1613 (((JCVariableDecl) env.tree).mods.flags&Flags.ENUM) == 0 ||
1614 ((JCVariableDecl) env.tree).init != tree))
1615 log.error(tree.pos(), "enum.cant.be.instantiated");
1616 // Check that class is not abstract
1617 if (cdef == null &&
1618 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
1619 log.error(tree.pos(), "abstract.cant.be.instantiated",
1620 clazztype.tsym);
1621 } else if (cdef != null && clazztype.tsym.isInterface()) {
1622 // Check that no constructor arguments are given to
1623 // anonymous classes implementing an interface
1624 if (!argtypes.isEmpty())
1625 log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args");
1627 if (!typeargtypes.isEmpty())
1628 log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs");
1630 // Error recovery: pretend no arguments were supplied.
1631 argtypes = List.nil();
1632 typeargtypes = List.nil();
1633 }
1635 // Resolve the called constructor under the assumption
1636 // that we are referring to a superclass instance of the
1637 // current instance (JLS ???).
1638 else {
1639 localEnv.info.selectSuper = cdef != null;
1640 localEnv.info.varArgs = false;
1641 tree.constructor = rs.resolveConstructor(
1642 tree.pos(), localEnv, clazztype, argtypes, typeargtypes);
1643 tree.constructorType = tree.constructor.type.isErroneous() ?
1644 syms.errType :
1645 checkMethod(clazztype,
1646 tree.constructor,
1647 localEnv,
1648 tree.args,
1649 argtypes,
1650 typeargtypes,
1651 localEnv.info.varArgs);
1652 if (localEnv.info.varArgs)
1653 assert tree.constructorType.isErroneous() || tree.varargsElement != null;
1654 }
1656 if (cdef != null) {
1657 // We are seeing an anonymous class instance creation.
1658 // In this case, the class instance creation
1659 // expression
1660 //
1661 // E.new <typeargs1>C<typargs2>(args) { ... }
1662 //
1663 // is represented internally as
1664 //
1665 // E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } ) .
1666 //
1667 // This expression is then *transformed* as follows:
1668 //
1669 // (1) add a STATIC flag to the class definition
1670 // if the current environment is static
1671 // (2) add an extends or implements clause
1672 // (3) add a constructor.
1673 //
1674 // For instance, if C is a class, and ET is the type of E,
1675 // the expression
1676 //
1677 // E.new <typeargs1>C<typargs2>(args) { ... }
1678 //
1679 // is translated to (where X is a fresh name and typarams is the
1680 // parameter list of the super constructor):
1681 //
1682 // new <typeargs1>X(<*nullchk*>E, args) where
1683 // X extends C<typargs2> {
1684 // <typarams> X(ET e, args) {
1685 // e.<typeargs1>super(args)
1686 // }
1687 // ...
1688 // }
1689 if (Resolve.isStatic(env)) cdef.mods.flags |= STATIC;
1691 if (clazztype.tsym.isInterface()) {
1692 cdef.implementing = List.of(clazz);
1693 } else {
1694 cdef.extending = clazz;
1695 }
1697 attribStat(cdef, localEnv);
1699 // If an outer instance is given,
1700 // prefix it to the constructor arguments
1701 // and delete it from the new expression
1702 if (tree.encl != null && !clazztype.tsym.isInterface()) {
1703 tree.args = tree.args.prepend(makeNullCheck(tree.encl));
1704 argtypes = argtypes.prepend(tree.encl.type);
1705 tree.encl = null;
1706 }
1708 // Reassign clazztype and recompute constructor.
1709 clazztype = cdef.sym.type;
1710 Symbol sym = rs.resolveConstructor(
1711 tree.pos(), localEnv, clazztype, argtypes,
1712 typeargtypes, true, tree.varargsElement != null);
1713 assert sym.kind < AMBIGUOUS || tree.constructor.type.isErroneous();
1714 tree.constructor = sym;
1715 if (tree.constructor.kind > ERRONEOUS) {
1716 tree.constructorType = syms.errType;
1717 }
1718 else {
1719 tree.constructorType = checkMethod(clazztype,
1720 tree.constructor,
1721 localEnv,
1722 tree.args,
1723 argtypes,
1724 typeargtypes,
1725 localEnv.info.varArgs);
1726 }
1727 }
1729 if (tree.constructor != null && tree.constructor.kind == MTH)
1730 owntype = clazztype;
1731 }
1732 result = check(tree, owntype, VAL, pkind, pt);
1733 chk.validate(tree.typeargs, localEnv);
1734 }
1736 Type attribDiamond(Env<AttrContext> env,
1737 JCNewClass tree,
1738 Type clazztype,
1739 Pair<Scope, Scope> mapping,
1740 List<Type> argtypes,
1741 List<Type> typeargtypes) {
1742 if (clazztype.isErroneous() || mapping == erroneousMapping) {
1743 //if the type of the instance creation expression is erroneous,
1744 //or something prevented us to form a valid mapping, return the
1745 //(possibly erroneous) type unchanged
1746 return clazztype;
1747 }
1748 else if (clazztype.isInterface()) {
1749 //if the type of the instance creation expression is an interface
1750 //skip the method resolution step (JLS 15.12.2.7). The type to be
1751 //inferred is of the kind <X1,X2, ... Xn>C<X1,X2, ... Xn>
1752 clazztype = new ForAll(clazztype.tsym.type.allparams(), clazztype.tsym.type) {
1753 @Override
1754 public List<Type> getConstraints(TypeVar tv, ConstraintKind ck) {
1755 switch (ck) {
1756 case EXTENDS: return types.getBounds(tv);
1757 default: return List.nil();
1758 }
1759 }
1760 @Override
1761 public Type inst(List<Type> inferred, Types types) throws Infer.NoInstanceException {
1762 // check that inferred bounds conform to their bounds
1763 infer.checkWithinBounds(tvars,
1764 types.subst(tvars, tvars, inferred), Warner.noWarnings);
1765 return super.inst(inferred, types);
1766 }
1767 };
1768 } else {
1769 //if the type of the instance creation expression is a class type
1770 //apply method resolution inference (JLS 15.12.2.7). The return type
1771 //of the resolved constructor will be a partially instantiated type
1772 ((ClassSymbol) clazztype.tsym).members_field = mapping.snd;
1773 Symbol constructor;
1774 try {
1775 constructor = rs.resolveDiamond(tree.pos(),
1776 env,
1777 clazztype.tsym.type,
1778 argtypes,
1779 typeargtypes);
1780 } finally {
1781 ((ClassSymbol) clazztype.tsym).members_field = mapping.fst;
1782 }
1783 if (constructor.kind == MTH) {
1784 ClassType ct = new ClassType(clazztype.getEnclosingType(),
1785 clazztype.tsym.type.getTypeArguments(),
1786 clazztype.tsym);
1787 clazztype = checkMethod(ct,
1788 constructor,
1789 env,
1790 tree.args,
1791 argtypes,
1792 typeargtypes,
1793 env.info.varArgs).getReturnType();
1794 } else {
1795 clazztype = syms.errType;
1796 }
1797 }
1798 if (clazztype.tag == FORALL && !pt.isErroneous()) {
1799 //if the resolved constructor's return type has some uninferred
1800 //type-variables, infer them using the expected type and declared
1801 //bounds (JLS 15.12.2.8).
1802 try {
1803 clazztype = infer.instantiateExpr((ForAll) clazztype,
1804 pt.tag == NONE ? syms.objectType : pt,
1805 Warner.noWarnings);
1806 } catch (Infer.InferenceException ex) {
1807 //an error occurred while inferring uninstantiated type-variables
1808 log.error(tree.clazz.pos(),
1809 "cant.apply.diamond.1",
1810 diags.fragment("diamond", clazztype.tsym),
1811 ex.diagnostic);
1812 }
1813 }
1814 clazztype = chk.checkClassType(tree.clazz.pos(),
1815 clazztype,
1816 true);
1817 if (clazztype.tag == CLASS) {
1818 List<Type> invalidDiamondArgs = chk.checkDiamond((ClassType)clazztype);
1819 if (!clazztype.isErroneous() && invalidDiamondArgs.nonEmpty()) {
1820 //one or more types inferred in the previous steps is either a
1821 //captured type or an intersection type --- we need to report an error.
1822 String subkey = invalidDiamondArgs.size() > 1 ?
1823 "diamond.invalid.args" :
1824 "diamond.invalid.arg";
1825 //The error message is of the kind:
1826 //
1827 //cannot infer type arguments for {clazztype}<>;
1828 //reason: {subkey}
1829 //
1830 //where subkey is a fragment of the kind:
1831 //
1832 //type argument(s) {invalidDiamondArgs} inferred for {clazztype}<> is not allowed in this context
1833 log.error(tree.clazz.pos(),
1834 "cant.apply.diamond.1",
1835 diags.fragment("diamond", clazztype.tsym),
1836 diags.fragment(subkey,
1837 invalidDiamondArgs,
1838 diags.fragment("diamond", clazztype.tsym)));
1839 }
1840 }
1841 return clazztype;
1842 }
1844 /** Creates a synthetic scope containing fake generic constructors.
1845 * Assuming that the original scope contains a constructor of the kind:
1846 * Foo(X x, Y y), where X,Y are class type-variables declared in Foo,
1847 * the synthetic scope is added a generic constructor of the kind:
1848 * <X,Y>Foo<X,Y>(X x, Y y). This is crucial in order to enable diamond
1849 * inference. The inferred return type of the synthetic constructor IS
1850 * the inferred type for the diamond operator.
1851 */
1852 private Pair<Scope, Scope> getSyntheticScopeMapping(Type ctype) {
1853 if (ctype.tag != CLASS) {
1854 return erroneousMapping;
1855 }
1856 Pair<Scope, Scope> mapping =
1857 new Pair<Scope, Scope>(ctype.tsym.members(), new Scope(ctype.tsym));
1858 List<Type> typevars = ctype.tsym.type.getTypeArguments();
1859 for (Scope.Entry e = mapping.fst.lookup(names.init);
1860 e.scope != null;
1861 e = e.next()) {
1862 MethodSymbol newConstr = (MethodSymbol) e.sym.clone(ctype.tsym);
1863 newConstr.name = names.init;
1864 List<Type> oldTypeargs = List.nil();
1865 if (newConstr.type.tag == FORALL) {
1866 oldTypeargs = ((ForAll) newConstr.type).tvars;
1867 }
1868 newConstr.type = new MethodType(newConstr.type.getParameterTypes(),
1869 new ClassType(ctype.getEnclosingType(), ctype.tsym.type.getTypeArguments(), ctype.tsym),
1870 newConstr.type.getThrownTypes(),
1871 syms.methodClass);
1872 newConstr.type = new ForAll(typevars.prependList(oldTypeargs), newConstr.type);
1873 mapping.snd.enter(newConstr);
1874 }
1875 return mapping;
1876 }
1878 private final Pair<Scope,Scope> erroneousMapping = new Pair<Scope,Scope>(null, null);
1880 /** Make an attributed null check tree.
1881 */
1882 public JCExpression makeNullCheck(JCExpression arg) {
1883 // optimization: X.this is never null; skip null check
1884 Name name = TreeInfo.name(arg);
1885 if (name == names._this || name == names._super) return arg;
1887 int optag = JCTree.NULLCHK;
1888 JCUnary tree = make.at(arg.pos).Unary(optag, arg);
1889 tree.operator = syms.nullcheck;
1890 tree.type = arg.type;
1891 return tree;
1892 }
1894 public void visitNewArray(JCNewArray tree) {
1895 Type owntype = types.createErrorType(tree.type);
1896 Type elemtype;
1897 if (tree.elemtype != null) {
1898 elemtype = attribType(tree.elemtype, env);
1899 chk.validate(tree.elemtype, env);
1900 owntype = elemtype;
1901 for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
1902 attribExpr(l.head, env, syms.intType);
1903 owntype = new ArrayType(owntype, syms.arrayClass);
1904 }
1905 } else {
1906 // we are seeing an untyped aggregate { ... }
1907 // this is allowed only if the prototype is an array
1908 if (pt.tag == ARRAY) {
1909 elemtype = types.elemtype(pt);
1910 } else {
1911 if (pt.tag != ERROR) {
1912 log.error(tree.pos(), "illegal.initializer.for.type",
1913 pt);
1914 }
1915 elemtype = types.createErrorType(pt);
1916 }
1917 }
1918 if (tree.elems != null) {
1919 attribExprs(tree.elems, env, elemtype);
1920 owntype = new ArrayType(elemtype, syms.arrayClass);
1921 }
1922 if (!types.isReifiable(elemtype))
1923 log.error(tree.pos(), "generic.array.creation");
1924 result = check(tree, owntype, VAL, pkind, pt);
1925 }
1927 public void visitParens(JCParens tree) {
1928 Type owntype = attribTree(tree.expr, env, pkind, pt);
1929 result = check(tree, owntype, pkind, pkind, pt);
1930 Symbol sym = TreeInfo.symbol(tree);
1931 if (sym != null && (sym.kind&(TYP|PCK)) != 0)
1932 log.error(tree.pos(), "illegal.start.of.type");
1933 }
1935 public void visitAssign(JCAssign tree) {
1936 Type owntype = attribTree(tree.lhs, env.dup(tree), VAR, Type.noType);
1937 Type capturedType = capture(owntype);
1938 attribExpr(tree.rhs, env, owntype);
1939 result = check(tree, capturedType, VAL, pkind, pt);
1940 }
1942 public void visitAssignop(JCAssignOp tree) {
1943 // Attribute arguments.
1944 Type owntype = attribTree(tree.lhs, env, VAR, Type.noType);
1945 Type operand = attribExpr(tree.rhs, env);
1946 // Find operator.
1947 Symbol operator = tree.operator = rs.resolveBinaryOperator(
1948 tree.pos(), tree.getTag() - JCTree.ASGOffset, env,
1949 owntype, operand);
1951 if (operator.kind == MTH) {
1952 chk.checkOperator(tree.pos(),
1953 (OperatorSymbol)operator,
1954 tree.getTag() - JCTree.ASGOffset,
1955 owntype,
1956 operand);
1957 chk.checkDivZero(tree.rhs.pos(), operator, operand);
1958 chk.checkCastable(tree.rhs.pos(),
1959 operator.type.getReturnType(),
1960 owntype);
1961 }
1962 result = check(tree, owntype, VAL, pkind, pt);
1963 }
1965 public void visitUnary(JCUnary tree) {
1966 // Attribute arguments.
1967 Type argtype = (JCTree.PREINC <= tree.getTag() && tree.getTag() <= JCTree.POSTDEC)
1968 ? attribTree(tree.arg, env, VAR, Type.noType)
1969 : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
1971 // Find operator.
1972 Symbol operator = tree.operator =
1973 rs.resolveUnaryOperator(tree.pos(), tree.getTag(), env, argtype);
1975 Type owntype = types.createErrorType(tree.type);
1976 if (operator.kind == MTH) {
1977 owntype = (JCTree.PREINC <= tree.getTag() && tree.getTag() <= JCTree.POSTDEC)
1978 ? tree.arg.type
1979 : operator.type.getReturnType();
1980 int opc = ((OperatorSymbol)operator).opcode;
1982 // If the argument is constant, fold it.
1983 if (argtype.constValue() != null) {
1984 Type ctype = cfolder.fold1(opc, argtype);
1985 if (ctype != null) {
1986 owntype = cfolder.coerce(ctype, owntype);
1988 // Remove constant types from arguments to
1989 // conserve space. The parser will fold concatenations
1990 // of string literals; the code here also
1991 // gets rid of intermediate results when some of the
1992 // operands are constant identifiers.
1993 if (tree.arg.type.tsym == syms.stringType.tsym) {
1994 tree.arg.type = syms.stringType;
1995 }
1996 }
1997 }
1998 }
1999 result = check(tree, owntype, VAL, pkind, pt);
2000 }
2002 public void visitBinary(JCBinary tree) {
2003 // Attribute arguments.
2004 Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
2005 Type right = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.rhs, env));
2007 // Find operator.
2008 Symbol operator = tree.operator =
2009 rs.resolveBinaryOperator(tree.pos(), tree.getTag(), env, left, right);
2011 Type owntype = types.createErrorType(tree.type);
2012 if (operator.kind == MTH) {
2013 owntype = operator.type.getReturnType();
2014 int opc = chk.checkOperator(tree.lhs.pos(),
2015 (OperatorSymbol)operator,
2016 tree.getTag(),
2017 left,
2018 right);
2020 // If both arguments are constants, fold them.
2021 if (left.constValue() != null && right.constValue() != null) {
2022 Type ctype = cfolder.fold2(opc, left, right);
2023 if (ctype != null) {
2024 owntype = cfolder.coerce(ctype, owntype);
2026 // Remove constant types from arguments to
2027 // conserve space. The parser will fold concatenations
2028 // of string literals; the code here also
2029 // gets rid of intermediate results when some of the
2030 // operands are constant identifiers.
2031 if (tree.lhs.type.tsym == syms.stringType.tsym) {
2032 tree.lhs.type = syms.stringType;
2033 }
2034 if (tree.rhs.type.tsym == syms.stringType.tsym) {
2035 tree.rhs.type = syms.stringType;
2036 }
2037 }
2038 }
2040 // Check that argument types of a reference ==, != are
2041 // castable to each other, (JLS???).
2042 if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
2043 if (!types.isCastable(left, right, new Warner(tree.pos()))) {
2044 log.error(tree.pos(), "incomparable.types", left, right);
2045 }
2046 }
2048 chk.checkDivZero(tree.rhs.pos(), operator, right);
2049 }
2050 result = check(tree, owntype, VAL, pkind, pt);
2051 }
2053 public void visitTypeCast(JCTypeCast tree) {
2054 Type clazztype = attribType(tree.clazz, env);
2055 chk.validate(tree.clazz, env, false);
2056 //a fresh environment is required for 292 inference to work properly ---
2057 //see Infer.instantiatePolymorphicSignatureInstance()
2058 Env<AttrContext> localEnv = env.dup(tree);
2059 Type exprtype = attribExpr(tree.expr, localEnv, Infer.anyPoly);
2060 Type owntype = chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
2061 if (exprtype.constValue() != null)
2062 owntype = cfolder.coerce(exprtype, owntype);
2063 result = check(tree, capture(owntype), VAL, pkind, pt);
2064 }
2066 public void visitTypeTest(JCInstanceOf tree) {
2067 Type exprtype = chk.checkNullOrRefType(
2068 tree.expr.pos(), attribExpr(tree.expr, env));
2069 Type clazztype = chk.checkReifiableReferenceType(
2070 tree.clazz.pos(), attribType(tree.clazz, env));
2071 chk.validate(tree.clazz, env, false);
2072 chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
2073 result = check(tree, syms.booleanType, VAL, pkind, pt);
2074 }
2076 public void visitIndexed(JCArrayAccess tree) {
2077 Type owntype = types.createErrorType(tree.type);
2078 Type atype = attribExpr(tree.indexed, env);
2079 attribExpr(tree.index, env, syms.intType);
2080 if (types.isArray(atype))
2081 owntype = types.elemtype(atype);
2082 else if (atype.tag != ERROR)
2083 log.error(tree.pos(), "array.req.but.found", atype);
2084 if ((pkind & VAR) == 0) owntype = capture(owntype);
2085 result = check(tree, owntype, VAR, pkind, pt);
2086 }
2088 public void visitIdent(JCIdent tree) {
2089 Symbol sym;
2090 boolean varArgs = false;
2092 // Find symbol
2093 if (pt.tag == METHOD || pt.tag == FORALL) {
2094 // If we are looking for a method, the prototype `pt' will be a
2095 // method type with the type of the call's arguments as parameters.
2096 env.info.varArgs = false;
2097 sym = rs.resolveMethod(tree.pos(), env, tree.name, pt.getParameterTypes(), pt.getTypeArguments());
2098 varArgs = env.info.varArgs;
2099 } else if (tree.sym != null && tree.sym.kind != VAR) {
2100 sym = tree.sym;
2101 } else {
2102 sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind);
2103 }
2104 tree.sym = sym;
2106 // (1) Also find the environment current for the class where
2107 // sym is defined (`symEnv').
2108 // Only for pre-tiger versions (1.4 and earlier):
2109 // (2) Also determine whether we access symbol out of an anonymous
2110 // class in a this or super call. This is illegal for instance
2111 // members since such classes don't carry a this$n link.
2112 // (`noOuterThisPath').
2113 Env<AttrContext> symEnv = env;
2114 boolean noOuterThisPath = false;
2115 if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
2116 (sym.kind & (VAR | MTH | TYP)) != 0 &&
2117 sym.owner.kind == TYP &&
2118 tree.name != names._this && tree.name != names._super) {
2120 // Find environment in which identifier is defined.
2121 while (symEnv.outer != null &&
2122 !sym.isMemberOf(symEnv.enclClass.sym, types)) {
2123 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
2124 noOuterThisPath = !allowAnonOuterThis;
2125 symEnv = symEnv.outer;
2126 }
2127 }
2129 // If symbol is a variable, ...
2130 if (sym.kind == VAR) {
2131 VarSymbol v = (VarSymbol)sym;
2133 // ..., evaluate its initializer, if it has one, and check for
2134 // illegal forward reference.
2135 checkInit(tree, env, v, false);
2137 // If symbol is a local variable accessed from an embedded
2138 // inner class check that it is final.
2139 if (v.owner.kind == MTH &&
2140 v.owner != env.info.scope.owner &&
2141 (v.flags_field & FINAL) == 0) {
2142 log.error(tree.pos(),
2143 "local.var.accessed.from.icls.needs.final",
2144 v);
2145 }
2147 // If we are expecting a variable (as opposed to a value), check
2148 // that the variable is assignable in the current environment.
2149 if (pkind == VAR)
2150 checkAssignable(tree.pos(), v, null, env);
2151 }
2153 // In a constructor body,
2154 // if symbol is a field or instance method, check that it is
2155 // not accessed before the supertype constructor is called.
2156 if ((symEnv.info.isSelfCall || noOuterThisPath) &&
2157 (sym.kind & (VAR | MTH)) != 0 &&
2158 sym.owner.kind == TYP &&
2159 (sym.flags() & STATIC) == 0) {
2160 chk.earlyRefError(tree.pos(), sym.kind == VAR ? sym : thisSym(tree.pos(), env));
2161 }
2162 Env<AttrContext> env1 = env;
2163 if (sym.kind != ERR && sym.kind != TYP && sym.owner != null && sym.owner != env1.enclClass.sym) {
2164 // If the found symbol is inaccessible, then it is
2165 // accessed through an enclosing instance. Locate this
2166 // enclosing instance:
2167 while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
2168 env1 = env1.outer;
2169 }
2170 result = checkId(tree, env1.enclClass.sym.type, sym, env, pkind, pt, varArgs);
2171 }
2173 public void visitSelect(JCFieldAccess tree) {
2174 // Determine the expected kind of the qualifier expression.
2175 int skind = 0;
2176 if (tree.name == names._this || tree.name == names._super ||
2177 tree.name == names._class)
2178 {
2179 skind = TYP;
2180 } else {
2181 if ((pkind & PCK) != 0) skind = skind | PCK;
2182 if ((pkind & TYP) != 0) skind = skind | TYP | PCK;
2183 if ((pkind & (VAL | MTH)) != 0) skind = skind | VAL | TYP;
2184 }
2186 // Attribute the qualifier expression, and determine its symbol (if any).
2187 Type site = attribTree(tree.selected, env, skind, Infer.anyPoly);
2188 if ((pkind & (PCK | TYP)) == 0)
2189 site = capture(site); // Capture field access
2191 // don't allow T.class T[].class, etc
2192 if (skind == TYP) {
2193 Type elt = site;
2194 while (elt.tag == ARRAY)
2195 elt = ((ArrayType)elt).elemtype;
2196 if (elt.tag == TYPEVAR) {
2197 log.error(tree.pos(), "type.var.cant.be.deref");
2198 result = types.createErrorType(tree.type);
2199 return;
2200 }
2201 }
2203 // If qualifier symbol is a type or `super', assert `selectSuper'
2204 // for the selection. This is relevant for determining whether
2205 // protected symbols are accessible.
2206 Symbol sitesym = TreeInfo.symbol(tree.selected);
2207 boolean selectSuperPrev = env.info.selectSuper;
2208 env.info.selectSuper =
2209 sitesym != null &&
2210 sitesym.name == names._super;
2212 // If selected expression is polymorphic, strip
2213 // type parameters and remember in env.info.tvars, so that
2214 // they can be added later (in Attr.checkId and Infer.instantiateMethod).
2215 if (tree.selected.type.tag == FORALL) {
2216 ForAll pstype = (ForAll)tree.selected.type;
2217 env.info.tvars = pstype.tvars;
2218 site = tree.selected.type = pstype.qtype;
2219 }
2221 // Determine the symbol represented by the selection.
2222 env.info.varArgs = false;
2223 Symbol sym = selectSym(tree, site, env, pt, pkind);
2224 if (sym.exists() && !isType(sym) && (pkind & (PCK | TYP)) != 0) {
2225 site = capture(site);
2226 sym = selectSym(tree, site, env, pt, pkind);
2227 }
2228 boolean varArgs = env.info.varArgs;
2229 tree.sym = sym;
2231 if (site.tag == TYPEVAR && !isType(sym) && sym.kind != ERR) {
2232 while (site.tag == TYPEVAR) site = site.getUpperBound();
2233 site = capture(site);
2234 }
2236 // If that symbol is a variable, ...
2237 if (sym.kind == VAR) {
2238 VarSymbol v = (VarSymbol)sym;
2240 // ..., evaluate its initializer, if it has one, and check for
2241 // illegal forward reference.
2242 checkInit(tree, env, v, true);
2244 // If we are expecting a variable (as opposed to a value), check
2245 // that the variable is assignable in the current environment.
2246 if (pkind == VAR)
2247 checkAssignable(tree.pos(), v, tree.selected, env);
2248 }
2250 if (sitesym != null &&
2251 sitesym.kind == VAR &&
2252 ((VarSymbol)sitesym).isResourceVariable() &&
2253 sym.kind == MTH &&
2254 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) &&
2255 env.info.lint.isEnabled(Lint.LintCategory.ARM)) {
2256 log.warning(tree, "twr.explicit.close.call");
2257 }
2259 // Disallow selecting a type from an expression
2260 if (isType(sym) && (sitesym==null || (sitesym.kind&(TYP|PCK)) == 0)) {
2261 tree.type = check(tree.selected, pt,
2262 sitesym == null ? VAL : sitesym.kind, TYP|PCK, pt);
2263 }
2265 if (isType(sitesym)) {
2266 if (sym.name == names._this) {
2267 // If `C' is the currently compiled class, check that
2268 // C.this' does not appear in a call to a super(...)
2269 if (env.info.isSelfCall &&
2270 site.tsym == env.enclClass.sym) {
2271 chk.earlyRefError(tree.pos(), sym);
2272 }
2273 } else {
2274 // Check if type-qualified fields or methods are static (JLS)
2275 if ((sym.flags() & STATIC) == 0 &&
2276 sym.name != names._super &&
2277 (sym.kind == VAR || sym.kind == MTH)) {
2278 rs.access(rs.new StaticError(sym),
2279 tree.pos(), site, sym.name, true);
2280 }
2281 }
2282 } else if (sym.kind != ERR && (sym.flags() & STATIC) != 0 && sym.name != names._class) {
2283 // If the qualified item is not a type and the selected item is static, report
2284 // a warning. Make allowance for the class of an array type e.g. Object[].class)
2285 chk.warnStatic(tree, "static.not.qualified.by.type", Kinds.kindName(sym.kind), sym.owner);
2286 }
2288 // If we are selecting an instance member via a `super', ...
2289 if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
2291 // Check that super-qualified symbols are not abstract (JLS)
2292 rs.checkNonAbstract(tree.pos(), sym);
2294 if (site.isRaw()) {
2295 // Determine argument types for site.
2296 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
2297 if (site1 != null) site = site1;
2298 }
2299 }
2301 env.info.selectSuper = selectSuperPrev;
2302 result = checkId(tree, site, sym, env, pkind, pt, varArgs);
2303 env.info.tvars = List.nil();
2304 }
2305 //where
2306 /** Determine symbol referenced by a Select expression,
2307 *
2308 * @param tree The select tree.
2309 * @param site The type of the selected expression,
2310 * @param env The current environment.
2311 * @param pt The current prototype.
2312 * @param pkind The expected kind(s) of the Select expression.
2313 */
2314 private Symbol selectSym(JCFieldAccess tree,
2315 Type site,
2316 Env<AttrContext> env,
2317 Type pt,
2318 int pkind) {
2319 DiagnosticPosition pos = tree.pos();
2320 Name name = tree.name;
2322 switch (site.tag) {
2323 case PACKAGE:
2324 return rs.access(
2325 rs.findIdentInPackage(env, site.tsym, name, pkind),
2326 pos, site, name, true);
2327 case ARRAY:
2328 case CLASS:
2329 if (pt.tag == METHOD || pt.tag == FORALL) {
2330 return rs.resolveQualifiedMethod(
2331 pos, env, site, name, pt.getParameterTypes(), pt.getTypeArguments());
2332 } else if (name == names._this || name == names._super) {
2333 return rs.resolveSelf(pos, env, site.tsym, name);
2334 } else if (name == names._class) {
2335 // In this case, we have already made sure in
2336 // visitSelect that qualifier expression is a type.
2337 Type t = syms.classType;
2338 List<Type> typeargs = allowGenerics
2339 ? List.of(types.erasure(site))
2340 : List.<Type>nil();
2341 t = new ClassType(t.getEnclosingType(), typeargs, t.tsym);
2342 return new VarSymbol(
2343 STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
2344 } else {
2345 // We are seeing a plain identifier as selector.
2346 Symbol sym = rs.findIdentInType(env, site, name, pkind);
2347 if ((pkind & ERRONEOUS) == 0)
2348 sym = rs.access(sym, pos, site, name, true);
2349 return sym;
2350 }
2351 case WILDCARD:
2352 throw new AssertionError(tree);
2353 case TYPEVAR:
2354 // Normally, site.getUpperBound() shouldn't be null.
2355 // It should only happen during memberEnter/attribBase
2356 // when determining the super type which *must* be
2357 // done before attributing the type variables. In
2358 // other words, we are seeing this illegal program:
2359 // class B<T> extends A<T.foo> {}
2360 Symbol sym = (site.getUpperBound() != null)
2361 ? selectSym(tree, capture(site.getUpperBound()), env, pt, pkind)
2362 : null;
2363 if (sym == null) {
2364 log.error(pos, "type.var.cant.be.deref");
2365 return syms.errSymbol;
2366 } else {
2367 Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
2368 rs.new AccessError(env, site, sym) :
2369 sym;
2370 rs.access(sym2, pos, site, name, true);
2371 return sym;
2372 }
2373 case ERROR:
2374 // preserve identifier names through errors
2375 return types.createErrorType(name, site.tsym, site).tsym;
2376 default:
2377 // The qualifier expression is of a primitive type -- only
2378 // .class is allowed for these.
2379 if (name == names._class) {
2380 // In this case, we have already made sure in Select that
2381 // qualifier expression is a type.
2382 Type t = syms.classType;
2383 Type arg = types.boxedClass(site).type;
2384 t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym);
2385 return new VarSymbol(
2386 STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
2387 } else {
2388 log.error(pos, "cant.deref", site);
2389 return syms.errSymbol;
2390 }
2391 }
2392 }
2394 /** Determine type of identifier or select expression and check that
2395 * (1) the referenced symbol is not deprecated
2396 * (2) the symbol's type is safe (@see checkSafe)
2397 * (3) if symbol is a variable, check that its type and kind are
2398 * compatible with the prototype and protokind.
2399 * (4) if symbol is an instance field of a raw type,
2400 * which is being assigned to, issue an unchecked warning if its
2401 * type changes under erasure.
2402 * (5) if symbol is an instance method of a raw type, issue an
2403 * unchecked warning if its argument types change under erasure.
2404 * If checks succeed:
2405 * If symbol is a constant, return its constant type
2406 * else if symbol is a method, return its result type
2407 * otherwise return its type.
2408 * Otherwise return errType.
2409 *
2410 * @param tree The syntax tree representing the identifier
2411 * @param site If this is a select, the type of the selected
2412 * expression, otherwise the type of the current class.
2413 * @param sym The symbol representing the identifier.
2414 * @param env The current environment.
2415 * @param pkind The set of expected kinds.
2416 * @param pt The expected type.
2417 */
2418 Type checkId(JCTree tree,
2419 Type site,
2420 Symbol sym,
2421 Env<AttrContext> env,
2422 int pkind,
2423 Type pt,
2424 boolean useVarargs) {
2425 if (pt.isErroneous()) return types.createErrorType(site);
2426 Type owntype; // The computed type of this identifier occurrence.
2427 switch (sym.kind) {
2428 case TYP:
2429 // For types, the computed type equals the symbol's type,
2430 // except for two situations:
2431 owntype = sym.type;
2432 if (owntype.tag == CLASS) {
2433 Type ownOuter = owntype.getEnclosingType();
2435 // (a) If the symbol's type is parameterized, erase it
2436 // because no type parameters were given.
2437 // We recover generic outer type later in visitTypeApply.
2438 if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
2439 owntype = types.erasure(owntype);
2440 }
2442 // (b) If the symbol's type is an inner class, then
2443 // we have to interpret its outer type as a superclass
2444 // of the site type. Example:
2445 //
2446 // class Tree<A> { class Visitor { ... } }
2447 // class PointTree extends Tree<Point> { ... }
2448 // ...PointTree.Visitor...
2449 //
2450 // Then the type of the last expression above is
2451 // Tree<Point>.Visitor.
2452 else if (ownOuter.tag == CLASS && site != ownOuter) {
2453 Type normOuter = site;
2454 if (normOuter.tag == CLASS)
2455 normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
2456 if (normOuter == null) // perhaps from an import
2457 normOuter = types.erasure(ownOuter);
2458 if (normOuter != ownOuter)
2459 owntype = new ClassType(
2460 normOuter, List.<Type>nil(), owntype.tsym);
2461 }
2462 }
2463 break;
2464 case VAR:
2465 VarSymbol v = (VarSymbol)sym;
2466 // Test (4): if symbol is an instance field of a raw type,
2467 // which is being assigned to, issue an unchecked warning if
2468 // its type changes under erasure.
2469 if (allowGenerics &&
2470 pkind == VAR &&
2471 v.owner.kind == TYP &&
2472 (v.flags() & STATIC) == 0 &&
2473 (site.tag == CLASS || site.tag == TYPEVAR)) {
2474 Type s = types.asOuterSuper(site, v.owner);
2475 if (s != null &&
2476 s.isRaw() &&
2477 !types.isSameType(v.type, v.erasure(types))) {
2478 chk.warnUnchecked(tree.pos(),
2479 "unchecked.assign.to.var",
2480 v, s);
2481 }
2482 }
2483 // The computed type of a variable is the type of the
2484 // variable symbol, taken as a member of the site type.
2485 owntype = (sym.owner.kind == TYP &&
2486 sym.name != names._this && sym.name != names._super)
2487 ? types.memberType(site, sym)
2488 : sym.type;
2490 if (env.info.tvars.nonEmpty()) {
2491 Type owntype1 = new ForAll(env.info.tvars, owntype);
2492 for (List<Type> l = env.info.tvars; l.nonEmpty(); l = l.tail)
2493 if (!owntype.contains(l.head)) {
2494 log.error(tree.pos(), "undetermined.type", owntype1);
2495 owntype1 = types.createErrorType(owntype1);
2496 }
2497 owntype = owntype1;
2498 }
2500 // If the variable is a constant, record constant value in
2501 // computed type.
2502 if (v.getConstValue() != null && isStaticReference(tree))
2503 owntype = owntype.constType(v.getConstValue());
2505 if (pkind == VAL) {
2506 owntype = capture(owntype); // capture "names as expressions"
2507 }
2508 break;
2509 case MTH: {
2510 JCMethodInvocation app = (JCMethodInvocation)env.tree;
2511 owntype = checkMethod(site, sym, env, app.args,
2512 pt.getParameterTypes(), pt.getTypeArguments(),
2513 env.info.varArgs);
2514 break;
2515 }
2516 case PCK: case ERR:
2517 owntype = sym.type;
2518 break;
2519 default:
2520 throw new AssertionError("unexpected kind: " + sym.kind +
2521 " in tree " + tree);
2522 }
2524 // Test (1): emit a `deprecation' warning if symbol is deprecated.
2525 // (for constructors, the error was given when the constructor was
2526 // resolved)
2527 if (sym.name != names.init &&
2528 (sym.flags() & DEPRECATED) != 0 &&
2529 (env.info.scope.owner.flags() & DEPRECATED) == 0 &&
2530 sym.outermostClass() != env.info.scope.owner.outermostClass())
2531 chk.warnDeprecated(tree.pos(), sym);
2533 if ((sym.flags() & PROPRIETARY) != 0) {
2534 if (enableSunApiLintControl)
2535 chk.warnSunApi(tree.pos(), "sun.proprietary", sym);
2536 else
2537 log.strictWarning(tree.pos(), "sun.proprietary", sym);
2538 }
2540 // Test (3): if symbol is a variable, check that its type and
2541 // kind are compatible with the prototype and protokind.
2542 return check(tree, owntype, sym.kind, pkind, pt);
2543 }
2545 /** Check that variable is initialized and evaluate the variable's
2546 * initializer, if not yet done. Also check that variable is not
2547 * referenced before it is defined.
2548 * @param tree The tree making up the variable reference.
2549 * @param env The current environment.
2550 * @param v The variable's symbol.
2551 */
2552 private void checkInit(JCTree tree,
2553 Env<AttrContext> env,
2554 VarSymbol v,
2555 boolean onlyWarning) {
2556 // System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " +
2557 // tree.pos + " " + v.pos + " " +
2558 // Resolve.isStatic(env));//DEBUG
2560 // A forward reference is diagnosed if the declaration position
2561 // of the variable is greater than the current tree position
2562 // and the tree and variable definition occur in the same class
2563 // definition. Note that writes don't count as references.
2564 // This check applies only to class and instance
2565 // variables. Local variables follow different scope rules,
2566 // and are subject to definite assignment checking.
2567 if ((env.info.enclVar == v || v.pos > tree.pos) &&
2568 v.owner.kind == TYP &&
2569 canOwnInitializer(env.info.scope.owner) &&
2570 v.owner == env.info.scope.owner.enclClass() &&
2571 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
2572 (env.tree.getTag() != JCTree.ASSIGN ||
2573 TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
2574 String suffix = (env.info.enclVar == v) ?
2575 "self.ref" : "forward.ref";
2576 if (!onlyWarning || isStaticEnumField(v)) {
2577 log.error(tree.pos(), "illegal." + suffix);
2578 } else if (useBeforeDeclarationWarning) {
2579 log.warning(tree.pos(), suffix, v);
2580 }
2581 }
2583 v.getConstValue(); // ensure initializer is evaluated
2585 checkEnumInitializer(tree, env, v);
2586 }
2588 /**
2589 * Check for illegal references to static members of enum. In
2590 * an enum type, constructors and initializers may not
2591 * reference its static members unless they are constant.
2592 *
2593 * @param tree The tree making up the variable reference.
2594 * @param env The current environment.
2595 * @param v The variable's symbol.
2596 * @see JLS 3rd Ed. (8.9 Enums)
2597 */
2598 private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
2599 // JLS 3rd Ed.:
2600 //
2601 // "It is a compile-time error to reference a static field
2602 // of an enum type that is not a compile-time constant
2603 // (15.28) from constructors, instance initializer blocks,
2604 // or instance variable initializer expressions of that
2605 // type. It is a compile-time error for the constructors,
2606 // instance initializer blocks, or instance variable
2607 // initializer expressions of an enum constant e to refer
2608 // to itself or to an enum constant of the same type that
2609 // is declared to the right of e."
2610 if (isStaticEnumField(v)) {
2611 ClassSymbol enclClass = env.info.scope.owner.enclClass();
2613 if (enclClass == null || enclClass.owner == null)
2614 return;
2616 // See if the enclosing class is the enum (or a
2617 // subclass thereof) declaring v. If not, this
2618 // reference is OK.
2619 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
2620 return;
2622 // If the reference isn't from an initializer, then
2623 // the reference is OK.
2624 if (!Resolve.isInitializer(env))
2625 return;
2627 log.error(tree.pos(), "illegal.enum.static.ref");
2628 }
2629 }
2631 /** Is the given symbol a static, non-constant field of an Enum?
2632 * Note: enum literals should not be regarded as such
2633 */
2634 private boolean isStaticEnumField(VarSymbol v) {
2635 return Flags.isEnum(v.owner) &&
2636 Flags.isStatic(v) &&
2637 !Flags.isConstant(v) &&
2638 v.name != names._class;
2639 }
2641 /** Can the given symbol be the owner of code which forms part
2642 * if class initialization? This is the case if the symbol is
2643 * a type or field, or if the symbol is the synthetic method.
2644 * owning a block.
2645 */
2646 private boolean canOwnInitializer(Symbol sym) {
2647 return
2648 (sym.kind & (VAR | TYP)) != 0 ||
2649 (sym.kind == MTH && (sym.flags() & BLOCK) != 0);
2650 }
2652 Warner noteWarner = new Warner();
2654 /**
2655 * Check that method arguments conform to its instantation.
2656 **/
2657 public Type checkMethod(Type site,
2658 Symbol sym,
2659 Env<AttrContext> env,
2660 final List<JCExpression> argtrees,
2661 List<Type> argtypes,
2662 List<Type> typeargtypes,
2663 boolean useVarargs) {
2664 // Test (5): if symbol is an instance method of a raw type, issue
2665 // an unchecked warning if its argument types change under erasure.
2666 if (allowGenerics &&
2667 (sym.flags() & STATIC) == 0 &&
2668 (site.tag == CLASS || site.tag == TYPEVAR)) {
2669 Type s = types.asOuterSuper(site, sym.owner);
2670 if (s != null && s.isRaw() &&
2671 !types.isSameTypes(sym.type.getParameterTypes(),
2672 sym.erasure(types).getParameterTypes())) {
2673 chk.warnUnchecked(env.tree.pos(),
2674 "unchecked.call.mbr.of.raw.type",
2675 sym, s);
2676 }
2677 }
2679 // Compute the identifier's instantiated type.
2680 // For methods, we need to compute the instance type by
2681 // Resolve.instantiate from the symbol's type as well as
2682 // any type arguments and value arguments.
2683 noteWarner.warned = false;
2684 Type owntype = rs.instantiate(env,
2685 site,
2686 sym,
2687 argtypes,
2688 typeargtypes,
2689 true,
2690 useVarargs,
2691 noteWarner);
2692 boolean warned = noteWarner.warned;
2694 // If this fails, something went wrong; we should not have
2695 // found the identifier in the first place.
2696 if (owntype == null) {
2697 if (!pt.isErroneous())
2698 log.error(env.tree.pos(),
2699 "internal.error.cant.instantiate",
2700 sym, site,
2701 Type.toString(pt.getParameterTypes()));
2702 owntype = types.createErrorType(site);
2703 } else {
2704 // System.out.println("call : " + env.tree);
2705 // System.out.println("method : " + owntype);
2706 // System.out.println("actuals: " + argtypes);
2707 List<Type> formals = owntype.getParameterTypes();
2708 Type last = useVarargs ? formals.last() : null;
2709 if (sym.name==names.init &&
2710 sym.owner == syms.enumSym)
2711 formals = formals.tail.tail;
2712 List<JCExpression> args = argtrees;
2713 while (formals.head != last) {
2714 JCTree arg = args.head;
2715 Warner warn = chk.convertWarner(arg.pos(), arg.type, formals.head);
2716 assertConvertible(arg, arg.type, formals.head, warn);
2717 warned |= warn.warned;
2718 args = args.tail;
2719 formals = formals.tail;
2720 }
2721 if (useVarargs) {
2722 Type varArg = types.elemtype(last);
2723 while (args.tail != null) {
2724 JCTree arg = args.head;
2725 Warner warn = chk.convertWarner(arg.pos(), arg.type, varArg);
2726 assertConvertible(arg, arg.type, varArg, warn);
2727 warned |= warn.warned;
2728 args = args.tail;
2729 }
2730 } else if ((sym.flags() & VARARGS) != 0 && allowVarargs) {
2731 // non-varargs call to varargs method
2732 Type varParam = owntype.getParameterTypes().last();
2733 Type lastArg = argtypes.last();
2734 if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) &&
2735 !types.isSameType(types.erasure(varParam), types.erasure(lastArg)))
2736 log.warning(argtrees.last().pos(), "inexact.non-varargs.call",
2737 types.elemtype(varParam),
2738 varParam);
2739 }
2741 if (warned && sym.type.tag == FORALL) {
2742 chk.warnUnchecked(env.tree.pos(),
2743 "unchecked.meth.invocation.applied",
2744 kindName(sym),
2745 sym.name,
2746 rs.methodArguments(sym.type.getParameterTypes()),
2747 rs.methodArguments(argtypes),
2748 kindName(sym.location()),
2749 sym.location());
2750 owntype = new MethodType(owntype.getParameterTypes(),
2751 types.erasure(owntype.getReturnType()),
2752 owntype.getThrownTypes(),
2753 syms.methodClass);
2754 }
2755 if (useVarargs) {
2756 JCTree tree = env.tree;
2757 Type argtype = owntype.getParameterTypes().last();
2758 if (owntype.getReturnType().tag != FORALL || warned) {
2759 chk.checkVararg(env.tree.pos(), owntype.getParameterTypes(), sym, env);
2760 }
2761 Type elemtype = types.elemtype(argtype);
2762 switch (tree.getTag()) {
2763 case JCTree.APPLY:
2764 ((JCMethodInvocation) tree).varargsElement = elemtype;
2765 break;
2766 case JCTree.NEWCLASS:
2767 ((JCNewClass) tree).varargsElement = elemtype;
2768 break;
2769 default:
2770 throw new AssertionError(""+tree);
2771 }
2772 }
2773 }
2774 return owntype;
2775 }
2777 private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) {
2778 if (types.isConvertible(actual, formal, warn))
2779 return;
2781 if (formal.isCompound()
2782 && types.isSubtype(actual, types.supertype(formal))
2783 && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn))
2784 return;
2786 if (false) {
2787 // TODO: make assertConvertible work
2788 chk.typeError(tree.pos(), diags.fragment("incompatible.types"), actual, formal);
2789 throw new AssertionError("Tree: " + tree
2790 + " actual:" + actual
2791 + " formal: " + formal);
2792 }
2793 }
2795 public void visitLiteral(JCLiteral tree) {
2796 result = check(
2797 tree, litType(tree.typetag).constType(tree.value), VAL, pkind, pt);
2798 }
2799 //where
2800 /** Return the type of a literal with given type tag.
2801 */
2802 Type litType(int tag) {
2803 return (tag == TypeTags.CLASS) ? syms.stringType : syms.typeOfTag[tag];
2804 }
2806 public void visitTypeIdent(JCPrimitiveTypeTree tree) {
2807 result = check(tree, syms.typeOfTag[tree.typetag], TYP, pkind, pt);
2808 }
2810 public void visitTypeArray(JCArrayTypeTree tree) {
2811 Type etype = attribType(tree.elemtype, env);
2812 Type type = new ArrayType(etype, syms.arrayClass);
2813 result = check(tree, type, TYP, pkind, pt);
2814 }
2816 /** Visitor method for parameterized types.
2817 * Bound checking is left until later, since types are attributed
2818 * before supertype structure is completely known
2819 */
2820 public void visitTypeApply(JCTypeApply tree) {
2821 Type owntype = types.createErrorType(tree.type);
2823 // Attribute functor part of application and make sure it's a class.
2824 Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
2826 // Attribute type parameters
2827 List<Type> actuals = attribTypes(tree.arguments, env);
2829 if (clazztype.tag == CLASS) {
2830 List<Type> formals = clazztype.tsym.type.getTypeArguments();
2832 if (actuals.length() == formals.length() || actuals.length() == 0) {
2833 List<Type> a = actuals;
2834 List<Type> f = formals;
2835 while (a.nonEmpty()) {
2836 a.head = a.head.withTypeVar(f.head);
2837 a = a.tail;
2838 f = f.tail;
2839 }
2840 // Compute the proper generic outer
2841 Type clazzOuter = clazztype.getEnclosingType();
2842 if (clazzOuter.tag == CLASS) {
2843 Type site;
2844 JCExpression clazz = TreeInfo.typeIn(tree.clazz);
2845 if (clazz.getTag() == JCTree.IDENT) {
2846 site = env.enclClass.sym.type;
2847 } else if (clazz.getTag() == JCTree.SELECT) {
2848 site = ((JCFieldAccess) clazz).selected.type;
2849 } else throw new AssertionError(""+tree);
2850 if (clazzOuter.tag == CLASS && site != clazzOuter) {
2851 if (site.tag == CLASS)
2852 site = types.asOuterSuper(site, clazzOuter.tsym);
2853 if (site == null)
2854 site = types.erasure(clazzOuter);
2855 clazzOuter = site;
2856 }
2857 }
2858 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym);
2859 } else {
2860 if (formals.length() != 0) {
2861 log.error(tree.pos(), "wrong.number.type.args",
2862 Integer.toString(formals.length()));
2863 } else {
2864 log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym);
2865 }
2866 owntype = types.createErrorType(tree.type);
2867 }
2868 }
2869 result = check(tree, owntype, TYP, pkind, pt);
2870 }
2872 public void visitTypeDisjunction(JCTypeDisjunction tree) {
2873 List<Type> alternatives = attribTypes(tree.alternatives, env);
2874 tree.type = result = check(tree, types.lub(alternatives), TYP, pkind, pt);
2875 }
2877 public void visitTypeParameter(JCTypeParameter tree) {
2878 TypeVar a = (TypeVar)tree.type;
2879 Set<Type> boundSet = new HashSet<Type>();
2880 if (a.bound.isErroneous())
2881 return;
2882 List<Type> bs = types.getBounds(a);
2883 if (tree.bounds.nonEmpty()) {
2884 // accept class or interface or typevar as first bound.
2885 Type b = checkBase(bs.head, tree.bounds.head, env, false, false, false);
2886 boundSet.add(types.erasure(b));
2887 if (b.isErroneous()) {
2888 a.bound = b;
2889 }
2890 else if (b.tag == TYPEVAR) {
2891 // if first bound was a typevar, do not accept further bounds.
2892 if (tree.bounds.tail.nonEmpty()) {
2893 log.error(tree.bounds.tail.head.pos(),
2894 "type.var.may.not.be.followed.by.other.bounds");
2895 tree.bounds = List.of(tree.bounds.head);
2896 a.bound = bs.head;
2897 }
2898 } else {
2899 // if first bound was a class or interface, accept only interfaces
2900 // as further bounds.
2901 for (JCExpression bound : tree.bounds.tail) {
2902 bs = bs.tail;
2903 Type i = checkBase(bs.head, bound, env, false, true, false);
2904 if (i.isErroneous())
2905 a.bound = i;
2906 else if (i.tag == CLASS)
2907 chk.checkNotRepeated(bound.pos(), types.erasure(i), boundSet);
2908 }
2909 }
2910 }
2911 bs = types.getBounds(a);
2913 // in case of multiple bounds ...
2914 if (bs.length() > 1) {
2915 // ... the variable's bound is a class type flagged COMPOUND
2916 // (see comment for TypeVar.bound).
2917 // In this case, generate a class tree that represents the
2918 // bound class, ...
2919 JCTree extending;
2920 List<JCExpression> implementing;
2921 if ((bs.head.tsym.flags() & INTERFACE) == 0) {
2922 extending = tree.bounds.head;
2923 implementing = tree.bounds.tail;
2924 } else {
2925 extending = null;
2926 implementing = tree.bounds;
2927 }
2928 JCClassDecl cd = make.at(tree.pos).ClassDef(
2929 make.Modifiers(PUBLIC | ABSTRACT),
2930 tree.name, List.<JCTypeParameter>nil(),
2931 extending, implementing, List.<JCTree>nil());
2933 ClassSymbol c = (ClassSymbol)a.getUpperBound().tsym;
2934 assert (c.flags() & COMPOUND) != 0;
2935 cd.sym = c;
2936 c.sourcefile = env.toplevel.sourcefile;
2938 // ... and attribute the bound class
2939 c.flags_field |= UNATTRIBUTED;
2940 Env<AttrContext> cenv = enter.classEnv(cd, env);
2941 enter.typeEnvs.put(c, cenv);
2942 }
2943 }
2946 public void visitWildcard(JCWildcard tree) {
2947 //- System.err.println("visitWildcard("+tree+");");//DEBUG
2948 Type type = (tree.kind.kind == BoundKind.UNBOUND)
2949 ? syms.objectType
2950 : attribType(tree.inner, env);
2951 result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
2952 tree.kind.kind,
2953 syms.boundClass),
2954 TYP, pkind, pt);
2955 }
2957 public void visitAnnotation(JCAnnotation tree) {
2958 log.error(tree.pos(), "annotation.not.valid.for.type", pt);
2959 result = tree.type = syms.errType;
2960 }
2962 public void visitAnnotatedType(JCAnnotatedType tree) {
2963 result = tree.type = attribType(tree.getUnderlyingType(), env);
2964 }
2966 public void visitErroneous(JCErroneous tree) {
2967 if (tree.errs != null)
2968 for (JCTree err : tree.errs)
2969 attribTree(err, env, ERR, pt);
2970 result = tree.type = syms.errType;
2971 }
2973 /** Default visitor method for all other trees.
2974 */
2975 public void visitTree(JCTree tree) {
2976 throw new AssertionError();
2977 }
2979 /** Main method: attribute class definition associated with given class symbol.
2980 * reporting completion failures at the given position.
2981 * @param pos The source position at which completion errors are to be
2982 * reported.
2983 * @param c The class symbol whose definition will be attributed.
2984 */
2985 public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
2986 try {
2987 annotate.flush();
2988 attribClass(c);
2989 } catch (CompletionFailure ex) {
2990 chk.completionError(pos, ex);
2991 }
2992 }
2994 /** Attribute class definition associated with given class symbol.
2995 * @param c The class symbol whose definition will be attributed.
2996 */
2997 void attribClass(ClassSymbol c) throws CompletionFailure {
2998 if (c.type.tag == ERROR) return;
3000 // Check for cycles in the inheritance graph, which can arise from
3001 // ill-formed class files.
3002 chk.checkNonCyclic(null, c.type);
3004 Type st = types.supertype(c.type);
3005 if ((c.flags_field & Flags.COMPOUND) == 0) {
3006 // First, attribute superclass.
3007 if (st.tag == CLASS)
3008 attribClass((ClassSymbol)st.tsym);
3010 // Next attribute owner, if it is a class.
3011 if (c.owner.kind == TYP && c.owner.type.tag == CLASS)
3012 attribClass((ClassSymbol)c.owner);
3013 }
3015 // The previous operations might have attributed the current class
3016 // if there was a cycle. So we test first whether the class is still
3017 // UNATTRIBUTED.
3018 if ((c.flags_field & UNATTRIBUTED) != 0) {
3019 c.flags_field &= ~UNATTRIBUTED;
3021 // Get environment current at the point of class definition.
3022 Env<AttrContext> env = enter.typeEnvs.get(c);
3024 // The info.lint field in the envs stored in enter.typeEnvs is deliberately uninitialized,
3025 // because the annotations were not available at the time the env was created. Therefore,
3026 // we look up the environment chain for the first enclosing environment for which the
3027 // lint value is set. Typically, this is the parent env, but might be further if there
3028 // are any envs created as a result of TypeParameter nodes.
3029 Env<AttrContext> lintEnv = env;
3030 while (lintEnv.info.lint == null)
3031 lintEnv = lintEnv.next;
3033 // Having found the enclosing lint value, we can initialize the lint value for this class
3034 env.info.lint = lintEnv.info.lint.augment(c.attributes_field, c.flags());
3036 Lint prevLint = chk.setLint(env.info.lint);
3037 JavaFileObject prev = log.useSource(c.sourcefile);
3039 try {
3040 // java.lang.Enum may not be subclassed by a non-enum
3041 if (st.tsym == syms.enumSym &&
3042 ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
3043 log.error(env.tree.pos(), "enum.no.subclassing");
3045 // Enums may not be extended by source-level classes
3046 if (st.tsym != null &&
3047 ((st.tsym.flags_field & Flags.ENUM) != 0) &&
3048 ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0) &&
3049 !target.compilerBootstrap(c)) {
3050 log.error(env.tree.pos(), "enum.types.not.extensible");
3051 }
3052 attribClassBody(env, c);
3054 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
3055 } finally {
3056 log.useSource(prev);
3057 chk.setLint(prevLint);
3058 }
3060 }
3061 }
3063 public void visitImport(JCImport tree) {
3064 // nothing to do
3065 }
3067 /** Finish the attribution of a class. */
3068 private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
3069 JCClassDecl tree = (JCClassDecl)env.tree;
3070 assert c == tree.sym;
3072 // Validate annotations
3073 chk.validateAnnotations(tree.mods.annotations, c);
3075 // Validate type parameters, supertype and interfaces.
3076 attribBounds(tree.typarams);
3077 if (!c.isAnonymous()) {
3078 //already checked if anonymous
3079 chk.validate(tree.typarams, env);
3080 chk.validate(tree.extending, env);
3081 chk.validate(tree.implementing, env);
3082 }
3084 // If this is a non-abstract class, check that it has no abstract
3085 // methods or unimplemented methods of an implemented interface.
3086 if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
3087 if (!relax)
3088 chk.checkAllDefined(tree.pos(), c);
3089 }
3091 if ((c.flags() & ANNOTATION) != 0) {
3092 if (tree.implementing.nonEmpty())
3093 log.error(tree.implementing.head.pos(),
3094 "cant.extend.intf.annotation");
3095 if (tree.typarams.nonEmpty())
3096 log.error(tree.typarams.head.pos(),
3097 "intf.annotation.cant.have.type.params");
3098 } else {
3099 // Check that all extended classes and interfaces
3100 // are compatible (i.e. no two define methods with same arguments
3101 // yet different return types). (JLS 8.4.6.3)
3102 chk.checkCompatibleSupertypes(tree.pos(), c.type);
3103 }
3105 // Check that class does not import the same parameterized interface
3106 // with two different argument lists.
3107 chk.checkClassBounds(tree.pos(), c.type);
3109 tree.type = c.type;
3111 boolean assertsEnabled = false;
3112 assert assertsEnabled = true;
3113 if (assertsEnabled) {
3114 for (List<JCTypeParameter> l = tree.typarams;
3115 l.nonEmpty(); l = l.tail)
3116 assert env.info.scope.lookup(l.head.name).scope != null;
3117 }
3119 // Check that a generic class doesn't extend Throwable
3120 if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
3121 log.error(tree.extending.pos(), "generic.throwable");
3123 // Check that all methods which implement some
3124 // method conform to the method they implement.
3125 chk.checkImplementations(tree);
3127 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
3128 // Attribute declaration
3129 attribStat(l.head, env);
3130 // Check that declarations in inner classes are not static (JLS 8.1.2)
3131 // Make an exception for static constants.
3132 if (c.owner.kind != PCK &&
3133 ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
3134 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
3135 Symbol sym = null;
3136 if (l.head.getTag() == JCTree.VARDEF) sym = ((JCVariableDecl) l.head).sym;
3137 if (sym == null ||
3138 sym.kind != VAR ||
3139 ((VarSymbol) sym).getConstValue() == null)
3140 log.error(l.head.pos(), "icls.cant.have.static.decl");
3141 }
3142 }
3144 // Check for cycles among non-initial constructors.
3145 chk.checkCyclicConstructors(tree);
3147 // Check for cycles among annotation elements.
3148 chk.checkNonCyclicElements(tree);
3150 // Check for proper use of serialVersionUID
3151 if (env.info.lint.isEnabled(Lint.LintCategory.SERIAL) &&
3152 isSerializable(c) &&
3153 (c.flags() & Flags.ENUM) == 0 &&
3154 (c.flags() & ABSTRACT) == 0) {
3155 checkSerialVersionUID(tree, c);
3156 }
3158 // Check type annotations applicability rules
3159 validateTypeAnnotations(tree);
3160 }
3161 // where
3162 /** check if a class is a subtype of Serializable, if that is available. */
3163 private boolean isSerializable(ClassSymbol c) {
3164 try {
3165 syms.serializableType.complete();
3166 }
3167 catch (CompletionFailure e) {
3168 return false;
3169 }
3170 return types.isSubtype(c.type, syms.serializableType);
3171 }
3173 /** Check that an appropriate serialVersionUID member is defined. */
3174 private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
3176 // check for presence of serialVersionUID
3177 Scope.Entry e = c.members().lookup(names.serialVersionUID);
3178 while (e.scope != null && e.sym.kind != VAR) e = e.next();
3179 if (e.scope == null) {
3180 log.warning(Lint.LintCategory.SERIAL,
3181 tree.pos(), "missing.SVUID", c);
3182 return;
3183 }
3185 // check that it is static final
3186 VarSymbol svuid = (VarSymbol)e.sym;
3187 if ((svuid.flags() & (STATIC | FINAL)) !=
3188 (STATIC | FINAL))
3189 log.warning(Lint.LintCategory.SERIAL,
3190 TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c);
3192 // check that it is long
3193 else if (svuid.type.tag != TypeTags.LONG)
3194 log.warning(Lint.LintCategory.SERIAL,
3195 TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c);
3197 // check constant
3198 else if (svuid.getConstValue() == null)
3199 log.warning(Lint.LintCategory.SERIAL,
3200 TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c);
3201 }
3203 private Type capture(Type type) {
3204 return types.capture(type);
3205 }
3207 private void validateTypeAnnotations(JCTree tree) {
3208 tree.accept(typeAnnotationsValidator);
3209 }
3210 //where
3211 private final JCTree.Visitor typeAnnotationsValidator =
3212 new TreeScanner() {
3213 public void visitAnnotation(JCAnnotation tree) {
3214 if (tree instanceof JCTypeAnnotation) {
3215 chk.validateTypeAnnotation((JCTypeAnnotation)tree, false);
3216 }
3217 super.visitAnnotation(tree);
3218 }
3219 public void visitTypeParameter(JCTypeParameter tree) {
3220 chk.validateTypeAnnotations(tree.annotations, true);
3221 // don't call super. skip type annotations
3222 scan(tree.bounds);
3223 }
3224 public void visitMethodDef(JCMethodDecl tree) {
3225 // need to check static methods
3226 if ((tree.sym.flags() & Flags.STATIC) != 0) {
3227 for (JCTypeAnnotation a : tree.receiverAnnotations) {
3228 if (chk.isTypeAnnotation(a, false))
3229 log.error(a.pos(), "annotation.type.not.applicable");
3230 }
3231 }
3232 super.visitMethodDef(tree);
3233 }
3234 };
3236 // <editor-fold desc="post-attribution visitor">
3238 /**
3239 * Handle missing types/symbols in an AST. This routine is useful when
3240 * the compiler has encountered some errors (which might have ended up
3241 * terminating attribution abruptly); if the compiler is used in fail-over
3242 * mode (e.g. by an IDE) and the AST contains semantic errors, this routine
3243 * prevents NPE to be progagated during subsequent compilation steps.
3244 */
3245 public void postAttr(Env<AttrContext> env) {
3246 new PostAttrAnalyzer().scan(env.tree);
3247 }
3249 class PostAttrAnalyzer extends TreeScanner {
3251 private void initTypeIfNeeded(JCTree that) {
3252 if (that.type == null) {
3253 that.type = syms.unknownType;
3254 }
3255 }
3257 @Override
3258 public void scan(JCTree tree) {
3259 if (tree == null) return;
3260 if (tree instanceof JCExpression) {
3261 initTypeIfNeeded(tree);
3262 }
3263 super.scan(tree);
3264 }
3266 @Override
3267 public void visitIdent(JCIdent that) {
3268 if (that.sym == null) {
3269 that.sym = syms.unknownSymbol;
3270 }
3271 }
3273 @Override
3274 public void visitSelect(JCFieldAccess that) {
3275 if (that.sym == null) {
3276 that.sym = syms.unknownSymbol;
3277 }
3278 super.visitSelect(that);
3279 }
3281 @Override
3282 public void visitClassDef(JCClassDecl that) {
3283 initTypeIfNeeded(that);
3284 if (that.sym == null) {
3285 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol);
3286 }
3287 super.visitClassDef(that);
3288 }
3290 @Override
3291 public void visitMethodDef(JCMethodDecl that) {
3292 initTypeIfNeeded(that);
3293 if (that.sym == null) {
3294 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol);
3295 }
3296 super.visitMethodDef(that);
3297 }
3299 @Override
3300 public void visitVarDef(JCVariableDecl that) {
3301 initTypeIfNeeded(that);
3302 if (that.sym == null) {
3303 that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol);
3304 that.sym.adr = 0;
3305 }
3306 super.visitVarDef(that);
3307 }
3309 @Override
3310 public void visitNewClass(JCNewClass that) {
3311 if (that.constructor == null) {
3312 that.constructor = new MethodSymbol(0, names.init, syms.unknownType, syms.noSymbol);
3313 }
3314 if (that.constructorType == null) {
3315 that.constructorType = syms.unknownType;
3316 }
3317 super.visitNewClass(that);
3318 }
3320 @Override
3321 public void visitBinary(JCBinary that) {
3322 if (that.operator == null)
3323 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
3324 super.visitBinary(that);
3325 }
3327 @Override
3328 public void visitUnary(JCUnary that) {
3329 if (that.operator == null)
3330 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
3331 super.visitUnary(that);
3332 }
3333 }
3334 // </editor-fold>
3335 }