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