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