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