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