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