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