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