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