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