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