Thu, 25 Feb 2010 11:04:11 -0800
6929645: Address various findbugs warnings in langtools
Reviewed-by: jjg
1 /*
2 * Copyright 1999-2009 Sun Microsystems, Inc. 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. Sun designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
22 * CA 95054 USA or visit www.sun.com if you need additional information or
23 * have any 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 API supported by Sun Microsystems. If
63 * 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 Check chk;
76 final MemberEnter memberEnter;
77 final TreeMaker make;
78 final ConstFold cfolder;
79 final Enter enter;
80 final Target target;
81 final Types types;
82 final JCDiagnostic.Factory diags;
83 final Annotate annotate;
85 public static Attr instance(Context context) {
86 Attr instance = context.get(attrKey);
87 if (instance == null)
88 instance = new Attr(context);
89 return instance;
90 }
92 protected Attr(Context context) {
93 context.put(attrKey, this);
95 names = Names.instance(context);
96 log = Log.instance(context);
97 syms = Symtab.instance(context);
98 rs = Resolve.instance(context);
99 chk = Check.instance(context);
100 memberEnter = MemberEnter.instance(context);
101 make = TreeMaker.instance(context);
102 enter = Enter.instance(context);
103 cfolder = ConstFold.instance(context);
104 target = Target.instance(context);
105 types = Types.instance(context);
106 diags = JCDiagnostic.Factory.instance(context);
107 annotate = Annotate.instance(context);
109 Options options = Options.instance(context);
111 Source source = Source.instance(context);
112 allowGenerics = source.allowGenerics();
113 allowVarargs = source.allowVarargs();
114 allowEnums = source.allowEnums();
115 allowBoxing = source.allowBoxing();
116 allowCovariantReturns = source.allowCovariantReturns();
117 allowAnonOuterThis = source.allowAnonOuterThis();
118 allowStringsInSwitch = source.allowStringsInSwitch();
119 sourceName = source.name;
120 relax = (options.get("-retrofit") != null ||
121 options.get("-relax") != null);
122 useBeforeDeclarationWarning = options.get("useBeforeDeclarationWarning") != null;
123 allowInvokedynamic = options.get("invokedynamic") != null;
124 enableSunApiLintControl = options.get("enableSunApiLintControl") != null;
125 }
127 /** Switch: relax some constraints for retrofit mode.
128 */
129 boolean relax;
131 /** Switch: support generics?
132 */
133 boolean allowGenerics;
135 /** Switch: allow variable-arity methods.
136 */
137 boolean allowVarargs;
139 /** Switch: support enums?
140 */
141 boolean allowEnums;
143 /** Switch: support boxing and unboxing?
144 */
145 boolean allowBoxing;
147 /** Switch: support covariant result types?
148 */
149 boolean allowCovariantReturns;
151 /** Switch: allow references to surrounding object from anonymous
152 * objects during constructor call?
153 */
154 boolean allowAnonOuterThis;
156 /** Switch: allow invokedynamic syntax
157 */
158 boolean allowInvokedynamic;
160 /**
161 * Switch: warn about use of variable before declaration?
162 * RFE: 6425594
163 */
164 boolean useBeforeDeclarationWarning;
166 /**
167 * Switch: allow lint infrastructure to control Sun proprietary
168 * API warnings.
169 */
170 boolean enableSunApiLintControl;
172 /**
173 * Switch: allow strings in switch?
174 */
175 boolean allowStringsInSwitch;
177 /**
178 * Switch: name of source level; used for error reporting.
179 */
180 String sourceName;
182 /** Check kind and type of given tree against protokind and prototype.
183 * If check succeeds, store type in tree and return it.
184 * If check fails, store errType in tree and return it.
185 * No checks are performed if the prototype is a method type.
186 * It is not necessary in this case since we know that kind and type
187 * are correct.
188 *
189 * @param tree The tree whose kind and type is checked
190 * @param owntype The computed type of the tree
191 * @param ownkind The computed kind of the tree
192 * @param pkind The expected kind (or: protokind) of the tree
193 * @param pt The expected type (or: prototype) of the tree
194 */
195 Type check(JCTree tree, Type owntype, int ownkind, int pkind, Type pt) {
196 if (owntype.tag != ERROR && pt.tag != METHOD && pt.tag != FORALL) {
197 if ((ownkind & ~pkind) == 0) {
198 owntype = chk.checkType(tree.pos(), owntype, pt);
199 } else {
200 log.error(tree.pos(), "unexpected.type",
201 kindNames(pkind),
202 kindName(ownkind));
203 owntype = types.createErrorType(owntype);
204 }
205 }
206 tree.type = owntype;
207 return owntype;
208 }
210 Type checkReturn(JCTree tree, Type owntype, int ownkind, int pkind, Type pt) {
211 if (owntype.tag != ERROR && pt.tag != METHOD && pt.tag != FORALL) {
212 if ((ownkind & ~pkind) == 0) {
213 owntype = chk.checkReturnType(tree.pos(), owntype, pt);
214 } else {
215 log.error(tree.pos(), "unexpected.type",
216 kindNames(pkind),
217 kindName(ownkind));
218 owntype = types.createErrorType(owntype);
219 }
220 }
221 tree.type = owntype;
222 return owntype;
223 }
225 /** Is given blank final variable assignable, i.e. in a scope where it
226 * may be assigned to even though it is final?
227 * @param v The blank final variable.
228 * @param env The current environment.
229 */
230 boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
231 Symbol owner = env.info.scope.owner;
232 // owner refers to the innermost variable, method or
233 // initializer block declaration at this point.
234 return
235 v.owner == owner
236 ||
237 ((owner.name == names.init || // i.e. we are in a constructor
238 owner.kind == VAR || // i.e. we are in a variable initializer
239 (owner.flags() & BLOCK) != 0) // i.e. we are in an initializer block
240 &&
241 v.owner == owner.owner
242 &&
243 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
244 }
246 /** Check that variable can be assigned to.
247 * @param pos The current source code position.
248 * @param v The assigned varaible
249 * @param base If the variable is referred to in a Select, the part
250 * to the left of the `.', null otherwise.
251 * @param env The current environment.
252 */
253 void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
254 if ((v.flags() & FINAL) != 0 &&
255 ((v.flags() & HASINIT) != 0
256 ||
257 !((base == null ||
258 (base.getTag() == JCTree.IDENT && TreeInfo.name(base) == names._this)) &&
259 isAssignableAsBlankFinal(v, env)))) {
260 log.error(pos, "cant.assign.val.to.final.var", v);
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 } finally {
346 breakTree = null;
347 log.useSource(prev);
348 }
349 return env;
350 }
352 public Env<AttrContext> attribStatToTree(JCTree stmt, Env<AttrContext> env, JCTree tree) {
353 breakTree = tree;
354 JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
355 try {
356 attribStat(stmt, env);
357 } catch (BreakAttr b) {
358 return b.env;
359 } finally {
360 breakTree = null;
361 log.useSource(prev);
362 }
363 return env;
364 }
366 private JCTree breakTree = null;
368 private static class BreakAttr extends RuntimeException {
369 static final long serialVersionUID = -6924771130405446405L;
370 private Env<AttrContext> env;
371 private BreakAttr(Env<AttrContext> env) {
372 this.env = env;
373 }
374 }
377 /* ************************************************************************
378 * Visitor methods
379 *************************************************************************/
381 /** Visitor argument: the current environment.
382 */
383 Env<AttrContext> env;
385 /** Visitor argument: the currently expected proto-kind.
386 */
387 int pkind;
389 /** Visitor argument: the currently expected proto-type.
390 */
391 Type pt;
393 /** Visitor result: the computed type.
394 */
395 Type result;
397 /** Visitor method: attribute a tree, catching any completion failure
398 * exceptions. Return the tree's type.
399 *
400 * @param tree The tree to be visited.
401 * @param env The environment visitor argument.
402 * @param pkind The protokind visitor argument.
403 * @param pt The prototype visitor argument.
404 */
405 Type attribTree(JCTree tree, Env<AttrContext> env, int pkind, Type pt) {
406 Env<AttrContext> prevEnv = this.env;
407 int prevPkind = this.pkind;
408 Type prevPt = this.pt;
409 try {
410 this.env = env;
411 this.pkind = pkind;
412 this.pt = pt;
413 tree.accept(this);
414 if (tree == breakTree)
415 throw new BreakAttr(env);
416 return result;
417 } catch (CompletionFailure ex) {
418 tree.type = syms.errType;
419 return chk.completionError(tree.pos(), ex);
420 } finally {
421 this.env = prevEnv;
422 this.pkind = prevPkind;
423 this.pt = prevPt;
424 }
425 }
427 /** Derived visitor method: attribute an expression tree.
428 */
429 public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) {
430 return attribTree(tree, env, VAL, pt.tag != ERROR ? pt : Type.noType);
431 }
433 /** Derived visitor method: attribute an expression tree with
434 * no constraints on the computed type.
435 */
436 Type attribExpr(JCTree tree, Env<AttrContext> env) {
437 return attribTree(tree, env, VAL, Type.noType);
438 }
440 /** Derived visitor method: attribute a type tree.
441 */
442 Type attribType(JCTree tree, Env<AttrContext> env) {
443 Type result = attribType(tree, env, Type.noType);
444 return result;
445 }
447 /** Derived visitor method: attribute a type tree.
448 */
449 Type attribType(JCTree tree, Env<AttrContext> env, Type pt) {
450 Type result = attribTree(tree, env, TYP, pt);
451 return result;
452 }
454 /** Derived visitor method: attribute a statement or definition tree.
455 */
456 public Type attribStat(JCTree tree, Env<AttrContext> env) {
457 return attribTree(tree, env, NIL, Type.noType);
458 }
460 /** Attribute a list of expressions, returning a list of types.
461 */
462 List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) {
463 ListBuffer<Type> ts = new ListBuffer<Type>();
464 for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
465 ts.append(attribExpr(l.head, env, pt));
466 return ts.toList();
467 }
469 /** Attribute a list of statements, returning nothing.
470 */
471 <T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) {
472 for (List<T> l = trees; l.nonEmpty(); l = l.tail)
473 attribStat(l.head, env);
474 }
476 /** Attribute the arguments in a method call, returning a list of types.
477 */
478 List<Type> attribArgs(List<JCExpression> trees, Env<AttrContext> env) {
479 ListBuffer<Type> argtypes = new ListBuffer<Type>();
480 for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
481 argtypes.append(chk.checkNonVoid(
482 l.head.pos(), types.upperBound(attribTree(l.head, env, VAL, Infer.anyPoly))));
483 return argtypes.toList();
484 }
486 /** Attribute a type argument list, returning a list of types.
487 * Caller is responsible for calling checkRefTypes.
488 */
489 List<Type> attribAnyTypes(List<JCExpression> trees, Env<AttrContext> env) {
490 ListBuffer<Type> argtypes = new ListBuffer<Type>();
491 for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
492 argtypes.append(attribType(l.head, env));
493 return argtypes.toList();
494 }
496 /** Attribute a type argument list, returning a list of types.
497 * Check that all the types are references.
498 */
499 List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
500 List<Type> types = attribAnyTypes(trees, env);
501 return chk.checkRefTypes(trees, types);
502 }
504 /**
505 * Attribute type variables (of generic classes or methods).
506 * Compound types are attributed later in attribBounds.
507 * @param typarams the type variables to enter
508 * @param env the current environment
509 */
510 void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env) {
511 for (JCTypeParameter tvar : typarams) {
512 TypeVar a = (TypeVar)tvar.type;
513 a.tsym.flags_field |= UNATTRIBUTED;
514 a.bound = Type.noType;
515 if (!tvar.bounds.isEmpty()) {
516 List<Type> bounds = List.of(attribType(tvar.bounds.head, env));
517 for (JCExpression bound : tvar.bounds.tail)
518 bounds = bounds.prepend(attribType(bound, env));
519 types.setBounds(a, bounds.reverse());
520 } else {
521 // if no bounds are given, assume a single bound of
522 // java.lang.Object.
523 types.setBounds(a, List.of(syms.objectType));
524 }
525 a.tsym.flags_field &= ~UNATTRIBUTED;
526 }
527 for (JCTypeParameter tvar : typarams)
528 chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
529 attribStats(typarams, env);
530 }
532 void attribBounds(List<JCTypeParameter> typarams) {
533 for (JCTypeParameter typaram : typarams) {
534 Type bound = typaram.type.getUpperBound();
535 if (bound != null && bound.tsym instanceof ClassSymbol) {
536 ClassSymbol c = (ClassSymbol)bound.tsym;
537 if ((c.flags_field & COMPOUND) != 0) {
538 assert (c.flags_field & UNATTRIBUTED) != 0 : c;
539 attribClass(typaram.pos(), c);
540 }
541 }
542 }
543 }
545 /**
546 * Attribute the type references in a list of annotations.
547 */
548 void attribAnnotationTypes(List<JCAnnotation> annotations,
549 Env<AttrContext> env) {
550 for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
551 JCAnnotation a = al.head;
552 attribType(a.annotationType, env);
553 }
554 }
556 /** Attribute type reference in an `extends' or `implements' clause.
557 *
558 * @param tree The tree making up the type reference.
559 * @param env The environment current at the reference.
560 * @param classExpected true if only a class is expected here.
561 * @param interfaceExpected true if only an interface is expected here.
562 */
563 Type attribBase(JCTree tree,
564 Env<AttrContext> env,
565 boolean classExpected,
566 boolean interfaceExpected,
567 boolean checkExtensible) {
568 Type t = attribType(tree, env);
569 return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible);
570 }
571 Type checkBase(Type t,
572 JCTree tree,
573 Env<AttrContext> env,
574 boolean classExpected,
575 boolean interfaceExpected,
576 boolean checkExtensible) {
577 if (t.tag == TYPEVAR && !classExpected && !interfaceExpected) {
578 // check that type variable is already visible
579 if (t.getUpperBound() == null) {
580 log.error(tree.pos(), "illegal.forward.ref");
581 return types.createErrorType(t);
582 }
583 } else {
584 t = chk.checkClassType(tree.pos(), t, checkExtensible|!allowGenerics);
585 }
586 if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) {
587 log.error(tree.pos(), "intf.expected.here");
588 // return errType is necessary since otherwise there might
589 // be undetected cycles which cause attribution to loop
590 return types.createErrorType(t);
591 } else if (checkExtensible &&
592 classExpected &&
593 (t.tsym.flags() & INTERFACE) != 0) {
594 log.error(tree.pos(), "no.intf.expected.here");
595 return types.createErrorType(t);
596 }
597 if (checkExtensible &&
598 ((t.tsym.flags() & FINAL) != 0)) {
599 log.error(tree.pos(),
600 "cant.inherit.from.final", t.tsym);
601 }
602 chk.checkNonCyclic(tree.pos(), t);
603 return t;
604 }
606 public void visitClassDef(JCClassDecl tree) {
607 // Local classes have not been entered yet, so we need to do it now:
608 if ((env.info.scope.owner.kind & (VAR | MTH)) != 0)
609 enter.classEnter(tree, env);
611 ClassSymbol c = tree.sym;
612 if (c == null) {
613 // exit in case something drastic went wrong during enter.
614 result = null;
615 } else {
616 // make sure class has been completed:
617 c.complete();
619 // If this class appears as an anonymous class
620 // in a superclass constructor call where
621 // no explicit outer instance is given,
622 // disable implicit outer instance from being passed.
623 // (This would be an illegal access to "this before super").
624 if (env.info.isSelfCall &&
625 env.tree.getTag() == JCTree.NEWCLASS &&
626 ((JCNewClass) env.tree).encl == null)
627 {
628 c.flags_field |= NOOUTERTHIS;
629 }
630 attribClass(tree.pos(), c);
631 result = tree.type = c.type;
632 }
633 }
635 public void visitMethodDef(JCMethodDecl tree) {
636 MethodSymbol m = tree.sym;
638 Lint lint = env.info.lint.augment(m.attributes_field, m.flags());
639 Lint prevLint = chk.setLint(lint);
640 try {
641 chk.checkDeprecatedAnnotation(tree.pos(), m);
643 attribBounds(tree.typarams);
645 // If we override any other methods, check that we do so properly.
646 // JLS ???
647 chk.checkOverride(tree, m);
649 // Create a new environment with local scope
650 // for attributing the method.
651 Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
653 localEnv.info.lint = lint;
655 // Enter all type parameters into the local method scope.
656 for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
657 localEnv.info.scope.enterIfAbsent(l.head.type.tsym);
659 ClassSymbol owner = env.enclClass.sym;
660 if ((owner.flags() & ANNOTATION) != 0 &&
661 tree.params.nonEmpty())
662 log.error(tree.params.head.pos(),
663 "intf.annotation.members.cant.have.params");
665 // Attribute all value parameters.
666 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
667 attribStat(l.head, localEnv);
668 }
670 // Check that type parameters are well-formed.
671 chk.validate(tree.typarams, localEnv);
672 if ((owner.flags() & ANNOTATION) != 0 &&
673 tree.typarams.nonEmpty())
674 log.error(tree.typarams.head.pos(),
675 "intf.annotation.members.cant.have.type.params");
677 // Check that result type is well-formed.
678 chk.validate(tree.restype, localEnv);
679 if ((owner.flags() & ANNOTATION) != 0)
680 chk.validateAnnotationType(tree.restype);
682 if ((owner.flags() & ANNOTATION) != 0)
683 chk.validateAnnotationMethod(tree.pos(), m);
685 // Check that all exceptions mentioned in the throws clause extend
686 // java.lang.Throwable.
687 if ((owner.flags() & ANNOTATION) != 0 && tree.thrown.nonEmpty())
688 log.error(tree.thrown.head.pos(),
689 "throws.not.allowed.in.intf.annotation");
690 for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
691 chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
693 if (tree.body == null) {
694 // Empty bodies are only allowed for
695 // abstract, native, or interface methods, or for methods
696 // in a retrofit signature class.
697 if ((owner.flags() & INTERFACE) == 0 &&
698 (tree.mods.flags & (ABSTRACT | NATIVE)) == 0 &&
699 !relax)
700 log.error(tree.pos(), "missing.meth.body.or.decl.abstract");
701 if (tree.defaultValue != null) {
702 if ((owner.flags() & ANNOTATION) == 0)
703 log.error(tree.pos(),
704 "default.allowed.in.intf.annotation.member");
705 }
706 } else if ((owner.flags() & INTERFACE) != 0) {
707 log.error(tree.body.pos(), "intf.meth.cant.have.body");
708 } else if ((tree.mods.flags & ABSTRACT) != 0) {
709 log.error(tree.pos(), "abstract.meth.cant.have.body");
710 } else if ((tree.mods.flags & NATIVE) != 0) {
711 log.error(tree.pos(), "native.meth.cant.have.body");
712 } else {
713 // Add an implicit super() call unless an explicit call to
714 // super(...) or this(...) is given
715 // or we are compiling class java.lang.Object.
716 if (tree.name == names.init && owner.type != syms.objectType) {
717 JCBlock body = tree.body;
718 if (body.stats.isEmpty() ||
719 !TreeInfo.isSelfCall(body.stats.head)) {
720 body.stats = body.stats.
721 prepend(memberEnter.SuperCall(make.at(body.pos),
722 List.<Type>nil(),
723 List.<JCVariableDecl>nil(),
724 false));
725 } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
726 (tree.mods.flags & GENERATEDCONSTR) == 0 &&
727 TreeInfo.isSuperCall(body.stats.head)) {
728 // enum constructors are not allowed to call super
729 // directly, so make sure there aren't any super calls
730 // in enum constructors, except in the compiler
731 // generated one.
732 log.error(tree.body.stats.head.pos(),
733 "call.to.super.not.allowed.in.enum.ctor",
734 env.enclClass.sym);
735 }
736 }
738 // Attribute method body.
739 attribStat(tree.body, localEnv);
740 }
741 localEnv.info.scope.leave();
742 result = tree.type = m.type;
743 chk.validateAnnotations(tree.mods.annotations, m);
744 }
745 finally {
746 chk.setLint(prevLint);
747 }
748 }
750 public void visitVarDef(JCVariableDecl tree) {
751 // Local variables have not been entered yet, so we need to do it now:
752 if (env.info.scope.owner.kind == MTH) {
753 if (tree.sym != null) {
754 // parameters have already been entered
755 env.info.scope.enter(tree.sym);
756 } else {
757 memberEnter.memberEnter(tree, env);
758 annotate.flush();
759 }
760 }
762 VarSymbol v = tree.sym;
763 Lint lint = env.info.lint.augment(v.attributes_field, v.flags());
764 Lint prevLint = chk.setLint(lint);
766 // Check that the variable's declared type is well-formed.
767 chk.validate(tree.vartype, env);
769 try {
770 chk.checkDeprecatedAnnotation(tree.pos(), v);
772 if (tree.init != null) {
773 if ((v.flags_field & FINAL) != 0 && tree.init.getTag() != JCTree.NEWCLASS) {
774 // In this case, `v' is final. Ensure that it's initializer is
775 // evaluated.
776 v.getConstValue(); // ensure initializer is evaluated
777 } else {
778 // Attribute initializer in a new environment
779 // with the declared variable as owner.
780 // Check that initializer conforms to variable's declared type.
781 Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
782 initEnv.info.lint = lint;
783 // In order to catch self-references, we set the variable's
784 // declaration position to maximal possible value, effectively
785 // marking the variable as undefined.
786 initEnv.info.enclVar = v;
787 attribExpr(tree.init, initEnv, v.type);
788 }
789 }
790 result = tree.type = v.type;
791 chk.validateAnnotations(tree.mods.annotations, v);
792 }
793 finally {
794 chk.setLint(prevLint);
795 }
796 }
798 public void visitSkip(JCSkip tree) {
799 result = null;
800 }
802 public void visitBlock(JCBlock tree) {
803 if (env.info.scope.owner.kind == TYP) {
804 // Block is a static or instance initializer;
805 // let the owner of the environment be a freshly
806 // created BLOCK-method.
807 Env<AttrContext> localEnv =
808 env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
809 localEnv.info.scope.owner =
810 new MethodSymbol(tree.flags | BLOCK, names.empty, null,
811 env.info.scope.owner);
812 if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
813 attribStats(tree.stats, localEnv);
814 } else {
815 // Create a new local environment with a local scope.
816 Env<AttrContext> localEnv =
817 env.dup(tree, env.info.dup(env.info.scope.dup()));
818 attribStats(tree.stats, localEnv);
819 localEnv.info.scope.leave();
820 }
821 result = null;
822 }
824 public void visitDoLoop(JCDoWhileLoop tree) {
825 attribStat(tree.body, env.dup(tree));
826 attribExpr(tree.cond, env, syms.booleanType);
827 result = null;
828 }
830 public void visitWhileLoop(JCWhileLoop tree) {
831 attribExpr(tree.cond, env, syms.booleanType);
832 attribStat(tree.body, env.dup(tree));
833 result = null;
834 }
836 public void visitForLoop(JCForLoop tree) {
837 Env<AttrContext> loopEnv =
838 env.dup(env.tree, env.info.dup(env.info.scope.dup()));
839 attribStats(tree.init, loopEnv);
840 if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType);
841 loopEnv.tree = tree; // before, we were not in loop!
842 attribStats(tree.step, loopEnv);
843 attribStat(tree.body, loopEnv);
844 loopEnv.info.scope.leave();
845 result = null;
846 }
848 public void visitForeachLoop(JCEnhancedForLoop tree) {
849 Env<AttrContext> loopEnv =
850 env.dup(env.tree, env.info.dup(env.info.scope.dup()));
851 attribStat(tree.var, loopEnv);
852 Type exprType = types.upperBound(attribExpr(tree.expr, loopEnv));
853 chk.checkNonVoid(tree.pos(), exprType);
854 Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
855 if (elemtype == null) {
856 // or perhaps expr implements Iterable<T>?
857 Type base = types.asSuper(exprType, syms.iterableType.tsym);
858 if (base == null) {
859 log.error(tree.expr.pos(), "foreach.not.applicable.to.type");
860 elemtype = types.createErrorType(exprType);
861 } else {
862 List<Type> iterableParams = base.allparams();
863 elemtype = iterableParams.isEmpty()
864 ? syms.objectType
865 : types.upperBound(iterableParams.head);
866 }
867 }
868 chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
869 loopEnv.tree = tree; // before, we were not in loop!
870 attribStat(tree.body, loopEnv);
871 loopEnv.info.scope.leave();
872 result = null;
873 }
875 public void visitLabelled(JCLabeledStatement tree) {
876 // Check that label is not used in an enclosing statement
877 Env<AttrContext> env1 = env;
878 while (env1 != null && env1.tree.getTag() != JCTree.CLASSDEF) {
879 if (env1.tree.getTag() == JCTree.LABELLED &&
880 ((JCLabeledStatement) env1.tree).label == tree.label) {
881 log.error(tree.pos(), "label.already.in.use",
882 tree.label);
883 break;
884 }
885 env1 = env1.next;
886 }
888 attribStat(tree.body, env.dup(tree));
889 result = null;
890 }
892 public void visitSwitch(JCSwitch tree) {
893 Type seltype = attribExpr(tree.selector, env);
895 Env<AttrContext> switchEnv =
896 env.dup(tree, env.info.dup(env.info.scope.dup()));
898 boolean enumSwitch =
899 allowEnums &&
900 (seltype.tsym.flags() & Flags.ENUM) != 0;
901 boolean stringSwitch = false;
902 if (types.isSameType(seltype, syms.stringType)) {
903 if (allowStringsInSwitch) {
904 stringSwitch = true;
905 } else {
906 log.error(tree.selector.pos(), "string.switch.not.supported.in.source", sourceName);
907 }
908 }
909 if (!enumSwitch && !stringSwitch)
910 seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType);
912 // Attribute all cases and
913 // check that there are no duplicate case labels or default clauses.
914 Set<Object> labels = new HashSet<Object>(); // The set of case labels.
915 boolean hasDefault = false; // Is there a default label?
916 for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
917 JCCase c = l.head;
918 Env<AttrContext> caseEnv =
919 switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup()));
920 if (c.pat != null) {
921 if (enumSwitch) {
922 Symbol sym = enumConstant(c.pat, seltype);
923 if (sym == null) {
924 log.error(c.pat.pos(), "enum.const.req");
925 } else if (!labels.add(sym)) {
926 log.error(c.pos(), "duplicate.case.label");
927 }
928 } else {
929 Type pattype = attribExpr(c.pat, switchEnv, seltype);
930 if (pattype.tag != ERROR) {
931 if (pattype.constValue() == null) {
932 log.error(c.pat.pos(),
933 (stringSwitch ? "string.const.req" : "const.expr.req"));
934 } else if (labels.contains(pattype.constValue())) {
935 log.error(c.pos(), "duplicate.case.label");
936 } else {
937 labels.add(pattype.constValue());
938 }
939 }
940 }
941 } else if (hasDefault) {
942 log.error(c.pos(), "duplicate.default.label");
943 } else {
944 hasDefault = true;
945 }
946 attribStats(c.stats, caseEnv);
947 caseEnv.info.scope.leave();
948 addVars(c.stats, switchEnv.info.scope);
949 }
951 switchEnv.info.scope.leave();
952 result = null;
953 }
954 // where
955 /** Add any variables defined in stats to the switch scope. */
956 private static void addVars(List<JCStatement> stats, Scope switchScope) {
957 for (;stats.nonEmpty(); stats = stats.tail) {
958 JCTree stat = stats.head;
959 if (stat.getTag() == JCTree.VARDEF)
960 switchScope.enter(((JCVariableDecl) stat).sym);
961 }
962 }
963 // where
964 /** Return the selected enumeration constant symbol, or null. */
965 private Symbol enumConstant(JCTree tree, Type enumType) {
966 if (tree.getTag() != JCTree.IDENT) {
967 log.error(tree.pos(), "enum.label.must.be.unqualified.enum");
968 return syms.errSymbol;
969 }
970 JCIdent ident = (JCIdent)tree;
971 Name name = ident.name;
972 for (Scope.Entry e = enumType.tsym.members().lookup(name);
973 e.scope != null; e = e.next()) {
974 if (e.sym.kind == VAR) {
975 Symbol s = ident.sym = e.sym;
976 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
977 ident.type = s.type;
978 return ((s.flags_field & Flags.ENUM) == 0)
979 ? null : s;
980 }
981 }
982 return null;
983 }
985 public void visitSynchronized(JCSynchronized tree) {
986 chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
987 attribStat(tree.body, env);
988 result = null;
989 }
991 public void visitTry(JCTry tree) {
992 // Attribute body
993 attribStat(tree.body, env.dup(tree, env.info.dup()));
995 // Attribute catch clauses
996 for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
997 JCCatch c = l.head;
998 Env<AttrContext> catchEnv =
999 env.dup(c, env.info.dup(env.info.scope.dup()));
1000 Type ctype = attribStat(c.param, catchEnv);
1001 if (c.param.type.tsym.kind == Kinds.VAR) {
1002 c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
1003 }
1004 chk.checkType(c.param.vartype.pos(),
1005 chk.checkClassType(c.param.vartype.pos(), ctype),
1006 syms.throwableType);
1007 attribStat(c.body, catchEnv);
1008 catchEnv.info.scope.leave();
1009 }
1011 // Attribute finalizer
1012 if (tree.finalizer != null) attribStat(tree.finalizer, env);
1013 result = null;
1014 }
1016 public void visitConditional(JCConditional tree) {
1017 attribExpr(tree.cond, env, syms.booleanType);
1018 attribExpr(tree.truepart, env);
1019 attribExpr(tree.falsepart, env);
1020 result = check(tree,
1021 capture(condType(tree.pos(), tree.cond.type,
1022 tree.truepart.type, tree.falsepart.type)),
1023 VAL, pkind, pt);
1024 }
1025 //where
1026 /** Compute the type of a conditional expression, after
1027 * checking that it exists. See Spec 15.25.
1028 *
1029 * @param pos The source position to be used for
1030 * error diagnostics.
1031 * @param condtype The type of the expression's condition.
1032 * @param thentype The type of the expression's then-part.
1033 * @param elsetype The type of the expression's else-part.
1034 */
1035 private Type condType(DiagnosticPosition pos,
1036 Type condtype,
1037 Type thentype,
1038 Type elsetype) {
1039 Type ctype = condType1(pos, condtype, thentype, elsetype);
1041 // If condition and both arms are numeric constants,
1042 // evaluate at compile-time.
1043 return ((condtype.constValue() != null) &&
1044 (thentype.constValue() != null) &&
1045 (elsetype.constValue() != null))
1046 ? cfolder.coerce(condtype.isTrue()?thentype:elsetype, ctype)
1047 : ctype;
1048 }
1049 /** Compute the type of a conditional expression, after
1050 * checking that it exists. Does not take into
1051 * account the special case where condition and both arms
1052 * are constants.
1053 *
1054 * @param pos The source position to be used for error
1055 * diagnostics.
1056 * @param condtype The type of the expression's condition.
1057 * @param thentype The type of the expression's then-part.
1058 * @param elsetype The type of the expression's else-part.
1059 */
1060 private Type condType1(DiagnosticPosition pos, Type condtype,
1061 Type thentype, Type elsetype) {
1062 // If same type, that is the result
1063 if (types.isSameType(thentype, elsetype))
1064 return thentype.baseType();
1066 Type thenUnboxed = (!allowBoxing || thentype.isPrimitive())
1067 ? thentype : types.unboxedType(thentype);
1068 Type elseUnboxed = (!allowBoxing || elsetype.isPrimitive())
1069 ? elsetype : types.unboxedType(elsetype);
1071 // Otherwise, if both arms can be converted to a numeric
1072 // type, return the least numeric type that fits both arms
1073 // (i.e. return larger of the two, or return int if one
1074 // arm is short, the other is char).
1075 if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) {
1076 // If one arm has an integer subrange type (i.e., byte,
1077 // short, or char), and the other is an integer constant
1078 // that fits into the subrange, return the subrange type.
1079 if (thenUnboxed.tag < INT && elseUnboxed.tag == INT &&
1080 types.isAssignable(elseUnboxed, thenUnboxed))
1081 return thenUnboxed.baseType();
1082 if (elseUnboxed.tag < INT && thenUnboxed.tag == INT &&
1083 types.isAssignable(thenUnboxed, elseUnboxed))
1084 return elseUnboxed.baseType();
1086 for (int i = BYTE; i < VOID; i++) {
1087 Type candidate = syms.typeOfTag[i];
1088 if (types.isSubtype(thenUnboxed, candidate) &&
1089 types.isSubtype(elseUnboxed, candidate))
1090 return candidate;
1091 }
1092 }
1094 // Those were all the cases that could result in a primitive
1095 if (allowBoxing) {
1096 if (thentype.isPrimitive())
1097 thentype = types.boxedClass(thentype).type;
1098 if (elsetype.isPrimitive())
1099 elsetype = types.boxedClass(elsetype).type;
1100 }
1102 if (types.isSubtype(thentype, elsetype))
1103 return elsetype.baseType();
1104 if (types.isSubtype(elsetype, thentype))
1105 return thentype.baseType();
1107 if (!allowBoxing || thentype.tag == VOID || elsetype.tag == VOID) {
1108 log.error(pos, "neither.conditional.subtype",
1109 thentype, elsetype);
1110 return thentype.baseType();
1111 }
1113 // both are known to be reference types. The result is
1114 // lub(thentype,elsetype). This cannot fail, as it will
1115 // always be possible to infer "Object" if nothing better.
1116 return types.lub(thentype.baseType(), elsetype.baseType());
1117 }
1119 public void visitIf(JCIf tree) {
1120 attribExpr(tree.cond, env, syms.booleanType);
1121 attribStat(tree.thenpart, env);
1122 if (tree.elsepart != null)
1123 attribStat(tree.elsepart, env);
1124 chk.checkEmptyIf(tree);
1125 result = null;
1126 }
1128 public void visitExec(JCExpressionStatement tree) {
1129 attribExpr(tree.expr, env);
1130 result = null;
1131 }
1133 public void visitBreak(JCBreak tree) {
1134 tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
1135 result = null;
1136 }
1138 public void visitContinue(JCContinue tree) {
1139 tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
1140 result = null;
1141 }
1142 //where
1143 /** Return the target of a break or continue statement, if it exists,
1144 * report an error if not.
1145 * Note: The target of a labelled break or continue is the
1146 * (non-labelled) statement tree referred to by the label,
1147 * not the tree representing the labelled statement itself.
1148 *
1149 * @param pos The position to be used for error diagnostics
1150 * @param tag The tag of the jump statement. This is either
1151 * Tree.BREAK or Tree.CONTINUE.
1152 * @param label The label of the jump statement, or null if no
1153 * label is given.
1154 * @param env The environment current at the jump statement.
1155 */
1156 private JCTree findJumpTarget(DiagnosticPosition pos,
1157 int tag,
1158 Name label,
1159 Env<AttrContext> env) {
1160 // Search environments outwards from the point of jump.
1161 Env<AttrContext> env1 = env;
1162 LOOP:
1163 while (env1 != null) {
1164 switch (env1.tree.getTag()) {
1165 case JCTree.LABELLED:
1166 JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
1167 if (label == labelled.label) {
1168 // If jump is a continue, check that target is a loop.
1169 if (tag == JCTree.CONTINUE) {
1170 if (labelled.body.getTag() != JCTree.DOLOOP &&
1171 labelled.body.getTag() != JCTree.WHILELOOP &&
1172 labelled.body.getTag() != JCTree.FORLOOP &&
1173 labelled.body.getTag() != JCTree.FOREACHLOOP)
1174 log.error(pos, "not.loop.label", label);
1175 // Found labelled statement target, now go inwards
1176 // to next non-labelled tree.
1177 return TreeInfo.referencedStatement(labelled);
1178 } else {
1179 return labelled;
1180 }
1181 }
1182 break;
1183 case JCTree.DOLOOP:
1184 case JCTree.WHILELOOP:
1185 case JCTree.FORLOOP:
1186 case JCTree.FOREACHLOOP:
1187 if (label == null) return env1.tree;
1188 break;
1189 case JCTree.SWITCH:
1190 if (label == null && tag == JCTree.BREAK) return env1.tree;
1191 break;
1192 case JCTree.METHODDEF:
1193 case JCTree.CLASSDEF:
1194 break LOOP;
1195 default:
1196 }
1197 env1 = env1.next;
1198 }
1199 if (label != null)
1200 log.error(pos, "undef.label", label);
1201 else if (tag == JCTree.CONTINUE)
1202 log.error(pos, "cont.outside.loop");
1203 else
1204 log.error(pos, "break.outside.switch.loop");
1205 return null;
1206 }
1208 public void visitReturn(JCReturn tree) {
1209 // Check that there is an enclosing method which is
1210 // nested within than the enclosing class.
1211 if (env.enclMethod == null ||
1212 env.enclMethod.sym.owner != env.enclClass.sym) {
1213 log.error(tree.pos(), "ret.outside.meth");
1215 } else {
1216 // Attribute return expression, if it exists, and check that
1217 // it conforms to result type of enclosing method.
1218 Symbol m = env.enclMethod.sym;
1219 if (m.type.getReturnType().tag == VOID) {
1220 if (tree.expr != null)
1221 log.error(tree.expr.pos(),
1222 "cant.ret.val.from.meth.decl.void");
1223 } else if (tree.expr == null) {
1224 log.error(tree.pos(), "missing.ret.val");
1225 } else {
1226 attribExpr(tree.expr, env, m.type.getReturnType());
1227 }
1228 }
1229 result = null;
1230 }
1232 public void visitThrow(JCThrow tree) {
1233 attribExpr(tree.expr, env, syms.throwableType);
1234 result = null;
1235 }
1237 public void visitAssert(JCAssert tree) {
1238 attribExpr(tree.cond, env, syms.booleanType);
1239 if (tree.detail != null) {
1240 chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
1241 }
1242 result = null;
1243 }
1245 /** Visitor method for method invocations.
1246 * NOTE: The method part of an application will have in its type field
1247 * the return type of the method, not the method's type itself!
1248 */
1249 public void visitApply(JCMethodInvocation tree) {
1250 // The local environment of a method application is
1251 // a new environment nested in the current one.
1252 Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
1254 // The types of the actual method arguments.
1255 List<Type> argtypes;
1257 // The types of the actual method type arguments.
1258 List<Type> typeargtypes = null;
1259 boolean typeargtypesNonRefOK = false;
1261 Name methName = TreeInfo.name(tree.meth);
1263 boolean isConstructorCall =
1264 methName == names._this || methName == names._super;
1266 if (isConstructorCall) {
1267 // We are seeing a ...this(...) or ...super(...) call.
1268 // Check that this is the first statement in a constructor.
1269 if (checkFirstConstructorStat(tree, env)) {
1271 // Record the fact
1272 // that this is a constructor call (using isSelfCall).
1273 localEnv.info.isSelfCall = true;
1275 // Attribute arguments, yielding list of argument types.
1276 argtypes = attribArgs(tree.args, localEnv);
1277 typeargtypes = attribTypes(tree.typeargs, localEnv);
1279 // Variable `site' points to the class in which the called
1280 // constructor is defined.
1281 Type site = env.enclClass.sym.type;
1282 if (methName == names._super) {
1283 if (site == syms.objectType) {
1284 log.error(tree.meth.pos(), "no.superclass", site);
1285 site = types.createErrorType(syms.objectType);
1286 } else {
1287 site = types.supertype(site);
1288 }
1289 }
1291 if (site.tag == CLASS) {
1292 Type encl = site.getEnclosingType();
1293 while (encl != null && encl.tag == TYPEVAR)
1294 encl = encl.getUpperBound();
1295 if (encl.tag == CLASS) {
1296 // we are calling a nested class
1298 if (tree.meth.getTag() == JCTree.SELECT) {
1299 JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
1301 // We are seeing a prefixed call, of the form
1302 // <expr>.super(...).
1303 // Check that the prefix expression conforms
1304 // to the outer instance type of the class.
1305 chk.checkRefType(qualifier.pos(),
1306 attribExpr(qualifier, localEnv,
1307 encl));
1308 } else if (methName == names._super) {
1309 // qualifier omitted; check for existence
1310 // of an appropriate implicit qualifier.
1311 rs.resolveImplicitThis(tree.meth.pos(),
1312 localEnv, site);
1313 }
1314 } else if (tree.meth.getTag() == JCTree.SELECT) {
1315 log.error(tree.meth.pos(), "illegal.qual.not.icls",
1316 site.tsym);
1317 }
1319 // if we're calling a java.lang.Enum constructor,
1320 // prefix the implicit String and int parameters
1321 if (site.tsym == syms.enumSym && allowEnums)
1322 argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
1324 // Resolve the called constructor under the assumption
1325 // that we are referring to a superclass instance of the
1326 // current instance (JLS ???).
1327 boolean selectSuperPrev = localEnv.info.selectSuper;
1328 localEnv.info.selectSuper = true;
1329 localEnv.info.varArgs = false;
1330 Symbol sym = rs.resolveConstructor(
1331 tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
1332 localEnv.info.selectSuper = selectSuperPrev;
1334 // Set method symbol to resolved constructor...
1335 TreeInfo.setSymbol(tree.meth, sym);
1337 // ...and check that it is legal in the current context.
1338 // (this will also set the tree's type)
1339 Type mpt = newMethTemplate(argtypes, typeargtypes);
1340 checkId(tree.meth, site, sym, localEnv, MTH,
1341 mpt, tree.varargsElement != null);
1342 }
1343 // Otherwise, `site' is an error type and we do nothing
1344 }
1345 result = tree.type = syms.voidType;
1346 } else {
1347 // Otherwise, we are seeing a regular method call.
1348 // Attribute the arguments, yielding list of argument types, ...
1349 argtypes = attribArgs(tree.args, localEnv);
1350 typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
1352 // ... and attribute the method using as a prototype a methodtype
1353 // whose formal argument types is exactly the list of actual
1354 // arguments (this will also set the method symbol).
1355 Type mpt = newMethTemplate(argtypes, typeargtypes);
1356 localEnv.info.varArgs = false;
1357 Type mtype = attribExpr(tree.meth, localEnv, mpt);
1358 if (localEnv.info.varArgs)
1359 assert mtype.isErroneous() || tree.varargsElement != null;
1361 // Compute the result type.
1362 Type restype = mtype.getReturnType();
1363 assert restype.tag != WILDCARD : mtype;
1365 // as a special case, array.clone() has a result that is
1366 // the same as static type of the array being cloned
1367 if (tree.meth.getTag() == JCTree.SELECT &&
1368 allowCovariantReturns &&
1369 methName == names.clone &&
1370 types.isArray(((JCFieldAccess) tree.meth).selected.type))
1371 restype = ((JCFieldAccess) tree.meth).selected.type;
1373 // as a special case, x.getClass() has type Class<? extends |X|>
1374 if (allowGenerics &&
1375 methName == names.getClass && tree.args.isEmpty()) {
1376 Type qualifier = (tree.meth.getTag() == JCTree.SELECT)
1377 ? ((JCFieldAccess) tree.meth).selected.type
1378 : env.enclClass.sym.type;
1379 restype = new
1380 ClassType(restype.getEnclosingType(),
1381 List.<Type>of(new WildcardType(types.erasure(qualifier),
1382 BoundKind.EXTENDS,
1383 syms.boundClass)),
1384 restype.tsym);
1385 }
1387 // as a special case, MethodHandle.<T>invoke(abc) and InvokeDynamic.<T>foo(abc)
1388 // has type <T>, and T can be a primitive type.
1389 if (tree.meth.getTag() == JCTree.SELECT && !typeargtypes.isEmpty()) {
1390 Type selt = ((JCFieldAccess) tree.meth).selected.type;
1391 if ((selt == syms.methodHandleType && methName == names.invoke) || selt == syms.invokeDynamicType) {
1392 assert types.isSameType(restype, typeargtypes.head) : mtype;
1393 typeargtypesNonRefOK = true;
1394 }
1395 }
1397 if (!typeargtypesNonRefOK) {
1398 chk.checkRefTypes(tree.typeargs, typeargtypes);
1399 }
1401 // Check that value of resulting type is admissible in the
1402 // current context. Also, capture the return type
1403 result = checkReturn(tree, capture(restype), VAL, pkind, pt);
1404 }
1405 chk.validate(tree.typeargs, localEnv);
1406 }
1407 //where
1408 /** Check that given application node appears as first statement
1409 * in a constructor call.
1410 * @param tree The application node
1411 * @param env The environment current at the application.
1412 */
1413 boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) {
1414 JCMethodDecl enclMethod = env.enclMethod;
1415 if (enclMethod != null && enclMethod.name == names.init) {
1416 JCBlock body = enclMethod.body;
1417 if (body.stats.head.getTag() == JCTree.EXEC &&
1418 ((JCExpressionStatement) body.stats.head).expr == tree)
1419 return true;
1420 }
1421 log.error(tree.pos(),"call.must.be.first.stmt.in.ctor",
1422 TreeInfo.name(tree.meth));
1423 return false;
1424 }
1426 /** Obtain a method type with given argument types.
1427 */
1428 Type newMethTemplate(List<Type> argtypes, List<Type> typeargtypes) {
1429 MethodType mt = new MethodType(argtypes, null, null, syms.methodClass);
1430 return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
1431 }
1433 public void visitNewClass(JCNewClass tree) {
1434 Type owntype = types.createErrorType(tree.type);
1436 // The local environment of a class creation is
1437 // a new environment nested in the current one.
1438 Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
1440 // The anonymous inner class definition of the new expression,
1441 // if one is defined by it.
1442 JCClassDecl cdef = tree.def;
1444 // If enclosing class is given, attribute it, and
1445 // complete class name to be fully qualified
1446 JCExpression clazz = tree.clazz; // Class field following new
1447 JCExpression clazzid = // Identifier in class field
1448 (clazz.getTag() == JCTree.TYPEAPPLY)
1449 ? ((JCTypeApply) clazz).clazz
1450 : clazz;
1452 JCExpression clazzid1 = clazzid; // The same in fully qualified form
1454 if (tree.encl != null) {
1455 // We are seeing a qualified new, of the form
1456 // <expr>.new C <...> (...) ...
1457 // In this case, we let clazz stand for the name of the
1458 // allocated class C prefixed with the type of the qualifier
1459 // expression, so that we can
1460 // resolve it with standard techniques later. I.e., if
1461 // <expr> has type T, then <expr>.new C <...> (...)
1462 // yields a clazz T.C.
1463 Type encltype = chk.checkRefType(tree.encl.pos(),
1464 attribExpr(tree.encl, env));
1465 clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
1466 ((JCIdent) clazzid).name);
1467 if (clazz.getTag() == JCTree.TYPEAPPLY)
1468 clazz = make.at(tree.pos).
1469 TypeApply(clazzid1,
1470 ((JCTypeApply) clazz).arguments);
1471 else
1472 clazz = clazzid1;
1473 // System.out.println(clazz + " generated.");//DEBUG
1474 }
1476 // Attribute clazz expression and store
1477 // symbol + type back into the attributed tree.
1478 Type clazztype = attribType(clazz, env);
1479 chk.validate(clazz, localEnv);
1480 clazztype = chk.checkNewClassType(clazz.pos(), clazztype, true, pt);
1481 if (tree.encl != null) {
1482 // We have to work in this case to store
1483 // symbol + type back into the attributed tree.
1484 tree.clazz.type = clazztype;
1485 TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
1486 clazzid.type = ((JCIdent) clazzid).sym.type;
1487 if (!clazztype.isErroneous()) {
1488 if (cdef != null && clazztype.tsym.isInterface()) {
1489 log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new");
1490 } else if (clazztype.tsym.isStatic()) {
1491 log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym);
1492 }
1493 }
1494 } else if (!clazztype.tsym.isInterface() &&
1495 clazztype.getEnclosingType().tag == CLASS) {
1496 // Check for the existence of an apropos outer instance
1497 rs.resolveImplicitThis(tree.pos(), env, clazztype);
1498 }
1500 // Attribute constructor arguments.
1501 List<Type> argtypes = attribArgs(tree.args, localEnv);
1502 List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
1504 // If we have made no mistakes in the class type...
1505 if (clazztype.tag == CLASS) {
1506 // Enums may not be instantiated except implicitly
1507 if (allowEnums &&
1508 (clazztype.tsym.flags_field&Flags.ENUM) != 0 &&
1509 (env.tree.getTag() != JCTree.VARDEF ||
1510 (((JCVariableDecl) env.tree).mods.flags&Flags.ENUM) == 0 ||
1511 ((JCVariableDecl) env.tree).init != tree))
1512 log.error(tree.pos(), "enum.cant.be.instantiated");
1513 // Check that class is not abstract
1514 if (cdef == null &&
1515 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
1516 log.error(tree.pos(), "abstract.cant.be.instantiated",
1517 clazztype.tsym);
1518 } else if (cdef != null && clazztype.tsym.isInterface()) {
1519 // Check that no constructor arguments are given to
1520 // anonymous classes implementing an interface
1521 if (!argtypes.isEmpty())
1522 log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args");
1524 if (!typeargtypes.isEmpty())
1525 log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs");
1527 // Error recovery: pretend no arguments were supplied.
1528 argtypes = List.nil();
1529 typeargtypes = List.nil();
1530 }
1532 // Resolve the called constructor under the assumption
1533 // that we are referring to a superclass instance of the
1534 // current instance (JLS ???).
1535 else {
1536 localEnv.info.selectSuper = cdef != null;
1537 localEnv.info.varArgs = false;
1538 tree.constructor = rs.resolveConstructor(
1539 tree.pos(), localEnv, clazztype, argtypes, typeargtypes);
1540 tree.constructorType = checkMethod(clazztype,
1541 tree.constructor,
1542 localEnv,
1543 tree.args,
1544 argtypes,
1545 typeargtypes,
1546 localEnv.info.varArgs);
1547 if (localEnv.info.varArgs)
1548 assert tree.constructorType.isErroneous() || tree.varargsElement != null;
1549 }
1551 if (cdef != null) {
1552 // We are seeing an anonymous class instance creation.
1553 // In this case, the class instance creation
1554 // expression
1555 //
1556 // E.new <typeargs1>C<typargs2>(args) { ... }
1557 //
1558 // is represented internally as
1559 //
1560 // E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } ) .
1561 //
1562 // This expression is then *transformed* as follows:
1563 //
1564 // (1) add a STATIC flag to the class definition
1565 // if the current environment is static
1566 // (2) add an extends or implements clause
1567 // (3) add a constructor.
1568 //
1569 // For instance, if C is a class, and ET is the type of E,
1570 // the expression
1571 //
1572 // E.new <typeargs1>C<typargs2>(args) { ... }
1573 //
1574 // is translated to (where X is a fresh name and typarams is the
1575 // parameter list of the super constructor):
1576 //
1577 // new <typeargs1>X(<*nullchk*>E, args) where
1578 // X extends C<typargs2> {
1579 // <typarams> X(ET e, args) {
1580 // e.<typeargs1>super(args)
1581 // }
1582 // ...
1583 // }
1584 if (Resolve.isStatic(env)) cdef.mods.flags |= STATIC;
1585 clazz = TreeInfo.isDiamond(tree) ?
1586 make.Type(clazztype)
1587 : clazz;
1588 if (clazztype.tsym.isInterface()) {
1589 cdef.implementing = List.of(clazz);
1590 } else {
1591 cdef.extending = clazz;
1592 }
1594 attribStat(cdef, localEnv);
1596 // If an outer instance is given,
1597 // prefix it to the constructor arguments
1598 // and delete it from the new expression
1599 if (tree.encl != null && !clazztype.tsym.isInterface()) {
1600 tree.args = tree.args.prepend(makeNullCheck(tree.encl));
1601 argtypes = argtypes.prepend(tree.encl.type);
1602 tree.encl = null;
1603 }
1605 // Reassign clazztype and recompute constructor.
1606 clazztype = cdef.sym.type;
1607 Symbol sym = rs.resolveConstructor(
1608 tree.pos(), localEnv, clazztype, argtypes,
1609 typeargtypes, true, tree.varargsElement != null);
1610 assert sym.kind < AMBIGUOUS || tree.constructor.type.isErroneous();
1611 tree.constructor = sym;
1612 if (tree.constructor.kind > ERRONEOUS) {
1613 tree.constructorType = syms.errType;
1614 }
1615 else {
1616 tree.constructorType = checkMethod(clazztype,
1617 tree.constructor,
1618 localEnv,
1619 tree.args,
1620 argtypes,
1621 typeargtypes,
1622 localEnv.info.varArgs);
1623 }
1624 }
1626 if (tree.constructor != null && tree.constructor.kind == MTH)
1627 owntype = clazztype;
1628 }
1629 result = check(tree, owntype, VAL, pkind, pt);
1630 chk.validate(tree.typeargs, localEnv);
1631 }
1633 /** Make an attributed null check tree.
1634 */
1635 public JCExpression makeNullCheck(JCExpression arg) {
1636 // optimization: X.this is never null; skip null check
1637 Name name = TreeInfo.name(arg);
1638 if (name == names._this || name == names._super) return arg;
1640 int optag = JCTree.NULLCHK;
1641 JCUnary tree = make.at(arg.pos).Unary(optag, arg);
1642 tree.operator = syms.nullcheck;
1643 tree.type = arg.type;
1644 return tree;
1645 }
1647 public void visitNewArray(JCNewArray tree) {
1648 Type owntype = types.createErrorType(tree.type);
1649 Type elemtype;
1650 if (tree.elemtype != null) {
1651 elemtype = attribType(tree.elemtype, env);
1652 chk.validate(tree.elemtype, env);
1653 owntype = elemtype;
1654 for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
1655 attribExpr(l.head, env, syms.intType);
1656 owntype = new ArrayType(owntype, syms.arrayClass);
1657 }
1658 } else {
1659 // we are seeing an untyped aggregate { ... }
1660 // this is allowed only if the prototype is an array
1661 if (pt.tag == ARRAY) {
1662 elemtype = types.elemtype(pt);
1663 } else {
1664 if (pt.tag != ERROR) {
1665 log.error(tree.pos(), "illegal.initializer.for.type",
1666 pt);
1667 }
1668 elemtype = types.createErrorType(pt);
1669 }
1670 }
1671 if (tree.elems != null) {
1672 attribExprs(tree.elems, env, elemtype);
1673 owntype = new ArrayType(elemtype, syms.arrayClass);
1674 }
1675 if (!types.isReifiable(elemtype))
1676 log.error(tree.pos(), "generic.array.creation");
1677 result = check(tree, owntype, VAL, pkind, pt);
1678 }
1680 public void visitParens(JCParens tree) {
1681 Type owntype = attribTree(tree.expr, env, pkind, pt);
1682 result = check(tree, owntype, pkind, pkind, pt);
1683 Symbol sym = TreeInfo.symbol(tree);
1684 if (sym != null && (sym.kind&(TYP|PCK)) != 0)
1685 log.error(tree.pos(), "illegal.start.of.type");
1686 }
1688 public void visitAssign(JCAssign tree) {
1689 Type owntype = attribTree(tree.lhs, env.dup(tree), VAR, Type.noType);
1690 Type capturedType = capture(owntype);
1691 attribExpr(tree.rhs, env, owntype);
1692 result = check(tree, capturedType, VAL, pkind, pt);
1693 }
1695 public void visitAssignop(JCAssignOp tree) {
1696 // Attribute arguments.
1697 Type owntype = attribTree(tree.lhs, env, VAR, Type.noType);
1698 Type operand = attribExpr(tree.rhs, env);
1699 // Find operator.
1700 Symbol operator = tree.operator = rs.resolveBinaryOperator(
1701 tree.pos(), tree.getTag() - JCTree.ASGOffset, env,
1702 owntype, operand);
1704 if (operator.kind == MTH) {
1705 chk.checkOperator(tree.pos(),
1706 (OperatorSymbol)operator,
1707 tree.getTag() - JCTree.ASGOffset,
1708 owntype,
1709 operand);
1710 chk.checkDivZero(tree.rhs.pos(), operator, operand);
1711 chk.checkCastable(tree.rhs.pos(),
1712 operator.type.getReturnType(),
1713 owntype);
1714 }
1715 result = check(tree, owntype, VAL, pkind, pt);
1716 }
1718 public void visitUnary(JCUnary tree) {
1719 // Attribute arguments.
1720 Type argtype = (JCTree.PREINC <= tree.getTag() && tree.getTag() <= JCTree.POSTDEC)
1721 ? attribTree(tree.arg, env, VAR, Type.noType)
1722 : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
1724 // Find operator.
1725 Symbol operator = tree.operator =
1726 rs.resolveUnaryOperator(tree.pos(), tree.getTag(), env, argtype);
1728 Type owntype = types.createErrorType(tree.type);
1729 if (operator.kind == MTH) {
1730 owntype = (JCTree.PREINC <= tree.getTag() && tree.getTag() <= JCTree.POSTDEC)
1731 ? tree.arg.type
1732 : operator.type.getReturnType();
1733 int opc = ((OperatorSymbol)operator).opcode;
1735 // If the argument is constant, fold it.
1736 if (argtype.constValue() != null) {
1737 Type ctype = cfolder.fold1(opc, argtype);
1738 if (ctype != null) {
1739 owntype = cfolder.coerce(ctype, owntype);
1741 // Remove constant types from arguments to
1742 // conserve space. The parser will fold concatenations
1743 // of string literals; the code here also
1744 // gets rid of intermediate results when some of the
1745 // operands are constant identifiers.
1746 if (tree.arg.type.tsym == syms.stringType.tsym) {
1747 tree.arg.type = syms.stringType;
1748 }
1749 }
1750 }
1751 }
1752 result = check(tree, owntype, VAL, pkind, pt);
1753 }
1755 public void visitBinary(JCBinary tree) {
1756 // Attribute arguments.
1757 Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
1758 Type right = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.rhs, env));
1760 // Find operator.
1761 Symbol operator = tree.operator =
1762 rs.resolveBinaryOperator(tree.pos(), tree.getTag(), env, left, right);
1764 Type owntype = types.createErrorType(tree.type);
1765 if (operator.kind == MTH) {
1766 owntype = operator.type.getReturnType();
1767 int opc = chk.checkOperator(tree.lhs.pos(),
1768 (OperatorSymbol)operator,
1769 tree.getTag(),
1770 left,
1771 right);
1773 // If both arguments are constants, fold them.
1774 if (left.constValue() != null && right.constValue() != null) {
1775 Type ctype = cfolder.fold2(opc, left, right);
1776 if (ctype != null) {
1777 owntype = cfolder.coerce(ctype, owntype);
1779 // Remove constant types from arguments to
1780 // conserve space. The parser will fold concatenations
1781 // of string literals; the code here also
1782 // gets rid of intermediate results when some of the
1783 // operands are constant identifiers.
1784 if (tree.lhs.type.tsym == syms.stringType.tsym) {
1785 tree.lhs.type = syms.stringType;
1786 }
1787 if (tree.rhs.type.tsym == syms.stringType.tsym) {
1788 tree.rhs.type = syms.stringType;
1789 }
1790 }
1791 }
1793 // Check that argument types of a reference ==, != are
1794 // castable to each other, (JLS???).
1795 if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
1796 if (!types.isCastable(left, right, new Warner(tree.pos()))) {
1797 log.error(tree.pos(), "incomparable.types", left, right);
1798 }
1799 }
1801 chk.checkDivZero(tree.rhs.pos(), operator, right);
1802 }
1803 result = check(tree, owntype, VAL, pkind, pt);
1804 }
1806 public void visitTypeCast(JCTypeCast tree) {
1807 Type clazztype = attribType(tree.clazz, env);
1808 chk.validate(tree.clazz, env);
1809 Type exprtype = attribExpr(tree.expr, env, Infer.anyPoly);
1810 Type owntype = chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
1811 if (exprtype.constValue() != null)
1812 owntype = cfolder.coerce(exprtype, owntype);
1813 result = check(tree, capture(owntype), VAL, pkind, pt);
1814 }
1816 public void visitTypeTest(JCInstanceOf tree) {
1817 Type exprtype = chk.checkNullOrRefType(
1818 tree.expr.pos(), attribExpr(tree.expr, env));
1819 Type clazztype = chk.checkReifiableReferenceType(
1820 tree.clazz.pos(), attribType(tree.clazz, env));
1821 chk.validate(tree.clazz, env);
1822 chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
1823 result = check(tree, syms.booleanType, VAL, pkind, pt);
1824 }
1826 public void visitIndexed(JCArrayAccess tree) {
1827 Type owntype = types.createErrorType(tree.type);
1828 Type atype = attribExpr(tree.indexed, env);
1829 attribExpr(tree.index, env, syms.intType);
1830 if (types.isArray(atype))
1831 owntype = types.elemtype(atype);
1832 else if (atype.tag != ERROR)
1833 log.error(tree.pos(), "array.req.but.found", atype);
1834 if ((pkind & VAR) == 0) owntype = capture(owntype);
1835 result = check(tree, owntype, VAR, pkind, pt);
1836 }
1838 public void visitIdent(JCIdent tree) {
1839 Symbol sym;
1840 boolean varArgs = false;
1842 // Find symbol
1843 if (pt.tag == METHOD || pt.tag == FORALL) {
1844 // If we are looking for a method, the prototype `pt' will be a
1845 // method type with the type of the call's arguments as parameters.
1846 env.info.varArgs = false;
1847 sym = rs.resolveMethod(tree.pos(), env, tree.name, pt.getParameterTypes(), pt.getTypeArguments());
1848 varArgs = env.info.varArgs;
1849 } else if (tree.sym != null && tree.sym.kind != VAR) {
1850 sym = tree.sym;
1851 } else {
1852 sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind);
1853 }
1854 tree.sym = sym;
1856 // (1) Also find the environment current for the class where
1857 // sym is defined (`symEnv').
1858 // Only for pre-tiger versions (1.4 and earlier):
1859 // (2) Also determine whether we access symbol out of an anonymous
1860 // class in a this or super call. This is illegal for instance
1861 // members since such classes don't carry a this$n link.
1862 // (`noOuterThisPath').
1863 Env<AttrContext> symEnv = env;
1864 boolean noOuterThisPath = false;
1865 if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
1866 (sym.kind & (VAR | MTH | TYP)) != 0 &&
1867 sym.owner.kind == TYP &&
1868 tree.name != names._this && tree.name != names._super) {
1870 // Find environment in which identifier is defined.
1871 while (symEnv.outer != null &&
1872 !sym.isMemberOf(symEnv.enclClass.sym, types)) {
1873 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
1874 noOuterThisPath = !allowAnonOuterThis;
1875 symEnv = symEnv.outer;
1876 }
1877 }
1879 // If symbol is a variable, ...
1880 if (sym.kind == VAR) {
1881 VarSymbol v = (VarSymbol)sym;
1883 // ..., evaluate its initializer, if it has one, and check for
1884 // illegal forward reference.
1885 checkInit(tree, env, v, false);
1887 // If symbol is a local variable accessed from an embedded
1888 // inner class check that it is final.
1889 if (v.owner.kind == MTH &&
1890 v.owner != env.info.scope.owner &&
1891 (v.flags_field & FINAL) == 0) {
1892 log.error(tree.pos(),
1893 "local.var.accessed.from.icls.needs.final",
1894 v);
1895 }
1897 // If we are expecting a variable (as opposed to a value), check
1898 // that the variable is assignable in the current environment.
1899 if (pkind == VAR)
1900 checkAssignable(tree.pos(), v, null, env);
1901 }
1903 // In a constructor body,
1904 // if symbol is a field or instance method, check that it is
1905 // not accessed before the supertype constructor is called.
1906 if ((symEnv.info.isSelfCall || noOuterThisPath) &&
1907 (sym.kind & (VAR | MTH)) != 0 &&
1908 sym.owner.kind == TYP &&
1909 (sym.flags() & STATIC) == 0) {
1910 chk.earlyRefError(tree.pos(), sym.kind == VAR ? sym : thisSym(tree.pos(), env));
1911 }
1912 Env<AttrContext> env1 = env;
1913 if (sym.kind != ERR && sym.kind != TYP && sym.owner != null && sym.owner != env1.enclClass.sym) {
1914 // If the found symbol is inaccessible, then it is
1915 // accessed through an enclosing instance. Locate this
1916 // enclosing instance:
1917 while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
1918 env1 = env1.outer;
1919 }
1920 result = checkId(tree, env1.enclClass.sym.type, sym, env, pkind, pt, varArgs);
1921 }
1923 public void visitSelect(JCFieldAccess tree) {
1924 // Determine the expected kind of the qualifier expression.
1925 int skind = 0;
1926 if (tree.name == names._this || tree.name == names._super ||
1927 tree.name == names._class)
1928 {
1929 skind = TYP;
1930 } else {
1931 if ((pkind & PCK) != 0) skind = skind | PCK;
1932 if ((pkind & TYP) != 0) skind = skind | TYP | PCK;
1933 if ((pkind & (VAL | MTH)) != 0) skind = skind | VAL | TYP;
1934 }
1936 // Attribute the qualifier expression, and determine its symbol (if any).
1937 Type site = attribTree(tree.selected, env, skind, Infer.anyPoly);
1938 if ((pkind & (PCK | TYP)) == 0)
1939 site = capture(site); // Capture field access
1941 // don't allow T.class T[].class, etc
1942 if (skind == TYP) {
1943 Type elt = site;
1944 while (elt.tag == ARRAY)
1945 elt = ((ArrayType)elt).elemtype;
1946 if (elt.tag == TYPEVAR) {
1947 log.error(tree.pos(), "type.var.cant.be.deref");
1948 result = types.createErrorType(tree.type);
1949 return;
1950 }
1951 }
1953 // If qualifier symbol is a type or `super', assert `selectSuper'
1954 // for the selection. This is relevant for determining whether
1955 // protected symbols are accessible.
1956 Symbol sitesym = TreeInfo.symbol(tree.selected);
1957 boolean selectSuperPrev = env.info.selectSuper;
1958 env.info.selectSuper =
1959 sitesym != null &&
1960 sitesym.name == names._super;
1962 // If selected expression is polymorphic, strip
1963 // type parameters and remember in env.info.tvars, so that
1964 // they can be added later (in Attr.checkId and Infer.instantiateMethod).
1965 if (tree.selected.type.tag == FORALL) {
1966 ForAll pstype = (ForAll)tree.selected.type;
1967 env.info.tvars = pstype.tvars;
1968 site = tree.selected.type = pstype.qtype;
1969 }
1971 // Determine the symbol represented by the selection.
1972 env.info.varArgs = false;
1973 Symbol sym = selectSym(tree, site, env, pt, pkind);
1974 if (sym.exists() && !isType(sym) && (pkind & (PCK | TYP)) != 0) {
1975 site = capture(site);
1976 sym = selectSym(tree, site, env, pt, pkind);
1977 }
1978 boolean varArgs = env.info.varArgs;
1979 tree.sym = sym;
1981 if (site.tag == TYPEVAR && !isType(sym) && sym.kind != ERR) {
1982 while (site.tag == TYPEVAR) site = site.getUpperBound();
1983 site = capture(site);
1984 }
1986 // If that symbol is a variable, ...
1987 if (sym.kind == VAR) {
1988 VarSymbol v = (VarSymbol)sym;
1990 // ..., evaluate its initializer, if it has one, and check for
1991 // illegal forward reference.
1992 checkInit(tree, env, v, true);
1994 // If we are expecting a variable (as opposed to a value), check
1995 // that the variable is assignable in the current environment.
1996 if (pkind == VAR)
1997 checkAssignable(tree.pos(), v, tree.selected, env);
1998 }
2000 // Disallow selecting a type from an expression
2001 if (isType(sym) && (sitesym==null || (sitesym.kind&(TYP|PCK)) == 0)) {
2002 tree.type = check(tree.selected, pt,
2003 sitesym == null ? VAL : sitesym.kind, TYP|PCK, pt);
2004 }
2006 if (isType(sitesym)) {
2007 if (sym.name == names._this) {
2008 // If `C' is the currently compiled class, check that
2009 // C.this' does not appear in a call to a super(...)
2010 if (env.info.isSelfCall &&
2011 site.tsym == env.enclClass.sym) {
2012 chk.earlyRefError(tree.pos(), sym);
2013 }
2014 } else {
2015 // Check if type-qualified fields or methods are static (JLS)
2016 if ((sym.flags() & STATIC) == 0 &&
2017 sym.name != names._super &&
2018 (sym.kind == VAR || sym.kind == MTH)) {
2019 rs.access(rs.new StaticError(sym),
2020 tree.pos(), site, sym.name, true);
2021 }
2022 }
2023 } else if (sym.kind != ERR && (sym.flags() & STATIC) != 0 && sym.name != names._class) {
2024 // If the qualified item is not a type and the selected item is static, report
2025 // a warning. Make allowance for the class of an array type e.g. Object[].class)
2026 chk.warnStatic(tree, "static.not.qualified.by.type", Kinds.kindName(sym.kind), sym.owner);
2027 }
2029 // If we are selecting an instance member via a `super', ...
2030 if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
2032 // Check that super-qualified symbols are not abstract (JLS)
2033 rs.checkNonAbstract(tree.pos(), sym);
2035 if (site.isRaw()) {
2036 // Determine argument types for site.
2037 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
2038 if (site1 != null) site = site1;
2039 }
2040 }
2042 env.info.selectSuper = selectSuperPrev;
2043 result = checkId(tree, site, sym, env, pkind, pt, varArgs);
2044 env.info.tvars = List.nil();
2045 }
2046 //where
2047 /** Determine symbol referenced by a Select expression,
2048 *
2049 * @param tree The select tree.
2050 * @param site The type of the selected expression,
2051 * @param env The current environment.
2052 * @param pt The current prototype.
2053 * @param pkind The expected kind(s) of the Select expression.
2054 */
2055 private Symbol selectSym(JCFieldAccess tree,
2056 Type site,
2057 Env<AttrContext> env,
2058 Type pt,
2059 int pkind) {
2060 DiagnosticPosition pos = tree.pos();
2061 Name name = tree.name;
2063 switch (site.tag) {
2064 case PACKAGE:
2065 return rs.access(
2066 rs.findIdentInPackage(env, site.tsym, name, pkind),
2067 pos, site, name, true);
2068 case ARRAY:
2069 case CLASS:
2070 if (pt.tag == METHOD || pt.tag == FORALL) {
2071 return rs.resolveQualifiedMethod(
2072 pos, env, site, name, pt.getParameterTypes(), pt.getTypeArguments());
2073 } else if (name == names._this || name == names._super) {
2074 return rs.resolveSelf(pos, env, site.tsym, name);
2075 } else if (name == names._class) {
2076 // In this case, we have already made sure in
2077 // visitSelect that qualifier expression is a type.
2078 Type t = syms.classType;
2079 List<Type> typeargs = allowGenerics
2080 ? List.of(types.erasure(site))
2081 : List.<Type>nil();
2082 t = new ClassType(t.getEnclosingType(), typeargs, t.tsym);
2083 return new VarSymbol(
2084 STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
2085 } else {
2086 // We are seeing a plain identifier as selector.
2087 Symbol sym = rs.findIdentInType(env, site, name, pkind);
2088 if ((pkind & ERRONEOUS) == 0)
2089 sym = rs.access(sym, pos, site, name, true);
2090 return sym;
2091 }
2092 case WILDCARD:
2093 throw new AssertionError(tree);
2094 case TYPEVAR:
2095 // Normally, site.getUpperBound() shouldn't be null.
2096 // It should only happen during memberEnter/attribBase
2097 // when determining the super type which *must* be
2098 // done before attributing the type variables. In
2099 // other words, we are seeing this illegal program:
2100 // class B<T> extends A<T.foo> {}
2101 Symbol sym = (site.getUpperBound() != null)
2102 ? selectSym(tree, capture(site.getUpperBound()), env, pt, pkind)
2103 : null;
2104 if (sym == null) {
2105 log.error(pos, "type.var.cant.be.deref");
2106 return syms.errSymbol;
2107 } else {
2108 Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
2109 rs.new AccessError(env, site, sym) :
2110 sym;
2111 rs.access(sym2, pos, site, name, true);
2112 return sym;
2113 }
2114 case ERROR:
2115 // preserve identifier names through errors
2116 return types.createErrorType(name, site.tsym, site).tsym;
2117 default:
2118 // The qualifier expression is of a primitive type -- only
2119 // .class is allowed for these.
2120 if (name == names._class) {
2121 // In this case, we have already made sure in Select that
2122 // qualifier expression is a type.
2123 Type t = syms.classType;
2124 Type arg = types.boxedClass(site).type;
2125 t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym);
2126 return new VarSymbol(
2127 STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
2128 } else {
2129 log.error(pos, "cant.deref", site);
2130 return syms.errSymbol;
2131 }
2132 }
2133 }
2135 /** Determine type of identifier or select expression and check that
2136 * (1) the referenced symbol is not deprecated
2137 * (2) the symbol's type is safe (@see checkSafe)
2138 * (3) if symbol is a variable, check that its type and kind are
2139 * compatible with the prototype and protokind.
2140 * (4) if symbol is an instance field of a raw type,
2141 * which is being assigned to, issue an unchecked warning if its
2142 * type changes under erasure.
2143 * (5) if symbol is an instance method of a raw type, issue an
2144 * unchecked warning if its argument types change under erasure.
2145 * If checks succeed:
2146 * If symbol is a constant, return its constant type
2147 * else if symbol is a method, return its result type
2148 * otherwise return its type.
2149 * Otherwise return errType.
2150 *
2151 * @param tree The syntax tree representing the identifier
2152 * @param site If this is a select, the type of the selected
2153 * expression, otherwise the type of the current class.
2154 * @param sym The symbol representing the identifier.
2155 * @param env The current environment.
2156 * @param pkind The set of expected kinds.
2157 * @param pt The expected type.
2158 */
2159 Type checkId(JCTree tree,
2160 Type site,
2161 Symbol sym,
2162 Env<AttrContext> env,
2163 int pkind,
2164 Type pt,
2165 boolean useVarargs) {
2166 if (pt.isErroneous()) return types.createErrorType(site);
2167 Type owntype; // The computed type of this identifier occurrence.
2168 switch (sym.kind) {
2169 case TYP:
2170 // For types, the computed type equals the symbol's type,
2171 // except for two situations:
2172 owntype = sym.type;
2173 if (owntype.tag == CLASS) {
2174 Type ownOuter = owntype.getEnclosingType();
2176 // (a) If the symbol's type is parameterized, erase it
2177 // because no type parameters were given.
2178 // We recover generic outer type later in visitTypeApply.
2179 if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
2180 owntype = types.erasure(owntype);
2181 }
2183 // (b) If the symbol's type is an inner class, then
2184 // we have to interpret its outer type as a superclass
2185 // of the site type. Example:
2186 //
2187 // class Tree<A> { class Visitor { ... } }
2188 // class PointTree extends Tree<Point> { ... }
2189 // ...PointTree.Visitor...
2190 //
2191 // Then the type of the last expression above is
2192 // Tree<Point>.Visitor.
2193 else if (ownOuter.tag == CLASS && site != ownOuter) {
2194 Type normOuter = site;
2195 if (normOuter.tag == CLASS)
2196 normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
2197 if (normOuter == null) // perhaps from an import
2198 normOuter = types.erasure(ownOuter);
2199 if (normOuter != ownOuter)
2200 owntype = new ClassType(
2201 normOuter, List.<Type>nil(), owntype.tsym);
2202 }
2203 }
2204 break;
2205 case VAR:
2206 VarSymbol v = (VarSymbol)sym;
2207 // Test (4): if symbol is an instance field of a raw type,
2208 // which is being assigned to, issue an unchecked warning if
2209 // its type changes under erasure.
2210 if (allowGenerics &&
2211 pkind == VAR &&
2212 v.owner.kind == TYP &&
2213 (v.flags() & STATIC) == 0 &&
2214 (site.tag == CLASS || site.tag == TYPEVAR)) {
2215 Type s = types.asOuterSuper(site, v.owner);
2216 if (s != null &&
2217 s.isRaw() &&
2218 !types.isSameType(v.type, v.erasure(types))) {
2219 chk.warnUnchecked(tree.pos(),
2220 "unchecked.assign.to.var",
2221 v, s);
2222 }
2223 }
2224 // The computed type of a variable is the type of the
2225 // variable symbol, taken as a member of the site type.
2226 owntype = (sym.owner.kind == TYP &&
2227 sym.name != names._this && sym.name != names._super)
2228 ? types.memberType(site, sym)
2229 : sym.type;
2231 if (env.info.tvars.nonEmpty()) {
2232 Type owntype1 = new ForAll(env.info.tvars, owntype);
2233 for (List<Type> l = env.info.tvars; l.nonEmpty(); l = l.tail)
2234 if (!owntype.contains(l.head)) {
2235 log.error(tree.pos(), "undetermined.type", owntype1);
2236 owntype1 = types.createErrorType(owntype1);
2237 }
2238 owntype = owntype1;
2239 }
2241 // If the variable is a constant, record constant value in
2242 // computed type.
2243 if (v.getConstValue() != null && isStaticReference(tree))
2244 owntype = owntype.constType(v.getConstValue());
2246 if (pkind == VAL) {
2247 owntype = capture(owntype); // capture "names as expressions"
2248 }
2249 break;
2250 case MTH: {
2251 JCMethodInvocation app = (JCMethodInvocation)env.tree;
2252 owntype = checkMethod(site, sym, env, app.args,
2253 pt.getParameterTypes(), pt.getTypeArguments(),
2254 env.info.varArgs);
2255 break;
2256 }
2257 case PCK: case ERR:
2258 owntype = sym.type;
2259 break;
2260 default:
2261 throw new AssertionError("unexpected kind: " + sym.kind +
2262 " in tree " + tree);
2263 }
2265 // Test (1): emit a `deprecation' warning if symbol is deprecated.
2266 // (for constructors, the error was given when the constructor was
2267 // resolved)
2268 if (sym.name != names.init &&
2269 (sym.flags() & DEPRECATED) != 0 &&
2270 (env.info.scope.owner.flags() & DEPRECATED) == 0 &&
2271 sym.outermostClass() != env.info.scope.owner.outermostClass())
2272 chk.warnDeprecated(tree.pos(), sym);
2274 if ((sym.flags() & PROPRIETARY) != 0) {
2275 if (enableSunApiLintControl)
2276 chk.warnSunApi(tree.pos(), "sun.proprietary", sym);
2277 else
2278 log.strictWarning(tree.pos(), "sun.proprietary", sym);
2279 }
2281 // Test (3): if symbol is a variable, check that its type and
2282 // kind are compatible with the prototype and protokind.
2283 return check(tree, owntype, sym.kind, pkind, pt);
2284 }
2286 /** Check that variable is initialized and evaluate the variable's
2287 * initializer, if not yet done. Also check that variable is not
2288 * referenced before it is defined.
2289 * @param tree The tree making up the variable reference.
2290 * @param env The current environment.
2291 * @param v The variable's symbol.
2292 */
2293 private void checkInit(JCTree tree,
2294 Env<AttrContext> env,
2295 VarSymbol v,
2296 boolean onlyWarning) {
2297 // System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " +
2298 // tree.pos + " " + v.pos + " " +
2299 // Resolve.isStatic(env));//DEBUG
2301 // A forward reference is diagnosed if the declaration position
2302 // of the variable is greater than the current tree position
2303 // and the tree and variable definition occur in the same class
2304 // definition. Note that writes don't count as references.
2305 // This check applies only to class and instance
2306 // variables. Local variables follow different scope rules,
2307 // and are subject to definite assignment checking.
2308 if ((env.info.enclVar == v || v.pos > tree.pos) &&
2309 v.owner.kind == TYP &&
2310 canOwnInitializer(env.info.scope.owner) &&
2311 v.owner == env.info.scope.owner.enclClass() &&
2312 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
2313 (env.tree.getTag() != JCTree.ASSIGN ||
2314 TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
2315 String suffix = (env.info.enclVar == v) ?
2316 "self.ref" : "forward.ref";
2317 if (!onlyWarning || isStaticEnumField(v)) {
2318 log.error(tree.pos(), "illegal." + suffix);
2319 } else if (useBeforeDeclarationWarning) {
2320 log.warning(tree.pos(), suffix, v);
2321 }
2322 }
2324 v.getConstValue(); // ensure initializer is evaluated
2326 checkEnumInitializer(tree, env, v);
2327 }
2329 /**
2330 * Check for illegal references to static members of enum. In
2331 * an enum type, constructors and initializers may not
2332 * reference its static members unless they are constant.
2333 *
2334 * @param tree The tree making up the variable reference.
2335 * @param env The current environment.
2336 * @param v The variable's symbol.
2337 * @see JLS 3rd Ed. (8.9 Enums)
2338 */
2339 private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
2340 // JLS 3rd Ed.:
2341 //
2342 // "It is a compile-time error to reference a static field
2343 // of an enum type that is not a compile-time constant
2344 // (15.28) from constructors, instance initializer blocks,
2345 // or instance variable initializer expressions of that
2346 // type. It is a compile-time error for the constructors,
2347 // instance initializer blocks, or instance variable
2348 // initializer expressions of an enum constant e to refer
2349 // to itself or to an enum constant of the same type that
2350 // is declared to the right of e."
2351 if (isStaticEnumField(v)) {
2352 ClassSymbol enclClass = env.info.scope.owner.enclClass();
2354 if (enclClass == null || enclClass.owner == null)
2355 return;
2357 // See if the enclosing class is the enum (or a
2358 // subclass thereof) declaring v. If not, this
2359 // reference is OK.
2360 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
2361 return;
2363 // If the reference isn't from an initializer, then
2364 // the reference is OK.
2365 if (!Resolve.isInitializer(env))
2366 return;
2368 log.error(tree.pos(), "illegal.enum.static.ref");
2369 }
2370 }
2372 /** Is the given symbol a static, non-constant field of an Enum?
2373 * Note: enum literals should not be regarded as such
2374 */
2375 private boolean isStaticEnumField(VarSymbol v) {
2376 return Flags.isEnum(v.owner) &&
2377 Flags.isStatic(v) &&
2378 !Flags.isConstant(v) &&
2379 v.name != names._class;
2380 }
2382 /** Can the given symbol be the owner of code which forms part
2383 * if class initialization? This is the case if the symbol is
2384 * a type or field, or if the symbol is the synthetic method.
2385 * owning a block.
2386 */
2387 private boolean canOwnInitializer(Symbol sym) {
2388 return
2389 (sym.kind & (VAR | TYP)) != 0 ||
2390 (sym.kind == MTH && (sym.flags() & BLOCK) != 0);
2391 }
2393 Warner noteWarner = new Warner();
2395 /**
2396 * Check that method arguments conform to its instantation.
2397 **/
2398 public Type checkMethod(Type site,
2399 Symbol sym,
2400 Env<AttrContext> env,
2401 final List<JCExpression> argtrees,
2402 List<Type> argtypes,
2403 List<Type> typeargtypes,
2404 boolean useVarargs) {
2405 // Test (5): if symbol is an instance method of a raw type, issue
2406 // an unchecked warning if its argument types change under erasure.
2407 if (allowGenerics &&
2408 (sym.flags() & STATIC) == 0 &&
2409 (site.tag == CLASS || site.tag == TYPEVAR)) {
2410 Type s = types.asOuterSuper(site, sym.owner);
2411 if (s != null && s.isRaw() &&
2412 !types.isSameTypes(sym.type.getParameterTypes(),
2413 sym.erasure(types).getParameterTypes())) {
2414 chk.warnUnchecked(env.tree.pos(),
2415 "unchecked.call.mbr.of.raw.type",
2416 sym, s);
2417 }
2418 }
2420 // Compute the identifier's instantiated type.
2421 // For methods, we need to compute the instance type by
2422 // Resolve.instantiate from the symbol's type as well as
2423 // any type arguments and value arguments.
2424 noteWarner.warned = false;
2425 Type owntype = rs.instantiate(env,
2426 site,
2427 sym,
2428 argtypes,
2429 typeargtypes,
2430 true,
2431 useVarargs,
2432 noteWarner);
2433 boolean warned = noteWarner.warned;
2435 // If this fails, something went wrong; we should not have
2436 // found the identifier in the first place.
2437 if (owntype == null) {
2438 if (!pt.isErroneous())
2439 log.error(env.tree.pos(),
2440 "internal.error.cant.instantiate",
2441 sym, site,
2442 Type.toString(pt.getParameterTypes()));
2443 owntype = types.createErrorType(site);
2444 } else {
2445 // System.out.println("call : " + env.tree);
2446 // System.out.println("method : " + owntype);
2447 // System.out.println("actuals: " + argtypes);
2448 List<Type> formals = owntype.getParameterTypes();
2449 Type last = useVarargs ? formals.last() : null;
2450 if (sym.name==names.init &&
2451 sym.owner == syms.enumSym)
2452 formals = formals.tail.tail;
2453 List<JCExpression> args = argtrees;
2454 while (formals.head != last) {
2455 JCTree arg = args.head;
2456 Warner warn = chk.convertWarner(arg.pos(), arg.type, formals.head);
2457 assertConvertible(arg, arg.type, formals.head, warn);
2458 warned |= warn.warned;
2459 args = args.tail;
2460 formals = formals.tail;
2461 }
2462 if (useVarargs) {
2463 Type varArg = types.elemtype(last);
2464 while (args.tail != null) {
2465 JCTree arg = args.head;
2466 Warner warn = chk.convertWarner(arg.pos(), arg.type, varArg);
2467 assertConvertible(arg, arg.type, varArg, warn);
2468 warned |= warn.warned;
2469 args = args.tail;
2470 }
2471 } else if ((sym.flags() & VARARGS) != 0 && allowVarargs) {
2472 // non-varargs call to varargs method
2473 Type varParam = owntype.getParameterTypes().last();
2474 Type lastArg = argtypes.last();
2475 if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) &&
2476 !types.isSameType(types.erasure(varParam), types.erasure(lastArg)))
2477 log.warning(argtrees.last().pos(), "inexact.non-varargs.call",
2478 types.elemtype(varParam),
2479 varParam);
2480 }
2482 if (warned && sym.type.tag == FORALL) {
2483 chk.warnUnchecked(env.tree.pos(),
2484 "unchecked.meth.invocation.applied",
2485 kindName(sym),
2486 sym.name,
2487 rs.methodArguments(sym.type.getParameterTypes()),
2488 rs.methodArguments(argtypes),
2489 kindName(sym.location()),
2490 sym.location());
2491 owntype = new MethodType(owntype.getParameterTypes(),
2492 types.erasure(owntype.getReturnType()),
2493 owntype.getThrownTypes(),
2494 syms.methodClass);
2495 }
2496 if (useVarargs) {
2497 JCTree tree = env.tree;
2498 Type argtype = owntype.getParameterTypes().last();
2499 if (!types.isReifiable(argtype))
2500 chk.warnUnchecked(env.tree.pos(),
2501 "unchecked.generic.array.creation",
2502 argtype);
2503 Type elemtype = types.elemtype(argtype);
2504 switch (tree.getTag()) {
2505 case JCTree.APPLY:
2506 ((JCMethodInvocation) tree).varargsElement = elemtype;
2507 break;
2508 case JCTree.NEWCLASS:
2509 ((JCNewClass) tree).varargsElement = elemtype;
2510 break;
2511 default:
2512 throw new AssertionError(""+tree);
2513 }
2514 }
2515 }
2516 return owntype;
2517 }
2519 private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) {
2520 if (types.isConvertible(actual, formal, warn))
2521 return;
2523 if (formal.isCompound()
2524 && types.isSubtype(actual, types.supertype(formal))
2525 && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn))
2526 return;
2528 if (false) {
2529 // TODO: make assertConvertible work
2530 chk.typeError(tree.pos(), diags.fragment("incompatible.types"), actual, formal);
2531 throw new AssertionError("Tree: " + tree
2532 + " actual:" + actual
2533 + " formal: " + formal);
2534 }
2535 }
2537 public void visitLiteral(JCLiteral tree) {
2538 result = check(
2539 tree, litType(tree.typetag).constType(tree.value), VAL, pkind, pt);
2540 }
2541 //where
2542 /** Return the type of a literal with given type tag.
2543 */
2544 Type litType(int tag) {
2545 return (tag == TypeTags.CLASS) ? syms.stringType : syms.typeOfTag[tag];
2546 }
2548 public void visitTypeIdent(JCPrimitiveTypeTree tree) {
2549 result = check(tree, syms.typeOfTag[tree.typetag], TYP, pkind, pt);
2550 }
2552 public void visitTypeArray(JCArrayTypeTree tree) {
2553 Type etype = attribType(tree.elemtype, env);
2554 Type type = new ArrayType(etype, syms.arrayClass);
2555 result = check(tree, type, TYP, pkind, pt);
2556 }
2558 /** Visitor method for parameterized types.
2559 * Bound checking is left until later, since types are attributed
2560 * before supertype structure is completely known
2561 */
2562 public void visitTypeApply(JCTypeApply tree) {
2563 Type owntype = types.createErrorType(tree.type);
2565 // Attribute functor part of application and make sure it's a class.
2566 Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
2568 // Attribute type parameters
2569 List<Type> actuals = attribTypes(tree.arguments, env);
2571 if (clazztype.tag == CLASS) {
2572 List<Type> formals = clazztype.tsym.type.getTypeArguments();
2574 if (actuals.length() == formals.length() || actuals.isEmpty()) {
2575 List<Type> a = actuals;
2576 List<Type> f = formals;
2577 while (a.nonEmpty()) {
2578 a.head = a.head.withTypeVar(f.head);
2579 a = a.tail;
2580 f = f.tail;
2581 }
2582 // Compute the proper generic outer
2583 Type clazzOuter = clazztype.getEnclosingType();
2584 if (clazzOuter.tag == CLASS) {
2585 Type site;
2586 JCExpression clazz = TreeInfo.typeIn(tree.clazz);
2587 if (clazz.getTag() == JCTree.IDENT) {
2588 site = env.enclClass.sym.type;
2589 } else if (clazz.getTag() == JCTree.SELECT) {
2590 site = ((JCFieldAccess) clazz).selected.type;
2591 } else throw new AssertionError(""+tree);
2592 if (clazzOuter.tag == CLASS && site != clazzOuter) {
2593 if (site.tag == CLASS)
2594 site = types.asOuterSuper(site, clazzOuter.tsym);
2595 if (site == null)
2596 site = types.erasure(clazzOuter);
2597 clazzOuter = site;
2598 }
2599 }
2600 if (actuals.nonEmpty()) {
2601 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym);
2602 }
2603 else if (TreeInfo.isDiamond(tree)) {
2604 //a type apply with no explicit type arguments - diamond operator
2605 //the result type is a forall F where F's tvars are the type-variables
2606 //that will be inferred when F is checked against the expected type
2607 List<Type> ftvars = clazztype.tsym.type.getTypeArguments();
2608 List<Type> new_tvars = types.newInstances(ftvars);
2609 clazztype = new ClassType(clazzOuter, new_tvars, clazztype.tsym);
2610 owntype = new ForAll(new_tvars, clazztype);
2611 }
2612 } else {
2613 if (formals.length() != 0) {
2614 log.error(tree.pos(), "wrong.number.type.args",
2615 Integer.toString(formals.length()));
2616 } else {
2617 log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym);
2618 }
2619 owntype = types.createErrorType(tree.type);
2620 }
2621 }
2622 result = check(tree, owntype, TYP, pkind, pt);
2623 }
2625 public void visitTypeParameter(JCTypeParameter tree) {
2626 TypeVar a = (TypeVar)tree.type;
2627 Set<Type> boundSet = new HashSet<Type>();
2628 if (a.bound.isErroneous())
2629 return;
2630 List<Type> bs = types.getBounds(a);
2631 if (tree.bounds.nonEmpty()) {
2632 // accept class or interface or typevar as first bound.
2633 Type b = checkBase(bs.head, tree.bounds.head, env, false, false, false);
2634 boundSet.add(types.erasure(b));
2635 if (b.isErroneous()) {
2636 a.bound = b;
2637 }
2638 else if (b.tag == TYPEVAR) {
2639 // if first bound was a typevar, do not accept further bounds.
2640 if (tree.bounds.tail.nonEmpty()) {
2641 log.error(tree.bounds.tail.head.pos(),
2642 "type.var.may.not.be.followed.by.other.bounds");
2643 log.unrecoverableError = true;
2644 tree.bounds = List.of(tree.bounds.head);
2645 a.bound = bs.head;
2646 }
2647 } else {
2648 // if first bound was a class or interface, accept only interfaces
2649 // as further bounds.
2650 for (JCExpression bound : tree.bounds.tail) {
2651 bs = bs.tail;
2652 Type i = checkBase(bs.head, bound, env, false, true, false);
2653 if (i.isErroneous())
2654 a.bound = i;
2655 else if (i.tag == CLASS)
2656 chk.checkNotRepeated(bound.pos(), types.erasure(i), boundSet);
2657 }
2658 }
2659 }
2660 bs = types.getBounds(a);
2662 // in case of multiple bounds ...
2663 if (bs.length() > 1) {
2664 // ... the variable's bound is a class type flagged COMPOUND
2665 // (see comment for TypeVar.bound).
2666 // In this case, generate a class tree that represents the
2667 // bound class, ...
2668 JCTree extending;
2669 List<JCExpression> implementing;
2670 if ((bs.head.tsym.flags() & INTERFACE) == 0) {
2671 extending = tree.bounds.head;
2672 implementing = tree.bounds.tail;
2673 } else {
2674 extending = null;
2675 implementing = tree.bounds;
2676 }
2677 JCClassDecl cd = make.at(tree.pos).ClassDef(
2678 make.Modifiers(PUBLIC | ABSTRACT),
2679 tree.name, List.<JCTypeParameter>nil(),
2680 extending, implementing, List.<JCTree>nil());
2682 ClassSymbol c = (ClassSymbol)a.getUpperBound().tsym;
2683 assert (c.flags() & COMPOUND) != 0;
2684 cd.sym = c;
2685 c.sourcefile = env.toplevel.sourcefile;
2687 // ... and attribute the bound class
2688 c.flags_field |= UNATTRIBUTED;
2689 Env<AttrContext> cenv = enter.classEnv(cd, env);
2690 enter.typeEnvs.put(c, cenv);
2691 }
2692 }
2695 public void visitWildcard(JCWildcard tree) {
2696 //- System.err.println("visitWildcard("+tree+");");//DEBUG
2697 Type type = (tree.kind.kind == BoundKind.UNBOUND)
2698 ? syms.objectType
2699 : attribType(tree.inner, env);
2700 result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
2701 tree.kind.kind,
2702 syms.boundClass),
2703 TYP, pkind, pt);
2704 }
2706 public void visitAnnotation(JCAnnotation tree) {
2707 log.error(tree.pos(), "annotation.not.valid.for.type", pt);
2708 result = tree.type = syms.errType;
2709 }
2711 public void visitAnnotatedType(JCAnnotatedType tree) {
2712 result = tree.type = attribType(tree.getUnderlyingType(), env);
2713 }
2715 public void visitErroneous(JCErroneous tree) {
2716 if (tree.errs != null)
2717 for (JCTree err : tree.errs)
2718 attribTree(err, env, ERR, pt);
2719 result = tree.type = syms.errType;
2720 }
2722 /** Default visitor method for all other trees.
2723 */
2724 public void visitTree(JCTree tree) {
2725 throw new AssertionError();
2726 }
2728 /** Main method: attribute class definition associated with given class symbol.
2729 * reporting completion failures at the given position.
2730 * @param pos The source position at which completion errors are to be
2731 * reported.
2732 * @param c The class symbol whose definition will be attributed.
2733 */
2734 public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
2735 try {
2736 annotate.flush();
2737 attribClass(c);
2738 } catch (CompletionFailure ex) {
2739 chk.completionError(pos, ex);
2740 }
2741 }
2743 /** Attribute class definition associated with given class symbol.
2744 * @param c The class symbol whose definition will be attributed.
2745 */
2746 void attribClass(ClassSymbol c) throws CompletionFailure {
2747 if (c.type.tag == ERROR) return;
2749 // Check for cycles in the inheritance graph, which can arise from
2750 // ill-formed class files.
2751 chk.checkNonCyclic(null, c.type);
2753 Type st = types.supertype(c.type);
2754 if ((c.flags_field & Flags.COMPOUND) == 0) {
2755 // First, attribute superclass.
2756 if (st.tag == CLASS)
2757 attribClass((ClassSymbol)st.tsym);
2759 // Next attribute owner, if it is a class.
2760 if (c.owner.kind == TYP && c.owner.type.tag == CLASS)
2761 attribClass((ClassSymbol)c.owner);
2762 }
2764 // The previous operations might have attributed the current class
2765 // if there was a cycle. So we test first whether the class is still
2766 // UNATTRIBUTED.
2767 if ((c.flags_field & UNATTRIBUTED) != 0) {
2768 c.flags_field &= ~UNATTRIBUTED;
2770 // Get environment current at the point of class definition.
2771 Env<AttrContext> env = enter.typeEnvs.get(c);
2773 // The info.lint field in the envs stored in enter.typeEnvs is deliberately uninitialized,
2774 // because the annotations were not available at the time the env was created. Therefore,
2775 // we look up the environment chain for the first enclosing environment for which the
2776 // lint value is set. Typically, this is the parent env, but might be further if there
2777 // are any envs created as a result of TypeParameter nodes.
2778 Env<AttrContext> lintEnv = env;
2779 while (lintEnv.info.lint == null)
2780 lintEnv = lintEnv.next;
2782 // Having found the enclosing lint value, we can initialize the lint value for this class
2783 env.info.lint = lintEnv.info.lint.augment(c.attributes_field, c.flags());
2785 Lint prevLint = chk.setLint(env.info.lint);
2786 JavaFileObject prev = log.useSource(c.sourcefile);
2788 try {
2789 // java.lang.Enum may not be subclassed by a non-enum
2790 if (st.tsym == syms.enumSym &&
2791 ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
2792 log.error(env.tree.pos(), "enum.no.subclassing");
2794 // Enums may not be extended by source-level classes
2795 if (st.tsym != null &&
2796 ((st.tsym.flags_field & Flags.ENUM) != 0) &&
2797 ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0) &&
2798 !target.compilerBootstrap(c)) {
2799 log.error(env.tree.pos(), "enum.types.not.extensible");
2800 }
2801 attribClassBody(env, c);
2803 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
2804 } finally {
2805 log.useSource(prev);
2806 chk.setLint(prevLint);
2807 }
2809 }
2810 }
2812 public void visitImport(JCImport tree) {
2813 // nothing to do
2814 }
2816 /** Finish the attribution of a class. */
2817 private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
2818 JCClassDecl tree = (JCClassDecl)env.tree;
2819 assert c == tree.sym;
2821 // Validate annotations
2822 chk.validateAnnotations(tree.mods.annotations, c);
2824 // Validate type parameters, supertype and interfaces.
2825 attribBounds(tree.typarams);
2826 chk.validate(tree.typarams, env);
2827 chk.validate(tree.extending, env);
2828 chk.validate(tree.implementing, env);
2830 // If this is a non-abstract class, check that it has no abstract
2831 // methods or unimplemented methods of an implemented interface.
2832 if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
2833 if (!relax)
2834 chk.checkAllDefined(tree.pos(), c);
2835 }
2837 if ((c.flags() & ANNOTATION) != 0) {
2838 if (tree.implementing.nonEmpty())
2839 log.error(tree.implementing.head.pos(),
2840 "cant.extend.intf.annotation");
2841 if (tree.typarams.nonEmpty())
2842 log.error(tree.typarams.head.pos(),
2843 "intf.annotation.cant.have.type.params");
2844 } else {
2845 // Check that all extended classes and interfaces
2846 // are compatible (i.e. no two define methods with same arguments
2847 // yet different return types). (JLS 8.4.6.3)
2848 chk.checkCompatibleSupertypes(tree.pos(), c.type);
2849 }
2851 // Check that class does not import the same parameterized interface
2852 // with two different argument lists.
2853 chk.checkClassBounds(tree.pos(), c.type);
2855 tree.type = c.type;
2857 boolean assertsEnabled = false;
2858 assert assertsEnabled = true;
2859 if (assertsEnabled) {
2860 for (List<JCTypeParameter> l = tree.typarams;
2861 l.nonEmpty(); l = l.tail)
2862 assert env.info.scope.lookup(l.head.name).scope != null;
2863 }
2865 // Check that a generic class doesn't extend Throwable
2866 if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
2867 log.error(tree.extending.pos(), "generic.throwable");
2869 // Check that all methods which implement some
2870 // method conform to the method they implement.
2871 chk.checkImplementations(tree);
2873 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
2874 // Attribute declaration
2875 attribStat(l.head, env);
2876 // Check that declarations in inner classes are not static (JLS 8.1.2)
2877 // Make an exception for static constants.
2878 if (c.owner.kind != PCK &&
2879 ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
2880 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
2881 Symbol sym = null;
2882 if (l.head.getTag() == JCTree.VARDEF) sym = ((JCVariableDecl) l.head).sym;
2883 if (sym == null ||
2884 sym.kind != VAR ||
2885 ((VarSymbol) sym).getConstValue() == null)
2886 log.error(l.head.pos(), "icls.cant.have.static.decl");
2887 }
2888 }
2890 // Check for cycles among non-initial constructors.
2891 chk.checkCyclicConstructors(tree);
2893 // Check for cycles among annotation elements.
2894 chk.checkNonCyclicElements(tree);
2896 // Check for proper use of serialVersionUID
2897 if (env.info.lint.isEnabled(Lint.LintCategory.SERIAL) &&
2898 isSerializable(c) &&
2899 (c.flags() & Flags.ENUM) == 0 &&
2900 (c.flags() & ABSTRACT) == 0) {
2901 checkSerialVersionUID(tree, c);
2902 }
2904 // Check type annotations applicability rules
2905 validateTypeAnnotations(tree);
2906 }
2907 // where
2908 /** check if a class is a subtype of Serializable, if that is available. */
2909 private boolean isSerializable(ClassSymbol c) {
2910 try {
2911 syms.serializableType.complete();
2912 }
2913 catch (CompletionFailure e) {
2914 return false;
2915 }
2916 return types.isSubtype(c.type, syms.serializableType);
2917 }
2919 /** Check that an appropriate serialVersionUID member is defined. */
2920 private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
2922 // check for presence of serialVersionUID
2923 Scope.Entry e = c.members().lookup(names.serialVersionUID);
2924 while (e.scope != null && e.sym.kind != VAR) e = e.next();
2925 if (e.scope == null) {
2926 log.warning(tree.pos(), "missing.SVUID", c);
2927 return;
2928 }
2930 // check that it is static final
2931 VarSymbol svuid = (VarSymbol)e.sym;
2932 if ((svuid.flags() & (STATIC | FINAL)) !=
2933 (STATIC | FINAL))
2934 log.warning(TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c);
2936 // check that it is long
2937 else if (svuid.type.tag != TypeTags.LONG)
2938 log.warning(TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c);
2940 // check constant
2941 else if (svuid.getConstValue() == null)
2942 log.warning(TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c);
2943 }
2945 private Type capture(Type type) {
2946 return types.capture(type);
2947 }
2949 private void validateTypeAnnotations(JCTree tree) {
2950 tree.accept(typeAnnotationsValidator);
2951 }
2952 //where
2953 private final JCTree.Visitor typeAnnotationsValidator =
2954 new TreeScanner() {
2955 public void visitAnnotation(JCAnnotation tree) {
2956 if (tree instanceof JCTypeAnnotation) {
2957 chk.validateTypeAnnotation((JCTypeAnnotation)tree, false);
2958 }
2959 super.visitAnnotation(tree);
2960 }
2961 public void visitTypeParameter(JCTypeParameter tree) {
2962 chk.validateTypeAnnotations(tree.annotations, true);
2963 // don't call super. skip type annotations
2964 scan(tree.bounds);
2965 }
2966 public void visitMethodDef(JCMethodDecl tree) {
2967 // need to check static methods
2968 if ((tree.sym.flags() & Flags.STATIC) != 0) {
2969 for (JCTypeAnnotation a : tree.receiverAnnotations) {
2970 if (chk.isTypeAnnotation(a, false))
2971 log.error(a.pos(), "annotation.type.not.applicable");
2972 }
2973 }
2974 super.visitMethodDef(tree);
2975 }
2976 };
2977 }