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