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