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