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