Mon, 21 Jan 2013 20:13:56 +0000
8005244: Implement overload resolution as per latest spec EDR
Summary: Add support for stuck expressions and provisional applicability
Reviewed-by: jjg
1 /*
2 * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
26 package com.sun.tools.javac.comp;
28 import java.util.*;
29 import java.util.Set;
31 import javax.lang.model.element.ElementKind;
32 import javax.tools.JavaFileObject;
34 import com.sun.source.tree.IdentifierTree;
35 import com.sun.source.tree.MemberReferenceTree.ReferenceMode;
36 import com.sun.source.tree.MemberSelectTree;
37 import com.sun.source.tree.TreeVisitor;
38 import com.sun.source.util.SimpleTreeVisitor;
39 import com.sun.tools.javac.code.*;
40 import com.sun.tools.javac.code.Lint.LintCategory;
41 import com.sun.tools.javac.code.Symbol.*;
42 import com.sun.tools.javac.code.Type.*;
43 import com.sun.tools.javac.comp.Check.CheckContext;
44 import com.sun.tools.javac.comp.DeferredAttr.AttrMode;
45 import com.sun.tools.javac.comp.Infer.InferenceContext;
46 import com.sun.tools.javac.comp.Infer.InferenceContext.FreeTypeListener;
47 import com.sun.tools.javac.jvm.*;
48 import com.sun.tools.javac.jvm.Target;
49 import com.sun.tools.javac.tree.*;
50 import com.sun.tools.javac.tree.JCTree.*;
51 import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*;
52 import com.sun.tools.javac.util.*;
53 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
54 import com.sun.tools.javac.util.List;
55 import static com.sun.tools.javac.code.Flags.*;
56 import static com.sun.tools.javac.code.Flags.ANNOTATION;
57 import static com.sun.tools.javac.code.Flags.BLOCK;
58 import static com.sun.tools.javac.code.Kinds.*;
59 import static com.sun.tools.javac.code.Kinds.ERRONEOUS;
60 import static com.sun.tools.javac.code.TypeTag.*;
61 import static com.sun.tools.javac.code.TypeTag.WILDCARD;
62 import static com.sun.tools.javac.tree.JCTree.Tag.*;
64 /** This is the main context-dependent analysis phase in GJC. It
65 * encompasses name resolution, type checking and constant folding as
66 * subtasks. Some subtasks involve auxiliary classes.
67 * @see Check
68 * @see Resolve
69 * @see ConstFold
70 * @see Infer
71 *
72 * <p><b>This is NOT part of any supported API.
73 * If you write code that depends on this, you do so at your own risk.
74 * This code and its internal interfaces are subject to change or
75 * deletion without notice.</b>
76 */
77 public class Attr extends JCTree.Visitor {
78 protected static final Context.Key<Attr> attrKey =
79 new Context.Key<Attr>();
81 final Names names;
82 final Log log;
83 final Symtab syms;
84 final Resolve rs;
85 final Infer infer;
86 final DeferredAttr deferredAttr;
87 final Check chk;
88 final Flow flow;
89 final MemberEnter memberEnter;
90 final TreeMaker make;
91 final ConstFold cfolder;
92 final Enter enter;
93 final Target target;
94 final Types types;
95 final JCDiagnostic.Factory diags;
96 final Annotate annotate;
97 final DeferredLintHandler deferredLintHandler;
99 public static Attr instance(Context context) {
100 Attr instance = context.get(attrKey);
101 if (instance == null)
102 instance = new Attr(context);
103 return instance;
104 }
106 protected Attr(Context context) {
107 context.put(attrKey, this);
109 names = Names.instance(context);
110 log = Log.instance(context);
111 syms = Symtab.instance(context);
112 rs = Resolve.instance(context);
113 chk = Check.instance(context);
114 flow = Flow.instance(context);
115 memberEnter = MemberEnter.instance(context);
116 make = TreeMaker.instance(context);
117 enter = Enter.instance(context);
118 infer = Infer.instance(context);
119 deferredAttr = DeferredAttr.instance(context);
120 cfolder = ConstFold.instance(context);
121 target = Target.instance(context);
122 types = Types.instance(context);
123 diags = JCDiagnostic.Factory.instance(context);
124 annotate = Annotate.instance(context);
125 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 allowLambda = source.allowLambda();
139 allowDefaultMethods = source.allowDefaultMethods();
140 sourceName = source.name;
141 relax = (options.isSet("-retrofit") ||
142 options.isSet("-relax"));
143 findDiamonds = options.get("findDiamond") != null &&
144 source.allowDiamond();
145 useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
146 identifyLambdaCandidate = options.getBoolean("identifyLambdaCandidate", false);
148 statInfo = new ResultInfo(NIL, Type.noType);
149 varInfo = new ResultInfo(VAR, Type.noType);
150 unknownExprInfo = new ResultInfo(VAL, Type.noType);
151 unknownTypeInfo = new ResultInfo(TYP, Type.noType);
152 recoveryInfo = new RecoveryInfo(deferredAttr.emptyDeferredAttrContext);
153 }
155 /** Switch: relax some constraints for retrofit mode.
156 */
157 boolean relax;
159 /** Switch: support target-typing inference
160 */
161 boolean allowPoly;
163 /** Switch: support generics?
164 */
165 boolean allowGenerics;
167 /** Switch: allow variable-arity methods.
168 */
169 boolean allowVarargs;
171 /** Switch: support enums?
172 */
173 boolean allowEnums;
175 /** Switch: support boxing and unboxing?
176 */
177 boolean allowBoxing;
179 /** Switch: support covariant result types?
180 */
181 boolean allowCovariantReturns;
183 /** Switch: support lambda expressions ?
184 */
185 boolean allowLambda;
187 /** Switch: support default methods ?
188 */
189 boolean allowDefaultMethods;
191 /** Switch: allow references to surrounding object from anonymous
192 * objects during constructor call?
193 */
194 boolean allowAnonOuterThis;
196 /** Switch: generates a warning if diamond can be safely applied
197 * to a given new expression
198 */
199 boolean findDiamonds;
201 /**
202 * Internally enables/disables diamond finder feature
203 */
204 static final boolean allowDiamondFinder = true;
206 /**
207 * Switch: warn about use of variable before declaration?
208 * RFE: 6425594
209 */
210 boolean useBeforeDeclarationWarning;
212 /**
213 * Switch: generate warnings whenever an anonymous inner class that is convertible
214 * to a lambda expression is found
215 */
216 boolean identifyLambdaCandidate;
218 /**
219 * Switch: allow strings in switch?
220 */
221 boolean allowStringsInSwitch;
223 /**
224 * Switch: name of source level; used for error reporting.
225 */
226 String sourceName;
228 /** Check kind and type of given tree against protokind and prototype.
229 * If check succeeds, store type in tree and return it.
230 * If check fails, store errType in tree and return it.
231 * No checks are performed if the prototype is a method type.
232 * It is not necessary in this case since we know that kind and type
233 * are correct.
234 *
235 * @param tree The tree whose kind and type is checked
236 * @param ownkind The computed kind of the tree
237 * @param resultInfo The expected result of the tree
238 */
239 Type check(final JCTree tree, final Type found, final int ownkind, final ResultInfo resultInfo) {
240 InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
241 Type owntype = found;
242 if (!owntype.hasTag(ERROR) && !resultInfo.pt.hasTag(METHOD) && !resultInfo.pt.hasTag(FORALL)) {
243 if (inferenceContext.free(found)) {
244 inferenceContext.addFreeTypeListener(List.of(found, resultInfo.pt), new FreeTypeListener() {
245 @Override
246 public void typesInferred(InferenceContext inferenceContext) {
247 ResultInfo pendingResult =
248 resultInfo.dup(inferenceContext.asInstType(resultInfo.pt, types));
249 check(tree, inferenceContext.asInstType(found, types), ownkind, pendingResult);
250 }
251 });
252 return tree.type = resultInfo.pt;
253 } else {
254 if ((ownkind & ~resultInfo.pkind) == 0) {
255 owntype = resultInfo.check(tree, owntype);
256 } else {
257 log.error(tree.pos(), "unexpected.type",
258 kindNames(resultInfo.pkind),
259 kindName(ownkind));
260 owntype = types.createErrorType(owntype);
261 }
262 }
263 }
264 tree.type = owntype;
265 return owntype;
266 }
268 /** Is given blank final variable assignable, i.e. in a scope where it
269 * may be assigned to even though it is final?
270 * @param v The blank final variable.
271 * @param env The current environment.
272 */
273 boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
274 Symbol owner = owner(env);
275 // owner refers to the innermost variable, method or
276 // initializer block declaration at this point.
277 return
278 v.owner == owner
279 ||
280 ((owner.name == names.init || // i.e. we are in a constructor
281 owner.kind == VAR || // i.e. we are in a variable initializer
282 (owner.flags() & BLOCK) != 0) // i.e. we are in an initializer block
283 &&
284 v.owner == owner.owner
285 &&
286 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
287 }
289 /**
290 * Return the innermost enclosing owner symbol in a given attribution context
291 */
292 Symbol owner(Env<AttrContext> env) {
293 while (true) {
294 switch (env.tree.getTag()) {
295 case VARDEF:
296 //a field can be owner
297 VarSymbol vsym = ((JCVariableDecl)env.tree).sym;
298 if (vsym.owner.kind == TYP) {
299 return vsym;
300 }
301 break;
302 case METHODDEF:
303 //method def is always an owner
304 return ((JCMethodDecl)env.tree).sym;
305 case CLASSDEF:
306 //class def is always an owner
307 return ((JCClassDecl)env.tree).sym;
308 case LAMBDA:
309 //a lambda is an owner - return a fresh synthetic method symbol
310 return new MethodSymbol(0, names.empty, null, syms.methodClass);
311 case BLOCK:
312 //static/instance init blocks are owner
313 Symbol blockSym = env.info.scope.owner;
314 if ((blockSym.flags() & BLOCK) != 0) {
315 return blockSym;
316 }
317 break;
318 case TOPLEVEL:
319 //toplevel is always an owner (for pkge decls)
320 return env.info.scope.owner;
321 }
322 Assert.checkNonNull(env.next);
323 env = env.next;
324 }
325 }
327 /** Check that variable can be assigned to.
328 * @param pos The current source code position.
329 * @param v The assigned varaible
330 * @param base If the variable is referred to in a Select, the part
331 * to the left of the `.', null otherwise.
332 * @param env The current environment.
333 */
334 void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
335 if ((v.flags() & FINAL) != 0 &&
336 ((v.flags() & HASINIT) != 0
337 ||
338 !((base == null ||
339 (base.hasTag(IDENT) && TreeInfo.name(base) == names._this)) &&
340 isAssignableAsBlankFinal(v, env)))) {
341 if (v.isResourceVariable()) { //TWR resource
342 log.error(pos, "try.resource.may.not.be.assigned", v);
343 } else {
344 log.error(pos, "cant.assign.val.to.final.var", v);
345 }
346 }
347 }
349 /** Does tree represent a static reference to an identifier?
350 * It is assumed that tree is either a SELECT or an IDENT.
351 * We have to weed out selects from non-type names here.
352 * @param tree The candidate tree.
353 */
354 boolean isStaticReference(JCTree tree) {
355 if (tree.hasTag(SELECT)) {
356 Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
357 if (lsym == null || lsym.kind != TYP) {
358 return false;
359 }
360 }
361 return true;
362 }
364 /** Is this symbol a type?
365 */
366 static boolean isType(Symbol sym) {
367 return sym != null && sym.kind == TYP;
368 }
370 /** The current `this' symbol.
371 * @param env The current environment.
372 */
373 Symbol thisSym(DiagnosticPosition pos, Env<AttrContext> env) {
374 return rs.resolveSelf(pos, env, env.enclClass.sym, names._this);
375 }
377 /** Attribute a parsed identifier.
378 * @param tree Parsed identifier name
379 * @param topLevel The toplevel to use
380 */
381 public Symbol attribIdent(JCTree tree, JCCompilationUnit topLevel) {
382 Env<AttrContext> localEnv = enter.topLevelEnv(topLevel);
383 localEnv.enclClass = make.ClassDef(make.Modifiers(0),
384 syms.errSymbol.name,
385 null, null, null, null);
386 localEnv.enclClass.sym = syms.errSymbol;
387 return tree.accept(identAttributer, localEnv);
388 }
389 // where
390 private TreeVisitor<Symbol,Env<AttrContext>> identAttributer = new IdentAttributer();
391 private class IdentAttributer extends SimpleTreeVisitor<Symbol,Env<AttrContext>> {
392 @Override
393 public Symbol visitMemberSelect(MemberSelectTree node, Env<AttrContext> env) {
394 Symbol site = visit(node.getExpression(), env);
395 if (site.kind == ERR)
396 return site;
397 Name name = (Name)node.getIdentifier();
398 if (site.kind == PCK) {
399 env.toplevel.packge = (PackageSymbol)site;
400 return rs.findIdentInPackage(env, (TypeSymbol)site, name, TYP | PCK);
401 } else {
402 env.enclClass.sym = (ClassSymbol)site;
403 return rs.findMemberType(env, site.asType(), name, (TypeSymbol)site);
404 }
405 }
407 @Override
408 public Symbol visitIdentifier(IdentifierTree node, Env<AttrContext> env) {
409 return rs.findIdent(env, (Name)node.getName(), TYP | PCK);
410 }
411 }
413 public Type coerce(Type etype, Type ttype) {
414 return cfolder.coerce(etype, ttype);
415 }
417 public Type attribType(JCTree node, TypeSymbol sym) {
418 Env<AttrContext> env = enter.typeEnvs.get(sym);
419 Env<AttrContext> localEnv = env.dup(node, env.info.dup());
420 return attribTree(node, localEnv, unknownTypeInfo);
421 }
423 public Type attribImportQualifier(JCImport tree, Env<AttrContext> env) {
424 // Attribute qualifying package or class.
425 JCFieldAccess s = (JCFieldAccess)tree.qualid;
426 return attribTree(s.selected,
427 env,
428 new ResultInfo(tree.staticImport ? TYP : (TYP | PCK),
429 Type.noType));
430 }
432 public Env<AttrContext> attribExprToTree(JCTree expr, Env<AttrContext> env, JCTree tree) {
433 breakTree = tree;
434 JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
435 try {
436 attribExpr(expr, env);
437 } catch (BreakAttr b) {
438 return b.env;
439 } catch (AssertionError ae) {
440 if (ae.getCause() instanceof BreakAttr) {
441 return ((BreakAttr)(ae.getCause())).env;
442 } else {
443 throw ae;
444 }
445 } finally {
446 breakTree = null;
447 log.useSource(prev);
448 }
449 return env;
450 }
452 public Env<AttrContext> attribStatToTree(JCTree stmt, Env<AttrContext> env, JCTree tree) {
453 breakTree = tree;
454 JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
455 try {
456 attribStat(stmt, env);
457 } catch (BreakAttr b) {
458 return b.env;
459 } catch (AssertionError ae) {
460 if (ae.getCause() instanceof BreakAttr) {
461 return ((BreakAttr)(ae.getCause())).env;
462 } else {
463 throw ae;
464 }
465 } finally {
466 breakTree = null;
467 log.useSource(prev);
468 }
469 return env;
470 }
472 private JCTree breakTree = null;
474 private static class BreakAttr extends RuntimeException {
475 static final long serialVersionUID = -6924771130405446405L;
476 private Env<AttrContext> env;
477 private BreakAttr(Env<AttrContext> env) {
478 this.env = copyEnv(env);
479 }
481 private Env<AttrContext> copyEnv(Env<AttrContext> env) {
482 Env<AttrContext> newEnv =
483 env.dup(env.tree, env.info.dup(copyScope(env.info.scope)));
484 if (newEnv.outer != null) {
485 newEnv.outer = copyEnv(newEnv.outer);
486 }
487 return newEnv;
488 }
490 private Scope copyScope(Scope sc) {
491 Scope newScope = new Scope(sc.owner);
492 List<Symbol> elemsList = List.nil();
493 while (sc != null) {
494 for (Scope.Entry e = sc.elems ; e != null ; e = e.sibling) {
495 elemsList = elemsList.prepend(e.sym);
496 }
497 sc = sc.next;
498 }
499 for (Symbol s : elemsList) {
500 newScope.enter(s);
501 }
502 return newScope;
503 }
504 }
506 class ResultInfo {
507 final int pkind;
508 final Type pt;
509 final CheckContext checkContext;
511 ResultInfo(int pkind, Type pt) {
512 this(pkind, pt, chk.basicHandler);
513 }
515 protected ResultInfo(int pkind, Type pt, CheckContext checkContext) {
516 this.pkind = pkind;
517 this.pt = pt;
518 this.checkContext = checkContext;
519 }
521 protected Type check(final DiagnosticPosition pos, final Type found) {
522 return chk.checkType(pos, found, pt, checkContext);
523 }
525 protected ResultInfo dup(Type newPt) {
526 return new ResultInfo(pkind, newPt, checkContext);
527 }
529 protected ResultInfo dup(CheckContext newContext) {
530 return new ResultInfo(pkind, pt, newContext);
531 }
532 }
534 class RecoveryInfo extends ResultInfo {
536 public RecoveryInfo(final DeferredAttr.DeferredAttrContext deferredAttrContext) {
537 super(Kinds.VAL, Type.recoveryType, new Check.NestedCheckContext(chk.basicHandler) {
538 @Override
539 public DeferredAttr.DeferredAttrContext deferredAttrContext() {
540 return deferredAttrContext;
541 }
542 @Override
543 public boolean compatible(Type found, Type req, Warner warn) {
544 return true;
545 }
546 @Override
547 public void report(DiagnosticPosition pos, JCDiagnostic details) {
548 chk.basicHandler.report(pos, details);
549 }
550 });
551 }
553 @Override
554 protected Type check(DiagnosticPosition pos, Type found) {
555 return chk.checkNonVoid(pos, super.check(pos, found));
556 }
557 }
559 final ResultInfo statInfo;
560 final ResultInfo varInfo;
561 final ResultInfo unknownExprInfo;
562 final ResultInfo unknownTypeInfo;
563 final ResultInfo recoveryInfo;
565 Type pt() {
566 return resultInfo.pt;
567 }
569 int pkind() {
570 return resultInfo.pkind;
571 }
573 /* ************************************************************************
574 * Visitor methods
575 *************************************************************************/
577 /** Visitor argument: the current environment.
578 */
579 Env<AttrContext> env;
581 /** Visitor argument: the currently expected attribution result.
582 */
583 ResultInfo resultInfo;
585 /** Visitor result: the computed type.
586 */
587 Type result;
589 /** Visitor method: attribute a tree, catching any completion failure
590 * exceptions. Return the tree's type.
591 *
592 * @param tree The tree to be visited.
593 * @param env The environment visitor argument.
594 * @param resultInfo The result info visitor argument.
595 */
596 Type attribTree(JCTree tree, Env<AttrContext> env, ResultInfo resultInfo) {
597 Env<AttrContext> prevEnv = this.env;
598 ResultInfo prevResult = this.resultInfo;
599 try {
600 this.env = env;
601 this.resultInfo = resultInfo;
602 tree.accept(this);
603 if (tree == breakTree &&
604 resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
605 throw new BreakAttr(env);
606 }
607 return result;
608 } catch (CompletionFailure ex) {
609 tree.type = syms.errType;
610 return chk.completionError(tree.pos(), ex);
611 } finally {
612 this.env = prevEnv;
613 this.resultInfo = prevResult;
614 }
615 }
617 /** Derived visitor method: attribute an expression tree.
618 */
619 public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) {
620 return attribTree(tree, env, new ResultInfo(VAL, !pt.hasTag(ERROR) ? pt : Type.noType));
621 }
623 /** Derived visitor method: attribute an expression tree with
624 * no constraints on the computed type.
625 */
626 public Type attribExpr(JCTree tree, Env<AttrContext> env) {
627 return attribTree(tree, env, unknownExprInfo);
628 }
630 /** Derived visitor method: attribute a type tree.
631 */
632 public Type attribType(JCTree tree, Env<AttrContext> env) {
633 Type result = attribType(tree, env, Type.noType);
634 return result;
635 }
637 /** Derived visitor method: attribute a type tree.
638 */
639 Type attribType(JCTree tree, Env<AttrContext> env, Type pt) {
640 Type result = attribTree(tree, env, new ResultInfo(TYP, pt));
641 return result;
642 }
644 /** Derived visitor method: attribute a statement or definition tree.
645 */
646 public Type attribStat(JCTree tree, Env<AttrContext> env) {
647 return attribTree(tree, env, statInfo);
648 }
650 /** Attribute a list of expressions, returning a list of types.
651 */
652 List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) {
653 ListBuffer<Type> ts = new ListBuffer<Type>();
654 for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
655 ts.append(attribExpr(l.head, env, pt));
656 return ts.toList();
657 }
659 /** Attribute a list of statements, returning nothing.
660 */
661 <T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) {
662 for (List<T> l = trees; l.nonEmpty(); l = l.tail)
663 attribStat(l.head, env);
664 }
666 /** Attribute the arguments in a method call, returning a list of types.
667 */
668 List<Type> attribArgs(List<JCExpression> trees, Env<AttrContext> env) {
669 ListBuffer<Type> argtypes = new ListBuffer<Type>();
670 for (JCExpression arg : trees) {
671 Type argtype = allowPoly && TreeInfo.isPoly(arg, env.tree) ?
672 deferredAttr.new DeferredType(arg, env) :
673 chk.checkNonVoid(arg, attribExpr(arg, env, Infer.anyPoly));
674 argtypes.append(argtype);
675 }
676 return argtypes.toList();
677 }
679 /** Attribute a type argument list, returning a list of types.
680 * Caller is responsible for calling checkRefTypes.
681 */
682 List<Type> attribAnyTypes(List<JCExpression> trees, Env<AttrContext> env) {
683 ListBuffer<Type> argtypes = new ListBuffer<Type>();
684 for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
685 argtypes.append(attribType(l.head, env));
686 return argtypes.toList();
687 }
689 /** Attribute a type argument list, returning a list of types.
690 * Check that all the types are references.
691 */
692 List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
693 List<Type> types = attribAnyTypes(trees, env);
694 return chk.checkRefTypes(trees, types);
695 }
697 /**
698 * Attribute type variables (of generic classes or methods).
699 * Compound types are attributed later in attribBounds.
700 * @param typarams the type variables to enter
701 * @param env the current environment
702 */
703 void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env) {
704 for (JCTypeParameter tvar : typarams) {
705 TypeVar a = (TypeVar)tvar.type;
706 a.tsym.flags_field |= UNATTRIBUTED;
707 a.bound = Type.noType;
708 if (!tvar.bounds.isEmpty()) {
709 List<Type> bounds = List.of(attribType(tvar.bounds.head, env));
710 for (JCExpression bound : tvar.bounds.tail)
711 bounds = bounds.prepend(attribType(bound, env));
712 types.setBounds(a, bounds.reverse());
713 } else {
714 // if no bounds are given, assume a single bound of
715 // java.lang.Object.
716 types.setBounds(a, List.of(syms.objectType));
717 }
718 a.tsym.flags_field &= ~UNATTRIBUTED;
719 }
720 for (JCTypeParameter tvar : typarams) {
721 chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
722 }
723 }
725 /**
726 * Attribute the type references in a list of annotations.
727 */
728 void attribAnnotationTypes(List<JCAnnotation> annotations,
729 Env<AttrContext> env) {
730 for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
731 JCAnnotation a = al.head;
732 attribType(a.annotationType, env);
733 }
734 }
736 /**
737 * Attribute a "lazy constant value".
738 * @param env The env for the const value
739 * @param initializer The initializer for the const value
740 * @param type The expected type, or null
741 * @see VarSymbol#setLazyConstValue
742 */
743 public Object attribLazyConstantValue(Env<AttrContext> env,
744 JCTree.JCExpression initializer,
745 Type type) {
747 // in case no lint value has been set up for this env, scan up
748 // env stack looking for smallest enclosing env for which it is set.
749 Env<AttrContext> lintEnv = env;
750 while (lintEnv.info.lint == null)
751 lintEnv = lintEnv.next;
753 // Having found the enclosing lint value, we can initialize the lint value for this class
754 // ... but ...
755 // There's a problem with evaluating annotations in the right order, such that
756 // env.info.enclVar.attributes_field might not yet have been evaluated, and so might be
757 // null. In that case, calling augment will throw an NPE. To avoid this, for now we
758 // revert to the jdk 6 behavior and ignore the (unevaluated) attributes.
759 if (env.info.enclVar.annotations.pendingCompletion()) {
760 env.info.lint = lintEnv.info.lint;
761 } else {
762 env.info.lint = lintEnv.info.lint.augment(env.info.enclVar.annotations,
763 env.info.enclVar.flags());
764 }
766 Lint prevLint = chk.setLint(env.info.lint);
767 JavaFileObject prevSource = log.useSource(env.toplevel.sourcefile);
769 try {
770 Type itype = attribExpr(initializer, env, type);
771 if (itype.constValue() != null)
772 return coerce(itype, type).constValue();
773 else
774 return null;
775 } finally {
776 env.info.lint = prevLint;
777 log.useSource(prevSource);
778 }
779 }
781 /** Attribute type reference in an `extends' or `implements' clause.
782 * Supertypes of anonymous inner classes are usually already attributed.
783 *
784 * @param tree The tree making up the type reference.
785 * @param env The environment current at the reference.
786 * @param classExpected true if only a class is expected here.
787 * @param interfaceExpected true if only an interface is expected here.
788 */
789 Type attribBase(JCTree tree,
790 Env<AttrContext> env,
791 boolean classExpected,
792 boolean interfaceExpected,
793 boolean checkExtensible) {
794 Type t = tree.type != null ?
795 tree.type :
796 attribType(tree, env);
797 return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible);
798 }
799 Type checkBase(Type t,
800 JCTree tree,
801 Env<AttrContext> env,
802 boolean classExpected,
803 boolean interfaceExpected,
804 boolean checkExtensible) {
805 if (t.isErroneous())
806 return t;
807 if (t.hasTag(TYPEVAR) && !classExpected && !interfaceExpected) {
808 // check that type variable is already visible
809 if (t.getUpperBound() == null) {
810 log.error(tree.pos(), "illegal.forward.ref");
811 return types.createErrorType(t);
812 }
813 } else {
814 t = chk.checkClassType(tree.pos(), t, checkExtensible|!allowGenerics);
815 }
816 if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) {
817 log.error(tree.pos(), "intf.expected.here");
818 // return errType is necessary since otherwise there might
819 // be undetected cycles which cause attribution to loop
820 return types.createErrorType(t);
821 } else if (checkExtensible &&
822 classExpected &&
823 (t.tsym.flags() & INTERFACE) != 0) {
824 log.error(tree.pos(), "no.intf.expected.here");
825 return types.createErrorType(t);
826 }
827 if (checkExtensible &&
828 ((t.tsym.flags() & FINAL) != 0)) {
829 log.error(tree.pos(),
830 "cant.inherit.from.final", t.tsym);
831 }
832 chk.checkNonCyclic(tree.pos(), t);
833 return t;
834 }
836 Type attribIdentAsEnumType(Env<AttrContext> env, JCIdent id) {
837 Assert.check((env.enclClass.sym.flags() & ENUM) != 0);
838 id.type = env.info.scope.owner.type;
839 id.sym = env.info.scope.owner;
840 return id.type;
841 }
843 public void visitClassDef(JCClassDecl tree) {
844 // Local classes have not been entered yet, so we need to do it now:
845 if ((env.info.scope.owner.kind & (VAR | MTH)) != 0)
846 enter.classEnter(tree, env);
848 ClassSymbol c = tree.sym;
849 if (c == null) {
850 // exit in case something drastic went wrong during enter.
851 result = null;
852 } else {
853 // make sure class has been completed:
854 c.complete();
856 // If this class appears as an anonymous class
857 // in a superclass constructor call where
858 // no explicit outer instance is given,
859 // disable implicit outer instance from being passed.
860 // (This would be an illegal access to "this before super").
861 if (env.info.isSelfCall &&
862 env.tree.hasTag(NEWCLASS) &&
863 ((JCNewClass) env.tree).encl == null)
864 {
865 c.flags_field |= NOOUTERTHIS;
866 }
867 attribClass(tree.pos(), c);
868 result = tree.type = c.type;
869 }
870 }
872 public void visitMethodDef(JCMethodDecl tree) {
873 MethodSymbol m = tree.sym;
874 boolean isDefaultMethod = (m.flags() & DEFAULT) != 0;
876 Lint lint = env.info.lint.augment(m.annotations, m.flags());
877 Lint prevLint = chk.setLint(lint);
878 MethodSymbol prevMethod = chk.setMethod(m);
879 try {
880 deferredLintHandler.flush(tree.pos());
881 chk.checkDeprecatedAnnotation(tree.pos(), m);
883 // Create a new environment with local scope
884 // for attributing the method.
885 Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
886 localEnv.info.lint = lint;
888 attribStats(tree.typarams, localEnv);
890 // If we override any other methods, check that we do so properly.
891 // JLS ???
892 if (m.isStatic()) {
893 chk.checkHideClashes(tree.pos(), env.enclClass.type, m);
894 } else {
895 chk.checkOverrideClashes(tree.pos(), env.enclClass.type, m);
896 }
897 chk.checkOverride(tree, m);
899 if (isDefaultMethod && types.overridesObjectMethod(m.enclClass(), m)) {
900 log.error(tree, "default.overrides.object.member", m.name, Kinds.kindName(m.location()), m.location());
901 }
903 // Enter all type parameters into the local method scope.
904 for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
905 localEnv.info.scope.enterIfAbsent(l.head.type.tsym);
907 ClassSymbol owner = env.enclClass.sym;
908 if ((owner.flags() & ANNOTATION) != 0 &&
909 tree.params.nonEmpty())
910 log.error(tree.params.head.pos(),
911 "intf.annotation.members.cant.have.params");
913 // Attribute all value parameters.
914 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
915 attribStat(l.head, localEnv);
916 }
918 chk.checkVarargsMethodDecl(localEnv, tree);
920 // Check that type parameters are well-formed.
921 chk.validate(tree.typarams, localEnv);
923 // Check that result type is well-formed.
924 chk.validate(tree.restype, localEnv);
926 // annotation method checks
927 if ((owner.flags() & ANNOTATION) != 0) {
928 // annotation method cannot have throws clause
929 if (tree.thrown.nonEmpty()) {
930 log.error(tree.thrown.head.pos(),
931 "throws.not.allowed.in.intf.annotation");
932 }
933 // annotation method cannot declare type-parameters
934 if (tree.typarams.nonEmpty()) {
935 log.error(tree.typarams.head.pos(),
936 "intf.annotation.members.cant.have.type.params");
937 }
938 // validate annotation method's return type (could be an annotation type)
939 chk.validateAnnotationType(tree.restype);
940 // ensure that annotation method does not clash with members of Object/Annotation
941 chk.validateAnnotationMethod(tree.pos(), m);
943 if (tree.defaultValue != null) {
944 // if default value is an annotation, check it is a well-formed
945 // annotation value (e.g. no duplicate values, no missing values, etc.)
946 chk.validateAnnotationTree(tree.defaultValue);
947 }
948 }
950 for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
951 chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
953 if (tree.body == null) {
954 // Empty bodies are only allowed for
955 // abstract, native, or interface methods, or for methods
956 // in a retrofit signature class.
957 if (isDefaultMethod || ((owner.flags() & INTERFACE) == 0 &&
958 (tree.mods.flags & (ABSTRACT | NATIVE)) == 0) &&
959 !relax)
960 log.error(tree.pos(), "missing.meth.body.or.decl.abstract");
961 if (tree.defaultValue != null) {
962 if ((owner.flags() & ANNOTATION) == 0)
963 log.error(tree.pos(),
964 "default.allowed.in.intf.annotation.member");
965 }
966 } else if ((tree.sym.flags() & ABSTRACT) != 0 && !isDefaultMethod) {
967 if ((owner.flags() & INTERFACE) != 0) {
968 log.error(tree.body.pos(), "intf.meth.cant.have.body");
969 } else {
970 log.error(tree.pos(), "abstract.meth.cant.have.body");
971 }
972 } else if ((tree.mods.flags & NATIVE) != 0) {
973 log.error(tree.pos(), "native.meth.cant.have.body");
974 } else {
975 // Add an implicit super() call unless an explicit call to
976 // super(...) or this(...) is given
977 // or we are compiling class java.lang.Object.
978 if (tree.name == names.init && owner.type != syms.objectType) {
979 JCBlock body = tree.body;
980 if (body.stats.isEmpty() ||
981 !TreeInfo.isSelfCall(body.stats.head)) {
982 body.stats = body.stats.
983 prepend(memberEnter.SuperCall(make.at(body.pos),
984 List.<Type>nil(),
985 List.<JCVariableDecl>nil(),
986 false));
987 } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
988 (tree.mods.flags & GENERATEDCONSTR) == 0 &&
989 TreeInfo.isSuperCall(body.stats.head)) {
990 // enum constructors are not allowed to call super
991 // directly, so make sure there aren't any super calls
992 // in enum constructors, except in the compiler
993 // generated one.
994 log.error(tree.body.stats.head.pos(),
995 "call.to.super.not.allowed.in.enum.ctor",
996 env.enclClass.sym);
997 }
998 }
1000 // Attribute method body.
1001 attribStat(tree.body, localEnv);
1002 }
1003 localEnv.info.scope.leave();
1004 result = tree.type = m.type;
1005 chk.validateAnnotations(tree.mods.annotations, m);
1006 }
1007 finally {
1008 chk.setLint(prevLint);
1009 chk.setMethod(prevMethod);
1010 }
1011 }
1013 public void visitVarDef(JCVariableDecl tree) {
1014 // Local variables have not been entered yet, so we need to do it now:
1015 if (env.info.scope.owner.kind == MTH) {
1016 if (tree.sym != null) {
1017 // parameters have already been entered
1018 env.info.scope.enter(tree.sym);
1019 } else {
1020 memberEnter.memberEnter(tree, env);
1021 annotate.flush();
1022 }
1023 }
1025 VarSymbol v = tree.sym;
1026 Lint lint = env.info.lint.augment(v.annotations, v.flags());
1027 Lint prevLint = chk.setLint(lint);
1029 // Check that the variable's declared type is well-formed.
1030 chk.validate(tree.vartype, env);
1031 deferredLintHandler.flush(tree.pos());
1033 try {
1034 chk.checkDeprecatedAnnotation(tree.pos(), v);
1036 if (tree.init != null) {
1037 if ((v.flags_field & FINAL) != 0 &&
1038 !tree.init.hasTag(NEWCLASS) &&
1039 !tree.init.hasTag(LAMBDA) &&
1040 !tree.init.hasTag(REFERENCE)) {
1041 // In this case, `v' is final. Ensure that it's initializer is
1042 // evaluated.
1043 v.getConstValue(); // ensure initializer is evaluated
1044 } else {
1045 // Attribute initializer in a new environment
1046 // with the declared variable as owner.
1047 // Check that initializer conforms to variable's declared type.
1048 Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
1049 initEnv.info.lint = lint;
1050 // In order to catch self-references, we set the variable's
1051 // declaration position to maximal possible value, effectively
1052 // marking the variable as undefined.
1053 initEnv.info.enclVar = v;
1054 attribExpr(tree.init, initEnv, v.type);
1055 }
1056 }
1057 result = tree.type = v.type;
1058 chk.validateAnnotations(tree.mods.annotations, v);
1059 }
1060 finally {
1061 chk.setLint(prevLint);
1062 }
1063 }
1065 public void visitSkip(JCSkip tree) {
1066 result = null;
1067 }
1069 public void visitBlock(JCBlock tree) {
1070 if (env.info.scope.owner.kind == TYP) {
1071 // Block is a static or instance initializer;
1072 // let the owner of the environment be a freshly
1073 // created BLOCK-method.
1074 Env<AttrContext> localEnv =
1075 env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
1076 localEnv.info.scope.owner =
1077 new MethodSymbol(tree.flags | BLOCK, names.empty, null,
1078 env.info.scope.owner);
1079 if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
1080 attribStats(tree.stats, localEnv);
1081 } else {
1082 // Create a new local environment with a local scope.
1083 Env<AttrContext> localEnv =
1084 env.dup(tree, env.info.dup(env.info.scope.dup()));
1085 try {
1086 attribStats(tree.stats, localEnv);
1087 } finally {
1088 localEnv.info.scope.leave();
1089 }
1090 }
1091 result = null;
1092 }
1094 public void visitDoLoop(JCDoWhileLoop tree) {
1095 attribStat(tree.body, env.dup(tree));
1096 attribExpr(tree.cond, env, syms.booleanType);
1097 result = null;
1098 }
1100 public void visitWhileLoop(JCWhileLoop tree) {
1101 attribExpr(tree.cond, env, syms.booleanType);
1102 attribStat(tree.body, env.dup(tree));
1103 result = null;
1104 }
1106 public void visitForLoop(JCForLoop tree) {
1107 Env<AttrContext> loopEnv =
1108 env.dup(env.tree, env.info.dup(env.info.scope.dup()));
1109 try {
1110 attribStats(tree.init, loopEnv);
1111 if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType);
1112 loopEnv.tree = tree; // before, we were not in loop!
1113 attribStats(tree.step, loopEnv);
1114 attribStat(tree.body, loopEnv);
1115 result = null;
1116 }
1117 finally {
1118 loopEnv.info.scope.leave();
1119 }
1120 }
1122 public void visitForeachLoop(JCEnhancedForLoop tree) {
1123 Env<AttrContext> loopEnv =
1124 env.dup(env.tree, env.info.dup(env.info.scope.dup()));
1125 try {
1126 attribStat(tree.var, loopEnv);
1127 Type exprType = types.upperBound(attribExpr(tree.expr, loopEnv));
1128 chk.checkNonVoid(tree.pos(), exprType);
1129 Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
1130 if (elemtype == null) {
1131 // or perhaps expr implements Iterable<T>?
1132 Type base = types.asSuper(exprType, syms.iterableType.tsym);
1133 if (base == null) {
1134 log.error(tree.expr.pos(),
1135 "foreach.not.applicable.to.type",
1136 exprType,
1137 diags.fragment("type.req.array.or.iterable"));
1138 elemtype = types.createErrorType(exprType);
1139 } else {
1140 List<Type> iterableParams = base.allparams();
1141 elemtype = iterableParams.isEmpty()
1142 ? syms.objectType
1143 : types.upperBound(iterableParams.head);
1144 }
1145 }
1146 chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
1147 loopEnv.tree = tree; // before, we were not in loop!
1148 attribStat(tree.body, loopEnv);
1149 result = null;
1150 }
1151 finally {
1152 loopEnv.info.scope.leave();
1153 }
1154 }
1156 public void visitLabelled(JCLabeledStatement tree) {
1157 // Check that label is not used in an enclosing statement
1158 Env<AttrContext> env1 = env;
1159 while (env1 != null && !env1.tree.hasTag(CLASSDEF)) {
1160 if (env1.tree.hasTag(LABELLED) &&
1161 ((JCLabeledStatement) env1.tree).label == tree.label) {
1162 log.error(tree.pos(), "label.already.in.use",
1163 tree.label);
1164 break;
1165 }
1166 env1 = env1.next;
1167 }
1169 attribStat(tree.body, env.dup(tree));
1170 result = null;
1171 }
1173 public void visitSwitch(JCSwitch tree) {
1174 Type seltype = attribExpr(tree.selector, env);
1176 Env<AttrContext> switchEnv =
1177 env.dup(tree, env.info.dup(env.info.scope.dup()));
1179 try {
1181 boolean enumSwitch =
1182 allowEnums &&
1183 (seltype.tsym.flags() & Flags.ENUM) != 0;
1184 boolean stringSwitch = false;
1185 if (types.isSameType(seltype, syms.stringType)) {
1186 if (allowStringsInSwitch) {
1187 stringSwitch = true;
1188 } else {
1189 log.error(tree.selector.pos(), "string.switch.not.supported.in.source", sourceName);
1190 }
1191 }
1192 if (!enumSwitch && !stringSwitch)
1193 seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType);
1195 // Attribute all cases and
1196 // check that there are no duplicate case labels or default clauses.
1197 Set<Object> labels = new HashSet<Object>(); // The set of case labels.
1198 boolean hasDefault = false; // Is there a default label?
1199 for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
1200 JCCase c = l.head;
1201 Env<AttrContext> caseEnv =
1202 switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup()));
1203 try {
1204 if (c.pat != null) {
1205 if (enumSwitch) {
1206 Symbol sym = enumConstant(c.pat, seltype);
1207 if (sym == null) {
1208 log.error(c.pat.pos(), "enum.label.must.be.unqualified.enum");
1209 } else if (!labels.add(sym)) {
1210 log.error(c.pos(), "duplicate.case.label");
1211 }
1212 } else {
1213 Type pattype = attribExpr(c.pat, switchEnv, seltype);
1214 if (!pattype.hasTag(ERROR)) {
1215 if (pattype.constValue() == null) {
1216 log.error(c.pat.pos(),
1217 (stringSwitch ? "string.const.req" : "const.expr.req"));
1218 } else if (labels.contains(pattype.constValue())) {
1219 log.error(c.pos(), "duplicate.case.label");
1220 } else {
1221 labels.add(pattype.constValue());
1222 }
1223 }
1224 }
1225 } else if (hasDefault) {
1226 log.error(c.pos(), "duplicate.default.label");
1227 } else {
1228 hasDefault = true;
1229 }
1230 attribStats(c.stats, caseEnv);
1231 } finally {
1232 caseEnv.info.scope.leave();
1233 addVars(c.stats, switchEnv.info.scope);
1234 }
1235 }
1237 result = null;
1238 }
1239 finally {
1240 switchEnv.info.scope.leave();
1241 }
1242 }
1243 // where
1244 /** Add any variables defined in stats to the switch scope. */
1245 private static void addVars(List<JCStatement> stats, Scope switchScope) {
1246 for (;stats.nonEmpty(); stats = stats.tail) {
1247 JCTree stat = stats.head;
1248 if (stat.hasTag(VARDEF))
1249 switchScope.enter(((JCVariableDecl) stat).sym);
1250 }
1251 }
1252 // where
1253 /** Return the selected enumeration constant symbol, or null. */
1254 private Symbol enumConstant(JCTree tree, Type enumType) {
1255 if (!tree.hasTag(IDENT)) {
1256 log.error(tree.pos(), "enum.label.must.be.unqualified.enum");
1257 return syms.errSymbol;
1258 }
1259 JCIdent ident = (JCIdent)tree;
1260 Name name = ident.name;
1261 for (Scope.Entry e = enumType.tsym.members().lookup(name);
1262 e.scope != null; e = e.next()) {
1263 if (e.sym.kind == VAR) {
1264 Symbol s = ident.sym = e.sym;
1265 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
1266 ident.type = s.type;
1267 return ((s.flags_field & Flags.ENUM) == 0)
1268 ? null : s;
1269 }
1270 }
1271 return null;
1272 }
1274 public void visitSynchronized(JCSynchronized tree) {
1275 chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
1276 attribStat(tree.body, env);
1277 result = null;
1278 }
1280 public void visitTry(JCTry tree) {
1281 // Create a new local environment with a local
1282 Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
1283 try {
1284 boolean isTryWithResource = tree.resources.nonEmpty();
1285 // Create a nested environment for attributing the try block if needed
1286 Env<AttrContext> tryEnv = isTryWithResource ?
1287 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
1288 localEnv;
1289 try {
1290 // Attribute resource declarations
1291 for (JCTree resource : tree.resources) {
1292 CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) {
1293 @Override
1294 public void report(DiagnosticPosition pos, JCDiagnostic details) {
1295 chk.basicHandler.report(pos, diags.fragment("try.not.applicable.to.type", details));
1296 }
1297 };
1298 ResultInfo twrResult = new ResultInfo(VAL, syms.autoCloseableType, twrContext);
1299 if (resource.hasTag(VARDEF)) {
1300 attribStat(resource, tryEnv);
1301 twrResult.check(resource, resource.type);
1303 //check that resource type cannot throw InterruptedException
1304 checkAutoCloseable(resource.pos(), localEnv, resource.type);
1306 VarSymbol var = (VarSymbol)TreeInfo.symbolFor(resource);
1307 var.setData(ElementKind.RESOURCE_VARIABLE);
1308 } else {
1309 attribTree(resource, tryEnv, twrResult);
1310 }
1311 }
1312 // Attribute body
1313 attribStat(tree.body, tryEnv);
1314 } finally {
1315 if (isTryWithResource)
1316 tryEnv.info.scope.leave();
1317 }
1319 // Attribute catch clauses
1320 for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
1321 JCCatch c = l.head;
1322 Env<AttrContext> catchEnv =
1323 localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup()));
1324 try {
1325 Type ctype = attribStat(c.param, catchEnv);
1326 if (TreeInfo.isMultiCatch(c)) {
1327 //multi-catch parameter is implicitly marked as final
1328 c.param.sym.flags_field |= FINAL | UNION;
1329 }
1330 if (c.param.sym.kind == Kinds.VAR) {
1331 c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
1332 }
1333 chk.checkType(c.param.vartype.pos(),
1334 chk.checkClassType(c.param.vartype.pos(), ctype),
1335 syms.throwableType);
1336 attribStat(c.body, catchEnv);
1337 } finally {
1338 catchEnv.info.scope.leave();
1339 }
1340 }
1342 // Attribute finalizer
1343 if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
1344 result = null;
1345 }
1346 finally {
1347 localEnv.info.scope.leave();
1348 }
1349 }
1351 void checkAutoCloseable(DiagnosticPosition pos, Env<AttrContext> env, Type resource) {
1352 if (!resource.isErroneous() &&
1353 types.asSuper(resource, syms.autoCloseableType.tsym) != null &&
1354 !types.isSameType(resource, syms.autoCloseableType)) { // Don't emit warning for AutoCloseable itself
1355 Symbol close = syms.noSymbol;
1356 Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log);
1357 try {
1358 close = rs.resolveQualifiedMethod(pos,
1359 env,
1360 resource,
1361 names.close,
1362 List.<Type>nil(),
1363 List.<Type>nil());
1364 }
1365 finally {
1366 log.popDiagnosticHandler(discardHandler);
1367 }
1368 if (close.kind == MTH &&
1369 close.overrides(syms.autoCloseableClose, resource.tsym, types, true) &&
1370 chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes()) &&
1371 env.info.lint.isEnabled(LintCategory.TRY)) {
1372 log.warning(LintCategory.TRY, pos, "try.resource.throws.interrupted.exc", resource);
1373 }
1374 }
1375 }
1377 public void visitConditional(JCConditional tree) {
1378 Type condtype = attribExpr(tree.cond, env, syms.booleanType);
1380 tree.polyKind = (!allowPoly ||
1381 pt().hasTag(NONE) && pt() != Type.recoveryType ||
1382 isBooleanOrNumeric(env, tree)) ?
1383 PolyKind.STANDALONE : PolyKind.POLY;
1385 if (tree.polyKind == PolyKind.POLY && resultInfo.pt.hasTag(VOID)) {
1386 //cannot get here (i.e. it means we are returning from void method - which is already an error)
1387 resultInfo.checkContext.report(tree, diags.fragment("conditional.target.cant.be.void"));
1388 result = tree.type = types.createErrorType(resultInfo.pt);
1389 return;
1390 }
1392 ResultInfo condInfo = tree.polyKind == PolyKind.STANDALONE ?
1393 unknownExprInfo :
1394 resultInfo.dup(new Check.NestedCheckContext(resultInfo.checkContext) {
1395 //this will use enclosing check context to check compatibility of
1396 //subexpression against target type; if we are in a method check context,
1397 //depending on whether boxing is allowed, we could have incompatibilities
1398 @Override
1399 public void report(DiagnosticPosition pos, JCDiagnostic details) {
1400 enclosingContext.report(pos, diags.fragment("incompatible.type.in.conditional", details));
1401 }
1402 });
1404 Type truetype = attribTree(tree.truepart, env, condInfo);
1405 Type falsetype = attribTree(tree.falsepart, env, condInfo);
1407 Type owntype = (tree.polyKind == PolyKind.STANDALONE) ? condType(tree, truetype, falsetype) : pt();
1408 if (condtype.constValue() != null &&
1409 truetype.constValue() != null &&
1410 falsetype.constValue() != null &&
1411 !owntype.hasTag(NONE)) {
1412 //constant folding
1413 owntype = cfolder.coerce(condtype.isTrue() ? truetype : falsetype, owntype);
1414 }
1415 result = check(tree, owntype, VAL, resultInfo);
1416 }
1417 //where
1418 private boolean isBooleanOrNumeric(Env<AttrContext> env, JCExpression tree) {
1419 switch (tree.getTag()) {
1420 case LITERAL: return ((JCLiteral)tree).typetag.isSubRangeOf(DOUBLE) ||
1421 ((JCLiteral)tree).typetag == BOOLEAN ||
1422 ((JCLiteral)tree).typetag == BOT;
1423 case LAMBDA: case REFERENCE: return false;
1424 case PARENS: return isBooleanOrNumeric(env, ((JCParens)tree).expr);
1425 case CONDEXPR:
1426 JCConditional condTree = (JCConditional)tree;
1427 return isBooleanOrNumeric(env, condTree.truepart) &&
1428 isBooleanOrNumeric(env, condTree.falsepart);
1429 case APPLY:
1430 JCMethodInvocation speculativeMethodTree =
1431 (JCMethodInvocation)deferredAttr.attribSpeculative(tree, env, unknownExprInfo);
1432 Type owntype = TreeInfo.symbol(speculativeMethodTree.meth).type.getReturnType();
1433 return types.unboxedTypeOrType(owntype).isPrimitive();
1434 case NEWCLASS:
1435 JCExpression className =
1436 removeClassParams.translate(((JCNewClass)tree).clazz);
1437 JCExpression speculativeNewClassTree =
1438 (JCExpression)deferredAttr.attribSpeculative(className, env, unknownTypeInfo);
1439 return types.unboxedTypeOrType(speculativeNewClassTree.type).isPrimitive();
1440 default:
1441 Type speculativeType = deferredAttr.attribSpeculative(tree, env, unknownExprInfo).type;
1442 speculativeType = types.unboxedTypeOrType(speculativeType);
1443 return speculativeType.isPrimitive();
1444 }
1445 }
1446 //where
1447 TreeTranslator removeClassParams = new TreeTranslator() {
1448 @Override
1449 public void visitTypeApply(JCTypeApply tree) {
1450 result = translate(tree.clazz);
1451 }
1452 };
1454 /** Compute the type of a conditional expression, after
1455 * checking that it exists. See JLS 15.25. Does not take into
1456 * account the special case where condition and both arms
1457 * are constants.
1458 *
1459 * @param pos The source position to be used for error
1460 * diagnostics.
1461 * @param thentype The type of the expression's then-part.
1462 * @param elsetype The type of the expression's else-part.
1463 */
1464 private Type condType(DiagnosticPosition pos,
1465 Type thentype, Type elsetype) {
1466 // If same type, that is the result
1467 if (types.isSameType(thentype, elsetype))
1468 return thentype.baseType();
1470 Type thenUnboxed = (!allowBoxing || thentype.isPrimitive())
1471 ? thentype : types.unboxedType(thentype);
1472 Type elseUnboxed = (!allowBoxing || elsetype.isPrimitive())
1473 ? elsetype : types.unboxedType(elsetype);
1475 // Otherwise, if both arms can be converted to a numeric
1476 // type, return the least numeric type that fits both arms
1477 // (i.e. return larger of the two, or return int if one
1478 // arm is short, the other is char).
1479 if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) {
1480 // If one arm has an integer subrange type (i.e., byte,
1481 // short, or char), and the other is an integer constant
1482 // that fits into the subrange, return the subrange type.
1483 if (thenUnboxed.getTag().isStrictSubRangeOf(INT) && elseUnboxed.hasTag(INT) &&
1484 types.isAssignable(elseUnboxed, thenUnboxed))
1485 return thenUnboxed.baseType();
1486 if (elseUnboxed.getTag().isStrictSubRangeOf(INT) && thenUnboxed.hasTag(INT) &&
1487 types.isAssignable(thenUnboxed, elseUnboxed))
1488 return elseUnboxed.baseType();
1490 for (TypeTag tag : TypeTag.values()) {
1491 if (tag.ordinal() >= TypeTag.getTypeTagCount()) break;
1492 Type candidate = syms.typeOfTag[tag.ordinal()];
1493 if (candidate != null &&
1494 candidate.isPrimitive() &&
1495 types.isSubtype(thenUnboxed, candidate) &&
1496 types.isSubtype(elseUnboxed, candidate))
1497 return candidate;
1498 }
1499 }
1501 // Those were all the cases that could result in a primitive
1502 if (allowBoxing) {
1503 if (thentype.isPrimitive())
1504 thentype = types.boxedClass(thentype).type;
1505 if (elsetype.isPrimitive())
1506 elsetype = types.boxedClass(elsetype).type;
1507 }
1509 if (types.isSubtype(thentype, elsetype))
1510 return elsetype.baseType();
1511 if (types.isSubtype(elsetype, thentype))
1512 return thentype.baseType();
1514 if (!allowBoxing || thentype.hasTag(VOID) || elsetype.hasTag(VOID)) {
1515 log.error(pos, "neither.conditional.subtype",
1516 thentype, elsetype);
1517 return thentype.baseType();
1518 }
1520 // both are known to be reference types. The result is
1521 // lub(thentype,elsetype). This cannot fail, as it will
1522 // always be possible to infer "Object" if nothing better.
1523 return types.lub(thentype.baseType(), elsetype.baseType());
1524 }
1526 public void visitIf(JCIf tree) {
1527 attribExpr(tree.cond, env, syms.booleanType);
1528 attribStat(tree.thenpart, env);
1529 if (tree.elsepart != null)
1530 attribStat(tree.elsepart, env);
1531 chk.checkEmptyIf(tree);
1532 result = null;
1533 }
1535 public void visitExec(JCExpressionStatement tree) {
1536 //a fresh environment is required for 292 inference to work properly ---
1537 //see Infer.instantiatePolymorphicSignatureInstance()
1538 Env<AttrContext> localEnv = env.dup(tree);
1539 attribExpr(tree.expr, localEnv);
1540 result = null;
1541 }
1543 public void visitBreak(JCBreak tree) {
1544 tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
1545 result = null;
1546 }
1548 public void visitContinue(JCContinue tree) {
1549 tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
1550 result = null;
1551 }
1552 //where
1553 /** Return the target of a break or continue statement, if it exists,
1554 * report an error if not.
1555 * Note: The target of a labelled break or continue is the
1556 * (non-labelled) statement tree referred to by the label,
1557 * not the tree representing the labelled statement itself.
1558 *
1559 * @param pos The position to be used for error diagnostics
1560 * @param tag The tag of the jump statement. This is either
1561 * Tree.BREAK or Tree.CONTINUE.
1562 * @param label The label of the jump statement, or null if no
1563 * label is given.
1564 * @param env The environment current at the jump statement.
1565 */
1566 private JCTree findJumpTarget(DiagnosticPosition pos,
1567 JCTree.Tag tag,
1568 Name label,
1569 Env<AttrContext> env) {
1570 // Search environments outwards from the point of jump.
1571 Env<AttrContext> env1 = env;
1572 LOOP:
1573 while (env1 != null) {
1574 switch (env1.tree.getTag()) {
1575 case LABELLED:
1576 JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
1577 if (label == labelled.label) {
1578 // If jump is a continue, check that target is a loop.
1579 if (tag == CONTINUE) {
1580 if (!labelled.body.hasTag(DOLOOP) &&
1581 !labelled.body.hasTag(WHILELOOP) &&
1582 !labelled.body.hasTag(FORLOOP) &&
1583 !labelled.body.hasTag(FOREACHLOOP))
1584 log.error(pos, "not.loop.label", label);
1585 // Found labelled statement target, now go inwards
1586 // to next non-labelled tree.
1587 return TreeInfo.referencedStatement(labelled);
1588 } else {
1589 return labelled;
1590 }
1591 }
1592 break;
1593 case DOLOOP:
1594 case WHILELOOP:
1595 case FORLOOP:
1596 case FOREACHLOOP:
1597 if (label == null) return env1.tree;
1598 break;
1599 case SWITCH:
1600 if (label == null && tag == BREAK) return env1.tree;
1601 break;
1602 case LAMBDA:
1603 case METHODDEF:
1604 case CLASSDEF:
1605 break LOOP;
1606 default:
1607 }
1608 env1 = env1.next;
1609 }
1610 if (label != null)
1611 log.error(pos, "undef.label", label);
1612 else if (tag == CONTINUE)
1613 log.error(pos, "cont.outside.loop");
1614 else
1615 log.error(pos, "break.outside.switch.loop");
1616 return null;
1617 }
1619 public void visitReturn(JCReturn tree) {
1620 // Check that there is an enclosing method which is
1621 // nested within than the enclosing class.
1622 if (env.info.returnResult == null) {
1623 log.error(tree.pos(), "ret.outside.meth");
1624 } else {
1625 // Attribute return expression, if it exists, and check that
1626 // it conforms to result type of enclosing method.
1627 if (tree.expr != null) {
1628 if (env.info.returnResult.pt.hasTag(VOID)) {
1629 env.info.returnResult.checkContext.report(tree.expr.pos(),
1630 diags.fragment("unexpected.ret.val"));
1631 }
1632 attribTree(tree.expr, env, env.info.returnResult);
1633 } else if (!env.info.returnResult.pt.hasTag(VOID)) {
1634 env.info.returnResult.checkContext.report(tree.pos(),
1635 diags.fragment("missing.ret.val"));
1636 }
1637 }
1638 result = null;
1639 }
1641 public void visitThrow(JCThrow tree) {
1642 Type owntype = attribExpr(tree.expr, env, allowPoly ? Type.noType : syms.throwableType);
1643 if (allowPoly) {
1644 chk.checkType(tree, owntype, syms.throwableType);
1645 }
1646 result = null;
1647 }
1649 public void visitAssert(JCAssert tree) {
1650 attribExpr(tree.cond, env, syms.booleanType);
1651 if (tree.detail != null) {
1652 chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
1653 }
1654 result = null;
1655 }
1657 /** Visitor method for method invocations.
1658 * NOTE: The method part of an application will have in its type field
1659 * the return type of the method, not the method's type itself!
1660 */
1661 public void visitApply(JCMethodInvocation tree) {
1662 // The local environment of a method application is
1663 // a new environment nested in the current one.
1664 Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
1666 // The types of the actual method arguments.
1667 List<Type> argtypes;
1669 // The types of the actual method type arguments.
1670 List<Type> typeargtypes = null;
1672 Name methName = TreeInfo.name(tree.meth);
1674 boolean isConstructorCall =
1675 methName == names._this || methName == names._super;
1677 if (isConstructorCall) {
1678 // We are seeing a ...this(...) or ...super(...) call.
1679 // Check that this is the first statement in a constructor.
1680 if (checkFirstConstructorStat(tree, env)) {
1682 // Record the fact
1683 // that this is a constructor call (using isSelfCall).
1684 localEnv.info.isSelfCall = true;
1686 // Attribute arguments, yielding list of argument types.
1687 argtypes = attribArgs(tree.args, localEnv);
1688 typeargtypes = attribTypes(tree.typeargs, localEnv);
1690 // Variable `site' points to the class in which the called
1691 // constructor is defined.
1692 Type site = env.enclClass.sym.type;
1693 if (methName == names._super) {
1694 if (site == syms.objectType) {
1695 log.error(tree.meth.pos(), "no.superclass", site);
1696 site = types.createErrorType(syms.objectType);
1697 } else {
1698 site = types.supertype(site);
1699 }
1700 }
1702 if (site.hasTag(CLASS)) {
1703 Type encl = site.getEnclosingType();
1704 while (encl != null && encl.hasTag(TYPEVAR))
1705 encl = encl.getUpperBound();
1706 if (encl.hasTag(CLASS)) {
1707 // we are calling a nested class
1709 if (tree.meth.hasTag(SELECT)) {
1710 JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
1712 // We are seeing a prefixed call, of the form
1713 // <expr>.super(...).
1714 // Check that the prefix expression conforms
1715 // to the outer instance type of the class.
1716 chk.checkRefType(qualifier.pos(),
1717 attribExpr(qualifier, localEnv,
1718 encl));
1719 } else if (methName == names._super) {
1720 // qualifier omitted; check for existence
1721 // of an appropriate implicit qualifier.
1722 rs.resolveImplicitThis(tree.meth.pos(),
1723 localEnv, site, true);
1724 }
1725 } else if (tree.meth.hasTag(SELECT)) {
1726 log.error(tree.meth.pos(), "illegal.qual.not.icls",
1727 site.tsym);
1728 }
1730 // if we're calling a java.lang.Enum constructor,
1731 // prefix the implicit String and int parameters
1732 if (site.tsym == syms.enumSym && allowEnums)
1733 argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
1735 // Resolve the called constructor under the assumption
1736 // that we are referring to a superclass instance of the
1737 // current instance (JLS ???).
1738 boolean selectSuperPrev = localEnv.info.selectSuper;
1739 localEnv.info.selectSuper = true;
1740 localEnv.info.pendingResolutionPhase = null;
1741 Symbol sym = rs.resolveConstructor(
1742 tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
1743 localEnv.info.selectSuper = selectSuperPrev;
1745 // Set method symbol to resolved constructor...
1746 TreeInfo.setSymbol(tree.meth, sym);
1748 // ...and check that it is legal in the current context.
1749 // (this will also set the tree's type)
1750 Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
1751 checkId(tree.meth, site, sym, localEnv, new ResultInfo(MTH, mpt));
1752 }
1753 // Otherwise, `site' is an error type and we do nothing
1754 }
1755 result = tree.type = syms.voidType;
1756 } else {
1757 // Otherwise, we are seeing a regular method call.
1758 // Attribute the arguments, yielding list of argument types, ...
1759 argtypes = attribArgs(tree.args, localEnv);
1760 typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
1762 // ... and attribute the method using as a prototype a methodtype
1763 // whose formal argument types is exactly the list of actual
1764 // arguments (this will also set the method symbol).
1765 Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
1766 localEnv.info.pendingResolutionPhase = null;
1767 Type mtype = attribTree(tree.meth, localEnv, new ResultInfo(VAL, mpt, resultInfo.checkContext));
1769 // Compute the result type.
1770 Type restype = mtype.getReturnType();
1771 if (restype.hasTag(WILDCARD))
1772 throw new AssertionError(mtype);
1774 Type qualifier = (tree.meth.hasTag(SELECT))
1775 ? ((JCFieldAccess) tree.meth).selected.type
1776 : env.enclClass.sym.type;
1777 restype = adjustMethodReturnType(qualifier, methName, argtypes, restype);
1779 chk.checkRefTypes(tree.typeargs, typeargtypes);
1781 // Check that value of resulting type is admissible in the
1782 // current context. Also, capture the return type
1783 result = check(tree, capture(restype), VAL, resultInfo);
1785 if (localEnv.info.lastResolveVarargs())
1786 Assert.check(result.isErroneous() || tree.varargsElement != null);
1787 }
1788 chk.validate(tree.typeargs, localEnv);
1789 }
1790 //where
1791 Type adjustMethodReturnType(Type qualifierType, Name methodName, List<Type> argtypes, Type restype) {
1792 if (allowCovariantReturns &&
1793 methodName == names.clone &&
1794 types.isArray(qualifierType)) {
1795 // as a special case, array.clone() has a result that is
1796 // the same as static type of the array being cloned
1797 return qualifierType;
1798 } else if (allowGenerics &&
1799 methodName == names.getClass &&
1800 argtypes.isEmpty()) {
1801 // as a special case, x.getClass() has type Class<? extends |X|>
1802 return new ClassType(restype.getEnclosingType(),
1803 List.<Type>of(new WildcardType(types.erasure(qualifierType),
1804 BoundKind.EXTENDS,
1805 syms.boundClass)),
1806 restype.tsym);
1807 } else {
1808 return restype;
1809 }
1810 }
1812 /** Check that given application node appears as first statement
1813 * in a constructor call.
1814 * @param tree The application node
1815 * @param env The environment current at the application.
1816 */
1817 boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) {
1818 JCMethodDecl enclMethod = env.enclMethod;
1819 if (enclMethod != null && enclMethod.name == names.init) {
1820 JCBlock body = enclMethod.body;
1821 if (body.stats.head.hasTag(EXEC) &&
1822 ((JCExpressionStatement) body.stats.head).expr == tree)
1823 return true;
1824 }
1825 log.error(tree.pos(),"call.must.be.first.stmt.in.ctor",
1826 TreeInfo.name(tree.meth));
1827 return false;
1828 }
1830 /** Obtain a method type with given argument types.
1831 */
1832 Type newMethodTemplate(Type restype, List<Type> argtypes, List<Type> typeargtypes) {
1833 MethodType mt = new MethodType(argtypes, restype, List.<Type>nil(), syms.methodClass);
1834 return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
1835 }
1837 public void visitNewClass(final JCNewClass tree) {
1838 Type owntype = types.createErrorType(tree.type);
1840 // The local environment of a class creation is
1841 // a new environment nested in the current one.
1842 Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
1844 // The anonymous inner class definition of the new expression,
1845 // if one is defined by it.
1846 JCClassDecl cdef = tree.def;
1848 // If enclosing class is given, attribute it, and
1849 // complete class name to be fully qualified
1850 JCExpression clazz = tree.clazz; // Class field following new
1851 JCExpression clazzid = // Identifier in class field
1852 (clazz.hasTag(TYPEAPPLY))
1853 ? ((JCTypeApply) clazz).clazz
1854 : clazz;
1856 JCExpression clazzid1 = clazzid; // The same in fully qualified form
1858 if (tree.encl != null) {
1859 // We are seeing a qualified new, of the form
1860 // <expr>.new C <...> (...) ...
1861 // In this case, we let clazz stand for the name of the
1862 // allocated class C prefixed with the type of the qualifier
1863 // expression, so that we can
1864 // resolve it with standard techniques later. I.e., if
1865 // <expr> has type T, then <expr>.new C <...> (...)
1866 // yields a clazz T.C.
1867 Type encltype = chk.checkRefType(tree.encl.pos(),
1868 attribExpr(tree.encl, env));
1869 clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
1870 ((JCIdent) clazzid).name);
1871 if (clazz.hasTag(TYPEAPPLY))
1872 clazz = make.at(tree.pos).
1873 TypeApply(clazzid1,
1874 ((JCTypeApply) clazz).arguments);
1875 else
1876 clazz = clazzid1;
1877 }
1879 // Attribute clazz expression and store
1880 // symbol + type back into the attributed tree.
1881 Type clazztype = TreeInfo.isEnumInit(env.tree) ?
1882 attribIdentAsEnumType(env, (JCIdent)clazz) :
1883 attribType(clazz, env);
1885 clazztype = chk.checkDiamond(tree, clazztype);
1886 chk.validate(clazz, localEnv);
1887 if (tree.encl != null) {
1888 // We have to work in this case to store
1889 // symbol + type back into the attributed tree.
1890 tree.clazz.type = clazztype;
1891 TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
1892 clazzid.type = ((JCIdent) clazzid).sym.type;
1893 if (!clazztype.isErroneous()) {
1894 if (cdef != null && clazztype.tsym.isInterface()) {
1895 log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new");
1896 } else if (clazztype.tsym.isStatic()) {
1897 log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym);
1898 }
1899 }
1900 } else if (!clazztype.tsym.isInterface() &&
1901 clazztype.getEnclosingType().hasTag(CLASS)) {
1902 // Check for the existence of an apropos outer instance
1903 rs.resolveImplicitThis(tree.pos(), env, clazztype);
1904 }
1906 // Attribute constructor arguments.
1907 List<Type> argtypes = attribArgs(tree.args, localEnv);
1908 List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
1910 // If we have made no mistakes in the class type...
1911 if (clazztype.hasTag(CLASS)) {
1912 // Enums may not be instantiated except implicitly
1913 if (allowEnums &&
1914 (clazztype.tsym.flags_field&Flags.ENUM) != 0 &&
1915 (!env.tree.hasTag(VARDEF) ||
1916 (((JCVariableDecl) env.tree).mods.flags&Flags.ENUM) == 0 ||
1917 ((JCVariableDecl) env.tree).init != tree))
1918 log.error(tree.pos(), "enum.cant.be.instantiated");
1919 // Check that class is not abstract
1920 if (cdef == null &&
1921 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
1922 log.error(tree.pos(), "abstract.cant.be.instantiated",
1923 clazztype.tsym);
1924 } else if (cdef != null && clazztype.tsym.isInterface()) {
1925 // Check that no constructor arguments are given to
1926 // anonymous classes implementing an interface
1927 if (!argtypes.isEmpty())
1928 log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args");
1930 if (!typeargtypes.isEmpty())
1931 log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs");
1933 // Error recovery: pretend no arguments were supplied.
1934 argtypes = List.nil();
1935 typeargtypes = List.nil();
1936 } else if (TreeInfo.isDiamond(tree)) {
1937 ClassType site = new ClassType(clazztype.getEnclosingType(),
1938 clazztype.tsym.type.getTypeArguments(),
1939 clazztype.tsym);
1941 Env<AttrContext> diamondEnv = localEnv.dup(tree);
1942 diamondEnv.info.selectSuper = cdef != null;
1943 diamondEnv.info.pendingResolutionPhase = null;
1945 //if the type of the instance creation expression is a class type
1946 //apply method resolution inference (JLS 15.12.2.7). The return type
1947 //of the resolved constructor will be a partially instantiated type
1948 Symbol constructor = rs.resolveDiamond(tree.pos(),
1949 diamondEnv,
1950 site,
1951 argtypes,
1952 typeargtypes);
1953 tree.constructor = constructor.baseSymbol();
1955 final TypeSymbol csym = clazztype.tsym;
1956 ResultInfo diamondResult = new ResultInfo(MTH, newMethodTemplate(resultInfo.pt, argtypes, typeargtypes), new Check.NestedCheckContext(resultInfo.checkContext) {
1957 @Override
1958 public void report(DiagnosticPosition _unused, JCDiagnostic details) {
1959 enclosingContext.report(tree.clazz,
1960 diags.fragment("cant.apply.diamond.1", diags.fragment("diamond", csym), details));
1961 }
1962 });
1963 Type constructorType = tree.constructorType = types.createErrorType(clazztype);
1964 constructorType = checkId(tree, site,
1965 constructor,
1966 diamondEnv,
1967 diamondResult);
1969 tree.clazz.type = types.createErrorType(clazztype);
1970 if (!constructorType.isErroneous()) {
1971 tree.clazz.type = clazztype = constructorType.getReturnType();
1972 tree.constructorType = types.createMethodTypeWithReturn(constructorType, syms.voidType);
1973 }
1974 clazztype = chk.checkClassType(tree.clazz, tree.clazz.type, true);
1975 }
1977 // Resolve the called constructor under the assumption
1978 // that we are referring to a superclass instance of the
1979 // current instance (JLS ???).
1980 else {
1981 //the following code alters some of the fields in the current
1982 //AttrContext - hence, the current context must be dup'ed in
1983 //order to avoid downstream failures
1984 Env<AttrContext> rsEnv = localEnv.dup(tree);
1985 rsEnv.info.selectSuper = cdef != null;
1986 rsEnv.info.pendingResolutionPhase = null;
1987 tree.constructor = rs.resolveConstructor(
1988 tree.pos(), rsEnv, clazztype, argtypes, typeargtypes);
1989 if (cdef == null) { //do not check twice!
1990 tree.constructorType = checkId(tree,
1991 clazztype,
1992 tree.constructor,
1993 rsEnv,
1994 new ResultInfo(MTH, newMethodTemplate(syms.voidType, argtypes, typeargtypes)));
1995 if (rsEnv.info.lastResolveVarargs())
1996 Assert.check(tree.constructorType.isErroneous() || tree.varargsElement != null);
1997 }
1998 findDiamondIfNeeded(localEnv, tree, clazztype);
1999 }
2001 if (cdef != null) {
2002 // We are seeing an anonymous class instance creation.
2003 // In this case, the class instance creation
2004 // expression
2005 //
2006 // E.new <typeargs1>C<typargs2>(args) { ... }
2007 //
2008 // is represented internally as
2009 //
2010 // E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } ) .
2011 //
2012 // This expression is then *transformed* as follows:
2013 //
2014 // (1) add a STATIC flag to the class definition
2015 // if the current environment is static
2016 // (2) add an extends or implements clause
2017 // (3) add a constructor.
2018 //
2019 // For instance, if C is a class, and ET is the type of E,
2020 // the expression
2021 //
2022 // E.new <typeargs1>C<typargs2>(args) { ... }
2023 //
2024 // is translated to (where X is a fresh name and typarams is the
2025 // parameter list of the super constructor):
2026 //
2027 // new <typeargs1>X(<*nullchk*>E, args) where
2028 // X extends C<typargs2> {
2029 // <typarams> X(ET e, args) {
2030 // e.<typeargs1>super(args)
2031 // }
2032 // ...
2033 // }
2034 if (Resolve.isStatic(env)) cdef.mods.flags |= STATIC;
2036 if (clazztype.tsym.isInterface()) {
2037 cdef.implementing = List.of(clazz);
2038 } else {
2039 cdef.extending = clazz;
2040 }
2042 attribStat(cdef, localEnv);
2044 checkLambdaCandidate(tree, cdef.sym, clazztype);
2046 // If an outer instance is given,
2047 // prefix it to the constructor arguments
2048 // and delete it from the new expression
2049 if (tree.encl != null && !clazztype.tsym.isInterface()) {
2050 tree.args = tree.args.prepend(makeNullCheck(tree.encl));
2051 argtypes = argtypes.prepend(tree.encl.type);
2052 tree.encl = null;
2053 }
2055 // Reassign clazztype and recompute constructor.
2056 clazztype = cdef.sym.type;
2057 Symbol sym = tree.constructor = rs.resolveConstructor(
2058 tree.pos(), localEnv, clazztype, argtypes, typeargtypes);
2059 Assert.check(sym.kind < AMBIGUOUS);
2060 tree.constructor = sym;
2061 tree.constructorType = checkId(tree,
2062 clazztype,
2063 tree.constructor,
2064 localEnv,
2065 new ResultInfo(VAL, newMethodTemplate(syms.voidType, argtypes, typeargtypes)));
2066 }
2068 if (tree.constructor != null && tree.constructor.kind == MTH)
2069 owntype = clazztype;
2070 }
2071 result = check(tree, owntype, VAL, resultInfo);
2072 chk.validate(tree.typeargs, localEnv);
2073 }
2074 //where
2075 void findDiamondIfNeeded(Env<AttrContext> env, JCNewClass tree, Type clazztype) {
2076 if (tree.def == null &&
2077 !clazztype.isErroneous() &&
2078 clazztype.getTypeArguments().nonEmpty() &&
2079 findDiamonds) {
2080 JCTypeApply ta = (JCTypeApply)tree.clazz;
2081 List<JCExpression> prevTypeargs = ta.arguments;
2082 try {
2083 //create a 'fake' diamond AST node by removing type-argument trees
2084 ta.arguments = List.nil();
2085 ResultInfo findDiamondResult = new ResultInfo(VAL,
2086 resultInfo.checkContext.inferenceContext().free(resultInfo.pt) ? Type.noType : pt());
2087 Type inferred = deferredAttr.attribSpeculative(tree, env, findDiamondResult).type;
2088 if (!inferred.isErroneous() &&
2089 types.isAssignable(inferred, pt().hasTag(NONE) ? syms.objectType : pt(), types.noWarnings)) {
2090 String key = types.isSameType(clazztype, inferred) ?
2091 "diamond.redundant.args" :
2092 "diamond.redundant.args.1";
2093 log.warning(tree.clazz.pos(), key, clazztype, inferred);
2094 }
2095 } finally {
2096 ta.arguments = prevTypeargs;
2097 }
2098 }
2099 }
2101 private void checkLambdaCandidate(JCNewClass tree, ClassSymbol csym, Type clazztype) {
2102 if (allowLambda &&
2103 identifyLambdaCandidate &&
2104 clazztype.hasTag(CLASS) &&
2105 !pt().hasTag(NONE) &&
2106 types.isFunctionalInterface(clazztype.tsym)) {
2107 Symbol descriptor = types.findDescriptorSymbol(clazztype.tsym);
2108 int count = 0;
2109 boolean found = false;
2110 for (Symbol sym : csym.members().getElements()) {
2111 if ((sym.flags() & SYNTHETIC) != 0 ||
2112 sym.isConstructor()) continue;
2113 count++;
2114 if (sym.kind != MTH ||
2115 !sym.name.equals(descriptor.name)) continue;
2116 Type mtype = types.memberType(clazztype, sym);
2117 if (types.overrideEquivalent(mtype, types.memberType(clazztype, descriptor))) {
2118 found = true;
2119 }
2120 }
2121 if (found && count == 1) {
2122 log.note(tree.def, "potential.lambda.found");
2123 }
2124 }
2125 }
2127 /** Make an attributed null check tree.
2128 */
2129 public JCExpression makeNullCheck(JCExpression arg) {
2130 // optimization: X.this is never null; skip null check
2131 Name name = TreeInfo.name(arg);
2132 if (name == names._this || name == names._super) return arg;
2134 JCTree.Tag optag = NULLCHK;
2135 JCUnary tree = make.at(arg.pos).Unary(optag, arg);
2136 tree.operator = syms.nullcheck;
2137 tree.type = arg.type;
2138 return tree;
2139 }
2141 public void visitNewArray(JCNewArray tree) {
2142 Type owntype = types.createErrorType(tree.type);
2143 Env<AttrContext> localEnv = env.dup(tree);
2144 Type elemtype;
2145 if (tree.elemtype != null) {
2146 elemtype = attribType(tree.elemtype, localEnv);
2147 chk.validate(tree.elemtype, localEnv);
2148 owntype = elemtype;
2149 for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
2150 attribExpr(l.head, localEnv, syms.intType);
2151 owntype = new ArrayType(owntype, syms.arrayClass);
2152 }
2153 } else {
2154 // we are seeing an untyped aggregate { ... }
2155 // this is allowed only if the prototype is an array
2156 if (pt().hasTag(ARRAY)) {
2157 elemtype = types.elemtype(pt());
2158 } else {
2159 if (!pt().hasTag(ERROR)) {
2160 log.error(tree.pos(), "illegal.initializer.for.type",
2161 pt());
2162 }
2163 elemtype = types.createErrorType(pt());
2164 }
2165 }
2166 if (tree.elems != null) {
2167 attribExprs(tree.elems, localEnv, elemtype);
2168 owntype = new ArrayType(elemtype, syms.arrayClass);
2169 }
2170 if (!types.isReifiable(elemtype))
2171 log.error(tree.pos(), "generic.array.creation");
2172 result = check(tree, owntype, VAL, resultInfo);
2173 }
2175 /*
2176 * A lambda expression can only be attributed when a target-type is available.
2177 * In addition, if the target-type is that of a functional interface whose
2178 * descriptor contains inference variables in argument position the lambda expression
2179 * is 'stuck' (see DeferredAttr).
2180 */
2181 @Override
2182 public void visitLambda(final JCLambda that) {
2183 if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
2184 if (pt().hasTag(NONE)) {
2185 //lambda only allowed in assignment or method invocation/cast context
2186 log.error(that.pos(), "unexpected.lambda");
2187 }
2188 result = that.type = types.createErrorType(pt());
2189 return;
2190 }
2191 //create an environment for attribution of the lambda expression
2192 final Env<AttrContext> localEnv = lambdaEnv(that, env);
2193 boolean needsRecovery =
2194 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK;
2195 try {
2196 Type target = pt();
2197 List<Type> explicitParamTypes = null;
2198 if (that.paramKind == JCLambda.ParameterKind.EXPLICIT) {
2199 //attribute lambda parameters
2200 attribStats(that.params, localEnv);
2201 explicitParamTypes = TreeInfo.types(that.params);
2202 target = infer.instantiateFunctionalInterface(that, target, explicitParamTypes, resultInfo.checkContext);
2203 }
2205 Type lambdaType;
2206 if (pt() != Type.recoveryType) {
2207 target = checkIntersectionTarget(that, target, resultInfo.checkContext);
2208 lambdaType = types.findDescriptorType(target);
2209 chk.checkFunctionalInterface(that, target);
2210 } else {
2211 target = Type.recoveryType;
2212 lambdaType = fallbackDescriptorType(that);
2213 }
2215 setFunctionalInfo(that, pt(), lambdaType, resultInfo.checkContext.inferenceContext());
2217 if (lambdaType.hasTag(FORALL)) {
2218 //lambda expression target desc cannot be a generic method
2219 resultInfo.checkContext.report(that, diags.fragment("invalid.generic.lambda.target",
2220 lambdaType, kindName(target.tsym), target.tsym));
2221 result = that.type = types.createErrorType(pt());
2222 return;
2223 }
2225 if (that.paramKind == JCLambda.ParameterKind.IMPLICIT) {
2226 //add param type info in the AST
2227 List<Type> actuals = lambdaType.getParameterTypes();
2228 List<JCVariableDecl> params = that.params;
2230 boolean arityMismatch = false;
2232 while (params.nonEmpty()) {
2233 if (actuals.isEmpty()) {
2234 //not enough actuals to perform lambda parameter inference
2235 arityMismatch = true;
2236 }
2237 //reset previously set info
2238 Type argType = arityMismatch ?
2239 syms.errType :
2240 actuals.head;
2241 params.head.vartype = make.Type(argType);
2242 params.head.sym = null;
2243 actuals = actuals.isEmpty() ?
2244 actuals :
2245 actuals.tail;
2246 params = params.tail;
2247 }
2249 //attribute lambda parameters
2250 attribStats(that.params, localEnv);
2252 if (arityMismatch) {
2253 resultInfo.checkContext.report(that, diags.fragment("incompatible.arg.types.in.lambda"));
2254 result = that.type = types.createErrorType(target);
2255 return;
2256 }
2257 }
2259 //from this point on, no recovery is needed; if we are in assignment context
2260 //we will be able to attribute the whole lambda body, regardless of errors;
2261 //if we are in a 'check' method context, and the lambda is not compatible
2262 //with the target-type, it will be recovered anyway in Attr.checkId
2263 needsRecovery = false;
2265 FunctionalReturnContext funcContext = that.getBodyKind() == JCLambda.BodyKind.EXPRESSION ?
2266 new ExpressionLambdaReturnContext((JCExpression)that.getBody(), resultInfo.checkContext) :
2267 new FunctionalReturnContext(resultInfo.checkContext);
2269 ResultInfo bodyResultInfo = lambdaType.getReturnType() == Type.recoveryType ?
2270 recoveryInfo :
2271 new ResultInfo(VAL, lambdaType.getReturnType(), funcContext);
2272 localEnv.info.returnResult = bodyResultInfo;
2274 if (that.getBodyKind() == JCLambda.BodyKind.EXPRESSION) {
2275 attribTree(that.getBody(), localEnv, bodyResultInfo);
2276 } else {
2277 JCBlock body = (JCBlock)that.body;
2278 attribStats(body.stats, localEnv);
2279 }
2281 result = check(that, target, VAL, resultInfo);
2283 boolean isSpeculativeRound =
2284 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
2286 postAttr(that);
2287 flow.analyzeLambda(env, that, make, isSpeculativeRound);
2289 checkLambdaCompatible(that, lambdaType, resultInfo.checkContext, isSpeculativeRound);
2291 if (!isSpeculativeRound) {
2292 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), lambdaType, target);
2293 }
2294 result = check(that, target, VAL, resultInfo);
2295 } catch (Types.FunctionDescriptorLookupError ex) {
2296 JCDiagnostic cause = ex.getDiagnostic();
2297 resultInfo.checkContext.report(that, cause);
2298 result = that.type = types.createErrorType(pt());
2299 return;
2300 } finally {
2301 localEnv.info.scope.leave();
2302 if (needsRecovery) {
2303 attribTree(that, env, recoveryInfo);
2304 }
2305 }
2306 }
2308 private Type checkIntersectionTarget(DiagnosticPosition pos, Type pt, CheckContext checkContext) {
2309 if (pt != Type.recoveryType && pt.isCompound()) {
2310 IntersectionClassType ict = (IntersectionClassType)pt;
2311 List<Type> bounds = ict.allInterfaces ?
2312 ict.getComponents().tail :
2313 ict.getComponents();
2314 types.findDescriptorType(bounds.head); //propagate exception outwards!
2315 for (Type bound : bounds.tail) {
2316 if (!types.isMarkerInterface(bound)) {
2317 checkContext.report(pos, diags.fragment("secondary.bound.must.be.marker.intf", bound));
2318 }
2319 }
2320 //for now (translation doesn't support intersection types)
2321 return bounds.head;
2322 } else {
2323 return pt;
2324 }
2325 }
2326 //where
2327 private Type fallbackDescriptorType(JCExpression tree) {
2328 switch (tree.getTag()) {
2329 case LAMBDA:
2330 JCLambda lambda = (JCLambda)tree;
2331 List<Type> argtypes = List.nil();
2332 for (JCVariableDecl param : lambda.params) {
2333 argtypes = param.vartype != null ?
2334 argtypes.append(param.vartype.type) :
2335 argtypes.append(syms.errType);
2336 }
2337 return new MethodType(argtypes, Type.recoveryType, List.<Type>nil(), syms.methodClass);
2338 case REFERENCE:
2339 return new MethodType(List.<Type>nil(), Type.recoveryType, List.<Type>nil(), syms.methodClass);
2340 default:
2341 Assert.error("Cannot get here!");
2342 }
2343 return null;
2344 }
2346 private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env, final InferenceContext inferenceContext, final Type... ts) {
2347 checkAccessibleTypes(pos, env, inferenceContext, List.from(ts));
2348 }
2350 private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env, final InferenceContext inferenceContext, final List<Type> ts) {
2351 if (inferenceContext.free(ts)) {
2352 inferenceContext.addFreeTypeListener(ts, new FreeTypeListener() {
2353 @Override
2354 public void typesInferred(InferenceContext inferenceContext) {
2355 checkAccessibleTypes(pos, env, inferenceContext, inferenceContext.asInstTypes(ts, types));
2356 }
2357 });
2358 } else {
2359 for (Type t : ts) {
2360 rs.checkAccessibleType(env, t);
2361 }
2362 }
2363 }
2365 /**
2366 * Lambda/method reference have a special check context that ensures
2367 * that i.e. a lambda return type is compatible with the expected
2368 * type according to both the inherited context and the assignment
2369 * context.
2370 */
2371 class FunctionalReturnContext extends Check.NestedCheckContext {
2373 FunctionalReturnContext(CheckContext enclosingContext) {
2374 super(enclosingContext);
2375 }
2377 @Override
2378 public boolean compatible(Type found, Type req, Warner warn) {
2379 //return type must be compatible in both current context and assignment context
2380 return chk.basicHandler.compatible(found, inferenceContext().asFree(req, types), warn);
2381 }
2383 @Override
2384 public void report(DiagnosticPosition pos, JCDiagnostic details) {
2385 enclosingContext.report(pos, diags.fragment("incompatible.ret.type.in.lambda", details));
2386 }
2387 }
2389 class ExpressionLambdaReturnContext extends FunctionalReturnContext {
2391 JCExpression expr;
2393 ExpressionLambdaReturnContext(JCExpression expr, CheckContext enclosingContext) {
2394 super(enclosingContext);
2395 this.expr = expr;
2396 }
2398 @Override
2399 public boolean compatible(Type found, Type req, Warner warn) {
2400 //a void return is compatible with an expression statement lambda
2401 return TreeInfo.isExpressionStatement(expr) && req.hasTag(VOID) ||
2402 super.compatible(found, req, warn);
2403 }
2404 }
2406 /**
2407 * Lambda compatibility. Check that given return types, thrown types, parameter types
2408 * are compatible with the expected functional interface descriptor. This means that:
2409 * (i) parameter types must be identical to those of the target descriptor; (ii) return
2410 * types must be compatible with the return type of the expected descriptor;
2411 * (iii) thrown types must be 'included' in the thrown types list of the expected
2412 * descriptor.
2413 */
2414 private void checkLambdaCompatible(JCLambda tree, Type descriptor, CheckContext checkContext, boolean speculativeAttr) {
2415 Type returnType = checkContext.inferenceContext().asFree(descriptor.getReturnType(), types);
2417 //return values have already been checked - but if lambda has no return
2418 //values, we must ensure that void/value compatibility is correct;
2419 //this amounts at checking that, if a lambda body can complete normally,
2420 //the descriptor's return type must be void
2421 if (tree.getBodyKind() == JCLambda.BodyKind.STATEMENT && tree.canCompleteNormally &&
2422 !returnType.hasTag(VOID) && returnType != Type.recoveryType) {
2423 checkContext.report(tree, diags.fragment("incompatible.ret.type.in.lambda",
2424 diags.fragment("missing.ret.val", returnType)));
2425 }
2427 List<Type> argTypes = checkContext.inferenceContext().asFree(descriptor.getParameterTypes(), types);
2428 if (!types.isSameTypes(argTypes, TreeInfo.types(tree.params))) {
2429 checkContext.report(tree, diags.fragment("incompatible.arg.types.in.lambda"));
2430 }
2432 if (!speculativeAttr) {
2433 List<Type> thrownTypes = checkContext.inferenceContext().asFree(descriptor.getThrownTypes(), types);
2434 if (chk.unhandled(tree.inferredThrownTypes == null ? List.<Type>nil() : tree.inferredThrownTypes, thrownTypes).nonEmpty()) {
2435 log.error(tree, "incompatible.thrown.types.in.lambda", tree.inferredThrownTypes);
2436 }
2437 }
2438 }
2440 private Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) {
2441 Env<AttrContext> lambdaEnv;
2442 Symbol owner = env.info.scope.owner;
2443 if (owner.kind == VAR && owner.owner.kind == TYP) {
2444 //field initializer
2445 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared()));
2446 lambdaEnv.info.scope.owner =
2447 new MethodSymbol(0, names.empty, null,
2448 env.info.scope.owner);
2449 } else {
2450 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dup()));
2451 }
2452 return lambdaEnv;
2453 }
2455 @Override
2456 public void visitReference(final JCMemberReference that) {
2457 if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
2458 if (pt().hasTag(NONE)) {
2459 //method reference only allowed in assignment or method invocation/cast context
2460 log.error(that.pos(), "unexpected.mref");
2461 }
2462 result = that.type = types.createErrorType(pt());
2463 return;
2464 }
2465 final Env<AttrContext> localEnv = env.dup(that);
2466 try {
2467 //attribute member reference qualifier - if this is a constructor
2468 //reference, the expected kind must be a type
2469 Type exprType = attribTree(that.expr,
2470 env, new ResultInfo(that.getMode() == ReferenceMode.INVOKE ? VAL | TYP : TYP, Type.noType));
2472 if (that.getMode() == JCMemberReference.ReferenceMode.NEW) {
2473 exprType = chk.checkConstructorRefType(that.expr, exprType);
2474 }
2476 if (exprType.isErroneous()) {
2477 //if the qualifier expression contains problems,
2478 //give up atttribution of method reference
2479 result = that.type = exprType;
2480 return;
2481 }
2483 if (TreeInfo.isStaticSelector(that.expr, names) &&
2484 (that.getMode() != ReferenceMode.NEW || !that.expr.type.isRaw())) {
2485 //if the qualifier is a type, validate it
2486 chk.validate(that.expr, env);
2487 }
2489 //attrib type-arguments
2490 List<Type> typeargtypes = List.nil();
2491 if (that.typeargs != null) {
2492 typeargtypes = attribTypes(that.typeargs, localEnv);
2493 }
2495 Type target;
2496 Type desc;
2497 if (pt() != Type.recoveryType) {
2498 target = checkIntersectionTarget(that, pt(), resultInfo.checkContext);
2499 desc = types.findDescriptorType(target);
2500 chk.checkFunctionalInterface(that, target);
2501 } else {
2502 target = Type.recoveryType;
2503 desc = fallbackDescriptorType(that);
2504 }
2506 setFunctionalInfo(that, pt(), desc, resultInfo.checkContext.inferenceContext());
2507 List<Type> argtypes = desc.getParameterTypes();
2509 Pair<Symbol, Resolve.ReferenceLookupHelper> refResult = rs.resolveMemberReference(that.pos(), localEnv, that,
2510 that.expr.type, that.name, argtypes, typeargtypes, true);
2512 Symbol refSym = refResult.fst;
2513 Resolve.ReferenceLookupHelper lookupHelper = refResult.snd;
2515 if (refSym.kind != MTH) {
2516 boolean targetError;
2517 switch (refSym.kind) {
2518 case ABSENT_MTH:
2519 targetError = false;
2520 break;
2521 case WRONG_MTH:
2522 case WRONG_MTHS:
2523 case AMBIGUOUS:
2524 case HIDDEN:
2525 case STATICERR:
2526 case MISSING_ENCL:
2527 targetError = true;
2528 break;
2529 default:
2530 Assert.error("unexpected result kind " + refSym.kind);
2531 targetError = false;
2532 }
2534 JCDiagnostic detailsDiag = ((Resolve.ResolveError)refSym).getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT,
2535 that, exprType.tsym, exprType, that.name, argtypes, typeargtypes);
2537 JCDiagnostic.DiagnosticType diagKind = targetError ?
2538 JCDiagnostic.DiagnosticType.FRAGMENT : JCDiagnostic.DiagnosticType.ERROR;
2540 JCDiagnostic diag = diags.create(diagKind, log.currentSource(), that,
2541 "invalid.mref", Kinds.kindName(that.getMode()), detailsDiag);
2543 if (targetError && target == Type.recoveryType) {
2544 //a target error doesn't make sense during recovery stage
2545 //as we don't know what actual parameter types are
2546 result = that.type = target;
2547 return;
2548 } else {
2549 if (targetError) {
2550 resultInfo.checkContext.report(that, diag);
2551 } else {
2552 log.report(diag);
2553 }
2554 result = that.type = types.createErrorType(target);
2555 return;
2556 }
2557 }
2559 if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
2560 if (refSym.isStatic() && TreeInfo.isStaticSelector(that.expr, names) &&
2561 exprType.getTypeArguments().nonEmpty()) {
2562 //static ref with class type-args
2563 log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
2564 diags.fragment("static.mref.with.targs"));
2565 result = that.type = types.createErrorType(target);
2566 return;
2567 }
2569 if (refSym.isStatic() && !TreeInfo.isStaticSelector(that.expr, names) &&
2570 !lookupHelper.referenceKind(refSym).isUnbound()) {
2571 //no static bound mrefs
2572 log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
2573 diags.fragment("static.bound.mref"));
2574 result = that.type = types.createErrorType(target);
2575 return;
2576 }
2577 }
2579 if (desc.getReturnType() == Type.recoveryType) {
2580 // stop here
2581 result = that.type = target;
2582 return;
2583 }
2585 that.sym = refSym.baseSymbol();
2586 that.kind = lookupHelper.referenceKind(that.sym);
2588 ResultInfo checkInfo =
2589 resultInfo.dup(newMethodTemplate(
2590 desc.getReturnType().hasTag(VOID) ? Type.noType : desc.getReturnType(),
2591 lookupHelper.argtypes,
2592 typeargtypes));
2594 Type refType = checkId(that, lookupHelper.site, refSym, localEnv, checkInfo);
2596 if (!refType.isErroneous()) {
2597 refType = types.createMethodTypeWithReturn(refType,
2598 adjustMethodReturnType(lookupHelper.site, that.name, checkInfo.pt.getParameterTypes(), refType.getReturnType()));
2599 }
2601 //go ahead with standard method reference compatibility check - note that param check
2602 //is a no-op (as this has been taken care during method applicability)
2603 boolean isSpeculativeRound =
2604 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
2605 checkReferenceCompatible(that, desc, refType, resultInfo.checkContext, isSpeculativeRound);
2606 if (!isSpeculativeRound) {
2607 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), desc, target);
2608 }
2609 result = check(that, target, VAL, resultInfo);
2610 } catch (Types.FunctionDescriptorLookupError ex) {
2611 JCDiagnostic cause = ex.getDiagnostic();
2612 resultInfo.checkContext.report(that, cause);
2613 result = that.type = types.createErrorType(pt());
2614 return;
2615 }
2616 }
2618 @SuppressWarnings("fallthrough")
2619 void checkReferenceCompatible(JCMemberReference tree, Type descriptor, Type refType, CheckContext checkContext, boolean speculativeAttr) {
2620 Type returnType = checkContext.inferenceContext().asFree(descriptor.getReturnType(), types);
2622 Type resType;
2623 switch (tree.getMode()) {
2624 case NEW:
2625 if (!tree.expr.type.isRaw()) {
2626 resType = tree.expr.type;
2627 break;
2628 }
2629 default:
2630 resType = refType.getReturnType();
2631 }
2633 Type incompatibleReturnType = resType;
2635 if (returnType.hasTag(VOID)) {
2636 incompatibleReturnType = null;
2637 }
2639 if (!returnType.hasTag(VOID) && !resType.hasTag(VOID)) {
2640 if (resType.isErroneous() ||
2641 new FunctionalReturnContext(checkContext).compatible(resType, returnType, types.noWarnings)) {
2642 incompatibleReturnType = null;
2643 }
2644 }
2646 if (incompatibleReturnType != null) {
2647 checkContext.report(tree, diags.fragment("incompatible.ret.type.in.mref",
2648 diags.fragment("inconvertible.types", resType, descriptor.getReturnType())));
2649 }
2651 if (!speculativeAttr) {
2652 List<Type> thrownTypes = checkContext.inferenceContext().asFree(descriptor.getThrownTypes(), types);
2653 if (chk.unhandled(refType.getThrownTypes(), thrownTypes).nonEmpty()) {
2654 log.error(tree, "incompatible.thrown.types.in.mref", refType.getThrownTypes());
2655 }
2656 }
2657 }
2659 /**
2660 * Set functional type info on the underlying AST. Note: as the target descriptor
2661 * might contain inference variables, we might need to register an hook in the
2662 * current inference context.
2663 */
2664 private void setFunctionalInfo(final JCFunctionalExpression fExpr, final Type pt, final Type descriptorType, InferenceContext inferenceContext) {
2665 if (inferenceContext.free(descriptorType)) {
2666 inferenceContext.addFreeTypeListener(List.of(pt, descriptorType), new FreeTypeListener() {
2667 public void typesInferred(InferenceContext inferenceContext) {
2668 setFunctionalInfo(fExpr, pt, inferenceContext.asInstType(descriptorType, types), inferenceContext);
2669 }
2670 });
2671 } else {
2672 ListBuffer<TypeSymbol> targets = ListBuffer.lb();
2673 if (pt.hasTag(CLASS)) {
2674 if (pt.isCompound()) {
2675 for (Type t : ((IntersectionClassType)pt()).interfaces_field) {
2676 targets.append(t.tsym);
2677 }
2678 } else {
2679 targets.append(pt.tsym);
2680 }
2681 }
2682 fExpr.targets = targets.toList();
2683 fExpr.descriptorType = descriptorType;
2684 }
2685 }
2687 public void visitParens(JCParens tree) {
2688 Type owntype = attribTree(tree.expr, env, resultInfo);
2689 result = check(tree, owntype, pkind(), resultInfo);
2690 Symbol sym = TreeInfo.symbol(tree);
2691 if (sym != null && (sym.kind&(TYP|PCK)) != 0)
2692 log.error(tree.pos(), "illegal.start.of.type");
2693 }
2695 public void visitAssign(JCAssign tree) {
2696 Type owntype = attribTree(tree.lhs, env.dup(tree), varInfo);
2697 Type capturedType = capture(owntype);
2698 attribExpr(tree.rhs, env, owntype);
2699 result = check(tree, capturedType, VAL, resultInfo);
2700 }
2702 public void visitAssignop(JCAssignOp tree) {
2703 // Attribute arguments.
2704 Type owntype = attribTree(tree.lhs, env, varInfo);
2705 Type operand = attribExpr(tree.rhs, env);
2706 // Find operator.
2707 Symbol operator = tree.operator = rs.resolveBinaryOperator(
2708 tree.pos(), tree.getTag().noAssignOp(), env,
2709 owntype, operand);
2711 if (operator.kind == MTH &&
2712 !owntype.isErroneous() &&
2713 !operand.isErroneous()) {
2714 chk.checkOperator(tree.pos(),
2715 (OperatorSymbol)operator,
2716 tree.getTag().noAssignOp(),
2717 owntype,
2718 operand);
2719 chk.checkDivZero(tree.rhs.pos(), operator, operand);
2720 chk.checkCastable(tree.rhs.pos(),
2721 operator.type.getReturnType(),
2722 owntype);
2723 }
2724 result = check(tree, owntype, VAL, resultInfo);
2725 }
2727 public void visitUnary(JCUnary tree) {
2728 // Attribute arguments.
2729 Type argtype = (tree.getTag().isIncOrDecUnaryOp())
2730 ? attribTree(tree.arg, env, varInfo)
2731 : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
2733 // Find operator.
2734 Symbol operator = tree.operator =
2735 rs.resolveUnaryOperator(tree.pos(), tree.getTag(), env, argtype);
2737 Type owntype = types.createErrorType(tree.type);
2738 if (operator.kind == MTH &&
2739 !argtype.isErroneous()) {
2740 owntype = (tree.getTag().isIncOrDecUnaryOp())
2741 ? tree.arg.type
2742 : operator.type.getReturnType();
2743 int opc = ((OperatorSymbol)operator).opcode;
2745 // If the argument is constant, fold it.
2746 if (argtype.constValue() != null) {
2747 Type ctype = cfolder.fold1(opc, argtype);
2748 if (ctype != null) {
2749 owntype = cfolder.coerce(ctype, owntype);
2751 // Remove constant types from arguments to
2752 // conserve space. The parser will fold concatenations
2753 // of string literals; the code here also
2754 // gets rid of intermediate results when some of the
2755 // operands are constant identifiers.
2756 if (tree.arg.type.tsym == syms.stringType.tsym) {
2757 tree.arg.type = syms.stringType;
2758 }
2759 }
2760 }
2761 }
2762 result = check(tree, owntype, VAL, resultInfo);
2763 }
2765 public void visitBinary(JCBinary tree) {
2766 // Attribute arguments.
2767 Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
2768 Type right = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.rhs, env));
2770 // Find operator.
2771 Symbol operator = tree.operator =
2772 rs.resolveBinaryOperator(tree.pos(), tree.getTag(), env, left, right);
2774 Type owntype = types.createErrorType(tree.type);
2775 if (operator.kind == MTH &&
2776 !left.isErroneous() &&
2777 !right.isErroneous()) {
2778 owntype = operator.type.getReturnType();
2779 int opc = chk.checkOperator(tree.lhs.pos(),
2780 (OperatorSymbol)operator,
2781 tree.getTag(),
2782 left,
2783 right);
2785 // If both arguments are constants, fold them.
2786 if (left.constValue() != null && right.constValue() != null) {
2787 Type ctype = cfolder.fold2(opc, left, right);
2788 if (ctype != null) {
2789 owntype = cfolder.coerce(ctype, owntype);
2791 // Remove constant types from arguments to
2792 // conserve space. The parser will fold concatenations
2793 // of string literals; the code here also
2794 // gets rid of intermediate results when some of the
2795 // operands are constant identifiers.
2796 if (tree.lhs.type.tsym == syms.stringType.tsym) {
2797 tree.lhs.type = syms.stringType;
2798 }
2799 if (tree.rhs.type.tsym == syms.stringType.tsym) {
2800 tree.rhs.type = syms.stringType;
2801 }
2802 }
2803 }
2805 // Check that argument types of a reference ==, != are
2806 // castable to each other, (JLS???).
2807 if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
2808 if (!types.isCastable(left, right, new Warner(tree.pos()))) {
2809 log.error(tree.pos(), "incomparable.types", left, right);
2810 }
2811 }
2813 chk.checkDivZero(tree.rhs.pos(), operator, right);
2814 }
2815 result = check(tree, owntype, VAL, resultInfo);
2816 }
2818 public void visitTypeCast(final JCTypeCast tree) {
2819 Type clazztype = attribType(tree.clazz, env);
2820 chk.validate(tree.clazz, env, false);
2821 //a fresh environment is required for 292 inference to work properly ---
2822 //see Infer.instantiatePolymorphicSignatureInstance()
2823 Env<AttrContext> localEnv = env.dup(tree);
2824 //should we propagate the target type?
2825 final ResultInfo castInfo;
2826 final boolean isPoly = TreeInfo.isPoly(tree.expr, tree);
2827 if (isPoly) {
2828 //expression is a poly - we need to propagate target type info
2829 castInfo = new ResultInfo(VAL, clazztype, new Check.NestedCheckContext(resultInfo.checkContext) {
2830 @Override
2831 public boolean compatible(Type found, Type req, Warner warn) {
2832 return types.isCastable(found, req, warn);
2833 }
2834 });
2835 } else {
2836 //standalone cast - target-type info is not propagated
2837 castInfo = unknownExprInfo;
2838 }
2839 Type exprtype = attribTree(tree.expr, localEnv, castInfo);
2840 Type owntype = isPoly ? clazztype : chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
2841 if (exprtype.constValue() != null)
2842 owntype = cfolder.coerce(exprtype, owntype);
2843 result = check(tree, capture(owntype), VAL, resultInfo);
2844 if (!isPoly)
2845 chk.checkRedundantCast(localEnv, tree);
2846 }
2848 public void visitTypeTest(JCInstanceOf tree) {
2849 Type exprtype = chk.checkNullOrRefType(
2850 tree.expr.pos(), attribExpr(tree.expr, env));
2851 Type clazztype = chk.checkReifiableReferenceType(
2852 tree.clazz.pos(), attribType(tree.clazz, env));
2853 chk.validate(tree.clazz, env, false);
2854 chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
2855 result = check(tree, syms.booleanType, VAL, resultInfo);
2856 }
2858 public void visitIndexed(JCArrayAccess tree) {
2859 Type owntype = types.createErrorType(tree.type);
2860 Type atype = attribExpr(tree.indexed, env);
2861 attribExpr(tree.index, env, syms.intType);
2862 if (types.isArray(atype))
2863 owntype = types.elemtype(atype);
2864 else if (!atype.hasTag(ERROR))
2865 log.error(tree.pos(), "array.req.but.found", atype);
2866 if ((pkind() & VAR) == 0) owntype = capture(owntype);
2867 result = check(tree, owntype, VAR, resultInfo);
2868 }
2870 public void visitIdent(JCIdent tree) {
2871 Symbol sym;
2873 // Find symbol
2874 if (pt().hasTag(METHOD) || pt().hasTag(FORALL)) {
2875 // If we are looking for a method, the prototype `pt' will be a
2876 // method type with the type of the call's arguments as parameters.
2877 env.info.pendingResolutionPhase = null;
2878 sym = rs.resolveMethod(tree.pos(), env, tree.name, pt().getParameterTypes(), pt().getTypeArguments());
2879 } else if (tree.sym != null && tree.sym.kind != VAR) {
2880 sym = tree.sym;
2881 } else {
2882 sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind());
2883 }
2884 tree.sym = sym;
2886 // (1) Also find the environment current for the class where
2887 // sym is defined (`symEnv').
2888 // Only for pre-tiger versions (1.4 and earlier):
2889 // (2) Also determine whether we access symbol out of an anonymous
2890 // class in a this or super call. This is illegal for instance
2891 // members since such classes don't carry a this$n link.
2892 // (`noOuterThisPath').
2893 Env<AttrContext> symEnv = env;
2894 boolean noOuterThisPath = false;
2895 if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
2896 (sym.kind & (VAR | MTH | TYP)) != 0 &&
2897 sym.owner.kind == TYP &&
2898 tree.name != names._this && tree.name != names._super) {
2900 // Find environment in which identifier is defined.
2901 while (symEnv.outer != null &&
2902 !sym.isMemberOf(symEnv.enclClass.sym, types)) {
2903 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
2904 noOuterThisPath = !allowAnonOuterThis;
2905 symEnv = symEnv.outer;
2906 }
2907 }
2909 // If symbol is a variable, ...
2910 if (sym.kind == VAR) {
2911 VarSymbol v = (VarSymbol)sym;
2913 // ..., evaluate its initializer, if it has one, and check for
2914 // illegal forward reference.
2915 checkInit(tree, env, v, false);
2917 // If we are expecting a variable (as opposed to a value), check
2918 // that the variable is assignable in the current environment.
2919 if (pkind() == VAR)
2920 checkAssignable(tree.pos(), v, null, env);
2921 }
2923 // In a constructor body,
2924 // if symbol is a field or instance method, check that it is
2925 // not accessed before the supertype constructor is called.
2926 if ((symEnv.info.isSelfCall || noOuterThisPath) &&
2927 (sym.kind & (VAR | MTH)) != 0 &&
2928 sym.owner.kind == TYP &&
2929 (sym.flags() & STATIC) == 0) {
2930 chk.earlyRefError(tree.pos(), sym.kind == VAR ? sym : thisSym(tree.pos(), env));
2931 }
2932 Env<AttrContext> env1 = env;
2933 if (sym.kind != ERR && sym.kind != TYP && sym.owner != null && sym.owner != env1.enclClass.sym) {
2934 // If the found symbol is inaccessible, then it is
2935 // accessed through an enclosing instance. Locate this
2936 // enclosing instance:
2937 while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
2938 env1 = env1.outer;
2939 }
2940 result = checkId(tree, env1.enclClass.sym.type, sym, env, resultInfo);
2941 }
2943 public void visitSelect(JCFieldAccess tree) {
2944 // Determine the expected kind of the qualifier expression.
2945 int skind = 0;
2946 if (tree.name == names._this || tree.name == names._super ||
2947 tree.name == names._class)
2948 {
2949 skind = TYP;
2950 } else {
2951 if ((pkind() & PCK) != 0) skind = skind | PCK;
2952 if ((pkind() & TYP) != 0) skind = skind | TYP | PCK;
2953 if ((pkind() & (VAL | MTH)) != 0) skind = skind | VAL | TYP;
2954 }
2956 // Attribute the qualifier expression, and determine its symbol (if any).
2957 Type site = attribTree(tree.selected, env, new ResultInfo(skind, Infer.anyPoly));
2958 if ((pkind() & (PCK | TYP)) == 0)
2959 site = capture(site); // Capture field access
2961 // don't allow T.class T[].class, etc
2962 if (skind == TYP) {
2963 Type elt = site;
2964 while (elt.hasTag(ARRAY))
2965 elt = ((ArrayType)elt).elemtype;
2966 if (elt.hasTag(TYPEVAR)) {
2967 log.error(tree.pos(), "type.var.cant.be.deref");
2968 result = types.createErrorType(tree.type);
2969 return;
2970 }
2971 }
2973 // If qualifier symbol is a type or `super', assert `selectSuper'
2974 // for the selection. This is relevant for determining whether
2975 // protected symbols are accessible.
2976 Symbol sitesym = TreeInfo.symbol(tree.selected);
2977 boolean selectSuperPrev = env.info.selectSuper;
2978 env.info.selectSuper =
2979 sitesym != null &&
2980 sitesym.name == names._super;
2982 // Determine the symbol represented by the selection.
2983 env.info.pendingResolutionPhase = null;
2984 Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
2985 if (sym.exists() && !isType(sym) && (pkind() & (PCK | TYP)) != 0) {
2986 site = capture(site);
2987 sym = selectSym(tree, sitesym, site, env, resultInfo);
2988 }
2989 boolean varArgs = env.info.lastResolveVarargs();
2990 tree.sym = sym;
2992 if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) {
2993 while (site.hasTag(TYPEVAR)) site = site.getUpperBound();
2994 site = capture(site);
2995 }
2997 // If that symbol is a variable, ...
2998 if (sym.kind == VAR) {
2999 VarSymbol v = (VarSymbol)sym;
3001 // ..., evaluate its initializer, if it has one, and check for
3002 // illegal forward reference.
3003 checkInit(tree, env, v, true);
3005 // If we are expecting a variable (as opposed to a value), check
3006 // that the variable is assignable in the current environment.
3007 if (pkind() == VAR)
3008 checkAssignable(tree.pos(), v, tree.selected, env);
3009 }
3011 if (sitesym != null &&
3012 sitesym.kind == VAR &&
3013 ((VarSymbol)sitesym).isResourceVariable() &&
3014 sym.kind == MTH &&
3015 sym.name.equals(names.close) &&
3016 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) &&
3017 env.info.lint.isEnabled(LintCategory.TRY)) {
3018 log.warning(LintCategory.TRY, tree, "try.explicit.close.call");
3019 }
3021 // Disallow selecting a type from an expression
3022 if (isType(sym) && (sitesym==null || (sitesym.kind&(TYP|PCK)) == 0)) {
3023 tree.type = check(tree.selected, pt(),
3024 sitesym == null ? VAL : sitesym.kind, new ResultInfo(TYP|PCK, pt()));
3025 }
3027 if (isType(sitesym)) {
3028 if (sym.name == names._this) {
3029 // If `C' is the currently compiled class, check that
3030 // C.this' does not appear in a call to a super(...)
3031 if (env.info.isSelfCall &&
3032 site.tsym == env.enclClass.sym) {
3033 chk.earlyRefError(tree.pos(), sym);
3034 }
3035 } else {
3036 // Check if type-qualified fields or methods are static (JLS)
3037 if ((sym.flags() & STATIC) == 0 &&
3038 !env.next.tree.hasTag(REFERENCE) &&
3039 sym.name != names._super &&
3040 (sym.kind == VAR || sym.kind == MTH)) {
3041 rs.accessBase(rs.new StaticError(sym),
3042 tree.pos(), site, sym.name, true);
3043 }
3044 }
3045 } else if (sym.kind != ERR && (sym.flags() & STATIC) != 0 && sym.name != names._class) {
3046 // If the qualified item is not a type and the selected item is static, report
3047 // a warning. Make allowance for the class of an array type e.g. Object[].class)
3048 chk.warnStatic(tree, "static.not.qualified.by.type", Kinds.kindName(sym.kind), sym.owner);
3049 }
3051 // If we are selecting an instance member via a `super', ...
3052 if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
3054 // Check that super-qualified symbols are not abstract (JLS)
3055 rs.checkNonAbstract(tree.pos(), sym);
3057 if (site.isRaw()) {
3058 // Determine argument types for site.
3059 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
3060 if (site1 != null) site = site1;
3061 }
3062 }
3064 env.info.selectSuper = selectSuperPrev;
3065 result = checkId(tree, site, sym, env, resultInfo);
3066 }
3067 //where
3068 /** Determine symbol referenced by a Select expression,
3069 *
3070 * @param tree The select tree.
3071 * @param site The type of the selected expression,
3072 * @param env The current environment.
3073 * @param resultInfo The current result.
3074 */
3075 private Symbol selectSym(JCFieldAccess tree,
3076 Symbol location,
3077 Type site,
3078 Env<AttrContext> env,
3079 ResultInfo resultInfo) {
3080 DiagnosticPosition pos = tree.pos();
3081 Name name = tree.name;
3082 switch (site.getTag()) {
3083 case PACKAGE:
3084 return rs.accessBase(
3085 rs.findIdentInPackage(env, site.tsym, name, resultInfo.pkind),
3086 pos, location, site, name, true);
3087 case ARRAY:
3088 case CLASS:
3089 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) {
3090 return rs.resolveQualifiedMethod(
3091 pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
3092 } else if (name == names._this || name == names._super) {
3093 return rs.resolveSelf(pos, env, site.tsym, name);
3094 } else if (name == names._class) {
3095 // In this case, we have already made sure in
3096 // visitSelect that qualifier expression is a type.
3097 Type t = syms.classType;
3098 List<Type> typeargs = allowGenerics
3099 ? List.of(types.erasure(site))
3100 : List.<Type>nil();
3101 t = new ClassType(t.getEnclosingType(), typeargs, t.tsym);
3102 return new VarSymbol(
3103 STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
3104 } else {
3105 // We are seeing a plain identifier as selector.
3106 Symbol sym = rs.findIdentInType(env, site, name, resultInfo.pkind);
3107 if ((resultInfo.pkind & ERRONEOUS) == 0)
3108 sym = rs.accessBase(sym, pos, location, site, name, true);
3109 return sym;
3110 }
3111 case WILDCARD:
3112 throw new AssertionError(tree);
3113 case TYPEVAR:
3114 // Normally, site.getUpperBound() shouldn't be null.
3115 // It should only happen during memberEnter/attribBase
3116 // when determining the super type which *must* beac
3117 // done before attributing the type variables. In
3118 // other words, we are seeing this illegal program:
3119 // class B<T> extends A<T.foo> {}
3120 Symbol sym = (site.getUpperBound() != null)
3121 ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
3122 : null;
3123 if (sym == null) {
3124 log.error(pos, "type.var.cant.be.deref");
3125 return syms.errSymbol;
3126 } else {
3127 Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
3128 rs.new AccessError(env, site, sym) :
3129 sym;
3130 rs.accessBase(sym2, pos, location, site, name, true);
3131 return sym;
3132 }
3133 case ERROR:
3134 // preserve identifier names through errors
3135 return types.createErrorType(name, site.tsym, site).tsym;
3136 default:
3137 // The qualifier expression is of a primitive type -- only
3138 // .class is allowed for these.
3139 if (name == names._class) {
3140 // In this case, we have already made sure in Select that
3141 // qualifier expression is a type.
3142 Type t = syms.classType;
3143 Type arg = types.boxedClass(site).type;
3144 t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym);
3145 return new VarSymbol(
3146 STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
3147 } else {
3148 log.error(pos, "cant.deref", site);
3149 return syms.errSymbol;
3150 }
3151 }
3152 }
3154 /** Determine type of identifier or select expression and check that
3155 * (1) the referenced symbol is not deprecated
3156 * (2) the symbol's type is safe (@see checkSafe)
3157 * (3) if symbol is a variable, check that its type and kind are
3158 * compatible with the prototype and protokind.
3159 * (4) if symbol is an instance field of a raw type,
3160 * which is being assigned to, issue an unchecked warning if its
3161 * type changes under erasure.
3162 * (5) if symbol is an instance method of a raw type, issue an
3163 * unchecked warning if its argument types change under erasure.
3164 * If checks succeed:
3165 * If symbol is a constant, return its constant type
3166 * else if symbol is a method, return its result type
3167 * otherwise return its type.
3168 * Otherwise return errType.
3169 *
3170 * @param tree The syntax tree representing the identifier
3171 * @param site If this is a select, the type of the selected
3172 * expression, otherwise the type of the current class.
3173 * @param sym The symbol representing the identifier.
3174 * @param env The current environment.
3175 * @param resultInfo The expected result
3176 */
3177 Type checkId(JCTree tree,
3178 Type site,
3179 Symbol sym,
3180 Env<AttrContext> env,
3181 ResultInfo resultInfo) {
3182 return (resultInfo.pt.hasTag(FORALL) || resultInfo.pt.hasTag(METHOD)) ?
3183 checkMethodId(tree, site, sym, env, resultInfo) :
3184 checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
3185 }
3187 Type checkMethodId(JCTree tree,
3188 Type site,
3189 Symbol sym,
3190 Env<AttrContext> env,
3191 ResultInfo resultInfo) {
3192 boolean isPolymorhicSignature =
3193 sym.kind == MTH && ((MethodSymbol)sym.baseSymbol()).isSignaturePolymorphic(types);
3194 return isPolymorhicSignature ?
3195 checkSigPolyMethodId(tree, site, sym, env, resultInfo) :
3196 checkMethodIdInternal(tree, site, sym, env, resultInfo);
3197 }
3199 Type checkSigPolyMethodId(JCTree tree,
3200 Type site,
3201 Symbol sym,
3202 Env<AttrContext> env,
3203 ResultInfo resultInfo) {
3204 //recover original symbol for signature polymorphic methods
3205 checkMethodIdInternal(tree, site, sym.baseSymbol(), env, resultInfo);
3206 env.info.pendingResolutionPhase = Resolve.MethodResolutionPhase.BASIC;
3207 return sym.type;
3208 }
3210 Type checkMethodIdInternal(JCTree tree,
3211 Type site,
3212 Symbol sym,
3213 Env<AttrContext> env,
3214 ResultInfo resultInfo) {
3215 Type pt = resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, sym, env.info.pendingResolutionPhase));
3216 Type owntype = checkIdInternal(tree, site, sym, pt, env, resultInfo);
3217 resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
3218 return owntype;
3219 }
3221 Type checkIdInternal(JCTree tree,
3222 Type site,
3223 Symbol sym,
3224 Type pt,
3225 Env<AttrContext> env,
3226 ResultInfo resultInfo) {
3227 if (pt.isErroneous()) {
3228 return types.createErrorType(site);
3229 }
3230 Type owntype; // The computed type of this identifier occurrence.
3231 switch (sym.kind) {
3232 case TYP:
3233 // For types, the computed type equals the symbol's type,
3234 // except for two situations:
3235 owntype = sym.type;
3236 if (owntype.hasTag(CLASS)) {
3237 chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym);
3238 Type ownOuter = owntype.getEnclosingType();
3240 // (a) If the symbol's type is parameterized, erase it
3241 // because no type parameters were given.
3242 // We recover generic outer type later in visitTypeApply.
3243 if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
3244 owntype = types.erasure(owntype);
3245 }
3247 // (b) If the symbol's type is an inner class, then
3248 // we have to interpret its outer type as a superclass
3249 // of the site type. Example:
3250 //
3251 // class Tree<A> { class Visitor { ... } }
3252 // class PointTree extends Tree<Point> { ... }
3253 // ...PointTree.Visitor...
3254 //
3255 // Then the type of the last expression above is
3256 // Tree<Point>.Visitor.
3257 else if (ownOuter.hasTag(CLASS) && site != ownOuter) {
3258 Type normOuter = site;
3259 if (normOuter.hasTag(CLASS))
3260 normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
3261 if (normOuter == null) // perhaps from an import
3262 normOuter = types.erasure(ownOuter);
3263 if (normOuter != ownOuter)
3264 owntype = new ClassType(
3265 normOuter, List.<Type>nil(), owntype.tsym);
3266 }
3267 }
3268 break;
3269 case VAR:
3270 VarSymbol v = (VarSymbol)sym;
3271 // Test (4): if symbol is an instance field of a raw type,
3272 // which is being assigned to, issue an unchecked warning if
3273 // its type changes under erasure.
3274 if (allowGenerics &&
3275 resultInfo.pkind == VAR &&
3276 v.owner.kind == TYP &&
3277 (v.flags() & STATIC) == 0 &&
3278 (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
3279 Type s = types.asOuterSuper(site, v.owner);
3280 if (s != null &&
3281 s.isRaw() &&
3282 !types.isSameType(v.type, v.erasure(types))) {
3283 chk.warnUnchecked(tree.pos(),
3284 "unchecked.assign.to.var",
3285 v, s);
3286 }
3287 }
3288 // The computed type of a variable is the type of the
3289 // variable symbol, taken as a member of the site type.
3290 owntype = (sym.owner.kind == TYP &&
3291 sym.name != names._this && sym.name != names._super)
3292 ? types.memberType(site, sym)
3293 : sym.type;
3295 // If the variable is a constant, record constant value in
3296 // computed type.
3297 if (v.getConstValue() != null && isStaticReference(tree))
3298 owntype = owntype.constType(v.getConstValue());
3300 if (resultInfo.pkind == VAL) {
3301 owntype = capture(owntype); // capture "names as expressions"
3302 }
3303 break;
3304 case MTH: {
3305 owntype = checkMethod(site, sym,
3306 new ResultInfo(VAL, resultInfo.pt.getReturnType(), resultInfo.checkContext),
3307 env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(),
3308 resultInfo.pt.getTypeArguments());
3309 break;
3310 }
3311 case PCK: case ERR:
3312 owntype = sym.type;
3313 break;
3314 default:
3315 throw new AssertionError("unexpected kind: " + sym.kind +
3316 " in tree " + tree);
3317 }
3319 // Test (1): emit a `deprecation' warning if symbol is deprecated.
3320 // (for constructors, the error was given when the constructor was
3321 // resolved)
3323 if (sym.name != names.init) {
3324 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym);
3325 chk.checkSunAPI(tree.pos(), sym);
3326 }
3328 // Test (3): if symbol is a variable, check that its type and
3329 // kind are compatible with the prototype and protokind.
3330 return check(tree, owntype, sym.kind, resultInfo);
3331 }
3333 /** Check that variable is initialized and evaluate the variable's
3334 * initializer, if not yet done. Also check that variable is not
3335 * referenced before it is defined.
3336 * @param tree The tree making up the variable reference.
3337 * @param env The current environment.
3338 * @param v The variable's symbol.
3339 */
3340 private void checkInit(JCTree tree,
3341 Env<AttrContext> env,
3342 VarSymbol v,
3343 boolean onlyWarning) {
3344 // System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " +
3345 // tree.pos + " " + v.pos + " " +
3346 // Resolve.isStatic(env));//DEBUG
3348 // A forward reference is diagnosed if the declaration position
3349 // of the variable is greater than the current tree position
3350 // and the tree and variable definition occur in the same class
3351 // definition. Note that writes don't count as references.
3352 // This check applies only to class and instance
3353 // variables. Local variables follow different scope rules,
3354 // and are subject to definite assignment checking.
3355 if ((env.info.enclVar == v || v.pos > tree.pos) &&
3356 v.owner.kind == TYP &&
3357 canOwnInitializer(owner(env)) &&
3358 v.owner == env.info.scope.owner.enclClass() &&
3359 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
3360 (!env.tree.hasTag(ASSIGN) ||
3361 TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
3362 String suffix = (env.info.enclVar == v) ?
3363 "self.ref" : "forward.ref";
3364 if (!onlyWarning || isStaticEnumField(v)) {
3365 log.error(tree.pos(), "illegal." + suffix);
3366 } else if (useBeforeDeclarationWarning) {
3367 log.warning(tree.pos(), suffix, v);
3368 }
3369 }
3371 v.getConstValue(); // ensure initializer is evaluated
3373 checkEnumInitializer(tree, env, v);
3374 }
3376 /**
3377 * Check for illegal references to static members of enum. In
3378 * an enum type, constructors and initializers may not
3379 * reference its static members unless they are constant.
3380 *
3381 * @param tree The tree making up the variable reference.
3382 * @param env The current environment.
3383 * @param v The variable's symbol.
3384 * @jls section 8.9 Enums
3385 */
3386 private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
3387 // JLS:
3388 //
3389 // "It is a compile-time error to reference a static field
3390 // of an enum type that is not a compile-time constant
3391 // (15.28) from constructors, instance initializer blocks,
3392 // or instance variable initializer expressions of that
3393 // type. It is a compile-time error for the constructors,
3394 // instance initializer blocks, or instance variable
3395 // initializer expressions of an enum constant e to refer
3396 // to itself or to an enum constant of the same type that
3397 // is declared to the right of e."
3398 if (isStaticEnumField(v)) {
3399 ClassSymbol enclClass = env.info.scope.owner.enclClass();
3401 if (enclClass == null || enclClass.owner == null)
3402 return;
3404 // See if the enclosing class is the enum (or a
3405 // subclass thereof) declaring v. If not, this
3406 // reference is OK.
3407 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
3408 return;
3410 // If the reference isn't from an initializer, then
3411 // the reference is OK.
3412 if (!Resolve.isInitializer(env))
3413 return;
3415 log.error(tree.pos(), "illegal.enum.static.ref");
3416 }
3417 }
3419 /** Is the given symbol a static, non-constant field of an Enum?
3420 * Note: enum literals should not be regarded as such
3421 */
3422 private boolean isStaticEnumField(VarSymbol v) {
3423 return Flags.isEnum(v.owner) &&
3424 Flags.isStatic(v) &&
3425 !Flags.isConstant(v) &&
3426 v.name != names._class;
3427 }
3429 /** Can the given symbol be the owner of code which forms part
3430 * if class initialization? This is the case if the symbol is
3431 * a type or field, or if the symbol is the synthetic method.
3432 * owning a block.
3433 */
3434 private boolean canOwnInitializer(Symbol sym) {
3435 return
3436 (sym.kind & (VAR | TYP)) != 0 ||
3437 (sym.kind == MTH && (sym.flags() & BLOCK) != 0);
3438 }
3440 Warner noteWarner = new Warner();
3442 /**
3443 * Check that method arguments conform to its instantiation.
3444 **/
3445 public Type checkMethod(Type site,
3446 Symbol sym,
3447 ResultInfo resultInfo,
3448 Env<AttrContext> env,
3449 final List<JCExpression> argtrees,
3450 List<Type> argtypes,
3451 List<Type> typeargtypes) {
3452 // Test (5): if symbol is an instance method of a raw type, issue
3453 // an unchecked warning if its argument types change under erasure.
3454 if (allowGenerics &&
3455 (sym.flags() & STATIC) == 0 &&
3456 (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
3457 Type s = types.asOuterSuper(site, sym.owner);
3458 if (s != null && s.isRaw() &&
3459 !types.isSameTypes(sym.type.getParameterTypes(),
3460 sym.erasure(types).getParameterTypes())) {
3461 chk.warnUnchecked(env.tree.pos(),
3462 "unchecked.call.mbr.of.raw.type",
3463 sym, s);
3464 }
3465 }
3467 if (env.info.defaultSuperCallSite != null) {
3468 for (Type sup : types.interfaces(env.enclClass.type).prepend(types.supertype((env.enclClass.type)))) {
3469 if (!sup.tsym.isSubClass(sym.enclClass(), types) ||
3470 types.isSameType(sup, env.info.defaultSuperCallSite)) continue;
3471 List<MethodSymbol> icand_sup =
3472 types.interfaceCandidates(sup, (MethodSymbol)sym);
3473 if (icand_sup.nonEmpty() &&
3474 icand_sup.head != sym &&
3475 icand_sup.head.overrides(sym, icand_sup.head.enclClass(), types, true)) {
3476 log.error(env.tree.pos(), "illegal.default.super.call", env.info.defaultSuperCallSite,
3477 diags.fragment("overridden.default", sym, sup));
3478 break;
3479 }
3480 }
3481 env.info.defaultSuperCallSite = null;
3482 }
3484 // Compute the identifier's instantiated type.
3485 // For methods, we need to compute the instance type by
3486 // Resolve.instantiate from the symbol's type as well as
3487 // any type arguments and value arguments.
3488 noteWarner.clear();
3489 try {
3490 Type owntype = rs.checkMethod(
3491 env,
3492 site,
3493 sym,
3494 resultInfo,
3495 argtypes,
3496 typeargtypes,
3497 noteWarner);
3499 return chk.checkMethod(owntype, sym, env, argtrees, argtypes, env.info.lastResolveVarargs(),
3500 noteWarner.hasNonSilentLint(LintCategory.UNCHECKED));
3501 } catch (Infer.InferenceException ex) {
3502 //invalid target type - propagate exception outwards or report error
3503 //depending on the current check context
3504 resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic());
3505 return types.createErrorType(site);
3506 } catch (Resolve.InapplicableMethodException ex) {
3507 Assert.error(ex.getDiagnostic().getMessage(Locale.getDefault()));
3508 return null;
3509 }
3510 }
3512 public void visitLiteral(JCLiteral tree) {
3513 result = check(
3514 tree, litType(tree.typetag).constType(tree.value), VAL, resultInfo);
3515 }
3516 //where
3517 /** Return the type of a literal with given type tag.
3518 */
3519 Type litType(TypeTag tag) {
3520 return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()];
3521 }
3523 public void visitTypeIdent(JCPrimitiveTypeTree tree) {
3524 result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], TYP, resultInfo);
3525 }
3527 public void visitTypeArray(JCArrayTypeTree tree) {
3528 Type etype = attribType(tree.elemtype, env);
3529 Type type = new ArrayType(etype, syms.arrayClass);
3530 result = check(tree, type, TYP, resultInfo);
3531 }
3533 /** Visitor method for parameterized types.
3534 * Bound checking is left until later, since types are attributed
3535 * before supertype structure is completely known
3536 */
3537 public void visitTypeApply(JCTypeApply tree) {
3538 Type owntype = types.createErrorType(tree.type);
3540 // Attribute functor part of application and make sure it's a class.
3541 Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
3543 // Attribute type parameters
3544 List<Type> actuals = attribTypes(tree.arguments, env);
3546 if (clazztype.hasTag(CLASS)) {
3547 List<Type> formals = clazztype.tsym.type.getTypeArguments();
3548 if (actuals.isEmpty()) //diamond
3549 actuals = formals;
3551 if (actuals.length() == formals.length()) {
3552 List<Type> a = actuals;
3553 List<Type> f = formals;
3554 while (a.nonEmpty()) {
3555 a.head = a.head.withTypeVar(f.head);
3556 a = a.tail;
3557 f = f.tail;
3558 }
3559 // Compute the proper generic outer
3560 Type clazzOuter = clazztype.getEnclosingType();
3561 if (clazzOuter.hasTag(CLASS)) {
3562 Type site;
3563 JCExpression clazz = TreeInfo.typeIn(tree.clazz);
3564 if (clazz.hasTag(IDENT)) {
3565 site = env.enclClass.sym.type;
3566 } else if (clazz.hasTag(SELECT)) {
3567 site = ((JCFieldAccess) clazz).selected.type;
3568 } else throw new AssertionError(""+tree);
3569 if (clazzOuter.hasTag(CLASS) && site != clazzOuter) {
3570 if (site.hasTag(CLASS))
3571 site = types.asOuterSuper(site, clazzOuter.tsym);
3572 if (site == null)
3573 site = types.erasure(clazzOuter);
3574 clazzOuter = site;
3575 }
3576 }
3577 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym);
3578 } else {
3579 if (formals.length() != 0) {
3580 log.error(tree.pos(), "wrong.number.type.args",
3581 Integer.toString(formals.length()));
3582 } else {
3583 log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym);
3584 }
3585 owntype = types.createErrorType(tree.type);
3586 }
3587 }
3588 result = check(tree, owntype, TYP, resultInfo);
3589 }
3591 public void visitTypeUnion(JCTypeUnion tree) {
3592 ListBuffer<Type> multicatchTypes = ListBuffer.lb();
3593 ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
3594 for (JCExpression typeTree : tree.alternatives) {
3595 Type ctype = attribType(typeTree, env);
3596 ctype = chk.checkType(typeTree.pos(),
3597 chk.checkClassType(typeTree.pos(), ctype),
3598 syms.throwableType);
3599 if (!ctype.isErroneous()) {
3600 //check that alternatives of a union type are pairwise
3601 //unrelated w.r.t. subtyping
3602 if (chk.intersects(ctype, multicatchTypes.toList())) {
3603 for (Type t : multicatchTypes) {
3604 boolean sub = types.isSubtype(ctype, t);
3605 boolean sup = types.isSubtype(t, ctype);
3606 if (sub || sup) {
3607 //assume 'a' <: 'b'
3608 Type a = sub ? ctype : t;
3609 Type b = sub ? t : ctype;
3610 log.error(typeTree.pos(), "multicatch.types.must.be.disjoint", a, b);
3611 }
3612 }
3613 }
3614 multicatchTypes.append(ctype);
3615 if (all_multicatchTypes != null)
3616 all_multicatchTypes.append(ctype);
3617 } else {
3618 if (all_multicatchTypes == null) {
3619 all_multicatchTypes = ListBuffer.lb();
3620 all_multicatchTypes.appendList(multicatchTypes);
3621 }
3622 all_multicatchTypes.append(ctype);
3623 }
3624 }
3625 Type t = check(tree, types.lub(multicatchTypes.toList()), TYP, resultInfo);
3626 if (t.hasTag(CLASS)) {
3627 List<Type> alternatives =
3628 ((all_multicatchTypes == null) ? multicatchTypes : all_multicatchTypes).toList();
3629 t = new UnionClassType((ClassType) t, alternatives);
3630 }
3631 tree.type = result = t;
3632 }
3634 public void visitTypeIntersection(JCTypeIntersection tree) {
3635 attribTypes(tree.bounds, env);
3636 tree.type = result = checkIntersection(tree, tree.bounds);
3637 }
3639 public void visitTypeParameter(JCTypeParameter tree) {
3640 TypeVar typeVar = (TypeVar)tree.type;
3641 if (!typeVar.bound.isErroneous()) {
3642 //fixup type-parameter bound computed in 'attribTypeVariables'
3643 typeVar.bound = checkIntersection(tree, tree.bounds);
3644 }
3645 }
3647 Type checkIntersection(JCTree tree, List<JCExpression> bounds) {
3648 Set<Type> boundSet = new HashSet<Type>();
3649 if (bounds.nonEmpty()) {
3650 // accept class or interface or typevar as first bound.
3651 bounds.head.type = checkBase(bounds.head.type, bounds.head, env, false, false, false);
3652 boundSet.add(types.erasure(bounds.head.type));
3653 if (bounds.head.type.isErroneous()) {
3654 return bounds.head.type;
3655 }
3656 else if (bounds.head.type.hasTag(TYPEVAR)) {
3657 // if first bound was a typevar, do not accept further bounds.
3658 if (bounds.tail.nonEmpty()) {
3659 log.error(bounds.tail.head.pos(),
3660 "type.var.may.not.be.followed.by.other.bounds");
3661 return bounds.head.type;
3662 }
3663 } else {
3664 // if first bound was a class or interface, accept only interfaces
3665 // as further bounds.
3666 for (JCExpression bound : bounds.tail) {
3667 bound.type = checkBase(bound.type, bound, env, false, true, false);
3668 if (bound.type.isErroneous()) {
3669 bounds = List.of(bound);
3670 }
3671 else if (bound.type.hasTag(CLASS)) {
3672 chk.checkNotRepeated(bound.pos(), types.erasure(bound.type), boundSet);
3673 }
3674 }
3675 }
3676 }
3678 if (bounds.length() == 0) {
3679 return syms.objectType;
3680 } else if (bounds.length() == 1) {
3681 return bounds.head.type;
3682 } else {
3683 Type owntype = types.makeCompoundType(TreeInfo.types(bounds));
3684 if (tree.hasTag(TYPEINTERSECTION)) {
3685 ((IntersectionClassType)owntype).intersectionKind =
3686 IntersectionClassType.IntersectionKind.EXPLICIT;
3687 }
3688 // ... the variable's bound is a class type flagged COMPOUND
3689 // (see comment for TypeVar.bound).
3690 // In this case, generate a class tree that represents the
3691 // bound class, ...
3692 JCExpression extending;
3693 List<JCExpression> implementing;
3694 if (!bounds.head.type.isInterface()) {
3695 extending = bounds.head;
3696 implementing = bounds.tail;
3697 } else {
3698 extending = null;
3699 implementing = bounds;
3700 }
3701 JCClassDecl cd = make.at(tree).ClassDef(
3702 make.Modifiers(PUBLIC | ABSTRACT),
3703 names.empty, List.<JCTypeParameter>nil(),
3704 extending, implementing, List.<JCTree>nil());
3706 ClassSymbol c = (ClassSymbol)owntype.tsym;
3707 Assert.check((c.flags() & COMPOUND) != 0);
3708 cd.sym = c;
3709 c.sourcefile = env.toplevel.sourcefile;
3711 // ... and attribute the bound class
3712 c.flags_field |= UNATTRIBUTED;
3713 Env<AttrContext> cenv = enter.classEnv(cd, env);
3714 enter.typeEnvs.put(c, cenv);
3715 attribClass(c);
3716 return owntype;
3717 }
3718 }
3720 public void visitWildcard(JCWildcard tree) {
3721 //- System.err.println("visitWildcard("+tree+");");//DEBUG
3722 Type type = (tree.kind.kind == BoundKind.UNBOUND)
3723 ? syms.objectType
3724 : attribType(tree.inner, env);
3725 result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
3726 tree.kind.kind,
3727 syms.boundClass),
3728 TYP, resultInfo);
3729 }
3731 public void visitAnnotation(JCAnnotation tree) {
3732 log.error(tree.pos(), "annotation.not.valid.for.type", pt());
3733 result = tree.type = syms.errType;
3734 }
3736 public void visitErroneous(JCErroneous tree) {
3737 if (tree.errs != null)
3738 for (JCTree err : tree.errs)
3739 attribTree(err, env, new ResultInfo(ERR, pt()));
3740 result = tree.type = syms.errType;
3741 }
3743 /** Default visitor method for all other trees.
3744 */
3745 public void visitTree(JCTree tree) {
3746 throw new AssertionError();
3747 }
3749 /**
3750 * Attribute an env for either a top level tree or class declaration.
3751 */
3752 public void attrib(Env<AttrContext> env) {
3753 if (env.tree.hasTag(TOPLEVEL))
3754 attribTopLevel(env);
3755 else
3756 attribClass(env.tree.pos(), env.enclClass.sym);
3757 }
3759 /**
3760 * Attribute a top level tree. These trees are encountered when the
3761 * package declaration has annotations.
3762 */
3763 public void attribTopLevel(Env<AttrContext> env) {
3764 JCCompilationUnit toplevel = env.toplevel;
3765 try {
3766 annotate.flush();
3767 chk.validateAnnotations(toplevel.packageAnnotations, toplevel.packge);
3768 } catch (CompletionFailure ex) {
3769 chk.completionError(toplevel.pos(), ex);
3770 }
3771 }
3773 /** Main method: attribute class definition associated with given class symbol.
3774 * reporting completion failures at the given position.
3775 * @param pos The source position at which completion errors are to be
3776 * reported.
3777 * @param c The class symbol whose definition will be attributed.
3778 */
3779 public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
3780 try {
3781 annotate.flush();
3782 attribClass(c);
3783 } catch (CompletionFailure ex) {
3784 chk.completionError(pos, ex);
3785 }
3786 }
3788 /** Attribute class definition associated with given class symbol.
3789 * @param c The class symbol whose definition will be attributed.
3790 */
3791 void attribClass(ClassSymbol c) throws CompletionFailure {
3792 if (c.type.hasTag(ERROR)) return;
3794 // Check for cycles in the inheritance graph, which can arise from
3795 // ill-formed class files.
3796 chk.checkNonCyclic(null, c.type);
3798 Type st = types.supertype(c.type);
3799 if ((c.flags_field & Flags.COMPOUND) == 0) {
3800 // First, attribute superclass.
3801 if (st.hasTag(CLASS))
3802 attribClass((ClassSymbol)st.tsym);
3804 // Next attribute owner, if it is a class.
3805 if (c.owner.kind == TYP && c.owner.type.hasTag(CLASS))
3806 attribClass((ClassSymbol)c.owner);
3807 }
3809 // The previous operations might have attributed the current class
3810 // if there was a cycle. So we test first whether the class is still
3811 // UNATTRIBUTED.
3812 if ((c.flags_field & UNATTRIBUTED) != 0) {
3813 c.flags_field &= ~UNATTRIBUTED;
3815 // Get environment current at the point of class definition.
3816 Env<AttrContext> env = enter.typeEnvs.get(c);
3818 // The info.lint field in the envs stored in enter.typeEnvs is deliberately uninitialized,
3819 // because the annotations were not available at the time the env was created. Therefore,
3820 // we look up the environment chain for the first enclosing environment for which the
3821 // lint value is set. Typically, this is the parent env, but might be further if there
3822 // are any envs created as a result of TypeParameter nodes.
3823 Env<AttrContext> lintEnv = env;
3824 while (lintEnv.info.lint == null)
3825 lintEnv = lintEnv.next;
3827 // Having found the enclosing lint value, we can initialize the lint value for this class
3828 env.info.lint = lintEnv.info.lint.augment(c.annotations, c.flags());
3830 Lint prevLint = chk.setLint(env.info.lint);
3831 JavaFileObject prev = log.useSource(c.sourcefile);
3832 ResultInfo prevReturnRes = env.info.returnResult;
3834 try {
3835 env.info.returnResult = null;
3836 // java.lang.Enum may not be subclassed by a non-enum
3837 if (st.tsym == syms.enumSym &&
3838 ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
3839 log.error(env.tree.pos(), "enum.no.subclassing");
3841 // Enums may not be extended by source-level classes
3842 if (st.tsym != null &&
3843 ((st.tsym.flags_field & Flags.ENUM) != 0) &&
3844 ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0) &&
3845 !target.compilerBootstrap(c)) {
3846 log.error(env.tree.pos(), "enum.types.not.extensible");
3847 }
3848 attribClassBody(env, c);
3850 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
3851 } finally {
3852 env.info.returnResult = prevReturnRes;
3853 log.useSource(prev);
3854 chk.setLint(prevLint);
3855 }
3857 }
3858 }
3860 public void visitImport(JCImport tree) {
3861 // nothing to do
3862 }
3864 /** Finish the attribution of a class. */
3865 private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
3866 JCClassDecl tree = (JCClassDecl)env.tree;
3867 Assert.check(c == tree.sym);
3869 // Validate annotations
3870 chk.validateAnnotations(tree.mods.annotations, c);
3872 // Validate type parameters, supertype and interfaces.
3873 attribStats(tree.typarams, env);
3874 if (!c.isAnonymous()) {
3875 //already checked if anonymous
3876 chk.validate(tree.typarams, env);
3877 chk.validate(tree.extending, env);
3878 chk.validate(tree.implementing, env);
3879 }
3881 // If this is a non-abstract class, check that it has no abstract
3882 // methods or unimplemented methods of an implemented interface.
3883 if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
3884 if (!relax)
3885 chk.checkAllDefined(tree.pos(), c);
3886 }
3888 if ((c.flags() & ANNOTATION) != 0) {
3889 if (tree.implementing.nonEmpty())
3890 log.error(tree.implementing.head.pos(),
3891 "cant.extend.intf.annotation");
3892 if (tree.typarams.nonEmpty())
3893 log.error(tree.typarams.head.pos(),
3894 "intf.annotation.cant.have.type.params");
3896 // If this annotation has a @Repeatable, validate
3897 Attribute.Compound repeatable = c.attribute(syms.repeatableType.tsym);
3898 if (repeatable != null) {
3899 // get diagnostic position for error reporting
3900 DiagnosticPosition cbPos = getDiagnosticPosition(tree, repeatable.type);
3901 Assert.checkNonNull(cbPos);
3903 chk.validateRepeatable(c, repeatable, cbPos);
3904 }
3905 } else {
3906 // Check that all extended classes and interfaces
3907 // are compatible (i.e. no two define methods with same arguments
3908 // yet different return types). (JLS 8.4.6.3)
3909 chk.checkCompatibleSupertypes(tree.pos(), c.type);
3910 if (allowDefaultMethods) {
3911 chk.checkDefaultMethodClashes(tree.pos(), c.type);
3912 }
3913 }
3915 // Check that class does not import the same parameterized interface
3916 // with two different argument lists.
3917 chk.checkClassBounds(tree.pos(), c.type);
3919 tree.type = c.type;
3921 for (List<JCTypeParameter> l = tree.typarams;
3922 l.nonEmpty(); l = l.tail) {
3923 Assert.checkNonNull(env.info.scope.lookup(l.head.name).scope);
3924 }
3926 // Check that a generic class doesn't extend Throwable
3927 if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
3928 log.error(tree.extending.pos(), "generic.throwable");
3930 // Check that all methods which implement some
3931 // method conform to the method they implement.
3932 chk.checkImplementations(tree);
3934 //check that a resource implementing AutoCloseable cannot throw InterruptedException
3935 checkAutoCloseable(tree.pos(), env, c.type);
3937 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
3938 // Attribute declaration
3939 attribStat(l.head, env);
3940 // Check that declarations in inner classes are not static (JLS 8.1.2)
3941 // Make an exception for static constants.
3942 if (c.owner.kind != PCK &&
3943 ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
3944 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
3945 Symbol sym = null;
3946 if (l.head.hasTag(VARDEF)) sym = ((JCVariableDecl) l.head).sym;
3947 if (sym == null ||
3948 sym.kind != VAR ||
3949 ((VarSymbol) sym).getConstValue() == null)
3950 log.error(l.head.pos(), "icls.cant.have.static.decl", c);
3951 }
3952 }
3954 // Check for cycles among non-initial constructors.
3955 chk.checkCyclicConstructors(tree);
3957 // Check for cycles among annotation elements.
3958 chk.checkNonCyclicElements(tree);
3960 // Check for proper use of serialVersionUID
3961 if (env.info.lint.isEnabled(LintCategory.SERIAL) &&
3962 isSerializable(c) &&
3963 (c.flags() & Flags.ENUM) == 0 &&
3964 (c.flags() & ABSTRACT) == 0) {
3965 checkSerialVersionUID(tree, c);
3966 }
3967 }
3968 // where
3969 /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
3970 private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
3971 for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
3972 if (types.isSameType(al.head.annotationType.type, t))
3973 return al.head.pos();
3974 }
3976 return null;
3977 }
3979 /** check if a class is a subtype of Serializable, if that is available. */
3980 private boolean isSerializable(ClassSymbol c) {
3981 try {
3982 syms.serializableType.complete();
3983 }
3984 catch (CompletionFailure e) {
3985 return false;
3986 }
3987 return types.isSubtype(c.type, syms.serializableType);
3988 }
3990 /** Check that an appropriate serialVersionUID member is defined. */
3991 private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
3993 // check for presence of serialVersionUID
3994 Scope.Entry e = c.members().lookup(names.serialVersionUID);
3995 while (e.scope != null && e.sym.kind != VAR) e = e.next();
3996 if (e.scope == null) {
3997 log.warning(LintCategory.SERIAL,
3998 tree.pos(), "missing.SVUID", c);
3999 return;
4000 }
4002 // check that it is static final
4003 VarSymbol svuid = (VarSymbol)e.sym;
4004 if ((svuid.flags() & (STATIC | FINAL)) !=
4005 (STATIC | FINAL))
4006 log.warning(LintCategory.SERIAL,
4007 TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c);
4009 // check that it is long
4010 else if (!svuid.type.hasTag(LONG))
4011 log.warning(LintCategory.SERIAL,
4012 TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c);
4014 // check constant
4015 else if (svuid.getConstValue() == null)
4016 log.warning(LintCategory.SERIAL,
4017 TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c);
4018 }
4020 private Type capture(Type type) {
4021 return types.capture(type);
4022 }
4024 // <editor-fold desc="post-attribution visitor">
4026 /**
4027 * Handle missing types/symbols in an AST. This routine is useful when
4028 * the compiler has encountered some errors (which might have ended up
4029 * terminating attribution abruptly); if the compiler is used in fail-over
4030 * mode (e.g. by an IDE) and the AST contains semantic errors, this routine
4031 * prevents NPE to be progagated during subsequent compilation steps.
4032 */
4033 public void postAttr(JCTree tree) {
4034 new PostAttrAnalyzer().scan(tree);
4035 }
4037 class PostAttrAnalyzer extends TreeScanner {
4039 private void initTypeIfNeeded(JCTree that) {
4040 if (that.type == null) {
4041 that.type = syms.unknownType;
4042 }
4043 }
4045 @Override
4046 public void scan(JCTree tree) {
4047 if (tree == null) return;
4048 if (tree instanceof JCExpression) {
4049 initTypeIfNeeded(tree);
4050 }
4051 super.scan(tree);
4052 }
4054 @Override
4055 public void visitIdent(JCIdent that) {
4056 if (that.sym == null) {
4057 that.sym = syms.unknownSymbol;
4058 }
4059 }
4061 @Override
4062 public void visitSelect(JCFieldAccess that) {
4063 if (that.sym == null) {
4064 that.sym = syms.unknownSymbol;
4065 }
4066 super.visitSelect(that);
4067 }
4069 @Override
4070 public void visitClassDef(JCClassDecl that) {
4071 initTypeIfNeeded(that);
4072 if (that.sym == null) {
4073 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol);
4074 }
4075 super.visitClassDef(that);
4076 }
4078 @Override
4079 public void visitMethodDef(JCMethodDecl that) {
4080 initTypeIfNeeded(that);
4081 if (that.sym == null) {
4082 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol);
4083 }
4084 super.visitMethodDef(that);
4085 }
4087 @Override
4088 public void visitVarDef(JCVariableDecl that) {
4089 initTypeIfNeeded(that);
4090 if (that.sym == null) {
4091 that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol);
4092 that.sym.adr = 0;
4093 }
4094 super.visitVarDef(that);
4095 }
4097 @Override
4098 public void visitNewClass(JCNewClass that) {
4099 if (that.constructor == null) {
4100 that.constructor = new MethodSymbol(0, names.init, syms.unknownType, syms.noSymbol);
4101 }
4102 if (that.constructorType == null) {
4103 that.constructorType = syms.unknownType;
4104 }
4105 super.visitNewClass(that);
4106 }
4108 @Override
4109 public void visitAssignop(JCAssignOp that) {
4110 if (that.operator == null)
4111 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
4112 super.visitAssignop(that);
4113 }
4115 @Override
4116 public void visitBinary(JCBinary that) {
4117 if (that.operator == null)
4118 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
4119 super.visitBinary(that);
4120 }
4122 @Override
4123 public void visitUnary(JCUnary that) {
4124 if (that.operator == null)
4125 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
4126 super.visitUnary(that);
4127 }
4129 @Override
4130 public void visitLambda(JCLambda that) {
4131 super.visitLambda(that);
4132 if (that.descriptorType == null) {
4133 that.descriptorType = syms.unknownType;
4134 }
4135 if (that.targets == null) {
4136 that.targets = List.nil();
4137 }
4138 }
4140 @Override
4141 public void visitReference(JCMemberReference that) {
4142 super.visitReference(that);
4143 if (that.sym == null) {
4144 that.sym = new MethodSymbol(0, names.empty, syms.unknownType, syms.noSymbol);
4145 }
4146 if (that.descriptorType == null) {
4147 that.descriptorType = syms.unknownType;
4148 }
4149 if (that.targets == null) {
4150 that.targets = List.nil();
4151 }
4152 }
4153 }
4154 // </editor-fold>
4155 }