Thu, 21 Feb 2013 17:49:56 -0800
Merge
1 /*
2 * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
26 package com.sun.tools.javac.comp;
28 import java.util.*;
30 import javax.lang.model.element.ElementKind;
31 import javax.lang.model.type.TypeKind;
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.FreeTypeListener;
47 import com.sun.tools.javac.jvm.*;
48 import com.sun.tools.javac.tree.*;
49 import com.sun.tools.javac.tree.JCTree.*;
50 import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*;
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));
248 check(tree, inferenceContext.asInstType(found), 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 memberEnter.typeAnnotate(initializer, env, env.info.enclVar);
770 annotate.flush();
771 Type itype = attribExpr(initializer, env, type);
772 if (itype.constValue() != null)
773 return coerce(itype, type).constValue();
774 else
775 return null;
776 } finally {
777 env.info.lint = prevLint;
778 log.useSource(prevSource);
779 }
780 }
782 /** Attribute type reference in an `extends' or `implements' clause.
783 * Supertypes of anonymous inner classes are usually already attributed.
784 *
785 * @param tree The tree making up the type reference.
786 * @param env The environment current at the reference.
787 * @param classExpected true if only a class is expected here.
788 * @param interfaceExpected true if only an interface is expected here.
789 */
790 Type attribBase(JCTree tree,
791 Env<AttrContext> env,
792 boolean classExpected,
793 boolean interfaceExpected,
794 boolean checkExtensible) {
795 Type t = tree.type != null ?
796 tree.type :
797 attribType(tree, env);
798 return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible);
799 }
800 Type checkBase(Type t,
801 JCTree tree,
802 Env<AttrContext> env,
803 boolean classExpected,
804 boolean interfaceExpected,
805 boolean checkExtensible) {
806 if (t.isErroneous())
807 return t;
808 if (t.hasTag(TYPEVAR) && !classExpected && !interfaceExpected) {
809 // check that type variable is already visible
810 if (t.getUpperBound() == null) {
811 log.error(tree.pos(), "illegal.forward.ref");
812 return types.createErrorType(t);
813 }
814 } else {
815 t = chk.checkClassType(tree.pos(), t, checkExtensible|!allowGenerics);
816 }
817 if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) {
818 log.error(tree.pos(), "intf.expected.here");
819 // return errType is necessary since otherwise there might
820 // be undetected cycles which cause attribution to loop
821 return types.createErrorType(t);
822 } else if (checkExtensible &&
823 classExpected &&
824 (t.tsym.flags() & INTERFACE) != 0) {
825 log.error(tree.pos(), "no.intf.expected.here");
826 return types.createErrorType(t);
827 }
828 if (checkExtensible &&
829 ((t.tsym.flags() & FINAL) != 0)) {
830 log.error(tree.pos(),
831 "cant.inherit.from.final", t.tsym);
832 }
833 chk.checkNonCyclic(tree.pos(), t);
834 return t;
835 }
837 Type attribIdentAsEnumType(Env<AttrContext> env, JCIdent id) {
838 Assert.check((env.enclClass.sym.flags() & ENUM) != 0);
839 id.type = env.info.scope.owner.type;
840 id.sym = env.info.scope.owner;
841 return id.type;
842 }
844 public void visitClassDef(JCClassDecl tree) {
845 // Local classes have not been entered yet, so we need to do it now:
846 if ((env.info.scope.owner.kind & (VAR | MTH)) != 0)
847 enter.classEnter(tree, env);
849 ClassSymbol c = tree.sym;
850 if (c == null) {
851 // exit in case something drastic went wrong during enter.
852 result = null;
853 } else {
854 // make sure class has been completed:
855 c.complete();
857 // If this class appears as an anonymous class
858 // in a superclass constructor call where
859 // no explicit outer instance is given,
860 // disable implicit outer instance from being passed.
861 // (This would be an illegal access to "this before super").
862 if (env.info.isSelfCall &&
863 env.tree.hasTag(NEWCLASS) &&
864 ((JCNewClass) env.tree).encl == null)
865 {
866 c.flags_field |= NOOUTERTHIS;
867 }
868 attribClass(tree.pos(), c);
869 result = tree.type = c.type;
870 }
871 }
873 public void visitMethodDef(JCMethodDecl tree) {
874 MethodSymbol m = tree.sym;
875 boolean isDefaultMethod = (m.flags() & DEFAULT) != 0;
877 Lint lint = env.info.lint.augment(m.annotations, m.flags());
878 Lint prevLint = chk.setLint(lint);
879 MethodSymbol prevMethod = chk.setMethod(m);
880 try {
881 deferredLintHandler.flush(tree.pos());
882 chk.checkDeprecatedAnnotation(tree.pos(), m);
885 // Create a new environment with local scope
886 // for attributing the method.
887 Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
888 localEnv.info.lint = lint;
890 attribStats(tree.typarams, localEnv);
892 // If we override any other methods, check that we do so properly.
893 // JLS ???
894 if (m.isStatic()) {
895 chk.checkHideClashes(tree.pos(), env.enclClass.type, m);
896 } else {
897 chk.checkOverrideClashes(tree.pos(), env.enclClass.type, m);
898 }
899 chk.checkOverride(tree, m);
901 if (isDefaultMethod && types.overridesObjectMethod(m.enclClass(), m)) {
902 log.error(tree, "default.overrides.object.member", m.name, Kinds.kindName(m.location()), m.location());
903 }
905 // Enter all type parameters into the local method scope.
906 for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
907 localEnv.info.scope.enterIfAbsent(l.head.type.tsym);
909 ClassSymbol owner = env.enclClass.sym;
910 if ((owner.flags() & ANNOTATION) != 0 &&
911 tree.params.nonEmpty())
912 log.error(tree.params.head.pos(),
913 "intf.annotation.members.cant.have.params");
915 // Attribute all value parameters.
916 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
917 attribStat(l.head, localEnv);
918 }
920 chk.checkVarargsMethodDecl(localEnv, tree);
922 // Check that type parameters are well-formed.
923 chk.validate(tree.typarams, localEnv);
925 // Check that result type is well-formed.
926 chk.validate(tree.restype, localEnv);
928 // Check that receiver type is well-formed.
929 if (tree.recvparam != null) {
930 // Use a new environment to check the receiver parameter.
931 // Otherwise I get "might not have been initialized" errors.
932 // Is there a better way?
933 Env<AttrContext> newEnv = memberEnter.methodEnv(tree, env);
934 attribType(tree.recvparam, newEnv);
935 chk.validate(tree.recvparam, newEnv);
936 if (!(tree.recvparam.type == m.owner.type || types.isSameType(tree.recvparam.type, m.owner.type))) {
937 // The == covers the common non-generic case, but for generic classes we need isSameType;
938 // note that equals didn't work.
939 log.error(tree.recvparam.pos(), "incorrect.receiver.type");
940 }
941 }
943 // annotation method checks
944 if ((owner.flags() & ANNOTATION) != 0) {
945 // annotation method cannot have throws clause
946 if (tree.thrown.nonEmpty()) {
947 log.error(tree.thrown.head.pos(),
948 "throws.not.allowed.in.intf.annotation");
949 }
950 // annotation method cannot declare type-parameters
951 if (tree.typarams.nonEmpty()) {
952 log.error(tree.typarams.head.pos(),
953 "intf.annotation.members.cant.have.type.params");
954 }
955 // validate annotation method's return type (could be an annotation type)
956 chk.validateAnnotationType(tree.restype);
957 // ensure that annotation method does not clash with members of Object/Annotation
958 chk.validateAnnotationMethod(tree.pos(), m);
960 if (tree.defaultValue != null) {
961 // if default value is an annotation, check it is a well-formed
962 // annotation value (e.g. no duplicate values, no missing values, etc.)
963 chk.validateAnnotationTree(tree.defaultValue);
964 }
965 }
967 for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
968 chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
970 if (tree.body == null) {
971 // Empty bodies are only allowed for
972 // abstract, native, or interface methods, or for methods
973 // in a retrofit signature class.
974 if (isDefaultMethod || (tree.sym.flags() & (ABSTRACT | NATIVE)) == 0 &&
975 !relax)
976 log.error(tree.pos(), "missing.meth.body.or.decl.abstract");
977 if (tree.defaultValue != null) {
978 if ((owner.flags() & ANNOTATION) == 0)
979 log.error(tree.pos(),
980 "default.allowed.in.intf.annotation.member");
981 }
982 } else if ((tree.sym.flags() & ABSTRACT) != 0 && !isDefaultMethod) {
983 if ((owner.flags() & INTERFACE) != 0) {
984 log.error(tree.body.pos(), "intf.meth.cant.have.body");
985 } else {
986 log.error(tree.pos(), "abstract.meth.cant.have.body");
987 }
988 } else if ((tree.mods.flags & NATIVE) != 0) {
989 log.error(tree.pos(), "native.meth.cant.have.body");
990 } else {
991 // Add an implicit super() call unless an explicit call to
992 // super(...) or this(...) is given
993 // or we are compiling class java.lang.Object.
994 if (tree.name == names.init && owner.type != syms.objectType) {
995 JCBlock body = tree.body;
996 if (body.stats.isEmpty() ||
997 !TreeInfo.isSelfCall(body.stats.head)) {
998 body.stats = body.stats.
999 prepend(memberEnter.SuperCall(make.at(body.pos),
1000 List.<Type>nil(),
1001 List.<JCVariableDecl>nil(),
1002 false));
1003 } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
1004 (tree.mods.flags & GENERATEDCONSTR) == 0 &&
1005 TreeInfo.isSuperCall(body.stats.head)) {
1006 // enum constructors are not allowed to call super
1007 // directly, so make sure there aren't any super calls
1008 // in enum constructors, except in the compiler
1009 // generated one.
1010 log.error(tree.body.stats.head.pos(),
1011 "call.to.super.not.allowed.in.enum.ctor",
1012 env.enclClass.sym);
1013 }
1014 }
1016 // Attribute all type annotations in the body
1017 memberEnter.typeAnnotate(tree.body, localEnv, m);
1018 annotate.flush();
1020 // Attribute method body.
1021 attribStat(tree.body, localEnv);
1022 }
1024 localEnv.info.scope.leave();
1025 result = tree.type = m.type;
1026 chk.validateAnnotations(tree.mods.annotations, m);
1027 }
1028 finally {
1029 chk.setLint(prevLint);
1030 chk.setMethod(prevMethod);
1031 }
1032 }
1034 public void visitVarDef(JCVariableDecl tree) {
1035 // Local variables have not been entered yet, so we need to do it now:
1036 if (env.info.scope.owner.kind == MTH) {
1037 if (tree.sym != null) {
1038 // parameters have already been entered
1039 env.info.scope.enter(tree.sym);
1040 } else {
1041 memberEnter.memberEnter(tree, env);
1042 annotate.flush();
1043 }
1044 } else {
1045 if (tree.init != null) {
1046 // Field initializer expression need to be entered.
1047 memberEnter.typeAnnotate(tree.init, env, tree.sym);
1048 annotate.flush();
1049 }
1050 }
1052 VarSymbol v = tree.sym;
1053 Lint lint = env.info.lint.augment(v.annotations, v.flags());
1054 Lint prevLint = chk.setLint(lint);
1056 // Check that the variable's declared type is well-formed.
1057 chk.validate(tree.vartype, env);
1058 deferredLintHandler.flush(tree.pos());
1060 try {
1061 chk.checkDeprecatedAnnotation(tree.pos(), v);
1063 if (tree.init != null) {
1064 if ((v.flags_field & FINAL) != 0 &&
1065 !tree.init.hasTag(NEWCLASS) &&
1066 !tree.init.hasTag(LAMBDA) &&
1067 !tree.init.hasTag(REFERENCE)) {
1068 // In this case, `v' is final. Ensure that it's initializer is
1069 // evaluated.
1070 v.getConstValue(); // ensure initializer is evaluated
1071 } else {
1072 // Attribute initializer in a new environment
1073 // with the declared variable as owner.
1074 // Check that initializer conforms to variable's declared type.
1075 Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
1076 initEnv.info.lint = lint;
1077 // In order to catch self-references, we set the variable's
1078 // declaration position to maximal possible value, effectively
1079 // marking the variable as undefined.
1080 initEnv.info.enclVar = v;
1081 attribExpr(tree.init, initEnv, v.type);
1082 }
1083 }
1084 result = tree.type = v.type;
1085 chk.validateAnnotations(tree.mods.annotations, v);
1086 }
1087 finally {
1088 chk.setLint(prevLint);
1089 }
1090 }
1092 public void visitSkip(JCSkip tree) {
1093 result = null;
1094 }
1096 public void visitBlock(JCBlock tree) {
1097 if (env.info.scope.owner.kind == TYP) {
1098 // Block is a static or instance initializer;
1099 // let the owner of the environment be a freshly
1100 // created BLOCK-method.
1101 Env<AttrContext> localEnv =
1102 env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
1103 localEnv.info.scope.owner =
1104 new MethodSymbol(tree.flags | BLOCK |
1105 env.info.scope.owner.flags() & STRICTFP, names.empty, null,
1106 env.info.scope.owner);
1107 if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
1109 // Attribute all type annotations in the block
1110 memberEnter.typeAnnotate(tree, localEnv, localEnv.info.scope.owner);
1111 annotate.flush();
1113 attribStats(tree.stats, localEnv);
1114 } else {
1115 // Create a new local environment with a local scope.
1116 Env<AttrContext> localEnv =
1117 env.dup(tree, env.info.dup(env.info.scope.dup()));
1118 try {
1119 attribStats(tree.stats, localEnv);
1120 } finally {
1121 localEnv.info.scope.leave();
1122 }
1123 }
1124 result = null;
1125 }
1127 public void visitDoLoop(JCDoWhileLoop tree) {
1128 attribStat(tree.body, env.dup(tree));
1129 attribExpr(tree.cond, env, syms.booleanType);
1130 result = null;
1131 }
1133 public void visitWhileLoop(JCWhileLoop tree) {
1134 attribExpr(tree.cond, env, syms.booleanType);
1135 attribStat(tree.body, env.dup(tree));
1136 result = null;
1137 }
1139 public void visitForLoop(JCForLoop tree) {
1140 Env<AttrContext> loopEnv =
1141 env.dup(env.tree, env.info.dup(env.info.scope.dup()));
1142 try {
1143 attribStats(tree.init, loopEnv);
1144 if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType);
1145 loopEnv.tree = tree; // before, we were not in loop!
1146 attribStats(tree.step, loopEnv);
1147 attribStat(tree.body, loopEnv);
1148 result = null;
1149 }
1150 finally {
1151 loopEnv.info.scope.leave();
1152 }
1153 }
1155 public void visitForeachLoop(JCEnhancedForLoop tree) {
1156 Env<AttrContext> loopEnv =
1157 env.dup(env.tree, env.info.dup(env.info.scope.dup()));
1158 try {
1159 attribStat(tree.var, loopEnv);
1160 Type exprType = types.upperBound(attribExpr(tree.expr, loopEnv));
1161 chk.checkNonVoid(tree.pos(), exprType);
1162 Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
1163 if (elemtype == null) {
1164 // or perhaps expr implements Iterable<T>?
1165 Type base = types.asSuper(exprType, syms.iterableType.tsym);
1166 if (base == null) {
1167 log.error(tree.expr.pos(),
1168 "foreach.not.applicable.to.type",
1169 exprType,
1170 diags.fragment("type.req.array.or.iterable"));
1171 elemtype = types.createErrorType(exprType);
1172 } else {
1173 List<Type> iterableParams = base.allparams();
1174 elemtype = iterableParams.isEmpty()
1175 ? syms.objectType
1176 : types.upperBound(iterableParams.head);
1177 }
1178 }
1179 chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
1180 loopEnv.tree = tree; // before, we were not in loop!
1181 attribStat(tree.body, loopEnv);
1182 result = null;
1183 }
1184 finally {
1185 loopEnv.info.scope.leave();
1186 }
1187 }
1189 public void visitLabelled(JCLabeledStatement tree) {
1190 // Check that label is not used in an enclosing statement
1191 Env<AttrContext> env1 = env;
1192 while (env1 != null && !env1.tree.hasTag(CLASSDEF)) {
1193 if (env1.tree.hasTag(LABELLED) &&
1194 ((JCLabeledStatement) env1.tree).label == tree.label) {
1195 log.error(tree.pos(), "label.already.in.use",
1196 tree.label);
1197 break;
1198 }
1199 env1 = env1.next;
1200 }
1202 attribStat(tree.body, env.dup(tree));
1203 result = null;
1204 }
1206 public void visitSwitch(JCSwitch tree) {
1207 Type seltype = attribExpr(tree.selector, env);
1209 Env<AttrContext> switchEnv =
1210 env.dup(tree, env.info.dup(env.info.scope.dup()));
1212 try {
1214 boolean enumSwitch =
1215 allowEnums &&
1216 (seltype.tsym.flags() & Flags.ENUM) != 0;
1217 boolean stringSwitch = false;
1218 if (types.isSameType(seltype, syms.stringType)) {
1219 if (allowStringsInSwitch) {
1220 stringSwitch = true;
1221 } else {
1222 log.error(tree.selector.pos(), "string.switch.not.supported.in.source", sourceName);
1223 }
1224 }
1225 if (!enumSwitch && !stringSwitch)
1226 seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType);
1228 // Attribute all cases and
1229 // check that there are no duplicate case labels or default clauses.
1230 Set<Object> labels = new HashSet<Object>(); // The set of case labels.
1231 boolean hasDefault = false; // Is there a default label?
1232 for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
1233 JCCase c = l.head;
1234 Env<AttrContext> caseEnv =
1235 switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup()));
1236 try {
1237 if (c.pat != null) {
1238 if (enumSwitch) {
1239 Symbol sym = enumConstant(c.pat, seltype);
1240 if (sym == null) {
1241 log.error(c.pat.pos(), "enum.label.must.be.unqualified.enum");
1242 } else if (!labels.add(sym)) {
1243 log.error(c.pos(), "duplicate.case.label");
1244 }
1245 } else {
1246 Type pattype = attribExpr(c.pat, switchEnv, seltype);
1247 if (!pattype.hasTag(ERROR)) {
1248 if (pattype.constValue() == null) {
1249 log.error(c.pat.pos(),
1250 (stringSwitch ? "string.const.req" : "const.expr.req"));
1251 } else if (labels.contains(pattype.constValue())) {
1252 log.error(c.pos(), "duplicate.case.label");
1253 } else {
1254 labels.add(pattype.constValue());
1255 }
1256 }
1257 }
1258 } else if (hasDefault) {
1259 log.error(c.pos(), "duplicate.default.label");
1260 } else {
1261 hasDefault = true;
1262 }
1263 attribStats(c.stats, caseEnv);
1264 } finally {
1265 caseEnv.info.scope.leave();
1266 addVars(c.stats, switchEnv.info.scope);
1267 }
1268 }
1270 result = null;
1271 }
1272 finally {
1273 switchEnv.info.scope.leave();
1274 }
1275 }
1276 // where
1277 /** Add any variables defined in stats to the switch scope. */
1278 private static void addVars(List<JCStatement> stats, Scope switchScope) {
1279 for (;stats.nonEmpty(); stats = stats.tail) {
1280 JCTree stat = stats.head;
1281 if (stat.hasTag(VARDEF))
1282 switchScope.enter(((JCVariableDecl) stat).sym);
1283 }
1284 }
1285 // where
1286 /** Return the selected enumeration constant symbol, or null. */
1287 private Symbol enumConstant(JCTree tree, Type enumType) {
1288 if (!tree.hasTag(IDENT)) {
1289 log.error(tree.pos(), "enum.label.must.be.unqualified.enum");
1290 return syms.errSymbol;
1291 }
1292 JCIdent ident = (JCIdent)tree;
1293 Name name = ident.name;
1294 for (Scope.Entry e = enumType.tsym.members().lookup(name);
1295 e.scope != null; e = e.next()) {
1296 if (e.sym.kind == VAR) {
1297 Symbol s = ident.sym = e.sym;
1298 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
1299 ident.type = s.type;
1300 return ((s.flags_field & Flags.ENUM) == 0)
1301 ? null : s;
1302 }
1303 }
1304 return null;
1305 }
1307 public void visitSynchronized(JCSynchronized tree) {
1308 chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
1309 attribStat(tree.body, env);
1310 result = null;
1311 }
1313 public void visitTry(JCTry tree) {
1314 // Create a new local environment with a local
1315 Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
1316 try {
1317 boolean isTryWithResource = tree.resources.nonEmpty();
1318 // Create a nested environment for attributing the try block if needed
1319 Env<AttrContext> tryEnv = isTryWithResource ?
1320 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
1321 localEnv;
1322 try {
1323 // Attribute resource declarations
1324 for (JCTree resource : tree.resources) {
1325 CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) {
1326 @Override
1327 public void report(DiagnosticPosition pos, JCDiagnostic details) {
1328 chk.basicHandler.report(pos, diags.fragment("try.not.applicable.to.type", details));
1329 }
1330 };
1331 ResultInfo twrResult = new ResultInfo(VAL, syms.autoCloseableType, twrContext);
1332 if (resource.hasTag(VARDEF)) {
1333 attribStat(resource, tryEnv);
1334 twrResult.check(resource, resource.type);
1336 //check that resource type cannot throw InterruptedException
1337 checkAutoCloseable(resource.pos(), localEnv, resource.type);
1339 VarSymbol var = (VarSymbol)TreeInfo.symbolFor(resource);
1340 var.setData(ElementKind.RESOURCE_VARIABLE);
1341 } else {
1342 attribTree(resource, tryEnv, twrResult);
1343 }
1344 }
1345 // Attribute body
1346 attribStat(tree.body, tryEnv);
1347 } finally {
1348 if (isTryWithResource)
1349 tryEnv.info.scope.leave();
1350 }
1352 // Attribute catch clauses
1353 for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
1354 JCCatch c = l.head;
1355 Env<AttrContext> catchEnv =
1356 localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup()));
1357 try {
1358 Type ctype = attribStat(c.param, catchEnv);
1359 if (TreeInfo.isMultiCatch(c)) {
1360 //multi-catch parameter is implicitly marked as final
1361 c.param.sym.flags_field |= FINAL | UNION;
1362 }
1363 if (c.param.sym.kind == Kinds.VAR) {
1364 c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
1365 }
1366 chk.checkType(c.param.vartype.pos(),
1367 chk.checkClassType(c.param.vartype.pos(), ctype),
1368 syms.throwableType);
1369 attribStat(c.body, catchEnv);
1370 } finally {
1371 catchEnv.info.scope.leave();
1372 }
1373 }
1375 // Attribute finalizer
1376 if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
1377 result = null;
1378 }
1379 finally {
1380 localEnv.info.scope.leave();
1381 }
1382 }
1384 void checkAutoCloseable(DiagnosticPosition pos, Env<AttrContext> env, Type resource) {
1385 if (!resource.isErroneous() &&
1386 types.asSuper(resource, syms.autoCloseableType.tsym) != null &&
1387 !types.isSameType(resource, syms.autoCloseableType)) { // Don't emit warning for AutoCloseable itself
1388 Symbol close = syms.noSymbol;
1389 Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log);
1390 try {
1391 close = rs.resolveQualifiedMethod(pos,
1392 env,
1393 resource,
1394 names.close,
1395 List.<Type>nil(),
1396 List.<Type>nil());
1397 }
1398 finally {
1399 log.popDiagnosticHandler(discardHandler);
1400 }
1401 if (close.kind == MTH &&
1402 close.overrides(syms.autoCloseableClose, resource.tsym, types, true) &&
1403 chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes()) &&
1404 env.info.lint.isEnabled(LintCategory.TRY)) {
1405 log.warning(LintCategory.TRY, pos, "try.resource.throws.interrupted.exc", resource);
1406 }
1407 }
1408 }
1410 public void visitConditional(JCConditional tree) {
1411 Type condtype = attribExpr(tree.cond, env, syms.booleanType);
1413 tree.polyKind = (!allowPoly ||
1414 pt().hasTag(NONE) && pt() != Type.recoveryType ||
1415 isBooleanOrNumeric(env, tree)) ?
1416 PolyKind.STANDALONE : PolyKind.POLY;
1418 if (tree.polyKind == PolyKind.POLY && resultInfo.pt.hasTag(VOID)) {
1419 //cannot get here (i.e. it means we are returning from void method - which is already an error)
1420 resultInfo.checkContext.report(tree, diags.fragment("conditional.target.cant.be.void"));
1421 result = tree.type = types.createErrorType(resultInfo.pt);
1422 return;
1423 }
1425 ResultInfo condInfo = tree.polyKind == PolyKind.STANDALONE ?
1426 unknownExprInfo :
1427 resultInfo.dup(new Check.NestedCheckContext(resultInfo.checkContext) {
1428 //this will use enclosing check context to check compatibility of
1429 //subexpression against target type; if we are in a method check context,
1430 //depending on whether boxing is allowed, we could have incompatibilities
1431 @Override
1432 public void report(DiagnosticPosition pos, JCDiagnostic details) {
1433 enclosingContext.report(pos, diags.fragment("incompatible.type.in.conditional", details));
1434 }
1435 });
1437 Type truetype = attribTree(tree.truepart, env, condInfo);
1438 Type falsetype = attribTree(tree.falsepart, env, condInfo);
1440 Type owntype = (tree.polyKind == PolyKind.STANDALONE) ? condType(tree, truetype, falsetype) : pt();
1441 if (condtype.constValue() != null &&
1442 truetype.constValue() != null &&
1443 falsetype.constValue() != null &&
1444 !owntype.hasTag(NONE)) {
1445 //constant folding
1446 owntype = cfolder.coerce(condtype.isTrue() ? truetype : falsetype, owntype);
1447 }
1448 result = check(tree, owntype, VAL, resultInfo);
1449 }
1450 //where
1451 private boolean isBooleanOrNumeric(Env<AttrContext> env, JCExpression tree) {
1452 switch (tree.getTag()) {
1453 case LITERAL: return ((JCLiteral)tree).typetag.isSubRangeOf(DOUBLE) ||
1454 ((JCLiteral)tree).typetag == BOOLEAN ||
1455 ((JCLiteral)tree).typetag == BOT;
1456 case LAMBDA: case REFERENCE: return false;
1457 case PARENS: return isBooleanOrNumeric(env, ((JCParens)tree).expr);
1458 case CONDEXPR:
1459 JCConditional condTree = (JCConditional)tree;
1460 return isBooleanOrNumeric(env, condTree.truepart) &&
1461 isBooleanOrNumeric(env, condTree.falsepart);
1462 case APPLY:
1463 JCMethodInvocation speculativeMethodTree =
1464 (JCMethodInvocation)deferredAttr.attribSpeculative(tree, env, unknownExprInfo);
1465 Type owntype = TreeInfo.symbol(speculativeMethodTree.meth).type.getReturnType();
1466 return types.unboxedTypeOrType(owntype).isPrimitive();
1467 case NEWCLASS:
1468 JCExpression className =
1469 removeClassParams.translate(((JCNewClass)tree).clazz);
1470 JCExpression speculativeNewClassTree =
1471 (JCExpression)deferredAttr.attribSpeculative(className, env, unknownTypeInfo);
1472 return types.unboxedTypeOrType(speculativeNewClassTree.type).isPrimitive();
1473 default:
1474 Type speculativeType = deferredAttr.attribSpeculative(tree, env, unknownExprInfo).type;
1475 speculativeType = types.unboxedTypeOrType(speculativeType);
1476 return speculativeType.isPrimitive();
1477 }
1478 }
1479 //where
1480 TreeTranslator removeClassParams = new TreeTranslator() {
1481 @Override
1482 public void visitTypeApply(JCTypeApply tree) {
1483 result = translate(tree.clazz);
1484 }
1485 };
1487 /** Compute the type of a conditional expression, after
1488 * checking that it exists. See JLS 15.25. Does not take into
1489 * account the special case where condition and both arms
1490 * are constants.
1491 *
1492 * @param pos The source position to be used for error
1493 * diagnostics.
1494 * @param thentype The type of the expression's then-part.
1495 * @param elsetype The type of the expression's else-part.
1496 */
1497 private Type condType(DiagnosticPosition pos,
1498 Type thentype, Type elsetype) {
1499 // If same type, that is the result
1500 if (types.isSameType(thentype, elsetype))
1501 return thentype.baseType();
1503 Type thenUnboxed = (!allowBoxing || thentype.isPrimitive())
1504 ? thentype : types.unboxedType(thentype);
1505 Type elseUnboxed = (!allowBoxing || elsetype.isPrimitive())
1506 ? elsetype : types.unboxedType(elsetype);
1508 // Otherwise, if both arms can be converted to a numeric
1509 // type, return the least numeric type that fits both arms
1510 // (i.e. return larger of the two, or return int if one
1511 // arm is short, the other is char).
1512 if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) {
1513 // If one arm has an integer subrange type (i.e., byte,
1514 // short, or char), and the other is an integer constant
1515 // that fits into the subrange, return the subrange type.
1516 if (thenUnboxed.getTag().isStrictSubRangeOf(INT) && elseUnboxed.hasTag(INT) &&
1517 types.isAssignable(elseUnboxed, thenUnboxed))
1518 return thenUnboxed.baseType();
1519 if (elseUnboxed.getTag().isStrictSubRangeOf(INT) && thenUnboxed.hasTag(INT) &&
1520 types.isAssignable(thenUnboxed, elseUnboxed))
1521 return elseUnboxed.baseType();
1523 for (TypeTag tag : TypeTag.values()) {
1524 if (tag.ordinal() >= TypeTag.getTypeTagCount()) break;
1525 Type candidate = syms.typeOfTag[tag.ordinal()];
1526 if (candidate != null &&
1527 candidate.isPrimitive() &&
1528 types.isSubtype(thenUnboxed, candidate) &&
1529 types.isSubtype(elseUnboxed, candidate))
1530 return candidate;
1531 }
1532 }
1534 // Those were all the cases that could result in a primitive
1535 if (allowBoxing) {
1536 if (thentype.isPrimitive())
1537 thentype = types.boxedClass(thentype).type;
1538 if (elsetype.isPrimitive())
1539 elsetype = types.boxedClass(elsetype).type;
1540 }
1542 if (types.isSubtype(thentype, elsetype))
1543 return elsetype.baseType();
1544 if (types.isSubtype(elsetype, thentype))
1545 return thentype.baseType();
1547 if (!allowBoxing || thentype.hasTag(VOID) || elsetype.hasTag(VOID)) {
1548 log.error(pos, "neither.conditional.subtype",
1549 thentype, elsetype);
1550 return thentype.baseType();
1551 }
1553 // both are known to be reference types. The result is
1554 // lub(thentype,elsetype). This cannot fail, as it will
1555 // always be possible to infer "Object" if nothing better.
1556 return types.lub(thentype.baseType(), elsetype.baseType());
1557 }
1559 public void visitIf(JCIf tree) {
1560 attribExpr(tree.cond, env, syms.booleanType);
1561 attribStat(tree.thenpart, env);
1562 if (tree.elsepart != null)
1563 attribStat(tree.elsepart, env);
1564 chk.checkEmptyIf(tree);
1565 result = null;
1566 }
1568 public void visitExec(JCExpressionStatement tree) {
1569 //a fresh environment is required for 292 inference to work properly ---
1570 //see Infer.instantiatePolymorphicSignatureInstance()
1571 Env<AttrContext> localEnv = env.dup(tree);
1572 attribExpr(tree.expr, localEnv);
1573 result = null;
1574 }
1576 public void visitBreak(JCBreak tree) {
1577 tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
1578 result = null;
1579 }
1581 public void visitContinue(JCContinue tree) {
1582 tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
1583 result = null;
1584 }
1585 //where
1586 /** Return the target of a break or continue statement, if it exists,
1587 * report an error if not.
1588 * Note: The target of a labelled break or continue is the
1589 * (non-labelled) statement tree referred to by the label,
1590 * not the tree representing the labelled statement itself.
1591 *
1592 * @param pos The position to be used for error diagnostics
1593 * @param tag The tag of the jump statement. This is either
1594 * Tree.BREAK or Tree.CONTINUE.
1595 * @param label The label of the jump statement, or null if no
1596 * label is given.
1597 * @param env The environment current at the jump statement.
1598 */
1599 private JCTree findJumpTarget(DiagnosticPosition pos,
1600 JCTree.Tag tag,
1601 Name label,
1602 Env<AttrContext> env) {
1603 // Search environments outwards from the point of jump.
1604 Env<AttrContext> env1 = env;
1605 LOOP:
1606 while (env1 != null) {
1607 switch (env1.tree.getTag()) {
1608 case LABELLED:
1609 JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
1610 if (label == labelled.label) {
1611 // If jump is a continue, check that target is a loop.
1612 if (tag == CONTINUE) {
1613 if (!labelled.body.hasTag(DOLOOP) &&
1614 !labelled.body.hasTag(WHILELOOP) &&
1615 !labelled.body.hasTag(FORLOOP) &&
1616 !labelled.body.hasTag(FOREACHLOOP))
1617 log.error(pos, "not.loop.label", label);
1618 // Found labelled statement target, now go inwards
1619 // to next non-labelled tree.
1620 return TreeInfo.referencedStatement(labelled);
1621 } else {
1622 return labelled;
1623 }
1624 }
1625 break;
1626 case DOLOOP:
1627 case WHILELOOP:
1628 case FORLOOP:
1629 case FOREACHLOOP:
1630 if (label == null) return env1.tree;
1631 break;
1632 case SWITCH:
1633 if (label == null && tag == BREAK) return env1.tree;
1634 break;
1635 case LAMBDA:
1636 case METHODDEF:
1637 case CLASSDEF:
1638 break LOOP;
1639 default:
1640 }
1641 env1 = env1.next;
1642 }
1643 if (label != null)
1644 log.error(pos, "undef.label", label);
1645 else if (tag == CONTINUE)
1646 log.error(pos, "cont.outside.loop");
1647 else
1648 log.error(pos, "break.outside.switch.loop");
1649 return null;
1650 }
1652 public void visitReturn(JCReturn tree) {
1653 // Check that there is an enclosing method which is
1654 // nested within than the enclosing class.
1655 if (env.info.returnResult == null) {
1656 log.error(tree.pos(), "ret.outside.meth");
1657 } else {
1658 // Attribute return expression, if it exists, and check that
1659 // it conforms to result type of enclosing method.
1660 if (tree.expr != null) {
1661 if (env.info.returnResult.pt.hasTag(VOID)) {
1662 env.info.returnResult.checkContext.report(tree.expr.pos(),
1663 diags.fragment("unexpected.ret.val"));
1664 }
1665 attribTree(tree.expr, env, env.info.returnResult);
1666 } else if (!env.info.returnResult.pt.hasTag(VOID)) {
1667 env.info.returnResult.checkContext.report(tree.pos(),
1668 diags.fragment("missing.ret.val"));
1669 }
1670 }
1671 result = null;
1672 }
1674 public void visitThrow(JCThrow tree) {
1675 Type owntype = attribExpr(tree.expr, env, allowPoly ? Type.noType : syms.throwableType);
1676 if (allowPoly) {
1677 chk.checkType(tree, owntype, syms.throwableType);
1678 }
1679 result = null;
1680 }
1682 public void visitAssert(JCAssert tree) {
1683 attribExpr(tree.cond, env, syms.booleanType);
1684 if (tree.detail != null) {
1685 chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
1686 }
1687 result = null;
1688 }
1690 /** Visitor method for method invocations.
1691 * NOTE: The method part of an application will have in its type field
1692 * the return type of the method, not the method's type itself!
1693 */
1694 public void visitApply(JCMethodInvocation tree) {
1695 // The local environment of a method application is
1696 // a new environment nested in the current one.
1697 Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
1699 // The types of the actual method arguments.
1700 List<Type> argtypes;
1702 // The types of the actual method type arguments.
1703 List<Type> typeargtypes = null;
1705 Name methName = TreeInfo.name(tree.meth);
1707 boolean isConstructorCall =
1708 methName == names._this || methName == names._super;
1710 if (isConstructorCall) {
1711 // We are seeing a ...this(...) or ...super(...) call.
1712 // Check that this is the first statement in a constructor.
1713 if (checkFirstConstructorStat(tree, env)) {
1715 // Record the fact
1716 // that this is a constructor call (using isSelfCall).
1717 localEnv.info.isSelfCall = true;
1719 // Attribute arguments, yielding list of argument types.
1720 argtypes = attribArgs(tree.args, localEnv);
1721 typeargtypes = attribTypes(tree.typeargs, localEnv);
1723 // Variable `site' points to the class in which the called
1724 // constructor is defined.
1725 Type site = env.enclClass.sym.type;
1726 if (methName == names._super) {
1727 if (site == syms.objectType) {
1728 log.error(tree.meth.pos(), "no.superclass", site);
1729 site = types.createErrorType(syms.objectType);
1730 } else {
1731 site = types.supertype(site);
1732 }
1733 }
1735 if (site.hasTag(CLASS)) {
1736 Type encl = site.getEnclosingType();
1737 while (encl != null && encl.hasTag(TYPEVAR))
1738 encl = encl.getUpperBound();
1739 if (encl.hasTag(CLASS)) {
1740 // we are calling a nested class
1742 if (tree.meth.hasTag(SELECT)) {
1743 JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
1745 // We are seeing a prefixed call, of the form
1746 // <expr>.super(...).
1747 // Check that the prefix expression conforms
1748 // to the outer instance type of the class.
1749 chk.checkRefType(qualifier.pos(),
1750 attribExpr(qualifier, localEnv,
1751 encl));
1752 } else if (methName == names._super) {
1753 // qualifier omitted; check for existence
1754 // of an appropriate implicit qualifier.
1755 rs.resolveImplicitThis(tree.meth.pos(),
1756 localEnv, site, true);
1757 }
1758 } else if (tree.meth.hasTag(SELECT)) {
1759 log.error(tree.meth.pos(), "illegal.qual.not.icls",
1760 site.tsym);
1761 }
1763 // if we're calling a java.lang.Enum constructor,
1764 // prefix the implicit String and int parameters
1765 if (site.tsym == syms.enumSym && allowEnums)
1766 argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
1768 // Resolve the called constructor under the assumption
1769 // that we are referring to a superclass instance of the
1770 // current instance (JLS ???).
1771 boolean selectSuperPrev = localEnv.info.selectSuper;
1772 localEnv.info.selectSuper = true;
1773 localEnv.info.pendingResolutionPhase = null;
1774 Symbol sym = rs.resolveConstructor(
1775 tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
1776 localEnv.info.selectSuper = selectSuperPrev;
1778 // Set method symbol to resolved constructor...
1779 TreeInfo.setSymbol(tree.meth, sym);
1781 // ...and check that it is legal in the current context.
1782 // (this will also set the tree's type)
1783 Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
1784 checkId(tree.meth, site, sym, localEnv, new ResultInfo(MTH, mpt));
1785 }
1786 // Otherwise, `site' is an error type and we do nothing
1787 }
1788 result = tree.type = syms.voidType;
1789 } else {
1790 // Otherwise, we are seeing a regular method call.
1791 // Attribute the arguments, yielding list of argument types, ...
1792 argtypes = attribArgs(tree.args, localEnv);
1793 typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
1795 // ... and attribute the method using as a prototype a methodtype
1796 // whose formal argument types is exactly the list of actual
1797 // arguments (this will also set the method symbol).
1798 Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
1799 localEnv.info.pendingResolutionPhase = null;
1800 Type mtype = attribTree(tree.meth, localEnv, new ResultInfo(VAL, mpt, resultInfo.checkContext));
1802 // Compute the result type.
1803 Type restype = mtype.getReturnType();
1804 if (restype.hasTag(WILDCARD))
1805 throw new AssertionError(mtype);
1807 Type qualifier = (tree.meth.hasTag(SELECT))
1808 ? ((JCFieldAccess) tree.meth).selected.type
1809 : env.enclClass.sym.type;
1810 restype = adjustMethodReturnType(qualifier, methName, argtypes, restype);
1812 chk.checkRefTypes(tree.typeargs, typeargtypes);
1814 // Check that value of resulting type is admissible in the
1815 // current context. Also, capture the return type
1816 result = check(tree, capture(restype), VAL, resultInfo);
1818 if (localEnv.info.lastResolveVarargs())
1819 Assert.check(result.isErroneous() || tree.varargsElement != null);
1820 }
1821 chk.validate(tree.typeargs, localEnv);
1822 }
1823 //where
1824 Type adjustMethodReturnType(Type qualifierType, Name methodName, List<Type> argtypes, Type restype) {
1825 if (allowCovariantReturns &&
1826 methodName == names.clone &&
1827 types.isArray(qualifierType)) {
1828 // as a special case, array.clone() has a result that is
1829 // the same as static type of the array being cloned
1830 return qualifierType;
1831 } else if (allowGenerics &&
1832 methodName == names.getClass &&
1833 argtypes.isEmpty()) {
1834 // as a special case, x.getClass() has type Class<? extends |X|>
1835 return new ClassType(restype.getEnclosingType(),
1836 List.<Type>of(new WildcardType(types.erasure(qualifierType),
1837 BoundKind.EXTENDS,
1838 syms.boundClass)),
1839 restype.tsym);
1840 } else {
1841 return restype;
1842 }
1843 }
1845 /** Check that given application node appears as first statement
1846 * in a constructor call.
1847 * @param tree The application node
1848 * @param env The environment current at the application.
1849 */
1850 boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) {
1851 JCMethodDecl enclMethod = env.enclMethod;
1852 if (enclMethod != null && enclMethod.name == names.init) {
1853 JCBlock body = enclMethod.body;
1854 if (body.stats.head.hasTag(EXEC) &&
1855 ((JCExpressionStatement) body.stats.head).expr == tree)
1856 return true;
1857 }
1858 log.error(tree.pos(),"call.must.be.first.stmt.in.ctor",
1859 TreeInfo.name(tree.meth));
1860 return false;
1861 }
1863 /** Obtain a method type with given argument types.
1864 */
1865 Type newMethodTemplate(Type restype, List<Type> argtypes, List<Type> typeargtypes) {
1866 MethodType mt = new MethodType(argtypes, restype, List.<Type>nil(), syms.methodClass);
1867 return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
1868 }
1870 public void visitNewClass(final JCNewClass tree) {
1871 Type owntype = types.createErrorType(tree.type);
1873 // The local environment of a class creation is
1874 // a new environment nested in the current one.
1875 Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
1877 // The anonymous inner class definition of the new expression,
1878 // if one is defined by it.
1879 JCClassDecl cdef = tree.def;
1881 // If enclosing class is given, attribute it, and
1882 // complete class name to be fully qualified
1883 JCExpression clazz = tree.clazz; // Class field following new
1884 JCExpression clazzid; // Identifier in class field
1885 JCAnnotatedType annoclazzid; // Annotated type enclosing clazzid
1886 annoclazzid = null;
1888 if (clazz.hasTag(TYPEAPPLY)) {
1889 clazzid = ((JCTypeApply) clazz).clazz;
1890 if (clazzid.hasTag(ANNOTATED_TYPE)) {
1891 annoclazzid = (JCAnnotatedType) clazzid;
1892 clazzid = annoclazzid.underlyingType;
1893 }
1894 } else {
1895 if (clazz.hasTag(ANNOTATED_TYPE)) {
1896 annoclazzid = (JCAnnotatedType) clazz;
1897 clazzid = annoclazzid.underlyingType;
1898 } else {
1899 clazzid = clazz;
1900 }
1901 }
1903 JCExpression clazzid1 = clazzid; // The same in fully qualified form
1905 if (tree.encl != null) {
1906 // We are seeing a qualified new, of the form
1907 // <expr>.new C <...> (...) ...
1908 // In this case, we let clazz stand for the name of the
1909 // allocated class C prefixed with the type of the qualifier
1910 // expression, so that we can
1911 // resolve it with standard techniques later. I.e., if
1912 // <expr> has type T, then <expr>.new C <...> (...)
1913 // yields a clazz T.C.
1914 Type encltype = chk.checkRefType(tree.encl.pos(),
1915 attribExpr(tree.encl, env));
1916 // TODO 308: in <expr>.new C, do we also want to add the type annotations
1917 // from expr to the combined type, or not? Yes, do this.
1918 clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
1919 ((JCIdent) clazzid).name);
1921 if (clazz.hasTag(ANNOTATED_TYPE)) {
1922 JCAnnotatedType annoType = (JCAnnotatedType) clazz;
1923 List<JCAnnotation> annos = annoType.annotations;
1925 if (annoType.underlyingType.hasTag(TYPEAPPLY)) {
1926 clazzid1 = make.at(tree.pos).
1927 TypeApply(clazzid1,
1928 ((JCTypeApply) clazz).arguments);
1929 }
1931 clazzid1 = make.at(tree.pos).
1932 AnnotatedType(annos, clazzid1);
1933 } else if (clazz.hasTag(TYPEAPPLY)) {
1934 clazzid1 = make.at(tree.pos).
1935 TypeApply(clazzid1,
1936 ((JCTypeApply) clazz).arguments);
1937 }
1939 clazz = clazzid1;
1940 }
1942 // Attribute clazz expression and store
1943 // symbol + type back into the attributed tree.
1944 Type clazztype = TreeInfo.isEnumInit(env.tree) ?
1945 attribIdentAsEnumType(env, (JCIdent)clazz) :
1946 attribType(clazz, env);
1948 clazztype = chk.checkDiamond(tree, clazztype);
1949 chk.validate(clazz, localEnv);
1950 if (tree.encl != null) {
1951 // We have to work in this case to store
1952 // symbol + type back into the attributed tree.
1953 tree.clazz.type = clazztype;
1954 TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
1955 clazzid.type = ((JCIdent) clazzid).sym.type;
1956 if (annoclazzid != null) {
1957 annoclazzid.type = clazzid.type;
1958 }
1959 if (!clazztype.isErroneous()) {
1960 if (cdef != null && clazztype.tsym.isInterface()) {
1961 log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new");
1962 } else if (clazztype.tsym.isStatic()) {
1963 log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym);
1964 }
1965 }
1966 } else if (!clazztype.tsym.isInterface() &&
1967 clazztype.getEnclosingType().hasTag(CLASS)) {
1968 // Check for the existence of an apropos outer instance
1969 rs.resolveImplicitThis(tree.pos(), env, clazztype);
1970 }
1972 // Attribute constructor arguments.
1973 List<Type> argtypes = attribArgs(tree.args, localEnv);
1974 List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
1976 // If we have made no mistakes in the class type...
1977 if (clazztype.hasTag(CLASS)) {
1978 // Enums may not be instantiated except implicitly
1979 if (allowEnums &&
1980 (clazztype.tsym.flags_field&Flags.ENUM) != 0 &&
1981 (!env.tree.hasTag(VARDEF) ||
1982 (((JCVariableDecl) env.tree).mods.flags&Flags.ENUM) == 0 ||
1983 ((JCVariableDecl) env.tree).init != tree))
1984 log.error(tree.pos(), "enum.cant.be.instantiated");
1985 // Check that class is not abstract
1986 if (cdef == null &&
1987 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
1988 log.error(tree.pos(), "abstract.cant.be.instantiated",
1989 clazztype.tsym);
1990 } else if (cdef != null && clazztype.tsym.isInterface()) {
1991 // Check that no constructor arguments are given to
1992 // anonymous classes implementing an interface
1993 if (!argtypes.isEmpty())
1994 log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args");
1996 if (!typeargtypes.isEmpty())
1997 log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs");
1999 // Error recovery: pretend no arguments were supplied.
2000 argtypes = List.nil();
2001 typeargtypes = List.nil();
2002 } else if (TreeInfo.isDiamond(tree)) {
2003 ClassType site = new ClassType(clazztype.getEnclosingType(),
2004 clazztype.tsym.type.getTypeArguments(),
2005 clazztype.tsym);
2007 Env<AttrContext> diamondEnv = localEnv.dup(tree);
2008 diamondEnv.info.selectSuper = cdef != null;
2009 diamondEnv.info.pendingResolutionPhase = null;
2011 //if the type of the instance creation expression is a class type
2012 //apply method resolution inference (JLS 15.12.2.7). The return type
2013 //of the resolved constructor will be a partially instantiated type
2014 Symbol constructor = rs.resolveDiamond(tree.pos(),
2015 diamondEnv,
2016 site,
2017 argtypes,
2018 typeargtypes);
2019 tree.constructor = constructor.baseSymbol();
2021 final TypeSymbol csym = clazztype.tsym;
2022 ResultInfo diamondResult = new ResultInfo(MTH, newMethodTemplate(resultInfo.pt, argtypes, typeargtypes), new Check.NestedCheckContext(resultInfo.checkContext) {
2023 @Override
2024 public void report(DiagnosticPosition _unused, JCDiagnostic details) {
2025 enclosingContext.report(tree.clazz,
2026 diags.fragment("cant.apply.diamond.1", diags.fragment("diamond", csym), details));
2027 }
2028 });
2029 Type constructorType = tree.constructorType = types.createErrorType(clazztype);
2030 constructorType = checkId(tree, site,
2031 constructor,
2032 diamondEnv,
2033 diamondResult);
2035 tree.clazz.type = types.createErrorType(clazztype);
2036 if (!constructorType.isErroneous()) {
2037 tree.clazz.type = clazztype = constructorType.getReturnType();
2038 tree.constructorType = types.createMethodTypeWithReturn(constructorType, syms.voidType);
2039 }
2040 clazztype = chk.checkClassType(tree.clazz, tree.clazz.type, true);
2041 }
2043 // Resolve the called constructor under the assumption
2044 // that we are referring to a superclass instance of the
2045 // current instance (JLS ???).
2046 else {
2047 //the following code alters some of the fields in the current
2048 //AttrContext - hence, the current context must be dup'ed in
2049 //order to avoid downstream failures
2050 Env<AttrContext> rsEnv = localEnv.dup(tree);
2051 rsEnv.info.selectSuper = cdef != null;
2052 rsEnv.info.pendingResolutionPhase = null;
2053 tree.constructor = rs.resolveConstructor(
2054 tree.pos(), rsEnv, clazztype, argtypes, typeargtypes);
2055 if (cdef == null) { //do not check twice!
2056 tree.constructorType = checkId(tree,
2057 clazztype,
2058 tree.constructor,
2059 rsEnv,
2060 new ResultInfo(MTH, newMethodTemplate(syms.voidType, argtypes, typeargtypes)));
2061 if (rsEnv.info.lastResolveVarargs())
2062 Assert.check(tree.constructorType.isErroneous() || tree.varargsElement != null);
2063 }
2064 findDiamondIfNeeded(localEnv, tree, clazztype);
2065 }
2067 if (cdef != null) {
2068 // We are seeing an anonymous class instance creation.
2069 // In this case, the class instance creation
2070 // expression
2071 //
2072 // E.new <typeargs1>C<typargs2>(args) { ... }
2073 //
2074 // is represented internally as
2075 //
2076 // E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } ) .
2077 //
2078 // This expression is then *transformed* as follows:
2079 //
2080 // (1) add a STATIC flag to the class definition
2081 // if the current environment is static
2082 // (2) add an extends or implements clause
2083 // (3) add a constructor.
2084 //
2085 // For instance, if C is a class, and ET is the type of E,
2086 // the expression
2087 //
2088 // E.new <typeargs1>C<typargs2>(args) { ... }
2089 //
2090 // is translated to (where X is a fresh name and typarams is the
2091 // parameter list of the super constructor):
2092 //
2093 // new <typeargs1>X(<*nullchk*>E, args) where
2094 // X extends C<typargs2> {
2095 // <typarams> X(ET e, args) {
2096 // e.<typeargs1>super(args)
2097 // }
2098 // ...
2099 // }
2100 if (Resolve.isStatic(env)) cdef.mods.flags |= STATIC;
2102 if (clazztype.tsym.isInterface()) {
2103 cdef.implementing = List.of(clazz);
2104 } else {
2105 cdef.extending = clazz;
2106 }
2108 attribStat(cdef, localEnv);
2110 checkLambdaCandidate(tree, cdef.sym, clazztype);
2112 // If an outer instance is given,
2113 // prefix it to the constructor arguments
2114 // and delete it from the new expression
2115 if (tree.encl != null && !clazztype.tsym.isInterface()) {
2116 tree.args = tree.args.prepend(makeNullCheck(tree.encl));
2117 argtypes = argtypes.prepend(tree.encl.type);
2118 tree.encl = null;
2119 }
2121 // Reassign clazztype and recompute constructor.
2122 clazztype = cdef.sym.type;
2123 Symbol sym = tree.constructor = rs.resolveConstructor(
2124 tree.pos(), localEnv, clazztype, argtypes, typeargtypes);
2125 Assert.check(sym.kind < AMBIGUOUS);
2126 tree.constructor = sym;
2127 tree.constructorType = checkId(tree,
2128 clazztype,
2129 tree.constructor,
2130 localEnv,
2131 new ResultInfo(VAL, newMethodTemplate(syms.voidType, argtypes, typeargtypes)));
2132 }
2134 if (tree.constructor != null && tree.constructor.kind == MTH)
2135 owntype = clazztype;
2136 }
2137 result = check(tree, owntype, VAL, resultInfo);
2138 chk.validate(tree.typeargs, localEnv);
2139 }
2140 //where
2141 void findDiamondIfNeeded(Env<AttrContext> env, JCNewClass tree, Type clazztype) {
2142 if (tree.def == null &&
2143 !clazztype.isErroneous() &&
2144 clazztype.getTypeArguments().nonEmpty() &&
2145 findDiamonds) {
2146 JCTypeApply ta = (JCTypeApply)tree.clazz;
2147 List<JCExpression> prevTypeargs = ta.arguments;
2148 try {
2149 //create a 'fake' diamond AST node by removing type-argument trees
2150 ta.arguments = List.nil();
2151 ResultInfo findDiamondResult = new ResultInfo(VAL,
2152 resultInfo.checkContext.inferenceContext().free(resultInfo.pt) ? Type.noType : pt());
2153 Type inferred = deferredAttr.attribSpeculative(tree, env, findDiamondResult).type;
2154 if (!inferred.isErroneous() &&
2155 types.isAssignable(inferred, pt().hasTag(NONE) ? syms.objectType : pt(), types.noWarnings)) {
2156 String key = types.isSameType(clazztype, inferred) ?
2157 "diamond.redundant.args" :
2158 "diamond.redundant.args.1";
2159 log.warning(tree.clazz.pos(), key, clazztype, inferred);
2160 }
2161 } finally {
2162 ta.arguments = prevTypeargs;
2163 }
2164 }
2165 }
2167 private void checkLambdaCandidate(JCNewClass tree, ClassSymbol csym, Type clazztype) {
2168 if (allowLambda &&
2169 identifyLambdaCandidate &&
2170 clazztype.hasTag(CLASS) &&
2171 !pt().hasTag(NONE) &&
2172 types.isFunctionalInterface(clazztype.tsym)) {
2173 Symbol descriptor = types.findDescriptorSymbol(clazztype.tsym);
2174 int count = 0;
2175 boolean found = false;
2176 for (Symbol sym : csym.members().getElements()) {
2177 if ((sym.flags() & SYNTHETIC) != 0 ||
2178 sym.isConstructor()) continue;
2179 count++;
2180 if (sym.kind != MTH ||
2181 !sym.name.equals(descriptor.name)) continue;
2182 Type mtype = types.memberType(clazztype, sym);
2183 if (types.overrideEquivalent(mtype, types.memberType(clazztype, descriptor))) {
2184 found = true;
2185 }
2186 }
2187 if (found && count == 1) {
2188 log.note(tree.def, "potential.lambda.found");
2189 }
2190 }
2191 }
2193 /** Make an attributed null check tree.
2194 */
2195 public JCExpression makeNullCheck(JCExpression arg) {
2196 // optimization: X.this is never null; skip null check
2197 Name name = TreeInfo.name(arg);
2198 if (name == names._this || name == names._super) return arg;
2200 JCTree.Tag optag = NULLCHK;
2201 JCUnary tree = make.at(arg.pos).Unary(optag, arg);
2202 tree.operator = syms.nullcheck;
2203 tree.type = arg.type;
2204 return tree;
2205 }
2207 public void visitNewArray(JCNewArray tree) {
2208 Type owntype = types.createErrorType(tree.type);
2209 Env<AttrContext> localEnv = env.dup(tree);
2210 Type elemtype;
2211 if (tree.elemtype != null) {
2212 elemtype = attribType(tree.elemtype, localEnv);
2213 chk.validate(tree.elemtype, localEnv);
2214 owntype = elemtype;
2215 for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
2216 attribExpr(l.head, localEnv, syms.intType);
2217 owntype = new ArrayType(owntype, syms.arrayClass);
2218 }
2219 } else {
2220 // we are seeing an untyped aggregate { ... }
2221 // this is allowed only if the prototype is an array
2222 if (pt().hasTag(ARRAY)) {
2223 elemtype = types.elemtype(pt());
2224 } else {
2225 if (!pt().hasTag(ERROR)) {
2226 log.error(tree.pos(), "illegal.initializer.for.type",
2227 pt());
2228 }
2229 elemtype = types.createErrorType(pt());
2230 }
2231 }
2232 if (tree.elems != null) {
2233 attribExprs(tree.elems, localEnv, elemtype);
2234 owntype = new ArrayType(elemtype, syms.arrayClass);
2235 }
2236 if (!types.isReifiable(elemtype))
2237 log.error(tree.pos(), "generic.array.creation");
2238 result = check(tree, owntype, VAL, resultInfo);
2239 }
2241 /*
2242 * A lambda expression can only be attributed when a target-type is available.
2243 * In addition, if the target-type is that of a functional interface whose
2244 * descriptor contains inference variables in argument position the lambda expression
2245 * is 'stuck' (see DeferredAttr).
2246 */
2247 @Override
2248 public void visitLambda(final JCLambda that) {
2249 if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
2250 if (pt().hasTag(NONE)) {
2251 //lambda only allowed in assignment or method invocation/cast context
2252 log.error(that.pos(), "unexpected.lambda");
2253 }
2254 result = that.type = types.createErrorType(pt());
2255 return;
2256 }
2257 //create an environment for attribution of the lambda expression
2258 final Env<AttrContext> localEnv = lambdaEnv(that, env);
2259 boolean needsRecovery =
2260 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK;
2261 try {
2262 Type target = pt();
2263 List<Type> explicitParamTypes = null;
2264 if (that.paramKind == JCLambda.ParameterKind.EXPLICIT) {
2265 //attribute lambda parameters
2266 attribStats(that.params, localEnv);
2267 explicitParamTypes = TreeInfo.types(that.params);
2268 target = infer.instantiateFunctionalInterface(that, target, explicitParamTypes, resultInfo.checkContext);
2269 }
2271 Type lambdaType;
2272 if (pt() != Type.recoveryType) {
2273 target = checkIntersectionTarget(that, target, resultInfo.checkContext);
2274 lambdaType = types.findDescriptorType(target);
2275 chk.checkFunctionalInterface(that, target);
2276 } else {
2277 target = Type.recoveryType;
2278 lambdaType = fallbackDescriptorType(that);
2279 }
2281 setFunctionalInfo(that, pt(), lambdaType, resultInfo.checkContext.inferenceContext());
2283 if (lambdaType.hasTag(FORALL)) {
2284 //lambda expression target desc cannot be a generic method
2285 resultInfo.checkContext.report(that, diags.fragment("invalid.generic.lambda.target",
2286 lambdaType, kindName(target.tsym), target.tsym));
2287 result = that.type = types.createErrorType(pt());
2288 return;
2289 }
2291 if (that.paramKind == JCLambda.ParameterKind.IMPLICIT) {
2292 //add param type info in the AST
2293 List<Type> actuals = lambdaType.getParameterTypes();
2294 List<JCVariableDecl> params = that.params;
2296 boolean arityMismatch = false;
2298 while (params.nonEmpty()) {
2299 if (actuals.isEmpty()) {
2300 //not enough actuals to perform lambda parameter inference
2301 arityMismatch = true;
2302 }
2303 //reset previously set info
2304 Type argType = arityMismatch ?
2305 syms.errType :
2306 actuals.head;
2307 params.head.vartype = make.Type(argType);
2308 params.head.sym = null;
2309 actuals = actuals.isEmpty() ?
2310 actuals :
2311 actuals.tail;
2312 params = params.tail;
2313 }
2315 //attribute lambda parameters
2316 attribStats(that.params, localEnv);
2318 if (arityMismatch) {
2319 resultInfo.checkContext.report(that, diags.fragment("incompatible.arg.types.in.lambda"));
2320 result = that.type = types.createErrorType(target);
2321 return;
2322 }
2323 }
2325 //from this point on, no recovery is needed; if we are in assignment context
2326 //we will be able to attribute the whole lambda body, regardless of errors;
2327 //if we are in a 'check' method context, and the lambda is not compatible
2328 //with the target-type, it will be recovered anyway in Attr.checkId
2329 needsRecovery = false;
2331 FunctionalReturnContext funcContext = that.getBodyKind() == JCLambda.BodyKind.EXPRESSION ?
2332 new ExpressionLambdaReturnContext((JCExpression)that.getBody(), resultInfo.checkContext) :
2333 new FunctionalReturnContext(resultInfo.checkContext);
2335 ResultInfo bodyResultInfo = lambdaType.getReturnType() == Type.recoveryType ?
2336 recoveryInfo :
2337 new ResultInfo(VAL, lambdaType.getReturnType(), funcContext);
2338 localEnv.info.returnResult = bodyResultInfo;
2340 if (that.getBodyKind() == JCLambda.BodyKind.EXPRESSION) {
2341 attribTree(that.getBody(), localEnv, bodyResultInfo);
2342 } else {
2343 JCBlock body = (JCBlock)that.body;
2344 attribStats(body.stats, localEnv);
2345 }
2347 result = check(that, target, VAL, resultInfo);
2349 boolean isSpeculativeRound =
2350 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
2352 postAttr(that);
2353 flow.analyzeLambda(env, that, make, isSpeculativeRound);
2355 checkLambdaCompatible(that, lambdaType, resultInfo.checkContext, isSpeculativeRound);
2357 if (!isSpeculativeRound) {
2358 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), lambdaType, target);
2359 }
2360 result = check(that, target, VAL, resultInfo);
2361 } catch (Types.FunctionDescriptorLookupError ex) {
2362 JCDiagnostic cause = ex.getDiagnostic();
2363 resultInfo.checkContext.report(that, cause);
2364 result = that.type = types.createErrorType(pt());
2365 return;
2366 } finally {
2367 localEnv.info.scope.leave();
2368 if (needsRecovery) {
2369 attribTree(that, env, recoveryInfo);
2370 }
2371 }
2372 }
2374 private Type checkIntersectionTarget(DiagnosticPosition pos, Type pt, CheckContext checkContext) {
2375 if (pt != Type.recoveryType && pt.isCompound()) {
2376 IntersectionClassType ict = (IntersectionClassType)pt;
2377 List<Type> bounds = ict.allInterfaces ?
2378 ict.getComponents().tail :
2379 ict.getComponents();
2380 types.findDescriptorType(bounds.head); //propagate exception outwards!
2381 for (Type bound : bounds.tail) {
2382 if (!types.isMarkerInterface(bound)) {
2383 checkContext.report(pos, diags.fragment("secondary.bound.must.be.marker.intf", bound));
2384 }
2385 }
2386 //for now (translation doesn't support intersection types)
2387 return bounds.head;
2388 } else {
2389 return pt;
2390 }
2391 }
2392 //where
2393 private Type fallbackDescriptorType(JCExpression tree) {
2394 switch (tree.getTag()) {
2395 case LAMBDA:
2396 JCLambda lambda = (JCLambda)tree;
2397 List<Type> argtypes = List.nil();
2398 for (JCVariableDecl param : lambda.params) {
2399 argtypes = param.vartype != null ?
2400 argtypes.append(param.vartype.type) :
2401 argtypes.append(syms.errType);
2402 }
2403 return new MethodType(argtypes, Type.recoveryType, List.<Type>nil(), syms.methodClass);
2404 case REFERENCE:
2405 return new MethodType(List.<Type>nil(), Type.recoveryType, List.<Type>nil(), syms.methodClass);
2406 default:
2407 Assert.error("Cannot get here!");
2408 }
2409 return null;
2410 }
2412 private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env, final InferenceContext inferenceContext, final Type... ts) {
2413 checkAccessibleTypes(pos, env, inferenceContext, List.from(ts));
2414 }
2416 private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env, final InferenceContext inferenceContext, final List<Type> ts) {
2417 if (inferenceContext.free(ts)) {
2418 inferenceContext.addFreeTypeListener(ts, new FreeTypeListener() {
2419 @Override
2420 public void typesInferred(InferenceContext inferenceContext) {
2421 checkAccessibleTypes(pos, env, inferenceContext, inferenceContext.asInstTypes(ts));
2422 }
2423 });
2424 } else {
2425 for (Type t : ts) {
2426 rs.checkAccessibleType(env, t);
2427 }
2428 }
2429 }
2431 /**
2432 * Lambda/method reference have a special check context that ensures
2433 * that i.e. a lambda return type is compatible with the expected
2434 * type according to both the inherited context and the assignment
2435 * context.
2436 */
2437 class FunctionalReturnContext extends Check.NestedCheckContext {
2439 FunctionalReturnContext(CheckContext enclosingContext) {
2440 super(enclosingContext);
2441 }
2443 @Override
2444 public boolean compatible(Type found, Type req, Warner warn) {
2445 //return type must be compatible in both current context and assignment context
2446 return chk.basicHandler.compatible(found, inferenceContext().asFree(req), warn);
2447 }
2449 @Override
2450 public void report(DiagnosticPosition pos, JCDiagnostic details) {
2451 enclosingContext.report(pos, diags.fragment("incompatible.ret.type.in.lambda", details));
2452 }
2453 }
2455 class ExpressionLambdaReturnContext extends FunctionalReturnContext {
2457 JCExpression expr;
2459 ExpressionLambdaReturnContext(JCExpression expr, CheckContext enclosingContext) {
2460 super(enclosingContext);
2461 this.expr = expr;
2462 }
2464 @Override
2465 public boolean compatible(Type found, Type req, Warner warn) {
2466 //a void return is compatible with an expression statement lambda
2467 return TreeInfo.isExpressionStatement(expr) && req.hasTag(VOID) ||
2468 super.compatible(found, req, warn);
2469 }
2470 }
2472 /**
2473 * Lambda compatibility. Check that given return types, thrown types, parameter types
2474 * are compatible with the expected functional interface descriptor. This means that:
2475 * (i) parameter types must be identical to those of the target descriptor; (ii) return
2476 * types must be compatible with the return type of the expected descriptor;
2477 * (iii) thrown types must be 'included' in the thrown types list of the expected
2478 * descriptor.
2479 */
2480 private void checkLambdaCompatible(JCLambda tree, Type descriptor, CheckContext checkContext, boolean speculativeAttr) {
2481 Type returnType = checkContext.inferenceContext().asFree(descriptor.getReturnType());
2483 //return values have already been checked - but if lambda has no return
2484 //values, we must ensure that void/value compatibility is correct;
2485 //this amounts at checking that, if a lambda body can complete normally,
2486 //the descriptor's return type must be void
2487 if (tree.getBodyKind() == JCLambda.BodyKind.STATEMENT && tree.canCompleteNormally &&
2488 !returnType.hasTag(VOID) && returnType != Type.recoveryType) {
2489 checkContext.report(tree, diags.fragment("incompatible.ret.type.in.lambda",
2490 diags.fragment("missing.ret.val", returnType)));
2491 }
2493 List<Type> argTypes = checkContext.inferenceContext().asFree(descriptor.getParameterTypes());
2494 if (!types.isSameTypes(argTypes, TreeInfo.types(tree.params))) {
2495 checkContext.report(tree, diags.fragment("incompatible.arg.types.in.lambda"));
2496 }
2498 if (!speculativeAttr) {
2499 List<Type> thrownTypes = checkContext.inferenceContext().asFree(descriptor.getThrownTypes());
2500 if (chk.unhandled(tree.inferredThrownTypes == null ? List.<Type>nil() : tree.inferredThrownTypes, thrownTypes).nonEmpty()) {
2501 log.error(tree, "incompatible.thrown.types.in.lambda", tree.inferredThrownTypes);
2502 }
2503 }
2504 }
2506 private Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) {
2507 Env<AttrContext> lambdaEnv;
2508 Symbol owner = env.info.scope.owner;
2509 if (owner.kind == VAR && owner.owner.kind == TYP) {
2510 //field initializer
2511 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared()));
2512 lambdaEnv.info.scope.owner =
2513 new MethodSymbol(0, names.empty, null,
2514 env.info.scope.owner);
2515 } else {
2516 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dup()));
2517 }
2518 return lambdaEnv;
2519 }
2521 @Override
2522 public void visitReference(final JCMemberReference that) {
2523 if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
2524 if (pt().hasTag(NONE)) {
2525 //method reference only allowed in assignment or method invocation/cast context
2526 log.error(that.pos(), "unexpected.mref");
2527 }
2528 result = that.type = types.createErrorType(pt());
2529 return;
2530 }
2531 final Env<AttrContext> localEnv = env.dup(that);
2532 try {
2533 //attribute member reference qualifier - if this is a constructor
2534 //reference, the expected kind must be a type
2535 Type exprType = attribTree(that.expr, env, memberReferenceQualifierResult(that));
2537 if (that.getMode() == JCMemberReference.ReferenceMode.NEW) {
2538 exprType = chk.checkConstructorRefType(that.expr, exprType);
2539 }
2541 if (exprType.isErroneous()) {
2542 //if the qualifier expression contains problems,
2543 //give up attribution of method reference
2544 result = that.type = exprType;
2545 return;
2546 }
2548 if (TreeInfo.isStaticSelector(that.expr, names) &&
2549 (that.getMode() != ReferenceMode.NEW || !that.expr.type.isRaw())) {
2550 //if the qualifier is a type, validate it
2551 chk.validate(that.expr, env);
2552 }
2554 //attrib type-arguments
2555 List<Type> typeargtypes = List.nil();
2556 if (that.typeargs != null) {
2557 typeargtypes = attribTypes(that.typeargs, localEnv);
2558 }
2560 Type target;
2561 Type desc;
2562 if (pt() != Type.recoveryType) {
2563 target = checkIntersectionTarget(that, pt(), resultInfo.checkContext);
2564 desc = types.findDescriptorType(target);
2565 chk.checkFunctionalInterface(that, target);
2566 } else {
2567 target = Type.recoveryType;
2568 desc = fallbackDescriptorType(that);
2569 }
2571 setFunctionalInfo(that, pt(), desc, resultInfo.checkContext.inferenceContext());
2572 List<Type> argtypes = desc.getParameterTypes();
2574 Pair<Symbol, Resolve.ReferenceLookupHelper> refResult = rs.resolveMemberReference(that.pos(), localEnv, that,
2575 that.expr.type, that.name, argtypes, typeargtypes, true);
2577 Symbol refSym = refResult.fst;
2578 Resolve.ReferenceLookupHelper lookupHelper = refResult.snd;
2580 if (refSym.kind != MTH) {
2581 boolean targetError;
2582 switch (refSym.kind) {
2583 case ABSENT_MTH:
2584 targetError = false;
2585 break;
2586 case WRONG_MTH:
2587 case WRONG_MTHS:
2588 case AMBIGUOUS:
2589 case HIDDEN:
2590 case STATICERR:
2591 case MISSING_ENCL:
2592 targetError = true;
2593 break;
2594 default:
2595 Assert.error("unexpected result kind " + refSym.kind);
2596 targetError = false;
2597 }
2599 JCDiagnostic detailsDiag = ((Resolve.ResolveError)refSym).getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT,
2600 that, exprType.tsym, exprType, that.name, argtypes, typeargtypes);
2602 JCDiagnostic.DiagnosticType diagKind = targetError ?
2603 JCDiagnostic.DiagnosticType.FRAGMENT : JCDiagnostic.DiagnosticType.ERROR;
2605 JCDiagnostic diag = diags.create(diagKind, log.currentSource(), that,
2606 "invalid.mref", Kinds.kindName(that.getMode()), detailsDiag);
2608 if (targetError && target == Type.recoveryType) {
2609 //a target error doesn't make sense during recovery stage
2610 //as we don't know what actual parameter types are
2611 result = that.type = target;
2612 return;
2613 } else {
2614 if (targetError) {
2615 resultInfo.checkContext.report(that, diag);
2616 } else {
2617 log.report(diag);
2618 }
2619 result = that.type = types.createErrorType(target);
2620 return;
2621 }
2622 }
2624 that.sym = refSym.baseSymbol();
2625 that.kind = lookupHelper.referenceKind(that.sym);
2627 if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
2628 if (that.sym.isStatic() && TreeInfo.isStaticSelector(that.expr, names) &&
2629 exprType.getTypeArguments().nonEmpty()) {
2630 //static ref with class type-args
2631 log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
2632 diags.fragment("static.mref.with.targs"));
2633 result = that.type = types.createErrorType(target);
2634 return;
2635 }
2637 if (that.sym.isStatic() && !TreeInfo.isStaticSelector(that.expr, names) &&
2638 !that.kind.isUnbound()) {
2639 //no static bound mrefs
2640 log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
2641 diags.fragment("static.bound.mref"));
2642 result = that.type = types.createErrorType(target);
2643 return;
2644 }
2646 if (!refSym.isStatic() && that.kind == JCMemberReference.ReferenceKind.SUPER) {
2647 // Check that super-qualified symbols are not abstract (JLS)
2648 rs.checkNonAbstract(that.pos(), that.sym);
2649 }
2650 }
2652 if (desc.getReturnType() == Type.recoveryType) {
2653 // stop here
2654 result = that.type = target;
2655 return;
2656 }
2658 that.sym = refSym.baseSymbol();
2659 that.kind = lookupHelper.referenceKind(that.sym);
2661 ResultInfo checkInfo =
2662 resultInfo.dup(newMethodTemplate(
2663 desc.getReturnType().hasTag(VOID) ? Type.noType : desc.getReturnType(),
2664 lookupHelper.argtypes,
2665 typeargtypes));
2667 Type refType = checkId(that, lookupHelper.site, refSym, localEnv, checkInfo);
2669 if (!refType.isErroneous()) {
2670 refType = types.createMethodTypeWithReturn(refType,
2671 adjustMethodReturnType(lookupHelper.site, that.name, checkInfo.pt.getParameterTypes(), refType.getReturnType()));
2672 }
2674 //go ahead with standard method reference compatibility check - note that param check
2675 //is a no-op (as this has been taken care during method applicability)
2676 boolean isSpeculativeRound =
2677 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
2678 checkReferenceCompatible(that, desc, refType, resultInfo.checkContext, isSpeculativeRound);
2679 if (!isSpeculativeRound) {
2680 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), desc, target);
2681 }
2682 result = check(that, target, VAL, resultInfo);
2683 } catch (Types.FunctionDescriptorLookupError ex) {
2684 JCDiagnostic cause = ex.getDiagnostic();
2685 resultInfo.checkContext.report(that, cause);
2686 result = that.type = types.createErrorType(pt());
2687 return;
2688 }
2689 }
2690 //where
2691 ResultInfo memberReferenceQualifierResult(JCMemberReference tree) {
2692 //if this is a constructor reference, the expected kind must be a type
2693 return new ResultInfo(tree.getMode() == ReferenceMode.INVOKE ? VAL | TYP : TYP, Type.noType);
2694 }
2697 @SuppressWarnings("fallthrough")
2698 void checkReferenceCompatible(JCMemberReference tree, Type descriptor, Type refType, CheckContext checkContext, boolean speculativeAttr) {
2699 Type returnType = checkContext.inferenceContext().asFree(descriptor.getReturnType());
2701 Type resType;
2702 switch (tree.getMode()) {
2703 case NEW:
2704 if (!tree.expr.type.isRaw()) {
2705 resType = tree.expr.type;
2706 break;
2707 }
2708 default:
2709 resType = refType.getReturnType();
2710 }
2712 Type incompatibleReturnType = resType;
2714 if (returnType.hasTag(VOID)) {
2715 incompatibleReturnType = null;
2716 }
2718 if (!returnType.hasTag(VOID) && !resType.hasTag(VOID)) {
2719 if (resType.isErroneous() ||
2720 new FunctionalReturnContext(checkContext).compatible(resType, returnType, types.noWarnings)) {
2721 incompatibleReturnType = null;
2722 }
2723 }
2725 if (incompatibleReturnType != null) {
2726 checkContext.report(tree, diags.fragment("incompatible.ret.type.in.mref",
2727 diags.fragment("inconvertible.types", resType, descriptor.getReturnType())));
2728 }
2730 if (!speculativeAttr) {
2731 List<Type> thrownTypes = checkContext.inferenceContext().asFree(descriptor.getThrownTypes());
2732 if (chk.unhandled(refType.getThrownTypes(), thrownTypes).nonEmpty()) {
2733 log.error(tree, "incompatible.thrown.types.in.mref", refType.getThrownTypes());
2734 }
2735 }
2736 }
2738 /**
2739 * Set functional type info on the underlying AST. Note: as the target descriptor
2740 * might contain inference variables, we might need to register an hook in the
2741 * current inference context.
2742 */
2743 private void setFunctionalInfo(final JCFunctionalExpression fExpr, final Type pt, final Type descriptorType, InferenceContext inferenceContext) {
2744 if (inferenceContext.free(descriptorType)) {
2745 inferenceContext.addFreeTypeListener(List.of(pt, descriptorType), new FreeTypeListener() {
2746 public void typesInferred(InferenceContext inferenceContext) {
2747 setFunctionalInfo(fExpr, pt, inferenceContext.asInstType(descriptorType), inferenceContext);
2748 }
2749 });
2750 } else {
2751 ListBuffer<TypeSymbol> targets = ListBuffer.lb();
2752 if (pt.hasTag(CLASS)) {
2753 if (pt.isCompound()) {
2754 for (Type t : ((IntersectionClassType)pt()).interfaces_field) {
2755 targets.append(t.tsym);
2756 }
2757 } else {
2758 targets.append(pt.tsym);
2759 }
2760 }
2761 fExpr.targets = targets.toList();
2762 fExpr.descriptorType = descriptorType;
2763 }
2764 }
2766 public void visitParens(JCParens tree) {
2767 Type owntype = attribTree(tree.expr, env, resultInfo);
2768 result = check(tree, owntype, pkind(), resultInfo);
2769 Symbol sym = TreeInfo.symbol(tree);
2770 if (sym != null && (sym.kind&(TYP|PCK)) != 0)
2771 log.error(tree.pos(), "illegal.start.of.type");
2772 }
2774 public void visitAssign(JCAssign tree) {
2775 Type owntype = attribTree(tree.lhs, env.dup(tree), varInfo);
2776 Type capturedType = capture(owntype);
2777 attribExpr(tree.rhs, env, owntype);
2778 result = check(tree, capturedType, VAL, resultInfo);
2779 }
2781 public void visitAssignop(JCAssignOp tree) {
2782 // Attribute arguments.
2783 Type owntype = attribTree(tree.lhs, env, varInfo);
2784 Type operand = attribExpr(tree.rhs, env);
2785 // Find operator.
2786 Symbol operator = tree.operator = rs.resolveBinaryOperator(
2787 tree.pos(), tree.getTag().noAssignOp(), env,
2788 owntype, operand);
2790 if (operator.kind == MTH &&
2791 !owntype.isErroneous() &&
2792 !operand.isErroneous()) {
2793 chk.checkOperator(tree.pos(),
2794 (OperatorSymbol)operator,
2795 tree.getTag().noAssignOp(),
2796 owntype,
2797 operand);
2798 chk.checkDivZero(tree.rhs.pos(), operator, operand);
2799 chk.checkCastable(tree.rhs.pos(),
2800 operator.type.getReturnType(),
2801 owntype);
2802 }
2803 result = check(tree, owntype, VAL, resultInfo);
2804 }
2806 public void visitUnary(JCUnary tree) {
2807 // Attribute arguments.
2808 Type argtype = (tree.getTag().isIncOrDecUnaryOp())
2809 ? attribTree(tree.arg, env, varInfo)
2810 : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
2812 // Find operator.
2813 Symbol operator = tree.operator =
2814 rs.resolveUnaryOperator(tree.pos(), tree.getTag(), env, argtype);
2816 Type owntype = types.createErrorType(tree.type);
2817 if (operator.kind == MTH &&
2818 !argtype.isErroneous()) {
2819 owntype = (tree.getTag().isIncOrDecUnaryOp())
2820 ? tree.arg.type
2821 : operator.type.getReturnType();
2822 int opc = ((OperatorSymbol)operator).opcode;
2824 // If the argument is constant, fold it.
2825 if (argtype.constValue() != null) {
2826 Type ctype = cfolder.fold1(opc, argtype);
2827 if (ctype != null) {
2828 owntype = cfolder.coerce(ctype, owntype);
2830 // Remove constant types from arguments to
2831 // conserve space. The parser will fold concatenations
2832 // of string literals; the code here also
2833 // gets rid of intermediate results when some of the
2834 // operands are constant identifiers.
2835 if (tree.arg.type.tsym == syms.stringType.tsym) {
2836 tree.arg.type = syms.stringType;
2837 }
2838 }
2839 }
2840 }
2841 result = check(tree, owntype, VAL, resultInfo);
2842 }
2844 public void visitBinary(JCBinary tree) {
2845 // Attribute arguments.
2846 Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
2847 Type right = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.rhs, env));
2849 // Find operator.
2850 Symbol operator = tree.operator =
2851 rs.resolveBinaryOperator(tree.pos(), tree.getTag(), env, left, right);
2853 Type owntype = types.createErrorType(tree.type);
2854 if (operator.kind == MTH &&
2855 !left.isErroneous() &&
2856 !right.isErroneous()) {
2857 owntype = operator.type.getReturnType();
2858 int opc = chk.checkOperator(tree.lhs.pos(),
2859 (OperatorSymbol)operator,
2860 tree.getTag(),
2861 left,
2862 right);
2864 // If both arguments are constants, fold them.
2865 if (left.constValue() != null && right.constValue() != null) {
2866 Type ctype = cfolder.fold2(opc, left, right);
2867 if (ctype != null) {
2868 owntype = cfolder.coerce(ctype, owntype);
2870 // Remove constant types from arguments to
2871 // conserve space. The parser will fold concatenations
2872 // of string literals; the code here also
2873 // gets rid of intermediate results when some of the
2874 // operands are constant identifiers.
2875 if (tree.lhs.type.tsym == syms.stringType.tsym) {
2876 tree.lhs.type = syms.stringType;
2877 }
2878 if (tree.rhs.type.tsym == syms.stringType.tsym) {
2879 tree.rhs.type = syms.stringType;
2880 }
2881 }
2882 }
2884 // Check that argument types of a reference ==, != are
2885 // castable to each other, (JLS???).
2886 if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
2887 if (!types.isCastable(left, right, new Warner(tree.pos()))) {
2888 log.error(tree.pos(), "incomparable.types", left, right);
2889 }
2890 }
2892 chk.checkDivZero(tree.rhs.pos(), operator, right);
2893 }
2894 result = check(tree, owntype, VAL, resultInfo);
2895 }
2897 public void visitTypeCast(final JCTypeCast tree) {
2898 Type clazztype = attribType(tree.clazz, env);
2899 chk.validate(tree.clazz, env, false);
2900 //a fresh environment is required for 292 inference to work properly ---
2901 //see Infer.instantiatePolymorphicSignatureInstance()
2902 Env<AttrContext> localEnv = env.dup(tree);
2903 //should we propagate the target type?
2904 final ResultInfo castInfo;
2905 final boolean isPoly = TreeInfo.isPoly(tree.expr, tree);
2906 if (isPoly) {
2907 //expression is a poly - we need to propagate target type info
2908 castInfo = new ResultInfo(VAL, clazztype, new Check.NestedCheckContext(resultInfo.checkContext) {
2909 @Override
2910 public boolean compatible(Type found, Type req, Warner warn) {
2911 return types.isCastable(found, req, warn);
2912 }
2913 });
2914 } else {
2915 //standalone cast - target-type info is not propagated
2916 castInfo = unknownExprInfo;
2917 }
2918 Type exprtype = attribTree(tree.expr, localEnv, castInfo);
2919 Type owntype = isPoly ? clazztype : chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
2920 if (exprtype.constValue() != null)
2921 owntype = cfolder.coerce(exprtype, owntype);
2922 result = check(tree, capture(owntype), VAL, resultInfo);
2923 if (!isPoly)
2924 chk.checkRedundantCast(localEnv, tree);
2925 }
2927 public void visitTypeTest(JCInstanceOf tree) {
2928 Type exprtype = chk.checkNullOrRefType(
2929 tree.expr.pos(), attribExpr(tree.expr, env));
2930 Type clazztype = chk.checkReifiableReferenceType(
2931 tree.clazz.pos(), attribType(tree.clazz, env));
2932 chk.validate(tree.clazz, env, false);
2933 chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
2934 result = check(tree, syms.booleanType, VAL, resultInfo);
2935 }
2937 public void visitIndexed(JCArrayAccess tree) {
2938 Type owntype = types.createErrorType(tree.type);
2939 Type atype = attribExpr(tree.indexed, env);
2940 attribExpr(tree.index, env, syms.intType);
2941 if (types.isArray(atype))
2942 owntype = types.elemtype(atype);
2943 else if (!atype.hasTag(ERROR))
2944 log.error(tree.pos(), "array.req.but.found", atype);
2945 if ((pkind() & VAR) == 0) owntype = capture(owntype);
2946 result = check(tree, owntype, VAR, resultInfo);
2947 }
2949 public void visitIdent(JCIdent tree) {
2950 Symbol sym;
2952 // Find symbol
2953 if (pt().hasTag(METHOD) || pt().hasTag(FORALL)) {
2954 // If we are looking for a method, the prototype `pt' will be a
2955 // method type with the type of the call's arguments as parameters.
2956 env.info.pendingResolutionPhase = null;
2957 sym = rs.resolveMethod(tree.pos(), env, tree.name, pt().getParameterTypes(), pt().getTypeArguments());
2958 } else if (tree.sym != null && tree.sym.kind != VAR) {
2959 sym = tree.sym;
2960 } else {
2961 sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind());
2962 }
2963 tree.sym = sym;
2965 // (1) Also find the environment current for the class where
2966 // sym is defined (`symEnv').
2967 // Only for pre-tiger versions (1.4 and earlier):
2968 // (2) Also determine whether we access symbol out of an anonymous
2969 // class in a this or super call. This is illegal for instance
2970 // members since such classes don't carry a this$n link.
2971 // (`noOuterThisPath').
2972 Env<AttrContext> symEnv = env;
2973 boolean noOuterThisPath = false;
2974 if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
2975 (sym.kind & (VAR | MTH | TYP)) != 0 &&
2976 sym.owner.kind == TYP &&
2977 tree.name != names._this && tree.name != names._super) {
2979 // Find environment in which identifier is defined.
2980 while (symEnv.outer != null &&
2981 !sym.isMemberOf(symEnv.enclClass.sym, types)) {
2982 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
2983 noOuterThisPath = !allowAnonOuterThis;
2984 symEnv = symEnv.outer;
2985 }
2986 }
2988 // If symbol is a variable, ...
2989 if (sym.kind == VAR) {
2990 VarSymbol v = (VarSymbol)sym;
2992 // ..., evaluate its initializer, if it has one, and check for
2993 // illegal forward reference.
2994 checkInit(tree, env, v, false);
2996 // If we are expecting a variable (as opposed to a value), check
2997 // that the variable is assignable in the current environment.
2998 if (pkind() == VAR)
2999 checkAssignable(tree.pos(), v, null, env);
3000 }
3002 // In a constructor body,
3003 // if symbol is a field or instance method, check that it is
3004 // not accessed before the supertype constructor is called.
3005 if ((symEnv.info.isSelfCall || noOuterThisPath) &&
3006 (sym.kind & (VAR | MTH)) != 0 &&
3007 sym.owner.kind == TYP &&
3008 (sym.flags() & STATIC) == 0) {
3009 chk.earlyRefError(tree.pos(), sym.kind == VAR ? sym : thisSym(tree.pos(), env));
3010 }
3011 Env<AttrContext> env1 = env;
3012 if (sym.kind != ERR && sym.kind != TYP && sym.owner != null && sym.owner != env1.enclClass.sym) {
3013 // If the found symbol is inaccessible, then it is
3014 // accessed through an enclosing instance. Locate this
3015 // enclosing instance:
3016 while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
3017 env1 = env1.outer;
3018 }
3019 result = checkId(tree, env1.enclClass.sym.type, sym, env, resultInfo);
3020 }
3022 public void visitSelect(JCFieldAccess tree) {
3023 // Determine the expected kind of the qualifier expression.
3024 int skind = 0;
3025 if (tree.name == names._this || tree.name == names._super ||
3026 tree.name == names._class)
3027 {
3028 skind = TYP;
3029 } else {
3030 if ((pkind() & PCK) != 0) skind = skind | PCK;
3031 if ((pkind() & TYP) != 0) skind = skind | TYP | PCK;
3032 if ((pkind() & (VAL | MTH)) != 0) skind = skind | VAL | TYP;
3033 }
3035 // Attribute the qualifier expression, and determine its symbol (if any).
3036 Type site = attribTree(tree.selected, env, new ResultInfo(skind, Infer.anyPoly));
3037 if ((pkind() & (PCK | TYP)) == 0)
3038 site = capture(site); // Capture field access
3040 // don't allow T.class T[].class, etc
3041 if (skind == TYP) {
3042 Type elt = site;
3043 while (elt.hasTag(ARRAY))
3044 elt = ((ArrayType)elt).elemtype;
3045 if (elt.hasTag(TYPEVAR)) {
3046 log.error(tree.pos(), "type.var.cant.be.deref");
3047 result = types.createErrorType(tree.type);
3048 return;
3049 }
3050 }
3052 // If qualifier symbol is a type or `super', assert `selectSuper'
3053 // for the selection. This is relevant for determining whether
3054 // protected symbols are accessible.
3055 Symbol sitesym = TreeInfo.symbol(tree.selected);
3056 boolean selectSuperPrev = env.info.selectSuper;
3057 env.info.selectSuper =
3058 sitesym != null &&
3059 sitesym.name == names._super;
3061 // Determine the symbol represented by the selection.
3062 env.info.pendingResolutionPhase = null;
3063 Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
3064 if (sym.exists() && !isType(sym) && (pkind() & (PCK | TYP)) != 0) {
3065 site = capture(site);
3066 sym = selectSym(tree, sitesym, site, env, resultInfo);
3067 }
3068 boolean varArgs = env.info.lastResolveVarargs();
3069 tree.sym = sym;
3071 if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) {
3072 while (site.hasTag(TYPEVAR)) site = site.getUpperBound();
3073 site = capture(site);
3074 }
3076 // If that symbol is a variable, ...
3077 if (sym.kind == VAR) {
3078 VarSymbol v = (VarSymbol)sym;
3080 // ..., evaluate its initializer, if it has one, and check for
3081 // illegal forward reference.
3082 checkInit(tree, env, v, true);
3084 // If we are expecting a variable (as opposed to a value), check
3085 // that the variable is assignable in the current environment.
3086 if (pkind() == VAR)
3087 checkAssignable(tree.pos(), v, tree.selected, env);
3088 }
3090 if (sitesym != null &&
3091 sitesym.kind == VAR &&
3092 ((VarSymbol)sitesym).isResourceVariable() &&
3093 sym.kind == MTH &&
3094 sym.name.equals(names.close) &&
3095 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) &&
3096 env.info.lint.isEnabled(LintCategory.TRY)) {
3097 log.warning(LintCategory.TRY, tree, "try.explicit.close.call");
3098 }
3100 // Disallow selecting a type from an expression
3101 if (isType(sym) && (sitesym==null || (sitesym.kind&(TYP|PCK)) == 0)) {
3102 tree.type = check(tree.selected, pt(),
3103 sitesym == null ? VAL : sitesym.kind, new ResultInfo(TYP|PCK, pt()));
3104 }
3106 if (isType(sitesym)) {
3107 if (sym.name == names._this) {
3108 // If `C' is the currently compiled class, check that
3109 // C.this' does not appear in a call to a super(...)
3110 if (env.info.isSelfCall &&
3111 site.tsym == env.enclClass.sym) {
3112 chk.earlyRefError(tree.pos(), sym);
3113 }
3114 } else {
3115 // Check if type-qualified fields or methods are static (JLS)
3116 if ((sym.flags() & STATIC) == 0 &&
3117 !env.next.tree.hasTag(REFERENCE) &&
3118 sym.name != names._super &&
3119 (sym.kind == VAR || sym.kind == MTH)) {
3120 rs.accessBase(rs.new StaticError(sym),
3121 tree.pos(), site, sym.name, true);
3122 }
3123 }
3124 } else if (sym.kind != ERR && (sym.flags() & STATIC) != 0 && sym.name != names._class) {
3125 // If the qualified item is not a type and the selected item is static, report
3126 // a warning. Make allowance for the class of an array type e.g. Object[].class)
3127 chk.warnStatic(tree, "static.not.qualified.by.type", Kinds.kindName(sym.kind), sym.owner);
3128 }
3130 // If we are selecting an instance member via a `super', ...
3131 if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
3133 // Check that super-qualified symbols are not abstract (JLS)
3134 rs.checkNonAbstract(tree.pos(), sym);
3136 if (site.isRaw()) {
3137 // Determine argument types for site.
3138 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
3139 if (site1 != null) site = site1;
3140 }
3141 }
3143 env.info.selectSuper = selectSuperPrev;
3144 result = checkId(tree, site, sym, env, resultInfo);
3145 }
3146 //where
3147 /** Determine symbol referenced by a Select expression,
3148 *
3149 * @param tree The select tree.
3150 * @param site The type of the selected expression,
3151 * @param env The current environment.
3152 * @param resultInfo The current result.
3153 */
3154 private Symbol selectSym(JCFieldAccess tree,
3155 Symbol location,
3156 Type site,
3157 Env<AttrContext> env,
3158 ResultInfo resultInfo) {
3159 DiagnosticPosition pos = tree.pos();
3160 Name name = tree.name;
3161 switch (site.getTag()) {
3162 case PACKAGE:
3163 return rs.accessBase(
3164 rs.findIdentInPackage(env, site.tsym, name, resultInfo.pkind),
3165 pos, location, site, name, true);
3166 case ARRAY:
3167 case CLASS:
3168 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) {
3169 return rs.resolveQualifiedMethod(
3170 pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
3171 } else if (name == names._this || name == names._super) {
3172 return rs.resolveSelf(pos, env, site.tsym, name);
3173 } else if (name == names._class) {
3174 // In this case, we have already made sure in
3175 // visitSelect that qualifier expression is a type.
3176 Type t = syms.classType;
3177 List<Type> typeargs = allowGenerics
3178 ? List.of(types.erasure(site))
3179 : List.<Type>nil();
3180 t = new ClassType(t.getEnclosingType(), typeargs, t.tsym);
3181 return new VarSymbol(
3182 STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
3183 } else {
3184 // We are seeing a plain identifier as selector.
3185 Symbol sym = rs.findIdentInType(env, site, name, resultInfo.pkind);
3186 if ((resultInfo.pkind & ERRONEOUS) == 0)
3187 sym = rs.accessBase(sym, pos, location, site, name, true);
3188 return sym;
3189 }
3190 case WILDCARD:
3191 throw new AssertionError(tree);
3192 case TYPEVAR:
3193 // Normally, site.getUpperBound() shouldn't be null.
3194 // It should only happen during memberEnter/attribBase
3195 // when determining the super type which *must* beac
3196 // done before attributing the type variables. In
3197 // other words, we are seeing this illegal program:
3198 // class B<T> extends A<T.foo> {}
3199 Symbol sym = (site.getUpperBound() != null)
3200 ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
3201 : null;
3202 if (sym == null) {
3203 log.error(pos, "type.var.cant.be.deref");
3204 return syms.errSymbol;
3205 } else {
3206 Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
3207 rs.new AccessError(env, site, sym) :
3208 sym;
3209 rs.accessBase(sym2, pos, location, site, name, true);
3210 return sym;
3211 }
3212 case ERROR:
3213 // preserve identifier names through errors
3214 return types.createErrorType(name, site.tsym, site).tsym;
3215 default:
3216 // The qualifier expression is of a primitive type -- only
3217 // .class is allowed for these.
3218 if (name == names._class) {
3219 // In this case, we have already made sure in Select that
3220 // qualifier expression is a type.
3221 Type t = syms.classType;
3222 Type arg = types.boxedClass(site).type;
3223 t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym);
3224 return new VarSymbol(
3225 STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
3226 } else {
3227 log.error(pos, "cant.deref", site);
3228 return syms.errSymbol;
3229 }
3230 }
3231 }
3233 /** Determine type of identifier or select expression and check that
3234 * (1) the referenced symbol is not deprecated
3235 * (2) the symbol's type is safe (@see checkSafe)
3236 * (3) if symbol is a variable, check that its type and kind are
3237 * compatible with the prototype and protokind.
3238 * (4) if symbol is an instance field of a raw type,
3239 * which is being assigned to, issue an unchecked warning if its
3240 * type changes under erasure.
3241 * (5) if symbol is an instance method of a raw type, issue an
3242 * unchecked warning if its argument types change under erasure.
3243 * If checks succeed:
3244 * If symbol is a constant, return its constant type
3245 * else if symbol is a method, return its result type
3246 * otherwise return its type.
3247 * Otherwise return errType.
3248 *
3249 * @param tree The syntax tree representing the identifier
3250 * @param site If this is a select, the type of the selected
3251 * expression, otherwise the type of the current class.
3252 * @param sym The symbol representing the identifier.
3253 * @param env The current environment.
3254 * @param resultInfo The expected result
3255 */
3256 Type checkId(JCTree tree,
3257 Type site,
3258 Symbol sym,
3259 Env<AttrContext> env,
3260 ResultInfo resultInfo) {
3261 return (resultInfo.pt.hasTag(FORALL) || resultInfo.pt.hasTag(METHOD)) ?
3262 checkMethodId(tree, site, sym, env, resultInfo) :
3263 checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
3264 }
3266 Type checkMethodId(JCTree tree,
3267 Type site,
3268 Symbol sym,
3269 Env<AttrContext> env,
3270 ResultInfo resultInfo) {
3271 boolean isPolymorhicSignature =
3272 sym.kind == MTH && ((MethodSymbol)sym.baseSymbol()).isSignaturePolymorphic(types);
3273 return isPolymorhicSignature ?
3274 checkSigPolyMethodId(tree, site, sym, env, resultInfo) :
3275 checkMethodIdInternal(tree, site, sym, env, resultInfo);
3276 }
3278 Type checkSigPolyMethodId(JCTree tree,
3279 Type site,
3280 Symbol sym,
3281 Env<AttrContext> env,
3282 ResultInfo resultInfo) {
3283 //recover original symbol for signature polymorphic methods
3284 checkMethodIdInternal(tree, site, sym.baseSymbol(), env, resultInfo);
3285 env.info.pendingResolutionPhase = Resolve.MethodResolutionPhase.BASIC;
3286 return sym.type;
3287 }
3289 Type checkMethodIdInternal(JCTree tree,
3290 Type site,
3291 Symbol sym,
3292 Env<AttrContext> env,
3293 ResultInfo resultInfo) {
3294 Type pt = resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, sym, env.info.pendingResolutionPhase));
3295 Type owntype = checkIdInternal(tree, site, sym, pt, env, resultInfo);
3296 resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
3297 return owntype;
3298 }
3300 Type checkIdInternal(JCTree tree,
3301 Type site,
3302 Symbol sym,
3303 Type pt,
3304 Env<AttrContext> env,
3305 ResultInfo resultInfo) {
3306 if (pt.isErroneous()) {
3307 return types.createErrorType(site);
3308 }
3309 Type owntype; // The computed type of this identifier occurrence.
3310 switch (sym.kind) {
3311 case TYP:
3312 // For types, the computed type equals the symbol's type,
3313 // except for two situations:
3314 owntype = sym.type;
3315 if (owntype.hasTag(CLASS)) {
3316 chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym);
3317 Type ownOuter = owntype.getEnclosingType();
3319 // (a) If the symbol's type is parameterized, erase it
3320 // because no type parameters were given.
3321 // We recover generic outer type later in visitTypeApply.
3322 if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
3323 owntype = types.erasure(owntype);
3324 }
3326 // (b) If the symbol's type is an inner class, then
3327 // we have to interpret its outer type as a superclass
3328 // of the site type. Example:
3329 //
3330 // class Tree<A> { class Visitor { ... } }
3331 // class PointTree extends Tree<Point> { ... }
3332 // ...PointTree.Visitor...
3333 //
3334 // Then the type of the last expression above is
3335 // Tree<Point>.Visitor.
3336 else if (ownOuter.hasTag(CLASS) && site != ownOuter) {
3337 Type normOuter = site;
3338 if (normOuter.hasTag(CLASS)) {
3339 normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
3340 if (site.getKind() == TypeKind.ANNOTATED) {
3341 // Propagate any type annotations.
3342 // TODO: should asEnclosingSuper do this?
3343 // Note that the type annotations in site will be updated
3344 // by annotateType. Therefore, modify site instead
3345 // of creating a new AnnotatedType.
3346 ((AnnotatedType)site).underlyingType = normOuter;
3347 normOuter = site;
3348 }
3349 }
3350 if (normOuter == null) // perhaps from an import
3351 normOuter = types.erasure(ownOuter);
3352 if (normOuter != ownOuter)
3353 owntype = new ClassType(
3354 normOuter, List.<Type>nil(), owntype.tsym);
3355 }
3356 }
3357 break;
3358 case VAR:
3359 VarSymbol v = (VarSymbol)sym;
3360 // Test (4): if symbol is an instance field of a raw type,
3361 // which is being assigned to, issue an unchecked warning if
3362 // its type changes under erasure.
3363 if (allowGenerics &&
3364 resultInfo.pkind == VAR &&
3365 v.owner.kind == TYP &&
3366 (v.flags() & STATIC) == 0 &&
3367 (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
3368 Type s = types.asOuterSuper(site, v.owner);
3369 if (s != null &&
3370 s.isRaw() &&
3371 !types.isSameType(v.type, v.erasure(types))) {
3372 chk.warnUnchecked(tree.pos(),
3373 "unchecked.assign.to.var",
3374 v, s);
3375 }
3376 }
3377 // The computed type of a variable is the type of the
3378 // variable symbol, taken as a member of the site type.
3379 owntype = (sym.owner.kind == TYP &&
3380 sym.name != names._this && sym.name != names._super)
3381 ? types.memberType(site, sym)
3382 : sym.type;
3384 // If the variable is a constant, record constant value in
3385 // computed type.
3386 if (v.getConstValue() != null && isStaticReference(tree))
3387 owntype = owntype.constType(v.getConstValue());
3389 if (resultInfo.pkind == VAL) {
3390 owntype = capture(owntype); // capture "names as expressions"
3391 }
3392 break;
3393 case MTH: {
3394 owntype = checkMethod(site, sym,
3395 new ResultInfo(VAL, resultInfo.pt.getReturnType(), resultInfo.checkContext),
3396 env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(),
3397 resultInfo.pt.getTypeArguments());
3398 break;
3399 }
3400 case PCK: case ERR:
3401 owntype = sym.type;
3402 break;
3403 default:
3404 throw new AssertionError("unexpected kind: " + sym.kind +
3405 " in tree " + tree);
3406 }
3408 // Test (1): emit a `deprecation' warning if symbol is deprecated.
3409 // (for constructors, the error was given when the constructor was
3410 // resolved)
3412 if (sym.name != names.init) {
3413 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym);
3414 chk.checkSunAPI(tree.pos(), sym);
3415 chk.checkProfile(tree.pos(), sym);
3416 }
3418 // Test (3): if symbol is a variable, check that its type and
3419 // kind are compatible with the prototype and protokind.
3420 return check(tree, owntype, sym.kind, resultInfo);
3421 }
3423 /** Check that variable is initialized and evaluate the variable's
3424 * initializer, if not yet done. Also check that variable is not
3425 * referenced before it is defined.
3426 * @param tree The tree making up the variable reference.
3427 * @param env The current environment.
3428 * @param v The variable's symbol.
3429 */
3430 private void checkInit(JCTree tree,
3431 Env<AttrContext> env,
3432 VarSymbol v,
3433 boolean onlyWarning) {
3434 // System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " +
3435 // tree.pos + " " + v.pos + " " +
3436 // Resolve.isStatic(env));//DEBUG
3438 // A forward reference is diagnosed if the declaration position
3439 // of the variable is greater than the current tree position
3440 // and the tree and variable definition occur in the same class
3441 // definition. Note that writes don't count as references.
3442 // This check applies only to class and instance
3443 // variables. Local variables follow different scope rules,
3444 // and are subject to definite assignment checking.
3445 if ((env.info.enclVar == v || v.pos > tree.pos) &&
3446 v.owner.kind == TYP &&
3447 canOwnInitializer(owner(env)) &&
3448 v.owner == env.info.scope.owner.enclClass() &&
3449 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
3450 (!env.tree.hasTag(ASSIGN) ||
3451 TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
3452 String suffix = (env.info.enclVar == v) ?
3453 "self.ref" : "forward.ref";
3454 if (!onlyWarning || isStaticEnumField(v)) {
3455 log.error(tree.pos(), "illegal." + suffix);
3456 } else if (useBeforeDeclarationWarning) {
3457 log.warning(tree.pos(), suffix, v);
3458 }
3459 }
3461 v.getConstValue(); // ensure initializer is evaluated
3463 checkEnumInitializer(tree, env, v);
3464 }
3466 /**
3467 * Check for illegal references to static members of enum. In
3468 * an enum type, constructors and initializers may not
3469 * reference its static members unless they are constant.
3470 *
3471 * @param tree The tree making up the variable reference.
3472 * @param env The current environment.
3473 * @param v The variable's symbol.
3474 * @jls section 8.9 Enums
3475 */
3476 private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
3477 // JLS:
3478 //
3479 // "It is a compile-time error to reference a static field
3480 // of an enum type that is not a compile-time constant
3481 // (15.28) from constructors, instance initializer blocks,
3482 // or instance variable initializer expressions of that
3483 // type. It is a compile-time error for the constructors,
3484 // instance initializer blocks, or instance variable
3485 // initializer expressions of an enum constant e to refer
3486 // to itself or to an enum constant of the same type that
3487 // is declared to the right of e."
3488 if (isStaticEnumField(v)) {
3489 ClassSymbol enclClass = env.info.scope.owner.enclClass();
3491 if (enclClass == null || enclClass.owner == null)
3492 return;
3494 // See if the enclosing class is the enum (or a
3495 // subclass thereof) declaring v. If not, this
3496 // reference is OK.
3497 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
3498 return;
3500 // If the reference isn't from an initializer, then
3501 // the reference is OK.
3502 if (!Resolve.isInitializer(env))
3503 return;
3505 log.error(tree.pos(), "illegal.enum.static.ref");
3506 }
3507 }
3509 /** Is the given symbol a static, non-constant field of an Enum?
3510 * Note: enum literals should not be regarded as such
3511 */
3512 private boolean isStaticEnumField(VarSymbol v) {
3513 return Flags.isEnum(v.owner) &&
3514 Flags.isStatic(v) &&
3515 !Flags.isConstant(v) &&
3516 v.name != names._class;
3517 }
3519 /** Can the given symbol be the owner of code which forms part
3520 * if class initialization? This is the case if the symbol is
3521 * a type or field, or if the symbol is the synthetic method.
3522 * owning a block.
3523 */
3524 private boolean canOwnInitializer(Symbol sym) {
3525 return
3526 (sym.kind & (VAR | TYP)) != 0 ||
3527 (sym.kind == MTH && (sym.flags() & BLOCK) != 0);
3528 }
3530 Warner noteWarner = new Warner();
3532 /**
3533 * Check that method arguments conform to its instantiation.
3534 **/
3535 public Type checkMethod(Type site,
3536 Symbol sym,
3537 ResultInfo resultInfo,
3538 Env<AttrContext> env,
3539 final List<JCExpression> argtrees,
3540 List<Type> argtypes,
3541 List<Type> typeargtypes) {
3542 // Test (5): if symbol is an instance method of a raw type, issue
3543 // an unchecked warning if its argument types change under erasure.
3544 if (allowGenerics &&
3545 (sym.flags() & STATIC) == 0 &&
3546 (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
3547 Type s = types.asOuterSuper(site, sym.owner);
3548 if (s != null && s.isRaw() &&
3549 !types.isSameTypes(sym.type.getParameterTypes(),
3550 sym.erasure(types).getParameterTypes())) {
3551 chk.warnUnchecked(env.tree.pos(),
3552 "unchecked.call.mbr.of.raw.type",
3553 sym, s);
3554 }
3555 }
3557 if (env.info.defaultSuperCallSite != null) {
3558 for (Type sup : types.interfaces(env.enclClass.type).prepend(types.supertype((env.enclClass.type)))) {
3559 if (!sup.tsym.isSubClass(sym.enclClass(), types) ||
3560 types.isSameType(sup, env.info.defaultSuperCallSite)) continue;
3561 List<MethodSymbol> icand_sup =
3562 types.interfaceCandidates(sup, (MethodSymbol)sym);
3563 if (icand_sup.nonEmpty() &&
3564 icand_sup.head != sym &&
3565 icand_sup.head.overrides(sym, icand_sup.head.enclClass(), types, true)) {
3566 log.error(env.tree.pos(), "illegal.default.super.call", env.info.defaultSuperCallSite,
3567 diags.fragment("overridden.default", sym, sup));
3568 break;
3569 }
3570 }
3571 env.info.defaultSuperCallSite = null;
3572 }
3574 if (sym.isStatic() && site.isInterface()) {
3575 Assert.check(env.tree.hasTag(APPLY));
3576 JCMethodInvocation app = (JCMethodInvocation)env.tree;
3577 if (app.meth.hasTag(SELECT) &&
3578 !TreeInfo.isStaticSelector(((JCFieldAccess)app.meth).selected, names)) {
3579 log.error(env.tree.pos(), "illegal.static.intf.meth.call", site);
3580 }
3581 }
3583 // Compute the identifier's instantiated type.
3584 // For methods, we need to compute the instance type by
3585 // Resolve.instantiate from the symbol's type as well as
3586 // any type arguments and value arguments.
3587 noteWarner.clear();
3588 try {
3589 Type owntype = rs.checkMethod(
3590 env,
3591 site,
3592 sym,
3593 resultInfo,
3594 argtypes,
3595 typeargtypes,
3596 noteWarner);
3598 return chk.checkMethod(owntype, sym, env, argtrees, argtypes, env.info.lastResolveVarargs(),
3599 noteWarner.hasNonSilentLint(LintCategory.UNCHECKED));
3600 } catch (Infer.InferenceException ex) {
3601 //invalid target type - propagate exception outwards or report error
3602 //depending on the current check context
3603 resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic());
3604 return types.createErrorType(site);
3605 } catch (Resolve.InapplicableMethodException ex) {
3606 Assert.error(ex.getDiagnostic().getMessage(Locale.getDefault()));
3607 return null;
3608 }
3609 }
3611 public void visitLiteral(JCLiteral tree) {
3612 result = check(
3613 tree, litType(tree.typetag).constType(tree.value), VAL, resultInfo);
3614 }
3615 //where
3616 /** Return the type of a literal with given type tag.
3617 */
3618 Type litType(TypeTag tag) {
3619 return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()];
3620 }
3622 public void visitTypeIdent(JCPrimitiveTypeTree tree) {
3623 result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], TYP, resultInfo);
3624 }
3626 public void visitTypeArray(JCArrayTypeTree tree) {
3627 Type etype = attribType(tree.elemtype, env);
3628 Type type = new ArrayType(etype, syms.arrayClass);
3629 result = check(tree, type, TYP, resultInfo);
3630 }
3632 /** Visitor method for parameterized types.
3633 * Bound checking is left until later, since types are attributed
3634 * before supertype structure is completely known
3635 */
3636 public void visitTypeApply(JCTypeApply tree) {
3637 Type owntype = types.createErrorType(tree.type);
3639 // Attribute functor part of application and make sure it's a class.
3640 Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
3642 // Attribute type parameters
3643 List<Type> actuals = attribTypes(tree.arguments, env);
3645 if (clazztype.hasTag(CLASS)) {
3646 List<Type> formals = clazztype.tsym.type.getTypeArguments();
3647 if (actuals.isEmpty()) //diamond
3648 actuals = formals;
3650 if (actuals.length() == formals.length()) {
3651 List<Type> a = actuals;
3652 List<Type> f = formals;
3653 while (a.nonEmpty()) {
3654 a.head = a.head.withTypeVar(f.head);
3655 a = a.tail;
3656 f = f.tail;
3657 }
3658 // Compute the proper generic outer
3659 Type clazzOuter = clazztype.getEnclosingType();
3660 if (clazzOuter.hasTag(CLASS)) {
3661 Type site;
3662 JCExpression clazz = TreeInfo.typeIn(tree.clazz);
3663 if (clazz.hasTag(IDENT)) {
3664 site = env.enclClass.sym.type;
3665 } else if (clazz.hasTag(SELECT)) {
3666 site = ((JCFieldAccess) clazz).selected.type;
3667 } else throw new AssertionError(""+tree);
3668 if (clazzOuter.hasTag(CLASS) && site != clazzOuter) {
3669 if (site.hasTag(CLASS))
3670 site = types.asOuterSuper(site, clazzOuter.tsym);
3671 if (site == null)
3672 site = types.erasure(clazzOuter);
3673 clazzOuter = site;
3674 }
3675 }
3676 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym);
3677 } else {
3678 if (formals.length() != 0) {
3679 log.error(tree.pos(), "wrong.number.type.args",
3680 Integer.toString(formals.length()));
3681 } else {
3682 log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym);
3683 }
3684 owntype = types.createErrorType(tree.type);
3685 }
3686 }
3687 result = check(tree, owntype, TYP, resultInfo);
3688 }
3690 public void visitTypeUnion(JCTypeUnion tree) {
3691 ListBuffer<Type> multicatchTypes = ListBuffer.lb();
3692 ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
3693 for (JCExpression typeTree : tree.alternatives) {
3694 Type ctype = attribType(typeTree, env);
3695 ctype = chk.checkType(typeTree.pos(),
3696 chk.checkClassType(typeTree.pos(), ctype),
3697 syms.throwableType);
3698 if (!ctype.isErroneous()) {
3699 //check that alternatives of a union type are pairwise
3700 //unrelated w.r.t. subtyping
3701 if (chk.intersects(ctype, multicatchTypes.toList())) {
3702 for (Type t : multicatchTypes) {
3703 boolean sub = types.isSubtype(ctype, t);
3704 boolean sup = types.isSubtype(t, ctype);
3705 if (sub || sup) {
3706 //assume 'a' <: 'b'
3707 Type a = sub ? ctype : t;
3708 Type b = sub ? t : ctype;
3709 log.error(typeTree.pos(), "multicatch.types.must.be.disjoint", a, b);
3710 }
3711 }
3712 }
3713 multicatchTypes.append(ctype);
3714 if (all_multicatchTypes != null)
3715 all_multicatchTypes.append(ctype);
3716 } else {
3717 if (all_multicatchTypes == null) {
3718 all_multicatchTypes = ListBuffer.lb();
3719 all_multicatchTypes.appendList(multicatchTypes);
3720 }
3721 all_multicatchTypes.append(ctype);
3722 }
3723 }
3724 Type t = check(tree, types.lub(multicatchTypes.toList()), TYP, resultInfo);
3725 if (t.hasTag(CLASS)) {
3726 List<Type> alternatives =
3727 ((all_multicatchTypes == null) ? multicatchTypes : all_multicatchTypes).toList();
3728 t = new UnionClassType((ClassType) t, alternatives);
3729 }
3730 tree.type = result = t;
3731 }
3733 public void visitTypeIntersection(JCTypeIntersection tree) {
3734 attribTypes(tree.bounds, env);
3735 tree.type = result = checkIntersection(tree, tree.bounds);
3736 }
3738 public void visitTypeParameter(JCTypeParameter tree) {
3739 TypeVar typeVar = (TypeVar) tree.type;
3741 if (tree.annotations != null && tree.annotations.nonEmpty()) {
3742 AnnotatedType antype = new AnnotatedType(typeVar);
3743 annotateType(antype, tree.annotations);
3744 tree.type = antype;
3745 }
3747 if (!typeVar.bound.isErroneous()) {
3748 //fixup type-parameter bound computed in 'attribTypeVariables'
3749 typeVar.bound = checkIntersection(tree, tree.bounds);
3750 }
3751 }
3753 Type checkIntersection(JCTree tree, List<JCExpression> bounds) {
3754 Set<Type> boundSet = new HashSet<Type>();
3755 if (bounds.nonEmpty()) {
3756 // accept class or interface or typevar as first bound.
3757 bounds.head.type = checkBase(bounds.head.type, bounds.head, env, false, false, false);
3758 boundSet.add(types.erasure(bounds.head.type));
3759 if (bounds.head.type.isErroneous()) {
3760 return bounds.head.type;
3761 }
3762 else if (bounds.head.type.hasTag(TYPEVAR)) {
3763 // if first bound was a typevar, do not accept further bounds.
3764 if (bounds.tail.nonEmpty()) {
3765 log.error(bounds.tail.head.pos(),
3766 "type.var.may.not.be.followed.by.other.bounds");
3767 return bounds.head.type;
3768 }
3769 } else {
3770 // if first bound was a class or interface, accept only interfaces
3771 // as further bounds.
3772 for (JCExpression bound : bounds.tail) {
3773 bound.type = checkBase(bound.type, bound, env, false, true, false);
3774 if (bound.type.isErroneous()) {
3775 bounds = List.of(bound);
3776 }
3777 else if (bound.type.hasTag(CLASS)) {
3778 chk.checkNotRepeated(bound.pos(), types.erasure(bound.type), boundSet);
3779 }
3780 }
3781 }
3782 }
3784 if (bounds.length() == 0) {
3785 return syms.objectType;
3786 } else if (bounds.length() == 1) {
3787 return bounds.head.type;
3788 } else {
3789 Type owntype = types.makeCompoundType(TreeInfo.types(bounds));
3790 if (tree.hasTag(TYPEINTERSECTION)) {
3791 ((IntersectionClassType)owntype).intersectionKind =
3792 IntersectionClassType.IntersectionKind.EXPLICIT;
3793 }
3794 // ... the variable's bound is a class type flagged COMPOUND
3795 // (see comment for TypeVar.bound).
3796 // In this case, generate a class tree that represents the
3797 // bound class, ...
3798 JCExpression extending;
3799 List<JCExpression> implementing;
3800 if (!bounds.head.type.isInterface()) {
3801 extending = bounds.head;
3802 implementing = bounds.tail;
3803 } else {
3804 extending = null;
3805 implementing = bounds;
3806 }
3807 JCClassDecl cd = make.at(tree).ClassDef(
3808 make.Modifiers(PUBLIC | ABSTRACT),
3809 names.empty, List.<JCTypeParameter>nil(),
3810 extending, implementing, List.<JCTree>nil());
3812 ClassSymbol c = (ClassSymbol)owntype.tsym;
3813 Assert.check((c.flags() & COMPOUND) != 0);
3814 cd.sym = c;
3815 c.sourcefile = env.toplevel.sourcefile;
3817 // ... and attribute the bound class
3818 c.flags_field |= UNATTRIBUTED;
3819 Env<AttrContext> cenv = enter.classEnv(cd, env);
3820 enter.typeEnvs.put(c, cenv);
3821 attribClass(c);
3822 return owntype;
3823 }
3824 }
3826 public void visitWildcard(JCWildcard tree) {
3827 //- System.err.println("visitWildcard("+tree+");");//DEBUG
3828 Type type = (tree.kind.kind == BoundKind.UNBOUND)
3829 ? syms.objectType
3830 : attribType(tree.inner, env);
3831 result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
3832 tree.kind.kind,
3833 syms.boundClass),
3834 TYP, resultInfo);
3835 }
3837 public void visitAnnotation(JCAnnotation tree) {
3838 log.error(tree.pos(), "annotation.not.valid.for.type", pt());
3839 result = tree.type = syms.errType;
3840 }
3842 public void visitAnnotatedType(JCAnnotatedType tree) {
3843 Type underlyingType = attribType(tree.getUnderlyingType(), env);
3844 this.attribAnnotationTypes(tree.annotations, env);
3845 AnnotatedType antype = new AnnotatedType(underlyingType);
3846 annotateType(antype, tree.annotations);
3847 result = tree.type = antype;
3848 }
3850 /**
3851 * Apply the annotations to the particular type.
3852 */
3853 public void annotateType(final AnnotatedType type, final List<JCAnnotation> annotations) {
3854 if (annotations.isEmpty())
3855 return;
3856 annotate.typeAnnotation(new Annotate.Annotator() {
3857 @Override
3858 public String toString() {
3859 return "annotate " + annotations + " onto " + type;
3860 }
3861 @Override
3862 public void enterAnnotation() {
3863 List<Attribute.TypeCompound> compounds = fromAnnotations(annotations);
3864 type.typeAnnotations = compounds;
3865 }
3866 });
3867 }
3869 private static List<Attribute.TypeCompound> fromAnnotations(List<JCAnnotation> annotations) {
3870 if (annotations.isEmpty())
3871 return List.nil();
3873 ListBuffer<Attribute.TypeCompound> buf = ListBuffer.lb();
3874 for (JCAnnotation anno : annotations) {
3875 buf.append((Attribute.TypeCompound) anno.attribute);
3876 }
3877 return buf.toList();
3878 }
3880 public void visitErroneous(JCErroneous tree) {
3881 if (tree.errs != null)
3882 for (JCTree err : tree.errs)
3883 attribTree(err, env, new ResultInfo(ERR, pt()));
3884 result = tree.type = syms.errType;
3885 }
3887 /** Default visitor method for all other trees.
3888 */
3889 public void visitTree(JCTree tree) {
3890 throw new AssertionError();
3891 }
3893 /**
3894 * Attribute an env for either a top level tree or class declaration.
3895 */
3896 public void attrib(Env<AttrContext> env) {
3897 if (env.tree.hasTag(TOPLEVEL))
3898 attribTopLevel(env);
3899 else
3900 attribClass(env.tree.pos(), env.enclClass.sym);
3901 }
3903 /**
3904 * Attribute a top level tree. These trees are encountered when the
3905 * package declaration has annotations.
3906 */
3907 public void attribTopLevel(Env<AttrContext> env) {
3908 JCCompilationUnit toplevel = env.toplevel;
3909 try {
3910 annotate.flush();
3911 chk.validateAnnotations(toplevel.packageAnnotations, toplevel.packge);
3912 } catch (CompletionFailure ex) {
3913 chk.completionError(toplevel.pos(), ex);
3914 }
3915 }
3917 /** Main method: attribute class definition associated with given class symbol.
3918 * reporting completion failures at the given position.
3919 * @param pos The source position at which completion errors are to be
3920 * reported.
3921 * @param c The class symbol whose definition will be attributed.
3922 */
3923 public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
3924 try {
3925 annotate.flush();
3926 attribClass(c);
3927 } catch (CompletionFailure ex) {
3928 chk.completionError(pos, ex);
3929 }
3930 }
3932 /** Attribute class definition associated with given class symbol.
3933 * @param c The class symbol whose definition will be attributed.
3934 */
3935 void attribClass(ClassSymbol c) throws CompletionFailure {
3936 if (c.type.hasTag(ERROR)) return;
3938 // Check for cycles in the inheritance graph, which can arise from
3939 // ill-formed class files.
3940 chk.checkNonCyclic(null, c.type);
3942 Type st = types.supertype(c.type);
3943 if ((c.flags_field & Flags.COMPOUND) == 0) {
3944 // First, attribute superclass.
3945 if (st.hasTag(CLASS))
3946 attribClass((ClassSymbol)st.tsym);
3948 // Next attribute owner, if it is a class.
3949 if (c.owner.kind == TYP && c.owner.type.hasTag(CLASS))
3950 attribClass((ClassSymbol)c.owner);
3951 }
3953 // The previous operations might have attributed the current class
3954 // if there was a cycle. So we test first whether the class is still
3955 // UNATTRIBUTED.
3956 if ((c.flags_field & UNATTRIBUTED) != 0) {
3957 c.flags_field &= ~UNATTRIBUTED;
3959 // Get environment current at the point of class definition.
3960 Env<AttrContext> env = enter.typeEnvs.get(c);
3962 // The info.lint field in the envs stored in enter.typeEnvs is deliberately uninitialized,
3963 // because the annotations were not available at the time the env was created. Therefore,
3964 // we look up the environment chain for the first enclosing environment for which the
3965 // lint value is set. Typically, this is the parent env, but might be further if there
3966 // are any envs created as a result of TypeParameter nodes.
3967 Env<AttrContext> lintEnv = env;
3968 while (lintEnv.info.lint == null)
3969 lintEnv = lintEnv.next;
3971 // Having found the enclosing lint value, we can initialize the lint value for this class
3972 env.info.lint = lintEnv.info.lint.augment(c.annotations, c.flags());
3974 Lint prevLint = chk.setLint(env.info.lint);
3975 JavaFileObject prev = log.useSource(c.sourcefile);
3976 ResultInfo prevReturnRes = env.info.returnResult;
3978 try {
3979 env.info.returnResult = null;
3980 // java.lang.Enum may not be subclassed by a non-enum
3981 if (st.tsym == syms.enumSym &&
3982 ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
3983 log.error(env.tree.pos(), "enum.no.subclassing");
3985 // Enums may not be extended by source-level classes
3986 if (st.tsym != null &&
3987 ((st.tsym.flags_field & Flags.ENUM) != 0) &&
3988 ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0) &&
3989 !target.compilerBootstrap(c)) {
3990 log.error(env.tree.pos(), "enum.types.not.extensible");
3991 }
3992 attribClassBody(env, c);
3994 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
3995 chk.checkClassOverrideEqualsAndHash(c);
3996 } finally {
3997 env.info.returnResult = prevReturnRes;
3998 log.useSource(prev);
3999 chk.setLint(prevLint);
4000 }
4002 }
4003 }
4005 public void visitImport(JCImport tree) {
4006 // nothing to do
4007 }
4009 /** Finish the attribution of a class. */
4010 private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
4011 JCClassDecl tree = (JCClassDecl)env.tree;
4012 Assert.check(c == tree.sym);
4014 // Validate annotations
4015 chk.validateAnnotations(tree.mods.annotations, c);
4017 // Validate type parameters, supertype and interfaces.
4018 attribStats(tree.typarams, env);
4019 if (!c.isAnonymous()) {
4020 //already checked if anonymous
4021 chk.validate(tree.typarams, env);
4022 chk.validate(tree.extending, env);
4023 chk.validate(tree.implementing, env);
4024 }
4026 // If this is a non-abstract class, check that it has no abstract
4027 // methods or unimplemented methods of an implemented interface.
4028 if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
4029 if (!relax)
4030 chk.checkAllDefined(tree.pos(), c);
4031 }
4033 if ((c.flags() & ANNOTATION) != 0) {
4034 if (tree.implementing.nonEmpty())
4035 log.error(tree.implementing.head.pos(),
4036 "cant.extend.intf.annotation");
4037 if (tree.typarams.nonEmpty())
4038 log.error(tree.typarams.head.pos(),
4039 "intf.annotation.cant.have.type.params");
4041 // If this annotation has a @Repeatable, validate
4042 Attribute.Compound repeatable = c.attribute(syms.repeatableType.tsym);
4043 if (repeatable != null) {
4044 // get diagnostic position for error reporting
4045 DiagnosticPosition cbPos = getDiagnosticPosition(tree, repeatable.type);
4046 Assert.checkNonNull(cbPos);
4048 chk.validateRepeatable(c, repeatable, cbPos);
4049 }
4050 } else {
4051 // Check that all extended classes and interfaces
4052 // are compatible (i.e. no two define methods with same arguments
4053 // yet different return types). (JLS 8.4.6.3)
4054 chk.checkCompatibleSupertypes(tree.pos(), c.type);
4055 if (allowDefaultMethods) {
4056 chk.checkDefaultMethodClashes(tree.pos(), c.type);
4057 }
4058 }
4060 // Check that class does not import the same parameterized interface
4061 // with two different argument lists.
4062 chk.checkClassBounds(tree.pos(), c.type);
4064 tree.type = c.type;
4066 for (List<JCTypeParameter> l = tree.typarams;
4067 l.nonEmpty(); l = l.tail) {
4068 Assert.checkNonNull(env.info.scope.lookup(l.head.name).scope);
4069 }
4071 // Check that a generic class doesn't extend Throwable
4072 if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
4073 log.error(tree.extending.pos(), "generic.throwable");
4075 // Check that all methods which implement some
4076 // method conform to the method they implement.
4077 chk.checkImplementations(tree);
4079 //check that a resource implementing AutoCloseable cannot throw InterruptedException
4080 checkAutoCloseable(tree.pos(), env, c.type);
4082 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
4083 // Attribute declaration
4084 attribStat(l.head, env);
4085 // Check that declarations in inner classes are not static (JLS 8.1.2)
4086 // Make an exception for static constants.
4087 if (c.owner.kind != PCK &&
4088 ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
4089 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
4090 Symbol sym = null;
4091 if (l.head.hasTag(VARDEF)) sym = ((JCVariableDecl) l.head).sym;
4092 if (sym == null ||
4093 sym.kind != VAR ||
4094 ((VarSymbol) sym).getConstValue() == null)
4095 log.error(l.head.pos(), "icls.cant.have.static.decl", c);
4096 }
4097 }
4099 // Check for cycles among non-initial constructors.
4100 chk.checkCyclicConstructors(tree);
4102 // Check for cycles among annotation elements.
4103 chk.checkNonCyclicElements(tree);
4105 // Check for proper use of serialVersionUID
4106 if (env.info.lint.isEnabled(LintCategory.SERIAL) &&
4107 isSerializable(c) &&
4108 (c.flags() & Flags.ENUM) == 0 &&
4109 (c.flags() & ABSTRACT) == 0) {
4110 checkSerialVersionUID(tree, c);
4111 }
4113 // Correctly organize the postions of the type annotations
4114 TypeAnnotations.organizeTypeAnnotationsBodies(this.syms, this.names, this.log, tree);
4116 // Check type annotations applicability rules
4117 validateTypeAnnotations(tree);
4118 }
4119 // where
4120 /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
4121 private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
4122 for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
4123 if (types.isSameType(al.head.annotationType.type, t))
4124 return al.head.pos();
4125 }
4127 return null;
4128 }
4130 /** check if a class is a subtype of Serializable, if that is available. */
4131 private boolean isSerializable(ClassSymbol c) {
4132 try {
4133 syms.serializableType.complete();
4134 }
4135 catch (CompletionFailure e) {
4136 return false;
4137 }
4138 return types.isSubtype(c.type, syms.serializableType);
4139 }
4141 /** Check that an appropriate serialVersionUID member is defined. */
4142 private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
4144 // check for presence of serialVersionUID
4145 Scope.Entry e = c.members().lookup(names.serialVersionUID);
4146 while (e.scope != null && e.sym.kind != VAR) e = e.next();
4147 if (e.scope == null) {
4148 log.warning(LintCategory.SERIAL,
4149 tree.pos(), "missing.SVUID", c);
4150 return;
4151 }
4153 // check that it is static final
4154 VarSymbol svuid = (VarSymbol)e.sym;
4155 if ((svuid.flags() & (STATIC | FINAL)) !=
4156 (STATIC | FINAL))
4157 log.warning(LintCategory.SERIAL,
4158 TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c);
4160 // check that it is long
4161 else if (!svuid.type.hasTag(LONG))
4162 log.warning(LintCategory.SERIAL,
4163 TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c);
4165 // check constant
4166 else if (svuid.getConstValue() == null)
4167 log.warning(LintCategory.SERIAL,
4168 TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c);
4169 }
4171 private Type capture(Type type) {
4172 //do not capture free types
4173 return resultInfo.checkContext.inferenceContext().free(type) ?
4174 type : types.capture(type);
4175 }
4177 private void validateTypeAnnotations(JCTree tree) {
4178 tree.accept(typeAnnotationsValidator);
4179 }
4180 //where
4181 private final JCTree.Visitor typeAnnotationsValidator =
4182 new TreeScanner() {
4183 public void visitAnnotation(JCAnnotation tree) {
4184 if (tree.hasTag(TYPE_ANNOTATION)) {
4185 // TODO: It seems to WMD as if the annotation in
4186 // parameters, in particular also the recvparam, are never
4187 // of type JCTypeAnnotation and therefore never checked!
4188 // Luckily this check doesn't really do anything that isn't
4189 // also done elsewhere.
4190 chk.validateTypeAnnotation(tree, false);
4191 }
4192 super.visitAnnotation(tree);
4193 }
4194 public void visitTypeParameter(JCTypeParameter tree) {
4195 chk.validateTypeAnnotations(tree.annotations, true);
4196 scan(tree.bounds);
4197 // Don't call super.
4198 // This is needed because above we call validateTypeAnnotation with
4199 // false, which would forbid annotations on type parameters.
4200 // super.visitTypeParameter(tree);
4201 }
4202 public void visitMethodDef(JCMethodDecl tree) {
4203 // Static methods cannot have receiver type annotations.
4204 // In test case FailOver15.java, the nested method getString has
4205 // a null sym, because an unknown class is instantiated.
4206 // I would say it's safe to skip.
4207 if (tree.sym != null && (tree.sym.flags() & Flags.STATIC) != 0) {
4208 if (tree.recvparam != null) {
4209 // TODO: better error message. Is the pos good?
4210 log.error(tree.recvparam.pos(), "annotation.type.not.applicable");
4211 }
4212 }
4213 if (tree.restype != null && tree.restype.type != null) {
4214 validateAnnotatedType(tree.restype, tree.restype.type);
4215 }
4216 super.visitMethodDef(tree);
4217 }
4218 public void visitVarDef(final JCVariableDecl tree) {
4219 if (tree.sym != null && tree.sym.type != null)
4220 validateAnnotatedType(tree, tree.sym.type);
4221 super.visitVarDef(tree);
4222 }
4223 public void visitTypeCast(JCTypeCast tree) {
4224 if (tree.clazz != null && tree.clazz.type != null)
4225 validateAnnotatedType(tree.clazz, tree.clazz.type);
4226 super.visitTypeCast(tree);
4227 }
4228 public void visitTypeTest(JCInstanceOf tree) {
4229 if (tree.clazz != null && tree.clazz.type != null)
4230 validateAnnotatedType(tree.clazz, tree.clazz.type);
4231 super.visitTypeTest(tree);
4232 }
4233 // TODO: what else do we need?
4234 // public void visitNewClass(JCNewClass tree) {
4235 // public void visitNewArray(JCNewArray tree) {
4237 /* I would want to model this after
4238 * com.sun.tools.javac.comp.Check.Validator.visitSelectInternal(JCFieldAccess)
4239 * and override visitSelect and visitTypeApply.
4240 * However, we only set the annotated type in the top-level type
4241 * of the symbol.
4242 * Therefore, we need to override each individual location where a type
4243 * can occur.
4244 */
4245 private void validateAnnotatedType(final JCTree errtree, final Type type) {
4246 if (type.getEnclosingType() != null &&
4247 type != type.getEnclosingType()) {
4248 validateEnclosingAnnotatedType(errtree, type.getEnclosingType());
4249 }
4250 for (Type targ : type.getTypeArguments()) {
4251 validateAnnotatedType(errtree, targ);
4252 }
4253 }
4254 private void validateEnclosingAnnotatedType(final JCTree errtree, final Type type) {
4255 validateAnnotatedType(errtree, type);
4256 if (type.tsym != null &&
4257 type.tsym.isStatic() &&
4258 type.getAnnotations().nonEmpty()) {
4259 // Enclosing static classes cannot have type annotations.
4260 log.error(errtree.pos(), "cant.annotate.static.class");
4261 }
4262 }
4263 };
4265 // <editor-fold desc="post-attribution visitor">
4267 /**
4268 * Handle missing types/symbols in an AST. This routine is useful when
4269 * the compiler has encountered some errors (which might have ended up
4270 * terminating attribution abruptly); if the compiler is used in fail-over
4271 * mode (e.g. by an IDE) and the AST contains semantic errors, this routine
4272 * prevents NPE to be progagated during subsequent compilation steps.
4273 */
4274 public void postAttr(JCTree tree) {
4275 new PostAttrAnalyzer().scan(tree);
4276 }
4278 class PostAttrAnalyzer extends TreeScanner {
4280 private void initTypeIfNeeded(JCTree that) {
4281 if (that.type == null) {
4282 that.type = syms.unknownType;
4283 }
4284 }
4286 @Override
4287 public void scan(JCTree tree) {
4288 if (tree == null) return;
4289 if (tree instanceof JCExpression) {
4290 initTypeIfNeeded(tree);
4291 }
4292 super.scan(tree);
4293 }
4295 @Override
4296 public void visitIdent(JCIdent that) {
4297 if (that.sym == null) {
4298 that.sym = syms.unknownSymbol;
4299 }
4300 }
4302 @Override
4303 public void visitSelect(JCFieldAccess that) {
4304 if (that.sym == null) {
4305 that.sym = syms.unknownSymbol;
4306 }
4307 super.visitSelect(that);
4308 }
4310 @Override
4311 public void visitClassDef(JCClassDecl that) {
4312 initTypeIfNeeded(that);
4313 if (that.sym == null) {
4314 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol);
4315 }
4316 super.visitClassDef(that);
4317 }
4319 @Override
4320 public void visitMethodDef(JCMethodDecl that) {
4321 initTypeIfNeeded(that);
4322 if (that.sym == null) {
4323 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol);
4324 }
4325 super.visitMethodDef(that);
4326 }
4328 @Override
4329 public void visitVarDef(JCVariableDecl that) {
4330 initTypeIfNeeded(that);
4331 if (that.sym == null) {
4332 that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol);
4333 that.sym.adr = 0;
4334 }
4335 super.visitVarDef(that);
4336 }
4338 @Override
4339 public void visitNewClass(JCNewClass that) {
4340 if (that.constructor == null) {
4341 that.constructor = new MethodSymbol(0, names.init, syms.unknownType, syms.noSymbol);
4342 }
4343 if (that.constructorType == null) {
4344 that.constructorType = syms.unknownType;
4345 }
4346 super.visitNewClass(that);
4347 }
4349 @Override
4350 public void visitAssignop(JCAssignOp that) {
4351 if (that.operator == null)
4352 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
4353 super.visitAssignop(that);
4354 }
4356 @Override
4357 public void visitBinary(JCBinary that) {
4358 if (that.operator == null)
4359 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
4360 super.visitBinary(that);
4361 }
4363 @Override
4364 public void visitUnary(JCUnary that) {
4365 if (that.operator == null)
4366 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
4367 super.visitUnary(that);
4368 }
4370 @Override
4371 public void visitLambda(JCLambda that) {
4372 super.visitLambda(that);
4373 if (that.descriptorType == null) {
4374 that.descriptorType = syms.unknownType;
4375 }
4376 if (that.targets == null) {
4377 that.targets = List.nil();
4378 }
4379 }
4381 @Override
4382 public void visitReference(JCMemberReference that) {
4383 super.visitReference(that);
4384 if (that.sym == null) {
4385 that.sym = new MethodSymbol(0, names.empty, syms.unknownType, syms.noSymbol);
4386 }
4387 if (that.descriptorType == null) {
4388 that.descriptorType = syms.unknownType;
4389 }
4390 if (that.targets == null) {
4391 that.targets = List.nil();
4392 }
4393 }
4394 }
4395 // </editor-fold>
4396 }