Tue, 09 Oct 2012 19:10:00 -0700
8000663: clean up langtools imports
Reviewed-by: darcy
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;
31 import javax.lang.model.element.ElementKind;
32 import javax.tools.JavaFileObject;
34 import com.sun.source.tree.IdentifierTree;
35 import com.sun.source.tree.MemberReferenceTree.ReferenceMode;
36 import com.sun.source.tree.MemberSelectTree;
37 import com.sun.source.tree.TreeVisitor;
38 import com.sun.source.util.SimpleTreeVisitor;
39 import com.sun.tools.javac.code.*;
40 import com.sun.tools.javac.code.Lint.LintCategory;
41 import com.sun.tools.javac.code.Symbol.*;
42 import com.sun.tools.javac.code.Type.*;
43 import com.sun.tools.javac.comp.Check.CheckContext;
44 import com.sun.tools.javac.comp.DeferredAttr.AttrMode;
45 import com.sun.tools.javac.comp.Infer.InferenceContext;
46 import com.sun.tools.javac.comp.Infer.InferenceContext.FreeTypeListener;
47 import com.sun.tools.javac.jvm.*;
48 import com.sun.tools.javac.jvm.Target;
49 import com.sun.tools.javac.tree.*;
50 import com.sun.tools.javac.tree.JCTree.*;
51 import com.sun.tools.javac.util.*;
52 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
53 import com.sun.tools.javac.util.List;
54 import static com.sun.tools.javac.code.Flags.*;
55 import static com.sun.tools.javac.code.Flags.ANNOTATION;
56 import static com.sun.tools.javac.code.Flags.BLOCK;
57 import static com.sun.tools.javac.code.Kinds.*;
58 import static com.sun.tools.javac.code.Kinds.ERRONEOUS;
59 import static com.sun.tools.javac.code.TypeTags.*;
60 import static com.sun.tools.javac.code.TypeTags.WILDCARD;
61 import static com.sun.tools.javac.tree.JCTree.Tag.*;
63 /** This is the main context-dependent analysis phase in GJC. It
64 * encompasses name resolution, type checking and constant folding as
65 * subtasks. Some subtasks involve auxiliary classes.
66 * @see Check
67 * @see Resolve
68 * @see ConstFold
69 * @see Infer
70 *
71 * <p><b>This is NOT part of any supported API.
72 * If you write code that depends on this, you do so at your own risk.
73 * This code and its internal interfaces are subject to change or
74 * deletion without notice.</b>
75 */
76 public class Attr extends JCTree.Visitor {
77 protected static final Context.Key<Attr> attrKey =
78 new Context.Key<Attr>();
80 final Names names;
81 final Log log;
82 final Symtab syms;
83 final Resolve rs;
84 final Infer infer;
85 final DeferredAttr deferredAttr;
86 final Check chk;
87 final Flow flow;
88 final MemberEnter memberEnter;
89 final TreeMaker make;
90 final ConstFold cfolder;
91 final Enter enter;
92 final Target target;
93 final Types types;
94 final JCDiagnostic.Factory diags;
95 final Annotate annotate;
96 final DeferredLintHandler deferredLintHandler;
98 public static Attr instance(Context context) {
99 Attr instance = context.get(attrKey);
100 if (instance == null)
101 instance = new Attr(context);
102 return instance;
103 }
105 protected Attr(Context context) {
106 context.put(attrKey, this);
108 names = Names.instance(context);
109 log = Log.instance(context);
110 syms = Symtab.instance(context);
111 rs = Resolve.instance(context);
112 chk = Check.instance(context);
113 flow = Flow.instance(context);
114 memberEnter = MemberEnter.instance(context);
115 make = TreeMaker.instance(context);
116 enter = Enter.instance(context);
117 infer = Infer.instance(context);
118 deferredAttr = DeferredAttr.instance(context);
119 cfolder = ConstFold.instance(context);
120 target = Target.instance(context);
121 types = Types.instance(context);
122 diags = JCDiagnostic.Factory.instance(context);
123 annotate = Annotate.instance(context);
124 deferredLintHandler = DeferredLintHandler.instance(context);
126 Options options = Options.instance(context);
128 Source source = Source.instance(context);
129 allowGenerics = source.allowGenerics();
130 allowVarargs = source.allowVarargs();
131 allowEnums = source.allowEnums();
132 allowBoxing = source.allowBoxing();
133 allowCovariantReturns = source.allowCovariantReturns();
134 allowAnonOuterThis = source.allowAnonOuterThis();
135 allowStringsInSwitch = source.allowStringsInSwitch();
136 allowPoly = source.allowPoly() && options.isSet("allowPoly");
137 allowLambda = source.allowLambda();
138 sourceName = source.name;
139 relax = (options.isSet("-retrofit") ||
140 options.isSet("-relax"));
141 findDiamonds = options.get("findDiamond") != null &&
142 source.allowDiamond();
143 useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
144 identifyLambdaCandidate = options.getBoolean("identifyLambdaCandidate", false);
146 statInfo = new ResultInfo(NIL, Type.noType);
147 varInfo = new ResultInfo(VAR, Type.noType);
148 unknownExprInfo = new ResultInfo(VAL, Type.noType);
149 unknownTypeInfo = new ResultInfo(TYP, Type.noType);
150 recoveryInfo = new RecoveryInfo(deferredAttr.emptyDeferredAttrContext);
151 }
153 /** Switch: relax some constraints for retrofit mode.
154 */
155 boolean relax;
157 /** Switch: support target-typing inference
158 */
159 boolean allowPoly;
161 /** Switch: support generics?
162 */
163 boolean allowGenerics;
165 /** Switch: allow variable-arity methods.
166 */
167 boolean allowVarargs;
169 /** Switch: support enums?
170 */
171 boolean allowEnums;
173 /** Switch: support boxing and unboxing?
174 */
175 boolean allowBoxing;
177 /** Switch: support covariant result types?
178 */
179 boolean allowCovariantReturns;
181 /** Switch: support lambda expressions ?
182 */
183 boolean allowLambda;
185 /** Switch: allow references to surrounding object from anonymous
186 * objects during constructor call?
187 */
188 boolean allowAnonOuterThis;
190 /** Switch: generates a warning if diamond can be safely applied
191 * to a given new expression
192 */
193 boolean findDiamonds;
195 /**
196 * Internally enables/disables diamond finder feature
197 */
198 static final boolean allowDiamondFinder = true;
200 /**
201 * Switch: warn about use of variable before declaration?
202 * RFE: 6425594
203 */
204 boolean useBeforeDeclarationWarning;
206 /**
207 * Switch: generate warnings whenever an anonymous inner class that is convertible
208 * to a lambda expression is found
209 */
210 boolean identifyLambdaCandidate;
212 /**
213 * Switch: allow strings in switch?
214 */
215 boolean allowStringsInSwitch;
217 /**
218 * Switch: name of source level; used for error reporting.
219 */
220 String sourceName;
222 /** Check kind and type of given tree against protokind and prototype.
223 * If check succeeds, store type in tree and return it.
224 * If check fails, store errType in tree and return it.
225 * No checks are performed if the prototype is a method type.
226 * It is not necessary in this case since we know that kind and type
227 * are correct.
228 *
229 * @param tree The tree whose kind and type is checked
230 * @param owntype The computed type of the tree
231 * @param ownkind The computed kind of the tree
232 * @param resultInfo The expected result of the tree
233 */
234 Type check(final JCTree tree, final Type found, final int ownkind, final ResultInfo resultInfo) {
235 InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
236 Type owntype = found;
237 if (owntype.tag != ERROR && resultInfo.pt.tag != METHOD && resultInfo.pt.tag != FORALL) {
238 if (inferenceContext.free(found)) {
239 inferenceContext.addFreeTypeListener(List.of(found, resultInfo.pt), new FreeTypeListener() {
240 @Override
241 public void typesInferred(InferenceContext inferenceContext) {
242 ResultInfo pendingResult =
243 resultInfo.dup(inferenceContext.asInstType(resultInfo.pt, types));
244 check(tree, inferenceContext.asInstType(found, types), ownkind, pendingResult);
245 }
246 });
247 return tree.type = resultInfo.pt;
248 } else {
249 if ((ownkind & ~resultInfo.pkind) == 0) {
250 owntype = resultInfo.check(tree, owntype);
251 } else {
252 log.error(tree.pos(), "unexpected.type",
253 kindNames(resultInfo.pkind),
254 kindName(ownkind));
255 owntype = types.createErrorType(owntype);
256 }
257 }
258 }
259 tree.type = owntype;
260 return owntype;
261 }
263 /** Is given blank final variable assignable, i.e. in a scope where it
264 * may be assigned to even though it is final?
265 * @param v The blank final variable.
266 * @param env The current environment.
267 */
268 boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
269 Symbol owner = owner(env);
270 // owner refers to the innermost variable, method or
271 // initializer block declaration at this point.
272 return
273 v.owner == owner
274 ||
275 ((owner.name == names.init || // i.e. we are in a constructor
276 owner.kind == VAR || // i.e. we are in a variable initializer
277 (owner.flags() & BLOCK) != 0) // i.e. we are in an initializer block
278 &&
279 v.owner == owner.owner
280 &&
281 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
282 }
284 /**
285 * Return the innermost enclosing owner symbol in a given attribution context
286 */
287 Symbol owner(Env<AttrContext> env) {
288 while (true) {
289 switch (env.tree.getTag()) {
290 case VARDEF:
291 //a field can be owner
292 VarSymbol vsym = ((JCVariableDecl)env.tree).sym;
293 if (vsym.owner.kind == TYP) {
294 return vsym;
295 }
296 break;
297 case METHODDEF:
298 //method def is always an owner
299 return ((JCMethodDecl)env.tree).sym;
300 case CLASSDEF:
301 //class def is always an owner
302 return ((JCClassDecl)env.tree).sym;
303 case LAMBDA:
304 //a lambda is an owner - return a fresh synthetic method symbol
305 return new MethodSymbol(0, names.empty, null, syms.methodClass);
306 case BLOCK:
307 //static/instance init blocks are owner
308 Symbol blockSym = env.info.scope.owner;
309 if ((blockSym.flags() & BLOCK) != 0) {
310 return blockSym;
311 }
312 break;
313 case TOPLEVEL:
314 //toplevel is always an owner (for pkge decls)
315 return env.info.scope.owner;
316 }
317 Assert.checkNonNull(env.next);
318 env = env.next;
319 }
320 }
322 /** Check that variable can be assigned to.
323 * @param pos The current source code position.
324 * @param v The assigned varaible
325 * @param base If the variable is referred to in a Select, the part
326 * to the left of the `.', null otherwise.
327 * @param env The current environment.
328 */
329 void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
330 if ((v.flags() & FINAL) != 0 &&
331 ((v.flags() & HASINIT) != 0
332 ||
333 !((base == null ||
334 (base.hasTag(IDENT) && TreeInfo.name(base) == names._this)) &&
335 isAssignableAsBlankFinal(v, env)))) {
336 if (v.isResourceVariable()) { //TWR resource
337 log.error(pos, "try.resource.may.not.be.assigned", v);
338 } else {
339 log.error(pos, "cant.assign.val.to.final.var", v);
340 }
341 }
342 }
344 /** Does tree represent a static reference to an identifier?
345 * It is assumed that tree is either a SELECT or an IDENT.
346 * We have to weed out selects from non-type names here.
347 * @param tree The candidate tree.
348 */
349 boolean isStaticReference(JCTree tree) {
350 if (tree.hasTag(SELECT)) {
351 Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
352 if (lsym == null || lsym.kind != TYP) {
353 return false;
354 }
355 }
356 return true;
357 }
359 /** Is this symbol a type?
360 */
361 static boolean isType(Symbol sym) {
362 return sym != null && sym.kind == TYP;
363 }
365 /** The current `this' symbol.
366 * @param env The current environment.
367 */
368 Symbol thisSym(DiagnosticPosition pos, Env<AttrContext> env) {
369 return rs.resolveSelf(pos, env, env.enclClass.sym, names._this);
370 }
372 /** Attribute a parsed identifier.
373 * @param tree Parsed identifier name
374 * @param topLevel The toplevel to use
375 */
376 public Symbol attribIdent(JCTree tree, JCCompilationUnit topLevel) {
377 Env<AttrContext> localEnv = enter.topLevelEnv(topLevel);
378 localEnv.enclClass = make.ClassDef(make.Modifiers(0),
379 syms.errSymbol.name,
380 null, null, null, null);
381 localEnv.enclClass.sym = syms.errSymbol;
382 return tree.accept(identAttributer, localEnv);
383 }
384 // where
385 private TreeVisitor<Symbol,Env<AttrContext>> identAttributer = new IdentAttributer();
386 private class IdentAttributer extends SimpleTreeVisitor<Symbol,Env<AttrContext>> {
387 @Override
388 public Symbol visitMemberSelect(MemberSelectTree node, Env<AttrContext> env) {
389 Symbol site = visit(node.getExpression(), env);
390 if (site.kind == ERR)
391 return site;
392 Name name = (Name)node.getIdentifier();
393 if (site.kind == PCK) {
394 env.toplevel.packge = (PackageSymbol)site;
395 return rs.findIdentInPackage(env, (TypeSymbol)site, name, TYP | PCK);
396 } else {
397 env.enclClass.sym = (ClassSymbol)site;
398 return rs.findMemberType(env, site.asType(), name, (TypeSymbol)site);
399 }
400 }
402 @Override
403 public Symbol visitIdentifier(IdentifierTree node, Env<AttrContext> env) {
404 return rs.findIdent(env, (Name)node.getName(), TYP | PCK);
405 }
406 }
408 public Type coerce(Type etype, Type ttype) {
409 return cfolder.coerce(etype, ttype);
410 }
412 public Type attribType(JCTree node, TypeSymbol sym) {
413 Env<AttrContext> env = enter.typeEnvs.get(sym);
414 Env<AttrContext> localEnv = env.dup(node, env.info.dup());
415 return attribTree(node, localEnv, unknownTypeInfo);
416 }
418 public Type attribImportQualifier(JCImport tree, Env<AttrContext> env) {
419 // Attribute qualifying package or class.
420 JCFieldAccess s = (JCFieldAccess)tree.qualid;
421 return attribTree(s.selected,
422 env,
423 new ResultInfo(tree.staticImport ? TYP : (TYP | PCK),
424 Type.noType));
425 }
427 public Env<AttrContext> attribExprToTree(JCTree expr, Env<AttrContext> env, JCTree tree) {
428 breakTree = tree;
429 JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
430 try {
431 attribExpr(expr, env);
432 } catch (BreakAttr b) {
433 return b.env;
434 } catch (AssertionError ae) {
435 if (ae.getCause() instanceof BreakAttr) {
436 return ((BreakAttr)(ae.getCause())).env;
437 } else {
438 throw ae;
439 }
440 } finally {
441 breakTree = null;
442 log.useSource(prev);
443 }
444 return env;
445 }
447 public Env<AttrContext> attribStatToTree(JCTree stmt, Env<AttrContext> env, JCTree tree) {
448 breakTree = tree;
449 JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
450 try {
451 attribStat(stmt, env);
452 } catch (BreakAttr b) {
453 return b.env;
454 } catch (AssertionError ae) {
455 if (ae.getCause() instanceof BreakAttr) {
456 return ((BreakAttr)(ae.getCause())).env;
457 } else {
458 throw ae;
459 }
460 } finally {
461 breakTree = null;
462 log.useSource(prev);
463 }
464 return env;
465 }
467 private JCTree breakTree = null;
469 private static class BreakAttr extends RuntimeException {
470 static final long serialVersionUID = -6924771130405446405L;
471 private Env<AttrContext> env;
472 private BreakAttr(Env<AttrContext> env) {
473 this.env = copyEnv(env);
474 }
476 private Env<AttrContext> copyEnv(Env<AttrContext> env) {
477 Env<AttrContext> newEnv =
478 env.dup(env.tree, env.info.dup(copyScope(env.info.scope)));
479 if (newEnv.outer != null) {
480 newEnv.outer = copyEnv(newEnv.outer);
481 }
482 return newEnv;
483 }
485 private Scope copyScope(Scope sc) {
486 Scope newScope = new Scope(sc.owner);
487 List<Symbol> elemsList = List.nil();
488 while (sc != null) {
489 for (Scope.Entry e = sc.elems ; e != null ; e = e.sibling) {
490 elemsList = elemsList.prepend(e.sym);
491 }
492 sc = sc.next;
493 }
494 for (Symbol s : elemsList) {
495 newScope.enter(s);
496 }
497 return newScope;
498 }
499 }
501 class ResultInfo {
502 final int pkind;
503 final Type pt;
504 final CheckContext checkContext;
506 ResultInfo(int pkind, Type pt) {
507 this(pkind, pt, chk.basicHandler);
508 }
510 protected ResultInfo(int pkind, Type pt, CheckContext checkContext) {
511 this.pkind = pkind;
512 this.pt = pt;
513 this.checkContext = checkContext;
514 }
516 protected Type check(final DiagnosticPosition pos, final Type found) {
517 return chk.checkType(pos, found, pt, checkContext);
518 }
520 protected ResultInfo dup(Type newPt) {
521 return new ResultInfo(pkind, newPt, checkContext);
522 }
523 }
525 class RecoveryInfo extends ResultInfo {
527 public RecoveryInfo(final DeferredAttr.DeferredAttrContext deferredAttrContext) {
528 super(Kinds.VAL, Type.recoveryType, new Check.NestedCheckContext(chk.basicHandler) {
529 @Override
530 public DeferredAttr.DeferredAttrContext deferredAttrContext() {
531 return deferredAttrContext;
532 }
533 @Override
534 public boolean compatible(Type found, Type req, Warner warn) {
535 return true;
536 }
537 @Override
538 public void report(DiagnosticPosition pos, JCDiagnostic details) {
539 //do nothing
540 }
541 });
542 }
544 @Override
545 protected Type check(DiagnosticPosition pos, Type found) {
546 return chk.checkNonVoid(pos, super.check(pos, found));
547 }
548 }
550 final ResultInfo statInfo;
551 final ResultInfo varInfo;
552 final ResultInfo unknownExprInfo;
553 final ResultInfo unknownTypeInfo;
554 final ResultInfo recoveryInfo;
556 Type pt() {
557 return resultInfo.pt;
558 }
560 int pkind() {
561 return resultInfo.pkind;
562 }
564 /* ************************************************************************
565 * Visitor methods
566 *************************************************************************/
568 /** Visitor argument: the current environment.
569 */
570 Env<AttrContext> env;
572 /** Visitor argument: the currently expected attribution result.
573 */
574 ResultInfo resultInfo;
576 /** Visitor result: the computed type.
577 */
578 Type result;
580 /** Visitor method: attribute a tree, catching any completion failure
581 * exceptions. Return the tree's type.
582 *
583 * @param tree The tree to be visited.
584 * @param env The environment visitor argument.
585 * @param resultInfo The result info visitor argument.
586 */
587 Type attribTree(JCTree tree, Env<AttrContext> env, ResultInfo resultInfo) {
588 Env<AttrContext> prevEnv = this.env;
589 ResultInfo prevResult = this.resultInfo;
590 try {
591 this.env = env;
592 this.resultInfo = resultInfo;
593 tree.accept(this);
594 if (tree == breakTree)
595 throw new BreakAttr(env);
596 return result;
597 } catch (CompletionFailure ex) {
598 tree.type = syms.errType;
599 return chk.completionError(tree.pos(), ex);
600 } finally {
601 this.env = prevEnv;
602 this.resultInfo = prevResult;
603 }
604 }
606 /** Derived visitor method: attribute an expression tree.
607 */
608 public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) {
609 return attribTree(tree, env, new ResultInfo(VAL, pt.tag != ERROR ? pt : Type.noType));
610 }
612 /** Derived visitor method: attribute an expression tree with
613 * no constraints on the computed type.
614 */
615 Type attribExpr(JCTree tree, Env<AttrContext> env) {
616 return attribTree(tree, env, unknownExprInfo);
617 }
619 /** Derived visitor method: attribute a type tree.
620 */
621 Type attribType(JCTree tree, Env<AttrContext> env) {
622 Type result = attribType(tree, env, Type.noType);
623 return result;
624 }
626 /** Derived visitor method: attribute a type tree.
627 */
628 Type attribType(JCTree tree, Env<AttrContext> env, Type pt) {
629 Type result = attribTree(tree, env, new ResultInfo(TYP, pt));
630 return result;
631 }
633 /** Derived visitor method: attribute a statement or definition tree.
634 */
635 public Type attribStat(JCTree tree, Env<AttrContext> env) {
636 return attribTree(tree, env, statInfo);
637 }
639 /** Attribute a list of expressions, returning a list of types.
640 */
641 List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) {
642 ListBuffer<Type> ts = new ListBuffer<Type>();
643 for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
644 ts.append(attribExpr(l.head, env, pt));
645 return ts.toList();
646 }
648 /** Attribute a list of statements, returning nothing.
649 */
650 <T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) {
651 for (List<T> l = trees; l.nonEmpty(); l = l.tail)
652 attribStat(l.head, env);
653 }
655 /** Attribute the arguments in a method call, returning a list of types.
656 */
657 List<Type> attribArgs(List<JCExpression> trees, Env<AttrContext> env) {
658 ListBuffer<Type> argtypes = new ListBuffer<Type>();
659 for (JCExpression arg : trees) {
660 Type argtype = allowPoly && TreeInfo.isPoly(arg, env.tree) ?
661 deferredAttr.new DeferredType(arg, env) :
662 chk.checkNonVoid(arg, attribExpr(arg, env, Infer.anyPoly));
663 argtypes.append(argtype);
664 }
665 return argtypes.toList();
666 }
668 /** Attribute a type argument list, returning a list of types.
669 * Caller is responsible for calling checkRefTypes.
670 */
671 List<Type> attribAnyTypes(List<JCExpression> trees, Env<AttrContext> env) {
672 ListBuffer<Type> argtypes = new ListBuffer<Type>();
673 for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
674 argtypes.append(attribType(l.head, env));
675 return argtypes.toList();
676 }
678 /** Attribute a type argument list, returning a list of types.
679 * Check that all the types are references.
680 */
681 List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
682 List<Type> types = attribAnyTypes(trees, env);
683 return chk.checkRefTypes(trees, types);
684 }
686 /**
687 * Attribute type variables (of generic classes or methods).
688 * Compound types are attributed later in attribBounds.
689 * @param typarams the type variables to enter
690 * @param env the current environment
691 */
692 void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env) {
693 for (JCTypeParameter tvar : typarams) {
694 TypeVar a = (TypeVar)tvar.type;
695 a.tsym.flags_field |= UNATTRIBUTED;
696 a.bound = Type.noType;
697 if (!tvar.bounds.isEmpty()) {
698 List<Type> bounds = List.of(attribType(tvar.bounds.head, env));
699 for (JCExpression bound : tvar.bounds.tail)
700 bounds = bounds.prepend(attribType(bound, env));
701 types.setBounds(a, bounds.reverse());
702 } else {
703 // if no bounds are given, assume a single bound of
704 // java.lang.Object.
705 types.setBounds(a, List.of(syms.objectType));
706 }
707 a.tsym.flags_field &= ~UNATTRIBUTED;
708 }
709 for (JCTypeParameter tvar : typarams)
710 chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
711 attribStats(typarams, env);
712 }
714 void attribBounds(List<JCTypeParameter> typarams) {
715 for (JCTypeParameter typaram : typarams) {
716 Type bound = typaram.type.getUpperBound();
717 if (bound != null && bound.tsym instanceof ClassSymbol) {
718 ClassSymbol c = (ClassSymbol)bound.tsym;
719 if ((c.flags_field & COMPOUND) != 0) {
720 Assert.check((c.flags_field & UNATTRIBUTED) != 0, c);
721 attribClass(typaram.pos(), c);
722 }
723 }
724 }
725 }
727 /**
728 * Attribute the type references in a list of annotations.
729 */
730 void attribAnnotationTypes(List<JCAnnotation> annotations,
731 Env<AttrContext> env) {
732 for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
733 JCAnnotation a = al.head;
734 attribType(a.annotationType, env);
735 }
736 }
738 /**
739 * Attribute a "lazy constant value".
740 * @param env The env for the const value
741 * @param initializer The initializer for the const value
742 * @param type The expected type, or null
743 * @see VarSymbol#setlazyConstValue
744 */
745 public Object attribLazyConstantValue(Env<AttrContext> env,
746 JCTree.JCExpression initializer,
747 Type type) {
749 // in case no lint value has been set up for this env, scan up
750 // env stack looking for smallest enclosing env for which it is set.
751 Env<AttrContext> lintEnv = env;
752 while (lintEnv.info.lint == null)
753 lintEnv = lintEnv.next;
755 // Having found the enclosing lint value, we can initialize the lint value for this class
756 // ... but ...
757 // There's a problem with evaluating annotations in the right order, such that
758 // env.info.enclVar.attributes_field might not yet have been evaluated, and so might be
759 // null. In that case, calling augment will throw an NPE. To avoid this, for now we
760 // revert to the jdk 6 behavior and ignore the (unevaluated) attributes.
761 if (env.info.enclVar.annotations.pendingCompletion()) {
762 env.info.lint = lintEnv.info.lint;
763 } else {
764 env.info.lint = lintEnv.info.lint.augment(env.info.enclVar.annotations,
765 env.info.enclVar.flags());
766 }
768 Lint prevLint = chk.setLint(env.info.lint);
769 JavaFileObject prevSource = log.useSource(env.toplevel.sourcefile);
771 try {
772 Type itype = attribExpr(initializer, env, type);
773 if (itype.constValue() != null)
774 return coerce(itype, type).constValue();
775 else
776 return null;
777 } finally {
778 env.info.lint = prevLint;
779 log.useSource(prevSource);
780 }
781 }
783 /** Attribute type reference in an `extends' or `implements' clause.
784 * Supertypes of anonymous inner classes are usually already attributed.
785 *
786 * @param tree The tree making up the type reference.
787 * @param env The environment current at the reference.
788 * @param classExpected true if only a class is expected here.
789 * @param interfaceExpected true if only an interface is expected here.
790 */
791 Type attribBase(JCTree tree,
792 Env<AttrContext> env,
793 boolean classExpected,
794 boolean interfaceExpected,
795 boolean checkExtensible) {
796 Type t = tree.type != null ?
797 tree.type :
798 attribType(tree, env);
799 return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible);
800 }
801 Type checkBase(Type t,
802 JCTree tree,
803 Env<AttrContext> env,
804 boolean classExpected,
805 boolean interfaceExpected,
806 boolean checkExtensible) {
807 if (t.isErroneous())
808 return t;
809 if (t.tag == TYPEVAR && !classExpected && !interfaceExpected) {
810 // check that type variable is already visible
811 if (t.getUpperBound() == null) {
812 log.error(tree.pos(), "illegal.forward.ref");
813 return types.createErrorType(t);
814 }
815 } else {
816 t = chk.checkClassType(tree.pos(), t, checkExtensible|!allowGenerics);
817 }
818 if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) {
819 log.error(tree.pos(), "intf.expected.here");
820 // return errType is necessary since otherwise there might
821 // be undetected cycles which cause attribution to loop
822 return types.createErrorType(t);
823 } else if (checkExtensible &&
824 classExpected &&
825 (t.tsym.flags() & INTERFACE) != 0) {
826 log.error(tree.pos(), "no.intf.expected.here");
827 return types.createErrorType(t);
828 }
829 if (checkExtensible &&
830 ((t.tsym.flags() & FINAL) != 0)) {
831 log.error(tree.pos(),
832 "cant.inherit.from.final", t.tsym);
833 }
834 chk.checkNonCyclic(tree.pos(), t);
835 return t;
836 }
838 Type attribIdentAsEnumType(Env<AttrContext> env, JCIdent id) {
839 Assert.check((env.enclClass.sym.flags() & ENUM) != 0);
840 id.type = env.info.scope.owner.type;
841 id.sym = env.info.scope.owner;
842 return id.type;
843 }
845 public void visitClassDef(JCClassDecl tree) {
846 // Local classes have not been entered yet, so we need to do it now:
847 if ((env.info.scope.owner.kind & (VAR | MTH)) != 0)
848 enter.classEnter(tree, env);
850 ClassSymbol c = tree.sym;
851 if (c == null) {
852 // exit in case something drastic went wrong during enter.
853 result = null;
854 } else {
855 // make sure class has been completed:
856 c.complete();
858 // If this class appears as an anonymous class
859 // in a superclass constructor call where
860 // no explicit outer instance is given,
861 // disable implicit outer instance from being passed.
862 // (This would be an illegal access to "this before super").
863 if (env.info.isSelfCall &&
864 env.tree.hasTag(NEWCLASS) &&
865 ((JCNewClass) env.tree).encl == null)
866 {
867 c.flags_field |= NOOUTERTHIS;
868 }
869 attribClass(tree.pos(), c);
870 result = tree.type = c.type;
871 }
872 }
874 public void visitMethodDef(JCMethodDecl tree) {
875 MethodSymbol m = tree.sym;
877 Lint lint = env.info.lint.augment(m.annotations, m.flags());
878 Lint prevLint = chk.setLint(lint);
879 MethodSymbol prevMethod = chk.setMethod(m);
880 try {
881 deferredLintHandler.flush(tree.pos());
882 chk.checkDeprecatedAnnotation(tree.pos(), m);
884 attribBounds(tree.typarams);
886 // If we override any other methods, check that we do so properly.
887 // JLS ???
888 if (m.isStatic()) {
889 chk.checkHideClashes(tree.pos(), env.enclClass.type, m);
890 } else {
891 chk.checkOverrideClashes(tree.pos(), env.enclClass.type, m);
892 }
893 chk.checkOverride(tree, m);
895 // Create a new environment with local scope
896 // for attributing the method.
897 Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
899 localEnv.info.lint = lint;
901 // Enter all type parameters into the local method scope.
902 for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
903 localEnv.info.scope.enterIfAbsent(l.head.type.tsym);
905 ClassSymbol owner = env.enclClass.sym;
906 if ((owner.flags() & ANNOTATION) != 0 &&
907 tree.params.nonEmpty())
908 log.error(tree.params.head.pos(),
909 "intf.annotation.members.cant.have.params");
911 // Attribute all value parameters.
912 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
913 attribStat(l.head, localEnv);
914 }
916 chk.checkVarargsMethodDecl(localEnv, tree);
918 // Check that type parameters are well-formed.
919 chk.validate(tree.typarams, localEnv);
921 // Check that result type is well-formed.
922 chk.validate(tree.restype, localEnv);
924 // annotation method checks
925 if ((owner.flags() & ANNOTATION) != 0) {
926 // annotation method cannot have throws clause
927 if (tree.thrown.nonEmpty()) {
928 log.error(tree.thrown.head.pos(),
929 "throws.not.allowed.in.intf.annotation");
930 }
931 // annotation method cannot declare type-parameters
932 if (tree.typarams.nonEmpty()) {
933 log.error(tree.typarams.head.pos(),
934 "intf.annotation.members.cant.have.type.params");
935 }
936 // validate annotation method's return type (could be an annotation type)
937 chk.validateAnnotationType(tree.restype);
938 // ensure that annotation method does not clash with members of Object/Annotation
939 chk.validateAnnotationMethod(tree.pos(), m);
941 if (tree.defaultValue != null) {
942 // if default value is an annotation, check it is a well-formed
943 // annotation value (e.g. no duplicate values, no missing values, etc.)
944 chk.validateAnnotationTree(tree.defaultValue);
945 }
946 }
948 for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
949 chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
951 if (tree.body == null) {
952 // Empty bodies are only allowed for
953 // abstract, native, or interface methods, or for methods
954 // in a retrofit signature class.
955 if ((owner.flags() & INTERFACE) == 0 &&
956 (tree.mods.flags & (ABSTRACT | NATIVE)) == 0 &&
957 !relax)
958 log.error(tree.pos(), "missing.meth.body.or.decl.abstract");
959 if (tree.defaultValue != null) {
960 if ((owner.flags() & ANNOTATION) == 0)
961 log.error(tree.pos(),
962 "default.allowed.in.intf.annotation.member");
963 }
964 } else if ((owner.flags() & INTERFACE) != 0) {
965 log.error(tree.body.pos(), "intf.meth.cant.have.body");
966 } else if ((tree.mods.flags & ABSTRACT) != 0) {
967 log.error(tree.pos(), "abstract.meth.cant.have.body");
968 } else if ((tree.mods.flags & NATIVE) != 0) {
969 log.error(tree.pos(), "native.meth.cant.have.body");
970 } else {
971 // Add an implicit super() call unless an explicit call to
972 // super(...) or this(...) is given
973 // or we are compiling class java.lang.Object.
974 if (tree.name == names.init && owner.type != syms.objectType) {
975 JCBlock body = tree.body;
976 if (body.stats.isEmpty() ||
977 !TreeInfo.isSelfCall(body.stats.head)) {
978 body.stats = body.stats.
979 prepend(memberEnter.SuperCall(make.at(body.pos),
980 List.<Type>nil(),
981 List.<JCVariableDecl>nil(),
982 false));
983 } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
984 (tree.mods.flags & GENERATEDCONSTR) == 0 &&
985 TreeInfo.isSuperCall(body.stats.head)) {
986 // enum constructors are not allowed to call super
987 // directly, so make sure there aren't any super calls
988 // in enum constructors, except in the compiler
989 // generated one.
990 log.error(tree.body.stats.head.pos(),
991 "call.to.super.not.allowed.in.enum.ctor",
992 env.enclClass.sym);
993 }
994 }
996 // Attribute method body.
997 attribStat(tree.body, localEnv);
998 }
999 localEnv.info.scope.leave();
1000 result = tree.type = m.type;
1001 chk.validateAnnotations(tree.mods.annotations, m);
1002 }
1003 finally {
1004 chk.setLint(prevLint);
1005 chk.setMethod(prevMethod);
1006 }
1007 }
1009 public void visitVarDef(JCVariableDecl tree) {
1010 // Local variables have not been entered yet, so we need to do it now:
1011 if (env.info.scope.owner.kind == MTH) {
1012 if (tree.sym != null) {
1013 // parameters have already been entered
1014 env.info.scope.enter(tree.sym);
1015 } else {
1016 memberEnter.memberEnter(tree, env);
1017 annotate.flush();
1018 }
1019 }
1021 VarSymbol v = tree.sym;
1022 Lint lint = env.info.lint.augment(v.annotations, v.flags());
1023 Lint prevLint = chk.setLint(lint);
1025 // Check that the variable's declared type is well-formed.
1026 chk.validate(tree.vartype, env);
1027 deferredLintHandler.flush(tree.pos());
1029 try {
1030 chk.checkDeprecatedAnnotation(tree.pos(), v);
1032 if (tree.init != null) {
1033 if ((v.flags_field & FINAL) != 0 &&
1034 !tree.init.hasTag(NEWCLASS) &&
1035 !tree.init.hasTag(LAMBDA) &&
1036 !tree.init.hasTag(REFERENCE)) {
1037 // In this case, `v' is final. Ensure that it's initializer is
1038 // evaluated.
1039 v.getConstValue(); // ensure initializer is evaluated
1040 } else {
1041 // Attribute initializer in a new environment
1042 // with the declared variable as owner.
1043 // Check that initializer conforms to variable's declared type.
1044 Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
1045 initEnv.info.lint = lint;
1046 // In order to catch self-references, we set the variable's
1047 // declaration position to maximal possible value, effectively
1048 // marking the variable as undefined.
1049 initEnv.info.enclVar = v;
1050 attribExpr(tree.init, initEnv, v.type);
1051 }
1052 }
1053 result = tree.type = v.type;
1054 chk.validateAnnotations(tree.mods.annotations, v);
1055 }
1056 finally {
1057 chk.setLint(prevLint);
1058 }
1059 }
1061 public void visitSkip(JCSkip tree) {
1062 result = null;
1063 }
1065 public void visitBlock(JCBlock tree) {
1066 if (env.info.scope.owner.kind == TYP) {
1067 // Block is a static or instance initializer;
1068 // let the owner of the environment be a freshly
1069 // created BLOCK-method.
1070 Env<AttrContext> localEnv =
1071 env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
1072 localEnv.info.scope.owner =
1073 new MethodSymbol(tree.flags | BLOCK, names.empty, null,
1074 env.info.scope.owner);
1075 if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
1076 attribStats(tree.stats, localEnv);
1077 } else {
1078 // Create a new local environment with a local scope.
1079 Env<AttrContext> localEnv =
1080 env.dup(tree, env.info.dup(env.info.scope.dup()));
1081 try {
1082 attribStats(tree.stats, localEnv);
1083 } finally {
1084 localEnv.info.scope.leave();
1085 }
1086 }
1087 result = null;
1088 }
1090 public void visitDoLoop(JCDoWhileLoop tree) {
1091 attribStat(tree.body, env.dup(tree));
1092 attribExpr(tree.cond, env, syms.booleanType);
1093 result = null;
1094 }
1096 public void visitWhileLoop(JCWhileLoop tree) {
1097 attribExpr(tree.cond, env, syms.booleanType);
1098 attribStat(tree.body, env.dup(tree));
1099 result = null;
1100 }
1102 public void visitForLoop(JCForLoop tree) {
1103 Env<AttrContext> loopEnv =
1104 env.dup(env.tree, env.info.dup(env.info.scope.dup()));
1105 try {
1106 attribStats(tree.init, loopEnv);
1107 if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType);
1108 loopEnv.tree = tree; // before, we were not in loop!
1109 attribStats(tree.step, loopEnv);
1110 attribStat(tree.body, loopEnv);
1111 result = null;
1112 }
1113 finally {
1114 loopEnv.info.scope.leave();
1115 }
1116 }
1118 public void visitForeachLoop(JCEnhancedForLoop tree) {
1119 Env<AttrContext> loopEnv =
1120 env.dup(env.tree, env.info.dup(env.info.scope.dup()));
1121 try {
1122 attribStat(tree.var, loopEnv);
1123 Type exprType = types.upperBound(attribExpr(tree.expr, loopEnv));
1124 chk.checkNonVoid(tree.pos(), exprType);
1125 Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
1126 if (elemtype == null) {
1127 // or perhaps expr implements Iterable<T>?
1128 Type base = types.asSuper(exprType, syms.iterableType.tsym);
1129 if (base == null) {
1130 log.error(tree.expr.pos(),
1131 "foreach.not.applicable.to.type",
1132 exprType,
1133 diags.fragment("type.req.array.or.iterable"));
1134 elemtype = types.createErrorType(exprType);
1135 } else {
1136 List<Type> iterableParams = base.allparams();
1137 elemtype = iterableParams.isEmpty()
1138 ? syms.objectType
1139 : types.upperBound(iterableParams.head);
1140 }
1141 }
1142 chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
1143 loopEnv.tree = tree; // before, we were not in loop!
1144 attribStat(tree.body, loopEnv);
1145 result = null;
1146 }
1147 finally {
1148 loopEnv.info.scope.leave();
1149 }
1150 }
1152 public void visitLabelled(JCLabeledStatement tree) {
1153 // Check that label is not used in an enclosing statement
1154 Env<AttrContext> env1 = env;
1155 while (env1 != null && !env1.tree.hasTag(CLASSDEF)) {
1156 if (env1.tree.hasTag(LABELLED) &&
1157 ((JCLabeledStatement) env1.tree).label == tree.label) {
1158 log.error(tree.pos(), "label.already.in.use",
1159 tree.label);
1160 break;
1161 }
1162 env1 = env1.next;
1163 }
1165 attribStat(tree.body, env.dup(tree));
1166 result = null;
1167 }
1169 public void visitSwitch(JCSwitch tree) {
1170 Type seltype = attribExpr(tree.selector, env);
1172 Env<AttrContext> switchEnv =
1173 env.dup(tree, env.info.dup(env.info.scope.dup()));
1175 try {
1177 boolean enumSwitch =
1178 allowEnums &&
1179 (seltype.tsym.flags() & Flags.ENUM) != 0;
1180 boolean stringSwitch = false;
1181 if (types.isSameType(seltype, syms.stringType)) {
1182 if (allowStringsInSwitch) {
1183 stringSwitch = true;
1184 } else {
1185 log.error(tree.selector.pos(), "string.switch.not.supported.in.source", sourceName);
1186 }
1187 }
1188 if (!enumSwitch && !stringSwitch)
1189 seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType);
1191 // Attribute all cases and
1192 // check that there are no duplicate case labels or default clauses.
1193 Set<Object> labels = new HashSet<Object>(); // The set of case labels.
1194 boolean hasDefault = false; // Is there a default label?
1195 for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
1196 JCCase c = l.head;
1197 Env<AttrContext> caseEnv =
1198 switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup()));
1199 try {
1200 if (c.pat != null) {
1201 if (enumSwitch) {
1202 Symbol sym = enumConstant(c.pat, seltype);
1203 if (sym == null) {
1204 log.error(c.pat.pos(), "enum.label.must.be.unqualified.enum");
1205 } else if (!labels.add(sym)) {
1206 log.error(c.pos(), "duplicate.case.label");
1207 }
1208 } else {
1209 Type pattype = attribExpr(c.pat, switchEnv, seltype);
1210 if (pattype.tag != ERROR) {
1211 if (pattype.constValue() == null) {
1212 log.error(c.pat.pos(),
1213 (stringSwitch ? "string.const.req" : "const.expr.req"));
1214 } else if (labels.contains(pattype.constValue())) {
1215 log.error(c.pos(), "duplicate.case.label");
1216 } else {
1217 labels.add(pattype.constValue());
1218 }
1219 }
1220 }
1221 } else if (hasDefault) {
1222 log.error(c.pos(), "duplicate.default.label");
1223 } else {
1224 hasDefault = true;
1225 }
1226 attribStats(c.stats, caseEnv);
1227 } finally {
1228 caseEnv.info.scope.leave();
1229 addVars(c.stats, switchEnv.info.scope);
1230 }
1231 }
1233 result = null;
1234 }
1235 finally {
1236 switchEnv.info.scope.leave();
1237 }
1238 }
1239 // where
1240 /** Add any variables defined in stats to the switch scope. */
1241 private static void addVars(List<JCStatement> stats, Scope switchScope) {
1242 for (;stats.nonEmpty(); stats = stats.tail) {
1243 JCTree stat = stats.head;
1244 if (stat.hasTag(VARDEF))
1245 switchScope.enter(((JCVariableDecl) stat).sym);
1246 }
1247 }
1248 // where
1249 /** Return the selected enumeration constant symbol, or null. */
1250 private Symbol enumConstant(JCTree tree, Type enumType) {
1251 if (!tree.hasTag(IDENT)) {
1252 log.error(tree.pos(), "enum.label.must.be.unqualified.enum");
1253 return syms.errSymbol;
1254 }
1255 JCIdent ident = (JCIdent)tree;
1256 Name name = ident.name;
1257 for (Scope.Entry e = enumType.tsym.members().lookup(name);
1258 e.scope != null; e = e.next()) {
1259 if (e.sym.kind == VAR) {
1260 Symbol s = ident.sym = e.sym;
1261 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
1262 ident.type = s.type;
1263 return ((s.flags_field & Flags.ENUM) == 0)
1264 ? null : s;
1265 }
1266 }
1267 return null;
1268 }
1270 public void visitSynchronized(JCSynchronized tree) {
1271 chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
1272 attribStat(tree.body, env);
1273 result = null;
1274 }
1276 public void visitTry(JCTry tree) {
1277 // Create a new local environment with a local
1278 Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
1279 try {
1280 boolean isTryWithResource = tree.resources.nonEmpty();
1281 // Create a nested environment for attributing the try block if needed
1282 Env<AttrContext> tryEnv = isTryWithResource ?
1283 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
1284 localEnv;
1285 try {
1286 // Attribute resource declarations
1287 for (JCTree resource : tree.resources) {
1288 CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) {
1289 @Override
1290 public void report(DiagnosticPosition pos, JCDiagnostic details) {
1291 chk.basicHandler.report(pos, diags.fragment("try.not.applicable.to.type", details));
1292 }
1293 };
1294 ResultInfo twrResult = new ResultInfo(VAL, syms.autoCloseableType, twrContext);
1295 if (resource.hasTag(VARDEF)) {
1296 attribStat(resource, tryEnv);
1297 twrResult.check(resource, resource.type);
1299 //check that resource type cannot throw InterruptedException
1300 checkAutoCloseable(resource.pos(), localEnv, resource.type);
1302 VarSymbol var = (VarSymbol)TreeInfo.symbolFor(resource);
1303 var.setData(ElementKind.RESOURCE_VARIABLE);
1304 } else {
1305 attribTree(resource, tryEnv, twrResult);
1306 }
1307 }
1308 // Attribute body
1309 attribStat(tree.body, tryEnv);
1310 } finally {
1311 if (isTryWithResource)
1312 tryEnv.info.scope.leave();
1313 }
1315 // Attribute catch clauses
1316 for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
1317 JCCatch c = l.head;
1318 Env<AttrContext> catchEnv =
1319 localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup()));
1320 try {
1321 Type ctype = attribStat(c.param, catchEnv);
1322 if (TreeInfo.isMultiCatch(c)) {
1323 //multi-catch parameter is implicitly marked as final
1324 c.param.sym.flags_field |= FINAL | UNION;
1325 }
1326 if (c.param.sym.kind == Kinds.VAR) {
1327 c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
1328 }
1329 chk.checkType(c.param.vartype.pos(),
1330 chk.checkClassType(c.param.vartype.pos(), ctype),
1331 syms.throwableType);
1332 attribStat(c.body, catchEnv);
1333 } finally {
1334 catchEnv.info.scope.leave();
1335 }
1336 }
1338 // Attribute finalizer
1339 if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
1340 result = null;
1341 }
1342 finally {
1343 localEnv.info.scope.leave();
1344 }
1345 }
1347 void checkAutoCloseable(DiagnosticPosition pos, Env<AttrContext> env, Type resource) {
1348 if (!resource.isErroneous() &&
1349 types.asSuper(resource, syms.autoCloseableType.tsym) != null &&
1350 !types.isSameType(resource, syms.autoCloseableType)) { // Don't emit warning for AutoCloseable itself
1351 Symbol close = syms.noSymbol;
1352 Filter<JCDiagnostic> prevDeferDiagsFilter = log.deferredDiagFilter;
1353 Queue<JCDiagnostic> prevDeferredDiags = log.deferredDiagnostics;
1354 try {
1355 log.deferAll();
1356 log.deferredDiagnostics = ListBuffer.lb();
1357 close = rs.resolveQualifiedMethod(pos,
1358 env,
1359 resource,
1360 names.close,
1361 List.<Type>nil(),
1362 List.<Type>nil());
1363 }
1364 finally {
1365 log.deferredDiagFilter = prevDeferDiagsFilter;
1366 log.deferredDiagnostics = prevDeferredDiags;
1367 }
1368 if (close.kind == MTH &&
1369 close.overrides(syms.autoCloseableClose, resource.tsym, types, true) &&
1370 chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes()) &&
1371 env.info.lint.isEnabled(LintCategory.TRY)) {
1372 log.warning(LintCategory.TRY, pos, "try.resource.throws.interrupted.exc", resource);
1373 }
1374 }
1375 }
1377 public void visitConditional(JCConditional tree) {
1378 Type condtype = attribExpr(tree.cond, env, syms.booleanType);
1380 boolean standaloneConditional = !allowPoly ||
1381 pt().tag == NONE && pt() != Type.recoveryType ||
1382 isBooleanOrNumeric(env, tree);
1384 if (!standaloneConditional && resultInfo.pt.tag == VOID) {
1385 //cannot get here (i.e. it means we are returning from void method - which is already an error)
1386 result = tree.type = types.createErrorType(resultInfo.pt);
1387 return;
1388 }
1390 ResultInfo condInfo = standaloneConditional ?
1391 unknownExprInfo :
1392 new ResultInfo(VAL, pt(), new Check.NestedCheckContext(resultInfo.checkContext) {
1393 //this will use enclosing check context to check compatibility of
1394 //subexpression against target type; if we are in a method check context,
1395 //depending on whether boxing is allowed, we could have incompatibilities
1396 @Override
1397 public void report(DiagnosticPosition pos, JCDiagnostic details) {
1398 enclosingContext.report(pos, diags.fragment("incompatible.type.in.conditional", details));
1399 }
1400 });
1402 Type truetype = attribTree(tree.truepart, env, condInfo);
1403 Type falsetype = attribTree(tree.falsepart, env, condInfo);
1405 Type owntype = standaloneConditional ? condType(tree, truetype, falsetype) : pt();
1406 if (condtype.constValue() != null &&
1407 truetype.constValue() != null &&
1408 falsetype.constValue() != null) {
1409 //constant folding
1410 owntype = cfolder.coerce(condtype.isTrue() ? truetype : falsetype, owntype);
1411 }
1412 result = check(tree, owntype, VAL, resultInfo);
1413 }
1414 //where
1415 @SuppressWarnings("fallthrough")
1416 private boolean isBooleanOrNumeric(Env<AttrContext> env, JCExpression tree) {
1417 switch (tree.getTag()) {
1418 case LITERAL: return ((JCLiteral)tree).typetag < CLASS;
1419 case LAMBDA: case REFERENCE: return false;
1420 case PARENS: return isBooleanOrNumeric(env, ((JCParens)tree).expr);
1421 case CONDEXPR:
1422 JCConditional condTree = (JCConditional)tree;
1423 return isBooleanOrNumeric(env, condTree.truepart) &&
1424 isBooleanOrNumeric(env, condTree.falsepart);
1425 default:
1426 Type speculativeType = deferredAttr.attribSpeculative(tree, env, unknownExprInfo).type;
1427 speculativeType = types.unboxedTypeOrType(speculativeType);
1428 return speculativeType.tag <= BOOLEAN;
1429 }
1430 }
1432 /** Compute the type of a conditional expression, after
1433 * checking that it exists. See JLS 15.25. Does not take into
1434 * account the special case where condition and both arms
1435 * are constants.
1436 *
1437 * @param pos The source position to be used for error
1438 * diagnostics.
1439 * @param thentype The type of the expression's then-part.
1440 * @param elsetype The type of the expression's else-part.
1441 */
1442 private Type condType(DiagnosticPosition pos,
1443 Type thentype, Type elsetype) {
1444 // If same type, that is the result
1445 if (types.isSameType(thentype, elsetype))
1446 return thentype.baseType();
1448 Type thenUnboxed = (!allowBoxing || thentype.isPrimitive())
1449 ? thentype : types.unboxedType(thentype);
1450 Type elseUnboxed = (!allowBoxing || elsetype.isPrimitive())
1451 ? elsetype : types.unboxedType(elsetype);
1453 // Otherwise, if both arms can be converted to a numeric
1454 // type, return the least numeric type that fits both arms
1455 // (i.e. return larger of the two, or return int if one
1456 // arm is short, the other is char).
1457 if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) {
1458 // If one arm has an integer subrange type (i.e., byte,
1459 // short, or char), and the other is an integer constant
1460 // that fits into the subrange, return the subrange type.
1461 if (thenUnboxed.tag < INT && elseUnboxed.tag == INT &&
1462 types.isAssignable(elseUnboxed, thenUnboxed))
1463 return thenUnboxed.baseType();
1464 if (elseUnboxed.tag < INT && thenUnboxed.tag == INT &&
1465 types.isAssignable(thenUnboxed, elseUnboxed))
1466 return elseUnboxed.baseType();
1468 for (int i = BYTE; i < VOID; i++) {
1469 Type candidate = syms.typeOfTag[i];
1470 if (types.isSubtype(thenUnboxed, candidate) &&
1471 types.isSubtype(elseUnboxed, candidate))
1472 return candidate;
1473 }
1474 }
1476 // Those were all the cases that could result in a primitive
1477 if (allowBoxing) {
1478 if (thentype.isPrimitive())
1479 thentype = types.boxedClass(thentype).type;
1480 if (elsetype.isPrimitive())
1481 elsetype = types.boxedClass(elsetype).type;
1482 }
1484 if (types.isSubtype(thentype, elsetype))
1485 return elsetype.baseType();
1486 if (types.isSubtype(elsetype, thentype))
1487 return thentype.baseType();
1489 if (!allowBoxing || thentype.tag == VOID || elsetype.tag == VOID) {
1490 log.error(pos, "neither.conditional.subtype",
1491 thentype, elsetype);
1492 return thentype.baseType();
1493 }
1495 // both are known to be reference types. The result is
1496 // lub(thentype,elsetype). This cannot fail, as it will
1497 // always be possible to infer "Object" if nothing better.
1498 return types.lub(thentype.baseType(), elsetype.baseType());
1499 }
1501 public void visitIf(JCIf tree) {
1502 attribExpr(tree.cond, env, syms.booleanType);
1503 attribStat(tree.thenpart, env);
1504 if (tree.elsepart != null)
1505 attribStat(tree.elsepart, env);
1506 chk.checkEmptyIf(tree);
1507 result = null;
1508 }
1510 public void visitExec(JCExpressionStatement tree) {
1511 //a fresh environment is required for 292 inference to work properly ---
1512 //see Infer.instantiatePolymorphicSignatureInstance()
1513 Env<AttrContext> localEnv = env.dup(tree);
1514 attribExpr(tree.expr, localEnv);
1515 result = null;
1516 }
1518 public void visitBreak(JCBreak tree) {
1519 tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
1520 result = null;
1521 }
1523 public void visitContinue(JCContinue tree) {
1524 tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
1525 result = null;
1526 }
1527 //where
1528 /** Return the target of a break or continue statement, if it exists,
1529 * report an error if not.
1530 * Note: The target of a labelled break or continue is the
1531 * (non-labelled) statement tree referred to by the label,
1532 * not the tree representing the labelled statement itself.
1533 *
1534 * @param pos The position to be used for error diagnostics
1535 * @param tag The tag of the jump statement. This is either
1536 * Tree.BREAK or Tree.CONTINUE.
1537 * @param label The label of the jump statement, or null if no
1538 * label is given.
1539 * @param env The environment current at the jump statement.
1540 */
1541 private JCTree findJumpTarget(DiagnosticPosition pos,
1542 JCTree.Tag tag,
1543 Name label,
1544 Env<AttrContext> env) {
1545 // Search environments outwards from the point of jump.
1546 Env<AttrContext> env1 = env;
1547 LOOP:
1548 while (env1 != null) {
1549 switch (env1.tree.getTag()) {
1550 case LABELLED:
1551 JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
1552 if (label == labelled.label) {
1553 // If jump is a continue, check that target is a loop.
1554 if (tag == CONTINUE) {
1555 if (!labelled.body.hasTag(DOLOOP) &&
1556 !labelled.body.hasTag(WHILELOOP) &&
1557 !labelled.body.hasTag(FORLOOP) &&
1558 !labelled.body.hasTag(FOREACHLOOP))
1559 log.error(pos, "not.loop.label", label);
1560 // Found labelled statement target, now go inwards
1561 // to next non-labelled tree.
1562 return TreeInfo.referencedStatement(labelled);
1563 } else {
1564 return labelled;
1565 }
1566 }
1567 break;
1568 case DOLOOP:
1569 case WHILELOOP:
1570 case FORLOOP:
1571 case FOREACHLOOP:
1572 if (label == null) return env1.tree;
1573 break;
1574 case SWITCH:
1575 if (label == null && tag == BREAK) return env1.tree;
1576 break;
1577 case LAMBDA:
1578 case METHODDEF:
1579 case CLASSDEF:
1580 break LOOP;
1581 default:
1582 }
1583 env1 = env1.next;
1584 }
1585 if (label != null)
1586 log.error(pos, "undef.label", label);
1587 else if (tag == CONTINUE)
1588 log.error(pos, "cont.outside.loop");
1589 else
1590 log.error(pos, "break.outside.switch.loop");
1591 return null;
1592 }
1594 public void visitReturn(JCReturn tree) {
1595 // Check that there is an enclosing method which is
1596 // nested within than the enclosing class.
1597 if (env.info.returnResult == null) {
1598 log.error(tree.pos(), "ret.outside.meth");
1599 } else {
1600 // Attribute return expression, if it exists, and check that
1601 // it conforms to result type of enclosing method.
1602 if (tree.expr != null) {
1603 if (env.info.returnResult.pt.tag == VOID) {
1604 log.error(tree.expr.pos(),
1605 "cant.ret.val.from.meth.decl.void");
1606 }
1607 attribTree(tree.expr, env, env.info.returnResult);
1608 } else if (env.info.returnResult.pt.tag != VOID) {
1609 log.error(tree.pos(), "missing.ret.val");
1610 }
1611 }
1612 result = null;
1613 }
1615 public void visitThrow(JCThrow tree) {
1616 attribExpr(tree.expr, env, syms.throwableType);
1617 result = null;
1618 }
1620 public void visitAssert(JCAssert tree) {
1621 attribExpr(tree.cond, env, syms.booleanType);
1622 if (tree.detail != null) {
1623 chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
1624 }
1625 result = null;
1626 }
1628 /** Visitor method for method invocations.
1629 * NOTE: The method part of an application will have in its type field
1630 * the return type of the method, not the method's type itself!
1631 */
1632 public void visitApply(JCMethodInvocation tree) {
1633 // The local environment of a method application is
1634 // a new environment nested in the current one.
1635 Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
1637 // The types of the actual method arguments.
1638 List<Type> argtypes;
1640 // The types of the actual method type arguments.
1641 List<Type> typeargtypes = null;
1643 Name methName = TreeInfo.name(tree.meth);
1645 boolean isConstructorCall =
1646 methName == names._this || methName == names._super;
1648 if (isConstructorCall) {
1649 // We are seeing a ...this(...) or ...super(...) call.
1650 // Check that this is the first statement in a constructor.
1651 if (checkFirstConstructorStat(tree, env)) {
1653 // Record the fact
1654 // that this is a constructor call (using isSelfCall).
1655 localEnv.info.isSelfCall = true;
1657 // Attribute arguments, yielding list of argument types.
1658 argtypes = attribArgs(tree.args, localEnv);
1659 typeargtypes = attribTypes(tree.typeargs, localEnv);
1661 // Variable `site' points to the class in which the called
1662 // constructor is defined.
1663 Type site = env.enclClass.sym.type;
1664 if (methName == names._super) {
1665 if (site == syms.objectType) {
1666 log.error(tree.meth.pos(), "no.superclass", site);
1667 site = types.createErrorType(syms.objectType);
1668 } else {
1669 site = types.supertype(site);
1670 }
1671 }
1673 if (site.tag == CLASS) {
1674 Type encl = site.getEnclosingType();
1675 while (encl != null && encl.tag == TYPEVAR)
1676 encl = encl.getUpperBound();
1677 if (encl.tag == CLASS) {
1678 // we are calling a nested class
1680 if (tree.meth.hasTag(SELECT)) {
1681 JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
1683 // We are seeing a prefixed call, of the form
1684 // <expr>.super(...).
1685 // Check that the prefix expression conforms
1686 // to the outer instance type of the class.
1687 chk.checkRefType(qualifier.pos(),
1688 attribExpr(qualifier, localEnv,
1689 encl));
1690 } else if (methName == names._super) {
1691 // qualifier omitted; check for existence
1692 // of an appropriate implicit qualifier.
1693 rs.resolveImplicitThis(tree.meth.pos(),
1694 localEnv, site, true);
1695 }
1696 } else if (tree.meth.hasTag(SELECT)) {
1697 log.error(tree.meth.pos(), "illegal.qual.not.icls",
1698 site.tsym);
1699 }
1701 // if we're calling a java.lang.Enum constructor,
1702 // prefix the implicit String and int parameters
1703 if (site.tsym == syms.enumSym && allowEnums)
1704 argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
1706 // Resolve the called constructor under the assumption
1707 // that we are referring to a superclass instance of the
1708 // current instance (JLS ???).
1709 boolean selectSuperPrev = localEnv.info.selectSuper;
1710 localEnv.info.selectSuper = true;
1711 localEnv.info.pendingResolutionPhase = null;
1712 Symbol sym = rs.resolveConstructor(
1713 tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
1714 localEnv.info.selectSuper = selectSuperPrev;
1716 // Set method symbol to resolved constructor...
1717 TreeInfo.setSymbol(tree.meth, sym);
1719 // ...and check that it is legal in the current context.
1720 // (this will also set the tree's type)
1721 Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
1722 checkId(tree.meth, site, sym, localEnv, new ResultInfo(MTH, mpt));
1723 }
1724 // Otherwise, `site' is an error type and we do nothing
1725 }
1726 result = tree.type = syms.voidType;
1727 } else {
1728 // Otherwise, we are seeing a regular method call.
1729 // Attribute the arguments, yielding list of argument types, ...
1730 argtypes = attribArgs(tree.args, localEnv);
1731 typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
1733 // ... and attribute the method using as a prototype a methodtype
1734 // whose formal argument types is exactly the list of actual
1735 // arguments (this will also set the method symbol).
1736 Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
1737 localEnv.info.pendingResolutionPhase = null;
1738 Type mtype = attribTree(tree.meth, localEnv, new ResultInfo(VAL, mpt, resultInfo.checkContext));
1740 // Compute the result type.
1741 Type restype = mtype.getReturnType();
1742 if (restype.tag == WILDCARD)
1743 throw new AssertionError(mtype);
1745 Type qualifier = (tree.meth.hasTag(SELECT))
1746 ? ((JCFieldAccess) tree.meth).selected.type
1747 : env.enclClass.sym.type;
1748 restype = adjustMethodReturnType(qualifier, methName, argtypes, restype);
1750 chk.checkRefTypes(tree.typeargs, typeargtypes);
1752 // Check that value of resulting type is admissible in the
1753 // current context. Also, capture the return type
1754 result = check(tree, capture(restype), VAL, resultInfo);
1756 if (localEnv.info.lastResolveVarargs())
1757 Assert.check(result.isErroneous() || tree.varargsElement != null);
1758 }
1759 chk.validate(tree.typeargs, localEnv);
1760 }
1761 //where
1762 Type adjustMethodReturnType(Type qualifierType, Name methodName, List<Type> argtypes, Type restype) {
1763 if (allowCovariantReturns &&
1764 methodName == names.clone &&
1765 types.isArray(qualifierType)) {
1766 // as a special case, array.clone() has a result that is
1767 // the same as static type of the array being cloned
1768 return qualifierType;
1769 } else if (allowGenerics &&
1770 methodName == names.getClass &&
1771 argtypes.isEmpty()) {
1772 // as a special case, x.getClass() has type Class<? extends |X|>
1773 return new ClassType(restype.getEnclosingType(),
1774 List.<Type>of(new WildcardType(types.erasure(qualifierType),
1775 BoundKind.EXTENDS,
1776 syms.boundClass)),
1777 restype.tsym);
1778 } else {
1779 return restype;
1780 }
1781 }
1783 /** Check that given application node appears as first statement
1784 * in a constructor call.
1785 * @param tree The application node
1786 * @param env The environment current at the application.
1787 */
1788 boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) {
1789 JCMethodDecl enclMethod = env.enclMethod;
1790 if (enclMethod != null && enclMethod.name == names.init) {
1791 JCBlock body = enclMethod.body;
1792 if (body.stats.head.hasTag(EXEC) &&
1793 ((JCExpressionStatement) body.stats.head).expr == tree)
1794 return true;
1795 }
1796 log.error(tree.pos(),"call.must.be.first.stmt.in.ctor",
1797 TreeInfo.name(tree.meth));
1798 return false;
1799 }
1801 /** Obtain a method type with given argument types.
1802 */
1803 Type newMethodTemplate(Type restype, List<Type> argtypes, List<Type> typeargtypes) {
1804 MethodType mt = new MethodType(argtypes, restype, List.<Type>nil(), syms.methodClass);
1805 return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
1806 }
1808 public void visitNewClass(final JCNewClass tree) {
1809 Type owntype = types.createErrorType(tree.type);
1811 // The local environment of a class creation is
1812 // a new environment nested in the current one.
1813 Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
1815 // The anonymous inner class definition of the new expression,
1816 // if one is defined by it.
1817 JCClassDecl cdef = tree.def;
1819 // If enclosing class is given, attribute it, and
1820 // complete class name to be fully qualified
1821 JCExpression clazz = tree.clazz; // Class field following new
1822 JCExpression clazzid = // Identifier in class field
1823 (clazz.hasTag(TYPEAPPLY))
1824 ? ((JCTypeApply) clazz).clazz
1825 : clazz;
1827 JCExpression clazzid1 = clazzid; // The same in fully qualified form
1829 if (tree.encl != null) {
1830 // We are seeing a qualified new, of the form
1831 // <expr>.new C <...> (...) ...
1832 // In this case, we let clazz stand for the name of the
1833 // allocated class C prefixed with the type of the qualifier
1834 // expression, so that we can
1835 // resolve it with standard techniques later. I.e., if
1836 // <expr> has type T, then <expr>.new C <...> (...)
1837 // yields a clazz T.C.
1838 Type encltype = chk.checkRefType(tree.encl.pos(),
1839 attribExpr(tree.encl, env));
1840 clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
1841 ((JCIdent) clazzid).name);
1842 if (clazz.hasTag(TYPEAPPLY))
1843 clazz = make.at(tree.pos).
1844 TypeApply(clazzid1,
1845 ((JCTypeApply) clazz).arguments);
1846 else
1847 clazz = clazzid1;
1848 }
1850 // Attribute clazz expression and store
1851 // symbol + type back into the attributed tree.
1852 Type clazztype = TreeInfo.isEnumInit(env.tree) ?
1853 attribIdentAsEnumType(env, (JCIdent)clazz) :
1854 attribType(clazz, env);
1856 clazztype = chk.checkDiamond(tree, clazztype);
1857 chk.validate(clazz, localEnv);
1858 if (tree.encl != null) {
1859 // We have to work in this case to store
1860 // symbol + type back into the attributed tree.
1861 tree.clazz.type = clazztype;
1862 TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
1863 clazzid.type = ((JCIdent) clazzid).sym.type;
1864 if (!clazztype.isErroneous()) {
1865 if (cdef != null && clazztype.tsym.isInterface()) {
1866 log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new");
1867 } else if (clazztype.tsym.isStatic()) {
1868 log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym);
1869 }
1870 }
1871 } else if (!clazztype.tsym.isInterface() &&
1872 clazztype.getEnclosingType().tag == CLASS) {
1873 // Check for the existence of an apropos outer instance
1874 rs.resolveImplicitThis(tree.pos(), env, clazztype);
1875 }
1877 // Attribute constructor arguments.
1878 List<Type> argtypes = attribArgs(tree.args, localEnv);
1879 List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
1881 // If we have made no mistakes in the class type...
1882 if (clazztype.tag == CLASS) {
1883 // Enums may not be instantiated except implicitly
1884 if (allowEnums &&
1885 (clazztype.tsym.flags_field&Flags.ENUM) != 0 &&
1886 (!env.tree.hasTag(VARDEF) ||
1887 (((JCVariableDecl) env.tree).mods.flags&Flags.ENUM) == 0 ||
1888 ((JCVariableDecl) env.tree).init != tree))
1889 log.error(tree.pos(), "enum.cant.be.instantiated");
1890 // Check that class is not abstract
1891 if (cdef == null &&
1892 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
1893 log.error(tree.pos(), "abstract.cant.be.instantiated",
1894 clazztype.tsym);
1895 } else if (cdef != null && clazztype.tsym.isInterface()) {
1896 // Check that no constructor arguments are given to
1897 // anonymous classes implementing an interface
1898 if (!argtypes.isEmpty())
1899 log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args");
1901 if (!typeargtypes.isEmpty())
1902 log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs");
1904 // Error recovery: pretend no arguments were supplied.
1905 argtypes = List.nil();
1906 typeargtypes = List.nil();
1907 } else if (TreeInfo.isDiamond(tree)) {
1908 ClassType site = new ClassType(clazztype.getEnclosingType(),
1909 clazztype.tsym.type.getTypeArguments(),
1910 clazztype.tsym);
1912 Env<AttrContext> diamondEnv = localEnv.dup(tree);
1913 diamondEnv.info.selectSuper = cdef != null;
1914 diamondEnv.info.pendingResolutionPhase = null;
1916 //if the type of the instance creation expression is a class type
1917 //apply method resolution inference (JLS 15.12.2.7). The return type
1918 //of the resolved constructor will be a partially instantiated type
1919 Symbol constructor = rs.resolveDiamond(tree.pos(),
1920 diamondEnv,
1921 site,
1922 argtypes,
1923 typeargtypes);
1924 tree.constructor = constructor.baseSymbol();
1926 final TypeSymbol csym = clazztype.tsym;
1927 ResultInfo diamondResult = new ResultInfo(MTH, newMethodTemplate(resultInfo.pt, argtypes, typeargtypes), new Check.NestedCheckContext(resultInfo.checkContext) {
1928 @Override
1929 public void report(DiagnosticPosition _unused, JCDiagnostic details) {
1930 enclosingContext.report(tree.clazz,
1931 diags.fragment("cant.apply.diamond.1", diags.fragment("diamond", csym), details));
1932 }
1933 });
1934 Type constructorType = tree.constructorType = types.createErrorType(clazztype);
1935 constructorType = checkId(tree, site,
1936 constructor,
1937 diamondEnv,
1938 diamondResult);
1940 tree.clazz.type = types.createErrorType(clazztype);
1941 if (!constructorType.isErroneous()) {
1942 tree.clazz.type = clazztype = constructorType.getReturnType();
1943 tree.constructorType = types.createMethodTypeWithReturn(constructorType, syms.voidType);
1944 }
1945 clazztype = chk.checkClassType(tree.clazz, tree.clazz.type, true);
1946 }
1948 // Resolve the called constructor under the assumption
1949 // that we are referring to a superclass instance of the
1950 // current instance (JLS ???).
1951 else {
1952 //the following code alters some of the fields in the current
1953 //AttrContext - hence, the current context must be dup'ed in
1954 //order to avoid downstream failures
1955 Env<AttrContext> rsEnv = localEnv.dup(tree);
1956 rsEnv.info.selectSuper = cdef != null;
1957 rsEnv.info.pendingResolutionPhase = null;
1958 tree.constructor = rs.resolveConstructor(
1959 tree.pos(), rsEnv, clazztype, argtypes, typeargtypes);
1960 if (cdef == null) { //do not check twice!
1961 tree.constructorType = checkId(tree,
1962 clazztype,
1963 tree.constructor,
1964 rsEnv,
1965 new ResultInfo(MTH, newMethodTemplate(syms.voidType, argtypes, typeargtypes)));
1966 if (rsEnv.info.lastResolveVarargs())
1967 Assert.check(tree.constructorType.isErroneous() || tree.varargsElement != null);
1968 }
1969 findDiamondIfNeeded(localEnv, tree, clazztype);
1970 }
1972 if (cdef != null) {
1973 // We are seeing an anonymous class instance creation.
1974 // In this case, the class instance creation
1975 // expression
1976 //
1977 // E.new <typeargs1>C<typargs2>(args) { ... }
1978 //
1979 // is represented internally as
1980 //
1981 // E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } ) .
1982 //
1983 // This expression is then *transformed* as follows:
1984 //
1985 // (1) add a STATIC flag to the class definition
1986 // if the current environment is static
1987 // (2) add an extends or implements clause
1988 // (3) add a constructor.
1989 //
1990 // For instance, if C is a class, and ET is the type of E,
1991 // the expression
1992 //
1993 // E.new <typeargs1>C<typargs2>(args) { ... }
1994 //
1995 // is translated to (where X is a fresh name and typarams is the
1996 // parameter list of the super constructor):
1997 //
1998 // new <typeargs1>X(<*nullchk*>E, args) where
1999 // X extends C<typargs2> {
2000 // <typarams> X(ET e, args) {
2001 // e.<typeargs1>super(args)
2002 // }
2003 // ...
2004 // }
2005 if (Resolve.isStatic(env)) cdef.mods.flags |= STATIC;
2007 if (clazztype.tsym.isInterface()) {
2008 cdef.implementing = List.of(clazz);
2009 } else {
2010 cdef.extending = clazz;
2011 }
2013 attribStat(cdef, localEnv);
2015 checkLambdaCandidate(tree, cdef.sym, clazztype);
2017 // If an outer instance is given,
2018 // prefix it to the constructor arguments
2019 // and delete it from the new expression
2020 if (tree.encl != null && !clazztype.tsym.isInterface()) {
2021 tree.args = tree.args.prepend(makeNullCheck(tree.encl));
2022 argtypes = argtypes.prepend(tree.encl.type);
2023 tree.encl = null;
2024 }
2026 // Reassign clazztype and recompute constructor.
2027 clazztype = cdef.sym.type;
2028 Symbol sym = tree.constructor = rs.resolveConstructor(
2029 tree.pos(), localEnv, clazztype, argtypes, typeargtypes);
2030 Assert.check(sym.kind < AMBIGUOUS);
2031 tree.constructor = sym;
2032 tree.constructorType = checkId(tree,
2033 clazztype,
2034 tree.constructor,
2035 localEnv,
2036 new ResultInfo(VAL, newMethodTemplate(syms.voidType, argtypes, typeargtypes)));
2037 }
2039 if (tree.constructor != null && tree.constructor.kind == MTH)
2040 owntype = clazztype;
2041 }
2042 result = check(tree, owntype, VAL, resultInfo);
2043 chk.validate(tree.typeargs, localEnv);
2044 }
2045 //where
2046 void findDiamondIfNeeded(Env<AttrContext> env, JCNewClass tree, Type clazztype) {
2047 if (tree.def == null &&
2048 !clazztype.isErroneous() &&
2049 clazztype.getTypeArguments().nonEmpty() &&
2050 findDiamonds) {
2051 JCTypeApply ta = (JCTypeApply)tree.clazz;
2052 List<JCExpression> prevTypeargs = ta.arguments;
2053 try {
2054 //create a 'fake' diamond AST node by removing type-argument trees
2055 ta.arguments = List.nil();
2056 ResultInfo findDiamondResult = new ResultInfo(VAL,
2057 resultInfo.checkContext.inferenceContext().free(resultInfo.pt) ? Type.noType : pt());
2058 Type inferred = deferredAttr.attribSpeculative(tree, env, findDiamondResult).type;
2059 if (!inferred.isErroneous() &&
2060 types.isAssignable(inferred, pt().tag == NONE ? syms.objectType : pt(), Warner.noWarnings)) {
2061 String key = types.isSameType(clazztype, inferred) ?
2062 "diamond.redundant.args" :
2063 "diamond.redundant.args.1";
2064 log.warning(tree.clazz.pos(), key, clazztype, inferred);
2065 }
2066 } finally {
2067 ta.arguments = prevTypeargs;
2068 }
2069 }
2070 }
2072 private void checkLambdaCandidate(JCNewClass tree, ClassSymbol csym, Type clazztype) {
2073 if (allowLambda &&
2074 identifyLambdaCandidate &&
2075 clazztype.tag == CLASS &&
2076 pt().tag != NONE &&
2077 types.isFunctionalInterface(clazztype.tsym)) {
2078 Symbol descriptor = types.findDescriptorSymbol(clazztype.tsym);
2079 int count = 0;
2080 boolean found = false;
2081 for (Symbol sym : csym.members().getElements()) {
2082 if ((sym.flags() & SYNTHETIC) != 0 ||
2083 sym.isConstructor()) continue;
2084 count++;
2085 if (sym.kind != MTH ||
2086 !sym.name.equals(descriptor.name)) continue;
2087 Type mtype = types.memberType(clazztype, sym);
2088 if (types.overrideEquivalent(mtype, types.memberType(clazztype, descriptor))) {
2089 found = true;
2090 }
2091 }
2092 if (found && count == 1) {
2093 log.note(tree.def, "potential.lambda.found");
2094 }
2095 }
2096 }
2098 /** Make an attributed null check tree.
2099 */
2100 public JCExpression makeNullCheck(JCExpression arg) {
2101 // optimization: X.this is never null; skip null check
2102 Name name = TreeInfo.name(arg);
2103 if (name == names._this || name == names._super) return arg;
2105 JCTree.Tag optag = NULLCHK;
2106 JCUnary tree = make.at(arg.pos).Unary(optag, arg);
2107 tree.operator = syms.nullcheck;
2108 tree.type = arg.type;
2109 return tree;
2110 }
2112 public void visitNewArray(JCNewArray tree) {
2113 Type owntype = types.createErrorType(tree.type);
2114 Env<AttrContext> localEnv = env.dup(tree);
2115 Type elemtype;
2116 if (tree.elemtype != null) {
2117 elemtype = attribType(tree.elemtype, localEnv);
2118 chk.validate(tree.elemtype, localEnv);
2119 owntype = elemtype;
2120 for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
2121 attribExpr(l.head, localEnv, syms.intType);
2122 owntype = new ArrayType(owntype, syms.arrayClass);
2123 }
2124 } else {
2125 // we are seeing an untyped aggregate { ... }
2126 // this is allowed only if the prototype is an array
2127 if (pt().tag == ARRAY) {
2128 elemtype = types.elemtype(pt());
2129 } else {
2130 if (pt().tag != ERROR) {
2131 log.error(tree.pos(), "illegal.initializer.for.type",
2132 pt());
2133 }
2134 elemtype = types.createErrorType(pt());
2135 }
2136 }
2137 if (tree.elems != null) {
2138 attribExprs(tree.elems, localEnv, elemtype);
2139 owntype = new ArrayType(elemtype, syms.arrayClass);
2140 }
2141 if (!types.isReifiable(elemtype))
2142 log.error(tree.pos(), "generic.array.creation");
2143 result = check(tree, owntype, VAL, resultInfo);
2144 }
2146 /*
2147 * A lambda expression can only be attributed when a target-type is available.
2148 * In addition, if the target-type is that of a functional interface whose
2149 * descriptor contains inference variables in argument position the lambda expression
2150 * is 'stuck' (see DeferredAttr).
2151 */
2152 @Override
2153 public void visitLambda(final JCLambda that) {
2154 if (pt().isErroneous() || (pt().tag == NONE && pt() != Type.recoveryType)) {
2155 if (pt().tag == NONE) {
2156 //lambda only allowed in assignment or method invocation/cast context
2157 log.error(that.pos(), "unexpected.lambda");
2158 }
2159 result = that.type = types.createErrorType(pt());
2160 return;
2161 }
2162 //create an environment for attribution of the lambda expression
2163 final Env<AttrContext> localEnv = lambdaEnv(that, env);
2164 boolean needsRecovery = resultInfo.checkContext.deferredAttrContext() == deferredAttr.emptyDeferredAttrContext ||
2165 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK;
2166 try {
2167 List<Type> explicitParamTypes = null;
2168 if (TreeInfo.isExplicitLambda(that)) {
2169 //attribute lambda parameters
2170 attribStats(that.params, localEnv);
2171 explicitParamTypes = TreeInfo.types(that.params);
2172 }
2174 Type target = infer.instantiateFunctionalInterface(that, pt(), explicitParamTypes, resultInfo.checkContext);
2175 Type lambdaType = (target == Type.recoveryType) ?
2176 fallbackDescriptorType(that) :
2177 types.findDescriptorType(target);
2179 if (!TreeInfo.isExplicitLambda(that)) {
2180 //add param type info in the AST
2181 List<Type> actuals = lambdaType.getParameterTypes();
2182 List<JCVariableDecl> params = that.params;
2184 boolean arityMismatch = false;
2186 while (params.nonEmpty()) {
2187 if (actuals.isEmpty()) {
2188 //not enough actuals to perform lambda parameter inference
2189 arityMismatch = true;
2190 }
2191 //reset previously set info
2192 Type argType = arityMismatch ?
2193 syms.errType :
2194 actuals.head;
2195 params.head.vartype = make.Type(argType);
2196 params.head.sym = null;
2197 actuals = actuals.isEmpty() ?
2198 actuals :
2199 actuals.tail;
2200 params = params.tail;
2201 }
2203 //attribute lambda parameters
2204 attribStats(that.params, localEnv);
2206 if (arityMismatch) {
2207 resultInfo.checkContext.report(that, diags.fragment("incompatible.arg.types.in.lambda"));
2208 result = that.type = types.createErrorType(target);
2209 return;
2210 }
2211 }
2213 //from this point on, no recovery is needed; if we are in assignment context
2214 //we will be able to attribute the whole lambda body, regardless of errors;
2215 //if we are in a 'check' method context, and the lambda is not compatible
2216 //with the target-type, it will be recovered anyway in Attr.checkId
2217 needsRecovery = false;
2219 ResultInfo bodyResultInfo = lambdaType.getReturnType() == Type.recoveryType ?
2220 recoveryInfo :
2221 new ResultInfo(VAL, lambdaType.getReturnType(), new LambdaReturnContext(resultInfo.checkContext));
2222 localEnv.info.returnResult = bodyResultInfo;
2224 if (that.getBodyKind() == JCLambda.BodyKind.EXPRESSION) {
2225 attribTree(that.getBody(), localEnv, bodyResultInfo);
2226 } else {
2227 JCBlock body = (JCBlock)that.body;
2228 attribStats(body.stats, localEnv);
2229 }
2231 result = check(that, target, VAL, resultInfo);
2233 boolean isSpeculativeRound =
2234 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
2236 postAttr(that);
2237 flow.analyzeLambda(env, that, make, isSpeculativeRound);
2239 checkLambdaCompatible(that, lambdaType, resultInfo.checkContext, isSpeculativeRound);
2241 if (!isSpeculativeRound) {
2242 checkAccessibleFunctionalDescriptor(that, localEnv, resultInfo.checkContext.inferenceContext(), lambdaType);
2243 }
2244 result = check(that, target, VAL, resultInfo);
2245 } catch (Types.FunctionDescriptorLookupError ex) {
2246 JCDiagnostic cause = ex.getDiagnostic();
2247 resultInfo.checkContext.report(that, cause);
2248 result = that.type = types.createErrorType(pt());
2249 return;
2250 } finally {
2251 localEnv.info.scope.leave();
2252 if (needsRecovery) {
2253 attribTree(that, env, recoveryInfo);
2254 }
2255 }
2256 }
2257 //where
2258 private Type fallbackDescriptorType(JCExpression tree) {
2259 switch (tree.getTag()) {
2260 case LAMBDA:
2261 JCLambda lambda = (JCLambda)tree;
2262 List<Type> argtypes = List.nil();
2263 for (JCVariableDecl param : lambda.params) {
2264 argtypes = param.vartype != null ?
2265 argtypes.append(param.vartype.type) :
2266 argtypes.append(syms.errType);
2267 }
2268 return new MethodType(argtypes, Type.recoveryType, List.<Type>nil(), syms.methodClass);
2269 case REFERENCE:
2270 return new MethodType(List.<Type>nil(), Type.recoveryType, List.<Type>nil(), syms.methodClass);
2271 default:
2272 Assert.error("Cannot get here!");
2273 }
2274 return null;
2275 }
2277 private void checkAccessibleFunctionalDescriptor(final DiagnosticPosition pos,
2278 final Env<AttrContext> env, final InferenceContext inferenceContext, final Type desc) {
2279 if (inferenceContext.free(desc)) {
2280 inferenceContext.addFreeTypeListener(List.of(desc), new FreeTypeListener() {
2281 @Override
2282 public void typesInferred(InferenceContext inferenceContext) {
2283 checkAccessibleFunctionalDescriptor(pos, env, inferenceContext, inferenceContext.asInstType(desc, types));
2284 }
2285 });
2286 } else {
2287 chk.checkAccessibleFunctionalDescriptor(pos, env, desc);
2288 }
2289 }
2291 /**
2292 * Lambda/method reference have a special check context that ensures
2293 * that i.e. a lambda return type is compatible with the expected
2294 * type according to both the inherited context and the assignment
2295 * context.
2296 */
2297 class LambdaReturnContext extends Check.NestedCheckContext {
2298 public LambdaReturnContext(CheckContext enclosingContext) {
2299 super(enclosingContext);
2300 }
2302 @Override
2303 public boolean compatible(Type found, Type req, Warner warn) {
2304 //return type must be compatible in both current context and assignment context
2305 return types.isAssignable(found, inferenceContext().asFree(req, types), warn) &&
2306 super.compatible(found, req, warn);
2307 }
2308 @Override
2309 public void report(DiagnosticPosition pos, JCDiagnostic details) {
2310 enclosingContext.report(pos, diags.fragment("incompatible.ret.type.in.lambda", details));
2311 }
2312 }
2314 /**
2315 * Lambda compatibility. Check that given return types, thrown types, parameter types
2316 * are compatible with the expected functional interface descriptor. This means that:
2317 * (i) parameter types must be identical to those of the target descriptor; (ii) return
2318 * types must be compatible with the return type of the expected descriptor;
2319 * (iii) thrown types must be 'included' in the thrown types list of the expected
2320 * descriptor.
2321 */
2322 private void checkLambdaCompatible(JCLambda tree, Type descriptor, CheckContext checkContext, boolean speculativeAttr) {
2323 Type returnType = checkContext.inferenceContext().asFree(descriptor.getReturnType(), types);
2325 //return values have already been checked - but if lambda has no return
2326 //values, we must ensure that void/value compatibility is correct;
2327 //this amounts at checking that, if a lambda body can complete normally,
2328 //the descriptor's return type must be void
2329 if (tree.getBodyKind() == JCLambda.BodyKind.STATEMENT && tree.canCompleteNormally &&
2330 returnType.tag != VOID && returnType != Type.recoveryType) {
2331 checkContext.report(tree, diags.fragment("incompatible.ret.type.in.lambda",
2332 diags.fragment("missing.ret.val", returnType)));
2333 }
2335 List<Type> argTypes = checkContext.inferenceContext().asFree(descriptor.getParameterTypes(), types);
2336 if (!types.isSameTypes(argTypes, TreeInfo.types(tree.params))) {
2337 checkContext.report(tree, diags.fragment("incompatible.arg.types.in.lambda"));
2338 }
2340 if (!speculativeAttr) {
2341 List<Type> thrownTypes = checkContext.inferenceContext().asFree(descriptor.getThrownTypes(), types);
2342 if (chk.unhandled(tree.inferredThrownTypes == null ? List.<Type>nil() : tree.inferredThrownTypes, thrownTypes).nonEmpty()) {
2343 log.error(tree, "incompatible.thrown.types.in.lambda", tree.inferredThrownTypes);
2344 }
2345 }
2346 }
2348 private Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) {
2349 Env<AttrContext> lambdaEnv;
2350 Symbol owner = env.info.scope.owner;
2351 if (owner.kind == VAR && owner.owner.kind == TYP) {
2352 //field initializer
2353 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared()));
2354 lambdaEnv.info.scope.owner =
2355 new MethodSymbol(0, names.empty, null,
2356 env.info.scope.owner);
2357 } else {
2358 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dup()));
2359 }
2360 return lambdaEnv;
2361 }
2363 @Override
2364 public void visitReference(final JCMemberReference that) {
2365 if (pt().isErroneous() || (pt().tag == NONE && pt() != Type.recoveryType)) {
2366 if (pt().tag == NONE) {
2367 //method reference only allowed in assignment or method invocation/cast context
2368 log.error(that.pos(), "unexpected.mref");
2369 }
2370 result = that.type = types.createErrorType(pt());
2371 return;
2372 }
2373 final Env<AttrContext> localEnv = env.dup(that);
2374 try {
2375 //attribute member reference qualifier - if this is a constructor
2376 //reference, the expected kind must be a type
2377 Type exprType = attribTree(that.expr,
2378 env, new ResultInfo(that.getMode() == ReferenceMode.INVOKE ? VAL | TYP : TYP, Type.noType));
2380 if (that.getMode() == JCMemberReference.ReferenceMode.NEW) {
2381 exprType = chk.checkConstructorRefType(that.expr, exprType);
2382 }
2384 if (exprType.isErroneous()) {
2385 //if the qualifier expression contains problems,
2386 //give up atttribution of method reference
2387 result = that.type = exprType;
2388 return;
2389 }
2391 if (TreeInfo.isStaticSelector(that.expr, names) &&
2392 (that.getMode() != ReferenceMode.NEW || !that.expr.type.isRaw())) {
2393 //if the qualifier is a type, validate it
2394 chk.validate(that.expr, env);
2395 }
2397 //attrib type-arguments
2398 List<Type> typeargtypes = null;
2399 if (that.typeargs != null) {
2400 typeargtypes = attribTypes(that.typeargs, localEnv);
2401 }
2403 Type target = infer.instantiateFunctionalInterface(that, pt(), null, resultInfo.checkContext);
2404 Type desc = (target == Type.recoveryType) ?
2405 fallbackDescriptorType(that) :
2406 types.findDescriptorType(target);
2408 List<Type> argtypes = desc.getParameterTypes();
2410 boolean allowBoxing =
2411 resultInfo.checkContext.deferredAttrContext() == deferredAttr.emptyDeferredAttrContext ||
2412 resultInfo.checkContext.deferredAttrContext().phase.isBoxingRequired();
2413 Pair<Symbol, Resolve.ReferenceLookupHelper> refResult = rs.resolveMemberReference(that.pos(), localEnv, that,
2414 that.expr.type, that.name, argtypes, typeargtypes, allowBoxing);
2416 Symbol refSym = refResult.fst;
2417 Resolve.ReferenceLookupHelper lookupHelper = refResult.snd;
2419 if (refSym.kind != MTH) {
2420 boolean targetError;
2421 switch (refSym.kind) {
2422 case ABSENT_MTH:
2423 targetError = false;
2424 break;
2425 case WRONG_MTH:
2426 case WRONG_MTHS:
2427 case AMBIGUOUS:
2428 case HIDDEN:
2429 case STATICERR:
2430 case MISSING_ENCL:
2431 targetError = true;
2432 break;
2433 default:
2434 Assert.error("unexpected result kind " + refSym.kind);
2435 targetError = false;
2436 }
2438 JCDiagnostic detailsDiag = ((Resolve.ResolveError)refSym).getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT,
2439 that, exprType.tsym, exprType, that.name, argtypes, typeargtypes);
2441 JCDiagnostic.DiagnosticType diagKind = targetError ?
2442 JCDiagnostic.DiagnosticType.FRAGMENT : JCDiagnostic.DiagnosticType.ERROR;
2444 JCDiagnostic diag = diags.create(diagKind, log.currentSource(), that,
2445 "invalid.mref", Kinds.kindName(that.getMode()), detailsDiag);
2447 if (targetError) {
2448 resultInfo.checkContext.report(that, diag);
2449 } else {
2450 log.report(diag);
2451 }
2452 result = that.type = types.createErrorType(target);
2453 return;
2454 }
2456 if (desc.getReturnType() == Type.recoveryType) {
2457 // stop here
2458 result = that.type = types.createErrorType(target);
2459 return;
2460 }
2462 that.sym = refSym.baseSymbol();
2463 that.kind = lookupHelper.referenceKind(that.sym);
2465 ResultInfo checkInfo =
2466 resultInfo.dup(newMethodTemplate(
2467 desc.getReturnType().tag == VOID ? Type.noType : desc.getReturnType(),
2468 lookupHelper.argtypes,
2469 typeargtypes));
2471 Type refType = checkId(that, lookupHelper.site, refSym, localEnv, checkInfo);
2473 if (!refType.isErroneous()) {
2474 refType = types.createMethodTypeWithReturn(refType,
2475 adjustMethodReturnType(lookupHelper.site, that.name, checkInfo.pt.getParameterTypes(), refType.getReturnType()));
2476 }
2478 //go ahead with standard method reference compatibility check - note that param check
2479 //is a no-op (as this has been taken care during method applicability)
2480 boolean isSpeculativeRound =
2481 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
2482 checkReferenceCompatible(that, desc, refType, resultInfo.checkContext, isSpeculativeRound);
2483 if (!isSpeculativeRound) {
2484 checkAccessibleFunctionalDescriptor(that, localEnv, resultInfo.checkContext.inferenceContext(), desc);
2485 }
2486 result = check(that, target, VAL, resultInfo);
2487 } catch (Types.FunctionDescriptorLookupError ex) {
2488 JCDiagnostic cause = ex.getDiagnostic();
2489 resultInfo.checkContext.report(that, cause);
2490 result = that.type = types.createErrorType(pt());
2491 return;
2492 }
2493 }
2495 @SuppressWarnings("fallthrough")
2496 void checkReferenceCompatible(JCMemberReference tree, Type descriptor, Type refType, CheckContext checkContext, boolean speculativeAttr) {
2497 Type returnType = checkContext.inferenceContext().asFree(descriptor.getReturnType(), types);
2499 Type resType;
2500 switch (tree.getMode()) {
2501 case NEW:
2502 if (!tree.expr.type.isRaw()) {
2503 resType = tree.expr.type;
2504 break;
2505 }
2506 default:
2507 resType = refType.getReturnType();
2508 }
2510 Type incompatibleReturnType = resType;
2512 if (returnType.tag == VOID) {
2513 incompatibleReturnType = null;
2514 }
2516 if (returnType.tag != VOID && resType.tag != VOID) {
2517 if (resType.isErroneous() ||
2518 new LambdaReturnContext(checkContext).compatible(resType, returnType, Warner.noWarnings)) {
2519 incompatibleReturnType = null;
2520 }
2521 }
2523 if (incompatibleReturnType != null) {
2524 checkContext.report(tree, diags.fragment("incompatible.ret.type.in.mref",
2525 diags.fragment("inconvertible.types", resType, descriptor.getReturnType())));
2526 }
2528 if (!speculativeAttr) {
2529 List<Type> thrownTypes = checkContext.inferenceContext().asFree(descriptor.getThrownTypes(), types);
2530 if (chk.unhandled(refType.getThrownTypes(), thrownTypes).nonEmpty()) {
2531 log.error(tree, "incompatible.thrown.types.in.mref", refType.getThrownTypes());
2532 }
2533 }
2534 }
2536 public void visitParens(JCParens tree) {
2537 Type owntype = attribTree(tree.expr, env, resultInfo);
2538 result = check(tree, owntype, pkind(), resultInfo);
2539 Symbol sym = TreeInfo.symbol(tree);
2540 if (sym != null && (sym.kind&(TYP|PCK)) != 0)
2541 log.error(tree.pos(), "illegal.start.of.type");
2542 }
2544 public void visitAssign(JCAssign tree) {
2545 Type owntype = attribTree(tree.lhs, env.dup(tree), varInfo);
2546 Type capturedType = capture(owntype);
2547 attribExpr(tree.rhs, env, owntype);
2548 result = check(tree, capturedType, VAL, resultInfo);
2549 }
2551 public void visitAssignop(JCAssignOp tree) {
2552 // Attribute arguments.
2553 Type owntype = attribTree(tree.lhs, env, varInfo);
2554 Type operand = attribExpr(tree.rhs, env);
2555 // Find operator.
2556 Symbol operator = tree.operator = rs.resolveBinaryOperator(
2557 tree.pos(), tree.getTag().noAssignOp(), env,
2558 owntype, operand);
2560 if (operator.kind == MTH &&
2561 !owntype.isErroneous() &&
2562 !operand.isErroneous()) {
2563 chk.checkOperator(tree.pos(),
2564 (OperatorSymbol)operator,
2565 tree.getTag().noAssignOp(),
2566 owntype,
2567 operand);
2568 chk.checkDivZero(tree.rhs.pos(), operator, operand);
2569 chk.checkCastable(tree.rhs.pos(),
2570 operator.type.getReturnType(),
2571 owntype);
2572 }
2573 result = check(tree, owntype, VAL, resultInfo);
2574 }
2576 public void visitUnary(JCUnary tree) {
2577 // Attribute arguments.
2578 Type argtype = (tree.getTag().isIncOrDecUnaryOp())
2579 ? attribTree(tree.arg, env, varInfo)
2580 : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
2582 // Find operator.
2583 Symbol operator = tree.operator =
2584 rs.resolveUnaryOperator(tree.pos(), tree.getTag(), env, argtype);
2586 Type owntype = types.createErrorType(tree.type);
2587 if (operator.kind == MTH &&
2588 !argtype.isErroneous()) {
2589 owntype = (tree.getTag().isIncOrDecUnaryOp())
2590 ? tree.arg.type
2591 : operator.type.getReturnType();
2592 int opc = ((OperatorSymbol)operator).opcode;
2594 // If the argument is constant, fold it.
2595 if (argtype.constValue() != null) {
2596 Type ctype = cfolder.fold1(opc, argtype);
2597 if (ctype != null) {
2598 owntype = cfolder.coerce(ctype, owntype);
2600 // Remove constant types from arguments to
2601 // conserve space. The parser will fold concatenations
2602 // of string literals; the code here also
2603 // gets rid of intermediate results when some of the
2604 // operands are constant identifiers.
2605 if (tree.arg.type.tsym == syms.stringType.tsym) {
2606 tree.arg.type = syms.stringType;
2607 }
2608 }
2609 }
2610 }
2611 result = check(tree, owntype, VAL, resultInfo);
2612 }
2614 public void visitBinary(JCBinary tree) {
2615 // Attribute arguments.
2616 Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
2617 Type right = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.rhs, env));
2619 // Find operator.
2620 Symbol operator = tree.operator =
2621 rs.resolveBinaryOperator(tree.pos(), tree.getTag(), env, left, right);
2623 Type owntype = types.createErrorType(tree.type);
2624 if (operator.kind == MTH &&
2625 !left.isErroneous() &&
2626 !right.isErroneous()) {
2627 owntype = operator.type.getReturnType();
2628 int opc = chk.checkOperator(tree.lhs.pos(),
2629 (OperatorSymbol)operator,
2630 tree.getTag(),
2631 left,
2632 right);
2634 // If both arguments are constants, fold them.
2635 if (left.constValue() != null && right.constValue() != null) {
2636 Type ctype = cfolder.fold2(opc, left, right);
2637 if (ctype != null) {
2638 owntype = cfolder.coerce(ctype, owntype);
2640 // Remove constant types from arguments to
2641 // conserve space. The parser will fold concatenations
2642 // of string literals; the code here also
2643 // gets rid of intermediate results when some of the
2644 // operands are constant identifiers.
2645 if (tree.lhs.type.tsym == syms.stringType.tsym) {
2646 tree.lhs.type = syms.stringType;
2647 }
2648 if (tree.rhs.type.tsym == syms.stringType.tsym) {
2649 tree.rhs.type = syms.stringType;
2650 }
2651 }
2652 }
2654 // Check that argument types of a reference ==, != are
2655 // castable to each other, (JLS???).
2656 if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
2657 if (!types.isCastable(left, right, new Warner(tree.pos()))) {
2658 log.error(tree.pos(), "incomparable.types", left, right);
2659 }
2660 }
2662 chk.checkDivZero(tree.rhs.pos(), operator, right);
2663 }
2664 result = check(tree, owntype, VAL, resultInfo);
2665 }
2667 public void visitTypeCast(final JCTypeCast tree) {
2668 Type clazztype = attribType(tree.clazz, env);
2669 chk.validate(tree.clazz, env, false);
2670 //a fresh environment is required for 292 inference to work properly ---
2671 //see Infer.instantiatePolymorphicSignatureInstance()
2672 Env<AttrContext> localEnv = env.dup(tree);
2673 //should we propagate the target type?
2674 final ResultInfo castInfo;
2675 final boolean isPoly = TreeInfo.isPoly(tree.expr, tree);
2676 if (isPoly) {
2677 //expression is a poly - we need to propagate target type info
2678 castInfo = new ResultInfo(VAL, clazztype, new Check.NestedCheckContext(resultInfo.checkContext) {
2679 @Override
2680 public boolean compatible(Type found, Type req, Warner warn) {
2681 return types.isCastable(found, req, warn);
2682 }
2683 });
2684 } else {
2685 //standalone cast - target-type info is not propagated
2686 castInfo = unknownExprInfo;
2687 }
2688 Type exprtype = attribTree(tree.expr, localEnv, castInfo);
2689 Type owntype = isPoly ? clazztype : chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
2690 if (exprtype.constValue() != null)
2691 owntype = cfolder.coerce(exprtype, owntype);
2692 result = check(tree, capture(owntype), VAL, resultInfo);
2693 if (!isPoly)
2694 chk.checkRedundantCast(localEnv, tree);
2695 }
2697 public void visitTypeTest(JCInstanceOf tree) {
2698 Type exprtype = chk.checkNullOrRefType(
2699 tree.expr.pos(), attribExpr(tree.expr, env));
2700 Type clazztype = chk.checkReifiableReferenceType(
2701 tree.clazz.pos(), attribType(tree.clazz, env));
2702 chk.validate(tree.clazz, env, false);
2703 chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
2704 result = check(tree, syms.booleanType, VAL, resultInfo);
2705 }
2707 public void visitIndexed(JCArrayAccess tree) {
2708 Type owntype = types.createErrorType(tree.type);
2709 Type atype = attribExpr(tree.indexed, env);
2710 attribExpr(tree.index, env, syms.intType);
2711 if (types.isArray(atype))
2712 owntype = types.elemtype(atype);
2713 else if (atype.tag != ERROR)
2714 log.error(tree.pos(), "array.req.but.found", atype);
2715 if ((pkind() & VAR) == 0) owntype = capture(owntype);
2716 result = check(tree, owntype, VAR, resultInfo);
2717 }
2719 public void visitIdent(JCIdent tree) {
2720 Symbol sym;
2722 // Find symbol
2723 if (pt().tag == METHOD || pt().tag == FORALL) {
2724 // If we are looking for a method, the prototype `pt' will be a
2725 // method type with the type of the call's arguments as parameters.
2726 env.info.pendingResolutionPhase = null;
2727 sym = rs.resolveMethod(tree.pos(), env, tree.name, pt().getParameterTypes(), pt().getTypeArguments());
2728 } else if (tree.sym != null && tree.sym.kind != VAR) {
2729 sym = tree.sym;
2730 } else {
2731 sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind());
2732 }
2733 tree.sym = sym;
2735 // (1) Also find the environment current for the class where
2736 // sym is defined (`symEnv').
2737 // Only for pre-tiger versions (1.4 and earlier):
2738 // (2) Also determine whether we access symbol out of an anonymous
2739 // class in a this or super call. This is illegal for instance
2740 // members since such classes don't carry a this$n link.
2741 // (`noOuterThisPath').
2742 Env<AttrContext> symEnv = env;
2743 boolean noOuterThisPath = false;
2744 if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
2745 (sym.kind & (VAR | MTH | TYP)) != 0 &&
2746 sym.owner.kind == TYP &&
2747 tree.name != names._this && tree.name != names._super) {
2749 // Find environment in which identifier is defined.
2750 while (symEnv.outer != null &&
2751 !sym.isMemberOf(symEnv.enclClass.sym, types)) {
2752 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
2753 noOuterThisPath = !allowAnonOuterThis;
2754 symEnv = symEnv.outer;
2755 }
2756 }
2758 // If symbol is a variable, ...
2759 if (sym.kind == VAR) {
2760 VarSymbol v = (VarSymbol)sym;
2762 // ..., evaluate its initializer, if it has one, and check for
2763 // illegal forward reference.
2764 checkInit(tree, env, v, false);
2766 // If we are expecting a variable (as opposed to a value), check
2767 // that the variable is assignable in the current environment.
2768 if (pkind() == VAR)
2769 checkAssignable(tree.pos(), v, null, env);
2770 }
2772 // In a constructor body,
2773 // if symbol is a field or instance method, check that it is
2774 // not accessed before the supertype constructor is called.
2775 if ((symEnv.info.isSelfCall || noOuterThisPath) &&
2776 (sym.kind & (VAR | MTH)) != 0 &&
2777 sym.owner.kind == TYP &&
2778 (sym.flags() & STATIC) == 0) {
2779 chk.earlyRefError(tree.pos(), sym.kind == VAR ? sym : thisSym(tree.pos(), env));
2780 }
2781 Env<AttrContext> env1 = env;
2782 if (sym.kind != ERR && sym.kind != TYP && sym.owner != null && sym.owner != env1.enclClass.sym) {
2783 // If the found symbol is inaccessible, then it is
2784 // accessed through an enclosing instance. Locate this
2785 // enclosing instance:
2786 while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
2787 env1 = env1.outer;
2788 }
2789 result = checkId(tree, env1.enclClass.sym.type, sym, env, resultInfo);
2790 }
2792 public void visitSelect(JCFieldAccess tree) {
2793 // Determine the expected kind of the qualifier expression.
2794 int skind = 0;
2795 if (tree.name == names._this || tree.name == names._super ||
2796 tree.name == names._class)
2797 {
2798 skind = TYP;
2799 } else {
2800 if ((pkind() & PCK) != 0) skind = skind | PCK;
2801 if ((pkind() & TYP) != 0) skind = skind | TYP | PCK;
2802 if ((pkind() & (VAL | MTH)) != 0) skind = skind | VAL | TYP;
2803 }
2805 // Attribute the qualifier expression, and determine its symbol (if any).
2806 Type site = attribTree(tree.selected, env, new ResultInfo(skind, Infer.anyPoly));
2807 if ((pkind() & (PCK | TYP)) == 0)
2808 site = capture(site); // Capture field access
2810 // don't allow T.class T[].class, etc
2811 if (skind == TYP) {
2812 Type elt = site;
2813 while (elt.tag == ARRAY)
2814 elt = ((ArrayType)elt).elemtype;
2815 if (elt.tag == TYPEVAR) {
2816 log.error(tree.pos(), "type.var.cant.be.deref");
2817 result = types.createErrorType(tree.type);
2818 return;
2819 }
2820 }
2822 // If qualifier symbol is a type or `super', assert `selectSuper'
2823 // for the selection. This is relevant for determining whether
2824 // protected symbols are accessible.
2825 Symbol sitesym = TreeInfo.symbol(tree.selected);
2826 boolean selectSuperPrev = env.info.selectSuper;
2827 env.info.selectSuper =
2828 sitesym != null &&
2829 sitesym.name == names._super;
2831 // Determine the symbol represented by the selection.
2832 env.info.pendingResolutionPhase = null;
2833 Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
2834 if (sym.exists() && !isType(sym) && (pkind() & (PCK | TYP)) != 0) {
2835 site = capture(site);
2836 sym = selectSym(tree, sitesym, site, env, resultInfo);
2837 }
2838 boolean varArgs = env.info.lastResolveVarargs();
2839 tree.sym = sym;
2841 if (site.tag == TYPEVAR && !isType(sym) && sym.kind != ERR) {
2842 while (site.tag == TYPEVAR) site = site.getUpperBound();
2843 site = capture(site);
2844 }
2846 // If that symbol is a variable, ...
2847 if (sym.kind == VAR) {
2848 VarSymbol v = (VarSymbol)sym;
2850 // ..., evaluate its initializer, if it has one, and check for
2851 // illegal forward reference.
2852 checkInit(tree, env, v, true);
2854 // If we are expecting a variable (as opposed to a value), check
2855 // that the variable is assignable in the current environment.
2856 if (pkind() == VAR)
2857 checkAssignable(tree.pos(), v, tree.selected, env);
2858 }
2860 if (sitesym != null &&
2861 sitesym.kind == VAR &&
2862 ((VarSymbol)sitesym).isResourceVariable() &&
2863 sym.kind == MTH &&
2864 sym.name.equals(names.close) &&
2865 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) &&
2866 env.info.lint.isEnabled(LintCategory.TRY)) {
2867 log.warning(LintCategory.TRY, tree, "try.explicit.close.call");
2868 }
2870 // Disallow selecting a type from an expression
2871 if (isType(sym) && (sitesym==null || (sitesym.kind&(TYP|PCK)) == 0)) {
2872 tree.type = check(tree.selected, pt(),
2873 sitesym == null ? VAL : sitesym.kind, new ResultInfo(TYP|PCK, pt()));
2874 }
2876 if (isType(sitesym)) {
2877 if (sym.name == names._this) {
2878 // If `C' is the currently compiled class, check that
2879 // C.this' does not appear in a call to a super(...)
2880 if (env.info.isSelfCall &&
2881 site.tsym == env.enclClass.sym) {
2882 chk.earlyRefError(tree.pos(), sym);
2883 }
2884 } else {
2885 // Check if type-qualified fields or methods are static (JLS)
2886 if ((sym.flags() & STATIC) == 0 &&
2887 !env.next.tree.hasTag(REFERENCE) &&
2888 sym.name != names._super &&
2889 (sym.kind == VAR || sym.kind == MTH)) {
2890 rs.accessBase(rs.new StaticError(sym),
2891 tree.pos(), site, sym.name, true);
2892 }
2893 }
2894 } else if (sym.kind != ERR && (sym.flags() & STATIC) != 0 && sym.name != names._class) {
2895 // If the qualified item is not a type and the selected item is static, report
2896 // a warning. Make allowance for the class of an array type e.g. Object[].class)
2897 chk.warnStatic(tree, "static.not.qualified.by.type", Kinds.kindName(sym.kind), sym.owner);
2898 }
2900 // If we are selecting an instance member via a `super', ...
2901 if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
2903 // Check that super-qualified symbols are not abstract (JLS)
2904 rs.checkNonAbstract(tree.pos(), sym);
2906 if (site.isRaw()) {
2907 // Determine argument types for site.
2908 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
2909 if (site1 != null) site = site1;
2910 }
2911 }
2913 env.info.selectSuper = selectSuperPrev;
2914 result = checkId(tree, site, sym, env, resultInfo);
2915 }
2916 //where
2917 /** Determine symbol referenced by a Select expression,
2918 *
2919 * @param tree The select tree.
2920 * @param site The type of the selected expression,
2921 * @param env The current environment.
2922 * @param resultInfo The current result.
2923 */
2924 private Symbol selectSym(JCFieldAccess tree,
2925 Symbol location,
2926 Type site,
2927 Env<AttrContext> env,
2928 ResultInfo resultInfo) {
2929 DiagnosticPosition pos = tree.pos();
2930 Name name = tree.name;
2931 switch (site.tag) {
2932 case PACKAGE:
2933 return rs.accessBase(
2934 rs.findIdentInPackage(env, site.tsym, name, resultInfo.pkind),
2935 pos, location, site, name, true);
2936 case ARRAY:
2937 case CLASS:
2938 if (resultInfo.pt.tag == METHOD || resultInfo.pt.tag == FORALL) {
2939 return rs.resolveQualifiedMethod(
2940 pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
2941 } else if (name == names._this || name == names._super) {
2942 return rs.resolveSelf(pos, env, site.tsym, name);
2943 } else if (name == names._class) {
2944 // In this case, we have already made sure in
2945 // visitSelect that qualifier expression is a type.
2946 Type t = syms.classType;
2947 List<Type> typeargs = allowGenerics
2948 ? List.of(types.erasure(site))
2949 : List.<Type>nil();
2950 t = new ClassType(t.getEnclosingType(), typeargs, t.tsym);
2951 return new VarSymbol(
2952 STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
2953 } else {
2954 // We are seeing a plain identifier as selector.
2955 Symbol sym = rs.findIdentInType(env, site, name, resultInfo.pkind);
2956 if ((resultInfo.pkind & ERRONEOUS) == 0)
2957 sym = rs.accessBase(sym, pos, location, site, name, true);
2958 return sym;
2959 }
2960 case WILDCARD:
2961 throw new AssertionError(tree);
2962 case TYPEVAR:
2963 // Normally, site.getUpperBound() shouldn't be null.
2964 // It should only happen during memberEnter/attribBase
2965 // when determining the super type which *must* beac
2966 // done before attributing the type variables. In
2967 // other words, we are seeing this illegal program:
2968 // class B<T> extends A<T.foo> {}
2969 Symbol sym = (site.getUpperBound() != null)
2970 ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
2971 : null;
2972 if (sym == null) {
2973 log.error(pos, "type.var.cant.be.deref");
2974 return syms.errSymbol;
2975 } else {
2976 Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
2977 rs.new AccessError(env, site, sym) :
2978 sym;
2979 rs.accessBase(sym2, pos, location, site, name, true);
2980 return sym;
2981 }
2982 case ERROR:
2983 // preserve identifier names through errors
2984 return types.createErrorType(name, site.tsym, site).tsym;
2985 default:
2986 // The qualifier expression is of a primitive type -- only
2987 // .class is allowed for these.
2988 if (name == names._class) {
2989 // In this case, we have already made sure in Select that
2990 // qualifier expression is a type.
2991 Type t = syms.classType;
2992 Type arg = types.boxedClass(site).type;
2993 t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym);
2994 return new VarSymbol(
2995 STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
2996 } else {
2997 log.error(pos, "cant.deref", site);
2998 return syms.errSymbol;
2999 }
3000 }
3001 }
3003 /** Determine type of identifier or select expression and check that
3004 * (1) the referenced symbol is not deprecated
3005 * (2) the symbol's type is safe (@see checkSafe)
3006 * (3) if symbol is a variable, check that its type and kind are
3007 * compatible with the prototype and protokind.
3008 * (4) if symbol is an instance field of a raw type,
3009 * which is being assigned to, issue an unchecked warning if its
3010 * type changes under erasure.
3011 * (5) if symbol is an instance method of a raw type, issue an
3012 * unchecked warning if its argument types change under erasure.
3013 * If checks succeed:
3014 * If symbol is a constant, return its constant type
3015 * else if symbol is a method, return its result type
3016 * otherwise return its type.
3017 * Otherwise return errType.
3018 *
3019 * @param tree The syntax tree representing the identifier
3020 * @param site If this is a select, the type of the selected
3021 * expression, otherwise the type of the current class.
3022 * @param sym The symbol representing the identifier.
3023 * @param env The current environment.
3024 * @param resultInfo The expected result
3025 */
3026 Type checkId(JCTree tree,
3027 Type site,
3028 Symbol sym,
3029 Env<AttrContext> env,
3030 ResultInfo resultInfo) {
3031 Type pt = resultInfo.pt.tag == FORALL || resultInfo.pt.tag == METHOD ?
3032 resultInfo.pt.map(deferredAttr.new DeferredTypeMap(AttrMode.SPECULATIVE, sym, env.info.pendingResolutionPhase)) :
3033 resultInfo.pt;
3035 DeferredAttr.DeferredTypeMap recoveryMap =
3036 deferredAttr.new RecoveryDeferredTypeMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase);
3038 if (pt.isErroneous()) {
3039 Type.map(resultInfo.pt.getParameterTypes(), recoveryMap);
3040 return types.createErrorType(site);
3041 }
3042 Type owntype; // The computed type of this identifier occurrence.
3043 switch (sym.kind) {
3044 case TYP:
3045 // For types, the computed type equals the symbol's type,
3046 // except for two situations:
3047 owntype = sym.type;
3048 if (owntype.tag == CLASS) {
3049 Type ownOuter = owntype.getEnclosingType();
3051 // (a) If the symbol's type is parameterized, erase it
3052 // because no type parameters were given.
3053 // We recover generic outer type later in visitTypeApply.
3054 if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
3055 owntype = types.erasure(owntype);
3056 }
3058 // (b) If the symbol's type is an inner class, then
3059 // we have to interpret its outer type as a superclass
3060 // of the site type. Example:
3061 //
3062 // class Tree<A> { class Visitor { ... } }
3063 // class PointTree extends Tree<Point> { ... }
3064 // ...PointTree.Visitor...
3065 //
3066 // Then the type of the last expression above is
3067 // Tree<Point>.Visitor.
3068 else if (ownOuter.tag == CLASS && site != ownOuter) {
3069 Type normOuter = site;
3070 if (normOuter.tag == CLASS)
3071 normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
3072 if (normOuter == null) // perhaps from an import
3073 normOuter = types.erasure(ownOuter);
3074 if (normOuter != ownOuter)
3075 owntype = new ClassType(
3076 normOuter, List.<Type>nil(), owntype.tsym);
3077 }
3078 }
3079 break;
3080 case VAR:
3081 VarSymbol v = (VarSymbol)sym;
3082 // Test (4): if symbol is an instance field of a raw type,
3083 // which is being assigned to, issue an unchecked warning if
3084 // its type changes under erasure.
3085 if (allowGenerics &&
3086 resultInfo.pkind == VAR &&
3087 v.owner.kind == TYP &&
3088 (v.flags() & STATIC) == 0 &&
3089 (site.tag == CLASS || site.tag == TYPEVAR)) {
3090 Type s = types.asOuterSuper(site, v.owner);
3091 if (s != null &&
3092 s.isRaw() &&
3093 !types.isSameType(v.type, v.erasure(types))) {
3094 chk.warnUnchecked(tree.pos(),
3095 "unchecked.assign.to.var",
3096 v, s);
3097 }
3098 }
3099 // The computed type of a variable is the type of the
3100 // variable symbol, taken as a member of the site type.
3101 owntype = (sym.owner.kind == TYP &&
3102 sym.name != names._this && sym.name != names._super)
3103 ? types.memberType(site, sym)
3104 : sym.type;
3106 // If the variable is a constant, record constant value in
3107 // computed type.
3108 if (v.getConstValue() != null && isStaticReference(tree))
3109 owntype = owntype.constType(v.getConstValue());
3111 if (resultInfo.pkind == VAL) {
3112 owntype = capture(owntype); // capture "names as expressions"
3113 }
3114 break;
3115 case MTH: {
3116 owntype = checkMethod(site, sym,
3117 new ResultInfo(VAL, resultInfo.pt.getReturnType(), resultInfo.checkContext),
3118 env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(),
3119 resultInfo.pt.getTypeArguments());
3120 break;
3121 }
3122 case PCK: case ERR:
3123 Type.map(resultInfo.pt.getParameterTypes(), recoveryMap);
3124 owntype = sym.type;
3125 break;
3126 default:
3127 throw new AssertionError("unexpected kind: " + sym.kind +
3128 " in tree " + tree);
3129 }
3131 // Test (1): emit a `deprecation' warning if symbol is deprecated.
3132 // (for constructors, the error was given when the constructor was
3133 // resolved)
3135 if (sym.name != names.init) {
3136 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym);
3137 chk.checkSunAPI(tree.pos(), sym);
3138 }
3140 // Test (3): if symbol is a variable, check that its type and
3141 // kind are compatible with the prototype and protokind.
3142 return check(tree, owntype, sym.kind, resultInfo);
3143 }
3145 /** Check that variable is initialized and evaluate the variable's
3146 * initializer, if not yet done. Also check that variable is not
3147 * referenced before it is defined.
3148 * @param tree The tree making up the variable reference.
3149 * @param env The current environment.
3150 * @param v The variable's symbol.
3151 */
3152 private void checkInit(JCTree tree,
3153 Env<AttrContext> env,
3154 VarSymbol v,
3155 boolean onlyWarning) {
3156 // System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " +
3157 // tree.pos + " " + v.pos + " " +
3158 // Resolve.isStatic(env));//DEBUG
3160 // A forward reference is diagnosed if the declaration position
3161 // of the variable is greater than the current tree position
3162 // and the tree and variable definition occur in the same class
3163 // definition. Note that writes don't count as references.
3164 // This check applies only to class and instance
3165 // variables. Local variables follow different scope rules,
3166 // and are subject to definite assignment checking.
3167 if ((env.info.enclVar == v || v.pos > tree.pos) &&
3168 v.owner.kind == TYP &&
3169 canOwnInitializer(owner(env)) &&
3170 v.owner == env.info.scope.owner.enclClass() &&
3171 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
3172 (!env.tree.hasTag(ASSIGN) ||
3173 TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
3174 String suffix = (env.info.enclVar == v) ?
3175 "self.ref" : "forward.ref";
3176 if (!onlyWarning || isStaticEnumField(v)) {
3177 log.error(tree.pos(), "illegal." + suffix);
3178 } else if (useBeforeDeclarationWarning) {
3179 log.warning(tree.pos(), suffix, v);
3180 }
3181 }
3183 v.getConstValue(); // ensure initializer is evaluated
3185 checkEnumInitializer(tree, env, v);
3186 }
3188 /**
3189 * Check for illegal references to static members of enum. In
3190 * an enum type, constructors and initializers may not
3191 * reference its static members unless they are constant.
3192 *
3193 * @param tree The tree making up the variable reference.
3194 * @param env The current environment.
3195 * @param v The variable's symbol.
3196 * @jls section 8.9 Enums
3197 */
3198 private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
3199 // JLS:
3200 //
3201 // "It is a compile-time error to reference a static field
3202 // of an enum type that is not a compile-time constant
3203 // (15.28) from constructors, instance initializer blocks,
3204 // or instance variable initializer expressions of that
3205 // type. It is a compile-time error for the constructors,
3206 // instance initializer blocks, or instance variable
3207 // initializer expressions of an enum constant e to refer
3208 // to itself or to an enum constant of the same type that
3209 // is declared to the right of e."
3210 if (isStaticEnumField(v)) {
3211 ClassSymbol enclClass = env.info.scope.owner.enclClass();
3213 if (enclClass == null || enclClass.owner == null)
3214 return;
3216 // See if the enclosing class is the enum (or a
3217 // subclass thereof) declaring v. If not, this
3218 // reference is OK.
3219 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
3220 return;
3222 // If the reference isn't from an initializer, then
3223 // the reference is OK.
3224 if (!Resolve.isInitializer(env))
3225 return;
3227 log.error(tree.pos(), "illegal.enum.static.ref");
3228 }
3229 }
3231 /** Is the given symbol a static, non-constant field of an Enum?
3232 * Note: enum literals should not be regarded as such
3233 */
3234 private boolean isStaticEnumField(VarSymbol v) {
3235 return Flags.isEnum(v.owner) &&
3236 Flags.isStatic(v) &&
3237 !Flags.isConstant(v) &&
3238 v.name != names._class;
3239 }
3241 /** Can the given symbol be the owner of code which forms part
3242 * if class initialization? This is the case if the symbol is
3243 * a type or field, or if the symbol is the synthetic method.
3244 * owning a block.
3245 */
3246 private boolean canOwnInitializer(Symbol sym) {
3247 return
3248 (sym.kind & (VAR | TYP)) != 0 ||
3249 (sym.kind == MTH && (sym.flags() & BLOCK) != 0);
3250 }
3252 Warner noteWarner = new Warner();
3254 /**
3255 * Check that method arguments conform to its instantiation.
3256 **/
3257 public Type checkMethod(Type site,
3258 Symbol sym,
3259 ResultInfo resultInfo,
3260 Env<AttrContext> env,
3261 final List<JCExpression> argtrees,
3262 List<Type> argtypes,
3263 List<Type> typeargtypes) {
3264 // Test (5): if symbol is an instance method of a raw type, issue
3265 // an unchecked warning if its argument types change under erasure.
3266 if (allowGenerics &&
3267 (sym.flags() & STATIC) == 0 &&
3268 (site.tag == CLASS || site.tag == TYPEVAR)) {
3269 Type s = types.asOuterSuper(site, sym.owner);
3270 if (s != null && s.isRaw() &&
3271 !types.isSameTypes(sym.type.getParameterTypes(),
3272 sym.erasure(types).getParameterTypes())) {
3273 chk.warnUnchecked(env.tree.pos(),
3274 "unchecked.call.mbr.of.raw.type",
3275 sym, s);
3276 }
3277 }
3279 // Compute the identifier's instantiated type.
3280 // For methods, we need to compute the instance type by
3281 // Resolve.instantiate from the symbol's type as well as
3282 // any type arguments and value arguments.
3283 noteWarner.clear();
3284 try {
3285 Type owntype = rs.checkMethod(
3286 env,
3287 site,
3288 sym,
3289 resultInfo,
3290 argtypes,
3291 typeargtypes,
3292 noteWarner);
3294 return chk.checkMethod(owntype, sym, env, argtrees, argtypes, env.info.lastResolveVarargs(),
3295 noteWarner.hasNonSilentLint(LintCategory.UNCHECKED));
3296 } catch (Infer.InferenceException ex) {
3297 //invalid target type - propagate exception outwards or report error
3298 //depending on the current check context
3299 resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic());
3300 return types.createErrorType(site);
3301 } catch (Resolve.InapplicableMethodException ex) {
3302 Assert.error(ex.getDiagnostic().getMessage(Locale.getDefault()));
3303 return null;
3304 }
3305 }
3307 public void visitLiteral(JCLiteral tree) {
3308 result = check(
3309 tree, litType(tree.typetag).constType(tree.value), VAL, resultInfo);
3310 }
3311 //where
3312 /** Return the type of a literal with given type tag.
3313 */
3314 Type litType(int tag) {
3315 return (tag == TypeTags.CLASS) ? syms.stringType : syms.typeOfTag[tag];
3316 }
3318 public void visitTypeIdent(JCPrimitiveTypeTree tree) {
3319 result = check(tree, syms.typeOfTag[tree.typetag], TYP, resultInfo);
3320 }
3322 public void visitTypeArray(JCArrayTypeTree tree) {
3323 Type etype = attribType(tree.elemtype, env);
3324 Type type = new ArrayType(etype, syms.arrayClass);
3325 result = check(tree, type, TYP, resultInfo);
3326 }
3328 /** Visitor method for parameterized types.
3329 * Bound checking is left until later, since types are attributed
3330 * before supertype structure is completely known
3331 */
3332 public void visitTypeApply(JCTypeApply tree) {
3333 Type owntype = types.createErrorType(tree.type);
3335 // Attribute functor part of application and make sure it's a class.
3336 Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
3338 // Attribute type parameters
3339 List<Type> actuals = attribTypes(tree.arguments, env);
3341 if (clazztype.tag == CLASS) {
3342 List<Type> formals = clazztype.tsym.type.getTypeArguments();
3343 if (actuals.isEmpty()) //diamond
3344 actuals = formals;
3346 if (actuals.length() == formals.length()) {
3347 List<Type> a = actuals;
3348 List<Type> f = formals;
3349 while (a.nonEmpty()) {
3350 a.head = a.head.withTypeVar(f.head);
3351 a = a.tail;
3352 f = f.tail;
3353 }
3354 // Compute the proper generic outer
3355 Type clazzOuter = clazztype.getEnclosingType();
3356 if (clazzOuter.tag == CLASS) {
3357 Type site;
3358 JCExpression clazz = TreeInfo.typeIn(tree.clazz);
3359 if (clazz.hasTag(IDENT)) {
3360 site = env.enclClass.sym.type;
3361 } else if (clazz.hasTag(SELECT)) {
3362 site = ((JCFieldAccess) clazz).selected.type;
3363 } else throw new AssertionError(""+tree);
3364 if (clazzOuter.tag == CLASS && site != clazzOuter) {
3365 if (site.tag == CLASS)
3366 site = types.asOuterSuper(site, clazzOuter.tsym);
3367 if (site == null)
3368 site = types.erasure(clazzOuter);
3369 clazzOuter = site;
3370 }
3371 }
3372 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym);
3373 } else {
3374 if (formals.length() != 0) {
3375 log.error(tree.pos(), "wrong.number.type.args",
3376 Integer.toString(formals.length()));
3377 } else {
3378 log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym);
3379 }
3380 owntype = types.createErrorType(tree.type);
3381 }
3382 }
3383 result = check(tree, owntype, TYP, resultInfo);
3384 }
3386 public void visitTypeUnion(JCTypeUnion tree) {
3387 ListBuffer<Type> multicatchTypes = ListBuffer.lb();
3388 ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
3389 for (JCExpression typeTree : tree.alternatives) {
3390 Type ctype = attribType(typeTree, env);
3391 ctype = chk.checkType(typeTree.pos(),
3392 chk.checkClassType(typeTree.pos(), ctype),
3393 syms.throwableType);
3394 if (!ctype.isErroneous()) {
3395 //check that alternatives of a union type are pairwise
3396 //unrelated w.r.t. subtyping
3397 if (chk.intersects(ctype, multicatchTypes.toList())) {
3398 for (Type t : multicatchTypes) {
3399 boolean sub = types.isSubtype(ctype, t);
3400 boolean sup = types.isSubtype(t, ctype);
3401 if (sub || sup) {
3402 //assume 'a' <: 'b'
3403 Type a = sub ? ctype : t;
3404 Type b = sub ? t : ctype;
3405 log.error(typeTree.pos(), "multicatch.types.must.be.disjoint", a, b);
3406 }
3407 }
3408 }
3409 multicatchTypes.append(ctype);
3410 if (all_multicatchTypes != null)
3411 all_multicatchTypes.append(ctype);
3412 } else {
3413 if (all_multicatchTypes == null) {
3414 all_multicatchTypes = ListBuffer.lb();
3415 all_multicatchTypes.appendList(multicatchTypes);
3416 }
3417 all_multicatchTypes.append(ctype);
3418 }
3419 }
3420 Type t = check(tree, types.lub(multicatchTypes.toList()), TYP, resultInfo);
3421 if (t.tag == CLASS) {
3422 List<Type> alternatives =
3423 ((all_multicatchTypes == null) ? multicatchTypes : all_multicatchTypes).toList();
3424 t = new UnionClassType((ClassType) t, alternatives);
3425 }
3426 tree.type = result = t;
3427 }
3429 public void visitTypeParameter(JCTypeParameter tree) {
3430 TypeVar a = (TypeVar)tree.type;
3431 Set<Type> boundSet = new HashSet<Type>();
3432 if (a.bound.isErroneous())
3433 return;
3434 List<Type> bs = types.getBounds(a);
3435 if (tree.bounds.nonEmpty()) {
3436 // accept class or interface or typevar as first bound.
3437 Type b = checkBase(bs.head, tree.bounds.head, env, false, false, false);
3438 boundSet.add(types.erasure(b));
3439 if (b.isErroneous()) {
3440 a.bound = b;
3441 }
3442 else if (b.tag == TYPEVAR) {
3443 // if first bound was a typevar, do not accept further bounds.
3444 if (tree.bounds.tail.nonEmpty()) {
3445 log.error(tree.bounds.tail.head.pos(),
3446 "type.var.may.not.be.followed.by.other.bounds");
3447 tree.bounds = List.of(tree.bounds.head);
3448 a.bound = bs.head;
3449 }
3450 } else {
3451 // if first bound was a class or interface, accept only interfaces
3452 // as further bounds.
3453 for (JCExpression bound : tree.bounds.tail) {
3454 bs = bs.tail;
3455 Type i = checkBase(bs.head, bound, env, false, true, false);
3456 if (i.isErroneous())
3457 a.bound = i;
3458 else if (i.tag == CLASS)
3459 chk.checkNotRepeated(bound.pos(), types.erasure(i), boundSet);
3460 }
3461 }
3462 }
3463 bs = types.getBounds(a);
3465 // in case of multiple bounds ...
3466 if (bs.length() > 1) {
3467 // ... the variable's bound is a class type flagged COMPOUND
3468 // (see comment for TypeVar.bound).
3469 // In this case, generate a class tree that represents the
3470 // bound class, ...
3471 JCExpression extending;
3472 List<JCExpression> implementing;
3473 if ((bs.head.tsym.flags() & INTERFACE) == 0) {
3474 extending = tree.bounds.head;
3475 implementing = tree.bounds.tail;
3476 } else {
3477 extending = null;
3478 implementing = tree.bounds;
3479 }
3480 JCClassDecl cd = make.at(tree.pos).ClassDef(
3481 make.Modifiers(PUBLIC | ABSTRACT),
3482 tree.name, List.<JCTypeParameter>nil(),
3483 extending, implementing, List.<JCTree>nil());
3485 ClassSymbol c = (ClassSymbol)a.getUpperBound().tsym;
3486 Assert.check((c.flags() & COMPOUND) != 0);
3487 cd.sym = c;
3488 c.sourcefile = env.toplevel.sourcefile;
3490 // ... and attribute the bound class
3491 c.flags_field |= UNATTRIBUTED;
3492 Env<AttrContext> cenv = enter.classEnv(cd, env);
3493 enter.typeEnvs.put(c, cenv);
3494 }
3495 }
3498 public void visitWildcard(JCWildcard tree) {
3499 //- System.err.println("visitWildcard("+tree+");");//DEBUG
3500 Type type = (tree.kind.kind == BoundKind.UNBOUND)
3501 ? syms.objectType
3502 : attribType(tree.inner, env);
3503 result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
3504 tree.kind.kind,
3505 syms.boundClass),
3506 TYP, resultInfo);
3507 }
3509 public void visitAnnotation(JCAnnotation tree) {
3510 log.error(tree.pos(), "annotation.not.valid.for.type", pt());
3511 result = tree.type = syms.errType;
3512 }
3514 public void visitErroneous(JCErroneous tree) {
3515 if (tree.errs != null)
3516 for (JCTree err : tree.errs)
3517 attribTree(err, env, new ResultInfo(ERR, pt()));
3518 result = tree.type = syms.errType;
3519 }
3521 /** Default visitor method for all other trees.
3522 */
3523 public void visitTree(JCTree tree) {
3524 throw new AssertionError();
3525 }
3527 /**
3528 * Attribute an env for either a top level tree or class declaration.
3529 */
3530 public void attrib(Env<AttrContext> env) {
3531 if (env.tree.hasTag(TOPLEVEL))
3532 attribTopLevel(env);
3533 else
3534 attribClass(env.tree.pos(), env.enclClass.sym);
3535 }
3537 /**
3538 * Attribute a top level tree. These trees are encountered when the
3539 * package declaration has annotations.
3540 */
3541 public void attribTopLevel(Env<AttrContext> env) {
3542 JCCompilationUnit toplevel = env.toplevel;
3543 try {
3544 annotate.flush();
3545 chk.validateAnnotations(toplevel.packageAnnotations, toplevel.packge);
3546 } catch (CompletionFailure ex) {
3547 chk.completionError(toplevel.pos(), ex);
3548 }
3549 }
3551 /** Main method: attribute class definition associated with given class symbol.
3552 * reporting completion failures at the given position.
3553 * @param pos The source position at which completion errors are to be
3554 * reported.
3555 * @param c The class symbol whose definition will be attributed.
3556 */
3557 public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
3558 try {
3559 annotate.flush();
3560 attribClass(c);
3561 } catch (CompletionFailure ex) {
3562 chk.completionError(pos, ex);
3563 }
3564 }
3566 /** Attribute class definition associated with given class symbol.
3567 * @param c The class symbol whose definition will be attributed.
3568 */
3569 void attribClass(ClassSymbol c) throws CompletionFailure {
3570 if (c.type.tag == ERROR) return;
3572 // Check for cycles in the inheritance graph, which can arise from
3573 // ill-formed class files.
3574 chk.checkNonCyclic(null, c.type);
3576 Type st = types.supertype(c.type);
3577 if ((c.flags_field & Flags.COMPOUND) == 0) {
3578 // First, attribute superclass.
3579 if (st.tag == CLASS)
3580 attribClass((ClassSymbol)st.tsym);
3582 // Next attribute owner, if it is a class.
3583 if (c.owner.kind == TYP && c.owner.type.tag == CLASS)
3584 attribClass((ClassSymbol)c.owner);
3585 }
3587 // The previous operations might have attributed the current class
3588 // if there was a cycle. So we test first whether the class is still
3589 // UNATTRIBUTED.
3590 if ((c.flags_field & UNATTRIBUTED) != 0) {
3591 c.flags_field &= ~UNATTRIBUTED;
3593 // Get environment current at the point of class definition.
3594 Env<AttrContext> env = enter.typeEnvs.get(c);
3596 // The info.lint field in the envs stored in enter.typeEnvs is deliberately uninitialized,
3597 // because the annotations were not available at the time the env was created. Therefore,
3598 // we look up the environment chain for the first enclosing environment for which the
3599 // lint value is set. Typically, this is the parent env, but might be further if there
3600 // are any envs created as a result of TypeParameter nodes.
3601 Env<AttrContext> lintEnv = env;
3602 while (lintEnv.info.lint == null)
3603 lintEnv = lintEnv.next;
3605 // Having found the enclosing lint value, we can initialize the lint value for this class
3606 env.info.lint = lintEnv.info.lint.augment(c.annotations, c.flags());
3608 Lint prevLint = chk.setLint(env.info.lint);
3609 JavaFileObject prev = log.useSource(c.sourcefile);
3610 ResultInfo prevReturnRes = env.info.returnResult;
3612 try {
3613 env.info.returnResult = null;
3614 // java.lang.Enum may not be subclassed by a non-enum
3615 if (st.tsym == syms.enumSym &&
3616 ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
3617 log.error(env.tree.pos(), "enum.no.subclassing");
3619 // Enums may not be extended by source-level classes
3620 if (st.tsym != null &&
3621 ((st.tsym.flags_field & Flags.ENUM) != 0) &&
3622 ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0) &&
3623 !target.compilerBootstrap(c)) {
3624 log.error(env.tree.pos(), "enum.types.not.extensible");
3625 }
3626 attribClassBody(env, c);
3628 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
3629 } finally {
3630 env.info.returnResult = prevReturnRes;
3631 log.useSource(prev);
3632 chk.setLint(prevLint);
3633 }
3635 }
3636 }
3638 public void visitImport(JCImport tree) {
3639 // nothing to do
3640 }
3642 /** Finish the attribution of a class. */
3643 private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
3644 JCClassDecl tree = (JCClassDecl)env.tree;
3645 Assert.check(c == tree.sym);
3647 // Validate annotations
3648 chk.validateAnnotations(tree.mods.annotations, c);
3650 // Validate type parameters, supertype and interfaces.
3651 attribBounds(tree.typarams);
3652 if (!c.isAnonymous()) {
3653 //already checked if anonymous
3654 chk.validate(tree.typarams, env);
3655 chk.validate(tree.extending, env);
3656 chk.validate(tree.implementing, env);
3657 }
3659 // If this is a non-abstract class, check that it has no abstract
3660 // methods or unimplemented methods of an implemented interface.
3661 if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
3662 if (!relax)
3663 chk.checkAllDefined(tree.pos(), c);
3664 }
3666 if ((c.flags() & ANNOTATION) != 0) {
3667 if (tree.implementing.nonEmpty())
3668 log.error(tree.implementing.head.pos(),
3669 "cant.extend.intf.annotation");
3670 if (tree.typarams.nonEmpty())
3671 log.error(tree.typarams.head.pos(),
3672 "intf.annotation.cant.have.type.params");
3674 // If this annotation has a @ContainedBy, validate
3675 Attribute.Compound containedBy = c.attribute(syms.containedByType.tsym);
3676 if (containedBy != null) {
3677 // get diagnositc position for error reporting
3678 DiagnosticPosition cbPos = getDiagnosticPosition(tree, containedBy.type);
3679 Assert.checkNonNull(cbPos);
3681 chk.validateContainedBy(c, containedBy, cbPos);
3682 }
3684 // If this annotation has a @ContainerFor, validate
3685 Attribute.Compound containerFor = c.attribute(syms.containerForType.tsym);
3686 if (containerFor != null) {
3687 // get diagnositc position for error reporting
3688 DiagnosticPosition cfPos = getDiagnosticPosition(tree, containerFor.type);
3689 Assert.checkNonNull(cfPos);
3691 chk.validateContainerFor(c, containerFor, cfPos);
3692 }
3693 } else {
3694 // Check that all extended classes and interfaces
3695 // are compatible (i.e. no two define methods with same arguments
3696 // yet different return types). (JLS 8.4.6.3)
3697 chk.checkCompatibleSupertypes(tree.pos(), c.type);
3698 }
3700 // Check that class does not import the same parameterized interface
3701 // with two different argument lists.
3702 chk.checkClassBounds(tree.pos(), c.type);
3704 tree.type = c.type;
3706 for (List<JCTypeParameter> l = tree.typarams;
3707 l.nonEmpty(); l = l.tail) {
3708 Assert.checkNonNull(env.info.scope.lookup(l.head.name).scope);
3709 }
3711 // Check that a generic class doesn't extend Throwable
3712 if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
3713 log.error(tree.extending.pos(), "generic.throwable");
3715 // Check that all methods which implement some
3716 // method conform to the method they implement.
3717 chk.checkImplementations(tree);
3719 //check that a resource implementing AutoCloseable cannot throw InterruptedException
3720 checkAutoCloseable(tree.pos(), env, c.type);
3722 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
3723 // Attribute declaration
3724 attribStat(l.head, env);
3725 // Check that declarations in inner classes are not static (JLS 8.1.2)
3726 // Make an exception for static constants.
3727 if (c.owner.kind != PCK &&
3728 ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
3729 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
3730 Symbol sym = null;
3731 if (l.head.hasTag(VARDEF)) sym = ((JCVariableDecl) l.head).sym;
3732 if (sym == null ||
3733 sym.kind != VAR ||
3734 ((VarSymbol) sym).getConstValue() == null)
3735 log.error(l.head.pos(), "icls.cant.have.static.decl", c);
3736 }
3737 }
3739 // Check for cycles among non-initial constructors.
3740 chk.checkCyclicConstructors(tree);
3742 // Check for cycles among annotation elements.
3743 chk.checkNonCyclicElements(tree);
3745 // Check for proper use of serialVersionUID
3746 if (env.info.lint.isEnabled(LintCategory.SERIAL) &&
3747 isSerializable(c) &&
3748 (c.flags() & Flags.ENUM) == 0 &&
3749 (c.flags() & ABSTRACT) == 0) {
3750 checkSerialVersionUID(tree, c);
3751 }
3752 }
3753 // where
3754 /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
3755 private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
3756 for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
3757 if (types.isSameType(al.head.annotationType.type, t))
3758 return al.head.pos();
3759 }
3761 return null;
3762 }
3764 /** check if a class is a subtype of Serializable, if that is available. */
3765 private boolean isSerializable(ClassSymbol c) {
3766 try {
3767 syms.serializableType.complete();
3768 }
3769 catch (CompletionFailure e) {
3770 return false;
3771 }
3772 return types.isSubtype(c.type, syms.serializableType);
3773 }
3775 /** Check that an appropriate serialVersionUID member is defined. */
3776 private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
3778 // check for presence of serialVersionUID
3779 Scope.Entry e = c.members().lookup(names.serialVersionUID);
3780 while (e.scope != null && e.sym.kind != VAR) e = e.next();
3781 if (e.scope == null) {
3782 log.warning(LintCategory.SERIAL,
3783 tree.pos(), "missing.SVUID", c);
3784 return;
3785 }
3787 // check that it is static final
3788 VarSymbol svuid = (VarSymbol)e.sym;
3789 if ((svuid.flags() & (STATIC | FINAL)) !=
3790 (STATIC | FINAL))
3791 log.warning(LintCategory.SERIAL,
3792 TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c);
3794 // check that it is long
3795 else if (svuid.type.tag != TypeTags.LONG)
3796 log.warning(LintCategory.SERIAL,
3797 TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c);
3799 // check constant
3800 else if (svuid.getConstValue() == null)
3801 log.warning(LintCategory.SERIAL,
3802 TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c);
3803 }
3805 private Type capture(Type type) {
3806 return types.capture(type);
3807 }
3809 // <editor-fold desc="post-attribution visitor">
3811 /**
3812 * Handle missing types/symbols in an AST. This routine is useful when
3813 * the compiler has encountered some errors (which might have ended up
3814 * terminating attribution abruptly); if the compiler is used in fail-over
3815 * mode (e.g. by an IDE) and the AST contains semantic errors, this routine
3816 * prevents NPE to be progagated during subsequent compilation steps.
3817 */
3818 public void postAttr(JCTree tree) {
3819 new PostAttrAnalyzer().scan(tree);
3820 }
3822 class PostAttrAnalyzer extends TreeScanner {
3824 private void initTypeIfNeeded(JCTree that) {
3825 if (that.type == null) {
3826 that.type = syms.unknownType;
3827 }
3828 }
3830 @Override
3831 public void scan(JCTree tree) {
3832 if (tree == null) return;
3833 if (tree instanceof JCExpression) {
3834 initTypeIfNeeded(tree);
3835 }
3836 super.scan(tree);
3837 }
3839 @Override
3840 public void visitIdent(JCIdent that) {
3841 if (that.sym == null) {
3842 that.sym = syms.unknownSymbol;
3843 }
3844 }
3846 @Override
3847 public void visitSelect(JCFieldAccess that) {
3848 if (that.sym == null) {
3849 that.sym = syms.unknownSymbol;
3850 }
3851 super.visitSelect(that);
3852 }
3854 @Override
3855 public void visitClassDef(JCClassDecl that) {
3856 initTypeIfNeeded(that);
3857 if (that.sym == null) {
3858 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol);
3859 }
3860 super.visitClassDef(that);
3861 }
3863 @Override
3864 public void visitMethodDef(JCMethodDecl that) {
3865 initTypeIfNeeded(that);
3866 if (that.sym == null) {
3867 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol);
3868 }
3869 super.visitMethodDef(that);
3870 }
3872 @Override
3873 public void visitVarDef(JCVariableDecl that) {
3874 initTypeIfNeeded(that);
3875 if (that.sym == null) {
3876 that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol);
3877 that.sym.adr = 0;
3878 }
3879 super.visitVarDef(that);
3880 }
3882 @Override
3883 public void visitNewClass(JCNewClass that) {
3884 if (that.constructor == null) {
3885 that.constructor = new MethodSymbol(0, names.init, syms.unknownType, syms.noSymbol);
3886 }
3887 if (that.constructorType == null) {
3888 that.constructorType = syms.unknownType;
3889 }
3890 super.visitNewClass(that);
3891 }
3893 @Override
3894 public void visitAssignop(JCAssignOp that) {
3895 if (that.operator == null)
3896 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
3897 super.visitAssignop(that);
3898 }
3900 @Override
3901 public void visitBinary(JCBinary that) {
3902 if (that.operator == null)
3903 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
3904 super.visitBinary(that);
3905 }
3907 @Override
3908 public void visitUnary(JCUnary that) {
3909 if (that.operator == null)
3910 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
3911 super.visitUnary(that);
3912 }
3914 @Override
3915 public void visitReference(JCMemberReference that) {
3916 super.visitReference(that);
3917 if (that.sym == null) {
3918 that.sym = new MethodSymbol(0, names.empty, syms.unknownType, syms.noSymbol);
3919 }
3920 }
3921 }
3922 // </editor-fold>
3923 }