Mon, 17 Dec 2012 07:47:05 -0800
8004832: Add new doclint package
Reviewed-by: mcimadamore
1 /*
2 * Copyright (c) 1999, 2012, 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.util.*;
52 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
53 import com.sun.tools.javac.util.List;
54 import static com.sun.tools.javac.code.Flags.*;
55 import static com.sun.tools.javac.code.Flags.ANNOTATION;
56 import static com.sun.tools.javac.code.Flags.BLOCK;
57 import static com.sun.tools.javac.code.Kinds.*;
58 import static com.sun.tools.javac.code.Kinds.ERRONEOUS;
59 import static com.sun.tools.javac.code.TypeTag.*;
60 import static com.sun.tools.javac.code.TypeTag.WILDCARD;
61 import static com.sun.tools.javac.tree.JCTree.Tag.*;
63 /** This is the main context-dependent analysis phase in GJC. It
64 * encompasses name resolution, type checking and constant folding as
65 * subtasks. Some subtasks involve auxiliary classes.
66 * @see Check
67 * @see Resolve
68 * @see ConstFold
69 * @see Infer
70 *
71 * <p><b>This is NOT part of any supported API.
72 * If you write code that depends on this, you do so at your own risk.
73 * This code and its internal interfaces are subject to change or
74 * deletion without notice.</b>
75 */
76 public class Attr extends JCTree.Visitor {
77 protected static final Context.Key<Attr> attrKey =
78 new Context.Key<Attr>();
80 final Names names;
81 final Log log;
82 final Symtab syms;
83 final Resolve rs;
84 final Infer infer;
85 final DeferredAttr deferredAttr;
86 final Check chk;
87 final Flow flow;
88 final MemberEnter memberEnter;
89 final TreeMaker make;
90 final ConstFold cfolder;
91 final Enter enter;
92 final Target target;
93 final Types types;
94 final JCDiagnostic.Factory diags;
95 final Annotate annotate;
96 final DeferredLintHandler deferredLintHandler;
98 public static Attr instance(Context context) {
99 Attr instance = context.get(attrKey);
100 if (instance == null)
101 instance = new Attr(context);
102 return instance;
103 }
105 protected Attr(Context context) {
106 context.put(attrKey, this);
108 names = Names.instance(context);
109 log = Log.instance(context);
110 syms = Symtab.instance(context);
111 rs = Resolve.instance(context);
112 chk = Check.instance(context);
113 flow = Flow.instance(context);
114 memberEnter = MemberEnter.instance(context);
115 make = TreeMaker.instance(context);
116 enter = Enter.instance(context);
117 infer = Infer.instance(context);
118 deferredAttr = DeferredAttr.instance(context);
119 cfolder = ConstFold.instance(context);
120 target = Target.instance(context);
121 types = Types.instance(context);
122 diags = JCDiagnostic.Factory.instance(context);
123 annotate = Annotate.instance(context);
124 deferredLintHandler = DeferredLintHandler.instance(context);
126 Options options = Options.instance(context);
128 Source source = Source.instance(context);
129 allowGenerics = source.allowGenerics();
130 allowVarargs = source.allowVarargs();
131 allowEnums = source.allowEnums();
132 allowBoxing = source.allowBoxing();
133 allowCovariantReturns = source.allowCovariantReturns();
134 allowAnonOuterThis = source.allowAnonOuterThis();
135 allowStringsInSwitch = source.allowStringsInSwitch();
136 allowPoly = source.allowPoly();
137 allowLambda = source.allowLambda();
138 allowDefaultMethods = source.allowDefaultMethods();
139 sourceName = source.name;
140 relax = (options.isSet("-retrofit") ||
141 options.isSet("-relax"));
142 findDiamonds = options.get("findDiamond") != null &&
143 source.allowDiamond();
144 useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
145 identifyLambdaCandidate = options.getBoolean("identifyLambdaCandidate", false);
147 statInfo = new ResultInfo(NIL, Type.noType);
148 varInfo = new ResultInfo(VAR, Type.noType);
149 unknownExprInfo = new ResultInfo(VAL, Type.noType);
150 unknownTypeInfo = new ResultInfo(TYP, Type.noType);
151 recoveryInfo = new RecoveryInfo(deferredAttr.emptyDeferredAttrContext);
152 }
154 /** Switch: relax some constraints for retrofit mode.
155 */
156 boolean relax;
158 /** Switch: support target-typing inference
159 */
160 boolean allowPoly;
162 /** Switch: support generics?
163 */
164 boolean allowGenerics;
166 /** Switch: allow variable-arity methods.
167 */
168 boolean allowVarargs;
170 /** Switch: support enums?
171 */
172 boolean allowEnums;
174 /** Switch: support boxing and unboxing?
175 */
176 boolean allowBoxing;
178 /** Switch: support covariant result types?
179 */
180 boolean allowCovariantReturns;
182 /** Switch: support lambda expressions ?
183 */
184 boolean allowLambda;
186 /** Switch: support default methods ?
187 */
188 boolean allowDefaultMethods;
190 /** Switch: allow references to surrounding object from anonymous
191 * objects during constructor call?
192 */
193 boolean allowAnonOuterThis;
195 /** Switch: generates a warning if diamond can be safely applied
196 * to a given new expression
197 */
198 boolean findDiamonds;
200 /**
201 * Internally enables/disables diamond finder feature
202 */
203 static final boolean allowDiamondFinder = true;
205 /**
206 * Switch: warn about use of variable before declaration?
207 * RFE: 6425594
208 */
209 boolean useBeforeDeclarationWarning;
211 /**
212 * Switch: generate warnings whenever an anonymous inner class that is convertible
213 * to a lambda expression is found
214 */
215 boolean identifyLambdaCandidate;
217 /**
218 * Switch: allow strings in switch?
219 */
220 boolean allowStringsInSwitch;
222 /**
223 * Switch: name of source level; used for error reporting.
224 */
225 String sourceName;
227 /** Check kind and type of given tree against protokind and prototype.
228 * If check succeeds, store type in tree and return it.
229 * If check fails, store errType in tree and return it.
230 * No checks are performed if the prototype is a method type.
231 * It is not necessary in this case since we know that kind and type
232 * are correct.
233 *
234 * @param tree The tree whose kind and type is checked
235 * @param ownkind The computed kind of the tree
236 * @param resultInfo The expected result of the tree
237 */
238 Type check(final JCTree tree, final Type found, final int ownkind, final ResultInfo resultInfo) {
239 InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
240 Type owntype = found;
241 if (!owntype.hasTag(ERROR) && !resultInfo.pt.hasTag(METHOD) && !resultInfo.pt.hasTag(FORALL)) {
242 if (inferenceContext.free(found)) {
243 inferenceContext.addFreeTypeListener(List.of(found, resultInfo.pt), new FreeTypeListener() {
244 @Override
245 public void typesInferred(InferenceContext inferenceContext) {
246 ResultInfo pendingResult =
247 resultInfo.dup(inferenceContext.asInstType(resultInfo.pt, types));
248 check(tree, inferenceContext.asInstType(found, types), ownkind, pendingResult);
249 }
250 });
251 return tree.type = resultInfo.pt;
252 } else {
253 if ((ownkind & ~resultInfo.pkind) == 0) {
254 owntype = resultInfo.check(tree, owntype);
255 } else {
256 log.error(tree.pos(), "unexpected.type",
257 kindNames(resultInfo.pkind),
258 kindName(ownkind));
259 owntype = types.createErrorType(owntype);
260 }
261 }
262 }
263 tree.type = owntype;
264 return owntype;
265 }
267 /** Is given blank final variable assignable, i.e. in a scope where it
268 * may be assigned to even though it is final?
269 * @param v The blank final variable.
270 * @param env The current environment.
271 */
272 boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
273 Symbol owner = owner(env);
274 // owner refers to the innermost variable, method or
275 // initializer block declaration at this point.
276 return
277 v.owner == owner
278 ||
279 ((owner.name == names.init || // i.e. we are in a constructor
280 owner.kind == VAR || // i.e. we are in a variable initializer
281 (owner.flags() & BLOCK) != 0) // i.e. we are in an initializer block
282 &&
283 v.owner == owner.owner
284 &&
285 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
286 }
288 /**
289 * Return the innermost enclosing owner symbol in a given attribution context
290 */
291 Symbol owner(Env<AttrContext> env) {
292 while (true) {
293 switch (env.tree.getTag()) {
294 case VARDEF:
295 //a field can be owner
296 VarSymbol vsym = ((JCVariableDecl)env.tree).sym;
297 if (vsym.owner.kind == TYP) {
298 return vsym;
299 }
300 break;
301 case METHODDEF:
302 //method def is always an owner
303 return ((JCMethodDecl)env.tree).sym;
304 case CLASSDEF:
305 //class def is always an owner
306 return ((JCClassDecl)env.tree).sym;
307 case LAMBDA:
308 //a lambda is an owner - return a fresh synthetic method symbol
309 return new MethodSymbol(0, names.empty, null, syms.methodClass);
310 case BLOCK:
311 //static/instance init blocks are owner
312 Symbol blockSym = env.info.scope.owner;
313 if ((blockSym.flags() & BLOCK) != 0) {
314 return blockSym;
315 }
316 break;
317 case TOPLEVEL:
318 //toplevel is always an owner (for pkge decls)
319 return env.info.scope.owner;
320 }
321 Assert.checkNonNull(env.next);
322 env = env.next;
323 }
324 }
326 /** Check that variable can be assigned to.
327 * @param pos The current source code position.
328 * @param v The assigned varaible
329 * @param base If the variable is referred to in a Select, the part
330 * to the left of the `.', null otherwise.
331 * @param env The current environment.
332 */
333 void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
334 if ((v.flags() & FINAL) != 0 &&
335 ((v.flags() & HASINIT) != 0
336 ||
337 !((base == null ||
338 (base.hasTag(IDENT) && TreeInfo.name(base) == names._this)) &&
339 isAssignableAsBlankFinal(v, env)))) {
340 if (v.isResourceVariable()) { //TWR resource
341 log.error(pos, "try.resource.may.not.be.assigned", v);
342 } else {
343 log.error(pos, "cant.assign.val.to.final.var", v);
344 }
345 }
346 }
348 /** Does tree represent a static reference to an identifier?
349 * It is assumed that tree is either a SELECT or an IDENT.
350 * We have to weed out selects from non-type names here.
351 * @param tree The candidate tree.
352 */
353 boolean isStaticReference(JCTree tree) {
354 if (tree.hasTag(SELECT)) {
355 Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
356 if (lsym == null || lsym.kind != TYP) {
357 return false;
358 }
359 }
360 return true;
361 }
363 /** Is this symbol a type?
364 */
365 static boolean isType(Symbol sym) {
366 return sym != null && sym.kind == TYP;
367 }
369 /** The current `this' symbol.
370 * @param env The current environment.
371 */
372 Symbol thisSym(DiagnosticPosition pos, Env<AttrContext> env) {
373 return rs.resolveSelf(pos, env, env.enclClass.sym, names._this);
374 }
376 /** Attribute a parsed identifier.
377 * @param tree Parsed identifier name
378 * @param topLevel The toplevel to use
379 */
380 public Symbol attribIdent(JCTree tree, JCCompilationUnit topLevel) {
381 Env<AttrContext> localEnv = enter.topLevelEnv(topLevel);
382 localEnv.enclClass = make.ClassDef(make.Modifiers(0),
383 syms.errSymbol.name,
384 null, null, null, null);
385 localEnv.enclClass.sym = syms.errSymbol;
386 return tree.accept(identAttributer, localEnv);
387 }
388 // where
389 private TreeVisitor<Symbol,Env<AttrContext>> identAttributer = new IdentAttributer();
390 private class IdentAttributer extends SimpleTreeVisitor<Symbol,Env<AttrContext>> {
391 @Override
392 public Symbol visitMemberSelect(MemberSelectTree node, Env<AttrContext> env) {
393 Symbol site = visit(node.getExpression(), env);
394 if (site.kind == ERR)
395 return site;
396 Name name = (Name)node.getIdentifier();
397 if (site.kind == PCK) {
398 env.toplevel.packge = (PackageSymbol)site;
399 return rs.findIdentInPackage(env, (TypeSymbol)site, name, TYP | PCK);
400 } else {
401 env.enclClass.sym = (ClassSymbol)site;
402 return rs.findMemberType(env, site.asType(), name, (TypeSymbol)site);
403 }
404 }
406 @Override
407 public Symbol visitIdentifier(IdentifierTree node, Env<AttrContext> env) {
408 return rs.findIdent(env, (Name)node.getName(), TYP | PCK);
409 }
410 }
412 public Type coerce(Type etype, Type ttype) {
413 return cfolder.coerce(etype, ttype);
414 }
416 public Type attribType(JCTree node, TypeSymbol sym) {
417 Env<AttrContext> env = enter.typeEnvs.get(sym);
418 Env<AttrContext> localEnv = env.dup(node, env.info.dup());
419 return attribTree(node, localEnv, unknownTypeInfo);
420 }
422 public Type attribImportQualifier(JCImport tree, Env<AttrContext> env) {
423 // Attribute qualifying package or class.
424 JCFieldAccess s = (JCFieldAccess)tree.qualid;
425 return attribTree(s.selected,
426 env,
427 new ResultInfo(tree.staticImport ? TYP : (TYP | PCK),
428 Type.noType));
429 }
431 public Env<AttrContext> attribExprToTree(JCTree expr, Env<AttrContext> env, JCTree tree) {
432 breakTree = tree;
433 JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
434 try {
435 attribExpr(expr, env);
436 } catch (BreakAttr b) {
437 return b.env;
438 } catch (AssertionError ae) {
439 if (ae.getCause() instanceof BreakAttr) {
440 return ((BreakAttr)(ae.getCause())).env;
441 } else {
442 throw ae;
443 }
444 } finally {
445 breakTree = null;
446 log.useSource(prev);
447 }
448 return env;
449 }
451 public Env<AttrContext> attribStatToTree(JCTree stmt, Env<AttrContext> env, JCTree tree) {
452 breakTree = tree;
453 JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
454 try {
455 attribStat(stmt, env);
456 } catch (BreakAttr b) {
457 return b.env;
458 } catch (AssertionError ae) {
459 if (ae.getCause() instanceof BreakAttr) {
460 return ((BreakAttr)(ae.getCause())).env;
461 } else {
462 throw ae;
463 }
464 } finally {
465 breakTree = null;
466 log.useSource(prev);
467 }
468 return env;
469 }
471 private JCTree breakTree = null;
473 private static class BreakAttr extends RuntimeException {
474 static final long serialVersionUID = -6924771130405446405L;
475 private Env<AttrContext> env;
476 private BreakAttr(Env<AttrContext> env) {
477 this.env = copyEnv(env);
478 }
480 private Env<AttrContext> copyEnv(Env<AttrContext> env) {
481 Env<AttrContext> newEnv =
482 env.dup(env.tree, env.info.dup(copyScope(env.info.scope)));
483 if (newEnv.outer != null) {
484 newEnv.outer = copyEnv(newEnv.outer);
485 }
486 return newEnv;
487 }
489 private Scope copyScope(Scope sc) {
490 Scope newScope = new Scope(sc.owner);
491 List<Symbol> elemsList = List.nil();
492 while (sc != null) {
493 for (Scope.Entry e = sc.elems ; e != null ; e = e.sibling) {
494 elemsList = elemsList.prepend(e.sym);
495 }
496 sc = sc.next;
497 }
498 for (Symbol s : elemsList) {
499 newScope.enter(s);
500 }
501 return newScope;
502 }
503 }
505 class ResultInfo {
506 final int pkind;
507 final Type pt;
508 final CheckContext checkContext;
510 ResultInfo(int pkind, Type pt) {
511 this(pkind, pt, chk.basicHandler);
512 }
514 protected ResultInfo(int pkind, Type pt, CheckContext checkContext) {
515 this.pkind = pkind;
516 this.pt = pt;
517 this.checkContext = checkContext;
518 }
520 protected Type check(final DiagnosticPosition pos, final Type found) {
521 return chk.checkType(pos, found, pt, checkContext);
522 }
524 protected ResultInfo dup(Type newPt) {
525 return new ResultInfo(pkind, newPt, checkContext);
526 }
528 protected ResultInfo dup(CheckContext newContext) {
529 return new ResultInfo(pkind, pt, newContext);
530 }
531 }
533 class RecoveryInfo extends ResultInfo {
535 public RecoveryInfo(final DeferredAttr.DeferredAttrContext deferredAttrContext) {
536 super(Kinds.VAL, Type.recoveryType, new Check.NestedCheckContext(chk.basicHandler) {
537 @Override
538 public DeferredAttr.DeferredAttrContext deferredAttrContext() {
539 return deferredAttrContext;
540 }
541 @Override
542 public boolean compatible(Type found, Type req, Warner warn) {
543 return true;
544 }
545 @Override
546 public void report(DiagnosticPosition pos, JCDiagnostic details) {
547 chk.basicHandler.report(pos, details);
548 }
549 });
550 }
552 @Override
553 protected Type check(DiagnosticPosition pos, Type found) {
554 return chk.checkNonVoid(pos, super.check(pos, found));
555 }
556 }
558 final ResultInfo statInfo;
559 final ResultInfo varInfo;
560 final ResultInfo unknownExprInfo;
561 final ResultInfo unknownTypeInfo;
562 final ResultInfo recoveryInfo;
564 Type pt() {
565 return resultInfo.pt;
566 }
568 int pkind() {
569 return resultInfo.pkind;
570 }
572 /* ************************************************************************
573 * Visitor methods
574 *************************************************************************/
576 /** Visitor argument: the current environment.
577 */
578 Env<AttrContext> env;
580 /** Visitor argument: the currently expected attribution result.
581 */
582 ResultInfo resultInfo;
584 /** Visitor result: the computed type.
585 */
586 Type result;
588 /** Visitor method: attribute a tree, catching any completion failure
589 * exceptions. Return the tree's type.
590 *
591 * @param tree The tree to be visited.
592 * @param env The environment visitor argument.
593 * @param resultInfo The result info visitor argument.
594 */
595 Type attribTree(JCTree tree, Env<AttrContext> env, ResultInfo resultInfo) {
596 Env<AttrContext> prevEnv = this.env;
597 ResultInfo prevResult = this.resultInfo;
598 try {
599 this.env = env;
600 this.resultInfo = resultInfo;
601 tree.accept(this);
602 if (tree == breakTree &&
603 resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
604 throw new BreakAttr(env);
605 }
606 return result;
607 } catch (CompletionFailure ex) {
608 tree.type = syms.errType;
609 return chk.completionError(tree.pos(), ex);
610 } finally {
611 this.env = prevEnv;
612 this.resultInfo = prevResult;
613 }
614 }
616 /** Derived visitor method: attribute an expression tree.
617 */
618 public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) {
619 return attribTree(tree, env, new ResultInfo(VAL, !pt.hasTag(ERROR) ? pt : Type.noType));
620 }
622 /** Derived visitor method: attribute an expression tree with
623 * no constraints on the computed type.
624 */
625 public Type attribExpr(JCTree tree, Env<AttrContext> env) {
626 return attribTree(tree, env, unknownExprInfo);
627 }
629 /** Derived visitor method: attribute a type tree.
630 */
631 public Type attribType(JCTree tree, Env<AttrContext> env) {
632 Type result = attribType(tree, env, Type.noType);
633 return result;
634 }
636 /** Derived visitor method: attribute a type tree.
637 */
638 Type attribType(JCTree tree, Env<AttrContext> env, Type pt) {
639 Type result = attribTree(tree, env, new ResultInfo(TYP, pt));
640 return result;
641 }
643 /** Derived visitor method: attribute a statement or definition tree.
644 */
645 public Type attribStat(JCTree tree, Env<AttrContext> env) {
646 return attribTree(tree, env, statInfo);
647 }
649 /** Attribute a list of expressions, returning a list of types.
650 */
651 List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) {
652 ListBuffer<Type> ts = new ListBuffer<Type>();
653 for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
654 ts.append(attribExpr(l.head, env, pt));
655 return ts.toList();
656 }
658 /** Attribute a list of statements, returning nothing.
659 */
660 <T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) {
661 for (List<T> l = trees; l.nonEmpty(); l = l.tail)
662 attribStat(l.head, env);
663 }
665 /** Attribute the arguments in a method call, returning a list of types.
666 */
667 List<Type> attribArgs(List<JCExpression> trees, Env<AttrContext> env) {
668 ListBuffer<Type> argtypes = new ListBuffer<Type>();
669 for (JCExpression arg : trees) {
670 Type argtype = allowPoly && TreeInfo.isPoly(arg, env.tree) ?
671 deferredAttr.new DeferredType(arg, env) :
672 chk.checkNonVoid(arg, attribExpr(arg, env, Infer.anyPoly));
673 argtypes.append(argtype);
674 }
675 return argtypes.toList();
676 }
678 /** Attribute a type argument list, returning a list of types.
679 * Caller is responsible for calling checkRefTypes.
680 */
681 List<Type> attribAnyTypes(List<JCExpression> trees, Env<AttrContext> env) {
682 ListBuffer<Type> argtypes = new ListBuffer<Type>();
683 for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
684 argtypes.append(attribType(l.head, env));
685 return argtypes.toList();
686 }
688 /** Attribute a type argument list, returning a list of types.
689 * Check that all the types are references.
690 */
691 List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
692 List<Type> types = attribAnyTypes(trees, env);
693 return chk.checkRefTypes(trees, types);
694 }
696 /**
697 * Attribute type variables (of generic classes or methods).
698 * Compound types are attributed later in attribBounds.
699 * @param typarams the type variables to enter
700 * @param env the current environment
701 */
702 void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env) {
703 for (JCTypeParameter tvar : typarams) {
704 TypeVar a = (TypeVar)tvar.type;
705 a.tsym.flags_field |= UNATTRIBUTED;
706 a.bound = Type.noType;
707 if (!tvar.bounds.isEmpty()) {
708 List<Type> bounds = List.of(attribType(tvar.bounds.head, env));
709 for (JCExpression bound : tvar.bounds.tail)
710 bounds = bounds.prepend(attribType(bound, env));
711 types.setBounds(a, bounds.reverse());
712 } else {
713 // if no bounds are given, assume a single bound of
714 // java.lang.Object.
715 types.setBounds(a, List.of(syms.objectType));
716 }
717 a.tsym.flags_field &= ~UNATTRIBUTED;
718 }
719 for (JCTypeParameter tvar : typarams) {
720 chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
721 }
722 }
724 /**
725 * Attribute the type references in a list of annotations.
726 */
727 void attribAnnotationTypes(List<JCAnnotation> annotations,
728 Env<AttrContext> env) {
729 for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
730 JCAnnotation a = al.head;
731 attribType(a.annotationType, env);
732 }
733 }
735 /**
736 * Attribute a "lazy constant value".
737 * @param env The env for the const value
738 * @param initializer The initializer for the const value
739 * @param type The expected type, or null
740 * @see VarSymbol#setLazyConstValue
741 */
742 public Object attribLazyConstantValue(Env<AttrContext> env,
743 JCTree.JCExpression initializer,
744 Type type) {
746 // in case no lint value has been set up for this env, scan up
747 // env stack looking for smallest enclosing env for which it is set.
748 Env<AttrContext> lintEnv = env;
749 while (lintEnv.info.lint == null)
750 lintEnv = lintEnv.next;
752 // Having found the enclosing lint value, we can initialize the lint value for this class
753 // ... but ...
754 // There's a problem with evaluating annotations in the right order, such that
755 // env.info.enclVar.attributes_field might not yet have been evaluated, and so might be
756 // null. In that case, calling augment will throw an NPE. To avoid this, for now we
757 // revert to the jdk 6 behavior and ignore the (unevaluated) attributes.
758 if (env.info.enclVar.annotations.pendingCompletion()) {
759 env.info.lint = lintEnv.info.lint;
760 } else {
761 env.info.lint = lintEnv.info.lint.augment(env.info.enclVar.annotations,
762 env.info.enclVar.flags());
763 }
765 Lint prevLint = chk.setLint(env.info.lint);
766 JavaFileObject prevSource = log.useSource(env.toplevel.sourcefile);
768 try {
769 Type itype = attribExpr(initializer, env, type);
770 if (itype.constValue() != null)
771 return coerce(itype, type).constValue();
772 else
773 return null;
774 } finally {
775 env.info.lint = prevLint;
776 log.useSource(prevSource);
777 }
778 }
780 /** Attribute type reference in an `extends' or `implements' clause.
781 * Supertypes of anonymous inner classes are usually already attributed.
782 *
783 * @param tree The tree making up the type reference.
784 * @param env The environment current at the reference.
785 * @param classExpected true if only a class is expected here.
786 * @param interfaceExpected true if only an interface is expected here.
787 */
788 Type attribBase(JCTree tree,
789 Env<AttrContext> env,
790 boolean classExpected,
791 boolean interfaceExpected,
792 boolean checkExtensible) {
793 Type t = tree.type != null ?
794 tree.type :
795 attribType(tree, env);
796 return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible);
797 }
798 Type checkBase(Type t,
799 JCTree tree,
800 Env<AttrContext> env,
801 boolean classExpected,
802 boolean interfaceExpected,
803 boolean checkExtensible) {
804 if (t.isErroneous())
805 return t;
806 if (t.hasTag(TYPEVAR) && !classExpected && !interfaceExpected) {
807 // check that type variable is already visible
808 if (t.getUpperBound() == null) {
809 log.error(tree.pos(), "illegal.forward.ref");
810 return types.createErrorType(t);
811 }
812 } else {
813 t = chk.checkClassType(tree.pos(), t, checkExtensible|!allowGenerics);
814 }
815 if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) {
816 log.error(tree.pos(), "intf.expected.here");
817 // return errType is necessary since otherwise there might
818 // be undetected cycles which cause attribution to loop
819 return types.createErrorType(t);
820 } else if (checkExtensible &&
821 classExpected &&
822 (t.tsym.flags() & INTERFACE) != 0) {
823 log.error(tree.pos(), "no.intf.expected.here");
824 return types.createErrorType(t);
825 }
826 if (checkExtensible &&
827 ((t.tsym.flags() & FINAL) != 0)) {
828 log.error(tree.pos(),
829 "cant.inherit.from.final", t.tsym);
830 }
831 chk.checkNonCyclic(tree.pos(), t);
832 return t;
833 }
835 Type attribIdentAsEnumType(Env<AttrContext> env, JCIdent id) {
836 Assert.check((env.enclClass.sym.flags() & ENUM) != 0);
837 id.type = env.info.scope.owner.type;
838 id.sym = env.info.scope.owner;
839 return id.type;
840 }
842 public void visitClassDef(JCClassDecl tree) {
843 // Local classes have not been entered yet, so we need to do it now:
844 if ((env.info.scope.owner.kind & (VAR | MTH)) != 0)
845 enter.classEnter(tree, env);
847 ClassSymbol c = tree.sym;
848 if (c == null) {
849 // exit in case something drastic went wrong during enter.
850 result = null;
851 } else {
852 // make sure class has been completed:
853 c.complete();
855 // If this class appears as an anonymous class
856 // in a superclass constructor call where
857 // no explicit outer instance is given,
858 // disable implicit outer instance from being passed.
859 // (This would be an illegal access to "this before super").
860 if (env.info.isSelfCall &&
861 env.tree.hasTag(NEWCLASS) &&
862 ((JCNewClass) env.tree).encl == null)
863 {
864 c.flags_field |= NOOUTERTHIS;
865 }
866 attribClass(tree.pos(), c);
867 result = tree.type = c.type;
868 }
869 }
871 public void visitMethodDef(JCMethodDecl tree) {
872 MethodSymbol m = tree.sym;
873 boolean isDefaultMethod = (m.flags() & DEFAULT) != 0;
875 Lint lint = env.info.lint.augment(m.annotations, m.flags());
876 Lint prevLint = chk.setLint(lint);
877 MethodSymbol prevMethod = chk.setMethod(m);
878 try {
879 deferredLintHandler.flush(tree.pos());
880 chk.checkDeprecatedAnnotation(tree.pos(), m);
882 // Create a new environment with local scope
883 // for attributing the method.
884 Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
885 localEnv.info.lint = lint;
887 attribStats(tree.typarams, localEnv);
889 // If we override any other methods, check that we do so properly.
890 // JLS ???
891 if (m.isStatic()) {
892 chk.checkHideClashes(tree.pos(), env.enclClass.type, m);
893 } else {
894 chk.checkOverrideClashes(tree.pos(), env.enclClass.type, m);
895 }
896 chk.checkOverride(tree, m);
898 if (isDefaultMethod && types.overridesObjectMethod(m.enclClass(), m)) {
899 log.error(tree, "default.overrides.object.member", m.name, Kinds.kindName(m.location()), m.location());
900 }
902 // Enter all type parameters into the local method scope.
903 for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
904 localEnv.info.scope.enterIfAbsent(l.head.type.tsym);
906 ClassSymbol owner = env.enclClass.sym;
907 if ((owner.flags() & ANNOTATION) != 0 &&
908 tree.params.nonEmpty())
909 log.error(tree.params.head.pos(),
910 "intf.annotation.members.cant.have.params");
912 // Attribute all value parameters.
913 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
914 attribStat(l.head, localEnv);
915 }
917 chk.checkVarargsMethodDecl(localEnv, tree);
919 // Check that type parameters are well-formed.
920 chk.validate(tree.typarams, localEnv);
922 // Check that result type is well-formed.
923 chk.validate(tree.restype, localEnv);
925 // annotation method checks
926 if ((owner.flags() & ANNOTATION) != 0) {
927 // annotation method cannot have throws clause
928 if (tree.thrown.nonEmpty()) {
929 log.error(tree.thrown.head.pos(),
930 "throws.not.allowed.in.intf.annotation");
931 }
932 // annotation method cannot declare type-parameters
933 if (tree.typarams.nonEmpty()) {
934 log.error(tree.typarams.head.pos(),
935 "intf.annotation.members.cant.have.type.params");
936 }
937 // validate annotation method's return type (could be an annotation type)
938 chk.validateAnnotationType(tree.restype);
939 // ensure that annotation method does not clash with members of Object/Annotation
940 chk.validateAnnotationMethod(tree.pos(), m);
942 if (tree.defaultValue != null) {
943 // if default value is an annotation, check it is a well-formed
944 // annotation value (e.g. no duplicate values, no missing values, etc.)
945 chk.validateAnnotationTree(tree.defaultValue);
946 }
947 }
949 for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
950 chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
952 if (tree.body == null) {
953 // Empty bodies are only allowed for
954 // abstract, native, or interface methods, or for methods
955 // in a retrofit signature class.
956 if (isDefaultMethod || ((owner.flags() & INTERFACE) == 0 &&
957 (tree.mods.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 boolean standaloneConditional = !allowPoly ||
1380 pt().hasTag(NONE) && pt() != Type.recoveryType ||
1381 isBooleanOrNumeric(env, tree);
1383 if (!standaloneConditional && resultInfo.pt.hasTag(VOID)) {
1384 //cannot get here (i.e. it means we are returning from void method - which is already an error)
1385 resultInfo.checkContext.report(tree, diags.fragment("conditional.target.cant.be.void"));
1386 result = tree.type = types.createErrorType(resultInfo.pt);
1387 return;
1388 }
1390 ResultInfo condInfo = standaloneConditional ?
1391 unknownExprInfo :
1392 resultInfo.dup(new Check.NestedCheckContext(resultInfo.checkContext) {
1393 //this will use enclosing check context to check compatibility of
1394 //subexpression against target type; if we are in a method check context,
1395 //depending on whether boxing is allowed, we could have incompatibilities
1396 @Override
1397 public void report(DiagnosticPosition pos, JCDiagnostic details) {
1398 enclosingContext.report(pos, diags.fragment("incompatible.type.in.conditional", details));
1399 }
1400 });
1402 Type truetype = attribTree(tree.truepart, env, condInfo);
1403 Type falsetype = attribTree(tree.falsepart, env, condInfo);
1405 Type owntype = standaloneConditional ? condType(tree, truetype, falsetype) : pt();
1406 if (condtype.constValue() != null &&
1407 truetype.constValue() != null &&
1408 falsetype.constValue() != null) {
1409 //constant folding
1410 owntype = cfolder.coerce(condtype.isTrue() ? truetype : falsetype, owntype);
1411 }
1412 result = check(tree, owntype, VAL, resultInfo);
1413 }
1414 //where
1415 private boolean isBooleanOrNumeric(Env<AttrContext> env, JCExpression tree) {
1416 switch (tree.getTag()) {
1417 case LITERAL: return ((JCLiteral)tree).typetag.isSubRangeOf(DOUBLE) ||
1418 ((JCLiteral)tree).typetag == BOOLEAN ||
1419 ((JCLiteral)tree).typetag == BOT;
1420 case LAMBDA: case REFERENCE: return false;
1421 case PARENS: return isBooleanOrNumeric(env, ((JCParens)tree).expr);
1422 case CONDEXPR:
1423 JCConditional condTree = (JCConditional)tree;
1424 return isBooleanOrNumeric(env, condTree.truepart) &&
1425 isBooleanOrNumeric(env, condTree.falsepart);
1426 default:
1427 Type speculativeType = deferredAttr.attribSpeculative(tree, env, unknownExprInfo).type;
1428 speculativeType = types.unboxedTypeOrType(speculativeType);
1429 return speculativeType.isPrimitive();
1430 }
1431 }
1433 /** Compute the type of a conditional expression, after
1434 * checking that it exists. See JLS 15.25. Does not take into
1435 * account the special case where condition and both arms
1436 * are constants.
1437 *
1438 * @param pos The source position to be used for error
1439 * diagnostics.
1440 * @param thentype The type of the expression's then-part.
1441 * @param elsetype The type of the expression's else-part.
1442 */
1443 private Type condType(DiagnosticPosition pos,
1444 Type thentype, Type elsetype) {
1445 // If same type, that is the result
1446 if (types.isSameType(thentype, elsetype))
1447 return thentype.baseType();
1449 Type thenUnboxed = (!allowBoxing || thentype.isPrimitive())
1450 ? thentype : types.unboxedType(thentype);
1451 Type elseUnboxed = (!allowBoxing || elsetype.isPrimitive())
1452 ? elsetype : types.unboxedType(elsetype);
1454 // Otherwise, if both arms can be converted to a numeric
1455 // type, return the least numeric type that fits both arms
1456 // (i.e. return larger of the two, or return int if one
1457 // arm is short, the other is char).
1458 if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) {
1459 // If one arm has an integer subrange type (i.e., byte,
1460 // short, or char), and the other is an integer constant
1461 // that fits into the subrange, return the subrange type.
1462 if (thenUnboxed.getTag().isStrictSubRangeOf(INT) && elseUnboxed.hasTag(INT) &&
1463 types.isAssignable(elseUnboxed, thenUnboxed))
1464 return thenUnboxed.baseType();
1465 if (elseUnboxed.getTag().isStrictSubRangeOf(INT) && thenUnboxed.hasTag(INT) &&
1466 types.isAssignable(thenUnboxed, elseUnboxed))
1467 return elseUnboxed.baseType();
1469 for (TypeTag tag : TypeTag.values()) {
1470 if (tag.ordinal() >= TypeTag.getTypeTagCount()) break;
1471 Type candidate = syms.typeOfTag[tag.ordinal()];
1472 if (candidate != null &&
1473 candidate.isPrimitive() &&
1474 types.isSubtype(thenUnboxed, candidate) &&
1475 types.isSubtype(elseUnboxed, candidate))
1476 return candidate;
1477 }
1478 }
1480 // Those were all the cases that could result in a primitive
1481 if (allowBoxing) {
1482 if (thentype.isPrimitive())
1483 thentype = types.boxedClass(thentype).type;
1484 if (elsetype.isPrimitive())
1485 elsetype = types.boxedClass(elsetype).type;
1486 }
1488 if (types.isSubtype(thentype, elsetype))
1489 return elsetype.baseType();
1490 if (types.isSubtype(elsetype, thentype))
1491 return thentype.baseType();
1493 if (!allowBoxing || thentype.hasTag(VOID) || elsetype.hasTag(VOID)) {
1494 log.error(pos, "neither.conditional.subtype",
1495 thentype, elsetype);
1496 return thentype.baseType();
1497 }
1499 // both are known to be reference types. The result is
1500 // lub(thentype,elsetype). This cannot fail, as it will
1501 // always be possible to infer "Object" if nothing better.
1502 return types.lub(thentype.baseType(), elsetype.baseType());
1503 }
1505 public void visitIf(JCIf tree) {
1506 attribExpr(tree.cond, env, syms.booleanType);
1507 attribStat(tree.thenpart, env);
1508 if (tree.elsepart != null)
1509 attribStat(tree.elsepart, env);
1510 chk.checkEmptyIf(tree);
1511 result = null;
1512 }
1514 public void visitExec(JCExpressionStatement tree) {
1515 //a fresh environment is required for 292 inference to work properly ---
1516 //see Infer.instantiatePolymorphicSignatureInstance()
1517 Env<AttrContext> localEnv = env.dup(tree);
1518 attribExpr(tree.expr, localEnv);
1519 result = null;
1520 }
1522 public void visitBreak(JCBreak tree) {
1523 tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
1524 result = null;
1525 }
1527 public void visitContinue(JCContinue tree) {
1528 tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
1529 result = null;
1530 }
1531 //where
1532 /** Return the target of a break or continue statement, if it exists,
1533 * report an error if not.
1534 * Note: The target of a labelled break or continue is the
1535 * (non-labelled) statement tree referred to by the label,
1536 * not the tree representing the labelled statement itself.
1537 *
1538 * @param pos The position to be used for error diagnostics
1539 * @param tag The tag of the jump statement. This is either
1540 * Tree.BREAK or Tree.CONTINUE.
1541 * @param label The label of the jump statement, or null if no
1542 * label is given.
1543 * @param env The environment current at the jump statement.
1544 */
1545 private JCTree findJumpTarget(DiagnosticPosition pos,
1546 JCTree.Tag tag,
1547 Name label,
1548 Env<AttrContext> env) {
1549 // Search environments outwards from the point of jump.
1550 Env<AttrContext> env1 = env;
1551 LOOP:
1552 while (env1 != null) {
1553 switch (env1.tree.getTag()) {
1554 case LABELLED:
1555 JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
1556 if (label == labelled.label) {
1557 // If jump is a continue, check that target is a loop.
1558 if (tag == CONTINUE) {
1559 if (!labelled.body.hasTag(DOLOOP) &&
1560 !labelled.body.hasTag(WHILELOOP) &&
1561 !labelled.body.hasTag(FORLOOP) &&
1562 !labelled.body.hasTag(FOREACHLOOP))
1563 log.error(pos, "not.loop.label", label);
1564 // Found labelled statement target, now go inwards
1565 // to next non-labelled tree.
1566 return TreeInfo.referencedStatement(labelled);
1567 } else {
1568 return labelled;
1569 }
1570 }
1571 break;
1572 case DOLOOP:
1573 case WHILELOOP:
1574 case FORLOOP:
1575 case FOREACHLOOP:
1576 if (label == null) return env1.tree;
1577 break;
1578 case SWITCH:
1579 if (label == null && tag == BREAK) return env1.tree;
1580 break;
1581 case LAMBDA:
1582 case METHODDEF:
1583 case CLASSDEF:
1584 break LOOP;
1585 default:
1586 }
1587 env1 = env1.next;
1588 }
1589 if (label != null)
1590 log.error(pos, "undef.label", label);
1591 else if (tag == CONTINUE)
1592 log.error(pos, "cont.outside.loop");
1593 else
1594 log.error(pos, "break.outside.switch.loop");
1595 return null;
1596 }
1598 public void visitReturn(JCReturn tree) {
1599 // Check that there is an enclosing method which is
1600 // nested within than the enclosing class.
1601 if (env.info.returnResult == null) {
1602 log.error(tree.pos(), "ret.outside.meth");
1603 } else {
1604 // Attribute return expression, if it exists, and check that
1605 // it conforms to result type of enclosing method.
1606 if (tree.expr != null) {
1607 if (env.info.returnResult.pt.hasTag(VOID)) {
1608 env.info.returnResult.checkContext.report(tree.expr.pos(),
1609 diags.fragment("unexpected.ret.val"));
1610 }
1611 attribTree(tree.expr, env, env.info.returnResult);
1612 } else if (!env.info.returnResult.pt.hasTag(VOID)) {
1613 env.info.returnResult.checkContext.report(tree.pos(),
1614 diags.fragment("missing.ret.val"));
1615 }
1616 }
1617 result = null;
1618 }
1620 public void visitThrow(JCThrow tree) {
1621 Type owntype = attribExpr(tree.expr, env, allowPoly ? Type.noType : syms.throwableType);
1622 if (allowPoly) {
1623 chk.checkType(tree, owntype, syms.throwableType);
1624 }
1625 result = null;
1626 }
1628 public void visitAssert(JCAssert tree) {
1629 attribExpr(tree.cond, env, syms.booleanType);
1630 if (tree.detail != null) {
1631 chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
1632 }
1633 result = null;
1634 }
1636 /** Visitor method for method invocations.
1637 * NOTE: The method part of an application will have in its type field
1638 * the return type of the method, not the method's type itself!
1639 */
1640 public void visitApply(JCMethodInvocation tree) {
1641 // The local environment of a method application is
1642 // a new environment nested in the current one.
1643 Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
1645 // The types of the actual method arguments.
1646 List<Type> argtypes;
1648 // The types of the actual method type arguments.
1649 List<Type> typeargtypes = null;
1651 Name methName = TreeInfo.name(tree.meth);
1653 boolean isConstructorCall =
1654 methName == names._this || methName == names._super;
1656 if (isConstructorCall) {
1657 // We are seeing a ...this(...) or ...super(...) call.
1658 // Check that this is the first statement in a constructor.
1659 if (checkFirstConstructorStat(tree, env)) {
1661 // Record the fact
1662 // that this is a constructor call (using isSelfCall).
1663 localEnv.info.isSelfCall = true;
1665 // Attribute arguments, yielding list of argument types.
1666 argtypes = attribArgs(tree.args, localEnv);
1667 typeargtypes = attribTypes(tree.typeargs, localEnv);
1669 // Variable `site' points to the class in which the called
1670 // constructor is defined.
1671 Type site = env.enclClass.sym.type;
1672 if (methName == names._super) {
1673 if (site == syms.objectType) {
1674 log.error(tree.meth.pos(), "no.superclass", site);
1675 site = types.createErrorType(syms.objectType);
1676 } else {
1677 site = types.supertype(site);
1678 }
1679 }
1681 if (site.hasTag(CLASS)) {
1682 Type encl = site.getEnclosingType();
1683 while (encl != null && encl.hasTag(TYPEVAR))
1684 encl = encl.getUpperBound();
1685 if (encl.hasTag(CLASS)) {
1686 // we are calling a nested class
1688 if (tree.meth.hasTag(SELECT)) {
1689 JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
1691 // We are seeing a prefixed call, of the form
1692 // <expr>.super(...).
1693 // Check that the prefix expression conforms
1694 // to the outer instance type of the class.
1695 chk.checkRefType(qualifier.pos(),
1696 attribExpr(qualifier, localEnv,
1697 encl));
1698 } else if (methName == names._super) {
1699 // qualifier omitted; check for existence
1700 // of an appropriate implicit qualifier.
1701 rs.resolveImplicitThis(tree.meth.pos(),
1702 localEnv, site, true);
1703 }
1704 } else if (tree.meth.hasTag(SELECT)) {
1705 log.error(tree.meth.pos(), "illegal.qual.not.icls",
1706 site.tsym);
1707 }
1709 // if we're calling a java.lang.Enum constructor,
1710 // prefix the implicit String and int parameters
1711 if (site.tsym == syms.enumSym && allowEnums)
1712 argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
1714 // Resolve the called constructor under the assumption
1715 // that we are referring to a superclass instance of the
1716 // current instance (JLS ???).
1717 boolean selectSuperPrev = localEnv.info.selectSuper;
1718 localEnv.info.selectSuper = true;
1719 localEnv.info.pendingResolutionPhase = null;
1720 Symbol sym = rs.resolveConstructor(
1721 tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
1722 localEnv.info.selectSuper = selectSuperPrev;
1724 // Set method symbol to resolved constructor...
1725 TreeInfo.setSymbol(tree.meth, sym);
1727 // ...and check that it is legal in the current context.
1728 // (this will also set the tree's type)
1729 Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
1730 checkId(tree.meth, site, sym, localEnv, new ResultInfo(MTH, mpt));
1731 }
1732 // Otherwise, `site' is an error type and we do nothing
1733 }
1734 result = tree.type = syms.voidType;
1735 } else {
1736 // Otherwise, we are seeing a regular method call.
1737 // Attribute the arguments, yielding list of argument types, ...
1738 argtypes = attribArgs(tree.args, localEnv);
1739 typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
1741 // ... and attribute the method using as a prototype a methodtype
1742 // whose formal argument types is exactly the list of actual
1743 // arguments (this will also set the method symbol).
1744 Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
1745 localEnv.info.pendingResolutionPhase = null;
1746 Type mtype = attribTree(tree.meth, localEnv, new ResultInfo(VAL, mpt, resultInfo.checkContext));
1748 // Compute the result type.
1749 Type restype = mtype.getReturnType();
1750 if (restype.hasTag(WILDCARD))
1751 throw new AssertionError(mtype);
1753 Type qualifier = (tree.meth.hasTag(SELECT))
1754 ? ((JCFieldAccess) tree.meth).selected.type
1755 : env.enclClass.sym.type;
1756 restype = adjustMethodReturnType(qualifier, methName, argtypes, restype);
1758 chk.checkRefTypes(tree.typeargs, typeargtypes);
1760 // Check that value of resulting type is admissible in the
1761 // current context. Also, capture the return type
1762 result = check(tree, capture(restype), VAL, resultInfo);
1764 if (localEnv.info.lastResolveVarargs())
1765 Assert.check(result.isErroneous() || tree.varargsElement != null);
1766 }
1767 chk.validate(tree.typeargs, localEnv);
1768 }
1769 //where
1770 Type adjustMethodReturnType(Type qualifierType, Name methodName, List<Type> argtypes, Type restype) {
1771 if (allowCovariantReturns &&
1772 methodName == names.clone &&
1773 types.isArray(qualifierType)) {
1774 // as a special case, array.clone() has a result that is
1775 // the same as static type of the array being cloned
1776 return qualifierType;
1777 } else if (allowGenerics &&
1778 methodName == names.getClass &&
1779 argtypes.isEmpty()) {
1780 // as a special case, x.getClass() has type Class<? extends |X|>
1781 return new ClassType(restype.getEnclosingType(),
1782 List.<Type>of(new WildcardType(types.erasure(qualifierType),
1783 BoundKind.EXTENDS,
1784 syms.boundClass)),
1785 restype.tsym);
1786 } else {
1787 return restype;
1788 }
1789 }
1791 /** Check that given application node appears as first statement
1792 * in a constructor call.
1793 * @param tree The application node
1794 * @param env The environment current at the application.
1795 */
1796 boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) {
1797 JCMethodDecl enclMethod = env.enclMethod;
1798 if (enclMethod != null && enclMethod.name == names.init) {
1799 JCBlock body = enclMethod.body;
1800 if (body.stats.head.hasTag(EXEC) &&
1801 ((JCExpressionStatement) body.stats.head).expr == tree)
1802 return true;
1803 }
1804 log.error(tree.pos(),"call.must.be.first.stmt.in.ctor",
1805 TreeInfo.name(tree.meth));
1806 return false;
1807 }
1809 /** Obtain a method type with given argument types.
1810 */
1811 Type newMethodTemplate(Type restype, List<Type> argtypes, List<Type> typeargtypes) {
1812 MethodType mt = new MethodType(argtypes, restype, List.<Type>nil(), syms.methodClass);
1813 return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
1814 }
1816 public void visitNewClass(final JCNewClass tree) {
1817 Type owntype = types.createErrorType(tree.type);
1819 // The local environment of a class creation is
1820 // a new environment nested in the current one.
1821 Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
1823 // The anonymous inner class definition of the new expression,
1824 // if one is defined by it.
1825 JCClassDecl cdef = tree.def;
1827 // If enclosing class is given, attribute it, and
1828 // complete class name to be fully qualified
1829 JCExpression clazz = tree.clazz; // Class field following new
1830 JCExpression clazzid = // Identifier in class field
1831 (clazz.hasTag(TYPEAPPLY))
1832 ? ((JCTypeApply) clazz).clazz
1833 : clazz;
1835 JCExpression clazzid1 = clazzid; // The same in fully qualified form
1837 if (tree.encl != null) {
1838 // We are seeing a qualified new, of the form
1839 // <expr>.new C <...> (...) ...
1840 // In this case, we let clazz stand for the name of the
1841 // allocated class C prefixed with the type of the qualifier
1842 // expression, so that we can
1843 // resolve it with standard techniques later. I.e., if
1844 // <expr> has type T, then <expr>.new C <...> (...)
1845 // yields a clazz T.C.
1846 Type encltype = chk.checkRefType(tree.encl.pos(),
1847 attribExpr(tree.encl, env));
1848 clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
1849 ((JCIdent) clazzid).name);
1850 if (clazz.hasTag(TYPEAPPLY))
1851 clazz = make.at(tree.pos).
1852 TypeApply(clazzid1,
1853 ((JCTypeApply) clazz).arguments);
1854 else
1855 clazz = clazzid1;
1856 }
1858 // Attribute clazz expression and store
1859 // symbol + type back into the attributed tree.
1860 Type clazztype = TreeInfo.isEnumInit(env.tree) ?
1861 attribIdentAsEnumType(env, (JCIdent)clazz) :
1862 attribType(clazz, env);
1864 clazztype = chk.checkDiamond(tree, clazztype);
1865 chk.validate(clazz, localEnv);
1866 if (tree.encl != null) {
1867 // We have to work in this case to store
1868 // symbol + type back into the attributed tree.
1869 tree.clazz.type = clazztype;
1870 TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
1871 clazzid.type = ((JCIdent) clazzid).sym.type;
1872 if (!clazztype.isErroneous()) {
1873 if (cdef != null && clazztype.tsym.isInterface()) {
1874 log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new");
1875 } else if (clazztype.tsym.isStatic()) {
1876 log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym);
1877 }
1878 }
1879 } else if (!clazztype.tsym.isInterface() &&
1880 clazztype.getEnclosingType().hasTag(CLASS)) {
1881 // Check for the existence of an apropos outer instance
1882 rs.resolveImplicitThis(tree.pos(), env, clazztype);
1883 }
1885 // Attribute constructor arguments.
1886 List<Type> argtypes = attribArgs(tree.args, localEnv);
1887 List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
1889 // If we have made no mistakes in the class type...
1890 if (clazztype.hasTag(CLASS)) {
1891 // Enums may not be instantiated except implicitly
1892 if (allowEnums &&
1893 (clazztype.tsym.flags_field&Flags.ENUM) != 0 &&
1894 (!env.tree.hasTag(VARDEF) ||
1895 (((JCVariableDecl) env.tree).mods.flags&Flags.ENUM) == 0 ||
1896 ((JCVariableDecl) env.tree).init != tree))
1897 log.error(tree.pos(), "enum.cant.be.instantiated");
1898 // Check that class is not abstract
1899 if (cdef == null &&
1900 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
1901 log.error(tree.pos(), "abstract.cant.be.instantiated",
1902 clazztype.tsym);
1903 } else if (cdef != null && clazztype.tsym.isInterface()) {
1904 // Check that no constructor arguments are given to
1905 // anonymous classes implementing an interface
1906 if (!argtypes.isEmpty())
1907 log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args");
1909 if (!typeargtypes.isEmpty())
1910 log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs");
1912 // Error recovery: pretend no arguments were supplied.
1913 argtypes = List.nil();
1914 typeargtypes = List.nil();
1915 } else if (TreeInfo.isDiamond(tree)) {
1916 ClassType site = new ClassType(clazztype.getEnclosingType(),
1917 clazztype.tsym.type.getTypeArguments(),
1918 clazztype.tsym);
1920 Env<AttrContext> diamondEnv = localEnv.dup(tree);
1921 diamondEnv.info.selectSuper = cdef != null;
1922 diamondEnv.info.pendingResolutionPhase = null;
1924 //if the type of the instance creation expression is a class type
1925 //apply method resolution inference (JLS 15.12.2.7). The return type
1926 //of the resolved constructor will be a partially instantiated type
1927 Symbol constructor = rs.resolveDiamond(tree.pos(),
1928 diamondEnv,
1929 site,
1930 argtypes,
1931 typeargtypes);
1932 tree.constructor = constructor.baseSymbol();
1934 final TypeSymbol csym = clazztype.tsym;
1935 ResultInfo diamondResult = new ResultInfo(MTH, newMethodTemplate(resultInfo.pt, argtypes, typeargtypes), new Check.NestedCheckContext(resultInfo.checkContext) {
1936 @Override
1937 public void report(DiagnosticPosition _unused, JCDiagnostic details) {
1938 enclosingContext.report(tree.clazz,
1939 diags.fragment("cant.apply.diamond.1", diags.fragment("diamond", csym), details));
1940 }
1941 });
1942 Type constructorType = tree.constructorType = types.createErrorType(clazztype);
1943 constructorType = checkId(tree, site,
1944 constructor,
1945 diamondEnv,
1946 diamondResult);
1948 tree.clazz.type = types.createErrorType(clazztype);
1949 if (!constructorType.isErroneous()) {
1950 tree.clazz.type = clazztype = constructorType.getReturnType();
1951 tree.constructorType = types.createMethodTypeWithReturn(constructorType, syms.voidType);
1952 }
1953 clazztype = chk.checkClassType(tree.clazz, tree.clazz.type, true);
1954 }
1956 // Resolve the called constructor under the assumption
1957 // that we are referring to a superclass instance of the
1958 // current instance (JLS ???).
1959 else {
1960 //the following code alters some of the fields in the current
1961 //AttrContext - hence, the current context must be dup'ed in
1962 //order to avoid downstream failures
1963 Env<AttrContext> rsEnv = localEnv.dup(tree);
1964 rsEnv.info.selectSuper = cdef != null;
1965 rsEnv.info.pendingResolutionPhase = null;
1966 tree.constructor = rs.resolveConstructor(
1967 tree.pos(), rsEnv, clazztype, argtypes, typeargtypes);
1968 if (cdef == null) { //do not check twice!
1969 tree.constructorType = checkId(tree,
1970 clazztype,
1971 tree.constructor,
1972 rsEnv,
1973 new ResultInfo(MTH, newMethodTemplate(syms.voidType, argtypes, typeargtypes)));
1974 if (rsEnv.info.lastResolveVarargs())
1975 Assert.check(tree.constructorType.isErroneous() || tree.varargsElement != null);
1976 }
1977 findDiamondIfNeeded(localEnv, tree, clazztype);
1978 }
1980 if (cdef != null) {
1981 // We are seeing an anonymous class instance creation.
1982 // In this case, the class instance creation
1983 // expression
1984 //
1985 // E.new <typeargs1>C<typargs2>(args) { ... }
1986 //
1987 // is represented internally as
1988 //
1989 // E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } ) .
1990 //
1991 // This expression is then *transformed* as follows:
1992 //
1993 // (1) add a STATIC flag to the class definition
1994 // if the current environment is static
1995 // (2) add an extends or implements clause
1996 // (3) add a constructor.
1997 //
1998 // For instance, if C is a class, and ET is the type of E,
1999 // the expression
2000 //
2001 // E.new <typeargs1>C<typargs2>(args) { ... }
2002 //
2003 // is translated to (where X is a fresh name and typarams is the
2004 // parameter list of the super constructor):
2005 //
2006 // new <typeargs1>X(<*nullchk*>E, args) where
2007 // X extends C<typargs2> {
2008 // <typarams> X(ET e, args) {
2009 // e.<typeargs1>super(args)
2010 // }
2011 // ...
2012 // }
2013 if (Resolve.isStatic(env)) cdef.mods.flags |= STATIC;
2015 if (clazztype.tsym.isInterface()) {
2016 cdef.implementing = List.of(clazz);
2017 } else {
2018 cdef.extending = clazz;
2019 }
2021 attribStat(cdef, localEnv);
2023 checkLambdaCandidate(tree, cdef.sym, clazztype);
2025 // If an outer instance is given,
2026 // prefix it to the constructor arguments
2027 // and delete it from the new expression
2028 if (tree.encl != null && !clazztype.tsym.isInterface()) {
2029 tree.args = tree.args.prepend(makeNullCheck(tree.encl));
2030 argtypes = argtypes.prepend(tree.encl.type);
2031 tree.encl = null;
2032 }
2034 // Reassign clazztype and recompute constructor.
2035 clazztype = cdef.sym.type;
2036 Symbol sym = tree.constructor = rs.resolveConstructor(
2037 tree.pos(), localEnv, clazztype, argtypes, typeargtypes);
2038 Assert.check(sym.kind < AMBIGUOUS);
2039 tree.constructor = sym;
2040 tree.constructorType = checkId(tree,
2041 clazztype,
2042 tree.constructor,
2043 localEnv,
2044 new ResultInfo(VAL, newMethodTemplate(syms.voidType, argtypes, typeargtypes)));
2045 }
2047 if (tree.constructor != null && tree.constructor.kind == MTH)
2048 owntype = clazztype;
2049 }
2050 result = check(tree, owntype, VAL, resultInfo);
2051 chk.validate(tree.typeargs, localEnv);
2052 }
2053 //where
2054 void findDiamondIfNeeded(Env<AttrContext> env, JCNewClass tree, Type clazztype) {
2055 if (tree.def == null &&
2056 !clazztype.isErroneous() &&
2057 clazztype.getTypeArguments().nonEmpty() &&
2058 findDiamonds) {
2059 JCTypeApply ta = (JCTypeApply)tree.clazz;
2060 List<JCExpression> prevTypeargs = ta.arguments;
2061 try {
2062 //create a 'fake' diamond AST node by removing type-argument trees
2063 ta.arguments = List.nil();
2064 ResultInfo findDiamondResult = new ResultInfo(VAL,
2065 resultInfo.checkContext.inferenceContext().free(resultInfo.pt) ? Type.noType : pt());
2066 Type inferred = deferredAttr.attribSpeculative(tree, env, findDiamondResult).type;
2067 if (!inferred.isErroneous() &&
2068 types.isAssignable(inferred, pt().hasTag(NONE) ? syms.objectType : pt(), types.noWarnings)) {
2069 String key = types.isSameType(clazztype, inferred) ?
2070 "diamond.redundant.args" :
2071 "diamond.redundant.args.1";
2072 log.warning(tree.clazz.pos(), key, clazztype, inferred);
2073 }
2074 } finally {
2075 ta.arguments = prevTypeargs;
2076 }
2077 }
2078 }
2080 private void checkLambdaCandidate(JCNewClass tree, ClassSymbol csym, Type clazztype) {
2081 if (allowLambda &&
2082 identifyLambdaCandidate &&
2083 clazztype.hasTag(CLASS) &&
2084 !pt().hasTag(NONE) &&
2085 types.isFunctionalInterface(clazztype.tsym)) {
2086 Symbol descriptor = types.findDescriptorSymbol(clazztype.tsym);
2087 int count = 0;
2088 boolean found = false;
2089 for (Symbol sym : csym.members().getElements()) {
2090 if ((sym.flags() & SYNTHETIC) != 0 ||
2091 sym.isConstructor()) continue;
2092 count++;
2093 if (sym.kind != MTH ||
2094 !sym.name.equals(descriptor.name)) continue;
2095 Type mtype = types.memberType(clazztype, sym);
2096 if (types.overrideEquivalent(mtype, types.memberType(clazztype, descriptor))) {
2097 found = true;
2098 }
2099 }
2100 if (found && count == 1) {
2101 log.note(tree.def, "potential.lambda.found");
2102 }
2103 }
2104 }
2106 /** Make an attributed null check tree.
2107 */
2108 public JCExpression makeNullCheck(JCExpression arg) {
2109 // optimization: X.this is never null; skip null check
2110 Name name = TreeInfo.name(arg);
2111 if (name == names._this || name == names._super) return arg;
2113 JCTree.Tag optag = NULLCHK;
2114 JCUnary tree = make.at(arg.pos).Unary(optag, arg);
2115 tree.operator = syms.nullcheck;
2116 tree.type = arg.type;
2117 return tree;
2118 }
2120 public void visitNewArray(JCNewArray tree) {
2121 Type owntype = types.createErrorType(tree.type);
2122 Env<AttrContext> localEnv = env.dup(tree);
2123 Type elemtype;
2124 if (tree.elemtype != null) {
2125 elemtype = attribType(tree.elemtype, localEnv);
2126 chk.validate(tree.elemtype, localEnv);
2127 owntype = elemtype;
2128 for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
2129 attribExpr(l.head, localEnv, syms.intType);
2130 owntype = new ArrayType(owntype, syms.arrayClass);
2131 }
2132 } else {
2133 // we are seeing an untyped aggregate { ... }
2134 // this is allowed only if the prototype is an array
2135 if (pt().hasTag(ARRAY)) {
2136 elemtype = types.elemtype(pt());
2137 } else {
2138 if (!pt().hasTag(ERROR)) {
2139 log.error(tree.pos(), "illegal.initializer.for.type",
2140 pt());
2141 }
2142 elemtype = types.createErrorType(pt());
2143 }
2144 }
2145 if (tree.elems != null) {
2146 attribExprs(tree.elems, localEnv, elemtype);
2147 owntype = new ArrayType(elemtype, syms.arrayClass);
2148 }
2149 if (!types.isReifiable(elemtype))
2150 log.error(tree.pos(), "generic.array.creation");
2151 result = check(tree, owntype, VAL, resultInfo);
2152 }
2154 /*
2155 * A lambda expression can only be attributed when a target-type is available.
2156 * In addition, if the target-type is that of a functional interface whose
2157 * descriptor contains inference variables in argument position the lambda expression
2158 * is 'stuck' (see DeferredAttr).
2159 */
2160 @Override
2161 public void visitLambda(final JCLambda that) {
2162 if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
2163 if (pt().hasTag(NONE)) {
2164 //lambda only allowed in assignment or method invocation/cast context
2165 log.error(that.pos(), "unexpected.lambda");
2166 }
2167 result = that.type = types.createErrorType(pt());
2168 return;
2169 }
2170 //create an environment for attribution of the lambda expression
2171 final Env<AttrContext> localEnv = lambdaEnv(that, env);
2172 boolean needsRecovery =
2173 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK;
2174 try {
2175 List<Type> explicitParamTypes = null;
2176 if (TreeInfo.isExplicitLambda(that)) {
2177 //attribute lambda parameters
2178 attribStats(that.params, localEnv);
2179 explicitParamTypes = TreeInfo.types(that.params);
2180 }
2182 Type target;
2183 Type lambdaType;
2184 if (pt() != Type.recoveryType) {
2185 target = infer.instantiateFunctionalInterface(that, checkIntersectionTarget(that, resultInfo), explicitParamTypes, resultInfo.checkContext);
2186 lambdaType = types.findDescriptorType(target);
2187 chk.checkFunctionalInterface(that, target);
2188 } else {
2189 target = Type.recoveryType;
2190 lambdaType = fallbackDescriptorType(that);
2191 }
2193 if (lambdaType.hasTag(FORALL)) {
2194 //lambda expression target desc cannot be a generic method
2195 resultInfo.checkContext.report(that, diags.fragment("invalid.generic.lambda.target",
2196 lambdaType, kindName(target.tsym), target.tsym));
2197 result = that.type = types.createErrorType(pt());
2198 return;
2199 }
2201 if (!TreeInfo.isExplicitLambda(that)) {
2202 //add param type info in the AST
2203 List<Type> actuals = lambdaType.getParameterTypes();
2204 List<JCVariableDecl> params = that.params;
2206 boolean arityMismatch = false;
2208 while (params.nonEmpty()) {
2209 if (actuals.isEmpty()) {
2210 //not enough actuals to perform lambda parameter inference
2211 arityMismatch = true;
2212 }
2213 //reset previously set info
2214 Type argType = arityMismatch ?
2215 syms.errType :
2216 actuals.head;
2217 params.head.vartype = make.Type(argType);
2218 params.head.sym = null;
2219 actuals = actuals.isEmpty() ?
2220 actuals :
2221 actuals.tail;
2222 params = params.tail;
2223 }
2225 //attribute lambda parameters
2226 attribStats(that.params, localEnv);
2228 if (arityMismatch) {
2229 resultInfo.checkContext.report(that, diags.fragment("incompatible.arg.types.in.lambda"));
2230 result = that.type = types.createErrorType(target);
2231 return;
2232 }
2233 }
2235 //from this point on, no recovery is needed; if we are in assignment context
2236 //we will be able to attribute the whole lambda body, regardless of errors;
2237 //if we are in a 'check' method context, and the lambda is not compatible
2238 //with the target-type, it will be recovered anyway in Attr.checkId
2239 needsRecovery = false;
2241 FunctionalReturnContext funcContext = that.getBodyKind() == JCLambda.BodyKind.EXPRESSION ?
2242 new ExpressionLambdaReturnContext((JCExpression)that.getBody(), resultInfo.checkContext) :
2243 new FunctionalReturnContext(resultInfo.checkContext);
2245 ResultInfo bodyResultInfo = lambdaType.getReturnType() == Type.recoveryType ?
2246 recoveryInfo :
2247 new ResultInfo(VAL, lambdaType.getReturnType(), funcContext);
2248 localEnv.info.returnResult = bodyResultInfo;
2250 if (that.getBodyKind() == JCLambda.BodyKind.EXPRESSION) {
2251 attribTree(that.getBody(), localEnv, bodyResultInfo);
2252 } else {
2253 JCBlock body = (JCBlock)that.body;
2254 attribStats(body.stats, localEnv);
2255 }
2257 result = check(that, target, VAL, resultInfo);
2259 boolean isSpeculativeRound =
2260 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
2262 postAttr(that);
2263 flow.analyzeLambda(env, that, make, isSpeculativeRound);
2265 checkLambdaCompatible(that, lambdaType, resultInfo.checkContext, isSpeculativeRound);
2267 if (!isSpeculativeRound) {
2268 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), lambdaType, target);
2269 }
2270 result = check(that, target, VAL, resultInfo);
2271 } catch (Types.FunctionDescriptorLookupError ex) {
2272 JCDiagnostic cause = ex.getDiagnostic();
2273 resultInfo.checkContext.report(that, cause);
2274 result = that.type = types.createErrorType(pt());
2275 return;
2276 } finally {
2277 localEnv.info.scope.leave();
2278 if (needsRecovery) {
2279 attribTree(that, env, recoveryInfo);
2280 }
2281 }
2282 }
2284 private Type checkIntersectionTarget(DiagnosticPosition pos, ResultInfo resultInfo) {
2285 Type pt = resultInfo.pt;
2286 if (pt != Type.recoveryType && pt.isCompound()) {
2287 IntersectionClassType ict = (IntersectionClassType)pt;
2288 List<Type> bounds = ict.allInterfaces ?
2289 ict.getComponents().tail :
2290 ict.getComponents();
2291 types.findDescriptorType(bounds.head); //propagate exception outwards!
2292 for (Type bound : bounds.tail) {
2293 if (!types.isMarkerInterface(bound)) {
2294 resultInfo.checkContext.report(pos, diags.fragment("secondary.bound.must.be.marker.intf", bound));
2295 }
2296 }
2297 //for now (translation doesn't support intersection types)
2298 return bounds.head;
2299 } else {
2300 return pt;
2301 }
2302 }
2303 //where
2304 private Type fallbackDescriptorType(JCExpression tree) {
2305 switch (tree.getTag()) {
2306 case LAMBDA:
2307 JCLambda lambda = (JCLambda)tree;
2308 List<Type> argtypes = List.nil();
2309 for (JCVariableDecl param : lambda.params) {
2310 argtypes = param.vartype != null ?
2311 argtypes.append(param.vartype.type) :
2312 argtypes.append(syms.errType);
2313 }
2314 return new MethodType(argtypes, Type.recoveryType, List.<Type>nil(), syms.methodClass);
2315 case REFERENCE:
2316 return new MethodType(List.<Type>nil(), Type.recoveryType, List.<Type>nil(), syms.methodClass);
2317 default:
2318 Assert.error("Cannot get here!");
2319 }
2320 return null;
2321 }
2323 private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env, final InferenceContext inferenceContext, final Type... ts) {
2324 checkAccessibleTypes(pos, env, inferenceContext, List.from(ts));
2325 }
2327 private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env, final InferenceContext inferenceContext, final List<Type> ts) {
2328 if (inferenceContext.free(ts)) {
2329 inferenceContext.addFreeTypeListener(ts, new FreeTypeListener() {
2330 @Override
2331 public void typesInferred(InferenceContext inferenceContext) {
2332 checkAccessibleTypes(pos, env, inferenceContext, inferenceContext.asInstTypes(ts, types));
2333 }
2334 });
2335 } else {
2336 for (Type t : ts) {
2337 rs.checkAccessibleType(env, t);
2338 }
2339 }
2340 }
2342 /**
2343 * Lambda/method reference have a special check context that ensures
2344 * that i.e. a lambda return type is compatible with the expected
2345 * type according to both the inherited context and the assignment
2346 * context.
2347 */
2348 class FunctionalReturnContext extends Check.NestedCheckContext {
2350 FunctionalReturnContext(CheckContext enclosingContext) {
2351 super(enclosingContext);
2352 }
2354 @Override
2355 public boolean compatible(Type found, Type req, Warner warn) {
2356 //return type must be compatible in both current context and assignment context
2357 return types.isAssignable(found, inferenceContext().asFree(req, types), warn) &&
2358 super.compatible(found, req, warn);
2359 }
2360 @Override
2361 public void report(DiagnosticPosition pos, JCDiagnostic details) {
2362 enclosingContext.report(pos, diags.fragment("incompatible.ret.type.in.lambda", details));
2363 }
2364 }
2366 class ExpressionLambdaReturnContext extends FunctionalReturnContext {
2368 JCExpression expr;
2370 ExpressionLambdaReturnContext(JCExpression expr, CheckContext enclosingContext) {
2371 super(enclosingContext);
2372 this.expr = expr;
2373 }
2375 @Override
2376 public boolean compatible(Type found, Type req, Warner warn) {
2377 //a void return is compatible with an expression statement lambda
2378 return TreeInfo.isExpressionStatement(expr) && req.hasTag(VOID) ||
2379 super.compatible(found, req, warn);
2380 }
2381 }
2383 /**
2384 * Lambda compatibility. Check that given return types, thrown types, parameter types
2385 * are compatible with the expected functional interface descriptor. This means that:
2386 * (i) parameter types must be identical to those of the target descriptor; (ii) return
2387 * types must be compatible with the return type of the expected descriptor;
2388 * (iii) thrown types must be 'included' in the thrown types list of the expected
2389 * descriptor.
2390 */
2391 private void checkLambdaCompatible(JCLambda tree, Type descriptor, CheckContext checkContext, boolean speculativeAttr) {
2392 Type returnType = checkContext.inferenceContext().asFree(descriptor.getReturnType(), types);
2394 //return values have already been checked - but if lambda has no return
2395 //values, we must ensure that void/value compatibility is correct;
2396 //this amounts at checking that, if a lambda body can complete normally,
2397 //the descriptor's return type must be void
2398 if (tree.getBodyKind() == JCLambda.BodyKind.STATEMENT && tree.canCompleteNormally &&
2399 !returnType.hasTag(VOID) && returnType != Type.recoveryType) {
2400 checkContext.report(tree, diags.fragment("incompatible.ret.type.in.lambda",
2401 diags.fragment("missing.ret.val", returnType)));
2402 }
2404 List<Type> argTypes = checkContext.inferenceContext().asFree(descriptor.getParameterTypes(), types);
2405 if (!types.isSameTypes(argTypes, TreeInfo.types(tree.params))) {
2406 checkContext.report(tree, diags.fragment("incompatible.arg.types.in.lambda"));
2407 }
2409 if (!speculativeAttr) {
2410 List<Type> thrownTypes = checkContext.inferenceContext().asFree(descriptor.getThrownTypes(), types);
2411 if (chk.unhandled(tree.inferredThrownTypes == null ? List.<Type>nil() : tree.inferredThrownTypes, thrownTypes).nonEmpty()) {
2412 log.error(tree, "incompatible.thrown.types.in.lambda", tree.inferredThrownTypes);
2413 }
2414 }
2415 }
2417 private Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) {
2418 Env<AttrContext> lambdaEnv;
2419 Symbol owner = env.info.scope.owner;
2420 if (owner.kind == VAR && owner.owner.kind == TYP) {
2421 //field initializer
2422 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared()));
2423 lambdaEnv.info.scope.owner =
2424 new MethodSymbol(0, names.empty, null,
2425 env.info.scope.owner);
2426 } else {
2427 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dup()));
2428 }
2429 return lambdaEnv;
2430 }
2432 @Override
2433 public void visitReference(final JCMemberReference that) {
2434 if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
2435 if (pt().hasTag(NONE)) {
2436 //method reference only allowed in assignment or method invocation/cast context
2437 log.error(that.pos(), "unexpected.mref");
2438 }
2439 result = that.type = types.createErrorType(pt());
2440 return;
2441 }
2442 final Env<AttrContext> localEnv = env.dup(that);
2443 try {
2444 //attribute member reference qualifier - if this is a constructor
2445 //reference, the expected kind must be a type
2446 Type exprType = attribTree(that.expr,
2447 env, new ResultInfo(that.getMode() == ReferenceMode.INVOKE ? VAL | TYP : TYP, Type.noType));
2449 if (that.getMode() == JCMemberReference.ReferenceMode.NEW) {
2450 exprType = chk.checkConstructorRefType(that.expr, exprType);
2451 }
2453 if (exprType.isErroneous()) {
2454 //if the qualifier expression contains problems,
2455 //give up atttribution of method reference
2456 result = that.type = exprType;
2457 return;
2458 }
2460 if (TreeInfo.isStaticSelector(that.expr, names) &&
2461 (that.getMode() != ReferenceMode.NEW || !that.expr.type.isRaw())) {
2462 //if the qualifier is a type, validate it
2463 chk.validate(that.expr, env);
2464 }
2466 //attrib type-arguments
2467 List<Type> typeargtypes = List.nil();
2468 if (that.typeargs != null) {
2469 typeargtypes = attribTypes(that.typeargs, localEnv);
2470 }
2472 Type target;
2473 Type desc;
2474 if (pt() != Type.recoveryType) {
2475 target = infer.instantiateFunctionalInterface(that, checkIntersectionTarget(that, resultInfo), null, resultInfo.checkContext);
2476 desc = types.findDescriptorType(target);
2477 chk.checkFunctionalInterface(that, target);
2478 } else {
2479 target = Type.recoveryType;
2480 desc = fallbackDescriptorType(that);
2481 }
2483 List<Type> argtypes = desc.getParameterTypes();
2485 boolean allowBoxing =
2486 resultInfo.checkContext.deferredAttrContext().phase.isBoxingRequired();
2487 Pair<Symbol, Resolve.ReferenceLookupHelper> refResult = rs.resolveMemberReference(that.pos(), localEnv, that,
2488 that.expr.type, that.name, argtypes, typeargtypes, allowBoxing);
2490 Symbol refSym = refResult.fst;
2491 Resolve.ReferenceLookupHelper lookupHelper = refResult.snd;
2493 if (refSym.kind != MTH) {
2494 boolean targetError;
2495 switch (refSym.kind) {
2496 case ABSENT_MTH:
2497 targetError = false;
2498 break;
2499 case WRONG_MTH:
2500 case WRONG_MTHS:
2501 case AMBIGUOUS:
2502 case HIDDEN:
2503 case STATICERR:
2504 case MISSING_ENCL:
2505 targetError = true;
2506 break;
2507 default:
2508 Assert.error("unexpected result kind " + refSym.kind);
2509 targetError = false;
2510 }
2512 JCDiagnostic detailsDiag = ((Resolve.ResolveError)refSym).getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT,
2513 that, exprType.tsym, exprType, that.name, argtypes, typeargtypes);
2515 JCDiagnostic.DiagnosticType diagKind = targetError ?
2516 JCDiagnostic.DiagnosticType.FRAGMENT : JCDiagnostic.DiagnosticType.ERROR;
2518 JCDiagnostic diag = diags.create(diagKind, log.currentSource(), that,
2519 "invalid.mref", Kinds.kindName(that.getMode()), detailsDiag);
2521 if (targetError && target == Type.recoveryType) {
2522 //a target error doesn't make sense during recovery stage
2523 //as we don't know what actual parameter types are
2524 result = that.type = target;
2525 return;
2526 } else {
2527 if (targetError) {
2528 resultInfo.checkContext.report(that, diag);
2529 } else {
2530 log.report(diag);
2531 }
2532 result = that.type = types.createErrorType(target);
2533 return;
2534 }
2535 }
2537 if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
2538 if (refSym.isStatic() && TreeInfo.isStaticSelector(that.expr, names) &&
2539 exprType.getTypeArguments().nonEmpty()) {
2540 //static ref with class type-args
2541 log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
2542 diags.fragment("static.mref.with.targs"));
2543 result = that.type = types.createErrorType(target);
2544 return;
2545 }
2547 if (refSym.isStatic() && !TreeInfo.isStaticSelector(that.expr, names) &&
2548 !lookupHelper.referenceKind(refSym).isUnbound()) {
2549 //no static bound mrefs
2550 log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
2551 diags.fragment("static.bound.mref"));
2552 result = that.type = types.createErrorType(target);
2553 return;
2554 }
2555 }
2557 if (desc.getReturnType() == Type.recoveryType) {
2558 // stop here
2559 result = that.type = target;
2560 return;
2561 }
2563 that.sym = refSym.baseSymbol();
2564 that.kind = lookupHelper.referenceKind(that.sym);
2566 ResultInfo checkInfo =
2567 resultInfo.dup(newMethodTemplate(
2568 desc.getReturnType().hasTag(VOID) ? Type.noType : desc.getReturnType(),
2569 lookupHelper.argtypes,
2570 typeargtypes));
2572 Type refType = checkId(that, lookupHelper.site, refSym, localEnv, checkInfo);
2574 if (!refType.isErroneous()) {
2575 refType = types.createMethodTypeWithReturn(refType,
2576 adjustMethodReturnType(lookupHelper.site, that.name, checkInfo.pt.getParameterTypes(), refType.getReturnType()));
2577 }
2579 //go ahead with standard method reference compatibility check - note that param check
2580 //is a no-op (as this has been taken care during method applicability)
2581 boolean isSpeculativeRound =
2582 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
2583 checkReferenceCompatible(that, desc, refType, resultInfo.checkContext, isSpeculativeRound);
2584 if (!isSpeculativeRound) {
2585 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), desc, target);
2586 }
2587 result = check(that, target, VAL, resultInfo);
2588 } catch (Types.FunctionDescriptorLookupError ex) {
2589 JCDiagnostic cause = ex.getDiagnostic();
2590 resultInfo.checkContext.report(that, cause);
2591 result = that.type = types.createErrorType(pt());
2592 return;
2593 }
2594 }
2596 @SuppressWarnings("fallthrough")
2597 void checkReferenceCompatible(JCMemberReference tree, Type descriptor, Type refType, CheckContext checkContext, boolean speculativeAttr) {
2598 Type returnType = checkContext.inferenceContext().asFree(descriptor.getReturnType(), types);
2600 Type resType;
2601 switch (tree.getMode()) {
2602 case NEW:
2603 if (!tree.expr.type.isRaw()) {
2604 resType = tree.expr.type;
2605 break;
2606 }
2607 default:
2608 resType = refType.getReturnType();
2609 }
2611 Type incompatibleReturnType = resType;
2613 if (returnType.hasTag(VOID)) {
2614 incompatibleReturnType = null;
2615 }
2617 if (!returnType.hasTag(VOID) && !resType.hasTag(VOID)) {
2618 if (resType.isErroneous() ||
2619 new FunctionalReturnContext(checkContext).compatible(resType, returnType, types.noWarnings)) {
2620 incompatibleReturnType = null;
2621 }
2622 }
2624 if (incompatibleReturnType != null) {
2625 checkContext.report(tree, diags.fragment("incompatible.ret.type.in.mref",
2626 diags.fragment("inconvertible.types", resType, descriptor.getReturnType())));
2627 }
2629 if (!speculativeAttr) {
2630 List<Type> thrownTypes = checkContext.inferenceContext().asFree(descriptor.getThrownTypes(), types);
2631 if (chk.unhandled(refType.getThrownTypes(), thrownTypes).nonEmpty()) {
2632 log.error(tree, "incompatible.thrown.types.in.mref", refType.getThrownTypes());
2633 }
2634 }
2635 }
2637 public void visitParens(JCParens tree) {
2638 Type owntype = attribTree(tree.expr, env, resultInfo);
2639 result = check(tree, owntype, pkind(), resultInfo);
2640 Symbol sym = TreeInfo.symbol(tree);
2641 if (sym != null && (sym.kind&(TYP|PCK)) != 0)
2642 log.error(tree.pos(), "illegal.start.of.type");
2643 }
2645 public void visitAssign(JCAssign tree) {
2646 Type owntype = attribTree(tree.lhs, env.dup(tree), varInfo);
2647 Type capturedType = capture(owntype);
2648 attribExpr(tree.rhs, env, owntype);
2649 result = check(tree, capturedType, VAL, resultInfo);
2650 }
2652 public void visitAssignop(JCAssignOp tree) {
2653 // Attribute arguments.
2654 Type owntype = attribTree(tree.lhs, env, varInfo);
2655 Type operand = attribExpr(tree.rhs, env);
2656 // Find operator.
2657 Symbol operator = tree.operator = rs.resolveBinaryOperator(
2658 tree.pos(), tree.getTag().noAssignOp(), env,
2659 owntype, operand);
2661 if (operator.kind == MTH &&
2662 !owntype.isErroneous() &&
2663 !operand.isErroneous()) {
2664 chk.checkOperator(tree.pos(),
2665 (OperatorSymbol)operator,
2666 tree.getTag().noAssignOp(),
2667 owntype,
2668 operand);
2669 chk.checkDivZero(tree.rhs.pos(), operator, operand);
2670 chk.checkCastable(tree.rhs.pos(),
2671 operator.type.getReturnType(),
2672 owntype);
2673 }
2674 result = check(tree, owntype, VAL, resultInfo);
2675 }
2677 public void visitUnary(JCUnary tree) {
2678 // Attribute arguments.
2679 Type argtype = (tree.getTag().isIncOrDecUnaryOp())
2680 ? attribTree(tree.arg, env, varInfo)
2681 : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
2683 // Find operator.
2684 Symbol operator = tree.operator =
2685 rs.resolveUnaryOperator(tree.pos(), tree.getTag(), env, argtype);
2687 Type owntype = types.createErrorType(tree.type);
2688 if (operator.kind == MTH &&
2689 !argtype.isErroneous()) {
2690 owntype = (tree.getTag().isIncOrDecUnaryOp())
2691 ? tree.arg.type
2692 : operator.type.getReturnType();
2693 int opc = ((OperatorSymbol)operator).opcode;
2695 // If the argument is constant, fold it.
2696 if (argtype.constValue() != null) {
2697 Type ctype = cfolder.fold1(opc, argtype);
2698 if (ctype != null) {
2699 owntype = cfolder.coerce(ctype, owntype);
2701 // Remove constant types from arguments to
2702 // conserve space. The parser will fold concatenations
2703 // of string literals; the code here also
2704 // gets rid of intermediate results when some of the
2705 // operands are constant identifiers.
2706 if (tree.arg.type.tsym == syms.stringType.tsym) {
2707 tree.arg.type = syms.stringType;
2708 }
2709 }
2710 }
2711 }
2712 result = check(tree, owntype, VAL, resultInfo);
2713 }
2715 public void visitBinary(JCBinary tree) {
2716 // Attribute arguments.
2717 Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
2718 Type right = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.rhs, env));
2720 // Find operator.
2721 Symbol operator = tree.operator =
2722 rs.resolveBinaryOperator(tree.pos(), tree.getTag(), env, left, right);
2724 Type owntype = types.createErrorType(tree.type);
2725 if (operator.kind == MTH &&
2726 !left.isErroneous() &&
2727 !right.isErroneous()) {
2728 owntype = operator.type.getReturnType();
2729 int opc = chk.checkOperator(tree.lhs.pos(),
2730 (OperatorSymbol)operator,
2731 tree.getTag(),
2732 left,
2733 right);
2735 // If both arguments are constants, fold them.
2736 if (left.constValue() != null && right.constValue() != null) {
2737 Type ctype = cfolder.fold2(opc, left, right);
2738 if (ctype != null) {
2739 owntype = cfolder.coerce(ctype, owntype);
2741 // Remove constant types from arguments to
2742 // conserve space. The parser will fold concatenations
2743 // of string literals; the code here also
2744 // gets rid of intermediate results when some of the
2745 // operands are constant identifiers.
2746 if (tree.lhs.type.tsym == syms.stringType.tsym) {
2747 tree.lhs.type = syms.stringType;
2748 }
2749 if (tree.rhs.type.tsym == syms.stringType.tsym) {
2750 tree.rhs.type = syms.stringType;
2751 }
2752 }
2753 }
2755 // Check that argument types of a reference ==, != are
2756 // castable to each other, (JLS???).
2757 if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
2758 if (!types.isCastable(left, right, new Warner(tree.pos()))) {
2759 log.error(tree.pos(), "incomparable.types", left, right);
2760 }
2761 }
2763 chk.checkDivZero(tree.rhs.pos(), operator, right);
2764 }
2765 result = check(tree, owntype, VAL, resultInfo);
2766 }
2768 public void visitTypeCast(final JCTypeCast tree) {
2769 Type clazztype = attribType(tree.clazz, env);
2770 chk.validate(tree.clazz, env, false);
2771 //a fresh environment is required for 292 inference to work properly ---
2772 //see Infer.instantiatePolymorphicSignatureInstance()
2773 Env<AttrContext> localEnv = env.dup(tree);
2774 //should we propagate the target type?
2775 final ResultInfo castInfo;
2776 final boolean isPoly = TreeInfo.isPoly(tree.expr, tree);
2777 if (isPoly) {
2778 //expression is a poly - we need to propagate target type info
2779 castInfo = new ResultInfo(VAL, clazztype, new Check.NestedCheckContext(resultInfo.checkContext) {
2780 @Override
2781 public boolean compatible(Type found, Type req, Warner warn) {
2782 return types.isCastable(found, req, warn);
2783 }
2784 });
2785 } else {
2786 //standalone cast - target-type info is not propagated
2787 castInfo = unknownExprInfo;
2788 }
2789 Type exprtype = attribTree(tree.expr, localEnv, castInfo);
2790 Type owntype = isPoly ? clazztype : chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
2791 if (exprtype.constValue() != null)
2792 owntype = cfolder.coerce(exprtype, owntype);
2793 result = check(tree, capture(owntype), VAL, resultInfo);
2794 if (!isPoly)
2795 chk.checkRedundantCast(localEnv, tree);
2796 }
2798 public void visitTypeTest(JCInstanceOf tree) {
2799 Type exprtype = chk.checkNullOrRefType(
2800 tree.expr.pos(), attribExpr(tree.expr, env));
2801 Type clazztype = chk.checkReifiableReferenceType(
2802 tree.clazz.pos(), attribType(tree.clazz, env));
2803 chk.validate(tree.clazz, env, false);
2804 chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
2805 result = check(tree, syms.booleanType, VAL, resultInfo);
2806 }
2808 public void visitIndexed(JCArrayAccess tree) {
2809 Type owntype = types.createErrorType(tree.type);
2810 Type atype = attribExpr(tree.indexed, env);
2811 attribExpr(tree.index, env, syms.intType);
2812 if (types.isArray(atype))
2813 owntype = types.elemtype(atype);
2814 else if (!atype.hasTag(ERROR))
2815 log.error(tree.pos(), "array.req.but.found", atype);
2816 if ((pkind() & VAR) == 0) owntype = capture(owntype);
2817 result = check(tree, owntype, VAR, resultInfo);
2818 }
2820 public void visitIdent(JCIdent tree) {
2821 Symbol sym;
2823 // Find symbol
2824 if (pt().hasTag(METHOD) || pt().hasTag(FORALL)) {
2825 // If we are looking for a method, the prototype `pt' will be a
2826 // method type with the type of the call's arguments as parameters.
2827 env.info.pendingResolutionPhase = null;
2828 sym = rs.resolveMethod(tree.pos(), env, tree.name, pt().getParameterTypes(), pt().getTypeArguments());
2829 } else if (tree.sym != null && tree.sym.kind != VAR) {
2830 sym = tree.sym;
2831 } else {
2832 sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind());
2833 }
2834 tree.sym = sym;
2836 // (1) Also find the environment current for the class where
2837 // sym is defined (`symEnv').
2838 // Only for pre-tiger versions (1.4 and earlier):
2839 // (2) Also determine whether we access symbol out of an anonymous
2840 // class in a this or super call. This is illegal for instance
2841 // members since such classes don't carry a this$n link.
2842 // (`noOuterThisPath').
2843 Env<AttrContext> symEnv = env;
2844 boolean noOuterThisPath = false;
2845 if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
2846 (sym.kind & (VAR | MTH | TYP)) != 0 &&
2847 sym.owner.kind == TYP &&
2848 tree.name != names._this && tree.name != names._super) {
2850 // Find environment in which identifier is defined.
2851 while (symEnv.outer != null &&
2852 !sym.isMemberOf(symEnv.enclClass.sym, types)) {
2853 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
2854 noOuterThisPath = !allowAnonOuterThis;
2855 symEnv = symEnv.outer;
2856 }
2857 }
2859 // If symbol is a variable, ...
2860 if (sym.kind == VAR) {
2861 VarSymbol v = (VarSymbol)sym;
2863 // ..., evaluate its initializer, if it has one, and check for
2864 // illegal forward reference.
2865 checkInit(tree, env, v, false);
2867 // If we are expecting a variable (as opposed to a value), check
2868 // that the variable is assignable in the current environment.
2869 if (pkind() == VAR)
2870 checkAssignable(tree.pos(), v, null, env);
2871 }
2873 // In a constructor body,
2874 // if symbol is a field or instance method, check that it is
2875 // not accessed before the supertype constructor is called.
2876 if ((symEnv.info.isSelfCall || noOuterThisPath) &&
2877 (sym.kind & (VAR | MTH)) != 0 &&
2878 sym.owner.kind == TYP &&
2879 (sym.flags() & STATIC) == 0) {
2880 chk.earlyRefError(tree.pos(), sym.kind == VAR ? sym : thisSym(tree.pos(), env));
2881 }
2882 Env<AttrContext> env1 = env;
2883 if (sym.kind != ERR && sym.kind != TYP && sym.owner != null && sym.owner != env1.enclClass.sym) {
2884 // If the found symbol is inaccessible, then it is
2885 // accessed through an enclosing instance. Locate this
2886 // enclosing instance:
2887 while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
2888 env1 = env1.outer;
2889 }
2890 result = checkId(tree, env1.enclClass.sym.type, sym, env, resultInfo);
2891 }
2893 public void visitSelect(JCFieldAccess tree) {
2894 // Determine the expected kind of the qualifier expression.
2895 int skind = 0;
2896 if (tree.name == names._this || tree.name == names._super ||
2897 tree.name == names._class)
2898 {
2899 skind = TYP;
2900 } else {
2901 if ((pkind() & PCK) != 0) skind = skind | PCK;
2902 if ((pkind() & TYP) != 0) skind = skind | TYP | PCK;
2903 if ((pkind() & (VAL | MTH)) != 0) skind = skind | VAL | TYP;
2904 }
2906 // Attribute the qualifier expression, and determine its symbol (if any).
2907 Type site = attribTree(tree.selected, env, new ResultInfo(skind, Infer.anyPoly));
2908 if ((pkind() & (PCK | TYP)) == 0)
2909 site = capture(site); // Capture field access
2911 // don't allow T.class T[].class, etc
2912 if (skind == TYP) {
2913 Type elt = site;
2914 while (elt.hasTag(ARRAY))
2915 elt = ((ArrayType)elt).elemtype;
2916 if (elt.hasTag(TYPEVAR)) {
2917 log.error(tree.pos(), "type.var.cant.be.deref");
2918 result = types.createErrorType(tree.type);
2919 return;
2920 }
2921 }
2923 // If qualifier symbol is a type or `super', assert `selectSuper'
2924 // for the selection. This is relevant for determining whether
2925 // protected symbols are accessible.
2926 Symbol sitesym = TreeInfo.symbol(tree.selected);
2927 boolean selectSuperPrev = env.info.selectSuper;
2928 env.info.selectSuper =
2929 sitesym != null &&
2930 sitesym.name == names._super;
2932 // Determine the symbol represented by the selection.
2933 env.info.pendingResolutionPhase = null;
2934 Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
2935 if (sym.exists() && !isType(sym) && (pkind() & (PCK | TYP)) != 0) {
2936 site = capture(site);
2937 sym = selectSym(tree, sitesym, site, env, resultInfo);
2938 }
2939 boolean varArgs = env.info.lastResolveVarargs();
2940 tree.sym = sym;
2942 if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) {
2943 while (site.hasTag(TYPEVAR)) site = site.getUpperBound();
2944 site = capture(site);
2945 }
2947 // If that symbol is a variable, ...
2948 if (sym.kind == VAR) {
2949 VarSymbol v = (VarSymbol)sym;
2951 // ..., evaluate its initializer, if it has one, and check for
2952 // illegal forward reference.
2953 checkInit(tree, env, v, true);
2955 // If we are expecting a variable (as opposed to a value), check
2956 // that the variable is assignable in the current environment.
2957 if (pkind() == VAR)
2958 checkAssignable(tree.pos(), v, tree.selected, env);
2959 }
2961 if (sitesym != null &&
2962 sitesym.kind == VAR &&
2963 ((VarSymbol)sitesym).isResourceVariable() &&
2964 sym.kind == MTH &&
2965 sym.name.equals(names.close) &&
2966 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) &&
2967 env.info.lint.isEnabled(LintCategory.TRY)) {
2968 log.warning(LintCategory.TRY, tree, "try.explicit.close.call");
2969 }
2971 // Disallow selecting a type from an expression
2972 if (isType(sym) && (sitesym==null || (sitesym.kind&(TYP|PCK)) == 0)) {
2973 tree.type = check(tree.selected, pt(),
2974 sitesym == null ? VAL : sitesym.kind, new ResultInfo(TYP|PCK, pt()));
2975 }
2977 if (isType(sitesym)) {
2978 if (sym.name == names._this) {
2979 // If `C' is the currently compiled class, check that
2980 // C.this' does not appear in a call to a super(...)
2981 if (env.info.isSelfCall &&
2982 site.tsym == env.enclClass.sym) {
2983 chk.earlyRefError(tree.pos(), sym);
2984 }
2985 } else {
2986 // Check if type-qualified fields or methods are static (JLS)
2987 if ((sym.flags() & STATIC) == 0 &&
2988 !env.next.tree.hasTag(REFERENCE) &&
2989 sym.name != names._super &&
2990 (sym.kind == VAR || sym.kind == MTH)) {
2991 rs.accessBase(rs.new StaticError(sym),
2992 tree.pos(), site, sym.name, true);
2993 }
2994 }
2995 } else if (sym.kind != ERR && (sym.flags() & STATIC) != 0 && sym.name != names._class) {
2996 // If the qualified item is not a type and the selected item is static, report
2997 // a warning. Make allowance for the class of an array type e.g. Object[].class)
2998 chk.warnStatic(tree, "static.not.qualified.by.type", Kinds.kindName(sym.kind), sym.owner);
2999 }
3001 // If we are selecting an instance member via a `super', ...
3002 if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
3004 // Check that super-qualified symbols are not abstract (JLS)
3005 rs.checkNonAbstract(tree.pos(), sym);
3007 if (site.isRaw()) {
3008 // Determine argument types for site.
3009 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
3010 if (site1 != null) site = site1;
3011 }
3012 }
3014 env.info.selectSuper = selectSuperPrev;
3015 result = checkId(tree, site, sym, env, resultInfo);
3016 }
3017 //where
3018 /** Determine symbol referenced by a Select expression,
3019 *
3020 * @param tree The select tree.
3021 * @param site The type of the selected expression,
3022 * @param env The current environment.
3023 * @param resultInfo The current result.
3024 */
3025 private Symbol selectSym(JCFieldAccess tree,
3026 Symbol location,
3027 Type site,
3028 Env<AttrContext> env,
3029 ResultInfo resultInfo) {
3030 DiagnosticPosition pos = tree.pos();
3031 Name name = tree.name;
3032 switch (site.getTag()) {
3033 case PACKAGE:
3034 return rs.accessBase(
3035 rs.findIdentInPackage(env, site.tsym, name, resultInfo.pkind),
3036 pos, location, site, name, true);
3037 case ARRAY:
3038 case CLASS:
3039 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) {
3040 return rs.resolveQualifiedMethod(
3041 pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
3042 } else if (name == names._this || name == names._super) {
3043 return rs.resolveSelf(pos, env, site.tsym, name);
3044 } else if (name == names._class) {
3045 // In this case, we have already made sure in
3046 // visitSelect that qualifier expression is a type.
3047 Type t = syms.classType;
3048 List<Type> typeargs = allowGenerics
3049 ? List.of(types.erasure(site))
3050 : List.<Type>nil();
3051 t = new ClassType(t.getEnclosingType(), typeargs, t.tsym);
3052 return new VarSymbol(
3053 STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
3054 } else {
3055 // We are seeing a plain identifier as selector.
3056 Symbol sym = rs.findIdentInType(env, site, name, resultInfo.pkind);
3057 if ((resultInfo.pkind & ERRONEOUS) == 0)
3058 sym = rs.accessBase(sym, pos, location, site, name, true);
3059 return sym;
3060 }
3061 case WILDCARD:
3062 throw new AssertionError(tree);
3063 case TYPEVAR:
3064 // Normally, site.getUpperBound() shouldn't be null.
3065 // It should only happen during memberEnter/attribBase
3066 // when determining the super type which *must* beac
3067 // done before attributing the type variables. In
3068 // other words, we are seeing this illegal program:
3069 // class B<T> extends A<T.foo> {}
3070 Symbol sym = (site.getUpperBound() != null)
3071 ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
3072 : null;
3073 if (sym == null) {
3074 log.error(pos, "type.var.cant.be.deref");
3075 return syms.errSymbol;
3076 } else {
3077 Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
3078 rs.new AccessError(env, site, sym) :
3079 sym;
3080 rs.accessBase(sym2, pos, location, site, name, true);
3081 return sym;
3082 }
3083 case ERROR:
3084 // preserve identifier names through errors
3085 return types.createErrorType(name, site.tsym, site).tsym;
3086 default:
3087 // The qualifier expression is of a primitive type -- only
3088 // .class is allowed for these.
3089 if (name == names._class) {
3090 // In this case, we have already made sure in Select that
3091 // qualifier expression is a type.
3092 Type t = syms.classType;
3093 Type arg = types.boxedClass(site).type;
3094 t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym);
3095 return new VarSymbol(
3096 STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
3097 } else {
3098 log.error(pos, "cant.deref", site);
3099 return syms.errSymbol;
3100 }
3101 }
3102 }
3104 /** Determine type of identifier or select expression and check that
3105 * (1) the referenced symbol is not deprecated
3106 * (2) the symbol's type is safe (@see checkSafe)
3107 * (3) if symbol is a variable, check that its type and kind are
3108 * compatible with the prototype and protokind.
3109 * (4) if symbol is an instance field of a raw type,
3110 * which is being assigned to, issue an unchecked warning if its
3111 * type changes under erasure.
3112 * (5) if symbol is an instance method of a raw type, issue an
3113 * unchecked warning if its argument types change under erasure.
3114 * If checks succeed:
3115 * If symbol is a constant, return its constant type
3116 * else if symbol is a method, return its result type
3117 * otherwise return its type.
3118 * Otherwise return errType.
3119 *
3120 * @param tree The syntax tree representing the identifier
3121 * @param site If this is a select, the type of the selected
3122 * expression, otherwise the type of the current class.
3123 * @param sym The symbol representing the identifier.
3124 * @param env The current environment.
3125 * @param resultInfo The expected result
3126 */
3127 Type checkId(JCTree tree,
3128 Type site,
3129 Symbol sym,
3130 Env<AttrContext> env,
3131 ResultInfo resultInfo) {
3132 return (resultInfo.pt.hasTag(FORALL) || resultInfo.pt.hasTag(METHOD)) ?
3133 checkMethodId(tree, site, sym, env, resultInfo) :
3134 checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
3135 }
3137 Type checkMethodId(JCTree tree,
3138 Type site,
3139 Symbol sym,
3140 Env<AttrContext> env,
3141 ResultInfo resultInfo) {
3142 boolean isPolymorhicSignature =
3143 sym.kind == MTH && ((MethodSymbol)sym.baseSymbol()).isSignaturePolymorphic(types);
3144 return isPolymorhicSignature ?
3145 checkSigPolyMethodId(tree, site, sym, env, resultInfo) :
3146 checkMethodIdInternal(tree, site, sym, env, resultInfo);
3147 }
3149 Type checkSigPolyMethodId(JCTree tree,
3150 Type site,
3151 Symbol sym,
3152 Env<AttrContext> env,
3153 ResultInfo resultInfo) {
3154 //recover original symbol for signature polymorphic methods
3155 checkMethodIdInternal(tree, site, sym.baseSymbol(), env, resultInfo);
3156 env.info.pendingResolutionPhase = Resolve.MethodResolutionPhase.BASIC;
3157 return sym.type;
3158 }
3160 Type checkMethodIdInternal(JCTree tree,
3161 Type site,
3162 Symbol sym,
3163 Env<AttrContext> env,
3164 ResultInfo resultInfo) {
3165 Type pt = resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, sym, env.info.pendingResolutionPhase));
3166 Type owntype = checkIdInternal(tree, site, sym, pt, env, resultInfo);
3167 resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
3168 return owntype;
3169 }
3171 Type checkIdInternal(JCTree tree,
3172 Type site,
3173 Symbol sym,
3174 Type pt,
3175 Env<AttrContext> env,
3176 ResultInfo resultInfo) {
3177 if (pt.isErroneous()) {
3178 return types.createErrorType(site);
3179 }
3180 Type owntype; // The computed type of this identifier occurrence.
3181 switch (sym.kind) {
3182 case TYP:
3183 // For types, the computed type equals the symbol's type,
3184 // except for two situations:
3185 owntype = sym.type;
3186 if (owntype.hasTag(CLASS)) {
3187 chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym);
3188 Type ownOuter = owntype.getEnclosingType();
3190 // (a) If the symbol's type is parameterized, erase it
3191 // because no type parameters were given.
3192 // We recover generic outer type later in visitTypeApply.
3193 if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
3194 owntype = types.erasure(owntype);
3195 }
3197 // (b) If the symbol's type is an inner class, then
3198 // we have to interpret its outer type as a superclass
3199 // of the site type. Example:
3200 //
3201 // class Tree<A> { class Visitor { ... } }
3202 // class PointTree extends Tree<Point> { ... }
3203 // ...PointTree.Visitor...
3204 //
3205 // Then the type of the last expression above is
3206 // Tree<Point>.Visitor.
3207 else if (ownOuter.hasTag(CLASS) && site != ownOuter) {
3208 Type normOuter = site;
3209 if (normOuter.hasTag(CLASS))
3210 normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
3211 if (normOuter == null) // perhaps from an import
3212 normOuter = types.erasure(ownOuter);
3213 if (normOuter != ownOuter)
3214 owntype = new ClassType(
3215 normOuter, List.<Type>nil(), owntype.tsym);
3216 }
3217 }
3218 break;
3219 case VAR:
3220 VarSymbol v = (VarSymbol)sym;
3221 // Test (4): if symbol is an instance field of a raw type,
3222 // which is being assigned to, issue an unchecked warning if
3223 // its type changes under erasure.
3224 if (allowGenerics &&
3225 resultInfo.pkind == VAR &&
3226 v.owner.kind == TYP &&
3227 (v.flags() & STATIC) == 0 &&
3228 (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
3229 Type s = types.asOuterSuper(site, v.owner);
3230 if (s != null &&
3231 s.isRaw() &&
3232 !types.isSameType(v.type, v.erasure(types))) {
3233 chk.warnUnchecked(tree.pos(),
3234 "unchecked.assign.to.var",
3235 v, s);
3236 }
3237 }
3238 // The computed type of a variable is the type of the
3239 // variable symbol, taken as a member of the site type.
3240 owntype = (sym.owner.kind == TYP &&
3241 sym.name != names._this && sym.name != names._super)
3242 ? types.memberType(site, sym)
3243 : sym.type;
3245 // If the variable is a constant, record constant value in
3246 // computed type.
3247 if (v.getConstValue() != null && isStaticReference(tree))
3248 owntype = owntype.constType(v.getConstValue());
3250 if (resultInfo.pkind == VAL) {
3251 owntype = capture(owntype); // capture "names as expressions"
3252 }
3253 break;
3254 case MTH: {
3255 owntype = checkMethod(site, sym,
3256 new ResultInfo(VAL, resultInfo.pt.getReturnType(), resultInfo.checkContext),
3257 env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(),
3258 resultInfo.pt.getTypeArguments());
3259 break;
3260 }
3261 case PCK: case ERR:
3262 owntype = sym.type;
3263 break;
3264 default:
3265 throw new AssertionError("unexpected kind: " + sym.kind +
3266 " in tree " + tree);
3267 }
3269 // Test (1): emit a `deprecation' warning if symbol is deprecated.
3270 // (for constructors, the error was given when the constructor was
3271 // resolved)
3273 if (sym.name != names.init) {
3274 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym);
3275 chk.checkSunAPI(tree.pos(), sym);
3276 }
3278 // Test (3): if symbol is a variable, check that its type and
3279 // kind are compatible with the prototype and protokind.
3280 return check(tree, owntype, sym.kind, resultInfo);
3281 }
3283 /** Check that variable is initialized and evaluate the variable's
3284 * initializer, if not yet done. Also check that variable is not
3285 * referenced before it is defined.
3286 * @param tree The tree making up the variable reference.
3287 * @param env The current environment.
3288 * @param v The variable's symbol.
3289 */
3290 private void checkInit(JCTree tree,
3291 Env<AttrContext> env,
3292 VarSymbol v,
3293 boolean onlyWarning) {
3294 // System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " +
3295 // tree.pos + " " + v.pos + " " +
3296 // Resolve.isStatic(env));//DEBUG
3298 // A forward reference is diagnosed if the declaration position
3299 // of the variable is greater than the current tree position
3300 // and the tree and variable definition occur in the same class
3301 // definition. Note that writes don't count as references.
3302 // This check applies only to class and instance
3303 // variables. Local variables follow different scope rules,
3304 // and are subject to definite assignment checking.
3305 if ((env.info.enclVar == v || v.pos > tree.pos) &&
3306 v.owner.kind == TYP &&
3307 canOwnInitializer(owner(env)) &&
3308 v.owner == env.info.scope.owner.enclClass() &&
3309 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
3310 (!env.tree.hasTag(ASSIGN) ||
3311 TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
3312 String suffix = (env.info.enclVar == v) ?
3313 "self.ref" : "forward.ref";
3314 if (!onlyWarning || isStaticEnumField(v)) {
3315 log.error(tree.pos(), "illegal." + suffix);
3316 } else if (useBeforeDeclarationWarning) {
3317 log.warning(tree.pos(), suffix, v);
3318 }
3319 }
3321 v.getConstValue(); // ensure initializer is evaluated
3323 checkEnumInitializer(tree, env, v);
3324 }
3326 /**
3327 * Check for illegal references to static members of enum. In
3328 * an enum type, constructors and initializers may not
3329 * reference its static members unless they are constant.
3330 *
3331 * @param tree The tree making up the variable reference.
3332 * @param env The current environment.
3333 * @param v The variable's symbol.
3334 * @jls section 8.9 Enums
3335 */
3336 private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
3337 // JLS:
3338 //
3339 // "It is a compile-time error to reference a static field
3340 // of an enum type that is not a compile-time constant
3341 // (15.28) from constructors, instance initializer blocks,
3342 // or instance variable initializer expressions of that
3343 // type. It is a compile-time error for the constructors,
3344 // instance initializer blocks, or instance variable
3345 // initializer expressions of an enum constant e to refer
3346 // to itself or to an enum constant of the same type that
3347 // is declared to the right of e."
3348 if (isStaticEnumField(v)) {
3349 ClassSymbol enclClass = env.info.scope.owner.enclClass();
3351 if (enclClass == null || enclClass.owner == null)
3352 return;
3354 // See if the enclosing class is the enum (or a
3355 // subclass thereof) declaring v. If not, this
3356 // reference is OK.
3357 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
3358 return;
3360 // If the reference isn't from an initializer, then
3361 // the reference is OK.
3362 if (!Resolve.isInitializer(env))
3363 return;
3365 log.error(tree.pos(), "illegal.enum.static.ref");
3366 }
3367 }
3369 /** Is the given symbol a static, non-constant field of an Enum?
3370 * Note: enum literals should not be regarded as such
3371 */
3372 private boolean isStaticEnumField(VarSymbol v) {
3373 return Flags.isEnum(v.owner) &&
3374 Flags.isStatic(v) &&
3375 !Flags.isConstant(v) &&
3376 v.name != names._class;
3377 }
3379 /** Can the given symbol be the owner of code which forms part
3380 * if class initialization? This is the case if the symbol is
3381 * a type or field, or if the symbol is the synthetic method.
3382 * owning a block.
3383 */
3384 private boolean canOwnInitializer(Symbol sym) {
3385 return
3386 (sym.kind & (VAR | TYP)) != 0 ||
3387 (sym.kind == MTH && (sym.flags() & BLOCK) != 0);
3388 }
3390 Warner noteWarner = new Warner();
3392 /**
3393 * Check that method arguments conform to its instantiation.
3394 **/
3395 public Type checkMethod(Type site,
3396 Symbol sym,
3397 ResultInfo resultInfo,
3398 Env<AttrContext> env,
3399 final List<JCExpression> argtrees,
3400 List<Type> argtypes,
3401 List<Type> typeargtypes) {
3402 // Test (5): if symbol is an instance method of a raw type, issue
3403 // an unchecked warning if its argument types change under erasure.
3404 if (allowGenerics &&
3405 (sym.flags() & STATIC) == 0 &&
3406 (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
3407 Type s = types.asOuterSuper(site, sym.owner);
3408 if (s != null && s.isRaw() &&
3409 !types.isSameTypes(sym.type.getParameterTypes(),
3410 sym.erasure(types).getParameterTypes())) {
3411 chk.warnUnchecked(env.tree.pos(),
3412 "unchecked.call.mbr.of.raw.type",
3413 sym, s);
3414 }
3415 }
3417 if (env.info.defaultSuperCallSite != null) {
3418 for (Type sup : types.interfaces(env.enclClass.type).prepend(types.supertype((env.enclClass.type)))) {
3419 if (!sup.tsym.isSubClass(sym.enclClass(), types) ||
3420 types.isSameType(sup, env.info.defaultSuperCallSite)) continue;
3421 List<MethodSymbol> icand_sup =
3422 types.interfaceCandidates(sup, (MethodSymbol)sym);
3423 if (icand_sup.nonEmpty() &&
3424 icand_sup.head != sym &&
3425 icand_sup.head.overrides(sym, icand_sup.head.enclClass(), types, true)) {
3426 log.error(env.tree.pos(), "illegal.default.super.call", env.info.defaultSuperCallSite,
3427 diags.fragment("overridden.default", sym, sup));
3428 break;
3429 }
3430 }
3431 env.info.defaultSuperCallSite = null;
3432 }
3434 // Compute the identifier's instantiated type.
3435 // For methods, we need to compute the instance type by
3436 // Resolve.instantiate from the symbol's type as well as
3437 // any type arguments and value arguments.
3438 noteWarner.clear();
3439 try {
3440 Type owntype = rs.checkMethod(
3441 env,
3442 site,
3443 sym,
3444 resultInfo,
3445 argtypes,
3446 typeargtypes,
3447 noteWarner);
3449 return chk.checkMethod(owntype, sym, env, argtrees, argtypes, env.info.lastResolveVarargs(),
3450 noteWarner.hasNonSilentLint(LintCategory.UNCHECKED));
3451 } catch (Infer.InferenceException ex) {
3452 //invalid target type - propagate exception outwards or report error
3453 //depending on the current check context
3454 resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic());
3455 return types.createErrorType(site);
3456 } catch (Resolve.InapplicableMethodException ex) {
3457 Assert.error(ex.getDiagnostic().getMessage(Locale.getDefault()));
3458 return null;
3459 }
3460 }
3462 public void visitLiteral(JCLiteral tree) {
3463 result = check(
3464 tree, litType(tree.typetag).constType(tree.value), VAL, resultInfo);
3465 }
3466 //where
3467 /** Return the type of a literal with given type tag.
3468 */
3469 Type litType(TypeTag tag) {
3470 return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()];
3471 }
3473 public void visitTypeIdent(JCPrimitiveTypeTree tree) {
3474 result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], TYP, resultInfo);
3475 }
3477 public void visitTypeArray(JCArrayTypeTree tree) {
3478 Type etype = attribType(tree.elemtype, env);
3479 Type type = new ArrayType(etype, syms.arrayClass);
3480 result = check(tree, type, TYP, resultInfo);
3481 }
3483 /** Visitor method for parameterized types.
3484 * Bound checking is left until later, since types are attributed
3485 * before supertype structure is completely known
3486 */
3487 public void visitTypeApply(JCTypeApply tree) {
3488 Type owntype = types.createErrorType(tree.type);
3490 // Attribute functor part of application and make sure it's a class.
3491 Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
3493 // Attribute type parameters
3494 List<Type> actuals = attribTypes(tree.arguments, env);
3496 if (clazztype.hasTag(CLASS)) {
3497 List<Type> formals = clazztype.tsym.type.getTypeArguments();
3498 if (actuals.isEmpty()) //diamond
3499 actuals = formals;
3501 if (actuals.length() == formals.length()) {
3502 List<Type> a = actuals;
3503 List<Type> f = formals;
3504 while (a.nonEmpty()) {
3505 a.head = a.head.withTypeVar(f.head);
3506 a = a.tail;
3507 f = f.tail;
3508 }
3509 // Compute the proper generic outer
3510 Type clazzOuter = clazztype.getEnclosingType();
3511 if (clazzOuter.hasTag(CLASS)) {
3512 Type site;
3513 JCExpression clazz = TreeInfo.typeIn(tree.clazz);
3514 if (clazz.hasTag(IDENT)) {
3515 site = env.enclClass.sym.type;
3516 } else if (clazz.hasTag(SELECT)) {
3517 site = ((JCFieldAccess) clazz).selected.type;
3518 } else throw new AssertionError(""+tree);
3519 if (clazzOuter.hasTag(CLASS) && site != clazzOuter) {
3520 if (site.hasTag(CLASS))
3521 site = types.asOuterSuper(site, clazzOuter.tsym);
3522 if (site == null)
3523 site = types.erasure(clazzOuter);
3524 clazzOuter = site;
3525 }
3526 }
3527 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym);
3528 } else {
3529 if (formals.length() != 0) {
3530 log.error(tree.pos(), "wrong.number.type.args",
3531 Integer.toString(formals.length()));
3532 } else {
3533 log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym);
3534 }
3535 owntype = types.createErrorType(tree.type);
3536 }
3537 }
3538 result = check(tree, owntype, TYP, resultInfo);
3539 }
3541 public void visitTypeUnion(JCTypeUnion tree) {
3542 ListBuffer<Type> multicatchTypes = ListBuffer.lb();
3543 ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
3544 for (JCExpression typeTree : tree.alternatives) {
3545 Type ctype = attribType(typeTree, env);
3546 ctype = chk.checkType(typeTree.pos(),
3547 chk.checkClassType(typeTree.pos(), ctype),
3548 syms.throwableType);
3549 if (!ctype.isErroneous()) {
3550 //check that alternatives of a union type are pairwise
3551 //unrelated w.r.t. subtyping
3552 if (chk.intersects(ctype, multicatchTypes.toList())) {
3553 for (Type t : multicatchTypes) {
3554 boolean sub = types.isSubtype(ctype, t);
3555 boolean sup = types.isSubtype(t, ctype);
3556 if (sub || sup) {
3557 //assume 'a' <: 'b'
3558 Type a = sub ? ctype : t;
3559 Type b = sub ? t : ctype;
3560 log.error(typeTree.pos(), "multicatch.types.must.be.disjoint", a, b);
3561 }
3562 }
3563 }
3564 multicatchTypes.append(ctype);
3565 if (all_multicatchTypes != null)
3566 all_multicatchTypes.append(ctype);
3567 } else {
3568 if (all_multicatchTypes == null) {
3569 all_multicatchTypes = ListBuffer.lb();
3570 all_multicatchTypes.appendList(multicatchTypes);
3571 }
3572 all_multicatchTypes.append(ctype);
3573 }
3574 }
3575 Type t = check(tree, types.lub(multicatchTypes.toList()), TYP, resultInfo);
3576 if (t.hasTag(CLASS)) {
3577 List<Type> alternatives =
3578 ((all_multicatchTypes == null) ? multicatchTypes : all_multicatchTypes).toList();
3579 t = new UnionClassType((ClassType) t, alternatives);
3580 }
3581 tree.type = result = t;
3582 }
3584 public void visitTypeIntersection(JCTypeIntersection tree) {
3585 attribTypes(tree.bounds, env);
3586 tree.type = result = checkIntersection(tree, tree.bounds);
3587 }
3589 public void visitTypeParameter(JCTypeParameter tree) {
3590 TypeVar typeVar = (TypeVar)tree.type;
3591 if (!typeVar.bound.isErroneous()) {
3592 //fixup type-parameter bound computed in 'attribTypeVariables'
3593 typeVar.bound = checkIntersection(tree, tree.bounds);
3594 }
3595 }
3597 Type checkIntersection(JCTree tree, List<JCExpression> bounds) {
3598 Set<Type> boundSet = new HashSet<Type>();
3599 if (bounds.nonEmpty()) {
3600 // accept class or interface or typevar as first bound.
3601 bounds.head.type = checkBase(bounds.head.type, bounds.head, env, false, false, false);
3602 boundSet.add(types.erasure(bounds.head.type));
3603 if (bounds.head.type.isErroneous()) {
3604 return bounds.head.type;
3605 }
3606 else if (bounds.head.type.hasTag(TYPEVAR)) {
3607 // if first bound was a typevar, do not accept further bounds.
3608 if (bounds.tail.nonEmpty()) {
3609 log.error(bounds.tail.head.pos(),
3610 "type.var.may.not.be.followed.by.other.bounds");
3611 return bounds.head.type;
3612 }
3613 } else {
3614 // if first bound was a class or interface, accept only interfaces
3615 // as further bounds.
3616 for (JCExpression bound : bounds.tail) {
3617 bound.type = checkBase(bound.type, bound, env, false, true, false);
3618 if (bound.type.isErroneous()) {
3619 bounds = List.of(bound);
3620 }
3621 else if (bound.type.hasTag(CLASS)) {
3622 chk.checkNotRepeated(bound.pos(), types.erasure(bound.type), boundSet);
3623 }
3624 }
3625 }
3626 }
3628 if (bounds.length() == 0) {
3629 return syms.objectType;
3630 } else if (bounds.length() == 1) {
3631 return bounds.head.type;
3632 } else {
3633 Type owntype = types.makeCompoundType(TreeInfo.types(bounds));
3634 if (tree.hasTag(TYPEINTERSECTION)) {
3635 ((IntersectionClassType)owntype).intersectionKind =
3636 IntersectionClassType.IntersectionKind.EXPLICIT;
3637 }
3638 // ... the variable's bound is a class type flagged COMPOUND
3639 // (see comment for TypeVar.bound).
3640 // In this case, generate a class tree that represents the
3641 // bound class, ...
3642 JCExpression extending;
3643 List<JCExpression> implementing;
3644 if (!bounds.head.type.isInterface()) {
3645 extending = bounds.head;
3646 implementing = bounds.tail;
3647 } else {
3648 extending = null;
3649 implementing = bounds;
3650 }
3651 JCClassDecl cd = make.at(tree).ClassDef(
3652 make.Modifiers(PUBLIC | ABSTRACT),
3653 names.empty, List.<JCTypeParameter>nil(),
3654 extending, implementing, List.<JCTree>nil());
3656 ClassSymbol c = (ClassSymbol)owntype.tsym;
3657 Assert.check((c.flags() & COMPOUND) != 0);
3658 cd.sym = c;
3659 c.sourcefile = env.toplevel.sourcefile;
3661 // ... and attribute the bound class
3662 c.flags_field |= UNATTRIBUTED;
3663 Env<AttrContext> cenv = enter.classEnv(cd, env);
3664 enter.typeEnvs.put(c, cenv);
3665 attribClass(c);
3666 return owntype;
3667 }
3668 }
3670 public void visitWildcard(JCWildcard tree) {
3671 //- System.err.println("visitWildcard("+tree+");");//DEBUG
3672 Type type = (tree.kind.kind == BoundKind.UNBOUND)
3673 ? syms.objectType
3674 : attribType(tree.inner, env);
3675 result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
3676 tree.kind.kind,
3677 syms.boundClass),
3678 TYP, resultInfo);
3679 }
3681 public void visitAnnotation(JCAnnotation tree) {
3682 log.error(tree.pos(), "annotation.not.valid.for.type", pt());
3683 result = tree.type = syms.errType;
3684 }
3686 public void visitErroneous(JCErroneous tree) {
3687 if (tree.errs != null)
3688 for (JCTree err : tree.errs)
3689 attribTree(err, env, new ResultInfo(ERR, pt()));
3690 result = tree.type = syms.errType;
3691 }
3693 /** Default visitor method for all other trees.
3694 */
3695 public void visitTree(JCTree tree) {
3696 throw new AssertionError();
3697 }
3699 /**
3700 * Attribute an env for either a top level tree or class declaration.
3701 */
3702 public void attrib(Env<AttrContext> env) {
3703 if (env.tree.hasTag(TOPLEVEL))
3704 attribTopLevel(env);
3705 else
3706 attribClass(env.tree.pos(), env.enclClass.sym);
3707 }
3709 /**
3710 * Attribute a top level tree. These trees are encountered when the
3711 * package declaration has annotations.
3712 */
3713 public void attribTopLevel(Env<AttrContext> env) {
3714 JCCompilationUnit toplevel = env.toplevel;
3715 try {
3716 annotate.flush();
3717 chk.validateAnnotations(toplevel.packageAnnotations, toplevel.packge);
3718 } catch (CompletionFailure ex) {
3719 chk.completionError(toplevel.pos(), ex);
3720 }
3721 }
3723 /** Main method: attribute class definition associated with given class symbol.
3724 * reporting completion failures at the given position.
3725 * @param pos The source position at which completion errors are to be
3726 * reported.
3727 * @param c The class symbol whose definition will be attributed.
3728 */
3729 public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
3730 try {
3731 annotate.flush();
3732 attribClass(c);
3733 } catch (CompletionFailure ex) {
3734 chk.completionError(pos, ex);
3735 }
3736 }
3738 /** Attribute class definition associated with given class symbol.
3739 * @param c The class symbol whose definition will be attributed.
3740 */
3741 void attribClass(ClassSymbol c) throws CompletionFailure {
3742 if (c.type.hasTag(ERROR)) return;
3744 // Check for cycles in the inheritance graph, which can arise from
3745 // ill-formed class files.
3746 chk.checkNonCyclic(null, c.type);
3748 Type st = types.supertype(c.type);
3749 if ((c.flags_field & Flags.COMPOUND) == 0) {
3750 // First, attribute superclass.
3751 if (st.hasTag(CLASS))
3752 attribClass((ClassSymbol)st.tsym);
3754 // Next attribute owner, if it is a class.
3755 if (c.owner.kind == TYP && c.owner.type.hasTag(CLASS))
3756 attribClass((ClassSymbol)c.owner);
3757 }
3759 // The previous operations might have attributed the current class
3760 // if there was a cycle. So we test first whether the class is still
3761 // UNATTRIBUTED.
3762 if ((c.flags_field & UNATTRIBUTED) != 0) {
3763 c.flags_field &= ~UNATTRIBUTED;
3765 // Get environment current at the point of class definition.
3766 Env<AttrContext> env = enter.typeEnvs.get(c);
3768 // The info.lint field in the envs stored in enter.typeEnvs is deliberately uninitialized,
3769 // because the annotations were not available at the time the env was created. Therefore,
3770 // we look up the environment chain for the first enclosing environment for which the
3771 // lint value is set. Typically, this is the parent env, but might be further if there
3772 // are any envs created as a result of TypeParameter nodes.
3773 Env<AttrContext> lintEnv = env;
3774 while (lintEnv.info.lint == null)
3775 lintEnv = lintEnv.next;
3777 // Having found the enclosing lint value, we can initialize the lint value for this class
3778 env.info.lint = lintEnv.info.lint.augment(c.annotations, c.flags());
3780 Lint prevLint = chk.setLint(env.info.lint);
3781 JavaFileObject prev = log.useSource(c.sourcefile);
3782 ResultInfo prevReturnRes = env.info.returnResult;
3784 try {
3785 env.info.returnResult = null;
3786 // java.lang.Enum may not be subclassed by a non-enum
3787 if (st.tsym == syms.enumSym &&
3788 ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
3789 log.error(env.tree.pos(), "enum.no.subclassing");
3791 // Enums may not be extended by source-level classes
3792 if (st.tsym != null &&
3793 ((st.tsym.flags_field & Flags.ENUM) != 0) &&
3794 ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0) &&
3795 !target.compilerBootstrap(c)) {
3796 log.error(env.tree.pos(), "enum.types.not.extensible");
3797 }
3798 attribClassBody(env, c);
3800 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
3801 } finally {
3802 env.info.returnResult = prevReturnRes;
3803 log.useSource(prev);
3804 chk.setLint(prevLint);
3805 }
3807 }
3808 }
3810 public void visitImport(JCImport tree) {
3811 // nothing to do
3812 }
3814 /** Finish the attribution of a class. */
3815 private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
3816 JCClassDecl tree = (JCClassDecl)env.tree;
3817 Assert.check(c == tree.sym);
3819 // Validate annotations
3820 chk.validateAnnotations(tree.mods.annotations, c);
3822 // Validate type parameters, supertype and interfaces.
3823 attribStats(tree.typarams, env);
3824 if (!c.isAnonymous()) {
3825 //already checked if anonymous
3826 chk.validate(tree.typarams, env);
3827 chk.validate(tree.extending, env);
3828 chk.validate(tree.implementing, env);
3829 }
3831 // If this is a non-abstract class, check that it has no abstract
3832 // methods or unimplemented methods of an implemented interface.
3833 if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
3834 if (!relax)
3835 chk.checkAllDefined(tree.pos(), c);
3836 }
3838 if ((c.flags() & ANNOTATION) != 0) {
3839 if (tree.implementing.nonEmpty())
3840 log.error(tree.implementing.head.pos(),
3841 "cant.extend.intf.annotation");
3842 if (tree.typarams.nonEmpty())
3843 log.error(tree.typarams.head.pos(),
3844 "intf.annotation.cant.have.type.params");
3846 // If this annotation has a @ContainedBy, validate
3847 Attribute.Compound containedBy = c.attribute(syms.containedByType.tsym);
3848 if (containedBy != null) {
3849 // get diagnositc position for error reporting
3850 DiagnosticPosition cbPos = getDiagnosticPosition(tree, containedBy.type);
3851 Assert.checkNonNull(cbPos);
3853 chk.validateContainedBy(c, containedBy, cbPos);
3854 }
3856 // If this annotation has a @ContainerFor, validate
3857 Attribute.Compound containerFor = c.attribute(syms.containerForType.tsym);
3858 if (containerFor != null) {
3859 // get diagnositc position for error reporting
3860 DiagnosticPosition cfPos = getDiagnosticPosition(tree, containerFor.type);
3861 Assert.checkNonNull(cfPos);
3863 chk.validateContainerFor(c, containerFor, cfPos);
3864 }
3865 } else {
3866 // Check that all extended classes and interfaces
3867 // are compatible (i.e. no two define methods with same arguments
3868 // yet different return types). (JLS 8.4.6.3)
3869 chk.checkCompatibleSupertypes(tree.pos(), c.type);
3870 if (allowDefaultMethods) {
3871 chk.checkDefaultMethodClashes(tree.pos(), c.type);
3872 }
3873 }
3875 // Check that class does not import the same parameterized interface
3876 // with two different argument lists.
3877 chk.checkClassBounds(tree.pos(), c.type);
3879 tree.type = c.type;
3881 for (List<JCTypeParameter> l = tree.typarams;
3882 l.nonEmpty(); l = l.tail) {
3883 Assert.checkNonNull(env.info.scope.lookup(l.head.name).scope);
3884 }
3886 // Check that a generic class doesn't extend Throwable
3887 if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
3888 log.error(tree.extending.pos(), "generic.throwable");
3890 // Check that all methods which implement some
3891 // method conform to the method they implement.
3892 chk.checkImplementations(tree);
3894 //check that a resource implementing AutoCloseable cannot throw InterruptedException
3895 checkAutoCloseable(tree.pos(), env, c.type);
3897 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
3898 // Attribute declaration
3899 attribStat(l.head, env);
3900 // Check that declarations in inner classes are not static (JLS 8.1.2)
3901 // Make an exception for static constants.
3902 if (c.owner.kind != PCK &&
3903 ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
3904 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
3905 Symbol sym = null;
3906 if (l.head.hasTag(VARDEF)) sym = ((JCVariableDecl) l.head).sym;
3907 if (sym == null ||
3908 sym.kind != VAR ||
3909 ((VarSymbol) sym).getConstValue() == null)
3910 log.error(l.head.pos(), "icls.cant.have.static.decl", c);
3911 }
3912 }
3914 // Check for cycles among non-initial constructors.
3915 chk.checkCyclicConstructors(tree);
3917 // Check for cycles among annotation elements.
3918 chk.checkNonCyclicElements(tree);
3920 // Check for proper use of serialVersionUID
3921 if (env.info.lint.isEnabled(LintCategory.SERIAL) &&
3922 isSerializable(c) &&
3923 (c.flags() & Flags.ENUM) == 0 &&
3924 (c.flags() & ABSTRACT) == 0) {
3925 checkSerialVersionUID(tree, c);
3926 }
3927 }
3928 // where
3929 /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
3930 private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
3931 for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
3932 if (types.isSameType(al.head.annotationType.type, t))
3933 return al.head.pos();
3934 }
3936 return null;
3937 }
3939 /** check if a class is a subtype of Serializable, if that is available. */
3940 private boolean isSerializable(ClassSymbol c) {
3941 try {
3942 syms.serializableType.complete();
3943 }
3944 catch (CompletionFailure e) {
3945 return false;
3946 }
3947 return types.isSubtype(c.type, syms.serializableType);
3948 }
3950 /** Check that an appropriate serialVersionUID member is defined. */
3951 private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
3953 // check for presence of serialVersionUID
3954 Scope.Entry e = c.members().lookup(names.serialVersionUID);
3955 while (e.scope != null && e.sym.kind != VAR) e = e.next();
3956 if (e.scope == null) {
3957 log.warning(LintCategory.SERIAL,
3958 tree.pos(), "missing.SVUID", c);
3959 return;
3960 }
3962 // check that it is static final
3963 VarSymbol svuid = (VarSymbol)e.sym;
3964 if ((svuid.flags() & (STATIC | FINAL)) !=
3965 (STATIC | FINAL))
3966 log.warning(LintCategory.SERIAL,
3967 TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c);
3969 // check that it is long
3970 else if (!svuid.type.hasTag(LONG))
3971 log.warning(LintCategory.SERIAL,
3972 TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c);
3974 // check constant
3975 else if (svuid.getConstValue() == null)
3976 log.warning(LintCategory.SERIAL,
3977 TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c);
3978 }
3980 private Type capture(Type type) {
3981 return types.capture(type);
3982 }
3984 // <editor-fold desc="post-attribution visitor">
3986 /**
3987 * Handle missing types/symbols in an AST. This routine is useful when
3988 * the compiler has encountered some errors (which might have ended up
3989 * terminating attribution abruptly); if the compiler is used in fail-over
3990 * mode (e.g. by an IDE) and the AST contains semantic errors, this routine
3991 * prevents NPE to be progagated during subsequent compilation steps.
3992 */
3993 public void postAttr(JCTree tree) {
3994 new PostAttrAnalyzer().scan(tree);
3995 }
3997 class PostAttrAnalyzer extends TreeScanner {
3999 private void initTypeIfNeeded(JCTree that) {
4000 if (that.type == null) {
4001 that.type = syms.unknownType;
4002 }
4003 }
4005 @Override
4006 public void scan(JCTree tree) {
4007 if (tree == null) return;
4008 if (tree instanceof JCExpression) {
4009 initTypeIfNeeded(tree);
4010 }
4011 super.scan(tree);
4012 }
4014 @Override
4015 public void visitIdent(JCIdent that) {
4016 if (that.sym == null) {
4017 that.sym = syms.unknownSymbol;
4018 }
4019 }
4021 @Override
4022 public void visitSelect(JCFieldAccess that) {
4023 if (that.sym == null) {
4024 that.sym = syms.unknownSymbol;
4025 }
4026 super.visitSelect(that);
4027 }
4029 @Override
4030 public void visitClassDef(JCClassDecl that) {
4031 initTypeIfNeeded(that);
4032 if (that.sym == null) {
4033 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol);
4034 }
4035 super.visitClassDef(that);
4036 }
4038 @Override
4039 public void visitMethodDef(JCMethodDecl that) {
4040 initTypeIfNeeded(that);
4041 if (that.sym == null) {
4042 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol);
4043 }
4044 super.visitMethodDef(that);
4045 }
4047 @Override
4048 public void visitVarDef(JCVariableDecl that) {
4049 initTypeIfNeeded(that);
4050 if (that.sym == null) {
4051 that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol);
4052 that.sym.adr = 0;
4053 }
4054 super.visitVarDef(that);
4055 }
4057 @Override
4058 public void visitNewClass(JCNewClass that) {
4059 if (that.constructor == null) {
4060 that.constructor = new MethodSymbol(0, names.init, syms.unknownType, syms.noSymbol);
4061 }
4062 if (that.constructorType == null) {
4063 that.constructorType = syms.unknownType;
4064 }
4065 super.visitNewClass(that);
4066 }
4068 @Override
4069 public void visitAssignop(JCAssignOp that) {
4070 if (that.operator == null)
4071 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
4072 super.visitAssignop(that);
4073 }
4075 @Override
4076 public void visitBinary(JCBinary that) {
4077 if (that.operator == null)
4078 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
4079 super.visitBinary(that);
4080 }
4082 @Override
4083 public void visitUnary(JCUnary that) {
4084 if (that.operator == null)
4085 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
4086 super.visitUnary(that);
4087 }
4089 @Override
4090 public void visitReference(JCMemberReference that) {
4091 super.visitReference(that);
4092 if (that.sym == null) {
4093 that.sym = new MethodSymbol(0, names.empty, syms.unknownType, syms.noSymbol);
4094 }
4095 }
4096 }
4097 // </editor-fold>
4098 }