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