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