1 /* 2 * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package com.sun.tools.javac.comp; 27 28 import java.util.*; 29 import java.util.function.BiConsumer; 30 import java.util.function.Consumer; 31 import java.util.stream.Stream; 32 33 import javax.lang.model.element.ElementKind; 34 import javax.tools.JavaFileObject; 35 36 import com.sun.source.tree.CaseTree; 37 import com.sun.source.tree.IdentifierTree; 38 import com.sun.source.tree.MemberReferenceTree.ReferenceMode; 39 import com.sun.source.tree.MemberSelectTree; 40 import com.sun.source.tree.TreeVisitor; 41 import com.sun.source.util.SimpleTreeVisitor; 42 import com.sun.tools.javac.code.*; 43 import com.sun.tools.javac.code.Lint.LintCategory; 44 import com.sun.tools.javac.code.Scope.WriteableScope; 45 import com.sun.tools.javac.code.Source.Feature; 46 import com.sun.tools.javac.code.Symbol.*; 47 import com.sun.tools.javac.code.Type.*; 48 import com.sun.tools.javac.code.Types.FunctionDescriptorLookupError; 49 import com.sun.tools.javac.comp.ArgumentAttr.LocalCacheContext; 50 import com.sun.tools.javac.comp.Check.CheckContext; 51 import com.sun.tools.javac.comp.DeferredAttr.AttrMode; 52 import com.sun.tools.javac.comp.MatchBindingsComputer.MatchBindings; 53 import com.sun.tools.javac.jvm.*; 54 55 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.Diamond; 56 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.DiamondInvalidArg; 57 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.DiamondInvalidArgs; 58 59 import com.sun.tools.javac.resources.CompilerProperties.Errors; 60 import com.sun.tools.javac.resources.CompilerProperties.Fragments; 61 import com.sun.tools.javac.resources.CompilerProperties.Warnings; 62 import com.sun.tools.javac.tree.*; 63 import com.sun.tools.javac.tree.JCTree.*; 64 import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*; 65 import com.sun.tools.javac.util.*; 66 import com.sun.tools.javac.util.DefinedBy.Api; 67 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; 68 import com.sun.tools.javac.util.JCDiagnostic.Error; 69 import com.sun.tools.javac.util.JCDiagnostic.Fragment; 70 import com.sun.tools.javac.util.JCDiagnostic.Warning; 71 import com.sun.tools.javac.util.List; 72 73 import static com.sun.tools.javac.code.Flags.*; 74 import static com.sun.tools.javac.code.Flags.ANNOTATION; 75 import static com.sun.tools.javac.code.Flags.BLOCK; 76 import static com.sun.tools.javac.code.Kinds.*; 77 import static com.sun.tools.javac.code.Kinds.Kind.*; 78 import static com.sun.tools.javac.code.TypeTag.*; 79 import static com.sun.tools.javac.code.TypeTag.WILDCARD; 80 import static com.sun.tools.javac.tree.JCTree.Tag.*; 81 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag; 82 83 /** This is the main context-dependent analysis phase in GJC. It 84 * encompasses name resolution, type checking and constant folding as 85 * subtasks. Some subtasks involve auxiliary classes. 86 * @see Check 87 * @see Resolve 88 * @see ConstFold 89 * @see Infer 90 * 91 * <p><b>This is NOT part of any supported API. 92 * If you write code that depends on this, you do so at your own risk. 93 * This code and its internal interfaces are subject to change or 94 * deletion without notice.</b> 95 */ 96 public class Attr extends JCTree.Visitor { 97 protected static final Context.Key<Attr> attrKey = new Context.Key<>(); 98 99 final Names names; 100 final Log log; 101 final Symtab syms; 102 final Resolve rs; 103 final Operators operators; 104 final Infer infer; 105 final Analyzer analyzer; 106 final DeferredAttr deferredAttr; 107 final Check chk; 108 final Flow flow; 109 final MemberEnter memberEnter; 110 final TypeEnter typeEnter; 111 final TreeMaker make; 112 final ConstFold cfolder; 113 final Enter enter; 114 final Target target; 115 final Types types; 116 final Preview preview; 117 final JCDiagnostic.Factory diags; 118 final TypeAnnotations typeAnnotations; 119 final DeferredLintHandler deferredLintHandler; 120 final TypeEnvs typeEnvs; 121 final Dependencies dependencies; 122 final Annotate annotate; 123 final ArgumentAttr argumentAttr; 124 final MatchBindingsComputer matchBindingsComputer; 125 final AttrRecover attrRecover; 126 127 public static Attr instance(Context context) { 128 Attr instance = context.get(attrKey); 129 if (instance == null) 130 instance = new Attr(context); 131 return instance; 132 } 133 134 @SuppressWarnings("this-escape") 135 protected Attr(Context context) { 136 context.put(attrKey, this); 137 138 names = Names.instance(context); 139 log = Log.instance(context); 140 syms = Symtab.instance(context); 141 rs = Resolve.instance(context); 142 operators = Operators.instance(context); 143 chk = Check.instance(context); 144 flow = Flow.instance(context); 145 memberEnter = MemberEnter.instance(context); 146 typeEnter = TypeEnter.instance(context); 147 make = TreeMaker.instance(context); 148 enter = Enter.instance(context); 149 infer = Infer.instance(context); 150 analyzer = Analyzer.instance(context); 151 deferredAttr = DeferredAttr.instance(context); 152 cfolder = ConstFold.instance(context); 153 target = Target.instance(context); 154 types = Types.instance(context); 155 preview = Preview.instance(context); 156 diags = JCDiagnostic.Factory.instance(context); 157 annotate = Annotate.instance(context); 158 typeAnnotations = TypeAnnotations.instance(context); 159 deferredLintHandler = DeferredLintHandler.instance(context); 160 typeEnvs = TypeEnvs.instance(context); 161 dependencies = Dependencies.instance(context); 162 argumentAttr = ArgumentAttr.instance(context); 163 matchBindingsComputer = MatchBindingsComputer.instance(context); 164 attrRecover = AttrRecover.instance(context); 165 166 Options options = Options.instance(context); 167 168 Source source = Source.instance(context); 169 allowReifiableTypesInInstanceof = Feature.REIFIABLE_TYPES_INSTANCEOF.allowedInSource(source); 170 allowRecords = Feature.RECORDS.allowedInSource(source); 171 allowPatternSwitch = (preview.isEnabled() || !preview.isPreview(Feature.PATTERN_SWITCH)) && 172 Feature.PATTERN_SWITCH.allowedInSource(source); 173 allowUnconditionalPatternsInstanceOf = 174 Feature.UNCONDITIONAL_PATTERN_IN_INSTANCEOF.allowedInSource(source); 175 sourceName = source.name; 176 useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning"); 177 178 statInfo = new ResultInfo(KindSelector.NIL, Type.noType); 179 varAssignmentInfo = new ResultInfo(KindSelector.ASG, Type.noType); 180 unknownExprInfo = new ResultInfo(KindSelector.VAL, Type.noType); 181 methodAttrInfo = new MethodAttrInfo(); 182 unknownTypeInfo = new ResultInfo(KindSelector.TYP, Type.noType); 183 unknownTypeExprInfo = new ResultInfo(KindSelector.VAL_TYP, Type.noType); 184 recoveryInfo = new RecoveryInfo(deferredAttr.emptyDeferredAttrContext); 185 } 186 187 /** Switch: reifiable types in instanceof enabled? 188 */ 189 boolean allowReifiableTypesInInstanceof; 190 191 /** Are records allowed 192 */ 193 private final boolean allowRecords; 194 195 /** Are patterns in switch allowed 196 */ 197 private final boolean allowPatternSwitch; 198 199 /** Are unconditional patterns in instanceof allowed 200 */ 201 private final boolean allowUnconditionalPatternsInstanceOf; 202 203 /** 204 * Switch: warn about use of variable before declaration? 205 * RFE: 6425594 206 */ 207 boolean useBeforeDeclarationWarning; 208 209 /** 210 * Switch: name of source level; used for error reporting. 211 */ 212 String sourceName; 213 214 /** Check kind and type of given tree against protokind and prototype. 215 * If check succeeds, store type in tree and return it. 216 * If check fails, store errType in tree and return it. 217 * No checks are performed if the prototype is a method type. 218 * It is not necessary in this case since we know that kind and type 219 * are correct. 220 * 221 * @param tree The tree whose kind and type is checked 222 * @param found The computed type of the tree 223 * @param ownkind The computed kind of the tree 224 * @param resultInfo The expected result of the tree 225 */ 226 Type check(final JCTree tree, 227 final Type found, 228 final KindSelector ownkind, 229 final ResultInfo resultInfo) { 230 InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext(); 231 Type owntype; 232 boolean shouldCheck = !found.hasTag(ERROR) && 233 !resultInfo.pt.hasTag(METHOD) && 234 !resultInfo.pt.hasTag(FORALL); 235 if (shouldCheck && !ownkind.subset(resultInfo.pkind)) { 236 log.error(tree.pos(), 237 Errors.UnexpectedType(resultInfo.pkind.kindNames(), 238 ownkind.kindNames())); 239 owntype = types.createErrorType(found); 240 } else if (inferenceContext.free(found)) { 241 //delay the check if there are inference variables in the found type 242 //this means we are dealing with a partially inferred poly expression 243 owntype = shouldCheck ? resultInfo.pt : found; 244 if (resultInfo.checkMode.installPostInferenceHook()) { 245 inferenceContext.addFreeTypeListener(List.of(found), 246 instantiatedContext -> { 247 ResultInfo pendingResult = 248 resultInfo.dup(inferenceContext.asInstType(resultInfo.pt)); 249 check(tree, inferenceContext.asInstType(found), ownkind, pendingResult); 250 }); 251 } 252 } else { 253 owntype = shouldCheck ? 254 resultInfo.check(tree, found) : 255 found; 256 } 257 if (resultInfo.checkMode.updateTreeType()) { 258 tree.type = owntype; 259 } 260 return owntype; 261 } 262 263 /** Is given blank final variable assignable, i.e. in a scope where it 264 * may be assigned to even though it is final? 265 * @param v The blank final variable. 266 * @param env The current environment. 267 */ 268 boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) { 269 Symbol owner = env.info.scope.owner; 270 // owner refers to the innermost variable, method or 271 // initializer block declaration at this point. 272 boolean isAssignable = 273 v.owner == owner 274 || 275 ((owner.name == names.init || // i.e. we are in a constructor 276 owner.kind == VAR || // i.e. we are in a variable initializer 277 (owner.flags() & BLOCK) != 0) // i.e. we are in an initializer block 278 && 279 v.owner == owner.owner 280 && 281 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env)); 282 boolean insideCompactConstructor = env.enclMethod != null && TreeInfo.isCompactConstructor(env.enclMethod); 283 return isAssignable & !insideCompactConstructor; 284 } 285 286 /** Check that variable can be assigned to. 287 * @param pos The current source code position. 288 * @param v The assigned variable 289 * @param base If the variable is referred to in a Select, the part 290 * to the left of the `.', null otherwise. 291 * @param env The current environment. 292 */ 293 void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) { 294 if (v.name == names._this) { 295 log.error(pos, Errors.CantAssignValToThis); 296 } else if ((v.flags() & FINAL) != 0 && 297 ((v.flags() & HASINIT) != 0 298 || 299 !((base == null || 300 TreeInfo.isThisQualifier(base)) && 301 isAssignableAsBlankFinal(v, env)))) { 302 if (v.isResourceVariable()) { //TWR resource 303 log.error(pos, Errors.TryResourceMayNotBeAssigned(v)); 304 } else { 305 log.error(pos, Errors.CantAssignValToVar(Flags.toSource(v.flags() & (STATIC | FINAL)), v)); 306 } 307 } 308 309 if (!env.info.ctorPrologue && 310 v.owner.isValueClass() && 311 !env.info.instanceInitializerBlock && // it is OK instance initializer blocks will go after super() anyways 312 v.owner.kind == TYP && 313 v.owner == env.enclClass.sym && 314 (v.flags() & STATIC) == 0 && 315 (base == null || 316 TreeInfo.isExplicitThisReference(types, (ClassType)env.enclClass.type, base))) { 317 log.error(pos, Errors.CantRefAfterCtorCalled(v)); 318 } 319 } 320 321 /** Does tree represent a static reference to an identifier? 322 * It is assumed that tree is either a SELECT or an IDENT. 323 * We have to weed out selects from non-type names here. 324 * @param tree The candidate tree. 325 */ 326 boolean isStaticReference(JCTree tree) { 327 if (tree.hasTag(SELECT)) { 328 Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected); 329 if (lsym == null || lsym.kind != TYP) { 330 return false; 331 } 332 } 333 return true; 334 } 335 336 /** Is this symbol a type? 337 */ 338 static boolean isType(Symbol sym) { 339 return sym != null && sym.kind == TYP; 340 } 341 342 /** The current `this' symbol. 343 * @param env The current environment. 344 */ 345 Symbol thisSym(DiagnosticPosition pos, Env<AttrContext> env) { 346 return rs.resolveSelf(pos, env, env.enclClass.sym, names._this); 347 } 348 349 /** Attribute a parsed identifier. 350 * @param tree Parsed identifier name 351 * @param topLevel The toplevel to use 352 */ 353 public Symbol attribIdent(JCTree tree, JCCompilationUnit topLevel) { 354 Env<AttrContext> localEnv = enter.topLevelEnv(topLevel); 355 localEnv.enclClass = make.ClassDef(make.Modifiers(0), 356 syms.errSymbol.name, 357 null, null, null, null); 358 localEnv.enclClass.sym = syms.errSymbol; 359 return attribIdent(tree, localEnv); 360 } 361 362 /** Attribute a parsed identifier. 363 * @param tree Parsed identifier name 364 * @param env The env to use 365 */ 366 public Symbol attribIdent(JCTree tree, Env<AttrContext> env) { 367 return tree.accept(identAttributer, env); 368 } 369 // where 370 private TreeVisitor<Symbol,Env<AttrContext>> identAttributer = new IdentAttributer(); 371 private class IdentAttributer extends SimpleTreeVisitor<Symbol,Env<AttrContext>> { 372 @Override @DefinedBy(Api.COMPILER_TREE) 373 public Symbol visitMemberSelect(MemberSelectTree node, Env<AttrContext> env) { 374 Symbol site = visit(node.getExpression(), env); 375 if (site.kind == ERR || site.kind == ABSENT_TYP || site.kind == HIDDEN) 376 return site; 377 Name name = (Name)node.getIdentifier(); 378 if (site.kind == PCK) { 379 env.toplevel.packge = (PackageSymbol)site; 380 return rs.findIdentInPackage(null, env, (TypeSymbol)site, name, 381 KindSelector.TYP_PCK); 382 } else { 383 env.enclClass.sym = (ClassSymbol)site; 384 return rs.findMemberType(env, site.asType(), name, (TypeSymbol)site); 385 } 386 } 387 388 @Override @DefinedBy(Api.COMPILER_TREE) 389 public Symbol visitIdentifier(IdentifierTree node, Env<AttrContext> env) { 390 return rs.findIdent(null, env, (Name)node.getName(), KindSelector.TYP_PCK); 391 } 392 } 393 394 public Type coerce(Type etype, Type ttype) { 395 return cfolder.coerce(etype, ttype); 396 } 397 398 public Type attribType(JCTree node, TypeSymbol sym) { 399 Env<AttrContext> env = typeEnvs.get(sym); 400 Env<AttrContext> localEnv = env.dup(node, env.info.dup()); 401 return attribTree(node, localEnv, unknownTypeInfo); 402 } 403 404 public Type attribImportQualifier(JCImport tree, Env<AttrContext> env) { 405 // Attribute qualifying package or class. 406 JCFieldAccess s = tree.qualid; 407 return attribTree(s.selected, env, 408 new ResultInfo(tree.staticImport ? 409 KindSelector.TYP : KindSelector.TYP_PCK, 410 Type.noType)); 411 } 412 413 public Env<AttrContext> attribExprToTree(JCTree expr, Env<AttrContext> env, JCTree tree) { 414 return attribToTree(expr, env, tree, unknownExprInfo); 415 } 416 417 public Env<AttrContext> attribStatToTree(JCTree stmt, Env<AttrContext> env, JCTree tree) { 418 return attribToTree(stmt, env, tree, statInfo); 419 } 420 421 private Env<AttrContext> attribToTree(JCTree root, Env<AttrContext> env, JCTree tree, ResultInfo resultInfo) { 422 breakTree = tree; 423 JavaFileObject prev = log.useSource(env.toplevel.sourcefile); 424 try { 425 deferredAttr.attribSpeculative(root, env, resultInfo, 426 null, DeferredAttr.AttributionMode.ATTRIB_TO_TREE, 427 argumentAttr.withLocalCacheContext()); 428 attrRecover.doRecovery(); 429 } catch (BreakAttr b) { 430 return b.env; 431 } catch (AssertionError ae) { 432 if (ae.getCause() instanceof BreakAttr breakAttr) { 433 return breakAttr.env; 434 } else { 435 throw ae; 436 } 437 } finally { 438 breakTree = null; 439 log.useSource(prev); 440 } 441 return env; 442 } 443 444 private JCTree breakTree = null; 445 446 private static class BreakAttr extends RuntimeException { 447 static final long serialVersionUID = -6924771130405446405L; 448 private transient Env<AttrContext> env; 449 private BreakAttr(Env<AttrContext> env) { 450 this.env = env; 451 } 452 } 453 454 /** 455 * Mode controlling behavior of Attr.Check 456 */ 457 enum CheckMode { 458 459 NORMAL, 460 461 /** 462 * Mode signalling 'fake check' - skip tree update. A side-effect of this mode is 463 * that the captured var cache in {@code InferenceContext} will be used in read-only 464 * mode when performing inference checks. 465 */ 466 NO_TREE_UPDATE { 467 @Override 468 public boolean updateTreeType() { 469 return false; 470 } 471 }, 472 /** 473 * Mode signalling that caller will manage free types in tree decorations. 474 */ 475 NO_INFERENCE_HOOK { 476 @Override 477 public boolean installPostInferenceHook() { 478 return false; 479 } 480 }; 481 482 public boolean updateTreeType() { 483 return true; 484 } 485 public boolean installPostInferenceHook() { 486 return true; 487 } 488 } 489 490 491 class ResultInfo { 492 final KindSelector pkind; 493 final Type pt; 494 final CheckContext checkContext; 495 final CheckMode checkMode; 496 497 ResultInfo(KindSelector pkind, Type pt) { 498 this(pkind, pt, chk.basicHandler, CheckMode.NORMAL); 499 } 500 501 ResultInfo(KindSelector pkind, Type pt, CheckMode checkMode) { 502 this(pkind, pt, chk.basicHandler, checkMode); 503 } 504 505 protected ResultInfo(KindSelector pkind, 506 Type pt, CheckContext checkContext) { 507 this(pkind, pt, checkContext, CheckMode.NORMAL); 508 } 509 510 protected ResultInfo(KindSelector pkind, 511 Type pt, CheckContext checkContext, CheckMode checkMode) { 512 this.pkind = pkind; 513 this.pt = pt; 514 this.checkContext = checkContext; 515 this.checkMode = checkMode; 516 } 517 518 /** 519 * Should {@link Attr#attribTree} use the {@code ArgumentAttr} visitor instead of this one? 520 * @param tree The tree to be type-checked. 521 * @return true if {@code ArgumentAttr} should be used. 522 */ 523 protected boolean needsArgumentAttr(JCTree tree) { return false; } 524 525 protected Type check(final DiagnosticPosition pos, final Type found) { 526 return chk.checkType(pos, found, pt, checkContext); 527 } 528 529 protected ResultInfo dup(Type newPt) { 530 return new ResultInfo(pkind, newPt, checkContext, checkMode); 531 } 532 533 protected ResultInfo dup(CheckContext newContext) { 534 return new ResultInfo(pkind, pt, newContext, checkMode); 535 } 536 537 protected ResultInfo dup(Type newPt, CheckContext newContext) { 538 return new ResultInfo(pkind, newPt, newContext, checkMode); 539 } 540 541 protected ResultInfo dup(Type newPt, CheckContext newContext, CheckMode newMode) { 542 return new ResultInfo(pkind, newPt, newContext, newMode); 543 } 544 545 protected ResultInfo dup(CheckMode newMode) { 546 return new ResultInfo(pkind, pt, checkContext, newMode); 547 } 548 549 @Override 550 public String toString() { 551 if (pt != null) { 552 return pt.toString(); 553 } else { 554 return ""; 555 } 556 } 557 } 558 559 class MethodAttrInfo extends ResultInfo { 560 public MethodAttrInfo() { 561 this(chk.basicHandler); 562 } 563 564 public MethodAttrInfo(CheckContext checkContext) { 565 super(KindSelector.VAL, Infer.anyPoly, checkContext); 566 } 567 568 @Override 569 protected boolean needsArgumentAttr(JCTree tree) { 570 return true; 571 } 572 573 protected ResultInfo dup(Type newPt) { 574 throw new IllegalStateException(); 575 } 576 577 protected ResultInfo dup(CheckContext newContext) { 578 return new MethodAttrInfo(newContext); 579 } 580 581 protected ResultInfo dup(Type newPt, CheckContext newContext) { 582 throw new IllegalStateException(); 583 } 584 585 protected ResultInfo dup(Type newPt, CheckContext newContext, CheckMode newMode) { 586 throw new IllegalStateException(); 587 } 588 589 protected ResultInfo dup(CheckMode newMode) { 590 throw new IllegalStateException(); 591 } 592 } 593 594 class RecoveryInfo extends ResultInfo { 595 596 public RecoveryInfo(final DeferredAttr.DeferredAttrContext deferredAttrContext) { 597 this(deferredAttrContext, Type.recoveryType); 598 } 599 600 public RecoveryInfo(final DeferredAttr.DeferredAttrContext deferredAttrContext, Type pt) { 601 super(KindSelector.VAL, pt, new Check.NestedCheckContext(chk.basicHandler) { 602 @Override 603 public DeferredAttr.DeferredAttrContext deferredAttrContext() { 604 return deferredAttrContext; 605 } 606 @Override 607 public boolean compatible(Type found, Type req, Warner warn) { 608 return true; 609 } 610 @Override 611 public void report(DiagnosticPosition pos, JCDiagnostic details) { 612 boolean needsReport = pt == Type.recoveryType || 613 (details.getDiagnosticPosition() != null && 614 details.getDiagnosticPosition().getTree().hasTag(LAMBDA)); 615 if (needsReport) { 616 chk.basicHandler.report(pos, details); 617 } 618 } 619 }); 620 } 621 } 622 623 final ResultInfo statInfo; 624 final ResultInfo varAssignmentInfo; 625 final ResultInfo methodAttrInfo; 626 final ResultInfo unknownExprInfo; 627 final ResultInfo unknownTypeInfo; 628 final ResultInfo unknownTypeExprInfo; 629 final ResultInfo recoveryInfo; 630 631 Type pt() { 632 return resultInfo.pt; 633 } 634 635 KindSelector pkind() { 636 return resultInfo.pkind; 637 } 638 639 /* ************************************************************************ 640 * Visitor methods 641 *************************************************************************/ 642 643 /** Visitor argument: the current environment. 644 */ 645 Env<AttrContext> env; 646 647 /** Visitor argument: the currently expected attribution result. 648 */ 649 ResultInfo resultInfo; 650 651 /** Visitor result: the computed type. 652 */ 653 Type result; 654 655 MatchBindings matchBindings = MatchBindingsComputer.EMPTY; 656 657 /** Visitor method: attribute a tree, catching any completion failure 658 * exceptions. Return the tree's type. 659 * 660 * @param tree The tree to be visited. 661 * @param env The environment visitor argument. 662 * @param resultInfo The result info visitor argument. 663 */ 664 Type attribTree(JCTree tree, Env<AttrContext> env, ResultInfo resultInfo) { 665 Env<AttrContext> prevEnv = this.env; 666 ResultInfo prevResult = this.resultInfo; 667 try { 668 this.env = env; 669 this.resultInfo = resultInfo; 670 if (resultInfo.needsArgumentAttr(tree)) { 671 result = argumentAttr.attribArg(tree, env); 672 } else { 673 tree.accept(this); 674 } 675 matchBindings = matchBindingsComputer.finishBindings(tree, 676 matchBindings); 677 if (tree == breakTree && 678 resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) { 679 breakTreeFound(copyEnv(env)); 680 } 681 return result; 682 } catch (CompletionFailure ex) { 683 tree.type = syms.errType; 684 return chk.completionError(tree.pos(), ex); 685 } finally { 686 this.env = prevEnv; 687 this.resultInfo = prevResult; 688 } 689 } 690 691 protected void breakTreeFound(Env<AttrContext> env) { 692 throw new BreakAttr(env); 693 } 694 695 Env<AttrContext> copyEnv(Env<AttrContext> env) { 696 Env<AttrContext> newEnv = 697 env.dup(env.tree, env.info.dup(copyScope(env.info.scope))); 698 if (newEnv.outer != null) { 699 newEnv.outer = copyEnv(newEnv.outer); 700 } 701 return newEnv; 702 } 703 704 WriteableScope copyScope(WriteableScope sc) { 705 WriteableScope newScope = WriteableScope.create(sc.owner); 706 List<Symbol> elemsList = List.nil(); 707 for (Symbol sym : sc.getSymbols()) { 708 elemsList = elemsList.prepend(sym); 709 } 710 for (Symbol s : elemsList) { 711 newScope.enter(s); 712 } 713 return newScope; 714 } 715 716 /** Derived visitor method: attribute an expression tree. 717 */ 718 public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) { 719 return attribTree(tree, env, new ResultInfo(KindSelector.VAL, !pt.hasTag(ERROR) ? pt : Type.noType)); 720 } 721 722 /** Derived visitor method: attribute an expression tree with 723 * no constraints on the computed type. 724 */ 725 public Type attribExpr(JCTree tree, Env<AttrContext> env) { 726 return attribTree(tree, env, unknownExprInfo); 727 } 728 729 /** Derived visitor method: attribute a type tree. 730 */ 731 public Type attribType(JCTree tree, Env<AttrContext> env) { 732 Type result = attribType(tree, env, Type.noType); 733 return result; 734 } 735 736 /** Derived visitor method: attribute a type tree. 737 */ 738 Type attribType(JCTree tree, Env<AttrContext> env, Type pt) { 739 Type result = attribTree(tree, env, new ResultInfo(KindSelector.TYP, pt)); 740 return result; 741 } 742 743 /** Derived visitor method: attribute a statement or definition tree. 744 */ 745 public Type attribStat(JCTree tree, Env<AttrContext> env) { 746 Env<AttrContext> analyzeEnv = analyzer.copyEnvIfNeeded(tree, env); 747 Type result = attribTree(tree, env, statInfo); 748 analyzer.analyzeIfNeeded(tree, analyzeEnv); 749 attrRecover.doRecovery(); 750 return result; 751 } 752 753 /** Attribute a list of expressions, returning a list of types. 754 */ 755 List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) { 756 ListBuffer<Type> ts = new ListBuffer<>(); 757 for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail) 758 ts.append(attribExpr(l.head, env, pt)); 759 return ts.toList(); 760 } 761 762 /** Attribute a list of statements, returning nothing. 763 */ 764 <T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) { 765 for (List<T> l = trees; l.nonEmpty(); l = l.tail) 766 attribStat(l.head, env); 767 } 768 769 /** Attribute the arguments in a method call, returning the method kind. 770 */ 771 KindSelector attribArgs(KindSelector initialKind, List<JCExpression> trees, Env<AttrContext> env, ListBuffer<Type> argtypes) { 772 KindSelector kind = initialKind; 773 for (JCExpression arg : trees) { 774 Type argtype = chk.checkNonVoid(arg, attribTree(arg, env, methodAttrInfo)); 775 if (argtype.hasTag(DEFERRED)) { 776 kind = KindSelector.of(KindSelector.POLY, kind); 777 } 778 argtypes.append(argtype); 779 } 780 return kind; 781 } 782 783 /** Attribute a type argument list, returning a list of types. 784 * Caller is responsible for calling checkRefTypes. 785 */ 786 List<Type> attribAnyTypes(List<JCExpression> trees, Env<AttrContext> env) { 787 ListBuffer<Type> argtypes = new ListBuffer<>(); 788 for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail) 789 argtypes.append(attribType(l.head, env)); 790 return argtypes.toList(); 791 } 792 793 /** Attribute a type argument list, returning a list of types. 794 * Check that all the types are references. 795 */ 796 List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) { 797 List<Type> types = attribAnyTypes(trees, env); 798 return chk.checkRefTypes(trees, types); 799 } 800 801 /** 802 * Attribute type variables (of generic classes or methods). 803 * Compound types are attributed later in attribBounds. 804 * @param typarams the type variables to enter 805 * @param env the current environment 806 */ 807 void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env, boolean checkCyclic) { 808 for (JCTypeParameter tvar : typarams) { 809 TypeVar a = (TypeVar)tvar.type; 810 a.tsym.flags_field |= UNATTRIBUTED; 811 a.setUpperBound(Type.noType); 812 if (!tvar.bounds.isEmpty()) { 813 List<Type> bounds = List.of(attribType(tvar.bounds.head, env)); 814 for (JCExpression bound : tvar.bounds.tail) 815 bounds = bounds.prepend(attribType(bound, env)); 816 types.setBounds(a, bounds.reverse()); 817 } else { 818 // if no bounds are given, assume a single bound of 819 // java.lang.Object. 820 types.setBounds(a, List.of(syms.objectType)); 821 } 822 a.tsym.flags_field &= ~UNATTRIBUTED; 823 } 824 if (checkCyclic) { 825 for (JCTypeParameter tvar : typarams) { 826 chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type); 827 } 828 } 829 } 830 831 /** 832 * Attribute the type references in a list of annotations. 833 */ 834 void attribAnnotationTypes(List<JCAnnotation> annotations, 835 Env<AttrContext> env) { 836 for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) { 837 JCAnnotation a = al.head; 838 attribType(a.annotationType, env); 839 } 840 } 841 842 /** 843 * Attribute a "lazy constant value". 844 * @param env The env for the const value 845 * @param variable The initializer for the const value 846 * @param type The expected type, or null 847 * @see VarSymbol#setLazyConstValue 848 */ 849 public Object attribLazyConstantValue(Env<AttrContext> env, 850 JCVariableDecl variable, 851 Type type) { 852 853 DiagnosticPosition prevLintPos 854 = deferredLintHandler.setPos(variable.pos()); 855 856 final JavaFileObject prevSource = log.useSource(env.toplevel.sourcefile); 857 try { 858 Type itype = attribExpr(variable.init, env, type); 859 if (variable.isImplicitlyTyped()) { 860 //fixup local variable type 861 type = variable.type = variable.sym.type = chk.checkLocalVarType(variable, itype, variable.name); 862 } 863 if (itype.constValue() != null) { 864 return coerce(itype, type).constValue(); 865 } else { 866 return null; 867 } 868 } finally { 869 log.useSource(prevSource); 870 deferredLintHandler.setPos(prevLintPos); 871 } 872 } 873 874 /** Attribute type reference in an `extends' or `implements' clause. 875 * Supertypes of anonymous inner classes are usually already attributed. 876 * 877 * @param tree The tree making up the type reference. 878 * @param env The environment current at the reference. 879 * @param classExpected true if only a class is expected here. 880 * @param interfaceExpected true if only an interface is expected here. 881 */ 882 Type attribBase(JCTree tree, 883 Env<AttrContext> env, 884 boolean classExpected, 885 boolean interfaceExpected, 886 boolean checkExtensible) { 887 Type t = tree.type != null ? 888 tree.type : 889 attribType(tree, env); 890 try { 891 return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible); 892 } catch (CompletionFailure ex) { 893 chk.completionError(tree.pos(), ex); 894 return t; 895 } 896 } 897 Type checkBase(Type t, 898 JCTree tree, 899 Env<AttrContext> env, 900 boolean classExpected, 901 boolean interfaceExpected, 902 boolean checkExtensible) { 903 final DiagnosticPosition pos = tree.hasTag(TYPEAPPLY) ? 904 (((JCTypeApply) tree).clazz).pos() : tree.pos(); 905 if (t.tsym.isAnonymous()) { 906 log.error(pos, Errors.CantInheritFromAnon); 907 return types.createErrorType(t); 908 } 909 if (t.isErroneous()) 910 return t; 911 if (t.hasTag(TYPEVAR) && !classExpected && !interfaceExpected) { 912 // check that type variable is already visible 913 if (t.getUpperBound() == null) { 914 log.error(pos, Errors.IllegalForwardRef); 915 return types.createErrorType(t); 916 } 917 } else { 918 t = chk.checkClassType(pos, t, checkExtensible); 919 } 920 if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) { 921 log.error(pos, Errors.IntfExpectedHere); 922 // return errType is necessary since otherwise there might 923 // be undetected cycles which cause attribution to loop 924 return types.createErrorType(t); 925 } else if (checkExtensible && 926 classExpected && 927 (t.tsym.flags() & INTERFACE) != 0) { 928 log.error(pos, Errors.NoIntfExpectedHere); 929 return types.createErrorType(t); 930 } 931 if (checkExtensible && 932 ((t.tsym.flags() & FINAL) != 0)) { 933 log.error(pos, 934 Errors.CantInheritFromFinal(t.tsym)); 935 } 936 chk.checkNonCyclic(pos, t); 937 return t; 938 } 939 940 Type attribIdentAsEnumType(Env<AttrContext> env, JCIdent id) { 941 Assert.check((env.enclClass.sym.flags() & ENUM) != 0); 942 id.type = env.info.scope.owner.enclClass().type; 943 id.sym = env.info.scope.owner.enclClass(); 944 return id.type; 945 } 946 947 public void visitClassDef(JCClassDecl tree) { 948 Optional<ArgumentAttr.LocalCacheContext> localCacheContext = 949 Optional.ofNullable(env.info.attributionMode.isSpeculative ? 950 argumentAttr.withLocalCacheContext() : null); 951 boolean ctorProloguePrev = env.info.ctorPrologue; 952 env.info.ctorPrologue = false; 953 try { 954 // Local and anonymous classes have not been entered yet, so we need to 955 // do it now. 956 if (env.info.scope.owner.kind.matches(KindSelector.VAL_MTH)) { 957 enter.classEnter(tree, env); 958 } else { 959 // If this class declaration is part of a class level annotation, 960 // as in @MyAnno(new Object() {}) class MyClass {}, enter it in 961 // order to simplify later steps and allow for sensible error 962 // messages. 963 if (env.tree.hasTag(NEWCLASS) && TreeInfo.isInAnnotation(env, tree)) 964 enter.classEnter(tree, env); 965 } 966 967 ClassSymbol c = tree.sym; 968 if (c == null) { 969 // exit in case something drastic went wrong during enter. 970 result = null; 971 } else { 972 // make sure class has been completed: 973 c.complete(); 974 975 // If this class appears as an anonymous class in a constructor 976 // prologue, disable implicit outer instance from being passed. 977 // (This would be an illegal access to "this before super"). 978 if (ctorProloguePrev && env.tree.hasTag(NEWCLASS)) { 979 c.flags_field |= NOOUTERTHIS; 980 } 981 attribClass(tree.pos(), c); 982 result = tree.type = c.type; 983 } 984 } finally { 985 localCacheContext.ifPresent(LocalCacheContext::leave); 986 env.info.ctorPrologue = ctorProloguePrev; 987 } 988 } 989 990 public void visitMethodDef(JCMethodDecl tree) { 991 MethodSymbol m = tree.sym; 992 boolean isDefaultMethod = (m.flags() & DEFAULT) != 0; 993 994 Lint lint = env.info.lint.augment(m); 995 Lint prevLint = chk.setLint(lint); 996 boolean ctorProloguePrev = env.info.ctorPrologue; 997 env.info.ctorPrologue = false; 998 MethodSymbol prevMethod = chk.setMethod(m); 999 try { 1000 deferredLintHandler.flush(tree.pos()); 1001 chk.checkDeprecatedAnnotation(tree.pos(), m); 1002 1003 1004 // Create a new environment with local scope 1005 // for attributing the method. 1006 Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env); 1007 localEnv.info.lint = lint; 1008 1009 attribStats(tree.typarams, localEnv); 1010 1011 // If we override any other methods, check that we do so properly. 1012 // JLS ??? 1013 if (m.isStatic()) { 1014 chk.checkHideClashes(tree.pos(), env.enclClass.type, m); 1015 } else { 1016 chk.checkOverrideClashes(tree.pos(), env.enclClass.type, m); 1017 } 1018 chk.checkOverride(env, tree, m); 1019 1020 if (isDefaultMethod && types.overridesObjectMethod(m.enclClass(), m)) { 1021 log.error(tree, Errors.DefaultOverridesObjectMember(m.name, Kinds.kindName(m.location()), m.location())); 1022 } 1023 1024 // Enter all type parameters into the local method scope. 1025 for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail) 1026 localEnv.info.scope.enterIfAbsent(l.head.type.tsym); 1027 1028 ClassSymbol owner = env.enclClass.sym; 1029 if ((owner.flags() & ANNOTATION) != 0 && 1030 (tree.params.nonEmpty() || 1031 tree.recvparam != null)) 1032 log.error(tree.params.nonEmpty() ? 1033 tree.params.head.pos() : 1034 tree.recvparam.pos(), 1035 Errors.IntfAnnotationMembersCantHaveParams); 1036 1037 // Attribute all value parameters. 1038 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) { 1039 attribStat(l.head, localEnv); 1040 } 1041 1042 chk.checkVarargsMethodDecl(localEnv, tree); 1043 1044 // Check that type parameters are well-formed. 1045 chk.validate(tree.typarams, localEnv); 1046 1047 // Check that result type is well-formed. 1048 if (tree.restype != null && !tree.restype.type.hasTag(VOID)) 1049 chk.validate(tree.restype, localEnv); 1050 1051 // Check that receiver type is well-formed. 1052 if (tree.recvparam != null) { 1053 // Use a new environment to check the receiver parameter. 1054 // Otherwise I get "might not have been initialized" errors. 1055 // Is there a better way? 1056 Env<AttrContext> newEnv = memberEnter.methodEnv(tree, env); 1057 attribType(tree.recvparam, newEnv); 1058 chk.validate(tree.recvparam, newEnv); 1059 } 1060 1061 // Is this method a constructor? 1062 boolean isConstructor = TreeInfo.isConstructor(tree); 1063 1064 if (env.enclClass.sym.isRecord() && tree.sym.owner.kind == TYP) { 1065 // lets find if this method is an accessor 1066 Optional<? extends RecordComponent> recordComponent = env.enclClass.sym.getRecordComponents().stream() 1067 .filter(rc -> rc.accessor == tree.sym && (rc.accessor.flags_field & GENERATED_MEMBER) == 0).findFirst(); 1068 if (recordComponent.isPresent()) { 1069 // the method is a user defined accessor lets check that everything is fine 1070 if (!tree.sym.isPublic()) { 1071 log.error(tree, Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, Fragments.MethodMustBePublic)); 1072 } 1073 if (!types.isSameType(tree.sym.type.getReturnType(), recordComponent.get().type)) { 1074 log.error(tree, Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, 1075 Fragments.AccessorReturnTypeDoesntMatch(tree.sym, recordComponent.get()))); 1076 } 1077 if (tree.sym.type.asMethodType().thrown != null && !tree.sym.type.asMethodType().thrown.isEmpty()) { 1078 log.error(tree, 1079 Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, Fragments.AccessorMethodCantThrowException)); 1080 } 1081 if (!tree.typarams.isEmpty()) { 1082 log.error(tree, 1083 Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, Fragments.AccessorMethodMustNotBeGeneric)); 1084 } 1085 if (tree.sym.isStatic()) { 1086 log.error(tree, 1087 Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, Fragments.AccessorMethodMustNotBeStatic)); 1088 } 1089 } 1090 1091 if (isConstructor) { 1092 // if this a constructor other than the canonical one 1093 if ((tree.sym.flags_field & RECORD) == 0) { 1094 if (!TreeInfo.hasConstructorCall(tree, names._this)) { 1095 log.error(tree, Errors.NonCanonicalConstructorInvokeAnotherConstructor(env.enclClass.sym)); 1096 } 1097 } else { 1098 // but if it is the canonical: 1099 1100 /* if user generated, then it shouldn't: 1101 * - have an accessibility stricter than that of the record type 1102 * - explicitly invoke any other constructor 1103 */ 1104 if ((tree.sym.flags_field & GENERATEDCONSTR) == 0) { 1105 if (Check.protection(m.flags()) > Check.protection(env.enclClass.sym.flags())) { 1106 log.error(tree, 1107 (env.enclClass.sym.flags() & AccessFlags) == 0 ? 1108 Errors.InvalidCanonicalConstructorInRecord( 1109 Fragments.Canonical, 1110 env.enclClass.sym.name, 1111 Fragments.CanonicalMustNotHaveStrongerAccess("package") 1112 ) : 1113 Errors.InvalidCanonicalConstructorInRecord( 1114 Fragments.Canonical, 1115 env.enclClass.sym.name, 1116 Fragments.CanonicalMustNotHaveStrongerAccess(asFlagSet(env.enclClass.sym.flags() & AccessFlags)) 1117 ) 1118 ); 1119 } 1120 1121 if (TreeInfo.hasAnyConstructorCall(tree)) { 1122 log.error(tree, Errors.InvalidCanonicalConstructorInRecord( 1123 Fragments.Canonical, env.enclClass.sym.name, 1124 Fragments.CanonicalMustNotContainExplicitConstructorInvocation)); 1125 } 1126 } 1127 1128 // also we want to check that no type variables have been defined 1129 if (!tree.typarams.isEmpty()) { 1130 log.error(tree, Errors.InvalidCanonicalConstructorInRecord( 1131 Fragments.Canonical, env.enclClass.sym.name, Fragments.CanonicalMustNotDeclareTypeVariables)); 1132 } 1133 1134 /* and now we need to check that the constructor's arguments are exactly the same as those of the 1135 * record components 1136 */ 1137 List<? extends RecordComponent> recordComponents = env.enclClass.sym.getRecordComponents(); 1138 List<Type> recordFieldTypes = TreeInfo.recordFields(env.enclClass).map(vd -> vd.sym.type); 1139 for (JCVariableDecl param: tree.params) { 1140 boolean paramIsVarArgs = (param.sym.flags_field & VARARGS) != 0; 1141 if (!types.isSameType(param.type, recordFieldTypes.head) || 1142 (recordComponents.head.isVarargs() != paramIsVarArgs)) { 1143 log.error(param, Errors.InvalidCanonicalConstructorInRecord( 1144 Fragments.Canonical, env.enclClass.sym.name, 1145 Fragments.TypeMustBeIdenticalToCorrespondingRecordComponentType)); 1146 } 1147 recordComponents = recordComponents.tail; 1148 recordFieldTypes = recordFieldTypes.tail; 1149 } 1150 } 1151 } 1152 } 1153 1154 // annotation method checks 1155 if ((owner.flags() & ANNOTATION) != 0) { 1156 // annotation method cannot have throws clause 1157 if (tree.thrown.nonEmpty()) { 1158 log.error(tree.thrown.head.pos(), 1159 Errors.ThrowsNotAllowedInIntfAnnotation); 1160 } 1161 // annotation method cannot declare type-parameters 1162 if (tree.typarams.nonEmpty()) { 1163 log.error(tree.typarams.head.pos(), 1164 Errors.IntfAnnotationMembersCantHaveTypeParams); 1165 } 1166 // validate annotation method's return type (could be an annotation type) 1167 chk.validateAnnotationType(tree.restype); 1168 // ensure that annotation method does not clash with members of Object/Annotation 1169 chk.validateAnnotationMethod(tree.pos(), m); 1170 } 1171 1172 for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail) 1173 chk.checkType(l.head.pos(), l.head.type, syms.throwableType); 1174 1175 if (tree.body == null) { 1176 // Empty bodies are only allowed for 1177 // abstract, native, or interface methods, or for methods 1178 // in a retrofit signature class. 1179 if (tree.defaultValue != null) { 1180 if ((owner.flags() & ANNOTATION) == 0) 1181 log.error(tree.pos(), 1182 Errors.DefaultAllowedInIntfAnnotationMember); 1183 } 1184 if (isDefaultMethod || (tree.sym.flags() & (ABSTRACT | NATIVE)) == 0) 1185 log.error(tree.pos(), Errors.MissingMethBodyOrDeclAbstract); 1186 } else { 1187 if ((tree.sym.flags() & (ABSTRACT|DEFAULT|PRIVATE)) == ABSTRACT) { 1188 if ((owner.flags() & INTERFACE) != 0) { 1189 log.error(tree.body.pos(), Errors.IntfMethCantHaveBody); 1190 } else { 1191 log.error(tree.pos(), Errors.AbstractMethCantHaveBody); 1192 } 1193 } else if ((tree.mods.flags & NATIVE) != 0) { 1194 log.error(tree.pos(), Errors.NativeMethCantHaveBody); 1195 } 1196 // Add an implicit super() call unless an explicit call to 1197 // super(...) or this(...) is given 1198 // or we are compiling class java.lang.Object. 1199 if (isConstructor && owner.type != syms.objectType) { 1200 if (!TreeInfo.hasAnyConstructorCall(tree)) { 1201 JCStatement supCall = make.at(tree.body.pos).Exec(make.Apply(List.nil(), 1202 make.Ident(names._super), make.Idents(List.nil()))); 1203 if (owner.isValueClass()) { 1204 tree.body.stats = tree.body.stats.append(supCall); 1205 } else { 1206 tree.body.stats = tree.body.stats.prepend(supCall); 1207 } 1208 } else if ((env.enclClass.sym.flags() & ENUM) != 0 && 1209 (tree.mods.flags & GENERATEDCONSTR) == 0 && 1210 TreeInfo.hasConstructorCall(tree, names._super)) { 1211 // enum constructors are not allowed to call super 1212 // directly, so make sure there aren't any super calls 1213 // in enum constructors, except in the compiler 1214 // generated one. 1215 log.error(tree.body.stats.head.pos(), 1216 Errors.CallToSuperNotAllowedInEnumCtor(env.enclClass.sym)); 1217 } 1218 if (env.enclClass.sym.isRecord() && (tree.sym.flags_field & RECORD) != 0) { // we are seeing the canonical constructor 1219 List<Name> recordComponentNames = TreeInfo.recordFields(env.enclClass).map(vd -> vd.sym.name); 1220 List<Name> initParamNames = tree.sym.params.map(p -> p.name); 1221 if (!initParamNames.equals(recordComponentNames)) { 1222 log.error(tree, Errors.InvalidCanonicalConstructorInRecord( 1223 Fragments.Canonical, env.enclClass.sym.name, Fragments.CanonicalWithNameMismatch)); 1224 } 1225 if (tree.sym.type.asMethodType().thrown != null && !tree.sym.type.asMethodType().thrown.isEmpty()) { 1226 log.error(tree, 1227 Errors.InvalidCanonicalConstructorInRecord( 1228 TreeInfo.isCompactConstructor(tree) ? Fragments.Compact : Fragments.Canonical, 1229 env.enclClass.sym.name, 1230 Fragments.ThrowsClauseNotAllowedForCanonicalConstructor( 1231 TreeInfo.isCompactConstructor(tree) ? Fragments.Compact : Fragments.Canonical))); 1232 } 1233 } 1234 } 1235 1236 // Attribute all type annotations in the body 1237 annotate.queueScanTreeAndTypeAnnotate(tree.body, localEnv, m, null); 1238 annotate.flush(); 1239 1240 // Start of constructor prologue 1241 localEnv.info.ctorPrologue = isConstructor; 1242 1243 // Attribute method body. 1244 attribStat(tree.body, localEnv); 1245 } 1246 1247 localEnv.info.scope.leave(); 1248 result = tree.type = m.type; 1249 } finally { 1250 chk.setLint(prevLint); 1251 chk.setMethod(prevMethod); 1252 env.info.ctorPrologue = ctorProloguePrev; 1253 } 1254 } 1255 1256 public void visitVarDef(JCVariableDecl tree) { 1257 // Local variables have not been entered yet, so we need to do it now: 1258 if (env.info.scope.owner.kind == MTH || env.info.scope.owner.kind == VAR) { 1259 if (tree.sym != null) { 1260 // parameters have already been entered 1261 env.info.scope.enter(tree.sym); 1262 } else { 1263 if (tree.isImplicitlyTyped() && (tree.getModifiers().flags & PARAMETER) == 0) { 1264 if (tree.init == null) { 1265 //cannot use 'var' without initializer 1266 log.error(tree, Errors.CantInferLocalVarType(tree.name, Fragments.LocalMissingInit)); 1267 tree.vartype = make.Erroneous(); 1268 } else { 1269 Fragment msg = canInferLocalVarType(tree); 1270 if (msg != null) { 1271 //cannot use 'var' with initializer which require an explicit target 1272 //(e.g. lambda, method reference, array initializer). 1273 log.error(tree, Errors.CantInferLocalVarType(tree.name, msg)); 1274 tree.vartype = make.Erroneous(); 1275 } 1276 } 1277 } 1278 try { 1279 annotate.blockAnnotations(); 1280 memberEnter.memberEnter(tree, env); 1281 } finally { 1282 annotate.unblockAnnotations(); 1283 } 1284 } 1285 } else { 1286 if (tree.init != null) { 1287 // Field initializer expression need to be entered. 1288 annotate.queueScanTreeAndTypeAnnotate(tree.init, env, tree.sym, tree.pos()); 1289 annotate.flush(); 1290 } 1291 } 1292 1293 VarSymbol v = tree.sym; 1294 Lint lint = env.info.lint.augment(v); 1295 Lint prevLint = chk.setLint(lint); 1296 1297 // Check that the variable's declared type is well-formed. 1298 boolean isImplicitLambdaParameter = env.tree.hasTag(LAMBDA) && 1299 ((JCLambda)env.tree).paramKind == JCLambda.ParameterKind.IMPLICIT && 1300 (tree.sym.flags() & PARAMETER) != 0; 1301 chk.validate(tree.vartype, env, !isImplicitLambdaParameter && !tree.isImplicitlyTyped()); 1302 1303 try { 1304 v.getConstValue(); // ensure compile-time constant initializer is evaluated 1305 deferredLintHandler.flush(tree.pos()); 1306 chk.checkDeprecatedAnnotation(tree.pos(), v); 1307 1308 if (tree.init != null) { 1309 if ((v.flags_field & FINAL) == 0 || 1310 !memberEnter.needsLazyConstValue(tree.init)) { 1311 // Not a compile-time constant 1312 // Attribute initializer in a new environment 1313 // with the declared variable as owner. 1314 // Check that initializer conforms to variable's declared type. 1315 Env<AttrContext> initEnv = memberEnter.initEnv(tree, env); 1316 initEnv.info.lint = lint; 1317 // In order to catch self-references, we set the variable's 1318 // declaration position to maximal possible value, effectively 1319 // marking the variable as undefined. 1320 initEnv.info.enclVar = v; 1321 attribExpr(tree.init, initEnv, v.type); 1322 if (tree.isImplicitlyTyped()) { 1323 //fixup local variable type 1324 v.type = chk.checkLocalVarType(tree, tree.init.type, tree.name); 1325 } 1326 } 1327 if (tree.isImplicitlyTyped()) { 1328 setSyntheticVariableType(tree, v.type); 1329 } 1330 } 1331 result = tree.type = v.type; 1332 if (env.enclClass.sym.isRecord() && tree.sym.owner.kind == TYP && !v.isStatic()) { 1333 if (isNonArgsMethodInObject(v.name)) { 1334 log.error(tree, Errors.IllegalRecordComponentName(v)); 1335 } 1336 } 1337 } 1338 finally { 1339 chk.setLint(prevLint); 1340 } 1341 } 1342 1343 private boolean isNonArgsMethodInObject(Name name) { 1344 for (Symbol s : syms.objectType.tsym.members().getSymbolsByName(name, s -> s.kind == MTH)) { 1345 if (s.type.getParameterTypes().isEmpty()) { 1346 return true; 1347 } 1348 } 1349 // isValueObject is not included in Object yet so we need a work around 1350 return name == names.isValueObject; 1351 } 1352 1353 Fragment canInferLocalVarType(JCVariableDecl tree) { 1354 LocalInitScanner lis = new LocalInitScanner(); 1355 lis.scan(tree.init); 1356 return lis.badInferenceMsg; 1357 } 1358 1359 static class LocalInitScanner extends TreeScanner { 1360 Fragment badInferenceMsg = null; 1361 boolean needsTarget = true; 1362 1363 @Override 1364 public void visitNewArray(JCNewArray tree) { 1365 if (tree.elemtype == null && needsTarget) { 1366 badInferenceMsg = Fragments.LocalArrayMissingTarget; 1367 } 1368 } 1369 1370 @Override 1371 public void visitLambda(JCLambda tree) { 1372 if (needsTarget) { 1373 badInferenceMsg = Fragments.LocalLambdaMissingTarget; 1374 } 1375 } 1376 1377 @Override 1378 public void visitTypeCast(JCTypeCast tree) { 1379 boolean prevNeedsTarget = needsTarget; 1380 try { 1381 needsTarget = false; 1382 super.visitTypeCast(tree); 1383 } finally { 1384 needsTarget = prevNeedsTarget; 1385 } 1386 } 1387 1388 @Override 1389 public void visitReference(JCMemberReference tree) { 1390 if (needsTarget) { 1391 badInferenceMsg = Fragments.LocalMrefMissingTarget; 1392 } 1393 } 1394 1395 @Override 1396 public void visitNewClass(JCNewClass tree) { 1397 boolean prevNeedsTarget = needsTarget; 1398 try { 1399 needsTarget = false; 1400 super.visitNewClass(tree); 1401 } finally { 1402 needsTarget = prevNeedsTarget; 1403 } 1404 } 1405 1406 @Override 1407 public void visitApply(JCMethodInvocation tree) { 1408 boolean prevNeedsTarget = needsTarget; 1409 try { 1410 needsTarget = false; 1411 super.visitApply(tree); 1412 } finally { 1413 needsTarget = prevNeedsTarget; 1414 } 1415 } 1416 } 1417 1418 public void visitSkip(JCSkip tree) { 1419 result = null; 1420 } 1421 1422 public void visitBlock(JCBlock tree) { 1423 if (env.info.scope.owner.kind == TYP || env.info.scope.owner.kind == ERR) { 1424 // Block is a static or instance initializer; 1425 // let the owner of the environment be a freshly 1426 // created BLOCK-method. 1427 Symbol fakeOwner = 1428 new MethodSymbol(tree.flags | BLOCK | 1429 env.info.scope.owner.flags() & STRICTFP, names.empty, null, 1430 env.info.scope.owner); 1431 final Env<AttrContext> localEnv = 1432 env.dup(tree, env.info.dup(env.info.scope.dupUnshared(fakeOwner))); 1433 1434 if ((tree.flags & STATIC) != 0) { 1435 localEnv.info.staticLevel++; 1436 } else { 1437 localEnv.info.instanceInitializerBlock = true; 1438 } 1439 // Attribute all type annotations in the block 1440 annotate.queueScanTreeAndTypeAnnotate(tree, localEnv, localEnv.info.scope.owner, null); 1441 annotate.flush(); 1442 attribStats(tree.stats, localEnv); 1443 1444 { 1445 // Store init and clinit type annotations with the ClassSymbol 1446 // to allow output in Gen.normalizeDefs. 1447 ClassSymbol cs = (ClassSymbol)env.info.scope.owner; 1448 List<Attribute.TypeCompound> tas = localEnv.info.scope.owner.getRawTypeAttributes(); 1449 if ((tree.flags & STATIC) != 0) { 1450 cs.appendClassInitTypeAttributes(tas); 1451 } else { 1452 cs.appendInitTypeAttributes(tas); 1453 } 1454 } 1455 } else { 1456 // Create a new local environment with a local scope. 1457 Env<AttrContext> localEnv = 1458 env.dup(tree, env.info.dup(env.info.scope.dup())); 1459 try { 1460 attribStats(tree.stats, localEnv); 1461 } finally { 1462 localEnv.info.scope.leave(); 1463 } 1464 } 1465 result = null; 1466 } 1467 1468 public void visitDoLoop(JCDoWhileLoop tree) { 1469 attribStat(tree.body, env.dup(tree)); 1470 attribExpr(tree.cond, env, syms.booleanType); 1471 handleLoopConditionBindings(matchBindings, tree, tree.body); 1472 result = null; 1473 } 1474 1475 public void visitWhileLoop(JCWhileLoop tree) { 1476 attribExpr(tree.cond, env, syms.booleanType); 1477 MatchBindings condBindings = matchBindings; 1478 // include condition's bindings when true in the body: 1479 Env<AttrContext> whileEnv = bindingEnv(env, condBindings.bindingsWhenTrue); 1480 try { 1481 attribStat(tree.body, whileEnv.dup(tree)); 1482 } finally { 1483 whileEnv.info.scope.leave(); 1484 } 1485 handleLoopConditionBindings(condBindings, tree, tree.body); 1486 result = null; 1487 } 1488 1489 public void visitForLoop(JCForLoop tree) { 1490 Env<AttrContext> loopEnv = 1491 env.dup(env.tree, env.info.dup(env.info.scope.dup())); 1492 MatchBindings condBindings = MatchBindingsComputer.EMPTY; 1493 try { 1494 attribStats(tree.init, loopEnv); 1495 if (tree.cond != null) { 1496 attribExpr(tree.cond, loopEnv, syms.booleanType); 1497 // include condition's bindings when true in the body and step: 1498 condBindings = matchBindings; 1499 } 1500 Env<AttrContext> bodyEnv = bindingEnv(loopEnv, condBindings.bindingsWhenTrue); 1501 try { 1502 bodyEnv.tree = tree; // before, we were not in loop! 1503 attribStats(tree.step, bodyEnv); 1504 attribStat(tree.body, bodyEnv); 1505 } finally { 1506 bodyEnv.info.scope.leave(); 1507 } 1508 result = null; 1509 } 1510 finally { 1511 loopEnv.info.scope.leave(); 1512 } 1513 handleLoopConditionBindings(condBindings, tree, tree.body); 1514 } 1515 1516 /** 1517 * Include condition's bindings when false after the loop, if cannot get out of the loop 1518 */ 1519 private void handleLoopConditionBindings(MatchBindings condBindings, 1520 JCStatement loop, 1521 JCStatement loopBody) { 1522 if (condBindings.bindingsWhenFalse.nonEmpty() && 1523 !breaksTo(env, loop, loopBody)) { 1524 addBindings2Scope(loop, condBindings.bindingsWhenFalse); 1525 } 1526 } 1527 1528 private boolean breaksTo(Env<AttrContext> env, JCTree loop, JCTree body) { 1529 preFlow(body); 1530 return flow.breaksToTree(env, loop, body, make); 1531 } 1532 1533 /** 1534 * Add given bindings to the current scope, unless there's a break to 1535 * an immediately enclosing labeled statement. 1536 */ 1537 private void addBindings2Scope(JCStatement introducingStatement, 1538 List<BindingSymbol> bindings) { 1539 if (bindings.isEmpty()) { 1540 return ; 1541 } 1542 1543 var searchEnv = env; 1544 while (searchEnv.tree instanceof JCLabeledStatement labeled && 1545 labeled.body == introducingStatement) { 1546 if (breaksTo(env, labeled, labeled.body)) { 1547 //breaking to an immediately enclosing labeled statement 1548 return ; 1549 } 1550 searchEnv = searchEnv.next; 1551 introducingStatement = labeled; 1552 } 1553 1554 //include condition's body when false after the while, if cannot get out of the loop 1555 bindings.forEach(env.info.scope::enter); 1556 bindings.forEach(BindingSymbol::preserveBinding); 1557 } 1558 1559 public void visitForeachLoop(JCEnhancedForLoop tree) { 1560 Env<AttrContext> loopEnv = 1561 env.dup(env.tree, env.info.dup(env.info.scope.dup())); 1562 try { 1563 //the Formal Parameter of a for-each loop is not in the scope when 1564 //attributing the for-each expression; we mimic this by attributing 1565 //the for-each expression first (against original scope). 1566 Type exprType = types.cvarUpperBound(attribExpr(tree.expr, loopEnv)); 1567 chk.checkNonVoid(tree.pos(), exprType); 1568 Type elemtype = types.elemtype(exprType); // perhaps expr is an array? 1569 if (elemtype == null) { 1570 // or perhaps expr implements Iterable<T>? 1571 Type base = types.asSuper(exprType, syms.iterableType.tsym); 1572 if (base == null) { 1573 log.error(tree.expr.pos(), 1574 Errors.ForeachNotApplicableToType(exprType, 1575 Fragments.TypeReqArrayOrIterable)); 1576 elemtype = types.createErrorType(exprType); 1577 } else { 1578 List<Type> iterableParams = base.allparams(); 1579 elemtype = iterableParams.isEmpty() 1580 ? syms.objectType 1581 : types.wildUpperBound(iterableParams.head); 1582 1583 // Check the return type of the method iterator(). 1584 // This is the bare minimum we need to verify to make sure code generation doesn't crash. 1585 Symbol iterSymbol = rs.resolveInternalMethod(tree.pos(), 1586 loopEnv, types.skipTypeVars(exprType, false), names.iterator, List.nil(), List.nil()); 1587 if (types.asSuper(iterSymbol.type.getReturnType(), syms.iteratorType.tsym) == null) { 1588 log.error(tree.pos(), 1589 Errors.ForeachNotApplicableToType(exprType, Fragments.TypeReqArrayOrIterable)); 1590 } 1591 } 1592 } 1593 if (tree.var.isImplicitlyTyped()) { 1594 Type inferredType = chk.checkLocalVarType(tree.var, elemtype, tree.var.name); 1595 setSyntheticVariableType(tree.var, inferredType); 1596 } 1597 attribStat(tree.var, loopEnv); 1598 chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type); 1599 loopEnv.tree = tree; // before, we were not in loop! 1600 attribStat(tree.body, loopEnv); 1601 result = null; 1602 } 1603 finally { 1604 loopEnv.info.scope.leave(); 1605 } 1606 } 1607 1608 public void visitLabelled(JCLabeledStatement tree) { 1609 // Check that label is not used in an enclosing statement 1610 Env<AttrContext> env1 = env; 1611 while (env1 != null && !env1.tree.hasTag(CLASSDEF)) { 1612 if (env1.tree.hasTag(LABELLED) && 1613 ((JCLabeledStatement) env1.tree).label == tree.label) { 1614 log.error(tree.pos(), 1615 Errors.LabelAlreadyInUse(tree.label)); 1616 break; 1617 } 1618 env1 = env1.next; 1619 } 1620 1621 attribStat(tree.body, env.dup(tree)); 1622 result = null; 1623 } 1624 1625 public void visitSwitch(JCSwitch tree) { 1626 handleSwitch(tree, tree.selector, tree.cases, (c, caseEnv) -> { 1627 attribStats(c.stats, caseEnv); 1628 }); 1629 result = null; 1630 } 1631 1632 public void visitSwitchExpression(JCSwitchExpression tree) { 1633 tree.polyKind = (pt().hasTag(NONE) && pt() != Type.recoveryType && pt() != Infer.anyPoly) ? 1634 PolyKind.STANDALONE : PolyKind.POLY; 1635 1636 if (tree.polyKind == PolyKind.POLY && resultInfo.pt.hasTag(VOID)) { 1637 //this means we are returning a poly conditional from void-compatible lambda expression 1638 resultInfo.checkContext.report(tree, diags.fragment(Fragments.SwitchExpressionTargetCantBeVoid)); 1639 result = tree.type = types.createErrorType(resultInfo.pt); 1640 return; 1641 } 1642 1643 ResultInfo condInfo = tree.polyKind == PolyKind.STANDALONE ? 1644 unknownExprInfo : 1645 resultInfo.dup(switchExpressionContext(resultInfo.checkContext)); 1646 1647 ListBuffer<DiagnosticPosition> caseTypePositions = new ListBuffer<>(); 1648 ListBuffer<Type> caseTypes = new ListBuffer<>(); 1649 1650 handleSwitch(tree, tree.selector, tree.cases, (c, caseEnv) -> { 1651 caseEnv.info.yieldResult = condInfo; 1652 attribStats(c.stats, caseEnv); 1653 new TreeScanner() { 1654 @Override 1655 public void visitYield(JCYield brk) { 1656 if (brk.target == tree) { 1657 caseTypePositions.append(brk.value != null ? brk.value.pos() : brk.pos()); 1658 caseTypes.append(brk.value != null ? brk.value.type : syms.errType); 1659 } 1660 super.visitYield(brk); 1661 } 1662 1663 @Override public void visitClassDef(JCClassDecl tree) {} 1664 @Override public void visitLambda(JCLambda tree) {} 1665 }.scan(c.stats); 1666 }); 1667 1668 if (tree.cases.isEmpty()) { 1669 log.error(tree.pos(), 1670 Errors.SwitchExpressionEmpty); 1671 } else if (caseTypes.isEmpty()) { 1672 log.error(tree.pos(), 1673 Errors.SwitchExpressionNoResultExpressions); 1674 } 1675 1676 Type owntype = (tree.polyKind == PolyKind.STANDALONE) ? condType(caseTypePositions.toList(), caseTypes.toList()) : pt(); 1677 1678 result = tree.type = check(tree, owntype, KindSelector.VAL, resultInfo); 1679 } 1680 //where: 1681 CheckContext switchExpressionContext(CheckContext checkContext) { 1682 return new Check.NestedCheckContext(checkContext) { 1683 //this will use enclosing check context to check compatibility of 1684 //subexpression against target type; if we are in a method check context, 1685 //depending on whether boxing is allowed, we could have incompatibilities 1686 @Override 1687 public void report(DiagnosticPosition pos, JCDiagnostic details) { 1688 enclosingContext.report(pos, diags.fragment(Fragments.IncompatibleTypeInSwitchExpression(details))); 1689 } 1690 }; 1691 } 1692 1693 private void handleSwitch(JCTree switchTree, 1694 JCExpression selector, 1695 List<JCCase> cases, 1696 BiConsumer<JCCase, Env<AttrContext>> attribCase) { 1697 Type seltype = attribExpr(selector, env); 1698 1699 Env<AttrContext> switchEnv = 1700 env.dup(switchTree, env.info.dup(env.info.scope.dup())); 1701 1702 try { 1703 boolean enumSwitch = (seltype.tsym.flags() & Flags.ENUM) != 0; 1704 boolean stringSwitch = types.isSameType(seltype, syms.stringType); 1705 boolean errorEnumSwitch = TreeInfo.isErrorEnumSwitch(selector, cases); 1706 boolean intSwitch = types.isAssignable(seltype, syms.intType); 1707 boolean errorPrimitiveSwitch = seltype.isPrimitive() && !intSwitch; 1708 boolean patternSwitch; 1709 if (!enumSwitch && !stringSwitch && !errorEnumSwitch && 1710 !intSwitch && !errorPrimitiveSwitch) { 1711 preview.checkSourceLevel(selector.pos(), Feature.PATTERN_SWITCH); 1712 patternSwitch = true; 1713 } else { 1714 if (errorPrimitiveSwitch) { 1715 log.error(selector.pos(), Errors.SelectorTypeNotAllowed(seltype)); 1716 } 1717 patternSwitch = cases.stream() 1718 .flatMap(c -> c.labels.stream()) 1719 .anyMatch(l -> l.hasTag(PATTERNCASELABEL) || 1720 TreeInfo.isNullCaseLabel(l)); 1721 } 1722 1723 // Attribute all cases and 1724 // check that there are no duplicate case labels or default clauses. 1725 Set<Object> constants = new HashSet<>(); // The set of case constants. 1726 boolean hasDefault = false; // Is there a default label? 1727 boolean hasUnconditionalPattern = false; // Is there a unconditional pattern? 1728 boolean lastPatternErroneous = false; // Has the last pattern erroneous type? 1729 boolean hasNullPattern = false; // Is there a null pattern? 1730 CaseTree.CaseKind caseKind = null; 1731 boolean wasError = false; 1732 for (List<JCCase> l = cases; l.nonEmpty(); l = l.tail) { 1733 JCCase c = l.head; 1734 if (caseKind == null) { 1735 caseKind = c.caseKind; 1736 } else if (caseKind != c.caseKind && !wasError) { 1737 log.error(c.pos(), 1738 Errors.SwitchMixingCaseTypes); 1739 wasError = true; 1740 } 1741 MatchBindings currentBindings = null; 1742 MatchBindings guardBindings = null; 1743 for (List<JCCaseLabel> labels = c.labels; labels.nonEmpty(); labels = labels.tail) { 1744 JCCaseLabel label = labels.head; 1745 if (label instanceof JCConstantCaseLabel constLabel) { 1746 JCExpression expr = constLabel.expr; 1747 if (TreeInfo.isNull(expr)) { 1748 preview.checkSourceLevel(expr.pos(), Feature.CASE_NULL); 1749 if (hasNullPattern) { 1750 log.error(label.pos(), Errors.DuplicateCaseLabel); 1751 } 1752 hasNullPattern = true; 1753 attribExpr(expr, switchEnv, seltype); 1754 matchBindings = new MatchBindings(matchBindings.bindingsWhenTrue, matchBindings.bindingsWhenFalse, true); 1755 } else if (enumSwitch) { 1756 Symbol sym = enumConstant(expr, seltype); 1757 if (sym == null) { 1758 if (allowPatternSwitch) { 1759 attribTree(expr, switchEnv, caseLabelResultInfo(seltype)); 1760 Symbol enumSym = TreeInfo.symbol(expr); 1761 if (enumSym == null || !enumSym.isEnum() || enumSym.kind != VAR) { 1762 log.error(expr.pos(), Errors.EnumLabelMustBeEnumConstant); 1763 } else if (!constants.add(enumSym)) { 1764 log.error(label.pos(), Errors.DuplicateCaseLabel); 1765 } 1766 } else { 1767 log.error(expr.pos(), Errors.EnumLabelMustBeUnqualifiedEnum); 1768 } 1769 } else if (!constants.add(sym)) { 1770 log.error(label.pos(), Errors.DuplicateCaseLabel); 1771 } 1772 } else if (errorEnumSwitch) { 1773 //error recovery: the selector is erroneous, and all the case labels 1774 //are identifiers. This could be an enum switch - don't report resolve 1775 //error for the case label: 1776 var prevResolveHelper = rs.basicLogResolveHelper; 1777 try { 1778 rs.basicLogResolveHelper = rs.silentLogResolveHelper; 1779 attribExpr(expr, switchEnv, seltype); 1780 } finally { 1781 rs.basicLogResolveHelper = prevResolveHelper; 1782 } 1783 } else { 1784 Type pattype = attribTree(expr, switchEnv, caseLabelResultInfo(seltype)); 1785 if (!pattype.hasTag(ERROR)) { 1786 if (pattype.constValue() == null) { 1787 Symbol s = TreeInfo.symbol(expr); 1788 if (s != null && s.kind == TYP) { 1789 log.error(expr.pos(), 1790 Errors.PatternExpected); 1791 } else if (s == null || !s.isEnum()) { 1792 log.error(expr.pos(), 1793 (stringSwitch ? Errors.StringConstReq 1794 : intSwitch ? Errors.ConstExprReq 1795 : Errors.PatternOrEnumReq)); 1796 } else if (!constants.add(s)) { 1797 log.error(label.pos(), Errors.DuplicateCaseLabel); 1798 } 1799 } else if (!stringSwitch && !intSwitch && !errorPrimitiveSwitch) { 1800 log.error(label.pos(), Errors.ConstantLabelNotCompatible(pattype, seltype)); 1801 } else if (!constants.add(pattype.constValue())) { 1802 log.error(c.pos(), Errors.DuplicateCaseLabel); 1803 } 1804 } 1805 } 1806 } else if (label instanceof JCDefaultCaseLabel def) { 1807 if (hasDefault) { 1808 log.error(label.pos(), Errors.DuplicateDefaultLabel); 1809 } else if (hasUnconditionalPattern) { 1810 log.error(label.pos(), Errors.UnconditionalPatternAndDefault); 1811 } 1812 hasDefault = true; 1813 matchBindings = MatchBindingsComputer.EMPTY; 1814 } else if (label instanceof JCPatternCaseLabel patternlabel) { 1815 //pattern 1816 JCPattern pat = patternlabel.pat; 1817 attribExpr(pat, switchEnv, seltype); 1818 Type primaryType = TreeInfo.primaryPatternType(pat); 1819 if (!primaryType.hasTag(TYPEVAR)) { 1820 primaryType = chk.checkClassOrArrayType(pat.pos(), primaryType); 1821 } 1822 if (!errorPrimitiveSwitch) { 1823 checkCastablePattern(pat.pos(), seltype, primaryType); 1824 } 1825 Type patternType = types.erasure(primaryType); 1826 JCExpression guard = c.guard; 1827 if (guardBindings == null && guard != null) { 1828 MatchBindings afterPattern = matchBindings; 1829 Env<AttrContext> bodyEnv = bindingEnv(switchEnv, matchBindings.bindingsWhenTrue); 1830 try { 1831 attribExpr(guard, bodyEnv, syms.booleanType); 1832 } finally { 1833 bodyEnv.info.scope.leave(); 1834 } 1835 1836 guardBindings = matchBindings; 1837 matchBindings = afterPattern; 1838 1839 if (TreeInfo.isBooleanWithValue(guard, 0)) { 1840 log.error(guard.pos(), Errors.GuardHasConstantExpressionFalse); 1841 } 1842 } 1843 boolean unguarded = TreeInfo.unguardedCase(c) && !pat.hasTag(RECORDPATTERN); 1844 boolean unconditional = 1845 unguarded && 1846 !patternType.isErroneous() && 1847 types.isSubtype(types.boxedTypeOrType(types.erasure(seltype)), 1848 patternType); 1849 if (unconditional) { 1850 if (hasUnconditionalPattern) { 1851 log.error(pat.pos(), Errors.DuplicateUnconditionalPattern); 1852 } else if (hasDefault) { 1853 log.error(pat.pos(), Errors.UnconditionalPatternAndDefault); 1854 } 1855 hasUnconditionalPattern = true; 1856 } 1857 lastPatternErroneous = patternType.isErroneous(); 1858 } else { 1859 Assert.error(); 1860 } 1861 currentBindings = matchBindingsComputer.switchCase(label, currentBindings, matchBindings); 1862 } 1863 1864 if (guardBindings != null) { 1865 currentBindings = matchBindingsComputer.caseGuard(c, currentBindings, guardBindings); 1866 } 1867 1868 Env<AttrContext> caseEnv = 1869 bindingEnv(switchEnv, c, currentBindings.bindingsWhenTrue); 1870 try { 1871 attribCase.accept(c, caseEnv); 1872 } finally { 1873 caseEnv.info.scope.leave(); 1874 } 1875 addVars(c.stats, switchEnv.info.scope); 1876 1877 preFlow(c); 1878 c.completesNormally = flow.aliveAfter(caseEnv, c, make); 1879 } 1880 if (patternSwitch) { 1881 chk.checkSwitchCaseStructure(cases); 1882 chk.checkSwitchCaseLabelDominated(cases); 1883 } 1884 if (switchTree.hasTag(SWITCH)) { 1885 ((JCSwitch) switchTree).hasUnconditionalPattern = 1886 hasDefault || hasUnconditionalPattern || lastPatternErroneous; 1887 ((JCSwitch) switchTree).patternSwitch = patternSwitch; 1888 } else if (switchTree.hasTag(SWITCH_EXPRESSION)) { 1889 ((JCSwitchExpression) switchTree).hasUnconditionalPattern = 1890 hasDefault || hasUnconditionalPattern || lastPatternErroneous; 1891 ((JCSwitchExpression) switchTree).patternSwitch = patternSwitch; 1892 } else { 1893 Assert.error(switchTree.getTag().name()); 1894 } 1895 } finally { 1896 switchEnv.info.scope.leave(); 1897 } 1898 } 1899 // where 1900 private ResultInfo caseLabelResultInfo(Type seltype) { 1901 return new ResultInfo(KindSelector.VAL_TYP, 1902 !seltype.hasTag(ERROR) ? seltype 1903 : Type.noType); 1904 } 1905 /** Add any variables defined in stats to the switch scope. */ 1906 private static void addVars(List<JCStatement> stats, WriteableScope switchScope) { 1907 for (;stats.nonEmpty(); stats = stats.tail) { 1908 JCTree stat = stats.head; 1909 if (stat.hasTag(VARDEF)) 1910 switchScope.enter(((JCVariableDecl) stat).sym); 1911 } 1912 } 1913 // where 1914 /** Return the selected enumeration constant symbol, or null. */ 1915 private Symbol enumConstant(JCTree tree, Type enumType) { 1916 if (tree.hasTag(IDENT)) { 1917 JCIdent ident = (JCIdent)tree; 1918 Name name = ident.name; 1919 for (Symbol sym : enumType.tsym.members().getSymbolsByName(name)) { 1920 if (sym.kind == VAR) { 1921 Symbol s = ident.sym = sym; 1922 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated 1923 ident.type = s.type; 1924 return ((s.flags_field & Flags.ENUM) == 0) 1925 ? null : s; 1926 } 1927 } 1928 } 1929 return null; 1930 } 1931 1932 public void visitSynchronized(JCSynchronized tree) { 1933 chk.checkIdentityType(tree.pos(), attribExpr(tree.lock, env)); 1934 if (env.info.lint.isEnabled(LintCategory.SYNCHRONIZATION) && isValueBased(tree.lock.type)) { 1935 log.warning(LintCategory.SYNCHRONIZATION, tree.pos(), Warnings.AttemptToSynchronizeOnInstanceOfValueBasedClass); 1936 } 1937 attribStat(tree.body, env); 1938 result = null; 1939 } 1940 // where 1941 private boolean isValueBased(Type t) { 1942 return t != null && t.tsym != null && (t.tsym.flags() & VALUE_BASED) != 0; 1943 } 1944 1945 1946 public void visitTry(JCTry tree) { 1947 // Create a new local environment with a local 1948 Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup())); 1949 try { 1950 boolean isTryWithResource = tree.resources.nonEmpty(); 1951 // Create a nested environment for attributing the try block if needed 1952 Env<AttrContext> tryEnv = isTryWithResource ? 1953 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) : 1954 localEnv; 1955 try { 1956 // Attribute resource declarations 1957 for (JCTree resource : tree.resources) { 1958 CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) { 1959 @Override 1960 public void report(DiagnosticPosition pos, JCDiagnostic details) { 1961 chk.basicHandler.report(pos, diags.fragment(Fragments.TryNotApplicableToType(details))); 1962 } 1963 }; 1964 ResultInfo twrResult = 1965 new ResultInfo(KindSelector.VAR, 1966 syms.autoCloseableType, 1967 twrContext); 1968 if (resource.hasTag(VARDEF)) { 1969 attribStat(resource, tryEnv); 1970 twrResult.check(resource, resource.type); 1971 1972 //check that resource type cannot throw InterruptedException 1973 checkAutoCloseable(resource.pos(), localEnv, resource.type); 1974 1975 VarSymbol var = ((JCVariableDecl) resource).sym; 1976 1977 var.flags_field |= Flags.FINAL; 1978 var.setData(ElementKind.RESOURCE_VARIABLE); 1979 } else { 1980 attribTree(resource, tryEnv, twrResult); 1981 } 1982 } 1983 // Attribute body 1984 attribStat(tree.body, tryEnv); 1985 } finally { 1986 if (isTryWithResource) 1987 tryEnv.info.scope.leave(); 1988 } 1989 1990 // Attribute catch clauses 1991 for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) { 1992 JCCatch c = l.head; 1993 Env<AttrContext> catchEnv = 1994 localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup())); 1995 try { 1996 Type ctype = attribStat(c.param, catchEnv); 1997 if (TreeInfo.isMultiCatch(c)) { 1998 //multi-catch parameter is implicitly marked as final 1999 c.param.sym.flags_field |= FINAL | UNION; 2000 } 2001 if (c.param.sym.kind == VAR) { 2002 c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER); 2003 } 2004 chk.checkType(c.param.vartype.pos(), 2005 chk.checkClassType(c.param.vartype.pos(), ctype), 2006 syms.throwableType); 2007 attribStat(c.body, catchEnv); 2008 } finally { 2009 catchEnv.info.scope.leave(); 2010 } 2011 } 2012 2013 // Attribute finalizer 2014 if (tree.finalizer != null) attribStat(tree.finalizer, localEnv); 2015 result = null; 2016 } 2017 finally { 2018 localEnv.info.scope.leave(); 2019 } 2020 } 2021 2022 void checkAutoCloseable(DiagnosticPosition pos, Env<AttrContext> env, Type resource) { 2023 if (!resource.isErroneous() && 2024 types.asSuper(resource, syms.autoCloseableType.tsym) != null && 2025 !types.isSameType(resource, syms.autoCloseableType)) { // Don't emit warning for AutoCloseable itself 2026 Symbol close = syms.noSymbol; 2027 Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log); 2028 try { 2029 close = rs.resolveQualifiedMethod(pos, 2030 env, 2031 types.skipTypeVars(resource, false), 2032 names.close, 2033 List.nil(), 2034 List.nil()); 2035 } 2036 finally { 2037 log.popDiagnosticHandler(discardHandler); 2038 } 2039 if (close.kind == MTH && 2040 close.overrides(syms.autoCloseableClose, resource.tsym, types, true) && 2041 chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes()) && 2042 env.info.lint.isEnabled(LintCategory.TRY)) { 2043 log.warning(LintCategory.TRY, pos, Warnings.TryResourceThrowsInterruptedExc(resource)); 2044 } 2045 } 2046 } 2047 2048 public void visitConditional(JCConditional tree) { 2049 Type condtype = attribExpr(tree.cond, env, syms.booleanType); 2050 MatchBindings condBindings = matchBindings; 2051 2052 tree.polyKind = (pt().hasTag(NONE) && pt() != Type.recoveryType && pt() != Infer.anyPoly || 2053 isBooleanOrNumeric(env, tree)) ? 2054 PolyKind.STANDALONE : PolyKind.POLY; 2055 2056 if (tree.polyKind == PolyKind.POLY && resultInfo.pt.hasTag(VOID)) { 2057 //this means we are returning a poly conditional from void-compatible lambda expression 2058 resultInfo.checkContext.report(tree, diags.fragment(Fragments.ConditionalTargetCantBeVoid)); 2059 result = tree.type = types.createErrorType(resultInfo.pt); 2060 return; 2061 } 2062 2063 ResultInfo condInfo = tree.polyKind == PolyKind.STANDALONE ? 2064 unknownExprInfo : 2065 resultInfo.dup(conditionalContext(resultInfo.checkContext)); 2066 2067 2068 // x ? y : z 2069 // include x's bindings when true in y 2070 // include x's bindings when false in z 2071 2072 Type truetype; 2073 Env<AttrContext> trueEnv = bindingEnv(env, condBindings.bindingsWhenTrue); 2074 try { 2075 truetype = attribTree(tree.truepart, trueEnv, condInfo); 2076 } finally { 2077 trueEnv.info.scope.leave(); 2078 } 2079 2080 MatchBindings trueBindings = matchBindings; 2081 2082 Type falsetype; 2083 Env<AttrContext> falseEnv = bindingEnv(env, condBindings.bindingsWhenFalse); 2084 try { 2085 falsetype = attribTree(tree.falsepart, falseEnv, condInfo); 2086 } finally { 2087 falseEnv.info.scope.leave(); 2088 } 2089 2090 MatchBindings falseBindings = matchBindings; 2091 2092 Type owntype = (tree.polyKind == PolyKind.STANDALONE) ? 2093 condType(List.of(tree.truepart.pos(), tree.falsepart.pos()), 2094 List.of(truetype, falsetype)) : pt(); 2095 if (condtype.constValue() != null && 2096 truetype.constValue() != null && 2097 falsetype.constValue() != null && 2098 !owntype.hasTag(NONE)) { 2099 //constant folding 2100 owntype = cfolder.coerce(condtype.isTrue() ? truetype : falsetype, owntype); 2101 } 2102 result = check(tree, owntype, KindSelector.VAL, resultInfo); 2103 matchBindings = matchBindingsComputer.conditional(tree, condBindings, trueBindings, falseBindings); 2104 } 2105 //where 2106 private boolean isBooleanOrNumeric(Env<AttrContext> env, JCExpression tree) { 2107 switch (tree.getTag()) { 2108 case LITERAL: return ((JCLiteral)tree).typetag.isSubRangeOf(DOUBLE) || 2109 ((JCLiteral)tree).typetag == BOOLEAN || 2110 ((JCLiteral)tree).typetag == BOT; 2111 case LAMBDA: case REFERENCE: return false; 2112 case PARENS: return isBooleanOrNumeric(env, ((JCParens)tree).expr); 2113 case CONDEXPR: 2114 JCConditional condTree = (JCConditional)tree; 2115 return isBooleanOrNumeric(env, condTree.truepart) && 2116 isBooleanOrNumeric(env, condTree.falsepart); 2117 case APPLY: 2118 JCMethodInvocation speculativeMethodTree = 2119 (JCMethodInvocation)deferredAttr.attribSpeculative( 2120 tree, env, unknownExprInfo, 2121 argumentAttr.withLocalCacheContext()); 2122 Symbol msym = TreeInfo.symbol(speculativeMethodTree.meth); 2123 Type receiverType = speculativeMethodTree.meth.hasTag(IDENT) ? 2124 env.enclClass.type : 2125 ((JCFieldAccess)speculativeMethodTree.meth).selected.type; 2126 Type owntype = types.memberType(receiverType, msym).getReturnType(); 2127 return primitiveOrBoxed(owntype); 2128 case NEWCLASS: 2129 JCExpression className = 2130 removeClassParams.translate(((JCNewClass)tree).clazz); 2131 JCExpression speculativeNewClassTree = 2132 (JCExpression)deferredAttr.attribSpeculative( 2133 className, env, unknownTypeInfo, 2134 argumentAttr.withLocalCacheContext()); 2135 return primitiveOrBoxed(speculativeNewClassTree.type); 2136 default: 2137 Type speculativeType = deferredAttr.attribSpeculative(tree, env, unknownExprInfo, 2138 argumentAttr.withLocalCacheContext()).type; 2139 return primitiveOrBoxed(speculativeType); 2140 } 2141 } 2142 //where 2143 boolean primitiveOrBoxed(Type t) { 2144 return (!t.hasTag(TYPEVAR) && !t.isErroneous() && types.unboxedTypeOrType(t).isPrimitive()); 2145 } 2146 2147 TreeTranslator removeClassParams = new TreeTranslator() { 2148 @Override 2149 public void visitTypeApply(JCTypeApply tree) { 2150 result = translate(tree.clazz); 2151 } 2152 }; 2153 2154 CheckContext conditionalContext(CheckContext checkContext) { 2155 return new Check.NestedCheckContext(checkContext) { 2156 //this will use enclosing check context to check compatibility of 2157 //subexpression against target type; if we are in a method check context, 2158 //depending on whether boxing is allowed, we could have incompatibilities 2159 @Override 2160 public void report(DiagnosticPosition pos, JCDiagnostic details) { 2161 enclosingContext.report(pos, diags.fragment(Fragments.IncompatibleTypeInConditional(details))); 2162 } 2163 }; 2164 } 2165 2166 /** Compute the type of a conditional expression, after 2167 * checking that it exists. See JLS 15.25. Does not take into 2168 * account the special case where condition and both arms 2169 * are constants. 2170 * 2171 * @param pos The source position to be used for error 2172 * diagnostics. 2173 * @param thentype The type of the expression's then-part. 2174 * @param elsetype The type of the expression's else-part. 2175 */ 2176 Type condType(List<DiagnosticPosition> positions, List<Type> condTypes) { 2177 if (condTypes.isEmpty()) { 2178 return syms.objectType; //TODO: how to handle? 2179 } 2180 Type first = condTypes.head; 2181 // If same type, that is the result 2182 if (condTypes.tail.stream().allMatch(t -> types.isSameType(first, t))) 2183 return first.baseType(); 2184 2185 List<Type> unboxedTypes = condTypes.stream() 2186 .map(t -> t.isPrimitive() ? t : types.unboxedType(t)) 2187 .collect(List.collector()); 2188 2189 // Otherwise, if both arms can be converted to a numeric 2190 // type, return the least numeric type that fits both arms 2191 // (i.e. return larger of the two, or return int if one 2192 // arm is short, the other is char). 2193 if (unboxedTypes.stream().allMatch(t -> t.isPrimitive())) { 2194 // If one arm has an integer subrange type (i.e., byte, 2195 // short, or char), and the other is an integer constant 2196 // that fits into the subrange, return the subrange type. 2197 for (Type type : unboxedTypes) { 2198 if (!type.getTag().isStrictSubRangeOf(INT)) { 2199 continue; 2200 } 2201 if (unboxedTypes.stream().filter(t -> t != type).allMatch(t -> t.hasTag(INT) && types.isAssignable(t, type))) 2202 return type.baseType(); 2203 } 2204 2205 for (TypeTag tag : primitiveTags) { 2206 Type candidate = syms.typeOfTag[tag.ordinal()]; 2207 if (unboxedTypes.stream().allMatch(t -> types.isSubtype(t, candidate))) { 2208 return candidate; 2209 } 2210 } 2211 } 2212 2213 // Those were all the cases that could result in a primitive 2214 condTypes = condTypes.stream() 2215 .map(t -> t.isPrimitive() ? types.boxedClass(t).type : t) 2216 .collect(List.collector()); 2217 2218 for (Type type : condTypes) { 2219 if (condTypes.stream().filter(t -> t != type).allMatch(t -> types.isAssignable(t, type))) 2220 return type.baseType(); 2221 } 2222 2223 Iterator<DiagnosticPosition> posIt = positions.iterator(); 2224 2225 condTypes = condTypes.stream() 2226 .map(t -> chk.checkNonVoid(posIt.next(), t)) 2227 .collect(List.collector()); 2228 2229 // both are known to be reference types. The result is 2230 // lub(thentype,elsetype). This cannot fail, as it will 2231 // always be possible to infer "Object" if nothing better. 2232 return types.lub(condTypes.stream() 2233 .map(t -> t.baseType()) 2234 .filter(t -> !t.hasTag(BOT)) 2235 .collect(List.collector())); 2236 } 2237 2238 static final TypeTag[] primitiveTags = new TypeTag[]{ 2239 BYTE, 2240 CHAR, 2241 SHORT, 2242 INT, 2243 LONG, 2244 FLOAT, 2245 DOUBLE, 2246 BOOLEAN, 2247 }; 2248 2249 Env<AttrContext> bindingEnv(Env<AttrContext> env, List<BindingSymbol> bindings) { 2250 return bindingEnv(env, env.tree, bindings); 2251 } 2252 2253 Env<AttrContext> bindingEnv(Env<AttrContext> env, JCTree newTree, List<BindingSymbol> bindings) { 2254 Env<AttrContext> env1 = env.dup(newTree, env.info.dup(env.info.scope.dup())); 2255 bindings.forEach(env1.info.scope::enter); 2256 return env1; 2257 } 2258 2259 public void visitIf(JCIf tree) { 2260 attribExpr(tree.cond, env, syms.booleanType); 2261 2262 // if (x) { y } [ else z ] 2263 // include x's bindings when true in y 2264 // include x's bindings when false in z 2265 2266 MatchBindings condBindings = matchBindings; 2267 Env<AttrContext> thenEnv = bindingEnv(env, condBindings.bindingsWhenTrue); 2268 2269 try { 2270 attribStat(tree.thenpart, thenEnv); 2271 } finally { 2272 thenEnv.info.scope.leave(); 2273 } 2274 2275 preFlow(tree.thenpart); 2276 boolean aliveAfterThen = flow.aliveAfter(env, tree.thenpart, make); 2277 boolean aliveAfterElse; 2278 2279 if (tree.elsepart != null) { 2280 Env<AttrContext> elseEnv = bindingEnv(env, condBindings.bindingsWhenFalse); 2281 try { 2282 attribStat(tree.elsepart, elseEnv); 2283 } finally { 2284 elseEnv.info.scope.leave(); 2285 } 2286 preFlow(tree.elsepart); 2287 aliveAfterElse = flow.aliveAfter(env, tree.elsepart, make); 2288 } else { 2289 aliveAfterElse = true; 2290 } 2291 2292 chk.checkEmptyIf(tree); 2293 2294 List<BindingSymbol> afterIfBindings = List.nil(); 2295 2296 if (aliveAfterThen && !aliveAfterElse) { 2297 afterIfBindings = condBindings.bindingsWhenTrue; 2298 } else if (aliveAfterElse && !aliveAfterThen) { 2299 afterIfBindings = condBindings.bindingsWhenFalse; 2300 } 2301 2302 addBindings2Scope(tree, afterIfBindings); 2303 2304 result = null; 2305 } 2306 2307 void preFlow(JCTree tree) { 2308 attrRecover.doRecovery(); 2309 new PostAttrAnalyzer() { 2310 @Override 2311 public void scan(JCTree tree) { 2312 if (tree == null || 2313 (tree.type != null && 2314 tree.type == Type.stuckType)) { 2315 //don't touch stuck expressions! 2316 return; 2317 } 2318 super.scan(tree); 2319 } 2320 2321 @Override 2322 public void visitClassDef(JCClassDecl that) { 2323 if (that.sym != null) { 2324 // Method preFlow shouldn't visit class definitions 2325 // that have not been entered and attributed. 2326 // See JDK-8254557 and JDK-8203277 for more details. 2327 super.visitClassDef(that); 2328 } 2329 } 2330 2331 @Override 2332 public void visitLambda(JCLambda that) { 2333 if (that.type != null) { 2334 // Method preFlow shouldn't visit lambda expressions 2335 // that have not been entered and attributed. 2336 // See JDK-8254557 and JDK-8203277 for more details. 2337 super.visitLambda(that); 2338 } 2339 } 2340 }.scan(tree); 2341 } 2342 2343 public void visitExec(JCExpressionStatement tree) { 2344 //a fresh environment is required for 292 inference to work properly --- 2345 //see Infer.instantiatePolymorphicSignatureInstance() 2346 Env<AttrContext> localEnv = env.dup(tree); 2347 attribExpr(tree.expr, localEnv); 2348 result = null; 2349 } 2350 2351 public void visitBreak(JCBreak tree) { 2352 tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env); 2353 result = null; 2354 } 2355 2356 public void visitYield(JCYield tree) { 2357 if (env.info.yieldResult != null) { 2358 attribTree(tree.value, env, env.info.yieldResult); 2359 tree.target = findJumpTarget(tree.pos(), tree.getTag(), names.empty, env); 2360 } else { 2361 log.error(tree.pos(), tree.value.hasTag(PARENS) 2362 ? Errors.NoSwitchExpressionQualify 2363 : Errors.NoSwitchExpression); 2364 attribTree(tree.value, env, unknownExprInfo); 2365 } 2366 result = null; 2367 } 2368 2369 public void visitContinue(JCContinue tree) { 2370 tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env); 2371 result = null; 2372 } 2373 //where 2374 /** Return the target of a break, continue or yield statement, 2375 * if it exists, report an error if not. 2376 * Note: The target of a labelled break or continue is the 2377 * (non-labelled) statement tree referred to by the label, 2378 * not the tree representing the labelled statement itself. 2379 * 2380 * @param pos The position to be used for error diagnostics 2381 * @param tag The tag of the jump statement. This is either 2382 * Tree.BREAK or Tree.CONTINUE. 2383 * @param label The label of the jump statement, or null if no 2384 * label is given. 2385 * @param env The environment current at the jump statement. 2386 */ 2387 private JCTree findJumpTarget(DiagnosticPosition pos, 2388 JCTree.Tag tag, 2389 Name label, 2390 Env<AttrContext> env) { 2391 Pair<JCTree, Error> jumpTarget = findJumpTargetNoError(tag, label, env); 2392 2393 if (jumpTarget.snd != null) { 2394 log.error(pos, jumpTarget.snd); 2395 } 2396 2397 return jumpTarget.fst; 2398 } 2399 /** Return the target of a break or continue statement, if it exists, 2400 * report an error if not. 2401 * Note: The target of a labelled break or continue is the 2402 * (non-labelled) statement tree referred to by the label, 2403 * not the tree representing the labelled statement itself. 2404 * 2405 * @param tag The tag of the jump statement. This is either 2406 * Tree.BREAK or Tree.CONTINUE. 2407 * @param label The label of the jump statement, or null if no 2408 * label is given. 2409 * @param env The environment current at the jump statement. 2410 */ 2411 private Pair<JCTree, JCDiagnostic.Error> findJumpTargetNoError(JCTree.Tag tag, 2412 Name label, 2413 Env<AttrContext> env) { 2414 // Search environments outwards from the point of jump. 2415 Env<AttrContext> env1 = env; 2416 JCDiagnostic.Error pendingError = null; 2417 LOOP: 2418 while (env1 != null) { 2419 switch (env1.tree.getTag()) { 2420 case LABELLED: 2421 JCLabeledStatement labelled = (JCLabeledStatement)env1.tree; 2422 if (label == labelled.label) { 2423 // If jump is a continue, check that target is a loop. 2424 if (tag == CONTINUE) { 2425 if (!labelled.body.hasTag(DOLOOP) && 2426 !labelled.body.hasTag(WHILELOOP) && 2427 !labelled.body.hasTag(FORLOOP) && 2428 !labelled.body.hasTag(FOREACHLOOP)) { 2429 pendingError = Errors.NotLoopLabel(label); 2430 } 2431 // Found labelled statement target, now go inwards 2432 // to next non-labelled tree. 2433 return Pair.of(TreeInfo.referencedStatement(labelled), pendingError); 2434 } else { 2435 return Pair.of(labelled, pendingError); 2436 } 2437 } 2438 break; 2439 case DOLOOP: 2440 case WHILELOOP: 2441 case FORLOOP: 2442 case FOREACHLOOP: 2443 if (label == null) return Pair.of(env1.tree, pendingError); 2444 break; 2445 case SWITCH: 2446 if (label == null && tag == BREAK) return Pair.of(env1.tree, null); 2447 break; 2448 case SWITCH_EXPRESSION: 2449 if (tag == YIELD) { 2450 return Pair.of(env1.tree, null); 2451 } else if (tag == BREAK) { 2452 pendingError = Errors.BreakOutsideSwitchExpression; 2453 } else { 2454 pendingError = Errors.ContinueOutsideSwitchExpression; 2455 } 2456 break; 2457 case LAMBDA: 2458 case METHODDEF: 2459 case CLASSDEF: 2460 break LOOP; 2461 default: 2462 } 2463 env1 = env1.next; 2464 } 2465 if (label != null) 2466 return Pair.of(null, Errors.UndefLabel(label)); 2467 else if (pendingError != null) 2468 return Pair.of(null, pendingError); 2469 else if (tag == CONTINUE) 2470 return Pair.of(null, Errors.ContOutsideLoop); 2471 else 2472 return Pair.of(null, Errors.BreakOutsideSwitchLoop); 2473 } 2474 2475 public void visitReturn(JCReturn tree) { 2476 // Check that there is an enclosing method which is 2477 // nested within than the enclosing class. 2478 if (env.info.returnResult == null) { 2479 log.error(tree.pos(), Errors.RetOutsideMeth); 2480 } else if (env.info.yieldResult != null) { 2481 log.error(tree.pos(), Errors.ReturnOutsideSwitchExpression); 2482 } else if (!env.info.isLambda && 2483 !env.info.isNewClass && 2484 env.enclMethod != null && 2485 TreeInfo.isCompactConstructor(env.enclMethod)) { 2486 log.error(env.enclMethod, 2487 Errors.InvalidCanonicalConstructorInRecord(Fragments.Compact, env.enclMethod.sym.name, Fragments.CanonicalCantHaveReturnStatement)); 2488 } else { 2489 // Attribute return expression, if it exists, and check that 2490 // it conforms to result type of enclosing method. 2491 if (tree.expr != null) { 2492 if (env.info.returnResult.pt.hasTag(VOID)) { 2493 env.info.returnResult.checkContext.report(tree.expr.pos(), 2494 diags.fragment(Fragments.UnexpectedRetVal)); 2495 } 2496 attribTree(tree.expr, env, env.info.returnResult); 2497 } else if (!env.info.returnResult.pt.hasTag(VOID) && 2498 !env.info.returnResult.pt.hasTag(NONE)) { 2499 env.info.returnResult.checkContext.report(tree.pos(), 2500 diags.fragment(Fragments.MissingRetVal(env.info.returnResult.pt))); 2501 } 2502 } 2503 result = null; 2504 } 2505 2506 public void visitThrow(JCThrow tree) { 2507 Type owntype = attribExpr(tree.expr, env, Type.noType); 2508 chk.checkType(tree, owntype, syms.throwableType); 2509 result = null; 2510 } 2511 2512 public void visitAssert(JCAssert tree) { 2513 attribExpr(tree.cond, env, syms.booleanType); 2514 if (tree.detail != null) { 2515 chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env)); 2516 } 2517 result = null; 2518 } 2519 2520 /** Visitor method for method invocations. 2521 * NOTE: The method part of an application will have in its type field 2522 * the return type of the method, not the method's type itself! 2523 */ 2524 public void visitApply(JCMethodInvocation tree) { 2525 // The local environment of a method application is 2526 // a new environment nested in the current one. 2527 Env<AttrContext> localEnv = env.dup(tree, env.info.dup()); 2528 2529 // The types of the actual method arguments. 2530 List<Type> argtypes; 2531 2532 // The types of the actual method type arguments. 2533 List<Type> typeargtypes = null; 2534 2535 Name methName = TreeInfo.name(tree.meth); 2536 2537 boolean isConstructorCall = 2538 methName == names._this || methName == names._super; 2539 2540 ListBuffer<Type> argtypesBuf = new ListBuffer<>(); 2541 if (isConstructorCall) { 2542 2543 // Attribute arguments, yielding list of argument types. 2544 KindSelector kind = attribArgs(KindSelector.MTH, tree.args, localEnv, argtypesBuf); 2545 argtypes = argtypesBuf.toList(); 2546 typeargtypes = attribTypes(tree.typeargs, localEnv); 2547 2548 // Done with this()/super() parameters. End of constructor prologue. 2549 env.info.ctorPrologue = false; 2550 2551 // Variable `site' points to the class in which the called 2552 // constructor is defined. 2553 Type site = env.enclClass.sym.type; 2554 if (methName == names._super) { 2555 if (site == syms.objectType) { 2556 log.error(tree.meth.pos(), Errors.NoSuperclass(site)); 2557 site = types.createErrorType(syms.objectType); 2558 } else { 2559 site = types.supertype(site); 2560 } 2561 } 2562 2563 if (site.hasTag(CLASS)) { 2564 Type encl = site.getEnclosingType(); 2565 while (encl != null && encl.hasTag(TYPEVAR)) 2566 encl = encl.getUpperBound(); 2567 if (encl.hasTag(CLASS)) { 2568 // we are calling a nested class 2569 2570 if (tree.meth.hasTag(SELECT)) { 2571 JCTree qualifier = ((JCFieldAccess) tree.meth).selected; 2572 2573 // We are seeing a prefixed call, of the form 2574 // <expr>.super(...). 2575 // Check that the prefix expression conforms 2576 // to the outer instance type of the class. 2577 chk.checkRefType(qualifier.pos(), 2578 attribExpr(qualifier, localEnv, 2579 encl)); 2580 } else if (methName == names._super) { 2581 // qualifier omitted; check for existence 2582 // of an appropriate implicit qualifier. 2583 rs.resolveImplicitThis(tree.meth.pos(), 2584 localEnv, site, true); 2585 } 2586 } else if (tree.meth.hasTag(SELECT)) { 2587 log.error(tree.meth.pos(), 2588 Errors.IllegalQualNotIcls(site.tsym)); 2589 attribExpr(((JCFieldAccess) tree.meth).selected, localEnv, site); 2590 } 2591 2592 // if we're calling a java.lang.Enum constructor, 2593 // prefix the implicit String and int parameters 2594 if (site.tsym == syms.enumSym) 2595 argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType); 2596 2597 // Resolve the called constructor under the assumption 2598 // that we are referring to a superclass instance of the 2599 // current instance (JLS ???). 2600 boolean selectSuperPrev = localEnv.info.selectSuper; 2601 localEnv.info.selectSuper = true; 2602 localEnv.info.pendingResolutionPhase = null; 2603 Symbol sym = rs.resolveConstructor( 2604 tree.meth.pos(), localEnv, site, argtypes, typeargtypes); 2605 localEnv.info.selectSuper = selectSuperPrev; 2606 2607 // Set method symbol to resolved constructor... 2608 TreeInfo.setSymbol(tree.meth, sym); 2609 2610 // ...and check that it is legal in the current context. 2611 // (this will also set the tree's type) 2612 Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes); 2613 checkId(tree.meth, site, sym, localEnv, 2614 new ResultInfo(kind, mpt)); 2615 } else if (site.hasTag(ERROR) && tree.meth.hasTag(SELECT)) { 2616 attribExpr(((JCFieldAccess) tree.meth).selected, localEnv, site); 2617 } 2618 // Otherwise, `site' is an error type and we do nothing 2619 result = tree.type = syms.voidType; 2620 } else { 2621 // Otherwise, we are seeing a regular method call. 2622 // Attribute the arguments, yielding list of argument types, ... 2623 KindSelector kind = attribArgs(KindSelector.VAL, tree.args, localEnv, argtypesBuf); 2624 argtypes = argtypesBuf.toList(); 2625 typeargtypes = attribAnyTypes(tree.typeargs, localEnv); 2626 2627 // ... and attribute the method using as a prototype a methodtype 2628 // whose formal argument types is exactly the list of actual 2629 // arguments (this will also set the method symbol). 2630 Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes); 2631 localEnv.info.pendingResolutionPhase = null; 2632 Type mtype = attribTree(tree.meth, localEnv, new ResultInfo(kind, mpt, resultInfo.checkContext)); 2633 2634 // Compute the result type. 2635 Type restype = mtype.getReturnType(); 2636 if (restype.hasTag(WILDCARD)) 2637 throw new AssertionError(mtype); 2638 2639 Type qualifier = (tree.meth.hasTag(SELECT)) 2640 ? ((JCFieldAccess) tree.meth).selected.type 2641 : env.enclClass.sym.type; 2642 Symbol msym = TreeInfo.symbol(tree.meth); 2643 restype = adjustMethodReturnType(msym, qualifier, methName, argtypes, restype); 2644 2645 chk.checkRefTypes(tree.typeargs, typeargtypes); 2646 2647 // Check that value of resulting type is admissible in the 2648 // current context. Also, capture the return type 2649 Type capturedRes = resultInfo.checkContext.inferenceContext().cachedCapture(tree, restype, true); 2650 result = check(tree, capturedRes, KindSelector.VAL, resultInfo); 2651 } 2652 chk.validate(tree.typeargs, localEnv); 2653 } 2654 //where 2655 Type adjustMethodReturnType(Symbol msym, Type qualifierType, Name methodName, List<Type> argtypes, Type restype) { 2656 if (msym != null && 2657 (msym.owner == syms.objectType.tsym || msym.owner.isInterface()) && 2658 methodName == names.getClass && 2659 argtypes.isEmpty()) { 2660 // as a special case, x.getClass() has type Class<? extends |X|> 2661 return new ClassType(restype.getEnclosingType(), 2662 List.of(new WildcardType(types.erasure(qualifierType.baseType()), 2663 BoundKind.EXTENDS, 2664 syms.boundClass)), 2665 restype.tsym, 2666 restype.getMetadata()); 2667 } else if (msym != null && 2668 msym.owner == syms.arrayClass && 2669 methodName == names.clone && 2670 types.isArray(qualifierType)) { 2671 // as a special case, array.clone() has a result that is 2672 // the same as static type of the array being cloned 2673 return qualifierType; 2674 } else { 2675 return restype; 2676 } 2677 } 2678 2679 /** Obtain a method type with given argument types. 2680 */ 2681 Type newMethodTemplate(Type restype, List<Type> argtypes, List<Type> typeargtypes) { 2682 MethodType mt = new MethodType(argtypes, restype, List.nil(), syms.methodClass); 2683 return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt); 2684 } 2685 2686 public void visitNewClass(final JCNewClass tree) { 2687 Type owntype = types.createErrorType(tree.type); 2688 2689 // The local environment of a class creation is 2690 // a new environment nested in the current one. 2691 Env<AttrContext> localEnv = env.dup(tree, env.info.dup()); 2692 2693 // The anonymous inner class definition of the new expression, 2694 // if one is defined by it. 2695 JCClassDecl cdef = tree.def; 2696 2697 // If enclosing class is given, attribute it, and 2698 // complete class name to be fully qualified 2699 JCExpression clazz = tree.clazz; // Class field following new 2700 JCExpression clazzid; // Identifier in class field 2701 JCAnnotatedType annoclazzid; // Annotated type enclosing clazzid 2702 annoclazzid = null; 2703 2704 if (clazz.hasTag(TYPEAPPLY)) { 2705 clazzid = ((JCTypeApply) clazz).clazz; 2706 if (clazzid.hasTag(ANNOTATED_TYPE)) { 2707 annoclazzid = (JCAnnotatedType) clazzid; 2708 clazzid = annoclazzid.underlyingType; 2709 } 2710 } else { 2711 if (clazz.hasTag(ANNOTATED_TYPE)) { 2712 annoclazzid = (JCAnnotatedType) clazz; 2713 clazzid = annoclazzid.underlyingType; 2714 } else { 2715 clazzid = clazz; 2716 } 2717 } 2718 2719 JCExpression clazzid1 = clazzid; // The same in fully qualified form 2720 2721 if (tree.encl != null) { 2722 // We are seeing a qualified new, of the form 2723 // <expr>.new C <...> (...) ... 2724 // In this case, we let clazz stand for the name of the 2725 // allocated class C prefixed with the type of the qualifier 2726 // expression, so that we can 2727 // resolve it with standard techniques later. I.e., if 2728 // <expr> has type T, then <expr>.new C <...> (...) 2729 // yields a clazz T.C. 2730 Type encltype = chk.checkRefType(tree.encl.pos(), 2731 attribExpr(tree.encl, env)); 2732 // TODO 308: in <expr>.new C, do we also want to add the type annotations 2733 // from expr to the combined type, or not? Yes, do this. 2734 clazzid1 = make.at(clazz.pos).Select(make.Type(encltype), 2735 ((JCIdent) clazzid).name); 2736 2737 EndPosTable endPosTable = this.env.toplevel.endPositions; 2738 endPosTable.storeEnd(clazzid1, clazzid.getEndPosition(endPosTable)); 2739 if (clazz.hasTag(ANNOTATED_TYPE)) { 2740 JCAnnotatedType annoType = (JCAnnotatedType) clazz; 2741 List<JCAnnotation> annos = annoType.annotations; 2742 2743 if (annoType.underlyingType.hasTag(TYPEAPPLY)) { 2744 clazzid1 = make.at(tree.pos). 2745 TypeApply(clazzid1, 2746 ((JCTypeApply) clazz).arguments); 2747 } 2748 2749 clazzid1 = make.at(tree.pos). 2750 AnnotatedType(annos, clazzid1); 2751 } else if (clazz.hasTag(TYPEAPPLY)) { 2752 clazzid1 = make.at(tree.pos). 2753 TypeApply(clazzid1, 2754 ((JCTypeApply) clazz).arguments); 2755 } 2756 2757 clazz = clazzid1; 2758 } 2759 2760 // Attribute clazz expression and store 2761 // symbol + type back into the attributed tree. 2762 Type clazztype; 2763 2764 try { 2765 env.info.isNewClass = true; 2766 clazztype = TreeInfo.isEnumInit(env.tree) ? 2767 attribIdentAsEnumType(env, (JCIdent)clazz) : 2768 attribType(clazz, env); 2769 } finally { 2770 env.info.isNewClass = false; 2771 } 2772 2773 clazztype = chk.checkDiamond(tree, clazztype); 2774 chk.validate(clazz, localEnv); 2775 if (tree.encl != null) { 2776 // We have to work in this case to store 2777 // symbol + type back into the attributed tree. 2778 tree.clazz.type = clazztype; 2779 TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1)); 2780 clazzid.type = ((JCIdent) clazzid).sym.type; 2781 if (annoclazzid != null) { 2782 annoclazzid.type = clazzid.type; 2783 } 2784 if (!clazztype.isErroneous()) { 2785 if (cdef != null && clazztype.tsym.isInterface()) { 2786 log.error(tree.encl.pos(), Errors.AnonClassImplIntfNoQualForNew); 2787 } else if (clazztype.tsym.isStatic()) { 2788 log.error(tree.encl.pos(), Errors.QualifiedNewOfStaticClass(clazztype.tsym)); 2789 } 2790 } 2791 } else if (!clazztype.tsym.isInterface() && 2792 clazztype.getEnclosingType().hasTag(CLASS)) { 2793 // Check for the existence of an apropos outer instance 2794 rs.resolveImplicitThis(tree.pos(), env, clazztype); 2795 } 2796 2797 // Attribute constructor arguments. 2798 ListBuffer<Type> argtypesBuf = new ListBuffer<>(); 2799 final KindSelector pkind = 2800 attribArgs(KindSelector.VAL, tree.args, localEnv, argtypesBuf); 2801 List<Type> argtypes = argtypesBuf.toList(); 2802 List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv); 2803 2804 if (clazztype.hasTag(CLASS) || clazztype.hasTag(ERROR)) { 2805 // Enums may not be instantiated except implicitly 2806 if ((clazztype.tsym.flags_field & Flags.ENUM) != 0 && 2807 (!env.tree.hasTag(VARDEF) || 2808 (((JCVariableDecl) env.tree).mods.flags & Flags.ENUM) == 0 || 2809 ((JCVariableDecl) env.tree).init != tree)) 2810 log.error(tree.pos(), Errors.EnumCantBeInstantiated); 2811 2812 boolean isSpeculativeDiamondInferenceRound = TreeInfo.isDiamond(tree) && 2813 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE; 2814 boolean skipNonDiamondPath = false; 2815 // Check that class is not abstract 2816 if (cdef == null && !isSpeculativeDiamondInferenceRound && // class body may be nulled out in speculative tree copy 2817 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) { 2818 log.error(tree.pos(), 2819 Errors.AbstractCantBeInstantiated(clazztype.tsym)); 2820 skipNonDiamondPath = true; 2821 } else if (cdef != null && clazztype.tsym.isInterface()) { 2822 // Check that no constructor arguments are given to 2823 // anonymous classes implementing an interface 2824 if (!argtypes.isEmpty()) 2825 log.error(tree.args.head.pos(), Errors.AnonClassImplIntfNoArgs); 2826 2827 if (!typeargtypes.isEmpty()) 2828 log.error(tree.typeargs.head.pos(), Errors.AnonClassImplIntfNoTypeargs); 2829 2830 // Error recovery: pretend no arguments were supplied. 2831 argtypes = List.nil(); 2832 typeargtypes = List.nil(); 2833 skipNonDiamondPath = true; 2834 } 2835 if (TreeInfo.isDiamond(tree)) { 2836 ClassType site = new ClassType(clazztype.getEnclosingType(), 2837 clazztype.tsym.type.getTypeArguments(), 2838 clazztype.tsym, 2839 clazztype.getMetadata()); 2840 2841 Env<AttrContext> diamondEnv = localEnv.dup(tree); 2842 diamondEnv.info.selectSuper = cdef != null || tree.classDeclRemoved(); 2843 diamondEnv.info.pendingResolutionPhase = null; 2844 2845 //if the type of the instance creation expression is a class type 2846 //apply method resolution inference (JLS 15.12.2.7). The return type 2847 //of the resolved constructor will be a partially instantiated type 2848 Symbol constructor = rs.resolveDiamond(tree.pos(), 2849 diamondEnv, 2850 site, 2851 argtypes, 2852 typeargtypes); 2853 tree.constructor = constructor.baseSymbol(); 2854 2855 final TypeSymbol csym = clazztype.tsym; 2856 ResultInfo diamondResult = new ResultInfo(pkind, newMethodTemplate(resultInfo.pt, argtypes, typeargtypes), 2857 diamondContext(tree, csym, resultInfo.checkContext), CheckMode.NO_TREE_UPDATE); 2858 Type constructorType = tree.constructorType = types.createErrorType(clazztype); 2859 constructorType = checkId(tree, site, 2860 constructor, 2861 diamondEnv, 2862 diamondResult); 2863 2864 tree.clazz.type = types.createErrorType(clazztype); 2865 if (!constructorType.isErroneous()) { 2866 tree.clazz.type = clazz.type = constructorType.getReturnType(); 2867 tree.constructorType = types.createMethodTypeWithReturn(constructorType, syms.voidType); 2868 } 2869 clazztype = chk.checkClassType(tree.clazz, tree.clazz.type, true); 2870 } 2871 2872 // Resolve the called constructor under the assumption 2873 // that we are referring to a superclass instance of the 2874 // current instance (JLS ???). 2875 else if (!skipNonDiamondPath) { 2876 //the following code alters some of the fields in the current 2877 //AttrContext - hence, the current context must be dup'ed in 2878 //order to avoid downstream failures 2879 Env<AttrContext> rsEnv = localEnv.dup(tree); 2880 rsEnv.info.selectSuper = cdef != null; 2881 rsEnv.info.pendingResolutionPhase = null; 2882 tree.constructor = rs.resolveConstructor( 2883 tree.pos(), rsEnv, clazztype, argtypes, typeargtypes); 2884 if (cdef == null) { //do not check twice! 2885 tree.constructorType = checkId(tree, 2886 clazztype, 2887 tree.constructor, 2888 rsEnv, 2889 new ResultInfo(pkind, newMethodTemplate(syms.voidType, argtypes, typeargtypes), CheckMode.NO_TREE_UPDATE)); 2890 if (rsEnv.info.lastResolveVarargs()) 2891 Assert.check(tree.constructorType.isErroneous() || tree.varargsElement != null); 2892 } 2893 } 2894 2895 if (cdef != null) { 2896 visitAnonymousClassDefinition(tree, clazz, clazztype, cdef, localEnv, argtypes, typeargtypes, pkind); 2897 return; 2898 } 2899 2900 if (tree.constructor != null && tree.constructor.kind == MTH) 2901 owntype = clazztype; 2902 } 2903 result = check(tree, owntype, KindSelector.VAL, resultInfo); 2904 InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext(); 2905 if (tree.constructorType != null && inferenceContext.free(tree.constructorType)) { 2906 //we need to wait for inference to finish and then replace inference vars in the constructor type 2907 inferenceContext.addFreeTypeListener(List.of(tree.constructorType), 2908 instantiatedContext -> { 2909 tree.constructorType = instantiatedContext.asInstType(tree.constructorType); 2910 }); 2911 } 2912 chk.validate(tree.typeargs, localEnv); 2913 } 2914 2915 // where 2916 private void visitAnonymousClassDefinition(JCNewClass tree, JCExpression clazz, Type clazztype, 2917 JCClassDecl cdef, Env<AttrContext> localEnv, 2918 List<Type> argtypes, List<Type> typeargtypes, 2919 KindSelector pkind) { 2920 // We are seeing an anonymous class instance creation. 2921 // In this case, the class instance creation 2922 // expression 2923 // 2924 // E.new <typeargs1>C<typargs2>(args) { ... } 2925 // 2926 // is represented internally as 2927 // 2928 // E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } ) . 2929 // 2930 // This expression is then *transformed* as follows: 2931 // 2932 // (1) add an extends or implements clause 2933 // (2) add a constructor. 2934 // 2935 // For instance, if C is a class, and ET is the type of E, 2936 // the expression 2937 // 2938 // E.new <typeargs1>C<typargs2>(args) { ... } 2939 // 2940 // is translated to (where X is a fresh name and typarams is the 2941 // parameter list of the super constructor): 2942 // 2943 // new <typeargs1>X(<*nullchk*>E, args) where 2944 // X extends C<typargs2> { 2945 // <typarams> X(ET e, args) { 2946 // e.<typeargs1>super(args) 2947 // } 2948 // ... 2949 // } 2950 InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext(); 2951 Type enclType = clazztype.getEnclosingType(); 2952 if (enclType != null && 2953 enclType.hasTag(CLASS) && 2954 !chk.checkDenotable((ClassType)enclType)) { 2955 log.error(tree.encl, Errors.EnclosingClassTypeNonDenotable(enclType)); 2956 } 2957 final boolean isDiamond = TreeInfo.isDiamond(tree); 2958 if (isDiamond 2959 && ((tree.constructorType != null && inferenceContext.free(tree.constructorType)) 2960 || (tree.clazz.type != null && inferenceContext.free(tree.clazz.type)))) { 2961 final ResultInfo resultInfoForClassDefinition = this.resultInfo; 2962 Env<AttrContext> dupLocalEnv = copyEnv(localEnv); 2963 inferenceContext.addFreeTypeListener(List.of(tree.constructorType, tree.clazz.type), 2964 instantiatedContext -> { 2965 tree.constructorType = instantiatedContext.asInstType(tree.constructorType); 2966 tree.clazz.type = clazz.type = instantiatedContext.asInstType(clazz.type); 2967 ResultInfo prevResult = this.resultInfo; 2968 try { 2969 this.resultInfo = resultInfoForClassDefinition; 2970 visitAnonymousClassDefinition(tree, clazz, clazz.type, cdef, 2971 dupLocalEnv, argtypes, typeargtypes, pkind); 2972 } finally { 2973 this.resultInfo = prevResult; 2974 } 2975 }); 2976 } else { 2977 if (isDiamond && clazztype.hasTag(CLASS)) { 2978 List<Type> invalidDiamondArgs = chk.checkDiamondDenotable((ClassType)clazztype); 2979 if (!clazztype.isErroneous() && invalidDiamondArgs.nonEmpty()) { 2980 // One or more types inferred in the previous steps is non-denotable. 2981 Fragment fragment = Diamond(clazztype.tsym); 2982 log.error(tree.clazz.pos(), 2983 Errors.CantApplyDiamond1( 2984 fragment, 2985 invalidDiamondArgs.size() > 1 ? 2986 DiamondInvalidArgs(invalidDiamondArgs, fragment) : 2987 DiamondInvalidArg(invalidDiamondArgs, fragment))); 2988 } 2989 // For <>(){}, inferred types must also be accessible. 2990 for (Type t : clazztype.getTypeArguments()) { 2991 rs.checkAccessibleType(env, t); 2992 } 2993 } 2994 2995 // If we already errored, be careful to avoid a further avalanche. ErrorType answers 2996 // false for isInterface call even when the original type is an interface. 2997 boolean implementing = clazztype.tsym.isInterface() || 2998 clazztype.isErroneous() && !clazztype.getOriginalType().hasTag(NONE) && 2999 clazztype.getOriginalType().tsym.isInterface(); 3000 3001 if (implementing) { 3002 cdef.implementing = List.of(clazz); 3003 } else { 3004 cdef.extending = clazz; 3005 } 3006 3007 if (resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK && 3008 rs.isSerializable(clazztype)) { 3009 localEnv.info.isSerializable = true; 3010 } 3011 3012 attribStat(cdef, localEnv); 3013 3014 List<Type> finalargtypes; 3015 // If an outer instance is given, 3016 // prefix it to the constructor arguments 3017 // and delete it from the new expression 3018 if (tree.encl != null && !clazztype.tsym.isInterface()) { 3019 finalargtypes = argtypes.prepend(tree.encl.type); 3020 } else { 3021 finalargtypes = argtypes; 3022 } 3023 3024 // Reassign clazztype and recompute constructor. As this necessarily involves 3025 // another attribution pass for deferred types in the case of <>, replicate 3026 // them. Original arguments have right decorations already. 3027 if (isDiamond && pkind.contains(KindSelector.POLY)) { 3028 finalargtypes = finalargtypes.map(deferredAttr.deferredCopier); 3029 } 3030 3031 clazztype = clazztype.hasTag(ERROR) ? types.createErrorType(cdef.sym.type) 3032 : cdef.sym.type; 3033 Symbol sym = tree.constructor = rs.resolveConstructor( 3034 tree.pos(), localEnv, clazztype, finalargtypes, typeargtypes); 3035 Assert.check(!sym.kind.isResolutionError()); 3036 tree.constructor = sym; 3037 tree.constructorType = checkId(tree, 3038 clazztype, 3039 tree.constructor, 3040 localEnv, 3041 new ResultInfo(pkind, newMethodTemplate(syms.voidType, finalargtypes, typeargtypes), CheckMode.NO_TREE_UPDATE)); 3042 } 3043 Type owntype = (tree.constructor != null && tree.constructor.kind == MTH) ? 3044 clazztype : types.createErrorType(tree.type); 3045 result = check(tree, owntype, KindSelector.VAL, resultInfo.dup(CheckMode.NO_INFERENCE_HOOK)); 3046 chk.validate(tree.typeargs, localEnv); 3047 } 3048 3049 CheckContext diamondContext(JCNewClass clazz, TypeSymbol tsym, CheckContext checkContext) { 3050 return new Check.NestedCheckContext(checkContext) { 3051 @Override 3052 public void report(DiagnosticPosition _unused, JCDiagnostic details) { 3053 enclosingContext.report(clazz.clazz, 3054 diags.fragment(Fragments.CantApplyDiamond1(Fragments.Diamond(tsym), details))); 3055 } 3056 }; 3057 } 3058 3059 /** Make an attributed null check tree. 3060 */ 3061 public JCExpression makeNullCheck(JCExpression arg) { 3062 // optimization: new Outer() can never be null; skip null check 3063 if (arg.getTag() == NEWCLASS) 3064 return arg; 3065 // optimization: X.this is never null; skip null check 3066 Name name = TreeInfo.name(arg); 3067 if (name == names._this || name == names._super) return arg; 3068 3069 JCTree.Tag optag = NULLCHK; 3070 JCUnary tree = make.at(arg.pos).Unary(optag, arg); 3071 tree.operator = operators.resolveUnary(arg, optag, arg.type); 3072 tree.type = arg.type; 3073 return tree; 3074 } 3075 3076 public void visitNewArray(JCNewArray tree) { 3077 Type owntype = types.createErrorType(tree.type); 3078 Env<AttrContext> localEnv = env.dup(tree); 3079 Type elemtype; 3080 if (tree.elemtype != null) { 3081 elemtype = attribType(tree.elemtype, localEnv); 3082 chk.validate(tree.elemtype, localEnv); 3083 owntype = elemtype; 3084 for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) { 3085 attribExpr(l.head, localEnv, syms.intType); 3086 owntype = new ArrayType(owntype, syms.arrayClass); 3087 } 3088 } else { 3089 // we are seeing an untyped aggregate { ... } 3090 // this is allowed only if the prototype is an array 3091 if (pt().hasTag(ARRAY)) { 3092 elemtype = types.elemtype(pt()); 3093 } else { 3094 if (!pt().hasTag(ERROR) && 3095 (env.info.enclVar == null || !env.info.enclVar.type.isErroneous())) { 3096 log.error(tree.pos(), 3097 Errors.IllegalInitializerForType(pt())); 3098 } 3099 elemtype = types.createErrorType(pt()); 3100 } 3101 } 3102 if (tree.elems != null) { 3103 attribExprs(tree.elems, localEnv, elemtype); 3104 owntype = new ArrayType(elemtype, syms.arrayClass); 3105 } 3106 if (!types.isReifiable(elemtype)) 3107 log.error(tree.pos(), Errors.GenericArrayCreation); 3108 result = check(tree, owntype, KindSelector.VAL, resultInfo); 3109 } 3110 3111 /* 3112 * A lambda expression can only be attributed when a target-type is available. 3113 * In addition, if the target-type is that of a functional interface whose 3114 * descriptor contains inference variables in argument position the lambda expression 3115 * is 'stuck' (see DeferredAttr). 3116 */ 3117 @Override 3118 public void visitLambda(final JCLambda that) { 3119 boolean wrongContext = false; 3120 if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) { 3121 if (pt().hasTag(NONE) && (env.info.enclVar == null || !env.info.enclVar.type.isErroneous())) { 3122 //lambda only allowed in assignment or method invocation/cast context 3123 log.error(that.pos(), Errors.UnexpectedLambda); 3124 } 3125 resultInfo = recoveryInfo; 3126 wrongContext = true; 3127 } 3128 //create an environment for attribution of the lambda expression 3129 final Env<AttrContext> localEnv = lambdaEnv(that, env); 3130 boolean needsRecovery = 3131 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK; 3132 try { 3133 if (needsRecovery && rs.isSerializable(pt())) { 3134 localEnv.info.isSerializable = true; 3135 localEnv.info.isSerializableLambda = true; 3136 } 3137 List<Type> explicitParamTypes = null; 3138 if (that.paramKind == JCLambda.ParameterKind.EXPLICIT) { 3139 //attribute lambda parameters 3140 attribStats(that.params, localEnv); 3141 explicitParamTypes = TreeInfo.types(that.params); 3142 } 3143 3144 TargetInfo targetInfo = getTargetInfo(that, resultInfo, explicitParamTypes); 3145 Type currentTarget = targetInfo.target; 3146 Type lambdaType = targetInfo.descriptor; 3147 3148 if (currentTarget.isErroneous()) { 3149 result = that.type = currentTarget; 3150 return; 3151 } 3152 3153 setFunctionalInfo(localEnv, that, pt(), lambdaType, currentTarget, resultInfo.checkContext); 3154 3155 if (lambdaType.hasTag(FORALL)) { 3156 //lambda expression target desc cannot be a generic method 3157 Fragment msg = Fragments.InvalidGenericLambdaTarget(lambdaType, 3158 kindName(currentTarget.tsym), 3159 currentTarget.tsym); 3160 resultInfo.checkContext.report(that, diags.fragment(msg)); 3161 result = that.type = types.createErrorType(pt()); 3162 return; 3163 } 3164 3165 if (that.paramKind == JCLambda.ParameterKind.IMPLICIT) { 3166 //add param type info in the AST 3167 List<Type> actuals = lambdaType.getParameterTypes(); 3168 List<JCVariableDecl> params = that.params; 3169 3170 boolean arityMismatch = false; 3171 3172 while (params.nonEmpty()) { 3173 if (actuals.isEmpty()) { 3174 //not enough actuals to perform lambda parameter inference 3175 arityMismatch = true; 3176 } 3177 //reset previously set info 3178 Type argType = arityMismatch ? 3179 syms.errType : 3180 actuals.head; 3181 if (params.head.isImplicitlyTyped()) { 3182 setSyntheticVariableType(params.head, argType); 3183 } 3184 params.head.sym = null; 3185 actuals = actuals.isEmpty() ? 3186 actuals : 3187 actuals.tail; 3188 params = params.tail; 3189 } 3190 3191 //attribute lambda parameters 3192 attribStats(that.params, localEnv); 3193 3194 if (arityMismatch) { 3195 resultInfo.checkContext.report(that, diags.fragment(Fragments.IncompatibleArgTypesInLambda)); 3196 result = that.type = types.createErrorType(currentTarget); 3197 return; 3198 } 3199 } 3200 3201 //from this point on, no recovery is needed; if we are in assignment context 3202 //we will be able to attribute the whole lambda body, regardless of errors; 3203 //if we are in a 'check' method context, and the lambda is not compatible 3204 //with the target-type, it will be recovered anyway in Attr.checkId 3205 needsRecovery = false; 3206 3207 ResultInfo bodyResultInfo = localEnv.info.returnResult = 3208 lambdaBodyResult(that, lambdaType, resultInfo); 3209 3210 if (that.getBodyKind() == JCLambda.BodyKind.EXPRESSION) { 3211 attribTree(that.getBody(), localEnv, bodyResultInfo); 3212 } else { 3213 JCBlock body = (JCBlock)that.body; 3214 if (body == breakTree && 3215 resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) { 3216 breakTreeFound(copyEnv(localEnv)); 3217 } 3218 attribStats(body.stats, localEnv); 3219 } 3220 3221 result = check(that, currentTarget, KindSelector.VAL, resultInfo); 3222 3223 boolean isSpeculativeRound = 3224 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE; 3225 3226 preFlow(that); 3227 flow.analyzeLambda(env, that, make, isSpeculativeRound); 3228 3229 that.type = currentTarget; //avoids recovery at this stage 3230 checkLambdaCompatible(that, lambdaType, resultInfo.checkContext); 3231 3232 if (!isSpeculativeRound) { 3233 //add thrown types as bounds to the thrown types free variables if needed: 3234 if (resultInfo.checkContext.inferenceContext().free(lambdaType.getThrownTypes())) { 3235 List<Type> inferredThrownTypes = flow.analyzeLambdaThrownTypes(env, that, make); 3236 if(!checkExConstraints(inferredThrownTypes, lambdaType.getThrownTypes(), resultInfo.checkContext.inferenceContext())) { 3237 log.error(that, Errors.IncompatibleThrownTypesInMref(lambdaType.getThrownTypes())); 3238 } 3239 } 3240 3241 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), lambdaType, currentTarget); 3242 } 3243 result = wrongContext ? that.type = types.createErrorType(pt()) 3244 : check(that, currentTarget, KindSelector.VAL, resultInfo); 3245 } catch (Types.FunctionDescriptorLookupError ex) { 3246 JCDiagnostic cause = ex.getDiagnostic(); 3247 resultInfo.checkContext.report(that, cause); 3248 result = that.type = types.createErrorType(pt()); 3249 return; 3250 } catch (CompletionFailure cf) { 3251 chk.completionError(that.pos(), cf); 3252 } catch (Throwable t) { 3253 //when an unexpected exception happens, avoid attempts to attribute the same tree again 3254 //as that would likely cause the same exception again. 3255 needsRecovery = false; 3256 throw t; 3257 } finally { 3258 localEnv.info.scope.leave(); 3259 if (needsRecovery) { 3260 Type prevResult = result; 3261 try { 3262 attribTree(that, env, recoveryInfo); 3263 } finally { 3264 if (result == Type.recoveryType) { 3265 result = prevResult; 3266 } 3267 } 3268 } 3269 } 3270 } 3271 //where 3272 class TargetInfo { 3273 Type target; 3274 Type descriptor; 3275 3276 public TargetInfo(Type target, Type descriptor) { 3277 this.target = target; 3278 this.descriptor = descriptor; 3279 } 3280 } 3281 3282 TargetInfo getTargetInfo(JCPolyExpression that, ResultInfo resultInfo, List<Type> explicitParamTypes) { 3283 Type lambdaType; 3284 Type currentTarget = resultInfo.pt; 3285 if (resultInfo.pt != Type.recoveryType) { 3286 /* We need to adjust the target. If the target is an 3287 * intersection type, for example: SAM & I1 & I2 ... 3288 * the target will be updated to SAM 3289 */ 3290 currentTarget = targetChecker.visit(currentTarget, that); 3291 if (!currentTarget.isIntersection()) { 3292 if (explicitParamTypes != null) { 3293 currentTarget = infer.instantiateFunctionalInterface(that, 3294 currentTarget, explicitParamTypes, resultInfo.checkContext); 3295 } 3296 currentTarget = types.removeWildcards(currentTarget); 3297 lambdaType = types.findDescriptorType(currentTarget); 3298 } else { 3299 IntersectionClassType ict = (IntersectionClassType)currentTarget; 3300 ListBuffer<Type> components = new ListBuffer<>(); 3301 for (Type bound : ict.getExplicitComponents()) { 3302 if (explicitParamTypes != null) { 3303 try { 3304 bound = infer.instantiateFunctionalInterface(that, 3305 bound, explicitParamTypes, resultInfo.checkContext); 3306 } catch (FunctionDescriptorLookupError t) { 3307 // do nothing 3308 } 3309 } 3310 bound = types.removeWildcards(bound); 3311 components.add(bound); 3312 } 3313 currentTarget = types.makeIntersectionType(components.toList()); 3314 currentTarget.tsym.flags_field |= INTERFACE; 3315 lambdaType = types.findDescriptorType(currentTarget); 3316 } 3317 3318 } else { 3319 currentTarget = Type.recoveryType; 3320 lambdaType = fallbackDescriptorType(that); 3321 } 3322 if (that.hasTag(LAMBDA) && lambdaType.hasTag(FORALL)) { 3323 //lambda expression target desc cannot be a generic method 3324 Fragment msg = Fragments.InvalidGenericLambdaTarget(lambdaType, 3325 kindName(currentTarget.tsym), 3326 currentTarget.tsym); 3327 resultInfo.checkContext.report(that, diags.fragment(msg)); 3328 currentTarget = types.createErrorType(pt()); 3329 } 3330 return new TargetInfo(currentTarget, lambdaType); 3331 } 3332 3333 void preFlow(JCLambda tree) { 3334 attrRecover.doRecovery(); 3335 new PostAttrAnalyzer() { 3336 @Override 3337 public void scan(JCTree tree) { 3338 if (tree == null || 3339 (tree.type != null && 3340 tree.type == Type.stuckType)) { 3341 //don't touch stuck expressions! 3342 return; 3343 } 3344 super.scan(tree); 3345 } 3346 3347 @Override 3348 public void visitClassDef(JCClassDecl that) { 3349 // or class declaration trees! 3350 } 3351 3352 public void visitLambda(JCLambda that) { 3353 // or lambda expressions! 3354 } 3355 }.scan(tree.body); 3356 } 3357 3358 Types.MapVisitor<DiagnosticPosition> targetChecker = new Types.MapVisitor<DiagnosticPosition>() { 3359 3360 @Override 3361 public Type visitClassType(ClassType t, DiagnosticPosition pos) { 3362 return t.isIntersection() ? 3363 visitIntersectionClassType((IntersectionClassType)t, pos) : t; 3364 } 3365 3366 public Type visitIntersectionClassType(IntersectionClassType ict, DiagnosticPosition pos) { 3367 types.findDescriptorSymbol(makeNotionalInterface(ict, pos)); 3368 return ict; 3369 } 3370 3371 private TypeSymbol makeNotionalInterface(IntersectionClassType ict, DiagnosticPosition pos) { 3372 ListBuffer<Type> targs = new ListBuffer<>(); 3373 ListBuffer<Type> supertypes = new ListBuffer<>(); 3374 for (Type i : ict.interfaces_field) { 3375 if (i.isParameterized()) { 3376 targs.appendList(i.tsym.type.allparams()); 3377 } 3378 supertypes.append(i.tsym.type); 3379 } 3380 IntersectionClassType notionalIntf = types.makeIntersectionType(supertypes.toList()); 3381 notionalIntf.allparams_field = targs.toList(); 3382 notionalIntf.tsym.flags_field |= INTERFACE; 3383 return notionalIntf.tsym; 3384 } 3385 }; 3386 3387 private Type fallbackDescriptorType(JCExpression tree) { 3388 switch (tree.getTag()) { 3389 case LAMBDA: 3390 JCLambda lambda = (JCLambda)tree; 3391 List<Type> argtypes = List.nil(); 3392 for (JCVariableDecl param : lambda.params) { 3393 argtypes = param.vartype != null && param.vartype.type != null ? 3394 argtypes.append(param.vartype.type) : 3395 argtypes.append(syms.errType); 3396 } 3397 return new MethodType(argtypes, Type.recoveryType, 3398 List.of(syms.throwableType), syms.methodClass); 3399 case REFERENCE: 3400 return new MethodType(List.nil(), Type.recoveryType, 3401 List.of(syms.throwableType), syms.methodClass); 3402 default: 3403 Assert.error("Cannot get here!"); 3404 } 3405 return null; 3406 } 3407 3408 private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env, 3409 final InferenceContext inferenceContext, final Type... ts) { 3410 checkAccessibleTypes(pos, env, inferenceContext, List.from(ts)); 3411 } 3412 3413 private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env, 3414 final InferenceContext inferenceContext, final List<Type> ts) { 3415 if (inferenceContext.free(ts)) { 3416 inferenceContext.addFreeTypeListener(ts, 3417 solvedContext -> checkAccessibleTypes(pos, env, solvedContext, solvedContext.asInstTypes(ts))); 3418 } else { 3419 for (Type t : ts) { 3420 rs.checkAccessibleType(env, t); 3421 } 3422 } 3423 } 3424 3425 /** 3426 * Lambda/method reference have a special check context that ensures 3427 * that i.e. a lambda return type is compatible with the expected 3428 * type according to both the inherited context and the assignment 3429 * context. 3430 */ 3431 class FunctionalReturnContext extends Check.NestedCheckContext { 3432 3433 FunctionalReturnContext(CheckContext enclosingContext) { 3434 super(enclosingContext); 3435 } 3436 3437 @Override 3438 public boolean compatible(Type found, Type req, Warner warn) { 3439 //return type must be compatible in both current context and assignment context 3440 return chk.basicHandler.compatible(inferenceContext().asUndetVar(found), inferenceContext().asUndetVar(req), warn); 3441 } 3442 3443 @Override 3444 public void report(DiagnosticPosition pos, JCDiagnostic details) { 3445 enclosingContext.report(pos, diags.fragment(Fragments.IncompatibleRetTypeInLambda(details))); 3446 } 3447 } 3448 3449 class ExpressionLambdaReturnContext extends FunctionalReturnContext { 3450 3451 JCExpression expr; 3452 boolean expStmtExpected; 3453 3454 ExpressionLambdaReturnContext(JCExpression expr, CheckContext enclosingContext) { 3455 super(enclosingContext); 3456 this.expr = expr; 3457 } 3458 3459 @Override 3460 public void report(DiagnosticPosition pos, JCDiagnostic details) { 3461 if (expStmtExpected) { 3462 enclosingContext.report(pos, diags.fragment(Fragments.StatExprExpected)); 3463 } else { 3464 super.report(pos, details); 3465 } 3466 } 3467 3468 @Override 3469 public boolean compatible(Type found, Type req, Warner warn) { 3470 //a void return is compatible with an expression statement lambda 3471 if (req.hasTag(VOID)) { 3472 expStmtExpected = true; 3473 return TreeInfo.isExpressionStatement(expr); 3474 } else { 3475 return super.compatible(found, req, warn); 3476 } 3477 } 3478 } 3479 3480 ResultInfo lambdaBodyResult(JCLambda that, Type descriptor, ResultInfo resultInfo) { 3481 FunctionalReturnContext funcContext = that.getBodyKind() == JCLambda.BodyKind.EXPRESSION ? 3482 new ExpressionLambdaReturnContext((JCExpression)that.getBody(), resultInfo.checkContext) : 3483 new FunctionalReturnContext(resultInfo.checkContext); 3484 3485 return descriptor.getReturnType() == Type.recoveryType ? 3486 recoveryInfo : 3487 new ResultInfo(KindSelector.VAL, 3488 descriptor.getReturnType(), funcContext); 3489 } 3490 3491 /** 3492 * Lambda compatibility. Check that given return types, thrown types, parameter types 3493 * are compatible with the expected functional interface descriptor. This means that: 3494 * (i) parameter types must be identical to those of the target descriptor; (ii) return 3495 * types must be compatible with the return type of the expected descriptor. 3496 */ 3497 void checkLambdaCompatible(JCLambda tree, Type descriptor, CheckContext checkContext) { 3498 Type returnType = checkContext.inferenceContext().asUndetVar(descriptor.getReturnType()); 3499 3500 //return values have already been checked - but if lambda has no return 3501 //values, we must ensure that void/value compatibility is correct; 3502 //this amounts at checking that, if a lambda body can complete normally, 3503 //the descriptor's return type must be void 3504 if (tree.getBodyKind() == JCLambda.BodyKind.STATEMENT && tree.canCompleteNormally && 3505 !returnType.hasTag(VOID) && returnType != Type.recoveryType) { 3506 Fragment msg = 3507 Fragments.IncompatibleRetTypeInLambda(Fragments.MissingRetVal(returnType)); 3508 checkContext.report(tree, 3509 diags.fragment(msg)); 3510 } 3511 3512 List<Type> argTypes = checkContext.inferenceContext().asUndetVars(descriptor.getParameterTypes()); 3513 if (!types.isSameTypes(argTypes, TreeInfo.types(tree.params))) { 3514 checkContext.report(tree, diags.fragment(Fragments.IncompatibleArgTypesInLambda)); 3515 } 3516 } 3517 3518 /* Map to hold 'fake' clinit methods. If a lambda is used to initialize a 3519 * static field and that lambda has type annotations, these annotations will 3520 * also be stored at these fake clinit methods. 3521 * 3522 * LambdaToMethod also use fake clinit methods so they can be reused. 3523 * Also as LTM is a phase subsequent to attribution, the methods from 3524 * clinits can be safely removed by LTM to save memory. 3525 */ 3526 private Map<ClassSymbol, MethodSymbol> clinits = new HashMap<>(); 3527 3528 public MethodSymbol removeClinit(ClassSymbol sym) { 3529 return clinits.remove(sym); 3530 } 3531 3532 /* This method returns an environment to be used to attribute a lambda 3533 * expression. 3534 * 3535 * The owner of this environment is a method symbol. If the current owner 3536 * is not a method, for example if the lambda is used to initialize 3537 * a field, then if the field is: 3538 * 3539 * - an instance field, we use the first constructor. 3540 * - a static field, we create a fake clinit method. 3541 */ 3542 public Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) { 3543 Env<AttrContext> lambdaEnv; 3544 Symbol owner = env.info.scope.owner; 3545 if (owner.kind == VAR && owner.owner.kind == TYP) { 3546 //field initializer 3547 ClassSymbol enclClass = owner.enclClass(); 3548 Symbol newScopeOwner = env.info.scope.owner; 3549 /* if the field isn't static, then we can get the first constructor 3550 * and use it as the owner of the environment. This is what 3551 * LTM code is doing to look for type annotations so we are fine. 3552 */ 3553 if ((owner.flags() & STATIC) == 0) { 3554 for (Symbol s : enclClass.members_field.getSymbolsByName(names.init)) { 3555 newScopeOwner = s; 3556 break; 3557 } 3558 } else { 3559 /* if the field is static then we need to create a fake clinit 3560 * method, this method can later be reused by LTM. 3561 */ 3562 MethodSymbol clinit = clinits.get(enclClass); 3563 if (clinit == null) { 3564 Type clinitType = new MethodType(List.nil(), 3565 syms.voidType, List.nil(), syms.methodClass); 3566 clinit = new MethodSymbol(STATIC | SYNTHETIC | PRIVATE, 3567 names.clinit, clinitType, enclClass); 3568 clinit.params = List.nil(); 3569 clinits.put(enclClass, clinit); 3570 } 3571 newScopeOwner = clinit; 3572 } 3573 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared(newScopeOwner))); 3574 } else { 3575 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dup())); 3576 } 3577 lambdaEnv.info.yieldResult = null; 3578 lambdaEnv.info.isLambda = true; 3579 return lambdaEnv; 3580 } 3581 3582 @Override 3583 public void visitReference(final JCMemberReference that) { 3584 if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) { 3585 if (pt().hasTag(NONE) && (env.info.enclVar == null || !env.info.enclVar.type.isErroneous())) { 3586 //method reference only allowed in assignment or method invocation/cast context 3587 log.error(that.pos(), Errors.UnexpectedMref); 3588 } 3589 result = that.type = types.createErrorType(pt()); 3590 return; 3591 } 3592 final Env<AttrContext> localEnv = env.dup(that); 3593 try { 3594 //attribute member reference qualifier - if this is a constructor 3595 //reference, the expected kind must be a type 3596 Type exprType = attribTree(that.expr, env, memberReferenceQualifierResult(that)); 3597 3598 if (that.getMode() == JCMemberReference.ReferenceMode.NEW) { 3599 exprType = chk.checkConstructorRefType(that.expr, exprType); 3600 if (!exprType.isErroneous() && 3601 exprType.isRaw() && 3602 that.typeargs != null) { 3603 log.error(that.expr.pos(), 3604 Errors.InvalidMref(Kinds.kindName(that.getMode()), 3605 Fragments.MrefInferAndExplicitParams)); 3606 exprType = types.createErrorType(exprType); 3607 } 3608 } 3609 3610 if (exprType.isErroneous()) { 3611 //if the qualifier expression contains problems, 3612 //give up attribution of method reference 3613 result = that.type = exprType; 3614 return; 3615 } 3616 3617 if (TreeInfo.isStaticSelector(that.expr, names)) { 3618 //if the qualifier is a type, validate it; raw warning check is 3619 //omitted as we don't know at this stage as to whether this is a 3620 //raw selector (because of inference) 3621 chk.validate(that.expr, env, false); 3622 } else { 3623 Symbol lhsSym = TreeInfo.symbol(that.expr); 3624 localEnv.info.selectSuper = lhsSym != null && lhsSym.name == names._super; 3625 } 3626 //attrib type-arguments 3627 List<Type> typeargtypes = List.nil(); 3628 if (that.typeargs != null) { 3629 typeargtypes = attribTypes(that.typeargs, localEnv); 3630 } 3631 3632 boolean isTargetSerializable = 3633 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK && 3634 rs.isSerializable(pt()); 3635 TargetInfo targetInfo = getTargetInfo(that, resultInfo, null); 3636 Type currentTarget = targetInfo.target; 3637 Type desc = targetInfo.descriptor; 3638 3639 setFunctionalInfo(localEnv, that, pt(), desc, currentTarget, resultInfo.checkContext); 3640 List<Type> argtypes = desc.getParameterTypes(); 3641 Resolve.MethodCheck referenceCheck = rs.resolveMethodCheck; 3642 3643 if (resultInfo.checkContext.inferenceContext().free(argtypes)) { 3644 referenceCheck = rs.new MethodReferenceCheck(resultInfo.checkContext.inferenceContext()); 3645 } 3646 3647 Pair<Symbol, Resolve.ReferenceLookupHelper> refResult = null; 3648 List<Type> saved_undet = resultInfo.checkContext.inferenceContext().save(); 3649 try { 3650 refResult = rs.resolveMemberReference(localEnv, that, that.expr.type, 3651 that.name, argtypes, typeargtypes, targetInfo.descriptor, referenceCheck, 3652 resultInfo.checkContext.inferenceContext(), rs.basicReferenceChooser); 3653 } finally { 3654 resultInfo.checkContext.inferenceContext().rollback(saved_undet); 3655 } 3656 3657 Symbol refSym = refResult.fst; 3658 Resolve.ReferenceLookupHelper lookupHelper = refResult.snd; 3659 3660 /** this switch will need to go away and be replaced by the new RESOLUTION_TARGET testing 3661 * JDK-8075541 3662 */ 3663 if (refSym.kind != MTH) { 3664 boolean targetError; 3665 switch (refSym.kind) { 3666 case ABSENT_MTH: 3667 case MISSING_ENCL: 3668 targetError = false; 3669 break; 3670 case WRONG_MTH: 3671 case WRONG_MTHS: 3672 case AMBIGUOUS: 3673 case HIDDEN: 3674 case STATICERR: 3675 targetError = true; 3676 break; 3677 default: 3678 Assert.error("unexpected result kind " + refSym.kind); 3679 targetError = false; 3680 } 3681 3682 JCDiagnostic detailsDiag = ((Resolve.ResolveError)refSym.baseSymbol()) 3683 .getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT, 3684 that, exprType.tsym, exprType, that.name, argtypes, typeargtypes); 3685 3686 JCDiagnostic diag = diags.create(log.currentSource(), that, 3687 targetError ? 3688 Fragments.InvalidMref(Kinds.kindName(that.getMode()), detailsDiag) : 3689 Errors.InvalidMref(Kinds.kindName(that.getMode()), detailsDiag)); 3690 3691 if (targetError && currentTarget == Type.recoveryType) { 3692 //a target error doesn't make sense during recovery stage 3693 //as we don't know what actual parameter types are 3694 result = that.type = currentTarget; 3695 return; 3696 } else { 3697 if (targetError) { 3698 resultInfo.checkContext.report(that, diag); 3699 } else { 3700 log.report(diag); 3701 } 3702 result = that.type = types.createErrorType(currentTarget); 3703 return; 3704 } 3705 } 3706 3707 that.sym = refSym.isConstructor() ? refSym.baseSymbol() : refSym; 3708 that.kind = lookupHelper.referenceKind(that.sym); 3709 that.ownerAccessible = rs.isAccessible(localEnv, that.sym.enclClass()); 3710 3711 if (desc.getReturnType() == Type.recoveryType) { 3712 // stop here 3713 result = that.type = currentTarget; 3714 return; 3715 } 3716 3717 if (!env.info.attributionMode.isSpeculative && that.getMode() == JCMemberReference.ReferenceMode.NEW) { 3718 Type enclosingType = exprType.getEnclosingType(); 3719 if (enclosingType != null && enclosingType.hasTag(CLASS)) { 3720 // Check for the existence of an appropriate outer instance 3721 rs.resolveImplicitThis(that.pos(), env, exprType); 3722 } 3723 } 3724 3725 if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) { 3726 3727 if (that.getMode() == ReferenceMode.INVOKE && 3728 TreeInfo.isStaticSelector(that.expr, names) && 3729 that.kind.isUnbound() && 3730 lookupHelper.site.isRaw()) { 3731 chk.checkRaw(that.expr, localEnv); 3732 } 3733 3734 if (that.sym.isStatic() && TreeInfo.isStaticSelector(that.expr, names) && 3735 exprType.getTypeArguments().nonEmpty()) { 3736 //static ref with class type-args 3737 log.error(that.expr.pos(), 3738 Errors.InvalidMref(Kinds.kindName(that.getMode()), 3739 Fragments.StaticMrefWithTargs)); 3740 result = that.type = types.createErrorType(currentTarget); 3741 return; 3742 } 3743 3744 if (!refSym.isStatic() && that.kind == JCMemberReference.ReferenceKind.SUPER) { 3745 // Check that super-qualified symbols are not abstract (JLS) 3746 rs.checkNonAbstract(that.pos(), that.sym); 3747 } 3748 3749 if (isTargetSerializable) { 3750 chk.checkAccessFromSerializableElement(that, true); 3751 } 3752 } 3753 3754 ResultInfo checkInfo = 3755 resultInfo.dup(newMethodTemplate( 3756 desc.getReturnType().hasTag(VOID) ? Type.noType : desc.getReturnType(), 3757 that.kind.isUnbound() ? argtypes.tail : argtypes, typeargtypes), 3758 new FunctionalReturnContext(resultInfo.checkContext), CheckMode.NO_TREE_UPDATE); 3759 3760 Type refType = checkId(that, lookupHelper.site, refSym, localEnv, checkInfo); 3761 3762 if (that.kind.isUnbound() && 3763 resultInfo.checkContext.inferenceContext().free(argtypes.head)) { 3764 //re-generate inference constraints for unbound receiver 3765 if (!types.isSubtype(resultInfo.checkContext.inferenceContext().asUndetVar(argtypes.head), exprType)) { 3766 //cannot happen as this has already been checked - we just need 3767 //to regenerate the inference constraints, as that has been lost 3768 //as a result of the call to inferenceContext.save() 3769 Assert.error("Can't get here"); 3770 } 3771 } 3772 3773 if (!refType.isErroneous()) { 3774 refType = types.createMethodTypeWithReturn(refType, 3775 adjustMethodReturnType(refSym, lookupHelper.site, that.name, checkInfo.pt.getParameterTypes(), refType.getReturnType())); 3776 } 3777 3778 //go ahead with standard method reference compatibility check - note that param check 3779 //is a no-op (as this has been taken care during method applicability) 3780 boolean isSpeculativeRound = 3781 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE; 3782 3783 that.type = currentTarget; //avoids recovery at this stage 3784 checkReferenceCompatible(that, desc, refType, resultInfo.checkContext, isSpeculativeRound); 3785 if (!isSpeculativeRound) { 3786 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), desc, currentTarget); 3787 } 3788 result = check(that, currentTarget, KindSelector.VAL, resultInfo); 3789 } catch (Types.FunctionDescriptorLookupError ex) { 3790 JCDiagnostic cause = ex.getDiagnostic(); 3791 resultInfo.checkContext.report(that, cause); 3792 result = that.type = types.createErrorType(pt()); 3793 return; 3794 } 3795 } 3796 //where 3797 ResultInfo memberReferenceQualifierResult(JCMemberReference tree) { 3798 //if this is a constructor reference, the expected kind must be a type 3799 return new ResultInfo(tree.getMode() == ReferenceMode.INVOKE ? 3800 KindSelector.VAL_TYP : KindSelector.TYP, 3801 Type.noType); 3802 } 3803 3804 3805 @SuppressWarnings("fallthrough") 3806 void checkReferenceCompatible(JCMemberReference tree, Type descriptor, Type refType, CheckContext checkContext, boolean speculativeAttr) { 3807 InferenceContext inferenceContext = checkContext.inferenceContext(); 3808 Type returnType = inferenceContext.asUndetVar(descriptor.getReturnType()); 3809 3810 Type resType; 3811 switch (tree.getMode()) { 3812 case NEW: 3813 if (!tree.expr.type.isRaw()) { 3814 resType = tree.expr.type; 3815 break; 3816 } 3817 default: 3818 resType = refType.getReturnType(); 3819 } 3820 3821 Type incompatibleReturnType = resType; 3822 3823 if (returnType.hasTag(VOID)) { 3824 incompatibleReturnType = null; 3825 } 3826 3827 if (!returnType.hasTag(VOID) && !resType.hasTag(VOID)) { 3828 if (resType.isErroneous() || 3829 new FunctionalReturnContext(checkContext).compatible(resType, returnType, 3830 checkContext.checkWarner(tree, resType, returnType))) { 3831 incompatibleReturnType = null; 3832 } 3833 } 3834 3835 if (incompatibleReturnType != null) { 3836 Fragment msg = 3837 Fragments.IncompatibleRetTypeInMref(Fragments.InconvertibleTypes(resType, descriptor.getReturnType())); 3838 checkContext.report(tree, diags.fragment(msg)); 3839 } else { 3840 if (inferenceContext.free(refType)) { 3841 // we need to wait for inference to finish and then replace inference vars in the referent type 3842 inferenceContext.addFreeTypeListener(List.of(refType), 3843 instantiatedContext -> { 3844 tree.referentType = instantiatedContext.asInstType(refType); 3845 }); 3846 } else { 3847 tree.referentType = refType; 3848 } 3849 } 3850 3851 if (!speculativeAttr) { 3852 if (!checkExConstraints(refType.getThrownTypes(), descriptor.getThrownTypes(), inferenceContext)) { 3853 log.error(tree, Errors.IncompatibleThrownTypesInMref(refType.getThrownTypes())); 3854 } 3855 } 3856 } 3857 3858 boolean checkExConstraints( 3859 List<Type> thrownByFuncExpr, 3860 List<Type> thrownAtFuncType, 3861 InferenceContext inferenceContext) { 3862 /** 18.2.5: Otherwise, let E1, ..., En be the types in the function type's throws clause that 3863 * are not proper types 3864 */ 3865 List<Type> nonProperList = thrownAtFuncType.stream() 3866 .filter(e -> inferenceContext.free(e)).collect(List.collector()); 3867 List<Type> properList = thrownAtFuncType.diff(nonProperList); 3868 3869 /** Let X1,...,Xm be the checked exception types that the lambda body can throw or 3870 * in the throws clause of the invocation type of the method reference's compile-time 3871 * declaration 3872 */ 3873 List<Type> checkedList = thrownByFuncExpr.stream() 3874 .filter(e -> chk.isChecked(e)).collect(List.collector()); 3875 3876 /** If n = 0 (the function type's throws clause consists only of proper types), then 3877 * if there exists some i (1 <= i <= m) such that Xi is not a subtype of any proper type 3878 * in the throws clause, the constraint reduces to false; otherwise, the constraint 3879 * reduces to true 3880 */ 3881 ListBuffer<Type> uncaughtByProperTypes = new ListBuffer<>(); 3882 for (Type checked : checkedList) { 3883 boolean isSubtype = false; 3884 for (Type proper : properList) { 3885 if (types.isSubtype(checked, proper)) { 3886 isSubtype = true; 3887 break; 3888 } 3889 } 3890 if (!isSubtype) { 3891 uncaughtByProperTypes.add(checked); 3892 } 3893 } 3894 3895 if (nonProperList.isEmpty() && !uncaughtByProperTypes.isEmpty()) { 3896 return false; 3897 } 3898 3899 /** If n > 0, the constraint reduces to a set of subtyping constraints: 3900 * for all i (1 <= i <= m), if Xi is not a subtype of any proper type in the 3901 * throws clause, then the constraints include, for all j (1 <= j <= n), <Xi <: Ej> 3902 */ 3903 List<Type> nonProperAsUndet = inferenceContext.asUndetVars(nonProperList); 3904 uncaughtByProperTypes.forEach(checkedEx -> { 3905 nonProperAsUndet.forEach(nonProper -> { 3906 types.isSubtype(checkedEx, nonProper); 3907 }); 3908 }); 3909 3910 /** In addition, for all j (1 <= j <= n), the constraint reduces to the bound throws Ej 3911 */ 3912 nonProperAsUndet.stream() 3913 .filter(t -> t.hasTag(UNDETVAR)) 3914 .forEach(t -> ((UndetVar)t).setThrow()); 3915 return true; 3916 } 3917 3918 /** 3919 * Set functional type info on the underlying AST. Note: as the target descriptor 3920 * might contain inference variables, we might need to register an hook in the 3921 * current inference context. 3922 */ 3923 private void setFunctionalInfo(final Env<AttrContext> env, final JCFunctionalExpression fExpr, 3924 final Type pt, final Type descriptorType, final Type primaryTarget, final CheckContext checkContext) { 3925 if (checkContext.inferenceContext().free(descriptorType)) { 3926 checkContext.inferenceContext().addFreeTypeListener(List.of(pt, descriptorType), 3927 inferenceContext -> setFunctionalInfo(env, fExpr, pt, inferenceContext.asInstType(descriptorType), 3928 inferenceContext.asInstType(primaryTarget), checkContext)); 3929 } else { 3930 if (pt.hasTag(CLASS)) { 3931 fExpr.target = primaryTarget; 3932 } 3933 if (checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK && 3934 pt != Type.recoveryType) { 3935 //check that functional interface class is well-formed 3936 try { 3937 /* Types.makeFunctionalInterfaceClass() may throw an exception 3938 * when it's executed post-inference. See the listener code 3939 * above. 3940 */ 3941 ClassSymbol csym = types.makeFunctionalInterfaceClass(env, 3942 names.empty, fExpr.target, ABSTRACT); 3943 if (csym != null) { 3944 chk.checkImplementations(env.tree, csym, csym); 3945 try { 3946 //perform an additional functional interface check on the synthetic class, 3947 //as there may be spurious errors for raw targets - because of existing issues 3948 //with membership and inheritance (see JDK-8074570). 3949 csym.flags_field |= INTERFACE; 3950 types.findDescriptorType(csym.type); 3951 } catch (FunctionDescriptorLookupError err) { 3952 resultInfo.checkContext.report(fExpr, 3953 diags.fragment(Fragments.NoSuitableFunctionalIntfInst(fExpr.target))); 3954 } 3955 } 3956 } catch (Types.FunctionDescriptorLookupError ex) { 3957 JCDiagnostic cause = ex.getDiagnostic(); 3958 resultInfo.checkContext.report(env.tree, cause); 3959 } 3960 } 3961 } 3962 } 3963 3964 public void visitParens(JCParens tree) { 3965 Type owntype = attribTree(tree.expr, env, resultInfo); 3966 result = check(tree, owntype, pkind(), resultInfo); 3967 Symbol sym = TreeInfo.symbol(tree); 3968 if (sym != null && sym.kind.matches(KindSelector.TYP_PCK) && sym.kind != Kind.ERR) 3969 log.error(tree.pos(), Errors.IllegalParenthesizedExpression); 3970 } 3971 3972 public void visitAssign(JCAssign tree) { 3973 Type owntype = attribTree(tree.lhs, env.dup(tree), varAssignmentInfo); 3974 Type capturedType = capture(owntype); 3975 attribExpr(tree.rhs, env, owntype); 3976 result = check(tree, capturedType, KindSelector.VAL, resultInfo); 3977 } 3978 3979 public void visitAssignop(JCAssignOp tree) { 3980 // Attribute arguments. 3981 Type owntype = attribTree(tree.lhs, env, varAssignmentInfo); 3982 Type operand = attribExpr(tree.rhs, env); 3983 // Find operator. 3984 Symbol operator = tree.operator = operators.resolveBinary(tree, tree.getTag().noAssignOp(), owntype, operand); 3985 if (operator != operators.noOpSymbol && 3986 !owntype.isErroneous() && 3987 !operand.isErroneous()) { 3988 chk.checkDivZero(tree.rhs.pos(), operator, operand); 3989 chk.checkCastable(tree.rhs.pos(), 3990 operator.type.getReturnType(), 3991 owntype); 3992 chk.checkLossOfPrecision(tree.rhs.pos(), operand, owntype); 3993 } 3994 result = check(tree, owntype, KindSelector.VAL, resultInfo); 3995 } 3996 3997 public void visitUnary(JCUnary tree) { 3998 // Attribute arguments. 3999 Type argtype = (tree.getTag().isIncOrDecUnaryOp()) 4000 ? attribTree(tree.arg, env, varAssignmentInfo) 4001 : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env)); 4002 4003 // Find operator. 4004 OperatorSymbol operator = tree.operator = operators.resolveUnary(tree, tree.getTag(), argtype); 4005 Type owntype = types.createErrorType(tree.type); 4006 if (operator != operators.noOpSymbol && 4007 !argtype.isErroneous()) { 4008 owntype = (tree.getTag().isIncOrDecUnaryOp()) 4009 ? tree.arg.type 4010 : operator.type.getReturnType(); 4011 int opc = operator.opcode; 4012 4013 // If the argument is constant, fold it. 4014 if (argtype.constValue() != null) { 4015 Type ctype = cfolder.fold1(opc, argtype); 4016 if (ctype != null) { 4017 owntype = cfolder.coerce(ctype, owntype); 4018 } 4019 } 4020 } 4021 result = check(tree, owntype, KindSelector.VAL, resultInfo); 4022 matchBindings = matchBindingsComputer.unary(tree, matchBindings); 4023 } 4024 4025 public void visitBinary(JCBinary tree) { 4026 // Attribute arguments. 4027 Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env)); 4028 // x && y 4029 // include x's bindings when true in y 4030 4031 // x || y 4032 // include x's bindings when false in y 4033 4034 MatchBindings lhsBindings = matchBindings; 4035 List<BindingSymbol> propagatedBindings; 4036 switch (tree.getTag()) { 4037 case AND: 4038 propagatedBindings = lhsBindings.bindingsWhenTrue; 4039 break; 4040 case OR: 4041 propagatedBindings = lhsBindings.bindingsWhenFalse; 4042 break; 4043 default: 4044 propagatedBindings = List.nil(); 4045 break; 4046 } 4047 Env<AttrContext> rhsEnv = bindingEnv(env, propagatedBindings); 4048 Type right; 4049 try { 4050 right = chk.checkNonVoid(tree.rhs.pos(), attribExpr(tree.rhs, rhsEnv)); 4051 } finally { 4052 rhsEnv.info.scope.leave(); 4053 } 4054 4055 matchBindings = matchBindingsComputer.binary(tree, lhsBindings, matchBindings); 4056 4057 // Find operator. 4058 OperatorSymbol operator = tree.operator = operators.resolveBinary(tree, tree.getTag(), left, right); 4059 Type owntype = types.createErrorType(tree.type); 4060 if (operator != operators.noOpSymbol && 4061 !left.isErroneous() && 4062 !right.isErroneous()) { 4063 owntype = operator.type.getReturnType(); 4064 int opc = operator.opcode; 4065 // If both arguments are constants, fold them. 4066 if (left.constValue() != null && right.constValue() != null) { 4067 Type ctype = cfolder.fold2(opc, left, right); 4068 if (ctype != null) { 4069 owntype = cfolder.coerce(ctype, owntype); 4070 } 4071 } 4072 4073 // Check that argument types of a reference ==, != are 4074 // castable to each other, (JLS 15.21). Note: unboxing 4075 // comparisons will not have an acmp* opc at this point. 4076 if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) { 4077 if (!types.isCastable(left, right, new Warner(tree.pos()))) { 4078 log.error(tree.pos(), Errors.IncomparableTypes(left, right)); 4079 } 4080 } 4081 4082 chk.checkDivZero(tree.rhs.pos(), operator, right); 4083 } 4084 result = check(tree, owntype, KindSelector.VAL, resultInfo); 4085 } 4086 4087 public void visitTypeCast(final JCTypeCast tree) { 4088 Type clazztype = attribType(tree.clazz, env); 4089 chk.validate(tree.clazz, env, false); 4090 //a fresh environment is required for 292 inference to work properly --- 4091 //see Infer.instantiatePolymorphicSignatureInstance() 4092 Env<AttrContext> localEnv = env.dup(tree); 4093 //should we propagate the target type? 4094 final ResultInfo castInfo; 4095 JCExpression expr = TreeInfo.skipParens(tree.expr); 4096 boolean isPoly = (expr.hasTag(LAMBDA) || expr.hasTag(REFERENCE)); 4097 if (isPoly) { 4098 //expression is a poly - we need to propagate target type info 4099 castInfo = new ResultInfo(KindSelector.VAL, clazztype, 4100 new Check.NestedCheckContext(resultInfo.checkContext) { 4101 @Override 4102 public boolean compatible(Type found, Type req, Warner warn) { 4103 return types.isCastable(found, req, warn); 4104 } 4105 }); 4106 } else { 4107 //standalone cast - target-type info is not propagated 4108 castInfo = unknownExprInfo; 4109 } 4110 Type exprtype = attribTree(tree.expr, localEnv, castInfo); 4111 Type owntype = isPoly ? clazztype : chk.checkCastable(tree.expr.pos(), exprtype, clazztype); 4112 if (exprtype.constValue() != null) 4113 owntype = cfolder.coerce(exprtype, owntype); 4114 result = check(tree, capture(owntype), KindSelector.VAL, resultInfo); 4115 if (!isPoly) 4116 chk.checkRedundantCast(localEnv, tree); 4117 } 4118 4119 public void visitTypeTest(JCInstanceOf tree) { 4120 Type exprtype = chk.checkNullOrRefType( 4121 tree.expr.pos(), attribExpr(tree.expr, env)); 4122 Type clazztype; 4123 JCTree typeTree; 4124 if (tree.pattern.getTag() == BINDINGPATTERN || 4125 tree.pattern.getTag() == RECORDPATTERN) { 4126 attribExpr(tree.pattern, env, exprtype); 4127 clazztype = tree.pattern.type; 4128 if (types.isSubtype(exprtype, clazztype) && 4129 !exprtype.isErroneous() && !clazztype.isErroneous() && 4130 tree.pattern.getTag() != RECORDPATTERN) { 4131 if (!allowUnconditionalPatternsInstanceOf) { 4132 log.error(DiagnosticFlag.SOURCE_LEVEL, tree.pos(), 4133 Feature.UNCONDITIONAL_PATTERN_IN_INSTANCEOF.error(this.sourceName)); 4134 } 4135 } 4136 typeTree = TreeInfo.primaryPatternTypeTree((JCPattern) tree.pattern); 4137 } else { 4138 clazztype = attribType(tree.pattern, env); 4139 typeTree = tree.pattern; 4140 chk.validate(typeTree, env, false); 4141 } 4142 if (!clazztype.hasTag(TYPEVAR)) { 4143 clazztype = chk.checkClassOrArrayType(typeTree.pos(), clazztype); 4144 } 4145 if (!clazztype.isErroneous() && !types.isReifiable(clazztype)) { 4146 boolean valid = false; 4147 if (allowReifiableTypesInInstanceof) { 4148 valid = checkCastablePattern(tree.expr.pos(), exprtype, clazztype); 4149 } else { 4150 log.error(DiagnosticFlag.SOURCE_LEVEL, tree.pos(), 4151 Feature.REIFIABLE_TYPES_INSTANCEOF.error(this.sourceName)); 4152 allowReifiableTypesInInstanceof = true; 4153 } 4154 if (!valid) { 4155 clazztype = types.createErrorType(clazztype); 4156 } 4157 } 4158 chk.checkCastable(tree.expr.pos(), exprtype, clazztype); 4159 result = check(tree, syms.booleanType, KindSelector.VAL, resultInfo); 4160 } 4161 4162 private boolean checkCastablePattern(DiagnosticPosition pos, 4163 Type exprType, 4164 Type pattType) { 4165 Warner warner = new Warner(); 4166 // if any type is erroneous, the problem is reported elsewhere 4167 if (exprType.isErroneous() || pattType.isErroneous()) { 4168 return false; 4169 } 4170 if (!types.isCastable(exprType, pattType, warner)) { 4171 chk.basicHandler.report(pos, 4172 diags.fragment(Fragments.InconvertibleTypes(exprType, pattType))); 4173 return false; 4174 } else if ((exprType.isPrimitive() || pattType.isPrimitive()) && 4175 (!exprType.isPrimitive() || 4176 !pattType.isPrimitive() || 4177 !types.isSameType(exprType, pattType))) { 4178 chk.basicHandler.report(pos, 4179 diags.fragment(Fragments.NotApplicableTypes(exprType, pattType))); 4180 return false; 4181 } else if (warner.hasLint(LintCategory.UNCHECKED)) { 4182 log.error(pos, 4183 Errors.InstanceofReifiableNotSafe(exprType, pattType)); 4184 return false; 4185 } else { 4186 return true; 4187 } 4188 } 4189 4190 @Override 4191 public void visitAnyPattern(JCAnyPattern tree) { 4192 result = tree.type = resultInfo.pt; 4193 } 4194 4195 public void visitBindingPattern(JCBindingPattern tree) { 4196 Type type; 4197 if (tree.var.vartype != null) { 4198 type = attribType(tree.var.vartype, env); 4199 } else { 4200 type = resultInfo.pt; 4201 } 4202 tree.type = tree.var.type = type; 4203 BindingSymbol v = new BindingSymbol(tree.var.mods.flags, tree.var.name, type, env.info.scope.owner); 4204 v.pos = tree.pos; 4205 tree.var.sym = v; 4206 if (chk.checkUnique(tree.var.pos(), v, env.info.scope)) { 4207 chk.checkTransparentVar(tree.var.pos(), v, env.info.scope); 4208 } 4209 if (tree.var.vartype != null) { 4210 annotate.annotateLater(tree.var.mods.annotations, env, v, tree.pos()); 4211 annotate.queueScanTreeAndTypeAnnotate(tree.var.vartype, env, v, tree.var.pos()); 4212 annotate.flush(); 4213 } 4214 chk.validate(tree.var.vartype, env, true); 4215 result = tree.type; 4216 if (v.isUnnamedVariable()) { 4217 matchBindings = MatchBindingsComputer.EMPTY; 4218 } else { 4219 matchBindings = new MatchBindings(List.of(v), List.nil()); 4220 } 4221 } 4222 4223 @Override 4224 public void visitRecordPattern(JCRecordPattern tree) { 4225 Type site; 4226 4227 if (tree.deconstructor == null) { 4228 log.error(tree.pos(), Errors.DeconstructionPatternVarNotAllowed); 4229 tree.record = syms.errSymbol; 4230 site = tree.type = types.createErrorType(tree.record.type); 4231 } else { 4232 Type type = attribType(tree.deconstructor, env); 4233 if (type.isRaw() && type.tsym.getTypeParameters().nonEmpty()) { 4234 Type inferred = infer.instantiatePatternType(resultInfo.pt, type.tsym); 4235 if (inferred == null) { 4236 log.error(tree.pos(), Errors.PatternTypeCannotInfer); 4237 } else { 4238 type = inferred; 4239 } 4240 } 4241 tree.type = tree.deconstructor.type = type; 4242 site = types.capture(tree.type); 4243 } 4244 4245 List<Type> expectedRecordTypes; 4246 if (site.tsym.kind == Kind.TYP && ((ClassSymbol) site.tsym).isRecord()) { 4247 ClassSymbol record = (ClassSymbol) site.tsym; 4248 expectedRecordTypes = record.getRecordComponents() 4249 .stream() 4250 .map(rc -> types.memberType(site, rc)) 4251 .map(t -> types.upward(t, types.captures(t)).baseType()) 4252 .collect(List.collector()); 4253 tree.record = record; 4254 } else { 4255 log.error(tree.pos(), Errors.DeconstructionPatternOnlyRecords(site.tsym)); 4256 expectedRecordTypes = Stream.generate(() -> types.createErrorType(tree.type)) 4257 .limit(tree.nested.size()) 4258 .collect(List.collector()); 4259 tree.record = syms.errSymbol; 4260 } 4261 ListBuffer<BindingSymbol> outBindings = new ListBuffer<>(); 4262 List<Type> recordTypes = expectedRecordTypes; 4263 List<JCPattern> nestedPatterns = tree.nested; 4264 Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup())); 4265 try { 4266 while (recordTypes.nonEmpty() && nestedPatterns.nonEmpty()) { 4267 attribExpr(nestedPatterns.head, localEnv, recordTypes.head); 4268 checkCastablePattern(nestedPatterns.head.pos(), recordTypes.head, nestedPatterns.head.type); 4269 outBindings.addAll(matchBindings.bindingsWhenTrue); 4270 matchBindings.bindingsWhenTrue.forEach(localEnv.info.scope::enter); 4271 nestedPatterns = nestedPatterns.tail; 4272 recordTypes = recordTypes.tail; 4273 } 4274 if (recordTypes.nonEmpty() || nestedPatterns.nonEmpty()) { 4275 while (nestedPatterns.nonEmpty()) { 4276 attribExpr(nestedPatterns.head, localEnv, Type.noType); 4277 nestedPatterns = nestedPatterns.tail; 4278 } 4279 List<Type> nestedTypes = 4280 tree.nested.stream().map(p -> p.type).collect(List.collector()); 4281 log.error(tree.pos(), 4282 Errors.IncorrectNumberOfNestedPatterns(expectedRecordTypes, 4283 nestedTypes)); 4284 } 4285 } finally { 4286 localEnv.info.scope.leave(); 4287 } 4288 chk.validate(tree.deconstructor, env, true); 4289 result = tree.type; 4290 matchBindings = new MatchBindings(outBindings.toList(), List.nil()); 4291 } 4292 4293 public void visitIndexed(JCArrayAccess tree) { 4294 Type owntype = types.createErrorType(tree.type); 4295 Type atype = attribExpr(tree.indexed, env); 4296 attribExpr(tree.index, env, syms.intType); 4297 if (types.isArray(atype)) 4298 owntype = types.elemtype(atype); 4299 else if (!atype.hasTag(ERROR)) 4300 log.error(tree.pos(), Errors.ArrayReqButFound(atype)); 4301 if (!pkind().contains(KindSelector.VAL)) 4302 owntype = capture(owntype); 4303 result = check(tree, owntype, KindSelector.VAR, resultInfo); 4304 } 4305 4306 public void visitIdent(JCIdent tree) { 4307 Symbol sym; 4308 4309 // Find symbol 4310 if (pt().hasTag(METHOD) || pt().hasTag(FORALL)) { 4311 // If we are looking for a method, the prototype `pt' will be a 4312 // method type with the type of the call's arguments as parameters. 4313 env.info.pendingResolutionPhase = null; 4314 sym = rs.resolveMethod(tree.pos(), env, tree.name, pt().getParameterTypes(), pt().getTypeArguments()); 4315 } else if (tree.sym != null && tree.sym.kind != VAR) { 4316 sym = tree.sym; 4317 } else { 4318 sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind()); 4319 } 4320 tree.sym = sym; 4321 4322 // Also find the environment current for the class where 4323 // sym is defined (`symEnv'). 4324 Env<AttrContext> symEnv = env; 4325 if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class 4326 sym.kind.matches(KindSelector.VAL_MTH) && 4327 sym.owner.kind == TYP && 4328 tree.name != names._this && tree.name != names._super) { 4329 4330 // Find environment in which identifier is defined. 4331 while (symEnv.outer != null && 4332 !sym.isMemberOf(symEnv.enclClass.sym, types)) { 4333 symEnv = symEnv.outer; 4334 } 4335 } 4336 4337 // If symbol is a variable, ... 4338 if (sym.kind == VAR) { 4339 VarSymbol v = (VarSymbol)sym; 4340 4341 // ..., evaluate its initializer, if it has one, and check for 4342 // illegal forward reference. 4343 checkInit(tree, env, v, false); 4344 4345 // If we are expecting a variable (as opposed to a value), check 4346 // that the variable is assignable in the current environment. 4347 if (KindSelector.ASG.subset(pkind())) 4348 checkAssignable(tree.pos(), v, null, env); 4349 } 4350 4351 Env<AttrContext> env1 = env; 4352 if (sym.kind != ERR && sym.kind != TYP && 4353 sym.owner != null && sym.owner != env1.enclClass.sym) { 4354 // If the found symbol is inaccessible, then it is 4355 // accessed through an enclosing instance. Locate this 4356 // enclosing instance: 4357 while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym)) 4358 env1 = env1.outer; 4359 } 4360 4361 if (env.info.isSerializable) { 4362 chk.checkAccessFromSerializableElement(tree, env.info.isSerializableLambda); 4363 } 4364 4365 result = checkId(tree, env1.enclClass.sym.type, sym, env, resultInfo); 4366 } 4367 4368 public void visitSelect(JCFieldAccess tree) { 4369 // Determine the expected kind of the qualifier expression. 4370 KindSelector skind = KindSelector.NIL; 4371 if (tree.name == names._this || tree.name == names._super || 4372 tree.name == names._class) 4373 { 4374 skind = KindSelector.TYP; 4375 } else { 4376 if (pkind().contains(KindSelector.PCK)) 4377 skind = KindSelector.of(skind, KindSelector.PCK); 4378 if (pkind().contains(KindSelector.TYP)) 4379 skind = KindSelector.of(skind, KindSelector.TYP, KindSelector.PCK); 4380 if (pkind().contains(KindSelector.VAL_MTH)) 4381 skind = KindSelector.of(skind, KindSelector.VAL, KindSelector.TYP); 4382 } 4383 4384 // Attribute the qualifier expression, and determine its symbol (if any). 4385 Type site = attribTree(tree.selected, env, new ResultInfo(skind, Type.noType)); 4386 Assert.check(site == tree.selected.type); 4387 if (!pkind().contains(KindSelector.TYP_PCK)) 4388 site = capture(site); // Capture field access 4389 4390 // don't allow T.class T[].class, etc 4391 if (skind == KindSelector.TYP) { 4392 Type elt = site; 4393 while (elt.hasTag(ARRAY)) 4394 elt = ((ArrayType)elt).elemtype; 4395 if (elt.hasTag(TYPEVAR)) { 4396 log.error(tree.pos(), Errors.TypeVarCantBeDeref); 4397 result = tree.type = types.createErrorType(tree.name, site.tsym, site); 4398 tree.sym = tree.type.tsym; 4399 return ; 4400 } 4401 } 4402 4403 // If qualifier symbol is a type or `super', assert `selectSuper' 4404 // for the selection. This is relevant for determining whether 4405 // protected symbols are accessible. 4406 Symbol sitesym = TreeInfo.symbol(tree.selected); 4407 boolean selectSuperPrev = env.info.selectSuper; 4408 env.info.selectSuper = 4409 sitesym != null && 4410 sitesym.name == names._super; 4411 4412 // Determine the symbol represented by the selection. 4413 env.info.pendingResolutionPhase = null; 4414 Symbol sym = selectSym(tree, sitesym, site, env, resultInfo); 4415 if (sym.kind == VAR && sym.name != names._super && env.info.defaultSuperCallSite != null) { 4416 log.error(tree.selected.pos(), Errors.NotEnclClass(site.tsym)); 4417 sym = syms.errSymbol; 4418 } 4419 if (sym.exists() && !isType(sym) && pkind().contains(KindSelector.TYP_PCK)) { 4420 site = capture(site); 4421 sym = selectSym(tree, sitesym, site, env, resultInfo); 4422 } 4423 boolean varArgs = env.info.lastResolveVarargs(); 4424 tree.sym = sym; 4425 4426 if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) { 4427 site = types.skipTypeVars(site, true); 4428 } 4429 4430 // If that symbol is a variable, ... 4431 if (sym.kind == VAR) { 4432 VarSymbol v = (VarSymbol)sym; 4433 4434 // ..., evaluate its initializer, if it has one, and check for 4435 // illegal forward reference. 4436 checkInit(tree, env, v, true); 4437 4438 // If we are expecting a variable (as opposed to a value), check 4439 // that the variable is assignable in the current environment. 4440 if (KindSelector.ASG.subset(pkind())) 4441 checkAssignable(tree.pos(), v, tree.selected, env); 4442 } 4443 4444 if (sitesym != null && 4445 sitesym.kind == VAR && 4446 ((VarSymbol)sitesym).isResourceVariable() && 4447 sym.kind == MTH && 4448 sym.name.equals(names.close) && 4449 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) && 4450 env.info.lint.isEnabled(LintCategory.TRY)) { 4451 log.warning(LintCategory.TRY, tree, Warnings.TryExplicitCloseCall); 4452 } 4453 4454 // Disallow selecting a type from an expression 4455 if (isType(sym) && (sitesym == null || !sitesym.kind.matches(KindSelector.TYP_PCK))) { 4456 tree.type = check(tree.selected, pt(), 4457 sitesym == null ? 4458 KindSelector.VAL : sitesym.kind.toSelector(), 4459 new ResultInfo(KindSelector.TYP_PCK, pt())); 4460 } 4461 4462 if (isType(sitesym)) { 4463 if (sym.name != names._this && sym.name != names._super) { 4464 // Check if type-qualified fields or methods are static (JLS) 4465 if ((sym.flags() & STATIC) == 0 && 4466 sym.name != names._super && 4467 (sym.kind == VAR || sym.kind == MTH)) { 4468 rs.accessBase(rs.new StaticError(sym), 4469 tree.pos(), site, sym.name, true); 4470 } 4471 } 4472 } else if (sym.kind != ERR && 4473 (sym.flags() & STATIC) != 0 && 4474 sym.name != names._class) { 4475 // If the qualified item is not a type and the selected item is static, report 4476 // a warning. Make allowance for the class of an array type e.g. Object[].class) 4477 if (!sym.owner.isAnonymous()) { 4478 chk.warnStatic(tree, Warnings.StaticNotQualifiedByType(sym.kind.kindName(), sym.owner)); 4479 } else { 4480 chk.warnStatic(tree, Warnings.StaticNotQualifiedByType2(sym.kind.kindName())); 4481 } 4482 } 4483 4484 // If we are selecting an instance member via a `super', ... 4485 if (env.info.selectSuper && (sym.flags() & STATIC) == 0) { 4486 4487 // Check that super-qualified symbols are not abstract (JLS) 4488 rs.checkNonAbstract(tree.pos(), sym); 4489 4490 if (site.isRaw()) { 4491 // Determine argument types for site. 4492 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym); 4493 if (site1 != null) site = site1; 4494 } 4495 } 4496 4497 if (env.info.isSerializable) { 4498 chk.checkAccessFromSerializableElement(tree, env.info.isSerializableLambda); 4499 } 4500 4501 env.info.selectSuper = selectSuperPrev; 4502 result = checkId(tree, site, sym, env, resultInfo); 4503 } 4504 //where 4505 /** Determine symbol referenced by a Select expression, 4506 * 4507 * @param tree The select tree. 4508 * @param site The type of the selected expression, 4509 * @param env The current environment. 4510 * @param resultInfo The current result. 4511 */ 4512 private Symbol selectSym(JCFieldAccess tree, 4513 Symbol location, 4514 Type site, 4515 Env<AttrContext> env, 4516 ResultInfo resultInfo) { 4517 DiagnosticPosition pos = tree.pos(); 4518 Name name = tree.name; 4519 switch (site.getTag()) { 4520 case PACKAGE: 4521 return rs.accessBase( 4522 rs.findIdentInPackage(pos, env, site.tsym, name, resultInfo.pkind), 4523 pos, location, site, name, true); 4524 case ARRAY: 4525 case CLASS: 4526 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) { 4527 return rs.resolveQualifiedMethod( 4528 pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments()); 4529 } else if (name == names._this || name == names._super) { 4530 return rs.resolveSelf(pos, env, site.tsym, name); 4531 } else if (name == names._class) { 4532 // In this case, we have already made sure in 4533 // visitSelect that qualifier expression is a type. 4534 return syms.getClassField(site, types); 4535 } else { 4536 // We are seeing a plain identifier as selector. 4537 Symbol sym = rs.findIdentInType(pos, env, site, name, resultInfo.pkind); 4538 sym = rs.accessBase(sym, pos, location, site, name, true); 4539 return sym; 4540 } 4541 case WILDCARD: 4542 throw new AssertionError(tree); 4543 case TYPEVAR: 4544 // Normally, site.getUpperBound() shouldn't be null. 4545 // It should only happen during memberEnter/attribBase 4546 // when determining the supertype which *must* be 4547 // done before attributing the type variables. In 4548 // other words, we are seeing this illegal program: 4549 // class B<T> extends A<T.foo> {} 4550 Symbol sym = (site.getUpperBound() != null) 4551 ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo) 4552 : null; 4553 if (sym == null) { 4554 log.error(pos, Errors.TypeVarCantBeDeref); 4555 return syms.errSymbol; 4556 } else { 4557 Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ? 4558 rs.new AccessError(env, site, sym) : 4559 sym; 4560 rs.accessBase(sym2, pos, location, site, name, true); 4561 return sym; 4562 } 4563 case ERROR: 4564 // preserve identifier names through errors 4565 return types.createErrorType(name, site.tsym, site).tsym; 4566 default: 4567 // The qualifier expression is of a primitive type -- only 4568 // .class is allowed for these. 4569 if (name == names._class) { 4570 // In this case, we have already made sure in Select that 4571 // qualifier expression is a type. 4572 return syms.getClassField(site, types); 4573 } else { 4574 log.error(pos, Errors.CantDeref(site)); 4575 return syms.errSymbol; 4576 } 4577 } 4578 } 4579 4580 /** Determine type of identifier or select expression and check that 4581 * (1) the referenced symbol is not deprecated 4582 * (2) the symbol's type is safe (@see checkSafe) 4583 * (3) if symbol is a variable, check that its type and kind are 4584 * compatible with the prototype and protokind. 4585 * (4) if symbol is an instance field of a raw type, 4586 * which is being assigned to, issue an unchecked warning if its 4587 * type changes under erasure. 4588 * (5) if symbol is an instance method of a raw type, issue an 4589 * unchecked warning if its argument types change under erasure. 4590 * If checks succeed: 4591 * If symbol is a constant, return its constant type 4592 * else if symbol is a method, return its result type 4593 * otherwise return its type. 4594 * Otherwise return errType. 4595 * 4596 * @param tree The syntax tree representing the identifier 4597 * @param site If this is a select, the type of the selected 4598 * expression, otherwise the type of the current class. 4599 * @param sym The symbol representing the identifier. 4600 * @param env The current environment. 4601 * @param resultInfo The expected result 4602 */ 4603 Type checkId(JCTree tree, 4604 Type site, 4605 Symbol sym, 4606 Env<AttrContext> env, 4607 ResultInfo resultInfo) { 4608 return (resultInfo.pt.hasTag(FORALL) || resultInfo.pt.hasTag(METHOD)) ? 4609 checkMethodIdInternal(tree, site, sym, env, resultInfo) : 4610 checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo); 4611 } 4612 4613 Type checkMethodIdInternal(JCTree tree, 4614 Type site, 4615 Symbol sym, 4616 Env<AttrContext> env, 4617 ResultInfo resultInfo) { 4618 if (resultInfo.pkind.contains(KindSelector.POLY)) { 4619 return attrRecover.recoverMethodInvocation(tree, site, sym, env, resultInfo); 4620 } else { 4621 return checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo); 4622 } 4623 } 4624 4625 Type checkIdInternal(JCTree tree, 4626 Type site, 4627 Symbol sym, 4628 Type pt, 4629 Env<AttrContext> env, 4630 ResultInfo resultInfo) { 4631 if (pt.isErroneous()) { 4632 return types.createErrorType(site); 4633 } 4634 Type owntype; // The computed type of this identifier occurrence. 4635 switch (sym.kind) { 4636 case TYP: 4637 // For types, the computed type equals the symbol's type, 4638 // except for two situations: 4639 owntype = sym.type; 4640 if (owntype.hasTag(CLASS)) { 4641 chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym); 4642 Type ownOuter = owntype.getEnclosingType(); 4643 4644 // (a) If the symbol's type is parameterized, erase it 4645 // because no type parameters were given. 4646 // We recover generic outer type later in visitTypeApply. 4647 if (owntype.tsym.type.getTypeArguments().nonEmpty()) { 4648 owntype = types.erasure(owntype); 4649 } 4650 4651 // (b) If the symbol's type is an inner class, then 4652 // we have to interpret its outer type as a superclass 4653 // of the site type. Example: 4654 // 4655 // class Tree<A> { class Visitor { ... } } 4656 // class PointTree extends Tree<Point> { ... } 4657 // ...PointTree.Visitor... 4658 // 4659 // Then the type of the last expression above is 4660 // Tree<Point>.Visitor. 4661 else if (ownOuter.hasTag(CLASS) && site != ownOuter) { 4662 Type normOuter = site; 4663 if (normOuter.hasTag(CLASS)) { 4664 normOuter = types.asEnclosingSuper(site, ownOuter.tsym); 4665 } 4666 if (normOuter == null) // perhaps from an import 4667 normOuter = types.erasure(ownOuter); 4668 if (normOuter != ownOuter) 4669 owntype = new ClassType( 4670 normOuter, List.nil(), owntype.tsym, 4671 owntype.getMetadata()); 4672 } 4673 } 4674 break; 4675 case VAR: 4676 VarSymbol v = (VarSymbol)sym; 4677 4678 if (env.info.enclVar != null 4679 && v.type.hasTag(NONE)) { 4680 //self reference to implicitly typed variable declaration 4681 log.error(TreeInfo.positionFor(v, env.enclClass), Errors.CantInferLocalVarType(v.name, Fragments.LocalSelfRef)); 4682 return tree.type = v.type = types.createErrorType(v.type); 4683 } 4684 4685 // Test (4): if symbol is an instance field of a raw type, 4686 // which is being assigned to, issue an unchecked warning if 4687 // its type changes under erasure. 4688 if (KindSelector.ASG.subset(pkind()) && 4689 v.owner.kind == TYP && 4690 (v.flags() & STATIC) == 0 && 4691 (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) { 4692 Type s = types.asOuterSuper(site, v.owner); 4693 if (s != null && 4694 s.isRaw() && 4695 !types.isSameType(v.type, v.erasure(types))) { 4696 chk.warnUnchecked(tree.pos(), Warnings.UncheckedAssignToVar(v, s)); 4697 } 4698 } 4699 // The computed type of a variable is the type of the 4700 // variable symbol, taken as a member of the site type. 4701 owntype = (sym.owner.kind == TYP && 4702 sym.name != names._this && sym.name != names._super) 4703 ? types.memberType(site, sym) 4704 : sym.type; 4705 4706 // If the variable is a constant, record constant value in 4707 // computed type. 4708 if (v.getConstValue() != null && isStaticReference(tree)) 4709 owntype = owntype.constType(v.getConstValue()); 4710 4711 if (resultInfo.pkind == KindSelector.VAL) { 4712 owntype = capture(owntype); // capture "names as expressions" 4713 } 4714 break; 4715 case MTH: { 4716 owntype = checkMethod(site, sym, 4717 new ResultInfo(resultInfo.pkind, resultInfo.pt.getReturnType(), resultInfo.checkContext, resultInfo.checkMode), 4718 env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(), 4719 resultInfo.pt.getTypeArguments()); 4720 chk.checkRestricted(tree.pos(), sym); 4721 break; 4722 } 4723 case PCK: case ERR: 4724 owntype = sym.type; 4725 break; 4726 default: 4727 throw new AssertionError("unexpected kind: " + sym.kind + 4728 " in tree " + tree); 4729 } 4730 4731 // Emit a `deprecation' warning if symbol is deprecated. 4732 // (for constructors (but not for constructor references), the error 4733 // was given when the constructor was resolved) 4734 4735 if (sym.name != names.init || tree.hasTag(REFERENCE)) { 4736 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym); 4737 chk.checkSunAPI(tree.pos(), sym); 4738 chk.checkProfile(tree.pos(), sym); 4739 chk.checkPreview(tree.pos(), env.info.scope.owner, sym); 4740 } 4741 4742 // If symbol is a variable, check that its type and 4743 // kind are compatible with the prototype and protokind. 4744 return check(tree, owntype, sym.kind.toSelector(), resultInfo); 4745 } 4746 4747 /** Check that variable is initialized and evaluate the variable's 4748 * initializer, if not yet done. Also check that variable is not 4749 * referenced before it is defined. 4750 * @param tree The tree making up the variable reference. 4751 * @param env The current environment. 4752 * @param v The variable's symbol. 4753 */ 4754 private void checkInit(JCTree tree, 4755 Env<AttrContext> env, 4756 VarSymbol v, 4757 boolean onlyWarning) { 4758 // A forward reference is diagnosed if the declaration position 4759 // of the variable is greater than the current tree position 4760 // and the tree and variable definition occur in the same class 4761 // definition. Note that writes don't count as references. 4762 // This check applies only to class and instance 4763 // variables. Local variables follow different scope rules, 4764 // and are subject to definite assignment checking. 4765 Env<AttrContext> initEnv = enclosingInitEnv(env); 4766 if (initEnv != null && 4767 (initEnv.info.enclVar == v || v.pos > tree.pos) && 4768 v.owner.kind == TYP && 4769 v.owner == env.info.scope.owner.enclClass() && 4770 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) && 4771 (!env.tree.hasTag(ASSIGN) || 4772 TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) { 4773 if (!onlyWarning || isStaticEnumField(v)) { 4774 Error errkey = (initEnv.info.enclVar == v) ? 4775 Errors.IllegalSelfRef : Errors.IllegalForwardRef; 4776 log.error(tree.pos(), errkey); 4777 } else if (useBeforeDeclarationWarning) { 4778 Warning warnkey = (initEnv.info.enclVar == v) ? 4779 Warnings.SelfRef(v) : Warnings.ForwardRef(v); 4780 log.warning(tree.pos(), warnkey); 4781 } 4782 } 4783 4784 v.getConstValue(); // ensure initializer is evaluated 4785 4786 checkEnumInitializer(tree, env, v); 4787 } 4788 4789 /** 4790 * Returns the enclosing init environment associated with this env (if any). An init env 4791 * can be either a field declaration env or a static/instance initializer env. 4792 */ 4793 Env<AttrContext> enclosingInitEnv(Env<AttrContext> env) { 4794 while (true) { 4795 switch (env.tree.getTag()) { 4796 case VARDEF: 4797 JCVariableDecl vdecl = (JCVariableDecl)env.tree; 4798 if (vdecl.sym.owner.kind == TYP) { 4799 //field 4800 return env; 4801 } 4802 break; 4803 case BLOCK: 4804 if (env.next.tree.hasTag(CLASSDEF)) { 4805 //instance/static initializer 4806 return env; 4807 } 4808 break; 4809 case METHODDEF: 4810 case CLASSDEF: 4811 case TOPLEVEL: 4812 return null; 4813 } 4814 Assert.checkNonNull(env.next); 4815 env = env.next; 4816 } 4817 } 4818 4819 /** 4820 * Check for illegal references to static members of enum. In 4821 * an enum type, constructors and initializers may not 4822 * reference its static members unless they are constant. 4823 * 4824 * @param tree The tree making up the variable reference. 4825 * @param env The current environment. 4826 * @param v The variable's symbol. 4827 * @jls 8.9 Enum Types 4828 */ 4829 private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) { 4830 // JLS: 4831 // 4832 // "It is a compile-time error to reference a static field 4833 // of an enum type that is not a compile-time constant 4834 // (15.28) from constructors, instance initializer blocks, 4835 // or instance variable initializer expressions of that 4836 // type. It is a compile-time error for the constructors, 4837 // instance initializer blocks, or instance variable 4838 // initializer expressions of an enum constant e to refer 4839 // to itself or to an enum constant of the same type that 4840 // is declared to the right of e." 4841 if (isStaticEnumField(v)) { 4842 ClassSymbol enclClass = env.info.scope.owner.enclClass(); 4843 4844 if (enclClass == null || enclClass.owner == null) 4845 return; 4846 4847 // See if the enclosing class is the enum (or a 4848 // subclass thereof) declaring v. If not, this 4849 // reference is OK. 4850 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type)) 4851 return; 4852 4853 // If the reference isn't from an initializer, then 4854 // the reference is OK. 4855 if (!Resolve.isInitializer(env)) 4856 return; 4857 4858 log.error(tree.pos(), Errors.IllegalEnumStaticRef); 4859 } 4860 } 4861 4862 /** Is the given symbol a static, non-constant field of an Enum? 4863 * Note: enum literals should not be regarded as such 4864 */ 4865 private boolean isStaticEnumField(VarSymbol v) { 4866 return Flags.isEnum(v.owner) && 4867 Flags.isStatic(v) && 4868 !Flags.isConstant(v) && 4869 v.name != names._class; 4870 } 4871 4872 /** 4873 * Check that method arguments conform to its instantiation. 4874 **/ 4875 public Type checkMethod(Type site, 4876 final Symbol sym, 4877 ResultInfo resultInfo, 4878 Env<AttrContext> env, 4879 final List<JCExpression> argtrees, 4880 List<Type> argtypes, 4881 List<Type> typeargtypes) { 4882 // Test (5): if symbol is an instance method of a raw type, issue 4883 // an unchecked warning if its argument types change under erasure. 4884 if ((sym.flags() & STATIC) == 0 && 4885 (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) { 4886 Type s = types.asOuterSuper(site, sym.owner); 4887 if (s != null && s.isRaw() && 4888 !types.isSameTypes(sym.type.getParameterTypes(), 4889 sym.erasure(types).getParameterTypes())) { 4890 chk.warnUnchecked(env.tree.pos(), Warnings.UncheckedCallMbrOfRawType(sym, s)); 4891 } 4892 } 4893 4894 if (env.info.defaultSuperCallSite != null) { 4895 for (Type sup : types.interfaces(env.enclClass.type).prepend(types.supertype((env.enclClass.type)))) { 4896 if (!sup.tsym.isSubClass(sym.enclClass(), types) || 4897 types.isSameType(sup, env.info.defaultSuperCallSite)) continue; 4898 List<MethodSymbol> icand_sup = 4899 types.interfaceCandidates(sup, (MethodSymbol)sym); 4900 if (icand_sup.nonEmpty() && 4901 icand_sup.head != sym && 4902 icand_sup.head.overrides(sym, icand_sup.head.enclClass(), types, true)) { 4903 log.error(env.tree.pos(), 4904 Errors.IllegalDefaultSuperCall(env.info.defaultSuperCallSite, Fragments.OverriddenDefault(sym, sup))); 4905 break; 4906 } 4907 } 4908 env.info.defaultSuperCallSite = null; 4909 } 4910 4911 if (sym.isStatic() && site.isInterface() && env.tree.hasTag(APPLY)) { 4912 JCMethodInvocation app = (JCMethodInvocation)env.tree; 4913 if (app.meth.hasTag(SELECT) && 4914 !TreeInfo.isStaticSelector(((JCFieldAccess)app.meth).selected, names)) { 4915 log.error(env.tree.pos(), Errors.IllegalStaticIntfMethCall(site)); 4916 } 4917 } 4918 4919 // Compute the identifier's instantiated type. 4920 // For methods, we need to compute the instance type by 4921 // Resolve.instantiate from the symbol's type as well as 4922 // any type arguments and value arguments. 4923 Warner noteWarner = new Warner(); 4924 try { 4925 Type owntype = rs.checkMethod( 4926 env, 4927 site, 4928 sym, 4929 resultInfo, 4930 argtypes, 4931 typeargtypes, 4932 noteWarner); 4933 4934 DeferredAttr.DeferredTypeMap<Void> checkDeferredMap = 4935 deferredAttr.new DeferredTypeMap<>(DeferredAttr.AttrMode.CHECK, sym, env.info.pendingResolutionPhase); 4936 4937 argtypes = argtypes.map(checkDeferredMap); 4938 4939 if (noteWarner.hasNonSilentLint(LintCategory.UNCHECKED)) { 4940 chk.warnUnchecked(env.tree.pos(), Warnings.UncheckedMethInvocationApplied(kindName(sym), 4941 sym.name, 4942 rs.methodArguments(sym.type.getParameterTypes()), 4943 rs.methodArguments(argtypes.map(checkDeferredMap)), 4944 kindName(sym.location()), 4945 sym.location())); 4946 if (resultInfo.pt != Infer.anyPoly || 4947 !owntype.hasTag(METHOD) || 4948 !owntype.isPartial()) { 4949 //if this is not a partially inferred method type, erase return type. Otherwise, 4950 //erasure is carried out in PartiallyInferredMethodType.check(). 4951 owntype = new MethodType(owntype.getParameterTypes(), 4952 types.erasure(owntype.getReturnType()), 4953 types.erasure(owntype.getThrownTypes()), 4954 syms.methodClass); 4955 } 4956 } 4957 4958 PolyKind pkind = (sym.type.hasTag(FORALL) && 4959 sym.type.getReturnType().containsAny(((ForAll)sym.type).tvars)) ? 4960 PolyKind.POLY : PolyKind.STANDALONE; 4961 TreeInfo.setPolyKind(env.tree, pkind); 4962 4963 return (resultInfo.pt == Infer.anyPoly) ? 4964 owntype : 4965 chk.checkMethod(owntype, sym, env, argtrees, argtypes, env.info.lastResolveVarargs(), 4966 resultInfo.checkContext.inferenceContext()); 4967 } catch (Infer.InferenceException ex) { 4968 //invalid target type - propagate exception outwards or report error 4969 //depending on the current check context 4970 resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic()); 4971 return types.createErrorType(site); 4972 } catch (Resolve.InapplicableMethodException ex) { 4973 final JCDiagnostic diag = ex.getDiagnostic(); 4974 Resolve.InapplicableSymbolError errSym = rs.new InapplicableSymbolError(null) { 4975 @Override 4976 protected Pair<Symbol, JCDiagnostic> errCandidate() { 4977 return new Pair<>(sym, diag); 4978 } 4979 }; 4980 List<Type> argtypes2 = argtypes.map( 4981 rs.new ResolveDeferredRecoveryMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase)); 4982 JCDiagnostic errDiag = errSym.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR, 4983 env.tree, sym, site, sym.name, argtypes2, typeargtypes); 4984 log.report(errDiag); 4985 return types.createErrorType(site); 4986 } 4987 } 4988 4989 public void visitLiteral(JCLiteral tree) { 4990 result = check(tree, litType(tree.typetag).constType(tree.value), 4991 KindSelector.VAL, resultInfo); 4992 } 4993 //where 4994 /** Return the type of a literal with given type tag. 4995 */ 4996 Type litType(TypeTag tag) { 4997 return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()]; 4998 } 4999 5000 public void visitStringTemplate(JCStringTemplate tree) { 5001 JCExpression processor = tree.processor; 5002 Type processorType = attribTree(processor, env, new ResultInfo(KindSelector.VAL, Type.noType)); 5003 chk.checkProcessorType(processor, processorType, env); 5004 Type processMethodType = getProcessMethodType(tree, processorType); 5005 tree.processMethodType = processMethodType; 5006 Type resultType = processMethodType.getReturnType(); 5007 5008 Env<AttrContext> localEnv = env.dup(tree, env.info.dup()); 5009 5010 for (JCExpression arg : tree.expressions) { 5011 chk.checkNonVoid(arg.pos(), attribExpr(arg, localEnv)); 5012 } 5013 5014 tree.type = resultType; 5015 result = resultType; 5016 check(tree, resultType, KindSelector.VAL, resultInfo); 5017 } 5018 5019 private Type getProcessMethodType(JCStringTemplate tree, Type processorType) { 5020 MethodSymbol processSymbol = rs.resolveInternalMethod(tree.pos(), 5021 env, types.skipTypeVars(processorType, false), 5022 names.process, List.of(syms.stringTemplateType), List.nil()); 5023 return types.memberType(processorType, processSymbol); 5024 } 5025 5026 public void visitTypeIdent(JCPrimitiveTypeTree tree) { 5027 result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], KindSelector.TYP, resultInfo); 5028 } 5029 5030 public void visitTypeArray(JCArrayTypeTree tree) { 5031 Type etype = attribType(tree.elemtype, env); 5032 Type type = new ArrayType(etype, syms.arrayClass); 5033 result = check(tree, type, KindSelector.TYP, resultInfo); 5034 } 5035 5036 /** Visitor method for parameterized types. 5037 * Bound checking is left until later, since types are attributed 5038 * before supertype structure is completely known 5039 */ 5040 public void visitTypeApply(JCTypeApply tree) { 5041 Type owntype = types.createErrorType(tree.type); 5042 5043 // Attribute functor part of application and make sure it's a class. 5044 Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env)); 5045 5046 // Attribute type parameters 5047 List<Type> actuals = attribTypes(tree.arguments, env); 5048 5049 if (clazztype.hasTag(CLASS)) { 5050 List<Type> formals = clazztype.tsym.type.getTypeArguments(); 5051 if (actuals.isEmpty()) //diamond 5052 actuals = formals; 5053 5054 if (actuals.length() == formals.length()) { 5055 List<Type> a = actuals; 5056 List<Type> f = formals; 5057 while (a.nonEmpty()) { 5058 a.head = a.head.withTypeVar(f.head); 5059 a = a.tail; 5060 f = f.tail; 5061 } 5062 // Compute the proper generic outer 5063 Type clazzOuter = clazztype.getEnclosingType(); 5064 if (clazzOuter.hasTag(CLASS)) { 5065 Type site; 5066 JCExpression clazz = TreeInfo.typeIn(tree.clazz); 5067 if (clazz.hasTag(IDENT)) { 5068 site = env.enclClass.sym.type; 5069 } else if (clazz.hasTag(SELECT)) { 5070 site = ((JCFieldAccess) clazz).selected.type; 5071 } else throw new AssertionError(""+tree); 5072 if (clazzOuter.hasTag(CLASS) && site != clazzOuter) { 5073 if (site.hasTag(CLASS)) 5074 site = types.asOuterSuper(site, clazzOuter.tsym); 5075 if (site == null) 5076 site = types.erasure(clazzOuter); 5077 clazzOuter = site; 5078 } 5079 } 5080 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym, 5081 clazztype.getMetadata()); 5082 } else { 5083 if (formals.length() != 0) { 5084 log.error(tree.pos(), 5085 Errors.WrongNumberTypeArgs(Integer.toString(formals.length()))); 5086 } else { 5087 log.error(tree.pos(), Errors.TypeDoesntTakeParams(clazztype.tsym)); 5088 } 5089 owntype = types.createErrorType(tree.type); 5090 } 5091 } 5092 result = check(tree, owntype, KindSelector.TYP, resultInfo); 5093 } 5094 5095 public void visitTypeUnion(JCTypeUnion tree) { 5096 ListBuffer<Type> multicatchTypes = new ListBuffer<>(); 5097 ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed 5098 for (JCExpression typeTree : tree.alternatives) { 5099 Type ctype = attribType(typeTree, env); 5100 ctype = chk.checkType(typeTree.pos(), 5101 chk.checkClassType(typeTree.pos(), ctype), 5102 syms.throwableType); 5103 if (!ctype.isErroneous()) { 5104 //check that alternatives of a union type are pairwise 5105 //unrelated w.r.t. subtyping 5106 if (chk.intersects(ctype, multicatchTypes.toList())) { 5107 for (Type t : multicatchTypes) { 5108 boolean sub = types.isSubtype(ctype, t); 5109 boolean sup = types.isSubtype(t, ctype); 5110 if (sub || sup) { 5111 //assume 'a' <: 'b' 5112 Type a = sub ? ctype : t; 5113 Type b = sub ? t : ctype; 5114 log.error(typeTree.pos(), Errors.MulticatchTypesMustBeDisjoint(a, b)); 5115 } 5116 } 5117 } 5118 multicatchTypes.append(ctype); 5119 if (all_multicatchTypes != null) 5120 all_multicatchTypes.append(ctype); 5121 } else { 5122 if (all_multicatchTypes == null) { 5123 all_multicatchTypes = new ListBuffer<>(); 5124 all_multicatchTypes.appendList(multicatchTypes); 5125 } 5126 all_multicatchTypes.append(ctype); 5127 } 5128 } 5129 Type t = check(tree, types.lub(multicatchTypes.toList()), 5130 KindSelector.TYP, resultInfo.dup(CheckMode.NO_TREE_UPDATE)); 5131 if (t.hasTag(CLASS)) { 5132 List<Type> alternatives = 5133 ((all_multicatchTypes == null) ? multicatchTypes : all_multicatchTypes).toList(); 5134 t = new UnionClassType((ClassType) t, alternatives); 5135 } 5136 tree.type = result = t; 5137 } 5138 5139 public void visitTypeIntersection(JCTypeIntersection tree) { 5140 attribTypes(tree.bounds, env); 5141 tree.type = result = checkIntersection(tree, tree.bounds); 5142 } 5143 5144 public void visitTypeParameter(JCTypeParameter tree) { 5145 TypeVar typeVar = (TypeVar) tree.type; 5146 5147 if (tree.annotations != null && tree.annotations.nonEmpty()) { 5148 annotate.annotateTypeParameterSecondStage(tree, tree.annotations); 5149 } 5150 5151 if (!typeVar.getUpperBound().isErroneous()) { 5152 //fixup type-parameter bound computed in 'attribTypeVariables' 5153 typeVar.setUpperBound(checkIntersection(tree, tree.bounds)); 5154 } 5155 } 5156 5157 Type checkIntersection(JCTree tree, List<JCExpression> bounds) { 5158 Set<Symbol> boundSet = new HashSet<>(); 5159 if (bounds.nonEmpty()) { 5160 // accept class or interface or typevar as first bound. 5161 bounds.head.type = checkBase(bounds.head.type, bounds.head, env, false, false, false); 5162 boundSet.add(types.erasure(bounds.head.type).tsym); 5163 if (bounds.head.type.isErroneous()) { 5164 return bounds.head.type; 5165 } 5166 else if (bounds.head.type.hasTag(TYPEVAR)) { 5167 // if first bound was a typevar, do not accept further bounds. 5168 if (bounds.tail.nonEmpty()) { 5169 log.error(bounds.tail.head.pos(), 5170 Errors.TypeVarMayNotBeFollowedByOtherBounds); 5171 return bounds.head.type; 5172 } 5173 } else { 5174 // if first bound was a class or interface, accept only interfaces 5175 // as further bounds. 5176 for (JCExpression bound : bounds.tail) { 5177 bound.type = checkBase(bound.type, bound, env, false, true, false); 5178 if (bound.type.isErroneous()) { 5179 bounds = List.of(bound); 5180 } 5181 else if (bound.type.hasTag(CLASS)) { 5182 chk.checkNotRepeated(bound.pos(), types.erasure(bound.type), boundSet); 5183 } 5184 } 5185 } 5186 } 5187 5188 if (bounds.length() == 0) { 5189 return syms.objectType; 5190 } else if (bounds.length() == 1) { 5191 return bounds.head.type; 5192 } else { 5193 Type owntype = types.makeIntersectionType(TreeInfo.types(bounds)); 5194 // ... the variable's bound is a class type flagged COMPOUND 5195 // (see comment for TypeVar.bound). 5196 // In this case, generate a class tree that represents the 5197 // bound class, ... 5198 JCExpression extending; 5199 List<JCExpression> implementing; 5200 if (!bounds.head.type.isInterface()) { 5201 extending = bounds.head; 5202 implementing = bounds.tail; 5203 } else { 5204 extending = null; 5205 implementing = bounds; 5206 } 5207 JCClassDecl cd = make.at(tree).ClassDef( 5208 make.Modifiers(PUBLIC | ABSTRACT), 5209 names.empty, List.nil(), 5210 extending, implementing, List.nil()); 5211 5212 ClassSymbol c = (ClassSymbol)owntype.tsym; 5213 Assert.check((c.flags() & COMPOUND) != 0); 5214 cd.sym = c; 5215 c.sourcefile = env.toplevel.sourcefile; 5216 5217 // ... and attribute the bound class 5218 c.flags_field |= UNATTRIBUTED; 5219 Env<AttrContext> cenv = enter.classEnv(cd, env); 5220 typeEnvs.put(c, cenv); 5221 attribClass(c); 5222 return owntype; 5223 } 5224 } 5225 5226 public void visitWildcard(JCWildcard tree) { 5227 //- System.err.println("visitWildcard("+tree+");");//DEBUG 5228 Type type = (tree.kind.kind == BoundKind.UNBOUND) 5229 ? syms.objectType 5230 : attribType(tree.inner, env); 5231 result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type), 5232 tree.kind.kind, 5233 syms.boundClass), 5234 KindSelector.TYP, resultInfo); 5235 } 5236 5237 public void visitAnnotation(JCAnnotation tree) { 5238 Assert.error("should be handled in annotate"); 5239 } 5240 5241 @Override 5242 public void visitModifiers(JCModifiers tree) { 5243 //error recovery only: 5244 Assert.check(resultInfo.pkind == KindSelector.ERR); 5245 5246 attribAnnotationTypes(tree.annotations, env); 5247 } 5248 5249 public void visitAnnotatedType(JCAnnotatedType tree) { 5250 attribAnnotationTypes(tree.annotations, env); 5251 Type underlyingType = attribType(tree.underlyingType, env); 5252 Type annotatedType = underlyingType.preannotatedType(); 5253 5254 if (!env.info.isNewClass) 5255 annotate.annotateTypeSecondStage(tree, tree.annotations, annotatedType); 5256 result = tree.type = annotatedType; 5257 } 5258 5259 public void visitErroneous(JCErroneous tree) { 5260 if (tree.errs != null) { 5261 Env<AttrContext> errEnv = env.dup(env.tree, env.info.dup()); 5262 errEnv.info.returnResult = unknownExprInfo; 5263 for (JCTree err : tree.errs) 5264 attribTree(err, errEnv, new ResultInfo(KindSelector.ERR, pt())); 5265 } 5266 result = tree.type = syms.errType; 5267 } 5268 5269 /** Default visitor method for all other trees. 5270 */ 5271 public void visitTree(JCTree tree) { 5272 throw new AssertionError(); 5273 } 5274 5275 /** 5276 * Attribute an env for either a top level tree or class or module declaration. 5277 */ 5278 public void attrib(Env<AttrContext> env) { 5279 switch (env.tree.getTag()) { 5280 case MODULEDEF: 5281 attribModule(env.tree.pos(), ((JCModuleDecl)env.tree).sym); 5282 break; 5283 case PACKAGEDEF: 5284 attribPackage(env.tree.pos(), ((JCPackageDecl) env.tree).packge); 5285 break; 5286 default: 5287 attribClass(env.tree.pos(), env.enclClass.sym); 5288 } 5289 } 5290 5291 public void attribPackage(DiagnosticPosition pos, PackageSymbol p) { 5292 try { 5293 annotate.flush(); 5294 attribPackage(p); 5295 } catch (CompletionFailure ex) { 5296 chk.completionError(pos, ex); 5297 } 5298 } 5299 5300 void attribPackage(PackageSymbol p) { 5301 attribWithLint(p, 5302 env -> chk.checkDeprecatedAnnotation(((JCPackageDecl) env.tree).pid.pos(), p)); 5303 } 5304 5305 public void attribModule(DiagnosticPosition pos, ModuleSymbol m) { 5306 try { 5307 annotate.flush(); 5308 attribModule(m); 5309 } catch (CompletionFailure ex) { 5310 chk.completionError(pos, ex); 5311 } 5312 } 5313 5314 void attribModule(ModuleSymbol m) { 5315 attribWithLint(m, env -> attribStat(env.tree, env)); 5316 } 5317 5318 private void attribWithLint(TypeSymbol sym, Consumer<Env<AttrContext>> attrib) { 5319 Env<AttrContext> env = typeEnvs.get(sym); 5320 5321 Env<AttrContext> lintEnv = env; 5322 while (lintEnv.info.lint == null) 5323 lintEnv = lintEnv.next; 5324 5325 Lint lint = lintEnv.info.lint.augment(sym); 5326 5327 Lint prevLint = chk.setLint(lint); 5328 JavaFileObject prev = log.useSource(env.toplevel.sourcefile); 5329 5330 try { 5331 deferredLintHandler.flush(env.tree.pos()); 5332 attrib.accept(env); 5333 } finally { 5334 log.useSource(prev); 5335 chk.setLint(prevLint); 5336 } 5337 } 5338 5339 /** Main method: attribute class definition associated with given class symbol. 5340 * reporting completion failures at the given position. 5341 * @param pos The source position at which completion errors are to be 5342 * reported. 5343 * @param c The class symbol whose definition will be attributed. 5344 */ 5345 public void attribClass(DiagnosticPosition pos, ClassSymbol c) { 5346 try { 5347 annotate.flush(); 5348 attribClass(c); 5349 } catch (CompletionFailure ex) { 5350 chk.completionError(pos, ex); 5351 } 5352 } 5353 5354 /** Attribute class definition associated with given class symbol. 5355 * @param c The class symbol whose definition will be attributed. 5356 */ 5357 void attribClass(ClassSymbol c) throws CompletionFailure { 5358 if (c.type.hasTag(ERROR)) return; 5359 5360 // Check for cycles in the inheritance graph, which can arise from 5361 // ill-formed class files. 5362 chk.checkNonCyclic(null, c.type); 5363 5364 Type st = types.supertype(c.type); 5365 if ((c.flags_field & Flags.COMPOUND) == 0 && 5366 (c.flags_field & Flags.SUPER_OWNER_ATTRIBUTED) == 0) { 5367 // First, attribute superclass. 5368 if (st.hasTag(CLASS)) 5369 attribClass((ClassSymbol)st.tsym); 5370 5371 // Next attribute owner, if it is a class. 5372 if (c.owner.kind == TYP && c.owner.type.hasTag(CLASS)) 5373 attribClass((ClassSymbol)c.owner); 5374 5375 c.flags_field |= Flags.SUPER_OWNER_ATTRIBUTED; 5376 } 5377 5378 // The previous operations might have attributed the current class 5379 // if there was a cycle. So we test first whether the class is still 5380 // UNATTRIBUTED. 5381 if ((c.flags_field & UNATTRIBUTED) != 0) { 5382 c.flags_field &= ~UNATTRIBUTED; 5383 5384 // Get environment current at the point of class definition. 5385 Env<AttrContext> env = typeEnvs.get(c); 5386 5387 // The info.lint field in the envs stored in typeEnvs is deliberately uninitialized, 5388 // because the annotations were not available at the time the env was created. Therefore, 5389 // we look up the environment chain for the first enclosing environment for which the 5390 // lint value is set. Typically, this is the parent env, but might be further if there 5391 // are any envs created as a result of TypeParameter nodes. 5392 Env<AttrContext> lintEnv = env; 5393 while (lintEnv.info.lint == null) 5394 lintEnv = lintEnv.next; 5395 5396 // Having found the enclosing lint value, we can initialize the lint value for this class 5397 env.info.lint = lintEnv.info.lint.augment(c); 5398 5399 Lint prevLint = chk.setLint(env.info.lint); 5400 JavaFileObject prev = log.useSource(c.sourcefile); 5401 ResultInfo prevReturnRes = env.info.returnResult; 5402 5403 try { 5404 if (c.isSealed() && 5405 !c.isEnum() && 5406 !c.isPermittedExplicit && 5407 c.permitted.isEmpty()) { 5408 log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.SealedClassMustHaveSubclasses); 5409 } 5410 5411 if (c.isSealed()) { 5412 Set<Symbol> permittedTypes = new HashSet<>(); 5413 boolean sealedInUnnamed = c.packge().modle == syms.unnamedModule || c.packge().modle == syms.noModule; 5414 for (Symbol subTypeSym : c.permitted) { 5415 boolean isTypeVar = false; 5416 if (subTypeSym.type.getTag() == TYPEVAR) { 5417 isTypeVar = true; //error recovery 5418 log.error(TreeInfo.diagnosticPositionFor(subTypeSym, env.tree), 5419 Errors.InvalidPermitsClause(Fragments.IsATypeVariable(subTypeSym.type))); 5420 } 5421 if (subTypeSym.isAnonymous() && !c.isEnum()) { 5422 log.error(TreeInfo.diagnosticPositionFor(subTypeSym, env.tree), Errors.LocalClassesCantExtendSealed(Fragments.Anonymous)); 5423 } 5424 if (permittedTypes.contains(subTypeSym)) { 5425 DiagnosticPosition pos = 5426 env.enclClass.permitting.stream() 5427 .filter(permittedExpr -> TreeInfo.diagnosticPositionFor(subTypeSym, permittedExpr, true) != null) 5428 .limit(2).collect(List.collector()).get(1); 5429 log.error(pos, Errors.InvalidPermitsClause(Fragments.IsDuplicated(subTypeSym.type))); 5430 } else { 5431 permittedTypes.add(subTypeSym); 5432 } 5433 if (sealedInUnnamed) { 5434 if (subTypeSym.packge() != c.packge()) { 5435 log.error(TreeInfo.diagnosticPositionFor(subTypeSym, env.tree), 5436 Errors.ClassInUnnamedModuleCantExtendSealedInDiffPackage(c) 5437 ); 5438 } 5439 } else if (subTypeSym.packge().modle != c.packge().modle) { 5440 log.error(TreeInfo.diagnosticPositionFor(subTypeSym, env.tree), 5441 Errors.ClassInModuleCantExtendSealedInDiffModule(c, c.packge().modle) 5442 ); 5443 } 5444 if (subTypeSym == c.type.tsym || types.isSuperType(subTypeSym.type, c.type)) { 5445 log.error(TreeInfo.diagnosticPositionFor(subTypeSym, ((JCClassDecl)env.tree).permitting), 5446 Errors.InvalidPermitsClause( 5447 subTypeSym == c.type.tsym ? 5448 Fragments.MustNotBeSameClass : 5449 Fragments.MustNotBeSupertype(subTypeSym.type) 5450 ) 5451 ); 5452 } else if (!isTypeVar) { 5453 boolean thisIsASuper = types.directSupertypes(subTypeSym.type) 5454 .stream() 5455 .anyMatch(d -> d.tsym == c); 5456 if (!thisIsASuper) { 5457 log.error(TreeInfo.diagnosticPositionFor(subTypeSym, env.tree), 5458 Errors.InvalidPermitsClause(Fragments.DoesntExtendSealed(subTypeSym.type))); 5459 } 5460 } 5461 } 5462 } 5463 5464 List<ClassSymbol> sealedSupers = types.directSupertypes(c.type) 5465 .stream() 5466 .filter(s -> s.tsym.isSealed()) 5467 .map(s -> (ClassSymbol) s.tsym) 5468 .collect(List.collector()); 5469 5470 if (sealedSupers.isEmpty()) { 5471 if ((c.flags_field & Flags.NON_SEALED) != 0) { 5472 boolean hasErrorSuper = false; 5473 5474 hasErrorSuper |= types.directSupertypes(c.type) 5475 .stream() 5476 .anyMatch(s -> s.tsym.kind == Kind.ERR); 5477 5478 ClassType ct = (ClassType) c.type; 5479 5480 hasErrorSuper |= !ct.isCompound() && ct.interfaces_field != ct.all_interfaces_field; 5481 5482 if (!hasErrorSuper) { 5483 log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.NonSealedWithNoSealedSupertype(c)); 5484 } 5485 } 5486 } else if ((c.flags_field & Flags.COMPOUND) == 0) { 5487 if (c.isDirectlyOrIndirectlyLocal() && !c.isEnum()) { 5488 log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.LocalClassesCantExtendSealed(c.isAnonymous() ? Fragments.Anonymous : Fragments.Local)); 5489 } 5490 5491 if (!c.type.isCompound()) { 5492 for (ClassSymbol supertypeSym : sealedSupers) { 5493 if (!supertypeSym.permitted.contains(c.type.tsym)) { 5494 log.error(TreeInfo.diagnosticPositionFor(c.type.tsym, env.tree), Errors.CantInheritFromSealed(supertypeSym)); 5495 } 5496 } 5497 if (!c.isNonSealed() && !c.isFinal() && !c.isSealed()) { 5498 log.error(TreeInfo.diagnosticPositionFor(c, env.tree), 5499 c.isInterface() ? 5500 Errors.NonSealedOrSealedExpected : 5501 Errors.NonSealedSealedOrFinalExpected); 5502 } 5503 } 5504 } 5505 5506 deferredLintHandler.flush(env.tree); 5507 env.info.returnResult = null; 5508 // java.lang.Enum may not be subclassed by a non-enum 5509 if (st.tsym == syms.enumSym && 5510 ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0)) 5511 log.error(env.tree.pos(), Errors.EnumNoSubclassing); 5512 5513 // Enums may not be extended by source-level classes 5514 if (st.tsym != null && 5515 ((st.tsym.flags_field & Flags.ENUM) != 0) && 5516 ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) { 5517 log.error(env.tree.pos(), Errors.EnumTypesNotExtensible); 5518 } 5519 5520 if (rs.isSerializable(c.type)) { 5521 env.info.isSerializable = true; 5522 } 5523 5524 if (c.isValueClass()) { 5525 Assert.check(env.tree.hasTag(CLASSDEF)); 5526 chk.checkConstraintsOfValueClass((JCClassDecl) env.tree, c); 5527 } 5528 5529 attribClassBody(env, c); 5530 5531 chk.checkDeprecatedAnnotation(env.tree.pos(), c); 5532 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c); 5533 chk.checkFunctionalInterface((JCClassDecl) env.tree, c); 5534 chk.checkLeaksNotAccessible(env, (JCClassDecl) env.tree); 5535 5536 if ((c.flags_field & Flags.UNNAMED_CLASS) != 0) { 5537 chk.checkHasMain(env.tree.pos(), c); 5538 } 5539 } finally { 5540 env.info.returnResult = prevReturnRes; 5541 log.useSource(prev); 5542 chk.setLint(prevLint); 5543 } 5544 5545 } 5546 } 5547 5548 public void visitImport(JCImport tree) { 5549 // nothing to do 5550 } 5551 5552 public void visitModuleDef(JCModuleDecl tree) { 5553 tree.sym.completeUsesProvides(); 5554 ModuleSymbol msym = tree.sym; 5555 Lint lint = env.outer.info.lint = env.outer.info.lint.augment(msym); 5556 Lint prevLint = chk.setLint(lint); 5557 chk.checkModuleName(tree); 5558 chk.checkDeprecatedAnnotation(tree, msym); 5559 5560 try { 5561 deferredLintHandler.flush(tree.pos()); 5562 } finally { 5563 chk.setLint(prevLint); 5564 } 5565 } 5566 5567 /** Finish the attribution of a class. */ 5568 private void attribClassBody(Env<AttrContext> env, ClassSymbol c) { 5569 JCClassDecl tree = (JCClassDecl)env.tree; 5570 Assert.check(c == tree.sym); 5571 5572 // Validate type parameters, supertype and interfaces. 5573 attribStats(tree.typarams, env); 5574 if (!c.isAnonymous()) { 5575 //already checked if anonymous 5576 chk.validate(tree.typarams, env); 5577 chk.validate(tree.extending, env); 5578 chk.validate(tree.implementing, env); 5579 } 5580 5581 c.markAbstractIfNeeded(types); 5582 5583 // If this is a non-abstract class, check that it has no abstract 5584 // methods or unimplemented methods of an implemented interface. 5585 if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) { 5586 chk.checkAllDefined(tree.pos(), c); 5587 } 5588 5589 if ((c.flags() & ANNOTATION) != 0) { 5590 if (tree.implementing.nonEmpty()) 5591 log.error(tree.implementing.head.pos(), 5592 Errors.CantExtendIntfAnnotation); 5593 if (tree.typarams.nonEmpty()) { 5594 log.error(tree.typarams.head.pos(), 5595 Errors.IntfAnnotationCantHaveTypeParams(c)); 5596 } 5597 5598 // If this annotation type has a @Repeatable, validate 5599 Attribute.Compound repeatable = c.getAnnotationTypeMetadata().getRepeatable(); 5600 // If this annotation type has a @Repeatable, validate 5601 if (repeatable != null) { 5602 // get diagnostic position for error reporting 5603 DiagnosticPosition cbPos = getDiagnosticPosition(tree, repeatable.type); 5604 Assert.checkNonNull(cbPos); 5605 5606 chk.validateRepeatable(c, repeatable, cbPos); 5607 } 5608 } else { 5609 // Check that all extended classes and interfaces 5610 // are compatible (i.e. no two define methods with same arguments 5611 // yet different return types). (JLS 8.4.8.3) 5612 chk.checkCompatibleSupertypes(tree.pos(), c.type); 5613 chk.checkDefaultMethodClashes(tree.pos(), c.type); 5614 chk.checkPotentiallyAmbiguousOverloads(tree, c.type); 5615 } 5616 5617 // Check that class does not import the same parameterized interface 5618 // with two different argument lists. 5619 chk.checkClassBounds(tree.pos(), c.type); 5620 5621 tree.type = c.type; 5622 5623 for (List<JCTypeParameter> l = tree.typarams; 5624 l.nonEmpty(); l = l.tail) { 5625 Assert.checkNonNull(env.info.scope.findFirst(l.head.name)); 5626 } 5627 5628 // Check that a generic class doesn't extend Throwable 5629 if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType)) 5630 log.error(tree.extending.pos(), Errors.GenericThrowable); 5631 5632 // Check that all methods which implement some 5633 // method conform to the method they implement. 5634 chk.checkImplementations(tree); 5635 5636 //check that a resource implementing AutoCloseable cannot throw InterruptedException 5637 checkAutoCloseable(tree.pos(), env, c.type); 5638 5639 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) { 5640 // Attribute declaration 5641 attribStat(l.head, env); 5642 // Check that declarations in inner classes are not static (JLS 8.1.2) 5643 // Make an exception for static constants. 5644 if (!allowRecords && 5645 c.owner.kind != PCK && 5646 ((c.flags() & STATIC) == 0 || c.name == names.empty) && 5647 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) { 5648 VarSymbol sym = null; 5649 if (l.head.hasTag(VARDEF)) sym = ((JCVariableDecl) l.head).sym; 5650 if (sym == null || 5651 sym.kind != VAR || 5652 sym.getConstValue() == null) 5653 log.error(l.head.pos(), Errors.IclsCantHaveStaticDecl(c)); 5654 } 5655 } 5656 5657 // Check for proper placement of super()/this() calls. 5658 chk.checkSuperInitCalls(tree); 5659 5660 // Check for cycles among non-initial constructors. 5661 chk.checkCyclicConstructors(tree); 5662 5663 // Check for cycles among annotation elements. 5664 chk.checkNonCyclicElements(tree); 5665 5666 // Check for proper use of serialVersionUID and other 5667 // serialization-related fields and methods 5668 if (env.info.lint.isEnabled(LintCategory.SERIAL) 5669 && rs.isSerializable(c.type) 5670 && !c.isAnonymous()) { 5671 chk.checkSerialStructure(tree, c); 5672 } 5673 // Correctly organize the positions of the type annotations 5674 typeAnnotations.organizeTypeAnnotationsBodies(tree); 5675 5676 // Check type annotations applicability rules 5677 validateTypeAnnotations(tree, false); 5678 } 5679 // where 5680 /** get a diagnostic position for an attribute of Type t, or null if attribute missing */ 5681 private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) { 5682 for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) { 5683 if (types.isSameType(al.head.annotationType.type, t)) 5684 return al.head.pos(); 5685 } 5686 5687 return null; 5688 } 5689 5690 private Type capture(Type type) { 5691 return types.capture(type); 5692 } 5693 5694 private void setSyntheticVariableType(JCVariableDecl tree, Type type) { 5695 if (type.isErroneous()) { 5696 tree.vartype = make.at(Position.NOPOS).Erroneous(); 5697 } else { 5698 tree.vartype = make.at(Position.NOPOS).Type(type); 5699 } 5700 } 5701 5702 public void validateTypeAnnotations(JCTree tree, boolean sigOnly) { 5703 tree.accept(new TypeAnnotationsValidator(sigOnly)); 5704 } 5705 //where 5706 private final class TypeAnnotationsValidator extends TreeScanner { 5707 5708 private final boolean sigOnly; 5709 public TypeAnnotationsValidator(boolean sigOnly) { 5710 this.sigOnly = sigOnly; 5711 } 5712 5713 public void visitAnnotation(JCAnnotation tree) { 5714 chk.validateTypeAnnotation(tree, null, false); 5715 super.visitAnnotation(tree); 5716 } 5717 public void visitAnnotatedType(JCAnnotatedType tree) { 5718 if (!tree.underlyingType.type.isErroneous()) { 5719 super.visitAnnotatedType(tree); 5720 } 5721 } 5722 public void visitTypeParameter(JCTypeParameter tree) { 5723 chk.validateTypeAnnotations(tree.annotations, tree.type.tsym, true); 5724 scan(tree.bounds); 5725 // Don't call super. 5726 // This is needed because above we call validateTypeAnnotation with 5727 // false, which would forbid annotations on type parameters. 5728 // super.visitTypeParameter(tree); 5729 } 5730 public void visitMethodDef(JCMethodDecl tree) { 5731 if (tree.recvparam != null && 5732 !tree.recvparam.vartype.type.isErroneous()) { 5733 checkForDeclarationAnnotations(tree.recvparam.mods.annotations, tree.recvparam.sym); 5734 } 5735 if (tree.restype != null && tree.restype.type != null) { 5736 validateAnnotatedType(tree.restype, tree.restype.type); 5737 } 5738 if (sigOnly) { 5739 scan(tree.mods); 5740 scan(tree.restype); 5741 scan(tree.typarams); 5742 scan(tree.recvparam); 5743 scan(tree.params); 5744 scan(tree.thrown); 5745 } else { 5746 scan(tree.defaultValue); 5747 scan(tree.body); 5748 } 5749 } 5750 public void visitVarDef(final JCVariableDecl tree) { 5751 //System.err.println("validateTypeAnnotations.visitVarDef " + tree); 5752 if (tree.sym != null && tree.sym.type != null && !tree.isImplicitlyTyped()) 5753 validateAnnotatedType(tree.vartype, tree.sym.type); 5754 scan(tree.mods); 5755 scan(tree.vartype); 5756 if (!sigOnly) { 5757 scan(tree.init); 5758 } 5759 } 5760 public void visitTypeCast(JCTypeCast tree) { 5761 if (tree.clazz != null && tree.clazz.type != null) 5762 validateAnnotatedType(tree.clazz, tree.clazz.type); 5763 super.visitTypeCast(tree); 5764 } 5765 public void visitTypeTest(JCInstanceOf tree) { 5766 if (tree.pattern != null && !(tree.pattern instanceof JCPattern) && tree.pattern.type != null) 5767 validateAnnotatedType(tree.pattern, tree.pattern.type); 5768 super.visitTypeTest(tree); 5769 } 5770 public void visitNewClass(JCNewClass tree) { 5771 if (tree.clazz != null && tree.clazz.type != null) { 5772 if (tree.clazz.hasTag(ANNOTATED_TYPE)) { 5773 checkForDeclarationAnnotations(((JCAnnotatedType) tree.clazz).annotations, 5774 tree.clazz.type.tsym); 5775 } 5776 if (tree.def != null) { 5777 checkForDeclarationAnnotations(tree.def.mods.annotations, tree.clazz.type.tsym); 5778 } 5779 5780 validateAnnotatedType(tree.clazz, tree.clazz.type); 5781 } 5782 super.visitNewClass(tree); 5783 } 5784 public void visitNewArray(JCNewArray tree) { 5785 if (tree.elemtype != null && tree.elemtype.type != null) { 5786 if (tree.elemtype.hasTag(ANNOTATED_TYPE)) { 5787 checkForDeclarationAnnotations(((JCAnnotatedType) tree.elemtype).annotations, 5788 tree.elemtype.type.tsym); 5789 } 5790 validateAnnotatedType(tree.elemtype, tree.elemtype.type); 5791 } 5792 super.visitNewArray(tree); 5793 } 5794 public void visitClassDef(JCClassDecl tree) { 5795 //System.err.println("validateTypeAnnotations.visitClassDef " + tree); 5796 if (sigOnly) { 5797 scan(tree.mods); 5798 scan(tree.typarams); 5799 scan(tree.extending); 5800 scan(tree.implementing); 5801 } 5802 for (JCTree member : tree.defs) { 5803 if (member.hasTag(Tag.CLASSDEF)) { 5804 continue; 5805 } 5806 scan(member); 5807 } 5808 } 5809 public void visitBlock(JCBlock tree) { 5810 if (!sigOnly) { 5811 scan(tree.stats); 5812 } 5813 } 5814 5815 /* I would want to model this after 5816 * com.sun.tools.javac.comp.Check.Validator.visitSelectInternal(JCFieldAccess) 5817 * and override visitSelect and visitTypeApply. 5818 * However, we only set the annotated type in the top-level type 5819 * of the symbol. 5820 * Therefore, we need to override each individual location where a type 5821 * can occur. 5822 */ 5823 private void validateAnnotatedType(final JCTree errtree, final Type type) { 5824 //System.err.println("Attr.validateAnnotatedType: " + errtree + " type: " + type); 5825 5826 if (type.isPrimitiveOrVoid()) { 5827 return; 5828 } 5829 5830 JCTree enclTr = errtree; 5831 Type enclTy = type; 5832 5833 boolean repeat = true; 5834 while (repeat) { 5835 if (enclTr.hasTag(TYPEAPPLY)) { 5836 List<Type> tyargs = enclTy.getTypeArguments(); 5837 List<JCExpression> trargs = ((JCTypeApply)enclTr).getTypeArguments(); 5838 if (trargs.length() > 0) { 5839 // Nothing to do for diamonds 5840 if (tyargs.length() == trargs.length()) { 5841 for (int i = 0; i < tyargs.length(); ++i) { 5842 validateAnnotatedType(trargs.get(i), tyargs.get(i)); 5843 } 5844 } 5845 // If the lengths don't match, it's either a diamond 5846 // or some nested type that redundantly provides 5847 // type arguments in the tree. 5848 } 5849 5850 // Look at the clazz part of a generic type 5851 enclTr = ((JCTree.JCTypeApply)enclTr).clazz; 5852 } 5853 5854 if (enclTr.hasTag(SELECT)) { 5855 enclTr = ((JCTree.JCFieldAccess)enclTr).getExpression(); 5856 if (enclTy != null && 5857 !enclTy.hasTag(NONE)) { 5858 enclTy = enclTy.getEnclosingType(); 5859 } 5860 } else if (enclTr.hasTag(ANNOTATED_TYPE)) { 5861 JCAnnotatedType at = (JCTree.JCAnnotatedType) enclTr; 5862 if (enclTy == null || enclTy.hasTag(NONE)) { 5863 if (at.getAnnotations().size() == 1) { 5864 log.error(at.underlyingType.pos(), Errors.CantTypeAnnotateScoping1(at.getAnnotations().head.attribute)); 5865 } else { 5866 ListBuffer<Attribute.Compound> comps = new ListBuffer<>(); 5867 for (JCAnnotation an : at.getAnnotations()) { 5868 comps.add(an.attribute); 5869 } 5870 log.error(at.underlyingType.pos(), Errors.CantTypeAnnotateScoping(comps.toList())); 5871 } 5872 repeat = false; 5873 } 5874 enclTr = at.underlyingType; 5875 // enclTy doesn't need to be changed 5876 } else if (enclTr.hasTag(IDENT)) { 5877 repeat = false; 5878 } else if (enclTr.hasTag(JCTree.Tag.WILDCARD)) { 5879 JCWildcard wc = (JCWildcard) enclTr; 5880 if (wc.getKind() == JCTree.Kind.EXTENDS_WILDCARD || 5881 wc.getKind() == JCTree.Kind.SUPER_WILDCARD) { 5882 validateAnnotatedType(wc.getBound(), wc.getBound().type); 5883 } else { 5884 // Nothing to do for UNBOUND 5885 } 5886 repeat = false; 5887 } else if (enclTr.hasTag(TYPEARRAY)) { 5888 JCArrayTypeTree art = (JCArrayTypeTree) enclTr; 5889 validateAnnotatedType(art.getType(), art.elemtype.type); 5890 repeat = false; 5891 } else if (enclTr.hasTag(TYPEUNION)) { 5892 JCTypeUnion ut = (JCTypeUnion) enclTr; 5893 for (JCTree t : ut.getTypeAlternatives()) { 5894 validateAnnotatedType(t, t.type); 5895 } 5896 repeat = false; 5897 } else if (enclTr.hasTag(TYPEINTERSECTION)) { 5898 JCTypeIntersection it = (JCTypeIntersection) enclTr; 5899 for (JCTree t : it.getBounds()) { 5900 validateAnnotatedType(t, t.type); 5901 } 5902 repeat = false; 5903 } else if (enclTr.getKind() == JCTree.Kind.PRIMITIVE_TYPE || 5904 enclTr.getKind() == JCTree.Kind.ERRONEOUS) { 5905 repeat = false; 5906 } else { 5907 Assert.error("Unexpected tree: " + enclTr + " with kind: " + enclTr.getKind() + 5908 " within: "+ errtree + " with kind: " + errtree.getKind()); 5909 } 5910 } 5911 } 5912 5913 private void checkForDeclarationAnnotations(List<? extends JCAnnotation> annotations, 5914 Symbol sym) { 5915 // Ensure that no declaration annotations are present. 5916 // Note that a tree type might be an AnnotatedType with 5917 // empty annotations, if only declaration annotations were given. 5918 // This method will raise an error for such a type. 5919 for (JCAnnotation ai : annotations) { 5920 if (!ai.type.isErroneous() && 5921 typeAnnotations.annotationTargetType(ai, ai.attribute, sym) == TypeAnnotations.AnnotationType.DECLARATION) { 5922 log.error(ai.pos(), Errors.AnnotationTypeNotApplicableToType(ai.type)); 5923 } 5924 } 5925 } 5926 } 5927 5928 // <editor-fold desc="post-attribution visitor"> 5929 5930 /** 5931 * Handle missing types/symbols in an AST. This routine is useful when 5932 * the compiler has encountered some errors (which might have ended up 5933 * terminating attribution abruptly); if the compiler is used in fail-over 5934 * mode (e.g. by an IDE) and the AST contains semantic errors, this routine 5935 * prevents NPE to be propagated during subsequent compilation steps. 5936 */ 5937 public void postAttr(JCTree tree) { 5938 new PostAttrAnalyzer().scan(tree); 5939 } 5940 5941 class PostAttrAnalyzer extends TreeScanner { 5942 5943 private void initTypeIfNeeded(JCTree that) { 5944 if (that.type == null) { 5945 if (that.hasTag(METHODDEF)) { 5946 that.type = dummyMethodType((JCMethodDecl)that); 5947 } else { 5948 that.type = syms.unknownType; 5949 } 5950 } 5951 } 5952 5953 /* Construct a dummy method type. If we have a method declaration, 5954 * and the declared return type is void, then use that return type 5955 * instead of UNKNOWN to avoid spurious error messages in lambda 5956 * bodies (see:JDK-8041704). 5957 */ 5958 private Type dummyMethodType(JCMethodDecl md) { 5959 Type restype = syms.unknownType; 5960 if (md != null && md.restype != null && md.restype.hasTag(TYPEIDENT)) { 5961 JCPrimitiveTypeTree prim = (JCPrimitiveTypeTree)md.restype; 5962 if (prim.typetag == VOID) 5963 restype = syms.voidType; 5964 } 5965 return new MethodType(List.nil(), restype, 5966 List.nil(), syms.methodClass); 5967 } 5968 private Type dummyMethodType() { 5969 return dummyMethodType(null); 5970 } 5971 5972 @Override 5973 public void scan(JCTree tree) { 5974 if (tree == null) return; 5975 if (tree instanceof JCExpression) { 5976 initTypeIfNeeded(tree); 5977 } 5978 super.scan(tree); 5979 } 5980 5981 @Override 5982 public void visitIdent(JCIdent that) { 5983 if (that.sym == null) { 5984 that.sym = syms.unknownSymbol; 5985 } 5986 } 5987 5988 @Override 5989 public void visitSelect(JCFieldAccess that) { 5990 if (that.sym == null) { 5991 that.sym = syms.unknownSymbol; 5992 } 5993 super.visitSelect(that); 5994 } 5995 5996 @Override 5997 public void visitClassDef(JCClassDecl that) { 5998 initTypeIfNeeded(that); 5999 if (that.sym == null) { 6000 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol); 6001 } 6002 super.visitClassDef(that); 6003 } 6004 6005 @Override 6006 public void visitMethodDef(JCMethodDecl that) { 6007 initTypeIfNeeded(that); 6008 if (that.sym == null) { 6009 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol); 6010 } 6011 super.visitMethodDef(that); 6012 } 6013 6014 @Override 6015 public void visitVarDef(JCVariableDecl that) { 6016 initTypeIfNeeded(that); 6017 if (that.sym == null) { 6018 that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol); 6019 that.sym.adr = 0; 6020 } 6021 if (that.vartype == null) { 6022 that.vartype = make.at(Position.NOPOS).Erroneous(); 6023 } 6024 super.visitVarDef(that); 6025 } 6026 6027 @Override 6028 public void visitBindingPattern(JCBindingPattern that) { 6029 initTypeIfNeeded(that); 6030 initTypeIfNeeded(that.var); 6031 if (that.var.sym == null) { 6032 that.var.sym = new BindingSymbol(0, that.var.name, that.var.type, syms.noSymbol); 6033 that.var.sym.adr = 0; 6034 } 6035 super.visitBindingPattern(that); 6036 } 6037 6038 @Override 6039 public void visitNewClass(JCNewClass that) { 6040 if (that.constructor == null) { 6041 that.constructor = new MethodSymbol(0, names.init, 6042 dummyMethodType(), syms.noSymbol); 6043 } 6044 if (that.constructorType == null) { 6045 that.constructorType = syms.unknownType; 6046 } 6047 super.visitNewClass(that); 6048 } 6049 6050 @Override 6051 public void visitAssignop(JCAssignOp that) { 6052 if (that.operator == null) { 6053 that.operator = new OperatorSymbol(names.empty, dummyMethodType(), 6054 -1, syms.noSymbol); 6055 } 6056 super.visitAssignop(that); 6057 } 6058 6059 @Override 6060 public void visitBinary(JCBinary that) { 6061 if (that.operator == null) { 6062 that.operator = new OperatorSymbol(names.empty, dummyMethodType(), 6063 -1, syms.noSymbol); 6064 } 6065 super.visitBinary(that); 6066 } 6067 6068 @Override 6069 public void visitUnary(JCUnary that) { 6070 if (that.operator == null) { 6071 that.operator = new OperatorSymbol(names.empty, dummyMethodType(), 6072 -1, syms.noSymbol); 6073 } 6074 super.visitUnary(that); 6075 } 6076 6077 @Override 6078 public void visitReference(JCMemberReference that) { 6079 super.visitReference(that); 6080 if (that.sym == null) { 6081 that.sym = new MethodSymbol(0, names.empty, dummyMethodType(), 6082 syms.noSymbol); 6083 } 6084 } 6085 } 6086 // </editor-fold> 6087 6088 public void setPackageSymbols(JCExpression pid, Symbol pkg) { 6089 new TreeScanner() { 6090 Symbol packge = pkg; 6091 @Override 6092 public void visitIdent(JCIdent that) { 6093 that.sym = packge; 6094 } 6095 6096 @Override 6097 public void visitSelect(JCFieldAccess that) { 6098 that.sym = packge; 6099 packge = packge.owner; 6100 super.visitSelect(that); 6101 } 6102 }.scan(pid); 6103 } 6104 6105 }