Mon, 14 Oct 2013 22:11:09 +0200
8014016: javac is too late detecting invalid annotation usage
Summary: Adding new queue to Annotate for validation tasks, performing annotation validation during enter
Reviewed-by: jjg, emc, jfranck
1 /*
2 * Copyright (c) 1999, 2013, 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.*;
30 import javax.lang.model.element.ElementKind;
31 import javax.lang.model.type.TypeKind;
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.FreeTypeListener;
47 import com.sun.tools.javac.jvm.*;
48 import com.sun.tools.javac.tree.*;
49 import com.sun.tools.javac.tree.JCTree.*;
50 import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*;
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.code.TypeTag.ARRAY;
62 import static com.sun.tools.javac.tree.JCTree.Tag.*;
64 /** This is the main context-dependent analysis phase in GJC. It
65 * encompasses name resolution, type checking and constant folding as
66 * subtasks. Some subtasks involve auxiliary classes.
67 * @see Check
68 * @see Resolve
69 * @see ConstFold
70 * @see Infer
71 *
72 * <p><b>This is NOT part of any supported API.
73 * If you write code that depends on this, you do so at your own risk.
74 * This code and its internal interfaces are subject to change or
75 * deletion without notice.</b>
76 */
77 public class Attr extends JCTree.Visitor {
78 protected static final Context.Key<Attr> attrKey =
79 new Context.Key<Attr>();
81 final Names names;
82 final Log log;
83 final Symtab syms;
84 final Resolve rs;
85 final Infer infer;
86 final DeferredAttr deferredAttr;
87 final Check chk;
88 final Flow flow;
89 final MemberEnter memberEnter;
90 final TreeMaker make;
91 final ConstFold cfolder;
92 final Enter enter;
93 final Target target;
94 final Types types;
95 final JCDiagnostic.Factory diags;
96 final Annotate annotate;
97 final TypeAnnotations typeAnnotations;
98 final DeferredLintHandler deferredLintHandler;
100 public static Attr instance(Context context) {
101 Attr instance = context.get(attrKey);
102 if (instance == null)
103 instance = new Attr(context);
104 return instance;
105 }
107 protected Attr(Context context) {
108 context.put(attrKey, this);
110 names = Names.instance(context);
111 log = Log.instance(context);
112 syms = Symtab.instance(context);
113 rs = Resolve.instance(context);
114 chk = Check.instance(context);
115 flow = Flow.instance(context);
116 memberEnter = MemberEnter.instance(context);
117 make = TreeMaker.instance(context);
118 enter = Enter.instance(context);
119 infer = Infer.instance(context);
120 deferredAttr = DeferredAttr.instance(context);
121 cfolder = ConstFold.instance(context);
122 target = Target.instance(context);
123 types = Types.instance(context);
124 diags = JCDiagnostic.Factory.instance(context);
125 annotate = Annotate.instance(context);
126 typeAnnotations = TypeAnnotations.instance(context);
127 deferredLintHandler = DeferredLintHandler.instance(context);
129 Options options = Options.instance(context);
131 Source source = Source.instance(context);
132 allowGenerics = source.allowGenerics();
133 allowVarargs = source.allowVarargs();
134 allowEnums = source.allowEnums();
135 allowBoxing = source.allowBoxing();
136 allowCovariantReturns = source.allowCovariantReturns();
137 allowAnonOuterThis = source.allowAnonOuterThis();
138 allowStringsInSwitch = source.allowStringsInSwitch();
139 allowPoly = source.allowPoly();
140 allowTypeAnnos = source.allowTypeAnnotations();
141 allowLambda = source.allowLambda();
142 allowDefaultMethods = source.allowDefaultMethods();
143 sourceName = source.name;
144 relax = (options.isSet("-retrofit") ||
145 options.isSet("-relax"));
146 findDiamonds = options.get("findDiamond") != null &&
147 source.allowDiamond();
148 useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
149 identifyLambdaCandidate = options.getBoolean("identifyLambdaCandidate", false);
151 statInfo = new ResultInfo(NIL, Type.noType);
152 varInfo = new ResultInfo(VAR, Type.noType);
153 unknownExprInfo = new ResultInfo(VAL, Type.noType);
154 unknownAnyPolyInfo = new ResultInfo(VAL, Infer.anyPoly);
155 unknownTypeInfo = new ResultInfo(TYP, Type.noType);
156 unknownTypeExprInfo = new ResultInfo(Kinds.TYP | Kinds.VAL, Type.noType);
157 recoveryInfo = new RecoveryInfo(deferredAttr.emptyDeferredAttrContext);
158 }
160 /** Switch: relax some constraints for retrofit mode.
161 */
162 boolean relax;
164 /** Switch: support target-typing inference
165 */
166 boolean allowPoly;
168 /** Switch: support type annotations.
169 */
170 boolean allowTypeAnnos;
172 /** Switch: support generics?
173 */
174 boolean allowGenerics;
176 /** Switch: allow variable-arity methods.
177 */
178 boolean allowVarargs;
180 /** Switch: support enums?
181 */
182 boolean allowEnums;
184 /** Switch: support boxing and unboxing?
185 */
186 boolean allowBoxing;
188 /** Switch: support covariant result types?
189 */
190 boolean allowCovariantReturns;
192 /** Switch: support lambda expressions ?
193 */
194 boolean allowLambda;
196 /** Switch: support default methods ?
197 */
198 boolean allowDefaultMethods;
200 /** Switch: allow references to surrounding object from anonymous
201 * objects during constructor call?
202 */
203 boolean allowAnonOuterThis;
205 /** Switch: generates a warning if diamond can be safely applied
206 * to a given new expression
207 */
208 boolean findDiamonds;
210 /**
211 * Internally enables/disables diamond finder feature
212 */
213 static final boolean allowDiamondFinder = true;
215 /**
216 * Switch: warn about use of variable before declaration?
217 * RFE: 6425594
218 */
219 boolean useBeforeDeclarationWarning;
221 /**
222 * Switch: generate warnings whenever an anonymous inner class that is convertible
223 * to a lambda expression is found
224 */
225 boolean identifyLambdaCandidate;
227 /**
228 * Switch: allow strings in switch?
229 */
230 boolean allowStringsInSwitch;
232 /**
233 * Switch: name of source level; used for error reporting.
234 */
235 String sourceName;
237 /** Check kind and type of given tree against protokind and prototype.
238 * If check succeeds, store type in tree and return it.
239 * If check fails, store errType in tree and return it.
240 * No checks are performed if the prototype is a method type.
241 * It is not necessary in this case since we know that kind and type
242 * are correct.
243 *
244 * @param tree The tree whose kind and type is checked
245 * @param ownkind The computed kind of the tree
246 * @param resultInfo The expected result of the tree
247 */
248 Type check(final JCTree tree, final Type found, final int ownkind, final ResultInfo resultInfo) {
249 InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
250 Type owntype = found;
251 if (!owntype.hasTag(ERROR) && !resultInfo.pt.hasTag(METHOD) && !resultInfo.pt.hasTag(FORALL)) {
252 if (allowPoly && inferenceContext.free(found)) {
253 inferenceContext.addFreeTypeListener(List.of(found, resultInfo.pt), new FreeTypeListener() {
254 @Override
255 public void typesInferred(InferenceContext inferenceContext) {
256 ResultInfo pendingResult =
257 resultInfo.dup(inferenceContext.asInstType(resultInfo.pt));
258 check(tree, inferenceContext.asInstType(found), ownkind, pendingResult);
259 }
260 });
261 return tree.type = resultInfo.pt;
262 } else {
263 if ((ownkind & ~resultInfo.pkind) == 0) {
264 owntype = resultInfo.check(tree, owntype);
265 } else {
266 log.error(tree.pos(), "unexpected.type",
267 kindNames(resultInfo.pkind),
268 kindName(ownkind));
269 owntype = types.createErrorType(owntype);
270 }
271 }
272 }
273 tree.type = owntype;
274 return owntype;
275 }
277 /** Is given blank final variable assignable, i.e. in a scope where it
278 * may be assigned to even though it is final?
279 * @param v The blank final variable.
280 * @param env The current environment.
281 */
282 boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
283 Symbol owner = owner(env);
284 // owner refers to the innermost variable, method or
285 // initializer block declaration at this point.
286 return
287 v.owner == owner
288 ||
289 ((owner.name == names.init || // i.e. we are in a constructor
290 owner.kind == VAR || // i.e. we are in a variable initializer
291 (owner.flags() & BLOCK) != 0) // i.e. we are in an initializer block
292 &&
293 v.owner == owner.owner
294 &&
295 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
296 }
298 /**
299 * Return the innermost enclosing owner symbol in a given attribution context
300 */
301 Symbol owner(Env<AttrContext> env) {
302 while (true) {
303 switch (env.tree.getTag()) {
304 case VARDEF:
305 //a field can be owner
306 VarSymbol vsym = ((JCVariableDecl)env.tree).sym;
307 if (vsym.owner.kind == TYP) {
308 return vsym;
309 }
310 break;
311 case METHODDEF:
312 //method def is always an owner
313 return ((JCMethodDecl)env.tree).sym;
314 case CLASSDEF:
315 //class def is always an owner
316 return ((JCClassDecl)env.tree).sym;
317 case LAMBDA:
318 //a lambda is an owner - return a fresh synthetic method symbol
319 return new MethodSymbol(0, names.empty, null, syms.methodClass);
320 case BLOCK:
321 //static/instance init blocks are owner
322 Symbol blockSym = env.info.scope.owner;
323 if ((blockSym.flags() & BLOCK) != 0) {
324 return blockSym;
325 }
326 break;
327 case TOPLEVEL:
328 //toplevel is always an owner (for pkge decls)
329 return env.info.scope.owner;
330 }
331 Assert.checkNonNull(env.next);
332 env = env.next;
333 }
334 }
336 /** Check that variable can be assigned to.
337 * @param pos The current source code position.
338 * @param v The assigned varaible
339 * @param base If the variable is referred to in a Select, the part
340 * to the left of the `.', null otherwise.
341 * @param env The current environment.
342 */
343 void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
344 if ((v.flags() & FINAL) != 0 &&
345 ((v.flags() & HASINIT) != 0
346 ||
347 !((base == null ||
348 (base.hasTag(IDENT) && TreeInfo.name(base) == names._this)) &&
349 isAssignableAsBlankFinal(v, env)))) {
350 if (v.isResourceVariable()) { //TWR resource
351 log.error(pos, "try.resource.may.not.be.assigned", v);
352 } else {
353 log.error(pos, "cant.assign.val.to.final.var", v);
354 }
355 }
356 }
358 /** Does tree represent a static reference to an identifier?
359 * It is assumed that tree is either a SELECT or an IDENT.
360 * We have to weed out selects from non-type names here.
361 * @param tree The candidate tree.
362 */
363 boolean isStaticReference(JCTree tree) {
364 if (tree.hasTag(SELECT)) {
365 Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
366 if (lsym == null || lsym.kind != TYP) {
367 return false;
368 }
369 }
370 return true;
371 }
373 /** Is this symbol a type?
374 */
375 static boolean isType(Symbol sym) {
376 return sym != null && sym.kind == TYP;
377 }
379 /** The current `this' symbol.
380 * @param env The current environment.
381 */
382 Symbol thisSym(DiagnosticPosition pos, Env<AttrContext> env) {
383 return rs.resolveSelf(pos, env, env.enclClass.sym, names._this);
384 }
386 /** Attribute a parsed identifier.
387 * @param tree Parsed identifier name
388 * @param topLevel The toplevel to use
389 */
390 public Symbol attribIdent(JCTree tree, JCCompilationUnit topLevel) {
391 Env<AttrContext> localEnv = enter.topLevelEnv(topLevel);
392 localEnv.enclClass = make.ClassDef(make.Modifiers(0),
393 syms.errSymbol.name,
394 null, null, null, null);
395 localEnv.enclClass.sym = syms.errSymbol;
396 return tree.accept(identAttributer, localEnv);
397 }
398 // where
399 private TreeVisitor<Symbol,Env<AttrContext>> identAttributer = new IdentAttributer();
400 private class IdentAttributer extends SimpleTreeVisitor<Symbol,Env<AttrContext>> {
401 @Override
402 public Symbol visitMemberSelect(MemberSelectTree node, Env<AttrContext> env) {
403 Symbol site = visit(node.getExpression(), env);
404 if (site.kind == ERR || site.kind == ABSENT_TYP)
405 return site;
406 Name name = (Name)node.getIdentifier();
407 if (site.kind == PCK) {
408 env.toplevel.packge = (PackageSymbol)site;
409 return rs.findIdentInPackage(env, (TypeSymbol)site, name, TYP | PCK);
410 } else {
411 env.enclClass.sym = (ClassSymbol)site;
412 return rs.findMemberType(env, site.asType(), name, (TypeSymbol)site);
413 }
414 }
416 @Override
417 public Symbol visitIdentifier(IdentifierTree node, Env<AttrContext> env) {
418 return rs.findIdent(env, (Name)node.getName(), TYP | PCK);
419 }
420 }
422 public Type coerce(Type etype, Type ttype) {
423 return cfolder.coerce(etype, ttype);
424 }
426 public Type attribType(JCTree node, TypeSymbol sym) {
427 Env<AttrContext> env = enter.typeEnvs.get(sym);
428 Env<AttrContext> localEnv = env.dup(node, env.info.dup());
429 return attribTree(node, localEnv, unknownTypeInfo);
430 }
432 public Type attribImportQualifier(JCImport tree, Env<AttrContext> env) {
433 // Attribute qualifying package or class.
434 JCFieldAccess s = (JCFieldAccess)tree.qualid;
435 return attribTree(s.selected,
436 env,
437 new ResultInfo(tree.staticImport ? TYP : (TYP | PCK),
438 Type.noType));
439 }
441 public Env<AttrContext> attribExprToTree(JCTree expr, Env<AttrContext> env, JCTree tree) {
442 breakTree = tree;
443 JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
444 try {
445 attribExpr(expr, env);
446 } catch (BreakAttr b) {
447 return b.env;
448 } catch (AssertionError ae) {
449 if (ae.getCause() instanceof BreakAttr) {
450 return ((BreakAttr)(ae.getCause())).env;
451 } else {
452 throw ae;
453 }
454 } finally {
455 breakTree = null;
456 log.useSource(prev);
457 }
458 return env;
459 }
461 public Env<AttrContext> attribStatToTree(JCTree stmt, Env<AttrContext> env, JCTree tree) {
462 breakTree = tree;
463 JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
464 try {
465 attribStat(stmt, env);
466 } catch (BreakAttr b) {
467 return b.env;
468 } catch (AssertionError ae) {
469 if (ae.getCause() instanceof BreakAttr) {
470 return ((BreakAttr)(ae.getCause())).env;
471 } else {
472 throw ae;
473 }
474 } finally {
475 breakTree = null;
476 log.useSource(prev);
477 }
478 return env;
479 }
481 private JCTree breakTree = null;
483 private static class BreakAttr extends RuntimeException {
484 static final long serialVersionUID = -6924771130405446405L;
485 private Env<AttrContext> env;
486 private BreakAttr(Env<AttrContext> env) {
487 this.env = env;
488 }
489 }
491 class ResultInfo {
492 final int pkind;
493 final Type pt;
494 final CheckContext checkContext;
496 ResultInfo(int pkind, Type pt) {
497 this(pkind, pt, chk.basicHandler);
498 }
500 protected ResultInfo(int pkind, Type pt, CheckContext checkContext) {
501 this.pkind = pkind;
502 this.pt = pt;
503 this.checkContext = checkContext;
504 }
506 protected Type check(final DiagnosticPosition pos, final Type found) {
507 return chk.checkType(pos, found, pt, checkContext);
508 }
510 protected ResultInfo dup(Type newPt) {
511 return new ResultInfo(pkind, newPt, checkContext);
512 }
514 protected ResultInfo dup(CheckContext newContext) {
515 return new ResultInfo(pkind, pt, newContext);
516 }
517 }
519 class RecoveryInfo extends ResultInfo {
521 public RecoveryInfo(final DeferredAttr.DeferredAttrContext deferredAttrContext) {
522 super(Kinds.VAL, Type.recoveryType, new Check.NestedCheckContext(chk.basicHandler) {
523 @Override
524 public DeferredAttr.DeferredAttrContext deferredAttrContext() {
525 return deferredAttrContext;
526 }
527 @Override
528 public boolean compatible(Type found, Type req, Warner warn) {
529 return true;
530 }
531 @Override
532 public void report(DiagnosticPosition pos, JCDiagnostic details) {
533 chk.basicHandler.report(pos, details);
534 }
535 });
536 }
537 }
539 final ResultInfo statInfo;
540 final ResultInfo varInfo;
541 final ResultInfo unknownAnyPolyInfo;
542 final ResultInfo unknownExprInfo;
543 final ResultInfo unknownTypeInfo;
544 final ResultInfo unknownTypeExprInfo;
545 final ResultInfo recoveryInfo;
547 Type pt() {
548 return resultInfo.pt;
549 }
551 int pkind() {
552 return resultInfo.pkind;
553 }
555 /* ************************************************************************
556 * Visitor methods
557 *************************************************************************/
559 /** Visitor argument: the current environment.
560 */
561 Env<AttrContext> env;
563 /** Visitor argument: the currently expected attribution result.
564 */
565 ResultInfo resultInfo;
567 /** Visitor result: the computed type.
568 */
569 Type result;
571 /** Visitor method: attribute a tree, catching any completion failure
572 * exceptions. Return the tree's type.
573 *
574 * @param tree The tree to be visited.
575 * @param env The environment visitor argument.
576 * @param resultInfo The result info visitor argument.
577 */
578 Type attribTree(JCTree tree, Env<AttrContext> env, ResultInfo resultInfo) {
579 Env<AttrContext> prevEnv = this.env;
580 ResultInfo prevResult = this.resultInfo;
581 try {
582 this.env = env;
583 this.resultInfo = resultInfo;
584 tree.accept(this);
585 if (tree == breakTree &&
586 resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
587 throw new BreakAttr(copyEnv(env));
588 }
589 return result;
590 } catch (CompletionFailure ex) {
591 tree.type = syms.errType;
592 return chk.completionError(tree.pos(), ex);
593 } finally {
594 this.env = prevEnv;
595 this.resultInfo = prevResult;
596 }
597 }
599 Env<AttrContext> copyEnv(Env<AttrContext> env) {
600 Env<AttrContext> newEnv =
601 env.dup(env.tree, env.info.dup(copyScope(env.info.scope)));
602 if (newEnv.outer != null) {
603 newEnv.outer = copyEnv(newEnv.outer);
604 }
605 return newEnv;
606 }
608 Scope copyScope(Scope sc) {
609 Scope newScope = new Scope(sc.owner);
610 List<Symbol> elemsList = List.nil();
611 while (sc != null) {
612 for (Scope.Entry e = sc.elems ; e != null ; e = e.sibling) {
613 elemsList = elemsList.prepend(e.sym);
614 }
615 sc = sc.next;
616 }
617 for (Symbol s : elemsList) {
618 newScope.enter(s);
619 }
620 return newScope;
621 }
623 /** Derived visitor method: attribute an expression tree.
624 */
625 public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) {
626 return attribTree(tree, env, new ResultInfo(VAL, !pt.hasTag(ERROR) ? pt : Type.noType));
627 }
629 /** Derived visitor method: attribute an expression tree with
630 * no constraints on the computed type.
631 */
632 public Type attribExpr(JCTree tree, Env<AttrContext> env) {
633 return attribTree(tree, env, unknownExprInfo);
634 }
636 /** Derived visitor method: attribute a type tree.
637 */
638 public Type attribType(JCTree tree, Env<AttrContext> env) {
639 Type result = attribType(tree, env, Type.noType);
640 return result;
641 }
643 /** Derived visitor method: attribute a type tree.
644 */
645 Type attribType(JCTree tree, Env<AttrContext> env, Type pt) {
646 Type result = attribTree(tree, env, new ResultInfo(TYP, pt));
647 return result;
648 }
650 /** Derived visitor method: attribute a statement or definition tree.
651 */
652 public Type attribStat(JCTree tree, Env<AttrContext> env) {
653 return attribTree(tree, env, statInfo);
654 }
656 /** Attribute a list of expressions, returning a list of types.
657 */
658 List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) {
659 ListBuffer<Type> ts = new ListBuffer<Type>();
660 for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
661 ts.append(attribExpr(l.head, env, pt));
662 return ts.toList();
663 }
665 /** Attribute a list of statements, returning nothing.
666 */
667 <T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) {
668 for (List<T> l = trees; l.nonEmpty(); l = l.tail)
669 attribStat(l.head, env);
670 }
672 /** Attribute the arguments in a method call, returning the method kind.
673 */
674 int attribArgs(List<JCExpression> trees, Env<AttrContext> env, ListBuffer<Type> argtypes) {
675 int kind = VAL;
676 for (JCExpression arg : trees) {
677 Type argtype;
678 if (allowPoly && deferredAttr.isDeferred(env, arg)) {
679 argtype = deferredAttr.new DeferredType(arg, env);
680 kind |= POLY;
681 } else {
682 argtype = chk.checkNonVoid(arg, attribTree(arg, env, unknownAnyPolyInfo));
683 }
684 argtypes.append(argtype);
685 }
686 return kind;
687 }
689 /** Attribute a type argument list, returning a list of types.
690 * Caller is responsible for calling checkRefTypes.
691 */
692 List<Type> attribAnyTypes(List<JCExpression> trees, Env<AttrContext> env) {
693 ListBuffer<Type> argtypes = new ListBuffer<Type>();
694 for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
695 argtypes.append(attribType(l.head, env));
696 return argtypes.toList();
697 }
699 /** Attribute a type argument list, returning a list of types.
700 * Check that all the types are references.
701 */
702 List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
703 List<Type> types = attribAnyTypes(trees, env);
704 return chk.checkRefTypes(trees, types);
705 }
707 /**
708 * Attribute type variables (of generic classes or methods).
709 * Compound types are attributed later in attribBounds.
710 * @param typarams the type variables to enter
711 * @param env the current environment
712 */
713 void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env) {
714 for (JCTypeParameter tvar : typarams) {
715 TypeVar a = (TypeVar)tvar.type;
716 a.tsym.flags_field |= UNATTRIBUTED;
717 a.bound = Type.noType;
718 if (!tvar.bounds.isEmpty()) {
719 List<Type> bounds = List.of(attribType(tvar.bounds.head, env));
720 for (JCExpression bound : tvar.bounds.tail)
721 bounds = bounds.prepend(attribType(bound, env));
722 types.setBounds(a, bounds.reverse());
723 } else {
724 // if no bounds are given, assume a single bound of
725 // java.lang.Object.
726 types.setBounds(a, List.of(syms.objectType));
727 }
728 a.tsym.flags_field &= ~UNATTRIBUTED;
729 }
730 for (JCTypeParameter tvar : typarams) {
731 chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
732 }
733 }
735 /**
736 * Attribute the type references in a list of annotations.
737 */
738 void attribAnnotationTypes(List<JCAnnotation> annotations,
739 Env<AttrContext> env) {
740 for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
741 JCAnnotation a = al.head;
742 attribType(a.annotationType, env);
743 }
744 }
746 /**
747 * Attribute a "lazy constant value".
748 * @param env The env for the const value
749 * @param initializer The initializer for the const value
750 * @param type The expected type, or null
751 * @see VarSymbol#setLazyConstValue
752 */
753 public Object attribLazyConstantValue(Env<AttrContext> env,
754 JCVariableDecl variable,
755 Type type) {
757 DiagnosticPosition prevLintPos
758 = deferredLintHandler.setPos(variable.pos());
760 try {
761 // Use null as symbol to not attach the type annotation to any symbol.
762 // The initializer will later also be visited and then we'll attach
763 // to the symbol.
764 // This prevents having multiple type annotations, just because of
765 // lazy constant value evaluation.
766 memberEnter.typeAnnotate(variable.init, env, null, variable.pos());
767 annotate.flush();
768 Type itype = attribExpr(variable.init, env, type);
769 if (itype.constValue() != null) {
770 return coerce(itype, type).constValue();
771 } else {
772 return null;
773 }
774 } finally {
775 deferredLintHandler.setPos(prevLintPos);
776 }
777 }
779 /** Attribute type reference in an `extends' or `implements' clause.
780 * Supertypes of anonymous inner classes are usually already attributed.
781 *
782 * @param tree The tree making up the type reference.
783 * @param env The environment current at the reference.
784 * @param classExpected true if only a class is expected here.
785 * @param interfaceExpected true if only an interface is expected here.
786 */
787 Type attribBase(JCTree tree,
788 Env<AttrContext> env,
789 boolean classExpected,
790 boolean interfaceExpected,
791 boolean checkExtensible) {
792 Type t = tree.type != null ?
793 tree.type :
794 attribType(tree, env);
795 return checkBase(t, tree, env, classExpected, interfaceExpected, false, checkExtensible);
796 }
797 Type checkBase(Type t,
798 JCTree tree,
799 Env<AttrContext> env,
800 boolean classExpected,
801 boolean interfacesOnlyExpected,
802 boolean interfacesOrArraysExpected,
803 boolean checkExtensible) {
804 if (t.isErroneous())
805 return t;
806 if (t.hasTag(TYPEVAR) && !classExpected &&
807 !interfacesOrArraysExpected && !interfacesOnlyExpected) {
808 // check that type variable is already visible
809 if (t.getUpperBound() == null) {
810 log.error(tree.pos(), "illegal.forward.ref");
811 return types.createErrorType(t);
812 }
813 } else if (classExpected) {
814 t = chk.checkClassType(tree.pos(), t, checkExtensible|!allowGenerics);
815 } else {
816 t = chk.checkClassOrArrayType(tree.pos(), t,
817 checkExtensible|!allowGenerics);
818 }
819 if (interfacesOnlyExpected && !t.tsym.isInterface()) {
820 log.error(tree.pos(), "intf.expected.here");
821 // return errType is necessary since otherwise there might
822 // be undetected cycles which cause attribution to loop
823 return types.createErrorType(t);
824 } else if (interfacesOrArraysExpected &&
825 !(t.tsym.isInterface() || t.getTag() == ARRAY)) {
826 log.error(tree.pos(), "intf.or.array.expected.here");
827 // return errType is necessary since otherwise there might
828 // be undetected cycles which cause attribution to loop
829 return types.createErrorType(t);
830 } else if (checkExtensible &&
831 classExpected &&
832 t.tsym.isInterface()) {
833 log.error(tree.pos(), "no.intf.expected.here");
834 return types.createErrorType(t);
835 }
836 if (checkExtensible &&
837 ((t.tsym.flags() & FINAL) != 0)) {
838 log.error(tree.pos(),
839 "cant.inherit.from.final", t.tsym);
840 }
841 chk.checkNonCyclic(tree.pos(), t);
842 return t;
843 }
844 //where
845 private Object asTypeParam(Type t) {
846 return (t.hasTag(TYPEVAR))
847 ? diags.fragment("type.parameter", t)
848 : t;
849 }
851 Type attribIdentAsEnumType(Env<AttrContext> env, JCIdent id) {
852 Assert.check((env.enclClass.sym.flags() & ENUM) != 0);
853 id.type = env.info.scope.owner.type;
854 id.sym = env.info.scope.owner;
855 return id.type;
856 }
858 public void visitClassDef(JCClassDecl tree) {
859 // Local classes have not been entered yet, so we need to do it now:
860 if ((env.info.scope.owner.kind & (VAR | MTH)) != 0)
861 enter.classEnter(tree, env);
863 ClassSymbol c = tree.sym;
864 if (c == null) {
865 // exit in case something drastic went wrong during enter.
866 result = null;
867 } else {
868 // make sure class has been completed:
869 c.complete();
871 // If this class appears as an anonymous class
872 // in a superclass constructor call where
873 // no explicit outer instance is given,
874 // disable implicit outer instance from being passed.
875 // (This would be an illegal access to "this before super").
876 if (env.info.isSelfCall &&
877 env.tree.hasTag(NEWCLASS) &&
878 ((JCNewClass) env.tree).encl == null)
879 {
880 c.flags_field |= NOOUTERTHIS;
881 }
882 attribClass(tree.pos(), c);
883 result = tree.type = c.type;
884 }
885 }
887 public void visitMethodDef(JCMethodDecl tree) {
888 MethodSymbol m = tree.sym;
889 boolean isDefaultMethod = (m.flags() & DEFAULT) != 0;
891 Lint lint = env.info.lint.augment(m);
892 Lint prevLint = chk.setLint(lint);
893 MethodSymbol prevMethod = chk.setMethod(m);
894 try {
895 deferredLintHandler.flush(tree.pos());
896 chk.checkDeprecatedAnnotation(tree.pos(), m);
899 // Create a new environment with local scope
900 // for attributing the method.
901 Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
902 localEnv.info.lint = lint;
904 attribStats(tree.typarams, localEnv);
906 // If we override any other methods, check that we do so properly.
907 // JLS ???
908 if (m.isStatic()) {
909 chk.checkHideClashes(tree.pos(), env.enclClass.type, m);
910 } else {
911 chk.checkOverrideClashes(tree.pos(), env.enclClass.type, m);
912 }
913 chk.checkOverride(tree, m);
915 if (isDefaultMethod && types.overridesObjectMethod(m.enclClass(), m)) {
916 log.error(tree, "default.overrides.object.member", m.name, Kinds.kindName(m.location()), m.location());
917 }
919 // Enter all type parameters into the local method scope.
920 for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
921 localEnv.info.scope.enterIfAbsent(l.head.type.tsym);
923 ClassSymbol owner = env.enclClass.sym;
924 if ((owner.flags() & ANNOTATION) != 0 &&
925 tree.params.nonEmpty())
926 log.error(tree.params.head.pos(),
927 "intf.annotation.members.cant.have.params");
929 // Attribute all value parameters.
930 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
931 attribStat(l.head, localEnv);
932 }
934 chk.checkVarargsMethodDecl(localEnv, tree);
936 // Check that type parameters are well-formed.
937 chk.validate(tree.typarams, localEnv);
939 // Check that result type is well-formed.
940 chk.validate(tree.restype, localEnv);
942 // Check that receiver type is well-formed.
943 if (tree.recvparam != null) {
944 // Use a new environment to check the receiver parameter.
945 // Otherwise I get "might not have been initialized" errors.
946 // Is there a better way?
947 Env<AttrContext> newEnv = memberEnter.methodEnv(tree, env);
948 attribType(tree.recvparam, newEnv);
949 chk.validate(tree.recvparam, newEnv);
950 }
952 // annotation method checks
953 if ((owner.flags() & ANNOTATION) != 0) {
954 // annotation method cannot have throws clause
955 if (tree.thrown.nonEmpty()) {
956 log.error(tree.thrown.head.pos(),
957 "throws.not.allowed.in.intf.annotation");
958 }
959 // annotation method cannot declare type-parameters
960 if (tree.typarams.nonEmpty()) {
961 log.error(tree.typarams.head.pos(),
962 "intf.annotation.members.cant.have.type.params");
963 }
964 // validate annotation method's return type (could be an annotation type)
965 chk.validateAnnotationType(tree.restype);
966 // ensure that annotation method does not clash with members of Object/Annotation
967 chk.validateAnnotationMethod(tree.pos(), m);
968 }
970 for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
971 chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
973 if (tree.body == null) {
974 // Empty bodies are only allowed for
975 // abstract, native, or interface methods, or for methods
976 // in a retrofit signature class.
977 if (isDefaultMethod || (tree.sym.flags() & (ABSTRACT | NATIVE)) == 0 &&
978 !relax)
979 log.error(tree.pos(), "missing.meth.body.or.decl.abstract");
980 if (tree.defaultValue != null) {
981 if ((owner.flags() & ANNOTATION) == 0)
982 log.error(tree.pos(),
983 "default.allowed.in.intf.annotation.member");
984 }
985 } else if ((tree.sym.flags() & ABSTRACT) != 0 && !isDefaultMethod) {
986 if ((owner.flags() & INTERFACE) != 0) {
987 log.error(tree.body.pos(), "intf.meth.cant.have.body");
988 } else {
989 log.error(tree.pos(), "abstract.meth.cant.have.body");
990 }
991 } else if ((tree.mods.flags & NATIVE) != 0) {
992 log.error(tree.pos(), "native.meth.cant.have.body");
993 } else {
994 // Add an implicit super() call unless an explicit call to
995 // super(...) or this(...) is given
996 // or we are compiling class java.lang.Object.
997 if (tree.name == names.init && owner.type != syms.objectType) {
998 JCBlock body = tree.body;
999 if (body.stats.isEmpty() ||
1000 !TreeInfo.isSelfCall(body.stats.head)) {
1001 body.stats = body.stats.
1002 prepend(memberEnter.SuperCall(make.at(body.pos),
1003 List.<Type>nil(),
1004 List.<JCVariableDecl>nil(),
1005 false));
1006 } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
1007 (tree.mods.flags & GENERATEDCONSTR) == 0 &&
1008 TreeInfo.isSuperCall(body.stats.head)) {
1009 // enum constructors are not allowed to call super
1010 // directly, so make sure there aren't any super calls
1011 // in enum constructors, except in the compiler
1012 // generated one.
1013 log.error(tree.body.stats.head.pos(),
1014 "call.to.super.not.allowed.in.enum.ctor",
1015 env.enclClass.sym);
1016 }
1017 }
1019 // Attribute all type annotations in the body
1020 memberEnter.typeAnnotate(tree.body, localEnv, m, null);
1021 annotate.flush();
1023 // Attribute method body.
1024 attribStat(tree.body, localEnv);
1025 }
1027 localEnv.info.scope.leave();
1028 result = tree.type = m.type;
1029 }
1030 finally {
1031 chk.setLint(prevLint);
1032 chk.setMethod(prevMethod);
1033 }
1034 }
1036 public void visitVarDef(JCVariableDecl tree) {
1037 // Local variables have not been entered yet, so we need to do it now:
1038 if (env.info.scope.owner.kind == MTH) {
1039 if (tree.sym != null) {
1040 // parameters have already been entered
1041 env.info.scope.enter(tree.sym);
1042 } else {
1043 memberEnter.memberEnter(tree, env);
1044 annotate.flush();
1045 }
1046 } else {
1047 if (tree.init != null) {
1048 // Field initializer expression need to be entered.
1049 memberEnter.typeAnnotate(tree.init, env, tree.sym, tree.pos());
1050 annotate.flush();
1051 }
1052 }
1054 VarSymbol v = tree.sym;
1055 Lint lint = env.info.lint.augment(v);
1056 Lint prevLint = chk.setLint(lint);
1058 // Check that the variable's declared type is well-formed.
1059 boolean isImplicitLambdaParameter = env.tree.hasTag(LAMBDA) &&
1060 ((JCLambda)env.tree).paramKind == JCLambda.ParameterKind.IMPLICIT &&
1061 (tree.sym.flags() & PARAMETER) != 0;
1062 chk.validate(tree.vartype, env, !isImplicitLambdaParameter);
1064 try {
1065 v.getConstValue(); // ensure compile-time constant initializer is evaluated
1066 deferredLintHandler.flush(tree.pos());
1067 chk.checkDeprecatedAnnotation(tree.pos(), v);
1069 if (tree.init != null) {
1070 if ((v.flags_field & FINAL) == 0 ||
1071 !memberEnter.needsLazyConstValue(tree.init)) {
1072 // Not a compile-time constant
1073 // Attribute initializer in a new environment
1074 // with the declared variable as owner.
1075 // Check that initializer conforms to variable's declared type.
1076 Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
1077 initEnv.info.lint = lint;
1078 // In order to catch self-references, we set the variable's
1079 // declaration position to maximal possible value, effectively
1080 // marking the variable as undefined.
1081 initEnv.info.enclVar = v;
1082 attribExpr(tree.init, initEnv, v.type);
1083 }
1084 }
1085 result = tree.type = v.type;
1086 }
1087 finally {
1088 chk.setLint(prevLint);
1089 }
1090 }
1092 public void visitSkip(JCSkip tree) {
1093 result = null;
1094 }
1096 public void visitBlock(JCBlock tree) {
1097 if (env.info.scope.owner.kind == TYP) {
1098 // Block is a static or instance initializer;
1099 // let the owner of the environment be a freshly
1100 // created BLOCK-method.
1101 Env<AttrContext> localEnv =
1102 env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
1103 localEnv.info.scope.owner =
1104 new MethodSymbol(tree.flags | BLOCK |
1105 env.info.scope.owner.flags() & STRICTFP, names.empty, null,
1106 env.info.scope.owner);
1107 if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
1109 // Attribute all type annotations in the block
1110 memberEnter.typeAnnotate(tree, localEnv, localEnv.info.scope.owner, null);
1111 annotate.flush();
1113 {
1114 // Store init and clinit type annotations with the ClassSymbol
1115 // to allow output in Gen.normalizeDefs.
1116 ClassSymbol cs = (ClassSymbol)env.info.scope.owner;
1117 List<Attribute.TypeCompound> tas = localEnv.info.scope.owner.getRawTypeAttributes();
1118 if ((tree.flags & STATIC) != 0) {
1119 cs.appendClassInitTypeAttributes(tas);
1120 } else {
1121 cs.appendInitTypeAttributes(tas);
1122 }
1123 }
1125 attribStats(tree.stats, localEnv);
1126 } else {
1127 // Create a new local environment with a local scope.
1128 Env<AttrContext> localEnv =
1129 env.dup(tree, env.info.dup(env.info.scope.dup()));
1130 try {
1131 attribStats(tree.stats, localEnv);
1132 } finally {
1133 localEnv.info.scope.leave();
1134 }
1135 }
1136 result = null;
1137 }
1139 public void visitDoLoop(JCDoWhileLoop tree) {
1140 attribStat(tree.body, env.dup(tree));
1141 attribExpr(tree.cond, env, syms.booleanType);
1142 result = null;
1143 }
1145 public void visitWhileLoop(JCWhileLoop tree) {
1146 attribExpr(tree.cond, env, syms.booleanType);
1147 attribStat(tree.body, env.dup(tree));
1148 result = null;
1149 }
1151 public void visitForLoop(JCForLoop tree) {
1152 Env<AttrContext> loopEnv =
1153 env.dup(env.tree, env.info.dup(env.info.scope.dup()));
1154 try {
1155 attribStats(tree.init, loopEnv);
1156 if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType);
1157 loopEnv.tree = tree; // before, we were not in loop!
1158 attribStats(tree.step, loopEnv);
1159 attribStat(tree.body, loopEnv);
1160 result = null;
1161 }
1162 finally {
1163 loopEnv.info.scope.leave();
1164 }
1165 }
1167 public void visitForeachLoop(JCEnhancedForLoop tree) {
1168 Env<AttrContext> loopEnv =
1169 env.dup(env.tree, env.info.dup(env.info.scope.dup()));
1170 try {
1171 //the Formal Parameter of a for-each loop is not in the scope when
1172 //attributing the for-each expression; we mimick this by attributing
1173 //the for-each expression first (against original scope).
1174 Type exprType = types.upperBound(attribExpr(tree.expr, loopEnv));
1175 attribStat(tree.var, loopEnv);
1176 chk.checkNonVoid(tree.pos(), exprType);
1177 Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
1178 if (elemtype == null) {
1179 // or perhaps expr implements Iterable<T>?
1180 Type base = types.asSuper(exprType, syms.iterableType.tsym);
1181 if (base == null) {
1182 log.error(tree.expr.pos(),
1183 "foreach.not.applicable.to.type",
1184 exprType,
1185 diags.fragment("type.req.array.or.iterable"));
1186 elemtype = types.createErrorType(exprType);
1187 } else {
1188 List<Type> iterableParams = base.allparams();
1189 elemtype = iterableParams.isEmpty()
1190 ? syms.objectType
1191 : types.upperBound(iterableParams.head);
1192 }
1193 }
1194 chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
1195 loopEnv.tree = tree; // before, we were not in loop!
1196 attribStat(tree.body, loopEnv);
1197 result = null;
1198 }
1199 finally {
1200 loopEnv.info.scope.leave();
1201 }
1202 }
1204 public void visitLabelled(JCLabeledStatement tree) {
1205 // Check that label is not used in an enclosing statement
1206 Env<AttrContext> env1 = env;
1207 while (env1 != null && !env1.tree.hasTag(CLASSDEF)) {
1208 if (env1.tree.hasTag(LABELLED) &&
1209 ((JCLabeledStatement) env1.tree).label == tree.label) {
1210 log.error(tree.pos(), "label.already.in.use",
1211 tree.label);
1212 break;
1213 }
1214 env1 = env1.next;
1215 }
1217 attribStat(tree.body, env.dup(tree));
1218 result = null;
1219 }
1221 public void visitSwitch(JCSwitch tree) {
1222 Type seltype = attribExpr(tree.selector, env);
1224 Env<AttrContext> switchEnv =
1225 env.dup(tree, env.info.dup(env.info.scope.dup()));
1227 try {
1229 boolean enumSwitch =
1230 allowEnums &&
1231 (seltype.tsym.flags() & Flags.ENUM) != 0;
1232 boolean stringSwitch = false;
1233 if (types.isSameType(seltype, syms.stringType)) {
1234 if (allowStringsInSwitch) {
1235 stringSwitch = true;
1236 } else {
1237 log.error(tree.selector.pos(), "string.switch.not.supported.in.source", sourceName);
1238 }
1239 }
1240 if (!enumSwitch && !stringSwitch)
1241 seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType);
1243 // Attribute all cases and
1244 // check that there are no duplicate case labels or default clauses.
1245 Set<Object> labels = new HashSet<Object>(); // The set of case labels.
1246 boolean hasDefault = false; // Is there a default label?
1247 for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
1248 JCCase c = l.head;
1249 Env<AttrContext> caseEnv =
1250 switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup()));
1251 try {
1252 if (c.pat != null) {
1253 if (enumSwitch) {
1254 Symbol sym = enumConstant(c.pat, seltype);
1255 if (sym == null) {
1256 log.error(c.pat.pos(), "enum.label.must.be.unqualified.enum");
1257 } else if (!labels.add(sym)) {
1258 log.error(c.pos(), "duplicate.case.label");
1259 }
1260 } else {
1261 Type pattype = attribExpr(c.pat, switchEnv, seltype);
1262 if (!pattype.hasTag(ERROR)) {
1263 if (pattype.constValue() == null) {
1264 log.error(c.pat.pos(),
1265 (stringSwitch ? "string.const.req" : "const.expr.req"));
1266 } else if (labels.contains(pattype.constValue())) {
1267 log.error(c.pos(), "duplicate.case.label");
1268 } else {
1269 labels.add(pattype.constValue());
1270 }
1271 }
1272 }
1273 } else if (hasDefault) {
1274 log.error(c.pos(), "duplicate.default.label");
1275 } else {
1276 hasDefault = true;
1277 }
1278 attribStats(c.stats, caseEnv);
1279 } finally {
1280 caseEnv.info.scope.leave();
1281 addVars(c.stats, switchEnv.info.scope);
1282 }
1283 }
1285 result = null;
1286 }
1287 finally {
1288 switchEnv.info.scope.leave();
1289 }
1290 }
1291 // where
1292 /** Add any variables defined in stats to the switch scope. */
1293 private static void addVars(List<JCStatement> stats, Scope switchScope) {
1294 for (;stats.nonEmpty(); stats = stats.tail) {
1295 JCTree stat = stats.head;
1296 if (stat.hasTag(VARDEF))
1297 switchScope.enter(((JCVariableDecl) stat).sym);
1298 }
1299 }
1300 // where
1301 /** Return the selected enumeration constant symbol, or null. */
1302 private Symbol enumConstant(JCTree tree, Type enumType) {
1303 if (!tree.hasTag(IDENT)) {
1304 log.error(tree.pos(), "enum.label.must.be.unqualified.enum");
1305 return syms.errSymbol;
1306 }
1307 JCIdent ident = (JCIdent)tree;
1308 Name name = ident.name;
1309 for (Scope.Entry e = enumType.tsym.members().lookup(name);
1310 e.scope != null; e = e.next()) {
1311 if (e.sym.kind == VAR) {
1312 Symbol s = ident.sym = e.sym;
1313 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
1314 ident.type = s.type;
1315 return ((s.flags_field & Flags.ENUM) == 0)
1316 ? null : s;
1317 }
1318 }
1319 return null;
1320 }
1322 public void visitSynchronized(JCSynchronized tree) {
1323 chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
1324 attribStat(tree.body, env);
1325 result = null;
1326 }
1328 public void visitTry(JCTry tree) {
1329 // Create a new local environment with a local
1330 Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
1331 try {
1332 boolean isTryWithResource = tree.resources.nonEmpty();
1333 // Create a nested environment for attributing the try block if needed
1334 Env<AttrContext> tryEnv = isTryWithResource ?
1335 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
1336 localEnv;
1337 try {
1338 // Attribute resource declarations
1339 for (JCTree resource : tree.resources) {
1340 CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) {
1341 @Override
1342 public void report(DiagnosticPosition pos, JCDiagnostic details) {
1343 chk.basicHandler.report(pos, diags.fragment("try.not.applicable.to.type", details));
1344 }
1345 };
1346 ResultInfo twrResult = new ResultInfo(VAL, syms.autoCloseableType, twrContext);
1347 if (resource.hasTag(VARDEF)) {
1348 attribStat(resource, tryEnv);
1349 twrResult.check(resource, resource.type);
1351 //check that resource type cannot throw InterruptedException
1352 checkAutoCloseable(resource.pos(), localEnv, resource.type);
1354 VarSymbol var = ((JCVariableDecl) resource).sym;
1355 var.setData(ElementKind.RESOURCE_VARIABLE);
1356 } else {
1357 attribTree(resource, tryEnv, twrResult);
1358 }
1359 }
1360 // Attribute body
1361 attribStat(tree.body, tryEnv);
1362 } finally {
1363 if (isTryWithResource)
1364 tryEnv.info.scope.leave();
1365 }
1367 // Attribute catch clauses
1368 for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
1369 JCCatch c = l.head;
1370 Env<AttrContext> catchEnv =
1371 localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup()));
1372 try {
1373 Type ctype = attribStat(c.param, catchEnv);
1374 if (TreeInfo.isMultiCatch(c)) {
1375 //multi-catch parameter is implicitly marked as final
1376 c.param.sym.flags_field |= FINAL | UNION;
1377 }
1378 if (c.param.sym.kind == Kinds.VAR) {
1379 c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
1380 }
1381 chk.checkType(c.param.vartype.pos(),
1382 chk.checkClassType(c.param.vartype.pos(), ctype),
1383 syms.throwableType);
1384 attribStat(c.body, catchEnv);
1385 } finally {
1386 catchEnv.info.scope.leave();
1387 }
1388 }
1390 // Attribute finalizer
1391 if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
1392 result = null;
1393 }
1394 finally {
1395 localEnv.info.scope.leave();
1396 }
1397 }
1399 void checkAutoCloseable(DiagnosticPosition pos, Env<AttrContext> env, Type resource) {
1400 if (!resource.isErroneous() &&
1401 types.asSuper(resource, syms.autoCloseableType.tsym) != null &&
1402 !types.isSameType(resource, syms.autoCloseableType)) { // Don't emit warning for AutoCloseable itself
1403 Symbol close = syms.noSymbol;
1404 Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log);
1405 try {
1406 close = rs.resolveQualifiedMethod(pos,
1407 env,
1408 resource,
1409 names.close,
1410 List.<Type>nil(),
1411 List.<Type>nil());
1412 }
1413 finally {
1414 log.popDiagnosticHandler(discardHandler);
1415 }
1416 if (close.kind == MTH &&
1417 close.overrides(syms.autoCloseableClose, resource.tsym, types, true) &&
1418 chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes()) &&
1419 env.info.lint.isEnabled(LintCategory.TRY)) {
1420 log.warning(LintCategory.TRY, pos, "try.resource.throws.interrupted.exc", resource);
1421 }
1422 }
1423 }
1425 public void visitConditional(JCConditional tree) {
1426 Type condtype = attribExpr(tree.cond, env, syms.booleanType);
1428 tree.polyKind = (!allowPoly ||
1429 pt().hasTag(NONE) && pt() != Type.recoveryType ||
1430 isBooleanOrNumeric(env, tree)) ?
1431 PolyKind.STANDALONE : PolyKind.POLY;
1433 if (tree.polyKind == PolyKind.POLY && resultInfo.pt.hasTag(VOID)) {
1434 //cannot get here (i.e. it means we are returning from void method - which is already an error)
1435 resultInfo.checkContext.report(tree, diags.fragment("conditional.target.cant.be.void"));
1436 result = tree.type = types.createErrorType(resultInfo.pt);
1437 return;
1438 }
1440 ResultInfo condInfo = tree.polyKind == PolyKind.STANDALONE ?
1441 unknownExprInfo :
1442 resultInfo.dup(new Check.NestedCheckContext(resultInfo.checkContext) {
1443 //this will use enclosing check context to check compatibility of
1444 //subexpression against target type; if we are in a method check context,
1445 //depending on whether boxing is allowed, we could have incompatibilities
1446 @Override
1447 public void report(DiagnosticPosition pos, JCDiagnostic details) {
1448 enclosingContext.report(pos, diags.fragment("incompatible.type.in.conditional", details));
1449 }
1450 });
1452 Type truetype = attribTree(tree.truepart, env, condInfo);
1453 Type falsetype = attribTree(tree.falsepart, env, condInfo);
1455 Type owntype = (tree.polyKind == PolyKind.STANDALONE) ? condType(tree, truetype, falsetype) : pt();
1456 if (condtype.constValue() != null &&
1457 truetype.constValue() != null &&
1458 falsetype.constValue() != null &&
1459 !owntype.hasTag(NONE)) {
1460 //constant folding
1461 owntype = cfolder.coerce(condtype.isTrue() ? truetype : falsetype, owntype);
1462 }
1463 result = check(tree, owntype, VAL, resultInfo);
1464 }
1465 //where
1466 private boolean isBooleanOrNumeric(Env<AttrContext> env, JCExpression tree) {
1467 switch (tree.getTag()) {
1468 case LITERAL: return ((JCLiteral)tree).typetag.isSubRangeOf(DOUBLE) ||
1469 ((JCLiteral)tree).typetag == BOOLEAN ||
1470 ((JCLiteral)tree).typetag == BOT;
1471 case LAMBDA: case REFERENCE: return false;
1472 case PARENS: return isBooleanOrNumeric(env, ((JCParens)tree).expr);
1473 case CONDEXPR:
1474 JCConditional condTree = (JCConditional)tree;
1475 return isBooleanOrNumeric(env, condTree.truepart) &&
1476 isBooleanOrNumeric(env, condTree.falsepart);
1477 case APPLY:
1478 JCMethodInvocation speculativeMethodTree =
1479 (JCMethodInvocation)deferredAttr.attribSpeculative(tree, env, unknownExprInfo);
1480 Type owntype = TreeInfo.symbol(speculativeMethodTree.meth).type.getReturnType();
1481 return types.unboxedTypeOrType(owntype).isPrimitive();
1482 case NEWCLASS:
1483 JCExpression className =
1484 removeClassParams.translate(((JCNewClass)tree).clazz);
1485 JCExpression speculativeNewClassTree =
1486 (JCExpression)deferredAttr.attribSpeculative(className, env, unknownTypeInfo);
1487 return types.unboxedTypeOrType(speculativeNewClassTree.type).isPrimitive();
1488 default:
1489 Type speculativeType = deferredAttr.attribSpeculative(tree, env, unknownExprInfo).type;
1490 speculativeType = types.unboxedTypeOrType(speculativeType);
1491 return speculativeType.isPrimitive();
1492 }
1493 }
1494 //where
1495 TreeTranslator removeClassParams = new TreeTranslator() {
1496 @Override
1497 public void visitTypeApply(JCTypeApply tree) {
1498 result = translate(tree.clazz);
1499 }
1500 };
1502 /** Compute the type of a conditional expression, after
1503 * checking that it exists. See JLS 15.25. Does not take into
1504 * account the special case where condition and both arms
1505 * are constants.
1506 *
1507 * @param pos The source position to be used for error
1508 * diagnostics.
1509 * @param thentype The type of the expression's then-part.
1510 * @param elsetype The type of the expression's else-part.
1511 */
1512 private Type condType(DiagnosticPosition pos,
1513 Type thentype, Type elsetype) {
1514 // If same type, that is the result
1515 if (types.isSameType(thentype, elsetype))
1516 return thentype.baseType();
1518 Type thenUnboxed = (!allowBoxing || thentype.isPrimitive())
1519 ? thentype : types.unboxedType(thentype);
1520 Type elseUnboxed = (!allowBoxing || elsetype.isPrimitive())
1521 ? elsetype : types.unboxedType(elsetype);
1523 // Otherwise, if both arms can be converted to a numeric
1524 // type, return the least numeric type that fits both arms
1525 // (i.e. return larger of the two, or return int if one
1526 // arm is short, the other is char).
1527 if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) {
1528 // If one arm has an integer subrange type (i.e., byte,
1529 // short, or char), and the other is an integer constant
1530 // that fits into the subrange, return the subrange type.
1531 if (thenUnboxed.getTag().isStrictSubRangeOf(INT) &&
1532 elseUnboxed.hasTag(INT) &&
1533 types.isAssignable(elseUnboxed, thenUnboxed)) {
1534 return thenUnboxed.baseType();
1535 }
1536 if (elseUnboxed.getTag().isStrictSubRangeOf(INT) &&
1537 thenUnboxed.hasTag(INT) &&
1538 types.isAssignable(thenUnboxed, elseUnboxed)) {
1539 return elseUnboxed.baseType();
1540 }
1542 for (TypeTag tag : primitiveTags) {
1543 Type candidate = syms.typeOfTag[tag.ordinal()];
1544 if (types.isSubtype(thenUnboxed, candidate) &&
1545 types.isSubtype(elseUnboxed, candidate)) {
1546 return candidate;
1547 }
1548 }
1549 }
1551 // Those were all the cases that could result in a primitive
1552 if (allowBoxing) {
1553 if (thentype.isPrimitive())
1554 thentype = types.boxedClass(thentype).type;
1555 if (elsetype.isPrimitive())
1556 elsetype = types.boxedClass(elsetype).type;
1557 }
1559 if (types.isSubtype(thentype, elsetype))
1560 return elsetype.baseType();
1561 if (types.isSubtype(elsetype, thentype))
1562 return thentype.baseType();
1564 if (!allowBoxing || thentype.hasTag(VOID) || elsetype.hasTag(VOID)) {
1565 log.error(pos, "neither.conditional.subtype",
1566 thentype, elsetype);
1567 return thentype.baseType();
1568 }
1570 // both are known to be reference types. The result is
1571 // lub(thentype,elsetype). This cannot fail, as it will
1572 // always be possible to infer "Object" if nothing better.
1573 return types.lub(thentype.baseType(), elsetype.baseType());
1574 }
1576 final static TypeTag[] primitiveTags = new TypeTag[]{
1577 BYTE,
1578 CHAR,
1579 SHORT,
1580 INT,
1581 LONG,
1582 FLOAT,
1583 DOUBLE,
1584 BOOLEAN,
1585 };
1587 public void visitIf(JCIf tree) {
1588 attribExpr(tree.cond, env, syms.booleanType);
1589 attribStat(tree.thenpart, env);
1590 if (tree.elsepart != null)
1591 attribStat(tree.elsepart, env);
1592 chk.checkEmptyIf(tree);
1593 result = null;
1594 }
1596 public void visitExec(JCExpressionStatement tree) {
1597 //a fresh environment is required for 292 inference to work properly ---
1598 //see Infer.instantiatePolymorphicSignatureInstance()
1599 Env<AttrContext> localEnv = env.dup(tree);
1600 attribExpr(tree.expr, localEnv);
1601 result = null;
1602 }
1604 public void visitBreak(JCBreak tree) {
1605 tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
1606 result = null;
1607 }
1609 public void visitContinue(JCContinue tree) {
1610 tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
1611 result = null;
1612 }
1613 //where
1614 /** Return the target of a break or continue statement, if it exists,
1615 * report an error if not.
1616 * Note: The target of a labelled break or continue is the
1617 * (non-labelled) statement tree referred to by the label,
1618 * not the tree representing the labelled statement itself.
1619 *
1620 * @param pos The position to be used for error diagnostics
1621 * @param tag The tag of the jump statement. This is either
1622 * Tree.BREAK or Tree.CONTINUE.
1623 * @param label The label of the jump statement, or null if no
1624 * label is given.
1625 * @param env The environment current at the jump statement.
1626 */
1627 private JCTree findJumpTarget(DiagnosticPosition pos,
1628 JCTree.Tag tag,
1629 Name label,
1630 Env<AttrContext> env) {
1631 // Search environments outwards from the point of jump.
1632 Env<AttrContext> env1 = env;
1633 LOOP:
1634 while (env1 != null) {
1635 switch (env1.tree.getTag()) {
1636 case LABELLED:
1637 JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
1638 if (label == labelled.label) {
1639 // If jump is a continue, check that target is a loop.
1640 if (tag == CONTINUE) {
1641 if (!labelled.body.hasTag(DOLOOP) &&
1642 !labelled.body.hasTag(WHILELOOP) &&
1643 !labelled.body.hasTag(FORLOOP) &&
1644 !labelled.body.hasTag(FOREACHLOOP))
1645 log.error(pos, "not.loop.label", label);
1646 // Found labelled statement target, now go inwards
1647 // to next non-labelled tree.
1648 return TreeInfo.referencedStatement(labelled);
1649 } else {
1650 return labelled;
1651 }
1652 }
1653 break;
1654 case DOLOOP:
1655 case WHILELOOP:
1656 case FORLOOP:
1657 case FOREACHLOOP:
1658 if (label == null) return env1.tree;
1659 break;
1660 case SWITCH:
1661 if (label == null && tag == BREAK) return env1.tree;
1662 break;
1663 case LAMBDA:
1664 case METHODDEF:
1665 case CLASSDEF:
1666 break LOOP;
1667 default:
1668 }
1669 env1 = env1.next;
1670 }
1671 if (label != null)
1672 log.error(pos, "undef.label", label);
1673 else if (tag == CONTINUE)
1674 log.error(pos, "cont.outside.loop");
1675 else
1676 log.error(pos, "break.outside.switch.loop");
1677 return null;
1678 }
1680 public void visitReturn(JCReturn tree) {
1681 // Check that there is an enclosing method which is
1682 // nested within than the enclosing class.
1683 if (env.info.returnResult == null) {
1684 log.error(tree.pos(), "ret.outside.meth");
1685 } else {
1686 // Attribute return expression, if it exists, and check that
1687 // it conforms to result type of enclosing method.
1688 if (tree.expr != null) {
1689 if (env.info.returnResult.pt.hasTag(VOID)) {
1690 env.info.returnResult.checkContext.report(tree.expr.pos(),
1691 diags.fragment("unexpected.ret.val"));
1692 }
1693 attribTree(tree.expr, env, env.info.returnResult);
1694 } else if (!env.info.returnResult.pt.hasTag(VOID) &&
1695 !env.info.returnResult.pt.hasTag(NONE)) {
1696 env.info.returnResult.checkContext.report(tree.pos(),
1697 diags.fragment("missing.ret.val"));
1698 }
1699 }
1700 result = null;
1701 }
1703 public void visitThrow(JCThrow tree) {
1704 Type owntype = attribExpr(tree.expr, env, allowPoly ? Type.noType : syms.throwableType);
1705 if (allowPoly) {
1706 chk.checkType(tree, owntype, syms.throwableType);
1707 }
1708 result = null;
1709 }
1711 public void visitAssert(JCAssert tree) {
1712 attribExpr(tree.cond, env, syms.booleanType);
1713 if (tree.detail != null) {
1714 chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
1715 }
1716 result = null;
1717 }
1719 /** Visitor method for method invocations.
1720 * NOTE: The method part of an application will have in its type field
1721 * the return type of the method, not the method's type itself!
1722 */
1723 public void visitApply(JCMethodInvocation tree) {
1724 // The local environment of a method application is
1725 // a new environment nested in the current one.
1726 Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
1728 // The types of the actual method arguments.
1729 List<Type> argtypes;
1731 // The types of the actual method type arguments.
1732 List<Type> typeargtypes = null;
1734 Name methName = TreeInfo.name(tree.meth);
1736 boolean isConstructorCall =
1737 methName == names._this || methName == names._super;
1739 ListBuffer<Type> argtypesBuf = new ListBuffer<>();
1740 if (isConstructorCall) {
1741 // We are seeing a ...this(...) or ...super(...) call.
1742 // Check that this is the first statement in a constructor.
1743 if (checkFirstConstructorStat(tree, env)) {
1745 // Record the fact
1746 // that this is a constructor call (using isSelfCall).
1747 localEnv.info.isSelfCall = true;
1749 // Attribute arguments, yielding list of argument types.
1750 attribArgs(tree.args, localEnv, argtypesBuf);
1751 argtypes = argtypesBuf.toList();
1752 typeargtypes = attribTypes(tree.typeargs, localEnv);
1754 // Variable `site' points to the class in which the called
1755 // constructor is defined.
1756 Type site = env.enclClass.sym.type;
1757 if (methName == names._super) {
1758 if (site == syms.objectType) {
1759 log.error(tree.meth.pos(), "no.superclass", site);
1760 site = types.createErrorType(syms.objectType);
1761 } else {
1762 site = types.supertype(site);
1763 }
1764 }
1766 if (site.hasTag(CLASS)) {
1767 Type encl = site.getEnclosingType();
1768 while (encl != null && encl.hasTag(TYPEVAR))
1769 encl = encl.getUpperBound();
1770 if (encl.hasTag(CLASS)) {
1771 // we are calling a nested class
1773 if (tree.meth.hasTag(SELECT)) {
1774 JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
1776 // We are seeing a prefixed call, of the form
1777 // <expr>.super(...).
1778 // Check that the prefix expression conforms
1779 // to the outer instance type of the class.
1780 chk.checkRefType(qualifier.pos(),
1781 attribExpr(qualifier, localEnv,
1782 encl));
1783 } else if (methName == names._super) {
1784 // qualifier omitted; check for existence
1785 // of an appropriate implicit qualifier.
1786 rs.resolveImplicitThis(tree.meth.pos(),
1787 localEnv, site, true);
1788 }
1789 } else if (tree.meth.hasTag(SELECT)) {
1790 log.error(tree.meth.pos(), "illegal.qual.not.icls",
1791 site.tsym);
1792 }
1794 // if we're calling a java.lang.Enum constructor,
1795 // prefix the implicit String and int parameters
1796 if (site.tsym == syms.enumSym && allowEnums)
1797 argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
1799 // Resolve the called constructor under the assumption
1800 // that we are referring to a superclass instance of the
1801 // current instance (JLS ???).
1802 boolean selectSuperPrev = localEnv.info.selectSuper;
1803 localEnv.info.selectSuper = true;
1804 localEnv.info.pendingResolutionPhase = null;
1805 Symbol sym = rs.resolveConstructor(
1806 tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
1807 localEnv.info.selectSuper = selectSuperPrev;
1809 // Set method symbol to resolved constructor...
1810 TreeInfo.setSymbol(tree.meth, sym);
1812 // ...and check that it is legal in the current context.
1813 // (this will also set the tree's type)
1814 Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
1815 checkId(tree.meth, site, sym, localEnv, new ResultInfo(MTH, mpt));
1816 }
1817 // Otherwise, `site' is an error type and we do nothing
1818 }
1819 result = tree.type = syms.voidType;
1820 } else {
1821 // Otherwise, we are seeing a regular method call.
1822 // Attribute the arguments, yielding list of argument types, ...
1823 int kind = attribArgs(tree.args, localEnv, argtypesBuf);
1824 argtypes = argtypesBuf.toList();
1825 typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
1827 // ... and attribute the method using as a prototype a methodtype
1828 // whose formal argument types is exactly the list of actual
1829 // arguments (this will also set the method symbol).
1830 Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
1831 localEnv.info.pendingResolutionPhase = null;
1832 Type mtype = attribTree(tree.meth, localEnv, new ResultInfo(kind, mpt, resultInfo.checkContext));
1834 // Compute the result type.
1835 Type restype = mtype.getReturnType();
1836 if (restype.hasTag(WILDCARD))
1837 throw new AssertionError(mtype);
1839 Type qualifier = (tree.meth.hasTag(SELECT))
1840 ? ((JCFieldAccess) tree.meth).selected.type
1841 : env.enclClass.sym.type;
1842 restype = adjustMethodReturnType(qualifier, methName, argtypes, restype);
1844 chk.checkRefTypes(tree.typeargs, typeargtypes);
1846 // Check that value of resulting type is admissible in the
1847 // current context. Also, capture the return type
1848 result = check(tree, capture(restype), VAL, resultInfo);
1849 }
1850 chk.validate(tree.typeargs, localEnv);
1851 }
1852 //where
1853 Type adjustMethodReturnType(Type qualifierType, Name methodName, List<Type> argtypes, Type restype) {
1854 if (allowCovariantReturns &&
1855 methodName == names.clone &&
1856 types.isArray(qualifierType)) {
1857 // as a special case, array.clone() has a result that is
1858 // the same as static type of the array being cloned
1859 return qualifierType;
1860 } else if (allowGenerics &&
1861 methodName == names.getClass &&
1862 argtypes.isEmpty()) {
1863 // as a special case, x.getClass() has type Class<? extends |X|>
1864 return new ClassType(restype.getEnclosingType(),
1865 List.<Type>of(new WildcardType(types.erasure(qualifierType),
1866 BoundKind.EXTENDS,
1867 syms.boundClass)),
1868 restype.tsym);
1869 } else {
1870 return restype;
1871 }
1872 }
1874 /** Check that given application node appears as first statement
1875 * in a constructor call.
1876 * @param tree The application node
1877 * @param env The environment current at the application.
1878 */
1879 boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) {
1880 JCMethodDecl enclMethod = env.enclMethod;
1881 if (enclMethod != null && enclMethod.name == names.init) {
1882 JCBlock body = enclMethod.body;
1883 if (body.stats.head.hasTag(EXEC) &&
1884 ((JCExpressionStatement) body.stats.head).expr == tree)
1885 return true;
1886 }
1887 log.error(tree.pos(),"call.must.be.first.stmt.in.ctor",
1888 TreeInfo.name(tree.meth));
1889 return false;
1890 }
1892 /** Obtain a method type with given argument types.
1893 */
1894 Type newMethodTemplate(Type restype, List<Type> argtypes, List<Type> typeargtypes) {
1895 MethodType mt = new MethodType(argtypes, restype, List.<Type>nil(), syms.methodClass);
1896 return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
1897 }
1899 public void visitNewClass(final JCNewClass tree) {
1900 Type owntype = types.createErrorType(tree.type);
1902 // The local environment of a class creation is
1903 // a new environment nested in the current one.
1904 Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
1906 // The anonymous inner class definition of the new expression,
1907 // if one is defined by it.
1908 JCClassDecl cdef = tree.def;
1910 // If enclosing class is given, attribute it, and
1911 // complete class name to be fully qualified
1912 JCExpression clazz = tree.clazz; // Class field following new
1913 JCExpression clazzid; // Identifier in class field
1914 JCAnnotatedType annoclazzid; // Annotated type enclosing clazzid
1915 annoclazzid = null;
1917 if (clazz.hasTag(TYPEAPPLY)) {
1918 clazzid = ((JCTypeApply) clazz).clazz;
1919 if (clazzid.hasTag(ANNOTATED_TYPE)) {
1920 annoclazzid = (JCAnnotatedType) clazzid;
1921 clazzid = annoclazzid.underlyingType;
1922 }
1923 } else {
1924 if (clazz.hasTag(ANNOTATED_TYPE)) {
1925 annoclazzid = (JCAnnotatedType) clazz;
1926 clazzid = annoclazzid.underlyingType;
1927 } else {
1928 clazzid = clazz;
1929 }
1930 }
1932 JCExpression clazzid1 = clazzid; // The same in fully qualified form
1934 if (tree.encl != null) {
1935 // We are seeing a qualified new, of the form
1936 // <expr>.new C <...> (...) ...
1937 // In this case, we let clazz stand for the name of the
1938 // allocated class C prefixed with the type of the qualifier
1939 // expression, so that we can
1940 // resolve it with standard techniques later. I.e., if
1941 // <expr> has type T, then <expr>.new C <...> (...)
1942 // yields a clazz T.C.
1943 Type encltype = chk.checkRefType(tree.encl.pos(),
1944 attribExpr(tree.encl, env));
1945 // TODO 308: in <expr>.new C, do we also want to add the type annotations
1946 // from expr to the combined type, or not? Yes, do this.
1947 clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
1948 ((JCIdent) clazzid).name);
1950 EndPosTable endPosTable = this.env.toplevel.endPositions;
1951 endPosTable.storeEnd(clazzid1, tree.getEndPosition(endPosTable));
1952 if (clazz.hasTag(ANNOTATED_TYPE)) {
1953 JCAnnotatedType annoType = (JCAnnotatedType) clazz;
1954 List<JCAnnotation> annos = annoType.annotations;
1956 if (annoType.underlyingType.hasTag(TYPEAPPLY)) {
1957 clazzid1 = make.at(tree.pos).
1958 TypeApply(clazzid1,
1959 ((JCTypeApply) clazz).arguments);
1960 }
1962 clazzid1 = make.at(tree.pos).
1963 AnnotatedType(annos, clazzid1);
1964 } else if (clazz.hasTag(TYPEAPPLY)) {
1965 clazzid1 = make.at(tree.pos).
1966 TypeApply(clazzid1,
1967 ((JCTypeApply) clazz).arguments);
1968 }
1970 clazz = clazzid1;
1971 }
1973 // Attribute clazz expression and store
1974 // symbol + type back into the attributed tree.
1975 Type clazztype = TreeInfo.isEnumInit(env.tree) ?
1976 attribIdentAsEnumType(env, (JCIdent)clazz) :
1977 attribType(clazz, env);
1979 clazztype = chk.checkDiamond(tree, clazztype);
1980 chk.validate(clazz, localEnv);
1981 if (tree.encl != null) {
1982 // We have to work in this case to store
1983 // symbol + type back into the attributed tree.
1984 tree.clazz.type = clazztype;
1985 TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
1986 clazzid.type = ((JCIdent) clazzid).sym.type;
1987 if (annoclazzid != null) {
1988 annoclazzid.type = clazzid.type;
1989 }
1990 if (!clazztype.isErroneous()) {
1991 if (cdef != null && clazztype.tsym.isInterface()) {
1992 log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new");
1993 } else if (clazztype.tsym.isStatic()) {
1994 log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym);
1995 }
1996 }
1997 } else if (!clazztype.tsym.isInterface() &&
1998 clazztype.getEnclosingType().hasTag(CLASS)) {
1999 // Check for the existence of an apropos outer instance
2000 rs.resolveImplicitThis(tree.pos(), env, clazztype);
2001 }
2003 // Attribute constructor arguments.
2004 ListBuffer<Type> argtypesBuf = new ListBuffer<>();
2005 int pkind = attribArgs(tree.args, localEnv, argtypesBuf);
2006 List<Type> argtypes = argtypesBuf.toList();
2007 List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
2009 // If we have made no mistakes in the class type...
2010 if (clazztype.hasTag(CLASS)) {
2011 // Enums may not be instantiated except implicitly
2012 if (allowEnums &&
2013 (clazztype.tsym.flags_field&Flags.ENUM) != 0 &&
2014 (!env.tree.hasTag(VARDEF) ||
2015 (((JCVariableDecl) env.tree).mods.flags&Flags.ENUM) == 0 ||
2016 ((JCVariableDecl) env.tree).init != tree))
2017 log.error(tree.pos(), "enum.cant.be.instantiated");
2018 // Check that class is not abstract
2019 if (cdef == null &&
2020 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
2021 log.error(tree.pos(), "abstract.cant.be.instantiated",
2022 clazztype.tsym);
2023 } else if (cdef != null && clazztype.tsym.isInterface()) {
2024 // Check that no constructor arguments are given to
2025 // anonymous classes implementing an interface
2026 if (!argtypes.isEmpty())
2027 log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args");
2029 if (!typeargtypes.isEmpty())
2030 log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs");
2032 // Error recovery: pretend no arguments were supplied.
2033 argtypes = List.nil();
2034 typeargtypes = List.nil();
2035 } else if (TreeInfo.isDiamond(tree)) {
2036 ClassType site = new ClassType(clazztype.getEnclosingType(),
2037 clazztype.tsym.type.getTypeArguments(),
2038 clazztype.tsym);
2040 Env<AttrContext> diamondEnv = localEnv.dup(tree);
2041 diamondEnv.info.selectSuper = cdef != null;
2042 diamondEnv.info.pendingResolutionPhase = null;
2044 //if the type of the instance creation expression is a class type
2045 //apply method resolution inference (JLS 15.12.2.7). The return type
2046 //of the resolved constructor will be a partially instantiated type
2047 Symbol constructor = rs.resolveDiamond(tree.pos(),
2048 diamondEnv,
2049 site,
2050 argtypes,
2051 typeargtypes);
2052 tree.constructor = constructor.baseSymbol();
2054 final TypeSymbol csym = clazztype.tsym;
2055 ResultInfo diamondResult = new ResultInfo(MTH, newMethodTemplate(resultInfo.pt, argtypes, typeargtypes), new Check.NestedCheckContext(resultInfo.checkContext) {
2056 @Override
2057 public void report(DiagnosticPosition _unused, JCDiagnostic details) {
2058 enclosingContext.report(tree.clazz,
2059 diags.fragment("cant.apply.diamond.1", diags.fragment("diamond", csym), details));
2060 }
2061 });
2062 Type constructorType = tree.constructorType = types.createErrorType(clazztype);
2063 constructorType = checkId(tree, site,
2064 constructor,
2065 diamondEnv,
2066 diamondResult);
2068 tree.clazz.type = types.createErrorType(clazztype);
2069 if (!constructorType.isErroneous()) {
2070 tree.clazz.type = clazztype = constructorType.getReturnType();
2071 tree.constructorType = types.createMethodTypeWithReturn(constructorType, syms.voidType);
2072 }
2073 clazztype = chk.checkClassType(tree.clazz, tree.clazz.type, true);
2074 }
2076 // Resolve the called constructor under the assumption
2077 // that we are referring to a superclass instance of the
2078 // current instance (JLS ???).
2079 else {
2080 //the following code alters some of the fields in the current
2081 //AttrContext - hence, the current context must be dup'ed in
2082 //order to avoid downstream failures
2083 Env<AttrContext> rsEnv = localEnv.dup(tree);
2084 rsEnv.info.selectSuper = cdef != null;
2085 rsEnv.info.pendingResolutionPhase = null;
2086 tree.constructor = rs.resolveConstructor(
2087 tree.pos(), rsEnv, clazztype, argtypes, typeargtypes);
2088 if (cdef == null) { //do not check twice!
2089 tree.constructorType = checkId(tree,
2090 clazztype,
2091 tree.constructor,
2092 rsEnv,
2093 new ResultInfo(pkind, newMethodTemplate(syms.voidType, argtypes, typeargtypes)));
2094 if (rsEnv.info.lastResolveVarargs())
2095 Assert.check(tree.constructorType.isErroneous() || tree.varargsElement != null);
2096 }
2097 if (cdef == null &&
2098 !clazztype.isErroneous() &&
2099 clazztype.getTypeArguments().nonEmpty() &&
2100 findDiamonds) {
2101 findDiamond(localEnv, tree, clazztype);
2102 }
2103 }
2105 if (cdef != null) {
2106 // We are seeing an anonymous class instance creation.
2107 // In this case, the class instance creation
2108 // expression
2109 //
2110 // E.new <typeargs1>C<typargs2>(args) { ... }
2111 //
2112 // is represented internally as
2113 //
2114 // E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } ) .
2115 //
2116 // This expression is then *transformed* as follows:
2117 //
2118 // (1) add a STATIC flag to the class definition
2119 // if the current environment is static
2120 // (2) add an extends or implements clause
2121 // (3) add a constructor.
2122 //
2123 // For instance, if C is a class, and ET is the type of E,
2124 // the expression
2125 //
2126 // E.new <typeargs1>C<typargs2>(args) { ... }
2127 //
2128 // is translated to (where X is a fresh name and typarams is the
2129 // parameter list of the super constructor):
2130 //
2131 // new <typeargs1>X(<*nullchk*>E, args) where
2132 // X extends C<typargs2> {
2133 // <typarams> X(ET e, args) {
2134 // e.<typeargs1>super(args)
2135 // }
2136 // ...
2137 // }
2138 if (Resolve.isStatic(env)) cdef.mods.flags |= STATIC;
2140 if (clazztype.tsym.isInterface()) {
2141 cdef.implementing = List.of(clazz);
2142 } else {
2143 cdef.extending = clazz;
2144 }
2146 attribStat(cdef, localEnv);
2148 checkLambdaCandidate(tree, cdef.sym, clazztype);
2150 // If an outer instance is given,
2151 // prefix it to the constructor arguments
2152 // and delete it from the new expression
2153 if (tree.encl != null && !clazztype.tsym.isInterface()) {
2154 tree.args = tree.args.prepend(makeNullCheck(tree.encl));
2155 argtypes = argtypes.prepend(tree.encl.type);
2156 tree.encl = null;
2157 }
2159 // Reassign clazztype and recompute constructor.
2160 clazztype = cdef.sym.type;
2161 Symbol sym = tree.constructor = rs.resolveConstructor(
2162 tree.pos(), localEnv, clazztype, argtypes, typeargtypes);
2163 Assert.check(sym.kind < AMBIGUOUS);
2164 tree.constructor = sym;
2165 tree.constructorType = checkId(tree,
2166 clazztype,
2167 tree.constructor,
2168 localEnv,
2169 new ResultInfo(pkind, newMethodTemplate(syms.voidType, argtypes, typeargtypes)));
2170 } else {
2171 if (tree.clazz.hasTag(ANNOTATED_TYPE)) {
2172 checkForDeclarationAnnotations(((JCAnnotatedType) tree.clazz).annotations,
2173 tree.clazz.type.tsym);
2174 }
2175 }
2177 if (tree.constructor != null && tree.constructor.kind == MTH)
2178 owntype = clazztype;
2179 }
2180 result = check(tree, owntype, VAL, resultInfo);
2181 chk.validate(tree.typeargs, localEnv);
2182 }
2183 //where
2184 void findDiamond(Env<AttrContext> env, JCNewClass tree, Type clazztype) {
2185 JCTypeApply ta = (JCTypeApply)tree.clazz;
2186 List<JCExpression> prevTypeargs = ta.arguments;
2187 try {
2188 //create a 'fake' diamond AST node by removing type-argument trees
2189 ta.arguments = List.nil();
2190 ResultInfo findDiamondResult = new ResultInfo(VAL,
2191 resultInfo.checkContext.inferenceContext().free(resultInfo.pt) ? Type.noType : pt());
2192 Type inferred = deferredAttr.attribSpeculative(tree, env, findDiamondResult).type;
2193 Type polyPt = allowPoly ?
2194 syms.objectType :
2195 clazztype;
2196 if (!inferred.isErroneous() &&
2197 (allowPoly && pt() == Infer.anyPoly ?
2198 types.isSameType(inferred, clazztype) :
2199 types.isAssignable(inferred, pt().hasTag(NONE) ? polyPt : pt(), types.noWarnings))) {
2200 String key = types.isSameType(clazztype, inferred) ?
2201 "diamond.redundant.args" :
2202 "diamond.redundant.args.1";
2203 log.warning(tree.clazz.pos(), key, clazztype, inferred);
2204 }
2205 } finally {
2206 ta.arguments = prevTypeargs;
2207 }
2208 }
2210 private void checkLambdaCandidate(JCNewClass tree, ClassSymbol csym, Type clazztype) {
2211 if (allowLambda &&
2212 identifyLambdaCandidate &&
2213 clazztype.hasTag(CLASS) &&
2214 !pt().hasTag(NONE) &&
2215 types.isFunctionalInterface(clazztype.tsym)) {
2216 Symbol descriptor = types.findDescriptorSymbol(clazztype.tsym);
2217 int count = 0;
2218 boolean found = false;
2219 for (Symbol sym : csym.members().getElements()) {
2220 if ((sym.flags() & SYNTHETIC) != 0 ||
2221 sym.isConstructor()) continue;
2222 count++;
2223 if (sym.kind != MTH ||
2224 !sym.name.equals(descriptor.name)) continue;
2225 Type mtype = types.memberType(clazztype, sym);
2226 if (types.overrideEquivalent(mtype, types.memberType(clazztype, descriptor))) {
2227 found = true;
2228 }
2229 }
2230 if (found && count == 1) {
2231 log.note(tree.def, "potential.lambda.found");
2232 }
2233 }
2234 }
2236 private void checkForDeclarationAnnotations(List<? extends JCAnnotation> annotations,
2237 Symbol sym) {
2238 // Ensure that no declaration annotations are present.
2239 // Note that a tree type might be an AnnotatedType with
2240 // empty annotations, if only declaration annotations were given.
2241 // This method will raise an error for such a type.
2242 for (JCAnnotation ai : annotations) {
2243 if (typeAnnotations.annotationType(ai.attribute, sym) == TypeAnnotations.AnnotationType.DECLARATION) {
2244 log.error(ai.pos(), "annotation.type.not.applicable");
2245 }
2246 }
2247 }
2250 /** Make an attributed null check tree.
2251 */
2252 public JCExpression makeNullCheck(JCExpression arg) {
2253 // optimization: X.this is never null; skip null check
2254 Name name = TreeInfo.name(arg);
2255 if (name == names._this || name == names._super) return arg;
2257 JCTree.Tag optag = NULLCHK;
2258 JCUnary tree = make.at(arg.pos).Unary(optag, arg);
2259 tree.operator = syms.nullcheck;
2260 tree.type = arg.type;
2261 return tree;
2262 }
2264 public void visitNewArray(JCNewArray tree) {
2265 Type owntype = types.createErrorType(tree.type);
2266 Env<AttrContext> localEnv = env.dup(tree);
2267 Type elemtype;
2268 if (tree.elemtype != null) {
2269 elemtype = attribType(tree.elemtype, localEnv);
2270 chk.validate(tree.elemtype, localEnv);
2271 owntype = elemtype;
2272 for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
2273 attribExpr(l.head, localEnv, syms.intType);
2274 owntype = new ArrayType(owntype, syms.arrayClass);
2275 }
2276 if (tree.elemtype.hasTag(ANNOTATED_TYPE)) {
2277 checkForDeclarationAnnotations(((JCAnnotatedType) tree.elemtype).annotations,
2278 tree.elemtype.type.tsym);
2279 }
2280 } else {
2281 // we are seeing an untyped aggregate { ... }
2282 // this is allowed only if the prototype is an array
2283 if (pt().hasTag(ARRAY)) {
2284 elemtype = types.elemtype(pt());
2285 } else {
2286 if (!pt().hasTag(ERROR)) {
2287 log.error(tree.pos(), "illegal.initializer.for.type",
2288 pt());
2289 }
2290 elemtype = types.createErrorType(pt());
2291 }
2292 }
2293 if (tree.elems != null) {
2294 attribExprs(tree.elems, localEnv, elemtype);
2295 owntype = new ArrayType(elemtype, syms.arrayClass);
2296 }
2297 if (!types.isReifiable(elemtype))
2298 log.error(tree.pos(), "generic.array.creation");
2299 result = check(tree, owntype, VAL, resultInfo);
2300 }
2302 /*
2303 * A lambda expression can only be attributed when a target-type is available.
2304 * In addition, if the target-type is that of a functional interface whose
2305 * descriptor contains inference variables in argument position the lambda expression
2306 * is 'stuck' (see DeferredAttr).
2307 */
2308 @Override
2309 public void visitLambda(final JCLambda that) {
2310 if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
2311 if (pt().hasTag(NONE)) {
2312 //lambda only allowed in assignment or method invocation/cast context
2313 log.error(that.pos(), "unexpected.lambda");
2314 }
2315 result = that.type = types.createErrorType(pt());
2316 return;
2317 }
2318 //create an environment for attribution of the lambda expression
2319 final Env<AttrContext> localEnv = lambdaEnv(that, env);
2320 boolean needsRecovery =
2321 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK;
2322 try {
2323 Type currentTarget = pt();
2324 List<Type> explicitParamTypes = null;
2325 if (that.paramKind == JCLambda.ParameterKind.EXPLICIT) {
2326 //attribute lambda parameters
2327 attribStats(that.params, localEnv);
2328 explicitParamTypes = TreeInfo.types(that.params);
2329 }
2331 Type lambdaType;
2332 if (pt() != Type.recoveryType) {
2333 /* We need to adjust the target. If the target is an
2334 * intersection type, for example: SAM & I1 & I2 ...
2335 * the target will be updated to SAM
2336 */
2337 currentTarget = targetChecker.visit(currentTarget, that);
2338 if (explicitParamTypes != null) {
2339 currentTarget = infer.instantiateFunctionalInterface(that,
2340 currentTarget, explicitParamTypes, resultInfo.checkContext);
2341 }
2342 lambdaType = types.findDescriptorType(currentTarget);
2343 } else {
2344 currentTarget = Type.recoveryType;
2345 lambdaType = fallbackDescriptorType(that);
2346 }
2348 setFunctionalInfo(localEnv, that, pt(), lambdaType, currentTarget, resultInfo.checkContext);
2350 if (lambdaType.hasTag(FORALL)) {
2351 //lambda expression target desc cannot be a generic method
2352 resultInfo.checkContext.report(that, diags.fragment("invalid.generic.lambda.target",
2353 lambdaType, kindName(currentTarget.tsym), currentTarget.tsym));
2354 result = that.type = types.createErrorType(pt());
2355 return;
2356 }
2358 if (that.paramKind == JCLambda.ParameterKind.IMPLICIT) {
2359 //add param type info in the AST
2360 List<Type> actuals = lambdaType.getParameterTypes();
2361 List<JCVariableDecl> params = that.params;
2363 boolean arityMismatch = false;
2365 while (params.nonEmpty()) {
2366 if (actuals.isEmpty()) {
2367 //not enough actuals to perform lambda parameter inference
2368 arityMismatch = true;
2369 }
2370 //reset previously set info
2371 Type argType = arityMismatch ?
2372 syms.errType :
2373 actuals.head;
2374 params.head.vartype = make.at(params.head).Type(argType);
2375 params.head.sym = null;
2376 actuals = actuals.isEmpty() ?
2377 actuals :
2378 actuals.tail;
2379 params = params.tail;
2380 }
2382 //attribute lambda parameters
2383 attribStats(that.params, localEnv);
2385 if (arityMismatch) {
2386 resultInfo.checkContext.report(that, diags.fragment("incompatible.arg.types.in.lambda"));
2387 result = that.type = types.createErrorType(currentTarget);
2388 return;
2389 }
2390 }
2392 //from this point on, no recovery is needed; if we are in assignment context
2393 //we will be able to attribute the whole lambda body, regardless of errors;
2394 //if we are in a 'check' method context, and the lambda is not compatible
2395 //with the target-type, it will be recovered anyway in Attr.checkId
2396 needsRecovery = false;
2398 FunctionalReturnContext funcContext = that.getBodyKind() == JCLambda.BodyKind.EXPRESSION ?
2399 new ExpressionLambdaReturnContext((JCExpression)that.getBody(), resultInfo.checkContext) :
2400 new FunctionalReturnContext(resultInfo.checkContext);
2402 ResultInfo bodyResultInfo = lambdaType.getReturnType() == Type.recoveryType ?
2403 recoveryInfo :
2404 new ResultInfo(VAL, lambdaType.getReturnType(), funcContext);
2405 localEnv.info.returnResult = bodyResultInfo;
2407 if (that.getBodyKind() == JCLambda.BodyKind.EXPRESSION) {
2408 attribTree(that.getBody(), localEnv, bodyResultInfo);
2409 } else {
2410 JCBlock body = (JCBlock)that.body;
2411 attribStats(body.stats, localEnv);
2412 }
2414 result = check(that, currentTarget, VAL, resultInfo);
2416 boolean isSpeculativeRound =
2417 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
2419 preFlow(that);
2420 flow.analyzeLambda(env, that, make, isSpeculativeRound);
2422 checkLambdaCompatible(that, lambdaType, resultInfo.checkContext);
2424 if (!isSpeculativeRound) {
2425 //add thrown types as bounds to the thrown types free variables if needed:
2426 if (resultInfo.checkContext.inferenceContext().free(lambdaType.getThrownTypes())) {
2427 List<Type> inferredThrownTypes = flow.analyzeLambdaThrownTypes(env, that, make);
2428 List<Type> thrownTypes = resultInfo.checkContext.inferenceContext().asFree(lambdaType.getThrownTypes());
2430 chk.unhandled(inferredThrownTypes, thrownTypes);
2431 }
2433 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), lambdaType, currentTarget);
2434 }
2435 result = check(that, currentTarget, VAL, resultInfo);
2436 } catch (Types.FunctionDescriptorLookupError ex) {
2437 JCDiagnostic cause = ex.getDiagnostic();
2438 resultInfo.checkContext.report(that, cause);
2439 result = that.type = types.createErrorType(pt());
2440 return;
2441 } finally {
2442 localEnv.info.scope.leave();
2443 if (needsRecovery) {
2444 attribTree(that, env, recoveryInfo);
2445 }
2446 }
2447 }
2448 //where
2449 void preFlow(JCLambda tree) {
2450 new PostAttrAnalyzer() {
2451 @Override
2452 public void scan(JCTree tree) {
2453 if (tree == null ||
2454 (tree.type != null &&
2455 tree.type == Type.stuckType)) {
2456 //don't touch stuck expressions!
2457 return;
2458 }
2459 super.scan(tree);
2460 }
2461 }.scan(tree);
2462 }
2464 Types.MapVisitor<DiagnosticPosition> targetChecker = new Types.MapVisitor<DiagnosticPosition>() {
2466 @Override
2467 public Type visitClassType(ClassType t, DiagnosticPosition pos) {
2468 return t.isCompound() ?
2469 visitIntersectionClassType((IntersectionClassType)t, pos) : t;
2470 }
2472 public Type visitIntersectionClassType(IntersectionClassType ict, DiagnosticPosition pos) {
2473 Symbol desc = types.findDescriptorSymbol(makeNotionalInterface(ict));
2474 Type target = null;
2475 for (Type bound : ict.getExplicitComponents()) {
2476 TypeSymbol boundSym = bound.tsym;
2477 if (types.isFunctionalInterface(boundSym) &&
2478 types.findDescriptorSymbol(boundSym) == desc) {
2479 target = bound;
2480 } else if (!boundSym.isInterface() || (boundSym.flags() & ANNOTATION) != 0) {
2481 //bound must be an interface
2482 reportIntersectionError(pos, "not.an.intf.component", boundSym);
2483 }
2484 }
2485 return target != null ?
2486 target :
2487 ict.getExplicitComponents().head; //error recovery
2488 }
2490 private TypeSymbol makeNotionalInterface(IntersectionClassType ict) {
2491 ListBuffer<Type> targs = new ListBuffer<>();
2492 ListBuffer<Type> supertypes = new ListBuffer<>();
2493 for (Type i : ict.interfaces_field) {
2494 if (i.isParameterized()) {
2495 targs.appendList(i.tsym.type.allparams());
2496 }
2497 supertypes.append(i.tsym.type);
2498 }
2499 IntersectionClassType notionalIntf =
2500 (IntersectionClassType)types.makeCompoundType(supertypes.toList());
2501 notionalIntf.allparams_field = targs.toList();
2502 notionalIntf.tsym.flags_field |= INTERFACE;
2503 return notionalIntf.tsym;
2504 }
2506 private void reportIntersectionError(DiagnosticPosition pos, String key, Object... args) {
2507 resultInfo.checkContext.report(pos, diags.fragment("bad.intersection.target.for.functional.expr",
2508 diags.fragment(key, args)));
2509 }
2510 };
2512 private Type fallbackDescriptorType(JCExpression tree) {
2513 switch (tree.getTag()) {
2514 case LAMBDA:
2515 JCLambda lambda = (JCLambda)tree;
2516 List<Type> argtypes = List.nil();
2517 for (JCVariableDecl param : lambda.params) {
2518 argtypes = param.vartype != null ?
2519 argtypes.append(param.vartype.type) :
2520 argtypes.append(syms.errType);
2521 }
2522 return new MethodType(argtypes, Type.recoveryType,
2523 List.of(syms.throwableType), syms.methodClass);
2524 case REFERENCE:
2525 return new MethodType(List.<Type>nil(), Type.recoveryType,
2526 List.of(syms.throwableType), syms.methodClass);
2527 default:
2528 Assert.error("Cannot get here!");
2529 }
2530 return null;
2531 }
2533 private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
2534 final InferenceContext inferenceContext, final Type... ts) {
2535 checkAccessibleTypes(pos, env, inferenceContext, List.from(ts));
2536 }
2538 private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
2539 final InferenceContext inferenceContext, final List<Type> ts) {
2540 if (inferenceContext.free(ts)) {
2541 inferenceContext.addFreeTypeListener(ts, new FreeTypeListener() {
2542 @Override
2543 public void typesInferred(InferenceContext inferenceContext) {
2544 checkAccessibleTypes(pos, env, inferenceContext, inferenceContext.asInstTypes(ts));
2545 }
2546 });
2547 } else {
2548 for (Type t : ts) {
2549 rs.checkAccessibleType(env, t);
2550 }
2551 }
2552 }
2554 /**
2555 * Lambda/method reference have a special check context that ensures
2556 * that i.e. a lambda return type is compatible with the expected
2557 * type according to both the inherited context and the assignment
2558 * context.
2559 */
2560 class FunctionalReturnContext extends Check.NestedCheckContext {
2562 FunctionalReturnContext(CheckContext enclosingContext) {
2563 super(enclosingContext);
2564 }
2566 @Override
2567 public boolean compatible(Type found, Type req, Warner warn) {
2568 //return type must be compatible in both current context and assignment context
2569 return chk.basicHandler.compatible(found, inferenceContext().asFree(req), warn);
2570 }
2572 @Override
2573 public void report(DiagnosticPosition pos, JCDiagnostic details) {
2574 enclosingContext.report(pos, diags.fragment("incompatible.ret.type.in.lambda", details));
2575 }
2576 }
2578 class ExpressionLambdaReturnContext extends FunctionalReturnContext {
2580 JCExpression expr;
2582 ExpressionLambdaReturnContext(JCExpression expr, CheckContext enclosingContext) {
2583 super(enclosingContext);
2584 this.expr = expr;
2585 }
2587 @Override
2588 public boolean compatible(Type found, Type req, Warner warn) {
2589 //a void return is compatible with an expression statement lambda
2590 return TreeInfo.isExpressionStatement(expr) && req.hasTag(VOID) ||
2591 super.compatible(found, req, warn);
2592 }
2593 }
2595 /**
2596 * Lambda compatibility. Check that given return types, thrown types, parameter types
2597 * are compatible with the expected functional interface descriptor. This means that:
2598 * (i) parameter types must be identical to those of the target descriptor; (ii) return
2599 * types must be compatible with the return type of the expected descriptor.
2600 */
2601 private void checkLambdaCompatible(JCLambda tree, Type descriptor, CheckContext checkContext) {
2602 Type returnType = checkContext.inferenceContext().asFree(descriptor.getReturnType());
2604 //return values have already been checked - but if lambda has no return
2605 //values, we must ensure that void/value compatibility is correct;
2606 //this amounts at checking that, if a lambda body can complete normally,
2607 //the descriptor's return type must be void
2608 if (tree.getBodyKind() == JCLambda.BodyKind.STATEMENT && tree.canCompleteNormally &&
2609 !returnType.hasTag(VOID) && returnType != Type.recoveryType) {
2610 checkContext.report(tree, diags.fragment("incompatible.ret.type.in.lambda",
2611 diags.fragment("missing.ret.val", returnType)));
2612 }
2614 List<Type> argTypes = checkContext.inferenceContext().asFree(descriptor.getParameterTypes());
2615 if (!types.isSameTypes(argTypes, TreeInfo.types(tree.params))) {
2616 checkContext.report(tree, diags.fragment("incompatible.arg.types.in.lambda"));
2617 }
2618 }
2620 private Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) {
2621 Env<AttrContext> lambdaEnv;
2622 Symbol owner = env.info.scope.owner;
2623 if (owner.kind == VAR && owner.owner.kind == TYP) {
2624 //field initializer
2625 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared()));
2626 lambdaEnv.info.scope.owner =
2627 new MethodSymbol((owner.flags() & STATIC) | BLOCK, names.empty, null,
2628 env.info.scope.owner);
2629 } else {
2630 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dup()));
2631 }
2632 return lambdaEnv;
2633 }
2635 @Override
2636 public void visitReference(final JCMemberReference that) {
2637 if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
2638 if (pt().hasTag(NONE)) {
2639 //method reference only allowed in assignment or method invocation/cast context
2640 log.error(that.pos(), "unexpected.mref");
2641 }
2642 result = that.type = types.createErrorType(pt());
2643 return;
2644 }
2645 final Env<AttrContext> localEnv = env.dup(that);
2646 try {
2647 //attribute member reference qualifier - if this is a constructor
2648 //reference, the expected kind must be a type
2649 Type exprType = attribTree(that.expr, env, memberReferenceQualifierResult(that));
2651 if (that.getMode() == JCMemberReference.ReferenceMode.NEW) {
2652 exprType = chk.checkConstructorRefType(that.expr, exprType);
2653 if (!exprType.isErroneous() &&
2654 exprType.isRaw() &&
2655 that.typeargs != null) {
2656 log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
2657 diags.fragment("mref.infer.and.explicit.params"));
2658 exprType = types.createErrorType(exprType);
2659 }
2660 }
2662 if (exprType.isErroneous()) {
2663 //if the qualifier expression contains problems,
2664 //give up attribution of method reference
2665 result = that.type = exprType;
2666 return;
2667 }
2669 if (TreeInfo.isStaticSelector(that.expr, names)) {
2670 //if the qualifier is a type, validate it; raw warning check is
2671 //omitted as we don't know at this stage as to whether this is a
2672 //raw selector (because of inference)
2673 chk.validate(that.expr, env, false);
2674 }
2676 //attrib type-arguments
2677 List<Type> typeargtypes = List.nil();
2678 if (that.typeargs != null) {
2679 typeargtypes = attribTypes(that.typeargs, localEnv);
2680 }
2682 Type target;
2683 Type desc;
2684 if (pt() != Type.recoveryType) {
2685 target = targetChecker.visit(pt(), that);
2686 desc = types.findDescriptorType(target);
2687 } else {
2688 target = Type.recoveryType;
2689 desc = fallbackDescriptorType(that);
2690 }
2692 setFunctionalInfo(localEnv, that, pt(), desc, target, resultInfo.checkContext);
2693 List<Type> argtypes = desc.getParameterTypes();
2694 Resolve.MethodCheck referenceCheck = rs.resolveMethodCheck;
2696 if (resultInfo.checkContext.inferenceContext().free(argtypes)) {
2697 referenceCheck = rs.new MethodReferenceCheck(resultInfo.checkContext.inferenceContext());
2698 }
2700 Pair<Symbol, Resolve.ReferenceLookupHelper> refResult = null;
2701 List<Type> saved_undet = resultInfo.checkContext.inferenceContext().save();
2702 try {
2703 refResult = rs.resolveMemberReference(that.pos(), localEnv, that, that.expr.type,
2704 that.name, argtypes, typeargtypes, true, referenceCheck,
2705 resultInfo.checkContext.inferenceContext());
2706 } finally {
2707 resultInfo.checkContext.inferenceContext().rollback(saved_undet);
2708 }
2710 Symbol refSym = refResult.fst;
2711 Resolve.ReferenceLookupHelper lookupHelper = refResult.snd;
2713 if (refSym.kind != MTH) {
2714 boolean targetError;
2715 switch (refSym.kind) {
2716 case ABSENT_MTH:
2717 targetError = false;
2718 break;
2719 case WRONG_MTH:
2720 case WRONG_MTHS:
2721 case AMBIGUOUS:
2722 case HIDDEN:
2723 case STATICERR:
2724 case MISSING_ENCL:
2725 targetError = true;
2726 break;
2727 default:
2728 Assert.error("unexpected result kind " + refSym.kind);
2729 targetError = false;
2730 }
2732 JCDiagnostic detailsDiag = ((Resolve.ResolveError)refSym).getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT,
2733 that, exprType.tsym, exprType, that.name, argtypes, typeargtypes);
2735 JCDiagnostic.DiagnosticType diagKind = targetError ?
2736 JCDiagnostic.DiagnosticType.FRAGMENT : JCDiagnostic.DiagnosticType.ERROR;
2738 JCDiagnostic diag = diags.create(diagKind, log.currentSource(), that,
2739 "invalid.mref", Kinds.kindName(that.getMode()), detailsDiag);
2741 if (targetError && target == Type.recoveryType) {
2742 //a target error doesn't make sense during recovery stage
2743 //as we don't know what actual parameter types are
2744 result = that.type = target;
2745 return;
2746 } else {
2747 if (targetError) {
2748 resultInfo.checkContext.report(that, diag);
2749 } else {
2750 log.report(diag);
2751 }
2752 result = that.type = types.createErrorType(target);
2753 return;
2754 }
2755 }
2757 that.sym = refSym.baseSymbol();
2758 that.kind = lookupHelper.referenceKind(that.sym);
2759 that.ownerAccessible = rs.isAccessible(localEnv, that.sym.enclClass());
2761 if (desc.getReturnType() == Type.recoveryType) {
2762 // stop here
2763 result = that.type = target;
2764 return;
2765 }
2767 if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
2769 if (that.getMode() == ReferenceMode.INVOKE &&
2770 TreeInfo.isStaticSelector(that.expr, names) &&
2771 that.kind.isUnbound() &&
2772 !desc.getParameterTypes().head.isParameterized()) {
2773 chk.checkRaw(that.expr, localEnv);
2774 }
2776 if (!that.kind.isUnbound() &&
2777 that.getMode() == ReferenceMode.INVOKE &&
2778 TreeInfo.isStaticSelector(that.expr, names) &&
2779 !that.sym.isStatic()) {
2780 log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
2781 diags.fragment("non-static.cant.be.ref", Kinds.kindName(refSym), refSym));
2782 result = that.type = types.createErrorType(target);
2783 return;
2784 }
2786 if (that.kind.isUnbound() &&
2787 that.getMode() == ReferenceMode.INVOKE &&
2788 TreeInfo.isStaticSelector(that.expr, names) &&
2789 that.sym.isStatic()) {
2790 log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
2791 diags.fragment("static.method.in.unbound.lookup", Kinds.kindName(refSym), refSym));
2792 result = that.type = types.createErrorType(target);
2793 return;
2794 }
2796 if (that.sym.isStatic() && TreeInfo.isStaticSelector(that.expr, names) &&
2797 exprType.getTypeArguments().nonEmpty()) {
2798 //static ref with class type-args
2799 log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
2800 diags.fragment("static.mref.with.targs"));
2801 result = that.type = types.createErrorType(target);
2802 return;
2803 }
2805 if (that.sym.isStatic() && !TreeInfo.isStaticSelector(that.expr, names) &&
2806 !that.kind.isUnbound()) {
2807 //no static bound mrefs
2808 log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
2809 diags.fragment("static.bound.mref"));
2810 result = that.type = types.createErrorType(target);
2811 return;
2812 }
2814 if (!refSym.isStatic() && that.kind == JCMemberReference.ReferenceKind.SUPER) {
2815 // Check that super-qualified symbols are not abstract (JLS)
2816 rs.checkNonAbstract(that.pos(), that.sym);
2817 }
2818 }
2820 ResultInfo checkInfo =
2821 resultInfo.dup(newMethodTemplate(
2822 desc.getReturnType().hasTag(VOID) ? Type.noType : desc.getReturnType(),
2823 that.kind.isUnbound() ? argtypes.tail : argtypes, typeargtypes));
2825 Type refType = checkId(that, lookupHelper.site, refSym, localEnv, checkInfo);
2827 if (that.kind.isUnbound() &&
2828 resultInfo.checkContext.inferenceContext().free(argtypes.head)) {
2829 //re-generate inference constraints for unbound receiver
2830 if (!types.isSubtype(resultInfo.checkContext.inferenceContext().asFree(argtypes.head), exprType)) {
2831 //cannot happen as this has already been checked - we just need
2832 //to regenerate the inference constraints, as that has been lost
2833 //as a result of the call to inferenceContext.save()
2834 Assert.error("Can't get here");
2835 }
2836 }
2838 if (!refType.isErroneous()) {
2839 refType = types.createMethodTypeWithReturn(refType,
2840 adjustMethodReturnType(lookupHelper.site, that.name, checkInfo.pt.getParameterTypes(), refType.getReturnType()));
2841 }
2843 //go ahead with standard method reference compatibility check - note that param check
2844 //is a no-op (as this has been taken care during method applicability)
2845 boolean isSpeculativeRound =
2846 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
2847 checkReferenceCompatible(that, desc, refType, resultInfo.checkContext, isSpeculativeRound);
2848 if (!isSpeculativeRound) {
2849 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), desc, target);
2850 }
2851 result = check(that, target, VAL, resultInfo);
2852 } catch (Types.FunctionDescriptorLookupError ex) {
2853 JCDiagnostic cause = ex.getDiagnostic();
2854 resultInfo.checkContext.report(that, cause);
2855 result = that.type = types.createErrorType(pt());
2856 return;
2857 }
2858 }
2859 //where
2860 ResultInfo memberReferenceQualifierResult(JCMemberReference tree) {
2861 //if this is a constructor reference, the expected kind must be a type
2862 return new ResultInfo(tree.getMode() == ReferenceMode.INVOKE ? VAL | TYP : TYP, Type.noType);
2863 }
2866 @SuppressWarnings("fallthrough")
2867 void checkReferenceCompatible(JCMemberReference tree, Type descriptor, Type refType, CheckContext checkContext, boolean speculativeAttr) {
2868 Type returnType = checkContext.inferenceContext().asFree(descriptor.getReturnType());
2870 Type resType;
2871 switch (tree.getMode()) {
2872 case NEW:
2873 if (!tree.expr.type.isRaw()) {
2874 resType = tree.expr.type;
2875 break;
2876 }
2877 default:
2878 resType = refType.getReturnType();
2879 }
2881 Type incompatibleReturnType = resType;
2883 if (returnType.hasTag(VOID)) {
2884 incompatibleReturnType = null;
2885 }
2887 if (!returnType.hasTag(VOID) && !resType.hasTag(VOID)) {
2888 if (resType.isErroneous() ||
2889 new FunctionalReturnContext(checkContext).compatible(resType, returnType, types.noWarnings)) {
2890 incompatibleReturnType = null;
2891 }
2892 }
2894 if (incompatibleReturnType != null) {
2895 checkContext.report(tree, diags.fragment("incompatible.ret.type.in.mref",
2896 diags.fragment("inconvertible.types", resType, descriptor.getReturnType())));
2897 }
2899 if (!speculativeAttr) {
2900 List<Type> thrownTypes = checkContext.inferenceContext().asFree(descriptor.getThrownTypes());
2901 if (chk.unhandled(refType.getThrownTypes(), thrownTypes).nonEmpty()) {
2902 log.error(tree, "incompatible.thrown.types.in.mref", refType.getThrownTypes());
2903 }
2904 }
2905 }
2907 /**
2908 * Set functional type info on the underlying AST. Note: as the target descriptor
2909 * might contain inference variables, we might need to register an hook in the
2910 * current inference context.
2911 */
2912 private void setFunctionalInfo(final Env<AttrContext> env, final JCFunctionalExpression fExpr,
2913 final Type pt, final Type descriptorType, final Type primaryTarget, final CheckContext checkContext) {
2914 if (checkContext.inferenceContext().free(descriptorType)) {
2915 checkContext.inferenceContext().addFreeTypeListener(List.of(pt, descriptorType), new FreeTypeListener() {
2916 public void typesInferred(InferenceContext inferenceContext) {
2917 setFunctionalInfo(env, fExpr, pt, inferenceContext.asInstType(descriptorType),
2918 inferenceContext.asInstType(primaryTarget), checkContext);
2919 }
2920 });
2921 } else {
2922 ListBuffer<Type> targets = new ListBuffer<>();
2923 if (pt.hasTag(CLASS)) {
2924 if (pt.isCompound()) {
2925 targets.append(types.removeWildcards(primaryTarget)); //this goes first
2926 for (Type t : ((IntersectionClassType)pt()).interfaces_field) {
2927 if (t != primaryTarget) {
2928 targets.append(types.removeWildcards(t));
2929 }
2930 }
2931 } else {
2932 targets.append(types.removeWildcards(primaryTarget));
2933 }
2934 }
2935 fExpr.targets = targets.toList();
2936 if (checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
2937 pt != Type.recoveryType) {
2938 //check that functional interface class is well-formed
2939 ClassSymbol csym = types.makeFunctionalInterfaceClass(env,
2940 names.empty, List.of(fExpr.targets.head), ABSTRACT);
2941 if (csym != null) {
2942 chk.checkImplementations(env.tree, csym, csym);
2943 }
2944 }
2945 }
2946 }
2948 public void visitParens(JCParens tree) {
2949 Type owntype = attribTree(tree.expr, env, resultInfo);
2950 result = check(tree, owntype, pkind(), resultInfo);
2951 Symbol sym = TreeInfo.symbol(tree);
2952 if (sym != null && (sym.kind&(TYP|PCK)) != 0)
2953 log.error(tree.pos(), "illegal.start.of.type");
2954 }
2956 public void visitAssign(JCAssign tree) {
2957 Type owntype = attribTree(tree.lhs, env.dup(tree), varInfo);
2958 Type capturedType = capture(owntype);
2959 attribExpr(tree.rhs, env, owntype);
2960 result = check(tree, capturedType, VAL, resultInfo);
2961 }
2963 public void visitAssignop(JCAssignOp tree) {
2964 // Attribute arguments.
2965 Type owntype = attribTree(tree.lhs, env, varInfo);
2966 Type operand = attribExpr(tree.rhs, env);
2967 // Find operator.
2968 Symbol operator = tree.operator = rs.resolveBinaryOperator(
2969 tree.pos(), tree.getTag().noAssignOp(), env,
2970 owntype, operand);
2972 if (operator.kind == MTH &&
2973 !owntype.isErroneous() &&
2974 !operand.isErroneous()) {
2975 chk.checkOperator(tree.pos(),
2976 (OperatorSymbol)operator,
2977 tree.getTag().noAssignOp(),
2978 owntype,
2979 operand);
2980 chk.checkDivZero(tree.rhs.pos(), operator, operand);
2981 chk.checkCastable(tree.rhs.pos(),
2982 operator.type.getReturnType(),
2983 owntype);
2984 }
2985 result = check(tree, owntype, VAL, resultInfo);
2986 }
2988 public void visitUnary(JCUnary tree) {
2989 // Attribute arguments.
2990 Type argtype = (tree.getTag().isIncOrDecUnaryOp())
2991 ? attribTree(tree.arg, env, varInfo)
2992 : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
2994 // Find operator.
2995 Symbol operator = tree.operator =
2996 rs.resolveUnaryOperator(tree.pos(), tree.getTag(), env, argtype);
2998 Type owntype = types.createErrorType(tree.type);
2999 if (operator.kind == MTH &&
3000 !argtype.isErroneous()) {
3001 owntype = (tree.getTag().isIncOrDecUnaryOp())
3002 ? tree.arg.type
3003 : operator.type.getReturnType();
3004 int opc = ((OperatorSymbol)operator).opcode;
3006 // If the argument is constant, fold it.
3007 if (argtype.constValue() != null) {
3008 Type ctype = cfolder.fold1(opc, argtype);
3009 if (ctype != null) {
3010 owntype = cfolder.coerce(ctype, owntype);
3012 // Remove constant types from arguments to
3013 // conserve space. The parser will fold concatenations
3014 // of string literals; the code here also
3015 // gets rid of intermediate results when some of the
3016 // operands are constant identifiers.
3017 if (tree.arg.type.tsym == syms.stringType.tsym) {
3018 tree.arg.type = syms.stringType;
3019 }
3020 }
3021 }
3022 }
3023 result = check(tree, owntype, VAL, resultInfo);
3024 }
3026 public void visitBinary(JCBinary tree) {
3027 // Attribute arguments.
3028 Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
3029 Type right = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.rhs, env));
3031 // Find operator.
3032 Symbol operator = tree.operator =
3033 rs.resolveBinaryOperator(tree.pos(), tree.getTag(), env, left, right);
3035 Type owntype = types.createErrorType(tree.type);
3036 if (operator.kind == MTH &&
3037 !left.isErroneous() &&
3038 !right.isErroneous()) {
3039 owntype = operator.type.getReturnType();
3040 // This will figure out when unboxing can happen and
3041 // choose the right comparison operator.
3042 int opc = chk.checkOperator(tree.lhs.pos(),
3043 (OperatorSymbol)operator,
3044 tree.getTag(),
3045 left,
3046 right);
3048 // If both arguments are constants, fold them.
3049 if (left.constValue() != null && right.constValue() != null) {
3050 Type ctype = cfolder.fold2(opc, left, right);
3051 if (ctype != null) {
3052 owntype = cfolder.coerce(ctype, owntype);
3054 // Remove constant types from arguments to
3055 // conserve space. The parser will fold concatenations
3056 // of string literals; the code here also
3057 // gets rid of intermediate results when some of the
3058 // operands are constant identifiers.
3059 if (tree.lhs.type.tsym == syms.stringType.tsym) {
3060 tree.lhs.type = syms.stringType;
3061 }
3062 if (tree.rhs.type.tsym == syms.stringType.tsym) {
3063 tree.rhs.type = syms.stringType;
3064 }
3065 }
3066 }
3068 // Check that argument types of a reference ==, != are
3069 // castable to each other, (JLS 15.21). Note: unboxing
3070 // comparisons will not have an acmp* opc at this point.
3071 if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
3072 if (!types.isEqualityComparable(left, right,
3073 new Warner(tree.pos()))) {
3074 log.error(tree.pos(), "incomparable.types", left, right);
3075 }
3076 }
3078 chk.checkDivZero(tree.rhs.pos(), operator, right);
3079 }
3080 result = check(tree, owntype, VAL, resultInfo);
3081 }
3083 public void visitTypeCast(final JCTypeCast tree) {
3084 Type clazztype = attribType(tree.clazz, env);
3085 chk.validate(tree.clazz, env, false);
3086 //a fresh environment is required for 292 inference to work properly ---
3087 //see Infer.instantiatePolymorphicSignatureInstance()
3088 Env<AttrContext> localEnv = env.dup(tree);
3089 //should we propagate the target type?
3090 final ResultInfo castInfo;
3091 JCExpression expr = TreeInfo.skipParens(tree.expr);
3092 boolean isPoly = allowPoly && (expr.hasTag(LAMBDA) || expr.hasTag(REFERENCE));
3093 if (isPoly) {
3094 //expression is a poly - we need to propagate target type info
3095 castInfo = new ResultInfo(VAL, clazztype, new Check.NestedCheckContext(resultInfo.checkContext) {
3096 @Override
3097 public boolean compatible(Type found, Type req, Warner warn) {
3098 return types.isCastable(found, req, warn);
3099 }
3100 });
3101 } else {
3102 //standalone cast - target-type info is not propagated
3103 castInfo = unknownExprInfo;
3104 }
3105 Type exprtype = attribTree(tree.expr, localEnv, castInfo);
3106 Type owntype = isPoly ? clazztype : chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
3107 if (exprtype.constValue() != null)
3108 owntype = cfolder.coerce(exprtype, owntype);
3109 result = check(tree, capture(owntype), VAL, resultInfo);
3110 if (!isPoly)
3111 chk.checkRedundantCast(localEnv, tree);
3112 }
3114 public void visitTypeTest(JCInstanceOf tree) {
3115 Type exprtype = chk.checkNullOrRefType(
3116 tree.expr.pos(), attribExpr(tree.expr, env));
3117 Type clazztype = attribType(tree.clazz, env);
3118 if (!clazztype.hasTag(TYPEVAR)) {
3119 clazztype = chk.checkClassOrArrayType(tree.clazz.pos(), clazztype);
3120 }
3121 if (!clazztype.isErroneous() && !types.isReifiable(clazztype)) {
3122 log.error(tree.clazz.pos(), "illegal.generic.type.for.instof");
3123 clazztype = types.createErrorType(clazztype);
3124 }
3125 chk.validate(tree.clazz, env, false);
3126 chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
3127 result = check(tree, syms.booleanType, VAL, resultInfo);
3128 }
3130 public void visitIndexed(JCArrayAccess tree) {
3131 Type owntype = types.createErrorType(tree.type);
3132 Type atype = attribExpr(tree.indexed, env);
3133 attribExpr(tree.index, env, syms.intType);
3134 if (types.isArray(atype))
3135 owntype = types.elemtype(atype);
3136 else if (!atype.hasTag(ERROR))
3137 log.error(tree.pos(), "array.req.but.found", atype);
3138 if ((pkind() & VAR) == 0) owntype = capture(owntype);
3139 result = check(tree, owntype, VAR, resultInfo);
3140 }
3142 public void visitIdent(JCIdent tree) {
3143 Symbol sym;
3145 // Find symbol
3146 if (pt().hasTag(METHOD) || pt().hasTag(FORALL)) {
3147 // If we are looking for a method, the prototype `pt' will be a
3148 // method type with the type of the call's arguments as parameters.
3149 env.info.pendingResolutionPhase = null;
3150 sym = rs.resolveMethod(tree.pos(), env, tree.name, pt().getParameterTypes(), pt().getTypeArguments());
3151 } else if (tree.sym != null && tree.sym.kind != VAR) {
3152 sym = tree.sym;
3153 } else {
3154 sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind());
3155 }
3156 tree.sym = sym;
3158 // (1) Also find the environment current for the class where
3159 // sym is defined (`symEnv').
3160 // Only for pre-tiger versions (1.4 and earlier):
3161 // (2) Also determine whether we access symbol out of an anonymous
3162 // class in a this or super call. This is illegal for instance
3163 // members since such classes don't carry a this$n link.
3164 // (`noOuterThisPath').
3165 Env<AttrContext> symEnv = env;
3166 boolean noOuterThisPath = false;
3167 if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
3168 (sym.kind & (VAR | MTH | TYP)) != 0 &&
3169 sym.owner.kind == TYP &&
3170 tree.name != names._this && tree.name != names._super) {
3172 // Find environment in which identifier is defined.
3173 while (symEnv.outer != null &&
3174 !sym.isMemberOf(symEnv.enclClass.sym, types)) {
3175 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
3176 noOuterThisPath = !allowAnonOuterThis;
3177 symEnv = symEnv.outer;
3178 }
3179 }
3181 // If symbol is a variable, ...
3182 if (sym.kind == VAR) {
3183 VarSymbol v = (VarSymbol)sym;
3185 // ..., evaluate its initializer, if it has one, and check for
3186 // illegal forward reference.
3187 checkInit(tree, env, v, false);
3189 // If we are expecting a variable (as opposed to a value), check
3190 // that the variable is assignable in the current environment.
3191 if (pkind() == VAR)
3192 checkAssignable(tree.pos(), v, null, env);
3193 }
3195 // In a constructor body,
3196 // if symbol is a field or instance method, check that it is
3197 // not accessed before the supertype constructor is called.
3198 if ((symEnv.info.isSelfCall || noOuterThisPath) &&
3199 (sym.kind & (VAR | MTH)) != 0 &&
3200 sym.owner.kind == TYP &&
3201 (sym.flags() & STATIC) == 0) {
3202 chk.earlyRefError(tree.pos(), sym.kind == VAR ? sym : thisSym(tree.pos(), env));
3203 }
3204 Env<AttrContext> env1 = env;
3205 if (sym.kind != ERR && sym.kind != TYP && sym.owner != null && sym.owner != env1.enclClass.sym) {
3206 // If the found symbol is inaccessible, then it is
3207 // accessed through an enclosing instance. Locate this
3208 // enclosing instance:
3209 while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
3210 env1 = env1.outer;
3211 }
3212 result = checkId(tree, env1.enclClass.sym.type, sym, env, resultInfo);
3213 }
3215 public void visitSelect(JCFieldAccess tree) {
3216 // Determine the expected kind of the qualifier expression.
3217 int skind = 0;
3218 if (tree.name == names._this || tree.name == names._super ||
3219 tree.name == names._class)
3220 {
3221 skind = TYP;
3222 } else {
3223 if ((pkind() & PCK) != 0) skind = skind | PCK;
3224 if ((pkind() & TYP) != 0) skind = skind | TYP | PCK;
3225 if ((pkind() & (VAL | MTH)) != 0) skind = skind | VAL | TYP;
3226 }
3228 // Attribute the qualifier expression, and determine its symbol (if any).
3229 Type site = attribTree(tree.selected, env, new ResultInfo(skind, Infer.anyPoly));
3230 if ((pkind() & (PCK | TYP)) == 0)
3231 site = capture(site); // Capture field access
3233 // don't allow T.class T[].class, etc
3234 if (skind == TYP) {
3235 Type elt = site;
3236 while (elt.hasTag(ARRAY))
3237 elt = ((ArrayType)elt.unannotatedType()).elemtype;
3238 if (elt.hasTag(TYPEVAR)) {
3239 log.error(tree.pos(), "type.var.cant.be.deref");
3240 result = types.createErrorType(tree.type);
3241 return;
3242 }
3243 }
3245 // If qualifier symbol is a type or `super', assert `selectSuper'
3246 // for the selection. This is relevant for determining whether
3247 // protected symbols are accessible.
3248 Symbol sitesym = TreeInfo.symbol(tree.selected);
3249 boolean selectSuperPrev = env.info.selectSuper;
3250 env.info.selectSuper =
3251 sitesym != null &&
3252 sitesym.name == names._super;
3254 // Determine the symbol represented by the selection.
3255 env.info.pendingResolutionPhase = null;
3256 Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
3257 if (sym.exists() && !isType(sym) && (pkind() & (PCK | TYP)) != 0) {
3258 site = capture(site);
3259 sym = selectSym(tree, sitesym, site, env, resultInfo);
3260 }
3261 boolean varArgs = env.info.lastResolveVarargs();
3262 tree.sym = sym;
3264 if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) {
3265 while (site.hasTag(TYPEVAR)) site = site.getUpperBound();
3266 site = capture(site);
3267 }
3269 // If that symbol is a variable, ...
3270 if (sym.kind == VAR) {
3271 VarSymbol v = (VarSymbol)sym;
3273 // ..., evaluate its initializer, if it has one, and check for
3274 // illegal forward reference.
3275 checkInit(tree, env, v, true);
3277 // If we are expecting a variable (as opposed to a value), check
3278 // that the variable is assignable in the current environment.
3279 if (pkind() == VAR)
3280 checkAssignable(tree.pos(), v, tree.selected, env);
3281 }
3283 if (sitesym != null &&
3284 sitesym.kind == VAR &&
3285 ((VarSymbol)sitesym).isResourceVariable() &&
3286 sym.kind == MTH &&
3287 sym.name.equals(names.close) &&
3288 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) &&
3289 env.info.lint.isEnabled(LintCategory.TRY)) {
3290 log.warning(LintCategory.TRY, tree, "try.explicit.close.call");
3291 }
3293 // Disallow selecting a type from an expression
3294 if (isType(sym) && (sitesym==null || (sitesym.kind&(TYP|PCK)) == 0)) {
3295 tree.type = check(tree.selected, pt(),
3296 sitesym == null ? VAL : sitesym.kind, new ResultInfo(TYP|PCK, pt()));
3297 }
3299 if (isType(sitesym)) {
3300 if (sym.name == names._this) {
3301 // If `C' is the currently compiled class, check that
3302 // C.this' does not appear in a call to a super(...)
3303 if (env.info.isSelfCall &&
3304 site.tsym == env.enclClass.sym) {
3305 chk.earlyRefError(tree.pos(), sym);
3306 }
3307 } else {
3308 // Check if type-qualified fields or methods are static (JLS)
3309 if ((sym.flags() & STATIC) == 0 &&
3310 !env.next.tree.hasTag(REFERENCE) &&
3311 sym.name != names._super &&
3312 (sym.kind == VAR || sym.kind == MTH)) {
3313 rs.accessBase(rs.new StaticError(sym),
3314 tree.pos(), site, sym.name, true);
3315 }
3316 }
3317 } else if (sym.kind != ERR && (sym.flags() & STATIC) != 0 && sym.name != names._class) {
3318 // If the qualified item is not a type and the selected item is static, report
3319 // a warning. Make allowance for the class of an array type e.g. Object[].class)
3320 chk.warnStatic(tree, "static.not.qualified.by.type", Kinds.kindName(sym.kind), sym.owner);
3321 }
3323 // If we are selecting an instance member via a `super', ...
3324 if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
3326 // Check that super-qualified symbols are not abstract (JLS)
3327 rs.checkNonAbstract(tree.pos(), sym);
3329 if (site.isRaw()) {
3330 // Determine argument types for site.
3331 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
3332 if (site1 != null) site = site1;
3333 }
3334 }
3336 env.info.selectSuper = selectSuperPrev;
3337 result = checkId(tree, site, sym, env, resultInfo);
3338 }
3339 //where
3340 /** Determine symbol referenced by a Select expression,
3341 *
3342 * @param tree The select tree.
3343 * @param site The type of the selected expression,
3344 * @param env The current environment.
3345 * @param resultInfo The current result.
3346 */
3347 private Symbol selectSym(JCFieldAccess tree,
3348 Symbol location,
3349 Type site,
3350 Env<AttrContext> env,
3351 ResultInfo resultInfo) {
3352 DiagnosticPosition pos = tree.pos();
3353 Name name = tree.name;
3354 switch (site.getTag()) {
3355 case PACKAGE:
3356 return rs.accessBase(
3357 rs.findIdentInPackage(env, site.tsym, name, resultInfo.pkind),
3358 pos, location, site, name, true);
3359 case ARRAY:
3360 case CLASS:
3361 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) {
3362 return rs.resolveQualifiedMethod(
3363 pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
3364 } else if (name == names._this || name == names._super) {
3365 return rs.resolveSelf(pos, env, site.tsym, name);
3366 } else if (name == names._class) {
3367 // In this case, we have already made sure in
3368 // visitSelect that qualifier expression is a type.
3369 Type t = syms.classType;
3370 List<Type> typeargs = allowGenerics
3371 ? List.of(types.erasure(site))
3372 : List.<Type>nil();
3373 t = new ClassType(t.getEnclosingType(), typeargs, t.tsym);
3374 return new VarSymbol(
3375 STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
3376 } else {
3377 // We are seeing a plain identifier as selector.
3378 Symbol sym = rs.findIdentInType(env, site, name, resultInfo.pkind);
3379 if ((resultInfo.pkind & ERRONEOUS) == 0)
3380 sym = rs.accessBase(sym, pos, location, site, name, true);
3381 return sym;
3382 }
3383 case WILDCARD:
3384 throw new AssertionError(tree);
3385 case TYPEVAR:
3386 // Normally, site.getUpperBound() shouldn't be null.
3387 // It should only happen during memberEnter/attribBase
3388 // when determining the super type which *must* beac
3389 // done before attributing the type variables. In
3390 // other words, we are seeing this illegal program:
3391 // class B<T> extends A<T.foo> {}
3392 Symbol sym = (site.getUpperBound() != null)
3393 ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
3394 : null;
3395 if (sym == null) {
3396 log.error(pos, "type.var.cant.be.deref");
3397 return syms.errSymbol;
3398 } else {
3399 Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
3400 rs.new AccessError(env, site, sym) :
3401 sym;
3402 rs.accessBase(sym2, pos, location, site, name, true);
3403 return sym;
3404 }
3405 case ERROR:
3406 // preserve identifier names through errors
3407 return types.createErrorType(name, site.tsym, site).tsym;
3408 default:
3409 // The qualifier expression is of a primitive type -- only
3410 // .class is allowed for these.
3411 if (name == names._class) {
3412 // In this case, we have already made sure in Select that
3413 // qualifier expression is a type.
3414 Type t = syms.classType;
3415 Type arg = types.boxedClass(site).type;
3416 t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym);
3417 return new VarSymbol(
3418 STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
3419 } else {
3420 log.error(pos, "cant.deref", site);
3421 return syms.errSymbol;
3422 }
3423 }
3424 }
3426 /** Determine type of identifier or select expression and check that
3427 * (1) the referenced symbol is not deprecated
3428 * (2) the symbol's type is safe (@see checkSafe)
3429 * (3) if symbol is a variable, check that its type and kind are
3430 * compatible with the prototype and protokind.
3431 * (4) if symbol is an instance field of a raw type,
3432 * which is being assigned to, issue an unchecked warning if its
3433 * type changes under erasure.
3434 * (5) if symbol is an instance method of a raw type, issue an
3435 * unchecked warning if its argument types change under erasure.
3436 * If checks succeed:
3437 * If symbol is a constant, return its constant type
3438 * else if symbol is a method, return its result type
3439 * otherwise return its type.
3440 * Otherwise return errType.
3441 *
3442 * @param tree The syntax tree representing the identifier
3443 * @param site If this is a select, the type of the selected
3444 * expression, otherwise the type of the current class.
3445 * @param sym The symbol representing the identifier.
3446 * @param env The current environment.
3447 * @param resultInfo The expected result
3448 */
3449 Type checkId(JCTree tree,
3450 Type site,
3451 Symbol sym,
3452 Env<AttrContext> env,
3453 ResultInfo resultInfo) {
3454 return (resultInfo.pt.hasTag(FORALL) || resultInfo.pt.hasTag(METHOD)) ?
3455 checkMethodId(tree, site, sym, env, resultInfo) :
3456 checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
3457 }
3459 Type checkMethodId(JCTree tree,
3460 Type site,
3461 Symbol sym,
3462 Env<AttrContext> env,
3463 ResultInfo resultInfo) {
3464 boolean isPolymorhicSignature =
3465 (sym.baseSymbol().flags() & SIGNATURE_POLYMORPHIC) != 0;
3466 return isPolymorhicSignature ?
3467 checkSigPolyMethodId(tree, site, sym, env, resultInfo) :
3468 checkMethodIdInternal(tree, site, sym, env, resultInfo);
3469 }
3471 Type checkSigPolyMethodId(JCTree tree,
3472 Type site,
3473 Symbol sym,
3474 Env<AttrContext> env,
3475 ResultInfo resultInfo) {
3476 //recover original symbol for signature polymorphic methods
3477 checkMethodIdInternal(tree, site, sym.baseSymbol(), env, resultInfo);
3478 env.info.pendingResolutionPhase = Resolve.MethodResolutionPhase.BASIC;
3479 return sym.type;
3480 }
3482 Type checkMethodIdInternal(JCTree tree,
3483 Type site,
3484 Symbol sym,
3485 Env<AttrContext> env,
3486 ResultInfo resultInfo) {
3487 if ((resultInfo.pkind & POLY) != 0) {
3488 Type pt = resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, sym, env.info.pendingResolutionPhase));
3489 Type owntype = checkIdInternal(tree, site, sym, pt, env, resultInfo);
3490 resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
3491 return owntype;
3492 } else {
3493 return checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
3494 }
3495 }
3497 Type checkIdInternal(JCTree tree,
3498 Type site,
3499 Symbol sym,
3500 Type pt,
3501 Env<AttrContext> env,
3502 ResultInfo resultInfo) {
3503 if (pt.isErroneous()) {
3504 return types.createErrorType(site);
3505 }
3506 Type owntype; // The computed type of this identifier occurrence.
3507 switch (sym.kind) {
3508 case TYP:
3509 // For types, the computed type equals the symbol's type,
3510 // except for two situations:
3511 owntype = sym.type;
3512 if (owntype.hasTag(CLASS)) {
3513 chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym);
3514 Type ownOuter = owntype.getEnclosingType();
3516 // (a) If the symbol's type is parameterized, erase it
3517 // because no type parameters were given.
3518 // We recover generic outer type later in visitTypeApply.
3519 if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
3520 owntype = types.erasure(owntype);
3521 }
3523 // (b) If the symbol's type is an inner class, then
3524 // we have to interpret its outer type as a superclass
3525 // of the site type. Example:
3526 //
3527 // class Tree<A> { class Visitor { ... } }
3528 // class PointTree extends Tree<Point> { ... }
3529 // ...PointTree.Visitor...
3530 //
3531 // Then the type of the last expression above is
3532 // Tree<Point>.Visitor.
3533 else if (ownOuter.hasTag(CLASS) && site != ownOuter) {
3534 Type normOuter = site;
3535 if (normOuter.hasTag(CLASS)) {
3536 normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
3537 if (site.isAnnotated()) {
3538 // Propagate any type annotations.
3539 // TODO: should asEnclosingSuper do this?
3540 // Note that the type annotations in site will be updated
3541 // by annotateType. Therefore, modify site instead
3542 // of creating a new AnnotatedType.
3543 ((AnnotatedType)site).underlyingType = normOuter;
3544 normOuter = site;
3545 }
3546 }
3547 if (normOuter == null) // perhaps from an import
3548 normOuter = types.erasure(ownOuter);
3549 if (normOuter != ownOuter)
3550 owntype = new ClassType(
3551 normOuter, List.<Type>nil(), owntype.tsym);
3552 }
3553 }
3554 break;
3555 case VAR:
3556 VarSymbol v = (VarSymbol)sym;
3557 // Test (4): if symbol is an instance field of a raw type,
3558 // which is being assigned to, issue an unchecked warning if
3559 // its type changes under erasure.
3560 if (allowGenerics &&
3561 resultInfo.pkind == VAR &&
3562 v.owner.kind == TYP &&
3563 (v.flags() & STATIC) == 0 &&
3564 (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
3565 Type s = types.asOuterSuper(site, v.owner);
3566 if (s != null &&
3567 s.isRaw() &&
3568 !types.isSameType(v.type, v.erasure(types))) {
3569 chk.warnUnchecked(tree.pos(),
3570 "unchecked.assign.to.var",
3571 v, s);
3572 }
3573 }
3574 // The computed type of a variable is the type of the
3575 // variable symbol, taken as a member of the site type.
3576 owntype = (sym.owner.kind == TYP &&
3577 sym.name != names._this && sym.name != names._super)
3578 ? types.memberType(site, sym)
3579 : sym.type;
3581 // If the variable is a constant, record constant value in
3582 // computed type.
3583 if (v.getConstValue() != null && isStaticReference(tree))
3584 owntype = owntype.constType(v.getConstValue());
3586 if (resultInfo.pkind == VAL) {
3587 owntype = capture(owntype); // capture "names as expressions"
3588 }
3589 break;
3590 case MTH: {
3591 owntype = checkMethod(site, sym,
3592 new ResultInfo(resultInfo.pkind, resultInfo.pt.getReturnType(), resultInfo.checkContext),
3593 env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(),
3594 resultInfo.pt.getTypeArguments());
3595 break;
3596 }
3597 case PCK: case ERR:
3598 owntype = sym.type;
3599 break;
3600 default:
3601 throw new AssertionError("unexpected kind: " + sym.kind +
3602 " in tree " + tree);
3603 }
3605 // Test (1): emit a `deprecation' warning if symbol is deprecated.
3606 // (for constructors, the error was given when the constructor was
3607 // resolved)
3609 if (sym.name != names.init) {
3610 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym);
3611 chk.checkSunAPI(tree.pos(), sym);
3612 chk.checkProfile(tree.pos(), sym);
3613 }
3615 // Test (3): if symbol is a variable, check that its type and
3616 // kind are compatible with the prototype and protokind.
3617 return check(tree, owntype, sym.kind, resultInfo);
3618 }
3620 /** Check that variable is initialized and evaluate the variable's
3621 * initializer, if not yet done. Also check that variable is not
3622 * referenced before it is defined.
3623 * @param tree The tree making up the variable reference.
3624 * @param env The current environment.
3625 * @param v The variable's symbol.
3626 */
3627 private void checkInit(JCTree tree,
3628 Env<AttrContext> env,
3629 VarSymbol v,
3630 boolean onlyWarning) {
3631 // System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " +
3632 // tree.pos + " " + v.pos + " " +
3633 // Resolve.isStatic(env));//DEBUG
3635 // A forward reference is diagnosed if the declaration position
3636 // of the variable is greater than the current tree position
3637 // and the tree and variable definition occur in the same class
3638 // definition. Note that writes don't count as references.
3639 // This check applies only to class and instance
3640 // variables. Local variables follow different scope rules,
3641 // and are subject to definite assignment checking.
3642 if ((env.info.enclVar == v || v.pos > tree.pos) &&
3643 v.owner.kind == TYP &&
3644 canOwnInitializer(owner(env)) &&
3645 v.owner == env.info.scope.owner.enclClass() &&
3646 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
3647 (!env.tree.hasTag(ASSIGN) ||
3648 TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
3649 String suffix = (env.info.enclVar == v) ?
3650 "self.ref" : "forward.ref";
3651 if (!onlyWarning || isStaticEnumField(v)) {
3652 log.error(tree.pos(), "illegal." + suffix);
3653 } else if (useBeforeDeclarationWarning) {
3654 log.warning(tree.pos(), suffix, v);
3655 }
3656 }
3658 v.getConstValue(); // ensure initializer is evaluated
3660 checkEnumInitializer(tree, env, v);
3661 }
3663 /**
3664 * Check for illegal references to static members of enum. In
3665 * an enum type, constructors and initializers may not
3666 * reference its static members unless they are constant.
3667 *
3668 * @param tree The tree making up the variable reference.
3669 * @param env The current environment.
3670 * @param v The variable's symbol.
3671 * @jls section 8.9 Enums
3672 */
3673 private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
3674 // JLS:
3675 //
3676 // "It is a compile-time error to reference a static field
3677 // of an enum type that is not a compile-time constant
3678 // (15.28) from constructors, instance initializer blocks,
3679 // or instance variable initializer expressions of that
3680 // type. It is a compile-time error for the constructors,
3681 // instance initializer blocks, or instance variable
3682 // initializer expressions of an enum constant e to refer
3683 // to itself or to an enum constant of the same type that
3684 // is declared to the right of e."
3685 if (isStaticEnumField(v)) {
3686 ClassSymbol enclClass = env.info.scope.owner.enclClass();
3688 if (enclClass == null || enclClass.owner == null)
3689 return;
3691 // See if the enclosing class is the enum (or a
3692 // subclass thereof) declaring v. If not, this
3693 // reference is OK.
3694 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
3695 return;
3697 // If the reference isn't from an initializer, then
3698 // the reference is OK.
3699 if (!Resolve.isInitializer(env))
3700 return;
3702 log.error(tree.pos(), "illegal.enum.static.ref");
3703 }
3704 }
3706 /** Is the given symbol a static, non-constant field of an Enum?
3707 * Note: enum literals should not be regarded as such
3708 */
3709 private boolean isStaticEnumField(VarSymbol v) {
3710 return Flags.isEnum(v.owner) &&
3711 Flags.isStatic(v) &&
3712 !Flags.isConstant(v) &&
3713 v.name != names._class;
3714 }
3716 /** Can the given symbol be the owner of code which forms part
3717 * if class initialization? This is the case if the symbol is
3718 * a type or field, or if the symbol is the synthetic method.
3719 * owning a block.
3720 */
3721 private boolean canOwnInitializer(Symbol sym) {
3722 return
3723 (sym.kind & (VAR | TYP)) != 0 ||
3724 (sym.kind == MTH && (sym.flags() & BLOCK) != 0);
3725 }
3727 Warner noteWarner = new Warner();
3729 /**
3730 * Check that method arguments conform to its instantiation.
3731 **/
3732 public Type checkMethod(Type site,
3733 final Symbol sym,
3734 ResultInfo resultInfo,
3735 Env<AttrContext> env,
3736 final List<JCExpression> argtrees,
3737 List<Type> argtypes,
3738 List<Type> typeargtypes) {
3739 // Test (5): if symbol is an instance method of a raw type, issue
3740 // an unchecked warning if its argument types change under erasure.
3741 if (allowGenerics &&
3742 (sym.flags() & STATIC) == 0 &&
3743 (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
3744 Type s = types.asOuterSuper(site, sym.owner);
3745 if (s != null && s.isRaw() &&
3746 !types.isSameTypes(sym.type.getParameterTypes(),
3747 sym.erasure(types).getParameterTypes())) {
3748 chk.warnUnchecked(env.tree.pos(),
3749 "unchecked.call.mbr.of.raw.type",
3750 sym, s);
3751 }
3752 }
3754 if (env.info.defaultSuperCallSite != null) {
3755 for (Type sup : types.interfaces(env.enclClass.type).prepend(types.supertype((env.enclClass.type)))) {
3756 if (!sup.tsym.isSubClass(sym.enclClass(), types) ||
3757 types.isSameType(sup, env.info.defaultSuperCallSite)) continue;
3758 List<MethodSymbol> icand_sup =
3759 types.interfaceCandidates(sup, (MethodSymbol)sym);
3760 if (icand_sup.nonEmpty() &&
3761 icand_sup.head != sym &&
3762 icand_sup.head.overrides(sym, icand_sup.head.enclClass(), types, true)) {
3763 log.error(env.tree.pos(), "illegal.default.super.call", env.info.defaultSuperCallSite,
3764 diags.fragment("overridden.default", sym, sup));
3765 break;
3766 }
3767 }
3768 env.info.defaultSuperCallSite = null;
3769 }
3771 if (sym.isStatic() && site.isInterface() && env.tree.hasTag(APPLY)) {
3772 JCMethodInvocation app = (JCMethodInvocation)env.tree;
3773 if (app.meth.hasTag(SELECT) &&
3774 !TreeInfo.isStaticSelector(((JCFieldAccess)app.meth).selected, names)) {
3775 log.error(env.tree.pos(), "illegal.static.intf.meth.call", site);
3776 }
3777 }
3779 // Compute the identifier's instantiated type.
3780 // For methods, we need to compute the instance type by
3781 // Resolve.instantiate from the symbol's type as well as
3782 // any type arguments and value arguments.
3783 noteWarner.clear();
3784 try {
3785 Type owntype = rs.checkMethod(
3786 env,
3787 site,
3788 sym,
3789 resultInfo,
3790 argtypes,
3791 typeargtypes,
3792 noteWarner);
3794 DeferredAttr.DeferredTypeMap checkDeferredMap =
3795 deferredAttr.new DeferredTypeMap(DeferredAttr.AttrMode.CHECK, sym, env.info.pendingResolutionPhase);
3797 argtypes = Type.map(argtypes, checkDeferredMap);
3799 if (noteWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
3800 chk.warnUnchecked(env.tree.pos(),
3801 "unchecked.meth.invocation.applied",
3802 kindName(sym),
3803 sym.name,
3804 rs.methodArguments(sym.type.getParameterTypes()),
3805 rs.methodArguments(Type.map(argtypes, checkDeferredMap)),
3806 kindName(sym.location()),
3807 sym.location());
3808 owntype = new MethodType(owntype.getParameterTypes(),
3809 types.erasure(owntype.getReturnType()),
3810 types.erasure(owntype.getThrownTypes()),
3811 syms.methodClass);
3812 }
3814 return chk.checkMethod(owntype, sym, env, argtrees, argtypes, env.info.lastResolveVarargs(),
3815 resultInfo.checkContext.inferenceContext());
3816 } catch (Infer.InferenceException ex) {
3817 //invalid target type - propagate exception outwards or report error
3818 //depending on the current check context
3819 resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic());
3820 return types.createErrorType(site);
3821 } catch (Resolve.InapplicableMethodException ex) {
3822 final JCDiagnostic diag = ex.getDiagnostic();
3823 Resolve.InapplicableSymbolError errSym = rs.new InapplicableSymbolError(null) {
3824 @Override
3825 protected Pair<Symbol, JCDiagnostic> errCandidate() {
3826 return new Pair<Symbol, JCDiagnostic>(sym, diag);
3827 }
3828 };
3829 List<Type> argtypes2 = Type.map(argtypes,
3830 rs.new ResolveDeferredRecoveryMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
3831 JCDiagnostic errDiag = errSym.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
3832 env.tree, sym, site, sym.name, argtypes2, typeargtypes);
3833 log.report(errDiag);
3834 return types.createErrorType(site);
3835 }
3836 }
3838 public void visitLiteral(JCLiteral tree) {
3839 result = check(
3840 tree, litType(tree.typetag).constType(tree.value), VAL, resultInfo);
3841 }
3842 //where
3843 /** Return the type of a literal with given type tag.
3844 */
3845 Type litType(TypeTag tag) {
3846 return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()];
3847 }
3849 public void visitTypeIdent(JCPrimitiveTypeTree tree) {
3850 result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], TYP, resultInfo);
3851 }
3853 public void visitTypeArray(JCArrayTypeTree tree) {
3854 Type etype = attribType(tree.elemtype, env);
3855 Type type = new ArrayType(etype, syms.arrayClass);
3856 result = check(tree, type, TYP, resultInfo);
3857 }
3859 /** Visitor method for parameterized types.
3860 * Bound checking is left until later, since types are attributed
3861 * before supertype structure is completely known
3862 */
3863 public void visitTypeApply(JCTypeApply tree) {
3864 Type owntype = types.createErrorType(tree.type);
3866 // Attribute functor part of application and make sure it's a class.
3867 Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
3869 // Attribute type parameters
3870 List<Type> actuals = attribTypes(tree.arguments, env);
3872 if (clazztype.hasTag(CLASS)) {
3873 List<Type> formals = clazztype.tsym.type.getTypeArguments();
3874 if (actuals.isEmpty()) //diamond
3875 actuals = formals;
3877 if (actuals.length() == formals.length()) {
3878 List<Type> a = actuals;
3879 List<Type> f = formals;
3880 while (a.nonEmpty()) {
3881 a.head = a.head.withTypeVar(f.head);
3882 a = a.tail;
3883 f = f.tail;
3884 }
3885 // Compute the proper generic outer
3886 Type clazzOuter = clazztype.getEnclosingType();
3887 if (clazzOuter.hasTag(CLASS)) {
3888 Type site;
3889 JCExpression clazz = TreeInfo.typeIn(tree.clazz);
3890 if (clazz.hasTag(IDENT)) {
3891 site = env.enclClass.sym.type;
3892 } else if (clazz.hasTag(SELECT)) {
3893 site = ((JCFieldAccess) clazz).selected.type;
3894 } else throw new AssertionError(""+tree);
3895 if (clazzOuter.hasTag(CLASS) && site != clazzOuter) {
3896 if (site.hasTag(CLASS))
3897 site = types.asOuterSuper(site, clazzOuter.tsym);
3898 if (site == null)
3899 site = types.erasure(clazzOuter);
3900 clazzOuter = site;
3901 }
3902 }
3903 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym);
3904 if (clazztype.isAnnotated()) {
3905 // Use the same AnnotatedType, because it will have
3906 // its annotations set later.
3907 ((AnnotatedType)clazztype).underlyingType = owntype;
3908 owntype = clazztype;
3909 }
3910 } else {
3911 if (formals.length() != 0) {
3912 log.error(tree.pos(), "wrong.number.type.args",
3913 Integer.toString(formals.length()));
3914 } else {
3915 log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym);
3916 }
3917 owntype = types.createErrorType(tree.type);
3918 }
3919 }
3920 result = check(tree, owntype, TYP, resultInfo);
3921 }
3923 public void visitTypeUnion(JCTypeUnion tree) {
3924 ListBuffer<Type> multicatchTypes = new ListBuffer<>();
3925 ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
3926 for (JCExpression typeTree : tree.alternatives) {
3927 Type ctype = attribType(typeTree, env);
3928 ctype = chk.checkType(typeTree.pos(),
3929 chk.checkClassType(typeTree.pos(), ctype),
3930 syms.throwableType);
3931 if (!ctype.isErroneous()) {
3932 //check that alternatives of a union type are pairwise
3933 //unrelated w.r.t. subtyping
3934 if (chk.intersects(ctype, multicatchTypes.toList())) {
3935 for (Type t : multicatchTypes) {
3936 boolean sub = types.isSubtype(ctype, t);
3937 boolean sup = types.isSubtype(t, ctype);
3938 if (sub || sup) {
3939 //assume 'a' <: 'b'
3940 Type a = sub ? ctype : t;
3941 Type b = sub ? t : ctype;
3942 log.error(typeTree.pos(), "multicatch.types.must.be.disjoint", a, b);
3943 }
3944 }
3945 }
3946 multicatchTypes.append(ctype);
3947 if (all_multicatchTypes != null)
3948 all_multicatchTypes.append(ctype);
3949 } else {
3950 if (all_multicatchTypes == null) {
3951 all_multicatchTypes = new ListBuffer<>();
3952 all_multicatchTypes.appendList(multicatchTypes);
3953 }
3954 all_multicatchTypes.append(ctype);
3955 }
3956 }
3957 Type t = check(tree, types.lub(multicatchTypes.toList()), TYP, resultInfo);
3958 if (t.hasTag(CLASS)) {
3959 List<Type> alternatives =
3960 ((all_multicatchTypes == null) ? multicatchTypes : all_multicatchTypes).toList();
3961 t = new UnionClassType((ClassType) t, alternatives);
3962 }
3963 tree.type = result = t;
3964 }
3966 public void visitTypeIntersection(JCTypeIntersection tree) {
3967 attribTypes(tree.bounds, env);
3968 tree.type = result = checkIntersection(tree, tree.bounds);
3969 }
3971 public void visitTypeParameter(JCTypeParameter tree) {
3972 TypeVar typeVar = (TypeVar) tree.type;
3974 if (tree.annotations != null && tree.annotations.nonEmpty()) {
3975 AnnotatedType antype = new AnnotatedType(typeVar);
3976 annotateType(antype, tree.annotations);
3977 tree.type = antype;
3978 }
3980 if (!typeVar.bound.isErroneous()) {
3981 //fixup type-parameter bound computed in 'attribTypeVariables'
3982 typeVar.bound = checkIntersection(tree, tree.bounds);
3983 }
3984 }
3986 Type checkIntersection(JCTree tree, List<JCExpression> bounds) {
3987 Set<Type> boundSet = new HashSet<Type>();
3988 if (bounds.nonEmpty()) {
3989 // accept class or interface or typevar as first bound.
3990 bounds.head.type = checkBase(bounds.head.type, bounds.head, env, false, false, false, false);
3991 boundSet.add(types.erasure(bounds.head.type));
3992 if (bounds.head.type.isErroneous()) {
3993 return bounds.head.type;
3994 }
3995 else if (bounds.head.type.hasTag(TYPEVAR)) {
3996 // if first bound was a typevar, do not accept further bounds.
3997 if (bounds.tail.nonEmpty()) {
3998 log.error(bounds.tail.head.pos(),
3999 "type.var.may.not.be.followed.by.other.bounds");
4000 return bounds.head.type;
4001 }
4002 } else {
4003 // if first bound was a class or interface, accept only interfaces
4004 // as further bounds.
4005 for (JCExpression bound : bounds.tail) {
4006 bound.type = checkBase(bound.type, bound, env, false, false, true, false);
4007 if (bound.type.isErroneous()) {
4008 bounds = List.of(bound);
4009 }
4010 else if (bound.type.hasTag(CLASS)) {
4011 chk.checkNotRepeated(bound.pos(), types.erasure(bound.type), boundSet);
4012 }
4013 }
4014 }
4015 }
4017 if (bounds.length() == 0) {
4018 return syms.objectType;
4019 } else if (bounds.length() == 1) {
4020 return bounds.head.type;
4021 } else {
4022 Type owntype = types.makeCompoundType(TreeInfo.types(bounds));
4023 if (tree.hasTag(TYPEINTERSECTION)) {
4024 ((IntersectionClassType)owntype).intersectionKind =
4025 IntersectionClassType.IntersectionKind.EXPLICIT;
4026 }
4027 // ... the variable's bound is a class type flagged COMPOUND
4028 // (see comment for TypeVar.bound).
4029 // In this case, generate a class tree that represents the
4030 // bound class, ...
4031 JCExpression extending;
4032 List<JCExpression> implementing;
4033 if (!bounds.head.type.isInterface()) {
4034 extending = bounds.head;
4035 implementing = bounds.tail;
4036 } else {
4037 extending = null;
4038 implementing = bounds;
4039 }
4040 JCClassDecl cd = make.at(tree).ClassDef(
4041 make.Modifiers(PUBLIC | ABSTRACT),
4042 names.empty, List.<JCTypeParameter>nil(),
4043 extending, implementing, List.<JCTree>nil());
4045 ClassSymbol c = (ClassSymbol)owntype.tsym;
4046 Assert.check((c.flags() & COMPOUND) != 0);
4047 cd.sym = c;
4048 c.sourcefile = env.toplevel.sourcefile;
4050 // ... and attribute the bound class
4051 c.flags_field |= UNATTRIBUTED;
4052 Env<AttrContext> cenv = enter.classEnv(cd, env);
4053 enter.typeEnvs.put(c, cenv);
4054 attribClass(c);
4055 return owntype;
4056 }
4057 }
4059 public void visitWildcard(JCWildcard tree) {
4060 //- System.err.println("visitWildcard("+tree+");");//DEBUG
4061 Type type = (tree.kind.kind == BoundKind.UNBOUND)
4062 ? syms.objectType
4063 : attribType(tree.inner, env);
4064 result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
4065 tree.kind.kind,
4066 syms.boundClass),
4067 TYP, resultInfo);
4068 }
4070 public void visitAnnotation(JCAnnotation tree) {
4071 Assert.error("should be handled in Annotate");
4072 }
4074 public void visitAnnotatedType(JCAnnotatedType tree) {
4075 Type underlyingType = attribType(tree.getUnderlyingType(), env);
4076 this.attribAnnotationTypes(tree.annotations, env);
4077 AnnotatedType antype = new AnnotatedType(underlyingType);
4078 annotateType(antype, tree.annotations);
4079 result = tree.type = antype;
4080 }
4082 /**
4083 * Apply the annotations to the particular type.
4084 */
4085 public void annotateType(final AnnotatedType type, final List<JCAnnotation> annotations) {
4086 if (annotations.isEmpty())
4087 return;
4088 annotate.typeAnnotation(new Annotate.Annotator() {
4089 @Override
4090 public String toString() {
4091 return "annotate " + annotations + " onto " + type;
4092 }
4093 @Override
4094 public void enterAnnotation() {
4095 List<Attribute.TypeCompound> compounds = fromAnnotations(annotations);
4096 type.typeAnnotations = compounds;
4097 }
4098 });
4099 }
4101 private static List<Attribute.TypeCompound> fromAnnotations(List<JCAnnotation> annotations) {
4102 if (annotations.isEmpty())
4103 return List.nil();
4105 ListBuffer<Attribute.TypeCompound> buf = new ListBuffer<>();
4106 for (JCAnnotation anno : annotations) {
4107 if (anno.attribute != null) {
4108 // TODO: this null-check is only needed for an obscure
4109 // ordering issue, where annotate.flush is called when
4110 // the attribute is not set yet. For an example failure
4111 // try the referenceinfos/NestedTypes.java test.
4112 // Any better solutions?
4113 buf.append((Attribute.TypeCompound) anno.attribute);
4114 }
4115 }
4116 return buf.toList();
4117 }
4119 public void visitErroneous(JCErroneous tree) {
4120 if (tree.errs != null)
4121 for (JCTree err : tree.errs)
4122 attribTree(err, env, new ResultInfo(ERR, pt()));
4123 result = tree.type = syms.errType;
4124 }
4126 /** Default visitor method for all other trees.
4127 */
4128 public void visitTree(JCTree tree) {
4129 throw new AssertionError();
4130 }
4132 /**
4133 * Attribute an env for either a top level tree or class declaration.
4134 */
4135 public void attrib(Env<AttrContext> env) {
4136 if (env.tree.hasTag(TOPLEVEL))
4137 attribTopLevel(env);
4138 else
4139 attribClass(env.tree.pos(), env.enclClass.sym);
4140 }
4142 /**
4143 * Attribute a top level tree. These trees are encountered when the
4144 * package declaration has annotations.
4145 */
4146 public void attribTopLevel(Env<AttrContext> env) {
4147 JCCompilationUnit toplevel = env.toplevel;
4148 try {
4149 annotate.flush();
4150 } catch (CompletionFailure ex) {
4151 chk.completionError(toplevel.pos(), ex);
4152 }
4153 }
4155 /** Main method: attribute class definition associated with given class symbol.
4156 * reporting completion failures at the given position.
4157 * @param pos The source position at which completion errors are to be
4158 * reported.
4159 * @param c The class symbol whose definition will be attributed.
4160 */
4161 public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
4162 try {
4163 annotate.flush();
4164 attribClass(c);
4165 } catch (CompletionFailure ex) {
4166 chk.completionError(pos, ex);
4167 }
4168 }
4170 /** Attribute class definition associated with given class symbol.
4171 * @param c The class symbol whose definition will be attributed.
4172 */
4173 void attribClass(ClassSymbol c) throws CompletionFailure {
4174 if (c.type.hasTag(ERROR)) return;
4176 // Check for cycles in the inheritance graph, which can arise from
4177 // ill-formed class files.
4178 chk.checkNonCyclic(null, c.type);
4180 Type st = types.supertype(c.type);
4181 if ((c.flags_field & Flags.COMPOUND) == 0) {
4182 // First, attribute superclass.
4183 if (st.hasTag(CLASS))
4184 attribClass((ClassSymbol)st.tsym);
4186 // Next attribute owner, if it is a class.
4187 if (c.owner.kind == TYP && c.owner.type.hasTag(CLASS))
4188 attribClass((ClassSymbol)c.owner);
4189 }
4191 // The previous operations might have attributed the current class
4192 // if there was a cycle. So we test first whether the class is still
4193 // UNATTRIBUTED.
4194 if ((c.flags_field & UNATTRIBUTED) != 0) {
4195 c.flags_field &= ~UNATTRIBUTED;
4197 // Get environment current at the point of class definition.
4198 Env<AttrContext> env = enter.typeEnvs.get(c);
4200 // The info.lint field in the envs stored in enter.typeEnvs is deliberately uninitialized,
4201 // because the annotations were not available at the time the env was created. Therefore,
4202 // we look up the environment chain for the first enclosing environment for which the
4203 // lint value is set. Typically, this is the parent env, but might be further if there
4204 // are any envs created as a result of TypeParameter nodes.
4205 Env<AttrContext> lintEnv = env;
4206 while (lintEnv.info.lint == null)
4207 lintEnv = lintEnv.next;
4209 // Having found the enclosing lint value, we can initialize the lint value for this class
4210 env.info.lint = lintEnv.info.lint.augment(c);
4212 Lint prevLint = chk.setLint(env.info.lint);
4213 JavaFileObject prev = log.useSource(c.sourcefile);
4214 ResultInfo prevReturnRes = env.info.returnResult;
4216 try {
4217 deferredLintHandler.flush(env.tree);
4218 env.info.returnResult = null;
4219 // java.lang.Enum may not be subclassed by a non-enum
4220 if (st.tsym == syms.enumSym &&
4221 ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
4222 log.error(env.tree.pos(), "enum.no.subclassing");
4224 // Enums may not be extended by source-level classes
4225 if (st.tsym != null &&
4226 ((st.tsym.flags_field & Flags.ENUM) != 0) &&
4227 ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
4228 log.error(env.tree.pos(), "enum.types.not.extensible");
4229 }
4230 attribClassBody(env, c);
4232 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
4233 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
4234 chk.checkFunctionalInterface((JCClassDecl) env.tree, c);
4235 } finally {
4236 env.info.returnResult = prevReturnRes;
4237 log.useSource(prev);
4238 chk.setLint(prevLint);
4239 }
4241 }
4242 }
4244 public void visitImport(JCImport tree) {
4245 // nothing to do
4246 }
4248 /** Finish the attribution of a class. */
4249 private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
4250 JCClassDecl tree = (JCClassDecl)env.tree;
4251 Assert.check(c == tree.sym);
4253 // Validate type parameters, supertype and interfaces.
4254 attribStats(tree.typarams, env);
4255 if (!c.isAnonymous()) {
4256 //already checked if anonymous
4257 chk.validate(tree.typarams, env);
4258 chk.validate(tree.extending, env);
4259 chk.validate(tree.implementing, env);
4260 }
4262 // If this is a non-abstract class, check that it has no abstract
4263 // methods or unimplemented methods of an implemented interface.
4264 if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
4265 if (!relax)
4266 chk.checkAllDefined(tree.pos(), c);
4267 }
4269 if ((c.flags() & ANNOTATION) != 0) {
4270 if (tree.implementing.nonEmpty())
4271 log.error(tree.implementing.head.pos(),
4272 "cant.extend.intf.annotation");
4273 if (tree.typarams.nonEmpty())
4274 log.error(tree.typarams.head.pos(),
4275 "intf.annotation.cant.have.type.params");
4277 // If this annotation has a @Repeatable, validate
4278 Attribute.Compound repeatable = c.attribute(syms.repeatableType.tsym);
4279 if (repeatable != null) {
4280 // get diagnostic position for error reporting
4281 DiagnosticPosition cbPos = getDiagnosticPosition(tree, repeatable.type);
4282 Assert.checkNonNull(cbPos);
4284 chk.validateRepeatable(c, repeatable, cbPos);
4285 }
4286 } else {
4287 // Check that all extended classes and interfaces
4288 // are compatible (i.e. no two define methods with same arguments
4289 // yet different return types). (JLS 8.4.6.3)
4290 chk.checkCompatibleSupertypes(tree.pos(), c.type);
4291 if (allowDefaultMethods) {
4292 chk.checkDefaultMethodClashes(tree.pos(), c.type);
4293 }
4294 }
4296 // Check that class does not import the same parameterized interface
4297 // with two different argument lists.
4298 chk.checkClassBounds(tree.pos(), c.type);
4300 tree.type = c.type;
4302 for (List<JCTypeParameter> l = tree.typarams;
4303 l.nonEmpty(); l = l.tail) {
4304 Assert.checkNonNull(env.info.scope.lookup(l.head.name).scope);
4305 }
4307 // Check that a generic class doesn't extend Throwable
4308 if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
4309 log.error(tree.extending.pos(), "generic.throwable");
4311 // Check that all methods which implement some
4312 // method conform to the method they implement.
4313 chk.checkImplementations(tree);
4315 //check that a resource implementing AutoCloseable cannot throw InterruptedException
4316 checkAutoCloseable(tree.pos(), env, c.type);
4318 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
4319 // Attribute declaration
4320 attribStat(l.head, env);
4321 // Check that declarations in inner classes are not static (JLS 8.1.2)
4322 // Make an exception for static constants.
4323 if (c.owner.kind != PCK &&
4324 ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
4325 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
4326 Symbol sym = null;
4327 if (l.head.hasTag(VARDEF)) sym = ((JCVariableDecl) l.head).sym;
4328 if (sym == null ||
4329 sym.kind != VAR ||
4330 ((VarSymbol) sym).getConstValue() == null)
4331 log.error(l.head.pos(), "icls.cant.have.static.decl", c);
4332 }
4333 }
4335 // Check for cycles among non-initial constructors.
4336 chk.checkCyclicConstructors(tree);
4338 // Check for cycles among annotation elements.
4339 chk.checkNonCyclicElements(tree);
4341 // Check for proper use of serialVersionUID
4342 if (env.info.lint.isEnabled(LintCategory.SERIAL) &&
4343 isSerializable(c) &&
4344 (c.flags() & Flags.ENUM) == 0 &&
4345 checkForSerial(c)) {
4346 checkSerialVersionUID(tree, c);
4347 }
4348 if (allowTypeAnnos) {
4349 // Correctly organize the postions of the type annotations
4350 typeAnnotations.organizeTypeAnnotationsBodies(tree);
4352 // Check type annotations applicability rules
4353 validateTypeAnnotations(tree, false);
4354 }
4355 }
4356 // where
4357 boolean checkForSerial(ClassSymbol c) {
4358 if ((c.flags() & ABSTRACT) == 0) {
4359 return true;
4360 } else {
4361 return c.members().anyMatch(anyNonAbstractOrDefaultMethod);
4362 }
4363 }
4365 public static final Filter<Symbol> anyNonAbstractOrDefaultMethod = new Filter<Symbol>() {
4366 @Override
4367 public boolean accepts(Symbol s) {
4368 return s.kind == Kinds.MTH &&
4369 (s.flags() & (DEFAULT | ABSTRACT)) != ABSTRACT;
4370 }
4371 };
4373 /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
4374 private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
4375 for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
4376 if (types.isSameType(al.head.annotationType.type, t))
4377 return al.head.pos();
4378 }
4380 return null;
4381 }
4383 /** check if a class is a subtype of Serializable, if that is available. */
4384 private boolean isSerializable(ClassSymbol c) {
4385 try {
4386 syms.serializableType.complete();
4387 }
4388 catch (CompletionFailure e) {
4389 return false;
4390 }
4391 return types.isSubtype(c.type, syms.serializableType);
4392 }
4394 /** Check that an appropriate serialVersionUID member is defined. */
4395 private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
4397 // check for presence of serialVersionUID
4398 Scope.Entry e = c.members().lookup(names.serialVersionUID);
4399 while (e.scope != null && e.sym.kind != VAR) e = e.next();
4400 if (e.scope == null) {
4401 log.warning(LintCategory.SERIAL,
4402 tree.pos(), "missing.SVUID", c);
4403 return;
4404 }
4406 // check that it is static final
4407 VarSymbol svuid = (VarSymbol)e.sym;
4408 if ((svuid.flags() & (STATIC | FINAL)) !=
4409 (STATIC | FINAL))
4410 log.warning(LintCategory.SERIAL,
4411 TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c);
4413 // check that it is long
4414 else if (!svuid.type.hasTag(LONG))
4415 log.warning(LintCategory.SERIAL,
4416 TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c);
4418 // check constant
4419 else if (svuid.getConstValue() == null)
4420 log.warning(LintCategory.SERIAL,
4421 TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c);
4422 }
4424 private Type capture(Type type) {
4425 return types.capture(type);
4426 }
4428 public void validateTypeAnnotations(JCTree tree, boolean sigOnly) {
4429 tree.accept(new TypeAnnotationsValidator(sigOnly));
4430 }
4431 //where
4432 private final class TypeAnnotationsValidator extends TreeScanner {
4434 private final boolean sigOnly;
4435 private boolean checkAllAnnotations = false;
4437 public TypeAnnotationsValidator(boolean sigOnly) {
4438 this.sigOnly = sigOnly;
4439 }
4441 public void visitAnnotation(JCAnnotation tree) {
4442 if (tree.hasTag(TYPE_ANNOTATION) || checkAllAnnotations) {
4443 chk.validateTypeAnnotation(tree, false);
4444 }
4445 super.visitAnnotation(tree);
4446 }
4447 public void visitTypeParameter(JCTypeParameter tree) {
4448 chk.validateTypeAnnotations(tree.annotations, true);
4449 scan(tree.bounds);
4450 // Don't call super.
4451 // This is needed because above we call validateTypeAnnotation with
4452 // false, which would forbid annotations on type parameters.
4453 // super.visitTypeParameter(tree);
4454 }
4455 public void visitMethodDef(JCMethodDecl tree) {
4456 if (tree.recvparam != null &&
4457 tree.recvparam.vartype.type.getKind() != TypeKind.ERROR) {
4458 checkForDeclarationAnnotations(tree.recvparam.mods.annotations,
4459 tree.recvparam.vartype.type.tsym);
4460 }
4461 if (tree.restype != null && tree.restype.type != null) {
4462 validateAnnotatedType(tree.restype, tree.restype.type);
4463 }
4464 if (sigOnly) {
4465 scan(tree.mods);
4466 scan(tree.restype);
4467 scan(tree.typarams);
4468 scan(tree.recvparam);
4469 scan(tree.params);
4470 scan(tree.thrown);
4471 } else {
4472 scan(tree.defaultValue);
4473 scan(tree.body);
4474 }
4475 }
4476 public void visitVarDef(final JCVariableDecl tree) {
4477 if (tree.sym != null && tree.sym.type != null)
4478 validateAnnotatedType(tree, tree.sym.type);
4479 scan(tree.mods);
4480 scan(tree.vartype);
4481 if (!sigOnly) {
4482 scan(tree.init);
4483 }
4484 }
4485 public void visitTypeCast(JCTypeCast tree) {
4486 if (tree.clazz != null && tree.clazz.type != null)
4487 validateAnnotatedType(tree.clazz, tree.clazz.type);
4488 super.visitTypeCast(tree);
4489 }
4490 public void visitTypeTest(JCInstanceOf tree) {
4491 if (tree.clazz != null && tree.clazz.type != null)
4492 validateAnnotatedType(tree.clazz, tree.clazz.type);
4493 super.visitTypeTest(tree);
4494 }
4495 public void visitNewClass(JCNewClass tree) {
4496 if (tree.clazz.hasTag(ANNOTATED_TYPE)) {
4497 boolean prevCheck = this.checkAllAnnotations;
4498 try {
4499 this.checkAllAnnotations = true;
4500 scan(((JCAnnotatedType)tree.clazz).annotations);
4501 } finally {
4502 this.checkAllAnnotations = prevCheck;
4503 }
4504 }
4505 super.visitNewClass(tree);
4506 }
4507 public void visitNewArray(JCNewArray tree) {
4508 if (tree.elemtype != null && tree.elemtype.hasTag(ANNOTATED_TYPE)) {
4509 boolean prevCheck = this.checkAllAnnotations;
4510 try {
4511 this.checkAllAnnotations = true;
4512 scan(((JCAnnotatedType)tree.elemtype).annotations);
4513 } finally {
4514 this.checkAllAnnotations = prevCheck;
4515 }
4516 }
4517 super.visitNewArray(tree);
4518 }
4520 @Override
4521 public void visitClassDef(JCClassDecl tree) {
4522 if (sigOnly) {
4523 scan(tree.mods);
4524 scan(tree.typarams);
4525 scan(tree.extending);
4526 scan(tree.implementing);
4527 }
4528 for (JCTree member : tree.defs) {
4529 if (member.hasTag(Tag.CLASSDEF)) {
4530 continue;
4531 }
4532 scan(member);
4533 }
4534 }
4536 @Override
4537 public void visitBlock(JCBlock tree) {
4538 if (!sigOnly) {
4539 scan(tree.stats);
4540 }
4541 }
4543 /* I would want to model this after
4544 * com.sun.tools.javac.comp.Check.Validator.visitSelectInternal(JCFieldAccess)
4545 * and override visitSelect and visitTypeApply.
4546 * However, we only set the annotated type in the top-level type
4547 * of the symbol.
4548 * Therefore, we need to override each individual location where a type
4549 * can occur.
4550 */
4551 private void validateAnnotatedType(final JCTree errtree, final Type type) {
4552 if (type.getEnclosingType() != null &&
4553 type != type.getEnclosingType()) {
4554 validateEnclosingAnnotatedType(errtree, type.getEnclosingType());
4555 }
4556 for (Type targ : type.getTypeArguments()) {
4557 validateAnnotatedType(errtree, targ);
4558 }
4559 }
4560 private void validateEnclosingAnnotatedType(final JCTree errtree, final Type type) {
4561 validateAnnotatedType(errtree, type);
4562 if (type.tsym != null &&
4563 type.tsym.isStatic() &&
4564 type.getAnnotationMirrors().nonEmpty()) {
4565 // Enclosing static classes cannot have type annotations.
4566 log.error(errtree.pos(), "cant.annotate.static.class");
4567 }
4568 }
4569 };
4571 // <editor-fold desc="post-attribution visitor">
4573 /**
4574 * Handle missing types/symbols in an AST. This routine is useful when
4575 * the compiler has encountered some errors (which might have ended up
4576 * terminating attribution abruptly); if the compiler is used in fail-over
4577 * mode (e.g. by an IDE) and the AST contains semantic errors, this routine
4578 * prevents NPE to be progagated during subsequent compilation steps.
4579 */
4580 public void postAttr(JCTree tree) {
4581 new PostAttrAnalyzer().scan(tree);
4582 }
4584 class PostAttrAnalyzer extends TreeScanner {
4586 private void initTypeIfNeeded(JCTree that) {
4587 if (that.type == null) {
4588 that.type = syms.unknownType;
4589 }
4590 }
4592 @Override
4593 public void scan(JCTree tree) {
4594 if (tree == null) return;
4595 if (tree instanceof JCExpression) {
4596 initTypeIfNeeded(tree);
4597 }
4598 super.scan(tree);
4599 }
4601 @Override
4602 public void visitIdent(JCIdent that) {
4603 if (that.sym == null) {
4604 that.sym = syms.unknownSymbol;
4605 }
4606 }
4608 @Override
4609 public void visitSelect(JCFieldAccess that) {
4610 if (that.sym == null) {
4611 that.sym = syms.unknownSymbol;
4612 }
4613 super.visitSelect(that);
4614 }
4616 @Override
4617 public void visitClassDef(JCClassDecl that) {
4618 initTypeIfNeeded(that);
4619 if (that.sym == null) {
4620 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol);
4621 }
4622 super.visitClassDef(that);
4623 }
4625 @Override
4626 public void visitMethodDef(JCMethodDecl that) {
4627 initTypeIfNeeded(that);
4628 if (that.sym == null) {
4629 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol);
4630 }
4631 super.visitMethodDef(that);
4632 }
4634 @Override
4635 public void visitVarDef(JCVariableDecl that) {
4636 initTypeIfNeeded(that);
4637 if (that.sym == null) {
4638 that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol);
4639 that.sym.adr = 0;
4640 }
4641 super.visitVarDef(that);
4642 }
4644 @Override
4645 public void visitNewClass(JCNewClass that) {
4646 if (that.constructor == null) {
4647 that.constructor = new MethodSymbol(0, names.init, syms.unknownType, syms.noSymbol);
4648 }
4649 if (that.constructorType == null) {
4650 that.constructorType = syms.unknownType;
4651 }
4652 super.visitNewClass(that);
4653 }
4655 @Override
4656 public void visitAssignop(JCAssignOp that) {
4657 if (that.operator == null)
4658 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
4659 super.visitAssignop(that);
4660 }
4662 @Override
4663 public void visitBinary(JCBinary that) {
4664 if (that.operator == null)
4665 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
4666 super.visitBinary(that);
4667 }
4669 @Override
4670 public void visitUnary(JCUnary that) {
4671 if (that.operator == null)
4672 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
4673 super.visitUnary(that);
4674 }
4676 @Override
4677 public void visitLambda(JCLambda that) {
4678 super.visitLambda(that);
4679 if (that.targets == null) {
4680 that.targets = List.nil();
4681 }
4682 }
4684 @Override
4685 public void visitReference(JCMemberReference that) {
4686 super.visitReference(that);
4687 if (that.sym == null) {
4688 that.sym = new MethodSymbol(0, names.empty, syms.unknownType, syms.noSymbol);
4689 }
4690 if (that.targets == null) {
4691 that.targets = List.nil();
4692 }
4693 }
4694 }
4695 // </editor-fold>
4696 }