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