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