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