Tue, 22 Apr 2014 17:55:22 +0100
8029718: Should always use lambda body structure to disambiguate overload resolution
Reviewed-by: dlsmith, jjg, jlahoda
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 attribStat(cdef, localEnv);
2148 checkLambdaCandidate(tree, cdef.sym, clazztype);
2150 // If an outer instance is given,
2151 // prefix it to the constructor arguments
2152 // and delete it from the new expression
2153 if (tree.encl != null && !clazztype.tsym.isInterface()) {
2154 tree.args = tree.args.prepend(makeNullCheck(tree.encl));
2155 argtypes = argtypes.prepend(tree.encl.type);
2156 tree.encl = null;
2157 }
2159 // Reassign clazztype and recompute constructor.
2160 clazztype = cdef.sym.type;
2161 Symbol sym = tree.constructor = rs.resolveConstructor(
2162 tree.pos(), localEnv, clazztype, argtypes, typeargtypes);
2163 Assert.check(sym.kind < AMBIGUOUS);
2164 tree.constructor = sym;
2165 tree.constructorType = checkId(tree,
2166 clazztype,
2167 tree.constructor,
2168 localEnv,
2169 new ResultInfo(pkind, newMethodTemplate(syms.voidType, argtypes, typeargtypes)));
2170 }
2172 if (tree.constructor != null && tree.constructor.kind == MTH)
2173 owntype = clazztype;
2174 }
2175 result = check(tree, owntype, VAL, resultInfo);
2176 chk.validate(tree.typeargs, localEnv);
2177 }
2178 //where
2179 void findDiamond(Env<AttrContext> env, JCNewClass tree, Type clazztype) {
2180 JCTypeApply ta = (JCTypeApply)tree.clazz;
2181 List<JCExpression> prevTypeargs = ta.arguments;
2182 try {
2183 //create a 'fake' diamond AST node by removing type-argument trees
2184 ta.arguments = List.nil();
2185 ResultInfo findDiamondResult = new ResultInfo(VAL,
2186 resultInfo.checkContext.inferenceContext().free(resultInfo.pt) ? Type.noType : pt());
2187 Type inferred = deferredAttr.attribSpeculative(tree, env, findDiamondResult).type;
2188 Type polyPt = allowPoly ?
2189 syms.objectType :
2190 clazztype;
2191 if (!inferred.isErroneous() &&
2192 (allowPoly && pt() == Infer.anyPoly ?
2193 types.isSameType(inferred, clazztype) :
2194 types.isAssignable(inferred, pt().hasTag(NONE) ? polyPt : pt(), types.noWarnings))) {
2195 String key = types.isSameType(clazztype, inferred) ?
2196 "diamond.redundant.args" :
2197 "diamond.redundant.args.1";
2198 log.warning(tree.clazz.pos(), key, clazztype, inferred);
2199 }
2200 } finally {
2201 ta.arguments = prevTypeargs;
2202 }
2203 }
2205 private void checkLambdaCandidate(JCNewClass tree, ClassSymbol csym, Type clazztype) {
2206 if (allowLambda &&
2207 identifyLambdaCandidate &&
2208 clazztype.hasTag(CLASS) &&
2209 !pt().hasTag(NONE) &&
2210 types.isFunctionalInterface(clazztype.tsym)) {
2211 Symbol descriptor = types.findDescriptorSymbol(clazztype.tsym);
2212 int count = 0;
2213 boolean found = false;
2214 for (Symbol sym : csym.members().getElements()) {
2215 if ((sym.flags() & SYNTHETIC) != 0 ||
2216 sym.isConstructor()) continue;
2217 count++;
2218 if (sym.kind != MTH ||
2219 !sym.name.equals(descriptor.name)) continue;
2220 Type mtype = types.memberType(clazztype, sym);
2221 if (types.overrideEquivalent(mtype, types.memberType(clazztype, descriptor))) {
2222 found = true;
2223 }
2224 }
2225 if (found && count == 1) {
2226 log.note(tree.def, "potential.lambda.found");
2227 }
2228 }
2229 }
2231 /** Make an attributed null check tree.
2232 */
2233 public JCExpression makeNullCheck(JCExpression arg) {
2234 // optimization: X.this is never null; skip null check
2235 Name name = TreeInfo.name(arg);
2236 if (name == names._this || name == names._super) return arg;
2238 JCTree.Tag optag = NULLCHK;
2239 JCUnary tree = make.at(arg.pos).Unary(optag, arg);
2240 tree.operator = syms.nullcheck;
2241 tree.type = arg.type;
2242 return tree;
2243 }
2245 public void visitNewArray(JCNewArray tree) {
2246 Type owntype = types.createErrorType(tree.type);
2247 Env<AttrContext> localEnv = env.dup(tree);
2248 Type elemtype;
2249 if (tree.elemtype != null) {
2250 elemtype = attribType(tree.elemtype, localEnv);
2251 chk.validate(tree.elemtype, localEnv);
2252 owntype = elemtype;
2253 for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
2254 attribExpr(l.head, localEnv, syms.intType);
2255 owntype = new ArrayType(owntype, syms.arrayClass);
2256 }
2257 } else {
2258 // we are seeing an untyped aggregate { ... }
2259 // this is allowed only if the prototype is an array
2260 if (pt().hasTag(ARRAY)) {
2261 elemtype = types.elemtype(pt());
2262 } else {
2263 if (!pt().hasTag(ERROR)) {
2264 log.error(tree.pos(), "illegal.initializer.for.type",
2265 pt());
2266 }
2267 elemtype = types.createErrorType(pt());
2268 }
2269 }
2270 if (tree.elems != null) {
2271 attribExprs(tree.elems, localEnv, elemtype);
2272 owntype = new ArrayType(elemtype, syms.arrayClass);
2273 }
2274 if (!types.isReifiable(elemtype))
2275 log.error(tree.pos(), "generic.array.creation");
2276 result = check(tree, owntype, VAL, resultInfo);
2277 }
2279 /*
2280 * A lambda expression can only be attributed when a target-type is available.
2281 * In addition, if the target-type is that of a functional interface whose
2282 * descriptor contains inference variables in argument position the lambda expression
2283 * is 'stuck' (see DeferredAttr).
2284 */
2285 @Override
2286 public void visitLambda(final JCLambda that) {
2287 if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
2288 if (pt().hasTag(NONE)) {
2289 //lambda only allowed in assignment or method invocation/cast context
2290 log.error(that.pos(), "unexpected.lambda");
2291 }
2292 result = that.type = types.createErrorType(pt());
2293 return;
2294 }
2295 //create an environment for attribution of the lambda expression
2296 final Env<AttrContext> localEnv = lambdaEnv(that, env);
2297 boolean needsRecovery =
2298 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK;
2299 try {
2300 Type currentTarget = pt();
2301 List<Type> explicitParamTypes = null;
2302 if (that.paramKind == JCLambda.ParameterKind.EXPLICIT) {
2303 //attribute lambda parameters
2304 attribStats(that.params, localEnv);
2305 explicitParamTypes = TreeInfo.types(that.params);
2306 }
2308 Type lambdaType;
2309 if (pt() != Type.recoveryType) {
2310 /* We need to adjust the target. If the target is an
2311 * intersection type, for example: SAM & I1 & I2 ...
2312 * the target will be updated to SAM
2313 */
2314 currentTarget = targetChecker.visit(currentTarget, that);
2315 if (explicitParamTypes != null) {
2316 currentTarget = infer.instantiateFunctionalInterface(that,
2317 currentTarget, explicitParamTypes, resultInfo.checkContext);
2318 }
2319 lambdaType = types.findDescriptorType(currentTarget);
2320 } else {
2321 currentTarget = Type.recoveryType;
2322 lambdaType = fallbackDescriptorType(that);
2323 }
2325 setFunctionalInfo(localEnv, that, pt(), lambdaType, currentTarget, resultInfo.checkContext);
2327 if (lambdaType.hasTag(FORALL)) {
2328 //lambda expression target desc cannot be a generic method
2329 resultInfo.checkContext.report(that, diags.fragment("invalid.generic.lambda.target",
2330 lambdaType, kindName(currentTarget.tsym), currentTarget.tsym));
2331 result = that.type = types.createErrorType(pt());
2332 return;
2333 }
2335 if (that.paramKind == JCLambda.ParameterKind.IMPLICIT) {
2336 //add param type info in the AST
2337 List<Type> actuals = lambdaType.getParameterTypes();
2338 List<JCVariableDecl> params = that.params;
2340 boolean arityMismatch = false;
2342 while (params.nonEmpty()) {
2343 if (actuals.isEmpty()) {
2344 //not enough actuals to perform lambda parameter inference
2345 arityMismatch = true;
2346 }
2347 //reset previously set info
2348 Type argType = arityMismatch ?
2349 syms.errType :
2350 actuals.head;
2351 params.head.vartype = make.at(params.head).Type(argType);
2352 params.head.sym = null;
2353 actuals = actuals.isEmpty() ?
2354 actuals :
2355 actuals.tail;
2356 params = params.tail;
2357 }
2359 //attribute lambda parameters
2360 attribStats(that.params, localEnv);
2362 if (arityMismatch) {
2363 resultInfo.checkContext.report(that, diags.fragment("incompatible.arg.types.in.lambda"));
2364 result = that.type = types.createErrorType(currentTarget);
2365 return;
2366 }
2367 }
2369 //from this point on, no recovery is needed; if we are in assignment context
2370 //we will be able to attribute the whole lambda body, regardless of errors;
2371 //if we are in a 'check' method context, and the lambda is not compatible
2372 //with the target-type, it will be recovered anyway in Attr.checkId
2373 needsRecovery = false;
2375 FunctionalReturnContext funcContext = that.getBodyKind() == JCLambda.BodyKind.EXPRESSION ?
2376 new ExpressionLambdaReturnContext((JCExpression)that.getBody(), resultInfo.checkContext) :
2377 new FunctionalReturnContext(resultInfo.checkContext);
2379 ResultInfo bodyResultInfo = lambdaType.getReturnType() == Type.recoveryType ?
2380 recoveryInfo :
2381 new ResultInfo(VAL, lambdaType.getReturnType(), funcContext);
2382 localEnv.info.returnResult = bodyResultInfo;
2384 if (that.getBodyKind() == JCLambda.BodyKind.EXPRESSION) {
2385 attribTree(that.getBody(), localEnv, bodyResultInfo);
2386 } else {
2387 JCBlock body = (JCBlock)that.body;
2388 attribStats(body.stats, localEnv);
2389 }
2391 result = check(that, currentTarget, VAL, resultInfo);
2393 boolean isSpeculativeRound =
2394 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
2396 preFlow(that);
2397 flow.analyzeLambda(env, that, make, isSpeculativeRound);
2399 checkLambdaCompatible(that, lambdaType, resultInfo.checkContext);
2401 if (!isSpeculativeRound) {
2402 //add thrown types as bounds to the thrown types free variables if needed:
2403 if (resultInfo.checkContext.inferenceContext().free(lambdaType.getThrownTypes())) {
2404 List<Type> inferredThrownTypes = flow.analyzeLambdaThrownTypes(env, that, make);
2405 List<Type> thrownTypes = resultInfo.checkContext.inferenceContext().asUndetVars(lambdaType.getThrownTypes());
2407 chk.unhandled(inferredThrownTypes, thrownTypes);
2408 }
2410 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), lambdaType, currentTarget);
2411 }
2412 result = check(that, currentTarget, VAL, resultInfo);
2413 } catch (Types.FunctionDescriptorLookupError ex) {
2414 JCDiagnostic cause = ex.getDiagnostic();
2415 resultInfo.checkContext.report(that, cause);
2416 result = that.type = types.createErrorType(pt());
2417 return;
2418 } finally {
2419 localEnv.info.scope.leave();
2420 if (needsRecovery) {
2421 attribTree(that, env, recoveryInfo);
2422 }
2423 }
2424 }
2425 //where
2426 void preFlow(JCLambda tree) {
2427 new PostAttrAnalyzer() {
2428 @Override
2429 public void scan(JCTree tree) {
2430 if (tree == null ||
2431 (tree.type != null &&
2432 tree.type == Type.stuckType)) {
2433 //don't touch stuck expressions!
2434 return;
2435 }
2436 super.scan(tree);
2437 }
2438 }.scan(tree);
2439 }
2441 Types.MapVisitor<DiagnosticPosition> targetChecker = new Types.MapVisitor<DiagnosticPosition>() {
2443 @Override
2444 public Type visitClassType(ClassType t, DiagnosticPosition pos) {
2445 return t.isCompound() ?
2446 visitIntersectionClassType((IntersectionClassType)t, pos) : t;
2447 }
2449 public Type visitIntersectionClassType(IntersectionClassType ict, DiagnosticPosition pos) {
2450 Symbol desc = types.findDescriptorSymbol(makeNotionalInterface(ict));
2451 Type target = null;
2452 for (Type bound : ict.getExplicitComponents()) {
2453 TypeSymbol boundSym = bound.tsym;
2454 if (types.isFunctionalInterface(boundSym) &&
2455 types.findDescriptorSymbol(boundSym) == desc) {
2456 target = bound;
2457 } else if (!boundSym.isInterface() || (boundSym.flags() & ANNOTATION) != 0) {
2458 //bound must be an interface
2459 reportIntersectionError(pos, "not.an.intf.component", boundSym);
2460 }
2461 }
2462 return target != null ?
2463 target :
2464 ict.getExplicitComponents().head; //error recovery
2465 }
2467 private TypeSymbol makeNotionalInterface(IntersectionClassType ict) {
2468 ListBuffer<Type> targs = new ListBuffer<>();
2469 ListBuffer<Type> supertypes = new ListBuffer<>();
2470 for (Type i : ict.interfaces_field) {
2471 if (i.isParameterized()) {
2472 targs.appendList(i.tsym.type.allparams());
2473 }
2474 supertypes.append(i.tsym.type);
2475 }
2476 IntersectionClassType notionalIntf =
2477 (IntersectionClassType)types.makeCompoundType(supertypes.toList());
2478 notionalIntf.allparams_field = targs.toList();
2479 notionalIntf.tsym.flags_field |= INTERFACE;
2480 return notionalIntf.tsym;
2481 }
2483 private void reportIntersectionError(DiagnosticPosition pos, String key, Object... args) {
2484 resultInfo.checkContext.report(pos, diags.fragment("bad.intersection.target.for.functional.expr",
2485 diags.fragment(key, args)));
2486 }
2487 };
2489 private Type fallbackDescriptorType(JCExpression tree) {
2490 switch (tree.getTag()) {
2491 case LAMBDA:
2492 JCLambda lambda = (JCLambda)tree;
2493 List<Type> argtypes = List.nil();
2494 for (JCVariableDecl param : lambda.params) {
2495 argtypes = param.vartype != null ?
2496 argtypes.append(param.vartype.type) :
2497 argtypes.append(syms.errType);
2498 }
2499 return new MethodType(argtypes, Type.recoveryType,
2500 List.of(syms.throwableType), syms.methodClass);
2501 case REFERENCE:
2502 return new MethodType(List.<Type>nil(), Type.recoveryType,
2503 List.of(syms.throwableType), syms.methodClass);
2504 default:
2505 Assert.error("Cannot get here!");
2506 }
2507 return null;
2508 }
2510 private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
2511 final InferenceContext inferenceContext, final Type... ts) {
2512 checkAccessibleTypes(pos, env, inferenceContext, List.from(ts));
2513 }
2515 private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
2516 final InferenceContext inferenceContext, final List<Type> ts) {
2517 if (inferenceContext.free(ts)) {
2518 inferenceContext.addFreeTypeListener(ts, new FreeTypeListener() {
2519 @Override
2520 public void typesInferred(InferenceContext inferenceContext) {
2521 checkAccessibleTypes(pos, env, inferenceContext, inferenceContext.asInstTypes(ts));
2522 }
2523 });
2524 } else {
2525 for (Type t : ts) {
2526 rs.checkAccessibleType(env, t);
2527 }
2528 }
2529 }
2531 /**
2532 * Lambda/method reference have a special check context that ensures
2533 * that i.e. a lambda return type is compatible with the expected
2534 * type according to both the inherited context and the assignment
2535 * context.
2536 */
2537 class FunctionalReturnContext extends Check.NestedCheckContext {
2539 FunctionalReturnContext(CheckContext enclosingContext) {
2540 super(enclosingContext);
2541 }
2543 @Override
2544 public boolean compatible(Type found, Type req, Warner warn) {
2545 //return type must be compatible in both current context and assignment context
2546 return chk.basicHandler.compatible(found, inferenceContext().asUndetVar(req), warn);
2547 }
2549 @Override
2550 public void report(DiagnosticPosition pos, JCDiagnostic details) {
2551 enclosingContext.report(pos, diags.fragment("incompatible.ret.type.in.lambda", details));
2552 }
2553 }
2555 class ExpressionLambdaReturnContext extends FunctionalReturnContext {
2557 JCExpression expr;
2559 ExpressionLambdaReturnContext(JCExpression expr, CheckContext enclosingContext) {
2560 super(enclosingContext);
2561 this.expr = expr;
2562 }
2564 @Override
2565 public boolean compatible(Type found, Type req, Warner warn) {
2566 //a void return is compatible with an expression statement lambda
2567 return TreeInfo.isExpressionStatement(expr) && req.hasTag(VOID) ||
2568 super.compatible(found, req, warn);
2569 }
2570 }
2572 /**
2573 * Lambda compatibility. Check that given return types, thrown types, parameter types
2574 * are compatible with the expected functional interface descriptor. This means that:
2575 * (i) parameter types must be identical to those of the target descriptor; (ii) return
2576 * types must be compatible with the return type of the expected descriptor.
2577 */
2578 private void checkLambdaCompatible(JCLambda tree, Type descriptor, CheckContext checkContext) {
2579 Type returnType = checkContext.inferenceContext().asUndetVar(descriptor.getReturnType());
2581 //return values have already been checked - but if lambda has no return
2582 //values, we must ensure that void/value compatibility is correct;
2583 //this amounts at checking that, if a lambda body can complete normally,
2584 //the descriptor's return type must be void
2585 if (tree.getBodyKind() == JCLambda.BodyKind.STATEMENT && tree.canCompleteNormally &&
2586 !returnType.hasTag(VOID) && returnType != Type.recoveryType) {
2587 checkContext.report(tree, diags.fragment("incompatible.ret.type.in.lambda",
2588 diags.fragment("missing.ret.val", returnType)));
2589 }
2591 List<Type> argTypes = checkContext.inferenceContext().asUndetVars(descriptor.getParameterTypes());
2592 if (!types.isSameTypes(argTypes, TreeInfo.types(tree.params))) {
2593 checkContext.report(tree, diags.fragment("incompatible.arg.types.in.lambda"));
2594 }
2595 }
2597 /* Map to hold 'fake' clinit methods. If a lambda is used to initialize a
2598 * static field and that lambda has type annotations, these annotations will
2599 * also be stored at these fake clinit methods.
2600 *
2601 * LambdaToMethod also use fake clinit methods so they can be reused.
2602 * Also as LTM is a phase subsequent to attribution, the methods from
2603 * clinits can be safely removed by LTM to save memory.
2604 */
2605 private Map<ClassSymbol, MethodSymbol> clinits = new HashMap<>();
2607 public MethodSymbol removeClinit(ClassSymbol sym) {
2608 return clinits.remove(sym);
2609 }
2611 /* This method returns an environment to be used to attribute a lambda
2612 * expression.
2613 *
2614 * The owner of this environment is a method symbol. If the current owner
2615 * is not a method, for example if the lambda is used to initialize
2616 * a field, then if the field is:
2617 *
2618 * - an instance field, we use the first constructor.
2619 * - a static field, we create a fake clinit method.
2620 */
2621 public Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) {
2622 Env<AttrContext> lambdaEnv;
2623 Symbol owner = env.info.scope.owner;
2624 if (owner.kind == VAR && owner.owner.kind == TYP) {
2625 //field initializer
2626 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared()));
2627 ClassSymbol enclClass = owner.enclClass();
2628 /* if the field isn't static, then we can get the first constructor
2629 * and use it as the owner of the environment. This is what
2630 * LTM code is doing to look for type annotations so we are fine.
2631 */
2632 if ((owner.flags() & STATIC) == 0) {
2633 for (Symbol s : enclClass.members_field.getElementsByName(names.init)) {
2634 lambdaEnv.info.scope.owner = s;
2635 break;
2636 }
2637 } else {
2638 /* if the field is static then we need to create a fake clinit
2639 * method, this method can later be reused by LTM.
2640 */
2641 MethodSymbol clinit = clinits.get(enclClass);
2642 if (clinit == null) {
2643 Type clinitType = new MethodType(List.<Type>nil(),
2644 syms.voidType, List.<Type>nil(), syms.methodClass);
2645 clinit = new MethodSymbol(STATIC | SYNTHETIC | PRIVATE,
2646 names.clinit, clinitType, enclClass);
2647 clinit.params = List.<VarSymbol>nil();
2648 clinits.put(enclClass, clinit);
2649 }
2650 lambdaEnv.info.scope.owner = clinit;
2651 }
2652 } else {
2653 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dup()));
2654 }
2655 return lambdaEnv;
2656 }
2658 @Override
2659 public void visitReference(final JCMemberReference that) {
2660 if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
2661 if (pt().hasTag(NONE)) {
2662 //method reference only allowed in assignment or method invocation/cast context
2663 log.error(that.pos(), "unexpected.mref");
2664 }
2665 result = that.type = types.createErrorType(pt());
2666 return;
2667 }
2668 final Env<AttrContext> localEnv = env.dup(that);
2669 try {
2670 //attribute member reference qualifier - if this is a constructor
2671 //reference, the expected kind must be a type
2672 Type exprType = attribTree(that.expr, env, memberReferenceQualifierResult(that));
2674 if (that.getMode() == JCMemberReference.ReferenceMode.NEW) {
2675 exprType = chk.checkConstructorRefType(that.expr, exprType);
2676 if (!exprType.isErroneous() &&
2677 exprType.isRaw() &&
2678 that.typeargs != null) {
2679 log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
2680 diags.fragment("mref.infer.and.explicit.params"));
2681 exprType = types.createErrorType(exprType);
2682 }
2683 }
2685 if (exprType.isErroneous()) {
2686 //if the qualifier expression contains problems,
2687 //give up attribution of method reference
2688 result = that.type = exprType;
2689 return;
2690 }
2692 if (TreeInfo.isStaticSelector(that.expr, names)) {
2693 //if the qualifier is a type, validate it; raw warning check is
2694 //omitted as we don't know at this stage as to whether this is a
2695 //raw selector (because of inference)
2696 chk.validate(that.expr, env, false);
2697 }
2699 //attrib type-arguments
2700 List<Type> typeargtypes = List.nil();
2701 if (that.typeargs != null) {
2702 typeargtypes = attribTypes(that.typeargs, localEnv);
2703 }
2705 Type target;
2706 Type desc;
2707 if (pt() != Type.recoveryType) {
2708 target = targetChecker.visit(pt(), that);
2709 desc = types.findDescriptorType(target);
2710 } else {
2711 target = Type.recoveryType;
2712 desc = fallbackDescriptorType(that);
2713 }
2715 setFunctionalInfo(localEnv, that, pt(), desc, target, resultInfo.checkContext);
2716 List<Type> argtypes = desc.getParameterTypes();
2717 Resolve.MethodCheck referenceCheck = rs.resolveMethodCheck;
2719 if (resultInfo.checkContext.inferenceContext().free(argtypes)) {
2720 referenceCheck = rs.new MethodReferenceCheck(resultInfo.checkContext.inferenceContext());
2721 }
2723 Pair<Symbol, Resolve.ReferenceLookupHelper> refResult = null;
2724 List<Type> saved_undet = resultInfo.checkContext.inferenceContext().save();
2725 try {
2726 refResult = rs.resolveMemberReference(localEnv, that, that.expr.type,
2727 that.name, argtypes, typeargtypes, referenceCheck,
2728 resultInfo.checkContext.inferenceContext(),
2729 resultInfo.checkContext.deferredAttrContext().mode);
2730 } finally {
2731 resultInfo.checkContext.inferenceContext().rollback(saved_undet);
2732 }
2734 Symbol refSym = refResult.fst;
2735 Resolve.ReferenceLookupHelper lookupHelper = refResult.snd;
2737 if (refSym.kind != MTH) {
2738 boolean targetError;
2739 switch (refSym.kind) {
2740 case ABSENT_MTH:
2741 targetError = false;
2742 break;
2743 case WRONG_MTH:
2744 case WRONG_MTHS:
2745 case AMBIGUOUS:
2746 case HIDDEN:
2747 case STATICERR:
2748 case MISSING_ENCL:
2749 case WRONG_STATICNESS:
2750 targetError = true;
2751 break;
2752 default:
2753 Assert.error("unexpected result kind " + refSym.kind);
2754 targetError = false;
2755 }
2757 JCDiagnostic detailsDiag = ((Resolve.ResolveError)refSym).getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT,
2758 that, exprType.tsym, exprType, that.name, argtypes, typeargtypes);
2760 JCDiagnostic.DiagnosticType diagKind = targetError ?
2761 JCDiagnostic.DiagnosticType.FRAGMENT : JCDiagnostic.DiagnosticType.ERROR;
2763 JCDiagnostic diag = diags.create(diagKind, log.currentSource(), that,
2764 "invalid.mref", Kinds.kindName(that.getMode()), detailsDiag);
2766 if (targetError && target == Type.recoveryType) {
2767 //a target error doesn't make sense during recovery stage
2768 //as we don't know what actual parameter types are
2769 result = that.type = target;
2770 return;
2771 } else {
2772 if (targetError) {
2773 resultInfo.checkContext.report(that, diag);
2774 } else {
2775 log.report(diag);
2776 }
2777 result = that.type = types.createErrorType(target);
2778 return;
2779 }
2780 }
2782 that.sym = refSym.baseSymbol();
2783 that.kind = lookupHelper.referenceKind(that.sym);
2784 that.ownerAccessible = rs.isAccessible(localEnv, that.sym.enclClass());
2786 if (desc.getReturnType() == Type.recoveryType) {
2787 // stop here
2788 result = that.type = target;
2789 return;
2790 }
2792 if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
2794 if (that.getMode() == ReferenceMode.INVOKE &&
2795 TreeInfo.isStaticSelector(that.expr, names) &&
2796 that.kind.isUnbound() &&
2797 !desc.getParameterTypes().head.isParameterized()) {
2798 chk.checkRaw(that.expr, localEnv);
2799 }
2801 if (that.sym.isStatic() && TreeInfo.isStaticSelector(that.expr, names) &&
2802 exprType.getTypeArguments().nonEmpty()) {
2803 //static ref with class type-args
2804 log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
2805 diags.fragment("static.mref.with.targs"));
2806 result = that.type = types.createErrorType(target);
2807 return;
2808 }
2810 if (that.sym.isStatic() && !TreeInfo.isStaticSelector(that.expr, names) &&
2811 !that.kind.isUnbound()) {
2812 //no static bound mrefs
2813 log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
2814 diags.fragment("static.bound.mref"));
2815 result = that.type = types.createErrorType(target);
2816 return;
2817 }
2819 if (!refSym.isStatic() && that.kind == JCMemberReference.ReferenceKind.SUPER) {
2820 // Check that super-qualified symbols are not abstract (JLS)
2821 rs.checkNonAbstract(that.pos(), that.sym);
2822 }
2823 }
2825 ResultInfo checkInfo =
2826 resultInfo.dup(newMethodTemplate(
2827 desc.getReturnType().hasTag(VOID) ? Type.noType : desc.getReturnType(),
2828 that.kind.isUnbound() ? argtypes.tail : argtypes, typeargtypes));
2830 Type refType = checkId(that, lookupHelper.site, refSym, localEnv, checkInfo);
2832 if (that.kind.isUnbound() &&
2833 resultInfo.checkContext.inferenceContext().free(argtypes.head)) {
2834 //re-generate inference constraints for unbound receiver
2835 if (!types.isSubtype(resultInfo.checkContext.inferenceContext().asUndetVar(argtypes.head), exprType)) {
2836 //cannot happen as this has already been checked - we just need
2837 //to regenerate the inference constraints, as that has been lost
2838 //as a result of the call to inferenceContext.save()
2839 Assert.error("Can't get here");
2840 }
2841 }
2843 if (!refType.isErroneous()) {
2844 refType = types.createMethodTypeWithReturn(refType,
2845 adjustMethodReturnType(lookupHelper.site, that.name, checkInfo.pt.getParameterTypes(), refType.getReturnType()));
2846 }
2848 //go ahead with standard method reference compatibility check - note that param check
2849 //is a no-op (as this has been taken care during method applicability)
2850 boolean isSpeculativeRound =
2851 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
2852 checkReferenceCompatible(that, desc, refType, resultInfo.checkContext, isSpeculativeRound);
2853 if (!isSpeculativeRound) {
2854 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), desc, target);
2855 }
2856 result = check(that, target, VAL, resultInfo);
2857 } catch (Types.FunctionDescriptorLookupError ex) {
2858 JCDiagnostic cause = ex.getDiagnostic();
2859 resultInfo.checkContext.report(that, cause);
2860 result = that.type = types.createErrorType(pt());
2861 return;
2862 }
2863 }
2864 //where
2865 ResultInfo memberReferenceQualifierResult(JCMemberReference tree) {
2866 //if this is a constructor reference, the expected kind must be a type
2867 return new ResultInfo(tree.getMode() == ReferenceMode.INVOKE ? VAL | TYP : TYP, Type.noType);
2868 }
2871 @SuppressWarnings("fallthrough")
2872 void checkReferenceCompatible(JCMemberReference tree, Type descriptor, Type refType, CheckContext checkContext, boolean speculativeAttr) {
2873 Type returnType = checkContext.inferenceContext().asUndetVar(descriptor.getReturnType());
2875 Type resType;
2876 switch (tree.getMode()) {
2877 case NEW:
2878 if (!tree.expr.type.isRaw()) {
2879 resType = tree.expr.type;
2880 break;
2881 }
2882 default:
2883 resType = refType.getReturnType();
2884 }
2886 Type incompatibleReturnType = resType;
2888 if (returnType.hasTag(VOID)) {
2889 incompatibleReturnType = null;
2890 }
2892 if (!returnType.hasTag(VOID) && !resType.hasTag(VOID)) {
2893 if (resType.isErroneous() ||
2894 new FunctionalReturnContext(checkContext).compatible(resType, returnType, types.noWarnings)) {
2895 incompatibleReturnType = null;
2896 }
2897 }
2899 if (incompatibleReturnType != null) {
2900 checkContext.report(tree, diags.fragment("incompatible.ret.type.in.mref",
2901 diags.fragment("inconvertible.types", resType, descriptor.getReturnType())));
2902 }
2904 if (!speculativeAttr) {
2905 List<Type> thrownTypes = checkContext.inferenceContext().asUndetVars(descriptor.getThrownTypes());
2906 if (chk.unhandled(refType.getThrownTypes(), thrownTypes).nonEmpty()) {
2907 log.error(tree, "incompatible.thrown.types.in.mref", refType.getThrownTypes());
2908 }
2909 }
2910 }
2912 /**
2913 * Set functional type info on the underlying AST. Note: as the target descriptor
2914 * might contain inference variables, we might need to register an hook in the
2915 * current inference context.
2916 */
2917 private void setFunctionalInfo(final Env<AttrContext> env, final JCFunctionalExpression fExpr,
2918 final Type pt, final Type descriptorType, final Type primaryTarget, final CheckContext checkContext) {
2919 if (checkContext.inferenceContext().free(descriptorType)) {
2920 checkContext.inferenceContext().addFreeTypeListener(List.of(pt, descriptorType), new FreeTypeListener() {
2921 public void typesInferred(InferenceContext inferenceContext) {
2922 setFunctionalInfo(env, fExpr, pt, inferenceContext.asInstType(descriptorType),
2923 inferenceContext.asInstType(primaryTarget), checkContext);
2924 }
2925 });
2926 } else {
2927 ListBuffer<Type> targets = new ListBuffer<>();
2928 if (pt.hasTag(CLASS)) {
2929 if (pt.isCompound()) {
2930 targets.append(types.removeWildcards(primaryTarget)); //this goes first
2931 for (Type t : ((IntersectionClassType)pt()).interfaces_field) {
2932 if (t != primaryTarget) {
2933 targets.append(types.removeWildcards(t));
2934 }
2935 }
2936 } else {
2937 targets.append(types.removeWildcards(primaryTarget));
2938 }
2939 }
2940 fExpr.targets = targets.toList();
2941 if (checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
2942 pt != Type.recoveryType) {
2943 //check that functional interface class is well-formed
2944 ClassSymbol csym = types.makeFunctionalInterfaceClass(env,
2945 names.empty, List.of(fExpr.targets.head), ABSTRACT);
2946 if (csym != null) {
2947 chk.checkImplementations(env.tree, csym, csym);
2948 }
2949 }
2950 }
2951 }
2953 public void visitParens(JCParens tree) {
2954 Type owntype = attribTree(tree.expr, env, resultInfo);
2955 result = check(tree, owntype, pkind(), resultInfo);
2956 Symbol sym = TreeInfo.symbol(tree);
2957 if (sym != null && (sym.kind&(TYP|PCK)) != 0)
2958 log.error(tree.pos(), "illegal.start.of.type");
2959 }
2961 public void visitAssign(JCAssign tree) {
2962 Type owntype = attribTree(tree.lhs, env.dup(tree), varInfo);
2963 Type capturedType = capture(owntype);
2964 attribExpr(tree.rhs, env, owntype);
2965 result = check(tree, capturedType, VAL, resultInfo);
2966 }
2968 public void visitAssignop(JCAssignOp tree) {
2969 // Attribute arguments.
2970 Type owntype = attribTree(tree.lhs, env, varInfo);
2971 Type operand = attribExpr(tree.rhs, env);
2972 // Find operator.
2973 Symbol operator = tree.operator = rs.resolveBinaryOperator(
2974 tree.pos(), tree.getTag().noAssignOp(), env,
2975 owntype, operand);
2977 if (operator.kind == MTH &&
2978 !owntype.isErroneous() &&
2979 !operand.isErroneous()) {
2980 chk.checkOperator(tree.pos(),
2981 (OperatorSymbol)operator,
2982 tree.getTag().noAssignOp(),
2983 owntype,
2984 operand);
2985 chk.checkDivZero(tree.rhs.pos(), operator, operand);
2986 chk.checkCastable(tree.rhs.pos(),
2987 operator.type.getReturnType(),
2988 owntype);
2989 }
2990 result = check(tree, owntype, VAL, resultInfo);
2991 }
2993 public void visitUnary(JCUnary tree) {
2994 // Attribute arguments.
2995 Type argtype = (tree.getTag().isIncOrDecUnaryOp())
2996 ? attribTree(tree.arg, env, varInfo)
2997 : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
2999 // Find operator.
3000 Symbol operator = tree.operator =
3001 rs.resolveUnaryOperator(tree.pos(), tree.getTag(), env, argtype);
3003 Type owntype = types.createErrorType(tree.type);
3004 if (operator.kind == MTH &&
3005 !argtype.isErroneous()) {
3006 owntype = (tree.getTag().isIncOrDecUnaryOp())
3007 ? tree.arg.type
3008 : operator.type.getReturnType();
3009 int opc = ((OperatorSymbol)operator).opcode;
3011 // If the argument is constant, fold it.
3012 if (argtype.constValue() != null) {
3013 Type ctype = cfolder.fold1(opc, argtype);
3014 if (ctype != null) {
3015 owntype = cfolder.coerce(ctype, owntype);
3016 }
3017 }
3018 }
3019 result = check(tree, owntype, VAL, resultInfo);
3020 }
3022 public void visitBinary(JCBinary tree) {
3023 // Attribute arguments.
3024 Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
3025 Type right = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.rhs, env));
3027 // Find operator.
3028 Symbol operator = tree.operator =
3029 rs.resolveBinaryOperator(tree.pos(), tree.getTag(), env, left, right);
3031 Type owntype = types.createErrorType(tree.type);
3032 if (operator.kind == MTH &&
3033 !left.isErroneous() &&
3034 !right.isErroneous()) {
3035 owntype = operator.type.getReturnType();
3036 // This will figure out when unboxing can happen and
3037 // choose the right comparison operator.
3038 int opc = chk.checkOperator(tree.lhs.pos(),
3039 (OperatorSymbol)operator,
3040 tree.getTag(),
3041 left,
3042 right);
3044 // If both arguments are constants, fold them.
3045 if (left.constValue() != null && right.constValue() != null) {
3046 Type ctype = cfolder.fold2(opc, left, right);
3047 if (ctype != null) {
3048 owntype = cfolder.coerce(ctype, owntype);
3049 }
3050 }
3052 // Check that argument types of a reference ==, != are
3053 // castable to each other, (JLS 15.21). Note: unboxing
3054 // comparisons will not have an acmp* opc at this point.
3055 if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
3056 if (!types.isEqualityComparable(left, right,
3057 new Warner(tree.pos()))) {
3058 log.error(tree.pos(), "incomparable.types", left, right);
3059 }
3060 }
3062 chk.checkDivZero(tree.rhs.pos(), operator, right);
3063 }
3064 result = check(tree, owntype, VAL, resultInfo);
3065 }
3067 public void visitTypeCast(final JCTypeCast tree) {
3068 Type clazztype = attribType(tree.clazz, env);
3069 chk.validate(tree.clazz, env, false);
3070 //a fresh environment is required for 292 inference to work properly ---
3071 //see Infer.instantiatePolymorphicSignatureInstance()
3072 Env<AttrContext> localEnv = env.dup(tree);
3073 //should we propagate the target type?
3074 final ResultInfo castInfo;
3075 JCExpression expr = TreeInfo.skipParens(tree.expr);
3076 boolean isPoly = allowPoly && (expr.hasTag(LAMBDA) || expr.hasTag(REFERENCE));
3077 if (isPoly) {
3078 //expression is a poly - we need to propagate target type info
3079 castInfo = new ResultInfo(VAL, clazztype, new Check.NestedCheckContext(resultInfo.checkContext) {
3080 @Override
3081 public boolean compatible(Type found, Type req, Warner warn) {
3082 return types.isCastable(found, req, warn);
3083 }
3084 });
3085 } else {
3086 //standalone cast - target-type info is not propagated
3087 castInfo = unknownExprInfo;
3088 }
3089 Type exprtype = attribTree(tree.expr, localEnv, castInfo);
3090 Type owntype = isPoly ? clazztype : chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
3091 if (exprtype.constValue() != null)
3092 owntype = cfolder.coerce(exprtype, owntype);
3093 result = check(tree, capture(owntype), VAL, resultInfo);
3094 if (!isPoly)
3095 chk.checkRedundantCast(localEnv, tree);
3096 }
3098 public void visitTypeTest(JCInstanceOf tree) {
3099 Type exprtype = chk.checkNullOrRefType(
3100 tree.expr.pos(), attribExpr(tree.expr, env));
3101 Type clazztype = attribType(tree.clazz, env);
3102 if (!clazztype.hasTag(TYPEVAR)) {
3103 clazztype = chk.checkClassOrArrayType(tree.clazz.pos(), clazztype);
3104 }
3105 if (!clazztype.isErroneous() && !types.isReifiable(clazztype)) {
3106 log.error(tree.clazz.pos(), "illegal.generic.type.for.instof");
3107 clazztype = types.createErrorType(clazztype);
3108 }
3109 chk.validate(tree.clazz, env, false);
3110 chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
3111 result = check(tree, syms.booleanType, VAL, resultInfo);
3112 }
3114 public void visitIndexed(JCArrayAccess tree) {
3115 Type owntype = types.createErrorType(tree.type);
3116 Type atype = attribExpr(tree.indexed, env);
3117 attribExpr(tree.index, env, syms.intType);
3118 if (types.isArray(atype))
3119 owntype = types.elemtype(atype);
3120 else if (!atype.hasTag(ERROR))
3121 log.error(tree.pos(), "array.req.but.found", atype);
3122 if ((pkind() & VAR) == 0) owntype = capture(owntype);
3123 result = check(tree, owntype, VAR, resultInfo);
3124 }
3126 public void visitIdent(JCIdent tree) {
3127 Symbol sym;
3129 // Find symbol
3130 if (pt().hasTag(METHOD) || pt().hasTag(FORALL)) {
3131 // If we are looking for a method, the prototype `pt' will be a
3132 // method type with the type of the call's arguments as parameters.
3133 env.info.pendingResolutionPhase = null;
3134 sym = rs.resolveMethod(tree.pos(), env, tree.name, pt().getParameterTypes(), pt().getTypeArguments());
3135 } else if (tree.sym != null && tree.sym.kind != VAR) {
3136 sym = tree.sym;
3137 } else {
3138 sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind());
3139 }
3140 tree.sym = sym;
3142 // (1) Also find the environment current for the class where
3143 // sym is defined (`symEnv').
3144 // Only for pre-tiger versions (1.4 and earlier):
3145 // (2) Also determine whether we access symbol out of an anonymous
3146 // class in a this or super call. This is illegal for instance
3147 // members since such classes don't carry a this$n link.
3148 // (`noOuterThisPath').
3149 Env<AttrContext> symEnv = env;
3150 boolean noOuterThisPath = false;
3151 if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
3152 (sym.kind & (VAR | MTH | TYP)) != 0 &&
3153 sym.owner.kind == TYP &&
3154 tree.name != names._this && tree.name != names._super) {
3156 // Find environment in which identifier is defined.
3157 while (symEnv.outer != null &&
3158 !sym.isMemberOf(symEnv.enclClass.sym, types)) {
3159 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
3160 noOuterThisPath = !allowAnonOuterThis;
3161 symEnv = symEnv.outer;
3162 }
3163 }
3165 // If symbol is a variable, ...
3166 if (sym.kind == VAR) {
3167 VarSymbol v = (VarSymbol)sym;
3169 // ..., evaluate its initializer, if it has one, and check for
3170 // illegal forward reference.
3171 checkInit(tree, env, v, false);
3173 // If we are expecting a variable (as opposed to a value), check
3174 // that the variable is assignable in the current environment.
3175 if (pkind() == VAR)
3176 checkAssignable(tree.pos(), v, null, env);
3177 }
3179 // In a constructor body,
3180 // if symbol is a field or instance method, check that it is
3181 // not accessed before the supertype constructor is called.
3182 if ((symEnv.info.isSelfCall || noOuterThisPath) &&
3183 (sym.kind & (VAR | MTH)) != 0 &&
3184 sym.owner.kind == TYP &&
3185 (sym.flags() & STATIC) == 0) {
3186 chk.earlyRefError(tree.pos(), sym.kind == VAR ? sym : thisSym(tree.pos(), env));
3187 }
3188 Env<AttrContext> env1 = env;
3189 if (sym.kind != ERR && sym.kind != TYP && sym.owner != null && sym.owner != env1.enclClass.sym) {
3190 // If the found symbol is inaccessible, then it is
3191 // accessed through an enclosing instance. Locate this
3192 // enclosing instance:
3193 while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
3194 env1 = env1.outer;
3195 }
3196 result = checkId(tree, env1.enclClass.sym.type, sym, env, resultInfo);
3197 }
3199 public void visitSelect(JCFieldAccess tree) {
3200 // Determine the expected kind of the qualifier expression.
3201 int skind = 0;
3202 if (tree.name == names._this || tree.name == names._super ||
3203 tree.name == names._class)
3204 {
3205 skind = TYP;
3206 } else {
3207 if ((pkind() & PCK) != 0) skind = skind | PCK;
3208 if ((pkind() & TYP) != 0) skind = skind | TYP | PCK;
3209 if ((pkind() & (VAL | MTH)) != 0) skind = skind | VAL | TYP;
3210 }
3212 // Attribute the qualifier expression, and determine its symbol (if any).
3213 Type site = attribTree(tree.selected, env, new ResultInfo(skind, Infer.anyPoly));
3214 if ((pkind() & (PCK | TYP)) == 0)
3215 site = capture(site); // Capture field access
3217 // don't allow T.class T[].class, etc
3218 if (skind == TYP) {
3219 Type elt = site;
3220 while (elt.hasTag(ARRAY))
3221 elt = ((ArrayType)elt.unannotatedType()).elemtype;
3222 if (elt.hasTag(TYPEVAR)) {
3223 log.error(tree.pos(), "type.var.cant.be.deref");
3224 result = types.createErrorType(tree.type);
3225 return;
3226 }
3227 }
3229 // If qualifier symbol is a type or `super', assert `selectSuper'
3230 // for the selection. This is relevant for determining whether
3231 // protected symbols are accessible.
3232 Symbol sitesym = TreeInfo.symbol(tree.selected);
3233 boolean selectSuperPrev = env.info.selectSuper;
3234 env.info.selectSuper =
3235 sitesym != null &&
3236 sitesym.name == names._super;
3238 // Determine the symbol represented by the selection.
3239 env.info.pendingResolutionPhase = null;
3240 Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
3241 if (sym.exists() && !isType(sym) && (pkind() & (PCK | TYP)) != 0) {
3242 site = capture(site);
3243 sym = selectSym(tree, sitesym, site, env, resultInfo);
3244 }
3245 boolean varArgs = env.info.lastResolveVarargs();
3246 tree.sym = sym;
3248 if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) {
3249 while (site.hasTag(TYPEVAR)) site = site.getUpperBound();
3250 site = capture(site);
3251 }
3253 // If that symbol is a variable, ...
3254 if (sym.kind == VAR) {
3255 VarSymbol v = (VarSymbol)sym;
3257 // ..., evaluate its initializer, if it has one, and check for
3258 // illegal forward reference.
3259 checkInit(tree, env, v, true);
3261 // If we are expecting a variable (as opposed to a value), check
3262 // that the variable is assignable in the current environment.
3263 if (pkind() == VAR)
3264 checkAssignable(tree.pos(), v, tree.selected, env);
3265 }
3267 if (sitesym != null &&
3268 sitesym.kind == VAR &&
3269 ((VarSymbol)sitesym).isResourceVariable() &&
3270 sym.kind == MTH &&
3271 sym.name.equals(names.close) &&
3272 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) &&
3273 env.info.lint.isEnabled(LintCategory.TRY)) {
3274 log.warning(LintCategory.TRY, tree, "try.explicit.close.call");
3275 }
3277 // Disallow selecting a type from an expression
3278 if (isType(sym) && (sitesym==null || (sitesym.kind&(TYP|PCK)) == 0)) {
3279 tree.type = check(tree.selected, pt(),
3280 sitesym == null ? VAL : sitesym.kind, new ResultInfo(TYP|PCK, pt()));
3281 }
3283 if (isType(sitesym)) {
3284 if (sym.name == names._this) {
3285 // If `C' is the currently compiled class, check that
3286 // C.this' does not appear in a call to a super(...)
3287 if (env.info.isSelfCall &&
3288 site.tsym == env.enclClass.sym) {
3289 chk.earlyRefError(tree.pos(), sym);
3290 }
3291 } else {
3292 // Check if type-qualified fields or methods are static (JLS)
3293 if ((sym.flags() & STATIC) == 0 &&
3294 !env.next.tree.hasTag(REFERENCE) &&
3295 sym.name != names._super &&
3296 (sym.kind == VAR || sym.kind == MTH)) {
3297 rs.accessBase(rs.new StaticError(sym),
3298 tree.pos(), site, sym.name, true);
3299 }
3300 }
3301 } else if (sym.kind != ERR && (sym.flags() & STATIC) != 0 && sym.name != names._class) {
3302 // If the qualified item is not a type and the selected item is static, report
3303 // a warning. Make allowance for the class of an array type e.g. Object[].class)
3304 chk.warnStatic(tree, "static.not.qualified.by.type", Kinds.kindName(sym.kind), sym.owner);
3305 }
3307 // If we are selecting an instance member via a `super', ...
3308 if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
3310 // Check that super-qualified symbols are not abstract (JLS)
3311 rs.checkNonAbstract(tree.pos(), sym);
3313 if (site.isRaw()) {
3314 // Determine argument types for site.
3315 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
3316 if (site1 != null) site = site1;
3317 }
3318 }
3320 env.info.selectSuper = selectSuperPrev;
3321 result = checkId(tree, site, sym, env, resultInfo);
3322 }
3323 //where
3324 /** Determine symbol referenced by a Select expression,
3325 *
3326 * @param tree The select tree.
3327 * @param site The type of the selected expression,
3328 * @param env The current environment.
3329 * @param resultInfo The current result.
3330 */
3331 private Symbol selectSym(JCFieldAccess tree,
3332 Symbol location,
3333 Type site,
3334 Env<AttrContext> env,
3335 ResultInfo resultInfo) {
3336 DiagnosticPosition pos = tree.pos();
3337 Name name = tree.name;
3338 switch (site.getTag()) {
3339 case PACKAGE:
3340 return rs.accessBase(
3341 rs.findIdentInPackage(env, site.tsym, name, resultInfo.pkind),
3342 pos, location, site, name, true);
3343 case ARRAY:
3344 case CLASS:
3345 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) {
3346 return rs.resolveQualifiedMethod(
3347 pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
3348 } else if (name == names._this || name == names._super) {
3349 return rs.resolveSelf(pos, env, site.tsym, name);
3350 } else if (name == names._class) {
3351 // In this case, we have already made sure in
3352 // visitSelect that qualifier expression is a type.
3353 Type t = syms.classType;
3354 List<Type> typeargs = allowGenerics
3355 ? List.of(types.erasure(site))
3356 : List.<Type>nil();
3357 t = new ClassType(t.getEnclosingType(), typeargs, t.tsym);
3358 return new VarSymbol(
3359 STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
3360 } else {
3361 // We are seeing a plain identifier as selector.
3362 Symbol sym = rs.findIdentInType(env, site, name, resultInfo.pkind);
3363 if ((resultInfo.pkind & ERRONEOUS) == 0)
3364 sym = rs.accessBase(sym, pos, location, site, name, true);
3365 return sym;
3366 }
3367 case WILDCARD:
3368 throw new AssertionError(tree);
3369 case TYPEVAR:
3370 // Normally, site.getUpperBound() shouldn't be null.
3371 // It should only happen during memberEnter/attribBase
3372 // when determining the super type which *must* beac
3373 // done before attributing the type variables. In
3374 // other words, we are seeing this illegal program:
3375 // class B<T> extends A<T.foo> {}
3376 Symbol sym = (site.getUpperBound() != null)
3377 ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
3378 : null;
3379 if (sym == null) {
3380 log.error(pos, "type.var.cant.be.deref");
3381 return syms.errSymbol;
3382 } else {
3383 Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
3384 rs.new AccessError(env, site, sym) :
3385 sym;
3386 rs.accessBase(sym2, pos, location, site, name, true);
3387 return sym;
3388 }
3389 case ERROR:
3390 // preserve identifier names through errors
3391 return types.createErrorType(name, site.tsym, site).tsym;
3392 default:
3393 // The qualifier expression is of a primitive type -- only
3394 // .class is allowed for these.
3395 if (name == names._class) {
3396 // In this case, we have already made sure in Select that
3397 // qualifier expression is a type.
3398 Type t = syms.classType;
3399 Type arg = types.boxedClass(site).type;
3400 t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym);
3401 return new VarSymbol(
3402 STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
3403 } else {
3404 log.error(pos, "cant.deref", site);
3405 return syms.errSymbol;
3406 }
3407 }
3408 }
3410 /** Determine type of identifier or select expression and check that
3411 * (1) the referenced symbol is not deprecated
3412 * (2) the symbol's type is safe (@see checkSafe)
3413 * (3) if symbol is a variable, check that its type and kind are
3414 * compatible with the prototype and protokind.
3415 * (4) if symbol is an instance field of a raw type,
3416 * which is being assigned to, issue an unchecked warning if its
3417 * type changes under erasure.
3418 * (5) if symbol is an instance method of a raw type, issue an
3419 * unchecked warning if its argument types change under erasure.
3420 * If checks succeed:
3421 * If symbol is a constant, return its constant type
3422 * else if symbol is a method, return its result type
3423 * otherwise return its type.
3424 * Otherwise return errType.
3425 *
3426 * @param tree The syntax tree representing the identifier
3427 * @param site If this is a select, the type of the selected
3428 * expression, otherwise the type of the current class.
3429 * @param sym The symbol representing the identifier.
3430 * @param env The current environment.
3431 * @param resultInfo The expected result
3432 */
3433 Type checkId(JCTree tree,
3434 Type site,
3435 Symbol sym,
3436 Env<AttrContext> env,
3437 ResultInfo resultInfo) {
3438 return (resultInfo.pt.hasTag(FORALL) || resultInfo.pt.hasTag(METHOD)) ?
3439 checkMethodId(tree, site, sym, env, resultInfo) :
3440 checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
3441 }
3443 Type checkMethodId(JCTree tree,
3444 Type site,
3445 Symbol sym,
3446 Env<AttrContext> env,
3447 ResultInfo resultInfo) {
3448 boolean isPolymorhicSignature =
3449 (sym.baseSymbol().flags() & SIGNATURE_POLYMORPHIC) != 0;
3450 return isPolymorhicSignature ?
3451 checkSigPolyMethodId(tree, site, sym, env, resultInfo) :
3452 checkMethodIdInternal(tree, site, sym, env, resultInfo);
3453 }
3455 Type checkSigPolyMethodId(JCTree tree,
3456 Type site,
3457 Symbol sym,
3458 Env<AttrContext> env,
3459 ResultInfo resultInfo) {
3460 //recover original symbol for signature polymorphic methods
3461 checkMethodIdInternal(tree, site, sym.baseSymbol(), env, resultInfo);
3462 env.info.pendingResolutionPhase = Resolve.MethodResolutionPhase.BASIC;
3463 return sym.type;
3464 }
3466 Type checkMethodIdInternal(JCTree tree,
3467 Type site,
3468 Symbol sym,
3469 Env<AttrContext> env,
3470 ResultInfo resultInfo) {
3471 if ((resultInfo.pkind & POLY) != 0) {
3472 Type pt = resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, sym, env.info.pendingResolutionPhase));
3473 Type owntype = checkIdInternal(tree, site, sym, pt, env, resultInfo);
3474 resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
3475 return owntype;
3476 } else {
3477 return checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
3478 }
3479 }
3481 Type checkIdInternal(JCTree tree,
3482 Type site,
3483 Symbol sym,
3484 Type pt,
3485 Env<AttrContext> env,
3486 ResultInfo resultInfo) {
3487 if (pt.isErroneous()) {
3488 return types.createErrorType(site);
3489 }
3490 Type owntype; // The computed type of this identifier occurrence.
3491 switch (sym.kind) {
3492 case TYP:
3493 // For types, the computed type equals the symbol's type,
3494 // except for two situations:
3495 owntype = sym.type;
3496 if (owntype.hasTag(CLASS)) {
3497 chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym);
3498 Type ownOuter = owntype.getEnclosingType();
3500 // (a) If the symbol's type is parameterized, erase it
3501 // because no type parameters were given.
3502 // We recover generic outer type later in visitTypeApply.
3503 if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
3504 owntype = types.erasure(owntype);
3505 }
3507 // (b) If the symbol's type is an inner class, then
3508 // we have to interpret its outer type as a superclass
3509 // of the site type. Example:
3510 //
3511 // class Tree<A> { class Visitor { ... } }
3512 // class PointTree extends Tree<Point> { ... }
3513 // ...PointTree.Visitor...
3514 //
3515 // Then the type of the last expression above is
3516 // Tree<Point>.Visitor.
3517 else if (ownOuter.hasTag(CLASS) && site != ownOuter) {
3518 Type normOuter = site;
3519 if (normOuter.hasTag(CLASS)) {
3520 normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
3521 }
3522 if (normOuter == null) // perhaps from an import
3523 normOuter = types.erasure(ownOuter);
3524 if (normOuter != ownOuter)
3525 owntype = new ClassType(
3526 normOuter, List.<Type>nil(), owntype.tsym);
3527 }
3528 }
3529 break;
3530 case VAR:
3531 VarSymbol v = (VarSymbol)sym;
3532 // Test (4): if symbol is an instance field of a raw type,
3533 // which is being assigned to, issue an unchecked warning if
3534 // its type changes under erasure.
3535 if (allowGenerics &&
3536 resultInfo.pkind == VAR &&
3537 v.owner.kind == TYP &&
3538 (v.flags() & STATIC) == 0 &&
3539 (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
3540 Type s = types.asOuterSuper(site, v.owner);
3541 if (s != null &&
3542 s.isRaw() &&
3543 !types.isSameType(v.type, v.erasure(types))) {
3544 chk.warnUnchecked(tree.pos(),
3545 "unchecked.assign.to.var",
3546 v, s);
3547 }
3548 }
3549 // The computed type of a variable is the type of the
3550 // variable symbol, taken as a member of the site type.
3551 owntype = (sym.owner.kind == TYP &&
3552 sym.name != names._this && sym.name != names._super)
3553 ? types.memberType(site, sym)
3554 : sym.type;
3556 // If the variable is a constant, record constant value in
3557 // computed type.
3558 if (v.getConstValue() != null && isStaticReference(tree))
3559 owntype = owntype.constType(v.getConstValue());
3561 if (resultInfo.pkind == VAL) {
3562 owntype = capture(owntype); // capture "names as expressions"
3563 }
3564 break;
3565 case MTH: {
3566 owntype = checkMethod(site, sym,
3567 new ResultInfo(resultInfo.pkind, resultInfo.pt.getReturnType(), resultInfo.checkContext),
3568 env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(),
3569 resultInfo.pt.getTypeArguments());
3570 break;
3571 }
3572 case PCK: case ERR:
3573 owntype = sym.type;
3574 break;
3575 default:
3576 throw new AssertionError("unexpected kind: " + sym.kind +
3577 " in tree " + tree);
3578 }
3580 // Test (1): emit a `deprecation' warning if symbol is deprecated.
3581 // (for constructors, the error was given when the constructor was
3582 // resolved)
3584 if (sym.name != names.init) {
3585 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym);
3586 chk.checkSunAPI(tree.pos(), sym);
3587 chk.checkProfile(tree.pos(), sym);
3588 }
3590 // Test (3): if symbol is a variable, check that its type and
3591 // kind are compatible with the prototype and protokind.
3592 return check(tree, owntype, sym.kind, resultInfo);
3593 }
3595 /** Check that variable is initialized and evaluate the variable's
3596 * initializer, if not yet done. Also check that variable is not
3597 * referenced before it is defined.
3598 * @param tree The tree making up the variable reference.
3599 * @param env The current environment.
3600 * @param v The variable's symbol.
3601 */
3602 private void checkInit(JCTree tree,
3603 Env<AttrContext> env,
3604 VarSymbol v,
3605 boolean onlyWarning) {
3606 // System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " +
3607 // tree.pos + " " + v.pos + " " +
3608 // Resolve.isStatic(env));//DEBUG
3610 // A forward reference is diagnosed if the declaration position
3611 // of the variable is greater than the current tree position
3612 // and the tree and variable definition occur in the same class
3613 // definition. Note that writes don't count as references.
3614 // This check applies only to class and instance
3615 // variables. Local variables follow different scope rules,
3616 // and are subject to definite assignment checking.
3617 if ((env.info.enclVar == v || v.pos > tree.pos) &&
3618 v.owner.kind == TYP &&
3619 canOwnInitializer(owner(env)) &&
3620 v.owner == env.info.scope.owner.enclClass() &&
3621 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
3622 (!env.tree.hasTag(ASSIGN) ||
3623 TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
3624 String suffix = (env.info.enclVar == v) ?
3625 "self.ref" : "forward.ref";
3626 if (!onlyWarning || isStaticEnumField(v)) {
3627 log.error(tree.pos(), "illegal." + suffix);
3628 } else if (useBeforeDeclarationWarning) {
3629 log.warning(tree.pos(), suffix, v);
3630 }
3631 }
3633 v.getConstValue(); // ensure initializer is evaluated
3635 checkEnumInitializer(tree, env, v);
3636 }
3638 /**
3639 * Check for illegal references to static members of enum. In
3640 * an enum type, constructors and initializers may not
3641 * reference its static members unless they are constant.
3642 *
3643 * @param tree The tree making up the variable reference.
3644 * @param env The current environment.
3645 * @param v The variable's symbol.
3646 * @jls section 8.9 Enums
3647 */
3648 private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
3649 // JLS:
3650 //
3651 // "It is a compile-time error to reference a static field
3652 // of an enum type that is not a compile-time constant
3653 // (15.28) from constructors, instance initializer blocks,
3654 // or instance variable initializer expressions of that
3655 // type. It is a compile-time error for the constructors,
3656 // instance initializer blocks, or instance variable
3657 // initializer expressions of an enum constant e to refer
3658 // to itself or to an enum constant of the same type that
3659 // is declared to the right of e."
3660 if (isStaticEnumField(v)) {
3661 ClassSymbol enclClass = env.info.scope.owner.enclClass();
3663 if (enclClass == null || enclClass.owner == null)
3664 return;
3666 // See if the enclosing class is the enum (or a
3667 // subclass thereof) declaring v. If not, this
3668 // reference is OK.
3669 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
3670 return;
3672 // If the reference isn't from an initializer, then
3673 // the reference is OK.
3674 if (!Resolve.isInitializer(env))
3675 return;
3677 log.error(tree.pos(), "illegal.enum.static.ref");
3678 }
3679 }
3681 /** Is the given symbol a static, non-constant field of an Enum?
3682 * Note: enum literals should not be regarded as such
3683 */
3684 private boolean isStaticEnumField(VarSymbol v) {
3685 return Flags.isEnum(v.owner) &&
3686 Flags.isStatic(v) &&
3687 !Flags.isConstant(v) &&
3688 v.name != names._class;
3689 }
3691 /** Can the given symbol be the owner of code which forms part
3692 * if class initialization? This is the case if the symbol is
3693 * a type or field, or if the symbol is the synthetic method.
3694 * owning a block.
3695 */
3696 private boolean canOwnInitializer(Symbol sym) {
3697 return
3698 (sym.kind & (VAR | TYP)) != 0 ||
3699 (sym.kind == MTH && (sym.flags() & BLOCK) != 0);
3700 }
3702 Warner noteWarner = new Warner();
3704 /**
3705 * Check that method arguments conform to its instantiation.
3706 **/
3707 public Type checkMethod(Type site,
3708 final Symbol sym,
3709 ResultInfo resultInfo,
3710 Env<AttrContext> env,
3711 final List<JCExpression> argtrees,
3712 List<Type> argtypes,
3713 List<Type> typeargtypes) {
3714 // Test (5): if symbol is an instance method of a raw type, issue
3715 // an unchecked warning if its argument types change under erasure.
3716 if (allowGenerics &&
3717 (sym.flags() & STATIC) == 0 &&
3718 (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
3719 Type s = types.asOuterSuper(site, sym.owner);
3720 if (s != null && s.isRaw() &&
3721 !types.isSameTypes(sym.type.getParameterTypes(),
3722 sym.erasure(types).getParameterTypes())) {
3723 chk.warnUnchecked(env.tree.pos(),
3724 "unchecked.call.mbr.of.raw.type",
3725 sym, s);
3726 }
3727 }
3729 if (env.info.defaultSuperCallSite != null) {
3730 for (Type sup : types.interfaces(env.enclClass.type).prepend(types.supertype((env.enclClass.type)))) {
3731 if (!sup.tsym.isSubClass(sym.enclClass(), types) ||
3732 types.isSameType(sup, env.info.defaultSuperCallSite)) continue;
3733 List<MethodSymbol> icand_sup =
3734 types.interfaceCandidates(sup, (MethodSymbol)sym);
3735 if (icand_sup.nonEmpty() &&
3736 icand_sup.head != sym &&
3737 icand_sup.head.overrides(sym, icand_sup.head.enclClass(), types, true)) {
3738 log.error(env.tree.pos(), "illegal.default.super.call", env.info.defaultSuperCallSite,
3739 diags.fragment("overridden.default", sym, sup));
3740 break;
3741 }
3742 }
3743 env.info.defaultSuperCallSite = null;
3744 }
3746 if (sym.isStatic() && site.isInterface() && env.tree.hasTag(APPLY)) {
3747 JCMethodInvocation app = (JCMethodInvocation)env.tree;
3748 if (app.meth.hasTag(SELECT) &&
3749 !TreeInfo.isStaticSelector(((JCFieldAccess)app.meth).selected, names)) {
3750 log.error(env.tree.pos(), "illegal.static.intf.meth.call", site);
3751 }
3752 }
3754 // Compute the identifier's instantiated type.
3755 // For methods, we need to compute the instance type by
3756 // Resolve.instantiate from the symbol's type as well as
3757 // any type arguments and value arguments.
3758 noteWarner.clear();
3759 try {
3760 Type owntype = rs.checkMethod(
3761 env,
3762 site,
3763 sym,
3764 resultInfo,
3765 argtypes,
3766 typeargtypes,
3767 noteWarner);
3769 DeferredAttr.DeferredTypeMap checkDeferredMap =
3770 deferredAttr.new DeferredTypeMap(DeferredAttr.AttrMode.CHECK, sym, env.info.pendingResolutionPhase);
3772 argtypes = Type.map(argtypes, checkDeferredMap);
3774 if (noteWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
3775 chk.warnUnchecked(env.tree.pos(),
3776 "unchecked.meth.invocation.applied",
3777 kindName(sym),
3778 sym.name,
3779 rs.methodArguments(sym.type.getParameterTypes()),
3780 rs.methodArguments(Type.map(argtypes, checkDeferredMap)),
3781 kindName(sym.location()),
3782 sym.location());
3783 owntype = new MethodType(owntype.getParameterTypes(),
3784 types.erasure(owntype.getReturnType()),
3785 types.erasure(owntype.getThrownTypes()),
3786 syms.methodClass);
3787 }
3789 return chk.checkMethod(owntype, sym, env, argtrees, argtypes, env.info.lastResolveVarargs(),
3790 resultInfo.checkContext.inferenceContext());
3791 } catch (Infer.InferenceException ex) {
3792 //invalid target type - propagate exception outwards or report error
3793 //depending on the current check context
3794 resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic());
3795 return types.createErrorType(site);
3796 } catch (Resolve.InapplicableMethodException ex) {
3797 final JCDiagnostic diag = ex.getDiagnostic();
3798 Resolve.InapplicableSymbolError errSym = rs.new InapplicableSymbolError(null) {
3799 @Override
3800 protected Pair<Symbol, JCDiagnostic> errCandidate() {
3801 return new Pair<Symbol, JCDiagnostic>(sym, diag);
3802 }
3803 };
3804 List<Type> argtypes2 = Type.map(argtypes,
3805 rs.new ResolveDeferredRecoveryMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
3806 JCDiagnostic errDiag = errSym.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
3807 env.tree, sym, site, sym.name, argtypes2, typeargtypes);
3808 log.report(errDiag);
3809 return types.createErrorType(site);
3810 }
3811 }
3813 public void visitLiteral(JCLiteral tree) {
3814 result = check(
3815 tree, litType(tree.typetag).constType(tree.value), VAL, resultInfo);
3816 }
3817 //where
3818 /** Return the type of a literal with given type tag.
3819 */
3820 Type litType(TypeTag tag) {
3821 return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()];
3822 }
3824 public void visitTypeIdent(JCPrimitiveTypeTree tree) {
3825 result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], TYP, resultInfo);
3826 }
3828 public void visitTypeArray(JCArrayTypeTree tree) {
3829 Type etype = attribType(tree.elemtype, env);
3830 Type type = new ArrayType(etype, syms.arrayClass);
3831 result = check(tree, type, TYP, resultInfo);
3832 }
3834 /** Visitor method for parameterized types.
3835 * Bound checking is left until later, since types are attributed
3836 * before supertype structure is completely known
3837 */
3838 public void visitTypeApply(JCTypeApply tree) {
3839 Type owntype = types.createErrorType(tree.type);
3841 // Attribute functor part of application and make sure it's a class.
3842 Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
3844 // Attribute type parameters
3845 List<Type> actuals = attribTypes(tree.arguments, env);
3847 if (clazztype.hasTag(CLASS)) {
3848 List<Type> formals = clazztype.tsym.type.getTypeArguments();
3849 if (actuals.isEmpty()) //diamond
3850 actuals = formals;
3852 if (actuals.length() == formals.length()) {
3853 List<Type> a = actuals;
3854 List<Type> f = formals;
3855 while (a.nonEmpty()) {
3856 a.head = a.head.withTypeVar(f.head);
3857 a = a.tail;
3858 f = f.tail;
3859 }
3860 // Compute the proper generic outer
3861 Type clazzOuter = clazztype.getEnclosingType();
3862 if (clazzOuter.hasTag(CLASS)) {
3863 Type site;
3864 JCExpression clazz = TreeInfo.typeIn(tree.clazz);
3865 if (clazz.hasTag(IDENT)) {
3866 site = env.enclClass.sym.type;
3867 } else if (clazz.hasTag(SELECT)) {
3868 site = ((JCFieldAccess) clazz).selected.type;
3869 } else throw new AssertionError(""+tree);
3870 if (clazzOuter.hasTag(CLASS) && site != clazzOuter) {
3871 if (site.hasTag(CLASS))
3872 site = types.asOuterSuper(site, clazzOuter.tsym);
3873 if (site == null)
3874 site = types.erasure(clazzOuter);
3875 clazzOuter = site;
3876 }
3877 }
3878 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym);
3879 } else {
3880 if (formals.length() != 0) {
3881 log.error(tree.pos(), "wrong.number.type.args",
3882 Integer.toString(formals.length()));
3883 } else {
3884 log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym);
3885 }
3886 owntype = types.createErrorType(tree.type);
3887 }
3888 }
3889 result = check(tree, owntype, TYP, resultInfo);
3890 }
3892 public void visitTypeUnion(JCTypeUnion tree) {
3893 ListBuffer<Type> multicatchTypes = new ListBuffer<>();
3894 ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
3895 for (JCExpression typeTree : tree.alternatives) {
3896 Type ctype = attribType(typeTree, env);
3897 ctype = chk.checkType(typeTree.pos(),
3898 chk.checkClassType(typeTree.pos(), ctype),
3899 syms.throwableType);
3900 if (!ctype.isErroneous()) {
3901 //check that alternatives of a union type are pairwise
3902 //unrelated w.r.t. subtyping
3903 if (chk.intersects(ctype, multicatchTypes.toList())) {
3904 for (Type t : multicatchTypes) {
3905 boolean sub = types.isSubtype(ctype, t);
3906 boolean sup = types.isSubtype(t, ctype);
3907 if (sub || sup) {
3908 //assume 'a' <: 'b'
3909 Type a = sub ? ctype : t;
3910 Type b = sub ? t : ctype;
3911 log.error(typeTree.pos(), "multicatch.types.must.be.disjoint", a, b);
3912 }
3913 }
3914 }
3915 multicatchTypes.append(ctype);
3916 if (all_multicatchTypes != null)
3917 all_multicatchTypes.append(ctype);
3918 } else {
3919 if (all_multicatchTypes == null) {
3920 all_multicatchTypes = new ListBuffer<>();
3921 all_multicatchTypes.appendList(multicatchTypes);
3922 }
3923 all_multicatchTypes.append(ctype);
3924 }
3925 }
3926 Type t = check(tree, types.lub(multicatchTypes.toList()), TYP, resultInfo);
3927 if (t.hasTag(CLASS)) {
3928 List<Type> alternatives =
3929 ((all_multicatchTypes == null) ? multicatchTypes : all_multicatchTypes).toList();
3930 t = new UnionClassType((ClassType) t, alternatives);
3931 }
3932 tree.type = result = t;
3933 }
3935 public void visitTypeIntersection(JCTypeIntersection tree) {
3936 attribTypes(tree.bounds, env);
3937 tree.type = result = checkIntersection(tree, tree.bounds);
3938 }
3940 public void visitTypeParameter(JCTypeParameter tree) {
3941 TypeVar typeVar = (TypeVar) tree.type;
3943 if (tree.annotations != null && tree.annotations.nonEmpty()) {
3944 annotateType(tree, tree.annotations);
3945 }
3947 if (!typeVar.bound.isErroneous()) {
3948 //fixup type-parameter bound computed in 'attribTypeVariables'
3949 typeVar.bound = checkIntersection(tree, tree.bounds);
3950 }
3951 }
3953 Type checkIntersection(JCTree tree, List<JCExpression> bounds) {
3954 Set<Type> boundSet = new HashSet<Type>();
3955 if (bounds.nonEmpty()) {
3956 // accept class or interface or typevar as first bound.
3957 bounds.head.type = checkBase(bounds.head.type, bounds.head, env, false, false, false);
3958 boundSet.add(types.erasure(bounds.head.type));
3959 if (bounds.head.type.isErroneous()) {
3960 return bounds.head.type;
3961 }
3962 else if (bounds.head.type.hasTag(TYPEVAR)) {
3963 // if first bound was a typevar, do not accept further bounds.
3964 if (bounds.tail.nonEmpty()) {
3965 log.error(bounds.tail.head.pos(),
3966 "type.var.may.not.be.followed.by.other.bounds");
3967 return bounds.head.type;
3968 }
3969 } else {
3970 // if first bound was a class or interface, accept only interfaces
3971 // as further bounds.
3972 for (JCExpression bound : bounds.tail) {
3973 bound.type = checkBase(bound.type, bound, env, false, true, false);
3974 if (bound.type.isErroneous()) {
3975 bounds = List.of(bound);
3976 }
3977 else if (bound.type.hasTag(CLASS)) {
3978 chk.checkNotRepeated(bound.pos(), types.erasure(bound.type), boundSet);
3979 }
3980 }
3981 }
3982 }
3984 if (bounds.length() == 0) {
3985 return syms.objectType;
3986 } else if (bounds.length() == 1) {
3987 return bounds.head.type;
3988 } else {
3989 Type owntype = types.makeCompoundType(TreeInfo.types(bounds));
3990 // ... the variable's bound is a class type flagged COMPOUND
3991 // (see comment for TypeVar.bound).
3992 // In this case, generate a class tree that represents the
3993 // bound class, ...
3994 JCExpression extending;
3995 List<JCExpression> implementing;
3996 if (!bounds.head.type.isInterface()) {
3997 extending = bounds.head;
3998 implementing = bounds.tail;
3999 } else {
4000 extending = null;
4001 implementing = bounds;
4002 }
4003 JCClassDecl cd = make.at(tree).ClassDef(
4004 make.Modifiers(PUBLIC | ABSTRACT),
4005 names.empty, List.<JCTypeParameter>nil(),
4006 extending, implementing, List.<JCTree>nil());
4008 ClassSymbol c = (ClassSymbol)owntype.tsym;
4009 Assert.check((c.flags() & COMPOUND) != 0);
4010 cd.sym = c;
4011 c.sourcefile = env.toplevel.sourcefile;
4013 // ... and attribute the bound class
4014 c.flags_field |= UNATTRIBUTED;
4015 Env<AttrContext> cenv = enter.classEnv(cd, env);
4016 enter.typeEnvs.put(c, cenv);
4017 attribClass(c);
4018 return owntype;
4019 }
4020 }
4022 public void visitWildcard(JCWildcard tree) {
4023 //- System.err.println("visitWildcard("+tree+");");//DEBUG
4024 Type type = (tree.kind.kind == BoundKind.UNBOUND)
4025 ? syms.objectType
4026 : attribType(tree.inner, env);
4027 result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
4028 tree.kind.kind,
4029 syms.boundClass),
4030 TYP, resultInfo);
4031 }
4033 public void visitAnnotation(JCAnnotation tree) {
4034 Assert.error("should be handled in Annotate");
4035 }
4037 public void visitAnnotatedType(JCAnnotatedType tree) {
4038 Type underlyingType = attribType(tree.getUnderlyingType(), env);
4039 this.attribAnnotationTypes(tree.annotations, env);
4040 annotateType(tree, tree.annotations);
4041 result = tree.type = underlyingType;
4042 }
4044 /**
4045 * Apply the annotations to the particular type.
4046 */
4047 public void annotateType(final JCTree tree, final List<JCAnnotation> annotations) {
4048 annotate.typeAnnotation(new Annotate.Worker() {
4049 @Override
4050 public String toString() {
4051 return "annotate " + annotations + " onto " + tree;
4052 }
4053 @Override
4054 public void run() {
4055 List<Attribute.TypeCompound> compounds = fromAnnotations(annotations);
4056 if (annotations.size() == compounds.size()) {
4057 // All annotations were successfully converted into compounds
4058 tree.type = tree.type.unannotatedType().annotatedType(compounds);
4059 }
4060 }
4061 });
4062 }
4064 private static List<Attribute.TypeCompound> fromAnnotations(List<JCAnnotation> annotations) {
4065 if (annotations.isEmpty()) {
4066 return List.nil();
4067 }
4069 ListBuffer<Attribute.TypeCompound> buf = new ListBuffer<>();
4070 for (JCAnnotation anno : annotations) {
4071 if (anno.attribute != null) {
4072 // TODO: this null-check is only needed for an obscure
4073 // ordering issue, where annotate.flush is called when
4074 // the attribute is not set yet. For an example failure
4075 // try the referenceinfos/NestedTypes.java test.
4076 // Any better solutions?
4077 buf.append((Attribute.TypeCompound) anno.attribute);
4078 }
4079 // Eventually we will want to throw an exception here, but
4080 // we can't do that just yet, because it gets triggered
4081 // when attempting to attach an annotation that isn't
4082 // defined.
4083 }
4084 return buf.toList();
4085 }
4087 public void visitErroneous(JCErroneous tree) {
4088 if (tree.errs != null)
4089 for (JCTree err : tree.errs)
4090 attribTree(err, env, new ResultInfo(ERR, pt()));
4091 result = tree.type = syms.errType;
4092 }
4094 /** Default visitor method for all other trees.
4095 */
4096 public void visitTree(JCTree tree) {
4097 throw new AssertionError();
4098 }
4100 /**
4101 * Attribute an env for either a top level tree or class declaration.
4102 */
4103 public void attrib(Env<AttrContext> env) {
4104 if (env.tree.hasTag(TOPLEVEL))
4105 attribTopLevel(env);
4106 else
4107 attribClass(env.tree.pos(), env.enclClass.sym);
4108 }
4110 /**
4111 * Attribute a top level tree. These trees are encountered when the
4112 * package declaration has annotations.
4113 */
4114 public void attribTopLevel(Env<AttrContext> env) {
4115 JCCompilationUnit toplevel = env.toplevel;
4116 try {
4117 annotate.flush();
4118 } catch (CompletionFailure ex) {
4119 chk.completionError(toplevel.pos(), ex);
4120 }
4121 }
4123 /** Main method: attribute class definition associated with given class symbol.
4124 * reporting completion failures at the given position.
4125 * @param pos The source position at which completion errors are to be
4126 * reported.
4127 * @param c The class symbol whose definition will be attributed.
4128 */
4129 public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
4130 try {
4131 annotate.flush();
4132 attribClass(c);
4133 } catch (CompletionFailure ex) {
4134 chk.completionError(pos, ex);
4135 }
4136 }
4138 /** Attribute class definition associated with given class symbol.
4139 * @param c The class symbol whose definition will be attributed.
4140 */
4141 void attribClass(ClassSymbol c) throws CompletionFailure {
4142 if (c.type.hasTag(ERROR)) return;
4144 // Check for cycles in the inheritance graph, which can arise from
4145 // ill-formed class files.
4146 chk.checkNonCyclic(null, c.type);
4148 Type st = types.supertype(c.type);
4149 if ((c.flags_field & Flags.COMPOUND) == 0) {
4150 // First, attribute superclass.
4151 if (st.hasTag(CLASS))
4152 attribClass((ClassSymbol)st.tsym);
4154 // Next attribute owner, if it is a class.
4155 if (c.owner.kind == TYP && c.owner.type.hasTag(CLASS))
4156 attribClass((ClassSymbol)c.owner);
4157 }
4159 // The previous operations might have attributed the current class
4160 // if there was a cycle. So we test first whether the class is still
4161 // UNATTRIBUTED.
4162 if ((c.flags_field & UNATTRIBUTED) != 0) {
4163 c.flags_field &= ~UNATTRIBUTED;
4165 // Get environment current at the point of class definition.
4166 Env<AttrContext> env = enter.typeEnvs.get(c);
4168 // The info.lint field in the envs stored in enter.typeEnvs is deliberately uninitialized,
4169 // because the annotations were not available at the time the env was created. Therefore,
4170 // we look up the environment chain for the first enclosing environment for which the
4171 // lint value is set. Typically, this is the parent env, but might be further if there
4172 // are any envs created as a result of TypeParameter nodes.
4173 Env<AttrContext> lintEnv = env;
4174 while (lintEnv.info.lint == null)
4175 lintEnv = lintEnv.next;
4177 // Having found the enclosing lint value, we can initialize the lint value for this class
4178 env.info.lint = lintEnv.info.lint.augment(c);
4180 Lint prevLint = chk.setLint(env.info.lint);
4181 JavaFileObject prev = log.useSource(c.sourcefile);
4182 ResultInfo prevReturnRes = env.info.returnResult;
4184 try {
4185 deferredLintHandler.flush(env.tree);
4186 env.info.returnResult = null;
4187 // java.lang.Enum may not be subclassed by a non-enum
4188 if (st.tsym == syms.enumSym &&
4189 ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
4190 log.error(env.tree.pos(), "enum.no.subclassing");
4192 // Enums may not be extended by source-level classes
4193 if (st.tsym != null &&
4194 ((st.tsym.flags_field & Flags.ENUM) != 0) &&
4195 ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
4196 log.error(env.tree.pos(), "enum.types.not.extensible");
4197 }
4198 attribClassBody(env, c);
4200 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
4201 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
4202 chk.checkFunctionalInterface((JCClassDecl) env.tree, c);
4203 } finally {
4204 env.info.returnResult = prevReturnRes;
4205 log.useSource(prev);
4206 chk.setLint(prevLint);
4207 }
4209 }
4210 }
4212 public void visitImport(JCImport tree) {
4213 // nothing to do
4214 }
4216 /** Finish the attribution of a class. */
4217 private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
4218 JCClassDecl tree = (JCClassDecl)env.tree;
4219 Assert.check(c == tree.sym);
4221 // Validate type parameters, supertype and interfaces.
4222 attribStats(tree.typarams, env);
4223 if (!c.isAnonymous()) {
4224 //already checked if anonymous
4225 chk.validate(tree.typarams, env);
4226 chk.validate(tree.extending, env);
4227 chk.validate(tree.implementing, env);
4228 }
4230 // If this is a non-abstract class, check that it has no abstract
4231 // methods or unimplemented methods of an implemented interface.
4232 if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
4233 if (!relax)
4234 chk.checkAllDefined(tree.pos(), c);
4235 }
4237 if ((c.flags() & ANNOTATION) != 0) {
4238 if (tree.implementing.nonEmpty())
4239 log.error(tree.implementing.head.pos(),
4240 "cant.extend.intf.annotation");
4241 if (tree.typarams.nonEmpty())
4242 log.error(tree.typarams.head.pos(),
4243 "intf.annotation.cant.have.type.params");
4245 // If this annotation has a @Repeatable, validate
4246 Attribute.Compound repeatable = c.attribute(syms.repeatableType.tsym);
4247 if (repeatable != null) {
4248 // get diagnostic position for error reporting
4249 DiagnosticPosition cbPos = getDiagnosticPosition(tree, repeatable.type);
4250 Assert.checkNonNull(cbPos);
4252 chk.validateRepeatable(c, repeatable, cbPos);
4253 }
4254 } else {
4255 // Check that all extended classes and interfaces
4256 // are compatible (i.e. no two define methods with same arguments
4257 // yet different return types). (JLS 8.4.6.3)
4258 chk.checkCompatibleSupertypes(tree.pos(), c.type);
4259 if (allowDefaultMethods) {
4260 chk.checkDefaultMethodClashes(tree.pos(), c.type);
4261 }
4262 }
4264 // Check that class does not import the same parameterized interface
4265 // with two different argument lists.
4266 chk.checkClassBounds(tree.pos(), c.type);
4268 tree.type = c.type;
4270 for (List<JCTypeParameter> l = tree.typarams;
4271 l.nonEmpty(); l = l.tail) {
4272 Assert.checkNonNull(env.info.scope.lookup(l.head.name).scope);
4273 }
4275 // Check that a generic class doesn't extend Throwable
4276 if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
4277 log.error(tree.extending.pos(), "generic.throwable");
4279 // Check that all methods which implement some
4280 // method conform to the method they implement.
4281 chk.checkImplementations(tree);
4283 //check that a resource implementing AutoCloseable cannot throw InterruptedException
4284 checkAutoCloseable(tree.pos(), env, c.type);
4286 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
4287 // Attribute declaration
4288 attribStat(l.head, env);
4289 // Check that declarations in inner classes are not static (JLS 8.1.2)
4290 // Make an exception for static constants.
4291 if (c.owner.kind != PCK &&
4292 ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
4293 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
4294 Symbol sym = null;
4295 if (l.head.hasTag(VARDEF)) sym = ((JCVariableDecl) l.head).sym;
4296 if (sym == null ||
4297 sym.kind != VAR ||
4298 ((VarSymbol) sym).getConstValue() == null)
4299 log.error(l.head.pos(), "icls.cant.have.static.decl", c);
4300 }
4301 }
4303 // Check for cycles among non-initial constructors.
4304 chk.checkCyclicConstructors(tree);
4306 // Check for cycles among annotation elements.
4307 chk.checkNonCyclicElements(tree);
4309 // Check for proper use of serialVersionUID
4310 if (env.info.lint.isEnabled(LintCategory.SERIAL) &&
4311 isSerializable(c) &&
4312 (c.flags() & Flags.ENUM) == 0 &&
4313 checkForSerial(c)) {
4314 checkSerialVersionUID(tree, c);
4315 }
4316 if (allowTypeAnnos) {
4317 // Correctly organize the postions of the type annotations
4318 typeAnnotations.organizeTypeAnnotationsBodies(tree);
4320 // Check type annotations applicability rules
4321 validateTypeAnnotations(tree, false);
4322 }
4323 }
4324 // where
4325 boolean checkForSerial(ClassSymbol c) {
4326 if ((c.flags() & ABSTRACT) == 0) {
4327 return true;
4328 } else {
4329 return c.members().anyMatch(anyNonAbstractOrDefaultMethod);
4330 }
4331 }
4333 public static final Filter<Symbol> anyNonAbstractOrDefaultMethod = new Filter<Symbol>() {
4334 @Override
4335 public boolean accepts(Symbol s) {
4336 return s.kind == Kinds.MTH &&
4337 (s.flags() & (DEFAULT | ABSTRACT)) != ABSTRACT;
4338 }
4339 };
4341 /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
4342 private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
4343 for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
4344 if (types.isSameType(al.head.annotationType.type, t))
4345 return al.head.pos();
4346 }
4348 return null;
4349 }
4351 /** check if a class is a subtype of Serializable, if that is available. */
4352 private boolean isSerializable(ClassSymbol c) {
4353 try {
4354 syms.serializableType.complete();
4355 }
4356 catch (CompletionFailure e) {
4357 return false;
4358 }
4359 return types.isSubtype(c.type, syms.serializableType);
4360 }
4362 /** Check that an appropriate serialVersionUID member is defined. */
4363 private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
4365 // check for presence of serialVersionUID
4366 Scope.Entry e = c.members().lookup(names.serialVersionUID);
4367 while (e.scope != null && e.sym.kind != VAR) e = e.next();
4368 if (e.scope == null) {
4369 log.warning(LintCategory.SERIAL,
4370 tree.pos(), "missing.SVUID", c);
4371 return;
4372 }
4374 // check that it is static final
4375 VarSymbol svuid = (VarSymbol)e.sym;
4376 if ((svuid.flags() & (STATIC | FINAL)) !=
4377 (STATIC | FINAL))
4378 log.warning(LintCategory.SERIAL,
4379 TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c);
4381 // check that it is long
4382 else if (!svuid.type.hasTag(LONG))
4383 log.warning(LintCategory.SERIAL,
4384 TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c);
4386 // check constant
4387 else if (svuid.getConstValue() == null)
4388 log.warning(LintCategory.SERIAL,
4389 TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c);
4390 }
4392 private Type capture(Type type) {
4393 return types.capture(type);
4394 }
4396 public void validateTypeAnnotations(JCTree tree, boolean sigOnly) {
4397 tree.accept(new TypeAnnotationsValidator(sigOnly));
4398 }
4399 //where
4400 private final class TypeAnnotationsValidator extends TreeScanner {
4402 private final boolean sigOnly;
4403 public TypeAnnotationsValidator(boolean sigOnly) {
4404 this.sigOnly = sigOnly;
4405 }
4407 public void visitAnnotation(JCAnnotation tree) {
4408 chk.validateTypeAnnotation(tree, false);
4409 super.visitAnnotation(tree);
4410 }
4411 public void visitAnnotatedType(JCAnnotatedType tree) {
4412 if (!tree.underlyingType.type.isErroneous()) {
4413 super.visitAnnotatedType(tree);
4414 }
4415 }
4416 public void visitTypeParameter(JCTypeParameter tree) {
4417 chk.validateTypeAnnotations(tree.annotations, true);
4418 scan(tree.bounds);
4419 // Don't call super.
4420 // This is needed because above we call validateTypeAnnotation with
4421 // false, which would forbid annotations on type parameters.
4422 // super.visitTypeParameter(tree);
4423 }
4424 public void visitMethodDef(JCMethodDecl tree) {
4425 if (tree.recvparam != null &&
4426 !tree.recvparam.vartype.type.isErroneous()) {
4427 checkForDeclarationAnnotations(tree.recvparam.mods.annotations,
4428 tree.recvparam.vartype.type.tsym);
4429 }
4430 if (tree.restype != null && tree.restype.type != null) {
4431 validateAnnotatedType(tree.restype, tree.restype.type);
4432 }
4433 if (sigOnly) {
4434 scan(tree.mods);
4435 scan(tree.restype);
4436 scan(tree.typarams);
4437 scan(tree.recvparam);
4438 scan(tree.params);
4439 scan(tree.thrown);
4440 } else {
4441 scan(tree.defaultValue);
4442 scan(tree.body);
4443 }
4444 }
4445 public void visitVarDef(final JCVariableDecl tree) {
4446 if (tree.sym != null && tree.sym.type != null)
4447 validateAnnotatedType(tree.vartype, tree.sym.type);
4448 scan(tree.mods);
4449 scan(tree.vartype);
4450 if (!sigOnly) {
4451 scan(tree.init);
4452 }
4453 }
4454 public void visitTypeCast(JCTypeCast tree) {
4455 if (tree.clazz != null && tree.clazz.type != null)
4456 validateAnnotatedType(tree.clazz, tree.clazz.type);
4457 super.visitTypeCast(tree);
4458 }
4459 public void visitTypeTest(JCInstanceOf tree) {
4460 if (tree.clazz != null && tree.clazz.type != null)
4461 validateAnnotatedType(tree.clazz, tree.clazz.type);
4462 super.visitTypeTest(tree);
4463 }
4464 public void visitNewClass(JCNewClass tree) {
4465 if (tree.clazz.hasTag(ANNOTATED_TYPE)) {
4466 checkForDeclarationAnnotations(((JCAnnotatedType) tree.clazz).annotations,
4467 tree.clazz.type.tsym);
4468 }
4469 if (tree.def != null) {
4470 checkForDeclarationAnnotations(tree.def.mods.annotations, tree.clazz.type.tsym);
4471 }
4472 if (tree.clazz.type != null) {
4473 validateAnnotatedType(tree.clazz, tree.clazz.type);
4474 }
4475 super.visitNewClass(tree);
4476 }
4477 public void visitNewArray(JCNewArray tree) {
4478 if (tree.elemtype != null && tree.elemtype.type != null) {
4479 if (tree.elemtype.hasTag(ANNOTATED_TYPE)) {
4480 checkForDeclarationAnnotations(((JCAnnotatedType) tree.elemtype).annotations,
4481 tree.elemtype.type.tsym);
4482 }
4483 validateAnnotatedType(tree.elemtype, tree.elemtype.type);
4484 }
4485 super.visitNewArray(tree);
4486 }
4487 public void visitClassDef(JCClassDecl tree) {
4488 if (sigOnly) {
4489 scan(tree.mods);
4490 scan(tree.typarams);
4491 scan(tree.extending);
4492 scan(tree.implementing);
4493 }
4494 for (JCTree member : tree.defs) {
4495 if (member.hasTag(Tag.CLASSDEF)) {
4496 continue;
4497 }
4498 scan(member);
4499 }
4500 }
4501 public void visitBlock(JCBlock tree) {
4502 if (!sigOnly) {
4503 scan(tree.stats);
4504 }
4505 }
4507 /* I would want to model this after
4508 * com.sun.tools.javac.comp.Check.Validator.visitSelectInternal(JCFieldAccess)
4509 * and override visitSelect and visitTypeApply.
4510 * However, we only set the annotated type in the top-level type
4511 * of the symbol.
4512 * Therefore, we need to override each individual location where a type
4513 * can occur.
4514 */
4515 private void validateAnnotatedType(final JCTree errtree, final Type type) {
4516 // System.out.println("Attr.validateAnnotatedType: " + errtree + " type: " + type);
4518 if (type.isPrimitiveOrVoid()) {
4519 return;
4520 }
4522 JCTree enclTr = errtree;
4523 Type enclTy = type;
4525 boolean repeat = true;
4526 while (repeat) {
4527 if (enclTr.hasTag(TYPEAPPLY)) {
4528 List<Type> tyargs = enclTy.getTypeArguments();
4529 List<JCExpression> trargs = ((JCTypeApply)enclTr).getTypeArguments();
4530 if (trargs.length() > 0) {
4531 // Nothing to do for diamonds
4532 if (tyargs.length() == trargs.length()) {
4533 for (int i = 0; i < tyargs.length(); ++i) {
4534 validateAnnotatedType(trargs.get(i), tyargs.get(i));
4535 }
4536 }
4537 // If the lengths don't match, it's either a diamond
4538 // or some nested type that redundantly provides
4539 // type arguments in the tree.
4540 }
4542 // Look at the clazz part of a generic type
4543 enclTr = ((JCTree.JCTypeApply)enclTr).clazz;
4544 }
4546 if (enclTr.hasTag(SELECT)) {
4547 enclTr = ((JCTree.JCFieldAccess)enclTr).getExpression();
4548 if (enclTy != null &&
4549 !enclTy.hasTag(NONE)) {
4550 enclTy = enclTy.getEnclosingType();
4551 }
4552 } else if (enclTr.hasTag(ANNOTATED_TYPE)) {
4553 JCAnnotatedType at = (JCTree.JCAnnotatedType) enclTr;
4554 if (enclTy == null ||
4555 enclTy.hasTag(NONE)) {
4556 if (at.getAnnotations().size() == 1) {
4557 log.error(at.underlyingType.pos(), "cant.type.annotate.scoping.1", at.getAnnotations().head.attribute);
4558 } else {
4559 ListBuffer<Attribute.Compound> comps = new ListBuffer<Attribute.Compound>();
4560 for (JCAnnotation an : at.getAnnotations()) {
4561 comps.add(an.attribute);
4562 }
4563 log.error(at.underlyingType.pos(), "cant.type.annotate.scoping", comps.toList());
4564 }
4565 repeat = false;
4566 }
4567 enclTr = at.underlyingType;
4568 // enclTy doesn't need to be changed
4569 } else if (enclTr.hasTag(IDENT)) {
4570 repeat = false;
4571 } else if (enclTr.hasTag(JCTree.Tag.WILDCARD)) {
4572 JCWildcard wc = (JCWildcard) enclTr;
4573 if (wc.getKind() == JCTree.Kind.EXTENDS_WILDCARD) {
4574 validateAnnotatedType(wc.getBound(), ((WildcardType)enclTy.unannotatedType()).getExtendsBound());
4575 } else if (wc.getKind() == JCTree.Kind.SUPER_WILDCARD) {
4576 validateAnnotatedType(wc.getBound(), ((WildcardType)enclTy.unannotatedType()).getSuperBound());
4577 } else {
4578 // Nothing to do for UNBOUND
4579 }
4580 repeat = false;
4581 } else if (enclTr.hasTag(TYPEARRAY)) {
4582 JCArrayTypeTree art = (JCArrayTypeTree) enclTr;
4583 validateAnnotatedType(art.getType(), ((ArrayType)enclTy.unannotatedType()).getComponentType());
4584 repeat = false;
4585 } else if (enclTr.hasTag(TYPEUNION)) {
4586 JCTypeUnion ut = (JCTypeUnion) enclTr;
4587 for (JCTree t : ut.getTypeAlternatives()) {
4588 validateAnnotatedType(t, t.type);
4589 }
4590 repeat = false;
4591 } else if (enclTr.hasTag(TYPEINTERSECTION)) {
4592 JCTypeIntersection it = (JCTypeIntersection) enclTr;
4593 for (JCTree t : it.getBounds()) {
4594 validateAnnotatedType(t, t.type);
4595 }
4596 repeat = false;
4597 } else if (enclTr.getKind() == JCTree.Kind.PRIMITIVE_TYPE ||
4598 enclTr.getKind() == JCTree.Kind.ERRONEOUS) {
4599 repeat = false;
4600 } else {
4601 Assert.error("Unexpected tree: " + enclTr + " with kind: " + enclTr.getKind() +
4602 " within: "+ errtree + " with kind: " + errtree.getKind());
4603 }
4604 }
4605 }
4607 private void checkForDeclarationAnnotations(List<? extends JCAnnotation> annotations,
4608 Symbol sym) {
4609 // Ensure that no declaration annotations are present.
4610 // Note that a tree type might be an AnnotatedType with
4611 // empty annotations, if only declaration annotations were given.
4612 // This method will raise an error for such a type.
4613 for (JCAnnotation ai : annotations) {
4614 if (!ai.type.isErroneous() &&
4615 typeAnnotations.annotationType(ai.attribute, sym) == TypeAnnotations.AnnotationType.DECLARATION) {
4616 log.error(ai.pos(), "annotation.type.not.applicable");
4617 }
4618 }
4619 }
4620 };
4622 // <editor-fold desc="post-attribution visitor">
4624 /**
4625 * Handle missing types/symbols in an AST. This routine is useful when
4626 * the compiler has encountered some errors (which might have ended up
4627 * terminating attribution abruptly); if the compiler is used in fail-over
4628 * mode (e.g. by an IDE) and the AST contains semantic errors, this routine
4629 * prevents NPE to be progagated during subsequent compilation steps.
4630 */
4631 public void postAttr(JCTree tree) {
4632 new PostAttrAnalyzer().scan(tree);
4633 }
4635 class PostAttrAnalyzer extends TreeScanner {
4637 private void initTypeIfNeeded(JCTree that) {
4638 if (that.type == null) {
4639 if (that.hasTag(METHODDEF)) {
4640 that.type = dummyMethodType();
4641 } else {
4642 that.type = syms.unknownType;
4643 }
4644 }
4645 }
4647 private Type dummyMethodType() {
4648 return new MethodType(List.<Type>nil(), syms.unknownType,
4649 List.<Type>nil(), syms.methodClass);
4650 }
4652 @Override
4653 public void scan(JCTree tree) {
4654 if (tree == null) return;
4655 if (tree instanceof JCExpression) {
4656 initTypeIfNeeded(tree);
4657 }
4658 super.scan(tree);
4659 }
4661 @Override
4662 public void visitIdent(JCIdent that) {
4663 if (that.sym == null) {
4664 that.sym = syms.unknownSymbol;
4665 }
4666 }
4668 @Override
4669 public void visitSelect(JCFieldAccess that) {
4670 if (that.sym == null) {
4671 that.sym = syms.unknownSymbol;
4672 }
4673 super.visitSelect(that);
4674 }
4676 @Override
4677 public void visitClassDef(JCClassDecl that) {
4678 initTypeIfNeeded(that);
4679 if (that.sym == null) {
4680 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol);
4681 }
4682 super.visitClassDef(that);
4683 }
4685 @Override
4686 public void visitMethodDef(JCMethodDecl that) {
4687 initTypeIfNeeded(that);
4688 if (that.sym == null) {
4689 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol);
4690 }
4691 super.visitMethodDef(that);
4692 }
4694 @Override
4695 public void visitVarDef(JCVariableDecl that) {
4696 initTypeIfNeeded(that);
4697 if (that.sym == null) {
4698 that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol);
4699 that.sym.adr = 0;
4700 }
4701 super.visitVarDef(that);
4702 }
4704 @Override
4705 public void visitNewClass(JCNewClass that) {
4706 if (that.constructor == null) {
4707 that.constructor = new MethodSymbol(0, names.init,
4708 dummyMethodType(), syms.noSymbol);
4709 }
4710 if (that.constructorType == null) {
4711 that.constructorType = syms.unknownType;
4712 }
4713 super.visitNewClass(that);
4714 }
4716 @Override
4717 public void visitAssignop(JCAssignOp that) {
4718 if (that.operator == null) {
4719 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
4720 -1, syms.noSymbol);
4721 }
4722 super.visitAssignop(that);
4723 }
4725 @Override
4726 public void visitBinary(JCBinary that) {
4727 if (that.operator == null) {
4728 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
4729 -1, syms.noSymbol);
4730 }
4731 super.visitBinary(that);
4732 }
4734 @Override
4735 public void visitUnary(JCUnary that) {
4736 if (that.operator == null) {
4737 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
4738 -1, syms.noSymbol);
4739 }
4740 super.visitUnary(that);
4741 }
4743 @Override
4744 public void visitLambda(JCLambda that) {
4745 super.visitLambda(that);
4746 if (that.targets == null) {
4747 that.targets = List.nil();
4748 }
4749 }
4751 @Override
4752 public void visitReference(JCMemberReference that) {
4753 super.visitReference(that);
4754 if (that.sym == null) {
4755 that.sym = new MethodSymbol(0, names.empty, dummyMethodType(),
4756 syms.noSymbol);
4757 }
4758 if (that.targets == null) {
4759 that.targets = List.nil();
4760 }
4761 }
4762 }
4763 // </editor-fold>
4764 }