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