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