Tue, 28 Oct 2014 08:56:23 +0100
8054448: (ann) Cannot reference field of inner class in an anonymous class
Reviewed-by: jlahoda, mcimadamore
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 try {
1014 annotate.enterStart();
1015 memberEnter.memberEnter(tree, env);
1016 } finally {
1017 annotate.enterDone();
1018 }
1019 }
1020 } else {
1021 if (tree.init != null) {
1022 // Field initializer expression need to be entered.
1023 memberEnter.typeAnnotate(tree.init, env, tree.sym, tree.pos());
1024 annotate.flush();
1025 }
1026 }
1028 VarSymbol v = tree.sym;
1029 Lint lint = env.info.lint.augment(v);
1030 Lint prevLint = chk.setLint(lint);
1032 // Check that the variable's declared type is well-formed.
1033 boolean isImplicitLambdaParameter = env.tree.hasTag(LAMBDA) &&
1034 ((JCLambda)env.tree).paramKind == JCLambda.ParameterKind.IMPLICIT &&
1035 (tree.sym.flags() & PARAMETER) != 0;
1036 chk.validate(tree.vartype, env, !isImplicitLambdaParameter);
1038 try {
1039 v.getConstValue(); // ensure compile-time constant initializer is evaluated
1040 deferredLintHandler.flush(tree.pos());
1041 chk.checkDeprecatedAnnotation(tree.pos(), v);
1043 if (tree.init != null) {
1044 if ((v.flags_field & FINAL) == 0 ||
1045 !memberEnter.needsLazyConstValue(tree.init)) {
1046 // Not a compile-time constant
1047 // Attribute initializer in a new environment
1048 // with the declared variable as owner.
1049 // Check that initializer conforms to variable's declared type.
1050 Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
1051 initEnv.info.lint = lint;
1052 // In order to catch self-references, we set the variable's
1053 // declaration position to maximal possible value, effectively
1054 // marking the variable as undefined.
1055 initEnv.info.enclVar = v;
1056 attribExpr(tree.init, initEnv, v.type);
1057 }
1058 }
1059 result = tree.type = v.type;
1060 }
1061 finally {
1062 chk.setLint(prevLint);
1063 }
1064 }
1066 public void visitSkip(JCSkip tree) {
1067 result = null;
1068 }
1070 public void visitBlock(JCBlock tree) {
1071 if (env.info.scope.owner.kind == TYP) {
1072 // Block is a static or instance initializer;
1073 // let the owner of the environment be a freshly
1074 // created BLOCK-method.
1075 Env<AttrContext> localEnv =
1076 env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
1077 localEnv.info.scope.owner =
1078 new MethodSymbol(tree.flags | BLOCK |
1079 env.info.scope.owner.flags() & STRICTFP, names.empty, null,
1080 env.info.scope.owner);
1081 if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
1083 // Attribute all type annotations in the block
1084 memberEnter.typeAnnotate(tree, localEnv, localEnv.info.scope.owner, null);
1085 annotate.flush();
1087 {
1088 // Store init and clinit type annotations with the ClassSymbol
1089 // to allow output in Gen.normalizeDefs.
1090 ClassSymbol cs = (ClassSymbol)env.info.scope.owner;
1091 List<Attribute.TypeCompound> tas = localEnv.info.scope.owner.getRawTypeAttributes();
1092 if ((tree.flags & STATIC) != 0) {
1093 cs.appendClassInitTypeAttributes(tas);
1094 } else {
1095 cs.appendInitTypeAttributes(tas);
1096 }
1097 }
1099 attribStats(tree.stats, localEnv);
1100 } else {
1101 // Create a new local environment with a local scope.
1102 Env<AttrContext> localEnv =
1103 env.dup(tree, env.info.dup(env.info.scope.dup()));
1104 try {
1105 attribStats(tree.stats, localEnv);
1106 } finally {
1107 localEnv.info.scope.leave();
1108 }
1109 }
1110 result = null;
1111 }
1113 public void visitDoLoop(JCDoWhileLoop tree) {
1114 attribStat(tree.body, env.dup(tree));
1115 attribExpr(tree.cond, env, syms.booleanType);
1116 result = null;
1117 }
1119 public void visitWhileLoop(JCWhileLoop tree) {
1120 attribExpr(tree.cond, env, syms.booleanType);
1121 attribStat(tree.body, env.dup(tree));
1122 result = null;
1123 }
1125 public void visitForLoop(JCForLoop tree) {
1126 Env<AttrContext> loopEnv =
1127 env.dup(env.tree, env.info.dup(env.info.scope.dup()));
1128 try {
1129 attribStats(tree.init, loopEnv);
1130 if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType);
1131 loopEnv.tree = tree; // before, we were not in loop!
1132 attribStats(tree.step, loopEnv);
1133 attribStat(tree.body, loopEnv);
1134 result = null;
1135 }
1136 finally {
1137 loopEnv.info.scope.leave();
1138 }
1139 }
1141 public void visitForeachLoop(JCEnhancedForLoop tree) {
1142 Env<AttrContext> loopEnv =
1143 env.dup(env.tree, env.info.dup(env.info.scope.dup()));
1144 try {
1145 //the Formal Parameter of a for-each loop is not in the scope when
1146 //attributing the for-each expression; we mimick this by attributing
1147 //the for-each expression first (against original scope).
1148 Type exprType = types.cvarUpperBound(attribExpr(tree.expr, loopEnv));
1149 attribStat(tree.var, loopEnv);
1150 chk.checkNonVoid(tree.pos(), exprType);
1151 Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
1152 if (elemtype == null) {
1153 // or perhaps expr implements Iterable<T>?
1154 Type base = types.asSuper(exprType, syms.iterableType.tsym);
1155 if (base == null) {
1156 log.error(tree.expr.pos(),
1157 "foreach.not.applicable.to.type",
1158 exprType,
1159 diags.fragment("type.req.array.or.iterable"));
1160 elemtype = types.createErrorType(exprType);
1161 } else {
1162 List<Type> iterableParams = base.allparams();
1163 elemtype = iterableParams.isEmpty()
1164 ? syms.objectType
1165 : types.wildUpperBound(iterableParams.head);
1166 }
1167 }
1168 chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
1169 loopEnv.tree = tree; // before, we were not in loop!
1170 attribStat(tree.body, loopEnv);
1171 result = null;
1172 }
1173 finally {
1174 loopEnv.info.scope.leave();
1175 }
1176 }
1178 public void visitLabelled(JCLabeledStatement tree) {
1179 // Check that label is not used in an enclosing statement
1180 Env<AttrContext> env1 = env;
1181 while (env1 != null && !env1.tree.hasTag(CLASSDEF)) {
1182 if (env1.tree.hasTag(LABELLED) &&
1183 ((JCLabeledStatement) env1.tree).label == tree.label) {
1184 log.error(tree.pos(), "label.already.in.use",
1185 tree.label);
1186 break;
1187 }
1188 env1 = env1.next;
1189 }
1191 attribStat(tree.body, env.dup(tree));
1192 result = null;
1193 }
1195 public void visitSwitch(JCSwitch tree) {
1196 Type seltype = attribExpr(tree.selector, env);
1198 Env<AttrContext> switchEnv =
1199 env.dup(tree, env.info.dup(env.info.scope.dup()));
1201 try {
1203 boolean enumSwitch =
1204 allowEnums &&
1205 (seltype.tsym.flags() & Flags.ENUM) != 0;
1206 boolean stringSwitch = false;
1207 if (types.isSameType(seltype, syms.stringType)) {
1208 if (allowStringsInSwitch) {
1209 stringSwitch = true;
1210 } else {
1211 log.error(tree.selector.pos(), "string.switch.not.supported.in.source", sourceName);
1212 }
1213 }
1214 if (!enumSwitch && !stringSwitch)
1215 seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType);
1217 // Attribute all cases and
1218 // check that there are no duplicate case labels or default clauses.
1219 Set<Object> labels = new HashSet<Object>(); // The set of case labels.
1220 boolean hasDefault = false; // Is there a default label?
1221 for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
1222 JCCase c = l.head;
1223 Env<AttrContext> caseEnv =
1224 switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup()));
1225 try {
1226 if (c.pat != null) {
1227 if (enumSwitch) {
1228 Symbol sym = enumConstant(c.pat, seltype);
1229 if (sym == null) {
1230 log.error(c.pat.pos(), "enum.label.must.be.unqualified.enum");
1231 } else if (!labels.add(sym)) {
1232 log.error(c.pos(), "duplicate.case.label");
1233 }
1234 } else {
1235 Type pattype = attribExpr(c.pat, switchEnv, seltype);
1236 if (!pattype.hasTag(ERROR)) {
1237 if (pattype.constValue() == null) {
1238 log.error(c.pat.pos(),
1239 (stringSwitch ? "string.const.req" : "const.expr.req"));
1240 } else if (labels.contains(pattype.constValue())) {
1241 log.error(c.pos(), "duplicate.case.label");
1242 } else {
1243 labels.add(pattype.constValue());
1244 }
1245 }
1246 }
1247 } else if (hasDefault) {
1248 log.error(c.pos(), "duplicate.default.label");
1249 } else {
1250 hasDefault = true;
1251 }
1252 attribStats(c.stats, caseEnv);
1253 } finally {
1254 caseEnv.info.scope.leave();
1255 addVars(c.stats, switchEnv.info.scope);
1256 }
1257 }
1259 result = null;
1260 }
1261 finally {
1262 switchEnv.info.scope.leave();
1263 }
1264 }
1265 // where
1266 /** Add any variables defined in stats to the switch scope. */
1267 private static void addVars(List<JCStatement> stats, Scope switchScope) {
1268 for (;stats.nonEmpty(); stats = stats.tail) {
1269 JCTree stat = stats.head;
1270 if (stat.hasTag(VARDEF))
1271 switchScope.enter(((JCVariableDecl) stat).sym);
1272 }
1273 }
1274 // where
1275 /** Return the selected enumeration constant symbol, or null. */
1276 private Symbol enumConstant(JCTree tree, Type enumType) {
1277 if (!tree.hasTag(IDENT)) {
1278 log.error(tree.pos(), "enum.label.must.be.unqualified.enum");
1279 return syms.errSymbol;
1280 }
1281 JCIdent ident = (JCIdent)tree;
1282 Name name = ident.name;
1283 for (Scope.Entry e = enumType.tsym.members().lookup(name);
1284 e.scope != null; e = e.next()) {
1285 if (e.sym.kind == VAR) {
1286 Symbol s = ident.sym = e.sym;
1287 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
1288 ident.type = s.type;
1289 return ((s.flags_field & Flags.ENUM) == 0)
1290 ? null : s;
1291 }
1292 }
1293 return null;
1294 }
1296 public void visitSynchronized(JCSynchronized tree) {
1297 chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
1298 attribStat(tree.body, env);
1299 result = null;
1300 }
1302 public void visitTry(JCTry tree) {
1303 // Create a new local environment with a local
1304 Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
1305 try {
1306 boolean isTryWithResource = tree.resources.nonEmpty();
1307 // Create a nested environment for attributing the try block if needed
1308 Env<AttrContext> tryEnv = isTryWithResource ?
1309 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
1310 localEnv;
1311 try {
1312 // Attribute resource declarations
1313 for (JCTree resource : tree.resources) {
1314 CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) {
1315 @Override
1316 public void report(DiagnosticPosition pos, JCDiagnostic details) {
1317 chk.basicHandler.report(pos, diags.fragment("try.not.applicable.to.type", details));
1318 }
1319 };
1320 ResultInfo twrResult = new ResultInfo(VAL, syms.autoCloseableType, twrContext);
1321 if (resource.hasTag(VARDEF)) {
1322 attribStat(resource, tryEnv);
1323 twrResult.check(resource, resource.type);
1325 //check that resource type cannot throw InterruptedException
1326 checkAutoCloseable(resource.pos(), localEnv, resource.type);
1328 VarSymbol var = ((JCVariableDecl) resource).sym;
1329 var.setData(ElementKind.RESOURCE_VARIABLE);
1330 } else {
1331 attribTree(resource, tryEnv, twrResult);
1332 }
1333 }
1334 // Attribute body
1335 attribStat(tree.body, tryEnv);
1336 } finally {
1337 if (isTryWithResource)
1338 tryEnv.info.scope.leave();
1339 }
1341 // Attribute catch clauses
1342 for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
1343 JCCatch c = l.head;
1344 Env<AttrContext> catchEnv =
1345 localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup()));
1346 try {
1347 Type ctype = attribStat(c.param, catchEnv);
1348 if (TreeInfo.isMultiCatch(c)) {
1349 //multi-catch parameter is implicitly marked as final
1350 c.param.sym.flags_field |= FINAL | UNION;
1351 }
1352 if (c.param.sym.kind == Kinds.VAR) {
1353 c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
1354 }
1355 chk.checkType(c.param.vartype.pos(),
1356 chk.checkClassType(c.param.vartype.pos(), ctype),
1357 syms.throwableType);
1358 attribStat(c.body, catchEnv);
1359 } finally {
1360 catchEnv.info.scope.leave();
1361 }
1362 }
1364 // Attribute finalizer
1365 if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
1366 result = null;
1367 }
1368 finally {
1369 localEnv.info.scope.leave();
1370 }
1371 }
1373 void checkAutoCloseable(DiagnosticPosition pos, Env<AttrContext> env, Type resource) {
1374 if (!resource.isErroneous() &&
1375 types.asSuper(resource, syms.autoCloseableType.tsym) != null &&
1376 !types.isSameType(resource, syms.autoCloseableType)) { // Don't emit warning for AutoCloseable itself
1377 Symbol close = syms.noSymbol;
1378 Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log);
1379 try {
1380 close = rs.resolveQualifiedMethod(pos,
1381 env,
1382 resource,
1383 names.close,
1384 List.<Type>nil(),
1385 List.<Type>nil());
1386 }
1387 finally {
1388 log.popDiagnosticHandler(discardHandler);
1389 }
1390 if (close.kind == MTH &&
1391 close.overrides(syms.autoCloseableClose, resource.tsym, types, true) &&
1392 chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes()) &&
1393 env.info.lint.isEnabled(LintCategory.TRY)) {
1394 log.warning(LintCategory.TRY, pos, "try.resource.throws.interrupted.exc", resource);
1395 }
1396 }
1397 }
1399 public void visitConditional(JCConditional tree) {
1400 Type condtype = attribExpr(tree.cond, env, syms.booleanType);
1402 tree.polyKind = (!allowPoly ||
1403 pt().hasTag(NONE) && pt() != Type.recoveryType ||
1404 isBooleanOrNumeric(env, tree)) ?
1405 PolyKind.STANDALONE : PolyKind.POLY;
1407 if (tree.polyKind == PolyKind.POLY && resultInfo.pt.hasTag(VOID)) {
1408 //cannot get here (i.e. it means we are returning from void method - which is already an error)
1409 resultInfo.checkContext.report(tree, diags.fragment("conditional.target.cant.be.void"));
1410 result = tree.type = types.createErrorType(resultInfo.pt);
1411 return;
1412 }
1414 ResultInfo condInfo = tree.polyKind == PolyKind.STANDALONE ?
1415 unknownExprInfo :
1416 resultInfo.dup(new Check.NestedCheckContext(resultInfo.checkContext) {
1417 //this will use enclosing check context to check compatibility of
1418 //subexpression against target type; if we are in a method check context,
1419 //depending on whether boxing is allowed, we could have incompatibilities
1420 @Override
1421 public void report(DiagnosticPosition pos, JCDiagnostic details) {
1422 enclosingContext.report(pos, diags.fragment("incompatible.type.in.conditional", details));
1423 }
1424 });
1426 Type truetype = attribTree(tree.truepart, env, condInfo);
1427 Type falsetype = attribTree(tree.falsepart, env, condInfo);
1429 Type owntype = (tree.polyKind == PolyKind.STANDALONE) ? condType(tree, truetype, falsetype) : pt();
1430 if (condtype.constValue() != null &&
1431 truetype.constValue() != null &&
1432 falsetype.constValue() != null &&
1433 !owntype.hasTag(NONE)) {
1434 //constant folding
1435 owntype = cfolder.coerce(condtype.isTrue() ? truetype : falsetype, owntype);
1436 }
1437 result = check(tree, owntype, VAL, resultInfo);
1438 }
1439 //where
1440 private boolean isBooleanOrNumeric(Env<AttrContext> env, JCExpression tree) {
1441 switch (tree.getTag()) {
1442 case LITERAL: return ((JCLiteral)tree).typetag.isSubRangeOf(DOUBLE) ||
1443 ((JCLiteral)tree).typetag == BOOLEAN ||
1444 ((JCLiteral)tree).typetag == BOT;
1445 case LAMBDA: case REFERENCE: return false;
1446 case PARENS: return isBooleanOrNumeric(env, ((JCParens)tree).expr);
1447 case CONDEXPR:
1448 JCConditional condTree = (JCConditional)tree;
1449 return isBooleanOrNumeric(env, condTree.truepart) &&
1450 isBooleanOrNumeric(env, condTree.falsepart);
1451 case APPLY:
1452 JCMethodInvocation speculativeMethodTree =
1453 (JCMethodInvocation)deferredAttr.attribSpeculative(tree, env, unknownExprInfo);
1454 Type owntype = TreeInfo.symbol(speculativeMethodTree.meth).type.getReturnType();
1455 return types.unboxedTypeOrType(owntype).isPrimitive();
1456 case NEWCLASS:
1457 JCExpression className =
1458 removeClassParams.translate(((JCNewClass)tree).clazz);
1459 JCExpression speculativeNewClassTree =
1460 (JCExpression)deferredAttr.attribSpeculative(className, env, unknownTypeInfo);
1461 return types.unboxedTypeOrType(speculativeNewClassTree.type).isPrimitive();
1462 default:
1463 Type speculativeType = deferredAttr.attribSpeculative(tree, env, unknownExprInfo).type;
1464 speculativeType = types.unboxedTypeOrType(speculativeType);
1465 return speculativeType.isPrimitive();
1466 }
1467 }
1468 //where
1469 TreeTranslator removeClassParams = new TreeTranslator() {
1470 @Override
1471 public void visitTypeApply(JCTypeApply tree) {
1472 result = translate(tree.clazz);
1473 }
1474 };
1476 /** Compute the type of a conditional expression, after
1477 * checking that it exists. See JLS 15.25. Does not take into
1478 * account the special case where condition and both arms
1479 * are constants.
1480 *
1481 * @param pos The source position to be used for error
1482 * diagnostics.
1483 * @param thentype The type of the expression's then-part.
1484 * @param elsetype The type of the expression's else-part.
1485 */
1486 private Type condType(DiagnosticPosition pos,
1487 Type thentype, Type elsetype) {
1488 // If same type, that is the result
1489 if (types.isSameType(thentype, elsetype))
1490 return thentype.baseType();
1492 Type thenUnboxed = (!allowBoxing || thentype.isPrimitive())
1493 ? thentype : types.unboxedType(thentype);
1494 Type elseUnboxed = (!allowBoxing || elsetype.isPrimitive())
1495 ? elsetype : types.unboxedType(elsetype);
1497 // Otherwise, if both arms can be converted to a numeric
1498 // type, return the least numeric type that fits both arms
1499 // (i.e. return larger of the two, or return int if one
1500 // arm is short, the other is char).
1501 if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) {
1502 // If one arm has an integer subrange type (i.e., byte,
1503 // short, or char), and the other is an integer constant
1504 // that fits into the subrange, return the subrange type.
1505 if (thenUnboxed.getTag().isStrictSubRangeOf(INT) &&
1506 elseUnboxed.hasTag(INT) &&
1507 types.isAssignable(elseUnboxed, thenUnboxed)) {
1508 return thenUnboxed.baseType();
1509 }
1510 if (elseUnboxed.getTag().isStrictSubRangeOf(INT) &&
1511 thenUnboxed.hasTag(INT) &&
1512 types.isAssignable(thenUnboxed, elseUnboxed)) {
1513 return elseUnboxed.baseType();
1514 }
1516 for (TypeTag tag : primitiveTags) {
1517 Type candidate = syms.typeOfTag[tag.ordinal()];
1518 if (types.isSubtype(thenUnboxed, candidate) &&
1519 types.isSubtype(elseUnboxed, candidate)) {
1520 return candidate;
1521 }
1522 }
1523 }
1525 // Those were all the cases that could result in a primitive
1526 if (allowBoxing) {
1527 if (thentype.isPrimitive())
1528 thentype = types.boxedClass(thentype).type;
1529 if (elsetype.isPrimitive())
1530 elsetype = types.boxedClass(elsetype).type;
1531 }
1533 if (types.isSubtype(thentype, elsetype))
1534 return elsetype.baseType();
1535 if (types.isSubtype(elsetype, thentype))
1536 return thentype.baseType();
1538 if (!allowBoxing || thentype.hasTag(VOID) || elsetype.hasTag(VOID)) {
1539 log.error(pos, "neither.conditional.subtype",
1540 thentype, elsetype);
1541 return thentype.baseType();
1542 }
1544 // both are known to be reference types. The result is
1545 // lub(thentype,elsetype). This cannot fail, as it will
1546 // always be possible to infer "Object" if nothing better.
1547 return types.lub(thentype.baseType(), elsetype.baseType());
1548 }
1550 final static TypeTag[] primitiveTags = new TypeTag[]{
1551 BYTE,
1552 CHAR,
1553 SHORT,
1554 INT,
1555 LONG,
1556 FLOAT,
1557 DOUBLE,
1558 BOOLEAN,
1559 };
1561 public void visitIf(JCIf tree) {
1562 attribExpr(tree.cond, env, syms.booleanType);
1563 attribStat(tree.thenpart, env);
1564 if (tree.elsepart != null)
1565 attribStat(tree.elsepart, env);
1566 chk.checkEmptyIf(tree);
1567 result = null;
1568 }
1570 public void visitExec(JCExpressionStatement tree) {
1571 //a fresh environment is required for 292 inference to work properly ---
1572 //see Infer.instantiatePolymorphicSignatureInstance()
1573 Env<AttrContext> localEnv = env.dup(tree);
1574 attribExpr(tree.expr, localEnv);
1575 result = null;
1576 }
1578 public void visitBreak(JCBreak tree) {
1579 tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
1580 result = null;
1581 }
1583 public void visitContinue(JCContinue tree) {
1584 tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
1585 result = null;
1586 }
1587 //where
1588 /** Return the target of a break or continue statement, if it exists,
1589 * report an error if not.
1590 * Note: The target of a labelled break or continue is the
1591 * (non-labelled) statement tree referred to by the label,
1592 * not the tree representing the labelled statement itself.
1593 *
1594 * @param pos The position to be used for error diagnostics
1595 * @param tag The tag of the jump statement. This is either
1596 * Tree.BREAK or Tree.CONTINUE.
1597 * @param label The label of the jump statement, or null if no
1598 * label is given.
1599 * @param env The environment current at the jump statement.
1600 */
1601 private JCTree findJumpTarget(DiagnosticPosition pos,
1602 JCTree.Tag tag,
1603 Name label,
1604 Env<AttrContext> env) {
1605 // Search environments outwards from the point of jump.
1606 Env<AttrContext> env1 = env;
1607 LOOP:
1608 while (env1 != null) {
1609 switch (env1.tree.getTag()) {
1610 case LABELLED:
1611 JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
1612 if (label == labelled.label) {
1613 // If jump is a continue, check that target is a loop.
1614 if (tag == CONTINUE) {
1615 if (!labelled.body.hasTag(DOLOOP) &&
1616 !labelled.body.hasTag(WHILELOOP) &&
1617 !labelled.body.hasTag(FORLOOP) &&
1618 !labelled.body.hasTag(FOREACHLOOP))
1619 log.error(pos, "not.loop.label", label);
1620 // Found labelled statement target, now go inwards
1621 // to next non-labelled tree.
1622 return TreeInfo.referencedStatement(labelled);
1623 } else {
1624 return labelled;
1625 }
1626 }
1627 break;
1628 case DOLOOP:
1629 case WHILELOOP:
1630 case FORLOOP:
1631 case FOREACHLOOP:
1632 if (label == null) return env1.tree;
1633 break;
1634 case SWITCH:
1635 if (label == null && tag == BREAK) return env1.tree;
1636 break;
1637 case LAMBDA:
1638 case METHODDEF:
1639 case CLASSDEF:
1640 break LOOP;
1641 default:
1642 }
1643 env1 = env1.next;
1644 }
1645 if (label != null)
1646 log.error(pos, "undef.label", label);
1647 else if (tag == CONTINUE)
1648 log.error(pos, "cont.outside.loop");
1649 else
1650 log.error(pos, "break.outside.switch.loop");
1651 return null;
1652 }
1654 public void visitReturn(JCReturn tree) {
1655 // Check that there is an enclosing method which is
1656 // nested within than the enclosing class.
1657 if (env.info.returnResult == null) {
1658 log.error(tree.pos(), "ret.outside.meth");
1659 } else {
1660 // Attribute return expression, if it exists, and check that
1661 // it conforms to result type of enclosing method.
1662 if (tree.expr != null) {
1663 if (env.info.returnResult.pt.hasTag(VOID)) {
1664 env.info.returnResult.checkContext.report(tree.expr.pos(),
1665 diags.fragment("unexpected.ret.val"));
1666 }
1667 attribTree(tree.expr, env, env.info.returnResult);
1668 } else if (!env.info.returnResult.pt.hasTag(VOID) &&
1669 !env.info.returnResult.pt.hasTag(NONE)) {
1670 env.info.returnResult.checkContext.report(tree.pos(),
1671 diags.fragment("missing.ret.val"));
1672 }
1673 }
1674 result = null;
1675 }
1677 public void visitThrow(JCThrow tree) {
1678 Type owntype = attribExpr(tree.expr, env, allowPoly ? Type.noType : syms.throwableType);
1679 if (allowPoly) {
1680 chk.checkType(tree, owntype, syms.throwableType);
1681 }
1682 result = null;
1683 }
1685 public void visitAssert(JCAssert tree) {
1686 attribExpr(tree.cond, env, syms.booleanType);
1687 if (tree.detail != null) {
1688 chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
1689 }
1690 result = null;
1691 }
1693 /** Visitor method for method invocations.
1694 * NOTE: The method part of an application will have in its type field
1695 * the return type of the method, not the method's type itself!
1696 */
1697 public void visitApply(JCMethodInvocation tree) {
1698 // The local environment of a method application is
1699 // a new environment nested in the current one.
1700 Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
1702 // The types of the actual method arguments.
1703 List<Type> argtypes;
1705 // The types of the actual method type arguments.
1706 List<Type> typeargtypes = null;
1708 Name methName = TreeInfo.name(tree.meth);
1710 boolean isConstructorCall =
1711 methName == names._this || methName == names._super;
1713 ListBuffer<Type> argtypesBuf = new ListBuffer<>();
1714 if (isConstructorCall) {
1715 // We are seeing a ...this(...) or ...super(...) call.
1716 // Check that this is the first statement in a constructor.
1717 if (checkFirstConstructorStat(tree, env)) {
1719 // Record the fact
1720 // that this is a constructor call (using isSelfCall).
1721 localEnv.info.isSelfCall = true;
1723 // Attribute arguments, yielding list of argument types.
1724 attribArgs(tree.args, localEnv, argtypesBuf);
1725 argtypes = argtypesBuf.toList();
1726 typeargtypes = attribTypes(tree.typeargs, localEnv);
1728 // Variable `site' points to the class in which the called
1729 // constructor is defined.
1730 Type site = env.enclClass.sym.type;
1731 if (methName == names._super) {
1732 if (site == syms.objectType) {
1733 log.error(tree.meth.pos(), "no.superclass", site);
1734 site = types.createErrorType(syms.objectType);
1735 } else {
1736 site = types.supertype(site);
1737 }
1738 }
1740 if (site.hasTag(CLASS)) {
1741 Type encl = site.getEnclosingType();
1742 while (encl != null && encl.hasTag(TYPEVAR))
1743 encl = encl.getUpperBound();
1744 if (encl.hasTag(CLASS)) {
1745 // we are calling a nested class
1747 if (tree.meth.hasTag(SELECT)) {
1748 JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
1750 // We are seeing a prefixed call, of the form
1751 // <expr>.super(...).
1752 // Check that the prefix expression conforms
1753 // to the outer instance type of the class.
1754 chk.checkRefType(qualifier.pos(),
1755 attribExpr(qualifier, localEnv,
1756 encl));
1757 } else if (methName == names._super) {
1758 // qualifier omitted; check for existence
1759 // of an appropriate implicit qualifier.
1760 rs.resolveImplicitThis(tree.meth.pos(),
1761 localEnv, site, true);
1762 }
1763 } else if (tree.meth.hasTag(SELECT)) {
1764 log.error(tree.meth.pos(), "illegal.qual.not.icls",
1765 site.tsym);
1766 }
1768 // if we're calling a java.lang.Enum constructor,
1769 // prefix the implicit String and int parameters
1770 if (site.tsym == syms.enumSym && allowEnums)
1771 argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
1773 // Resolve the called constructor under the assumption
1774 // that we are referring to a superclass instance of the
1775 // current instance (JLS ???).
1776 boolean selectSuperPrev = localEnv.info.selectSuper;
1777 localEnv.info.selectSuper = true;
1778 localEnv.info.pendingResolutionPhase = null;
1779 Symbol sym = rs.resolveConstructor(
1780 tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
1781 localEnv.info.selectSuper = selectSuperPrev;
1783 // Set method symbol to resolved constructor...
1784 TreeInfo.setSymbol(tree.meth, sym);
1786 // ...and check that it is legal in the current context.
1787 // (this will also set the tree's type)
1788 Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
1789 checkId(tree.meth, site, sym, localEnv, new ResultInfo(MTH, mpt));
1790 }
1791 // Otherwise, `site' is an error type and we do nothing
1792 }
1793 result = tree.type = syms.voidType;
1794 } else {
1795 // Otherwise, we are seeing a regular method call.
1796 // Attribute the arguments, yielding list of argument types, ...
1797 int kind = attribArgs(tree.args, localEnv, argtypesBuf);
1798 argtypes = argtypesBuf.toList();
1799 typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
1801 // ... and attribute the method using as a prototype a methodtype
1802 // whose formal argument types is exactly the list of actual
1803 // arguments (this will also set the method symbol).
1804 Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
1805 localEnv.info.pendingResolutionPhase = null;
1806 Type mtype = attribTree(tree.meth, localEnv, new ResultInfo(kind, mpt, resultInfo.checkContext));
1808 // Compute the result type.
1809 Type restype = mtype.getReturnType();
1810 if (restype.hasTag(WILDCARD))
1811 throw new AssertionError(mtype);
1813 Type qualifier = (tree.meth.hasTag(SELECT))
1814 ? ((JCFieldAccess) tree.meth).selected.type
1815 : env.enclClass.sym.type;
1816 restype = adjustMethodReturnType(qualifier, methName, argtypes, restype);
1818 chk.checkRefTypes(tree.typeargs, typeargtypes);
1820 // Check that value of resulting type is admissible in the
1821 // current context. Also, capture the return type
1822 result = check(tree, capture(restype), VAL, resultInfo);
1823 }
1824 chk.validate(tree.typeargs, localEnv);
1825 }
1826 //where
1827 Type adjustMethodReturnType(Type qualifierType, Name methodName, List<Type> argtypes, Type restype) {
1828 if (allowCovariantReturns &&
1829 methodName == names.clone &&
1830 types.isArray(qualifierType)) {
1831 // as a special case, array.clone() has a result that is
1832 // the same as static type of the array being cloned
1833 return qualifierType;
1834 } else if (allowGenerics &&
1835 methodName == names.getClass &&
1836 argtypes.isEmpty()) {
1837 // as a special case, x.getClass() has type Class<? extends |X|>
1838 return new ClassType(restype.getEnclosingType(),
1839 List.<Type>of(new WildcardType(types.erasure(qualifierType),
1840 BoundKind.EXTENDS,
1841 syms.boundClass)),
1842 restype.tsym);
1843 } else {
1844 return restype;
1845 }
1846 }
1848 /** Check that given application node appears as first statement
1849 * in a constructor call.
1850 * @param tree The application node
1851 * @param env The environment current at the application.
1852 */
1853 boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) {
1854 JCMethodDecl enclMethod = env.enclMethod;
1855 if (enclMethod != null && enclMethod.name == names.init) {
1856 JCBlock body = enclMethod.body;
1857 if (body.stats.head.hasTag(EXEC) &&
1858 ((JCExpressionStatement) body.stats.head).expr == tree)
1859 return true;
1860 }
1861 log.error(tree.pos(),"call.must.be.first.stmt.in.ctor",
1862 TreeInfo.name(tree.meth));
1863 return false;
1864 }
1866 /** Obtain a method type with given argument types.
1867 */
1868 Type newMethodTemplate(Type restype, List<Type> argtypes, List<Type> typeargtypes) {
1869 MethodType mt = new MethodType(argtypes, restype, List.<Type>nil(), syms.methodClass);
1870 return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
1871 }
1873 public void visitNewClass(final JCNewClass tree) {
1874 Type owntype = types.createErrorType(tree.type);
1876 // The local environment of a class creation is
1877 // a new environment nested in the current one.
1878 Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
1880 // The anonymous inner class definition of the new expression,
1881 // if one is defined by it.
1882 JCClassDecl cdef = tree.def;
1884 // If enclosing class is given, attribute it, and
1885 // complete class name to be fully qualified
1886 JCExpression clazz = tree.clazz; // Class field following new
1887 JCExpression clazzid; // Identifier in class field
1888 JCAnnotatedType annoclazzid; // Annotated type enclosing clazzid
1889 annoclazzid = null;
1891 if (clazz.hasTag(TYPEAPPLY)) {
1892 clazzid = ((JCTypeApply) clazz).clazz;
1893 if (clazzid.hasTag(ANNOTATED_TYPE)) {
1894 annoclazzid = (JCAnnotatedType) clazzid;
1895 clazzid = annoclazzid.underlyingType;
1896 }
1897 } else {
1898 if (clazz.hasTag(ANNOTATED_TYPE)) {
1899 annoclazzid = (JCAnnotatedType) clazz;
1900 clazzid = annoclazzid.underlyingType;
1901 } else {
1902 clazzid = clazz;
1903 }
1904 }
1906 JCExpression clazzid1 = clazzid; // The same in fully qualified form
1908 if (tree.encl != null) {
1909 // We are seeing a qualified new, of the form
1910 // <expr>.new C <...> (...) ...
1911 // In this case, we let clazz stand for the name of the
1912 // allocated class C prefixed with the type of the qualifier
1913 // expression, so that we can
1914 // resolve it with standard techniques later. I.e., if
1915 // <expr> has type T, then <expr>.new C <...> (...)
1916 // yields a clazz T.C.
1917 Type encltype = chk.checkRefType(tree.encl.pos(),
1918 attribExpr(tree.encl, env));
1919 // TODO 308: in <expr>.new C, do we also want to add the type annotations
1920 // from expr to the combined type, or not? Yes, do this.
1921 clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
1922 ((JCIdent) clazzid).name);
1924 EndPosTable endPosTable = this.env.toplevel.endPositions;
1925 endPosTable.storeEnd(clazzid1, tree.getEndPosition(endPosTable));
1926 if (clazz.hasTag(ANNOTATED_TYPE)) {
1927 JCAnnotatedType annoType = (JCAnnotatedType) clazz;
1928 List<JCAnnotation> annos = annoType.annotations;
1930 if (annoType.underlyingType.hasTag(TYPEAPPLY)) {
1931 clazzid1 = make.at(tree.pos).
1932 TypeApply(clazzid1,
1933 ((JCTypeApply) clazz).arguments);
1934 }
1936 clazzid1 = make.at(tree.pos).
1937 AnnotatedType(annos, clazzid1);
1938 } else if (clazz.hasTag(TYPEAPPLY)) {
1939 clazzid1 = make.at(tree.pos).
1940 TypeApply(clazzid1,
1941 ((JCTypeApply) clazz).arguments);
1942 }
1944 clazz = clazzid1;
1945 }
1947 // Attribute clazz expression and store
1948 // symbol + type back into the attributed tree.
1949 Type clazztype = TreeInfo.isEnumInit(env.tree) ?
1950 attribIdentAsEnumType(env, (JCIdent)clazz) :
1951 attribType(clazz, env);
1953 clazztype = chk.checkDiamond(tree, clazztype);
1954 chk.validate(clazz, localEnv);
1955 if (tree.encl != null) {
1956 // We have to work in this case to store
1957 // symbol + type back into the attributed tree.
1958 tree.clazz.type = clazztype;
1959 TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
1960 clazzid.type = ((JCIdent) clazzid).sym.type;
1961 if (annoclazzid != null) {
1962 annoclazzid.type = clazzid.type;
1963 }
1964 if (!clazztype.isErroneous()) {
1965 if (cdef != null && clazztype.tsym.isInterface()) {
1966 log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new");
1967 } else if (clazztype.tsym.isStatic()) {
1968 log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym);
1969 }
1970 }
1971 } else if (!clazztype.tsym.isInterface() &&
1972 clazztype.getEnclosingType().hasTag(CLASS)) {
1973 // Check for the existence of an apropos outer instance
1974 rs.resolveImplicitThis(tree.pos(), env, clazztype);
1975 }
1977 // Attribute constructor arguments.
1978 ListBuffer<Type> argtypesBuf = new ListBuffer<>();
1979 int pkind = attribArgs(tree.args, localEnv, argtypesBuf);
1980 List<Type> argtypes = argtypesBuf.toList();
1981 List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
1983 // If we have made no mistakes in the class type...
1984 if (clazztype.hasTag(CLASS)) {
1985 // Enums may not be instantiated except implicitly
1986 if (allowEnums &&
1987 (clazztype.tsym.flags_field&Flags.ENUM) != 0 &&
1988 (!env.tree.hasTag(VARDEF) ||
1989 (((JCVariableDecl) env.tree).mods.flags&Flags.ENUM) == 0 ||
1990 ((JCVariableDecl) env.tree).init != tree))
1991 log.error(tree.pos(), "enum.cant.be.instantiated");
1992 // Check that class is not abstract
1993 if (cdef == null &&
1994 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
1995 log.error(tree.pos(), "abstract.cant.be.instantiated",
1996 clazztype.tsym);
1997 } else if (cdef != null && clazztype.tsym.isInterface()) {
1998 // Check that no constructor arguments are given to
1999 // anonymous classes implementing an interface
2000 if (!argtypes.isEmpty())
2001 log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args");
2003 if (!typeargtypes.isEmpty())
2004 log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs");
2006 // Error recovery: pretend no arguments were supplied.
2007 argtypes = List.nil();
2008 typeargtypes = List.nil();
2009 } else if (TreeInfo.isDiamond(tree)) {
2010 ClassType site = new ClassType(clazztype.getEnclosingType(),
2011 clazztype.tsym.type.getTypeArguments(),
2012 clazztype.tsym);
2014 Env<AttrContext> diamondEnv = localEnv.dup(tree);
2015 diamondEnv.info.selectSuper = cdef != null;
2016 diamondEnv.info.pendingResolutionPhase = null;
2018 //if the type of the instance creation expression is a class type
2019 //apply method resolution inference (JLS 15.12.2.7). The return type
2020 //of the resolved constructor will be a partially instantiated type
2021 Symbol constructor = rs.resolveDiamond(tree.pos(),
2022 diamondEnv,
2023 site,
2024 argtypes,
2025 typeargtypes);
2026 tree.constructor = constructor.baseSymbol();
2028 final TypeSymbol csym = clazztype.tsym;
2029 ResultInfo diamondResult = new ResultInfo(pkind, newMethodTemplate(resultInfo.pt, argtypes, typeargtypes), new Check.NestedCheckContext(resultInfo.checkContext) {
2030 @Override
2031 public void report(DiagnosticPosition _unused, JCDiagnostic details) {
2032 enclosingContext.report(tree.clazz,
2033 diags.fragment("cant.apply.diamond.1", diags.fragment("diamond", csym), details));
2034 }
2035 });
2036 Type constructorType = tree.constructorType = types.createErrorType(clazztype);
2037 constructorType = checkId(tree, site,
2038 constructor,
2039 diamondEnv,
2040 diamondResult);
2042 tree.clazz.type = types.createErrorType(clazztype);
2043 if (!constructorType.isErroneous()) {
2044 tree.clazz.type = clazztype = constructorType.getReturnType();
2045 tree.constructorType = types.createMethodTypeWithReturn(constructorType, syms.voidType);
2046 }
2047 clazztype = chk.checkClassType(tree.clazz, tree.clazz.type, true);
2048 }
2050 // Resolve the called constructor under the assumption
2051 // that we are referring to a superclass instance of the
2052 // current instance (JLS ???).
2053 else {
2054 //the following code alters some of the fields in the current
2055 //AttrContext - hence, the current context must be dup'ed in
2056 //order to avoid downstream failures
2057 Env<AttrContext> rsEnv = localEnv.dup(tree);
2058 rsEnv.info.selectSuper = cdef != null;
2059 rsEnv.info.pendingResolutionPhase = null;
2060 tree.constructor = rs.resolveConstructor(
2061 tree.pos(), rsEnv, clazztype, argtypes, typeargtypes);
2062 if (cdef == null) { //do not check twice!
2063 tree.constructorType = checkId(tree,
2064 clazztype,
2065 tree.constructor,
2066 rsEnv,
2067 new ResultInfo(pkind, newMethodTemplate(syms.voidType, argtypes, typeargtypes)));
2068 if (rsEnv.info.lastResolveVarargs())
2069 Assert.check(tree.constructorType.isErroneous() || tree.varargsElement != null);
2070 }
2071 if (cdef == null &&
2072 !clazztype.isErroneous() &&
2073 clazztype.getTypeArguments().nonEmpty() &&
2074 findDiamonds) {
2075 findDiamond(localEnv, tree, clazztype);
2076 }
2077 }
2079 if (cdef != null) {
2080 // We are seeing an anonymous class instance creation.
2081 // In this case, the class instance creation
2082 // expression
2083 //
2084 // E.new <typeargs1>C<typargs2>(args) { ... }
2085 //
2086 // is represented internally as
2087 //
2088 // E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } ) .
2089 //
2090 // This expression is then *transformed* as follows:
2091 //
2092 // (1) add a STATIC flag to the class definition
2093 // if the current environment is static
2094 // (2) add an extends or implements clause
2095 // (3) add a constructor.
2096 //
2097 // For instance, if C is a class, and ET is the type of E,
2098 // the expression
2099 //
2100 // E.new <typeargs1>C<typargs2>(args) { ... }
2101 //
2102 // is translated to (where X is a fresh name and typarams is the
2103 // parameter list of the super constructor):
2104 //
2105 // new <typeargs1>X(<*nullchk*>E, args) where
2106 // X extends C<typargs2> {
2107 // <typarams> X(ET e, args) {
2108 // e.<typeargs1>super(args)
2109 // }
2110 // ...
2111 // }
2112 if (Resolve.isStatic(env)) cdef.mods.flags |= STATIC;
2114 if (clazztype.tsym.isInterface()) {
2115 cdef.implementing = List.of(clazz);
2116 } else {
2117 cdef.extending = clazz;
2118 }
2120 if (resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
2121 isSerializable(clazztype)) {
2122 localEnv.info.isSerializable = true;
2123 }
2125 attribStat(cdef, localEnv);
2127 checkLambdaCandidate(tree, cdef.sym, clazztype);
2129 // If an outer instance is given,
2130 // prefix it to the constructor arguments
2131 // and delete it from the new expression
2132 if (tree.encl != null && !clazztype.tsym.isInterface()) {
2133 tree.args = tree.args.prepend(makeNullCheck(tree.encl));
2134 argtypes = argtypes.prepend(tree.encl.type);
2135 tree.encl = null;
2136 }
2138 // Reassign clazztype and recompute constructor.
2139 clazztype = cdef.sym.type;
2140 Symbol sym = tree.constructor = rs.resolveConstructor(
2141 tree.pos(), localEnv, clazztype, argtypes, typeargtypes);
2142 Assert.check(sym.kind < AMBIGUOUS);
2143 tree.constructor = sym;
2144 tree.constructorType = checkId(tree,
2145 clazztype,
2146 tree.constructor,
2147 localEnv,
2148 new ResultInfo(pkind, newMethodTemplate(syms.voidType, argtypes, typeargtypes)));
2149 }
2151 if (tree.constructor != null && tree.constructor.kind == MTH)
2152 owntype = clazztype;
2153 }
2154 result = check(tree, owntype, VAL, resultInfo);
2155 chk.validate(tree.typeargs, localEnv);
2156 }
2157 //where
2158 void findDiamond(Env<AttrContext> env, JCNewClass tree, Type clazztype) {
2159 JCTypeApply ta = (JCTypeApply)tree.clazz;
2160 List<JCExpression> prevTypeargs = ta.arguments;
2161 try {
2162 //create a 'fake' diamond AST node by removing type-argument trees
2163 ta.arguments = List.nil();
2164 ResultInfo findDiamondResult = new ResultInfo(VAL,
2165 resultInfo.checkContext.inferenceContext().free(resultInfo.pt) ? Type.noType : pt());
2166 Type inferred = deferredAttr.attribSpeculative(tree, env, findDiamondResult).type;
2167 Type polyPt = allowPoly ?
2168 syms.objectType :
2169 clazztype;
2170 if (!inferred.isErroneous() &&
2171 (allowPoly && pt() == Infer.anyPoly ?
2172 types.isSameType(inferred, clazztype) :
2173 types.isAssignable(inferred, pt().hasTag(NONE) ? polyPt : pt(), types.noWarnings))) {
2174 String key = types.isSameType(clazztype, inferred) ?
2175 "diamond.redundant.args" :
2176 "diamond.redundant.args.1";
2177 log.warning(tree.clazz.pos(), key, clazztype, inferred);
2178 }
2179 } finally {
2180 ta.arguments = prevTypeargs;
2181 }
2182 }
2184 private void checkLambdaCandidate(JCNewClass tree, ClassSymbol csym, Type clazztype) {
2185 if (allowLambda &&
2186 identifyLambdaCandidate &&
2187 clazztype.hasTag(CLASS) &&
2188 !pt().hasTag(NONE) &&
2189 types.isFunctionalInterface(clazztype.tsym)) {
2190 Symbol descriptor = types.findDescriptorSymbol(clazztype.tsym);
2191 int count = 0;
2192 boolean found = false;
2193 for (Symbol sym : csym.members().getElements()) {
2194 if ((sym.flags() & SYNTHETIC) != 0 ||
2195 sym.isConstructor()) continue;
2196 count++;
2197 if (sym.kind != MTH ||
2198 !sym.name.equals(descriptor.name)) continue;
2199 Type mtype = types.memberType(clazztype, sym);
2200 if (types.overrideEquivalent(mtype, types.memberType(clazztype, descriptor))) {
2201 found = true;
2202 }
2203 }
2204 if (found && count == 1) {
2205 log.note(tree.def, "potential.lambda.found");
2206 }
2207 }
2208 }
2210 /** Make an attributed null check tree.
2211 */
2212 public JCExpression makeNullCheck(JCExpression arg) {
2213 // optimization: X.this is never null; skip null check
2214 Name name = TreeInfo.name(arg);
2215 if (name == names._this || name == names._super) return arg;
2217 JCTree.Tag optag = NULLCHK;
2218 JCUnary tree = make.at(arg.pos).Unary(optag, arg);
2219 tree.operator = syms.nullcheck;
2220 tree.type = arg.type;
2221 return tree;
2222 }
2224 public void visitNewArray(JCNewArray tree) {
2225 Type owntype = types.createErrorType(tree.type);
2226 Env<AttrContext> localEnv = env.dup(tree);
2227 Type elemtype;
2228 if (tree.elemtype != null) {
2229 elemtype = attribType(tree.elemtype, localEnv);
2230 chk.validate(tree.elemtype, localEnv);
2231 owntype = elemtype;
2232 for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
2233 attribExpr(l.head, localEnv, syms.intType);
2234 owntype = new ArrayType(owntype, syms.arrayClass);
2235 }
2236 } else {
2237 // we are seeing an untyped aggregate { ... }
2238 // this is allowed only if the prototype is an array
2239 if (pt().hasTag(ARRAY)) {
2240 elemtype = types.elemtype(pt());
2241 } else {
2242 if (!pt().hasTag(ERROR)) {
2243 log.error(tree.pos(), "illegal.initializer.for.type",
2244 pt());
2245 }
2246 elemtype = types.createErrorType(pt());
2247 }
2248 }
2249 if (tree.elems != null) {
2250 attribExprs(tree.elems, localEnv, elemtype);
2251 owntype = new ArrayType(elemtype, syms.arrayClass);
2252 }
2253 if (!types.isReifiable(elemtype))
2254 log.error(tree.pos(), "generic.array.creation");
2255 result = check(tree, owntype, VAL, resultInfo);
2256 }
2258 /*
2259 * A lambda expression can only be attributed when a target-type is available.
2260 * In addition, if the target-type is that of a functional interface whose
2261 * descriptor contains inference variables in argument position the lambda expression
2262 * is 'stuck' (see DeferredAttr).
2263 */
2264 @Override
2265 public void visitLambda(final JCLambda that) {
2266 if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
2267 if (pt().hasTag(NONE)) {
2268 //lambda only allowed in assignment or method invocation/cast context
2269 log.error(that.pos(), "unexpected.lambda");
2270 }
2271 result = that.type = types.createErrorType(pt());
2272 return;
2273 }
2274 //create an environment for attribution of the lambda expression
2275 final Env<AttrContext> localEnv = lambdaEnv(that, env);
2276 boolean needsRecovery =
2277 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK;
2278 try {
2279 Type currentTarget = pt();
2280 if (needsRecovery && isSerializable(currentTarget)) {
2281 localEnv.info.isSerializable = true;
2282 }
2283 List<Type> explicitParamTypes = null;
2284 if (that.paramKind == JCLambda.ParameterKind.EXPLICIT) {
2285 //attribute lambda parameters
2286 attribStats(that.params, localEnv);
2287 explicitParamTypes = TreeInfo.types(that.params);
2288 }
2290 Type lambdaType;
2291 if (pt() != Type.recoveryType) {
2292 /* We need to adjust the target. If the target is an
2293 * intersection type, for example: SAM & I1 & I2 ...
2294 * the target will be updated to SAM
2295 */
2296 currentTarget = targetChecker.visit(currentTarget, that);
2297 if (explicitParamTypes != null) {
2298 currentTarget = infer.instantiateFunctionalInterface(that,
2299 currentTarget, explicitParamTypes, resultInfo.checkContext);
2300 }
2301 currentTarget = types.removeWildcards(currentTarget);
2302 lambdaType = types.findDescriptorType(currentTarget);
2303 } else {
2304 currentTarget = Type.recoveryType;
2305 lambdaType = fallbackDescriptorType(that);
2306 }
2308 setFunctionalInfo(localEnv, that, pt(), lambdaType, currentTarget, resultInfo.checkContext);
2310 if (lambdaType.hasTag(FORALL)) {
2311 //lambda expression target desc cannot be a generic method
2312 resultInfo.checkContext.report(that, diags.fragment("invalid.generic.lambda.target",
2313 lambdaType, kindName(currentTarget.tsym), currentTarget.tsym));
2314 result = that.type = types.createErrorType(pt());
2315 return;
2316 }
2318 if (that.paramKind == JCLambda.ParameterKind.IMPLICIT) {
2319 //add param type info in the AST
2320 List<Type> actuals = lambdaType.getParameterTypes();
2321 List<JCVariableDecl> params = that.params;
2323 boolean arityMismatch = false;
2325 while (params.nonEmpty()) {
2326 if (actuals.isEmpty()) {
2327 //not enough actuals to perform lambda parameter inference
2328 arityMismatch = true;
2329 }
2330 //reset previously set info
2331 Type argType = arityMismatch ?
2332 syms.errType :
2333 actuals.head;
2334 params.head.vartype = make.at(params.head).Type(argType);
2335 params.head.sym = null;
2336 actuals = actuals.isEmpty() ?
2337 actuals :
2338 actuals.tail;
2339 params = params.tail;
2340 }
2342 //attribute lambda parameters
2343 attribStats(that.params, localEnv);
2345 if (arityMismatch) {
2346 resultInfo.checkContext.report(that, diags.fragment("incompatible.arg.types.in.lambda"));
2347 result = that.type = types.createErrorType(currentTarget);
2348 return;
2349 }
2350 }
2352 //from this point on, no recovery is needed; if we are in assignment context
2353 //we will be able to attribute the whole lambda body, regardless of errors;
2354 //if we are in a 'check' method context, and the lambda is not compatible
2355 //with the target-type, it will be recovered anyway in Attr.checkId
2356 needsRecovery = false;
2358 FunctionalReturnContext funcContext = that.getBodyKind() == JCLambda.BodyKind.EXPRESSION ?
2359 new ExpressionLambdaReturnContext((JCExpression)that.getBody(), resultInfo.checkContext) :
2360 new FunctionalReturnContext(resultInfo.checkContext);
2362 ResultInfo bodyResultInfo = lambdaType.getReturnType() == Type.recoveryType ?
2363 recoveryInfo :
2364 new ResultInfo(VAL, lambdaType.getReturnType(), funcContext);
2365 localEnv.info.returnResult = bodyResultInfo;
2367 if (that.getBodyKind() == JCLambda.BodyKind.EXPRESSION) {
2368 attribTree(that.getBody(), localEnv, bodyResultInfo);
2369 } else {
2370 JCBlock body = (JCBlock)that.body;
2371 attribStats(body.stats, localEnv);
2372 }
2374 result = check(that, currentTarget, VAL, resultInfo);
2376 boolean isSpeculativeRound =
2377 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
2379 preFlow(that);
2380 flow.analyzeLambda(env, that, make, isSpeculativeRound);
2382 checkLambdaCompatible(that, lambdaType, resultInfo.checkContext);
2384 if (!isSpeculativeRound) {
2385 //add thrown types as bounds to the thrown types free variables if needed:
2386 if (resultInfo.checkContext.inferenceContext().free(lambdaType.getThrownTypes())) {
2387 List<Type> inferredThrownTypes = flow.analyzeLambdaThrownTypes(env, that, make);
2388 List<Type> thrownTypes = resultInfo.checkContext.inferenceContext().asUndetVars(lambdaType.getThrownTypes());
2390 chk.unhandled(inferredThrownTypes, thrownTypes);
2391 }
2393 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), lambdaType, currentTarget);
2394 }
2395 result = check(that, currentTarget, VAL, resultInfo);
2396 } catch (Types.FunctionDescriptorLookupError ex) {
2397 JCDiagnostic cause = ex.getDiagnostic();
2398 resultInfo.checkContext.report(that, cause);
2399 result = that.type = types.createErrorType(pt());
2400 return;
2401 } finally {
2402 localEnv.info.scope.leave();
2403 if (needsRecovery) {
2404 attribTree(that, env, recoveryInfo);
2405 }
2406 }
2407 }
2408 //where
2409 void preFlow(JCLambda tree) {
2410 new PostAttrAnalyzer() {
2411 @Override
2412 public void scan(JCTree tree) {
2413 if (tree == null ||
2414 (tree.type != null &&
2415 tree.type == Type.stuckType)) {
2416 //don't touch stuck expressions!
2417 return;
2418 }
2419 super.scan(tree);
2420 }
2421 }.scan(tree);
2422 }
2424 Types.MapVisitor<DiagnosticPosition> targetChecker = new Types.MapVisitor<DiagnosticPosition>() {
2426 @Override
2427 public Type visitClassType(ClassType t, DiagnosticPosition pos) {
2428 return t.isCompound() ?
2429 visitIntersectionClassType((IntersectionClassType)t, pos) : t;
2430 }
2432 public Type visitIntersectionClassType(IntersectionClassType ict, DiagnosticPosition pos) {
2433 Symbol desc = types.findDescriptorSymbol(makeNotionalInterface(ict));
2434 Type target = null;
2435 for (Type bound : ict.getExplicitComponents()) {
2436 TypeSymbol boundSym = bound.tsym;
2437 if (types.isFunctionalInterface(boundSym) &&
2438 types.findDescriptorSymbol(boundSym) == desc) {
2439 target = bound;
2440 } else if (!boundSym.isInterface() || (boundSym.flags() & ANNOTATION) != 0) {
2441 //bound must be an interface
2442 reportIntersectionError(pos, "not.an.intf.component", boundSym);
2443 }
2444 }
2445 return target != null ?
2446 target :
2447 ict.getExplicitComponents().head; //error recovery
2448 }
2450 private TypeSymbol makeNotionalInterface(IntersectionClassType ict) {
2451 ListBuffer<Type> targs = new ListBuffer<>();
2452 ListBuffer<Type> supertypes = new ListBuffer<>();
2453 for (Type i : ict.interfaces_field) {
2454 if (i.isParameterized()) {
2455 targs.appendList(i.tsym.type.allparams());
2456 }
2457 supertypes.append(i.tsym.type);
2458 }
2459 IntersectionClassType notionalIntf =
2460 (IntersectionClassType)types.makeCompoundType(supertypes.toList());
2461 notionalIntf.allparams_field = targs.toList();
2462 notionalIntf.tsym.flags_field |= INTERFACE;
2463 return notionalIntf.tsym;
2464 }
2466 private void reportIntersectionError(DiagnosticPosition pos, String key, Object... args) {
2467 resultInfo.checkContext.report(pos, diags.fragment("bad.intersection.target.for.functional.expr",
2468 diags.fragment(key, args)));
2469 }
2470 };
2472 private Type fallbackDescriptorType(JCExpression tree) {
2473 switch (tree.getTag()) {
2474 case LAMBDA:
2475 JCLambda lambda = (JCLambda)tree;
2476 List<Type> argtypes = List.nil();
2477 for (JCVariableDecl param : lambda.params) {
2478 argtypes = param.vartype != null ?
2479 argtypes.append(param.vartype.type) :
2480 argtypes.append(syms.errType);
2481 }
2482 return new MethodType(argtypes, Type.recoveryType,
2483 List.of(syms.throwableType), syms.methodClass);
2484 case REFERENCE:
2485 return new MethodType(List.<Type>nil(), Type.recoveryType,
2486 List.of(syms.throwableType), syms.methodClass);
2487 default:
2488 Assert.error("Cannot get here!");
2489 }
2490 return null;
2491 }
2493 private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
2494 final InferenceContext inferenceContext, final Type... ts) {
2495 checkAccessibleTypes(pos, env, inferenceContext, List.from(ts));
2496 }
2498 private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
2499 final InferenceContext inferenceContext, final List<Type> ts) {
2500 if (inferenceContext.free(ts)) {
2501 inferenceContext.addFreeTypeListener(ts, new FreeTypeListener() {
2502 @Override
2503 public void typesInferred(InferenceContext inferenceContext) {
2504 checkAccessibleTypes(pos, env, inferenceContext, inferenceContext.asInstTypes(ts));
2505 }
2506 });
2507 } else {
2508 for (Type t : ts) {
2509 rs.checkAccessibleType(env, t);
2510 }
2511 }
2512 }
2514 /**
2515 * Lambda/method reference have a special check context that ensures
2516 * that i.e. a lambda return type is compatible with the expected
2517 * type according to both the inherited context and the assignment
2518 * context.
2519 */
2520 class FunctionalReturnContext extends Check.NestedCheckContext {
2522 FunctionalReturnContext(CheckContext enclosingContext) {
2523 super(enclosingContext);
2524 }
2526 @Override
2527 public boolean compatible(Type found, Type req, Warner warn) {
2528 //return type must be compatible in both current context and assignment context
2529 return chk.basicHandler.compatible(found, inferenceContext().asUndetVar(req), warn);
2530 }
2532 @Override
2533 public void report(DiagnosticPosition pos, JCDiagnostic details) {
2534 enclosingContext.report(pos, diags.fragment("incompatible.ret.type.in.lambda", details));
2535 }
2536 }
2538 class ExpressionLambdaReturnContext extends FunctionalReturnContext {
2540 JCExpression expr;
2542 ExpressionLambdaReturnContext(JCExpression expr, CheckContext enclosingContext) {
2543 super(enclosingContext);
2544 this.expr = expr;
2545 }
2547 @Override
2548 public boolean compatible(Type found, Type req, Warner warn) {
2549 //a void return is compatible with an expression statement lambda
2550 return TreeInfo.isExpressionStatement(expr) && req.hasTag(VOID) ||
2551 super.compatible(found, req, warn);
2552 }
2553 }
2555 /**
2556 * Lambda compatibility. Check that given return types, thrown types, parameter types
2557 * are compatible with the expected functional interface descriptor. This means that:
2558 * (i) parameter types must be identical to those of the target descriptor; (ii) return
2559 * types must be compatible with the return type of the expected descriptor.
2560 */
2561 private void checkLambdaCompatible(JCLambda tree, Type descriptor, CheckContext checkContext) {
2562 Type returnType = checkContext.inferenceContext().asUndetVar(descriptor.getReturnType());
2564 //return values have already been checked - but if lambda has no return
2565 //values, we must ensure that void/value compatibility is correct;
2566 //this amounts at checking that, if a lambda body can complete normally,
2567 //the descriptor's return type must be void
2568 if (tree.getBodyKind() == JCLambda.BodyKind.STATEMENT && tree.canCompleteNormally &&
2569 !returnType.hasTag(VOID) && returnType != Type.recoveryType) {
2570 checkContext.report(tree, diags.fragment("incompatible.ret.type.in.lambda",
2571 diags.fragment("missing.ret.val", returnType)));
2572 }
2574 List<Type> argTypes = checkContext.inferenceContext().asUndetVars(descriptor.getParameterTypes());
2575 if (!types.isSameTypes(argTypes, TreeInfo.types(tree.params))) {
2576 checkContext.report(tree, diags.fragment("incompatible.arg.types.in.lambda"));
2577 }
2578 }
2580 /* Map to hold 'fake' clinit methods. If a lambda is used to initialize a
2581 * static field and that lambda has type annotations, these annotations will
2582 * also be stored at these fake clinit methods.
2583 *
2584 * LambdaToMethod also use fake clinit methods so they can be reused.
2585 * Also as LTM is a phase subsequent to attribution, the methods from
2586 * clinits can be safely removed by LTM to save memory.
2587 */
2588 private Map<ClassSymbol, MethodSymbol> clinits = new HashMap<>();
2590 public MethodSymbol removeClinit(ClassSymbol sym) {
2591 return clinits.remove(sym);
2592 }
2594 /* This method returns an environment to be used to attribute a lambda
2595 * expression.
2596 *
2597 * The owner of this environment is a method symbol. If the current owner
2598 * is not a method, for example if the lambda is used to initialize
2599 * a field, then if the field is:
2600 *
2601 * - an instance field, we use the first constructor.
2602 * - a static field, we create a fake clinit method.
2603 */
2604 public Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) {
2605 Env<AttrContext> lambdaEnv;
2606 Symbol owner = env.info.scope.owner;
2607 if (owner.kind == VAR && owner.owner.kind == TYP) {
2608 //field initializer
2609 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared()));
2610 ClassSymbol enclClass = owner.enclClass();
2611 /* if the field isn't static, then we can get the first constructor
2612 * and use it as the owner of the environment. This is what
2613 * LTM code is doing to look for type annotations so we are fine.
2614 */
2615 if ((owner.flags() & STATIC) == 0) {
2616 for (Symbol s : enclClass.members_field.getElementsByName(names.init)) {
2617 lambdaEnv.info.scope.owner = s;
2618 break;
2619 }
2620 } else {
2621 /* if the field is static then we need to create a fake clinit
2622 * method, this method can later be reused by LTM.
2623 */
2624 MethodSymbol clinit = clinits.get(enclClass);
2625 if (clinit == null) {
2626 Type clinitType = new MethodType(List.<Type>nil(),
2627 syms.voidType, List.<Type>nil(), syms.methodClass);
2628 clinit = new MethodSymbol(STATIC | SYNTHETIC | PRIVATE,
2629 names.clinit, clinitType, enclClass);
2630 clinit.params = List.<VarSymbol>nil();
2631 clinits.put(enclClass, clinit);
2632 }
2633 lambdaEnv.info.scope.owner = clinit;
2634 }
2635 } else {
2636 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dup()));
2637 }
2638 return lambdaEnv;
2639 }
2641 @Override
2642 public void visitReference(final JCMemberReference that) {
2643 if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
2644 if (pt().hasTag(NONE)) {
2645 //method reference only allowed in assignment or method invocation/cast context
2646 log.error(that.pos(), "unexpected.mref");
2647 }
2648 result = that.type = types.createErrorType(pt());
2649 return;
2650 }
2651 final Env<AttrContext> localEnv = env.dup(that);
2652 try {
2653 //attribute member reference qualifier - if this is a constructor
2654 //reference, the expected kind must be a type
2655 Type exprType = attribTree(that.expr, env, memberReferenceQualifierResult(that));
2657 if (that.getMode() == JCMemberReference.ReferenceMode.NEW) {
2658 exprType = chk.checkConstructorRefType(that.expr, exprType);
2659 if (!exprType.isErroneous() &&
2660 exprType.isRaw() &&
2661 that.typeargs != null) {
2662 log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
2663 diags.fragment("mref.infer.and.explicit.params"));
2664 exprType = types.createErrorType(exprType);
2665 }
2666 }
2668 if (exprType.isErroneous()) {
2669 //if the qualifier expression contains problems,
2670 //give up attribution of method reference
2671 result = that.type = exprType;
2672 return;
2673 }
2675 if (TreeInfo.isStaticSelector(that.expr, names)) {
2676 //if the qualifier is a type, validate it; raw warning check is
2677 //omitted as we don't know at this stage as to whether this is a
2678 //raw selector (because of inference)
2679 chk.validate(that.expr, env, false);
2680 }
2682 //attrib type-arguments
2683 List<Type> typeargtypes = List.nil();
2684 if (that.typeargs != null) {
2685 typeargtypes = attribTypes(that.typeargs, localEnv);
2686 }
2688 Type desc;
2689 Type currentTarget = pt();
2690 boolean isTargetSerializable =
2691 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
2692 isSerializable(currentTarget);
2693 if (currentTarget != Type.recoveryType) {
2694 currentTarget = types.removeWildcards(targetChecker.visit(currentTarget, that));
2695 desc = types.findDescriptorType(currentTarget);
2696 } else {
2697 currentTarget = Type.recoveryType;
2698 desc = fallbackDescriptorType(that);
2699 }
2701 setFunctionalInfo(localEnv, that, pt(), desc, currentTarget, resultInfo.checkContext);
2702 List<Type> argtypes = desc.getParameterTypes();
2703 Resolve.MethodCheck referenceCheck = rs.resolveMethodCheck;
2705 if (resultInfo.checkContext.inferenceContext().free(argtypes)) {
2706 referenceCheck = rs.new MethodReferenceCheck(resultInfo.checkContext.inferenceContext());
2707 }
2709 Pair<Symbol, Resolve.ReferenceLookupHelper> refResult = null;
2710 List<Type> saved_undet = resultInfo.checkContext.inferenceContext().save();
2711 try {
2712 refResult = rs.resolveMemberReference(localEnv, that, that.expr.type,
2713 that.name, argtypes, typeargtypes, referenceCheck,
2714 resultInfo.checkContext.inferenceContext(),
2715 resultInfo.checkContext.deferredAttrContext().mode);
2716 } finally {
2717 resultInfo.checkContext.inferenceContext().rollback(saved_undet);
2718 }
2720 Symbol refSym = refResult.fst;
2721 Resolve.ReferenceLookupHelper lookupHelper = refResult.snd;
2723 if (refSym.kind != MTH) {
2724 boolean targetError;
2725 switch (refSym.kind) {
2726 case ABSENT_MTH:
2727 targetError = false;
2728 break;
2729 case WRONG_MTH:
2730 case WRONG_MTHS:
2731 case AMBIGUOUS:
2732 case HIDDEN:
2733 case STATICERR:
2734 case MISSING_ENCL:
2735 case WRONG_STATICNESS:
2736 targetError = true;
2737 break;
2738 default:
2739 Assert.error("unexpected result kind " + refSym.kind);
2740 targetError = false;
2741 }
2743 JCDiagnostic detailsDiag = ((Resolve.ResolveError)refSym.baseSymbol()).getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT,
2744 that, exprType.tsym, exprType, that.name, argtypes, typeargtypes);
2746 JCDiagnostic.DiagnosticType diagKind = targetError ?
2747 JCDiagnostic.DiagnosticType.FRAGMENT : JCDiagnostic.DiagnosticType.ERROR;
2749 JCDiagnostic diag = diags.create(diagKind, log.currentSource(), that,
2750 "invalid.mref", Kinds.kindName(that.getMode()), detailsDiag);
2752 if (targetError && currentTarget == Type.recoveryType) {
2753 //a target error doesn't make sense during recovery stage
2754 //as we don't know what actual parameter types are
2755 result = that.type = currentTarget;
2756 return;
2757 } else {
2758 if (targetError) {
2759 resultInfo.checkContext.report(that, diag);
2760 } else {
2761 log.report(diag);
2762 }
2763 result = that.type = types.createErrorType(currentTarget);
2764 return;
2765 }
2766 }
2768 that.sym = refSym.baseSymbol();
2769 that.kind = lookupHelper.referenceKind(that.sym);
2770 that.ownerAccessible = rs.isAccessible(localEnv, that.sym.enclClass());
2772 if (desc.getReturnType() == Type.recoveryType) {
2773 // stop here
2774 result = that.type = currentTarget;
2775 return;
2776 }
2778 if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
2780 if (that.getMode() == ReferenceMode.INVOKE &&
2781 TreeInfo.isStaticSelector(that.expr, names) &&
2782 that.kind.isUnbound() &&
2783 !desc.getParameterTypes().head.isParameterized()) {
2784 chk.checkRaw(that.expr, localEnv);
2785 }
2787 if (that.sym.isStatic() && TreeInfo.isStaticSelector(that.expr, names) &&
2788 exprType.getTypeArguments().nonEmpty()) {
2789 //static ref with class type-args
2790 log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
2791 diags.fragment("static.mref.with.targs"));
2792 result = that.type = types.createErrorType(currentTarget);
2793 return;
2794 }
2796 if (that.sym.isStatic() && !TreeInfo.isStaticSelector(that.expr, names) &&
2797 !that.kind.isUnbound()) {
2798 //no static bound mrefs
2799 log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
2800 diags.fragment("static.bound.mref"));
2801 result = that.type = types.createErrorType(currentTarget);
2802 return;
2803 }
2805 if (!refSym.isStatic() && that.kind == JCMemberReference.ReferenceKind.SUPER) {
2806 // Check that super-qualified symbols are not abstract (JLS)
2807 rs.checkNonAbstract(that.pos(), that.sym);
2808 }
2810 if (isTargetSerializable) {
2811 chk.checkElemAccessFromSerializableLambda(that);
2812 }
2813 }
2815 ResultInfo checkInfo =
2816 resultInfo.dup(newMethodTemplate(
2817 desc.getReturnType().hasTag(VOID) ? Type.noType : desc.getReturnType(),
2818 that.kind.isUnbound() ? argtypes.tail : argtypes, typeargtypes),
2819 new FunctionalReturnContext(resultInfo.checkContext));
2821 Type refType = checkId(that, lookupHelper.site, refSym, localEnv, checkInfo);
2823 if (that.kind.isUnbound() &&
2824 resultInfo.checkContext.inferenceContext().free(argtypes.head)) {
2825 //re-generate inference constraints for unbound receiver
2826 if (!types.isSubtype(resultInfo.checkContext.inferenceContext().asUndetVar(argtypes.head), exprType)) {
2827 //cannot happen as this has already been checked - we just need
2828 //to regenerate the inference constraints, as that has been lost
2829 //as a result of the call to inferenceContext.save()
2830 Assert.error("Can't get here");
2831 }
2832 }
2834 if (!refType.isErroneous()) {
2835 refType = types.createMethodTypeWithReturn(refType,
2836 adjustMethodReturnType(lookupHelper.site, that.name, checkInfo.pt.getParameterTypes(), refType.getReturnType()));
2837 }
2839 //go ahead with standard method reference compatibility check - note that param check
2840 //is a no-op (as this has been taken care during method applicability)
2841 boolean isSpeculativeRound =
2842 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
2843 checkReferenceCompatible(that, desc, refType, resultInfo.checkContext, isSpeculativeRound);
2844 if (!isSpeculativeRound) {
2845 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), desc, currentTarget);
2846 }
2847 result = check(that, currentTarget, VAL, resultInfo);
2848 } catch (Types.FunctionDescriptorLookupError ex) {
2849 JCDiagnostic cause = ex.getDiagnostic();
2850 resultInfo.checkContext.report(that, cause);
2851 result = that.type = types.createErrorType(pt());
2852 return;
2853 }
2854 }
2855 //where
2856 ResultInfo memberReferenceQualifierResult(JCMemberReference tree) {
2857 //if this is a constructor reference, the expected kind must be a type
2858 return new ResultInfo(tree.getMode() == ReferenceMode.INVOKE ? VAL | TYP : TYP, Type.noType);
2859 }
2862 @SuppressWarnings("fallthrough")
2863 void checkReferenceCompatible(JCMemberReference tree, Type descriptor, Type refType, CheckContext checkContext, boolean speculativeAttr) {
2864 Type returnType = checkContext.inferenceContext().asUndetVar(descriptor.getReturnType());
2866 Type resType;
2867 switch (tree.getMode()) {
2868 case NEW:
2869 if (!tree.expr.type.isRaw()) {
2870 resType = tree.expr.type;
2871 break;
2872 }
2873 default:
2874 resType = refType.getReturnType();
2875 }
2877 Type incompatibleReturnType = resType;
2879 if (returnType.hasTag(VOID)) {
2880 incompatibleReturnType = null;
2881 }
2883 if (!returnType.hasTag(VOID) && !resType.hasTag(VOID)) {
2884 if (resType.isErroneous() ||
2885 new FunctionalReturnContext(checkContext).compatible(resType, returnType, types.noWarnings)) {
2886 incompatibleReturnType = null;
2887 }
2888 }
2890 if (incompatibleReturnType != null) {
2891 checkContext.report(tree, diags.fragment("incompatible.ret.type.in.mref",
2892 diags.fragment("inconvertible.types", resType, descriptor.getReturnType())));
2893 }
2895 if (!speculativeAttr) {
2896 List<Type> thrownTypes = checkContext.inferenceContext().asUndetVars(descriptor.getThrownTypes());
2897 if (chk.unhandled(refType.getThrownTypes(), thrownTypes).nonEmpty()) {
2898 log.error(tree, "incompatible.thrown.types.in.mref", refType.getThrownTypes());
2899 }
2900 }
2901 }
2903 /**
2904 * Set functional type info on the underlying AST. Note: as the target descriptor
2905 * might contain inference variables, we might need to register an hook in the
2906 * current inference context.
2907 */
2908 private void setFunctionalInfo(final Env<AttrContext> env, final JCFunctionalExpression fExpr,
2909 final Type pt, final Type descriptorType, final Type primaryTarget, final CheckContext checkContext) {
2910 if (checkContext.inferenceContext().free(descriptorType)) {
2911 checkContext.inferenceContext().addFreeTypeListener(List.of(pt, descriptorType), new FreeTypeListener() {
2912 public void typesInferred(InferenceContext inferenceContext) {
2913 setFunctionalInfo(env, fExpr, pt, inferenceContext.asInstType(descriptorType),
2914 inferenceContext.asInstType(primaryTarget), checkContext);
2915 }
2916 });
2917 } else {
2918 ListBuffer<Type> targets = new ListBuffer<>();
2919 if (pt.hasTag(CLASS)) {
2920 if (pt.isCompound()) {
2921 targets.append(types.removeWildcards(primaryTarget)); //this goes first
2922 for (Type t : ((IntersectionClassType)pt()).interfaces_field) {
2923 if (t != primaryTarget) {
2924 targets.append(types.removeWildcards(t));
2925 }
2926 }
2927 } else {
2928 targets.append(types.removeWildcards(primaryTarget));
2929 }
2930 }
2931 fExpr.targets = targets.toList();
2932 if (checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
2933 pt != Type.recoveryType) {
2934 //check that functional interface class is well-formed
2935 try {
2936 /* Types.makeFunctionalInterfaceClass() may throw an exception
2937 * when it's executed post-inference. See the listener code
2938 * above.
2939 */
2940 ClassSymbol csym = types.makeFunctionalInterfaceClass(env,
2941 names.empty, List.of(fExpr.targets.head), ABSTRACT);
2942 if (csym != null) {
2943 chk.checkImplementations(env.tree, csym, csym);
2944 }
2945 } catch (Types.FunctionDescriptorLookupError ex) {
2946 JCDiagnostic cause = ex.getDiagnostic();
2947 resultInfo.checkContext.report(env.tree, cause);
2948 }
2949 }
2950 }
2951 }
2953 public void visitParens(JCParens tree) {
2954 Type owntype = attribTree(tree.expr, env, resultInfo);
2955 result = check(tree, owntype, pkind(), resultInfo);
2956 Symbol sym = TreeInfo.symbol(tree);
2957 if (sym != null && (sym.kind&(TYP|PCK)) != 0)
2958 log.error(tree.pos(), "illegal.start.of.type");
2959 }
2961 public void visitAssign(JCAssign tree) {
2962 Type owntype = attribTree(tree.lhs, env.dup(tree), varInfo);
2963 Type capturedType = capture(owntype);
2964 attribExpr(tree.rhs, env, owntype);
2965 result = check(tree, capturedType, VAL, resultInfo);
2966 }
2968 public void visitAssignop(JCAssignOp tree) {
2969 // Attribute arguments.
2970 Type owntype = attribTree(tree.lhs, env, varInfo);
2971 Type operand = attribExpr(tree.rhs, env);
2972 // Find operator.
2973 Symbol operator = tree.operator = rs.resolveBinaryOperator(
2974 tree.pos(), tree.getTag().noAssignOp(), env,
2975 owntype, operand);
2977 if (operator.kind == MTH &&
2978 !owntype.isErroneous() &&
2979 !operand.isErroneous()) {
2980 chk.checkOperator(tree.pos(),
2981 (OperatorSymbol)operator,
2982 tree.getTag().noAssignOp(),
2983 owntype,
2984 operand);
2985 chk.checkDivZero(tree.rhs.pos(), operator, operand);
2986 chk.checkCastable(tree.rhs.pos(),
2987 operator.type.getReturnType(),
2988 owntype);
2989 }
2990 result = check(tree, owntype, VAL, resultInfo);
2991 }
2993 public void visitUnary(JCUnary tree) {
2994 // Attribute arguments.
2995 Type argtype = (tree.getTag().isIncOrDecUnaryOp())
2996 ? attribTree(tree.arg, env, varInfo)
2997 : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
2999 // Find operator.
3000 Symbol operator = tree.operator =
3001 rs.resolveUnaryOperator(tree.pos(), tree.getTag(), env, argtype);
3003 Type owntype = types.createErrorType(tree.type);
3004 if (operator.kind == MTH &&
3005 !argtype.isErroneous()) {
3006 owntype = (tree.getTag().isIncOrDecUnaryOp())
3007 ? tree.arg.type
3008 : operator.type.getReturnType();
3009 int opc = ((OperatorSymbol)operator).opcode;
3011 // If the argument is constant, fold it.
3012 if (argtype.constValue() != null) {
3013 Type ctype = cfolder.fold1(opc, argtype);
3014 if (ctype != null) {
3015 owntype = cfolder.coerce(ctype, owntype);
3016 }
3017 }
3018 }
3019 result = check(tree, owntype, VAL, resultInfo);
3020 }
3022 public void visitBinary(JCBinary tree) {
3023 // Attribute arguments.
3024 Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
3025 Type right = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.rhs, env));
3027 // Find operator.
3028 Symbol operator = tree.operator =
3029 rs.resolveBinaryOperator(tree.pos(), tree.getTag(), env, left, right);
3031 Type owntype = types.createErrorType(tree.type);
3032 if (operator.kind == MTH &&
3033 !left.isErroneous() &&
3034 !right.isErroneous()) {
3035 owntype = operator.type.getReturnType();
3036 // This will figure out when unboxing can happen and
3037 // choose the right comparison operator.
3038 int opc = chk.checkOperator(tree.lhs.pos(),
3039 (OperatorSymbol)operator,
3040 tree.getTag(),
3041 left,
3042 right);
3044 // If both arguments are constants, fold them.
3045 if (left.constValue() != null && right.constValue() != null) {
3046 Type ctype = cfolder.fold2(opc, left, right);
3047 if (ctype != null) {
3048 owntype = cfolder.coerce(ctype, owntype);
3049 }
3050 }
3052 // Check that argument types of a reference ==, != are
3053 // castable to each other, (JLS 15.21). Note: unboxing
3054 // comparisons will not have an acmp* opc at this point.
3055 if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
3056 if (!types.isEqualityComparable(left, right,
3057 new Warner(tree.pos()))) {
3058 log.error(tree.pos(), "incomparable.types", left, right);
3059 }
3060 }
3062 chk.checkDivZero(tree.rhs.pos(), operator, right);
3063 }
3064 result = check(tree, owntype, VAL, resultInfo);
3065 }
3067 public void visitTypeCast(final JCTypeCast tree) {
3068 Type clazztype = attribType(tree.clazz, env);
3069 chk.validate(tree.clazz, env, false);
3070 //a fresh environment is required for 292 inference to work properly ---
3071 //see Infer.instantiatePolymorphicSignatureInstance()
3072 Env<AttrContext> localEnv = env.dup(tree);
3073 //should we propagate the target type?
3074 final ResultInfo castInfo;
3075 JCExpression expr = TreeInfo.skipParens(tree.expr);
3076 boolean isPoly = allowPoly && (expr.hasTag(LAMBDA) || expr.hasTag(REFERENCE));
3077 if (isPoly) {
3078 //expression is a poly - we need to propagate target type info
3079 castInfo = new ResultInfo(VAL, clazztype, new Check.NestedCheckContext(resultInfo.checkContext) {
3080 @Override
3081 public boolean compatible(Type found, Type req, Warner warn) {
3082 return types.isCastable(found, req, warn);
3083 }
3084 });
3085 } else {
3086 //standalone cast - target-type info is not propagated
3087 castInfo = unknownExprInfo;
3088 }
3089 Type exprtype = attribTree(tree.expr, localEnv, castInfo);
3090 Type owntype = isPoly ? clazztype : chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
3091 if (exprtype.constValue() != null)
3092 owntype = cfolder.coerce(exprtype, owntype);
3093 result = check(tree, capture(owntype), VAL, resultInfo);
3094 if (!isPoly)
3095 chk.checkRedundantCast(localEnv, tree);
3096 }
3098 public void visitTypeTest(JCInstanceOf tree) {
3099 Type exprtype = chk.checkNullOrRefType(
3100 tree.expr.pos(), attribExpr(tree.expr, env));
3101 Type clazztype = attribType(tree.clazz, env);
3102 if (!clazztype.hasTag(TYPEVAR)) {
3103 clazztype = chk.checkClassOrArrayType(tree.clazz.pos(), clazztype);
3104 }
3105 if (!clazztype.isErroneous() && !types.isReifiable(clazztype)) {
3106 log.error(tree.clazz.pos(), "illegal.generic.type.for.instof");
3107 clazztype = types.createErrorType(clazztype);
3108 }
3109 chk.validate(tree.clazz, env, false);
3110 chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
3111 result = check(tree, syms.booleanType, VAL, resultInfo);
3112 }
3114 public void visitIndexed(JCArrayAccess tree) {
3115 Type owntype = types.createErrorType(tree.type);
3116 Type atype = attribExpr(tree.indexed, env);
3117 attribExpr(tree.index, env, syms.intType);
3118 if (types.isArray(atype))
3119 owntype = types.elemtype(atype);
3120 else if (!atype.hasTag(ERROR))
3121 log.error(tree.pos(), "array.req.but.found", atype);
3122 if ((pkind() & VAR) == 0) owntype = capture(owntype);
3123 result = check(tree, owntype, VAR, resultInfo);
3124 }
3126 public void visitIdent(JCIdent tree) {
3127 Symbol sym;
3129 // Find symbol
3130 if (pt().hasTag(METHOD) || pt().hasTag(FORALL)) {
3131 // If we are looking for a method, the prototype `pt' will be a
3132 // method type with the type of the call's arguments as parameters.
3133 env.info.pendingResolutionPhase = null;
3134 sym = rs.resolveMethod(tree.pos(), env, tree.name, pt().getParameterTypes(), pt().getTypeArguments());
3135 } else if (tree.sym != null && tree.sym.kind != VAR) {
3136 sym = tree.sym;
3137 } else {
3138 sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind());
3139 }
3140 tree.sym = sym;
3142 // (1) Also find the environment current for the class where
3143 // sym is defined (`symEnv').
3144 // Only for pre-tiger versions (1.4 and earlier):
3145 // (2) Also determine whether we access symbol out of an anonymous
3146 // class in a this or super call. This is illegal for instance
3147 // members since such classes don't carry a this$n link.
3148 // (`noOuterThisPath').
3149 Env<AttrContext> symEnv = env;
3150 boolean noOuterThisPath = false;
3151 if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
3152 (sym.kind & (VAR | MTH | TYP)) != 0 &&
3153 sym.owner.kind == TYP &&
3154 tree.name != names._this && tree.name != names._super) {
3156 // Find environment in which identifier is defined.
3157 while (symEnv.outer != null &&
3158 !sym.isMemberOf(symEnv.enclClass.sym, types)) {
3159 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
3160 noOuterThisPath = !allowAnonOuterThis;
3161 symEnv = symEnv.outer;
3162 }
3163 }
3165 // If symbol is a variable, ...
3166 if (sym.kind == VAR) {
3167 VarSymbol v = (VarSymbol)sym;
3169 // ..., evaluate its initializer, if it has one, and check for
3170 // illegal forward reference.
3171 checkInit(tree, env, v, false);
3173 // If we are expecting a variable (as opposed to a value), check
3174 // that the variable is assignable in the current environment.
3175 if (pkind() == VAR)
3176 checkAssignable(tree.pos(), v, null, env);
3177 }
3179 // In a constructor body,
3180 // if symbol is a field or instance method, check that it is
3181 // not accessed before the supertype constructor is called.
3182 if ((symEnv.info.isSelfCall || noOuterThisPath) &&
3183 (sym.kind & (VAR | MTH)) != 0 &&
3184 sym.owner.kind == TYP &&
3185 (sym.flags() & STATIC) == 0) {
3186 chk.earlyRefError(tree.pos(), sym.kind == VAR ? sym : thisSym(tree.pos(), env));
3187 }
3188 Env<AttrContext> env1 = env;
3189 if (sym.kind != ERR && sym.kind != TYP && sym.owner != null && sym.owner != env1.enclClass.sym) {
3190 // If the found symbol is inaccessible, then it is
3191 // accessed through an enclosing instance. Locate this
3192 // enclosing instance:
3193 while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
3194 env1 = env1.outer;
3195 }
3197 if (env.info.isSerializable) {
3198 chk.checkElemAccessFromSerializableLambda(tree);
3199 }
3201 result = checkId(tree, env1.enclClass.sym.type, sym, env, resultInfo);
3202 }
3204 public void visitSelect(JCFieldAccess tree) {
3205 // Determine the expected kind of the qualifier expression.
3206 int skind = 0;
3207 if (tree.name == names._this || tree.name == names._super ||
3208 tree.name == names._class)
3209 {
3210 skind = TYP;
3211 } else {
3212 if ((pkind() & PCK) != 0) skind = skind | PCK;
3213 if ((pkind() & TYP) != 0) skind = skind | TYP | PCK;
3214 if ((pkind() & (VAL | MTH)) != 0) skind = skind | VAL | TYP;
3215 }
3217 // Attribute the qualifier expression, and determine its symbol (if any).
3218 Type site = attribTree(tree.selected, env, new ResultInfo(skind, Infer.anyPoly));
3219 if ((pkind() & (PCK | TYP)) == 0)
3220 site = capture(site); // Capture field access
3222 // don't allow T.class T[].class, etc
3223 if (skind == TYP) {
3224 Type elt = site;
3225 while (elt.hasTag(ARRAY))
3226 elt = ((ArrayType)elt.unannotatedType()).elemtype;
3227 if (elt.hasTag(TYPEVAR)) {
3228 log.error(tree.pos(), "type.var.cant.be.deref");
3229 result = types.createErrorType(tree.type);
3230 return;
3231 }
3232 }
3234 // If qualifier symbol is a type or `super', assert `selectSuper'
3235 // for the selection. This is relevant for determining whether
3236 // protected symbols are accessible.
3237 Symbol sitesym = TreeInfo.symbol(tree.selected);
3238 boolean selectSuperPrev = env.info.selectSuper;
3239 env.info.selectSuper =
3240 sitesym != null &&
3241 sitesym.name == names._super;
3243 // Determine the symbol represented by the selection.
3244 env.info.pendingResolutionPhase = null;
3245 Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
3246 if (sym.exists() && !isType(sym) && (pkind() & (PCK | TYP)) != 0) {
3247 site = capture(site);
3248 sym = selectSym(tree, sitesym, site, env, resultInfo);
3249 }
3250 boolean varArgs = env.info.lastResolveVarargs();
3251 tree.sym = sym;
3253 if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) {
3254 while (site.hasTag(TYPEVAR)) site = site.getUpperBound();
3255 site = capture(site);
3256 }
3258 // If that symbol is a variable, ...
3259 if (sym.kind == VAR) {
3260 VarSymbol v = (VarSymbol)sym;
3262 // ..., evaluate its initializer, if it has one, and check for
3263 // illegal forward reference.
3264 checkInit(tree, env, v, true);
3266 // If we are expecting a variable (as opposed to a value), check
3267 // that the variable is assignable in the current environment.
3268 if (pkind() == VAR)
3269 checkAssignable(tree.pos(), v, tree.selected, env);
3270 }
3272 if (sitesym != null &&
3273 sitesym.kind == VAR &&
3274 ((VarSymbol)sitesym).isResourceVariable() &&
3275 sym.kind == MTH &&
3276 sym.name.equals(names.close) &&
3277 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) &&
3278 env.info.lint.isEnabled(LintCategory.TRY)) {
3279 log.warning(LintCategory.TRY, tree, "try.explicit.close.call");
3280 }
3282 // Disallow selecting a type from an expression
3283 if (isType(sym) && (sitesym==null || (sitesym.kind&(TYP|PCK)) == 0)) {
3284 tree.type = check(tree.selected, pt(),
3285 sitesym == null ? VAL : sitesym.kind, new ResultInfo(TYP|PCK, pt()));
3286 }
3288 if (isType(sitesym)) {
3289 if (sym.name == names._this) {
3290 // If `C' is the currently compiled class, check that
3291 // C.this' does not appear in a call to a super(...)
3292 if (env.info.isSelfCall &&
3293 site.tsym == env.enclClass.sym) {
3294 chk.earlyRefError(tree.pos(), sym);
3295 }
3296 } else {
3297 // Check if type-qualified fields or methods are static (JLS)
3298 if ((sym.flags() & STATIC) == 0 &&
3299 !env.next.tree.hasTag(REFERENCE) &&
3300 sym.name != names._super &&
3301 (sym.kind == VAR || sym.kind == MTH)) {
3302 rs.accessBase(rs.new StaticError(sym),
3303 tree.pos(), site, sym.name, true);
3304 }
3305 }
3306 if (!allowStaticInterfaceMethods && sitesym.isInterface() &&
3307 sym.isStatic() && sym.kind == MTH) {
3308 log.error(tree.pos(), "static.intf.method.invoke.not.supported.in.source", sourceName);
3309 }
3310 } else if (sym.kind != ERR && (sym.flags() & STATIC) != 0 && sym.name != names._class) {
3311 // If the qualified item is not a type and the selected item is static, report
3312 // a warning. Make allowance for the class of an array type e.g. Object[].class)
3313 chk.warnStatic(tree, "static.not.qualified.by.type", Kinds.kindName(sym.kind), sym.owner);
3314 }
3316 // If we are selecting an instance member via a `super', ...
3317 if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
3319 // Check that super-qualified symbols are not abstract (JLS)
3320 rs.checkNonAbstract(tree.pos(), sym);
3322 if (site.isRaw()) {
3323 // Determine argument types for site.
3324 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
3325 if (site1 != null) site = site1;
3326 }
3327 }
3329 if (env.info.isSerializable) {
3330 chk.checkElemAccessFromSerializableLambda(tree);
3331 }
3333 env.info.selectSuper = selectSuperPrev;
3334 result = checkId(tree, site, sym, env, resultInfo);
3335 }
3336 //where
3337 /** Determine symbol referenced by a Select expression,
3338 *
3339 * @param tree The select tree.
3340 * @param site The type of the selected expression,
3341 * @param env The current environment.
3342 * @param resultInfo The current result.
3343 */
3344 private Symbol selectSym(JCFieldAccess tree,
3345 Symbol location,
3346 Type site,
3347 Env<AttrContext> env,
3348 ResultInfo resultInfo) {
3349 DiagnosticPosition pos = tree.pos();
3350 Name name = tree.name;
3351 switch (site.getTag()) {
3352 case PACKAGE:
3353 return rs.accessBase(
3354 rs.findIdentInPackage(env, site.tsym, name, resultInfo.pkind),
3355 pos, location, site, name, true);
3356 case ARRAY:
3357 case CLASS:
3358 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) {
3359 return rs.resolveQualifiedMethod(
3360 pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
3361 } else if (name == names._this || name == names._super) {
3362 return rs.resolveSelf(pos, env, site.tsym, name);
3363 } else if (name == names._class) {
3364 // In this case, we have already made sure in
3365 // visitSelect that qualifier expression is a type.
3366 Type t = syms.classType;
3367 List<Type> typeargs = allowGenerics
3368 ? List.of(types.erasure(site))
3369 : List.<Type>nil();
3370 t = new ClassType(t.getEnclosingType(), typeargs, t.tsym);
3371 return new VarSymbol(
3372 STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
3373 } else {
3374 // We are seeing a plain identifier as selector.
3375 Symbol sym = rs.findIdentInType(env, site, name, resultInfo.pkind);
3376 if ((resultInfo.pkind & ERRONEOUS) == 0)
3377 sym = rs.accessBase(sym, pos, location, site, name, true);
3378 return sym;
3379 }
3380 case WILDCARD:
3381 throw new AssertionError(tree);
3382 case TYPEVAR:
3383 // Normally, site.getUpperBound() shouldn't be null.
3384 // It should only happen during memberEnter/attribBase
3385 // when determining the super type which *must* beac
3386 // done before attributing the type variables. In
3387 // other words, we are seeing this illegal program:
3388 // class B<T> extends A<T.foo> {}
3389 Symbol sym = (site.getUpperBound() != null)
3390 ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
3391 : null;
3392 if (sym == null) {
3393 log.error(pos, "type.var.cant.be.deref");
3394 return syms.errSymbol;
3395 } else {
3396 Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
3397 rs.new AccessError(env, site, sym) :
3398 sym;
3399 rs.accessBase(sym2, pos, location, site, name, true);
3400 return sym;
3401 }
3402 case ERROR:
3403 // preserve identifier names through errors
3404 return types.createErrorType(name, site.tsym, site).tsym;
3405 default:
3406 // The qualifier expression is of a primitive type -- only
3407 // .class is allowed for these.
3408 if (name == names._class) {
3409 // In this case, we have already made sure in Select that
3410 // qualifier expression is a type.
3411 Type t = syms.classType;
3412 Type arg = types.boxedClass(site).type;
3413 t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym);
3414 return new VarSymbol(
3415 STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
3416 } else {
3417 log.error(pos, "cant.deref", site);
3418 return syms.errSymbol;
3419 }
3420 }
3421 }
3423 /** Determine type of identifier or select expression and check that
3424 * (1) the referenced symbol is not deprecated
3425 * (2) the symbol's type is safe (@see checkSafe)
3426 * (3) if symbol is a variable, check that its type and kind are
3427 * compatible with the prototype and protokind.
3428 * (4) if symbol is an instance field of a raw type,
3429 * which is being assigned to, issue an unchecked warning if its
3430 * type changes under erasure.
3431 * (5) if symbol is an instance method of a raw type, issue an
3432 * unchecked warning if its argument types change under erasure.
3433 * If checks succeed:
3434 * If symbol is a constant, return its constant type
3435 * else if symbol is a method, return its result type
3436 * otherwise return its type.
3437 * Otherwise return errType.
3438 *
3439 * @param tree The syntax tree representing the identifier
3440 * @param site If this is a select, the type of the selected
3441 * expression, otherwise the type of the current class.
3442 * @param sym The symbol representing the identifier.
3443 * @param env The current environment.
3444 * @param resultInfo The expected result
3445 */
3446 Type checkId(JCTree tree,
3447 Type site,
3448 Symbol sym,
3449 Env<AttrContext> env,
3450 ResultInfo resultInfo) {
3451 return (resultInfo.pt.hasTag(FORALL) || resultInfo.pt.hasTag(METHOD)) ?
3452 checkMethodId(tree, site, sym, env, resultInfo) :
3453 checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
3454 }
3456 Type checkMethodId(JCTree tree,
3457 Type site,
3458 Symbol sym,
3459 Env<AttrContext> env,
3460 ResultInfo resultInfo) {
3461 boolean isPolymorhicSignature =
3462 (sym.baseSymbol().flags() & SIGNATURE_POLYMORPHIC) != 0;
3463 return isPolymorhicSignature ?
3464 checkSigPolyMethodId(tree, site, sym, env, resultInfo) :
3465 checkMethodIdInternal(tree, site, sym, env, resultInfo);
3466 }
3468 Type checkSigPolyMethodId(JCTree tree,
3469 Type site,
3470 Symbol sym,
3471 Env<AttrContext> env,
3472 ResultInfo resultInfo) {
3473 //recover original symbol for signature polymorphic methods
3474 checkMethodIdInternal(tree, site, sym.baseSymbol(), env, resultInfo);
3475 env.info.pendingResolutionPhase = Resolve.MethodResolutionPhase.BASIC;
3476 return sym.type;
3477 }
3479 Type checkMethodIdInternal(JCTree tree,
3480 Type site,
3481 Symbol sym,
3482 Env<AttrContext> env,
3483 ResultInfo resultInfo) {
3484 if ((resultInfo.pkind & POLY) != 0) {
3485 Type pt = resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, sym, env.info.pendingResolutionPhase));
3486 Type owntype = checkIdInternal(tree, site, sym, pt, env, resultInfo);
3487 resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
3488 return owntype;
3489 } else {
3490 return checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
3491 }
3492 }
3494 Type checkIdInternal(JCTree tree,
3495 Type site,
3496 Symbol sym,
3497 Type pt,
3498 Env<AttrContext> env,
3499 ResultInfo resultInfo) {
3500 if (pt.isErroneous()) {
3501 return types.createErrorType(site);
3502 }
3503 Type owntype; // The computed type of this identifier occurrence.
3504 switch (sym.kind) {
3505 case TYP:
3506 // For types, the computed type equals the symbol's type,
3507 // except for two situations:
3508 owntype = sym.type;
3509 if (owntype.hasTag(CLASS)) {
3510 chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym);
3511 Type ownOuter = owntype.getEnclosingType();
3513 // (a) If the symbol's type is parameterized, erase it
3514 // because no type parameters were given.
3515 // We recover generic outer type later in visitTypeApply.
3516 if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
3517 owntype = types.erasure(owntype);
3518 }
3520 // (b) If the symbol's type is an inner class, then
3521 // we have to interpret its outer type as a superclass
3522 // of the site type. Example:
3523 //
3524 // class Tree<A> { class Visitor { ... } }
3525 // class PointTree extends Tree<Point> { ... }
3526 // ...PointTree.Visitor...
3527 //
3528 // Then the type of the last expression above is
3529 // Tree<Point>.Visitor.
3530 else if (ownOuter.hasTag(CLASS) && site != ownOuter) {
3531 Type normOuter = site;
3532 if (normOuter.hasTag(CLASS)) {
3533 normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
3534 }
3535 if (normOuter == null) // perhaps from an import
3536 normOuter = types.erasure(ownOuter);
3537 if (normOuter != ownOuter)
3538 owntype = new ClassType(
3539 normOuter, List.<Type>nil(), owntype.tsym);
3540 }
3541 }
3542 break;
3543 case VAR:
3544 VarSymbol v = (VarSymbol)sym;
3545 // Test (4): if symbol is an instance field of a raw type,
3546 // which is being assigned to, issue an unchecked warning if
3547 // its type changes under erasure.
3548 if (allowGenerics &&
3549 resultInfo.pkind == VAR &&
3550 v.owner.kind == TYP &&
3551 (v.flags() & STATIC) == 0 &&
3552 (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
3553 Type s = types.asOuterSuper(site, v.owner);
3554 if (s != null &&
3555 s.isRaw() &&
3556 !types.isSameType(v.type, v.erasure(types))) {
3557 chk.warnUnchecked(tree.pos(),
3558 "unchecked.assign.to.var",
3559 v, s);
3560 }
3561 }
3562 // The computed type of a variable is the type of the
3563 // variable symbol, taken as a member of the site type.
3564 owntype = (sym.owner.kind == TYP &&
3565 sym.name != names._this && sym.name != names._super)
3566 ? types.memberType(site, sym)
3567 : sym.type;
3569 // If the variable is a constant, record constant value in
3570 // computed type.
3571 if (v.getConstValue() != null && isStaticReference(tree))
3572 owntype = owntype.constType(v.getConstValue());
3574 if (resultInfo.pkind == VAL) {
3575 owntype = capture(owntype); // capture "names as expressions"
3576 }
3577 break;
3578 case MTH: {
3579 owntype = checkMethod(site, sym,
3580 new ResultInfo(resultInfo.pkind, resultInfo.pt.getReturnType(), resultInfo.checkContext),
3581 env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(),
3582 resultInfo.pt.getTypeArguments());
3583 break;
3584 }
3585 case PCK: case ERR:
3586 owntype = sym.type;
3587 break;
3588 default:
3589 throw new AssertionError("unexpected kind: " + sym.kind +
3590 " in tree " + tree);
3591 }
3593 // Test (1): emit a `deprecation' warning if symbol is deprecated.
3594 // (for constructors, the error was given when the constructor was
3595 // resolved)
3597 if (sym.name != names.init) {
3598 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym);
3599 chk.checkSunAPI(tree.pos(), sym);
3600 chk.checkProfile(tree.pos(), sym);
3601 }
3603 // Test (3): if symbol is a variable, check that its type and
3604 // kind are compatible with the prototype and protokind.
3605 return check(tree, owntype, sym.kind, resultInfo);
3606 }
3608 /** Check that variable is initialized and evaluate the variable's
3609 * initializer, if not yet done. Also check that variable is not
3610 * referenced before it is defined.
3611 * @param tree The tree making up the variable reference.
3612 * @param env The current environment.
3613 * @param v The variable's symbol.
3614 */
3615 private void checkInit(JCTree tree,
3616 Env<AttrContext> env,
3617 VarSymbol v,
3618 boolean onlyWarning) {
3619 // System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " +
3620 // tree.pos + " " + v.pos + " " +
3621 // Resolve.isStatic(env));//DEBUG
3623 // A forward reference is diagnosed if the declaration position
3624 // of the variable is greater than the current tree position
3625 // and the tree and variable definition occur in the same class
3626 // definition. Note that writes don't count as references.
3627 // This check applies only to class and instance
3628 // variables. Local variables follow different scope rules,
3629 // and are subject to definite assignment checking.
3630 if ((env.info.enclVar == v || v.pos > tree.pos) &&
3631 v.owner.kind == TYP &&
3632 enclosingInitEnv(env) != null &&
3633 v.owner == env.info.scope.owner.enclClass() &&
3634 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
3635 (!env.tree.hasTag(ASSIGN) ||
3636 TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
3637 String suffix = (env.info.enclVar == v) ?
3638 "self.ref" : "forward.ref";
3639 if (!onlyWarning || isStaticEnumField(v)) {
3640 log.error(tree.pos(), "illegal." + suffix);
3641 } else if (useBeforeDeclarationWarning) {
3642 log.warning(tree.pos(), suffix, v);
3643 }
3644 }
3646 v.getConstValue(); // ensure initializer is evaluated
3648 checkEnumInitializer(tree, env, v);
3649 }
3651 /**
3652 * Returns the enclosing init environment associated with this env (if any). An init env
3653 * can be either a field declaration env or a static/instance initializer env.
3654 */
3655 Env<AttrContext> enclosingInitEnv(Env<AttrContext> env) {
3656 while (true) {
3657 switch (env.tree.getTag()) {
3658 case VARDEF:
3659 JCVariableDecl vdecl = (JCVariableDecl)env.tree;
3660 if (vdecl.sym.owner.kind == TYP) {
3661 //field
3662 return env;
3663 }
3664 break;
3665 case BLOCK:
3666 if (env.next.tree.hasTag(CLASSDEF)) {
3667 //instance/static initializer
3668 return env;
3669 }
3670 break;
3671 case METHODDEF:
3672 case CLASSDEF:
3673 case TOPLEVEL:
3674 return null;
3675 }
3676 Assert.checkNonNull(env.next);
3677 env = env.next;
3678 }
3679 }
3681 /**
3682 * Check for illegal references to static members of enum. In
3683 * an enum type, constructors and initializers may not
3684 * reference its static members unless they are constant.
3685 *
3686 * @param tree The tree making up the variable reference.
3687 * @param env The current environment.
3688 * @param v The variable's symbol.
3689 * @jls section 8.9 Enums
3690 */
3691 private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
3692 // JLS:
3693 //
3694 // "It is a compile-time error to reference a static field
3695 // of an enum type that is not a compile-time constant
3696 // (15.28) from constructors, instance initializer blocks,
3697 // or instance variable initializer expressions of that
3698 // type. It is a compile-time error for the constructors,
3699 // instance initializer blocks, or instance variable
3700 // initializer expressions of an enum constant e to refer
3701 // to itself or to an enum constant of the same type that
3702 // is declared to the right of e."
3703 if (isStaticEnumField(v)) {
3704 ClassSymbol enclClass = env.info.scope.owner.enclClass();
3706 if (enclClass == null || enclClass.owner == null)
3707 return;
3709 // See if the enclosing class is the enum (or a
3710 // subclass thereof) declaring v. If not, this
3711 // reference is OK.
3712 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
3713 return;
3715 // If the reference isn't from an initializer, then
3716 // the reference is OK.
3717 if (!Resolve.isInitializer(env))
3718 return;
3720 log.error(tree.pos(), "illegal.enum.static.ref");
3721 }
3722 }
3724 /** Is the given symbol a static, non-constant field of an Enum?
3725 * Note: enum literals should not be regarded as such
3726 */
3727 private boolean isStaticEnumField(VarSymbol v) {
3728 return Flags.isEnum(v.owner) &&
3729 Flags.isStatic(v) &&
3730 !Flags.isConstant(v) &&
3731 v.name != names._class;
3732 }
3734 Warner noteWarner = new Warner();
3736 /**
3737 * Check that method arguments conform to its instantiation.
3738 **/
3739 public Type checkMethod(Type site,
3740 final Symbol sym,
3741 ResultInfo resultInfo,
3742 Env<AttrContext> env,
3743 final List<JCExpression> argtrees,
3744 List<Type> argtypes,
3745 List<Type> typeargtypes) {
3746 // Test (5): if symbol is an instance method of a raw type, issue
3747 // an unchecked warning if its argument types change under erasure.
3748 if (allowGenerics &&
3749 (sym.flags() & STATIC) == 0 &&
3750 (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
3751 Type s = types.asOuterSuper(site, sym.owner);
3752 if (s != null && s.isRaw() &&
3753 !types.isSameTypes(sym.type.getParameterTypes(),
3754 sym.erasure(types).getParameterTypes())) {
3755 chk.warnUnchecked(env.tree.pos(),
3756 "unchecked.call.mbr.of.raw.type",
3757 sym, s);
3758 }
3759 }
3761 if (env.info.defaultSuperCallSite != null) {
3762 for (Type sup : types.interfaces(env.enclClass.type).prepend(types.supertype((env.enclClass.type)))) {
3763 if (!sup.tsym.isSubClass(sym.enclClass(), types) ||
3764 types.isSameType(sup, env.info.defaultSuperCallSite)) continue;
3765 List<MethodSymbol> icand_sup =
3766 types.interfaceCandidates(sup, (MethodSymbol)sym);
3767 if (icand_sup.nonEmpty() &&
3768 icand_sup.head != sym &&
3769 icand_sup.head.overrides(sym, icand_sup.head.enclClass(), types, true)) {
3770 log.error(env.tree.pos(), "illegal.default.super.call", env.info.defaultSuperCallSite,
3771 diags.fragment("overridden.default", sym, sup));
3772 break;
3773 }
3774 }
3775 env.info.defaultSuperCallSite = null;
3776 }
3778 if (sym.isStatic() && site.isInterface() && env.tree.hasTag(APPLY)) {
3779 JCMethodInvocation app = (JCMethodInvocation)env.tree;
3780 if (app.meth.hasTag(SELECT) &&
3781 !TreeInfo.isStaticSelector(((JCFieldAccess)app.meth).selected, names)) {
3782 log.error(env.tree.pos(), "illegal.static.intf.meth.call", site);
3783 }
3784 }
3786 // Compute the identifier's instantiated type.
3787 // For methods, we need to compute the instance type by
3788 // Resolve.instantiate from the symbol's type as well as
3789 // any type arguments and value arguments.
3790 noteWarner.clear();
3791 try {
3792 Type owntype = rs.checkMethod(
3793 env,
3794 site,
3795 sym,
3796 resultInfo,
3797 argtypes,
3798 typeargtypes,
3799 noteWarner);
3801 DeferredAttr.DeferredTypeMap checkDeferredMap =
3802 deferredAttr.new DeferredTypeMap(DeferredAttr.AttrMode.CHECK, sym, env.info.pendingResolutionPhase);
3804 argtypes = Type.map(argtypes, checkDeferredMap);
3806 if (noteWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
3807 chk.warnUnchecked(env.tree.pos(),
3808 "unchecked.meth.invocation.applied",
3809 kindName(sym),
3810 sym.name,
3811 rs.methodArguments(sym.type.getParameterTypes()),
3812 rs.methodArguments(Type.map(argtypes, checkDeferredMap)),
3813 kindName(sym.location()),
3814 sym.location());
3815 owntype = new MethodType(owntype.getParameterTypes(),
3816 types.erasure(owntype.getReturnType()),
3817 types.erasure(owntype.getThrownTypes()),
3818 syms.methodClass);
3819 }
3821 return chk.checkMethod(owntype, sym, env, argtrees, argtypes, env.info.lastResolveVarargs(),
3822 resultInfo.checkContext.inferenceContext());
3823 } catch (Infer.InferenceException ex) {
3824 //invalid target type - propagate exception outwards or report error
3825 //depending on the current check context
3826 resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic());
3827 return types.createErrorType(site);
3828 } catch (Resolve.InapplicableMethodException ex) {
3829 final JCDiagnostic diag = ex.getDiagnostic();
3830 Resolve.InapplicableSymbolError errSym = rs.new InapplicableSymbolError(null) {
3831 @Override
3832 protected Pair<Symbol, JCDiagnostic> errCandidate() {
3833 return new Pair<Symbol, JCDiagnostic>(sym, diag);
3834 }
3835 };
3836 List<Type> argtypes2 = Type.map(argtypes,
3837 rs.new ResolveDeferredRecoveryMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
3838 JCDiagnostic errDiag = errSym.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
3839 env.tree, sym, site, sym.name, argtypes2, typeargtypes);
3840 log.report(errDiag);
3841 return types.createErrorType(site);
3842 }
3843 }
3845 public void visitLiteral(JCLiteral tree) {
3846 result = check(
3847 tree, litType(tree.typetag).constType(tree.value), VAL, resultInfo);
3848 }
3849 //where
3850 /** Return the type of a literal with given type tag.
3851 */
3852 Type litType(TypeTag tag) {
3853 return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()];
3854 }
3856 public void visitTypeIdent(JCPrimitiveTypeTree tree) {
3857 result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], TYP, resultInfo);
3858 }
3860 public void visitTypeArray(JCArrayTypeTree tree) {
3861 Type etype = attribType(tree.elemtype, env);
3862 Type type = new ArrayType(etype, syms.arrayClass);
3863 result = check(tree, type, TYP, resultInfo);
3864 }
3866 /** Visitor method for parameterized types.
3867 * Bound checking is left until later, since types are attributed
3868 * before supertype structure is completely known
3869 */
3870 public void visitTypeApply(JCTypeApply tree) {
3871 Type owntype = types.createErrorType(tree.type);
3873 // Attribute functor part of application and make sure it's a class.
3874 Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
3876 // Attribute type parameters
3877 List<Type> actuals = attribTypes(tree.arguments, env);
3879 if (clazztype.hasTag(CLASS)) {
3880 List<Type> formals = clazztype.tsym.type.getTypeArguments();
3881 if (actuals.isEmpty()) //diamond
3882 actuals = formals;
3884 if (actuals.length() == formals.length()) {
3885 List<Type> a = actuals;
3886 List<Type> f = formals;
3887 while (a.nonEmpty()) {
3888 a.head = a.head.withTypeVar(f.head);
3889 a = a.tail;
3890 f = f.tail;
3891 }
3892 // Compute the proper generic outer
3893 Type clazzOuter = clazztype.getEnclosingType();
3894 if (clazzOuter.hasTag(CLASS)) {
3895 Type site;
3896 JCExpression clazz = TreeInfo.typeIn(tree.clazz);
3897 if (clazz.hasTag(IDENT)) {
3898 site = env.enclClass.sym.type;
3899 } else if (clazz.hasTag(SELECT)) {
3900 site = ((JCFieldAccess) clazz).selected.type;
3901 } else throw new AssertionError(""+tree);
3902 if (clazzOuter.hasTag(CLASS) && site != clazzOuter) {
3903 if (site.hasTag(CLASS))
3904 site = types.asOuterSuper(site, clazzOuter.tsym);
3905 if (site == null)
3906 site = types.erasure(clazzOuter);
3907 clazzOuter = site;
3908 }
3909 }
3910 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym);
3911 } else {
3912 if (formals.length() != 0) {
3913 log.error(tree.pos(), "wrong.number.type.args",
3914 Integer.toString(formals.length()));
3915 } else {
3916 log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym);
3917 }
3918 owntype = types.createErrorType(tree.type);
3919 }
3920 }
3921 result = check(tree, owntype, TYP, resultInfo);
3922 }
3924 public void visitTypeUnion(JCTypeUnion tree) {
3925 ListBuffer<Type> multicatchTypes = new ListBuffer<>();
3926 ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
3927 for (JCExpression typeTree : tree.alternatives) {
3928 Type ctype = attribType(typeTree, env);
3929 ctype = chk.checkType(typeTree.pos(),
3930 chk.checkClassType(typeTree.pos(), ctype),
3931 syms.throwableType);
3932 if (!ctype.isErroneous()) {
3933 //check that alternatives of a union type are pairwise
3934 //unrelated w.r.t. subtyping
3935 if (chk.intersects(ctype, multicatchTypes.toList())) {
3936 for (Type t : multicatchTypes) {
3937 boolean sub = types.isSubtype(ctype, t);
3938 boolean sup = types.isSubtype(t, ctype);
3939 if (sub || sup) {
3940 //assume 'a' <: 'b'
3941 Type a = sub ? ctype : t;
3942 Type b = sub ? t : ctype;
3943 log.error(typeTree.pos(), "multicatch.types.must.be.disjoint", a, b);
3944 }
3945 }
3946 }
3947 multicatchTypes.append(ctype);
3948 if (all_multicatchTypes != null)
3949 all_multicatchTypes.append(ctype);
3950 } else {
3951 if (all_multicatchTypes == null) {
3952 all_multicatchTypes = new ListBuffer<>();
3953 all_multicatchTypes.appendList(multicatchTypes);
3954 }
3955 all_multicatchTypes.append(ctype);
3956 }
3957 }
3958 Type t = check(tree, types.lub(multicatchTypes.toList()), TYP, resultInfo);
3959 if (t.hasTag(CLASS)) {
3960 List<Type> alternatives =
3961 ((all_multicatchTypes == null) ? multicatchTypes : all_multicatchTypes).toList();
3962 t = new UnionClassType((ClassType) t, alternatives);
3963 }
3964 tree.type = result = t;
3965 }
3967 public void visitTypeIntersection(JCTypeIntersection tree) {
3968 attribTypes(tree.bounds, env);
3969 tree.type = result = checkIntersection(tree, tree.bounds);
3970 }
3972 public void visitTypeParameter(JCTypeParameter tree) {
3973 TypeVar typeVar = (TypeVar) tree.type;
3975 if (tree.annotations != null && tree.annotations.nonEmpty()) {
3976 annotateType(tree, tree.annotations);
3977 }
3979 if (!typeVar.bound.isErroneous()) {
3980 //fixup type-parameter bound computed in 'attribTypeVariables'
3981 typeVar.bound = checkIntersection(tree, tree.bounds);
3982 }
3983 }
3985 Type checkIntersection(JCTree tree, List<JCExpression> bounds) {
3986 Set<Type> boundSet = new HashSet<Type>();
3987 if (bounds.nonEmpty()) {
3988 // accept class or interface or typevar as first bound.
3989 bounds.head.type = checkBase(bounds.head.type, bounds.head, env, false, false, false);
3990 boundSet.add(types.erasure(bounds.head.type));
3991 if (bounds.head.type.isErroneous()) {
3992 return bounds.head.type;
3993 }
3994 else if (bounds.head.type.hasTag(TYPEVAR)) {
3995 // if first bound was a typevar, do not accept further bounds.
3996 if (bounds.tail.nonEmpty()) {
3997 log.error(bounds.tail.head.pos(),
3998 "type.var.may.not.be.followed.by.other.bounds");
3999 return bounds.head.type;
4000 }
4001 } else {
4002 // if first bound was a class or interface, accept only interfaces
4003 // as further bounds.
4004 for (JCExpression bound : bounds.tail) {
4005 bound.type = checkBase(bound.type, bound, env, false, true, false);
4006 if (bound.type.isErroneous()) {
4007 bounds = List.of(bound);
4008 }
4009 else if (bound.type.hasTag(CLASS)) {
4010 chk.checkNotRepeated(bound.pos(), types.erasure(bound.type), boundSet);
4011 }
4012 }
4013 }
4014 }
4016 if (bounds.length() == 0) {
4017 return syms.objectType;
4018 } else if (bounds.length() == 1) {
4019 return bounds.head.type;
4020 } else {
4021 Type owntype = types.makeCompoundType(TreeInfo.types(bounds));
4022 // ... the variable's bound is a class type flagged COMPOUND
4023 // (see comment for TypeVar.bound).
4024 // In this case, generate a class tree that represents the
4025 // bound class, ...
4026 JCExpression extending;
4027 List<JCExpression> implementing;
4028 if (!bounds.head.type.isInterface()) {
4029 extending = bounds.head;
4030 implementing = bounds.tail;
4031 } else {
4032 extending = null;
4033 implementing = bounds;
4034 }
4035 JCClassDecl cd = make.at(tree).ClassDef(
4036 make.Modifiers(PUBLIC | ABSTRACT),
4037 names.empty, List.<JCTypeParameter>nil(),
4038 extending, implementing, List.<JCTree>nil());
4040 ClassSymbol c = (ClassSymbol)owntype.tsym;
4041 Assert.check((c.flags() & COMPOUND) != 0);
4042 cd.sym = c;
4043 c.sourcefile = env.toplevel.sourcefile;
4045 // ... and attribute the bound class
4046 c.flags_field |= UNATTRIBUTED;
4047 Env<AttrContext> cenv = enter.classEnv(cd, env);
4048 typeEnvs.put(c, cenv);
4049 attribClass(c);
4050 return owntype;
4051 }
4052 }
4054 public void visitWildcard(JCWildcard tree) {
4055 //- System.err.println("visitWildcard("+tree+");");//DEBUG
4056 Type type = (tree.kind.kind == BoundKind.UNBOUND)
4057 ? syms.objectType
4058 : attribType(tree.inner, env);
4059 result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
4060 tree.kind.kind,
4061 syms.boundClass),
4062 TYP, resultInfo);
4063 }
4065 public void visitAnnotation(JCAnnotation tree) {
4066 Assert.error("should be handled in Annotate");
4067 }
4069 public void visitAnnotatedType(JCAnnotatedType tree) {
4070 Type underlyingType = attribType(tree.getUnderlyingType(), env);
4071 this.attribAnnotationTypes(tree.annotations, env);
4072 annotateType(tree, tree.annotations);
4073 result = tree.type = underlyingType;
4074 }
4076 /**
4077 * Apply the annotations to the particular type.
4078 */
4079 public void annotateType(final JCTree tree, final List<JCAnnotation> annotations) {
4080 annotate.typeAnnotation(new Annotate.Worker() {
4081 @Override
4082 public String toString() {
4083 return "annotate " + annotations + " onto " + tree;
4084 }
4085 @Override
4086 public void run() {
4087 List<Attribute.TypeCompound> compounds = fromAnnotations(annotations);
4088 if (annotations.size() == compounds.size()) {
4089 // All annotations were successfully converted into compounds
4090 tree.type = tree.type.unannotatedType().annotatedType(compounds);
4091 }
4092 }
4093 });
4094 }
4096 private static List<Attribute.TypeCompound> fromAnnotations(List<JCAnnotation> annotations) {
4097 if (annotations.isEmpty()) {
4098 return List.nil();
4099 }
4101 ListBuffer<Attribute.TypeCompound> buf = new ListBuffer<>();
4102 for (JCAnnotation anno : annotations) {
4103 if (anno.attribute != null) {
4104 // TODO: this null-check is only needed for an obscure
4105 // ordering issue, where annotate.flush is called when
4106 // the attribute is not set yet. For an example failure
4107 // try the referenceinfos/NestedTypes.java test.
4108 // Any better solutions?
4109 buf.append((Attribute.TypeCompound) anno.attribute);
4110 }
4111 // Eventually we will want to throw an exception here, but
4112 // we can't do that just yet, because it gets triggered
4113 // when attempting to attach an annotation that isn't
4114 // defined.
4115 }
4116 return buf.toList();
4117 }
4119 public void visitErroneous(JCErroneous tree) {
4120 if (tree.errs != null)
4121 for (JCTree err : tree.errs)
4122 attribTree(err, env, new ResultInfo(ERR, pt()));
4123 result = tree.type = syms.errType;
4124 }
4126 /** Default visitor method for all other trees.
4127 */
4128 public void visitTree(JCTree tree) {
4129 throw new AssertionError();
4130 }
4132 /**
4133 * Attribute an env for either a top level tree or class declaration.
4134 */
4135 public void attrib(Env<AttrContext> env) {
4136 if (env.tree.hasTag(TOPLEVEL))
4137 attribTopLevel(env);
4138 else
4139 attribClass(env.tree.pos(), env.enclClass.sym);
4140 }
4142 /**
4143 * Attribute a top level tree. These trees are encountered when the
4144 * package declaration has annotations.
4145 */
4146 public void attribTopLevel(Env<AttrContext> env) {
4147 JCCompilationUnit toplevel = env.toplevel;
4148 try {
4149 annotate.flush();
4150 } catch (CompletionFailure ex) {
4151 chk.completionError(toplevel.pos(), ex);
4152 }
4153 }
4155 /** Main method: attribute class definition associated with given class symbol.
4156 * reporting completion failures at the given position.
4157 * @param pos The source position at which completion errors are to be
4158 * reported.
4159 * @param c The class symbol whose definition will be attributed.
4160 */
4161 public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
4162 try {
4163 annotate.flush();
4164 attribClass(c);
4165 } catch (CompletionFailure ex) {
4166 chk.completionError(pos, ex);
4167 }
4168 }
4170 /** Attribute class definition associated with given class symbol.
4171 * @param c The class symbol whose definition will be attributed.
4172 */
4173 void attribClass(ClassSymbol c) throws CompletionFailure {
4174 if (c.type.hasTag(ERROR)) return;
4176 // Check for cycles in the inheritance graph, which can arise from
4177 // ill-formed class files.
4178 chk.checkNonCyclic(null, c.type);
4180 Type st = types.supertype(c.type);
4181 if ((c.flags_field & Flags.COMPOUND) == 0) {
4182 // First, attribute superclass.
4183 if (st.hasTag(CLASS))
4184 attribClass((ClassSymbol)st.tsym);
4186 // Next attribute owner, if it is a class.
4187 if (c.owner.kind == TYP && c.owner.type.hasTag(CLASS))
4188 attribClass((ClassSymbol)c.owner);
4189 }
4191 // The previous operations might have attributed the current class
4192 // if there was a cycle. So we test first whether the class is still
4193 // UNATTRIBUTED.
4194 if ((c.flags_field & UNATTRIBUTED) != 0) {
4195 c.flags_field &= ~UNATTRIBUTED;
4197 // Get environment current at the point of class definition.
4198 Env<AttrContext> env = typeEnvs.get(c);
4200 // The info.lint field in the envs stored in typeEnvs is deliberately uninitialized,
4201 // because the annotations were not available at the time the env was created. Therefore,
4202 // we look up the environment chain for the first enclosing environment for which the
4203 // lint value is set. Typically, this is the parent env, but might be further if there
4204 // are any envs created as a result of TypeParameter nodes.
4205 Env<AttrContext> lintEnv = env;
4206 while (lintEnv.info.lint == null)
4207 lintEnv = lintEnv.next;
4209 // Having found the enclosing lint value, we can initialize the lint value for this class
4210 env.info.lint = lintEnv.info.lint.augment(c);
4212 Lint prevLint = chk.setLint(env.info.lint);
4213 JavaFileObject prev = log.useSource(c.sourcefile);
4214 ResultInfo prevReturnRes = env.info.returnResult;
4216 try {
4217 deferredLintHandler.flush(env.tree);
4218 env.info.returnResult = null;
4219 // java.lang.Enum may not be subclassed by a non-enum
4220 if (st.tsym == syms.enumSym &&
4221 ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
4222 log.error(env.tree.pos(), "enum.no.subclassing");
4224 // Enums may not be extended by source-level classes
4225 if (st.tsym != null &&
4226 ((st.tsym.flags_field & Flags.ENUM) != 0) &&
4227 ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
4228 log.error(env.tree.pos(), "enum.types.not.extensible");
4229 }
4231 if (isSerializable(c.type)) {
4232 env.info.isSerializable = true;
4233 }
4235 attribClassBody(env, c);
4237 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
4238 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
4239 chk.checkFunctionalInterface((JCClassDecl) env.tree, c);
4240 } finally {
4241 env.info.returnResult = prevReturnRes;
4242 log.useSource(prev);
4243 chk.setLint(prevLint);
4244 }
4246 }
4247 }
4249 public void visitImport(JCImport tree) {
4250 // nothing to do
4251 }
4253 /** Finish the attribution of a class. */
4254 private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
4255 JCClassDecl tree = (JCClassDecl)env.tree;
4256 Assert.check(c == tree.sym);
4258 // Validate type parameters, supertype and interfaces.
4259 attribStats(tree.typarams, env);
4260 if (!c.isAnonymous()) {
4261 //already checked if anonymous
4262 chk.validate(tree.typarams, env);
4263 chk.validate(tree.extending, env);
4264 chk.validate(tree.implementing, env);
4265 }
4267 // If this is a non-abstract class, check that it has no abstract
4268 // methods or unimplemented methods of an implemented interface.
4269 if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
4270 if (!relax)
4271 chk.checkAllDefined(tree.pos(), c);
4272 }
4274 if ((c.flags() & ANNOTATION) != 0) {
4275 if (tree.implementing.nonEmpty())
4276 log.error(tree.implementing.head.pos(),
4277 "cant.extend.intf.annotation");
4278 if (tree.typarams.nonEmpty())
4279 log.error(tree.typarams.head.pos(),
4280 "intf.annotation.cant.have.type.params");
4282 // If this annotation has a @Repeatable, validate
4283 Attribute.Compound repeatable = c.attribute(syms.repeatableType.tsym);
4284 if (repeatable != null) {
4285 // get diagnostic position for error reporting
4286 DiagnosticPosition cbPos = getDiagnosticPosition(tree, repeatable.type);
4287 Assert.checkNonNull(cbPos);
4289 chk.validateRepeatable(c, repeatable, cbPos);
4290 }
4291 } else {
4292 // Check that all extended classes and interfaces
4293 // are compatible (i.e. no two define methods with same arguments
4294 // yet different return types). (JLS 8.4.6.3)
4295 chk.checkCompatibleSupertypes(tree.pos(), c.type);
4296 if (allowDefaultMethods) {
4297 chk.checkDefaultMethodClashes(tree.pos(), c.type);
4298 }
4299 }
4301 // Check that class does not import the same parameterized interface
4302 // with two different argument lists.
4303 chk.checkClassBounds(tree.pos(), c.type);
4305 tree.type = c.type;
4307 for (List<JCTypeParameter> l = tree.typarams;
4308 l.nonEmpty(); l = l.tail) {
4309 Assert.checkNonNull(env.info.scope.lookup(l.head.name).scope);
4310 }
4312 // Check that a generic class doesn't extend Throwable
4313 if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
4314 log.error(tree.extending.pos(), "generic.throwable");
4316 // Check that all methods which implement some
4317 // method conform to the method they implement.
4318 chk.checkImplementations(tree);
4320 //check that a resource implementing AutoCloseable cannot throw InterruptedException
4321 checkAutoCloseable(tree.pos(), env, c.type);
4323 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
4324 // Attribute declaration
4325 attribStat(l.head, env);
4326 // Check that declarations in inner classes are not static (JLS 8.1.2)
4327 // Make an exception for static constants.
4328 if (c.owner.kind != PCK &&
4329 ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
4330 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
4331 Symbol sym = null;
4332 if (l.head.hasTag(VARDEF)) sym = ((JCVariableDecl) l.head).sym;
4333 if (sym == null ||
4334 sym.kind != VAR ||
4335 ((VarSymbol) sym).getConstValue() == null)
4336 log.error(l.head.pos(), "icls.cant.have.static.decl", c);
4337 }
4338 }
4340 // Check for cycles among non-initial constructors.
4341 chk.checkCyclicConstructors(tree);
4343 // Check for cycles among annotation elements.
4344 chk.checkNonCyclicElements(tree);
4346 // Check for proper use of serialVersionUID
4347 if (env.info.lint.isEnabled(LintCategory.SERIAL) &&
4348 isSerializable(c.type) &&
4349 (c.flags() & Flags.ENUM) == 0 &&
4350 checkForSerial(c)) {
4351 checkSerialVersionUID(tree, c);
4352 }
4353 if (allowTypeAnnos) {
4354 // Correctly organize the postions of the type annotations
4355 typeAnnotations.organizeTypeAnnotationsBodies(tree);
4357 // Check type annotations applicability rules
4358 validateTypeAnnotations(tree, false);
4359 }
4360 }
4361 // where
4362 boolean checkForSerial(ClassSymbol c) {
4363 if ((c.flags() & ABSTRACT) == 0) {
4364 return true;
4365 } else {
4366 return c.members().anyMatch(anyNonAbstractOrDefaultMethod);
4367 }
4368 }
4370 public static final Filter<Symbol> anyNonAbstractOrDefaultMethod = new Filter<Symbol>() {
4371 @Override
4372 public boolean accepts(Symbol s) {
4373 return s.kind == Kinds.MTH &&
4374 (s.flags() & (DEFAULT | ABSTRACT)) != ABSTRACT;
4375 }
4376 };
4378 /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
4379 private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
4380 for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
4381 if (types.isSameType(al.head.annotationType.type, t))
4382 return al.head.pos();
4383 }
4385 return null;
4386 }
4388 /** check if a type is a subtype of Serializable, if that is available. */
4389 boolean isSerializable(Type t) {
4390 try {
4391 syms.serializableType.complete();
4392 }
4393 catch (CompletionFailure e) {
4394 return false;
4395 }
4396 return types.isSubtype(t, syms.serializableType);
4397 }
4399 /** Check that an appropriate serialVersionUID member is defined. */
4400 private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
4402 // check for presence of serialVersionUID
4403 Scope.Entry e = c.members().lookup(names.serialVersionUID);
4404 while (e.scope != null && e.sym.kind != VAR) e = e.next();
4405 if (e.scope == null) {
4406 log.warning(LintCategory.SERIAL,
4407 tree.pos(), "missing.SVUID", c);
4408 return;
4409 }
4411 // check that it is static final
4412 VarSymbol svuid = (VarSymbol)e.sym;
4413 if ((svuid.flags() & (STATIC | FINAL)) !=
4414 (STATIC | FINAL))
4415 log.warning(LintCategory.SERIAL,
4416 TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c);
4418 // check that it is long
4419 else if (!svuid.type.hasTag(LONG))
4420 log.warning(LintCategory.SERIAL,
4421 TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c);
4423 // check constant
4424 else if (svuid.getConstValue() == null)
4425 log.warning(LintCategory.SERIAL,
4426 TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c);
4427 }
4429 private Type capture(Type type) {
4430 return types.capture(type);
4431 }
4433 public void validateTypeAnnotations(JCTree tree, boolean sigOnly) {
4434 tree.accept(new TypeAnnotationsValidator(sigOnly));
4435 }
4436 //where
4437 private final class TypeAnnotationsValidator extends TreeScanner {
4439 private final boolean sigOnly;
4440 public TypeAnnotationsValidator(boolean sigOnly) {
4441 this.sigOnly = sigOnly;
4442 }
4444 public void visitAnnotation(JCAnnotation tree) {
4445 chk.validateTypeAnnotation(tree, false);
4446 super.visitAnnotation(tree);
4447 }
4448 public void visitAnnotatedType(JCAnnotatedType tree) {
4449 if (!tree.underlyingType.type.isErroneous()) {
4450 super.visitAnnotatedType(tree);
4451 }
4452 }
4453 public void visitTypeParameter(JCTypeParameter tree) {
4454 chk.validateTypeAnnotations(tree.annotations, true);
4455 scan(tree.bounds);
4456 // Don't call super.
4457 // This is needed because above we call validateTypeAnnotation with
4458 // false, which would forbid annotations on type parameters.
4459 // super.visitTypeParameter(tree);
4460 }
4461 public void visitMethodDef(JCMethodDecl tree) {
4462 if (tree.recvparam != null &&
4463 !tree.recvparam.vartype.type.isErroneous()) {
4464 checkForDeclarationAnnotations(tree.recvparam.mods.annotations,
4465 tree.recvparam.vartype.type.tsym);
4466 }
4467 if (tree.restype != null && tree.restype.type != null) {
4468 validateAnnotatedType(tree.restype, tree.restype.type);
4469 }
4470 if (sigOnly) {
4471 scan(tree.mods);
4472 scan(tree.restype);
4473 scan(tree.typarams);
4474 scan(tree.recvparam);
4475 scan(tree.params);
4476 scan(tree.thrown);
4477 } else {
4478 scan(tree.defaultValue);
4479 scan(tree.body);
4480 }
4481 }
4482 public void visitVarDef(final JCVariableDecl tree) {
4483 if (tree.sym != null && tree.sym.type != null)
4484 validateAnnotatedType(tree.vartype, tree.sym.type);
4485 scan(tree.mods);
4486 scan(tree.vartype);
4487 if (!sigOnly) {
4488 scan(tree.init);
4489 }
4490 }
4491 public void visitTypeCast(JCTypeCast tree) {
4492 if (tree.clazz != null && tree.clazz.type != null)
4493 validateAnnotatedType(tree.clazz, tree.clazz.type);
4494 super.visitTypeCast(tree);
4495 }
4496 public void visitTypeTest(JCInstanceOf tree) {
4497 if (tree.clazz != null && tree.clazz.type != null)
4498 validateAnnotatedType(tree.clazz, tree.clazz.type);
4499 super.visitTypeTest(tree);
4500 }
4501 public void visitNewClass(JCNewClass tree) {
4502 if (tree.clazz.hasTag(ANNOTATED_TYPE)) {
4503 checkForDeclarationAnnotations(((JCAnnotatedType) tree.clazz).annotations,
4504 tree.clazz.type.tsym);
4505 }
4506 if (tree.def != null) {
4507 checkForDeclarationAnnotations(tree.def.mods.annotations, tree.clazz.type.tsym);
4508 }
4509 if (tree.clazz.type != null) {
4510 validateAnnotatedType(tree.clazz, tree.clazz.type);
4511 }
4512 super.visitNewClass(tree);
4513 }
4514 public void visitNewArray(JCNewArray tree) {
4515 if (tree.elemtype != null && tree.elemtype.type != null) {
4516 if (tree.elemtype.hasTag(ANNOTATED_TYPE)) {
4517 checkForDeclarationAnnotations(((JCAnnotatedType) tree.elemtype).annotations,
4518 tree.elemtype.type.tsym);
4519 }
4520 validateAnnotatedType(tree.elemtype, tree.elemtype.type);
4521 }
4522 super.visitNewArray(tree);
4523 }
4524 public void visitClassDef(JCClassDecl tree) {
4525 if (sigOnly) {
4526 scan(tree.mods);
4527 scan(tree.typarams);
4528 scan(tree.extending);
4529 scan(tree.implementing);
4530 }
4531 for (JCTree member : tree.defs) {
4532 if (member.hasTag(Tag.CLASSDEF)) {
4533 continue;
4534 }
4535 scan(member);
4536 }
4537 }
4538 public void visitBlock(JCBlock tree) {
4539 if (!sigOnly) {
4540 scan(tree.stats);
4541 }
4542 }
4544 /* I would want to model this after
4545 * com.sun.tools.javac.comp.Check.Validator.visitSelectInternal(JCFieldAccess)
4546 * and override visitSelect and visitTypeApply.
4547 * However, we only set the annotated type in the top-level type
4548 * of the symbol.
4549 * Therefore, we need to override each individual location where a type
4550 * can occur.
4551 */
4552 private void validateAnnotatedType(final JCTree errtree, final Type type) {
4553 // System.out.println("Attr.validateAnnotatedType: " + errtree + " type: " + type);
4555 if (type.isPrimitiveOrVoid()) {
4556 return;
4557 }
4559 JCTree enclTr = errtree;
4560 Type enclTy = type;
4562 boolean repeat = true;
4563 while (repeat) {
4564 if (enclTr.hasTag(TYPEAPPLY)) {
4565 List<Type> tyargs = enclTy.getTypeArguments();
4566 List<JCExpression> trargs = ((JCTypeApply)enclTr).getTypeArguments();
4567 if (trargs.length() > 0) {
4568 // Nothing to do for diamonds
4569 if (tyargs.length() == trargs.length()) {
4570 for (int i = 0; i < tyargs.length(); ++i) {
4571 validateAnnotatedType(trargs.get(i), tyargs.get(i));
4572 }
4573 }
4574 // If the lengths don't match, it's either a diamond
4575 // or some nested type that redundantly provides
4576 // type arguments in the tree.
4577 }
4579 // Look at the clazz part of a generic type
4580 enclTr = ((JCTree.JCTypeApply)enclTr).clazz;
4581 }
4583 if (enclTr.hasTag(SELECT)) {
4584 enclTr = ((JCTree.JCFieldAccess)enclTr).getExpression();
4585 if (enclTy != null &&
4586 !enclTy.hasTag(NONE)) {
4587 enclTy = enclTy.getEnclosingType();
4588 }
4589 } else if (enclTr.hasTag(ANNOTATED_TYPE)) {
4590 JCAnnotatedType at = (JCTree.JCAnnotatedType) enclTr;
4591 if (enclTy == null ||
4592 enclTy.hasTag(NONE)) {
4593 if (at.getAnnotations().size() == 1) {
4594 log.error(at.underlyingType.pos(), "cant.type.annotate.scoping.1", at.getAnnotations().head.attribute);
4595 } else {
4596 ListBuffer<Attribute.Compound> comps = new ListBuffer<Attribute.Compound>();
4597 for (JCAnnotation an : at.getAnnotations()) {
4598 comps.add(an.attribute);
4599 }
4600 log.error(at.underlyingType.pos(), "cant.type.annotate.scoping", comps.toList());
4601 }
4602 repeat = false;
4603 }
4604 enclTr = at.underlyingType;
4605 // enclTy doesn't need to be changed
4606 } else if (enclTr.hasTag(IDENT)) {
4607 repeat = false;
4608 } else if (enclTr.hasTag(JCTree.Tag.WILDCARD)) {
4609 JCWildcard wc = (JCWildcard) enclTr;
4610 if (wc.getKind() == JCTree.Kind.EXTENDS_WILDCARD) {
4611 validateAnnotatedType(wc.getBound(), ((WildcardType)enclTy.unannotatedType()).getExtendsBound());
4612 } else if (wc.getKind() == JCTree.Kind.SUPER_WILDCARD) {
4613 validateAnnotatedType(wc.getBound(), ((WildcardType)enclTy.unannotatedType()).getSuperBound());
4614 } else {
4615 // Nothing to do for UNBOUND
4616 }
4617 repeat = false;
4618 } else if (enclTr.hasTag(TYPEARRAY)) {
4619 JCArrayTypeTree art = (JCArrayTypeTree) enclTr;
4620 validateAnnotatedType(art.getType(), ((ArrayType)enclTy.unannotatedType()).getComponentType());
4621 repeat = false;
4622 } else if (enclTr.hasTag(TYPEUNION)) {
4623 JCTypeUnion ut = (JCTypeUnion) enclTr;
4624 for (JCTree t : ut.getTypeAlternatives()) {
4625 validateAnnotatedType(t, t.type);
4626 }
4627 repeat = false;
4628 } else if (enclTr.hasTag(TYPEINTERSECTION)) {
4629 JCTypeIntersection it = (JCTypeIntersection) enclTr;
4630 for (JCTree t : it.getBounds()) {
4631 validateAnnotatedType(t, t.type);
4632 }
4633 repeat = false;
4634 } else if (enclTr.getKind() == JCTree.Kind.PRIMITIVE_TYPE ||
4635 enclTr.getKind() == JCTree.Kind.ERRONEOUS) {
4636 repeat = false;
4637 } else {
4638 Assert.error("Unexpected tree: " + enclTr + " with kind: " + enclTr.getKind() +
4639 " within: "+ errtree + " with kind: " + errtree.getKind());
4640 }
4641 }
4642 }
4644 private void checkForDeclarationAnnotations(List<? extends JCAnnotation> annotations,
4645 Symbol sym) {
4646 // Ensure that no declaration annotations are present.
4647 // Note that a tree type might be an AnnotatedType with
4648 // empty annotations, if only declaration annotations were given.
4649 // This method will raise an error for such a type.
4650 for (JCAnnotation ai : annotations) {
4651 if (!ai.type.isErroneous() &&
4652 typeAnnotations.annotationType(ai.attribute, sym) == TypeAnnotations.AnnotationType.DECLARATION) {
4653 log.error(ai.pos(), "annotation.type.not.applicable");
4654 }
4655 }
4656 }
4657 };
4659 // <editor-fold desc="post-attribution visitor">
4661 /**
4662 * Handle missing types/symbols in an AST. This routine is useful when
4663 * the compiler has encountered some errors (which might have ended up
4664 * terminating attribution abruptly); if the compiler is used in fail-over
4665 * mode (e.g. by an IDE) and the AST contains semantic errors, this routine
4666 * prevents NPE to be progagated during subsequent compilation steps.
4667 */
4668 public void postAttr(JCTree tree) {
4669 new PostAttrAnalyzer().scan(tree);
4670 }
4672 class PostAttrAnalyzer extends TreeScanner {
4674 private void initTypeIfNeeded(JCTree that) {
4675 if (that.type == null) {
4676 if (that.hasTag(METHODDEF)) {
4677 that.type = dummyMethodType((JCMethodDecl)that);
4678 } else {
4679 that.type = syms.unknownType;
4680 }
4681 }
4682 }
4684 /* Construct a dummy method type. If we have a method declaration,
4685 * and the declared return type is void, then use that return type
4686 * instead of UNKNOWN to avoid spurious error messages in lambda
4687 * bodies (see:JDK-8041704).
4688 */
4689 private Type dummyMethodType(JCMethodDecl md) {
4690 Type restype = syms.unknownType;
4691 if (md != null && md.restype.hasTag(TYPEIDENT)) {
4692 JCPrimitiveTypeTree prim = (JCPrimitiveTypeTree)md.restype;
4693 if (prim.typetag == VOID)
4694 restype = syms.voidType;
4695 }
4696 return new MethodType(List.<Type>nil(), restype,
4697 List.<Type>nil(), syms.methodClass);
4698 }
4699 private Type dummyMethodType() {
4700 return dummyMethodType(null);
4701 }
4703 @Override
4704 public void scan(JCTree tree) {
4705 if (tree == null) return;
4706 if (tree instanceof JCExpression) {
4707 initTypeIfNeeded(tree);
4708 }
4709 super.scan(tree);
4710 }
4712 @Override
4713 public void visitIdent(JCIdent that) {
4714 if (that.sym == null) {
4715 that.sym = syms.unknownSymbol;
4716 }
4717 }
4719 @Override
4720 public void visitSelect(JCFieldAccess that) {
4721 if (that.sym == null) {
4722 that.sym = syms.unknownSymbol;
4723 }
4724 super.visitSelect(that);
4725 }
4727 @Override
4728 public void visitClassDef(JCClassDecl that) {
4729 initTypeIfNeeded(that);
4730 if (that.sym == null) {
4731 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol);
4732 }
4733 super.visitClassDef(that);
4734 }
4736 @Override
4737 public void visitMethodDef(JCMethodDecl that) {
4738 initTypeIfNeeded(that);
4739 if (that.sym == null) {
4740 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol);
4741 }
4742 super.visitMethodDef(that);
4743 }
4745 @Override
4746 public void visitVarDef(JCVariableDecl that) {
4747 initTypeIfNeeded(that);
4748 if (that.sym == null) {
4749 that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol);
4750 that.sym.adr = 0;
4751 }
4752 super.visitVarDef(that);
4753 }
4755 @Override
4756 public void visitNewClass(JCNewClass that) {
4757 if (that.constructor == null) {
4758 that.constructor = new MethodSymbol(0, names.init,
4759 dummyMethodType(), syms.noSymbol);
4760 }
4761 if (that.constructorType == null) {
4762 that.constructorType = syms.unknownType;
4763 }
4764 super.visitNewClass(that);
4765 }
4767 @Override
4768 public void visitAssignop(JCAssignOp that) {
4769 if (that.operator == null) {
4770 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
4771 -1, syms.noSymbol);
4772 }
4773 super.visitAssignop(that);
4774 }
4776 @Override
4777 public void visitBinary(JCBinary that) {
4778 if (that.operator == null) {
4779 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
4780 -1, syms.noSymbol);
4781 }
4782 super.visitBinary(that);
4783 }
4785 @Override
4786 public void visitUnary(JCUnary that) {
4787 if (that.operator == null) {
4788 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
4789 -1, syms.noSymbol);
4790 }
4791 super.visitUnary(that);
4792 }
4794 @Override
4795 public void visitLambda(JCLambda that) {
4796 super.visitLambda(that);
4797 if (that.targets == null) {
4798 that.targets = List.nil();
4799 }
4800 }
4802 @Override
4803 public void visitReference(JCMemberReference that) {
4804 super.visitReference(that);
4805 if (that.sym == null) {
4806 that.sym = new MethodSymbol(0, names.empty, dummyMethodType(),
4807 syms.noSymbol);
4808 }
4809 if (that.targets == null) {
4810 that.targets = List.nil();
4811 }
4812 }
4813 }
4814 // </editor-fold>
4815 }