src/share/classes/com/sun/tools/javac/comp/Attr.java

Thu, 31 Aug 2017 15:17:03 +0800

author
aoqi
date
Thu, 31 Aug 2017 15:17:03 +0800
changeset 2525
2eb010b6cb22
parent 2428
ce1d9dd2e9eb
parent 0
959103a6100f
child 2702
9ca8d8713094
permissions
-rw-r--r--

merge

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

mercurial