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