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