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