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