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