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