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