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