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