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