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