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