Mon, 23 Aug 2010 15:13:33 -0700
6976747: JCDiagnostic: replace "boolean mandatory" with new "Set<JCDiagnostic.Flag>"
Reviewed-by: mcimadamore
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 (tree.defaultValue != null) {
700 // if default value is an annotation, check it is a well-formed
701 // annotation value (e.g. no duplicate values, no missing values, etc.)
702 chk.validateAnnotationTree(tree.defaultValue);
703 }
704 }
706 for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
707 chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
709 if (tree.body == null) {
710 // Empty bodies are only allowed for
711 // abstract, native, or interface methods, or for methods
712 // in a retrofit signature class.
713 if ((owner.flags() & INTERFACE) == 0 &&
714 (tree.mods.flags & (ABSTRACT | NATIVE)) == 0 &&
715 !relax)
716 log.error(tree.pos(), "missing.meth.body.or.decl.abstract");
717 if (tree.defaultValue != null) {
718 if ((owner.flags() & ANNOTATION) == 0)
719 log.error(tree.pos(),
720 "default.allowed.in.intf.annotation.member");
721 }
722 } else if ((owner.flags() & INTERFACE) != 0) {
723 log.error(tree.body.pos(), "intf.meth.cant.have.body");
724 } else if ((tree.mods.flags & ABSTRACT) != 0) {
725 log.error(tree.pos(), "abstract.meth.cant.have.body");
726 } else if ((tree.mods.flags & NATIVE) != 0) {
727 log.error(tree.pos(), "native.meth.cant.have.body");
728 } else {
729 // Add an implicit super() call unless an explicit call to
730 // super(...) or this(...) is given
731 // or we are compiling class java.lang.Object.
732 if (tree.name == names.init && owner.type != syms.objectType) {
733 JCBlock body = tree.body;
734 if (body.stats.isEmpty() ||
735 !TreeInfo.isSelfCall(body.stats.head)) {
736 body.stats = body.stats.
737 prepend(memberEnter.SuperCall(make.at(body.pos),
738 List.<Type>nil(),
739 List.<JCVariableDecl>nil(),
740 false));
741 } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
742 (tree.mods.flags & GENERATEDCONSTR) == 0 &&
743 TreeInfo.isSuperCall(body.stats.head)) {
744 // enum constructors are not allowed to call super
745 // directly, so make sure there aren't any super calls
746 // in enum constructors, except in the compiler
747 // generated one.
748 log.error(tree.body.stats.head.pos(),
749 "call.to.super.not.allowed.in.enum.ctor",
750 env.enclClass.sym);
751 }
752 }
754 // Attribute method body.
755 attribStat(tree.body, localEnv);
756 }
757 localEnv.info.scope.leave();
758 result = tree.type = m.type;
759 chk.validateAnnotations(tree.mods.annotations, m);
760 }
761 finally {
762 chk.setLint(prevLint);
763 }
764 }
766 public void visitVarDef(JCVariableDecl tree) {
767 // Local variables have not been entered yet, so we need to do it now:
768 if (env.info.scope.owner.kind == MTH) {
769 if (tree.sym != null) {
770 // parameters have already been entered
771 env.info.scope.enter(tree.sym);
772 } else {
773 memberEnter.memberEnter(tree, env);
774 annotate.flush();
775 }
776 }
778 VarSymbol v = tree.sym;
779 Lint lint = env.info.lint.augment(v.attributes_field, v.flags());
780 Lint prevLint = chk.setLint(lint);
782 // Check that the variable's declared type is well-formed.
783 chk.validate(tree.vartype, env);
785 try {
786 chk.checkDeprecatedAnnotation(tree.pos(), v);
788 if (tree.init != null) {
789 if ((v.flags_field & FINAL) != 0 && tree.init.getTag() != JCTree.NEWCLASS) {
790 // In this case, `v' is final. Ensure that it's initializer is
791 // evaluated.
792 v.getConstValue(); // ensure initializer is evaluated
793 } else {
794 // Attribute initializer in a new environment
795 // with the declared variable as owner.
796 // Check that initializer conforms to variable's declared type.
797 Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
798 initEnv.info.lint = lint;
799 // In order to catch self-references, we set the variable's
800 // declaration position to maximal possible value, effectively
801 // marking the variable as undefined.
802 initEnv.info.enclVar = v;
803 attribExpr(tree.init, initEnv, v.type);
804 }
805 }
806 result = tree.type = v.type;
807 chk.validateAnnotations(tree.mods.annotations, v);
808 }
809 finally {
810 chk.setLint(prevLint);
811 }
812 }
814 public void visitSkip(JCSkip tree) {
815 result = null;
816 }
818 public void visitBlock(JCBlock tree) {
819 if (env.info.scope.owner.kind == TYP) {
820 // Block is a static or instance initializer;
821 // let the owner of the environment be a freshly
822 // created BLOCK-method.
823 Env<AttrContext> localEnv =
824 env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
825 localEnv.info.scope.owner =
826 new MethodSymbol(tree.flags | BLOCK, names.empty, null,
827 env.info.scope.owner);
828 if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
829 attribStats(tree.stats, localEnv);
830 } else {
831 // Create a new local environment with a local scope.
832 Env<AttrContext> localEnv =
833 env.dup(tree, env.info.dup(env.info.scope.dup()));
834 attribStats(tree.stats, localEnv);
835 localEnv.info.scope.leave();
836 }
837 result = null;
838 }
840 public void visitDoLoop(JCDoWhileLoop tree) {
841 attribStat(tree.body, env.dup(tree));
842 attribExpr(tree.cond, env, syms.booleanType);
843 result = null;
844 }
846 public void visitWhileLoop(JCWhileLoop tree) {
847 attribExpr(tree.cond, env, syms.booleanType);
848 attribStat(tree.body, env.dup(tree));
849 result = null;
850 }
852 public void visitForLoop(JCForLoop tree) {
853 Env<AttrContext> loopEnv =
854 env.dup(env.tree, env.info.dup(env.info.scope.dup()));
855 attribStats(tree.init, loopEnv);
856 if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType);
857 loopEnv.tree = tree; // before, we were not in loop!
858 attribStats(tree.step, loopEnv);
859 attribStat(tree.body, loopEnv);
860 loopEnv.info.scope.leave();
861 result = null;
862 }
864 public void visitForeachLoop(JCEnhancedForLoop tree) {
865 Env<AttrContext> loopEnv =
866 env.dup(env.tree, env.info.dup(env.info.scope.dup()));
867 attribStat(tree.var, loopEnv);
868 Type exprType = types.upperBound(attribExpr(tree.expr, loopEnv));
869 chk.checkNonVoid(tree.pos(), exprType);
870 Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
871 if (elemtype == null) {
872 // or perhaps expr implements Iterable<T>?
873 Type base = types.asSuper(exprType, syms.iterableType.tsym);
874 if (base == null) {
875 log.error(tree.expr.pos(), "foreach.not.applicable.to.type");
876 elemtype = types.createErrorType(exprType);
877 } else {
878 List<Type> iterableParams = base.allparams();
879 elemtype = iterableParams.isEmpty()
880 ? syms.objectType
881 : types.upperBound(iterableParams.head);
882 }
883 }
884 chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
885 loopEnv.tree = tree; // before, we were not in loop!
886 attribStat(tree.body, loopEnv);
887 loopEnv.info.scope.leave();
888 result = null;
889 }
891 public void visitLabelled(JCLabeledStatement tree) {
892 // Check that label is not used in an enclosing statement
893 Env<AttrContext> env1 = env;
894 while (env1 != null && env1.tree.getTag() != JCTree.CLASSDEF) {
895 if (env1.tree.getTag() == JCTree.LABELLED &&
896 ((JCLabeledStatement) env1.tree).label == tree.label) {
897 log.error(tree.pos(), "label.already.in.use",
898 tree.label);
899 break;
900 }
901 env1 = env1.next;
902 }
904 attribStat(tree.body, env.dup(tree));
905 result = null;
906 }
908 public void visitSwitch(JCSwitch tree) {
909 Type seltype = attribExpr(tree.selector, env);
911 Env<AttrContext> switchEnv =
912 env.dup(tree, env.info.dup(env.info.scope.dup()));
914 boolean enumSwitch =
915 allowEnums &&
916 (seltype.tsym.flags() & Flags.ENUM) != 0;
917 boolean stringSwitch = false;
918 if (types.isSameType(seltype, syms.stringType)) {
919 if (allowStringsInSwitch) {
920 stringSwitch = true;
921 } else {
922 log.error(tree.selector.pos(), "string.switch.not.supported.in.source", sourceName);
923 }
924 }
925 if (!enumSwitch && !stringSwitch)
926 seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType);
928 // Attribute all cases and
929 // check that there are no duplicate case labels or default clauses.
930 Set<Object> labels = new HashSet<Object>(); // The set of case labels.
931 boolean hasDefault = false; // Is there a default label?
932 for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
933 JCCase c = l.head;
934 Env<AttrContext> caseEnv =
935 switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup()));
936 if (c.pat != null) {
937 if (enumSwitch) {
938 Symbol sym = enumConstant(c.pat, seltype);
939 if (sym == null) {
940 log.error(c.pat.pos(), "enum.const.req");
941 } else if (!labels.add(sym)) {
942 log.error(c.pos(), "duplicate.case.label");
943 }
944 } else {
945 Type pattype = attribExpr(c.pat, switchEnv, seltype);
946 if (pattype.tag != ERROR) {
947 if (pattype.constValue() == null) {
948 log.error(c.pat.pos(),
949 (stringSwitch ? "string.const.req" : "const.expr.req"));
950 } else if (labels.contains(pattype.constValue())) {
951 log.error(c.pos(), "duplicate.case.label");
952 } else {
953 labels.add(pattype.constValue());
954 }
955 }
956 }
957 } else if (hasDefault) {
958 log.error(c.pos(), "duplicate.default.label");
959 } else {
960 hasDefault = true;
961 }
962 attribStats(c.stats, caseEnv);
963 caseEnv.info.scope.leave();
964 addVars(c.stats, switchEnv.info.scope);
965 }
967 switchEnv.info.scope.leave();
968 result = null;
969 }
970 // where
971 /** Add any variables defined in stats to the switch scope. */
972 private static void addVars(List<JCStatement> stats, Scope switchScope) {
973 for (;stats.nonEmpty(); stats = stats.tail) {
974 JCTree stat = stats.head;
975 if (stat.getTag() == JCTree.VARDEF)
976 switchScope.enter(((JCVariableDecl) stat).sym);
977 }
978 }
979 // where
980 /** Return the selected enumeration constant symbol, or null. */
981 private Symbol enumConstant(JCTree tree, Type enumType) {
982 if (tree.getTag() != JCTree.IDENT) {
983 log.error(tree.pos(), "enum.label.must.be.unqualified.enum");
984 return syms.errSymbol;
985 }
986 JCIdent ident = (JCIdent)tree;
987 Name name = ident.name;
988 for (Scope.Entry e = enumType.tsym.members().lookup(name);
989 e.scope != null; e = e.next()) {
990 if (e.sym.kind == VAR) {
991 Symbol s = ident.sym = e.sym;
992 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
993 ident.type = s.type;
994 return ((s.flags_field & Flags.ENUM) == 0)
995 ? null : s;
996 }
997 }
998 return null;
999 }
1001 public void visitSynchronized(JCSynchronized tree) {
1002 chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
1003 attribStat(tree.body, env);
1004 result = null;
1005 }
1007 public void visitTry(JCTry tree) {
1008 // Create a new local environment with a local
1009 Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
1010 boolean isTryWithResource = tree.resources.nonEmpty();
1011 // Create a nested environment for attributing the try block if needed
1012 Env<AttrContext> tryEnv = isTryWithResource ?
1013 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
1014 localEnv;
1015 // Attribute resource declarations
1016 for (JCTree resource : tree.resources) {
1017 if (resource.getTag() == JCTree.VARDEF) {
1018 attribStat(resource, tryEnv);
1019 chk.checkType(resource, resource.type, syms.autoCloseableType, "twr.not.applicable.to.type");
1020 VarSymbol var = (VarSymbol)TreeInfo.symbolFor(resource);
1021 var.setData(ElementKind.RESOURCE_VARIABLE);
1022 } else {
1023 attribExpr(resource, tryEnv, syms.autoCloseableType, "twr.not.applicable.to.type");
1024 }
1025 }
1026 // Attribute body
1027 attribStat(tree.body, tryEnv);
1028 if (isTryWithResource)
1029 tryEnv.info.scope.leave();
1031 // Attribute catch clauses
1032 for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
1033 JCCatch c = l.head;
1034 Env<AttrContext> catchEnv =
1035 localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup()));
1036 Type ctype = attribStat(c.param, catchEnv);
1037 if (TreeInfo.isMultiCatch(c)) {
1038 //check that multi-catch parameter is marked as final
1039 if ((c.param.sym.flags() & FINAL) == 0) {
1040 log.error(c.param.pos(), "multicatch.param.must.be.final", c.param.sym);
1041 }
1042 c.param.sym.flags_field = c.param.sym.flags() | DISJOINT;
1043 }
1044 if (c.param.type.tsym.kind == Kinds.VAR) {
1045 c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
1046 }
1047 chk.checkType(c.param.vartype.pos(),
1048 chk.checkClassType(c.param.vartype.pos(), ctype),
1049 syms.throwableType);
1050 attribStat(c.body, catchEnv);
1051 catchEnv.info.scope.leave();
1052 }
1054 // Attribute finalizer
1055 if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
1057 localEnv.info.scope.leave();
1058 result = null;
1059 }
1061 public void visitConditional(JCConditional tree) {
1062 attribExpr(tree.cond, env, syms.booleanType);
1063 attribExpr(tree.truepart, env);
1064 attribExpr(tree.falsepart, env);
1065 result = check(tree,
1066 capture(condType(tree.pos(), tree.cond.type,
1067 tree.truepart.type, tree.falsepart.type)),
1068 VAL, pkind, pt);
1069 }
1070 //where
1071 /** Compute the type of a conditional expression, after
1072 * checking that it exists. See Spec 15.25.
1073 *
1074 * @param pos The source position to be used for
1075 * error diagnostics.
1076 * @param condtype The type of the expression's condition.
1077 * @param thentype The type of the expression's then-part.
1078 * @param elsetype The type of the expression's else-part.
1079 */
1080 private Type condType(DiagnosticPosition pos,
1081 Type condtype,
1082 Type thentype,
1083 Type elsetype) {
1084 Type ctype = condType1(pos, condtype, thentype, elsetype);
1086 // If condition and both arms are numeric constants,
1087 // evaluate at compile-time.
1088 return ((condtype.constValue() != null) &&
1089 (thentype.constValue() != null) &&
1090 (elsetype.constValue() != null))
1091 ? cfolder.coerce(condtype.isTrue()?thentype:elsetype, ctype)
1092 : ctype;
1093 }
1094 /** Compute the type of a conditional expression, after
1095 * checking that it exists. Does not take into
1096 * account the special case where condition and both arms
1097 * are constants.
1098 *
1099 * @param pos The source position to be used for error
1100 * diagnostics.
1101 * @param condtype The type of the expression's condition.
1102 * @param thentype The type of the expression's then-part.
1103 * @param elsetype The type of the expression's else-part.
1104 */
1105 private Type condType1(DiagnosticPosition pos, Type condtype,
1106 Type thentype, Type elsetype) {
1107 // If same type, that is the result
1108 if (types.isSameType(thentype, elsetype))
1109 return thentype.baseType();
1111 Type thenUnboxed = (!allowBoxing || thentype.isPrimitive())
1112 ? thentype : types.unboxedType(thentype);
1113 Type elseUnboxed = (!allowBoxing || elsetype.isPrimitive())
1114 ? elsetype : types.unboxedType(elsetype);
1116 // Otherwise, if both arms can be converted to a numeric
1117 // type, return the least numeric type that fits both arms
1118 // (i.e. return larger of the two, or return int if one
1119 // arm is short, the other is char).
1120 if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) {
1121 // If one arm has an integer subrange type (i.e., byte,
1122 // short, or char), and the other is an integer constant
1123 // that fits into the subrange, return the subrange type.
1124 if (thenUnboxed.tag < INT && elseUnboxed.tag == INT &&
1125 types.isAssignable(elseUnboxed, thenUnboxed))
1126 return thenUnboxed.baseType();
1127 if (elseUnboxed.tag < INT && thenUnboxed.tag == INT &&
1128 types.isAssignable(thenUnboxed, elseUnboxed))
1129 return elseUnboxed.baseType();
1131 for (int i = BYTE; i < VOID; i++) {
1132 Type candidate = syms.typeOfTag[i];
1133 if (types.isSubtype(thenUnboxed, candidate) &&
1134 types.isSubtype(elseUnboxed, candidate))
1135 return candidate;
1136 }
1137 }
1139 // Those were all the cases that could result in a primitive
1140 if (allowBoxing) {
1141 if (thentype.isPrimitive())
1142 thentype = types.boxedClass(thentype).type;
1143 if (elsetype.isPrimitive())
1144 elsetype = types.boxedClass(elsetype).type;
1145 }
1147 if (types.isSubtype(thentype, elsetype))
1148 return elsetype.baseType();
1149 if (types.isSubtype(elsetype, thentype))
1150 return thentype.baseType();
1152 if (!allowBoxing || thentype.tag == VOID || elsetype.tag == VOID) {
1153 log.error(pos, "neither.conditional.subtype",
1154 thentype, elsetype);
1155 return thentype.baseType();
1156 }
1158 // both are known to be reference types. The result is
1159 // lub(thentype,elsetype). This cannot fail, as it will
1160 // always be possible to infer "Object" if nothing better.
1161 return types.lub(thentype.baseType(), elsetype.baseType());
1162 }
1164 public void visitIf(JCIf tree) {
1165 attribExpr(tree.cond, env, syms.booleanType);
1166 attribStat(tree.thenpart, env);
1167 if (tree.elsepart != null)
1168 attribStat(tree.elsepart, env);
1169 chk.checkEmptyIf(tree);
1170 result = null;
1171 }
1173 public void visitExec(JCExpressionStatement tree) {
1174 attribExpr(tree.expr, env);
1175 result = null;
1176 }
1178 public void visitBreak(JCBreak tree) {
1179 tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
1180 result = null;
1181 }
1183 public void visitContinue(JCContinue tree) {
1184 tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
1185 result = null;
1186 }
1187 //where
1188 /** Return the target of a break or continue statement, if it exists,
1189 * report an error if not.
1190 * Note: The target of a labelled break or continue is the
1191 * (non-labelled) statement tree referred to by the label,
1192 * not the tree representing the labelled statement itself.
1193 *
1194 * @param pos The position to be used for error diagnostics
1195 * @param tag The tag of the jump statement. This is either
1196 * Tree.BREAK or Tree.CONTINUE.
1197 * @param label The label of the jump statement, or null if no
1198 * label is given.
1199 * @param env The environment current at the jump statement.
1200 */
1201 private JCTree findJumpTarget(DiagnosticPosition pos,
1202 int tag,
1203 Name label,
1204 Env<AttrContext> env) {
1205 // Search environments outwards from the point of jump.
1206 Env<AttrContext> env1 = env;
1207 LOOP:
1208 while (env1 != null) {
1209 switch (env1.tree.getTag()) {
1210 case JCTree.LABELLED:
1211 JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
1212 if (label == labelled.label) {
1213 // If jump is a continue, check that target is a loop.
1214 if (tag == JCTree.CONTINUE) {
1215 if (labelled.body.getTag() != JCTree.DOLOOP &&
1216 labelled.body.getTag() != JCTree.WHILELOOP &&
1217 labelled.body.getTag() != JCTree.FORLOOP &&
1218 labelled.body.getTag() != JCTree.FOREACHLOOP)
1219 log.error(pos, "not.loop.label", label);
1220 // Found labelled statement target, now go inwards
1221 // to next non-labelled tree.
1222 return TreeInfo.referencedStatement(labelled);
1223 } else {
1224 return labelled;
1225 }
1226 }
1227 break;
1228 case JCTree.DOLOOP:
1229 case JCTree.WHILELOOP:
1230 case JCTree.FORLOOP:
1231 case JCTree.FOREACHLOOP:
1232 if (label == null) return env1.tree;
1233 break;
1234 case JCTree.SWITCH:
1235 if (label == null && tag == JCTree.BREAK) return env1.tree;
1236 break;
1237 case JCTree.METHODDEF:
1238 case JCTree.CLASSDEF:
1239 break LOOP;
1240 default:
1241 }
1242 env1 = env1.next;
1243 }
1244 if (label != null)
1245 log.error(pos, "undef.label", label);
1246 else if (tag == JCTree.CONTINUE)
1247 log.error(pos, "cont.outside.loop");
1248 else
1249 log.error(pos, "break.outside.switch.loop");
1250 return null;
1251 }
1253 public void visitReturn(JCReturn tree) {
1254 // Check that there is an enclosing method which is
1255 // nested within than the enclosing class.
1256 if (env.enclMethod == null ||
1257 env.enclMethod.sym.owner != env.enclClass.sym) {
1258 log.error(tree.pos(), "ret.outside.meth");
1260 } else {
1261 // Attribute return expression, if it exists, and check that
1262 // it conforms to result type of enclosing method.
1263 Symbol m = env.enclMethod.sym;
1264 if (m.type.getReturnType().tag == VOID) {
1265 if (tree.expr != null)
1266 log.error(tree.expr.pos(),
1267 "cant.ret.val.from.meth.decl.void");
1268 } else if (tree.expr == null) {
1269 log.error(tree.pos(), "missing.ret.val");
1270 } else {
1271 attribExpr(tree.expr, env, m.type.getReturnType());
1272 }
1273 }
1274 result = null;
1275 }
1277 public void visitThrow(JCThrow tree) {
1278 attribExpr(tree.expr, env, syms.throwableType);
1279 result = null;
1280 }
1282 public void visitAssert(JCAssert tree) {
1283 attribExpr(tree.cond, env, syms.booleanType);
1284 if (tree.detail != null) {
1285 chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
1286 }
1287 result = null;
1288 }
1290 /** Visitor method for method invocations.
1291 * NOTE: The method part of an application will have in its type field
1292 * the return type of the method, not the method's type itself!
1293 */
1294 public void visitApply(JCMethodInvocation tree) {
1295 // The local environment of a method application is
1296 // a new environment nested in the current one.
1297 Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
1299 // The types of the actual method arguments.
1300 List<Type> argtypes;
1302 // The types of the actual method type arguments.
1303 List<Type> typeargtypes = null;
1304 boolean typeargtypesNonRefOK = false;
1306 Name methName = TreeInfo.name(tree.meth);
1308 boolean isConstructorCall =
1309 methName == names._this || methName == names._super;
1311 if (isConstructorCall) {
1312 // We are seeing a ...this(...) or ...super(...) call.
1313 // Check that this is the first statement in a constructor.
1314 if (checkFirstConstructorStat(tree, env)) {
1316 // Record the fact
1317 // that this is a constructor call (using isSelfCall).
1318 localEnv.info.isSelfCall = true;
1320 // Attribute arguments, yielding list of argument types.
1321 argtypes = attribArgs(tree.args, localEnv);
1322 typeargtypes = attribTypes(tree.typeargs, localEnv);
1324 // Variable `site' points to the class in which the called
1325 // constructor is defined.
1326 Type site = env.enclClass.sym.type;
1327 if (methName == names._super) {
1328 if (site == syms.objectType) {
1329 log.error(tree.meth.pos(), "no.superclass", site);
1330 site = types.createErrorType(syms.objectType);
1331 } else {
1332 site = types.supertype(site);
1333 }
1334 }
1336 if (site.tag == CLASS) {
1337 Type encl = site.getEnclosingType();
1338 while (encl != null && encl.tag == TYPEVAR)
1339 encl = encl.getUpperBound();
1340 if (encl.tag == CLASS) {
1341 // we are calling a nested class
1343 if (tree.meth.getTag() == JCTree.SELECT) {
1344 JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
1346 // We are seeing a prefixed call, of the form
1347 // <expr>.super(...).
1348 // Check that the prefix expression conforms
1349 // to the outer instance type of the class.
1350 chk.checkRefType(qualifier.pos(),
1351 attribExpr(qualifier, localEnv,
1352 encl));
1353 } else if (methName == names._super) {
1354 // qualifier omitted; check for existence
1355 // of an appropriate implicit qualifier.
1356 rs.resolveImplicitThis(tree.meth.pos(),
1357 localEnv, site);
1358 }
1359 } else if (tree.meth.getTag() == JCTree.SELECT) {
1360 log.error(tree.meth.pos(), "illegal.qual.not.icls",
1361 site.tsym);
1362 }
1364 // if we're calling a java.lang.Enum constructor,
1365 // prefix the implicit String and int parameters
1366 if (site.tsym == syms.enumSym && allowEnums)
1367 argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
1369 // Resolve the called constructor under the assumption
1370 // that we are referring to a superclass instance of the
1371 // current instance (JLS ???).
1372 boolean selectSuperPrev = localEnv.info.selectSuper;
1373 localEnv.info.selectSuper = true;
1374 localEnv.info.varArgs = false;
1375 Symbol sym = rs.resolveConstructor(
1376 tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
1377 localEnv.info.selectSuper = selectSuperPrev;
1379 // Set method symbol to resolved constructor...
1380 TreeInfo.setSymbol(tree.meth, sym);
1382 // ...and check that it is legal in the current context.
1383 // (this will also set the tree's type)
1384 Type mpt = newMethTemplate(argtypes, typeargtypes);
1385 checkId(tree.meth, site, sym, localEnv, MTH,
1386 mpt, tree.varargsElement != null);
1387 }
1388 // Otherwise, `site' is an error type and we do nothing
1389 }
1390 result = tree.type = syms.voidType;
1391 } else {
1392 // Otherwise, we are seeing a regular method call.
1393 // Attribute the arguments, yielding list of argument types, ...
1394 argtypes = attribArgs(tree.args, localEnv);
1395 typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
1397 // ... and attribute the method using as a prototype a methodtype
1398 // whose formal argument types is exactly the list of actual
1399 // arguments (this will also set the method symbol).
1400 Type mpt = newMethTemplate(argtypes, typeargtypes);
1401 localEnv.info.varArgs = false;
1402 Type mtype = attribExpr(tree.meth, localEnv, mpt);
1403 if (localEnv.info.varArgs)
1404 assert mtype.isErroneous() || tree.varargsElement != null;
1406 // Compute the result type.
1407 Type restype = mtype.getReturnType();
1408 assert restype.tag != WILDCARD : mtype;
1410 // as a special case, array.clone() has a result that is
1411 // the same as static type of the array being cloned
1412 if (tree.meth.getTag() == JCTree.SELECT &&
1413 allowCovariantReturns &&
1414 methName == names.clone &&
1415 types.isArray(((JCFieldAccess) tree.meth).selected.type))
1416 restype = ((JCFieldAccess) tree.meth).selected.type;
1418 // as a special case, x.getClass() has type Class<? extends |X|>
1419 if (allowGenerics &&
1420 methName == names.getClass && tree.args.isEmpty()) {
1421 Type qualifier = (tree.meth.getTag() == JCTree.SELECT)
1422 ? ((JCFieldAccess) tree.meth).selected.type
1423 : env.enclClass.sym.type;
1424 restype = new
1425 ClassType(restype.getEnclosingType(),
1426 List.<Type>of(new WildcardType(types.erasure(qualifier),
1427 BoundKind.EXTENDS,
1428 syms.boundClass)),
1429 restype.tsym);
1430 }
1432 // as a special case, MethodHandle.<T>invoke(abc) and InvokeDynamic.<T>foo(abc)
1433 // has type <T>, and T can be a primitive type.
1434 if (tree.meth.getTag() == JCTree.SELECT && !typeargtypes.isEmpty()) {
1435 JCFieldAccess mfield = (JCFieldAccess) tree.meth;
1436 if ((mfield.selected.type.tsym != null &&
1437 (mfield.selected.type.tsym.flags() & POLYMORPHIC_SIGNATURE) != 0)
1438 ||
1439 (mfield.sym != null &&
1440 (mfield.sym.flags() & POLYMORPHIC_SIGNATURE) != 0)) {
1441 assert types.isSameType(restype, typeargtypes.head) : mtype;
1442 assert mfield.selected.type == syms.methodHandleType
1443 || mfield.selected.type == syms.invokeDynamicType;
1444 typeargtypesNonRefOK = true;
1445 }
1446 }
1448 if (!typeargtypesNonRefOK) {
1449 chk.checkRefTypes(tree.typeargs, typeargtypes);
1450 }
1452 // Check that value of resulting type is admissible in the
1453 // current context. Also, capture the return type
1454 result = check(tree, capture(restype), VAL, pkind, pt);
1455 }
1456 chk.validate(tree.typeargs, localEnv);
1457 }
1458 //where
1459 /** Check that given application node appears as first statement
1460 * in a constructor call.
1461 * @param tree The application node
1462 * @param env The environment current at the application.
1463 */
1464 boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) {
1465 JCMethodDecl enclMethod = env.enclMethod;
1466 if (enclMethod != null && enclMethod.name == names.init) {
1467 JCBlock body = enclMethod.body;
1468 if (body.stats.head.getTag() == JCTree.EXEC &&
1469 ((JCExpressionStatement) body.stats.head).expr == tree)
1470 return true;
1471 }
1472 log.error(tree.pos(),"call.must.be.first.stmt.in.ctor",
1473 TreeInfo.name(tree.meth));
1474 return false;
1475 }
1477 /** Obtain a method type with given argument types.
1478 */
1479 Type newMethTemplate(List<Type> argtypes, List<Type> typeargtypes) {
1480 MethodType mt = new MethodType(argtypes, null, null, syms.methodClass);
1481 return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
1482 }
1484 public void visitNewClass(JCNewClass tree) {
1485 Type owntype = types.createErrorType(tree.type);
1487 // The local environment of a class creation is
1488 // a new environment nested in the current one.
1489 Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
1491 // The anonymous inner class definition of the new expression,
1492 // if one is defined by it.
1493 JCClassDecl cdef = tree.def;
1495 // If enclosing class is given, attribute it, and
1496 // complete class name to be fully qualified
1497 JCExpression clazz = tree.clazz; // Class field following new
1498 JCExpression clazzid = // Identifier in class field
1499 (clazz.getTag() == JCTree.TYPEAPPLY)
1500 ? ((JCTypeApply) clazz).clazz
1501 : clazz;
1503 JCExpression clazzid1 = clazzid; // The same in fully qualified form
1505 if (tree.encl != null) {
1506 // We are seeing a qualified new, of the form
1507 // <expr>.new C <...> (...) ...
1508 // In this case, we let clazz stand for the name of the
1509 // allocated class C prefixed with the type of the qualifier
1510 // expression, so that we can
1511 // resolve it with standard techniques later. I.e., if
1512 // <expr> has type T, then <expr>.new C <...> (...)
1513 // yields a clazz T.C.
1514 Type encltype = chk.checkRefType(tree.encl.pos(),
1515 attribExpr(tree.encl, env));
1516 clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
1517 ((JCIdent) clazzid).name);
1518 if (clazz.getTag() == JCTree.TYPEAPPLY)
1519 clazz = make.at(tree.pos).
1520 TypeApply(clazzid1,
1521 ((JCTypeApply) clazz).arguments);
1522 else
1523 clazz = clazzid1;
1524 }
1526 // Attribute clazz expression and store
1527 // symbol + type back into the attributed tree.
1528 Type clazztype = attribType(clazz, env);
1529 Pair<Scope,Scope> mapping = getSyntheticScopeMapping(clazztype);
1530 if (!TreeInfo.isDiamond(tree)) {
1531 clazztype = chk.checkClassType(
1532 tree.clazz.pos(), clazztype, true);
1533 }
1534 chk.validate(clazz, localEnv);
1535 if (tree.encl != null) {
1536 // We have to work in this case to store
1537 // symbol + type back into the attributed tree.
1538 tree.clazz.type = clazztype;
1539 TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
1540 clazzid.type = ((JCIdent) clazzid).sym.type;
1541 if (!clazztype.isErroneous()) {
1542 if (cdef != null && clazztype.tsym.isInterface()) {
1543 log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new");
1544 } else if (clazztype.tsym.isStatic()) {
1545 log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym);
1546 }
1547 }
1548 } else if (!clazztype.tsym.isInterface() &&
1549 clazztype.getEnclosingType().tag == CLASS) {
1550 // Check for the existence of an apropos outer instance
1551 rs.resolveImplicitThis(tree.pos(), env, clazztype);
1552 }
1554 // Attribute constructor arguments.
1555 List<Type> argtypes = attribArgs(tree.args, localEnv);
1556 List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
1558 if (TreeInfo.isDiamond(tree)) {
1559 clazztype = attribDiamond(localEnv, tree, clazztype, mapping, argtypes, typeargtypes);
1560 clazz.type = clazztype;
1561 }
1563 // If we have made no mistakes in the class type...
1564 if (clazztype.tag == CLASS) {
1565 // Enums may not be instantiated except implicitly
1566 if (allowEnums &&
1567 (clazztype.tsym.flags_field&Flags.ENUM) != 0 &&
1568 (env.tree.getTag() != JCTree.VARDEF ||
1569 (((JCVariableDecl) env.tree).mods.flags&Flags.ENUM) == 0 ||
1570 ((JCVariableDecl) env.tree).init != tree))
1571 log.error(tree.pos(), "enum.cant.be.instantiated");
1572 // Check that class is not abstract
1573 if (cdef == null &&
1574 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
1575 log.error(tree.pos(), "abstract.cant.be.instantiated",
1576 clazztype.tsym);
1577 } else if (cdef != null && clazztype.tsym.isInterface()) {
1578 // Check that no constructor arguments are given to
1579 // anonymous classes implementing an interface
1580 if (!argtypes.isEmpty())
1581 log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args");
1583 if (!typeargtypes.isEmpty())
1584 log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs");
1586 // Error recovery: pretend no arguments were supplied.
1587 argtypes = List.nil();
1588 typeargtypes = List.nil();
1589 }
1591 // Resolve the called constructor under the assumption
1592 // that we are referring to a superclass instance of the
1593 // current instance (JLS ???).
1594 else {
1595 localEnv.info.selectSuper = cdef != null;
1596 localEnv.info.varArgs = false;
1597 tree.constructor = rs.resolveConstructor(
1598 tree.pos(), localEnv, clazztype, argtypes, typeargtypes);
1599 tree.constructorType = tree.constructor.type.isErroneous() ?
1600 syms.errType :
1601 checkMethod(clazztype,
1602 tree.constructor,
1603 localEnv,
1604 tree.args,
1605 argtypes,
1606 typeargtypes,
1607 localEnv.info.varArgs);
1608 if (localEnv.info.varArgs)
1609 assert tree.constructorType.isErroneous() || tree.varargsElement != null;
1610 }
1612 if (cdef != null) {
1613 // We are seeing an anonymous class instance creation.
1614 // In this case, the class instance creation
1615 // expression
1616 //
1617 // E.new <typeargs1>C<typargs2>(args) { ... }
1618 //
1619 // is represented internally as
1620 //
1621 // E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } ) .
1622 //
1623 // This expression is then *transformed* as follows:
1624 //
1625 // (1) add a STATIC flag to the class definition
1626 // if the current environment is static
1627 // (2) add an extends or implements clause
1628 // (3) add a constructor.
1629 //
1630 // For instance, if C is a class, and ET is the type of E,
1631 // the expression
1632 //
1633 // E.new <typeargs1>C<typargs2>(args) { ... }
1634 //
1635 // is translated to (where X is a fresh name and typarams is the
1636 // parameter list of the super constructor):
1637 //
1638 // new <typeargs1>X(<*nullchk*>E, args) where
1639 // X extends C<typargs2> {
1640 // <typarams> X(ET e, args) {
1641 // e.<typeargs1>super(args)
1642 // }
1643 // ...
1644 // }
1645 if (Resolve.isStatic(env)) cdef.mods.flags |= STATIC;
1647 if (clazztype.tsym.isInterface()) {
1648 cdef.implementing = List.of(clazz);
1649 } else {
1650 cdef.extending = clazz;
1651 }
1653 attribStat(cdef, localEnv);
1655 // If an outer instance is given,
1656 // prefix it to the constructor arguments
1657 // and delete it from the new expression
1658 if (tree.encl != null && !clazztype.tsym.isInterface()) {
1659 tree.args = tree.args.prepend(makeNullCheck(tree.encl));
1660 argtypes = argtypes.prepend(tree.encl.type);
1661 tree.encl = null;
1662 }
1664 // Reassign clazztype and recompute constructor.
1665 clazztype = cdef.sym.type;
1666 Symbol sym = rs.resolveConstructor(
1667 tree.pos(), localEnv, clazztype, argtypes,
1668 typeargtypes, true, tree.varargsElement != null);
1669 assert sym.kind < AMBIGUOUS || tree.constructor.type.isErroneous();
1670 tree.constructor = sym;
1671 if (tree.constructor.kind > ERRONEOUS) {
1672 tree.constructorType = syms.errType;
1673 }
1674 else {
1675 tree.constructorType = checkMethod(clazztype,
1676 tree.constructor,
1677 localEnv,
1678 tree.args,
1679 argtypes,
1680 typeargtypes,
1681 localEnv.info.varArgs);
1682 }
1683 }
1685 if (tree.constructor != null && tree.constructor.kind == MTH)
1686 owntype = clazztype;
1687 }
1688 result = check(tree, owntype, VAL, pkind, pt);
1689 chk.validate(tree.typeargs, localEnv);
1690 }
1692 Type attribDiamond(Env<AttrContext> env,
1693 JCNewClass tree,
1694 Type clazztype,
1695 Pair<Scope, Scope> mapping,
1696 List<Type> argtypes,
1697 List<Type> typeargtypes) {
1698 if (clazztype.isErroneous() || mapping == erroneousMapping) {
1699 //if the type of the instance creation expression is erroneous,
1700 //or something prevented us to form a valid mapping, return the
1701 //(possibly erroneous) type unchanged
1702 return clazztype;
1703 }
1704 else if (clazztype.isInterface()) {
1705 //if the type of the instance creation expression is an interface
1706 //skip the method resolution step (JLS 15.12.2.7). The type to be
1707 //inferred is of the kind <X1,X2, ... Xn>C<X1,X2, ... Xn>
1708 clazztype = new ForAll(clazztype.tsym.type.allparams(), clazztype.tsym.type) {
1709 @Override
1710 public List<Type> getConstraints(TypeVar tv, ConstraintKind ck) {
1711 switch (ck) {
1712 case EXTENDS: return types.getBounds(tv);
1713 default: return List.nil();
1714 }
1715 }
1716 @Override
1717 public Type inst(List<Type> inferred, Types types) throws Infer.NoInstanceException {
1718 // check that inferred bounds conform to their bounds
1719 infer.checkWithinBounds(tvars,
1720 types.subst(tvars, tvars, inferred), Warner.noWarnings);
1721 return super.inst(inferred, types);
1722 }
1723 };
1724 } else {
1725 //if the type of the instance creation expression is a class type
1726 //apply method resolution inference (JLS 15.12.2.7). The return type
1727 //of the resolved constructor will be a partially instantiated type
1728 ((ClassSymbol) clazztype.tsym).members_field = mapping.snd;
1729 Symbol constructor;
1730 try {
1731 constructor = rs.resolveDiamond(tree.pos(),
1732 env,
1733 clazztype.tsym.type,
1734 argtypes,
1735 typeargtypes);
1736 } finally {
1737 ((ClassSymbol) clazztype.tsym).members_field = mapping.fst;
1738 }
1739 if (constructor.kind == MTH) {
1740 ClassType ct = new ClassType(clazztype.getEnclosingType(),
1741 clazztype.tsym.type.getTypeArguments(),
1742 clazztype.tsym);
1743 clazztype = checkMethod(ct,
1744 constructor,
1745 env,
1746 tree.args,
1747 argtypes,
1748 typeargtypes,
1749 env.info.varArgs).getReturnType();
1750 } else {
1751 clazztype = syms.errType;
1752 }
1753 }
1754 if (clazztype.tag == FORALL && !pt.isErroneous()) {
1755 //if the resolved constructor's return type has some uninferred
1756 //type-variables, infer them using the expected type and declared
1757 //bounds (JLS 15.12.2.8).
1758 try {
1759 clazztype = infer.instantiateExpr((ForAll) clazztype,
1760 pt.tag == NONE ? syms.objectType : pt,
1761 Warner.noWarnings);
1762 } catch (Infer.InferenceException ex) {
1763 //an error occurred while inferring uninstantiated type-variables
1764 log.error(tree.clazz.pos(),
1765 "cant.apply.diamond.1",
1766 diags.fragment("diamond", clazztype.tsym),
1767 ex.diagnostic);
1768 }
1769 }
1770 clazztype = chk.checkClassType(tree.clazz.pos(),
1771 clazztype,
1772 true);
1773 if (clazztype.tag == CLASS) {
1774 List<Type> invalidDiamondArgs = chk.checkDiamond((ClassType)clazztype);
1775 if (!clazztype.isErroneous() && invalidDiamondArgs.nonEmpty()) {
1776 //one or more types inferred in the previous steps is either a
1777 //captured type or an intersection type --- we need to report an error.
1778 String subkey = invalidDiamondArgs.size() > 1 ?
1779 "diamond.invalid.args" :
1780 "diamond.invalid.arg";
1781 //The error message is of the kind:
1782 //
1783 //cannot infer type arguments for {clazztype}<>;
1784 //reason: {subkey}
1785 //
1786 //where subkey is a fragment of the kind:
1787 //
1788 //type argument(s) {invalidDiamondArgs} inferred for {clazztype}<> is not allowed in this context
1789 log.error(tree.clazz.pos(),
1790 "cant.apply.diamond.1",
1791 diags.fragment("diamond", clazztype.tsym),
1792 diags.fragment(subkey,
1793 invalidDiamondArgs,
1794 diags.fragment("diamond", clazztype.tsym)));
1795 }
1796 }
1797 return clazztype;
1798 }
1800 /** Creates a synthetic scope containing fake generic constructors.
1801 * Assuming that the original scope contains a constructor of the kind:
1802 * Foo(X x, Y y), where X,Y are class type-variables declared in Foo,
1803 * the synthetic scope is added a generic constructor of the kind:
1804 * <X,Y>Foo<X,Y>(X x, Y y). This is crucial in order to enable diamond
1805 * inference. The inferred return type of the synthetic constructor IS
1806 * the inferred type for the diamond operator.
1807 */
1808 private Pair<Scope, Scope> getSyntheticScopeMapping(Type ctype) {
1809 if (ctype.tag != CLASS) {
1810 return erroneousMapping;
1811 }
1812 Pair<Scope, Scope> mapping =
1813 new Pair<Scope, Scope>(ctype.tsym.members(), new Scope(ctype.tsym));
1814 List<Type> typevars = ctype.tsym.type.getTypeArguments();
1815 for (Scope.Entry e = mapping.fst.lookup(names.init);
1816 e.scope != null;
1817 e = e.next()) {
1818 MethodSymbol newConstr = (MethodSymbol) e.sym.clone(ctype.tsym);
1819 newConstr.name = names.init;
1820 List<Type> oldTypeargs = List.nil();
1821 if (newConstr.type.tag == FORALL) {
1822 oldTypeargs = ((ForAll) newConstr.type).tvars;
1823 }
1824 newConstr.type = new MethodType(newConstr.type.getParameterTypes(),
1825 new ClassType(ctype.getEnclosingType(), ctype.tsym.type.getTypeArguments(), ctype.tsym),
1826 newConstr.type.getThrownTypes(),
1827 syms.methodClass);
1828 newConstr.type = new ForAll(typevars.prependList(oldTypeargs), newConstr.type);
1829 mapping.snd.enter(newConstr);
1830 }
1831 return mapping;
1832 }
1834 private final Pair<Scope,Scope> erroneousMapping = new Pair<Scope,Scope>(null, null);
1836 /** Make an attributed null check tree.
1837 */
1838 public JCExpression makeNullCheck(JCExpression arg) {
1839 // optimization: X.this is never null; skip null check
1840 Name name = TreeInfo.name(arg);
1841 if (name == names._this || name == names._super) return arg;
1843 int optag = JCTree.NULLCHK;
1844 JCUnary tree = make.at(arg.pos).Unary(optag, arg);
1845 tree.operator = syms.nullcheck;
1846 tree.type = arg.type;
1847 return tree;
1848 }
1850 public void visitNewArray(JCNewArray tree) {
1851 Type owntype = types.createErrorType(tree.type);
1852 Type elemtype;
1853 if (tree.elemtype != null) {
1854 elemtype = attribType(tree.elemtype, env);
1855 chk.validate(tree.elemtype, env);
1856 owntype = elemtype;
1857 for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
1858 attribExpr(l.head, env, syms.intType);
1859 owntype = new ArrayType(owntype, syms.arrayClass);
1860 }
1861 } else {
1862 // we are seeing an untyped aggregate { ... }
1863 // this is allowed only if the prototype is an array
1864 if (pt.tag == ARRAY) {
1865 elemtype = types.elemtype(pt);
1866 } else {
1867 if (pt.tag != ERROR) {
1868 log.error(tree.pos(), "illegal.initializer.for.type",
1869 pt);
1870 }
1871 elemtype = types.createErrorType(pt);
1872 }
1873 }
1874 if (tree.elems != null) {
1875 attribExprs(tree.elems, env, elemtype);
1876 owntype = new ArrayType(elemtype, syms.arrayClass);
1877 }
1878 if (!types.isReifiable(elemtype))
1879 log.error(tree.pos(), "generic.array.creation");
1880 result = check(tree, owntype, VAL, pkind, pt);
1881 }
1883 public void visitParens(JCParens tree) {
1884 Type owntype = attribTree(tree.expr, env, pkind, pt);
1885 result = check(tree, owntype, pkind, pkind, pt);
1886 Symbol sym = TreeInfo.symbol(tree);
1887 if (sym != null && (sym.kind&(TYP|PCK)) != 0)
1888 log.error(tree.pos(), "illegal.start.of.type");
1889 }
1891 public void visitAssign(JCAssign tree) {
1892 Type owntype = attribTree(tree.lhs, env.dup(tree), VAR, Type.noType);
1893 Type capturedType = capture(owntype);
1894 attribExpr(tree.rhs, env, owntype);
1895 result = check(tree, capturedType, VAL, pkind, pt);
1896 }
1898 public void visitAssignop(JCAssignOp tree) {
1899 // Attribute arguments.
1900 Type owntype = attribTree(tree.lhs, env, VAR, Type.noType);
1901 Type operand = attribExpr(tree.rhs, env);
1902 // Find operator.
1903 Symbol operator = tree.operator = rs.resolveBinaryOperator(
1904 tree.pos(), tree.getTag() - JCTree.ASGOffset, env,
1905 owntype, operand);
1907 if (operator.kind == MTH) {
1908 chk.checkOperator(tree.pos(),
1909 (OperatorSymbol)operator,
1910 tree.getTag() - JCTree.ASGOffset,
1911 owntype,
1912 operand);
1913 chk.checkDivZero(tree.rhs.pos(), operator, operand);
1914 chk.checkCastable(tree.rhs.pos(),
1915 operator.type.getReturnType(),
1916 owntype);
1917 }
1918 result = check(tree, owntype, VAL, pkind, pt);
1919 }
1921 public void visitUnary(JCUnary tree) {
1922 // Attribute arguments.
1923 Type argtype = (JCTree.PREINC <= tree.getTag() && tree.getTag() <= JCTree.POSTDEC)
1924 ? attribTree(tree.arg, env, VAR, Type.noType)
1925 : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
1927 // Find operator.
1928 Symbol operator = tree.operator =
1929 rs.resolveUnaryOperator(tree.pos(), tree.getTag(), env, argtype);
1931 Type owntype = types.createErrorType(tree.type);
1932 if (operator.kind == MTH) {
1933 owntype = (JCTree.PREINC <= tree.getTag() && tree.getTag() <= JCTree.POSTDEC)
1934 ? tree.arg.type
1935 : operator.type.getReturnType();
1936 int opc = ((OperatorSymbol)operator).opcode;
1938 // If the argument is constant, fold it.
1939 if (argtype.constValue() != null) {
1940 Type ctype = cfolder.fold1(opc, argtype);
1941 if (ctype != null) {
1942 owntype = cfolder.coerce(ctype, owntype);
1944 // Remove constant types from arguments to
1945 // conserve space. The parser will fold concatenations
1946 // of string literals; the code here also
1947 // gets rid of intermediate results when some of the
1948 // operands are constant identifiers.
1949 if (tree.arg.type.tsym == syms.stringType.tsym) {
1950 tree.arg.type = syms.stringType;
1951 }
1952 }
1953 }
1954 }
1955 result = check(tree, owntype, VAL, pkind, pt);
1956 }
1958 public void visitBinary(JCBinary tree) {
1959 // Attribute arguments.
1960 Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
1961 Type right = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.rhs, env));
1963 // Find operator.
1964 Symbol operator = tree.operator =
1965 rs.resolveBinaryOperator(tree.pos(), tree.getTag(), env, left, right);
1967 Type owntype = types.createErrorType(tree.type);
1968 if (operator.kind == MTH) {
1969 owntype = operator.type.getReturnType();
1970 int opc = chk.checkOperator(tree.lhs.pos(),
1971 (OperatorSymbol)operator,
1972 tree.getTag(),
1973 left,
1974 right);
1976 // If both arguments are constants, fold them.
1977 if (left.constValue() != null && right.constValue() != null) {
1978 Type ctype = cfolder.fold2(opc, left, right);
1979 if (ctype != null) {
1980 owntype = cfolder.coerce(ctype, owntype);
1982 // Remove constant types from arguments to
1983 // conserve space. The parser will fold concatenations
1984 // of string literals; the code here also
1985 // gets rid of intermediate results when some of the
1986 // operands are constant identifiers.
1987 if (tree.lhs.type.tsym == syms.stringType.tsym) {
1988 tree.lhs.type = syms.stringType;
1989 }
1990 if (tree.rhs.type.tsym == syms.stringType.tsym) {
1991 tree.rhs.type = syms.stringType;
1992 }
1993 }
1994 }
1996 // Check that argument types of a reference ==, != are
1997 // castable to each other, (JLS???).
1998 if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
1999 if (!types.isCastable(left, right, new Warner(tree.pos()))) {
2000 log.error(tree.pos(), "incomparable.types", left, right);
2001 }
2002 }
2004 chk.checkDivZero(tree.rhs.pos(), operator, right);
2005 }
2006 result = check(tree, owntype, VAL, pkind, pt);
2007 }
2009 public void visitTypeCast(JCTypeCast tree) {
2010 Type clazztype = attribType(tree.clazz, env);
2011 chk.validate(tree.clazz, env, false);
2012 Type exprtype = attribExpr(tree.expr, env, Infer.anyPoly);
2013 Type owntype = chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
2014 if (exprtype.constValue() != null)
2015 owntype = cfolder.coerce(exprtype, owntype);
2016 result = check(tree, capture(owntype), VAL, pkind, pt);
2017 }
2019 public void visitTypeTest(JCInstanceOf tree) {
2020 Type exprtype = chk.checkNullOrRefType(
2021 tree.expr.pos(), attribExpr(tree.expr, env));
2022 Type clazztype = chk.checkReifiableReferenceType(
2023 tree.clazz.pos(), attribType(tree.clazz, env));
2024 chk.validate(tree.clazz, env, false);
2025 chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
2026 result = check(tree, syms.booleanType, VAL, pkind, pt);
2027 }
2029 public void visitIndexed(JCArrayAccess tree) {
2030 Type owntype = types.createErrorType(tree.type);
2031 Type atype = attribExpr(tree.indexed, env);
2032 attribExpr(tree.index, env, syms.intType);
2033 if (types.isArray(atype))
2034 owntype = types.elemtype(atype);
2035 else if (atype.tag != ERROR)
2036 log.error(tree.pos(), "array.req.but.found", atype);
2037 if ((pkind & VAR) == 0) owntype = capture(owntype);
2038 result = check(tree, owntype, VAR, pkind, pt);
2039 }
2041 public void visitIdent(JCIdent tree) {
2042 Symbol sym;
2043 boolean varArgs = false;
2045 // Find symbol
2046 if (pt.tag == METHOD || pt.tag == FORALL) {
2047 // If we are looking for a method, the prototype `pt' will be a
2048 // method type with the type of the call's arguments as parameters.
2049 env.info.varArgs = false;
2050 sym = rs.resolveMethod(tree.pos(), env, tree.name, pt.getParameterTypes(), pt.getTypeArguments());
2051 varArgs = env.info.varArgs;
2052 } else if (tree.sym != null && tree.sym.kind != VAR) {
2053 sym = tree.sym;
2054 } else {
2055 sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind);
2056 }
2057 tree.sym = sym;
2059 // (1) Also find the environment current for the class where
2060 // sym is defined (`symEnv').
2061 // Only for pre-tiger versions (1.4 and earlier):
2062 // (2) Also determine whether we access symbol out of an anonymous
2063 // class in a this or super call. This is illegal for instance
2064 // members since such classes don't carry a this$n link.
2065 // (`noOuterThisPath').
2066 Env<AttrContext> symEnv = env;
2067 boolean noOuterThisPath = false;
2068 if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
2069 (sym.kind & (VAR | MTH | TYP)) != 0 &&
2070 sym.owner.kind == TYP &&
2071 tree.name != names._this && tree.name != names._super) {
2073 // Find environment in which identifier is defined.
2074 while (symEnv.outer != null &&
2075 !sym.isMemberOf(symEnv.enclClass.sym, types)) {
2076 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
2077 noOuterThisPath = !allowAnonOuterThis;
2078 symEnv = symEnv.outer;
2079 }
2080 }
2082 // If symbol is a variable, ...
2083 if (sym.kind == VAR) {
2084 VarSymbol v = (VarSymbol)sym;
2086 // ..., evaluate its initializer, if it has one, and check for
2087 // illegal forward reference.
2088 checkInit(tree, env, v, false);
2090 // If symbol is a local variable accessed from an embedded
2091 // inner class check that it is final.
2092 if (v.owner.kind == MTH &&
2093 v.owner != env.info.scope.owner &&
2094 (v.flags_field & FINAL) == 0) {
2095 log.error(tree.pos(),
2096 "local.var.accessed.from.icls.needs.final",
2097 v);
2098 }
2100 // If we are expecting a variable (as opposed to a value), check
2101 // that the variable is assignable in the current environment.
2102 if (pkind == VAR)
2103 checkAssignable(tree.pos(), v, null, env);
2104 }
2106 // In a constructor body,
2107 // if symbol is a field or instance method, check that it is
2108 // not accessed before the supertype constructor is called.
2109 if ((symEnv.info.isSelfCall || noOuterThisPath) &&
2110 (sym.kind & (VAR | MTH)) != 0 &&
2111 sym.owner.kind == TYP &&
2112 (sym.flags() & STATIC) == 0) {
2113 chk.earlyRefError(tree.pos(), sym.kind == VAR ? sym : thisSym(tree.pos(), env));
2114 }
2115 Env<AttrContext> env1 = env;
2116 if (sym.kind != ERR && sym.kind != TYP && sym.owner != null && sym.owner != env1.enclClass.sym) {
2117 // If the found symbol is inaccessible, then it is
2118 // accessed through an enclosing instance. Locate this
2119 // enclosing instance:
2120 while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
2121 env1 = env1.outer;
2122 }
2123 result = checkId(tree, env1.enclClass.sym.type, sym, env, pkind, pt, varArgs);
2124 }
2126 public void visitSelect(JCFieldAccess tree) {
2127 // Determine the expected kind of the qualifier expression.
2128 int skind = 0;
2129 if (tree.name == names._this || tree.name == names._super ||
2130 tree.name == names._class)
2131 {
2132 skind = TYP;
2133 } else {
2134 if ((pkind & PCK) != 0) skind = skind | PCK;
2135 if ((pkind & TYP) != 0) skind = skind | TYP | PCK;
2136 if ((pkind & (VAL | MTH)) != 0) skind = skind | VAL | TYP;
2137 }
2139 // Attribute the qualifier expression, and determine its symbol (if any).
2140 Type site = attribTree(tree.selected, env, skind, Infer.anyPoly);
2141 if ((pkind & (PCK | TYP)) == 0)
2142 site = capture(site); // Capture field access
2144 // don't allow T.class T[].class, etc
2145 if (skind == TYP) {
2146 Type elt = site;
2147 while (elt.tag == ARRAY)
2148 elt = ((ArrayType)elt).elemtype;
2149 if (elt.tag == TYPEVAR) {
2150 log.error(tree.pos(), "type.var.cant.be.deref");
2151 result = types.createErrorType(tree.type);
2152 return;
2153 }
2154 }
2156 // If qualifier symbol is a type or `super', assert `selectSuper'
2157 // for the selection. This is relevant for determining whether
2158 // protected symbols are accessible.
2159 Symbol sitesym = TreeInfo.symbol(tree.selected);
2160 boolean selectSuperPrev = env.info.selectSuper;
2161 env.info.selectSuper =
2162 sitesym != null &&
2163 sitesym.name == names._super;
2165 // If selected expression is polymorphic, strip
2166 // type parameters and remember in env.info.tvars, so that
2167 // they can be added later (in Attr.checkId and Infer.instantiateMethod).
2168 if (tree.selected.type.tag == FORALL) {
2169 ForAll pstype = (ForAll)tree.selected.type;
2170 env.info.tvars = pstype.tvars;
2171 site = tree.selected.type = pstype.qtype;
2172 }
2174 // Determine the symbol represented by the selection.
2175 env.info.varArgs = false;
2176 Symbol sym = selectSym(tree, site, env, pt, pkind);
2177 if (sym.exists() && !isType(sym) && (pkind & (PCK | TYP)) != 0) {
2178 site = capture(site);
2179 sym = selectSym(tree, site, env, pt, pkind);
2180 }
2181 boolean varArgs = env.info.varArgs;
2182 tree.sym = sym;
2184 if (site.tag == TYPEVAR && !isType(sym) && sym.kind != ERR) {
2185 while (site.tag == TYPEVAR) site = site.getUpperBound();
2186 site = capture(site);
2187 }
2189 // If that symbol is a variable, ...
2190 if (sym.kind == VAR) {
2191 VarSymbol v = (VarSymbol)sym;
2193 // ..., evaluate its initializer, if it has one, and check for
2194 // illegal forward reference.
2195 checkInit(tree, env, v, true);
2197 // If we are expecting a variable (as opposed to a value), check
2198 // that the variable is assignable in the current environment.
2199 if (pkind == VAR)
2200 checkAssignable(tree.pos(), v, tree.selected, env);
2201 }
2203 if (sitesym != null &&
2204 sitesym.kind == VAR &&
2205 ((VarSymbol)sitesym).isResourceVariable() &&
2206 sym.kind == MTH &&
2207 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) &&
2208 env.info.lint.isEnabled(Lint.LintCategory.ARM)) {
2209 log.warning(tree, "twr.explicit.close.call");
2210 }
2212 // Disallow selecting a type from an expression
2213 if (isType(sym) && (sitesym==null || (sitesym.kind&(TYP|PCK)) == 0)) {
2214 tree.type = check(tree.selected, pt,
2215 sitesym == null ? VAL : sitesym.kind, TYP|PCK, pt);
2216 }
2218 if (isType(sitesym)) {
2219 if (sym.name == names._this) {
2220 // If `C' is the currently compiled class, check that
2221 // C.this' does not appear in a call to a super(...)
2222 if (env.info.isSelfCall &&
2223 site.tsym == env.enclClass.sym) {
2224 chk.earlyRefError(tree.pos(), sym);
2225 }
2226 } else {
2227 // Check if type-qualified fields or methods are static (JLS)
2228 if ((sym.flags() & STATIC) == 0 &&
2229 sym.name != names._super &&
2230 (sym.kind == VAR || sym.kind == MTH)) {
2231 rs.access(rs.new StaticError(sym),
2232 tree.pos(), site, sym.name, true);
2233 }
2234 }
2235 } else if (sym.kind != ERR && (sym.flags() & STATIC) != 0 && sym.name != names._class) {
2236 // If the qualified item is not a type and the selected item is static, report
2237 // a warning. Make allowance for the class of an array type e.g. Object[].class)
2238 chk.warnStatic(tree, "static.not.qualified.by.type", Kinds.kindName(sym.kind), sym.owner);
2239 }
2241 // If we are selecting an instance member via a `super', ...
2242 if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
2244 // Check that super-qualified symbols are not abstract (JLS)
2245 rs.checkNonAbstract(tree.pos(), sym);
2247 if (site.isRaw()) {
2248 // Determine argument types for site.
2249 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
2250 if (site1 != null) site = site1;
2251 }
2252 }
2254 env.info.selectSuper = selectSuperPrev;
2255 result = checkId(tree, site, sym, env, pkind, pt, varArgs);
2256 env.info.tvars = List.nil();
2257 }
2258 //where
2259 /** Determine symbol referenced by a Select expression,
2260 *
2261 * @param tree The select tree.
2262 * @param site The type of the selected expression,
2263 * @param env The current environment.
2264 * @param pt The current prototype.
2265 * @param pkind The expected kind(s) of the Select expression.
2266 */
2267 private Symbol selectSym(JCFieldAccess tree,
2268 Type site,
2269 Env<AttrContext> env,
2270 Type pt,
2271 int pkind) {
2272 DiagnosticPosition pos = tree.pos();
2273 Name name = tree.name;
2275 switch (site.tag) {
2276 case PACKAGE:
2277 return rs.access(
2278 rs.findIdentInPackage(env, site.tsym, name, pkind),
2279 pos, site, name, true);
2280 case ARRAY:
2281 case CLASS:
2282 if (pt.tag == METHOD || pt.tag == FORALL) {
2283 return rs.resolveQualifiedMethod(
2284 pos, env, site, name, pt.getParameterTypes(), pt.getTypeArguments());
2285 } else if (name == names._this || name == names._super) {
2286 return rs.resolveSelf(pos, env, site.tsym, name);
2287 } else if (name == names._class) {
2288 // In this case, we have already made sure in
2289 // visitSelect that qualifier expression is a type.
2290 Type t = syms.classType;
2291 List<Type> typeargs = allowGenerics
2292 ? List.of(types.erasure(site))
2293 : List.<Type>nil();
2294 t = new ClassType(t.getEnclosingType(), typeargs, t.tsym);
2295 return new VarSymbol(
2296 STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
2297 } else {
2298 // We are seeing a plain identifier as selector.
2299 Symbol sym = rs.findIdentInType(env, site, name, pkind);
2300 if ((pkind & ERRONEOUS) == 0)
2301 sym = rs.access(sym, pos, site, name, true);
2302 return sym;
2303 }
2304 case WILDCARD:
2305 throw new AssertionError(tree);
2306 case TYPEVAR:
2307 // Normally, site.getUpperBound() shouldn't be null.
2308 // It should only happen during memberEnter/attribBase
2309 // when determining the super type which *must* be
2310 // done before attributing the type variables. In
2311 // other words, we are seeing this illegal program:
2312 // class B<T> extends A<T.foo> {}
2313 Symbol sym = (site.getUpperBound() != null)
2314 ? selectSym(tree, capture(site.getUpperBound()), env, pt, pkind)
2315 : null;
2316 if (sym == null) {
2317 log.error(pos, "type.var.cant.be.deref");
2318 return syms.errSymbol;
2319 } else {
2320 Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
2321 rs.new AccessError(env, site, sym) :
2322 sym;
2323 rs.access(sym2, pos, site, name, true);
2324 return sym;
2325 }
2326 case ERROR:
2327 // preserve identifier names through errors
2328 return types.createErrorType(name, site.tsym, site).tsym;
2329 default:
2330 // The qualifier expression is of a primitive type -- only
2331 // .class is allowed for these.
2332 if (name == names._class) {
2333 // In this case, we have already made sure in Select that
2334 // qualifier expression is a type.
2335 Type t = syms.classType;
2336 Type arg = types.boxedClass(site).type;
2337 t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym);
2338 return new VarSymbol(
2339 STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
2340 } else {
2341 log.error(pos, "cant.deref", site);
2342 return syms.errSymbol;
2343 }
2344 }
2345 }
2347 /** Determine type of identifier or select expression and check that
2348 * (1) the referenced symbol is not deprecated
2349 * (2) the symbol's type is safe (@see checkSafe)
2350 * (3) if symbol is a variable, check that its type and kind are
2351 * compatible with the prototype and protokind.
2352 * (4) if symbol is an instance field of a raw type,
2353 * which is being assigned to, issue an unchecked warning if its
2354 * type changes under erasure.
2355 * (5) if symbol is an instance method of a raw type, issue an
2356 * unchecked warning if its argument types change under erasure.
2357 * If checks succeed:
2358 * If symbol is a constant, return its constant type
2359 * else if symbol is a method, return its result type
2360 * otherwise return its type.
2361 * Otherwise return errType.
2362 *
2363 * @param tree The syntax tree representing the identifier
2364 * @param site If this is a select, the type of the selected
2365 * expression, otherwise the type of the current class.
2366 * @param sym The symbol representing the identifier.
2367 * @param env The current environment.
2368 * @param pkind The set of expected kinds.
2369 * @param pt The expected type.
2370 */
2371 Type checkId(JCTree tree,
2372 Type site,
2373 Symbol sym,
2374 Env<AttrContext> env,
2375 int pkind,
2376 Type pt,
2377 boolean useVarargs) {
2378 if (pt.isErroneous()) return types.createErrorType(site);
2379 Type owntype; // The computed type of this identifier occurrence.
2380 switch (sym.kind) {
2381 case TYP:
2382 // For types, the computed type equals the symbol's type,
2383 // except for two situations:
2384 owntype = sym.type;
2385 if (owntype.tag == CLASS) {
2386 Type ownOuter = owntype.getEnclosingType();
2388 // (a) If the symbol's type is parameterized, erase it
2389 // because no type parameters were given.
2390 // We recover generic outer type later in visitTypeApply.
2391 if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
2392 owntype = types.erasure(owntype);
2393 }
2395 // (b) If the symbol's type is an inner class, then
2396 // we have to interpret its outer type as a superclass
2397 // of the site type. Example:
2398 //
2399 // class Tree<A> { class Visitor { ... } }
2400 // class PointTree extends Tree<Point> { ... }
2401 // ...PointTree.Visitor...
2402 //
2403 // Then the type of the last expression above is
2404 // Tree<Point>.Visitor.
2405 else if (ownOuter.tag == CLASS && site != ownOuter) {
2406 Type normOuter = site;
2407 if (normOuter.tag == CLASS)
2408 normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
2409 if (normOuter == null) // perhaps from an import
2410 normOuter = types.erasure(ownOuter);
2411 if (normOuter != ownOuter)
2412 owntype = new ClassType(
2413 normOuter, List.<Type>nil(), owntype.tsym);
2414 }
2415 }
2416 break;
2417 case VAR:
2418 VarSymbol v = (VarSymbol)sym;
2419 // Test (4): if symbol is an instance field of a raw type,
2420 // which is being assigned to, issue an unchecked warning if
2421 // its type changes under erasure.
2422 if (allowGenerics &&
2423 pkind == VAR &&
2424 v.owner.kind == TYP &&
2425 (v.flags() & STATIC) == 0 &&
2426 (site.tag == CLASS || site.tag == TYPEVAR)) {
2427 Type s = types.asOuterSuper(site, v.owner);
2428 if (s != null &&
2429 s.isRaw() &&
2430 !types.isSameType(v.type, v.erasure(types))) {
2431 chk.warnUnchecked(tree.pos(),
2432 "unchecked.assign.to.var",
2433 v, s);
2434 }
2435 }
2436 // The computed type of a variable is the type of the
2437 // variable symbol, taken as a member of the site type.
2438 owntype = (sym.owner.kind == TYP &&
2439 sym.name != names._this && sym.name != names._super)
2440 ? types.memberType(site, sym)
2441 : sym.type;
2443 if (env.info.tvars.nonEmpty()) {
2444 Type owntype1 = new ForAll(env.info.tvars, owntype);
2445 for (List<Type> l = env.info.tvars; l.nonEmpty(); l = l.tail)
2446 if (!owntype.contains(l.head)) {
2447 log.error(tree.pos(), "undetermined.type", owntype1);
2448 owntype1 = types.createErrorType(owntype1);
2449 }
2450 owntype = owntype1;
2451 }
2453 // If the variable is a constant, record constant value in
2454 // computed type.
2455 if (v.getConstValue() != null && isStaticReference(tree))
2456 owntype = owntype.constType(v.getConstValue());
2458 if (pkind == VAL) {
2459 owntype = capture(owntype); // capture "names as expressions"
2460 }
2461 break;
2462 case MTH: {
2463 JCMethodInvocation app = (JCMethodInvocation)env.tree;
2464 owntype = checkMethod(site, sym, env, app.args,
2465 pt.getParameterTypes(), pt.getTypeArguments(),
2466 env.info.varArgs);
2467 break;
2468 }
2469 case PCK: case ERR:
2470 owntype = sym.type;
2471 break;
2472 default:
2473 throw new AssertionError("unexpected kind: " + sym.kind +
2474 " in tree " + tree);
2475 }
2477 // Test (1): emit a `deprecation' warning if symbol is deprecated.
2478 // (for constructors, the error was given when the constructor was
2479 // resolved)
2480 if (sym.name != names.init &&
2481 (sym.flags() & DEPRECATED) != 0 &&
2482 (env.info.scope.owner.flags() & DEPRECATED) == 0 &&
2483 sym.outermostClass() != env.info.scope.owner.outermostClass())
2484 chk.warnDeprecated(tree.pos(), sym);
2486 if ((sym.flags() & PROPRIETARY) != 0) {
2487 if (enableSunApiLintControl)
2488 chk.warnSunApi(tree.pos(), "sun.proprietary", sym);
2489 else
2490 log.strictWarning(tree.pos(), "sun.proprietary", sym);
2491 }
2493 // Test (3): if symbol is a variable, check that its type and
2494 // kind are compatible with the prototype and protokind.
2495 return check(tree, owntype, sym.kind, pkind, pt);
2496 }
2498 /** Check that variable is initialized and evaluate the variable's
2499 * initializer, if not yet done. Also check that variable is not
2500 * referenced before it is defined.
2501 * @param tree The tree making up the variable reference.
2502 * @param env The current environment.
2503 * @param v The variable's symbol.
2504 */
2505 private void checkInit(JCTree tree,
2506 Env<AttrContext> env,
2507 VarSymbol v,
2508 boolean onlyWarning) {
2509 // System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " +
2510 // tree.pos + " " + v.pos + " " +
2511 // Resolve.isStatic(env));//DEBUG
2513 // A forward reference is diagnosed if the declaration position
2514 // of the variable is greater than the current tree position
2515 // and the tree and variable definition occur in the same class
2516 // definition. Note that writes don't count as references.
2517 // This check applies only to class and instance
2518 // variables. Local variables follow different scope rules,
2519 // and are subject to definite assignment checking.
2520 if ((env.info.enclVar == v || v.pos > tree.pos) &&
2521 v.owner.kind == TYP &&
2522 canOwnInitializer(env.info.scope.owner) &&
2523 v.owner == env.info.scope.owner.enclClass() &&
2524 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
2525 (env.tree.getTag() != JCTree.ASSIGN ||
2526 TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
2527 String suffix = (env.info.enclVar == v) ?
2528 "self.ref" : "forward.ref";
2529 if (!onlyWarning || isStaticEnumField(v)) {
2530 log.error(tree.pos(), "illegal." + suffix);
2531 } else if (useBeforeDeclarationWarning) {
2532 log.warning(tree.pos(), suffix, v);
2533 }
2534 }
2536 v.getConstValue(); // ensure initializer is evaluated
2538 checkEnumInitializer(tree, env, v);
2539 }
2541 /**
2542 * Check for illegal references to static members of enum. In
2543 * an enum type, constructors and initializers may not
2544 * reference its static members unless they are constant.
2545 *
2546 * @param tree The tree making up the variable reference.
2547 * @param env The current environment.
2548 * @param v The variable's symbol.
2549 * @see JLS 3rd Ed. (8.9 Enums)
2550 */
2551 private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
2552 // JLS 3rd Ed.:
2553 //
2554 // "It is a compile-time error to reference a static field
2555 // of an enum type that is not a compile-time constant
2556 // (15.28) from constructors, instance initializer blocks,
2557 // or instance variable initializer expressions of that
2558 // type. It is a compile-time error for the constructors,
2559 // instance initializer blocks, or instance variable
2560 // initializer expressions of an enum constant e to refer
2561 // to itself or to an enum constant of the same type that
2562 // is declared to the right of e."
2563 if (isStaticEnumField(v)) {
2564 ClassSymbol enclClass = env.info.scope.owner.enclClass();
2566 if (enclClass == null || enclClass.owner == null)
2567 return;
2569 // See if the enclosing class is the enum (or a
2570 // subclass thereof) declaring v. If not, this
2571 // reference is OK.
2572 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
2573 return;
2575 // If the reference isn't from an initializer, then
2576 // the reference is OK.
2577 if (!Resolve.isInitializer(env))
2578 return;
2580 log.error(tree.pos(), "illegal.enum.static.ref");
2581 }
2582 }
2584 /** Is the given symbol a static, non-constant field of an Enum?
2585 * Note: enum literals should not be regarded as such
2586 */
2587 private boolean isStaticEnumField(VarSymbol v) {
2588 return Flags.isEnum(v.owner) &&
2589 Flags.isStatic(v) &&
2590 !Flags.isConstant(v) &&
2591 v.name != names._class;
2592 }
2594 /** Can the given symbol be the owner of code which forms part
2595 * if class initialization? This is the case if the symbol is
2596 * a type or field, or if the symbol is the synthetic method.
2597 * owning a block.
2598 */
2599 private boolean canOwnInitializer(Symbol sym) {
2600 return
2601 (sym.kind & (VAR | TYP)) != 0 ||
2602 (sym.kind == MTH && (sym.flags() & BLOCK) != 0);
2603 }
2605 Warner noteWarner = new Warner();
2607 /**
2608 * Check that method arguments conform to its instantation.
2609 **/
2610 public Type checkMethod(Type site,
2611 Symbol sym,
2612 Env<AttrContext> env,
2613 final List<JCExpression> argtrees,
2614 List<Type> argtypes,
2615 List<Type> typeargtypes,
2616 boolean useVarargs) {
2617 // Test (5): if symbol is an instance method of a raw type, issue
2618 // an unchecked warning if its argument types change under erasure.
2619 if (allowGenerics &&
2620 (sym.flags() & STATIC) == 0 &&
2621 (site.tag == CLASS || site.tag == TYPEVAR)) {
2622 Type s = types.asOuterSuper(site, sym.owner);
2623 if (s != null && s.isRaw() &&
2624 !types.isSameTypes(sym.type.getParameterTypes(),
2625 sym.erasure(types).getParameterTypes())) {
2626 chk.warnUnchecked(env.tree.pos(),
2627 "unchecked.call.mbr.of.raw.type",
2628 sym, s);
2629 }
2630 }
2632 // Compute the identifier's instantiated type.
2633 // For methods, we need to compute the instance type by
2634 // Resolve.instantiate from the symbol's type as well as
2635 // any type arguments and value arguments.
2636 noteWarner.warned = false;
2637 Type owntype = rs.instantiate(env,
2638 site,
2639 sym,
2640 argtypes,
2641 typeargtypes,
2642 true,
2643 useVarargs,
2644 noteWarner);
2645 boolean warned = noteWarner.warned;
2647 // If this fails, something went wrong; we should not have
2648 // found the identifier in the first place.
2649 if (owntype == null) {
2650 if (!pt.isErroneous())
2651 log.error(env.tree.pos(),
2652 "internal.error.cant.instantiate",
2653 sym, site,
2654 Type.toString(pt.getParameterTypes()));
2655 owntype = types.createErrorType(site);
2656 } else {
2657 // System.out.println("call : " + env.tree);
2658 // System.out.println("method : " + owntype);
2659 // System.out.println("actuals: " + argtypes);
2660 List<Type> formals = owntype.getParameterTypes();
2661 Type last = useVarargs ? formals.last() : null;
2662 if (sym.name==names.init &&
2663 sym.owner == syms.enumSym)
2664 formals = formals.tail.tail;
2665 List<JCExpression> args = argtrees;
2666 while (formals.head != last) {
2667 JCTree arg = args.head;
2668 Warner warn = chk.convertWarner(arg.pos(), arg.type, formals.head);
2669 assertConvertible(arg, arg.type, formals.head, warn);
2670 warned |= warn.warned;
2671 args = args.tail;
2672 formals = formals.tail;
2673 }
2674 if (useVarargs) {
2675 Type varArg = types.elemtype(last);
2676 while (args.tail != null) {
2677 JCTree arg = args.head;
2678 Warner warn = chk.convertWarner(arg.pos(), arg.type, varArg);
2679 assertConvertible(arg, arg.type, varArg, warn);
2680 warned |= warn.warned;
2681 args = args.tail;
2682 }
2683 } else if ((sym.flags() & VARARGS) != 0 && allowVarargs) {
2684 // non-varargs call to varargs method
2685 Type varParam = owntype.getParameterTypes().last();
2686 Type lastArg = argtypes.last();
2687 if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) &&
2688 !types.isSameType(types.erasure(varParam), types.erasure(lastArg)))
2689 log.warning(argtrees.last().pos(), "inexact.non-varargs.call",
2690 types.elemtype(varParam),
2691 varParam);
2692 }
2694 if (warned && sym.type.tag == FORALL) {
2695 chk.warnUnchecked(env.tree.pos(),
2696 "unchecked.meth.invocation.applied",
2697 kindName(sym),
2698 sym.name,
2699 rs.methodArguments(sym.type.getParameterTypes()),
2700 rs.methodArguments(argtypes),
2701 kindName(sym.location()),
2702 sym.location());
2703 owntype = new MethodType(owntype.getParameterTypes(),
2704 types.erasure(owntype.getReturnType()),
2705 owntype.getThrownTypes(),
2706 syms.methodClass);
2707 }
2708 if (useVarargs) {
2709 JCTree tree = env.tree;
2710 Type argtype = owntype.getParameterTypes().last();
2711 if (owntype.getReturnType().tag != FORALL || warned) {
2712 chk.checkVararg(env.tree.pos(), owntype.getParameterTypes(), sym, env);
2713 }
2714 Type elemtype = types.elemtype(argtype);
2715 switch (tree.getTag()) {
2716 case JCTree.APPLY:
2717 ((JCMethodInvocation) tree).varargsElement = elemtype;
2718 break;
2719 case JCTree.NEWCLASS:
2720 ((JCNewClass) tree).varargsElement = elemtype;
2721 break;
2722 default:
2723 throw new AssertionError(""+tree);
2724 }
2725 }
2726 }
2727 return owntype;
2728 }
2730 private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) {
2731 if (types.isConvertible(actual, formal, warn))
2732 return;
2734 if (formal.isCompound()
2735 && types.isSubtype(actual, types.supertype(formal))
2736 && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn))
2737 return;
2739 if (false) {
2740 // TODO: make assertConvertible work
2741 chk.typeError(tree.pos(), diags.fragment("incompatible.types"), actual, formal);
2742 throw new AssertionError("Tree: " + tree
2743 + " actual:" + actual
2744 + " formal: " + formal);
2745 }
2746 }
2748 public void visitLiteral(JCLiteral tree) {
2749 result = check(
2750 tree, litType(tree.typetag).constType(tree.value), VAL, pkind, pt);
2751 }
2752 //where
2753 /** Return the type of a literal with given type tag.
2754 */
2755 Type litType(int tag) {
2756 return (tag == TypeTags.CLASS) ? syms.stringType : syms.typeOfTag[tag];
2757 }
2759 public void visitTypeIdent(JCPrimitiveTypeTree tree) {
2760 result = check(tree, syms.typeOfTag[tree.typetag], TYP, pkind, pt);
2761 }
2763 public void visitTypeArray(JCArrayTypeTree tree) {
2764 Type etype = attribType(tree.elemtype, env);
2765 Type type = new ArrayType(etype, syms.arrayClass);
2766 result = check(tree, type, TYP, pkind, pt);
2767 }
2769 /** Visitor method for parameterized types.
2770 * Bound checking is left until later, since types are attributed
2771 * before supertype structure is completely known
2772 */
2773 public void visitTypeApply(JCTypeApply tree) {
2774 Type owntype = types.createErrorType(tree.type);
2776 // Attribute functor part of application and make sure it's a class.
2777 Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
2779 // Attribute type parameters
2780 List<Type> actuals = attribTypes(tree.arguments, env);
2782 if (clazztype.tag == CLASS) {
2783 List<Type> formals = clazztype.tsym.type.getTypeArguments();
2785 if (actuals.length() == formals.length() || actuals.length() == 0) {
2786 List<Type> a = actuals;
2787 List<Type> f = formals;
2788 while (a.nonEmpty()) {
2789 a.head = a.head.withTypeVar(f.head);
2790 a = a.tail;
2791 f = f.tail;
2792 }
2793 // Compute the proper generic outer
2794 Type clazzOuter = clazztype.getEnclosingType();
2795 if (clazzOuter.tag == CLASS) {
2796 Type site;
2797 JCExpression clazz = TreeInfo.typeIn(tree.clazz);
2798 if (clazz.getTag() == JCTree.IDENT) {
2799 site = env.enclClass.sym.type;
2800 } else if (clazz.getTag() == JCTree.SELECT) {
2801 site = ((JCFieldAccess) clazz).selected.type;
2802 } else throw new AssertionError(""+tree);
2803 if (clazzOuter.tag == CLASS && site != clazzOuter) {
2804 if (site.tag == CLASS)
2805 site = types.asOuterSuper(site, clazzOuter.tsym);
2806 if (site == null)
2807 site = types.erasure(clazzOuter);
2808 clazzOuter = site;
2809 }
2810 }
2811 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym);
2812 } else {
2813 if (formals.length() != 0) {
2814 log.error(tree.pos(), "wrong.number.type.args",
2815 Integer.toString(formals.length()));
2816 } else {
2817 log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym);
2818 }
2819 owntype = types.createErrorType(tree.type);
2820 }
2821 }
2822 result = check(tree, owntype, TYP, pkind, pt);
2823 }
2825 public void visitTypeDisjoint(JCTypeDisjoint tree) {
2826 List<Type> componentTypes = attribTypes(tree.components, env);
2827 tree.type = result = check(tree, types.lub(componentTypes), TYP, pkind, pt);
2828 }
2830 public void visitTypeParameter(JCTypeParameter tree) {
2831 TypeVar a = (TypeVar)tree.type;
2832 Set<Type> boundSet = new HashSet<Type>();
2833 if (a.bound.isErroneous())
2834 return;
2835 List<Type> bs = types.getBounds(a);
2836 if (tree.bounds.nonEmpty()) {
2837 // accept class or interface or typevar as first bound.
2838 Type b = checkBase(bs.head, tree.bounds.head, env, false, false, false);
2839 boundSet.add(types.erasure(b));
2840 if (b.isErroneous()) {
2841 a.bound = b;
2842 }
2843 else if (b.tag == TYPEVAR) {
2844 // if first bound was a typevar, do not accept further bounds.
2845 if (tree.bounds.tail.nonEmpty()) {
2846 log.error(tree.bounds.tail.head.pos(),
2847 "type.var.may.not.be.followed.by.other.bounds");
2848 log.unrecoverableError = true;
2849 tree.bounds = List.of(tree.bounds.head);
2850 a.bound = bs.head;
2851 }
2852 } else {
2853 // if first bound was a class or interface, accept only interfaces
2854 // as further bounds.
2855 for (JCExpression bound : tree.bounds.tail) {
2856 bs = bs.tail;
2857 Type i = checkBase(bs.head, bound, env, false, true, false);
2858 if (i.isErroneous())
2859 a.bound = i;
2860 else if (i.tag == CLASS)
2861 chk.checkNotRepeated(bound.pos(), types.erasure(i), boundSet);
2862 }
2863 }
2864 }
2865 bs = types.getBounds(a);
2867 // in case of multiple bounds ...
2868 if (bs.length() > 1) {
2869 // ... the variable's bound is a class type flagged COMPOUND
2870 // (see comment for TypeVar.bound).
2871 // In this case, generate a class tree that represents the
2872 // bound class, ...
2873 JCTree extending;
2874 List<JCExpression> implementing;
2875 if ((bs.head.tsym.flags() & INTERFACE) == 0) {
2876 extending = tree.bounds.head;
2877 implementing = tree.bounds.tail;
2878 } else {
2879 extending = null;
2880 implementing = tree.bounds;
2881 }
2882 JCClassDecl cd = make.at(tree.pos).ClassDef(
2883 make.Modifiers(PUBLIC | ABSTRACT),
2884 tree.name, List.<JCTypeParameter>nil(),
2885 extending, implementing, List.<JCTree>nil());
2887 ClassSymbol c = (ClassSymbol)a.getUpperBound().tsym;
2888 assert (c.flags() & COMPOUND) != 0;
2889 cd.sym = c;
2890 c.sourcefile = env.toplevel.sourcefile;
2892 // ... and attribute the bound class
2893 c.flags_field |= UNATTRIBUTED;
2894 Env<AttrContext> cenv = enter.classEnv(cd, env);
2895 enter.typeEnvs.put(c, cenv);
2896 }
2897 }
2900 public void visitWildcard(JCWildcard tree) {
2901 //- System.err.println("visitWildcard("+tree+");");//DEBUG
2902 Type type = (tree.kind.kind == BoundKind.UNBOUND)
2903 ? syms.objectType
2904 : attribType(tree.inner, env);
2905 result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
2906 tree.kind.kind,
2907 syms.boundClass),
2908 TYP, pkind, pt);
2909 }
2911 public void visitAnnotation(JCAnnotation tree) {
2912 log.error(tree.pos(), "annotation.not.valid.for.type", pt);
2913 result = tree.type = syms.errType;
2914 }
2916 public void visitAnnotatedType(JCAnnotatedType tree) {
2917 result = tree.type = attribType(tree.getUnderlyingType(), env);
2918 }
2920 public void visitErroneous(JCErroneous tree) {
2921 if (tree.errs != null)
2922 for (JCTree err : tree.errs)
2923 attribTree(err, env, ERR, pt);
2924 result = tree.type = syms.errType;
2925 }
2927 /** Default visitor method for all other trees.
2928 */
2929 public void visitTree(JCTree tree) {
2930 throw new AssertionError();
2931 }
2933 /** Main method: attribute class definition associated with given class symbol.
2934 * reporting completion failures at the given position.
2935 * @param pos The source position at which completion errors are to be
2936 * reported.
2937 * @param c The class symbol whose definition will be attributed.
2938 */
2939 public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
2940 try {
2941 annotate.flush();
2942 attribClass(c);
2943 } catch (CompletionFailure ex) {
2944 chk.completionError(pos, ex);
2945 }
2946 }
2948 /** Attribute class definition associated with given class symbol.
2949 * @param c The class symbol whose definition will be attributed.
2950 */
2951 void attribClass(ClassSymbol c) throws CompletionFailure {
2952 if (c.type.tag == ERROR) return;
2954 // Check for cycles in the inheritance graph, which can arise from
2955 // ill-formed class files.
2956 chk.checkNonCyclic(null, c.type);
2958 Type st = types.supertype(c.type);
2959 if ((c.flags_field & Flags.COMPOUND) == 0) {
2960 // First, attribute superclass.
2961 if (st.tag == CLASS)
2962 attribClass((ClassSymbol)st.tsym);
2964 // Next attribute owner, if it is a class.
2965 if (c.owner.kind == TYP && c.owner.type.tag == CLASS)
2966 attribClass((ClassSymbol)c.owner);
2967 }
2969 // The previous operations might have attributed the current class
2970 // if there was a cycle. So we test first whether the class is still
2971 // UNATTRIBUTED.
2972 if ((c.flags_field & UNATTRIBUTED) != 0) {
2973 c.flags_field &= ~UNATTRIBUTED;
2975 // Get environment current at the point of class definition.
2976 Env<AttrContext> env = enter.typeEnvs.get(c);
2978 // The info.lint field in the envs stored in enter.typeEnvs is deliberately uninitialized,
2979 // because the annotations were not available at the time the env was created. Therefore,
2980 // we look up the environment chain for the first enclosing environment for which the
2981 // lint value is set. Typically, this is the parent env, but might be further if there
2982 // are any envs created as a result of TypeParameter nodes.
2983 Env<AttrContext> lintEnv = env;
2984 while (lintEnv.info.lint == null)
2985 lintEnv = lintEnv.next;
2987 // Having found the enclosing lint value, we can initialize the lint value for this class
2988 env.info.lint = lintEnv.info.lint.augment(c.attributes_field, c.flags());
2990 Lint prevLint = chk.setLint(env.info.lint);
2991 JavaFileObject prev = log.useSource(c.sourcefile);
2993 try {
2994 // java.lang.Enum may not be subclassed by a non-enum
2995 if (st.tsym == syms.enumSym &&
2996 ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
2997 log.error(env.tree.pos(), "enum.no.subclassing");
2999 // Enums may not be extended by source-level classes
3000 if (st.tsym != null &&
3001 ((st.tsym.flags_field & Flags.ENUM) != 0) &&
3002 ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0) &&
3003 !target.compilerBootstrap(c)) {
3004 log.error(env.tree.pos(), "enum.types.not.extensible");
3005 }
3006 attribClassBody(env, c);
3008 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
3009 } finally {
3010 log.useSource(prev);
3011 chk.setLint(prevLint);
3012 }
3014 }
3015 }
3017 public void visitImport(JCImport tree) {
3018 // nothing to do
3019 }
3021 /** Finish the attribution of a class. */
3022 private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
3023 JCClassDecl tree = (JCClassDecl)env.tree;
3024 assert c == tree.sym;
3026 // Validate annotations
3027 chk.validateAnnotations(tree.mods.annotations, c);
3029 // Validate type parameters, supertype and interfaces.
3030 attribBounds(tree.typarams);
3031 if (!c.isAnonymous()) {
3032 //already checked if anonymous
3033 chk.validate(tree.typarams, env);
3034 chk.validate(tree.extending, env);
3035 chk.validate(tree.implementing, env);
3036 }
3038 // If this is a non-abstract class, check that it has no abstract
3039 // methods or unimplemented methods of an implemented interface.
3040 if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
3041 if (!relax)
3042 chk.checkAllDefined(tree.pos(), c);
3043 }
3045 if ((c.flags() & ANNOTATION) != 0) {
3046 if (tree.implementing.nonEmpty())
3047 log.error(tree.implementing.head.pos(),
3048 "cant.extend.intf.annotation");
3049 if (tree.typarams.nonEmpty())
3050 log.error(tree.typarams.head.pos(),
3051 "intf.annotation.cant.have.type.params");
3052 } else {
3053 // Check that all extended classes and interfaces
3054 // are compatible (i.e. no two define methods with same arguments
3055 // yet different return types). (JLS 8.4.6.3)
3056 chk.checkCompatibleSupertypes(tree.pos(), c.type);
3057 }
3059 // Check that class does not import the same parameterized interface
3060 // with two different argument lists.
3061 chk.checkClassBounds(tree.pos(), c.type);
3063 tree.type = c.type;
3065 boolean assertsEnabled = false;
3066 assert assertsEnabled = true;
3067 if (assertsEnabled) {
3068 for (List<JCTypeParameter> l = tree.typarams;
3069 l.nonEmpty(); l = l.tail)
3070 assert env.info.scope.lookup(l.head.name).scope != null;
3071 }
3073 // Check that a generic class doesn't extend Throwable
3074 if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
3075 log.error(tree.extending.pos(), "generic.throwable");
3077 // Check that all methods which implement some
3078 // method conform to the method they implement.
3079 chk.checkImplementations(tree);
3081 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
3082 // Attribute declaration
3083 attribStat(l.head, env);
3084 // Check that declarations in inner classes are not static (JLS 8.1.2)
3085 // Make an exception for static constants.
3086 if (c.owner.kind != PCK &&
3087 ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
3088 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
3089 Symbol sym = null;
3090 if (l.head.getTag() == JCTree.VARDEF) sym = ((JCVariableDecl) l.head).sym;
3091 if (sym == null ||
3092 sym.kind != VAR ||
3093 ((VarSymbol) sym).getConstValue() == null)
3094 log.error(l.head.pos(), "icls.cant.have.static.decl");
3095 }
3096 }
3098 // Check for cycles among non-initial constructors.
3099 chk.checkCyclicConstructors(tree);
3101 // Check for cycles among annotation elements.
3102 chk.checkNonCyclicElements(tree);
3104 // Check for proper use of serialVersionUID
3105 if (env.info.lint.isEnabled(Lint.LintCategory.SERIAL) &&
3106 isSerializable(c) &&
3107 (c.flags() & Flags.ENUM) == 0 &&
3108 (c.flags() & ABSTRACT) == 0) {
3109 checkSerialVersionUID(tree, c);
3110 }
3112 // Check type annotations applicability rules
3113 validateTypeAnnotations(tree);
3114 }
3115 // where
3116 /** check if a class is a subtype of Serializable, if that is available. */
3117 private boolean isSerializable(ClassSymbol c) {
3118 try {
3119 syms.serializableType.complete();
3120 }
3121 catch (CompletionFailure e) {
3122 return false;
3123 }
3124 return types.isSubtype(c.type, syms.serializableType);
3125 }
3127 /** Check that an appropriate serialVersionUID member is defined. */
3128 private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
3130 // check for presence of serialVersionUID
3131 Scope.Entry e = c.members().lookup(names.serialVersionUID);
3132 while (e.scope != null && e.sym.kind != VAR) e = e.next();
3133 if (e.scope == null) {
3134 log.warning(Lint.LintCategory.SERIAL,
3135 tree.pos(), "missing.SVUID", c);
3136 return;
3137 }
3139 // check that it is static final
3140 VarSymbol svuid = (VarSymbol)e.sym;
3141 if ((svuid.flags() & (STATIC | FINAL)) !=
3142 (STATIC | FINAL))
3143 log.warning(Lint.LintCategory.SERIAL,
3144 TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c);
3146 // check that it is long
3147 else if (svuid.type.tag != TypeTags.LONG)
3148 log.warning(Lint.LintCategory.SERIAL,
3149 TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c);
3151 // check constant
3152 else if (svuid.getConstValue() == null)
3153 log.warning(Lint.LintCategory.SERIAL,
3154 TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c);
3155 }
3157 private Type capture(Type type) {
3158 return types.capture(type);
3159 }
3161 private void validateTypeAnnotations(JCTree tree) {
3162 tree.accept(typeAnnotationsValidator);
3163 }
3164 //where
3165 private final JCTree.Visitor typeAnnotationsValidator =
3166 new TreeScanner() {
3167 public void visitAnnotation(JCAnnotation tree) {
3168 if (tree instanceof JCTypeAnnotation) {
3169 chk.validateTypeAnnotation((JCTypeAnnotation)tree, false);
3170 }
3171 super.visitAnnotation(tree);
3172 }
3173 public void visitTypeParameter(JCTypeParameter tree) {
3174 chk.validateTypeAnnotations(tree.annotations, true);
3175 // don't call super. skip type annotations
3176 scan(tree.bounds);
3177 }
3178 public void visitMethodDef(JCMethodDecl tree) {
3179 // need to check static methods
3180 if ((tree.sym.flags() & Flags.STATIC) != 0) {
3181 for (JCTypeAnnotation a : tree.receiverAnnotations) {
3182 if (chk.isTypeAnnotation(a, false))
3183 log.error(a.pos(), "annotation.type.not.applicable");
3184 }
3185 }
3186 super.visitMethodDef(tree);
3187 }
3188 };
3189 }