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