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