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