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