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