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