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