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