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