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