Mon, 21 Jan 2013 20:19:53 +0000
8005166: Add support for static interface methods
Summary: Support public static interface methods
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 || (tree.sym.flags() & (ABSTRACT | NATIVE)) == 0 &&
958 !relax)
959 log.error(tree.pos(), "missing.meth.body.or.decl.abstract");
960 if (tree.defaultValue != null) {
961 if ((owner.flags() & ANNOTATION) == 0)
962 log.error(tree.pos(),
963 "default.allowed.in.intf.annotation.member");
964 }
965 } else if ((tree.sym.flags() & ABSTRACT) != 0 && !isDefaultMethod) {
966 if ((owner.flags() & INTERFACE) != 0) {
967 log.error(tree.body.pos(), "intf.meth.cant.have.body");
968 } else {
969 log.error(tree.pos(), "abstract.meth.cant.have.body");
970 }
971 } else if ((tree.mods.flags & NATIVE) != 0) {
972 log.error(tree.pos(), "native.meth.cant.have.body");
973 } else {
974 // Add an implicit super() call unless an explicit call to
975 // super(...) or this(...) is given
976 // or we are compiling class java.lang.Object.
977 if (tree.name == names.init && owner.type != syms.objectType) {
978 JCBlock body = tree.body;
979 if (body.stats.isEmpty() ||
980 !TreeInfo.isSelfCall(body.stats.head)) {
981 body.stats = body.stats.
982 prepend(memberEnter.SuperCall(make.at(body.pos),
983 List.<Type>nil(),
984 List.<JCVariableDecl>nil(),
985 false));
986 } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
987 (tree.mods.flags & GENERATEDCONSTR) == 0 &&
988 TreeInfo.isSuperCall(body.stats.head)) {
989 // enum constructors are not allowed to call super
990 // directly, so make sure there aren't any super calls
991 // in enum constructors, except in the compiler
992 // generated one.
993 log.error(tree.body.stats.head.pos(),
994 "call.to.super.not.allowed.in.enum.ctor",
995 env.enclClass.sym);
996 }
997 }
999 // Attribute method body.
1000 attribStat(tree.body, localEnv);
1001 }
1002 localEnv.info.scope.leave();
1003 result = tree.type = m.type;
1004 chk.validateAnnotations(tree.mods.annotations, m);
1005 }
1006 finally {
1007 chk.setLint(prevLint);
1008 chk.setMethod(prevMethod);
1009 }
1010 }
1012 public void visitVarDef(JCVariableDecl tree) {
1013 // Local variables have not been entered yet, so we need to do it now:
1014 if (env.info.scope.owner.kind == MTH) {
1015 if (tree.sym != null) {
1016 // parameters have already been entered
1017 env.info.scope.enter(tree.sym);
1018 } else {
1019 memberEnter.memberEnter(tree, env);
1020 annotate.flush();
1021 }
1022 }
1024 VarSymbol v = tree.sym;
1025 Lint lint = env.info.lint.augment(v.annotations, v.flags());
1026 Lint prevLint = chk.setLint(lint);
1028 // Check that the variable's declared type is well-formed.
1029 chk.validate(tree.vartype, env);
1030 deferredLintHandler.flush(tree.pos());
1032 try {
1033 chk.checkDeprecatedAnnotation(tree.pos(), v);
1035 if (tree.init != null) {
1036 if ((v.flags_field & FINAL) != 0 &&
1037 !tree.init.hasTag(NEWCLASS) &&
1038 !tree.init.hasTag(LAMBDA) &&
1039 !tree.init.hasTag(REFERENCE)) {
1040 // In this case, `v' is final. Ensure that it's initializer is
1041 // evaluated.
1042 v.getConstValue(); // ensure initializer is evaluated
1043 } else {
1044 // Attribute initializer in a new environment
1045 // with the declared variable as owner.
1046 // Check that initializer conforms to variable's declared type.
1047 Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
1048 initEnv.info.lint = lint;
1049 // In order to catch self-references, we set the variable's
1050 // declaration position to maximal possible value, effectively
1051 // marking the variable as undefined.
1052 initEnv.info.enclVar = v;
1053 attribExpr(tree.init, initEnv, v.type);
1054 }
1055 }
1056 result = tree.type = v.type;
1057 chk.validateAnnotations(tree.mods.annotations, v);
1058 }
1059 finally {
1060 chk.setLint(prevLint);
1061 }
1062 }
1064 public void visitSkip(JCSkip tree) {
1065 result = null;
1066 }
1068 public void visitBlock(JCBlock tree) {
1069 if (env.info.scope.owner.kind == TYP) {
1070 // Block is a static or instance initializer;
1071 // let the owner of the environment be a freshly
1072 // created BLOCK-method.
1073 Env<AttrContext> localEnv =
1074 env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
1075 localEnv.info.scope.owner =
1076 new MethodSymbol(tree.flags | BLOCK, names.empty, null,
1077 env.info.scope.owner);
1078 if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
1079 attribStats(tree.stats, localEnv);
1080 } else {
1081 // Create a new local environment with a local scope.
1082 Env<AttrContext> localEnv =
1083 env.dup(tree, env.info.dup(env.info.scope.dup()));
1084 try {
1085 attribStats(tree.stats, localEnv);
1086 } finally {
1087 localEnv.info.scope.leave();
1088 }
1089 }
1090 result = null;
1091 }
1093 public void visitDoLoop(JCDoWhileLoop tree) {
1094 attribStat(tree.body, env.dup(tree));
1095 attribExpr(tree.cond, env, syms.booleanType);
1096 result = null;
1097 }
1099 public void visitWhileLoop(JCWhileLoop tree) {
1100 attribExpr(tree.cond, env, syms.booleanType);
1101 attribStat(tree.body, env.dup(tree));
1102 result = null;
1103 }
1105 public void visitForLoop(JCForLoop tree) {
1106 Env<AttrContext> loopEnv =
1107 env.dup(env.tree, env.info.dup(env.info.scope.dup()));
1108 try {
1109 attribStats(tree.init, loopEnv);
1110 if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType);
1111 loopEnv.tree = tree; // before, we were not in loop!
1112 attribStats(tree.step, loopEnv);
1113 attribStat(tree.body, loopEnv);
1114 result = null;
1115 }
1116 finally {
1117 loopEnv.info.scope.leave();
1118 }
1119 }
1121 public void visitForeachLoop(JCEnhancedForLoop tree) {
1122 Env<AttrContext> loopEnv =
1123 env.dup(env.tree, env.info.dup(env.info.scope.dup()));
1124 try {
1125 attribStat(tree.var, loopEnv);
1126 Type exprType = types.upperBound(attribExpr(tree.expr, loopEnv));
1127 chk.checkNonVoid(tree.pos(), exprType);
1128 Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
1129 if (elemtype == null) {
1130 // or perhaps expr implements Iterable<T>?
1131 Type base = types.asSuper(exprType, syms.iterableType.tsym);
1132 if (base == null) {
1133 log.error(tree.expr.pos(),
1134 "foreach.not.applicable.to.type",
1135 exprType,
1136 diags.fragment("type.req.array.or.iterable"));
1137 elemtype = types.createErrorType(exprType);
1138 } else {
1139 List<Type> iterableParams = base.allparams();
1140 elemtype = iterableParams.isEmpty()
1141 ? syms.objectType
1142 : types.upperBound(iterableParams.head);
1143 }
1144 }
1145 chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
1146 loopEnv.tree = tree; // before, we were not in loop!
1147 attribStat(tree.body, loopEnv);
1148 result = null;
1149 }
1150 finally {
1151 loopEnv.info.scope.leave();
1152 }
1153 }
1155 public void visitLabelled(JCLabeledStatement tree) {
1156 // Check that label is not used in an enclosing statement
1157 Env<AttrContext> env1 = env;
1158 while (env1 != null && !env1.tree.hasTag(CLASSDEF)) {
1159 if (env1.tree.hasTag(LABELLED) &&
1160 ((JCLabeledStatement) env1.tree).label == tree.label) {
1161 log.error(tree.pos(), "label.already.in.use",
1162 tree.label);
1163 break;
1164 }
1165 env1 = env1.next;
1166 }
1168 attribStat(tree.body, env.dup(tree));
1169 result = null;
1170 }
1172 public void visitSwitch(JCSwitch tree) {
1173 Type seltype = attribExpr(tree.selector, env);
1175 Env<AttrContext> switchEnv =
1176 env.dup(tree, env.info.dup(env.info.scope.dup()));
1178 try {
1180 boolean enumSwitch =
1181 allowEnums &&
1182 (seltype.tsym.flags() & Flags.ENUM) != 0;
1183 boolean stringSwitch = false;
1184 if (types.isSameType(seltype, syms.stringType)) {
1185 if (allowStringsInSwitch) {
1186 stringSwitch = true;
1187 } else {
1188 log.error(tree.selector.pos(), "string.switch.not.supported.in.source", sourceName);
1189 }
1190 }
1191 if (!enumSwitch && !stringSwitch)
1192 seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType);
1194 // Attribute all cases and
1195 // check that there are no duplicate case labels or default clauses.
1196 Set<Object> labels = new HashSet<Object>(); // The set of case labels.
1197 boolean hasDefault = false; // Is there a default label?
1198 for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
1199 JCCase c = l.head;
1200 Env<AttrContext> caseEnv =
1201 switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup()));
1202 try {
1203 if (c.pat != null) {
1204 if (enumSwitch) {
1205 Symbol sym = enumConstant(c.pat, seltype);
1206 if (sym == null) {
1207 log.error(c.pat.pos(), "enum.label.must.be.unqualified.enum");
1208 } else if (!labels.add(sym)) {
1209 log.error(c.pos(), "duplicate.case.label");
1210 }
1211 } else {
1212 Type pattype = attribExpr(c.pat, switchEnv, seltype);
1213 if (!pattype.hasTag(ERROR)) {
1214 if (pattype.constValue() == null) {
1215 log.error(c.pat.pos(),
1216 (stringSwitch ? "string.const.req" : "const.expr.req"));
1217 } else if (labels.contains(pattype.constValue())) {
1218 log.error(c.pos(), "duplicate.case.label");
1219 } else {
1220 labels.add(pattype.constValue());
1221 }
1222 }
1223 }
1224 } else if (hasDefault) {
1225 log.error(c.pos(), "duplicate.default.label");
1226 } else {
1227 hasDefault = true;
1228 }
1229 attribStats(c.stats, caseEnv);
1230 } finally {
1231 caseEnv.info.scope.leave();
1232 addVars(c.stats, switchEnv.info.scope);
1233 }
1234 }
1236 result = null;
1237 }
1238 finally {
1239 switchEnv.info.scope.leave();
1240 }
1241 }
1242 // where
1243 /** Add any variables defined in stats to the switch scope. */
1244 private static void addVars(List<JCStatement> stats, Scope switchScope) {
1245 for (;stats.nonEmpty(); stats = stats.tail) {
1246 JCTree stat = stats.head;
1247 if (stat.hasTag(VARDEF))
1248 switchScope.enter(((JCVariableDecl) stat).sym);
1249 }
1250 }
1251 // where
1252 /** Return the selected enumeration constant symbol, or null. */
1253 private Symbol enumConstant(JCTree tree, Type enumType) {
1254 if (!tree.hasTag(IDENT)) {
1255 log.error(tree.pos(), "enum.label.must.be.unqualified.enum");
1256 return syms.errSymbol;
1257 }
1258 JCIdent ident = (JCIdent)tree;
1259 Name name = ident.name;
1260 for (Scope.Entry e = enumType.tsym.members().lookup(name);
1261 e.scope != null; e = e.next()) {
1262 if (e.sym.kind == VAR) {
1263 Symbol s = ident.sym = e.sym;
1264 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
1265 ident.type = s.type;
1266 return ((s.flags_field & Flags.ENUM) == 0)
1267 ? null : s;
1268 }
1269 }
1270 return null;
1271 }
1273 public void visitSynchronized(JCSynchronized tree) {
1274 chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
1275 attribStat(tree.body, env);
1276 result = null;
1277 }
1279 public void visitTry(JCTry tree) {
1280 // Create a new local environment with a local
1281 Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
1282 try {
1283 boolean isTryWithResource = tree.resources.nonEmpty();
1284 // Create a nested environment for attributing the try block if needed
1285 Env<AttrContext> tryEnv = isTryWithResource ?
1286 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
1287 localEnv;
1288 try {
1289 // Attribute resource declarations
1290 for (JCTree resource : tree.resources) {
1291 CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) {
1292 @Override
1293 public void report(DiagnosticPosition pos, JCDiagnostic details) {
1294 chk.basicHandler.report(pos, diags.fragment("try.not.applicable.to.type", details));
1295 }
1296 };
1297 ResultInfo twrResult = new ResultInfo(VAL, syms.autoCloseableType, twrContext);
1298 if (resource.hasTag(VARDEF)) {
1299 attribStat(resource, tryEnv);
1300 twrResult.check(resource, resource.type);
1302 //check that resource type cannot throw InterruptedException
1303 checkAutoCloseable(resource.pos(), localEnv, resource.type);
1305 VarSymbol var = (VarSymbol)TreeInfo.symbolFor(resource);
1306 var.setData(ElementKind.RESOURCE_VARIABLE);
1307 } else {
1308 attribTree(resource, tryEnv, twrResult);
1309 }
1310 }
1311 // Attribute body
1312 attribStat(tree.body, tryEnv);
1313 } finally {
1314 if (isTryWithResource)
1315 tryEnv.info.scope.leave();
1316 }
1318 // Attribute catch clauses
1319 for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
1320 JCCatch c = l.head;
1321 Env<AttrContext> catchEnv =
1322 localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup()));
1323 try {
1324 Type ctype = attribStat(c.param, catchEnv);
1325 if (TreeInfo.isMultiCatch(c)) {
1326 //multi-catch parameter is implicitly marked as final
1327 c.param.sym.flags_field |= FINAL | UNION;
1328 }
1329 if (c.param.sym.kind == Kinds.VAR) {
1330 c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
1331 }
1332 chk.checkType(c.param.vartype.pos(),
1333 chk.checkClassType(c.param.vartype.pos(), ctype),
1334 syms.throwableType);
1335 attribStat(c.body, catchEnv);
1336 } finally {
1337 catchEnv.info.scope.leave();
1338 }
1339 }
1341 // Attribute finalizer
1342 if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
1343 result = null;
1344 }
1345 finally {
1346 localEnv.info.scope.leave();
1347 }
1348 }
1350 void checkAutoCloseable(DiagnosticPosition pos, Env<AttrContext> env, Type resource) {
1351 if (!resource.isErroneous() &&
1352 types.asSuper(resource, syms.autoCloseableType.tsym) != null &&
1353 !types.isSameType(resource, syms.autoCloseableType)) { // Don't emit warning for AutoCloseable itself
1354 Symbol close = syms.noSymbol;
1355 Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log);
1356 try {
1357 close = rs.resolveQualifiedMethod(pos,
1358 env,
1359 resource,
1360 names.close,
1361 List.<Type>nil(),
1362 List.<Type>nil());
1363 }
1364 finally {
1365 log.popDiagnosticHandler(discardHandler);
1366 }
1367 if (close.kind == MTH &&
1368 close.overrides(syms.autoCloseableClose, resource.tsym, types, true) &&
1369 chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes()) &&
1370 env.info.lint.isEnabled(LintCategory.TRY)) {
1371 log.warning(LintCategory.TRY, pos, "try.resource.throws.interrupted.exc", resource);
1372 }
1373 }
1374 }
1376 public void visitConditional(JCConditional tree) {
1377 Type condtype = attribExpr(tree.cond, env, syms.booleanType);
1379 tree.polyKind = (!allowPoly ||
1380 pt().hasTag(NONE) && pt() != Type.recoveryType ||
1381 isBooleanOrNumeric(env, tree)) ?
1382 PolyKind.STANDALONE : PolyKind.POLY;
1384 if (tree.polyKind == PolyKind.POLY && resultInfo.pt.hasTag(VOID)) {
1385 //cannot get here (i.e. it means we are returning from void method - which is already an error)
1386 resultInfo.checkContext.report(tree, diags.fragment("conditional.target.cant.be.void"));
1387 result = tree.type = types.createErrorType(resultInfo.pt);
1388 return;
1389 }
1391 ResultInfo condInfo = tree.polyKind == PolyKind.STANDALONE ?
1392 unknownExprInfo :
1393 resultInfo.dup(new Check.NestedCheckContext(resultInfo.checkContext) {
1394 //this will use enclosing check context to check compatibility of
1395 //subexpression against target type; if we are in a method check context,
1396 //depending on whether boxing is allowed, we could have incompatibilities
1397 @Override
1398 public void report(DiagnosticPosition pos, JCDiagnostic details) {
1399 enclosingContext.report(pos, diags.fragment("incompatible.type.in.conditional", details));
1400 }
1401 });
1403 Type truetype = attribTree(tree.truepart, env, condInfo);
1404 Type falsetype = attribTree(tree.falsepart, env, condInfo);
1406 Type owntype = (tree.polyKind == PolyKind.STANDALONE) ? condType(tree, truetype, falsetype) : pt();
1407 if (condtype.constValue() != null &&
1408 truetype.constValue() != null &&
1409 falsetype.constValue() != null &&
1410 !owntype.hasTag(NONE)) {
1411 //constant folding
1412 owntype = cfolder.coerce(condtype.isTrue() ? truetype : falsetype, owntype);
1413 }
1414 result = check(tree, owntype, VAL, resultInfo);
1415 }
1416 //where
1417 private boolean isBooleanOrNumeric(Env<AttrContext> env, JCExpression tree) {
1418 switch (tree.getTag()) {
1419 case LITERAL: return ((JCLiteral)tree).typetag.isSubRangeOf(DOUBLE) ||
1420 ((JCLiteral)tree).typetag == BOOLEAN ||
1421 ((JCLiteral)tree).typetag == BOT;
1422 case LAMBDA: case REFERENCE: return false;
1423 case PARENS: return isBooleanOrNumeric(env, ((JCParens)tree).expr);
1424 case CONDEXPR:
1425 JCConditional condTree = (JCConditional)tree;
1426 return isBooleanOrNumeric(env, condTree.truepart) &&
1427 isBooleanOrNumeric(env, condTree.falsepart);
1428 case APPLY:
1429 JCMethodInvocation speculativeMethodTree =
1430 (JCMethodInvocation)deferredAttr.attribSpeculative(tree, env, unknownExprInfo);
1431 Type owntype = TreeInfo.symbol(speculativeMethodTree.meth).type.getReturnType();
1432 return types.unboxedTypeOrType(owntype).isPrimitive();
1433 case NEWCLASS:
1434 JCExpression className =
1435 removeClassParams.translate(((JCNewClass)tree).clazz);
1436 JCExpression speculativeNewClassTree =
1437 (JCExpression)deferredAttr.attribSpeculative(className, env, unknownTypeInfo);
1438 return types.unboxedTypeOrType(speculativeNewClassTree.type).isPrimitive();
1439 default:
1440 Type speculativeType = deferredAttr.attribSpeculative(tree, env, unknownExprInfo).type;
1441 speculativeType = types.unboxedTypeOrType(speculativeType);
1442 return speculativeType.isPrimitive();
1443 }
1444 }
1445 //where
1446 TreeTranslator removeClassParams = new TreeTranslator() {
1447 @Override
1448 public void visitTypeApply(JCTypeApply tree) {
1449 result = translate(tree.clazz);
1450 }
1451 };
1453 /** Compute the type of a conditional expression, after
1454 * checking that it exists. See JLS 15.25. Does not take into
1455 * account the special case where condition and both arms
1456 * are constants.
1457 *
1458 * @param pos The source position to be used for error
1459 * diagnostics.
1460 * @param thentype The type of the expression's then-part.
1461 * @param elsetype The type of the expression's else-part.
1462 */
1463 private Type condType(DiagnosticPosition pos,
1464 Type thentype, Type elsetype) {
1465 // If same type, that is the result
1466 if (types.isSameType(thentype, elsetype))
1467 return thentype.baseType();
1469 Type thenUnboxed = (!allowBoxing || thentype.isPrimitive())
1470 ? thentype : types.unboxedType(thentype);
1471 Type elseUnboxed = (!allowBoxing || elsetype.isPrimitive())
1472 ? elsetype : types.unboxedType(elsetype);
1474 // Otherwise, if both arms can be converted to a numeric
1475 // type, return the least numeric type that fits both arms
1476 // (i.e. return larger of the two, or return int if one
1477 // arm is short, the other is char).
1478 if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) {
1479 // If one arm has an integer subrange type (i.e., byte,
1480 // short, or char), and the other is an integer constant
1481 // that fits into the subrange, return the subrange type.
1482 if (thenUnboxed.getTag().isStrictSubRangeOf(INT) && elseUnboxed.hasTag(INT) &&
1483 types.isAssignable(elseUnboxed, thenUnboxed))
1484 return thenUnboxed.baseType();
1485 if (elseUnboxed.getTag().isStrictSubRangeOf(INT) && thenUnboxed.hasTag(INT) &&
1486 types.isAssignable(thenUnboxed, elseUnboxed))
1487 return elseUnboxed.baseType();
1489 for (TypeTag tag : TypeTag.values()) {
1490 if (tag.ordinal() >= TypeTag.getTypeTagCount()) break;
1491 Type candidate = syms.typeOfTag[tag.ordinal()];
1492 if (candidate != null &&
1493 candidate.isPrimitive() &&
1494 types.isSubtype(thenUnboxed, candidate) &&
1495 types.isSubtype(elseUnboxed, candidate))
1496 return candidate;
1497 }
1498 }
1500 // Those were all the cases that could result in a primitive
1501 if (allowBoxing) {
1502 if (thentype.isPrimitive())
1503 thentype = types.boxedClass(thentype).type;
1504 if (elsetype.isPrimitive())
1505 elsetype = types.boxedClass(elsetype).type;
1506 }
1508 if (types.isSubtype(thentype, elsetype))
1509 return elsetype.baseType();
1510 if (types.isSubtype(elsetype, thentype))
1511 return thentype.baseType();
1513 if (!allowBoxing || thentype.hasTag(VOID) || elsetype.hasTag(VOID)) {
1514 log.error(pos, "neither.conditional.subtype",
1515 thentype, elsetype);
1516 return thentype.baseType();
1517 }
1519 // both are known to be reference types. The result is
1520 // lub(thentype,elsetype). This cannot fail, as it will
1521 // always be possible to infer "Object" if nothing better.
1522 return types.lub(thentype.baseType(), elsetype.baseType());
1523 }
1525 public void visitIf(JCIf tree) {
1526 attribExpr(tree.cond, env, syms.booleanType);
1527 attribStat(tree.thenpart, env);
1528 if (tree.elsepart != null)
1529 attribStat(tree.elsepart, env);
1530 chk.checkEmptyIf(tree);
1531 result = null;
1532 }
1534 public void visitExec(JCExpressionStatement tree) {
1535 //a fresh environment is required for 292 inference to work properly ---
1536 //see Infer.instantiatePolymorphicSignatureInstance()
1537 Env<AttrContext> localEnv = env.dup(tree);
1538 attribExpr(tree.expr, localEnv);
1539 result = null;
1540 }
1542 public void visitBreak(JCBreak tree) {
1543 tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
1544 result = null;
1545 }
1547 public void visitContinue(JCContinue tree) {
1548 tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
1549 result = null;
1550 }
1551 //where
1552 /** Return the target of a break or continue statement, if it exists,
1553 * report an error if not.
1554 * Note: The target of a labelled break or continue is the
1555 * (non-labelled) statement tree referred to by the label,
1556 * not the tree representing the labelled statement itself.
1557 *
1558 * @param pos The position to be used for error diagnostics
1559 * @param tag The tag of the jump statement. This is either
1560 * Tree.BREAK or Tree.CONTINUE.
1561 * @param label The label of the jump statement, or null if no
1562 * label is given.
1563 * @param env The environment current at the jump statement.
1564 */
1565 private JCTree findJumpTarget(DiagnosticPosition pos,
1566 JCTree.Tag tag,
1567 Name label,
1568 Env<AttrContext> env) {
1569 // Search environments outwards from the point of jump.
1570 Env<AttrContext> env1 = env;
1571 LOOP:
1572 while (env1 != null) {
1573 switch (env1.tree.getTag()) {
1574 case LABELLED:
1575 JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
1576 if (label == labelled.label) {
1577 // If jump is a continue, check that target is a loop.
1578 if (tag == CONTINUE) {
1579 if (!labelled.body.hasTag(DOLOOP) &&
1580 !labelled.body.hasTag(WHILELOOP) &&
1581 !labelled.body.hasTag(FORLOOP) &&
1582 !labelled.body.hasTag(FOREACHLOOP))
1583 log.error(pos, "not.loop.label", label);
1584 // Found labelled statement target, now go inwards
1585 // to next non-labelled tree.
1586 return TreeInfo.referencedStatement(labelled);
1587 } else {
1588 return labelled;
1589 }
1590 }
1591 break;
1592 case DOLOOP:
1593 case WHILELOOP:
1594 case FORLOOP:
1595 case FOREACHLOOP:
1596 if (label == null) return env1.tree;
1597 break;
1598 case SWITCH:
1599 if (label == null && tag == BREAK) return env1.tree;
1600 break;
1601 case LAMBDA:
1602 case METHODDEF:
1603 case CLASSDEF:
1604 break LOOP;
1605 default:
1606 }
1607 env1 = env1.next;
1608 }
1609 if (label != null)
1610 log.error(pos, "undef.label", label);
1611 else if (tag == CONTINUE)
1612 log.error(pos, "cont.outside.loop");
1613 else
1614 log.error(pos, "break.outside.switch.loop");
1615 return null;
1616 }
1618 public void visitReturn(JCReturn tree) {
1619 // Check that there is an enclosing method which is
1620 // nested within than the enclosing class.
1621 if (env.info.returnResult == null) {
1622 log.error(tree.pos(), "ret.outside.meth");
1623 } else {
1624 // Attribute return expression, if it exists, and check that
1625 // it conforms to result type of enclosing method.
1626 if (tree.expr != null) {
1627 if (env.info.returnResult.pt.hasTag(VOID)) {
1628 env.info.returnResult.checkContext.report(tree.expr.pos(),
1629 diags.fragment("unexpected.ret.val"));
1630 }
1631 attribTree(tree.expr, env, env.info.returnResult);
1632 } else if (!env.info.returnResult.pt.hasTag(VOID)) {
1633 env.info.returnResult.checkContext.report(tree.pos(),
1634 diags.fragment("missing.ret.val"));
1635 }
1636 }
1637 result = null;
1638 }
1640 public void visitThrow(JCThrow tree) {
1641 Type owntype = attribExpr(tree.expr, env, allowPoly ? Type.noType : syms.throwableType);
1642 if (allowPoly) {
1643 chk.checkType(tree, owntype, syms.throwableType);
1644 }
1645 result = null;
1646 }
1648 public void visitAssert(JCAssert tree) {
1649 attribExpr(tree.cond, env, syms.booleanType);
1650 if (tree.detail != null) {
1651 chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
1652 }
1653 result = null;
1654 }
1656 /** Visitor method for method invocations.
1657 * NOTE: The method part of an application will have in its type field
1658 * the return type of the method, not the method's type itself!
1659 */
1660 public void visitApply(JCMethodInvocation tree) {
1661 // The local environment of a method application is
1662 // a new environment nested in the current one.
1663 Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
1665 // The types of the actual method arguments.
1666 List<Type> argtypes;
1668 // The types of the actual method type arguments.
1669 List<Type> typeargtypes = null;
1671 Name methName = TreeInfo.name(tree.meth);
1673 boolean isConstructorCall =
1674 methName == names._this || methName == names._super;
1676 if (isConstructorCall) {
1677 // We are seeing a ...this(...) or ...super(...) call.
1678 // Check that this is the first statement in a constructor.
1679 if (checkFirstConstructorStat(tree, env)) {
1681 // Record the fact
1682 // that this is a constructor call (using isSelfCall).
1683 localEnv.info.isSelfCall = true;
1685 // Attribute arguments, yielding list of argument types.
1686 argtypes = attribArgs(tree.args, localEnv);
1687 typeargtypes = attribTypes(tree.typeargs, localEnv);
1689 // Variable `site' points to the class in which the called
1690 // constructor is defined.
1691 Type site = env.enclClass.sym.type;
1692 if (methName == names._super) {
1693 if (site == syms.objectType) {
1694 log.error(tree.meth.pos(), "no.superclass", site);
1695 site = types.createErrorType(syms.objectType);
1696 } else {
1697 site = types.supertype(site);
1698 }
1699 }
1701 if (site.hasTag(CLASS)) {
1702 Type encl = site.getEnclosingType();
1703 while (encl != null && encl.hasTag(TYPEVAR))
1704 encl = encl.getUpperBound();
1705 if (encl.hasTag(CLASS)) {
1706 // we are calling a nested class
1708 if (tree.meth.hasTag(SELECT)) {
1709 JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
1711 // We are seeing a prefixed call, of the form
1712 // <expr>.super(...).
1713 // Check that the prefix expression conforms
1714 // to the outer instance type of the class.
1715 chk.checkRefType(qualifier.pos(),
1716 attribExpr(qualifier, localEnv,
1717 encl));
1718 } else if (methName == names._super) {
1719 // qualifier omitted; check for existence
1720 // of an appropriate implicit qualifier.
1721 rs.resolveImplicitThis(tree.meth.pos(),
1722 localEnv, site, true);
1723 }
1724 } else if (tree.meth.hasTag(SELECT)) {
1725 log.error(tree.meth.pos(), "illegal.qual.not.icls",
1726 site.tsym);
1727 }
1729 // if we're calling a java.lang.Enum constructor,
1730 // prefix the implicit String and int parameters
1731 if (site.tsym == syms.enumSym && allowEnums)
1732 argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
1734 // Resolve the called constructor under the assumption
1735 // that we are referring to a superclass instance of the
1736 // current instance (JLS ???).
1737 boolean selectSuperPrev = localEnv.info.selectSuper;
1738 localEnv.info.selectSuper = true;
1739 localEnv.info.pendingResolutionPhase = null;
1740 Symbol sym = rs.resolveConstructor(
1741 tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
1742 localEnv.info.selectSuper = selectSuperPrev;
1744 // Set method symbol to resolved constructor...
1745 TreeInfo.setSymbol(tree.meth, sym);
1747 // ...and check that it is legal in the current context.
1748 // (this will also set the tree's type)
1749 Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
1750 checkId(tree.meth, site, sym, localEnv, new ResultInfo(MTH, mpt));
1751 }
1752 // Otherwise, `site' is an error type and we do nothing
1753 }
1754 result = tree.type = syms.voidType;
1755 } else {
1756 // Otherwise, we are seeing a regular method call.
1757 // Attribute the arguments, yielding list of argument types, ...
1758 argtypes = attribArgs(tree.args, localEnv);
1759 typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
1761 // ... and attribute the method using as a prototype a methodtype
1762 // whose formal argument types is exactly the list of actual
1763 // arguments (this will also set the method symbol).
1764 Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
1765 localEnv.info.pendingResolutionPhase = null;
1766 Type mtype = attribTree(tree.meth, localEnv, new ResultInfo(VAL, mpt, resultInfo.checkContext));
1768 // Compute the result type.
1769 Type restype = mtype.getReturnType();
1770 if (restype.hasTag(WILDCARD))
1771 throw new AssertionError(mtype);
1773 Type qualifier = (tree.meth.hasTag(SELECT))
1774 ? ((JCFieldAccess) tree.meth).selected.type
1775 : env.enclClass.sym.type;
1776 restype = adjustMethodReturnType(qualifier, methName, argtypes, restype);
1778 chk.checkRefTypes(tree.typeargs, typeargtypes);
1780 // Check that value of resulting type is admissible in the
1781 // current context. Also, capture the return type
1782 result = check(tree, capture(restype), VAL, resultInfo);
1784 if (localEnv.info.lastResolveVarargs())
1785 Assert.check(result.isErroneous() || tree.varargsElement != null);
1786 }
1787 chk.validate(tree.typeargs, localEnv);
1788 }
1789 //where
1790 Type adjustMethodReturnType(Type qualifierType, Name methodName, List<Type> argtypes, Type restype) {
1791 if (allowCovariantReturns &&
1792 methodName == names.clone &&
1793 types.isArray(qualifierType)) {
1794 // as a special case, array.clone() has a result that is
1795 // the same as static type of the array being cloned
1796 return qualifierType;
1797 } else if (allowGenerics &&
1798 methodName == names.getClass &&
1799 argtypes.isEmpty()) {
1800 // as a special case, x.getClass() has type Class<? extends |X|>
1801 return new ClassType(restype.getEnclosingType(),
1802 List.<Type>of(new WildcardType(types.erasure(qualifierType),
1803 BoundKind.EXTENDS,
1804 syms.boundClass)),
1805 restype.tsym);
1806 } else {
1807 return restype;
1808 }
1809 }
1811 /** Check that given application node appears as first statement
1812 * in a constructor call.
1813 * @param tree The application node
1814 * @param env The environment current at the application.
1815 */
1816 boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) {
1817 JCMethodDecl enclMethod = env.enclMethod;
1818 if (enclMethod != null && enclMethod.name == names.init) {
1819 JCBlock body = enclMethod.body;
1820 if (body.stats.head.hasTag(EXEC) &&
1821 ((JCExpressionStatement) body.stats.head).expr == tree)
1822 return true;
1823 }
1824 log.error(tree.pos(),"call.must.be.first.stmt.in.ctor",
1825 TreeInfo.name(tree.meth));
1826 return false;
1827 }
1829 /** Obtain a method type with given argument types.
1830 */
1831 Type newMethodTemplate(Type restype, List<Type> argtypes, List<Type> typeargtypes) {
1832 MethodType mt = new MethodType(argtypes, restype, List.<Type>nil(), syms.methodClass);
1833 return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
1834 }
1836 public void visitNewClass(final JCNewClass tree) {
1837 Type owntype = types.createErrorType(tree.type);
1839 // The local environment of a class creation is
1840 // a new environment nested in the current one.
1841 Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
1843 // The anonymous inner class definition of the new expression,
1844 // if one is defined by it.
1845 JCClassDecl cdef = tree.def;
1847 // If enclosing class is given, attribute it, and
1848 // complete class name to be fully qualified
1849 JCExpression clazz = tree.clazz; // Class field following new
1850 JCExpression clazzid = // Identifier in class field
1851 (clazz.hasTag(TYPEAPPLY))
1852 ? ((JCTypeApply) clazz).clazz
1853 : clazz;
1855 JCExpression clazzid1 = clazzid; // The same in fully qualified form
1857 if (tree.encl != null) {
1858 // We are seeing a qualified new, of the form
1859 // <expr>.new C <...> (...) ...
1860 // In this case, we let clazz stand for the name of the
1861 // allocated class C prefixed with the type of the qualifier
1862 // expression, so that we can
1863 // resolve it with standard techniques later. I.e., if
1864 // <expr> has type T, then <expr>.new C <...> (...)
1865 // yields a clazz T.C.
1866 Type encltype = chk.checkRefType(tree.encl.pos(),
1867 attribExpr(tree.encl, env));
1868 clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
1869 ((JCIdent) clazzid).name);
1870 if (clazz.hasTag(TYPEAPPLY))
1871 clazz = make.at(tree.pos).
1872 TypeApply(clazzid1,
1873 ((JCTypeApply) clazz).arguments);
1874 else
1875 clazz = clazzid1;
1876 }
1878 // Attribute clazz expression and store
1879 // symbol + type back into the attributed tree.
1880 Type clazztype = TreeInfo.isEnumInit(env.tree) ?
1881 attribIdentAsEnumType(env, (JCIdent)clazz) :
1882 attribType(clazz, env);
1884 clazztype = chk.checkDiamond(tree, clazztype);
1885 chk.validate(clazz, localEnv);
1886 if (tree.encl != null) {
1887 // We have to work in this case to store
1888 // symbol + type back into the attributed tree.
1889 tree.clazz.type = clazztype;
1890 TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
1891 clazzid.type = ((JCIdent) clazzid).sym.type;
1892 if (!clazztype.isErroneous()) {
1893 if (cdef != null && clazztype.tsym.isInterface()) {
1894 log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new");
1895 } else if (clazztype.tsym.isStatic()) {
1896 log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym);
1897 }
1898 }
1899 } else if (!clazztype.tsym.isInterface() &&
1900 clazztype.getEnclosingType().hasTag(CLASS)) {
1901 // Check for the existence of an apropos outer instance
1902 rs.resolveImplicitThis(tree.pos(), env, clazztype);
1903 }
1905 // Attribute constructor arguments.
1906 List<Type> argtypes = attribArgs(tree.args, localEnv);
1907 List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
1909 // If we have made no mistakes in the class type...
1910 if (clazztype.hasTag(CLASS)) {
1911 // Enums may not be instantiated except implicitly
1912 if (allowEnums &&
1913 (clazztype.tsym.flags_field&Flags.ENUM) != 0 &&
1914 (!env.tree.hasTag(VARDEF) ||
1915 (((JCVariableDecl) env.tree).mods.flags&Flags.ENUM) == 0 ||
1916 ((JCVariableDecl) env.tree).init != tree))
1917 log.error(tree.pos(), "enum.cant.be.instantiated");
1918 // Check that class is not abstract
1919 if (cdef == null &&
1920 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
1921 log.error(tree.pos(), "abstract.cant.be.instantiated",
1922 clazztype.tsym);
1923 } else if (cdef != null && clazztype.tsym.isInterface()) {
1924 // Check that no constructor arguments are given to
1925 // anonymous classes implementing an interface
1926 if (!argtypes.isEmpty())
1927 log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args");
1929 if (!typeargtypes.isEmpty())
1930 log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs");
1932 // Error recovery: pretend no arguments were supplied.
1933 argtypes = List.nil();
1934 typeargtypes = List.nil();
1935 } else if (TreeInfo.isDiamond(tree)) {
1936 ClassType site = new ClassType(clazztype.getEnclosingType(),
1937 clazztype.tsym.type.getTypeArguments(),
1938 clazztype.tsym);
1940 Env<AttrContext> diamondEnv = localEnv.dup(tree);
1941 diamondEnv.info.selectSuper = cdef != null;
1942 diamondEnv.info.pendingResolutionPhase = null;
1944 //if the type of the instance creation expression is a class type
1945 //apply method resolution inference (JLS 15.12.2.7). The return type
1946 //of the resolved constructor will be a partially instantiated type
1947 Symbol constructor = rs.resolveDiamond(tree.pos(),
1948 diamondEnv,
1949 site,
1950 argtypes,
1951 typeargtypes);
1952 tree.constructor = constructor.baseSymbol();
1954 final TypeSymbol csym = clazztype.tsym;
1955 ResultInfo diamondResult = new ResultInfo(MTH, newMethodTemplate(resultInfo.pt, argtypes, typeargtypes), new Check.NestedCheckContext(resultInfo.checkContext) {
1956 @Override
1957 public void report(DiagnosticPosition _unused, JCDiagnostic details) {
1958 enclosingContext.report(tree.clazz,
1959 diags.fragment("cant.apply.diamond.1", diags.fragment("diamond", csym), details));
1960 }
1961 });
1962 Type constructorType = tree.constructorType = types.createErrorType(clazztype);
1963 constructorType = checkId(tree, site,
1964 constructor,
1965 diamondEnv,
1966 diamondResult);
1968 tree.clazz.type = types.createErrorType(clazztype);
1969 if (!constructorType.isErroneous()) {
1970 tree.clazz.type = clazztype = constructorType.getReturnType();
1971 tree.constructorType = types.createMethodTypeWithReturn(constructorType, syms.voidType);
1972 }
1973 clazztype = chk.checkClassType(tree.clazz, tree.clazz.type, true);
1974 }
1976 // Resolve the called constructor under the assumption
1977 // that we are referring to a superclass instance of the
1978 // current instance (JLS ???).
1979 else {
1980 //the following code alters some of the fields in the current
1981 //AttrContext - hence, the current context must be dup'ed in
1982 //order to avoid downstream failures
1983 Env<AttrContext> rsEnv = localEnv.dup(tree);
1984 rsEnv.info.selectSuper = cdef != null;
1985 rsEnv.info.pendingResolutionPhase = null;
1986 tree.constructor = rs.resolveConstructor(
1987 tree.pos(), rsEnv, clazztype, argtypes, typeargtypes);
1988 if (cdef == null) { //do not check twice!
1989 tree.constructorType = checkId(tree,
1990 clazztype,
1991 tree.constructor,
1992 rsEnv,
1993 new ResultInfo(MTH, newMethodTemplate(syms.voidType, argtypes, typeargtypes)));
1994 if (rsEnv.info.lastResolveVarargs())
1995 Assert.check(tree.constructorType.isErroneous() || tree.varargsElement != null);
1996 }
1997 findDiamondIfNeeded(localEnv, tree, clazztype);
1998 }
2000 if (cdef != null) {
2001 // We are seeing an anonymous class instance creation.
2002 // In this case, the class instance creation
2003 // expression
2004 //
2005 // E.new <typeargs1>C<typargs2>(args) { ... }
2006 //
2007 // is represented internally as
2008 //
2009 // E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } ) .
2010 //
2011 // This expression is then *transformed* as follows:
2012 //
2013 // (1) add a STATIC flag to the class definition
2014 // if the current environment is static
2015 // (2) add an extends or implements clause
2016 // (3) add a constructor.
2017 //
2018 // For instance, if C is a class, and ET is the type of E,
2019 // the expression
2020 //
2021 // E.new <typeargs1>C<typargs2>(args) { ... }
2022 //
2023 // is translated to (where X is a fresh name and typarams is the
2024 // parameter list of the super constructor):
2025 //
2026 // new <typeargs1>X(<*nullchk*>E, args) where
2027 // X extends C<typargs2> {
2028 // <typarams> X(ET e, args) {
2029 // e.<typeargs1>super(args)
2030 // }
2031 // ...
2032 // }
2033 if (Resolve.isStatic(env)) cdef.mods.flags |= STATIC;
2035 if (clazztype.tsym.isInterface()) {
2036 cdef.implementing = List.of(clazz);
2037 } else {
2038 cdef.extending = clazz;
2039 }
2041 attribStat(cdef, localEnv);
2043 checkLambdaCandidate(tree, cdef.sym, clazztype);
2045 // If an outer instance is given,
2046 // prefix it to the constructor arguments
2047 // and delete it from the new expression
2048 if (tree.encl != null && !clazztype.tsym.isInterface()) {
2049 tree.args = tree.args.prepend(makeNullCheck(tree.encl));
2050 argtypes = argtypes.prepend(tree.encl.type);
2051 tree.encl = null;
2052 }
2054 // Reassign clazztype and recompute constructor.
2055 clazztype = cdef.sym.type;
2056 Symbol sym = tree.constructor = rs.resolveConstructor(
2057 tree.pos(), localEnv, clazztype, argtypes, typeargtypes);
2058 Assert.check(sym.kind < AMBIGUOUS);
2059 tree.constructor = sym;
2060 tree.constructorType = checkId(tree,
2061 clazztype,
2062 tree.constructor,
2063 localEnv,
2064 new ResultInfo(VAL, newMethodTemplate(syms.voidType, argtypes, typeargtypes)));
2065 }
2067 if (tree.constructor != null && tree.constructor.kind == MTH)
2068 owntype = clazztype;
2069 }
2070 result = check(tree, owntype, VAL, resultInfo);
2071 chk.validate(tree.typeargs, localEnv);
2072 }
2073 //where
2074 void findDiamondIfNeeded(Env<AttrContext> env, JCNewClass tree, Type clazztype) {
2075 if (tree.def == null &&
2076 !clazztype.isErroneous() &&
2077 clazztype.getTypeArguments().nonEmpty() &&
2078 findDiamonds) {
2079 JCTypeApply ta = (JCTypeApply)tree.clazz;
2080 List<JCExpression> prevTypeargs = ta.arguments;
2081 try {
2082 //create a 'fake' diamond AST node by removing type-argument trees
2083 ta.arguments = List.nil();
2084 ResultInfo findDiamondResult = new ResultInfo(VAL,
2085 resultInfo.checkContext.inferenceContext().free(resultInfo.pt) ? Type.noType : pt());
2086 Type inferred = deferredAttr.attribSpeculative(tree, env, findDiamondResult).type;
2087 if (!inferred.isErroneous() &&
2088 types.isAssignable(inferred, pt().hasTag(NONE) ? syms.objectType : pt(), types.noWarnings)) {
2089 String key = types.isSameType(clazztype, inferred) ?
2090 "diamond.redundant.args" :
2091 "diamond.redundant.args.1";
2092 log.warning(tree.clazz.pos(), key, clazztype, inferred);
2093 }
2094 } finally {
2095 ta.arguments = prevTypeargs;
2096 }
2097 }
2098 }
2100 private void checkLambdaCandidate(JCNewClass tree, ClassSymbol csym, Type clazztype) {
2101 if (allowLambda &&
2102 identifyLambdaCandidate &&
2103 clazztype.hasTag(CLASS) &&
2104 !pt().hasTag(NONE) &&
2105 types.isFunctionalInterface(clazztype.tsym)) {
2106 Symbol descriptor = types.findDescriptorSymbol(clazztype.tsym);
2107 int count = 0;
2108 boolean found = false;
2109 for (Symbol sym : csym.members().getElements()) {
2110 if ((sym.flags() & SYNTHETIC) != 0 ||
2111 sym.isConstructor()) continue;
2112 count++;
2113 if (sym.kind != MTH ||
2114 !sym.name.equals(descriptor.name)) continue;
2115 Type mtype = types.memberType(clazztype, sym);
2116 if (types.overrideEquivalent(mtype, types.memberType(clazztype, descriptor))) {
2117 found = true;
2118 }
2119 }
2120 if (found && count == 1) {
2121 log.note(tree.def, "potential.lambda.found");
2122 }
2123 }
2124 }
2126 /** Make an attributed null check tree.
2127 */
2128 public JCExpression makeNullCheck(JCExpression arg) {
2129 // optimization: X.this is never null; skip null check
2130 Name name = TreeInfo.name(arg);
2131 if (name == names._this || name == names._super) return arg;
2133 JCTree.Tag optag = NULLCHK;
2134 JCUnary tree = make.at(arg.pos).Unary(optag, arg);
2135 tree.operator = syms.nullcheck;
2136 tree.type = arg.type;
2137 return tree;
2138 }
2140 public void visitNewArray(JCNewArray tree) {
2141 Type owntype = types.createErrorType(tree.type);
2142 Env<AttrContext> localEnv = env.dup(tree);
2143 Type elemtype;
2144 if (tree.elemtype != null) {
2145 elemtype = attribType(tree.elemtype, localEnv);
2146 chk.validate(tree.elemtype, localEnv);
2147 owntype = elemtype;
2148 for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
2149 attribExpr(l.head, localEnv, syms.intType);
2150 owntype = new ArrayType(owntype, syms.arrayClass);
2151 }
2152 } else {
2153 // we are seeing an untyped aggregate { ... }
2154 // this is allowed only if the prototype is an array
2155 if (pt().hasTag(ARRAY)) {
2156 elemtype = types.elemtype(pt());
2157 } else {
2158 if (!pt().hasTag(ERROR)) {
2159 log.error(tree.pos(), "illegal.initializer.for.type",
2160 pt());
2161 }
2162 elemtype = types.createErrorType(pt());
2163 }
2164 }
2165 if (tree.elems != null) {
2166 attribExprs(tree.elems, localEnv, elemtype);
2167 owntype = new ArrayType(elemtype, syms.arrayClass);
2168 }
2169 if (!types.isReifiable(elemtype))
2170 log.error(tree.pos(), "generic.array.creation");
2171 result = check(tree, owntype, VAL, resultInfo);
2172 }
2174 /*
2175 * A lambda expression can only be attributed when a target-type is available.
2176 * In addition, if the target-type is that of a functional interface whose
2177 * descriptor contains inference variables in argument position the lambda expression
2178 * is 'stuck' (see DeferredAttr).
2179 */
2180 @Override
2181 public void visitLambda(final JCLambda that) {
2182 if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
2183 if (pt().hasTag(NONE)) {
2184 //lambda only allowed in assignment or method invocation/cast context
2185 log.error(that.pos(), "unexpected.lambda");
2186 }
2187 result = that.type = types.createErrorType(pt());
2188 return;
2189 }
2190 //create an environment for attribution of the lambda expression
2191 final Env<AttrContext> localEnv = lambdaEnv(that, env);
2192 boolean needsRecovery =
2193 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK;
2194 try {
2195 Type target = pt();
2196 List<Type> explicitParamTypes = null;
2197 if (that.paramKind == JCLambda.ParameterKind.EXPLICIT) {
2198 //attribute lambda parameters
2199 attribStats(that.params, localEnv);
2200 explicitParamTypes = TreeInfo.types(that.params);
2201 target = infer.instantiateFunctionalInterface(that, target, explicitParamTypes, resultInfo.checkContext);
2202 }
2204 Type lambdaType;
2205 if (pt() != Type.recoveryType) {
2206 target = checkIntersectionTarget(that, target, resultInfo.checkContext);
2207 lambdaType = types.findDescriptorType(target);
2208 chk.checkFunctionalInterface(that, target);
2209 } else {
2210 target = Type.recoveryType;
2211 lambdaType = fallbackDescriptorType(that);
2212 }
2214 setFunctionalInfo(that, pt(), lambdaType, resultInfo.checkContext.inferenceContext());
2216 if (lambdaType.hasTag(FORALL)) {
2217 //lambda expression target desc cannot be a generic method
2218 resultInfo.checkContext.report(that, diags.fragment("invalid.generic.lambda.target",
2219 lambdaType, kindName(target.tsym), target.tsym));
2220 result = that.type = types.createErrorType(pt());
2221 return;
2222 }
2224 if (that.paramKind == JCLambda.ParameterKind.IMPLICIT) {
2225 //add param type info in the AST
2226 List<Type> actuals = lambdaType.getParameterTypes();
2227 List<JCVariableDecl> params = that.params;
2229 boolean arityMismatch = false;
2231 while (params.nonEmpty()) {
2232 if (actuals.isEmpty()) {
2233 //not enough actuals to perform lambda parameter inference
2234 arityMismatch = true;
2235 }
2236 //reset previously set info
2237 Type argType = arityMismatch ?
2238 syms.errType :
2239 actuals.head;
2240 params.head.vartype = make.Type(argType);
2241 params.head.sym = null;
2242 actuals = actuals.isEmpty() ?
2243 actuals :
2244 actuals.tail;
2245 params = params.tail;
2246 }
2248 //attribute lambda parameters
2249 attribStats(that.params, localEnv);
2251 if (arityMismatch) {
2252 resultInfo.checkContext.report(that, diags.fragment("incompatible.arg.types.in.lambda"));
2253 result = that.type = types.createErrorType(target);
2254 return;
2255 }
2256 }
2258 //from this point on, no recovery is needed; if we are in assignment context
2259 //we will be able to attribute the whole lambda body, regardless of errors;
2260 //if we are in a 'check' method context, and the lambda is not compatible
2261 //with the target-type, it will be recovered anyway in Attr.checkId
2262 needsRecovery = false;
2264 FunctionalReturnContext funcContext = that.getBodyKind() == JCLambda.BodyKind.EXPRESSION ?
2265 new ExpressionLambdaReturnContext((JCExpression)that.getBody(), resultInfo.checkContext) :
2266 new FunctionalReturnContext(resultInfo.checkContext);
2268 ResultInfo bodyResultInfo = lambdaType.getReturnType() == Type.recoveryType ?
2269 recoveryInfo :
2270 new ResultInfo(VAL, lambdaType.getReturnType(), funcContext);
2271 localEnv.info.returnResult = bodyResultInfo;
2273 if (that.getBodyKind() == JCLambda.BodyKind.EXPRESSION) {
2274 attribTree(that.getBody(), localEnv, bodyResultInfo);
2275 } else {
2276 JCBlock body = (JCBlock)that.body;
2277 attribStats(body.stats, localEnv);
2278 }
2280 result = check(that, target, VAL, resultInfo);
2282 boolean isSpeculativeRound =
2283 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
2285 postAttr(that);
2286 flow.analyzeLambda(env, that, make, isSpeculativeRound);
2288 checkLambdaCompatible(that, lambdaType, resultInfo.checkContext, isSpeculativeRound);
2290 if (!isSpeculativeRound) {
2291 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), lambdaType, target);
2292 }
2293 result = check(that, target, VAL, resultInfo);
2294 } catch (Types.FunctionDescriptorLookupError ex) {
2295 JCDiagnostic cause = ex.getDiagnostic();
2296 resultInfo.checkContext.report(that, cause);
2297 result = that.type = types.createErrorType(pt());
2298 return;
2299 } finally {
2300 localEnv.info.scope.leave();
2301 if (needsRecovery) {
2302 attribTree(that, env, recoveryInfo);
2303 }
2304 }
2305 }
2307 private Type checkIntersectionTarget(DiagnosticPosition pos, Type pt, CheckContext checkContext) {
2308 if (pt != Type.recoveryType && pt.isCompound()) {
2309 IntersectionClassType ict = (IntersectionClassType)pt;
2310 List<Type> bounds = ict.allInterfaces ?
2311 ict.getComponents().tail :
2312 ict.getComponents();
2313 types.findDescriptorType(bounds.head); //propagate exception outwards!
2314 for (Type bound : bounds.tail) {
2315 if (!types.isMarkerInterface(bound)) {
2316 checkContext.report(pos, diags.fragment("secondary.bound.must.be.marker.intf", bound));
2317 }
2318 }
2319 //for now (translation doesn't support intersection types)
2320 return bounds.head;
2321 } else {
2322 return pt;
2323 }
2324 }
2325 //where
2326 private Type fallbackDescriptorType(JCExpression tree) {
2327 switch (tree.getTag()) {
2328 case LAMBDA:
2329 JCLambda lambda = (JCLambda)tree;
2330 List<Type> argtypes = List.nil();
2331 for (JCVariableDecl param : lambda.params) {
2332 argtypes = param.vartype != null ?
2333 argtypes.append(param.vartype.type) :
2334 argtypes.append(syms.errType);
2335 }
2336 return new MethodType(argtypes, Type.recoveryType, List.<Type>nil(), syms.methodClass);
2337 case REFERENCE:
2338 return new MethodType(List.<Type>nil(), Type.recoveryType, List.<Type>nil(), syms.methodClass);
2339 default:
2340 Assert.error("Cannot get here!");
2341 }
2342 return null;
2343 }
2345 private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env, final InferenceContext inferenceContext, final Type... ts) {
2346 checkAccessibleTypes(pos, env, inferenceContext, List.from(ts));
2347 }
2349 private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env, final InferenceContext inferenceContext, final List<Type> ts) {
2350 if (inferenceContext.free(ts)) {
2351 inferenceContext.addFreeTypeListener(ts, new FreeTypeListener() {
2352 @Override
2353 public void typesInferred(InferenceContext inferenceContext) {
2354 checkAccessibleTypes(pos, env, inferenceContext, inferenceContext.asInstTypes(ts, types));
2355 }
2356 });
2357 } else {
2358 for (Type t : ts) {
2359 rs.checkAccessibleType(env, t);
2360 }
2361 }
2362 }
2364 /**
2365 * Lambda/method reference have a special check context that ensures
2366 * that i.e. a lambda return type is compatible with the expected
2367 * type according to both the inherited context and the assignment
2368 * context.
2369 */
2370 class FunctionalReturnContext extends Check.NestedCheckContext {
2372 FunctionalReturnContext(CheckContext enclosingContext) {
2373 super(enclosingContext);
2374 }
2376 @Override
2377 public boolean compatible(Type found, Type req, Warner warn) {
2378 //return type must be compatible in both current context and assignment context
2379 return chk.basicHandler.compatible(found, inferenceContext().asFree(req, types), warn);
2380 }
2382 @Override
2383 public void report(DiagnosticPosition pos, JCDiagnostic details) {
2384 enclosingContext.report(pos, diags.fragment("incompatible.ret.type.in.lambda", details));
2385 }
2386 }
2388 class ExpressionLambdaReturnContext extends FunctionalReturnContext {
2390 JCExpression expr;
2392 ExpressionLambdaReturnContext(JCExpression expr, CheckContext enclosingContext) {
2393 super(enclosingContext);
2394 this.expr = expr;
2395 }
2397 @Override
2398 public boolean compatible(Type found, Type req, Warner warn) {
2399 //a void return is compatible with an expression statement lambda
2400 return TreeInfo.isExpressionStatement(expr) && req.hasTag(VOID) ||
2401 super.compatible(found, req, warn);
2402 }
2403 }
2405 /**
2406 * Lambda compatibility. Check that given return types, thrown types, parameter types
2407 * are compatible with the expected functional interface descriptor. This means that:
2408 * (i) parameter types must be identical to those of the target descriptor; (ii) return
2409 * types must be compatible with the return type of the expected descriptor;
2410 * (iii) thrown types must be 'included' in the thrown types list of the expected
2411 * descriptor.
2412 */
2413 private void checkLambdaCompatible(JCLambda tree, Type descriptor, CheckContext checkContext, boolean speculativeAttr) {
2414 Type returnType = checkContext.inferenceContext().asFree(descriptor.getReturnType(), types);
2416 //return values have already been checked - but if lambda has no return
2417 //values, we must ensure that void/value compatibility is correct;
2418 //this amounts at checking that, if a lambda body can complete normally,
2419 //the descriptor's return type must be void
2420 if (tree.getBodyKind() == JCLambda.BodyKind.STATEMENT && tree.canCompleteNormally &&
2421 !returnType.hasTag(VOID) && returnType != Type.recoveryType) {
2422 checkContext.report(tree, diags.fragment("incompatible.ret.type.in.lambda",
2423 diags.fragment("missing.ret.val", returnType)));
2424 }
2426 List<Type> argTypes = checkContext.inferenceContext().asFree(descriptor.getParameterTypes(), types);
2427 if (!types.isSameTypes(argTypes, TreeInfo.types(tree.params))) {
2428 checkContext.report(tree, diags.fragment("incompatible.arg.types.in.lambda"));
2429 }
2431 if (!speculativeAttr) {
2432 List<Type> thrownTypes = checkContext.inferenceContext().asFree(descriptor.getThrownTypes(), types);
2433 if (chk.unhandled(tree.inferredThrownTypes == null ? List.<Type>nil() : tree.inferredThrownTypes, thrownTypes).nonEmpty()) {
2434 log.error(tree, "incompatible.thrown.types.in.lambda", tree.inferredThrownTypes);
2435 }
2436 }
2437 }
2439 private Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) {
2440 Env<AttrContext> lambdaEnv;
2441 Symbol owner = env.info.scope.owner;
2442 if (owner.kind == VAR && owner.owner.kind == TYP) {
2443 //field initializer
2444 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared()));
2445 lambdaEnv.info.scope.owner =
2446 new MethodSymbol(0, names.empty, null,
2447 env.info.scope.owner);
2448 } else {
2449 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dup()));
2450 }
2451 return lambdaEnv;
2452 }
2454 @Override
2455 public void visitReference(final JCMemberReference that) {
2456 if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
2457 if (pt().hasTag(NONE)) {
2458 //method reference only allowed in assignment or method invocation/cast context
2459 log.error(that.pos(), "unexpected.mref");
2460 }
2461 result = that.type = types.createErrorType(pt());
2462 return;
2463 }
2464 final Env<AttrContext> localEnv = env.dup(that);
2465 try {
2466 //attribute member reference qualifier - if this is a constructor
2467 //reference, the expected kind must be a type
2468 Type exprType = attribTree(that.expr,
2469 env, new ResultInfo(that.getMode() == ReferenceMode.INVOKE ? VAL | TYP : TYP, Type.noType));
2471 if (that.getMode() == JCMemberReference.ReferenceMode.NEW) {
2472 exprType = chk.checkConstructorRefType(that.expr, exprType);
2473 }
2475 if (exprType.isErroneous()) {
2476 //if the qualifier expression contains problems,
2477 //give up atttribution of method reference
2478 result = that.type = exprType;
2479 return;
2480 }
2482 if (TreeInfo.isStaticSelector(that.expr, names) &&
2483 (that.getMode() != ReferenceMode.NEW || !that.expr.type.isRaw())) {
2484 //if the qualifier is a type, validate it
2485 chk.validate(that.expr, env);
2486 }
2488 //attrib type-arguments
2489 List<Type> typeargtypes = List.nil();
2490 if (that.typeargs != null) {
2491 typeargtypes = attribTypes(that.typeargs, localEnv);
2492 }
2494 Type target;
2495 Type desc;
2496 if (pt() != Type.recoveryType) {
2497 target = checkIntersectionTarget(that, pt(), resultInfo.checkContext);
2498 desc = types.findDescriptorType(target);
2499 chk.checkFunctionalInterface(that, target);
2500 } else {
2501 target = Type.recoveryType;
2502 desc = fallbackDescriptorType(that);
2503 }
2505 setFunctionalInfo(that, pt(), desc, resultInfo.checkContext.inferenceContext());
2506 List<Type> argtypes = desc.getParameterTypes();
2508 Pair<Symbol, Resolve.ReferenceLookupHelper> refResult = rs.resolveMemberReference(that.pos(), localEnv, that,
2509 that.expr.type, that.name, argtypes, typeargtypes, true);
2511 Symbol refSym = refResult.fst;
2512 Resolve.ReferenceLookupHelper lookupHelper = refResult.snd;
2514 if (refSym.kind != MTH) {
2515 boolean targetError;
2516 switch (refSym.kind) {
2517 case ABSENT_MTH:
2518 targetError = false;
2519 break;
2520 case WRONG_MTH:
2521 case WRONG_MTHS:
2522 case AMBIGUOUS:
2523 case HIDDEN:
2524 case STATICERR:
2525 case MISSING_ENCL:
2526 targetError = true;
2527 break;
2528 default:
2529 Assert.error("unexpected result kind " + refSym.kind);
2530 targetError = false;
2531 }
2533 JCDiagnostic detailsDiag = ((Resolve.ResolveError)refSym).getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT,
2534 that, exprType.tsym, exprType, that.name, argtypes, typeargtypes);
2536 JCDiagnostic.DiagnosticType diagKind = targetError ?
2537 JCDiagnostic.DiagnosticType.FRAGMENT : JCDiagnostic.DiagnosticType.ERROR;
2539 JCDiagnostic diag = diags.create(diagKind, log.currentSource(), that,
2540 "invalid.mref", Kinds.kindName(that.getMode()), detailsDiag);
2542 if (targetError && target == Type.recoveryType) {
2543 //a target error doesn't make sense during recovery stage
2544 //as we don't know what actual parameter types are
2545 result = that.type = target;
2546 return;
2547 } else {
2548 if (targetError) {
2549 resultInfo.checkContext.report(that, diag);
2550 } else {
2551 log.report(diag);
2552 }
2553 result = that.type = types.createErrorType(target);
2554 return;
2555 }
2556 }
2558 if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
2559 if (refSym.isStatic() && TreeInfo.isStaticSelector(that.expr, names) &&
2560 exprType.getTypeArguments().nonEmpty()) {
2561 //static ref with class type-args
2562 log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
2563 diags.fragment("static.mref.with.targs"));
2564 result = that.type = types.createErrorType(target);
2565 return;
2566 }
2568 if (refSym.isStatic() && !TreeInfo.isStaticSelector(that.expr, names) &&
2569 !lookupHelper.referenceKind(refSym).isUnbound()) {
2570 //no static bound mrefs
2571 log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
2572 diags.fragment("static.bound.mref"));
2573 result = that.type = types.createErrorType(target);
2574 return;
2575 }
2576 }
2578 if (desc.getReturnType() == Type.recoveryType) {
2579 // stop here
2580 result = that.type = target;
2581 return;
2582 }
2584 that.sym = refSym.baseSymbol();
2585 that.kind = lookupHelper.referenceKind(that.sym);
2587 ResultInfo checkInfo =
2588 resultInfo.dup(newMethodTemplate(
2589 desc.getReturnType().hasTag(VOID) ? Type.noType : desc.getReturnType(),
2590 lookupHelper.argtypes,
2591 typeargtypes));
2593 Type refType = checkId(that, lookupHelper.site, refSym, localEnv, checkInfo);
2595 if (!refType.isErroneous()) {
2596 refType = types.createMethodTypeWithReturn(refType,
2597 adjustMethodReturnType(lookupHelper.site, that.name, checkInfo.pt.getParameterTypes(), refType.getReturnType()));
2598 }
2600 //go ahead with standard method reference compatibility check - note that param check
2601 //is a no-op (as this has been taken care during method applicability)
2602 boolean isSpeculativeRound =
2603 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
2604 checkReferenceCompatible(that, desc, refType, resultInfo.checkContext, isSpeculativeRound);
2605 if (!isSpeculativeRound) {
2606 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), desc, target);
2607 }
2608 result = check(that, target, VAL, resultInfo);
2609 } catch (Types.FunctionDescriptorLookupError ex) {
2610 JCDiagnostic cause = ex.getDiagnostic();
2611 resultInfo.checkContext.report(that, cause);
2612 result = that.type = types.createErrorType(pt());
2613 return;
2614 }
2615 }
2617 @SuppressWarnings("fallthrough")
2618 void checkReferenceCompatible(JCMemberReference tree, Type descriptor, Type refType, CheckContext checkContext, boolean speculativeAttr) {
2619 Type returnType = checkContext.inferenceContext().asFree(descriptor.getReturnType(), types);
2621 Type resType;
2622 switch (tree.getMode()) {
2623 case NEW:
2624 if (!tree.expr.type.isRaw()) {
2625 resType = tree.expr.type;
2626 break;
2627 }
2628 default:
2629 resType = refType.getReturnType();
2630 }
2632 Type incompatibleReturnType = resType;
2634 if (returnType.hasTag(VOID)) {
2635 incompatibleReturnType = null;
2636 }
2638 if (!returnType.hasTag(VOID) && !resType.hasTag(VOID)) {
2639 if (resType.isErroneous() ||
2640 new FunctionalReturnContext(checkContext).compatible(resType, returnType, types.noWarnings)) {
2641 incompatibleReturnType = null;
2642 }
2643 }
2645 if (incompatibleReturnType != null) {
2646 checkContext.report(tree, diags.fragment("incompatible.ret.type.in.mref",
2647 diags.fragment("inconvertible.types", resType, descriptor.getReturnType())));
2648 }
2650 if (!speculativeAttr) {
2651 List<Type> thrownTypes = checkContext.inferenceContext().asFree(descriptor.getThrownTypes(), types);
2652 if (chk.unhandled(refType.getThrownTypes(), thrownTypes).nonEmpty()) {
2653 log.error(tree, "incompatible.thrown.types.in.mref", refType.getThrownTypes());
2654 }
2655 }
2656 }
2658 /**
2659 * Set functional type info on the underlying AST. Note: as the target descriptor
2660 * might contain inference variables, we might need to register an hook in the
2661 * current inference context.
2662 */
2663 private void setFunctionalInfo(final JCFunctionalExpression fExpr, final Type pt, final Type descriptorType, InferenceContext inferenceContext) {
2664 if (inferenceContext.free(descriptorType)) {
2665 inferenceContext.addFreeTypeListener(List.of(pt, descriptorType), new FreeTypeListener() {
2666 public void typesInferred(InferenceContext inferenceContext) {
2667 setFunctionalInfo(fExpr, pt, inferenceContext.asInstType(descriptorType, types), inferenceContext);
2668 }
2669 });
2670 } else {
2671 ListBuffer<TypeSymbol> targets = ListBuffer.lb();
2672 if (pt.hasTag(CLASS)) {
2673 if (pt.isCompound()) {
2674 for (Type t : ((IntersectionClassType)pt()).interfaces_field) {
2675 targets.append(t.tsym);
2676 }
2677 } else {
2678 targets.append(pt.tsym);
2679 }
2680 }
2681 fExpr.targets = targets.toList();
2682 fExpr.descriptorType = descriptorType;
2683 }
2684 }
2686 public void visitParens(JCParens tree) {
2687 Type owntype = attribTree(tree.expr, env, resultInfo);
2688 result = check(tree, owntype, pkind(), resultInfo);
2689 Symbol sym = TreeInfo.symbol(tree);
2690 if (sym != null && (sym.kind&(TYP|PCK)) != 0)
2691 log.error(tree.pos(), "illegal.start.of.type");
2692 }
2694 public void visitAssign(JCAssign tree) {
2695 Type owntype = attribTree(tree.lhs, env.dup(tree), varInfo);
2696 Type capturedType = capture(owntype);
2697 attribExpr(tree.rhs, env, owntype);
2698 result = check(tree, capturedType, VAL, resultInfo);
2699 }
2701 public void visitAssignop(JCAssignOp tree) {
2702 // Attribute arguments.
2703 Type owntype = attribTree(tree.lhs, env, varInfo);
2704 Type operand = attribExpr(tree.rhs, env);
2705 // Find operator.
2706 Symbol operator = tree.operator = rs.resolveBinaryOperator(
2707 tree.pos(), tree.getTag().noAssignOp(), env,
2708 owntype, operand);
2710 if (operator.kind == MTH &&
2711 !owntype.isErroneous() &&
2712 !operand.isErroneous()) {
2713 chk.checkOperator(tree.pos(),
2714 (OperatorSymbol)operator,
2715 tree.getTag().noAssignOp(),
2716 owntype,
2717 operand);
2718 chk.checkDivZero(tree.rhs.pos(), operator, operand);
2719 chk.checkCastable(tree.rhs.pos(),
2720 operator.type.getReturnType(),
2721 owntype);
2722 }
2723 result = check(tree, owntype, VAL, resultInfo);
2724 }
2726 public void visitUnary(JCUnary tree) {
2727 // Attribute arguments.
2728 Type argtype = (tree.getTag().isIncOrDecUnaryOp())
2729 ? attribTree(tree.arg, env, varInfo)
2730 : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
2732 // Find operator.
2733 Symbol operator = tree.operator =
2734 rs.resolveUnaryOperator(tree.pos(), tree.getTag(), env, argtype);
2736 Type owntype = types.createErrorType(tree.type);
2737 if (operator.kind == MTH &&
2738 !argtype.isErroneous()) {
2739 owntype = (tree.getTag().isIncOrDecUnaryOp())
2740 ? tree.arg.type
2741 : operator.type.getReturnType();
2742 int opc = ((OperatorSymbol)operator).opcode;
2744 // If the argument is constant, fold it.
2745 if (argtype.constValue() != null) {
2746 Type ctype = cfolder.fold1(opc, argtype);
2747 if (ctype != null) {
2748 owntype = cfolder.coerce(ctype, owntype);
2750 // Remove constant types from arguments to
2751 // conserve space. The parser will fold concatenations
2752 // of string literals; the code here also
2753 // gets rid of intermediate results when some of the
2754 // operands are constant identifiers.
2755 if (tree.arg.type.tsym == syms.stringType.tsym) {
2756 tree.arg.type = syms.stringType;
2757 }
2758 }
2759 }
2760 }
2761 result = check(tree, owntype, VAL, resultInfo);
2762 }
2764 public void visitBinary(JCBinary tree) {
2765 // Attribute arguments.
2766 Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
2767 Type right = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.rhs, env));
2769 // Find operator.
2770 Symbol operator = tree.operator =
2771 rs.resolveBinaryOperator(tree.pos(), tree.getTag(), env, left, right);
2773 Type owntype = types.createErrorType(tree.type);
2774 if (operator.kind == MTH &&
2775 !left.isErroneous() &&
2776 !right.isErroneous()) {
2777 owntype = operator.type.getReturnType();
2778 int opc = chk.checkOperator(tree.lhs.pos(),
2779 (OperatorSymbol)operator,
2780 tree.getTag(),
2781 left,
2782 right);
2784 // If both arguments are constants, fold them.
2785 if (left.constValue() != null && right.constValue() != null) {
2786 Type ctype = cfolder.fold2(opc, left, right);
2787 if (ctype != null) {
2788 owntype = cfolder.coerce(ctype, owntype);
2790 // Remove constant types from arguments to
2791 // conserve space. The parser will fold concatenations
2792 // of string literals; the code here also
2793 // gets rid of intermediate results when some of the
2794 // operands are constant identifiers.
2795 if (tree.lhs.type.tsym == syms.stringType.tsym) {
2796 tree.lhs.type = syms.stringType;
2797 }
2798 if (tree.rhs.type.tsym == syms.stringType.tsym) {
2799 tree.rhs.type = syms.stringType;
2800 }
2801 }
2802 }
2804 // Check that argument types of a reference ==, != are
2805 // castable to each other, (JLS???).
2806 if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
2807 if (!types.isCastable(left, right, new Warner(tree.pos()))) {
2808 log.error(tree.pos(), "incomparable.types", left, right);
2809 }
2810 }
2812 chk.checkDivZero(tree.rhs.pos(), operator, right);
2813 }
2814 result = check(tree, owntype, VAL, resultInfo);
2815 }
2817 public void visitTypeCast(final JCTypeCast tree) {
2818 Type clazztype = attribType(tree.clazz, env);
2819 chk.validate(tree.clazz, env, false);
2820 //a fresh environment is required for 292 inference to work properly ---
2821 //see Infer.instantiatePolymorphicSignatureInstance()
2822 Env<AttrContext> localEnv = env.dup(tree);
2823 //should we propagate the target type?
2824 final ResultInfo castInfo;
2825 final boolean isPoly = TreeInfo.isPoly(tree.expr, tree);
2826 if (isPoly) {
2827 //expression is a poly - we need to propagate target type info
2828 castInfo = new ResultInfo(VAL, clazztype, new Check.NestedCheckContext(resultInfo.checkContext) {
2829 @Override
2830 public boolean compatible(Type found, Type req, Warner warn) {
2831 return types.isCastable(found, req, warn);
2832 }
2833 });
2834 } else {
2835 //standalone cast - target-type info is not propagated
2836 castInfo = unknownExprInfo;
2837 }
2838 Type exprtype = attribTree(tree.expr, localEnv, castInfo);
2839 Type owntype = isPoly ? clazztype : chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
2840 if (exprtype.constValue() != null)
2841 owntype = cfolder.coerce(exprtype, owntype);
2842 result = check(tree, capture(owntype), VAL, resultInfo);
2843 if (!isPoly)
2844 chk.checkRedundantCast(localEnv, tree);
2845 }
2847 public void visitTypeTest(JCInstanceOf tree) {
2848 Type exprtype = chk.checkNullOrRefType(
2849 tree.expr.pos(), attribExpr(tree.expr, env));
2850 Type clazztype = chk.checkReifiableReferenceType(
2851 tree.clazz.pos(), attribType(tree.clazz, env));
2852 chk.validate(tree.clazz, env, false);
2853 chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
2854 result = check(tree, syms.booleanType, VAL, resultInfo);
2855 }
2857 public void visitIndexed(JCArrayAccess tree) {
2858 Type owntype = types.createErrorType(tree.type);
2859 Type atype = attribExpr(tree.indexed, env);
2860 attribExpr(tree.index, env, syms.intType);
2861 if (types.isArray(atype))
2862 owntype = types.elemtype(atype);
2863 else if (!atype.hasTag(ERROR))
2864 log.error(tree.pos(), "array.req.but.found", atype);
2865 if ((pkind() & VAR) == 0) owntype = capture(owntype);
2866 result = check(tree, owntype, VAR, resultInfo);
2867 }
2869 public void visitIdent(JCIdent tree) {
2870 Symbol sym;
2872 // Find symbol
2873 if (pt().hasTag(METHOD) || pt().hasTag(FORALL)) {
2874 // If we are looking for a method, the prototype `pt' will be a
2875 // method type with the type of the call's arguments as parameters.
2876 env.info.pendingResolutionPhase = null;
2877 sym = rs.resolveMethod(tree.pos(), env, tree.name, pt().getParameterTypes(), pt().getTypeArguments());
2878 } else if (tree.sym != null && tree.sym.kind != VAR) {
2879 sym = tree.sym;
2880 } else {
2881 sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind());
2882 }
2883 tree.sym = sym;
2885 // (1) Also find the environment current for the class where
2886 // sym is defined (`symEnv').
2887 // Only for pre-tiger versions (1.4 and earlier):
2888 // (2) Also determine whether we access symbol out of an anonymous
2889 // class in a this or super call. This is illegal for instance
2890 // members since such classes don't carry a this$n link.
2891 // (`noOuterThisPath').
2892 Env<AttrContext> symEnv = env;
2893 boolean noOuterThisPath = false;
2894 if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
2895 (sym.kind & (VAR | MTH | TYP)) != 0 &&
2896 sym.owner.kind == TYP &&
2897 tree.name != names._this && tree.name != names._super) {
2899 // Find environment in which identifier is defined.
2900 while (symEnv.outer != null &&
2901 !sym.isMemberOf(symEnv.enclClass.sym, types)) {
2902 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
2903 noOuterThisPath = !allowAnonOuterThis;
2904 symEnv = symEnv.outer;
2905 }
2906 }
2908 // If symbol is a variable, ...
2909 if (sym.kind == VAR) {
2910 VarSymbol v = (VarSymbol)sym;
2912 // ..., evaluate its initializer, if it has one, and check for
2913 // illegal forward reference.
2914 checkInit(tree, env, v, false);
2916 // If we are expecting a variable (as opposed to a value), check
2917 // that the variable is assignable in the current environment.
2918 if (pkind() == VAR)
2919 checkAssignable(tree.pos(), v, null, env);
2920 }
2922 // In a constructor body,
2923 // if symbol is a field or instance method, check that it is
2924 // not accessed before the supertype constructor is called.
2925 if ((symEnv.info.isSelfCall || noOuterThisPath) &&
2926 (sym.kind & (VAR | MTH)) != 0 &&
2927 sym.owner.kind == TYP &&
2928 (sym.flags() & STATIC) == 0) {
2929 chk.earlyRefError(tree.pos(), sym.kind == VAR ? sym : thisSym(tree.pos(), env));
2930 }
2931 Env<AttrContext> env1 = env;
2932 if (sym.kind != ERR && sym.kind != TYP && sym.owner != null && sym.owner != env1.enclClass.sym) {
2933 // If the found symbol is inaccessible, then it is
2934 // accessed through an enclosing instance. Locate this
2935 // enclosing instance:
2936 while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
2937 env1 = env1.outer;
2938 }
2939 result = checkId(tree, env1.enclClass.sym.type, sym, env, resultInfo);
2940 }
2942 public void visitSelect(JCFieldAccess tree) {
2943 // Determine the expected kind of the qualifier expression.
2944 int skind = 0;
2945 if (tree.name == names._this || tree.name == names._super ||
2946 tree.name == names._class)
2947 {
2948 skind = TYP;
2949 } else {
2950 if ((pkind() & PCK) != 0) skind = skind | PCK;
2951 if ((pkind() & TYP) != 0) skind = skind | TYP | PCK;
2952 if ((pkind() & (VAL | MTH)) != 0) skind = skind | VAL | TYP;
2953 }
2955 // Attribute the qualifier expression, and determine its symbol (if any).
2956 Type site = attribTree(tree.selected, env, new ResultInfo(skind, Infer.anyPoly));
2957 if ((pkind() & (PCK | TYP)) == 0)
2958 site = capture(site); // Capture field access
2960 // don't allow T.class T[].class, etc
2961 if (skind == TYP) {
2962 Type elt = site;
2963 while (elt.hasTag(ARRAY))
2964 elt = ((ArrayType)elt).elemtype;
2965 if (elt.hasTag(TYPEVAR)) {
2966 log.error(tree.pos(), "type.var.cant.be.deref");
2967 result = types.createErrorType(tree.type);
2968 return;
2969 }
2970 }
2972 // If qualifier symbol is a type or `super', assert `selectSuper'
2973 // for the selection. This is relevant for determining whether
2974 // protected symbols are accessible.
2975 Symbol sitesym = TreeInfo.symbol(tree.selected);
2976 boolean selectSuperPrev = env.info.selectSuper;
2977 env.info.selectSuper =
2978 sitesym != null &&
2979 sitesym.name == names._super;
2981 // Determine the symbol represented by the selection.
2982 env.info.pendingResolutionPhase = null;
2983 Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
2984 if (sym.exists() && !isType(sym) && (pkind() & (PCK | TYP)) != 0) {
2985 site = capture(site);
2986 sym = selectSym(tree, sitesym, site, env, resultInfo);
2987 }
2988 boolean varArgs = env.info.lastResolveVarargs();
2989 tree.sym = sym;
2991 if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) {
2992 while (site.hasTag(TYPEVAR)) site = site.getUpperBound();
2993 site = capture(site);
2994 }
2996 // If that symbol is a variable, ...
2997 if (sym.kind == VAR) {
2998 VarSymbol v = (VarSymbol)sym;
3000 // ..., evaluate its initializer, if it has one, and check for
3001 // illegal forward reference.
3002 checkInit(tree, env, v, true);
3004 // If we are expecting a variable (as opposed to a value), check
3005 // that the variable is assignable in the current environment.
3006 if (pkind() == VAR)
3007 checkAssignable(tree.pos(), v, tree.selected, env);
3008 }
3010 if (sitesym != null &&
3011 sitesym.kind == VAR &&
3012 ((VarSymbol)sitesym).isResourceVariable() &&
3013 sym.kind == MTH &&
3014 sym.name.equals(names.close) &&
3015 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) &&
3016 env.info.lint.isEnabled(LintCategory.TRY)) {
3017 log.warning(LintCategory.TRY, tree, "try.explicit.close.call");
3018 }
3020 // Disallow selecting a type from an expression
3021 if (isType(sym) && (sitesym==null || (sitesym.kind&(TYP|PCK)) == 0)) {
3022 tree.type = check(tree.selected, pt(),
3023 sitesym == null ? VAL : sitesym.kind, new ResultInfo(TYP|PCK, pt()));
3024 }
3026 if (isType(sitesym)) {
3027 if (sym.name == names._this) {
3028 // If `C' is the currently compiled class, check that
3029 // C.this' does not appear in a call to a super(...)
3030 if (env.info.isSelfCall &&
3031 site.tsym == env.enclClass.sym) {
3032 chk.earlyRefError(tree.pos(), sym);
3033 }
3034 } else {
3035 // Check if type-qualified fields or methods are static (JLS)
3036 if ((sym.flags() & STATIC) == 0 &&
3037 !env.next.tree.hasTag(REFERENCE) &&
3038 sym.name != names._super &&
3039 (sym.kind == VAR || sym.kind == MTH)) {
3040 rs.accessBase(rs.new StaticError(sym),
3041 tree.pos(), site, sym.name, true);
3042 }
3043 }
3044 } else if (sym.kind != ERR && (sym.flags() & STATIC) != 0 && sym.name != names._class) {
3045 // If the qualified item is not a type and the selected item is static, report
3046 // a warning. Make allowance for the class of an array type e.g. Object[].class)
3047 chk.warnStatic(tree, "static.not.qualified.by.type", Kinds.kindName(sym.kind), sym.owner);
3048 }
3050 // If we are selecting an instance member via a `super', ...
3051 if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
3053 // Check that super-qualified symbols are not abstract (JLS)
3054 rs.checkNonAbstract(tree.pos(), sym);
3056 if (site.isRaw()) {
3057 // Determine argument types for site.
3058 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
3059 if (site1 != null) site = site1;
3060 }
3061 }
3063 env.info.selectSuper = selectSuperPrev;
3064 result = checkId(tree, site, sym, env, resultInfo);
3065 }
3066 //where
3067 /** Determine symbol referenced by a Select expression,
3068 *
3069 * @param tree The select tree.
3070 * @param site The type of the selected expression,
3071 * @param env The current environment.
3072 * @param resultInfo The current result.
3073 */
3074 private Symbol selectSym(JCFieldAccess tree,
3075 Symbol location,
3076 Type site,
3077 Env<AttrContext> env,
3078 ResultInfo resultInfo) {
3079 DiagnosticPosition pos = tree.pos();
3080 Name name = tree.name;
3081 switch (site.getTag()) {
3082 case PACKAGE:
3083 return rs.accessBase(
3084 rs.findIdentInPackage(env, site.tsym, name, resultInfo.pkind),
3085 pos, location, site, name, true);
3086 case ARRAY:
3087 case CLASS:
3088 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) {
3089 return rs.resolveQualifiedMethod(
3090 pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
3091 } else if (name == names._this || name == names._super) {
3092 return rs.resolveSelf(pos, env, site.tsym, name);
3093 } else if (name == names._class) {
3094 // In this case, we have already made sure in
3095 // visitSelect that qualifier expression is a type.
3096 Type t = syms.classType;
3097 List<Type> typeargs = allowGenerics
3098 ? List.of(types.erasure(site))
3099 : List.<Type>nil();
3100 t = new ClassType(t.getEnclosingType(), typeargs, t.tsym);
3101 return new VarSymbol(
3102 STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
3103 } else {
3104 // We are seeing a plain identifier as selector.
3105 Symbol sym = rs.findIdentInType(env, site, name, resultInfo.pkind);
3106 if ((resultInfo.pkind & ERRONEOUS) == 0)
3107 sym = rs.accessBase(sym, pos, location, site, name, true);
3108 return sym;
3109 }
3110 case WILDCARD:
3111 throw new AssertionError(tree);
3112 case TYPEVAR:
3113 // Normally, site.getUpperBound() shouldn't be null.
3114 // It should only happen during memberEnter/attribBase
3115 // when determining the super type which *must* beac
3116 // done before attributing the type variables. In
3117 // other words, we are seeing this illegal program:
3118 // class B<T> extends A<T.foo> {}
3119 Symbol sym = (site.getUpperBound() != null)
3120 ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
3121 : null;
3122 if (sym == null) {
3123 log.error(pos, "type.var.cant.be.deref");
3124 return syms.errSymbol;
3125 } else {
3126 Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
3127 rs.new AccessError(env, site, sym) :
3128 sym;
3129 rs.accessBase(sym2, pos, location, site, name, true);
3130 return sym;
3131 }
3132 case ERROR:
3133 // preserve identifier names through errors
3134 return types.createErrorType(name, site.tsym, site).tsym;
3135 default:
3136 // The qualifier expression is of a primitive type -- only
3137 // .class is allowed for these.
3138 if (name == names._class) {
3139 // In this case, we have already made sure in Select that
3140 // qualifier expression is a type.
3141 Type t = syms.classType;
3142 Type arg = types.boxedClass(site).type;
3143 t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym);
3144 return new VarSymbol(
3145 STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
3146 } else {
3147 log.error(pos, "cant.deref", site);
3148 return syms.errSymbol;
3149 }
3150 }
3151 }
3153 /** Determine type of identifier or select expression and check that
3154 * (1) the referenced symbol is not deprecated
3155 * (2) the symbol's type is safe (@see checkSafe)
3156 * (3) if symbol is a variable, check that its type and kind are
3157 * compatible with the prototype and protokind.
3158 * (4) if symbol is an instance field of a raw type,
3159 * which is being assigned to, issue an unchecked warning if its
3160 * type changes under erasure.
3161 * (5) if symbol is an instance method of a raw type, issue an
3162 * unchecked warning if its argument types change under erasure.
3163 * If checks succeed:
3164 * If symbol is a constant, return its constant type
3165 * else if symbol is a method, return its result type
3166 * otherwise return its type.
3167 * Otherwise return errType.
3168 *
3169 * @param tree The syntax tree representing the identifier
3170 * @param site If this is a select, the type of the selected
3171 * expression, otherwise the type of the current class.
3172 * @param sym The symbol representing the identifier.
3173 * @param env The current environment.
3174 * @param resultInfo The expected result
3175 */
3176 Type checkId(JCTree tree,
3177 Type site,
3178 Symbol sym,
3179 Env<AttrContext> env,
3180 ResultInfo resultInfo) {
3181 return (resultInfo.pt.hasTag(FORALL) || resultInfo.pt.hasTag(METHOD)) ?
3182 checkMethodId(tree, site, sym, env, resultInfo) :
3183 checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
3184 }
3186 Type checkMethodId(JCTree tree,
3187 Type site,
3188 Symbol sym,
3189 Env<AttrContext> env,
3190 ResultInfo resultInfo) {
3191 boolean isPolymorhicSignature =
3192 sym.kind == MTH && ((MethodSymbol)sym.baseSymbol()).isSignaturePolymorphic(types);
3193 return isPolymorhicSignature ?
3194 checkSigPolyMethodId(tree, site, sym, env, resultInfo) :
3195 checkMethodIdInternal(tree, site, sym, env, resultInfo);
3196 }
3198 Type checkSigPolyMethodId(JCTree tree,
3199 Type site,
3200 Symbol sym,
3201 Env<AttrContext> env,
3202 ResultInfo resultInfo) {
3203 //recover original symbol for signature polymorphic methods
3204 checkMethodIdInternal(tree, site, sym.baseSymbol(), env, resultInfo);
3205 env.info.pendingResolutionPhase = Resolve.MethodResolutionPhase.BASIC;
3206 return sym.type;
3207 }
3209 Type checkMethodIdInternal(JCTree tree,
3210 Type site,
3211 Symbol sym,
3212 Env<AttrContext> env,
3213 ResultInfo resultInfo) {
3214 Type pt = resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, sym, env.info.pendingResolutionPhase));
3215 Type owntype = checkIdInternal(tree, site, sym, pt, env, resultInfo);
3216 resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
3217 return owntype;
3218 }
3220 Type checkIdInternal(JCTree tree,
3221 Type site,
3222 Symbol sym,
3223 Type pt,
3224 Env<AttrContext> env,
3225 ResultInfo resultInfo) {
3226 if (pt.isErroneous()) {
3227 return types.createErrorType(site);
3228 }
3229 Type owntype; // The computed type of this identifier occurrence.
3230 switch (sym.kind) {
3231 case TYP:
3232 // For types, the computed type equals the symbol's type,
3233 // except for two situations:
3234 owntype = sym.type;
3235 if (owntype.hasTag(CLASS)) {
3236 chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym);
3237 Type ownOuter = owntype.getEnclosingType();
3239 // (a) If the symbol's type is parameterized, erase it
3240 // because no type parameters were given.
3241 // We recover generic outer type later in visitTypeApply.
3242 if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
3243 owntype = types.erasure(owntype);
3244 }
3246 // (b) If the symbol's type is an inner class, then
3247 // we have to interpret its outer type as a superclass
3248 // of the site type. Example:
3249 //
3250 // class Tree<A> { class Visitor { ... } }
3251 // class PointTree extends Tree<Point> { ... }
3252 // ...PointTree.Visitor...
3253 //
3254 // Then the type of the last expression above is
3255 // Tree<Point>.Visitor.
3256 else if (ownOuter.hasTag(CLASS) && site != ownOuter) {
3257 Type normOuter = site;
3258 if (normOuter.hasTag(CLASS))
3259 normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
3260 if (normOuter == null) // perhaps from an import
3261 normOuter = types.erasure(ownOuter);
3262 if (normOuter != ownOuter)
3263 owntype = new ClassType(
3264 normOuter, List.<Type>nil(), owntype.tsym);
3265 }
3266 }
3267 break;
3268 case VAR:
3269 VarSymbol v = (VarSymbol)sym;
3270 // Test (4): if symbol is an instance field of a raw type,
3271 // which is being assigned to, issue an unchecked warning if
3272 // its type changes under erasure.
3273 if (allowGenerics &&
3274 resultInfo.pkind == VAR &&
3275 v.owner.kind == TYP &&
3276 (v.flags() & STATIC) == 0 &&
3277 (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
3278 Type s = types.asOuterSuper(site, v.owner);
3279 if (s != null &&
3280 s.isRaw() &&
3281 !types.isSameType(v.type, v.erasure(types))) {
3282 chk.warnUnchecked(tree.pos(),
3283 "unchecked.assign.to.var",
3284 v, s);
3285 }
3286 }
3287 // The computed type of a variable is the type of the
3288 // variable symbol, taken as a member of the site type.
3289 owntype = (sym.owner.kind == TYP &&
3290 sym.name != names._this && sym.name != names._super)
3291 ? types.memberType(site, sym)
3292 : sym.type;
3294 // If the variable is a constant, record constant value in
3295 // computed type.
3296 if (v.getConstValue() != null && isStaticReference(tree))
3297 owntype = owntype.constType(v.getConstValue());
3299 if (resultInfo.pkind == VAL) {
3300 owntype = capture(owntype); // capture "names as expressions"
3301 }
3302 break;
3303 case MTH: {
3304 owntype = checkMethod(site, sym,
3305 new ResultInfo(VAL, resultInfo.pt.getReturnType(), resultInfo.checkContext),
3306 env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(),
3307 resultInfo.pt.getTypeArguments());
3308 break;
3309 }
3310 case PCK: case ERR:
3311 owntype = sym.type;
3312 break;
3313 default:
3314 throw new AssertionError("unexpected kind: " + sym.kind +
3315 " in tree " + tree);
3316 }
3318 // Test (1): emit a `deprecation' warning if symbol is deprecated.
3319 // (for constructors, the error was given when the constructor was
3320 // resolved)
3322 if (sym.name != names.init) {
3323 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym);
3324 chk.checkSunAPI(tree.pos(), sym);
3325 }
3327 // Test (3): if symbol is a variable, check that its type and
3328 // kind are compatible with the prototype and protokind.
3329 return check(tree, owntype, sym.kind, resultInfo);
3330 }
3332 /** Check that variable is initialized and evaluate the variable's
3333 * initializer, if not yet done. Also check that variable is not
3334 * referenced before it is defined.
3335 * @param tree The tree making up the variable reference.
3336 * @param env The current environment.
3337 * @param v The variable's symbol.
3338 */
3339 private void checkInit(JCTree tree,
3340 Env<AttrContext> env,
3341 VarSymbol v,
3342 boolean onlyWarning) {
3343 // System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " +
3344 // tree.pos + " " + v.pos + " " +
3345 // Resolve.isStatic(env));//DEBUG
3347 // A forward reference is diagnosed if the declaration position
3348 // of the variable is greater than the current tree position
3349 // and the tree and variable definition occur in the same class
3350 // definition. Note that writes don't count as references.
3351 // This check applies only to class and instance
3352 // variables. Local variables follow different scope rules,
3353 // and are subject to definite assignment checking.
3354 if ((env.info.enclVar == v || v.pos > tree.pos) &&
3355 v.owner.kind == TYP &&
3356 canOwnInitializer(owner(env)) &&
3357 v.owner == env.info.scope.owner.enclClass() &&
3358 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
3359 (!env.tree.hasTag(ASSIGN) ||
3360 TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
3361 String suffix = (env.info.enclVar == v) ?
3362 "self.ref" : "forward.ref";
3363 if (!onlyWarning || isStaticEnumField(v)) {
3364 log.error(tree.pos(), "illegal." + suffix);
3365 } else if (useBeforeDeclarationWarning) {
3366 log.warning(tree.pos(), suffix, v);
3367 }
3368 }
3370 v.getConstValue(); // ensure initializer is evaluated
3372 checkEnumInitializer(tree, env, v);
3373 }
3375 /**
3376 * Check for illegal references to static members of enum. In
3377 * an enum type, constructors and initializers may not
3378 * reference its static members unless they are constant.
3379 *
3380 * @param tree The tree making up the variable reference.
3381 * @param env The current environment.
3382 * @param v The variable's symbol.
3383 * @jls section 8.9 Enums
3384 */
3385 private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
3386 // JLS:
3387 //
3388 // "It is a compile-time error to reference a static field
3389 // of an enum type that is not a compile-time constant
3390 // (15.28) from constructors, instance initializer blocks,
3391 // or instance variable initializer expressions of that
3392 // type. It is a compile-time error for the constructors,
3393 // instance initializer blocks, or instance variable
3394 // initializer expressions of an enum constant e to refer
3395 // to itself or to an enum constant of the same type that
3396 // is declared to the right of e."
3397 if (isStaticEnumField(v)) {
3398 ClassSymbol enclClass = env.info.scope.owner.enclClass();
3400 if (enclClass == null || enclClass.owner == null)
3401 return;
3403 // See if the enclosing class is the enum (or a
3404 // subclass thereof) declaring v. If not, this
3405 // reference is OK.
3406 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
3407 return;
3409 // If the reference isn't from an initializer, then
3410 // the reference is OK.
3411 if (!Resolve.isInitializer(env))
3412 return;
3414 log.error(tree.pos(), "illegal.enum.static.ref");
3415 }
3416 }
3418 /** Is the given symbol a static, non-constant field of an Enum?
3419 * Note: enum literals should not be regarded as such
3420 */
3421 private boolean isStaticEnumField(VarSymbol v) {
3422 return Flags.isEnum(v.owner) &&
3423 Flags.isStatic(v) &&
3424 !Flags.isConstant(v) &&
3425 v.name != names._class;
3426 }
3428 /** Can the given symbol be the owner of code which forms part
3429 * if class initialization? This is the case if the symbol is
3430 * a type or field, or if the symbol is the synthetic method.
3431 * owning a block.
3432 */
3433 private boolean canOwnInitializer(Symbol sym) {
3434 return
3435 (sym.kind & (VAR | TYP)) != 0 ||
3436 (sym.kind == MTH && (sym.flags() & BLOCK) != 0);
3437 }
3439 Warner noteWarner = new Warner();
3441 /**
3442 * Check that method arguments conform to its instantiation.
3443 **/
3444 public Type checkMethod(Type site,
3445 Symbol sym,
3446 ResultInfo resultInfo,
3447 Env<AttrContext> env,
3448 final List<JCExpression> argtrees,
3449 List<Type> argtypes,
3450 List<Type> typeargtypes) {
3451 // Test (5): if symbol is an instance method of a raw type, issue
3452 // an unchecked warning if its argument types change under erasure.
3453 if (allowGenerics &&
3454 (sym.flags() & STATIC) == 0 &&
3455 (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
3456 Type s = types.asOuterSuper(site, sym.owner);
3457 if (s != null && s.isRaw() &&
3458 !types.isSameTypes(sym.type.getParameterTypes(),
3459 sym.erasure(types).getParameterTypes())) {
3460 chk.warnUnchecked(env.tree.pos(),
3461 "unchecked.call.mbr.of.raw.type",
3462 sym, s);
3463 }
3464 }
3466 if (env.info.defaultSuperCallSite != null) {
3467 for (Type sup : types.interfaces(env.enclClass.type).prepend(types.supertype((env.enclClass.type)))) {
3468 if (!sup.tsym.isSubClass(sym.enclClass(), types) ||
3469 types.isSameType(sup, env.info.defaultSuperCallSite)) continue;
3470 List<MethodSymbol> icand_sup =
3471 types.interfaceCandidates(sup, (MethodSymbol)sym);
3472 if (icand_sup.nonEmpty() &&
3473 icand_sup.head != sym &&
3474 icand_sup.head.overrides(sym, icand_sup.head.enclClass(), types, true)) {
3475 log.error(env.tree.pos(), "illegal.default.super.call", env.info.defaultSuperCallSite,
3476 diags.fragment("overridden.default", sym, sup));
3477 break;
3478 }
3479 }
3480 env.info.defaultSuperCallSite = null;
3481 }
3483 if (sym.isStatic() && site.isInterface()) {
3484 Assert.check(env.tree.hasTag(APPLY));
3485 JCMethodInvocation app = (JCMethodInvocation)env.tree;
3486 if (app.meth.hasTag(SELECT) &&
3487 !TreeInfo.isStaticSelector(((JCFieldAccess)app.meth).selected, names)) {
3488 log.error(env.tree.pos(), "illegal.static.intf.meth.call", site);
3489 }
3490 }
3492 // Compute the identifier's instantiated type.
3493 // For methods, we need to compute the instance type by
3494 // Resolve.instantiate from the symbol's type as well as
3495 // any type arguments and value arguments.
3496 noteWarner.clear();
3497 try {
3498 Type owntype = rs.checkMethod(
3499 env,
3500 site,
3501 sym,
3502 resultInfo,
3503 argtypes,
3504 typeargtypes,
3505 noteWarner);
3507 return chk.checkMethod(owntype, sym, env, argtrees, argtypes, env.info.lastResolveVarargs(),
3508 noteWarner.hasNonSilentLint(LintCategory.UNCHECKED));
3509 } catch (Infer.InferenceException ex) {
3510 //invalid target type - propagate exception outwards or report error
3511 //depending on the current check context
3512 resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic());
3513 return types.createErrorType(site);
3514 } catch (Resolve.InapplicableMethodException ex) {
3515 Assert.error(ex.getDiagnostic().getMessage(Locale.getDefault()));
3516 return null;
3517 }
3518 }
3520 public void visitLiteral(JCLiteral tree) {
3521 result = check(
3522 tree, litType(tree.typetag).constType(tree.value), VAL, resultInfo);
3523 }
3524 //where
3525 /** Return the type of a literal with given type tag.
3526 */
3527 Type litType(TypeTag tag) {
3528 return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()];
3529 }
3531 public void visitTypeIdent(JCPrimitiveTypeTree tree) {
3532 result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], TYP, resultInfo);
3533 }
3535 public void visitTypeArray(JCArrayTypeTree tree) {
3536 Type etype = attribType(tree.elemtype, env);
3537 Type type = new ArrayType(etype, syms.arrayClass);
3538 result = check(tree, type, TYP, resultInfo);
3539 }
3541 /** Visitor method for parameterized types.
3542 * Bound checking is left until later, since types are attributed
3543 * before supertype structure is completely known
3544 */
3545 public void visitTypeApply(JCTypeApply tree) {
3546 Type owntype = types.createErrorType(tree.type);
3548 // Attribute functor part of application and make sure it's a class.
3549 Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
3551 // Attribute type parameters
3552 List<Type> actuals = attribTypes(tree.arguments, env);
3554 if (clazztype.hasTag(CLASS)) {
3555 List<Type> formals = clazztype.tsym.type.getTypeArguments();
3556 if (actuals.isEmpty()) //diamond
3557 actuals = formals;
3559 if (actuals.length() == formals.length()) {
3560 List<Type> a = actuals;
3561 List<Type> f = formals;
3562 while (a.nonEmpty()) {
3563 a.head = a.head.withTypeVar(f.head);
3564 a = a.tail;
3565 f = f.tail;
3566 }
3567 // Compute the proper generic outer
3568 Type clazzOuter = clazztype.getEnclosingType();
3569 if (clazzOuter.hasTag(CLASS)) {
3570 Type site;
3571 JCExpression clazz = TreeInfo.typeIn(tree.clazz);
3572 if (clazz.hasTag(IDENT)) {
3573 site = env.enclClass.sym.type;
3574 } else if (clazz.hasTag(SELECT)) {
3575 site = ((JCFieldAccess) clazz).selected.type;
3576 } else throw new AssertionError(""+tree);
3577 if (clazzOuter.hasTag(CLASS) && site != clazzOuter) {
3578 if (site.hasTag(CLASS))
3579 site = types.asOuterSuper(site, clazzOuter.tsym);
3580 if (site == null)
3581 site = types.erasure(clazzOuter);
3582 clazzOuter = site;
3583 }
3584 }
3585 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym);
3586 } else {
3587 if (formals.length() != 0) {
3588 log.error(tree.pos(), "wrong.number.type.args",
3589 Integer.toString(formals.length()));
3590 } else {
3591 log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym);
3592 }
3593 owntype = types.createErrorType(tree.type);
3594 }
3595 }
3596 result = check(tree, owntype, TYP, resultInfo);
3597 }
3599 public void visitTypeUnion(JCTypeUnion tree) {
3600 ListBuffer<Type> multicatchTypes = ListBuffer.lb();
3601 ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
3602 for (JCExpression typeTree : tree.alternatives) {
3603 Type ctype = attribType(typeTree, env);
3604 ctype = chk.checkType(typeTree.pos(),
3605 chk.checkClassType(typeTree.pos(), ctype),
3606 syms.throwableType);
3607 if (!ctype.isErroneous()) {
3608 //check that alternatives of a union type are pairwise
3609 //unrelated w.r.t. subtyping
3610 if (chk.intersects(ctype, multicatchTypes.toList())) {
3611 for (Type t : multicatchTypes) {
3612 boolean sub = types.isSubtype(ctype, t);
3613 boolean sup = types.isSubtype(t, ctype);
3614 if (sub || sup) {
3615 //assume 'a' <: 'b'
3616 Type a = sub ? ctype : t;
3617 Type b = sub ? t : ctype;
3618 log.error(typeTree.pos(), "multicatch.types.must.be.disjoint", a, b);
3619 }
3620 }
3621 }
3622 multicatchTypes.append(ctype);
3623 if (all_multicatchTypes != null)
3624 all_multicatchTypes.append(ctype);
3625 } else {
3626 if (all_multicatchTypes == null) {
3627 all_multicatchTypes = ListBuffer.lb();
3628 all_multicatchTypes.appendList(multicatchTypes);
3629 }
3630 all_multicatchTypes.append(ctype);
3631 }
3632 }
3633 Type t = check(tree, types.lub(multicatchTypes.toList()), TYP, resultInfo);
3634 if (t.hasTag(CLASS)) {
3635 List<Type> alternatives =
3636 ((all_multicatchTypes == null) ? multicatchTypes : all_multicatchTypes).toList();
3637 t = new UnionClassType((ClassType) t, alternatives);
3638 }
3639 tree.type = result = t;
3640 }
3642 public void visitTypeIntersection(JCTypeIntersection tree) {
3643 attribTypes(tree.bounds, env);
3644 tree.type = result = checkIntersection(tree, tree.bounds);
3645 }
3647 public void visitTypeParameter(JCTypeParameter tree) {
3648 TypeVar typeVar = (TypeVar)tree.type;
3649 if (!typeVar.bound.isErroneous()) {
3650 //fixup type-parameter bound computed in 'attribTypeVariables'
3651 typeVar.bound = checkIntersection(tree, tree.bounds);
3652 }
3653 }
3655 Type checkIntersection(JCTree tree, List<JCExpression> bounds) {
3656 Set<Type> boundSet = new HashSet<Type>();
3657 if (bounds.nonEmpty()) {
3658 // accept class or interface or typevar as first bound.
3659 bounds.head.type = checkBase(bounds.head.type, bounds.head, env, false, false, false);
3660 boundSet.add(types.erasure(bounds.head.type));
3661 if (bounds.head.type.isErroneous()) {
3662 return bounds.head.type;
3663 }
3664 else if (bounds.head.type.hasTag(TYPEVAR)) {
3665 // if first bound was a typevar, do not accept further bounds.
3666 if (bounds.tail.nonEmpty()) {
3667 log.error(bounds.tail.head.pos(),
3668 "type.var.may.not.be.followed.by.other.bounds");
3669 return bounds.head.type;
3670 }
3671 } else {
3672 // if first bound was a class or interface, accept only interfaces
3673 // as further bounds.
3674 for (JCExpression bound : bounds.tail) {
3675 bound.type = checkBase(bound.type, bound, env, false, true, false);
3676 if (bound.type.isErroneous()) {
3677 bounds = List.of(bound);
3678 }
3679 else if (bound.type.hasTag(CLASS)) {
3680 chk.checkNotRepeated(bound.pos(), types.erasure(bound.type), boundSet);
3681 }
3682 }
3683 }
3684 }
3686 if (bounds.length() == 0) {
3687 return syms.objectType;
3688 } else if (bounds.length() == 1) {
3689 return bounds.head.type;
3690 } else {
3691 Type owntype = types.makeCompoundType(TreeInfo.types(bounds));
3692 if (tree.hasTag(TYPEINTERSECTION)) {
3693 ((IntersectionClassType)owntype).intersectionKind =
3694 IntersectionClassType.IntersectionKind.EXPLICIT;
3695 }
3696 // ... the variable's bound is a class type flagged COMPOUND
3697 // (see comment for TypeVar.bound).
3698 // In this case, generate a class tree that represents the
3699 // bound class, ...
3700 JCExpression extending;
3701 List<JCExpression> implementing;
3702 if (!bounds.head.type.isInterface()) {
3703 extending = bounds.head;
3704 implementing = bounds.tail;
3705 } else {
3706 extending = null;
3707 implementing = bounds;
3708 }
3709 JCClassDecl cd = make.at(tree).ClassDef(
3710 make.Modifiers(PUBLIC | ABSTRACT),
3711 names.empty, List.<JCTypeParameter>nil(),
3712 extending, implementing, List.<JCTree>nil());
3714 ClassSymbol c = (ClassSymbol)owntype.tsym;
3715 Assert.check((c.flags() & COMPOUND) != 0);
3716 cd.sym = c;
3717 c.sourcefile = env.toplevel.sourcefile;
3719 // ... and attribute the bound class
3720 c.flags_field |= UNATTRIBUTED;
3721 Env<AttrContext> cenv = enter.classEnv(cd, env);
3722 enter.typeEnvs.put(c, cenv);
3723 attribClass(c);
3724 return owntype;
3725 }
3726 }
3728 public void visitWildcard(JCWildcard tree) {
3729 //- System.err.println("visitWildcard("+tree+");");//DEBUG
3730 Type type = (tree.kind.kind == BoundKind.UNBOUND)
3731 ? syms.objectType
3732 : attribType(tree.inner, env);
3733 result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
3734 tree.kind.kind,
3735 syms.boundClass),
3736 TYP, resultInfo);
3737 }
3739 public void visitAnnotation(JCAnnotation tree) {
3740 log.error(tree.pos(), "annotation.not.valid.for.type", pt());
3741 result = tree.type = syms.errType;
3742 }
3744 public void visitErroneous(JCErroneous tree) {
3745 if (tree.errs != null)
3746 for (JCTree err : tree.errs)
3747 attribTree(err, env, new ResultInfo(ERR, pt()));
3748 result = tree.type = syms.errType;
3749 }
3751 /** Default visitor method for all other trees.
3752 */
3753 public void visitTree(JCTree tree) {
3754 throw new AssertionError();
3755 }
3757 /**
3758 * Attribute an env for either a top level tree or class declaration.
3759 */
3760 public void attrib(Env<AttrContext> env) {
3761 if (env.tree.hasTag(TOPLEVEL))
3762 attribTopLevel(env);
3763 else
3764 attribClass(env.tree.pos(), env.enclClass.sym);
3765 }
3767 /**
3768 * Attribute a top level tree. These trees are encountered when the
3769 * package declaration has annotations.
3770 */
3771 public void attribTopLevel(Env<AttrContext> env) {
3772 JCCompilationUnit toplevel = env.toplevel;
3773 try {
3774 annotate.flush();
3775 chk.validateAnnotations(toplevel.packageAnnotations, toplevel.packge);
3776 } catch (CompletionFailure ex) {
3777 chk.completionError(toplevel.pos(), ex);
3778 }
3779 }
3781 /** Main method: attribute class definition associated with given class symbol.
3782 * reporting completion failures at the given position.
3783 * @param pos The source position at which completion errors are to be
3784 * reported.
3785 * @param c The class symbol whose definition will be attributed.
3786 */
3787 public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
3788 try {
3789 annotate.flush();
3790 attribClass(c);
3791 } catch (CompletionFailure ex) {
3792 chk.completionError(pos, ex);
3793 }
3794 }
3796 /** Attribute class definition associated with given class symbol.
3797 * @param c The class symbol whose definition will be attributed.
3798 */
3799 void attribClass(ClassSymbol c) throws CompletionFailure {
3800 if (c.type.hasTag(ERROR)) return;
3802 // Check for cycles in the inheritance graph, which can arise from
3803 // ill-formed class files.
3804 chk.checkNonCyclic(null, c.type);
3806 Type st = types.supertype(c.type);
3807 if ((c.flags_field & Flags.COMPOUND) == 0) {
3808 // First, attribute superclass.
3809 if (st.hasTag(CLASS))
3810 attribClass((ClassSymbol)st.tsym);
3812 // Next attribute owner, if it is a class.
3813 if (c.owner.kind == TYP && c.owner.type.hasTag(CLASS))
3814 attribClass((ClassSymbol)c.owner);
3815 }
3817 // The previous operations might have attributed the current class
3818 // if there was a cycle. So we test first whether the class is still
3819 // UNATTRIBUTED.
3820 if ((c.flags_field & UNATTRIBUTED) != 0) {
3821 c.flags_field &= ~UNATTRIBUTED;
3823 // Get environment current at the point of class definition.
3824 Env<AttrContext> env = enter.typeEnvs.get(c);
3826 // The info.lint field in the envs stored in enter.typeEnvs is deliberately uninitialized,
3827 // because the annotations were not available at the time the env was created. Therefore,
3828 // we look up the environment chain for the first enclosing environment for which the
3829 // lint value is set. Typically, this is the parent env, but might be further if there
3830 // are any envs created as a result of TypeParameter nodes.
3831 Env<AttrContext> lintEnv = env;
3832 while (lintEnv.info.lint == null)
3833 lintEnv = lintEnv.next;
3835 // Having found the enclosing lint value, we can initialize the lint value for this class
3836 env.info.lint = lintEnv.info.lint.augment(c.annotations, c.flags());
3838 Lint prevLint = chk.setLint(env.info.lint);
3839 JavaFileObject prev = log.useSource(c.sourcefile);
3840 ResultInfo prevReturnRes = env.info.returnResult;
3842 try {
3843 env.info.returnResult = null;
3844 // java.lang.Enum may not be subclassed by a non-enum
3845 if (st.tsym == syms.enumSym &&
3846 ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
3847 log.error(env.tree.pos(), "enum.no.subclassing");
3849 // Enums may not be extended by source-level classes
3850 if (st.tsym != null &&
3851 ((st.tsym.flags_field & Flags.ENUM) != 0) &&
3852 ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0) &&
3853 !target.compilerBootstrap(c)) {
3854 log.error(env.tree.pos(), "enum.types.not.extensible");
3855 }
3856 attribClassBody(env, c);
3858 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
3859 } finally {
3860 env.info.returnResult = prevReturnRes;
3861 log.useSource(prev);
3862 chk.setLint(prevLint);
3863 }
3865 }
3866 }
3868 public void visitImport(JCImport tree) {
3869 // nothing to do
3870 }
3872 /** Finish the attribution of a class. */
3873 private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
3874 JCClassDecl tree = (JCClassDecl)env.tree;
3875 Assert.check(c == tree.sym);
3877 // Validate annotations
3878 chk.validateAnnotations(tree.mods.annotations, c);
3880 // Validate type parameters, supertype and interfaces.
3881 attribStats(tree.typarams, env);
3882 if (!c.isAnonymous()) {
3883 //already checked if anonymous
3884 chk.validate(tree.typarams, env);
3885 chk.validate(tree.extending, env);
3886 chk.validate(tree.implementing, env);
3887 }
3889 // If this is a non-abstract class, check that it has no abstract
3890 // methods or unimplemented methods of an implemented interface.
3891 if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
3892 if (!relax)
3893 chk.checkAllDefined(tree.pos(), c);
3894 }
3896 if ((c.flags() & ANNOTATION) != 0) {
3897 if (tree.implementing.nonEmpty())
3898 log.error(tree.implementing.head.pos(),
3899 "cant.extend.intf.annotation");
3900 if (tree.typarams.nonEmpty())
3901 log.error(tree.typarams.head.pos(),
3902 "intf.annotation.cant.have.type.params");
3904 // If this annotation has a @Repeatable, validate
3905 Attribute.Compound repeatable = c.attribute(syms.repeatableType.tsym);
3906 if (repeatable != null) {
3907 // get diagnostic position for error reporting
3908 DiagnosticPosition cbPos = getDiagnosticPosition(tree, repeatable.type);
3909 Assert.checkNonNull(cbPos);
3911 chk.validateRepeatable(c, repeatable, cbPos);
3912 }
3913 } else {
3914 // Check that all extended classes and interfaces
3915 // are compatible (i.e. no two define methods with same arguments
3916 // yet different return types). (JLS 8.4.6.3)
3917 chk.checkCompatibleSupertypes(tree.pos(), c.type);
3918 if (allowDefaultMethods) {
3919 chk.checkDefaultMethodClashes(tree.pos(), c.type);
3920 }
3921 }
3923 // Check that class does not import the same parameterized interface
3924 // with two different argument lists.
3925 chk.checkClassBounds(tree.pos(), c.type);
3927 tree.type = c.type;
3929 for (List<JCTypeParameter> l = tree.typarams;
3930 l.nonEmpty(); l = l.tail) {
3931 Assert.checkNonNull(env.info.scope.lookup(l.head.name).scope);
3932 }
3934 // Check that a generic class doesn't extend Throwable
3935 if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
3936 log.error(tree.extending.pos(), "generic.throwable");
3938 // Check that all methods which implement some
3939 // method conform to the method they implement.
3940 chk.checkImplementations(tree);
3942 //check that a resource implementing AutoCloseable cannot throw InterruptedException
3943 checkAutoCloseable(tree.pos(), env, c.type);
3945 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
3946 // Attribute declaration
3947 attribStat(l.head, env);
3948 // Check that declarations in inner classes are not static (JLS 8.1.2)
3949 // Make an exception for static constants.
3950 if (c.owner.kind != PCK &&
3951 ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
3952 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
3953 Symbol sym = null;
3954 if (l.head.hasTag(VARDEF)) sym = ((JCVariableDecl) l.head).sym;
3955 if (sym == null ||
3956 sym.kind != VAR ||
3957 ((VarSymbol) sym).getConstValue() == null)
3958 log.error(l.head.pos(), "icls.cant.have.static.decl", c);
3959 }
3960 }
3962 // Check for cycles among non-initial constructors.
3963 chk.checkCyclicConstructors(tree);
3965 // Check for cycles among annotation elements.
3966 chk.checkNonCyclicElements(tree);
3968 // Check for proper use of serialVersionUID
3969 if (env.info.lint.isEnabled(LintCategory.SERIAL) &&
3970 isSerializable(c) &&
3971 (c.flags() & Flags.ENUM) == 0 &&
3972 (c.flags() & ABSTRACT) == 0) {
3973 checkSerialVersionUID(tree, c);
3974 }
3975 }
3976 // where
3977 /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
3978 private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
3979 for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
3980 if (types.isSameType(al.head.annotationType.type, t))
3981 return al.head.pos();
3982 }
3984 return null;
3985 }
3987 /** check if a class is a subtype of Serializable, if that is available. */
3988 private boolean isSerializable(ClassSymbol c) {
3989 try {
3990 syms.serializableType.complete();
3991 }
3992 catch (CompletionFailure e) {
3993 return false;
3994 }
3995 return types.isSubtype(c.type, syms.serializableType);
3996 }
3998 /** Check that an appropriate serialVersionUID member is defined. */
3999 private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
4001 // check for presence of serialVersionUID
4002 Scope.Entry e = c.members().lookup(names.serialVersionUID);
4003 while (e.scope != null && e.sym.kind != VAR) e = e.next();
4004 if (e.scope == null) {
4005 log.warning(LintCategory.SERIAL,
4006 tree.pos(), "missing.SVUID", c);
4007 return;
4008 }
4010 // check that it is static final
4011 VarSymbol svuid = (VarSymbol)e.sym;
4012 if ((svuid.flags() & (STATIC | FINAL)) !=
4013 (STATIC | FINAL))
4014 log.warning(LintCategory.SERIAL,
4015 TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c);
4017 // check that it is long
4018 else if (!svuid.type.hasTag(LONG))
4019 log.warning(LintCategory.SERIAL,
4020 TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c);
4022 // check constant
4023 else if (svuid.getConstValue() == null)
4024 log.warning(LintCategory.SERIAL,
4025 TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c);
4026 }
4028 private Type capture(Type type) {
4029 return types.capture(type);
4030 }
4032 // <editor-fold desc="post-attribution visitor">
4034 /**
4035 * Handle missing types/symbols in an AST. This routine is useful when
4036 * the compiler has encountered some errors (which might have ended up
4037 * terminating attribution abruptly); if the compiler is used in fail-over
4038 * mode (e.g. by an IDE) and the AST contains semantic errors, this routine
4039 * prevents NPE to be progagated during subsequent compilation steps.
4040 */
4041 public void postAttr(JCTree tree) {
4042 new PostAttrAnalyzer().scan(tree);
4043 }
4045 class PostAttrAnalyzer extends TreeScanner {
4047 private void initTypeIfNeeded(JCTree that) {
4048 if (that.type == null) {
4049 that.type = syms.unknownType;
4050 }
4051 }
4053 @Override
4054 public void scan(JCTree tree) {
4055 if (tree == null) return;
4056 if (tree instanceof JCExpression) {
4057 initTypeIfNeeded(tree);
4058 }
4059 super.scan(tree);
4060 }
4062 @Override
4063 public void visitIdent(JCIdent that) {
4064 if (that.sym == null) {
4065 that.sym = syms.unknownSymbol;
4066 }
4067 }
4069 @Override
4070 public void visitSelect(JCFieldAccess that) {
4071 if (that.sym == null) {
4072 that.sym = syms.unknownSymbol;
4073 }
4074 super.visitSelect(that);
4075 }
4077 @Override
4078 public void visitClassDef(JCClassDecl that) {
4079 initTypeIfNeeded(that);
4080 if (that.sym == null) {
4081 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol);
4082 }
4083 super.visitClassDef(that);
4084 }
4086 @Override
4087 public void visitMethodDef(JCMethodDecl that) {
4088 initTypeIfNeeded(that);
4089 if (that.sym == null) {
4090 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol);
4091 }
4092 super.visitMethodDef(that);
4093 }
4095 @Override
4096 public void visitVarDef(JCVariableDecl that) {
4097 initTypeIfNeeded(that);
4098 if (that.sym == null) {
4099 that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol);
4100 that.sym.adr = 0;
4101 }
4102 super.visitVarDef(that);
4103 }
4105 @Override
4106 public void visitNewClass(JCNewClass that) {
4107 if (that.constructor == null) {
4108 that.constructor = new MethodSymbol(0, names.init, syms.unknownType, syms.noSymbol);
4109 }
4110 if (that.constructorType == null) {
4111 that.constructorType = syms.unknownType;
4112 }
4113 super.visitNewClass(that);
4114 }
4116 @Override
4117 public void visitAssignop(JCAssignOp that) {
4118 if (that.operator == null)
4119 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
4120 super.visitAssignop(that);
4121 }
4123 @Override
4124 public void visitBinary(JCBinary that) {
4125 if (that.operator == null)
4126 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
4127 super.visitBinary(that);
4128 }
4130 @Override
4131 public void visitUnary(JCUnary that) {
4132 if (that.operator == null)
4133 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
4134 super.visitUnary(that);
4135 }
4137 @Override
4138 public void visitLambda(JCLambda that) {
4139 super.visitLambda(that);
4140 if (that.descriptorType == null) {
4141 that.descriptorType = syms.unknownType;
4142 }
4143 if (that.targets == null) {
4144 that.targets = List.nil();
4145 }
4146 }
4148 @Override
4149 public void visitReference(JCMemberReference that) {
4150 super.visitReference(that);
4151 if (that.sym == null) {
4152 that.sym = new MethodSymbol(0, names.empty, syms.unknownType, syms.noSymbol);
4153 }
4154 if (that.descriptorType == null) {
4155 that.descriptorType = syms.unknownType;
4156 }
4157 if (that.targets == null) {
4158 that.targets = List.nil();
4159 }
4160 }
4161 }
4162 // </editor-fold>
4163 }