Attr.java revision 3397:5c3dfebefa4a
1132718Skan/* 2189824Sdas * Copyright (c) 1999, 2016, Oracle and/or its affiliates. All rights reserved. 3189824Sdas * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4132718Skan * 5132718Skan * This code is free software; you can redistribute it and/or modify it 6132718Skan * under the terms of the GNU General Public License version 2 only, as 7132718Skan * published by the Free Software Foundation. Oracle designates this 8132718Skan * particular file as subject to the "Classpath" exception as provided 9132718Skan * by Oracle in the LICENSE file that accompanied this code. 10132718Skan * 11132718Skan * This code is distributed in the hope that it will be useful, but WITHOUT 12132718Skan * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13132718Skan * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14132718Skan * version 2 for more details (a copy is included in the LICENSE file that 15132718Skan * accompanied this code). 16132718Skan * 17132718Skan * You should have received a copy of the GNU General Public License version 18132718Skan * 2 along with this work; if not, write to the Free Software Foundation, 19169689Skan * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20169689Skan * 21132718Skan * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22132718Skan * or visit www.oracle.com if you need additional information or have any 23132718Skan * questions. 24132718Skan */ 25132718Skan 26132718Skanpackage com.sun.tools.javac.comp; 27169689Skan 28132718Skanimport java.util.*; 29132718Skan 30132718Skanimport javax.lang.model.element.ElementKind; 31132718Skanimport javax.tools.JavaFileObject; 32132718Skan 33132718Skanimport com.sun.source.tree.IdentifierTree; 34132718Skanimport com.sun.source.tree.MemberReferenceTree.ReferenceMode; 35132718Skanimport com.sun.source.tree.MemberSelectTree; 36169689Skanimport com.sun.source.tree.TreeVisitor; 37132718Skanimport com.sun.source.util.SimpleTreeVisitor; 38132718Skanimport com.sun.tools.javac.code.*; 39132718Skanimport com.sun.tools.javac.code.Directive.RequiresFlag; 40132718Skanimport com.sun.tools.javac.code.Lint.LintCategory; 41132718Skanimport com.sun.tools.javac.code.Scope.WriteableScope; 42132718Skanimport com.sun.tools.javac.code.Symbol.*; 43132718Skanimport com.sun.tools.javac.code.Type.*; 44132718Skanimport com.sun.tools.javac.code.TypeMetadata.Annotations; 45132718Skanimport com.sun.tools.javac.code.Types.FunctionDescriptorLookupError; 46132718Skanimport com.sun.tools.javac.comp.ArgumentAttr.LocalCacheContext; 47132718Skanimport com.sun.tools.javac.comp.Check.CheckContext; 48132718Skanimport com.sun.tools.javac.comp.DeferredAttr.AttrMode; 49132718Skanimport com.sun.tools.javac.comp.Infer.FreeTypeListener; 50132718Skanimport com.sun.tools.javac.jvm.*; 51132718Skanimport static com.sun.tools.javac.resources.CompilerProperties.Fragments.Diamond; 52132718Skanimport static com.sun.tools.javac.resources.CompilerProperties.Fragments.DiamondInvalidArg; 53132718Skanimport static com.sun.tools.javac.resources.CompilerProperties.Fragments.DiamondInvalidArgs; 54132718Skanimport com.sun.tools.javac.resources.CompilerProperties.Errors; 55132718Skanimport com.sun.tools.javac.resources.CompilerProperties.Fragments; 56132718Skanimport com.sun.tools.javac.tree.*; 57169689Skanimport com.sun.tools.javac.tree.JCTree.*; 58132718Skanimport com.sun.tools.javac.tree.JCTree.JCPolyExpression.*; 59169689Skanimport com.sun.tools.javac.util.*; 60132718Skanimport com.sun.tools.javac.util.DefinedBy.Api; 61132718Skanimport com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; 62169689Skanimport com.sun.tools.javac.util.JCDiagnostic.Fragment; 63169689Skanimport com.sun.tools.javac.util.List; 64169689Skan 65132718Skanimport static com.sun.tools.javac.code.Flags.*; 66132718Skanimport static com.sun.tools.javac.code.Flags.ANNOTATION; 67132718Skanimport static com.sun.tools.javac.code.Flags.BLOCK; 68132718Skanimport static com.sun.tools.javac.code.Kinds.*; 69132718Skanimport static com.sun.tools.javac.code.Kinds.Kind.*; 70132718Skanimport static com.sun.tools.javac.code.TypeTag.*; 71132718Skanimport static com.sun.tools.javac.code.TypeTag.WILDCARD; 72132718Skanimport static com.sun.tools.javac.tree.JCTree.Tag.*; 73132718Skan 74132718Skan/** This is the main context-dependent analysis phase in GJC. It 75169689Skan * encompasses name resolution, type checking and constant folding as 76169689Skan * subtasks. Some subtasks involve auxiliary classes. 77132718Skan * @see Check 78169689Skan * @see Resolve 79169689Skan * @see ConstFold 80169689Skan * @see Infer 81169689Skan * 82132718Skan * <p><b>This is NOT part of any supported API. 83132718Skan * If you write code that depends on this, you do so at your own risk. 84132718Skan * This code and its internal interfaces are subject to change or 85132718Skan * deletion without notice.</b> 86132718Skan */ 87132718Skanpublic class Attr extends JCTree.Visitor { 88132718Skan protected static final Context.Key<Attr> attrKey = new Context.Key<>(); 89132718Skan 90132718Skan final Names names; 91132718Skan final Log log; 92132718Skan final Symtab syms; 93132718Skan final Resolve rs; 94132718Skan final Operators operators; 95132718Skan final Infer infer; 96132718Skan final Analyzer analyzer; 97132718Skan final DeferredAttr deferredAttr; 98132718Skan final Check chk; 99132718Skan final Flow flow; 100169689Skan final MemberEnter memberEnter; 101132718Skan final TypeEnter typeEnter; 102132718Skan final TreeMaker make; 103132718Skan final ConstFold cfolder; 104132718Skan final Enter enter; 105132718Skan final Target target; 106132718Skan final Types types; 107132718Skan final JCDiagnostic.Factory diags; 108132718Skan final TypeAnnotations typeAnnotations; 109132718Skan final DeferredLintHandler deferredLintHandler; 110132718Skan final TypeEnvs typeEnvs; 111132718Skan final Dependencies dependencies; 112132718Skan final Annotate annotate; 113132718Skan final ArgumentAttr argumentAttr; 114132718Skan 115132718Skan public static Attr instance(Context context) { 116132718Skan Attr instance = context.get(attrKey); 117132718Skan if (instance == null) 118132718Skan instance = new Attr(context); 119132718Skan return instance; 120132718Skan } 121132718Skan 122132718Skan protected Attr(Context context) { 123132718Skan context.put(attrKey, this); 124132718Skan 125132718Skan names = Names.instance(context); 126132718Skan log = Log.instance(context); 127132718Skan syms = Symtab.instance(context); 128132718Skan rs = Resolve.instance(context); 129132718Skan operators = Operators.instance(context); 130132718Skan chk = Check.instance(context); 131132718Skan flow = Flow.instance(context); 132132718Skan memberEnter = MemberEnter.instance(context); 133132718Skan typeEnter = TypeEnter.instance(context); 134132718Skan make = TreeMaker.instance(context); 135132718Skan enter = Enter.instance(context); 136132718Skan infer = Infer.instance(context); 137132718Skan analyzer = Analyzer.instance(context); 138132718Skan deferredAttr = DeferredAttr.instance(context); 139132718Skan cfolder = ConstFold.instance(context); 140132718Skan target = Target.instance(context); 141132718Skan types = Types.instance(context); 142132718Skan diags = JCDiagnostic.Factory.instance(context); 143132718Skan annotate = Annotate.instance(context); 144132718Skan typeAnnotations = TypeAnnotations.instance(context); 145132718Skan deferredLintHandler = DeferredLintHandler.instance(context); 146132718Skan typeEnvs = TypeEnvs.instance(context); 147132718Skan dependencies = Dependencies.instance(context); 148132718Skan argumentAttr = ArgumentAttr.instance(context); 149132718Skan 150132718Skan Options options = Options.instance(context); 151132718Skan 152132718Skan Source source = Source.instance(context); 153132718Skan allowStringsInSwitch = source.allowStringsInSwitch(); 154132718Skan allowPoly = source.allowPoly(); 155132718Skan allowTypeAnnos = source.allowTypeAnnotations(); 156132718Skan allowLambda = source.allowLambda(); 157132718Skan allowDefaultMethods = source.allowDefaultMethods(); 158132718Skan allowStaticInterfaceMethods = source.allowStaticInterfaceMethods(); 159132718Skan sourceName = source.name; 160132718Skan useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning"); 161132718Skan 162132718Skan statInfo = new ResultInfo(KindSelector.NIL, Type.noType); 163132718Skan varAssignmentInfo = new ResultInfo(KindSelector.ASG, Type.noType); 164132718Skan unknownExprInfo = new ResultInfo(KindSelector.VAL, Type.noType); 165132718Skan methodAttrInfo = new MethodAttrInfo(); 166132718Skan unknownTypeInfo = new ResultInfo(KindSelector.TYP, Type.noType); 167132718Skan unknownTypeExprInfo = new ResultInfo(KindSelector.VAL_TYP, Type.noType); 168132718Skan recoveryInfo = new RecoveryInfo(deferredAttr.emptyDeferredAttrContext); 169132718Skan } 170132718Skan 171132718Skan /** Switch: support target-typing inference 172132718Skan */ 173132718Skan boolean allowPoly; 174132718Skan 175132718Skan /** Switch: support type annotations. 176132718Skan */ 177132718Skan boolean allowTypeAnnos; 178132718Skan 179132718Skan /** Switch: support lambda expressions ? 180132718Skan */ 181132718Skan boolean allowLambda; 182132718Skan 183132718Skan /** Switch: support default methods ? 184132718Skan */ 185132718Skan boolean allowDefaultMethods; 186132718Skan 187132718Skan /** Switch: static interface methods enabled? 188132718Skan */ 189132718Skan boolean allowStaticInterfaceMethods; 190132718Skan 191132718Skan /** 192132718Skan * Switch: warn about use of variable before declaration? 193132718Skan * RFE: 6425594 194132718Skan */ 195132718Skan boolean useBeforeDeclarationWarning; 196132718Skan 197132718Skan /** 198132718Skan * Switch: allow strings in switch? 199132718Skan */ 200132718Skan boolean allowStringsInSwitch; 201132718Skan 202132718Skan /** 203132718Skan * Switch: name of source level; used for error reporting. 204132718Skan */ 205132718Skan String sourceName; 206132718Skan 207132718Skan /** Check kind and type of given tree against protokind and prototype. 208132718Skan * If check succeeds, store type in tree and return it. 209132718Skan * If check fails, store errType in tree and return it. 210132718Skan * No checks are performed if the prototype is a method type. 211132718Skan * It is not necessary in this case since we know that kind and type 212132718Skan * are correct. 213132718Skan * 214132718Skan * @param tree The tree whose kind and type is checked 215132718Skan * @param found The computed type of the tree 216132718Skan * @param ownkind The computed kind of the tree 217132718Skan * @param resultInfo The expected result of the tree 218132718Skan */ 219132718Skan Type check(final JCTree tree, 220169689Skan final Type found, 221132718Skan final KindSelector ownkind, 222132718Skan final ResultInfo resultInfo) { 223132718Skan InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext(); 224132718Skan Type owntype; 225132718Skan boolean shouldCheck = !found.hasTag(ERROR) && 226169689Skan !resultInfo.pt.hasTag(METHOD) && 227132718Skan !resultInfo.pt.hasTag(FORALL); 228132718Skan if (shouldCheck && !ownkind.subset(resultInfo.pkind)) { 229132718Skan log.error(tree.pos(), "unexpected.type", 230132718Skan resultInfo.pkind.kindNames(), 231169689Skan ownkind.kindNames()); 232169689Skan owntype = types.createErrorType(found); 233169689Skan } else if (allowPoly && inferenceContext.free(found)) { 234169689Skan //delay the check if there are inference variables in the found type 235169689Skan //this means we are dealing with a partially inferred poly expression 236169689Skan owntype = shouldCheck ? resultInfo.pt : found; 237169689Skan if (resultInfo.checkMode.installPostInferenceHook()) { 238132718Skan inferenceContext.addFreeTypeListener(List.of(found), 239132718Skan instantiatedContext -> { 240132718Skan ResultInfo pendingResult = 241132718Skan resultInfo.dup(inferenceContext.asInstType(resultInfo.pt)); 242132718Skan check(tree, inferenceContext.asInstType(found), ownkind, pendingResult); 243132718Skan }); 244132718Skan } 245132718Skan } else { 246132718Skan owntype = shouldCheck ? 247169689Skan resultInfo.check(tree, found) : 248132718Skan found; 249132718Skan } 250132718Skan if (resultInfo.checkMode.updateTreeType()) { 251132718Skan tree.type = owntype; 252132718Skan } 253132718Skan return owntype; 254132718Skan } 255169689Skan 256169689Skan /** Is given blank final variable assignable, i.e. in a scope where it 257169689Skan * may be assigned to even though it is final? 258132718Skan * @param v The blank final variable. 259132718Skan * @param env The current environment. 260132718Skan */ 261132718Skan boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) { 262132718Skan Symbol owner = env.info.scope.owner; 263132718Skan // owner refers to the innermost variable, method or 264132718Skan // initializer block declaration at this point. 265132718Skan return 266132718Skan v.owner == owner 267132718Skan || 268132718Skan ((owner.name == names.init || // i.e. we are in a constructor 269132718Skan owner.kind == VAR || // i.e. we are in a variable initializer 270132718Skan (owner.flags() & BLOCK) != 0) // i.e. we are in an initializer block 271169689Skan && 272169689Skan v.owner == owner.owner 273169689Skan && 274169689Skan ((v.flags() & STATIC) != 0) == Resolve.isStatic(env)); 275169689Skan } 276169689Skan 277169689Skan /** Check that variable can be assigned to. 278169689Skan * @param pos The current source code position. 279169689Skan * @param v The assigned variable 280169689Skan * @param base If the variable is referred to in a Select, the part 281169689Skan * to the left of the `.', null otherwise. 282169689Skan * @param env The current environment. 283169689Skan */ 284169689Skan void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) { 285169689Skan if (v.name == names._this) { 286169689Skan log.error(pos, Errors.CantAssignValToThis); 287169689Skan } else if ((v.flags() & FINAL) != 0 && 288169689Skan ((v.flags() & HASINIT) != 0 289169689Skan || 290169689Skan !((base == null || 291169689Skan (base.hasTag(IDENT) && TreeInfo.name(base) == names._this)) && 292169689Skan isAssignableAsBlankFinal(v, env)))) { 293169689Skan if (v.isResourceVariable()) { //TWR resource 294169689Skan log.error(pos, "try.resource.may.not.be.assigned", v); 295169689Skan } else { 296169689Skan log.error(pos, "cant.assign.val.to.final.var", v); 297169689Skan } 298169689Skan } 299169689Skan } 300169689Skan 301169689Skan /** Does tree represent a static reference to an identifier? 302169689Skan * It is assumed that tree is either a SELECT or an IDENT. 303169689Skan * We have to weed out selects from non-type names here. 304169689Skan * @param tree The candidate tree. 305169689Skan */ 306169689Skan boolean isStaticReference(JCTree tree) { 307169689Skan if (tree.hasTag(SELECT)) { 308169689Skan Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected); 309169689Skan if (lsym == null || lsym.kind != TYP) { 310169689Skan return false; 311169689Skan } 312169689Skan } 313169689Skan return true; 314169689Skan } 315169689Skan 316169689Skan /** Is this symbol a type? 317169689Skan */ 318169689Skan static boolean isType(Symbol sym) { 319169689Skan return sym != null && sym.kind == TYP; 320169689Skan } 321169689Skan 322169689Skan /** The current `this' symbol. 323169689Skan * @param env The current environment. 324169689Skan */ 325169689Skan Symbol thisSym(DiagnosticPosition pos, Env<AttrContext> env) { 326169689Skan return rs.resolveSelf(pos, env, env.enclClass.sym, names._this); 327169689Skan } 328169689Skan 329169689Skan /** Attribute a parsed identifier. 330169689Skan * @param tree Parsed identifier name 331169689Skan * @param topLevel The toplevel to use 332169689Skan */ 333169689Skan public Symbol attribIdent(JCTree tree, JCCompilationUnit topLevel) { 334169689Skan Env<AttrContext> localEnv = enter.topLevelEnv(topLevel); 335132718Skan localEnv.enclClass = make.ClassDef(make.Modifiers(0), 336132718Skan syms.errSymbol.name, 337132718Skan null, null, null, null); 338132718Skan localEnv.enclClass.sym = syms.errSymbol; 339132718Skan return attribIdent(tree, localEnv); 340132718Skan } 341132718Skan 342132718Skan /** Attribute a parsed identifier. 343169689Skan * @param tree Parsed identifier name 344132718Skan * @param env The env to use 345169689Skan */ 346132718Skan public Symbol attribIdent(JCTree tree, Env<AttrContext> env) { 347132718Skan return tree.accept(identAttributer, env); 348132718Skan } 349132718Skan // where 350132718Skan private TreeVisitor<Symbol,Env<AttrContext>> identAttributer = new IdentAttributer(); 351132718Skan private class IdentAttributer extends SimpleTreeVisitor<Symbol,Env<AttrContext>> { 352132718Skan @Override @DefinedBy(Api.COMPILER_TREE) 353132718Skan public Symbol visitMemberSelect(MemberSelectTree node, Env<AttrContext> env) { 354169689Skan Symbol site = visit(node.getExpression(), env); 355169689Skan if (site.kind == ERR || site.kind == ABSENT_TYP) 356132718Skan return site; 357132718Skan Name name = (Name)node.getIdentifier(); 358132718Skan if (site.kind == PCK) { 359132718Skan env.toplevel.packge = (PackageSymbol)site; 360132718Skan return rs.findIdentInPackage(env, (TypeSymbol)site, name, 361132718Skan KindSelector.TYP_PCK); 362132718Skan } else { 363169689Skan env.enclClass.sym = (ClassSymbol)site; 364132718Skan return rs.findMemberType(env, site.asType(), name, (TypeSymbol)site); 365132718Skan } 366132718Skan } 367132718Skan 368132718Skan @Override @DefinedBy(Api.COMPILER_TREE) 369132718Skan public Symbol visitIdentifier(IdentifierTree node, Env<AttrContext> env) { 370132718Skan return rs.findIdent(env, (Name)node.getName(), KindSelector.TYP_PCK); 371132718Skan } 372169689Skan } 373132718Skan 374132718Skan public Type coerce(Type etype, Type ttype) { 375169689Skan return cfolder.coerce(etype, ttype); 376169689Skan } 377169689Skan 378169689Skan public Type attribType(JCTree node, TypeSymbol sym) { 379169689Skan Env<AttrContext> env = typeEnvs.get(sym); 380169689Skan Env<AttrContext> localEnv = env.dup(node, env.info.dup()); 381169689Skan return attribTree(node, localEnv, unknownTypeInfo); 382169689Skan } 383169689Skan 384169689Skan public Type attribImportQualifier(JCImport tree, Env<AttrContext> env) { 385169689Skan // Attribute qualifying package or class. 386169689Skan JCFieldAccess s = (JCFieldAccess)tree.qualid; 387169689Skan return attribTree(s.selected, env, 388169689Skan new ResultInfo(tree.staticImport ? 389169689Skan KindSelector.TYP : KindSelector.TYP_PCK, 390169689Skan Type.noType)); 391169689Skan } 392132718Skan 393132718Skan public Env<AttrContext> attribExprToTree(JCTree expr, Env<AttrContext> env, JCTree tree) { 394132718Skan breakTree = tree; 395132718Skan JavaFileObject prev = log.useSource(env.toplevel.sourcefile); 396132718Skan try { 397132718Skan attribExpr(expr, env); 398132718Skan } catch (BreakAttr b) { 399132718Skan return b.env; 400132718Skan } catch (AssertionError ae) { 401132718Skan if (ae.getCause() instanceof BreakAttr) { 402132718Skan return ((BreakAttr)(ae.getCause())).env; 403132718Skan } else { 404132718Skan throw ae; 405132718Skan } 406132718Skan } finally { 407169689Skan breakTree = null; 408132718Skan log.useSource(prev); 409132718Skan } 410132718Skan return env; 411132718Skan } 412132718Skan 413132718Skan public Env<AttrContext> attribStatToTree(JCTree stmt, Env<AttrContext> env, JCTree tree) { 414132718Skan breakTree = tree; 415132718Skan JavaFileObject prev = log.useSource(env.toplevel.sourcefile); 416132718Skan try { 417132718Skan attribStat(stmt, env); 418132718Skan } catch (BreakAttr b) { 419132718Skan return b.env; 420132718Skan } catch (AssertionError ae) { 421132718Skan if (ae.getCause() instanceof BreakAttr) { 422132718Skan return ((BreakAttr)(ae.getCause())).env; 423132718Skan } else { 424169689Skan throw ae; 425132718Skan } 426132718Skan } finally { 427132718Skan breakTree = null; 428132718Skan log.useSource(prev); 429132718Skan } 430132718Skan return env; 431169689Skan } 432132718Skan 433132718Skan private JCTree breakTree = null; 434132718Skan 435132718Skan private static class BreakAttr extends RuntimeException { 436169689Skan static final long serialVersionUID = -6924771130405446405L; 437132718Skan private Env<AttrContext> env; 438132718Skan private BreakAttr(Env<AttrContext> env) { 439132718Skan this.env = env; 440132718Skan } 441132718Skan } 442132718Skan 443132718Skan /** 444132718Skan * Mode controlling behavior of Attr.Check 445132718Skan */ 446132718Skan enum CheckMode { 447132718Skan 448132718Skan NORMAL, 449132718Skan 450132718Skan NO_TREE_UPDATE { // Mode signalling 'fake check' - skip tree update 451132718Skan @Override 452132718Skan public boolean updateTreeType() { 453169689Skan return false; 454169689Skan } 455169689Skan }, 456132718Skan NO_INFERENCE_HOOK { // Mode signalling that caller will manage free types in tree decorations. 457132718Skan @Override 458132718Skan public boolean installPostInferenceHook() { 459132718Skan return false; 460132718Skan } 461169689Skan }; 462169689Skan 463169689Skan public boolean updateTreeType() { 464132718Skan return true; 465169689Skan } 466169689Skan public boolean installPostInferenceHook() { 467169689Skan return true; 468169689Skan } 469169689Skan } 470169689Skan 471169689Skan 472169689Skan class ResultInfo { 473169689Skan final KindSelector pkind; 474169689Skan final Type pt; 475169689Skan final CheckContext checkContext; 476169689Skan final CheckMode checkMode; 477169689Skan 478169689Skan ResultInfo(KindSelector pkind, Type pt) { 479169689Skan this(pkind, pt, chk.basicHandler, CheckMode.NORMAL); 480169689Skan } 481132718Skan 482132718Skan ResultInfo(KindSelector pkind, Type pt, CheckMode checkMode) { 483132718Skan this(pkind, pt, chk.basicHandler, checkMode); 484132718Skan } 485132718Skan 486132718Skan protected ResultInfo(KindSelector pkind, 487132718Skan Type pt, CheckContext checkContext) { 488189824Sdas this(pkind, pt, checkContext, CheckMode.NORMAL); 489189824Sdas } 490189824Sdas 491189824Sdas protected ResultInfo(KindSelector pkind, 492169689Skan Type pt, CheckContext checkContext, CheckMode checkMode) { 493132718Skan this.pkind = pkind; 494132718Skan this.pt = pt; 495132718Skan this.checkContext = checkContext; 496132718Skan this.checkMode = checkMode; 497132718Skan } 498132718Skan 499132718Skan protected void attr(JCTree tree, Env<AttrContext> env) { 500132718Skan tree.accept(Attr.this); 501132718Skan } 502132718Skan 503132718Skan protected Type check(final DiagnosticPosition pos, final Type found) { 504261188Spfg return chk.checkType(pos, found, pt, checkContext); 505261188Spfg } 506261188Spfg 507264214Spfg protected ResultInfo dup(Type newPt) { 508264214Spfg return new ResultInfo(pkind, newPt, checkContext, checkMode); 509264214Spfg } 510264214Spfg 511261188Spfg protected ResultInfo dup(CheckContext newContext) { 512132718Skan return new ResultInfo(pkind, pt, newContext, checkMode); 513132718Skan } 514132718Skan 515132718Skan protected ResultInfo dup(Type newPt, CheckContext newContext) { 516132718Skan return new ResultInfo(pkind, newPt, newContext, checkMode); 517132718Skan } 518132718Skan 519132718Skan protected ResultInfo dup(Type newPt, CheckContext newContext, CheckMode newMode) { 520132718Skan return new ResultInfo(pkind, newPt, newContext, newMode); 521132718Skan } 522132718Skan 523132718Skan protected ResultInfo dup(CheckMode newMode) { 524132718Skan return new ResultInfo(pkind, pt, checkContext, newMode); 525132718Skan } 526132718Skan 527169689Skan @Override 528169689Skan public String toString() { 529169689Skan if (pt != null) { 530169689Skan return pt.toString(); 531169689Skan } else { 532132718Skan return ""; 533132718Skan } 534132718Skan } 535132718Skan } 536132718Skan 537132718Skan class MethodAttrInfo extends ResultInfo { 538132718Skan public MethodAttrInfo() { 539169689Skan this(chk.basicHandler); 540132718Skan } 541132718Skan 542132718Skan public MethodAttrInfo(CheckContext checkContext) { 543132718Skan super(KindSelector.VAL, Infer.anyPoly, checkContext); 544132718Skan } 545132718Skan 546169689Skan @Override 547169689Skan protected void attr(JCTree tree, Env<AttrContext> env) { 548169689Skan result = argumentAttr.attribArg(tree, env); 549169689Skan } 550169689Skan 551169689Skan protected ResultInfo dup(Type newPt) { 552169689Skan throw new IllegalStateException(); 553169689Skan } 554169689Skan 555169689Skan protected ResultInfo dup(CheckContext newContext) { 556169689Skan return new MethodAttrInfo(newContext); 557169689Skan } 558169689Skan 559169689Skan protected ResultInfo dup(Type newPt, CheckContext newContext) { 560169689Skan throw new IllegalStateException(); 561169689Skan } 562169689Skan 563169689Skan protected ResultInfo dup(Type newPt, CheckContext newContext, CheckMode newMode) { 564132718Skan throw new IllegalStateException(); 565132718Skan } 566132718Skan 567132718Skan protected ResultInfo dup(CheckMode newMode) { 568132718Skan throw new IllegalStateException(); 569132718Skan } 570132718Skan } 571132718Skan 572132718Skan class RecoveryInfo extends ResultInfo { 573169689Skan 574169689Skan public RecoveryInfo(final DeferredAttr.DeferredAttrContext deferredAttrContext) { 575169689Skan super(KindSelector.VAL, Type.recoveryType, 576169689Skan new Check.NestedCheckContext(chk.basicHandler) { 577169689Skan @Override 578169689Skan public DeferredAttr.DeferredAttrContext deferredAttrContext() { 579169689Skan return deferredAttrContext; 580169689Skan } 581169689Skan @Override 582132718Skan public boolean compatible(Type found, Type req, Warner warn) { 583132718Skan return true; 584132718Skan } 585132718Skan @Override 586132718Skan public void report(DiagnosticPosition pos, JCDiagnostic details) { 587132718Skan chk.basicHandler.report(pos, details); 588132718Skan } 589132718Skan }); 590132718Skan } 591132718Skan } 592132718Skan 593132718Skan final ResultInfo statInfo; 594132718Skan final ResultInfo varAssignmentInfo; 595132718Skan final ResultInfo methodAttrInfo; 596132718Skan final ResultInfo unknownExprInfo; 597169689Skan final ResultInfo unknownTypeInfo; 598132718Skan final ResultInfo unknownTypeExprInfo; 599132718Skan final ResultInfo recoveryInfo; 600132718Skan 601132718Skan Type pt() { 602132718Skan return resultInfo.pt; 603132718Skan } 604132718Skan 605132718Skan KindSelector pkind() { 606132718Skan return resultInfo.pkind; 607132718Skan } 608132718Skan 609132718Skan/* ************************************************************************ 610132718Skan * Visitor methods 611132718Skan *************************************************************************/ 612132718Skan 613132718Skan /** Visitor argument: the current environment. 614132718Skan */ 615132718Skan Env<AttrContext> env; 616132718Skan 617132718Skan /** Visitor argument: the currently expected attribution result. 618132718Skan */ 619132718Skan ResultInfo resultInfo; 620132718Skan 621132718Skan /** Visitor result: the computed type. 622132718Skan */ 623132718Skan Type result; 624132718Skan 625132718Skan /** Visitor method: attribute a tree, catching any completion failure 626132718Skan * exceptions. Return the tree's type. 627132718Skan * 628132718Skan * @param tree The tree to be visited. 629132718Skan * @param env The environment visitor argument. 630132718Skan * @param resultInfo The result info visitor argument. 631132718Skan */ 632132718Skan Type attribTree(JCTree tree, Env<AttrContext> env, ResultInfo resultInfo) { 633132718Skan Env<AttrContext> prevEnv = this.env; 634132718Skan ResultInfo prevResult = this.resultInfo; 635132718Skan try { 636132718Skan this.env = env; 637132718Skan this.resultInfo = resultInfo; 638132718Skan resultInfo.attr(tree, env); 639132718Skan if (tree == breakTree && 640132718Skan resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) { 641132718Skan throw new BreakAttr(copyEnv(env)); 642132718Skan } 643169689Skan return result; 644132718Skan } catch (CompletionFailure ex) { 645132718Skan tree.type = syms.errType; 646132718Skan return chk.completionError(tree.pos(), ex); 647132718Skan } finally { 648132718Skan this.env = prevEnv; 649132718Skan this.resultInfo = prevResult; 650132718Skan } 651132718Skan } 652132718Skan 653132718Skan Env<AttrContext> copyEnv(Env<AttrContext> env) { 654132718Skan Env<AttrContext> newEnv = 655132718Skan env.dup(env.tree, env.info.dup(copyScope(env.info.scope))); 656132718Skan if (newEnv.outer != null) { 657132718Skan newEnv.outer = copyEnv(newEnv.outer); 658132718Skan } 659132718Skan return newEnv; 660132718Skan } 661169689Skan 662132718Skan WriteableScope copyScope(WriteableScope sc) { 663132718Skan WriteableScope newScope = WriteableScope.create(sc.owner); 664132718Skan List<Symbol> elemsList = List.nil(); 665132718Skan for (Symbol sym : sc.getSymbols()) { 666132718Skan elemsList = elemsList.prepend(sym); 667132718Skan } 668132718Skan for (Symbol s : elemsList) { 669132718Skan newScope.enter(s); 670132718Skan } 671132718Skan return newScope; 672132718Skan } 673132718Skan 674132718Skan /** Derived visitor method: attribute an expression tree. 675132718Skan */ 676132718Skan public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) { 677132718Skan return attribTree(tree, env, new ResultInfo(KindSelector.VAL, !pt.hasTag(ERROR) ? pt : Type.noType)); 678132718Skan } 679169689Skan 680132718Skan /** Derived visitor method: attribute an expression tree with 681132718Skan * no constraints on the computed type. 682132718Skan */ 683132718Skan public Type attribExpr(JCTree tree, Env<AttrContext> env) { 684132718Skan return attribTree(tree, env, unknownExprInfo); 685132718Skan } 686132718Skan 687132718Skan /** Derived visitor method: attribute a type tree. 688132718Skan */ 689132718Skan public Type attribType(JCTree tree, Env<AttrContext> env) { 690132718Skan Type result = attribType(tree, env, Type.noType); 691169689Skan return result; 692169689Skan } 693169689Skan 694132718Skan /** Derived visitor method: attribute a type tree. 695132718Skan */ 696169689Skan Type attribType(JCTree tree, Env<AttrContext> env, Type pt) { 697132718Skan Type result = attribTree(tree, env, new ResultInfo(KindSelector.TYP, pt)); 698132718Skan return result; 699132718Skan } 700132718Skan 701132718Skan /** Derived visitor method: attribute a statement or definition tree. 702132718Skan */ 703132718Skan public Type attribStat(JCTree tree, Env<AttrContext> env) { 704132718Skan Env<AttrContext> analyzeEnv = 705132718Skan env.dup(tree, env.info.dup(env.info.scope.dupUnshared(env.info.scope.owner))); 706132718Skan try { 707132718Skan return attribTree(tree, env, statInfo); 708132718Skan } finally { 709132718Skan analyzer.analyzeIfNeeded(tree, analyzeEnv); 710132718Skan } 711169689Skan } 712169689Skan 713169689Skan /** Attribute a list of expressions, returning a list of types. 714169689Skan */ 715169689Skan List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) { 716169689Skan ListBuffer<Type> ts = new ListBuffer<>(); 717169689Skan for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail) 718132718Skan ts.append(attribExpr(l.head, env, pt)); 719132718Skan return ts.toList(); 720132718Skan } 721132718Skan 722132718Skan /** Attribute a list of statements, returning nothing. 723132718Skan */ 724132718Skan <T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) { 725132718Skan for (List<T> l = trees; l.nonEmpty(); l = l.tail) 726132718Skan attribStat(l.head, env); 727132718Skan } 728132718Skan 729132718Skan /** Attribute the arguments in a method call, returning the method kind. 730132718Skan */ 731132718Skan KindSelector attribArgs(KindSelector initialKind, List<JCExpression> trees, Env<AttrContext> env, ListBuffer<Type> argtypes) { 732132718Skan KindSelector kind = initialKind; 733132718Skan for (JCExpression arg : trees) { 734132718Skan Type argtype = chk.checkNonVoid(arg, attribTree(arg, env, allowPoly ? methodAttrInfo : unknownExprInfo)); 735132718Skan if (argtype.hasTag(DEFERRED)) { 736132718Skan kind = KindSelector.of(KindSelector.POLY, kind); 737132718Skan } 738132718Skan argtypes.append(argtype); 739132718Skan } 740132718Skan return kind; 741132718Skan } 742132718Skan 743132718Skan /** Attribute a type argument list, returning a list of types. 744132718Skan * Caller is responsible for calling checkRefTypes. 745132718Skan */ 746132718Skan List<Type> attribAnyTypes(List<JCExpression> trees, Env<AttrContext> env) { 747132718Skan ListBuffer<Type> argtypes = new ListBuffer<>(); 748132718Skan for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail) 749132718Skan argtypes.append(attribType(l.head, env)); 750169689Skan return argtypes.toList(); 751132718Skan } 752132718Skan 753169689Skan /** Attribute a type argument list, returning a list of types. 754169689Skan * Check that all the types are references. 755132718Skan */ 756169689Skan List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) { 757169689Skan List<Type> types = attribAnyTypes(trees, env); 758132718Skan return chk.checkRefTypes(trees, types); 759132718Skan } 760132718Skan 761132718Skan /** 762 * Attribute type variables (of generic classes or methods). 763 * Compound types are attributed later in attribBounds. 764 * @param typarams the type variables to enter 765 * @param env the current environment 766 */ 767 void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env) { 768 for (JCTypeParameter tvar : typarams) { 769 TypeVar a = (TypeVar)tvar.type; 770 a.tsym.flags_field |= UNATTRIBUTED; 771 a.bound = Type.noType; 772 if (!tvar.bounds.isEmpty()) { 773 List<Type> bounds = List.of(attribType(tvar.bounds.head, env)); 774 for (JCExpression bound : tvar.bounds.tail) 775 bounds = bounds.prepend(attribType(bound, env)); 776 types.setBounds(a, bounds.reverse()); 777 } else { 778 // if no bounds are given, assume a single bound of 779 // java.lang.Object. 780 types.setBounds(a, List.of(syms.objectType)); 781 } 782 a.tsym.flags_field &= ~UNATTRIBUTED; 783 } 784 for (JCTypeParameter tvar : typarams) { 785 chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type); 786 } 787 } 788 789 /** 790 * Attribute the type references in a list of annotations. 791 */ 792 void attribAnnotationTypes(List<JCAnnotation> annotations, 793 Env<AttrContext> env) { 794 for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) { 795 JCAnnotation a = al.head; 796 attribType(a.annotationType, env); 797 } 798 } 799 800 /** 801 * Attribute a "lazy constant value". 802 * @param env The env for the const value 803 * @param variable The initializer for the const value 804 * @param type The expected type, or null 805 * @see VarSymbol#setLazyConstValue 806 */ 807 public Object attribLazyConstantValue(Env<AttrContext> env, 808 JCVariableDecl variable, 809 Type type) { 810 811 DiagnosticPosition prevLintPos 812 = deferredLintHandler.setPos(variable.pos()); 813 814 try { 815 Type itype = attribExpr(variable.init, env, type); 816 if (itype.constValue() != null) { 817 return coerce(itype, type).constValue(); 818 } else { 819 return null; 820 } 821 } finally { 822 deferredLintHandler.setPos(prevLintPos); 823 } 824 } 825 826 /** Attribute type reference in an `extends' or `implements' clause. 827 * Supertypes of anonymous inner classes are usually already attributed. 828 * 829 * @param tree The tree making up the type reference. 830 * @param env The environment current at the reference. 831 * @param classExpected true if only a class is expected here. 832 * @param interfaceExpected true if only an interface is expected here. 833 */ 834 Type attribBase(JCTree tree, 835 Env<AttrContext> env, 836 boolean classExpected, 837 boolean interfaceExpected, 838 boolean checkExtensible) { 839 Type t = tree.type != null ? 840 tree.type : 841 attribType(tree, env); 842 return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible); 843 } 844 Type checkBase(Type t, 845 JCTree tree, 846 Env<AttrContext> env, 847 boolean classExpected, 848 boolean interfaceExpected, 849 boolean checkExtensible) { 850 final DiagnosticPosition pos = tree.hasTag(TYPEAPPLY) ? 851 (((JCTypeApply) tree).clazz).pos() : tree.pos(); 852 if (t.tsym.isAnonymous()) { 853 log.error(pos, "cant.inherit.from.anon"); 854 return types.createErrorType(t); 855 } 856 if (t.isErroneous()) 857 return t; 858 if (t.hasTag(TYPEVAR) && !classExpected && !interfaceExpected) { 859 // check that type variable is already visible 860 if (t.getUpperBound() == null) { 861 log.error(pos, "illegal.forward.ref"); 862 return types.createErrorType(t); 863 } 864 } else { 865 t = chk.checkClassType(pos, t, checkExtensible); 866 } 867 if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) { 868 log.error(pos, "intf.expected.here"); 869 // return errType is necessary since otherwise there might 870 // be undetected cycles which cause attribution to loop 871 return types.createErrorType(t); 872 } else if (checkExtensible && 873 classExpected && 874 (t.tsym.flags() & INTERFACE) != 0) { 875 log.error(pos, "no.intf.expected.here"); 876 return types.createErrorType(t); 877 } 878 if (checkExtensible && 879 ((t.tsym.flags() & FINAL) != 0)) { 880 log.error(pos, 881 "cant.inherit.from.final", t.tsym); 882 } 883 chk.checkNonCyclic(pos, t); 884 return t; 885 } 886 887 Type attribIdentAsEnumType(Env<AttrContext> env, JCIdent id) { 888 Assert.check((env.enclClass.sym.flags() & ENUM) != 0); 889 id.type = env.info.scope.owner.enclClass().type; 890 id.sym = env.info.scope.owner.enclClass(); 891 return id.type; 892 } 893 894 public void visitClassDef(JCClassDecl tree) { 895 Optional<ArgumentAttr.LocalCacheContext> localCacheContext = 896 Optional.ofNullable(env.info.isSpeculative ? 897 argumentAttr.withLocalCacheContext() : null); 898 try { 899 // Local and anonymous classes have not been entered yet, so we need to 900 // do it now. 901 if (env.info.scope.owner.kind.matches(KindSelector.VAL_MTH)) { 902 enter.classEnter(tree, env); 903 } else { 904 // If this class declaration is part of a class level annotation, 905 // as in @MyAnno(new Object() {}) class MyClass {}, enter it in 906 // order to simplify later steps and allow for sensible error 907 // messages. 908 if (env.tree.hasTag(NEWCLASS) && TreeInfo.isInAnnotation(env, tree)) 909 enter.classEnter(tree, env); 910 } 911 912 ClassSymbol c = tree.sym; 913 if (c == null) { 914 // exit in case something drastic went wrong during enter. 915 result = null; 916 } else { 917 // make sure class has been completed: 918 c.complete(); 919 920 // If this class appears as an anonymous class 921 // in a superclass constructor call where 922 // no explicit outer instance is given, 923 // disable implicit outer instance from being passed. 924 // (This would be an illegal access to "this before super"). 925 if (env.info.isSelfCall && 926 env.tree.hasTag(NEWCLASS) && 927 ((JCNewClass)env.tree).encl == null) { 928 c.flags_field |= NOOUTERTHIS; 929 } 930 attribClass(tree.pos(), c); 931 result = tree.type = c.type; 932 } 933 } finally { 934 localCacheContext.ifPresent(LocalCacheContext::leave); 935 } 936 } 937 938 public void visitMethodDef(JCMethodDecl tree) { 939 MethodSymbol m = tree.sym; 940 boolean isDefaultMethod = (m.flags() & DEFAULT) != 0; 941 942 Lint lint = env.info.lint.augment(m); 943 Lint prevLint = chk.setLint(lint); 944 MethodSymbol prevMethod = chk.setMethod(m); 945 try { 946 deferredLintHandler.flush(tree.pos()); 947 chk.checkDeprecatedAnnotation(tree.pos(), m); 948 949 950 // Create a new environment with local scope 951 // for attributing the method. 952 Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env); 953 localEnv.info.lint = lint; 954 955 attribStats(tree.typarams, localEnv); 956 957 // If we override any other methods, check that we do so properly. 958 // JLS ??? 959 if (m.isStatic()) { 960 chk.checkHideClashes(tree.pos(), env.enclClass.type, m); 961 } else { 962 chk.checkOverrideClashes(tree.pos(), env.enclClass.type, m); 963 } 964 chk.checkOverride(env, tree, m); 965 966 if (isDefaultMethod && types.overridesObjectMethod(m.enclClass(), m)) { 967 log.error(tree, "default.overrides.object.member", m.name, Kinds.kindName(m.location()), m.location()); 968 } 969 970 // Enter all type parameters into the local method scope. 971 for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail) 972 localEnv.info.scope.enterIfAbsent(l.head.type.tsym); 973 974 ClassSymbol owner = env.enclClass.sym; 975 if ((owner.flags() & ANNOTATION) != 0 && 976 tree.params.nonEmpty()) 977 log.error(tree.params.head.pos(), 978 "intf.annotation.members.cant.have.params"); 979 980 // Attribute all value parameters. 981 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) { 982 attribStat(l.head, localEnv); 983 } 984 985 chk.checkVarargsMethodDecl(localEnv, tree); 986 987 // Check that type parameters are well-formed. 988 chk.validate(tree.typarams, localEnv); 989 990 // Check that result type is well-formed. 991 if (tree.restype != null && !tree.restype.type.hasTag(VOID)) 992 chk.validate(tree.restype, localEnv); 993 994 // Check that receiver type is well-formed. 995 if (tree.recvparam != null) { 996 // Use a new environment to check the receiver parameter. 997 // Otherwise I get "might not have been initialized" errors. 998 // Is there a better way? 999 Env<AttrContext> newEnv = memberEnter.methodEnv(tree, env); 1000 attribType(tree.recvparam, newEnv); 1001 chk.validate(tree.recvparam, newEnv); 1002 } 1003 1004 // annotation method checks 1005 if ((owner.flags() & ANNOTATION) != 0) { 1006 // annotation method cannot have throws clause 1007 if (tree.thrown.nonEmpty()) { 1008 log.error(tree.thrown.head.pos(), 1009 "throws.not.allowed.in.intf.annotation"); 1010 } 1011 // annotation method cannot declare type-parameters 1012 if (tree.typarams.nonEmpty()) { 1013 log.error(tree.typarams.head.pos(), 1014 "intf.annotation.members.cant.have.type.params"); 1015 } 1016 // validate annotation method's return type (could be an annotation type) 1017 chk.validateAnnotationType(tree.restype); 1018 // ensure that annotation method does not clash with members of Object/Annotation 1019 chk.validateAnnotationMethod(tree.pos(), m); 1020 } 1021 1022 for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail) 1023 chk.checkType(l.head.pos(), l.head.type, syms.throwableType); 1024 1025 if (tree.body == null) { 1026 // Empty bodies are only allowed for 1027 // abstract, native, or interface methods, or for methods 1028 // in a retrofit signature class. 1029 if (tree.defaultValue != null) { 1030 if ((owner.flags() & ANNOTATION) == 0) 1031 log.error(tree.pos(), 1032 "default.allowed.in.intf.annotation.member"); 1033 } 1034 if (isDefaultMethod || (tree.sym.flags() & (ABSTRACT | NATIVE)) == 0) 1035 log.error(tree.pos(), "missing.meth.body.or.decl.abstract"); 1036 } else if ((tree.sym.flags() & (ABSTRACT|DEFAULT|PRIVATE)) == ABSTRACT) { 1037 if ((owner.flags() & INTERFACE) != 0) { 1038 log.error(tree.body.pos(), "intf.meth.cant.have.body"); 1039 } else { 1040 log.error(tree.pos(), "abstract.meth.cant.have.body"); 1041 } 1042 } else if ((tree.mods.flags & NATIVE) != 0) { 1043 log.error(tree.pos(), "native.meth.cant.have.body"); 1044 } else { 1045 // Add an implicit super() call unless an explicit call to 1046 // super(...) or this(...) is given 1047 // or we are compiling class java.lang.Object. 1048 if (tree.name == names.init && owner.type != syms.objectType) { 1049 JCBlock body = tree.body; 1050 if (body.stats.isEmpty() || 1051 !TreeInfo.isSelfCall(body.stats.head)) { 1052 body.stats = body.stats. 1053 prepend(typeEnter.SuperCall(make.at(body.pos), 1054 List.<Type>nil(), 1055 List.<JCVariableDecl>nil(), 1056 false)); 1057 } else if ((env.enclClass.sym.flags() & ENUM) != 0 && 1058 (tree.mods.flags & GENERATEDCONSTR) == 0 && 1059 TreeInfo.isSuperCall(body.stats.head)) { 1060 // enum constructors are not allowed to call super 1061 // directly, so make sure there aren't any super calls 1062 // in enum constructors, except in the compiler 1063 // generated one. 1064 log.error(tree.body.stats.head.pos(), 1065 "call.to.super.not.allowed.in.enum.ctor", 1066 env.enclClass.sym); 1067 } 1068 } 1069 1070 // Attribute all type annotations in the body 1071 annotate.queueScanTreeAndTypeAnnotate(tree.body, localEnv, m, null); 1072 annotate.flush(); 1073 1074 // Attribute method body. 1075 attribStat(tree.body, localEnv); 1076 } 1077 1078 localEnv.info.scope.leave(); 1079 result = tree.type = m.type; 1080 } finally { 1081 chk.setLint(prevLint); 1082 chk.setMethod(prevMethod); 1083 } 1084 } 1085 1086 public void visitVarDef(JCVariableDecl tree) { 1087 // Local variables have not been entered yet, so we need to do it now: 1088 if (env.info.scope.owner.kind == MTH) { 1089 if (tree.sym != null) { 1090 // parameters have already been entered 1091 env.info.scope.enter(tree.sym); 1092 } else { 1093 try { 1094 annotate.blockAnnotations(); 1095 memberEnter.memberEnter(tree, env); 1096 } finally { 1097 annotate.unblockAnnotations(); 1098 } 1099 } 1100 } else { 1101 if (tree.init != null) { 1102 // Field initializer expression need to be entered. 1103 annotate.queueScanTreeAndTypeAnnotate(tree.init, env, tree.sym, tree.pos()); 1104 annotate.flush(); 1105 } 1106 } 1107 1108 VarSymbol v = tree.sym; 1109 Lint lint = env.info.lint.augment(v); 1110 Lint prevLint = chk.setLint(lint); 1111 1112 // Check that the variable's declared type is well-formed. 1113 boolean isImplicitLambdaParameter = env.tree.hasTag(LAMBDA) && 1114 ((JCLambda)env.tree).paramKind == JCLambda.ParameterKind.IMPLICIT && 1115 (tree.sym.flags() & PARAMETER) != 0; 1116 chk.validate(tree.vartype, env, !isImplicitLambdaParameter); 1117 1118 try { 1119 v.getConstValue(); // ensure compile-time constant initializer is evaluated 1120 deferredLintHandler.flush(tree.pos()); 1121 chk.checkDeprecatedAnnotation(tree.pos(), v); 1122 1123 if (tree.init != null) { 1124 if ((v.flags_field & FINAL) == 0 || 1125 !memberEnter.needsLazyConstValue(tree.init)) { 1126 // Not a compile-time constant 1127 // Attribute initializer in a new environment 1128 // with the declared variable as owner. 1129 // Check that initializer conforms to variable's declared type. 1130 Env<AttrContext> initEnv = memberEnter.initEnv(tree, env); 1131 initEnv.info.lint = lint; 1132 // In order to catch self-references, we set the variable's 1133 // declaration position to maximal possible value, effectively 1134 // marking the variable as undefined. 1135 initEnv.info.enclVar = v; 1136 attribExpr(tree.init, initEnv, v.type); 1137 } 1138 } 1139 result = tree.type = v.type; 1140 } 1141 finally { 1142 chk.setLint(prevLint); 1143 } 1144 } 1145 1146 public void visitSkip(JCSkip tree) { 1147 result = null; 1148 } 1149 1150 public void visitBlock(JCBlock tree) { 1151 if (env.info.scope.owner.kind == TYP) { 1152 // Block is a static or instance initializer; 1153 // let the owner of the environment be a freshly 1154 // created BLOCK-method. 1155 Symbol fakeOwner = 1156 new MethodSymbol(tree.flags | BLOCK | 1157 env.info.scope.owner.flags() & STRICTFP, names.empty, null, 1158 env.info.scope.owner); 1159 final Env<AttrContext> localEnv = 1160 env.dup(tree, env.info.dup(env.info.scope.dupUnshared(fakeOwner))); 1161 1162 if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++; 1163 // Attribute all type annotations in the block 1164 annotate.queueScanTreeAndTypeAnnotate(tree, localEnv, localEnv.info.scope.owner, null); 1165 annotate.flush(); 1166 attribStats(tree.stats, localEnv); 1167 1168 { 1169 // Store init and clinit type annotations with the ClassSymbol 1170 // to allow output in Gen.normalizeDefs. 1171 ClassSymbol cs = (ClassSymbol)env.info.scope.owner; 1172 List<Attribute.TypeCompound> tas = localEnv.info.scope.owner.getRawTypeAttributes(); 1173 if ((tree.flags & STATIC) != 0) { 1174 cs.appendClassInitTypeAttributes(tas); 1175 } else { 1176 cs.appendInitTypeAttributes(tas); 1177 } 1178 } 1179 } else { 1180 // Create a new local environment with a local scope. 1181 Env<AttrContext> localEnv = 1182 env.dup(tree, env.info.dup(env.info.scope.dup())); 1183 try { 1184 attribStats(tree.stats, localEnv); 1185 } finally { 1186 localEnv.info.scope.leave(); 1187 } 1188 } 1189 result = null; 1190 } 1191 1192 public void visitDoLoop(JCDoWhileLoop tree) { 1193 attribStat(tree.body, env.dup(tree)); 1194 attribExpr(tree.cond, env, syms.booleanType); 1195 result = null; 1196 } 1197 1198 public void visitWhileLoop(JCWhileLoop tree) { 1199 attribExpr(tree.cond, env, syms.booleanType); 1200 attribStat(tree.body, env.dup(tree)); 1201 result = null; 1202 } 1203 1204 public void visitForLoop(JCForLoop tree) { 1205 Env<AttrContext> loopEnv = 1206 env.dup(env.tree, env.info.dup(env.info.scope.dup())); 1207 try { 1208 attribStats(tree.init, loopEnv); 1209 if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType); 1210 loopEnv.tree = tree; // before, we were not in loop! 1211 attribStats(tree.step, loopEnv); 1212 attribStat(tree.body, loopEnv); 1213 result = null; 1214 } 1215 finally { 1216 loopEnv.info.scope.leave(); 1217 } 1218 } 1219 1220 public void visitForeachLoop(JCEnhancedForLoop tree) { 1221 Env<AttrContext> loopEnv = 1222 env.dup(env.tree, env.info.dup(env.info.scope.dup())); 1223 try { 1224 //the Formal Parameter of a for-each loop is not in the scope when 1225 //attributing the for-each expression; we mimick this by attributing 1226 //the for-each expression first (against original scope). 1227 Type exprType = types.cvarUpperBound(attribExpr(tree.expr, loopEnv)); 1228 attribStat(tree.var, loopEnv); 1229 chk.checkNonVoid(tree.pos(), exprType); 1230 Type elemtype = types.elemtype(exprType); // perhaps expr is an array? 1231 if (elemtype == null) { 1232 // or perhaps expr implements Iterable<T>? 1233 Type base = types.asSuper(exprType, syms.iterableType.tsym); 1234 if (base == null) { 1235 log.error(tree.expr.pos(), 1236 "foreach.not.applicable.to.type", 1237 exprType, 1238 diags.fragment("type.req.array.or.iterable")); 1239 elemtype = types.createErrorType(exprType); 1240 } else { 1241 List<Type> iterableParams = base.allparams(); 1242 elemtype = iterableParams.isEmpty() 1243 ? syms.objectType 1244 : types.wildUpperBound(iterableParams.head); 1245 } 1246 } 1247 chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type); 1248 loopEnv.tree = tree; // before, we were not in loop! 1249 attribStat(tree.body, loopEnv); 1250 result = null; 1251 } 1252 finally { 1253 loopEnv.info.scope.leave(); 1254 } 1255 } 1256 1257 public void visitLabelled(JCLabeledStatement tree) { 1258 // Check that label is not used in an enclosing statement 1259 Env<AttrContext> env1 = env; 1260 while (env1 != null && !env1.tree.hasTag(CLASSDEF)) { 1261 if (env1.tree.hasTag(LABELLED) && 1262 ((JCLabeledStatement) env1.tree).label == tree.label) { 1263 log.error(tree.pos(), "label.already.in.use", 1264 tree.label); 1265 break; 1266 } 1267 env1 = env1.next; 1268 } 1269 1270 attribStat(tree.body, env.dup(tree)); 1271 result = null; 1272 } 1273 1274 public void visitSwitch(JCSwitch tree) { 1275 Type seltype = attribExpr(tree.selector, env); 1276 1277 Env<AttrContext> switchEnv = 1278 env.dup(tree, env.info.dup(env.info.scope.dup())); 1279 1280 try { 1281 1282 boolean enumSwitch = (seltype.tsym.flags() & Flags.ENUM) != 0; 1283 boolean stringSwitch = false; 1284 if (types.isSameType(seltype, syms.stringType)) { 1285 if (allowStringsInSwitch) { 1286 stringSwitch = true; 1287 } else { 1288 log.error(tree.selector.pos(), "string.switch.not.supported.in.source", sourceName); 1289 } 1290 } 1291 if (!enumSwitch && !stringSwitch) 1292 seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType); 1293 1294 // Attribute all cases and 1295 // check that there are no duplicate case labels or default clauses. 1296 Set<Object> labels = new HashSet<>(); // The set of case labels. 1297 boolean hasDefault = false; // Is there a default label? 1298 for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) { 1299 JCCase c = l.head; 1300 if (c.pat != null) { 1301 if (enumSwitch) { 1302 Symbol sym = enumConstant(c.pat, seltype); 1303 if (sym == null) { 1304 log.error(c.pat.pos(), "enum.label.must.be.unqualified.enum"); 1305 } else if (!labels.add(sym)) { 1306 log.error(c.pos(), "duplicate.case.label"); 1307 } 1308 } else { 1309 Type pattype = attribExpr(c.pat, switchEnv, seltype); 1310 if (!pattype.hasTag(ERROR)) { 1311 if (pattype.constValue() == null) { 1312 log.error(c.pat.pos(), 1313 (stringSwitch ? "string.const.req" : "const.expr.req")); 1314 } else if (!labels.add(pattype.constValue())) { 1315 log.error(c.pos(), "duplicate.case.label"); 1316 } 1317 } 1318 } 1319 } else if (hasDefault) { 1320 log.error(c.pos(), "duplicate.default.label"); 1321 } else { 1322 hasDefault = true; 1323 } 1324 Env<AttrContext> caseEnv = 1325 switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup())); 1326 try { 1327 attribStats(c.stats, caseEnv); 1328 } finally { 1329 caseEnv.info.scope.leave(); 1330 addVars(c.stats, switchEnv.info.scope); 1331 } 1332 } 1333 1334 result = null; 1335 } 1336 finally { 1337 switchEnv.info.scope.leave(); 1338 } 1339 } 1340 // where 1341 /** Add any variables defined in stats to the switch scope. */ 1342 private static void addVars(List<JCStatement> stats, WriteableScope switchScope) { 1343 for (;stats.nonEmpty(); stats = stats.tail) { 1344 JCTree stat = stats.head; 1345 if (stat.hasTag(VARDEF)) 1346 switchScope.enter(((JCVariableDecl) stat).sym); 1347 } 1348 } 1349 // where 1350 /** Return the selected enumeration constant symbol, or null. */ 1351 private Symbol enumConstant(JCTree tree, Type enumType) { 1352 if (tree.hasTag(IDENT)) { 1353 JCIdent ident = (JCIdent)tree; 1354 Name name = ident.name; 1355 for (Symbol sym : enumType.tsym.members().getSymbolsByName(name)) { 1356 if (sym.kind == VAR) { 1357 Symbol s = ident.sym = sym; 1358 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated 1359 ident.type = s.type; 1360 return ((s.flags_field & Flags.ENUM) == 0) 1361 ? null : s; 1362 } 1363 } 1364 } 1365 return null; 1366 } 1367 1368 public void visitSynchronized(JCSynchronized tree) { 1369 chk.checkRefType(tree.pos(), attribExpr(tree.lock, env)); 1370 attribStat(tree.body, env); 1371 result = null; 1372 } 1373 1374 public void visitTry(JCTry tree) { 1375 // Create a new local environment with a local 1376 Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup())); 1377 try { 1378 boolean isTryWithResource = tree.resources.nonEmpty(); 1379 // Create a nested environment for attributing the try block if needed 1380 Env<AttrContext> tryEnv = isTryWithResource ? 1381 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) : 1382 localEnv; 1383 try { 1384 // Attribute resource declarations 1385 for (JCTree resource : tree.resources) { 1386 CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) { 1387 @Override 1388 public void report(DiagnosticPosition pos, JCDiagnostic details) { 1389 chk.basicHandler.report(pos, diags.fragment("try.not.applicable.to.type", details)); 1390 } 1391 }; 1392 ResultInfo twrResult = 1393 new ResultInfo(KindSelector.VAR, 1394 syms.autoCloseableType, 1395 twrContext); 1396 if (resource.hasTag(VARDEF)) { 1397 attribStat(resource, tryEnv); 1398 twrResult.check(resource, resource.type); 1399 1400 //check that resource type cannot throw InterruptedException 1401 checkAutoCloseable(resource.pos(), localEnv, resource.type); 1402 1403 VarSymbol var = ((JCVariableDecl) resource).sym; 1404 var.setData(ElementKind.RESOURCE_VARIABLE); 1405 } else { 1406 attribTree(resource, tryEnv, twrResult); 1407 } 1408 } 1409 // Attribute body 1410 attribStat(tree.body, tryEnv); 1411 } finally { 1412 if (isTryWithResource) 1413 tryEnv.info.scope.leave(); 1414 } 1415 1416 // Attribute catch clauses 1417 for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) { 1418 JCCatch c = l.head; 1419 Env<AttrContext> catchEnv = 1420 localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup())); 1421 try { 1422 Type ctype = attribStat(c.param, catchEnv); 1423 if (TreeInfo.isMultiCatch(c)) { 1424 //multi-catch parameter is implicitly marked as final 1425 c.param.sym.flags_field |= FINAL | UNION; 1426 } 1427 if (c.param.sym.kind == VAR) { 1428 c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER); 1429 } 1430 chk.checkType(c.param.vartype.pos(), 1431 chk.checkClassType(c.param.vartype.pos(), ctype), 1432 syms.throwableType); 1433 attribStat(c.body, catchEnv); 1434 } finally { 1435 catchEnv.info.scope.leave(); 1436 } 1437 } 1438 1439 // Attribute finalizer 1440 if (tree.finalizer != null) attribStat(tree.finalizer, localEnv); 1441 result = null; 1442 } 1443 finally { 1444 localEnv.info.scope.leave(); 1445 } 1446 } 1447 1448 void checkAutoCloseable(DiagnosticPosition pos, Env<AttrContext> env, Type resource) { 1449 if (!resource.isErroneous() && 1450 types.asSuper(resource, syms.autoCloseableType.tsym) != null && 1451 !types.isSameType(resource, syms.autoCloseableType)) { // Don't emit warning for AutoCloseable itself 1452 Symbol close = syms.noSymbol; 1453 Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log); 1454 try { 1455 close = rs.resolveQualifiedMethod(pos, 1456 env, 1457 resource, 1458 names.close, 1459 List.<Type>nil(), 1460 List.<Type>nil()); 1461 } 1462 finally { 1463 log.popDiagnosticHandler(discardHandler); 1464 } 1465 if (close.kind == MTH && 1466 close.overrides(syms.autoCloseableClose, resource.tsym, types, true) && 1467 chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes()) && 1468 env.info.lint.isEnabled(LintCategory.TRY)) { 1469 log.warning(LintCategory.TRY, pos, "try.resource.throws.interrupted.exc", resource); 1470 } 1471 } 1472 } 1473 1474 public void visitConditional(JCConditional tree) { 1475 Type condtype = attribExpr(tree.cond, env, syms.booleanType); 1476 1477 tree.polyKind = (!allowPoly || 1478 pt().hasTag(NONE) && pt() != Type.recoveryType && pt() != Infer.anyPoly || 1479 isBooleanOrNumeric(env, tree)) ? 1480 PolyKind.STANDALONE : PolyKind.POLY; 1481 1482 if (tree.polyKind == PolyKind.POLY && resultInfo.pt.hasTag(VOID)) { 1483 //this means we are returning a poly conditional from void-compatible lambda expression 1484 resultInfo.checkContext.report(tree, diags.fragment("conditional.target.cant.be.void")); 1485 result = tree.type = types.createErrorType(resultInfo.pt); 1486 return; 1487 } 1488 1489 ResultInfo condInfo = tree.polyKind == PolyKind.STANDALONE ? 1490 unknownExprInfo : 1491 resultInfo.dup(conditionalContext(resultInfo.checkContext)); 1492 1493 Type truetype = attribTree(tree.truepart, env, condInfo); 1494 Type falsetype = attribTree(tree.falsepart, env, condInfo); 1495 1496 Type owntype = (tree.polyKind == PolyKind.STANDALONE) ? condType(tree, truetype, falsetype) : pt(); 1497 if (condtype.constValue() != null && 1498 truetype.constValue() != null && 1499 falsetype.constValue() != null && 1500 !owntype.hasTag(NONE)) { 1501 //constant folding 1502 owntype = cfolder.coerce(condtype.isTrue() ? truetype : falsetype, owntype); 1503 } 1504 result = check(tree, owntype, KindSelector.VAL, resultInfo); 1505 } 1506 //where 1507 private boolean isBooleanOrNumeric(Env<AttrContext> env, JCExpression tree) { 1508 switch (tree.getTag()) { 1509 case LITERAL: return ((JCLiteral)tree).typetag.isSubRangeOf(DOUBLE) || 1510 ((JCLiteral)tree).typetag == BOOLEAN || 1511 ((JCLiteral)tree).typetag == BOT; 1512 case LAMBDA: case REFERENCE: return false; 1513 case PARENS: return isBooleanOrNumeric(env, ((JCParens)tree).expr); 1514 case CONDEXPR: 1515 JCConditional condTree = (JCConditional)tree; 1516 return isBooleanOrNumeric(env, condTree.truepart) && 1517 isBooleanOrNumeric(env, condTree.falsepart); 1518 case APPLY: 1519 JCMethodInvocation speculativeMethodTree = 1520 (JCMethodInvocation)deferredAttr.attribSpeculative(tree, env, unknownExprInfo); 1521 Symbol msym = TreeInfo.symbol(speculativeMethodTree.meth); 1522 Type receiverType = speculativeMethodTree.meth.hasTag(IDENT) ? 1523 env.enclClass.type : 1524 ((JCFieldAccess)speculativeMethodTree.meth).selected.type; 1525 Type owntype = types.memberType(receiverType, msym).getReturnType(); 1526 return primitiveOrBoxed(owntype); 1527 case NEWCLASS: 1528 JCExpression className = 1529 removeClassParams.translate(((JCNewClass)tree).clazz); 1530 JCExpression speculativeNewClassTree = 1531 (JCExpression)deferredAttr.attribSpeculative(className, env, unknownTypeInfo); 1532 return primitiveOrBoxed(speculativeNewClassTree.type); 1533 default: 1534 Type speculativeType = deferredAttr.attribSpeculative(tree, env, unknownExprInfo).type; 1535 return primitiveOrBoxed(speculativeType); 1536 } 1537 } 1538 //where 1539 boolean primitiveOrBoxed(Type t) { 1540 return (!t.hasTag(TYPEVAR) && types.unboxedTypeOrType(t).isPrimitive()); 1541 } 1542 1543 TreeTranslator removeClassParams = new TreeTranslator() { 1544 @Override 1545 public void visitTypeApply(JCTypeApply tree) { 1546 result = translate(tree.clazz); 1547 } 1548 }; 1549 1550 CheckContext conditionalContext(CheckContext checkContext) { 1551 return new Check.NestedCheckContext(checkContext) { 1552 //this will use enclosing check context to check compatibility of 1553 //subexpression against target type; if we are in a method check context, 1554 //depending on whether boxing is allowed, we could have incompatibilities 1555 @Override 1556 public void report(DiagnosticPosition pos, JCDiagnostic details) { 1557 enclosingContext.report(pos, diags.fragment("incompatible.type.in.conditional", details)); 1558 } 1559 }; 1560 } 1561 1562 /** Compute the type of a conditional expression, after 1563 * checking that it exists. See JLS 15.25. Does not take into 1564 * account the special case where condition and both arms 1565 * are constants. 1566 * 1567 * @param pos The source position to be used for error 1568 * diagnostics. 1569 * @param thentype The type of the expression's then-part. 1570 * @param elsetype The type of the expression's else-part. 1571 */ 1572 Type condType(DiagnosticPosition pos, 1573 Type thentype, Type elsetype) { 1574 // If same type, that is the result 1575 if (types.isSameType(thentype, elsetype)) 1576 return thentype.baseType(); 1577 1578 Type thenUnboxed = (thentype.isPrimitive()) 1579 ? thentype : types.unboxedType(thentype); 1580 Type elseUnboxed = (elsetype.isPrimitive()) 1581 ? elsetype : types.unboxedType(elsetype); 1582 1583 // Otherwise, if both arms can be converted to a numeric 1584 // type, return the least numeric type that fits both arms 1585 // (i.e. return larger of the two, or return int if one 1586 // arm is short, the other is char). 1587 if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) { 1588 // If one arm has an integer subrange type (i.e., byte, 1589 // short, or char), and the other is an integer constant 1590 // that fits into the subrange, return the subrange type. 1591 if (thenUnboxed.getTag().isStrictSubRangeOf(INT) && 1592 elseUnboxed.hasTag(INT) && 1593 types.isAssignable(elseUnboxed, thenUnboxed)) { 1594 return thenUnboxed.baseType(); 1595 } 1596 if (elseUnboxed.getTag().isStrictSubRangeOf(INT) && 1597 thenUnboxed.hasTag(INT) && 1598 types.isAssignable(thenUnboxed, elseUnboxed)) { 1599 return elseUnboxed.baseType(); 1600 } 1601 1602 for (TypeTag tag : primitiveTags) { 1603 Type candidate = syms.typeOfTag[tag.ordinal()]; 1604 if (types.isSubtype(thenUnboxed, candidate) && 1605 types.isSubtype(elseUnboxed, candidate)) { 1606 return candidate; 1607 } 1608 } 1609 } 1610 1611 // Those were all the cases that could result in a primitive 1612 if (thentype.isPrimitive()) 1613 thentype = types.boxedClass(thentype).type; 1614 if (elsetype.isPrimitive()) 1615 elsetype = types.boxedClass(elsetype).type; 1616 1617 if (types.isSubtype(thentype, elsetype)) 1618 return elsetype.baseType(); 1619 if (types.isSubtype(elsetype, thentype)) 1620 return thentype.baseType(); 1621 1622 if (thentype.hasTag(VOID) || elsetype.hasTag(VOID)) { 1623 log.error(pos, "neither.conditional.subtype", 1624 thentype, elsetype); 1625 return thentype.baseType(); 1626 } 1627 1628 // both are known to be reference types. The result is 1629 // lub(thentype,elsetype). This cannot fail, as it will 1630 // always be possible to infer "Object" if nothing better. 1631 return types.lub(thentype.baseType(), elsetype.baseType()); 1632 } 1633 1634 final static TypeTag[] primitiveTags = new TypeTag[]{ 1635 BYTE, 1636 CHAR, 1637 SHORT, 1638 INT, 1639 LONG, 1640 FLOAT, 1641 DOUBLE, 1642 BOOLEAN, 1643 }; 1644 1645 public void visitIf(JCIf tree) { 1646 attribExpr(tree.cond, env, syms.booleanType); 1647 attribStat(tree.thenpart, env); 1648 if (tree.elsepart != null) 1649 attribStat(tree.elsepart, env); 1650 chk.checkEmptyIf(tree); 1651 result = null; 1652 } 1653 1654 public void visitExec(JCExpressionStatement tree) { 1655 //a fresh environment is required for 292 inference to work properly --- 1656 //see Infer.instantiatePolymorphicSignatureInstance() 1657 Env<AttrContext> localEnv = env.dup(tree); 1658 attribExpr(tree.expr, localEnv); 1659 result = null; 1660 } 1661 1662 public void visitBreak(JCBreak tree) { 1663 tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env); 1664 result = null; 1665 } 1666 1667 public void visitContinue(JCContinue tree) { 1668 tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env); 1669 result = null; 1670 } 1671 //where 1672 /** Return the target of a break or continue statement, if it exists, 1673 * report an error if not. 1674 * Note: The target of a labelled break or continue is the 1675 * (non-labelled) statement tree referred to by the label, 1676 * not the tree representing the labelled statement itself. 1677 * 1678 * @param pos The position to be used for error diagnostics 1679 * @param tag The tag of the jump statement. This is either 1680 * Tree.BREAK or Tree.CONTINUE. 1681 * @param label The label of the jump statement, or null if no 1682 * label is given. 1683 * @param env The environment current at the jump statement. 1684 */ 1685 private JCTree findJumpTarget(DiagnosticPosition pos, 1686 JCTree.Tag tag, 1687 Name label, 1688 Env<AttrContext> env) { 1689 // Search environments outwards from the point of jump. 1690 Env<AttrContext> env1 = env; 1691 LOOP: 1692 while (env1 != null) { 1693 switch (env1.tree.getTag()) { 1694 case LABELLED: 1695 JCLabeledStatement labelled = (JCLabeledStatement)env1.tree; 1696 if (label == labelled.label) { 1697 // If jump is a continue, check that target is a loop. 1698 if (tag == CONTINUE) { 1699 if (!labelled.body.hasTag(DOLOOP) && 1700 !labelled.body.hasTag(WHILELOOP) && 1701 !labelled.body.hasTag(FORLOOP) && 1702 !labelled.body.hasTag(FOREACHLOOP)) 1703 log.error(pos, "not.loop.label", label); 1704 // Found labelled statement target, now go inwards 1705 // to next non-labelled tree. 1706 return TreeInfo.referencedStatement(labelled); 1707 } else { 1708 return labelled; 1709 } 1710 } 1711 break; 1712 case DOLOOP: 1713 case WHILELOOP: 1714 case FORLOOP: 1715 case FOREACHLOOP: 1716 if (label == null) return env1.tree; 1717 break; 1718 case SWITCH: 1719 if (label == null && tag == BREAK) return env1.tree; 1720 break; 1721 case LAMBDA: 1722 case METHODDEF: 1723 case CLASSDEF: 1724 break LOOP; 1725 default: 1726 } 1727 env1 = env1.next; 1728 } 1729 if (label != null) 1730 log.error(pos, "undef.label", label); 1731 else if (tag == CONTINUE) 1732 log.error(pos, "cont.outside.loop"); 1733 else 1734 log.error(pos, "break.outside.switch.loop"); 1735 return null; 1736 } 1737 1738 public void visitReturn(JCReturn tree) { 1739 // Check that there is an enclosing method which is 1740 // nested within than the enclosing class. 1741 if (env.info.returnResult == null) { 1742 log.error(tree.pos(), "ret.outside.meth"); 1743 } else { 1744 // Attribute return expression, if it exists, and check that 1745 // it conforms to result type of enclosing method. 1746 if (tree.expr != null) { 1747 if (env.info.returnResult.pt.hasTag(VOID)) { 1748 env.info.returnResult.checkContext.report(tree.expr.pos(), 1749 diags.fragment("unexpected.ret.val")); 1750 } 1751 attribTree(tree.expr, env, env.info.returnResult); 1752 } else if (!env.info.returnResult.pt.hasTag(VOID) && 1753 !env.info.returnResult.pt.hasTag(NONE)) { 1754 env.info.returnResult.checkContext.report(tree.pos(), 1755 diags.fragment("missing.ret.val")); 1756 } 1757 } 1758 result = null; 1759 } 1760 1761 public void visitThrow(JCThrow tree) { 1762 Type owntype = attribExpr(tree.expr, env, allowPoly ? Type.noType : syms.throwableType); 1763 if (allowPoly) { 1764 chk.checkType(tree, owntype, syms.throwableType); 1765 } 1766 result = null; 1767 } 1768 1769 public void visitAssert(JCAssert tree) { 1770 attribExpr(tree.cond, env, syms.booleanType); 1771 if (tree.detail != null) { 1772 chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env)); 1773 } 1774 result = null; 1775 } 1776 1777 /** Visitor method for method invocations. 1778 * NOTE: The method part of an application will have in its type field 1779 * the return type of the method, not the method's type itself! 1780 */ 1781 public void visitApply(JCMethodInvocation tree) { 1782 // The local environment of a method application is 1783 // a new environment nested in the current one. 1784 Env<AttrContext> localEnv = env.dup(tree, env.info.dup()); 1785 1786 // The types of the actual method arguments. 1787 List<Type> argtypes; 1788 1789 // The types of the actual method type arguments. 1790 List<Type> typeargtypes = null; 1791 1792 Name methName = TreeInfo.name(tree.meth); 1793 1794 boolean isConstructorCall = 1795 methName == names._this || methName == names._super; 1796 1797 ListBuffer<Type> argtypesBuf = new ListBuffer<>(); 1798 if (isConstructorCall) { 1799 // We are seeing a ...this(...) or ...super(...) call. 1800 // Check that this is the first statement in a constructor. 1801 if (checkFirstConstructorStat(tree, env)) { 1802 1803 // Record the fact 1804 // that this is a constructor call (using isSelfCall). 1805 localEnv.info.isSelfCall = true; 1806 1807 // Attribute arguments, yielding list of argument types. 1808 KindSelector kind = attribArgs(KindSelector.MTH, tree.args, localEnv, argtypesBuf); 1809 argtypes = argtypesBuf.toList(); 1810 typeargtypes = attribTypes(tree.typeargs, localEnv); 1811 1812 // Variable `site' points to the class in which the called 1813 // constructor is defined. 1814 Type site = env.enclClass.sym.type; 1815 if (methName == names._super) { 1816 if (site == syms.objectType) { 1817 log.error(tree.meth.pos(), "no.superclass", site); 1818 site = types.createErrorType(syms.objectType); 1819 } else { 1820 site = types.supertype(site); 1821 } 1822 } 1823 1824 if (site.hasTag(CLASS)) { 1825 Type encl = site.getEnclosingType(); 1826 while (encl != null && encl.hasTag(TYPEVAR)) 1827 encl = encl.getUpperBound(); 1828 if (encl.hasTag(CLASS)) { 1829 // we are calling a nested class 1830 1831 if (tree.meth.hasTag(SELECT)) { 1832 JCTree qualifier = ((JCFieldAccess) tree.meth).selected; 1833 1834 // We are seeing a prefixed call, of the form 1835 // <expr>.super(...). 1836 // Check that the prefix expression conforms 1837 // to the outer instance type of the class. 1838 chk.checkRefType(qualifier.pos(), 1839 attribExpr(qualifier, localEnv, 1840 encl)); 1841 } else if (methName == names._super) { 1842 // qualifier omitted; check for existence 1843 // of an appropriate implicit qualifier. 1844 rs.resolveImplicitThis(tree.meth.pos(), 1845 localEnv, site, true); 1846 } 1847 } else if (tree.meth.hasTag(SELECT)) { 1848 log.error(tree.meth.pos(), "illegal.qual.not.icls", 1849 site.tsym); 1850 } 1851 1852 // if we're calling a java.lang.Enum constructor, 1853 // prefix the implicit String and int parameters 1854 if (site.tsym == syms.enumSym) 1855 argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType); 1856 1857 // Resolve the called constructor under the assumption 1858 // that we are referring to a superclass instance of the 1859 // current instance (JLS ???). 1860 boolean selectSuperPrev = localEnv.info.selectSuper; 1861 localEnv.info.selectSuper = true; 1862 localEnv.info.pendingResolutionPhase = null; 1863 Symbol sym = rs.resolveConstructor( 1864 tree.meth.pos(), localEnv, site, argtypes, typeargtypes); 1865 localEnv.info.selectSuper = selectSuperPrev; 1866 1867 // Set method symbol to resolved constructor... 1868 TreeInfo.setSymbol(tree.meth, sym); 1869 1870 // ...and check that it is legal in the current context. 1871 // (this will also set the tree's type) 1872 Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes); 1873 checkId(tree.meth, site, sym, localEnv, 1874 new ResultInfo(kind, mpt)); 1875 } 1876 // Otherwise, `site' is an error type and we do nothing 1877 } 1878 result = tree.type = syms.voidType; 1879 } else { 1880 // Otherwise, we are seeing a regular method call. 1881 // Attribute the arguments, yielding list of argument types, ... 1882 KindSelector kind = attribArgs(KindSelector.VAL, tree.args, localEnv, argtypesBuf); 1883 argtypes = argtypesBuf.toList(); 1884 typeargtypes = attribAnyTypes(tree.typeargs, localEnv); 1885 1886 // ... and attribute the method using as a prototype a methodtype 1887 // whose formal argument types is exactly the list of actual 1888 // arguments (this will also set the method symbol). 1889 Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes); 1890 localEnv.info.pendingResolutionPhase = null; 1891 Type mtype = attribTree(tree.meth, localEnv, new ResultInfo(kind, mpt, resultInfo.checkContext)); 1892 1893 // Compute the result type. 1894 Type restype = mtype.getReturnType(); 1895 if (restype.hasTag(WILDCARD)) 1896 throw new AssertionError(mtype); 1897 1898 Type qualifier = (tree.meth.hasTag(SELECT)) 1899 ? ((JCFieldAccess) tree.meth).selected.type 1900 : env.enclClass.sym.type; 1901 restype = adjustMethodReturnType(qualifier, methName, argtypes, restype); 1902 1903 chk.checkRefTypes(tree.typeargs, typeargtypes); 1904 1905 // Check that value of resulting type is admissible in the 1906 // current context. Also, capture the return type 1907 Type capturedRes = resultInfo.checkContext.inferenceContext().cachedCapture(tree, restype, true); 1908 result = check(tree, capturedRes, KindSelector.VAL, resultInfo); 1909 } 1910 chk.validate(tree.typeargs, localEnv); 1911 } 1912 //where 1913 Type adjustMethodReturnType(Type qualifierType, Name methodName, List<Type> argtypes, Type restype) { 1914 if (methodName == names.clone && types.isArray(qualifierType)) { 1915 // as a special case, array.clone() has a result that is 1916 // the same as static type of the array being cloned 1917 return qualifierType; 1918 } else if (methodName == names.getClass && argtypes.isEmpty()) { 1919 // as a special case, x.getClass() has type Class<? extends |X|> 1920 return new ClassType(restype.getEnclosingType(), 1921 List.<Type>of(new WildcardType(types.erasure(qualifierType), 1922 BoundKind.EXTENDS, 1923 syms.boundClass)), 1924 restype.tsym, 1925 restype.getMetadata()); 1926 } else { 1927 return restype; 1928 } 1929 } 1930 1931 /** Check that given application node appears as first statement 1932 * in a constructor call. 1933 * @param tree The application node 1934 * @param env The environment current at the application. 1935 */ 1936 boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) { 1937 JCMethodDecl enclMethod = env.enclMethod; 1938 if (enclMethod != null && enclMethod.name == names.init) { 1939 JCBlock body = enclMethod.body; 1940 if (body.stats.head.hasTag(EXEC) && 1941 ((JCExpressionStatement) body.stats.head).expr == tree) 1942 return true; 1943 } 1944 log.error(tree.pos(),"call.must.be.first.stmt.in.ctor", 1945 TreeInfo.name(tree.meth)); 1946 return false; 1947 } 1948 1949 /** Obtain a method type with given argument types. 1950 */ 1951 Type newMethodTemplate(Type restype, List<Type> argtypes, List<Type> typeargtypes) { 1952 MethodType mt = new MethodType(argtypes, restype, List.<Type>nil(), syms.methodClass); 1953 return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt); 1954 } 1955 1956 public void visitNewClass(final JCNewClass tree) { 1957 Type owntype = types.createErrorType(tree.type); 1958 1959 // The local environment of a class creation is 1960 // a new environment nested in the current one. 1961 Env<AttrContext> localEnv = env.dup(tree, env.info.dup()); 1962 1963 // The anonymous inner class definition of the new expression, 1964 // if one is defined by it. 1965 JCClassDecl cdef = tree.def; 1966 1967 // If enclosing class is given, attribute it, and 1968 // complete class name to be fully qualified 1969 JCExpression clazz = tree.clazz; // Class field following new 1970 JCExpression clazzid; // Identifier in class field 1971 JCAnnotatedType annoclazzid; // Annotated type enclosing clazzid 1972 annoclazzid = null; 1973 1974 if (clazz.hasTag(TYPEAPPLY)) { 1975 clazzid = ((JCTypeApply) clazz).clazz; 1976 if (clazzid.hasTag(ANNOTATED_TYPE)) { 1977 annoclazzid = (JCAnnotatedType) clazzid; 1978 clazzid = annoclazzid.underlyingType; 1979 } 1980 } else { 1981 if (clazz.hasTag(ANNOTATED_TYPE)) { 1982 annoclazzid = (JCAnnotatedType) clazz; 1983 clazzid = annoclazzid.underlyingType; 1984 } else { 1985 clazzid = clazz; 1986 } 1987 } 1988 1989 JCExpression clazzid1 = clazzid; // The same in fully qualified form 1990 1991 if (tree.encl != null) { 1992 // We are seeing a qualified new, of the form 1993 // <expr>.new C <...> (...) ... 1994 // In this case, we let clazz stand for the name of the 1995 // allocated class C prefixed with the type of the qualifier 1996 // expression, so that we can 1997 // resolve it with standard techniques later. I.e., if 1998 // <expr> has type T, then <expr>.new C <...> (...) 1999 // yields a clazz T.C. 2000 Type encltype = chk.checkRefType(tree.encl.pos(), 2001 attribExpr(tree.encl, env)); 2002 // TODO 308: in <expr>.new C, do we also want to add the type annotations 2003 // from expr to the combined type, or not? Yes, do this. 2004 clazzid1 = make.at(clazz.pos).Select(make.Type(encltype), 2005 ((JCIdent) clazzid).name); 2006 2007 EndPosTable endPosTable = this.env.toplevel.endPositions; 2008 endPosTable.storeEnd(clazzid1, tree.getEndPosition(endPosTable)); 2009 if (clazz.hasTag(ANNOTATED_TYPE)) { 2010 JCAnnotatedType annoType = (JCAnnotatedType) clazz; 2011 List<JCAnnotation> annos = annoType.annotations; 2012 2013 if (annoType.underlyingType.hasTag(TYPEAPPLY)) { 2014 clazzid1 = make.at(tree.pos). 2015 TypeApply(clazzid1, 2016 ((JCTypeApply) clazz).arguments); 2017 } 2018 2019 clazzid1 = make.at(tree.pos). 2020 AnnotatedType(annos, clazzid1); 2021 } else if (clazz.hasTag(TYPEAPPLY)) { 2022 clazzid1 = make.at(tree.pos). 2023 TypeApply(clazzid1, 2024 ((JCTypeApply) clazz).arguments); 2025 } 2026 2027 clazz = clazzid1; 2028 } 2029 2030 // Attribute clazz expression and store 2031 // symbol + type back into the attributed tree. 2032 Type clazztype; 2033 2034 try { 2035 env.info.isNewClass = true; 2036 clazztype = TreeInfo.isEnumInit(env.tree) ? 2037 attribIdentAsEnumType(env, (JCIdent)clazz) : 2038 attribType(clazz, env); 2039 } finally { 2040 env.info.isNewClass = false; 2041 } 2042 2043 clazztype = chk.checkDiamond(tree, clazztype); 2044 chk.validate(clazz, localEnv); 2045 if (tree.encl != null) { 2046 // We have to work in this case to store 2047 // symbol + type back into the attributed tree. 2048 tree.clazz.type = clazztype; 2049 TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1)); 2050 clazzid.type = ((JCIdent) clazzid).sym.type; 2051 if (annoclazzid != null) { 2052 annoclazzid.type = clazzid.type; 2053 } 2054 if (!clazztype.isErroneous()) { 2055 if (cdef != null && clazztype.tsym.isInterface()) { 2056 log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new"); 2057 } else if (clazztype.tsym.isStatic()) { 2058 log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym); 2059 } 2060 } 2061 } else if (!clazztype.tsym.isInterface() && 2062 clazztype.getEnclosingType().hasTag(CLASS)) { 2063 // Check for the existence of an apropos outer instance 2064 rs.resolveImplicitThis(tree.pos(), env, clazztype); 2065 } 2066 2067 // Attribute constructor arguments. 2068 ListBuffer<Type> argtypesBuf = new ListBuffer<>(); 2069 final KindSelector pkind = 2070 attribArgs(KindSelector.VAL, tree.args, localEnv, argtypesBuf); 2071 List<Type> argtypes = argtypesBuf.toList(); 2072 List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv); 2073 2074 // If we have made no mistakes in the class type... 2075 if (clazztype.hasTag(CLASS)) { 2076 // Enums may not be instantiated except implicitly 2077 if ((clazztype.tsym.flags_field & Flags.ENUM) != 0 && 2078 (!env.tree.hasTag(VARDEF) || 2079 (((JCVariableDecl) env.tree).mods.flags & Flags.ENUM) == 0 || 2080 ((JCVariableDecl) env.tree).init != tree)) 2081 log.error(tree.pos(), "enum.cant.be.instantiated"); 2082 2083 boolean isSpeculativeDiamondInferenceRound = TreeInfo.isDiamond(tree) && 2084 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE; 2085 boolean skipNonDiamondPath = false; 2086 // Check that class is not abstract 2087 if (cdef == null && !isSpeculativeDiamondInferenceRound && // class body may be nulled out in speculative tree copy 2088 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) { 2089 log.error(tree.pos(), "abstract.cant.be.instantiated", 2090 clazztype.tsym); 2091 skipNonDiamondPath = true; 2092 } else if (cdef != null && clazztype.tsym.isInterface()) { 2093 // Check that no constructor arguments are given to 2094 // anonymous classes implementing an interface 2095 if (!argtypes.isEmpty()) 2096 log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args"); 2097 2098 if (!typeargtypes.isEmpty()) 2099 log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs"); 2100 2101 // Error recovery: pretend no arguments were supplied. 2102 argtypes = List.nil(); 2103 typeargtypes = List.nil(); 2104 skipNonDiamondPath = true; 2105 } 2106 if (TreeInfo.isDiamond(tree)) { 2107 ClassType site = new ClassType(clazztype.getEnclosingType(), 2108 clazztype.tsym.type.getTypeArguments(), 2109 clazztype.tsym, 2110 clazztype.getMetadata()); 2111 2112 Env<AttrContext> diamondEnv = localEnv.dup(tree); 2113 diamondEnv.info.selectSuper = cdef != null; 2114 diamondEnv.info.pendingResolutionPhase = null; 2115 2116 //if the type of the instance creation expression is a class type 2117 //apply method resolution inference (JLS 15.12.2.7). The return type 2118 //of the resolved constructor will be a partially instantiated type 2119 Symbol constructor = rs.resolveDiamond(tree.pos(), 2120 diamondEnv, 2121 site, 2122 argtypes, 2123 typeargtypes); 2124 tree.constructor = constructor.baseSymbol(); 2125 2126 final TypeSymbol csym = clazztype.tsym; 2127 ResultInfo diamondResult = new ResultInfo(pkind, newMethodTemplate(resultInfo.pt, argtypes, typeargtypes), 2128 diamondContext(tree, csym, resultInfo.checkContext), CheckMode.NO_TREE_UPDATE); 2129 Type constructorType = tree.constructorType = types.createErrorType(clazztype); 2130 constructorType = checkId(tree, site, 2131 constructor, 2132 diamondEnv, 2133 diamondResult); 2134 2135 tree.clazz.type = types.createErrorType(clazztype); 2136 if (!constructorType.isErroneous()) { 2137 tree.clazz.type = clazz.type = constructorType.getReturnType(); 2138 tree.constructorType = types.createMethodTypeWithReturn(constructorType, syms.voidType); 2139 } 2140 clazztype = chk.checkClassType(tree.clazz, tree.clazz.type, true); 2141 } 2142 2143 // Resolve the called constructor under the assumption 2144 // that we are referring to a superclass instance of the 2145 // current instance (JLS ???). 2146 else if (!skipNonDiamondPath) { 2147 //the following code alters some of the fields in the current 2148 //AttrContext - hence, the current context must be dup'ed in 2149 //order to avoid downstream failures 2150 Env<AttrContext> rsEnv = localEnv.dup(tree); 2151 rsEnv.info.selectSuper = cdef != null; 2152 rsEnv.info.pendingResolutionPhase = null; 2153 tree.constructor = rs.resolveConstructor( 2154 tree.pos(), rsEnv, clazztype, argtypes, typeargtypes); 2155 if (cdef == null) { //do not check twice! 2156 tree.constructorType = checkId(tree, 2157 clazztype, 2158 tree.constructor, 2159 rsEnv, 2160 new ResultInfo(pkind, newMethodTemplate(syms.voidType, argtypes, typeargtypes), CheckMode.NO_TREE_UPDATE)); 2161 if (rsEnv.info.lastResolveVarargs()) 2162 Assert.check(tree.constructorType.isErroneous() || tree.varargsElement != null); 2163 } 2164 } 2165 2166 if (cdef != null) { 2167 visitAnonymousClassDefinition(tree, clazz, clazztype, cdef, localEnv, argtypes, typeargtypes, pkind); 2168 return; 2169 } 2170 2171 if (tree.constructor != null && tree.constructor.kind == MTH) 2172 owntype = clazztype; 2173 } 2174 result = check(tree, owntype, KindSelector.VAL, resultInfo); 2175 InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext(); 2176 if (tree.constructorType != null && inferenceContext.free(tree.constructorType)) { 2177 //we need to wait for inference to finish and then replace inference vars in the constructor type 2178 inferenceContext.addFreeTypeListener(List.of(tree.constructorType), 2179 instantiatedContext -> { 2180 tree.constructorType = instantiatedContext.asInstType(tree.constructorType); 2181 }); 2182 } 2183 chk.validate(tree.typeargs, localEnv); 2184 } 2185 2186 // where 2187 private void visitAnonymousClassDefinition(JCNewClass tree, JCExpression clazz, Type clazztype, 2188 JCClassDecl cdef, Env<AttrContext> localEnv, 2189 List<Type> argtypes, List<Type> typeargtypes, 2190 KindSelector pkind) { 2191 // We are seeing an anonymous class instance creation. 2192 // In this case, the class instance creation 2193 // expression 2194 // 2195 // E.new <typeargs1>C<typargs2>(args) { ... } 2196 // 2197 // is represented internally as 2198 // 2199 // E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } ) . 2200 // 2201 // This expression is then *transformed* as follows: 2202 // 2203 // (1) add an extends or implements clause 2204 // (2) add a constructor. 2205 // 2206 // For instance, if C is a class, and ET is the type of E, 2207 // the expression 2208 // 2209 // E.new <typeargs1>C<typargs2>(args) { ... } 2210 // 2211 // is translated to (where X is a fresh name and typarams is the 2212 // parameter list of the super constructor): 2213 // 2214 // new <typeargs1>X(<*nullchk*>E, args) where 2215 // X extends C<typargs2> { 2216 // <typarams> X(ET e, args) { 2217 // e.<typeargs1>super(args) 2218 // } 2219 // ... 2220 // } 2221 InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext(); 2222 final boolean isDiamond = TreeInfo.isDiamond(tree); 2223 if (isDiamond 2224 && ((tree.constructorType != null && inferenceContext.free(tree.constructorType)) 2225 || (tree.clazz.type != null && inferenceContext.free(tree.clazz.type)))) { 2226 final ResultInfo resultInfoForClassDefinition = this.resultInfo; 2227 inferenceContext.addFreeTypeListener(List.of(tree.constructorType, tree.clazz.type), 2228 instantiatedContext -> { 2229 tree.constructorType = instantiatedContext.asInstType(tree.constructorType); 2230 tree.clazz.type = clazz.type = instantiatedContext.asInstType(clazz.type); 2231 ResultInfo prevResult = this.resultInfo; 2232 try { 2233 this.resultInfo = resultInfoForClassDefinition; 2234 visitAnonymousClassDefinition(tree, clazz, clazz.type, cdef, 2235 localEnv, argtypes, typeargtypes, pkind); 2236 } finally { 2237 this.resultInfo = prevResult; 2238 } 2239 }); 2240 } else { 2241 if (isDiamond && clazztype.hasTag(CLASS)) { 2242 List<Type> invalidDiamondArgs = chk.checkDiamondDenotable((ClassType)clazztype); 2243 if (!clazztype.isErroneous() && invalidDiamondArgs.nonEmpty()) { 2244 // One or more types inferred in the previous steps is non-denotable. 2245 Fragment fragment = Diamond(clazztype.tsym); 2246 log.error(tree.clazz.pos(), 2247 Errors.CantApplyDiamond1( 2248 fragment, 2249 invalidDiamondArgs.size() > 1 ? 2250 DiamondInvalidArgs(invalidDiamondArgs, fragment) : 2251 DiamondInvalidArg(invalidDiamondArgs, fragment))); 2252 } 2253 // For <>(){}, inferred types must also be accessible. 2254 for (Type t : clazztype.getTypeArguments()) { 2255 rs.checkAccessibleType(env, t); 2256 } 2257 } 2258 2259 // If we already errored, be careful to avoid a further avalanche. ErrorType answers 2260 // false for isInterface call even when the original type is an interface. 2261 boolean implementing = clazztype.tsym.isInterface() || 2262 clazztype.isErroneous() && clazztype.getOriginalType().tsym.isInterface(); 2263 2264 if (implementing) { 2265 cdef.implementing = List.of(clazz); 2266 } else { 2267 cdef.extending = clazz; 2268 } 2269 2270 if (resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK && 2271 isSerializable(clazztype)) { 2272 localEnv.info.isSerializable = true; 2273 } 2274 2275 attribStat(cdef, localEnv); 2276 2277 List<Type> finalargtypes; 2278 // If an outer instance is given, 2279 // prefix it to the constructor arguments 2280 // and delete it from the new expression 2281 if (tree.encl != null && !clazztype.tsym.isInterface()) { 2282 tree.args = tree.args.prepend(makeNullCheck(tree.encl)); 2283 finalargtypes = argtypes.prepend(tree.encl.type); 2284 tree.encl = null; 2285 } else { 2286 finalargtypes = argtypes; 2287 } 2288 2289 // Reassign clazztype and recompute constructor. As this necessarily involves 2290 // another attribution pass for deferred types in the case of <>, replicate 2291 // them. Original arguments have right decorations already. 2292 if (isDiamond && pkind.contains(KindSelector.POLY)) { 2293 finalargtypes = finalargtypes.map(deferredAttr.deferredCopier); 2294 } 2295 2296 clazztype = cdef.sym.type; 2297 Symbol sym = tree.constructor = rs.resolveConstructor( 2298 tree.pos(), localEnv, clazztype, finalargtypes, typeargtypes); 2299 Assert.check(!sym.kind.isResolutionError()); 2300 tree.constructor = sym; 2301 tree.constructorType = checkId(tree, 2302 clazztype, 2303 tree.constructor, 2304 localEnv, 2305 new ResultInfo(pkind, newMethodTemplate(syms.voidType, finalargtypes, typeargtypes), CheckMode.NO_TREE_UPDATE)); 2306 } 2307 Type owntype = (tree.constructor != null && tree.constructor.kind == MTH) ? 2308 clazztype : types.createErrorType(tree.type); 2309 result = check(tree, owntype, KindSelector.VAL, resultInfo.dup(CheckMode.NO_INFERENCE_HOOK)); 2310 chk.validate(tree.typeargs, localEnv); 2311 } 2312 2313 CheckContext diamondContext(JCNewClass clazz, TypeSymbol tsym, CheckContext checkContext) { 2314 return new Check.NestedCheckContext(checkContext) { 2315 @Override 2316 public void report(DiagnosticPosition _unused, JCDiagnostic details) { 2317 enclosingContext.report(clazz.clazz, 2318 diags.fragment("cant.apply.diamond.1", diags.fragment("diamond", tsym), details)); 2319 } 2320 }; 2321 } 2322 2323 /** Make an attributed null check tree. 2324 */ 2325 public JCExpression makeNullCheck(JCExpression arg) { 2326 // optimization: X.this is never null; skip null check 2327 Name name = TreeInfo.name(arg); 2328 if (name == names._this || name == names._super) return arg; 2329 2330 JCTree.Tag optag = NULLCHK; 2331 JCUnary tree = make.at(arg.pos).Unary(optag, arg); 2332 tree.operator = operators.resolveUnary(arg, optag, arg.type); 2333 tree.type = arg.type; 2334 return tree; 2335 } 2336 2337 public void visitNewArray(JCNewArray tree) { 2338 Type owntype = types.createErrorType(tree.type); 2339 Env<AttrContext> localEnv = env.dup(tree); 2340 Type elemtype; 2341 if (tree.elemtype != null) { 2342 elemtype = attribType(tree.elemtype, localEnv); 2343 chk.validate(tree.elemtype, localEnv); 2344 owntype = elemtype; 2345 for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) { 2346 attribExpr(l.head, localEnv, syms.intType); 2347 owntype = new ArrayType(owntype, syms.arrayClass); 2348 } 2349 } else { 2350 // we are seeing an untyped aggregate { ... } 2351 // this is allowed only if the prototype is an array 2352 if (pt().hasTag(ARRAY)) { 2353 elemtype = types.elemtype(pt()); 2354 } else { 2355 if (!pt().hasTag(ERROR)) { 2356 log.error(tree.pos(), "illegal.initializer.for.type", 2357 pt()); 2358 } 2359 elemtype = types.createErrorType(pt()); 2360 } 2361 } 2362 if (tree.elems != null) { 2363 attribExprs(tree.elems, localEnv, elemtype); 2364 owntype = new ArrayType(elemtype, syms.arrayClass); 2365 } 2366 if (!types.isReifiable(elemtype)) 2367 log.error(tree.pos(), "generic.array.creation"); 2368 result = check(tree, owntype, KindSelector.VAL, resultInfo); 2369 } 2370 2371 /* 2372 * A lambda expression can only be attributed when a target-type is available. 2373 * In addition, if the target-type is that of a functional interface whose 2374 * descriptor contains inference variables in argument position the lambda expression 2375 * is 'stuck' (see DeferredAttr). 2376 */ 2377 @Override 2378 public void visitLambda(final JCLambda that) { 2379 if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) { 2380 if (pt().hasTag(NONE)) { 2381 //lambda only allowed in assignment or method invocation/cast context 2382 log.error(that.pos(), "unexpected.lambda"); 2383 } 2384 result = that.type = types.createErrorType(pt()); 2385 return; 2386 } 2387 //create an environment for attribution of the lambda expression 2388 final Env<AttrContext> localEnv = lambdaEnv(that, env); 2389 boolean needsRecovery = 2390 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK; 2391 try { 2392 if (needsRecovery && isSerializable(pt())) { 2393 localEnv.info.isSerializable = true; 2394 } 2395 List<Type> explicitParamTypes = null; 2396 if (that.paramKind == JCLambda.ParameterKind.EXPLICIT) { 2397 //attribute lambda parameters 2398 attribStats(that.params, localEnv); 2399 explicitParamTypes = TreeInfo.types(that.params); 2400 } 2401 2402 TargetInfo targetInfo = getTargetInfo(that, resultInfo, explicitParamTypes); 2403 Type currentTarget = targetInfo.target; 2404 Type lambdaType = targetInfo.descriptor; 2405 2406 if (currentTarget.isErroneous()) { 2407 result = that.type = currentTarget; 2408 return; 2409 } 2410 2411 setFunctionalInfo(localEnv, that, pt(), lambdaType, currentTarget, resultInfo.checkContext); 2412 2413 if (lambdaType.hasTag(FORALL)) { 2414 //lambda expression target desc cannot be a generic method 2415 resultInfo.checkContext.report(that, diags.fragment("invalid.generic.lambda.target", 2416 lambdaType, kindName(currentTarget.tsym), currentTarget.tsym)); 2417 result = that.type = types.createErrorType(pt()); 2418 return; 2419 } 2420 2421 if (that.paramKind == JCLambda.ParameterKind.IMPLICIT) { 2422 //add param type info in the AST 2423 List<Type> actuals = lambdaType.getParameterTypes(); 2424 List<JCVariableDecl> params = that.params; 2425 2426 boolean arityMismatch = false; 2427 2428 while (params.nonEmpty()) { 2429 if (actuals.isEmpty()) { 2430 //not enough actuals to perform lambda parameter inference 2431 arityMismatch = true; 2432 } 2433 //reset previously set info 2434 Type argType = arityMismatch ? 2435 syms.errType : 2436 actuals.head; 2437 params.head.vartype = make.at(params.head).Type(argType); 2438 params.head.sym = null; 2439 actuals = actuals.isEmpty() ? 2440 actuals : 2441 actuals.tail; 2442 params = params.tail; 2443 } 2444 2445 //attribute lambda parameters 2446 attribStats(that.params, localEnv); 2447 2448 if (arityMismatch) { 2449 resultInfo.checkContext.report(that, diags.fragment("incompatible.arg.types.in.lambda")); 2450 result = that.type = types.createErrorType(currentTarget); 2451 return; 2452 } 2453 } 2454 2455 //from this point on, no recovery is needed; if we are in assignment context 2456 //we will be able to attribute the whole lambda body, regardless of errors; 2457 //if we are in a 'check' method context, and the lambda is not compatible 2458 //with the target-type, it will be recovered anyway in Attr.checkId 2459 needsRecovery = false; 2460 2461 ResultInfo bodyResultInfo = localEnv.info.returnResult = 2462 lambdaBodyResult(that, lambdaType, resultInfo); 2463 2464 if (that.getBodyKind() == JCLambda.BodyKind.EXPRESSION) { 2465 attribTree(that.getBody(), localEnv, bodyResultInfo); 2466 } else { 2467 JCBlock body = (JCBlock)that.body; 2468 attribStats(body.stats, localEnv); 2469 } 2470 2471 result = check(that, currentTarget, KindSelector.VAL, resultInfo); 2472 2473 boolean isSpeculativeRound = 2474 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE; 2475 2476 preFlow(that); 2477 flow.analyzeLambda(env, that, make, isSpeculativeRound); 2478 2479 that.type = currentTarget; //avoids recovery at this stage 2480 checkLambdaCompatible(that, lambdaType, resultInfo.checkContext); 2481 2482 if (!isSpeculativeRound) { 2483 //add thrown types as bounds to the thrown types free variables if needed: 2484 if (resultInfo.checkContext.inferenceContext().free(lambdaType.getThrownTypes())) { 2485 List<Type> inferredThrownTypes = flow.analyzeLambdaThrownTypes(env, that, make); 2486 List<Type> thrownTypes = resultInfo.checkContext.inferenceContext().asUndetVars(lambdaType.getThrownTypes()); 2487 2488 chk.unhandled(inferredThrownTypes, thrownTypes); 2489 } 2490 2491 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), lambdaType, currentTarget); 2492 } 2493 result = check(that, currentTarget, KindSelector.VAL, resultInfo); 2494 } catch (Types.FunctionDescriptorLookupError ex) { 2495 JCDiagnostic cause = ex.getDiagnostic(); 2496 resultInfo.checkContext.report(that, cause); 2497 result = that.type = types.createErrorType(pt()); 2498 return; 2499 } catch (Throwable t) { 2500 //when an unexpected exception happens, avoid attempts to attribute the same tree again 2501 //as that would likely cause the same exception again. 2502 needsRecovery = false; 2503 throw t; 2504 } finally { 2505 localEnv.info.scope.leave(); 2506 if (needsRecovery) { 2507 attribTree(that, env, recoveryInfo); 2508 } 2509 } 2510 } 2511 //where 2512 class TargetInfo { 2513 Type target; 2514 Type descriptor; 2515 2516 public TargetInfo(Type target, Type descriptor) { 2517 this.target = target; 2518 this.descriptor = descriptor; 2519 } 2520 } 2521 2522 TargetInfo getTargetInfo(JCPolyExpression that, ResultInfo resultInfo, List<Type> explicitParamTypes) { 2523 Type lambdaType; 2524 Type currentTarget = resultInfo.pt; 2525 if (resultInfo.pt != Type.recoveryType) { 2526 /* We need to adjust the target. If the target is an 2527 * intersection type, for example: SAM & I1 & I2 ... 2528 * the target will be updated to SAM 2529 */ 2530 currentTarget = targetChecker.visit(currentTarget, that); 2531 if (explicitParamTypes != null) { 2532 currentTarget = infer.instantiateFunctionalInterface(that, 2533 currentTarget, explicitParamTypes, resultInfo.checkContext); 2534 } 2535 currentTarget = types.removeWildcards(currentTarget); 2536 lambdaType = types.findDescriptorType(currentTarget); 2537 } else { 2538 currentTarget = Type.recoveryType; 2539 lambdaType = fallbackDescriptorType(that); 2540 } 2541 if (that.hasTag(LAMBDA) && lambdaType.hasTag(FORALL)) { 2542 //lambda expression target desc cannot be a generic method 2543 resultInfo.checkContext.report(that, diags.fragment("invalid.generic.lambda.target", 2544 lambdaType, kindName(currentTarget.tsym), currentTarget.tsym)); 2545 currentTarget = types.createErrorType(pt()); 2546 } 2547 return new TargetInfo(currentTarget, lambdaType); 2548 } 2549 2550 void preFlow(JCLambda tree) { 2551 new PostAttrAnalyzer() { 2552 @Override 2553 public void scan(JCTree tree) { 2554 if (tree == null || 2555 (tree.type != null && 2556 tree.type == Type.stuckType)) { 2557 //don't touch stuck expressions! 2558 return; 2559 } 2560 super.scan(tree); 2561 } 2562 }.scan(tree); 2563 } 2564 2565 Types.MapVisitor<DiagnosticPosition> targetChecker = new Types.MapVisitor<DiagnosticPosition>() { 2566 2567 @Override 2568 public Type visitClassType(ClassType t, DiagnosticPosition pos) { 2569 return t.isIntersection() ? 2570 visitIntersectionClassType((IntersectionClassType)t, pos) : t; 2571 } 2572 2573 public Type visitIntersectionClassType(IntersectionClassType ict, DiagnosticPosition pos) { 2574 Symbol desc = types.findDescriptorSymbol(makeNotionalInterface(ict)); 2575 Type target = null; 2576 for (Type bound : ict.getExplicitComponents()) { 2577 TypeSymbol boundSym = bound.tsym; 2578 if (types.isFunctionalInterface(boundSym) && 2579 types.findDescriptorSymbol(boundSym) == desc) { 2580 target = bound; 2581 } else if (!boundSym.isInterface() || (boundSym.flags() & ANNOTATION) != 0) { 2582 //bound must be an interface 2583 reportIntersectionError(pos, "not.an.intf.component", boundSym); 2584 } 2585 } 2586 return target != null ? 2587 target : 2588 ict.getExplicitComponents().head; //error recovery 2589 } 2590 2591 private TypeSymbol makeNotionalInterface(IntersectionClassType ict) { 2592 ListBuffer<Type> targs = new ListBuffer<>(); 2593 ListBuffer<Type> supertypes = new ListBuffer<>(); 2594 for (Type i : ict.interfaces_field) { 2595 if (i.isParameterized()) { 2596 targs.appendList(i.tsym.type.allparams()); 2597 } 2598 supertypes.append(i.tsym.type); 2599 } 2600 IntersectionClassType notionalIntf = types.makeIntersectionType(supertypes.toList()); 2601 notionalIntf.allparams_field = targs.toList(); 2602 notionalIntf.tsym.flags_field |= INTERFACE; 2603 return notionalIntf.tsym; 2604 } 2605 2606 private void reportIntersectionError(DiagnosticPosition pos, String key, Object... args) { 2607 resultInfo.checkContext.report(pos, diags.fragment("bad.intersection.target.for.functional.expr", 2608 diags.fragment(key, args))); 2609 } 2610 }; 2611 2612 private Type fallbackDescriptorType(JCExpression tree) { 2613 switch (tree.getTag()) { 2614 case LAMBDA: 2615 JCLambda lambda = (JCLambda)tree; 2616 List<Type> argtypes = List.nil(); 2617 for (JCVariableDecl param : lambda.params) { 2618 argtypes = param.vartype != null ? 2619 argtypes.append(param.vartype.type) : 2620 argtypes.append(syms.errType); 2621 } 2622 return new MethodType(argtypes, Type.recoveryType, 2623 List.of(syms.throwableType), syms.methodClass); 2624 case REFERENCE: 2625 return new MethodType(List.<Type>nil(), Type.recoveryType, 2626 List.of(syms.throwableType), syms.methodClass); 2627 default: 2628 Assert.error("Cannot get here!"); 2629 } 2630 return null; 2631 } 2632 2633 private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env, 2634 final InferenceContext inferenceContext, final Type... ts) { 2635 checkAccessibleTypes(pos, env, inferenceContext, List.from(ts)); 2636 } 2637 2638 private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env, 2639 final InferenceContext inferenceContext, final List<Type> ts) { 2640 if (inferenceContext.free(ts)) { 2641 inferenceContext.addFreeTypeListener(ts, new FreeTypeListener() { 2642 @Override 2643 public void typesInferred(InferenceContext inferenceContext) { 2644 checkAccessibleTypes(pos, env, inferenceContext, inferenceContext.asInstTypes(ts)); 2645 } 2646 }); 2647 } else { 2648 for (Type t : ts) { 2649 rs.checkAccessibleType(env, t); 2650 } 2651 } 2652 } 2653 2654 /** 2655 * Lambda/method reference have a special check context that ensures 2656 * that i.e. a lambda return type is compatible with the expected 2657 * type according to both the inherited context and the assignment 2658 * context. 2659 */ 2660 class FunctionalReturnContext extends Check.NestedCheckContext { 2661 2662 FunctionalReturnContext(CheckContext enclosingContext) { 2663 super(enclosingContext); 2664 } 2665 2666 @Override 2667 public boolean compatible(Type found, Type req, Warner warn) { 2668 //return type must be compatible in both current context and assignment context 2669 return chk.basicHandler.compatible(found, inferenceContext().asUndetVar(req), warn); 2670 } 2671 2672 @Override 2673 public void report(DiagnosticPosition pos, JCDiagnostic details) { 2674 enclosingContext.report(pos, diags.fragment("incompatible.ret.type.in.lambda", details)); 2675 } 2676 } 2677 2678 class ExpressionLambdaReturnContext extends FunctionalReturnContext { 2679 2680 JCExpression expr; 2681 boolean expStmtExpected; 2682 2683 ExpressionLambdaReturnContext(JCExpression expr, CheckContext enclosingContext) { 2684 super(enclosingContext); 2685 this.expr = expr; 2686 } 2687 2688 @Override 2689 public void report(DiagnosticPosition pos, JCDiagnostic details) { 2690 if (expStmtExpected) { 2691 enclosingContext.report(pos, diags.fragment(Fragments.StatExprExpected)); 2692 } else { 2693 super.report(pos, details); 2694 } 2695 } 2696 2697 @Override 2698 public boolean compatible(Type found, Type req, Warner warn) { 2699 //a void return is compatible with an expression statement lambda 2700 if (req.hasTag(VOID)) { 2701 expStmtExpected = true; 2702 return TreeInfo.isExpressionStatement(expr); 2703 } else { 2704 return super.compatible(found, req, warn); 2705 } 2706 } 2707 } 2708 2709 ResultInfo lambdaBodyResult(JCLambda that, Type descriptor, ResultInfo resultInfo) { 2710 FunctionalReturnContext funcContext = that.getBodyKind() == JCLambda.BodyKind.EXPRESSION ? 2711 new ExpressionLambdaReturnContext((JCExpression)that.getBody(), resultInfo.checkContext) : 2712 new FunctionalReturnContext(resultInfo.checkContext); 2713 2714 return descriptor.getReturnType() == Type.recoveryType ? 2715 recoveryInfo : 2716 new ResultInfo(KindSelector.VAL, 2717 descriptor.getReturnType(), funcContext); 2718 } 2719 2720 /** 2721 * Lambda compatibility. Check that given return types, thrown types, parameter types 2722 * are compatible with the expected functional interface descriptor. This means that: 2723 * (i) parameter types must be identical to those of the target descriptor; (ii) return 2724 * types must be compatible with the return type of the expected descriptor. 2725 */ 2726 void checkLambdaCompatible(JCLambda tree, Type descriptor, CheckContext checkContext) { 2727 Type returnType = checkContext.inferenceContext().asUndetVar(descriptor.getReturnType()); 2728 2729 //return values have already been checked - but if lambda has no return 2730 //values, we must ensure that void/value compatibility is correct; 2731 //this amounts at checking that, if a lambda body can complete normally, 2732 //the descriptor's return type must be void 2733 if (tree.getBodyKind() == JCLambda.BodyKind.STATEMENT && tree.canCompleteNormally && 2734 !returnType.hasTag(VOID) && returnType != Type.recoveryType) { 2735 checkContext.report(tree, diags.fragment("incompatible.ret.type.in.lambda", 2736 diags.fragment("missing.ret.val", returnType))); 2737 } 2738 2739 List<Type> argTypes = checkContext.inferenceContext().asUndetVars(descriptor.getParameterTypes()); 2740 if (!types.isSameTypes(argTypes, TreeInfo.types(tree.params))) { 2741 checkContext.report(tree, diags.fragment("incompatible.arg.types.in.lambda")); 2742 } 2743 } 2744 2745 /* Map to hold 'fake' clinit methods. If a lambda is used to initialize a 2746 * static field and that lambda has type annotations, these annotations will 2747 * also be stored at these fake clinit methods. 2748 * 2749 * LambdaToMethod also use fake clinit methods so they can be reused. 2750 * Also as LTM is a phase subsequent to attribution, the methods from 2751 * clinits can be safely removed by LTM to save memory. 2752 */ 2753 private Map<ClassSymbol, MethodSymbol> clinits = new HashMap<>(); 2754 2755 public MethodSymbol removeClinit(ClassSymbol sym) { 2756 return clinits.remove(sym); 2757 } 2758 2759 /* This method returns an environment to be used to attribute a lambda 2760 * expression. 2761 * 2762 * The owner of this environment is a method symbol. If the current owner 2763 * is not a method, for example if the lambda is used to initialize 2764 * a field, then if the field is: 2765 * 2766 * - an instance field, we use the first constructor. 2767 * - a static field, we create a fake clinit method. 2768 */ 2769 public Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) { 2770 Env<AttrContext> lambdaEnv; 2771 Symbol owner = env.info.scope.owner; 2772 if (owner.kind == VAR && owner.owner.kind == TYP) { 2773 //field initializer 2774 ClassSymbol enclClass = owner.enclClass(); 2775 Symbol newScopeOwner = env.info.scope.owner; 2776 /* if the field isn't static, then we can get the first constructor 2777 * and use it as the owner of the environment. This is what 2778 * LTM code is doing to look for type annotations so we are fine. 2779 */ 2780 if ((owner.flags() & STATIC) == 0) { 2781 for (Symbol s : enclClass.members_field.getSymbolsByName(names.init)) { 2782 newScopeOwner = s; 2783 break; 2784 } 2785 } else { 2786 /* if the field is static then we need to create a fake clinit 2787 * method, this method can later be reused by LTM. 2788 */ 2789 MethodSymbol clinit = clinits.get(enclClass); 2790 if (clinit == null) { 2791 Type clinitType = new MethodType(List.<Type>nil(), 2792 syms.voidType, List.<Type>nil(), syms.methodClass); 2793 clinit = new MethodSymbol(STATIC | SYNTHETIC | PRIVATE, 2794 names.clinit, clinitType, enclClass); 2795 clinit.params = List.<VarSymbol>nil(); 2796 clinits.put(enclClass, clinit); 2797 } 2798 newScopeOwner = clinit; 2799 } 2800 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared(newScopeOwner))); 2801 } else { 2802 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dup())); 2803 } 2804 return lambdaEnv; 2805 } 2806 2807 @Override 2808 public void visitReference(final JCMemberReference that) { 2809 if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) { 2810 if (pt().hasTag(NONE)) { 2811 //method reference only allowed in assignment or method invocation/cast context 2812 log.error(that.pos(), "unexpected.mref"); 2813 } 2814 result = that.type = types.createErrorType(pt()); 2815 return; 2816 } 2817 final Env<AttrContext> localEnv = env.dup(that); 2818 try { 2819 //attribute member reference qualifier - if this is a constructor 2820 //reference, the expected kind must be a type 2821 Type exprType = attribTree(that.expr, env, memberReferenceQualifierResult(that)); 2822 2823 if (that.getMode() == JCMemberReference.ReferenceMode.NEW) { 2824 exprType = chk.checkConstructorRefType(that.expr, exprType); 2825 if (!exprType.isErroneous() && 2826 exprType.isRaw() && 2827 that.typeargs != null) { 2828 log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()), 2829 diags.fragment("mref.infer.and.explicit.params")); 2830 exprType = types.createErrorType(exprType); 2831 } 2832 } 2833 2834 if (exprType.isErroneous()) { 2835 //if the qualifier expression contains problems, 2836 //give up attribution of method reference 2837 result = that.type = exprType; 2838 return; 2839 } 2840 2841 if (TreeInfo.isStaticSelector(that.expr, names)) { 2842 //if the qualifier is a type, validate it; raw warning check is 2843 //omitted as we don't know at this stage as to whether this is a 2844 //raw selector (because of inference) 2845 chk.validate(that.expr, env, false); 2846 } else { 2847 Symbol lhsSym = TreeInfo.symbol(that.expr); 2848 localEnv.info.selectSuper = lhsSym != null && lhsSym.name == names._super; 2849 } 2850 //attrib type-arguments 2851 List<Type> typeargtypes = List.nil(); 2852 if (that.typeargs != null) { 2853 typeargtypes = attribTypes(that.typeargs, localEnv); 2854 } 2855 2856 boolean isTargetSerializable = 2857 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK && 2858 isSerializable(pt()); 2859 TargetInfo targetInfo = getTargetInfo(that, resultInfo, null); 2860 Type currentTarget = targetInfo.target; 2861 Type desc = targetInfo.descriptor; 2862 2863 setFunctionalInfo(localEnv, that, pt(), desc, currentTarget, resultInfo.checkContext); 2864 List<Type> argtypes = desc.getParameterTypes(); 2865 Resolve.MethodCheck referenceCheck = rs.resolveMethodCheck; 2866 2867 if (resultInfo.checkContext.inferenceContext().free(argtypes)) { 2868 referenceCheck = rs.new MethodReferenceCheck(resultInfo.checkContext.inferenceContext()); 2869 } 2870 2871 Pair<Symbol, Resolve.ReferenceLookupHelper> refResult = null; 2872 List<Type> saved_undet = resultInfo.checkContext.inferenceContext().save(); 2873 try { 2874 refResult = rs.resolveMemberReference(localEnv, that, that.expr.type, 2875 that.name, argtypes, typeargtypes, referenceCheck, 2876 resultInfo.checkContext.inferenceContext(), rs.basicReferenceChooser); 2877 } finally { 2878 resultInfo.checkContext.inferenceContext().rollback(saved_undet); 2879 } 2880 2881 Symbol refSym = refResult.fst; 2882 Resolve.ReferenceLookupHelper lookupHelper = refResult.snd; 2883 2884 /** this switch will need to go away and be replaced by the new RESOLUTION_TARGET testing 2885 * JDK-8075541 2886 */ 2887 if (refSym.kind != MTH) { 2888 boolean targetError; 2889 switch (refSym.kind) { 2890 case ABSENT_MTH: 2891 case MISSING_ENCL: 2892 targetError = false; 2893 break; 2894 case WRONG_MTH: 2895 case WRONG_MTHS: 2896 case AMBIGUOUS: 2897 case HIDDEN: 2898 case STATICERR: 2899 targetError = true; 2900 break; 2901 default: 2902 Assert.error("unexpected result kind " + refSym.kind); 2903 targetError = false; 2904 } 2905 2906 JCDiagnostic detailsDiag = ((Resolve.ResolveError)refSym.baseSymbol()).getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT, 2907 that, exprType.tsym, exprType, that.name, argtypes, typeargtypes); 2908 2909 JCDiagnostic.DiagnosticType diagKind = targetError ? 2910 JCDiagnostic.DiagnosticType.FRAGMENT : JCDiagnostic.DiagnosticType.ERROR; 2911 2912 JCDiagnostic diag = diags.create(diagKind, log.currentSource(), that, 2913 "invalid.mref", Kinds.kindName(that.getMode()), detailsDiag); 2914 2915 if (targetError && currentTarget == Type.recoveryType) { 2916 //a target error doesn't make sense during recovery stage 2917 //as we don't know what actual parameter types are 2918 result = that.type = currentTarget; 2919 return; 2920 } else { 2921 if (targetError) { 2922 resultInfo.checkContext.report(that, diag); 2923 } else { 2924 log.report(diag); 2925 } 2926 result = that.type = types.createErrorType(currentTarget); 2927 return; 2928 } 2929 } 2930 2931 that.sym = refSym.baseSymbol(); 2932 that.kind = lookupHelper.referenceKind(that.sym); 2933 that.ownerAccessible = rs.isAccessible(localEnv, that.sym.enclClass()); 2934 2935 if (desc.getReturnType() == Type.recoveryType) { 2936 // stop here 2937 result = that.type = currentTarget; 2938 return; 2939 } 2940 2941 if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) { 2942 2943 if (that.getMode() == ReferenceMode.INVOKE && 2944 TreeInfo.isStaticSelector(that.expr, names) && 2945 that.kind.isUnbound() && 2946 !desc.getParameterTypes().head.isParameterized()) { 2947 chk.checkRaw(that.expr, localEnv); 2948 } 2949 2950 if (that.sym.isStatic() && TreeInfo.isStaticSelector(that.expr, names) && 2951 exprType.getTypeArguments().nonEmpty()) { 2952 //static ref with class type-args 2953 log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()), 2954 diags.fragment("static.mref.with.targs")); 2955 result = that.type = types.createErrorType(currentTarget); 2956 return; 2957 } 2958 2959 if (!refSym.isStatic() && that.kind == JCMemberReference.ReferenceKind.SUPER) { 2960 // Check that super-qualified symbols are not abstract (JLS) 2961 rs.checkNonAbstract(that.pos(), that.sym); 2962 } 2963 2964 if (isTargetSerializable) { 2965 chk.checkElemAccessFromSerializableLambda(that); 2966 } 2967 } 2968 2969 ResultInfo checkInfo = 2970 resultInfo.dup(newMethodTemplate( 2971 desc.getReturnType().hasTag(VOID) ? Type.noType : desc.getReturnType(), 2972 that.kind.isUnbound() ? argtypes.tail : argtypes, typeargtypes), 2973 new FunctionalReturnContext(resultInfo.checkContext), CheckMode.NO_TREE_UPDATE); 2974 2975 Type refType = checkId(that, lookupHelper.site, refSym, localEnv, checkInfo); 2976 2977 if (that.kind.isUnbound() && 2978 resultInfo.checkContext.inferenceContext().free(argtypes.head)) { 2979 //re-generate inference constraints for unbound receiver 2980 if (!types.isSubtype(resultInfo.checkContext.inferenceContext().asUndetVar(argtypes.head), exprType)) { 2981 //cannot happen as this has already been checked - we just need 2982 //to regenerate the inference constraints, as that has been lost 2983 //as a result of the call to inferenceContext.save() 2984 Assert.error("Can't get here"); 2985 } 2986 } 2987 2988 if (!refType.isErroneous()) { 2989 refType = types.createMethodTypeWithReturn(refType, 2990 adjustMethodReturnType(lookupHelper.site, that.name, checkInfo.pt.getParameterTypes(), refType.getReturnType())); 2991 } 2992 2993 //go ahead with standard method reference compatibility check - note that param check 2994 //is a no-op (as this has been taken care during method applicability) 2995 boolean isSpeculativeRound = 2996 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE; 2997 2998 that.type = currentTarget; //avoids recovery at this stage 2999 checkReferenceCompatible(that, desc, refType, resultInfo.checkContext, isSpeculativeRound); 3000 if (!isSpeculativeRound) { 3001 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), desc, currentTarget); 3002 } 3003 result = check(that, currentTarget, KindSelector.VAL, resultInfo); 3004 } catch (Types.FunctionDescriptorLookupError ex) { 3005 JCDiagnostic cause = ex.getDiagnostic(); 3006 resultInfo.checkContext.report(that, cause); 3007 result = that.type = types.createErrorType(pt()); 3008 return; 3009 } 3010 } 3011 //where 3012 ResultInfo memberReferenceQualifierResult(JCMemberReference tree) { 3013 //if this is a constructor reference, the expected kind must be a type 3014 return new ResultInfo(tree.getMode() == ReferenceMode.INVOKE ? 3015 KindSelector.VAL_TYP : KindSelector.TYP, 3016 Type.noType); 3017 } 3018 3019 3020 @SuppressWarnings("fallthrough") 3021 void checkReferenceCompatible(JCMemberReference tree, Type descriptor, Type refType, CheckContext checkContext, boolean speculativeAttr) { 3022 InferenceContext inferenceContext = checkContext.inferenceContext(); 3023 Type returnType = inferenceContext.asUndetVar(descriptor.getReturnType()); 3024 3025 Type resType; 3026 switch (tree.getMode()) { 3027 case NEW: 3028 if (!tree.expr.type.isRaw()) { 3029 resType = tree.expr.type; 3030 break; 3031 } 3032 default: 3033 resType = refType.getReturnType(); 3034 } 3035 3036 Type incompatibleReturnType = resType; 3037 3038 if (returnType.hasTag(VOID)) { 3039 incompatibleReturnType = null; 3040 } 3041 3042 if (!returnType.hasTag(VOID) && !resType.hasTag(VOID)) { 3043 if (resType.isErroneous() || 3044 new FunctionalReturnContext(checkContext).compatible(resType, returnType, types.noWarnings)) { 3045 incompatibleReturnType = null; 3046 } 3047 } 3048 3049 if (incompatibleReturnType != null) { 3050 checkContext.report(tree, diags.fragment("incompatible.ret.type.in.mref", 3051 diags.fragment("inconvertible.types", resType, descriptor.getReturnType()))); 3052 } else { 3053 if (inferenceContext.free(refType)) { 3054 // we need to wait for inference to finish and then replace inference vars in the referent type 3055 inferenceContext.addFreeTypeListener(List.of(refType), 3056 instantiatedContext -> { 3057 tree.referentType = instantiatedContext.asInstType(refType); 3058 }); 3059 } else { 3060 tree.referentType = refType; 3061 } 3062 } 3063 3064 if (!speculativeAttr) { 3065 List<Type> thrownTypes = inferenceContext.asUndetVars(descriptor.getThrownTypes()); 3066 if (chk.unhandled(refType.getThrownTypes(), thrownTypes).nonEmpty()) { 3067 log.error(tree, "incompatible.thrown.types.in.mref", refType.getThrownTypes()); 3068 } 3069 } 3070 } 3071 3072 /** 3073 * Set functional type info on the underlying AST. Note: as the target descriptor 3074 * might contain inference variables, we might need to register an hook in the 3075 * current inference context. 3076 */ 3077 private void setFunctionalInfo(final Env<AttrContext> env, final JCFunctionalExpression fExpr, 3078 final Type pt, final Type descriptorType, final Type primaryTarget, final CheckContext checkContext) { 3079 if (checkContext.inferenceContext().free(descriptorType)) { 3080 checkContext.inferenceContext().addFreeTypeListener(List.of(pt, descriptorType), new FreeTypeListener() { 3081 public void typesInferred(InferenceContext inferenceContext) { 3082 setFunctionalInfo(env, fExpr, pt, inferenceContext.asInstType(descriptorType), 3083 inferenceContext.asInstType(primaryTarget), checkContext); 3084 } 3085 }); 3086 } else { 3087 ListBuffer<Type> targets = new ListBuffer<>(); 3088 if (pt.hasTag(CLASS)) { 3089 if (pt.isCompound()) { 3090 targets.append(types.removeWildcards(primaryTarget)); //this goes first 3091 for (Type t : ((IntersectionClassType)pt()).interfaces_field) { 3092 if (t != primaryTarget) { 3093 targets.append(types.removeWildcards(t)); 3094 } 3095 } 3096 } else { 3097 targets.append(types.removeWildcards(primaryTarget)); 3098 } 3099 } 3100 fExpr.targets = targets.toList(); 3101 if (checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK && 3102 pt != Type.recoveryType) { 3103 //check that functional interface class is well-formed 3104 try { 3105 /* Types.makeFunctionalInterfaceClass() may throw an exception 3106 * when it's executed post-inference. See the listener code 3107 * above. 3108 */ 3109 ClassSymbol csym = types.makeFunctionalInterfaceClass(env, 3110 names.empty, List.of(fExpr.targets.head), ABSTRACT); 3111 if (csym != null) { 3112 chk.checkImplementations(env.tree, csym, csym); 3113 try { 3114 //perform an additional functional interface check on the synthetic class, 3115 //as there may be spurious errors for raw targets - because of existing issues 3116 //with membership and inheritance (see JDK-8074570). 3117 csym.flags_field |= INTERFACE; 3118 types.findDescriptorType(csym.type); 3119 } catch (FunctionDescriptorLookupError err) { 3120 resultInfo.checkContext.report(fExpr, 3121 diags.fragment(Fragments.NoSuitableFunctionalIntfInst(fExpr.targets.head))); 3122 } 3123 } 3124 } catch (Types.FunctionDescriptorLookupError ex) { 3125 JCDiagnostic cause = ex.getDiagnostic(); 3126 resultInfo.checkContext.report(env.tree, cause); 3127 } 3128 } 3129 } 3130 } 3131 3132 public void visitParens(JCParens tree) { 3133 Type owntype = attribTree(tree.expr, env, resultInfo); 3134 result = check(tree, owntype, pkind(), resultInfo); 3135 Symbol sym = TreeInfo.symbol(tree); 3136 if (sym != null && sym.kind.matches(KindSelector.TYP_PCK)) 3137 log.error(tree.pos(), "illegal.start.of.type"); 3138 } 3139 3140 public void visitAssign(JCAssign tree) { 3141 Type owntype = attribTree(tree.lhs, env.dup(tree), varAssignmentInfo); 3142 Type capturedType = capture(owntype); 3143 attribExpr(tree.rhs, env, owntype); 3144 result = check(tree, capturedType, KindSelector.VAL, resultInfo); 3145 } 3146 3147 public void visitAssignop(JCAssignOp tree) { 3148 // Attribute arguments. 3149 Type owntype = attribTree(tree.lhs, env, varAssignmentInfo); 3150 Type operand = attribExpr(tree.rhs, env); 3151 // Find operator. 3152 Symbol operator = tree.operator = operators.resolveBinary(tree, tree.getTag().noAssignOp(), owntype, operand); 3153 if (operator.kind == MTH && 3154 !owntype.isErroneous() && 3155 !operand.isErroneous()) { 3156 chk.checkDivZero(tree.rhs.pos(), operator, operand); 3157 chk.checkCastable(tree.rhs.pos(), 3158 operator.type.getReturnType(), 3159 owntype); 3160 } 3161 result = check(tree, owntype, KindSelector.VAL, resultInfo); 3162 } 3163 3164 public void visitUnary(JCUnary tree) { 3165 // Attribute arguments. 3166 Type argtype = (tree.getTag().isIncOrDecUnaryOp()) 3167 ? attribTree(tree.arg, env, varAssignmentInfo) 3168 : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env)); 3169 3170 // Find operator. 3171 Symbol operator = tree.operator = operators.resolveUnary(tree, tree.getTag(), argtype); 3172 Type owntype = types.createErrorType(tree.type); 3173 if (operator.kind == MTH && 3174 !argtype.isErroneous()) { 3175 owntype = (tree.getTag().isIncOrDecUnaryOp()) 3176 ? tree.arg.type 3177 : operator.type.getReturnType(); 3178 int opc = ((OperatorSymbol)operator).opcode; 3179 3180 // If the argument is constant, fold it. 3181 if (argtype.constValue() != null) { 3182 Type ctype = cfolder.fold1(opc, argtype); 3183 if (ctype != null) { 3184 owntype = cfolder.coerce(ctype, owntype); 3185 } 3186 } 3187 } 3188 result = check(tree, owntype, KindSelector.VAL, resultInfo); 3189 } 3190 3191 public void visitBinary(JCBinary tree) { 3192 // Attribute arguments. 3193 Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env)); 3194 Type right = chk.checkNonVoid(tree.rhs.pos(), attribExpr(tree.rhs, env)); 3195 // Find operator. 3196 Symbol operator = tree.operator = operators.resolveBinary(tree, tree.getTag(), left, right); 3197 Type owntype = types.createErrorType(tree.type); 3198 if (operator.kind == MTH && 3199 !left.isErroneous() && 3200 !right.isErroneous()) { 3201 owntype = operator.type.getReturnType(); 3202 int opc = ((OperatorSymbol)operator).opcode; 3203 // If both arguments are constants, fold them. 3204 if (left.constValue() != null && right.constValue() != null) { 3205 Type ctype = cfolder.fold2(opc, left, right); 3206 if (ctype != null) { 3207 owntype = cfolder.coerce(ctype, owntype); 3208 } 3209 } 3210 3211 // Check that argument types of a reference ==, != are 3212 // castable to each other, (JLS 15.21). Note: unboxing 3213 // comparisons will not have an acmp* opc at this point. 3214 if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) { 3215 if (!types.isCastable(left, right, new Warner(tree.pos()))) { 3216 log.error(tree.pos(), "incomparable.types", left, right); 3217 } 3218 } 3219 3220 chk.checkDivZero(tree.rhs.pos(), operator, right); 3221 } 3222 result = check(tree, owntype, KindSelector.VAL, resultInfo); 3223 } 3224 3225 public void visitTypeCast(final JCTypeCast tree) { 3226 Type clazztype = attribType(tree.clazz, env); 3227 chk.validate(tree.clazz, env, false); 3228 //a fresh environment is required for 292 inference to work properly --- 3229 //see Infer.instantiatePolymorphicSignatureInstance() 3230 Env<AttrContext> localEnv = env.dup(tree); 3231 //should we propagate the target type? 3232 final ResultInfo castInfo; 3233 JCExpression expr = TreeInfo.skipParens(tree.expr); 3234 boolean isPoly = allowPoly && (expr.hasTag(LAMBDA) || expr.hasTag(REFERENCE)); 3235 if (isPoly) { 3236 //expression is a poly - we need to propagate target type info 3237 castInfo = new ResultInfo(KindSelector.VAL, clazztype, 3238 new Check.NestedCheckContext(resultInfo.checkContext) { 3239 @Override 3240 public boolean compatible(Type found, Type req, Warner warn) { 3241 return types.isCastable(found, req, warn); 3242 } 3243 }); 3244 } else { 3245 //standalone cast - target-type info is not propagated 3246 castInfo = unknownExprInfo; 3247 } 3248 Type exprtype = attribTree(tree.expr, localEnv, castInfo); 3249 Type owntype = isPoly ? clazztype : chk.checkCastable(tree.expr.pos(), exprtype, clazztype); 3250 if (exprtype.constValue() != null) 3251 owntype = cfolder.coerce(exprtype, owntype); 3252 result = check(tree, capture(owntype), KindSelector.VAL, resultInfo); 3253 if (!isPoly) 3254 chk.checkRedundantCast(localEnv, tree); 3255 } 3256 3257 public void visitTypeTest(JCInstanceOf tree) { 3258 Type exprtype = chk.checkNullOrRefType( 3259 tree.expr.pos(), attribExpr(tree.expr, env)); 3260 Type clazztype = attribType(tree.clazz, env); 3261 if (!clazztype.hasTag(TYPEVAR)) { 3262 clazztype = chk.checkClassOrArrayType(tree.clazz.pos(), clazztype); 3263 } 3264 if (!clazztype.isErroneous() && !types.isReifiable(clazztype)) { 3265 log.error(tree.clazz.pos(), "illegal.generic.type.for.instof"); 3266 clazztype = types.createErrorType(clazztype); 3267 } 3268 chk.validate(tree.clazz, env, false); 3269 chk.checkCastable(tree.expr.pos(), exprtype, clazztype); 3270 result = check(tree, syms.booleanType, KindSelector.VAL, resultInfo); 3271 } 3272 3273 public void visitIndexed(JCArrayAccess tree) { 3274 Type owntype = types.createErrorType(tree.type); 3275 Type atype = attribExpr(tree.indexed, env); 3276 attribExpr(tree.index, env, syms.intType); 3277 if (types.isArray(atype)) 3278 owntype = types.elemtype(atype); 3279 else if (!atype.hasTag(ERROR)) 3280 log.error(tree.pos(), "array.req.but.found", atype); 3281 if (!pkind().contains(KindSelector.VAL)) 3282 owntype = capture(owntype); 3283 result = check(tree, owntype, KindSelector.VAR, resultInfo); 3284 } 3285 3286 public void visitIdent(JCIdent tree) { 3287 Symbol sym; 3288 3289 // Find symbol 3290 if (pt().hasTag(METHOD) || pt().hasTag(FORALL)) { 3291 // If we are looking for a method, the prototype `pt' will be a 3292 // method type with the type of the call's arguments as parameters. 3293 env.info.pendingResolutionPhase = null; 3294 sym = rs.resolveMethod(tree.pos(), env, tree.name, pt().getParameterTypes(), pt().getTypeArguments()); 3295 } else if (tree.sym != null && tree.sym.kind != VAR) { 3296 sym = tree.sym; 3297 } else { 3298 sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind()); 3299 } 3300 tree.sym = sym; 3301 3302 // (1) Also find the environment current for the class where 3303 // sym is defined (`symEnv'). 3304 // Only for pre-tiger versions (1.4 and earlier): 3305 // (2) Also determine whether we access symbol out of an anonymous 3306 // class in a this or super call. This is illegal for instance 3307 // members since such classes don't carry a this$n link. 3308 // (`noOuterThisPath'). 3309 Env<AttrContext> symEnv = env; 3310 boolean noOuterThisPath = false; 3311 if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class 3312 sym.kind.matches(KindSelector.VAL_MTH) && 3313 sym.owner.kind == TYP && 3314 tree.name != names._this && tree.name != names._super) { 3315 3316 // Find environment in which identifier is defined. 3317 while (symEnv.outer != null && 3318 !sym.isMemberOf(symEnv.enclClass.sym, types)) { 3319 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0) 3320 noOuterThisPath = false; 3321 symEnv = symEnv.outer; 3322 } 3323 } 3324 3325 // If symbol is a variable, ... 3326 if (sym.kind == VAR) { 3327 VarSymbol v = (VarSymbol)sym; 3328 3329 // ..., evaluate its initializer, if it has one, and check for 3330 // illegal forward reference. 3331 checkInit(tree, env, v, false); 3332 3333 // If we are expecting a variable (as opposed to a value), check 3334 // that the variable is assignable in the current environment. 3335 if (KindSelector.ASG.subset(pkind())) 3336 checkAssignable(tree.pos(), v, null, env); 3337 } 3338 3339 // In a constructor body, 3340 // if symbol is a field or instance method, check that it is 3341 // not accessed before the supertype constructor is called. 3342 if ((symEnv.info.isSelfCall || noOuterThisPath) && 3343 sym.kind.matches(KindSelector.VAL_MTH) && 3344 sym.owner.kind == TYP && 3345 (sym.flags() & STATIC) == 0) { 3346 chk.earlyRefError(tree.pos(), sym.kind == VAR ? 3347 sym : thisSym(tree.pos(), env)); 3348 } 3349 Env<AttrContext> env1 = env; 3350 if (sym.kind != ERR && sym.kind != TYP && 3351 sym.owner != null && sym.owner != env1.enclClass.sym) { 3352 // If the found symbol is inaccessible, then it is 3353 // accessed through an enclosing instance. Locate this 3354 // enclosing instance: 3355 while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym)) 3356 env1 = env1.outer; 3357 } 3358 3359 if (env.info.isSerializable) { 3360 chk.checkElemAccessFromSerializableLambda(tree); 3361 } 3362 3363 result = checkId(tree, env1.enclClass.sym.type, sym, env, resultInfo); 3364 } 3365 3366 public void visitSelect(JCFieldAccess tree) { 3367 // Determine the expected kind of the qualifier expression. 3368 KindSelector skind = KindSelector.NIL; 3369 if (tree.name == names._this || tree.name == names._super || 3370 tree.name == names._class) 3371 { 3372 skind = KindSelector.TYP; 3373 } else { 3374 if (pkind().contains(KindSelector.PCK)) 3375 skind = KindSelector.of(skind, KindSelector.PCK); 3376 if (pkind().contains(KindSelector.TYP)) 3377 skind = KindSelector.of(skind, KindSelector.TYP, KindSelector.PCK); 3378 if (pkind().contains(KindSelector.VAL_MTH)) 3379 skind = KindSelector.of(skind, KindSelector.VAL, KindSelector.TYP); 3380 } 3381 3382 // Attribute the qualifier expression, and determine its symbol (if any). 3383 Type site = attribTree(tree.selected, env, new ResultInfo(skind, Type.noType)); 3384 if (!pkind().contains(KindSelector.TYP_PCK)) 3385 site = capture(site); // Capture field access 3386 3387 // don't allow T.class T[].class, etc 3388 if (skind == KindSelector.TYP) { 3389 Type elt = site; 3390 while (elt.hasTag(ARRAY)) 3391 elt = ((ArrayType)elt).elemtype; 3392 if (elt.hasTag(TYPEVAR)) { 3393 log.error(tree.pos(), "type.var.cant.be.deref"); 3394 result = tree.type = types.createErrorType(tree.name, site.tsym, site); 3395 tree.sym = tree.type.tsym; 3396 return ; 3397 } 3398 } 3399 3400 // If qualifier symbol is a type or `super', assert `selectSuper' 3401 // for the selection. This is relevant for determining whether 3402 // protected symbols are accessible. 3403 Symbol sitesym = TreeInfo.symbol(tree.selected); 3404 boolean selectSuperPrev = env.info.selectSuper; 3405 env.info.selectSuper = 3406 sitesym != null && 3407 sitesym.name == names._super; 3408 3409 // Determine the symbol represented by the selection. 3410 env.info.pendingResolutionPhase = null; 3411 Symbol sym = selectSym(tree, sitesym, site, env, resultInfo); 3412 if (sym.kind == VAR && sym.name != names._super && env.info.defaultSuperCallSite != null) { 3413 log.error(tree.selected.pos(), "not.encl.class", site.tsym); 3414 sym = syms.errSymbol; 3415 } 3416 if (sym.exists() && !isType(sym) && pkind().contains(KindSelector.TYP_PCK)) { 3417 site = capture(site); 3418 sym = selectSym(tree, sitesym, site, env, resultInfo); 3419 } 3420 boolean varArgs = env.info.lastResolveVarargs(); 3421 tree.sym = sym; 3422 3423 if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) { 3424 site = types.skipTypeVars(site, true); 3425 } 3426 3427 // If that symbol is a variable, ... 3428 if (sym.kind == VAR) { 3429 VarSymbol v = (VarSymbol)sym; 3430 3431 // ..., evaluate its initializer, if it has one, and check for 3432 // illegal forward reference. 3433 checkInit(tree, env, v, true); 3434 3435 // If we are expecting a variable (as opposed to a value), check 3436 // that the variable is assignable in the current environment. 3437 if (KindSelector.ASG.subset(pkind())) 3438 checkAssignable(tree.pos(), v, tree.selected, env); 3439 } 3440 3441 if (sitesym != null && 3442 sitesym.kind == VAR && 3443 ((VarSymbol)sitesym).isResourceVariable() && 3444 sym.kind == MTH && 3445 sym.name.equals(names.close) && 3446 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) && 3447 env.info.lint.isEnabled(LintCategory.TRY)) { 3448 log.warning(LintCategory.TRY, tree, "try.explicit.close.call"); 3449 } 3450 3451 // Disallow selecting a type from an expression 3452 if (isType(sym) && (sitesym == null || !sitesym.kind.matches(KindSelector.TYP_PCK))) { 3453 tree.type = check(tree.selected, pt(), 3454 sitesym == null ? 3455 KindSelector.VAL : sitesym.kind.toSelector(), 3456 new ResultInfo(KindSelector.TYP_PCK, pt())); 3457 } 3458 3459 if (isType(sitesym)) { 3460 if (sym.name == names._this) { 3461 // If `C' is the currently compiled class, check that 3462 // C.this' does not appear in a call to a super(...) 3463 if (env.info.isSelfCall && 3464 site.tsym == env.enclClass.sym) { 3465 chk.earlyRefError(tree.pos(), sym); 3466 } 3467 } else { 3468 // Check if type-qualified fields or methods are static (JLS) 3469 if ((sym.flags() & STATIC) == 0 && 3470 !env.next.tree.hasTag(REFERENCE) && 3471 sym.name != names._super && 3472 (sym.kind == VAR || sym.kind == MTH)) { 3473 rs.accessBase(rs.new StaticError(sym), 3474 tree.pos(), site, sym.name, true); 3475 } 3476 } 3477 if (!allowStaticInterfaceMethods && sitesym.isInterface() && 3478 sym.isStatic() && sym.kind == MTH) { 3479 log.error(tree.pos(), "static.intf.method.invoke.not.supported.in.source", sourceName); 3480 } 3481 } else if (sym.kind != ERR && 3482 (sym.flags() & STATIC) != 0 && 3483 sym.name != names._class) { 3484 // If the qualified item is not a type and the selected item is static, report 3485 // a warning. Make allowance for the class of an array type e.g. Object[].class) 3486 chk.warnStatic(tree, "static.not.qualified.by.type", 3487 sym.kind.kindName(), sym.owner); 3488 } 3489 3490 // If we are selecting an instance member via a `super', ... 3491 if (env.info.selectSuper && (sym.flags() & STATIC) == 0) { 3492 3493 // Check that super-qualified symbols are not abstract (JLS) 3494 rs.checkNonAbstract(tree.pos(), sym); 3495 3496 if (site.isRaw()) { 3497 // Determine argument types for site. 3498 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym); 3499 if (site1 != null) site = site1; 3500 } 3501 } 3502 3503 if (env.info.isSerializable) { 3504 chk.checkElemAccessFromSerializableLambda(tree); 3505 } 3506 3507 env.info.selectSuper = selectSuperPrev; 3508 result = checkId(tree, site, sym, env, resultInfo); 3509 } 3510 //where 3511 /** Determine symbol referenced by a Select expression, 3512 * 3513 * @param tree The select tree. 3514 * @param site The type of the selected expression, 3515 * @param env The current environment. 3516 * @param resultInfo The current result. 3517 */ 3518 private Symbol selectSym(JCFieldAccess tree, 3519 Symbol location, 3520 Type site, 3521 Env<AttrContext> env, 3522 ResultInfo resultInfo) { 3523 DiagnosticPosition pos = tree.pos(); 3524 Name name = tree.name; 3525 switch (site.getTag()) { 3526 case PACKAGE: 3527 return rs.accessBase( 3528 rs.findIdentInPackage(env, site.tsym, name, resultInfo.pkind), 3529 pos, location, site, name, true); 3530 case ARRAY: 3531 case CLASS: 3532 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) { 3533 return rs.resolveQualifiedMethod( 3534 pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments()); 3535 } else if (name == names._this || name == names._super) { 3536 return rs.resolveSelf(pos, env, site.tsym, name); 3537 } else if (name == names._class) { 3538 // In this case, we have already made sure in 3539 // visitSelect that qualifier expression is a type. 3540 Type t = syms.classType; 3541 List<Type> typeargs = List.of(types.erasure(site)); 3542 t = new ClassType(t.getEnclosingType(), typeargs, t.tsym); 3543 return new VarSymbol( 3544 STATIC | PUBLIC | FINAL, names._class, t, site.tsym); 3545 } else { 3546 // We are seeing a plain identifier as selector. 3547 Symbol sym = rs.findIdentInType(env, site, name, resultInfo.pkind); 3548 sym = rs.accessBase(sym, pos, location, site, name, true); 3549 return sym; 3550 } 3551 case WILDCARD: 3552 throw new AssertionError(tree); 3553 case TYPEVAR: 3554 // Normally, site.getUpperBound() shouldn't be null. 3555 // It should only happen during memberEnter/attribBase 3556 // when determining the super type which *must* beac 3557 // done before attributing the type variables. In 3558 // other words, we are seeing this illegal program: 3559 // class B<T> extends A<T.foo> {} 3560 Symbol sym = (site.getUpperBound() != null) 3561 ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo) 3562 : null; 3563 if (sym == null) { 3564 log.error(pos, "type.var.cant.be.deref"); 3565 return syms.errSymbol; 3566 } else { 3567 Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ? 3568 rs.new AccessError(env, site, sym) : 3569 sym; 3570 rs.accessBase(sym2, pos, location, site, name, true); 3571 return sym; 3572 } 3573 case ERROR: 3574 // preserve identifier names through errors 3575 return types.createErrorType(name, site.tsym, site).tsym; 3576 default: 3577 // The qualifier expression is of a primitive type -- only 3578 // .class is allowed for these. 3579 if (name == names._class) { 3580 // In this case, we have already made sure in Select that 3581 // qualifier expression is a type. 3582 Type t = syms.classType; 3583 Type arg = types.boxedClass(site).type; 3584 t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym); 3585 return new VarSymbol( 3586 STATIC | PUBLIC | FINAL, names._class, t, site.tsym); 3587 } else { 3588 log.error(pos, "cant.deref", site); 3589 return syms.errSymbol; 3590 } 3591 } 3592 } 3593 3594 /** Determine type of identifier or select expression and check that 3595 * (1) the referenced symbol is not deprecated 3596 * (2) the symbol's type is safe (@see checkSafe) 3597 * (3) if symbol is a variable, check that its type and kind are 3598 * compatible with the prototype and protokind. 3599 * (4) if symbol is an instance field of a raw type, 3600 * which is being assigned to, issue an unchecked warning if its 3601 * type changes under erasure. 3602 * (5) if symbol is an instance method of a raw type, issue an 3603 * unchecked warning if its argument types change under erasure. 3604 * If checks succeed: 3605 * If symbol is a constant, return its constant type 3606 * else if symbol is a method, return its result type 3607 * otherwise return its type. 3608 * Otherwise return errType. 3609 * 3610 * @param tree The syntax tree representing the identifier 3611 * @param site If this is a select, the type of the selected 3612 * expression, otherwise the type of the current class. 3613 * @param sym The symbol representing the identifier. 3614 * @param env The current environment. 3615 * @param resultInfo The expected result 3616 */ 3617 Type checkId(JCTree tree, 3618 Type site, 3619 Symbol sym, 3620 Env<AttrContext> env, 3621 ResultInfo resultInfo) { 3622 return (resultInfo.pt.hasTag(FORALL) || resultInfo.pt.hasTag(METHOD)) ? 3623 checkMethodId(tree, site, sym, env, resultInfo) : 3624 checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo); 3625 } 3626 3627 Type checkMethodId(JCTree tree, 3628 Type site, 3629 Symbol sym, 3630 Env<AttrContext> env, 3631 ResultInfo resultInfo) { 3632 boolean isPolymorhicSignature = 3633 (sym.baseSymbol().flags() & SIGNATURE_POLYMORPHIC) != 0; 3634 return isPolymorhicSignature ? 3635 checkSigPolyMethodId(tree, site, sym, env, resultInfo) : 3636 checkMethodIdInternal(tree, site, sym, env, resultInfo); 3637 } 3638 3639 Type checkSigPolyMethodId(JCTree tree, 3640 Type site, 3641 Symbol sym, 3642 Env<AttrContext> env, 3643 ResultInfo resultInfo) { 3644 //recover original symbol for signature polymorphic methods 3645 checkMethodIdInternal(tree, site, sym.baseSymbol(), env, resultInfo); 3646 env.info.pendingResolutionPhase = Resolve.MethodResolutionPhase.BASIC; 3647 return sym.type; 3648 } 3649 3650 Type checkMethodIdInternal(JCTree tree, 3651 Type site, 3652 Symbol sym, 3653 Env<AttrContext> env, 3654 ResultInfo resultInfo) { 3655 if (resultInfo.pkind.contains(KindSelector.POLY)) { 3656 Type pt = resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, sym, env.info.pendingResolutionPhase)); 3657 Type owntype = checkIdInternal(tree, site, sym, pt, env, resultInfo); 3658 resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase)); 3659 return owntype; 3660 } else { 3661 return checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo); 3662 } 3663 } 3664 3665 Type checkIdInternal(JCTree tree, 3666 Type site, 3667 Symbol sym, 3668 Type pt, 3669 Env<AttrContext> env, 3670 ResultInfo resultInfo) { 3671 if (pt.isErroneous()) { 3672 return types.createErrorType(site); 3673 } 3674 Type owntype; // The computed type of this identifier occurrence. 3675 switch (sym.kind) { 3676 case TYP: 3677 // For types, the computed type equals the symbol's type, 3678 // except for two situations: 3679 owntype = sym.type; 3680 if (owntype.hasTag(CLASS)) { 3681 chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym); 3682 Type ownOuter = owntype.getEnclosingType(); 3683 3684 // (a) If the symbol's type is parameterized, erase it 3685 // because no type parameters were given. 3686 // We recover generic outer type later in visitTypeApply. 3687 if (owntype.tsym.type.getTypeArguments().nonEmpty()) { 3688 owntype = types.erasure(owntype); 3689 } 3690 3691 // (b) If the symbol's type is an inner class, then 3692 // we have to interpret its outer type as a superclass 3693 // of the site type. Example: 3694 // 3695 // class Tree<A> { class Visitor { ... } } 3696 // class PointTree extends Tree<Point> { ... } 3697 // ...PointTree.Visitor... 3698 // 3699 // Then the type of the last expression above is 3700 // Tree<Point>.Visitor. 3701 else if (ownOuter.hasTag(CLASS) && site != ownOuter) { 3702 Type normOuter = site; 3703 if (normOuter.hasTag(CLASS)) { 3704 normOuter = types.asEnclosingSuper(site, ownOuter.tsym); 3705 } 3706 if (normOuter == null) // perhaps from an import 3707 normOuter = types.erasure(ownOuter); 3708 if (normOuter != ownOuter) 3709 owntype = new ClassType( 3710 normOuter, List.<Type>nil(), owntype.tsym, 3711 owntype.getMetadata()); 3712 } 3713 } 3714 break; 3715 case VAR: 3716 VarSymbol v = (VarSymbol)sym; 3717 // Test (4): if symbol is an instance field of a raw type, 3718 // which is being assigned to, issue an unchecked warning if 3719 // its type changes under erasure. 3720 if (KindSelector.ASG.subset(pkind()) && 3721 v.owner.kind == TYP && 3722 (v.flags() & STATIC) == 0 && 3723 (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) { 3724 Type s = types.asOuterSuper(site, v.owner); 3725 if (s != null && 3726 s.isRaw() && 3727 !types.isSameType(v.type, v.erasure(types))) { 3728 chk.warnUnchecked(tree.pos(), 3729 "unchecked.assign.to.var", 3730 v, s); 3731 } 3732 } 3733 // The computed type of a variable is the type of the 3734 // variable symbol, taken as a member of the site type. 3735 owntype = (sym.owner.kind == TYP && 3736 sym.name != names._this && sym.name != names._super) 3737 ? types.memberType(site, sym) 3738 : sym.type; 3739 3740 // If the variable is a constant, record constant value in 3741 // computed type. 3742 if (v.getConstValue() != null && isStaticReference(tree)) 3743 owntype = owntype.constType(v.getConstValue()); 3744 3745 if (resultInfo.pkind == KindSelector.VAL) { 3746 owntype = capture(owntype); // capture "names as expressions" 3747 } 3748 break; 3749 case MTH: { 3750 owntype = checkMethod(site, sym, 3751 new ResultInfo(resultInfo.pkind, resultInfo.pt.getReturnType(), resultInfo.checkContext), 3752 env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(), 3753 resultInfo.pt.getTypeArguments()); 3754 break; 3755 } 3756 case PCK: case ERR: 3757 owntype = sym.type; 3758 break; 3759 default: 3760 throw new AssertionError("unexpected kind: " + sym.kind + 3761 " in tree " + tree); 3762 } 3763 3764 // Emit a `deprecation' warning if symbol is deprecated. 3765 // (for constructors (but not for constructor references), the error 3766 // was given when the constructor was resolved) 3767 3768 if (sym.name != names.init || tree.hasTag(REFERENCE)) { 3769 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym); 3770 chk.checkSunAPI(tree.pos(), sym); 3771 chk.checkProfile(tree.pos(), sym); 3772 } 3773 3774 // If symbol is a variable, check that its type and 3775 // kind are compatible with the prototype and protokind. 3776 return check(tree, owntype, sym.kind.toSelector(), resultInfo); 3777 } 3778 3779 /** Check that variable is initialized and evaluate the variable's 3780 * initializer, if not yet done. Also check that variable is not 3781 * referenced before it is defined. 3782 * @param tree The tree making up the variable reference. 3783 * @param env The current environment. 3784 * @param v The variable's symbol. 3785 */ 3786 private void checkInit(JCTree tree, 3787 Env<AttrContext> env, 3788 VarSymbol v, 3789 boolean onlyWarning) { 3790 // A forward reference is diagnosed if the declaration position 3791 // of the variable is greater than the current tree position 3792 // and the tree and variable definition occur in the same class 3793 // definition. Note that writes don't count as references. 3794 // This check applies only to class and instance 3795 // variables. Local variables follow different scope rules, 3796 // and are subject to definite assignment checking. 3797 Env<AttrContext> initEnv = enclosingInitEnv(env); 3798 if (initEnv != null && 3799 (initEnv.info.enclVar == v || v.pos > tree.pos) && 3800 v.owner.kind == TYP && 3801 v.owner == env.info.scope.owner.enclClass() && 3802 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) && 3803 (!env.tree.hasTag(ASSIGN) || 3804 TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) { 3805 String suffix = (initEnv.info.enclVar == v) ? 3806 "self.ref" : "forward.ref"; 3807 if (!onlyWarning || isStaticEnumField(v)) { 3808 log.error(tree.pos(), "illegal." + suffix); 3809 } else if (useBeforeDeclarationWarning) { 3810 log.warning(tree.pos(), suffix, v); 3811 } 3812 } 3813 3814 v.getConstValue(); // ensure initializer is evaluated 3815 3816 checkEnumInitializer(tree, env, v); 3817 } 3818 3819 /** 3820 * Returns the enclosing init environment associated with this env (if any). An init env 3821 * can be either a field declaration env or a static/instance initializer env. 3822 */ 3823 Env<AttrContext> enclosingInitEnv(Env<AttrContext> env) { 3824 while (true) { 3825 switch (env.tree.getTag()) { 3826 case VARDEF: 3827 JCVariableDecl vdecl = (JCVariableDecl)env.tree; 3828 if (vdecl.sym.owner.kind == TYP) { 3829 //field 3830 return env; 3831 } 3832 break; 3833 case BLOCK: 3834 if (env.next.tree.hasTag(CLASSDEF)) { 3835 //instance/static initializer 3836 return env; 3837 } 3838 break; 3839 case METHODDEF: 3840 case CLASSDEF: 3841 case TOPLEVEL: 3842 return null; 3843 } 3844 Assert.checkNonNull(env.next); 3845 env = env.next; 3846 } 3847 } 3848 3849 /** 3850 * Check for illegal references to static members of enum. In 3851 * an enum type, constructors and initializers may not 3852 * reference its static members unless they are constant. 3853 * 3854 * @param tree The tree making up the variable reference. 3855 * @param env The current environment. 3856 * @param v The variable's symbol. 3857 * @jls section 8.9 Enums 3858 */ 3859 private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) { 3860 // JLS: 3861 // 3862 // "It is a compile-time error to reference a static field 3863 // of an enum type that is not a compile-time constant 3864 // (15.28) from constructors, instance initializer blocks, 3865 // or instance variable initializer expressions of that 3866 // type. It is a compile-time error for the constructors, 3867 // instance initializer blocks, or instance variable 3868 // initializer expressions of an enum constant e to refer 3869 // to itself or to an enum constant of the same type that 3870 // is declared to the right of e." 3871 if (isStaticEnumField(v)) { 3872 ClassSymbol enclClass = env.info.scope.owner.enclClass(); 3873 3874 if (enclClass == null || enclClass.owner == null) 3875 return; 3876 3877 // See if the enclosing class is the enum (or a 3878 // subclass thereof) declaring v. If not, this 3879 // reference is OK. 3880 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type)) 3881 return; 3882 3883 // If the reference isn't from an initializer, then 3884 // the reference is OK. 3885 if (!Resolve.isInitializer(env)) 3886 return; 3887 3888 log.error(tree.pos(), "illegal.enum.static.ref"); 3889 } 3890 } 3891 3892 /** Is the given symbol a static, non-constant field of an Enum? 3893 * Note: enum literals should not be regarded as such 3894 */ 3895 private boolean isStaticEnumField(VarSymbol v) { 3896 return Flags.isEnum(v.owner) && 3897 Flags.isStatic(v) && 3898 !Flags.isConstant(v) && 3899 v.name != names._class; 3900 } 3901 3902 /** 3903 * Check that method arguments conform to its instantiation. 3904 **/ 3905 public Type checkMethod(Type site, 3906 final Symbol sym, 3907 ResultInfo resultInfo, 3908 Env<AttrContext> env, 3909 final List<JCExpression> argtrees, 3910 List<Type> argtypes, 3911 List<Type> typeargtypes) { 3912 // Test (5): if symbol is an instance method of a raw type, issue 3913 // an unchecked warning if its argument types change under erasure. 3914 if ((sym.flags() & STATIC) == 0 && 3915 (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) { 3916 Type s = types.asOuterSuper(site, sym.owner); 3917 if (s != null && s.isRaw() && 3918 !types.isSameTypes(sym.type.getParameterTypes(), 3919 sym.erasure(types).getParameterTypes())) { 3920 chk.warnUnchecked(env.tree.pos(), 3921 "unchecked.call.mbr.of.raw.type", 3922 sym, s); 3923 } 3924 } 3925 3926 if (env.info.defaultSuperCallSite != null) { 3927 for (Type sup : types.interfaces(env.enclClass.type).prepend(types.supertype((env.enclClass.type)))) { 3928 if (!sup.tsym.isSubClass(sym.enclClass(), types) || 3929 types.isSameType(sup, env.info.defaultSuperCallSite)) continue; 3930 List<MethodSymbol> icand_sup = 3931 types.interfaceCandidates(sup, (MethodSymbol)sym); 3932 if (icand_sup.nonEmpty() && 3933 icand_sup.head != sym && 3934 icand_sup.head.overrides(sym, icand_sup.head.enclClass(), types, true)) { 3935 log.error(env.tree.pos(), "illegal.default.super.call", env.info.defaultSuperCallSite, 3936 diags.fragment("overridden.default", sym, sup)); 3937 break; 3938 } 3939 } 3940 env.info.defaultSuperCallSite = null; 3941 } 3942 3943 if (sym.isStatic() && site.isInterface() && env.tree.hasTag(APPLY)) { 3944 JCMethodInvocation app = (JCMethodInvocation)env.tree; 3945 if (app.meth.hasTag(SELECT) && 3946 !TreeInfo.isStaticSelector(((JCFieldAccess)app.meth).selected, names)) { 3947 log.error(env.tree.pos(), "illegal.static.intf.meth.call", site); 3948 } 3949 } 3950 3951 // Compute the identifier's instantiated type. 3952 // For methods, we need to compute the instance type by 3953 // Resolve.instantiate from the symbol's type as well as 3954 // any type arguments and value arguments. 3955 Warner noteWarner = new Warner(); 3956 try { 3957 Type owntype = rs.checkMethod( 3958 env, 3959 site, 3960 sym, 3961 resultInfo, 3962 argtypes, 3963 typeargtypes, 3964 noteWarner); 3965 3966 DeferredAttr.DeferredTypeMap checkDeferredMap = 3967 deferredAttr.new DeferredTypeMap(DeferredAttr.AttrMode.CHECK, sym, env.info.pendingResolutionPhase); 3968 3969 argtypes = argtypes.map(checkDeferredMap); 3970 3971 if (noteWarner.hasNonSilentLint(LintCategory.UNCHECKED)) { 3972 chk.warnUnchecked(env.tree.pos(), 3973 "unchecked.meth.invocation.applied", 3974 kindName(sym), 3975 sym.name, 3976 rs.methodArguments(sym.type.getParameterTypes()), 3977 rs.methodArguments(argtypes.map(checkDeferredMap)), 3978 kindName(sym.location()), 3979 sym.location()); 3980 owntype = new MethodType(owntype.getParameterTypes(), 3981 types.erasure(owntype.getReturnType()), 3982 types.erasure(owntype.getThrownTypes()), 3983 syms.methodClass); 3984 } 3985 3986 PolyKind pkind = (sym.type.hasTag(FORALL) && 3987 sym.type.getReturnType().containsAny(((ForAll)sym.type).tvars)) ? 3988 PolyKind.POLY : PolyKind.STANDALONE; 3989 TreeInfo.setPolyKind(env.tree, pkind); 3990 3991 return (resultInfo.pt == Infer.anyPoly) ? 3992 owntype : 3993 chk.checkMethod(owntype, sym, env, argtrees, argtypes, env.info.lastResolveVarargs(), 3994 resultInfo.checkContext.inferenceContext()); 3995 } catch (Infer.InferenceException ex) { 3996 //invalid target type - propagate exception outwards or report error 3997 //depending on the current check context 3998 resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic()); 3999 return types.createErrorType(site); 4000 } catch (Resolve.InapplicableMethodException ex) { 4001 final JCDiagnostic diag = ex.getDiagnostic(); 4002 Resolve.InapplicableSymbolError errSym = rs.new InapplicableSymbolError(null) { 4003 @Override 4004 protected Pair<Symbol, JCDiagnostic> errCandidate() { 4005 return new Pair<>(sym, diag); 4006 } 4007 }; 4008 List<Type> argtypes2 = argtypes.map( 4009 rs.new ResolveDeferredRecoveryMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase)); 4010 JCDiagnostic errDiag = errSym.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR, 4011 env.tree, sym, site, sym.name, argtypes2, typeargtypes); 4012 log.report(errDiag); 4013 return types.createErrorType(site); 4014 } 4015 } 4016 4017 public void visitLiteral(JCLiteral tree) { 4018 result = check(tree, litType(tree.typetag).constType(tree.value), 4019 KindSelector.VAL, resultInfo); 4020 } 4021 //where 4022 /** Return the type of a literal with given type tag. 4023 */ 4024 Type litType(TypeTag tag) { 4025 return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()]; 4026 } 4027 4028 public void visitTypeIdent(JCPrimitiveTypeTree tree) { 4029 result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], KindSelector.TYP, resultInfo); 4030 } 4031 4032 public void visitTypeArray(JCArrayTypeTree tree) { 4033 Type etype = attribType(tree.elemtype, env); 4034 Type type = new ArrayType(etype, syms.arrayClass); 4035 result = check(tree, type, KindSelector.TYP, resultInfo); 4036 } 4037 4038 /** Visitor method for parameterized types. 4039 * Bound checking is left until later, since types are attributed 4040 * before supertype structure is completely known 4041 */ 4042 public void visitTypeApply(JCTypeApply tree) { 4043 Type owntype = types.createErrorType(tree.type); 4044 4045 // Attribute functor part of application and make sure it's a class. 4046 Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env)); 4047 4048 // Attribute type parameters 4049 List<Type> actuals = attribTypes(tree.arguments, env); 4050 4051 if (clazztype.hasTag(CLASS)) { 4052 List<Type> formals = clazztype.tsym.type.getTypeArguments(); 4053 if (actuals.isEmpty()) //diamond 4054 actuals = formals; 4055 4056 if (actuals.length() == formals.length()) { 4057 List<Type> a = actuals; 4058 List<Type> f = formals; 4059 while (a.nonEmpty()) { 4060 a.head = a.head.withTypeVar(f.head); 4061 a = a.tail; 4062 f = f.tail; 4063 } 4064 // Compute the proper generic outer 4065 Type clazzOuter = clazztype.getEnclosingType(); 4066 if (clazzOuter.hasTag(CLASS)) { 4067 Type site; 4068 JCExpression clazz = TreeInfo.typeIn(tree.clazz); 4069 if (clazz.hasTag(IDENT)) { 4070 site = env.enclClass.sym.type; 4071 } else if (clazz.hasTag(SELECT)) { 4072 site = ((JCFieldAccess) clazz).selected.type; 4073 } else throw new AssertionError(""+tree); 4074 if (clazzOuter.hasTag(CLASS) && site != clazzOuter) { 4075 if (site.hasTag(CLASS)) 4076 site = types.asOuterSuper(site, clazzOuter.tsym); 4077 if (site == null) 4078 site = types.erasure(clazzOuter); 4079 clazzOuter = site; 4080 } 4081 } 4082 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym, 4083 clazztype.getMetadata()); 4084 } else { 4085 if (formals.length() != 0) { 4086 log.error(tree.pos(), "wrong.number.type.args", 4087 Integer.toString(formals.length())); 4088 } else { 4089 log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym); 4090 } 4091 owntype = types.createErrorType(tree.type); 4092 } 4093 } 4094 result = check(tree, owntype, KindSelector.TYP, resultInfo); 4095 } 4096 4097 public void visitTypeUnion(JCTypeUnion tree) { 4098 ListBuffer<Type> multicatchTypes = new ListBuffer<>(); 4099 ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed 4100 for (JCExpression typeTree : tree.alternatives) { 4101 Type ctype = attribType(typeTree, env); 4102 ctype = chk.checkType(typeTree.pos(), 4103 chk.checkClassType(typeTree.pos(), ctype), 4104 syms.throwableType); 4105 if (!ctype.isErroneous()) { 4106 //check that alternatives of a union type are pairwise 4107 //unrelated w.r.t. subtyping 4108 if (chk.intersects(ctype, multicatchTypes.toList())) { 4109 for (Type t : multicatchTypes) { 4110 boolean sub = types.isSubtype(ctype, t); 4111 boolean sup = types.isSubtype(t, ctype); 4112 if (sub || sup) { 4113 //assume 'a' <: 'b' 4114 Type a = sub ? ctype : t; 4115 Type b = sub ? t : ctype; 4116 log.error(typeTree.pos(), "multicatch.types.must.be.disjoint", a, b); 4117 } 4118 } 4119 } 4120 multicatchTypes.append(ctype); 4121 if (all_multicatchTypes != null) 4122 all_multicatchTypes.append(ctype); 4123 } else { 4124 if (all_multicatchTypes == null) { 4125 all_multicatchTypes = new ListBuffer<>(); 4126 all_multicatchTypes.appendList(multicatchTypes); 4127 } 4128 all_multicatchTypes.append(ctype); 4129 } 4130 } 4131 Type t = check(tree, types.lub(multicatchTypes.toList()), 4132 KindSelector.TYP, resultInfo.dup(CheckMode.NO_TREE_UPDATE)); 4133 if (t.hasTag(CLASS)) { 4134 List<Type> alternatives = 4135 ((all_multicatchTypes == null) ? multicatchTypes : all_multicatchTypes).toList(); 4136 t = new UnionClassType((ClassType) t, alternatives); 4137 } 4138 tree.type = result = t; 4139 } 4140 4141 public void visitTypeIntersection(JCTypeIntersection tree) { 4142 attribTypes(tree.bounds, env); 4143 tree.type = result = checkIntersection(tree, tree.bounds); 4144 } 4145 4146 public void visitTypeParameter(JCTypeParameter tree) { 4147 TypeVar typeVar = (TypeVar) tree.type; 4148 4149 if (tree.annotations != null && tree.annotations.nonEmpty()) { 4150 annotate.annotateTypeParameterSecondStage(tree, tree.annotations); 4151 } 4152 4153 if (!typeVar.bound.isErroneous()) { 4154 //fixup type-parameter bound computed in 'attribTypeVariables' 4155 typeVar.bound = checkIntersection(tree, tree.bounds); 4156 } 4157 } 4158 4159 Type checkIntersection(JCTree tree, List<JCExpression> bounds) { 4160 Set<Type> boundSet = new HashSet<>(); 4161 if (bounds.nonEmpty()) { 4162 // accept class or interface or typevar as first bound. 4163 bounds.head.type = checkBase(bounds.head.type, bounds.head, env, false, false, false); 4164 boundSet.add(types.erasure(bounds.head.type)); 4165 if (bounds.head.type.isErroneous()) { 4166 return bounds.head.type; 4167 } 4168 else if (bounds.head.type.hasTag(TYPEVAR)) { 4169 // if first bound was a typevar, do not accept further bounds. 4170 if (bounds.tail.nonEmpty()) { 4171 log.error(bounds.tail.head.pos(), 4172 "type.var.may.not.be.followed.by.other.bounds"); 4173 return bounds.head.type; 4174 } 4175 } else { 4176 // if first bound was a class or interface, accept only interfaces 4177 // as further bounds. 4178 for (JCExpression bound : bounds.tail) { 4179 bound.type = checkBase(bound.type, bound, env, false, true, false); 4180 if (bound.type.isErroneous()) { 4181 bounds = List.of(bound); 4182 } 4183 else if (bound.type.hasTag(CLASS)) { 4184 chk.checkNotRepeated(bound.pos(), types.erasure(bound.type), boundSet); 4185 } 4186 } 4187 } 4188 } 4189 4190 if (bounds.length() == 0) { 4191 return syms.objectType; 4192 } else if (bounds.length() == 1) { 4193 return bounds.head.type; 4194 } else { 4195 Type owntype = types.makeIntersectionType(TreeInfo.types(bounds)); 4196 // ... the variable's bound is a class type flagged COMPOUND 4197 // (see comment for TypeVar.bound). 4198 // In this case, generate a class tree that represents the 4199 // bound class, ... 4200 JCExpression extending; 4201 List<JCExpression> implementing; 4202 if (!bounds.head.type.isInterface()) { 4203 extending = bounds.head; 4204 implementing = bounds.tail; 4205 } else { 4206 extending = null; 4207 implementing = bounds; 4208 } 4209 JCClassDecl cd = make.at(tree).ClassDef( 4210 make.Modifiers(PUBLIC | ABSTRACT), 4211 names.empty, List.<JCTypeParameter>nil(), 4212 extending, implementing, List.<JCTree>nil()); 4213 4214 ClassSymbol c = (ClassSymbol)owntype.tsym; 4215 Assert.check((c.flags() & COMPOUND) != 0); 4216 cd.sym = c; 4217 c.sourcefile = env.toplevel.sourcefile; 4218 4219 // ... and attribute the bound class 4220 c.flags_field |= UNATTRIBUTED; 4221 Env<AttrContext> cenv = enter.classEnv(cd, env); 4222 typeEnvs.put(c, cenv); 4223 attribClass(c); 4224 return owntype; 4225 } 4226 } 4227 4228 public void visitWildcard(JCWildcard tree) { 4229 //- System.err.println("visitWildcard("+tree+");");//DEBUG 4230 Type type = (tree.kind.kind == BoundKind.UNBOUND) 4231 ? syms.objectType 4232 : attribType(tree.inner, env); 4233 result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type), 4234 tree.kind.kind, 4235 syms.boundClass), 4236 KindSelector.TYP, resultInfo); 4237 } 4238 4239 public void visitAnnotation(JCAnnotation tree) { 4240 Assert.error("should be handled in annotate"); 4241 } 4242 4243 public void visitAnnotatedType(JCAnnotatedType tree) { 4244 attribAnnotationTypes(tree.annotations, env); 4245 Type underlyingType = attribType(tree.underlyingType, env); 4246 Type annotatedType = underlyingType.annotatedType(Annotations.TO_BE_SET); 4247 4248 if (!env.info.isNewClass) 4249 annotate.annotateTypeSecondStage(tree, tree.annotations, annotatedType); 4250 result = tree.type = annotatedType; 4251 } 4252 4253 public void visitErroneous(JCErroneous tree) { 4254 if (tree.errs != null) 4255 for (JCTree err : tree.errs) 4256 attribTree(err, env, new ResultInfo(KindSelector.ERR, pt())); 4257 result = tree.type = syms.errType; 4258 } 4259 4260 /** Default visitor method for all other trees. 4261 */ 4262 public void visitTree(JCTree tree) { 4263 throw new AssertionError(); 4264 } 4265 4266 /** 4267 * Attribute an env for either a top level tree or class or module declaration. 4268 */ 4269 public void attrib(Env<AttrContext> env) { 4270 switch (env.tree.getTag()) { 4271 case MODULEDEF: 4272 attribModule(env.tree.pos(), ((JCModuleDecl)env.tree).sym); 4273 break; 4274 case TOPLEVEL: 4275 attribTopLevel(env); 4276 break; 4277 default: 4278 attribClass(env.tree.pos(), env.enclClass.sym); 4279 } 4280 } 4281 4282 /** 4283 * Attribute a top level tree. These trees are encountered when the 4284 * package declaration has annotations. 4285 */ 4286 public void attribTopLevel(Env<AttrContext> env) { 4287 JCCompilationUnit toplevel = env.toplevel; 4288 try { 4289 annotate.flush(); 4290 } catch (CompletionFailure ex) { 4291 chk.completionError(toplevel.pos(), ex); 4292 } 4293 } 4294 4295 public void attribModule(DiagnosticPosition pos, ModuleSymbol m) { 4296 try { 4297 annotate.flush(); 4298 attribModule(m); 4299 } catch (CompletionFailure ex) { 4300 chk.completionError(pos, ex); 4301 } 4302 } 4303 4304 void attribModule(ModuleSymbol m) { 4305 // Get environment current at the point of module definition. 4306 Env<AttrContext> env = enter.typeEnvs.get(m); 4307 attribStat(env.tree, env); 4308 } 4309 4310 /** Main method: attribute class definition associated with given class symbol. 4311 * reporting completion failures at the given position. 4312 * @param pos The source position at which completion errors are to be 4313 * reported. 4314 * @param c The class symbol whose definition will be attributed. 4315 */ 4316 public void attribClass(DiagnosticPosition pos, ClassSymbol c) { 4317 try { 4318 annotate.flush(); 4319 attribClass(c); 4320 } catch (CompletionFailure ex) { 4321 chk.completionError(pos, ex); 4322 } 4323 } 4324 4325 /** Attribute class definition associated with given class symbol. 4326 * @param c The class symbol whose definition will be attributed. 4327 */ 4328 void attribClass(ClassSymbol c) throws CompletionFailure { 4329 if (c.type.hasTag(ERROR)) return; 4330 4331 // Check for cycles in the inheritance graph, which can arise from 4332 // ill-formed class files. 4333 chk.checkNonCyclic(null, c.type); 4334 4335 Type st = types.supertype(c.type); 4336 if ((c.flags_field & Flags.COMPOUND) == 0) { 4337 // First, attribute superclass. 4338 if (st.hasTag(CLASS)) 4339 attribClass((ClassSymbol)st.tsym); 4340 4341 // Next attribute owner, if it is a class. 4342 if (c.owner.kind == TYP && c.owner.type.hasTag(CLASS)) 4343 attribClass((ClassSymbol)c.owner); 4344 } 4345 4346 // The previous operations might have attributed the current class 4347 // if there was a cycle. So we test first whether the class is still 4348 // UNATTRIBUTED. 4349 if ((c.flags_field & UNATTRIBUTED) != 0) { 4350 c.flags_field &= ~UNATTRIBUTED; 4351 4352 // Get environment current at the point of class definition. 4353 Env<AttrContext> env = typeEnvs.get(c); 4354 4355 // The info.lint field in the envs stored in typeEnvs is deliberately uninitialized, 4356 // because the annotations were not available at the time the env was created. Therefore, 4357 // we look up the environment chain for the first enclosing environment for which the 4358 // lint value is set. Typically, this is the parent env, but might be further if there 4359 // are any envs created as a result of TypeParameter nodes. 4360 Env<AttrContext> lintEnv = env; 4361 while (lintEnv.info.lint == null) 4362 lintEnv = lintEnv.next; 4363 4364 // Having found the enclosing lint value, we can initialize the lint value for this class 4365 env.info.lint = lintEnv.info.lint.augment(c); 4366 4367 Lint prevLint = chk.setLint(env.info.lint); 4368 JavaFileObject prev = log.useSource(c.sourcefile); 4369 ResultInfo prevReturnRes = env.info.returnResult; 4370 4371 try { 4372 deferredLintHandler.flush(env.tree); 4373 env.info.returnResult = null; 4374 // java.lang.Enum may not be subclassed by a non-enum 4375 if (st.tsym == syms.enumSym && 4376 ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0)) 4377 log.error(env.tree.pos(), "enum.no.subclassing"); 4378 4379 // Enums may not be extended by source-level classes 4380 if (st.tsym != null && 4381 ((st.tsym.flags_field & Flags.ENUM) != 0) && 4382 ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) { 4383 log.error(env.tree.pos(), "enum.types.not.extensible"); 4384 } 4385 4386 if (isSerializable(c.type)) { 4387 env.info.isSerializable = true; 4388 } 4389 4390 attribClassBody(env, c); 4391 4392 chk.checkDeprecatedAnnotation(env.tree.pos(), c); 4393 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c); 4394 chk.checkFunctionalInterface((JCClassDecl) env.tree, c); 4395 } finally { 4396 env.info.returnResult = prevReturnRes; 4397 log.useSource(prev); 4398 chk.setLint(prevLint); 4399 } 4400 4401 } 4402 } 4403 4404 public void visitImport(JCImport tree) { 4405 // nothing to do 4406 } 4407 4408 public void visitModuleDef(JCModuleDecl tree) { 4409 tree.sym.completeUsesProvides(); 4410 } 4411 4412 /** Finish the attribution of a class. */ 4413 private void attribClassBody(Env<AttrContext> env, ClassSymbol c) { 4414 JCClassDecl tree = (JCClassDecl)env.tree; 4415 Assert.check(c == tree.sym); 4416 4417 // Validate type parameters, supertype and interfaces. 4418 attribStats(tree.typarams, env); 4419 if (!c.isAnonymous()) { 4420 //already checked if anonymous 4421 chk.validate(tree.typarams, env); 4422 chk.validate(tree.extending, env); 4423 chk.validate(tree.implementing, env); 4424 } 4425 4426 c.markAbstractIfNeeded(types); 4427 4428 // If this is a non-abstract class, check that it has no abstract 4429 // methods or unimplemented methods of an implemented interface. 4430 if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) { 4431 chk.checkAllDefined(tree.pos(), c); 4432 } 4433 4434 if ((c.flags() & ANNOTATION) != 0) { 4435 if (tree.implementing.nonEmpty()) 4436 log.error(tree.implementing.head.pos(), 4437 "cant.extend.intf.annotation"); 4438 if (tree.typarams.nonEmpty()) 4439 log.error(tree.typarams.head.pos(), 4440 "intf.annotation.cant.have.type.params"); 4441 4442 // If this annotation type has a @Repeatable, validate 4443 Attribute.Compound repeatable = c.getAnnotationTypeMetadata().getRepeatable(); 4444 // If this annotation type has a @Repeatable, validate 4445 if (repeatable != null) { 4446 // get diagnostic position for error reporting 4447 DiagnosticPosition cbPos = getDiagnosticPosition(tree, repeatable.type); 4448 Assert.checkNonNull(cbPos); 4449 4450 chk.validateRepeatable(c, repeatable, cbPos); 4451 } 4452 } else { 4453 // Check that all extended classes and interfaces 4454 // are compatible (i.e. no two define methods with same arguments 4455 // yet different return types). (JLS 8.4.6.3) 4456 chk.checkCompatibleSupertypes(tree.pos(), c.type); 4457 if (allowDefaultMethods) { 4458 chk.checkDefaultMethodClashes(tree.pos(), c.type); 4459 } 4460 } 4461 4462 // Check that class does not import the same parameterized interface 4463 // with two different argument lists. 4464 chk.checkClassBounds(tree.pos(), c.type); 4465 4466 tree.type = c.type; 4467 4468 for (List<JCTypeParameter> l = tree.typarams; 4469 l.nonEmpty(); l = l.tail) { 4470 Assert.checkNonNull(env.info.scope.findFirst(l.head.name)); 4471 } 4472 4473 // Check that a generic class doesn't extend Throwable 4474 if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType)) 4475 log.error(tree.extending.pos(), "generic.throwable"); 4476 4477 // Check that all methods which implement some 4478 // method conform to the method they implement. 4479 chk.checkImplementations(tree); 4480 4481 //check that a resource implementing AutoCloseable cannot throw InterruptedException 4482 checkAutoCloseable(tree.pos(), env, c.type); 4483 4484 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) { 4485 // Attribute declaration 4486 attribStat(l.head, env); 4487 // Check that declarations in inner classes are not static (JLS 8.1.2) 4488 // Make an exception for static constants. 4489 if (c.owner.kind != PCK && 4490 ((c.flags() & STATIC) == 0 || c.name == names.empty) && 4491 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) { 4492 Symbol sym = null; 4493 if (l.head.hasTag(VARDEF)) sym = ((JCVariableDecl) l.head).sym; 4494 if (sym == null || 4495 sym.kind != VAR || 4496 ((VarSymbol) sym).getConstValue() == null) 4497 log.error(l.head.pos(), "icls.cant.have.static.decl", c); 4498 } 4499 } 4500 4501 // Check for cycles among non-initial constructors. 4502 chk.checkCyclicConstructors(tree); 4503 4504 // Check for cycles among annotation elements. 4505 chk.checkNonCyclicElements(tree); 4506 4507 // Check for proper use of serialVersionUID 4508 if (env.info.lint.isEnabled(LintCategory.SERIAL) 4509 && isSerializable(c.type) 4510 && (c.flags() & Flags.ENUM) == 0 4511 && !c.isAnonymous() 4512 && checkForSerial(c)) { 4513 checkSerialVersionUID(tree, c); 4514 } 4515 if (allowTypeAnnos) { 4516 // Correctly organize the postions of the type annotations 4517 typeAnnotations.organizeTypeAnnotationsBodies(tree); 4518 4519 // Check type annotations applicability rules 4520 validateTypeAnnotations(tree, false); 4521 } 4522 } 4523 // where 4524 boolean checkForSerial(ClassSymbol c) { 4525 if ((c.flags() & ABSTRACT) == 0) { 4526 return true; 4527 } else { 4528 return c.members().anyMatch(anyNonAbstractOrDefaultMethod); 4529 } 4530 } 4531 4532 public static final Filter<Symbol> anyNonAbstractOrDefaultMethod = new Filter<Symbol>() { 4533 @Override 4534 public boolean accepts(Symbol s) { 4535 return s.kind == MTH && 4536 (s.flags() & (DEFAULT | ABSTRACT)) != ABSTRACT; 4537 } 4538 }; 4539 4540 /** get a diagnostic position for an attribute of Type t, or null if attribute missing */ 4541 private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) { 4542 for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) { 4543 if (types.isSameType(al.head.annotationType.type, t)) 4544 return al.head.pos(); 4545 } 4546 4547 return null; 4548 } 4549 4550 /** check if a type is a subtype of Serializable, if that is available. */ 4551 boolean isSerializable(Type t) { 4552 try { 4553 syms.serializableType.complete(); 4554 } 4555 catch (CompletionFailure e) { 4556 return false; 4557 } 4558 return types.isSubtype(t, syms.serializableType); 4559 } 4560 4561 /** Check that an appropriate serialVersionUID member is defined. */ 4562 private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) { 4563 4564 // check for presence of serialVersionUID 4565 VarSymbol svuid = null; 4566 for (Symbol sym : c.members().getSymbolsByName(names.serialVersionUID)) { 4567 if (sym.kind == VAR) { 4568 svuid = (VarSymbol)sym; 4569 break; 4570 } 4571 } 4572 4573 if (svuid == null) { 4574 log.warning(LintCategory.SERIAL, 4575 tree.pos(), "missing.SVUID", c); 4576 return; 4577 } 4578 4579 // check that it is static final 4580 if ((svuid.flags() & (STATIC | FINAL)) != 4581 (STATIC | FINAL)) 4582 log.warning(LintCategory.SERIAL, 4583 TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c); 4584 4585 // check that it is long 4586 else if (!svuid.type.hasTag(LONG)) 4587 log.warning(LintCategory.SERIAL, 4588 TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c); 4589 4590 // check constant 4591 else if (svuid.getConstValue() == null) 4592 log.warning(LintCategory.SERIAL, 4593 TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c); 4594 } 4595 4596 private Type capture(Type type) { 4597 return types.capture(type); 4598 } 4599 4600 public void validateTypeAnnotations(JCTree tree, boolean sigOnly) { 4601 tree.accept(new TypeAnnotationsValidator(sigOnly)); 4602 } 4603 //where 4604 private final class TypeAnnotationsValidator extends TreeScanner { 4605 4606 private final boolean sigOnly; 4607 public TypeAnnotationsValidator(boolean sigOnly) { 4608 this.sigOnly = sigOnly; 4609 } 4610 4611 public void visitAnnotation(JCAnnotation tree) { 4612 chk.validateTypeAnnotation(tree, false); 4613 super.visitAnnotation(tree); 4614 } 4615 public void visitAnnotatedType(JCAnnotatedType tree) { 4616 if (!tree.underlyingType.type.isErroneous()) { 4617 super.visitAnnotatedType(tree); 4618 } 4619 } 4620 public void visitTypeParameter(JCTypeParameter tree) { 4621 chk.validateTypeAnnotations(tree.annotations, true); 4622 scan(tree.bounds); 4623 // Don't call super. 4624 // This is needed because above we call validateTypeAnnotation with 4625 // false, which would forbid annotations on type parameters. 4626 // super.visitTypeParameter(tree); 4627 } 4628 public void visitMethodDef(JCMethodDecl tree) { 4629 if (tree.recvparam != null && 4630 !tree.recvparam.vartype.type.isErroneous()) { 4631 checkForDeclarationAnnotations(tree.recvparam.mods.annotations, 4632 tree.recvparam.vartype.type.tsym); 4633 } 4634 if (tree.restype != null && tree.restype.type != null) { 4635 validateAnnotatedType(tree.restype, tree.restype.type); 4636 } 4637 if (sigOnly) { 4638 scan(tree.mods); 4639 scan(tree.restype); 4640 scan(tree.typarams); 4641 scan(tree.recvparam); 4642 scan(tree.params); 4643 scan(tree.thrown); 4644 } else { 4645 scan(tree.defaultValue); 4646 scan(tree.body); 4647 } 4648 } 4649 public void visitVarDef(final JCVariableDecl tree) { 4650 //System.err.println("validateTypeAnnotations.visitVarDef " + tree); 4651 if (tree.sym != null && tree.sym.type != null) 4652 validateAnnotatedType(tree.vartype, tree.sym.type); 4653 scan(tree.mods); 4654 scan(tree.vartype); 4655 if (!sigOnly) { 4656 scan(tree.init); 4657 } 4658 } 4659 public void visitTypeCast(JCTypeCast tree) { 4660 if (tree.clazz != null && tree.clazz.type != null) 4661 validateAnnotatedType(tree.clazz, tree.clazz.type); 4662 super.visitTypeCast(tree); 4663 } 4664 public void visitTypeTest(JCInstanceOf tree) { 4665 if (tree.clazz != null && tree.clazz.type != null) 4666 validateAnnotatedType(tree.clazz, tree.clazz.type); 4667 super.visitTypeTest(tree); 4668 } 4669 public void visitNewClass(JCNewClass tree) { 4670 if (tree.clazz != null && tree.clazz.type != null) { 4671 if (tree.clazz.hasTag(ANNOTATED_TYPE)) { 4672 checkForDeclarationAnnotations(((JCAnnotatedType) tree.clazz).annotations, 4673 tree.clazz.type.tsym); 4674 } 4675 if (tree.def != null) { 4676 checkForDeclarationAnnotations(tree.def.mods.annotations, tree.clazz.type.tsym); 4677 } 4678 4679 validateAnnotatedType(tree.clazz, tree.clazz.type); 4680 } 4681 super.visitNewClass(tree); 4682 } 4683 public void visitNewArray(JCNewArray tree) { 4684 if (tree.elemtype != null && tree.elemtype.type != null) { 4685 if (tree.elemtype.hasTag(ANNOTATED_TYPE)) { 4686 checkForDeclarationAnnotations(((JCAnnotatedType) tree.elemtype).annotations, 4687 tree.elemtype.type.tsym); 4688 } 4689 validateAnnotatedType(tree.elemtype, tree.elemtype.type); 4690 } 4691 super.visitNewArray(tree); 4692 } 4693 public void visitClassDef(JCClassDecl tree) { 4694 //System.err.println("validateTypeAnnotations.visitClassDef " + tree); 4695 if (sigOnly) { 4696 scan(tree.mods); 4697 scan(tree.typarams); 4698 scan(tree.extending); 4699 scan(tree.implementing); 4700 } 4701 for (JCTree member : tree.defs) { 4702 if (member.hasTag(Tag.CLASSDEF)) { 4703 continue; 4704 } 4705 scan(member); 4706 } 4707 } 4708 public void visitBlock(JCBlock tree) { 4709 if (!sigOnly) { 4710 scan(tree.stats); 4711 } 4712 } 4713 4714 /* I would want to model this after 4715 * com.sun.tools.javac.comp.Check.Validator.visitSelectInternal(JCFieldAccess) 4716 * and override visitSelect and visitTypeApply. 4717 * However, we only set the annotated type in the top-level type 4718 * of the symbol. 4719 * Therefore, we need to override each individual location where a type 4720 * can occur. 4721 */ 4722 private void validateAnnotatedType(final JCTree errtree, final Type type) { 4723 //System.err.println("Attr.validateAnnotatedType: " + errtree + " type: " + type); 4724 4725 if (type.isPrimitiveOrVoid()) { 4726 return; 4727 } 4728 4729 JCTree enclTr = errtree; 4730 Type enclTy = type; 4731 4732 boolean repeat = true; 4733 while (repeat) { 4734 if (enclTr.hasTag(TYPEAPPLY)) { 4735 List<Type> tyargs = enclTy.getTypeArguments(); 4736 List<JCExpression> trargs = ((JCTypeApply)enclTr).getTypeArguments(); 4737 if (trargs.length() > 0) { 4738 // Nothing to do for diamonds 4739 if (tyargs.length() == trargs.length()) { 4740 for (int i = 0; i < tyargs.length(); ++i) { 4741 validateAnnotatedType(trargs.get(i), tyargs.get(i)); 4742 } 4743 } 4744 // If the lengths don't match, it's either a diamond 4745 // or some nested type that redundantly provides 4746 // type arguments in the tree. 4747 } 4748 4749 // Look at the clazz part of a generic type 4750 enclTr = ((JCTree.JCTypeApply)enclTr).clazz; 4751 } 4752 4753 if (enclTr.hasTag(SELECT)) { 4754 enclTr = ((JCTree.JCFieldAccess)enclTr).getExpression(); 4755 if (enclTy != null && 4756 !enclTy.hasTag(NONE)) { 4757 enclTy = enclTy.getEnclosingType(); 4758 } 4759 } else if (enclTr.hasTag(ANNOTATED_TYPE)) { 4760 JCAnnotatedType at = (JCTree.JCAnnotatedType) enclTr; 4761 if (enclTy == null || enclTy.hasTag(NONE)) { 4762 if (at.getAnnotations().size() == 1) { 4763 log.error(at.underlyingType.pos(), "cant.type.annotate.scoping.1", at.getAnnotations().head.attribute); 4764 } else { 4765 ListBuffer<Attribute.Compound> comps = new ListBuffer<>(); 4766 for (JCAnnotation an : at.getAnnotations()) { 4767 comps.add(an.attribute); 4768 } 4769 log.error(at.underlyingType.pos(), "cant.type.annotate.scoping", comps.toList()); 4770 } 4771 repeat = false; 4772 } 4773 enclTr = at.underlyingType; 4774 // enclTy doesn't need to be changed 4775 } else if (enclTr.hasTag(IDENT)) { 4776 repeat = false; 4777 } else if (enclTr.hasTag(JCTree.Tag.WILDCARD)) { 4778 JCWildcard wc = (JCWildcard) enclTr; 4779 if (wc.getKind() == JCTree.Kind.EXTENDS_WILDCARD) { 4780 validateAnnotatedType(wc.getBound(), ((WildcardType)enclTy).getExtendsBound()); 4781 } else if (wc.getKind() == JCTree.Kind.SUPER_WILDCARD) { 4782 validateAnnotatedType(wc.getBound(), ((WildcardType)enclTy).getSuperBound()); 4783 } else { 4784 // Nothing to do for UNBOUND 4785 } 4786 repeat = false; 4787 } else if (enclTr.hasTag(TYPEARRAY)) { 4788 JCArrayTypeTree art = (JCArrayTypeTree) enclTr; 4789 validateAnnotatedType(art.getType(), ((ArrayType)enclTy).getComponentType()); 4790 repeat = false; 4791 } else if (enclTr.hasTag(TYPEUNION)) { 4792 JCTypeUnion ut = (JCTypeUnion) enclTr; 4793 for (JCTree t : ut.getTypeAlternatives()) { 4794 validateAnnotatedType(t, t.type); 4795 } 4796 repeat = false; 4797 } else if (enclTr.hasTag(TYPEINTERSECTION)) { 4798 JCTypeIntersection it = (JCTypeIntersection) enclTr; 4799 for (JCTree t : it.getBounds()) { 4800 validateAnnotatedType(t, t.type); 4801 } 4802 repeat = false; 4803 } else if (enclTr.getKind() == JCTree.Kind.PRIMITIVE_TYPE || 4804 enclTr.getKind() == JCTree.Kind.ERRONEOUS) { 4805 repeat = false; 4806 } else { 4807 Assert.error("Unexpected tree: " + enclTr + " with kind: " + enclTr.getKind() + 4808 " within: "+ errtree + " with kind: " + errtree.getKind()); 4809 } 4810 } 4811 } 4812 4813 private void checkForDeclarationAnnotations(List<? extends JCAnnotation> annotations, 4814 Symbol sym) { 4815 // Ensure that no declaration annotations are present. 4816 // Note that a tree type might be an AnnotatedType with 4817 // empty annotations, if only declaration annotations were given. 4818 // This method will raise an error for such a type. 4819 for (JCAnnotation ai : annotations) { 4820 if (!ai.type.isErroneous() && 4821 typeAnnotations.annotationTargetType(ai.attribute, sym) == TypeAnnotations.AnnotationType.DECLARATION) { 4822 log.error(ai.pos(), Errors.AnnotationTypeNotApplicableToType(ai.type)); 4823 } 4824 } 4825 } 4826 } 4827 4828 // <editor-fold desc="post-attribution visitor"> 4829 4830 /** 4831 * Handle missing types/symbols in an AST. This routine is useful when 4832 * the compiler has encountered some errors (which might have ended up 4833 * terminating attribution abruptly); if the compiler is used in fail-over 4834 * mode (e.g. by an IDE) and the AST contains semantic errors, this routine 4835 * prevents NPE to be progagated during subsequent compilation steps. 4836 */ 4837 public void postAttr(JCTree tree) { 4838 new PostAttrAnalyzer().scan(tree); 4839 } 4840 4841 class PostAttrAnalyzer extends TreeScanner { 4842 4843 private void initTypeIfNeeded(JCTree that) { 4844 if (that.type == null) { 4845 if (that.hasTag(METHODDEF)) { 4846 that.type = dummyMethodType((JCMethodDecl)that); 4847 } else { 4848 that.type = syms.unknownType; 4849 } 4850 } 4851 } 4852 4853 /* Construct a dummy method type. If we have a method declaration, 4854 * and the declared return type is void, then use that return type 4855 * instead of UNKNOWN to avoid spurious error messages in lambda 4856 * bodies (see:JDK-8041704). 4857 */ 4858 private Type dummyMethodType(JCMethodDecl md) { 4859 Type restype = syms.unknownType; 4860 if (md != null && md.restype.hasTag(TYPEIDENT)) { 4861 JCPrimitiveTypeTree prim = (JCPrimitiveTypeTree)md.restype; 4862 if (prim.typetag == VOID) 4863 restype = syms.voidType; 4864 } 4865 return new MethodType(List.<Type>nil(), restype, 4866 List.<Type>nil(), syms.methodClass); 4867 } 4868 private Type dummyMethodType() { 4869 return dummyMethodType(null); 4870 } 4871 4872 @Override 4873 public void scan(JCTree tree) { 4874 if (tree == null) return; 4875 if (tree instanceof JCExpression) { 4876 initTypeIfNeeded(tree); 4877 } 4878 super.scan(tree); 4879 } 4880 4881 @Override 4882 public void visitIdent(JCIdent that) { 4883 if (that.sym == null) { 4884 that.sym = syms.unknownSymbol; 4885 } 4886 } 4887 4888 @Override 4889 public void visitSelect(JCFieldAccess that) { 4890 if (that.sym == null) { 4891 that.sym = syms.unknownSymbol; 4892 } 4893 super.visitSelect(that); 4894 } 4895 4896 @Override 4897 public void visitClassDef(JCClassDecl that) { 4898 initTypeIfNeeded(that); 4899 if (that.sym == null) { 4900 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol); 4901 } 4902 super.visitClassDef(that); 4903 } 4904 4905 @Override 4906 public void visitMethodDef(JCMethodDecl that) { 4907 initTypeIfNeeded(that); 4908 if (that.sym == null) { 4909 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol); 4910 } 4911 super.visitMethodDef(that); 4912 } 4913 4914 @Override 4915 public void visitVarDef(JCVariableDecl that) { 4916 initTypeIfNeeded(that); 4917 if (that.sym == null) { 4918 that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol); 4919 that.sym.adr = 0; 4920 } 4921 super.visitVarDef(that); 4922 } 4923 4924 @Override 4925 public void visitNewClass(JCNewClass that) { 4926 if (that.constructor == null) { 4927 that.constructor = new MethodSymbol(0, names.init, 4928 dummyMethodType(), syms.noSymbol); 4929 } 4930 if (that.constructorType == null) { 4931 that.constructorType = syms.unknownType; 4932 } 4933 super.visitNewClass(that); 4934 } 4935 4936 @Override 4937 public void visitAssignop(JCAssignOp that) { 4938 if (that.operator == null) { 4939 that.operator = new OperatorSymbol(names.empty, dummyMethodType(), 4940 -1, syms.noSymbol); 4941 } 4942 super.visitAssignop(that); 4943 } 4944 4945 @Override 4946 public void visitBinary(JCBinary that) { 4947 if (that.operator == null) { 4948 that.operator = new OperatorSymbol(names.empty, dummyMethodType(), 4949 -1, syms.noSymbol); 4950 } 4951 super.visitBinary(that); 4952 } 4953 4954 @Override 4955 public void visitUnary(JCUnary that) { 4956 if (that.operator == null) { 4957 that.operator = new OperatorSymbol(names.empty, dummyMethodType(), 4958 -1, syms.noSymbol); 4959 } 4960 super.visitUnary(that); 4961 } 4962 4963 @Override 4964 public void visitLambda(JCLambda that) { 4965 super.visitLambda(that); 4966 if (that.targets == null) { 4967 that.targets = List.nil(); 4968 } 4969 } 4970 4971 @Override 4972 public void visitReference(JCMemberReference that) { 4973 super.visitReference(that); 4974 if (that.sym == null) { 4975 that.sym = new MethodSymbol(0, names.empty, dummyMethodType(), 4976 syms.noSymbol); 4977 } 4978 if (that.targets == null) { 4979 that.targets = List.nil(); 4980 } 4981 } 4982 } 4983 // </editor-fold> 4984 4985 public void setPackageSymbols(JCExpression pid, Symbol pkg) { 4986 new TreeScanner() { 4987 Symbol packge = pkg; 4988 @Override 4989 public void visitIdent(JCIdent that) { 4990 that.sym = packge; 4991 } 4992 4993 @Override 4994 public void visitSelect(JCFieldAccess that) { 4995 that.sym = packge; 4996 packge = packge.owner; 4997 super.visitSelect(that); 4998 } 4999 }.scan(pid); 5000 } 5001 5002} 5003