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