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