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

Thu, 12 Oct 2017 19:50:01 +0800

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

mercurial