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