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

Fri, 18 Jun 2010 15:12:04 -0700

author
jrose
date
Fri, 18 Jun 2010 15:12:04 -0700
changeset 573
005bec70ca27
parent 567
593a59e40bdb
parent 571
f0e3ec1f9d9f
child 591
d1d7595fa824
permissions
-rw-r--r--

Merge

duke@1 1 /*
ohair@554 2 * Copyright (c) 1999, 2009, Oracle and/or its affiliates. All rights reserved.
duke@1 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
duke@1 4 *
duke@1 5 * This code is free software; you can redistribute it and/or modify it
duke@1 6 * under the terms of the GNU General Public License version 2 only, as
ohair@554 7 * published by the Free Software Foundation. Oracle designates this
duke@1 8 * particular file as subject to the "Classpath" exception as provided
ohair@554 9 * by Oracle in the LICENSE file that accompanied this code.
duke@1 10 *
duke@1 11 * This code is distributed in the hope that it will be useful, but WITHOUT
duke@1 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
duke@1 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
duke@1 14 * version 2 for more details (a copy is included in the LICENSE file that
duke@1 15 * accompanied this code).
duke@1 16 *
duke@1 17 * You should have received a copy of the GNU General Public License version
duke@1 18 * 2 along with this work; if not, write to the Free Software Foundation,
duke@1 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
duke@1 20 *
ohair@554 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
ohair@554 22 * or visit www.oracle.com if you need additional information or have any
ohair@554 23 * questions.
duke@1 24 */
duke@1 25
duke@1 26 package com.sun.tools.javac.comp;
duke@1 27
duke@1 28 import java.util.*;
duke@1 29 import java.util.Set;
duke@1 30 import javax.lang.model.element.ElementKind;
duke@1 31 import javax.tools.JavaFileObject;
duke@1 32
duke@1 33 import com.sun.tools.javac.code.*;
duke@1 34 import com.sun.tools.javac.jvm.*;
duke@1 35 import com.sun.tools.javac.tree.*;
duke@1 36 import com.sun.tools.javac.util.*;
duke@1 37 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
duke@1 38 import com.sun.tools.javac.util.List;
duke@1 39
duke@1 40 import com.sun.tools.javac.jvm.Target;
duke@1 41 import com.sun.tools.javac.code.Symbol.*;
duke@1 42 import com.sun.tools.javac.tree.JCTree.*;
duke@1 43 import com.sun.tools.javac.code.Type.*;
duke@1 44
duke@1 45 import com.sun.source.tree.IdentifierTree;
duke@1 46 import com.sun.source.tree.MemberSelectTree;
duke@1 47 import com.sun.source.tree.TreeVisitor;
duke@1 48 import com.sun.source.util.SimpleTreeVisitor;
duke@1 49
duke@1 50 import static com.sun.tools.javac.code.Flags.*;
duke@1 51 import static com.sun.tools.javac.code.Kinds.*;
duke@1 52 import static com.sun.tools.javac.code.TypeTags.*;
duke@1 53
duke@1 54 /** This is the main context-dependent analysis phase in GJC. It
duke@1 55 * encompasses name resolution, type checking and constant folding as
duke@1 56 * subtasks. Some subtasks involve auxiliary classes.
duke@1 57 * @see Check
duke@1 58 * @see Resolve
duke@1 59 * @see ConstFold
duke@1 60 * @see Infer
duke@1 61 *
duke@1 62 * <p><b>This is NOT part of any API supported by Sun Microsystems. If
duke@1 63 * you write code that depends on this, you do so at your own risk.
duke@1 64 * This code and its internal interfaces are subject to change or
duke@1 65 * deletion without notice.</b>
duke@1 66 */
duke@1 67 public class Attr extends JCTree.Visitor {
duke@1 68 protected static final Context.Key<Attr> attrKey =
duke@1 69 new Context.Key<Attr>();
duke@1 70
jjg@113 71 final Names names;
duke@1 72 final Log log;
duke@1 73 final Symtab syms;
duke@1 74 final Resolve rs;
mcimadamore@537 75 final Infer infer;
duke@1 76 final Check chk;
duke@1 77 final MemberEnter memberEnter;
duke@1 78 final TreeMaker make;
duke@1 79 final ConstFold cfolder;
duke@1 80 final Enter enter;
duke@1 81 final Target target;
duke@1 82 final Types types;
mcimadamore@89 83 final JCDiagnostic.Factory diags;
duke@1 84 final Annotate annotate;
duke@1 85
duke@1 86 public static Attr instance(Context context) {
duke@1 87 Attr instance = context.get(attrKey);
duke@1 88 if (instance == null)
duke@1 89 instance = new Attr(context);
duke@1 90 return instance;
duke@1 91 }
duke@1 92
duke@1 93 protected Attr(Context context) {
duke@1 94 context.put(attrKey, this);
duke@1 95
jjg@113 96 names = Names.instance(context);
duke@1 97 log = Log.instance(context);
duke@1 98 syms = Symtab.instance(context);
duke@1 99 rs = Resolve.instance(context);
duke@1 100 chk = Check.instance(context);
duke@1 101 memberEnter = MemberEnter.instance(context);
duke@1 102 make = TreeMaker.instance(context);
duke@1 103 enter = Enter.instance(context);
mcimadamore@537 104 infer = Infer.instance(context);
duke@1 105 cfolder = ConstFold.instance(context);
duke@1 106 target = Target.instance(context);
duke@1 107 types = Types.instance(context);
mcimadamore@89 108 diags = JCDiagnostic.Factory.instance(context);
duke@1 109 annotate = Annotate.instance(context);
duke@1 110
duke@1 111 Options options = Options.instance(context);
duke@1 112
duke@1 113 Source source = Source.instance(context);
duke@1 114 allowGenerics = source.allowGenerics();
duke@1 115 allowVarargs = source.allowVarargs();
duke@1 116 allowEnums = source.allowEnums();
duke@1 117 allowBoxing = source.allowBoxing();
duke@1 118 allowCovariantReturns = source.allowCovariantReturns();
duke@1 119 allowAnonOuterThis = source.allowAnonOuterThis();
darcy@430 120 allowStringsInSwitch = source.allowStringsInSwitch();
darcy@430 121 sourceName = source.name;
duke@1 122 relax = (options.get("-retrofit") != null ||
duke@1 123 options.get("-relax") != null);
duke@1 124 useBeforeDeclarationWarning = options.get("useBeforeDeclarationWarning") != null;
jjg@377 125 enableSunApiLintControl = options.get("enableSunApiLintControl") != null;
duke@1 126 }
duke@1 127
duke@1 128 /** Switch: relax some constraints for retrofit mode.
duke@1 129 */
duke@1 130 boolean relax;
duke@1 131
duke@1 132 /** Switch: support generics?
duke@1 133 */
duke@1 134 boolean allowGenerics;
duke@1 135
duke@1 136 /** Switch: allow variable-arity methods.
duke@1 137 */
duke@1 138 boolean allowVarargs;
duke@1 139
duke@1 140 /** Switch: support enums?
duke@1 141 */
duke@1 142 boolean allowEnums;
duke@1 143
duke@1 144 /** Switch: support boxing and unboxing?
duke@1 145 */
duke@1 146 boolean allowBoxing;
duke@1 147
duke@1 148 /** Switch: support covariant result types?
duke@1 149 */
duke@1 150 boolean allowCovariantReturns;
duke@1 151
duke@1 152 /** Switch: allow references to surrounding object from anonymous
duke@1 153 * objects during constructor call?
duke@1 154 */
duke@1 155 boolean allowAnonOuterThis;
duke@1 156
duke@1 157 /**
duke@1 158 * Switch: warn about use of variable before declaration?
duke@1 159 * RFE: 6425594
duke@1 160 */
duke@1 161 boolean useBeforeDeclarationWarning;
duke@1 162
jjg@377 163 /**
jjg@377 164 * Switch: allow lint infrastructure to control Sun proprietary
jjg@377 165 * API warnings.
jjg@377 166 */
jjg@377 167 boolean enableSunApiLintControl;
jjg@377 168
darcy@430 169 /**
darcy@430 170 * Switch: allow strings in switch?
darcy@430 171 */
darcy@430 172 boolean allowStringsInSwitch;
darcy@430 173
darcy@430 174 /**
darcy@430 175 * Switch: name of source level; used for error reporting.
darcy@430 176 */
darcy@430 177 String sourceName;
darcy@430 178
duke@1 179 /** Check kind and type of given tree against protokind and prototype.
duke@1 180 * If check succeeds, store type in tree and return it.
duke@1 181 * If check fails, store errType in tree and return it.
duke@1 182 * No checks are performed if the prototype is a method type.
jjg@110 183 * It is not necessary in this case since we know that kind and type
duke@1 184 * are correct.
duke@1 185 *
duke@1 186 * @param tree The tree whose kind and type is checked
duke@1 187 * @param owntype The computed type of the tree
duke@1 188 * @param ownkind The computed kind of the tree
duke@1 189 * @param pkind The expected kind (or: protokind) of the tree
duke@1 190 * @param pt The expected type (or: prototype) of the tree
duke@1 191 */
duke@1 192 Type check(JCTree tree, Type owntype, int ownkind, int pkind, Type pt) {
duke@1 193 if (owntype.tag != ERROR && pt.tag != METHOD && pt.tag != FORALL) {
duke@1 194 if ((ownkind & ~pkind) == 0) {
duke@1 195 owntype = chk.checkType(tree.pos(), owntype, pt);
duke@1 196 } else {
duke@1 197 log.error(tree.pos(), "unexpected.type",
mcimadamore@80 198 kindNames(pkind),
mcimadamore@80 199 kindName(ownkind));
jjg@110 200 owntype = types.createErrorType(owntype);
duke@1 201 }
duke@1 202 }
duke@1 203 tree.type = owntype;
duke@1 204 return owntype;
duke@1 205 }
duke@1 206
duke@1 207 /** Is given blank final variable assignable, i.e. in a scope where it
duke@1 208 * may be assigned to even though it is final?
duke@1 209 * @param v The blank final variable.
duke@1 210 * @param env The current environment.
duke@1 211 */
duke@1 212 boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
duke@1 213 Symbol owner = env.info.scope.owner;
duke@1 214 // owner refers to the innermost variable, method or
duke@1 215 // initializer block declaration at this point.
duke@1 216 return
duke@1 217 v.owner == owner
duke@1 218 ||
duke@1 219 ((owner.name == names.init || // i.e. we are in a constructor
duke@1 220 owner.kind == VAR || // i.e. we are in a variable initializer
duke@1 221 (owner.flags() & BLOCK) != 0) // i.e. we are in an initializer block
duke@1 222 &&
duke@1 223 v.owner == owner.owner
duke@1 224 &&
duke@1 225 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
duke@1 226 }
duke@1 227
duke@1 228 /** Check that variable can be assigned to.
duke@1 229 * @param pos The current source code position.
duke@1 230 * @param v The assigned varaible
duke@1 231 * @param base If the variable is referred to in a Select, the part
duke@1 232 * to the left of the `.', null otherwise.
duke@1 233 * @param env The current environment.
duke@1 234 */
duke@1 235 void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
duke@1 236 if ((v.flags() & FINAL) != 0 &&
duke@1 237 ((v.flags() & HASINIT) != 0
duke@1 238 ||
duke@1 239 !((base == null ||
duke@1 240 (base.getTag() == JCTree.IDENT && TreeInfo.name(base) == names._this)) &&
duke@1 241 isAssignableAsBlankFinal(v, env)))) {
duke@1 242 log.error(pos, "cant.assign.val.to.final.var", v);
duke@1 243 }
duke@1 244 }
duke@1 245
duke@1 246 /** Does tree represent a static reference to an identifier?
duke@1 247 * It is assumed that tree is either a SELECT or an IDENT.
duke@1 248 * We have to weed out selects from non-type names here.
duke@1 249 * @param tree The candidate tree.
duke@1 250 */
duke@1 251 boolean isStaticReference(JCTree tree) {
duke@1 252 if (tree.getTag() == JCTree.SELECT) {
duke@1 253 Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
duke@1 254 if (lsym == null || lsym.kind != TYP) {
duke@1 255 return false;
duke@1 256 }
duke@1 257 }
duke@1 258 return true;
duke@1 259 }
duke@1 260
duke@1 261 /** Is this symbol a type?
duke@1 262 */
duke@1 263 static boolean isType(Symbol sym) {
duke@1 264 return sym != null && sym.kind == TYP;
duke@1 265 }
duke@1 266
duke@1 267 /** The current `this' symbol.
duke@1 268 * @param env The current environment.
duke@1 269 */
duke@1 270 Symbol thisSym(DiagnosticPosition pos, Env<AttrContext> env) {
duke@1 271 return rs.resolveSelf(pos, env, env.enclClass.sym, names._this);
duke@1 272 }
duke@1 273
duke@1 274 /** Attribute a parsed identifier.
duke@1 275 * @param tree Parsed identifier name
duke@1 276 * @param topLevel The toplevel to use
duke@1 277 */
duke@1 278 public Symbol attribIdent(JCTree tree, JCCompilationUnit topLevel) {
duke@1 279 Env<AttrContext> localEnv = enter.topLevelEnv(topLevel);
duke@1 280 localEnv.enclClass = make.ClassDef(make.Modifiers(0),
duke@1 281 syms.errSymbol.name,
duke@1 282 null, null, null, null);
duke@1 283 localEnv.enclClass.sym = syms.errSymbol;
duke@1 284 return tree.accept(identAttributer, localEnv);
duke@1 285 }
duke@1 286 // where
duke@1 287 private TreeVisitor<Symbol,Env<AttrContext>> identAttributer = new IdentAttributer();
duke@1 288 private class IdentAttributer extends SimpleTreeVisitor<Symbol,Env<AttrContext>> {
duke@1 289 @Override
duke@1 290 public Symbol visitMemberSelect(MemberSelectTree node, Env<AttrContext> env) {
duke@1 291 Symbol site = visit(node.getExpression(), env);
duke@1 292 if (site.kind == ERR)
duke@1 293 return site;
duke@1 294 Name name = (Name)node.getIdentifier();
duke@1 295 if (site.kind == PCK) {
duke@1 296 env.toplevel.packge = (PackageSymbol)site;
duke@1 297 return rs.findIdentInPackage(env, (TypeSymbol)site, name, TYP | PCK);
duke@1 298 } else {
duke@1 299 env.enclClass.sym = (ClassSymbol)site;
duke@1 300 return rs.findMemberType(env, site.asType(), name, (TypeSymbol)site);
duke@1 301 }
duke@1 302 }
duke@1 303
duke@1 304 @Override
duke@1 305 public Symbol visitIdentifier(IdentifierTree node, Env<AttrContext> env) {
duke@1 306 return rs.findIdent(env, (Name)node.getName(), TYP | PCK);
duke@1 307 }
duke@1 308 }
duke@1 309
duke@1 310 public Type coerce(Type etype, Type ttype) {
duke@1 311 return cfolder.coerce(etype, ttype);
duke@1 312 }
duke@1 313
duke@1 314 public Type attribType(JCTree node, TypeSymbol sym) {
duke@1 315 Env<AttrContext> env = enter.typeEnvs.get(sym);
duke@1 316 Env<AttrContext> localEnv = env.dup(node, env.info.dup());
duke@1 317 return attribTree(node, localEnv, Kinds.TYP, Type.noType);
duke@1 318 }
duke@1 319
duke@1 320 public Env<AttrContext> attribExprToTree(JCTree expr, Env<AttrContext> env, JCTree tree) {
duke@1 321 breakTree = tree;
mcimadamore@303 322 JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
duke@1 323 try {
duke@1 324 attribExpr(expr, env);
duke@1 325 } catch (BreakAttr b) {
duke@1 326 return b.env;
duke@1 327 } finally {
duke@1 328 breakTree = null;
duke@1 329 log.useSource(prev);
duke@1 330 }
duke@1 331 return env;
duke@1 332 }
duke@1 333
duke@1 334 public Env<AttrContext> attribStatToTree(JCTree stmt, Env<AttrContext> env, JCTree tree) {
duke@1 335 breakTree = tree;
mcimadamore@303 336 JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
duke@1 337 try {
duke@1 338 attribStat(stmt, env);
duke@1 339 } catch (BreakAttr b) {
duke@1 340 return b.env;
duke@1 341 } finally {
duke@1 342 breakTree = null;
duke@1 343 log.useSource(prev);
duke@1 344 }
duke@1 345 return env;
duke@1 346 }
duke@1 347
duke@1 348 private JCTree breakTree = null;
duke@1 349
duke@1 350 private static class BreakAttr extends RuntimeException {
duke@1 351 static final long serialVersionUID = -6924771130405446405L;
duke@1 352 private Env<AttrContext> env;
duke@1 353 private BreakAttr(Env<AttrContext> env) {
duke@1 354 this.env = env;
duke@1 355 }
duke@1 356 }
duke@1 357
duke@1 358
duke@1 359 /* ************************************************************************
duke@1 360 * Visitor methods
duke@1 361 *************************************************************************/
duke@1 362
duke@1 363 /** Visitor argument: the current environment.
duke@1 364 */
duke@1 365 Env<AttrContext> env;
duke@1 366
duke@1 367 /** Visitor argument: the currently expected proto-kind.
duke@1 368 */
duke@1 369 int pkind;
duke@1 370
duke@1 371 /** Visitor argument: the currently expected proto-type.
duke@1 372 */
duke@1 373 Type pt;
duke@1 374
duke@1 375 /** Visitor result: the computed type.
duke@1 376 */
duke@1 377 Type result;
duke@1 378
duke@1 379 /** Visitor method: attribute a tree, catching any completion failure
duke@1 380 * exceptions. Return the tree's type.
duke@1 381 *
duke@1 382 * @param tree The tree to be visited.
duke@1 383 * @param env The environment visitor argument.
duke@1 384 * @param pkind The protokind visitor argument.
duke@1 385 * @param pt The prototype visitor argument.
duke@1 386 */
duke@1 387 Type attribTree(JCTree tree, Env<AttrContext> env, int pkind, Type pt) {
duke@1 388 Env<AttrContext> prevEnv = this.env;
duke@1 389 int prevPkind = this.pkind;
duke@1 390 Type prevPt = this.pt;
duke@1 391 try {
duke@1 392 this.env = env;
duke@1 393 this.pkind = pkind;
duke@1 394 this.pt = pt;
duke@1 395 tree.accept(this);
duke@1 396 if (tree == breakTree)
duke@1 397 throw new BreakAttr(env);
duke@1 398 return result;
duke@1 399 } catch (CompletionFailure ex) {
duke@1 400 tree.type = syms.errType;
duke@1 401 return chk.completionError(tree.pos(), ex);
duke@1 402 } finally {
duke@1 403 this.env = prevEnv;
duke@1 404 this.pkind = prevPkind;
duke@1 405 this.pt = prevPt;
duke@1 406 }
duke@1 407 }
duke@1 408
duke@1 409 /** Derived visitor method: attribute an expression tree.
duke@1 410 */
duke@1 411 public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) {
duke@1 412 return attribTree(tree, env, VAL, pt.tag != ERROR ? pt : Type.noType);
duke@1 413 }
duke@1 414
duke@1 415 /** Derived visitor method: attribute an expression tree with
duke@1 416 * no constraints on the computed type.
duke@1 417 */
duke@1 418 Type attribExpr(JCTree tree, Env<AttrContext> env) {
duke@1 419 return attribTree(tree, env, VAL, Type.noType);
duke@1 420 }
duke@1 421
duke@1 422 /** Derived visitor method: attribute a type tree.
duke@1 423 */
duke@1 424 Type attribType(JCTree tree, Env<AttrContext> env) {
mcimadamore@537 425 Type result = attribType(tree, env, Type.noType);
mcimadamore@537 426 return result;
mcimadamore@537 427 }
mcimadamore@537 428
mcimadamore@537 429 /** Derived visitor method: attribute a type tree.
mcimadamore@537 430 */
mcimadamore@537 431 Type attribType(JCTree tree, Env<AttrContext> env, Type pt) {
mcimadamore@537 432 Type result = attribTree(tree, env, TYP, pt);
duke@1 433 return result;
duke@1 434 }
duke@1 435
duke@1 436 /** Derived visitor method: attribute a statement or definition tree.
duke@1 437 */
duke@1 438 public Type attribStat(JCTree tree, Env<AttrContext> env) {
duke@1 439 return attribTree(tree, env, NIL, Type.noType);
duke@1 440 }
duke@1 441
duke@1 442 /** Attribute a list of expressions, returning a list of types.
duke@1 443 */
duke@1 444 List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) {
duke@1 445 ListBuffer<Type> ts = new ListBuffer<Type>();
duke@1 446 for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
duke@1 447 ts.append(attribExpr(l.head, env, pt));
duke@1 448 return ts.toList();
duke@1 449 }
duke@1 450
duke@1 451 /** Attribute a list of statements, returning nothing.
duke@1 452 */
duke@1 453 <T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) {
duke@1 454 for (List<T> l = trees; l.nonEmpty(); l = l.tail)
duke@1 455 attribStat(l.head, env);
duke@1 456 }
duke@1 457
duke@1 458 /** Attribute the arguments in a method call, returning a list of types.
duke@1 459 */
duke@1 460 List<Type> attribArgs(List<JCExpression> trees, Env<AttrContext> env) {
duke@1 461 ListBuffer<Type> argtypes = new ListBuffer<Type>();
duke@1 462 for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
duke@1 463 argtypes.append(chk.checkNonVoid(
duke@1 464 l.head.pos(), types.upperBound(attribTree(l.head, env, VAL, Infer.anyPoly))));
duke@1 465 return argtypes.toList();
duke@1 466 }
duke@1 467
duke@1 468 /** Attribute a type argument list, returning a list of types.
jrose@267 469 * Caller is responsible for calling checkRefTypes.
duke@1 470 */
jrose@267 471 List<Type> attribAnyTypes(List<JCExpression> trees, Env<AttrContext> env) {
duke@1 472 ListBuffer<Type> argtypes = new ListBuffer<Type>();
duke@1 473 for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
jrose@267 474 argtypes.append(attribType(l.head, env));
duke@1 475 return argtypes.toList();
duke@1 476 }
duke@1 477
jrose@267 478 /** Attribute a type argument list, returning a list of types.
jrose@267 479 * Check that all the types are references.
jrose@267 480 */
jrose@267 481 List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
jrose@267 482 List<Type> types = attribAnyTypes(trees, env);
jrose@267 483 return chk.checkRefTypes(trees, types);
jrose@267 484 }
duke@1 485
duke@1 486 /**
duke@1 487 * Attribute type variables (of generic classes or methods).
duke@1 488 * Compound types are attributed later in attribBounds.
duke@1 489 * @param typarams the type variables to enter
duke@1 490 * @param env the current environment
duke@1 491 */
duke@1 492 void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env) {
duke@1 493 for (JCTypeParameter tvar : typarams) {
duke@1 494 TypeVar a = (TypeVar)tvar.type;
mcimadamore@42 495 a.tsym.flags_field |= UNATTRIBUTED;
mcimadamore@42 496 a.bound = Type.noType;
duke@1 497 if (!tvar.bounds.isEmpty()) {
duke@1 498 List<Type> bounds = List.of(attribType(tvar.bounds.head, env));
duke@1 499 for (JCExpression bound : tvar.bounds.tail)
duke@1 500 bounds = bounds.prepend(attribType(bound, env));
duke@1 501 types.setBounds(a, bounds.reverse());
duke@1 502 } else {
duke@1 503 // if no bounds are given, assume a single bound of
duke@1 504 // java.lang.Object.
duke@1 505 types.setBounds(a, List.of(syms.objectType));
duke@1 506 }
mcimadamore@42 507 a.tsym.flags_field &= ~UNATTRIBUTED;
duke@1 508 }
duke@1 509 for (JCTypeParameter tvar : typarams)
duke@1 510 chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
duke@1 511 attribStats(typarams, env);
mcimadamore@42 512 }
mcimadamore@42 513
mcimadamore@42 514 void attribBounds(List<JCTypeParameter> typarams) {
duke@1 515 for (JCTypeParameter typaram : typarams) {
duke@1 516 Type bound = typaram.type.getUpperBound();
duke@1 517 if (bound != null && bound.tsym instanceof ClassSymbol) {
duke@1 518 ClassSymbol c = (ClassSymbol)bound.tsym;
duke@1 519 if ((c.flags_field & COMPOUND) != 0) {
duke@1 520 assert (c.flags_field & UNATTRIBUTED) != 0 : c;
duke@1 521 attribClass(typaram.pos(), c);
duke@1 522 }
duke@1 523 }
duke@1 524 }
duke@1 525 }
duke@1 526
duke@1 527 /**
duke@1 528 * Attribute the type references in a list of annotations.
duke@1 529 */
duke@1 530 void attribAnnotationTypes(List<JCAnnotation> annotations,
duke@1 531 Env<AttrContext> env) {
duke@1 532 for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
duke@1 533 JCAnnotation a = al.head;
duke@1 534 attribType(a.annotationType, env);
duke@1 535 }
duke@1 536 }
duke@1 537
duke@1 538 /** Attribute type reference in an `extends' or `implements' clause.
mcimadamore@537 539 * Supertypes of anonymous inner classes are usually already attributed.
duke@1 540 *
duke@1 541 * @param tree The tree making up the type reference.
duke@1 542 * @param env The environment current at the reference.
duke@1 543 * @param classExpected true if only a class is expected here.
duke@1 544 * @param interfaceExpected true if only an interface is expected here.
duke@1 545 */
duke@1 546 Type attribBase(JCTree tree,
duke@1 547 Env<AttrContext> env,
duke@1 548 boolean classExpected,
duke@1 549 boolean interfaceExpected,
duke@1 550 boolean checkExtensible) {
mcimadamore@537 551 Type t = tree.type != null ?
mcimadamore@537 552 tree.type :
mcimadamore@537 553 attribType(tree, env);
duke@1 554 return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible);
duke@1 555 }
duke@1 556 Type checkBase(Type t,
duke@1 557 JCTree tree,
duke@1 558 Env<AttrContext> env,
duke@1 559 boolean classExpected,
duke@1 560 boolean interfaceExpected,
duke@1 561 boolean checkExtensible) {
duke@1 562 if (t.tag == TYPEVAR && !classExpected && !interfaceExpected) {
duke@1 563 // check that type variable is already visible
duke@1 564 if (t.getUpperBound() == null) {
duke@1 565 log.error(tree.pos(), "illegal.forward.ref");
jjg@110 566 return types.createErrorType(t);
duke@1 567 }
duke@1 568 } else {
duke@1 569 t = chk.checkClassType(tree.pos(), t, checkExtensible|!allowGenerics);
duke@1 570 }
duke@1 571 if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) {
duke@1 572 log.error(tree.pos(), "intf.expected.here");
duke@1 573 // return errType is necessary since otherwise there might
duke@1 574 // be undetected cycles which cause attribution to loop
jjg@110 575 return types.createErrorType(t);
duke@1 576 } else if (checkExtensible &&
duke@1 577 classExpected &&
duke@1 578 (t.tsym.flags() & INTERFACE) != 0) {
duke@1 579 log.error(tree.pos(), "no.intf.expected.here");
jjg@110 580 return types.createErrorType(t);
duke@1 581 }
duke@1 582 if (checkExtensible &&
duke@1 583 ((t.tsym.flags() & FINAL) != 0)) {
duke@1 584 log.error(tree.pos(),
duke@1 585 "cant.inherit.from.final", t.tsym);
duke@1 586 }
duke@1 587 chk.checkNonCyclic(tree.pos(), t);
duke@1 588 return t;
duke@1 589 }
duke@1 590
duke@1 591 public void visitClassDef(JCClassDecl tree) {
duke@1 592 // Local classes have not been entered yet, so we need to do it now:
duke@1 593 if ((env.info.scope.owner.kind & (VAR | MTH)) != 0)
duke@1 594 enter.classEnter(tree, env);
duke@1 595
duke@1 596 ClassSymbol c = tree.sym;
duke@1 597 if (c == null) {
duke@1 598 // exit in case something drastic went wrong during enter.
duke@1 599 result = null;
duke@1 600 } else {
duke@1 601 // make sure class has been completed:
duke@1 602 c.complete();
duke@1 603
duke@1 604 // If this class appears as an anonymous class
duke@1 605 // in a superclass constructor call where
duke@1 606 // no explicit outer instance is given,
duke@1 607 // disable implicit outer instance from being passed.
duke@1 608 // (This would be an illegal access to "this before super").
duke@1 609 if (env.info.isSelfCall &&
duke@1 610 env.tree.getTag() == JCTree.NEWCLASS &&
duke@1 611 ((JCNewClass) env.tree).encl == null)
duke@1 612 {
duke@1 613 c.flags_field |= NOOUTERTHIS;
duke@1 614 }
duke@1 615 attribClass(tree.pos(), c);
duke@1 616 result = tree.type = c.type;
duke@1 617 }
duke@1 618 }
duke@1 619
duke@1 620 public void visitMethodDef(JCMethodDecl tree) {
duke@1 621 MethodSymbol m = tree.sym;
duke@1 622
duke@1 623 Lint lint = env.info.lint.augment(m.attributes_field, m.flags());
duke@1 624 Lint prevLint = chk.setLint(lint);
duke@1 625 try {
duke@1 626 chk.checkDeprecatedAnnotation(tree.pos(), m);
duke@1 627
mcimadamore@42 628 attribBounds(tree.typarams);
duke@1 629
duke@1 630 // If we override any other methods, check that we do so properly.
duke@1 631 // JLS ???
duke@1 632 chk.checkOverride(tree, m);
duke@1 633
duke@1 634 // Create a new environment with local scope
duke@1 635 // for attributing the method.
duke@1 636 Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
duke@1 637
duke@1 638 localEnv.info.lint = lint;
duke@1 639
duke@1 640 // Enter all type parameters into the local method scope.
duke@1 641 for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
duke@1 642 localEnv.info.scope.enterIfAbsent(l.head.type.tsym);
duke@1 643
duke@1 644 ClassSymbol owner = env.enclClass.sym;
duke@1 645 if ((owner.flags() & ANNOTATION) != 0 &&
duke@1 646 tree.params.nonEmpty())
duke@1 647 log.error(tree.params.head.pos(),
duke@1 648 "intf.annotation.members.cant.have.params");
duke@1 649
duke@1 650 // Attribute all value parameters.
duke@1 651 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
duke@1 652 attribStat(l.head, localEnv);
duke@1 653 }
duke@1 654
duke@1 655 // Check that type parameters are well-formed.
mcimadamore@122 656 chk.validate(tree.typarams, localEnv);
duke@1 657 if ((owner.flags() & ANNOTATION) != 0 &&
duke@1 658 tree.typarams.nonEmpty())
duke@1 659 log.error(tree.typarams.head.pos(),
duke@1 660 "intf.annotation.members.cant.have.type.params");
duke@1 661
duke@1 662 // Check that result type is well-formed.
mcimadamore@122 663 chk.validate(tree.restype, localEnv);
duke@1 664 if ((owner.flags() & ANNOTATION) != 0)
duke@1 665 chk.validateAnnotationType(tree.restype);
duke@1 666
duke@1 667 if ((owner.flags() & ANNOTATION) != 0)
duke@1 668 chk.validateAnnotationMethod(tree.pos(), m);
duke@1 669
duke@1 670 // Check that all exceptions mentioned in the throws clause extend
duke@1 671 // java.lang.Throwable.
duke@1 672 if ((owner.flags() & ANNOTATION) != 0 && tree.thrown.nonEmpty())
duke@1 673 log.error(tree.thrown.head.pos(),
duke@1 674 "throws.not.allowed.in.intf.annotation");
duke@1 675 for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
duke@1 676 chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
duke@1 677
duke@1 678 if (tree.body == null) {
duke@1 679 // Empty bodies are only allowed for
duke@1 680 // abstract, native, or interface methods, or for methods
duke@1 681 // in a retrofit signature class.
duke@1 682 if ((owner.flags() & INTERFACE) == 0 &&
duke@1 683 (tree.mods.flags & (ABSTRACT | NATIVE)) == 0 &&
duke@1 684 !relax)
duke@1 685 log.error(tree.pos(), "missing.meth.body.or.decl.abstract");
duke@1 686 if (tree.defaultValue != null) {
duke@1 687 if ((owner.flags() & ANNOTATION) == 0)
duke@1 688 log.error(tree.pos(),
duke@1 689 "default.allowed.in.intf.annotation.member");
duke@1 690 }
duke@1 691 } else if ((owner.flags() & INTERFACE) != 0) {
duke@1 692 log.error(tree.body.pos(), "intf.meth.cant.have.body");
duke@1 693 } else if ((tree.mods.flags & ABSTRACT) != 0) {
duke@1 694 log.error(tree.pos(), "abstract.meth.cant.have.body");
duke@1 695 } else if ((tree.mods.flags & NATIVE) != 0) {
duke@1 696 log.error(tree.pos(), "native.meth.cant.have.body");
duke@1 697 } else {
duke@1 698 // Add an implicit super() call unless an explicit call to
duke@1 699 // super(...) or this(...) is given
duke@1 700 // or we are compiling class java.lang.Object.
duke@1 701 if (tree.name == names.init && owner.type != syms.objectType) {
duke@1 702 JCBlock body = tree.body;
duke@1 703 if (body.stats.isEmpty() ||
duke@1 704 !TreeInfo.isSelfCall(body.stats.head)) {
duke@1 705 body.stats = body.stats.
duke@1 706 prepend(memberEnter.SuperCall(make.at(body.pos),
duke@1 707 List.<Type>nil(),
duke@1 708 List.<JCVariableDecl>nil(),
duke@1 709 false));
duke@1 710 } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
duke@1 711 (tree.mods.flags & GENERATEDCONSTR) == 0 &&
duke@1 712 TreeInfo.isSuperCall(body.stats.head)) {
duke@1 713 // enum constructors are not allowed to call super
duke@1 714 // directly, so make sure there aren't any super calls
duke@1 715 // in enum constructors, except in the compiler
duke@1 716 // generated one.
duke@1 717 log.error(tree.body.stats.head.pos(),
duke@1 718 "call.to.super.not.allowed.in.enum.ctor",
duke@1 719 env.enclClass.sym);
duke@1 720 }
duke@1 721 }
duke@1 722
duke@1 723 // Attribute method body.
duke@1 724 attribStat(tree.body, localEnv);
duke@1 725 }
duke@1 726 localEnv.info.scope.leave();
duke@1 727 result = tree.type = m.type;
duke@1 728 chk.validateAnnotations(tree.mods.annotations, m);
duke@1 729 }
duke@1 730 finally {
duke@1 731 chk.setLint(prevLint);
duke@1 732 }
duke@1 733 }
duke@1 734
duke@1 735 public void visitVarDef(JCVariableDecl tree) {
duke@1 736 // Local variables have not been entered yet, so we need to do it now:
duke@1 737 if (env.info.scope.owner.kind == MTH) {
duke@1 738 if (tree.sym != null) {
duke@1 739 // parameters have already been entered
duke@1 740 env.info.scope.enter(tree.sym);
duke@1 741 } else {
duke@1 742 memberEnter.memberEnter(tree, env);
duke@1 743 annotate.flush();
duke@1 744 }
duke@1 745 }
duke@1 746
duke@1 747 VarSymbol v = tree.sym;
duke@1 748 Lint lint = env.info.lint.augment(v.attributes_field, v.flags());
duke@1 749 Lint prevLint = chk.setLint(lint);
duke@1 750
mcimadamore@165 751 // Check that the variable's declared type is well-formed.
mcimadamore@165 752 chk.validate(tree.vartype, env);
mcimadamore@165 753
duke@1 754 try {
duke@1 755 chk.checkDeprecatedAnnotation(tree.pos(), v);
duke@1 756
duke@1 757 if (tree.init != null) {
duke@1 758 if ((v.flags_field & FINAL) != 0 && tree.init.getTag() != JCTree.NEWCLASS) {
duke@1 759 // In this case, `v' is final. Ensure that it's initializer is
duke@1 760 // evaluated.
duke@1 761 v.getConstValue(); // ensure initializer is evaluated
duke@1 762 } else {
duke@1 763 // Attribute initializer in a new environment
duke@1 764 // with the declared variable as owner.
duke@1 765 // Check that initializer conforms to variable's declared type.
duke@1 766 Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
duke@1 767 initEnv.info.lint = lint;
duke@1 768 // In order to catch self-references, we set the variable's
duke@1 769 // declaration position to maximal possible value, effectively
duke@1 770 // marking the variable as undefined.
mcimadamore@94 771 initEnv.info.enclVar = v;
duke@1 772 attribExpr(tree.init, initEnv, v.type);
duke@1 773 }
duke@1 774 }
duke@1 775 result = tree.type = v.type;
duke@1 776 chk.validateAnnotations(tree.mods.annotations, v);
duke@1 777 }
duke@1 778 finally {
duke@1 779 chk.setLint(prevLint);
duke@1 780 }
duke@1 781 }
duke@1 782
duke@1 783 public void visitSkip(JCSkip tree) {
duke@1 784 result = null;
duke@1 785 }
duke@1 786
duke@1 787 public void visitBlock(JCBlock tree) {
duke@1 788 if (env.info.scope.owner.kind == TYP) {
duke@1 789 // Block is a static or instance initializer;
duke@1 790 // let the owner of the environment be a freshly
duke@1 791 // created BLOCK-method.
duke@1 792 Env<AttrContext> localEnv =
duke@1 793 env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
duke@1 794 localEnv.info.scope.owner =
duke@1 795 new MethodSymbol(tree.flags | BLOCK, names.empty, null,
duke@1 796 env.info.scope.owner);
duke@1 797 if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
duke@1 798 attribStats(tree.stats, localEnv);
duke@1 799 } else {
duke@1 800 // Create a new local environment with a local scope.
duke@1 801 Env<AttrContext> localEnv =
duke@1 802 env.dup(tree, env.info.dup(env.info.scope.dup()));
duke@1 803 attribStats(tree.stats, localEnv);
duke@1 804 localEnv.info.scope.leave();
duke@1 805 }
duke@1 806 result = null;
duke@1 807 }
duke@1 808
duke@1 809 public void visitDoLoop(JCDoWhileLoop tree) {
duke@1 810 attribStat(tree.body, env.dup(tree));
duke@1 811 attribExpr(tree.cond, env, syms.booleanType);
duke@1 812 result = null;
duke@1 813 }
duke@1 814
duke@1 815 public void visitWhileLoop(JCWhileLoop tree) {
duke@1 816 attribExpr(tree.cond, env, syms.booleanType);
duke@1 817 attribStat(tree.body, env.dup(tree));
duke@1 818 result = null;
duke@1 819 }
duke@1 820
duke@1 821 public void visitForLoop(JCForLoop tree) {
duke@1 822 Env<AttrContext> loopEnv =
duke@1 823 env.dup(env.tree, env.info.dup(env.info.scope.dup()));
duke@1 824 attribStats(tree.init, loopEnv);
duke@1 825 if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType);
duke@1 826 loopEnv.tree = tree; // before, we were not in loop!
duke@1 827 attribStats(tree.step, loopEnv);
duke@1 828 attribStat(tree.body, loopEnv);
duke@1 829 loopEnv.info.scope.leave();
duke@1 830 result = null;
duke@1 831 }
duke@1 832
duke@1 833 public void visitForeachLoop(JCEnhancedForLoop tree) {
duke@1 834 Env<AttrContext> loopEnv =
duke@1 835 env.dup(env.tree, env.info.dup(env.info.scope.dup()));
duke@1 836 attribStat(tree.var, loopEnv);
duke@1 837 Type exprType = types.upperBound(attribExpr(tree.expr, loopEnv));
duke@1 838 chk.checkNonVoid(tree.pos(), exprType);
duke@1 839 Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
duke@1 840 if (elemtype == null) {
duke@1 841 // or perhaps expr implements Iterable<T>?
duke@1 842 Type base = types.asSuper(exprType, syms.iterableType.tsym);
duke@1 843 if (base == null) {
duke@1 844 log.error(tree.expr.pos(), "foreach.not.applicable.to.type");
jjg@110 845 elemtype = types.createErrorType(exprType);
duke@1 846 } else {
duke@1 847 List<Type> iterableParams = base.allparams();
duke@1 848 elemtype = iterableParams.isEmpty()
duke@1 849 ? syms.objectType
duke@1 850 : types.upperBound(iterableParams.head);
duke@1 851 }
duke@1 852 }
duke@1 853 chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
duke@1 854 loopEnv.tree = tree; // before, we were not in loop!
duke@1 855 attribStat(tree.body, loopEnv);
duke@1 856 loopEnv.info.scope.leave();
duke@1 857 result = null;
duke@1 858 }
duke@1 859
duke@1 860 public void visitLabelled(JCLabeledStatement tree) {
duke@1 861 // Check that label is not used in an enclosing statement
duke@1 862 Env<AttrContext> env1 = env;
duke@1 863 while (env1 != null && env1.tree.getTag() != JCTree.CLASSDEF) {
duke@1 864 if (env1.tree.getTag() == JCTree.LABELLED &&
duke@1 865 ((JCLabeledStatement) env1.tree).label == tree.label) {
duke@1 866 log.error(tree.pos(), "label.already.in.use",
duke@1 867 tree.label);
duke@1 868 break;
duke@1 869 }
duke@1 870 env1 = env1.next;
duke@1 871 }
duke@1 872
duke@1 873 attribStat(tree.body, env.dup(tree));
duke@1 874 result = null;
duke@1 875 }
duke@1 876
duke@1 877 public void visitSwitch(JCSwitch tree) {
duke@1 878 Type seltype = attribExpr(tree.selector, env);
duke@1 879
duke@1 880 Env<AttrContext> switchEnv =
duke@1 881 env.dup(tree, env.info.dup(env.info.scope.dup()));
duke@1 882
duke@1 883 boolean enumSwitch =
duke@1 884 allowEnums &&
duke@1 885 (seltype.tsym.flags() & Flags.ENUM) != 0;
darcy@430 886 boolean stringSwitch = false;
darcy@430 887 if (types.isSameType(seltype, syms.stringType)) {
darcy@430 888 if (allowStringsInSwitch) {
darcy@430 889 stringSwitch = true;
darcy@430 890 } else {
darcy@430 891 log.error(tree.selector.pos(), "string.switch.not.supported.in.source", sourceName);
darcy@430 892 }
darcy@430 893 }
darcy@430 894 if (!enumSwitch && !stringSwitch)
duke@1 895 seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType);
duke@1 896
duke@1 897 // Attribute all cases and
duke@1 898 // check that there are no duplicate case labels or default clauses.
duke@1 899 Set<Object> labels = new HashSet<Object>(); // The set of case labels.
duke@1 900 boolean hasDefault = false; // Is there a default label?
duke@1 901 for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
duke@1 902 JCCase c = l.head;
duke@1 903 Env<AttrContext> caseEnv =
duke@1 904 switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup()));
duke@1 905 if (c.pat != null) {
duke@1 906 if (enumSwitch) {
duke@1 907 Symbol sym = enumConstant(c.pat, seltype);
duke@1 908 if (sym == null) {
duke@1 909 log.error(c.pat.pos(), "enum.const.req");
duke@1 910 } else if (!labels.add(sym)) {
duke@1 911 log.error(c.pos(), "duplicate.case.label");
duke@1 912 }
duke@1 913 } else {
duke@1 914 Type pattype = attribExpr(c.pat, switchEnv, seltype);
duke@1 915 if (pattype.tag != ERROR) {
duke@1 916 if (pattype.constValue() == null) {
darcy@430 917 log.error(c.pat.pos(),
darcy@430 918 (stringSwitch ? "string.const.req" : "const.expr.req"));
duke@1 919 } else if (labels.contains(pattype.constValue())) {
duke@1 920 log.error(c.pos(), "duplicate.case.label");
duke@1 921 } else {
duke@1 922 labels.add(pattype.constValue());
duke@1 923 }
duke@1 924 }
duke@1 925 }
duke@1 926 } else if (hasDefault) {
duke@1 927 log.error(c.pos(), "duplicate.default.label");
duke@1 928 } else {
duke@1 929 hasDefault = true;
duke@1 930 }
duke@1 931 attribStats(c.stats, caseEnv);
duke@1 932 caseEnv.info.scope.leave();
duke@1 933 addVars(c.stats, switchEnv.info.scope);
duke@1 934 }
duke@1 935
duke@1 936 switchEnv.info.scope.leave();
duke@1 937 result = null;
duke@1 938 }
duke@1 939 // where
duke@1 940 /** Add any variables defined in stats to the switch scope. */
duke@1 941 private static void addVars(List<JCStatement> stats, Scope switchScope) {
duke@1 942 for (;stats.nonEmpty(); stats = stats.tail) {
duke@1 943 JCTree stat = stats.head;
duke@1 944 if (stat.getTag() == JCTree.VARDEF)
duke@1 945 switchScope.enter(((JCVariableDecl) stat).sym);
duke@1 946 }
duke@1 947 }
duke@1 948 // where
duke@1 949 /** Return the selected enumeration constant symbol, or null. */
duke@1 950 private Symbol enumConstant(JCTree tree, Type enumType) {
duke@1 951 if (tree.getTag() != JCTree.IDENT) {
duke@1 952 log.error(tree.pos(), "enum.label.must.be.unqualified.enum");
duke@1 953 return syms.errSymbol;
duke@1 954 }
duke@1 955 JCIdent ident = (JCIdent)tree;
duke@1 956 Name name = ident.name;
duke@1 957 for (Scope.Entry e = enumType.tsym.members().lookup(name);
duke@1 958 e.scope != null; e = e.next()) {
duke@1 959 if (e.sym.kind == VAR) {
duke@1 960 Symbol s = ident.sym = e.sym;
duke@1 961 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
duke@1 962 ident.type = s.type;
duke@1 963 return ((s.flags_field & Flags.ENUM) == 0)
duke@1 964 ? null : s;
duke@1 965 }
duke@1 966 }
duke@1 967 return null;
duke@1 968 }
duke@1 969
duke@1 970 public void visitSynchronized(JCSynchronized tree) {
duke@1 971 chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
duke@1 972 attribStat(tree.body, env);
duke@1 973 result = null;
duke@1 974 }
duke@1 975
duke@1 976 public void visitTry(JCTry tree) {
duke@1 977 // Attribute body
duke@1 978 attribStat(tree.body, env.dup(tree, env.info.dup()));
duke@1 979
duke@1 980 // Attribute catch clauses
duke@1 981 for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
duke@1 982 JCCatch c = l.head;
duke@1 983 Env<AttrContext> catchEnv =
duke@1 984 env.dup(c, env.info.dup(env.info.scope.dup()));
duke@1 985 Type ctype = attribStat(c.param, catchEnv);
mcimadamore@550 986 if (TreeInfo.isMultiCatch(c)) {
mcimadamore@550 987 //check that multi-catch parameter is marked as final
mcimadamore@550 988 if ((c.param.sym.flags() & FINAL) == 0) {
mcimadamore@550 989 log.error(c.param.pos(), "multicatch.param.must.be.final", c.param.sym);
mcimadamore@550 990 }
mcimadamore@550 991 c.param.sym.flags_field = c.param.sym.flags() | DISJOINT;
mcimadamore@550 992 }
duke@1 993 if (c.param.type.tsym.kind == Kinds.VAR) {
duke@1 994 c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
duke@1 995 }
duke@1 996 chk.checkType(c.param.vartype.pos(),
duke@1 997 chk.checkClassType(c.param.vartype.pos(), ctype),
duke@1 998 syms.throwableType);
duke@1 999 attribStat(c.body, catchEnv);
duke@1 1000 catchEnv.info.scope.leave();
duke@1 1001 }
duke@1 1002
duke@1 1003 // Attribute finalizer
duke@1 1004 if (tree.finalizer != null) attribStat(tree.finalizer, env);
duke@1 1005 result = null;
duke@1 1006 }
duke@1 1007
duke@1 1008 public void visitConditional(JCConditional tree) {
duke@1 1009 attribExpr(tree.cond, env, syms.booleanType);
duke@1 1010 attribExpr(tree.truepart, env);
duke@1 1011 attribExpr(tree.falsepart, env);
duke@1 1012 result = check(tree,
duke@1 1013 capture(condType(tree.pos(), tree.cond.type,
duke@1 1014 tree.truepart.type, tree.falsepart.type)),
duke@1 1015 VAL, pkind, pt);
duke@1 1016 }
duke@1 1017 //where
duke@1 1018 /** Compute the type of a conditional expression, after
duke@1 1019 * checking that it exists. See Spec 15.25.
duke@1 1020 *
duke@1 1021 * @param pos The source position to be used for
duke@1 1022 * error diagnostics.
duke@1 1023 * @param condtype The type of the expression's condition.
duke@1 1024 * @param thentype The type of the expression's then-part.
duke@1 1025 * @param elsetype The type of the expression's else-part.
duke@1 1026 */
duke@1 1027 private Type condType(DiagnosticPosition pos,
duke@1 1028 Type condtype,
duke@1 1029 Type thentype,
duke@1 1030 Type elsetype) {
duke@1 1031 Type ctype = condType1(pos, condtype, thentype, elsetype);
duke@1 1032
duke@1 1033 // If condition and both arms are numeric constants,
duke@1 1034 // evaluate at compile-time.
duke@1 1035 return ((condtype.constValue() != null) &&
duke@1 1036 (thentype.constValue() != null) &&
duke@1 1037 (elsetype.constValue() != null))
duke@1 1038 ? cfolder.coerce(condtype.isTrue()?thentype:elsetype, ctype)
duke@1 1039 : ctype;
duke@1 1040 }
duke@1 1041 /** Compute the type of a conditional expression, after
duke@1 1042 * checking that it exists. Does not take into
duke@1 1043 * account the special case where condition and both arms
duke@1 1044 * are constants.
duke@1 1045 *
duke@1 1046 * @param pos The source position to be used for error
duke@1 1047 * diagnostics.
duke@1 1048 * @param condtype The type of the expression's condition.
duke@1 1049 * @param thentype The type of the expression's then-part.
duke@1 1050 * @param elsetype The type of the expression's else-part.
duke@1 1051 */
duke@1 1052 private Type condType1(DiagnosticPosition pos, Type condtype,
duke@1 1053 Type thentype, Type elsetype) {
duke@1 1054 // If same type, that is the result
duke@1 1055 if (types.isSameType(thentype, elsetype))
duke@1 1056 return thentype.baseType();
duke@1 1057
duke@1 1058 Type thenUnboxed = (!allowBoxing || thentype.isPrimitive())
duke@1 1059 ? thentype : types.unboxedType(thentype);
duke@1 1060 Type elseUnboxed = (!allowBoxing || elsetype.isPrimitive())
duke@1 1061 ? elsetype : types.unboxedType(elsetype);
duke@1 1062
duke@1 1063 // Otherwise, if both arms can be converted to a numeric
duke@1 1064 // type, return the least numeric type that fits both arms
duke@1 1065 // (i.e. return larger of the two, or return int if one
duke@1 1066 // arm is short, the other is char).
duke@1 1067 if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) {
duke@1 1068 // If one arm has an integer subrange type (i.e., byte,
duke@1 1069 // short, or char), and the other is an integer constant
duke@1 1070 // that fits into the subrange, return the subrange type.
duke@1 1071 if (thenUnboxed.tag < INT && elseUnboxed.tag == INT &&
duke@1 1072 types.isAssignable(elseUnboxed, thenUnboxed))
duke@1 1073 return thenUnboxed.baseType();
duke@1 1074 if (elseUnboxed.tag < INT && thenUnboxed.tag == INT &&
duke@1 1075 types.isAssignable(thenUnboxed, elseUnboxed))
duke@1 1076 return elseUnboxed.baseType();
duke@1 1077
duke@1 1078 for (int i = BYTE; i < VOID; i++) {
duke@1 1079 Type candidate = syms.typeOfTag[i];
duke@1 1080 if (types.isSubtype(thenUnboxed, candidate) &&
duke@1 1081 types.isSubtype(elseUnboxed, candidate))
duke@1 1082 return candidate;
duke@1 1083 }
duke@1 1084 }
duke@1 1085
duke@1 1086 // Those were all the cases that could result in a primitive
duke@1 1087 if (allowBoxing) {
duke@1 1088 if (thentype.isPrimitive())
duke@1 1089 thentype = types.boxedClass(thentype).type;
duke@1 1090 if (elsetype.isPrimitive())
duke@1 1091 elsetype = types.boxedClass(elsetype).type;
duke@1 1092 }
duke@1 1093
duke@1 1094 if (types.isSubtype(thentype, elsetype))
duke@1 1095 return elsetype.baseType();
duke@1 1096 if (types.isSubtype(elsetype, thentype))
duke@1 1097 return thentype.baseType();
duke@1 1098
duke@1 1099 if (!allowBoxing || thentype.tag == VOID || elsetype.tag == VOID) {
duke@1 1100 log.error(pos, "neither.conditional.subtype",
duke@1 1101 thentype, elsetype);
duke@1 1102 return thentype.baseType();
duke@1 1103 }
duke@1 1104
duke@1 1105 // both are known to be reference types. The result is
duke@1 1106 // lub(thentype,elsetype). This cannot fail, as it will
duke@1 1107 // always be possible to infer "Object" if nothing better.
duke@1 1108 return types.lub(thentype.baseType(), elsetype.baseType());
duke@1 1109 }
duke@1 1110
duke@1 1111 public void visitIf(JCIf tree) {
duke@1 1112 attribExpr(tree.cond, env, syms.booleanType);
duke@1 1113 attribStat(tree.thenpart, env);
duke@1 1114 if (tree.elsepart != null)
duke@1 1115 attribStat(tree.elsepart, env);
duke@1 1116 chk.checkEmptyIf(tree);
duke@1 1117 result = null;
duke@1 1118 }
duke@1 1119
duke@1 1120 public void visitExec(JCExpressionStatement tree) {
duke@1 1121 attribExpr(tree.expr, env);
duke@1 1122 result = null;
duke@1 1123 }
duke@1 1124
duke@1 1125 public void visitBreak(JCBreak tree) {
duke@1 1126 tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
duke@1 1127 result = null;
duke@1 1128 }
duke@1 1129
duke@1 1130 public void visitContinue(JCContinue tree) {
duke@1 1131 tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
duke@1 1132 result = null;
duke@1 1133 }
duke@1 1134 //where
duke@1 1135 /** Return the target of a break or continue statement, if it exists,
duke@1 1136 * report an error if not.
duke@1 1137 * Note: The target of a labelled break or continue is the
duke@1 1138 * (non-labelled) statement tree referred to by the label,
duke@1 1139 * not the tree representing the labelled statement itself.
duke@1 1140 *
duke@1 1141 * @param pos The position to be used for error diagnostics
duke@1 1142 * @param tag The tag of the jump statement. This is either
duke@1 1143 * Tree.BREAK or Tree.CONTINUE.
duke@1 1144 * @param label The label of the jump statement, or null if no
duke@1 1145 * label is given.
duke@1 1146 * @param env The environment current at the jump statement.
duke@1 1147 */
duke@1 1148 private JCTree findJumpTarget(DiagnosticPosition pos,
duke@1 1149 int tag,
duke@1 1150 Name label,
duke@1 1151 Env<AttrContext> env) {
duke@1 1152 // Search environments outwards from the point of jump.
duke@1 1153 Env<AttrContext> env1 = env;
duke@1 1154 LOOP:
duke@1 1155 while (env1 != null) {
duke@1 1156 switch (env1.tree.getTag()) {
duke@1 1157 case JCTree.LABELLED:
duke@1 1158 JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
duke@1 1159 if (label == labelled.label) {
duke@1 1160 // If jump is a continue, check that target is a loop.
duke@1 1161 if (tag == JCTree.CONTINUE) {
duke@1 1162 if (labelled.body.getTag() != JCTree.DOLOOP &&
duke@1 1163 labelled.body.getTag() != JCTree.WHILELOOP &&
duke@1 1164 labelled.body.getTag() != JCTree.FORLOOP &&
duke@1 1165 labelled.body.getTag() != JCTree.FOREACHLOOP)
duke@1 1166 log.error(pos, "not.loop.label", label);
duke@1 1167 // Found labelled statement target, now go inwards
duke@1 1168 // to next non-labelled tree.
duke@1 1169 return TreeInfo.referencedStatement(labelled);
duke@1 1170 } else {
duke@1 1171 return labelled;
duke@1 1172 }
duke@1 1173 }
duke@1 1174 break;
duke@1 1175 case JCTree.DOLOOP:
duke@1 1176 case JCTree.WHILELOOP:
duke@1 1177 case JCTree.FORLOOP:
duke@1 1178 case JCTree.FOREACHLOOP:
duke@1 1179 if (label == null) return env1.tree;
duke@1 1180 break;
duke@1 1181 case JCTree.SWITCH:
duke@1 1182 if (label == null && tag == JCTree.BREAK) return env1.tree;
duke@1 1183 break;
duke@1 1184 case JCTree.METHODDEF:
duke@1 1185 case JCTree.CLASSDEF:
duke@1 1186 break LOOP;
duke@1 1187 default:
duke@1 1188 }
duke@1 1189 env1 = env1.next;
duke@1 1190 }
duke@1 1191 if (label != null)
duke@1 1192 log.error(pos, "undef.label", label);
duke@1 1193 else if (tag == JCTree.CONTINUE)
duke@1 1194 log.error(pos, "cont.outside.loop");
duke@1 1195 else
duke@1 1196 log.error(pos, "break.outside.switch.loop");
duke@1 1197 return null;
duke@1 1198 }
duke@1 1199
duke@1 1200 public void visitReturn(JCReturn tree) {
duke@1 1201 // Check that there is an enclosing method which is
duke@1 1202 // nested within than the enclosing class.
duke@1 1203 if (env.enclMethod == null ||
duke@1 1204 env.enclMethod.sym.owner != env.enclClass.sym) {
duke@1 1205 log.error(tree.pos(), "ret.outside.meth");
duke@1 1206
duke@1 1207 } else {
duke@1 1208 // Attribute return expression, if it exists, and check that
duke@1 1209 // it conforms to result type of enclosing method.
duke@1 1210 Symbol m = env.enclMethod.sym;
duke@1 1211 if (m.type.getReturnType().tag == VOID) {
duke@1 1212 if (tree.expr != null)
duke@1 1213 log.error(tree.expr.pos(),
duke@1 1214 "cant.ret.val.from.meth.decl.void");
duke@1 1215 } else if (tree.expr == null) {
duke@1 1216 log.error(tree.pos(), "missing.ret.val");
duke@1 1217 } else {
duke@1 1218 attribExpr(tree.expr, env, m.type.getReturnType());
duke@1 1219 }
duke@1 1220 }
duke@1 1221 result = null;
duke@1 1222 }
duke@1 1223
duke@1 1224 public void visitThrow(JCThrow tree) {
duke@1 1225 attribExpr(tree.expr, env, syms.throwableType);
duke@1 1226 result = null;
duke@1 1227 }
duke@1 1228
duke@1 1229 public void visitAssert(JCAssert tree) {
duke@1 1230 attribExpr(tree.cond, env, syms.booleanType);
duke@1 1231 if (tree.detail != null) {
duke@1 1232 chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
duke@1 1233 }
duke@1 1234 result = null;
duke@1 1235 }
duke@1 1236
duke@1 1237 /** Visitor method for method invocations.
duke@1 1238 * NOTE: The method part of an application will have in its type field
duke@1 1239 * the return type of the method, not the method's type itself!
duke@1 1240 */
duke@1 1241 public void visitApply(JCMethodInvocation tree) {
duke@1 1242 // The local environment of a method application is
duke@1 1243 // a new environment nested in the current one.
duke@1 1244 Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
duke@1 1245
duke@1 1246 // The types of the actual method arguments.
duke@1 1247 List<Type> argtypes;
duke@1 1248
duke@1 1249 // The types of the actual method type arguments.
duke@1 1250 List<Type> typeargtypes = null;
jrose@267 1251 boolean typeargtypesNonRefOK = false;
duke@1 1252
duke@1 1253 Name methName = TreeInfo.name(tree.meth);
duke@1 1254
duke@1 1255 boolean isConstructorCall =
duke@1 1256 methName == names._this || methName == names._super;
duke@1 1257
duke@1 1258 if (isConstructorCall) {
duke@1 1259 // We are seeing a ...this(...) or ...super(...) call.
duke@1 1260 // Check that this is the first statement in a constructor.
duke@1 1261 if (checkFirstConstructorStat(tree, env)) {
duke@1 1262
duke@1 1263 // Record the fact
duke@1 1264 // that this is a constructor call (using isSelfCall).
duke@1 1265 localEnv.info.isSelfCall = true;
duke@1 1266
duke@1 1267 // Attribute arguments, yielding list of argument types.
duke@1 1268 argtypes = attribArgs(tree.args, localEnv);
duke@1 1269 typeargtypes = attribTypes(tree.typeargs, localEnv);
duke@1 1270
duke@1 1271 // Variable `site' points to the class in which the called
duke@1 1272 // constructor is defined.
duke@1 1273 Type site = env.enclClass.sym.type;
duke@1 1274 if (methName == names._super) {
duke@1 1275 if (site == syms.objectType) {
duke@1 1276 log.error(tree.meth.pos(), "no.superclass", site);
jjg@110 1277 site = types.createErrorType(syms.objectType);
duke@1 1278 } else {
duke@1 1279 site = types.supertype(site);
duke@1 1280 }
duke@1 1281 }
duke@1 1282
duke@1 1283 if (site.tag == CLASS) {
mcimadamore@361 1284 Type encl = site.getEnclosingType();
mcimadamore@361 1285 while (encl != null && encl.tag == TYPEVAR)
mcimadamore@361 1286 encl = encl.getUpperBound();
mcimadamore@361 1287 if (encl.tag == CLASS) {
duke@1 1288 // we are calling a nested class
duke@1 1289
duke@1 1290 if (tree.meth.getTag() == JCTree.SELECT) {
duke@1 1291 JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
duke@1 1292
duke@1 1293 // We are seeing a prefixed call, of the form
duke@1 1294 // <expr>.super(...).
duke@1 1295 // Check that the prefix expression conforms
duke@1 1296 // to the outer instance type of the class.
duke@1 1297 chk.checkRefType(qualifier.pos(),
duke@1 1298 attribExpr(qualifier, localEnv,
mcimadamore@361 1299 encl));
duke@1 1300 } else if (methName == names._super) {
duke@1 1301 // qualifier omitted; check for existence
duke@1 1302 // of an appropriate implicit qualifier.
duke@1 1303 rs.resolveImplicitThis(tree.meth.pos(),
duke@1 1304 localEnv, site);
duke@1 1305 }
duke@1 1306 } else if (tree.meth.getTag() == JCTree.SELECT) {
duke@1 1307 log.error(tree.meth.pos(), "illegal.qual.not.icls",
duke@1 1308 site.tsym);
duke@1 1309 }
duke@1 1310
duke@1 1311 // if we're calling a java.lang.Enum constructor,
duke@1 1312 // prefix the implicit String and int parameters
duke@1 1313 if (site.tsym == syms.enumSym && allowEnums)
duke@1 1314 argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
duke@1 1315
duke@1 1316 // Resolve the called constructor under the assumption
duke@1 1317 // that we are referring to a superclass instance of the
duke@1 1318 // current instance (JLS ???).
duke@1 1319 boolean selectSuperPrev = localEnv.info.selectSuper;
duke@1 1320 localEnv.info.selectSuper = true;
duke@1 1321 localEnv.info.varArgs = false;
duke@1 1322 Symbol sym = rs.resolveConstructor(
duke@1 1323 tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
duke@1 1324 localEnv.info.selectSuper = selectSuperPrev;
duke@1 1325
duke@1 1326 // Set method symbol to resolved constructor...
duke@1 1327 TreeInfo.setSymbol(tree.meth, sym);
duke@1 1328
duke@1 1329 // ...and check that it is legal in the current context.
duke@1 1330 // (this will also set the tree's type)
duke@1 1331 Type mpt = newMethTemplate(argtypes, typeargtypes);
duke@1 1332 checkId(tree.meth, site, sym, localEnv, MTH,
duke@1 1333 mpt, tree.varargsElement != null);
duke@1 1334 }
duke@1 1335 // Otherwise, `site' is an error type and we do nothing
duke@1 1336 }
duke@1 1337 result = tree.type = syms.voidType;
duke@1 1338 } else {
duke@1 1339 // Otherwise, we are seeing a regular method call.
duke@1 1340 // Attribute the arguments, yielding list of argument types, ...
duke@1 1341 argtypes = attribArgs(tree.args, localEnv);
jrose@267 1342 typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
duke@1 1343
duke@1 1344 // ... and attribute the method using as a prototype a methodtype
duke@1 1345 // whose formal argument types is exactly the list of actual
duke@1 1346 // arguments (this will also set the method symbol).
duke@1 1347 Type mpt = newMethTemplate(argtypes, typeargtypes);
duke@1 1348 localEnv.info.varArgs = false;
duke@1 1349 Type mtype = attribExpr(tree.meth, localEnv, mpt);
duke@1 1350 if (localEnv.info.varArgs)
duke@1 1351 assert mtype.isErroneous() || tree.varargsElement != null;
duke@1 1352
duke@1 1353 // Compute the result type.
duke@1 1354 Type restype = mtype.getReturnType();
duke@1 1355 assert restype.tag != WILDCARD : mtype;
duke@1 1356
duke@1 1357 // as a special case, array.clone() has a result that is
duke@1 1358 // the same as static type of the array being cloned
duke@1 1359 if (tree.meth.getTag() == JCTree.SELECT &&
duke@1 1360 allowCovariantReturns &&
duke@1 1361 methName == names.clone &&
duke@1 1362 types.isArray(((JCFieldAccess) tree.meth).selected.type))
duke@1 1363 restype = ((JCFieldAccess) tree.meth).selected.type;
duke@1 1364
duke@1 1365 // as a special case, x.getClass() has type Class<? extends |X|>
duke@1 1366 if (allowGenerics &&
duke@1 1367 methName == names.getClass && tree.args.isEmpty()) {
duke@1 1368 Type qualifier = (tree.meth.getTag() == JCTree.SELECT)
duke@1 1369 ? ((JCFieldAccess) tree.meth).selected.type
duke@1 1370 : env.enclClass.sym.type;
duke@1 1371 restype = new
duke@1 1372 ClassType(restype.getEnclosingType(),
duke@1 1373 List.<Type>of(new WildcardType(types.erasure(qualifier),
duke@1 1374 BoundKind.EXTENDS,
duke@1 1375 syms.boundClass)),
duke@1 1376 restype.tsym);
duke@1 1377 }
duke@1 1378
jrose@267 1379 // as a special case, MethodHandle.<T>invoke(abc) and InvokeDynamic.<T>foo(abc)
jrose@267 1380 // has type <T>, and T can be a primitive type.
jrose@267 1381 if (tree.meth.getTag() == JCTree.SELECT && !typeargtypes.isEmpty()) {
jrose@571 1382 JCFieldAccess mfield = (JCFieldAccess) tree.meth;
jrose@571 1383 if ((mfield.selected.type.tsym != null &&
jrose@571 1384 (mfield.selected.type.tsym.flags() & POLYMORPHIC_SIGNATURE) != 0)
jrose@571 1385 ||
jrose@571 1386 (mfield.sym != null &&
jrose@571 1387 (mfield.sym.flags() & POLYMORPHIC_SIGNATURE) != 0)) {
jrose@267 1388 assert types.isSameType(restype, typeargtypes.head) : mtype;
jrose@571 1389 assert mfield.selected.type == syms.methodHandleType
jrose@571 1390 || mfield.selected.type == syms.invokeDynamicType;
jrose@267 1391 typeargtypesNonRefOK = true;
jrose@267 1392 }
jrose@267 1393 }
jrose@267 1394
jrose@267 1395 if (!typeargtypesNonRefOK) {
jrose@267 1396 chk.checkRefTypes(tree.typeargs, typeargtypes);
jrose@267 1397 }
jrose@267 1398
duke@1 1399 // Check that value of resulting type is admissible in the
duke@1 1400 // current context. Also, capture the return type
mcimadamore@536 1401 result = check(tree, capture(restype), VAL, pkind, pt);
duke@1 1402 }
mcimadamore@122 1403 chk.validate(tree.typeargs, localEnv);
duke@1 1404 }
duke@1 1405 //where
duke@1 1406 /** Check that given application node appears as first statement
duke@1 1407 * in a constructor call.
duke@1 1408 * @param tree The application node
duke@1 1409 * @param env The environment current at the application.
duke@1 1410 */
duke@1 1411 boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) {
duke@1 1412 JCMethodDecl enclMethod = env.enclMethod;
duke@1 1413 if (enclMethod != null && enclMethod.name == names.init) {
duke@1 1414 JCBlock body = enclMethod.body;
duke@1 1415 if (body.stats.head.getTag() == JCTree.EXEC &&
duke@1 1416 ((JCExpressionStatement) body.stats.head).expr == tree)
duke@1 1417 return true;
duke@1 1418 }
duke@1 1419 log.error(tree.pos(),"call.must.be.first.stmt.in.ctor",
duke@1 1420 TreeInfo.name(tree.meth));
duke@1 1421 return false;
duke@1 1422 }
duke@1 1423
duke@1 1424 /** Obtain a method type with given argument types.
duke@1 1425 */
duke@1 1426 Type newMethTemplate(List<Type> argtypes, List<Type> typeargtypes) {
duke@1 1427 MethodType mt = new MethodType(argtypes, null, null, syms.methodClass);
duke@1 1428 return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
duke@1 1429 }
duke@1 1430
duke@1 1431 public void visitNewClass(JCNewClass tree) {
jjg@110 1432 Type owntype = types.createErrorType(tree.type);
duke@1 1433
duke@1 1434 // The local environment of a class creation is
duke@1 1435 // a new environment nested in the current one.
duke@1 1436 Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
duke@1 1437
duke@1 1438 // The anonymous inner class definition of the new expression,
duke@1 1439 // if one is defined by it.
duke@1 1440 JCClassDecl cdef = tree.def;
duke@1 1441
duke@1 1442 // If enclosing class is given, attribute it, and
duke@1 1443 // complete class name to be fully qualified
duke@1 1444 JCExpression clazz = tree.clazz; // Class field following new
duke@1 1445 JCExpression clazzid = // Identifier in class field
duke@1 1446 (clazz.getTag() == JCTree.TYPEAPPLY)
duke@1 1447 ? ((JCTypeApply) clazz).clazz
duke@1 1448 : clazz;
duke@1 1449
duke@1 1450 JCExpression clazzid1 = clazzid; // The same in fully qualified form
duke@1 1451
duke@1 1452 if (tree.encl != null) {
duke@1 1453 // We are seeing a qualified new, of the form
duke@1 1454 // <expr>.new C <...> (...) ...
duke@1 1455 // In this case, we let clazz stand for the name of the
duke@1 1456 // allocated class C prefixed with the type of the qualifier
duke@1 1457 // expression, so that we can
duke@1 1458 // resolve it with standard techniques later. I.e., if
duke@1 1459 // <expr> has type T, then <expr>.new C <...> (...)
duke@1 1460 // yields a clazz T.C.
duke@1 1461 Type encltype = chk.checkRefType(tree.encl.pos(),
duke@1 1462 attribExpr(tree.encl, env));
duke@1 1463 clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
duke@1 1464 ((JCIdent) clazzid).name);
duke@1 1465 if (clazz.getTag() == JCTree.TYPEAPPLY)
duke@1 1466 clazz = make.at(tree.pos).
duke@1 1467 TypeApply(clazzid1,
duke@1 1468 ((JCTypeApply) clazz).arguments);
duke@1 1469 else
duke@1 1470 clazz = clazzid1;
duke@1 1471 }
duke@1 1472
duke@1 1473 // Attribute clazz expression and store
duke@1 1474 // symbol + type back into the attributed tree.
mcimadamore@537 1475 Type clazztype = attribType(clazz, env);
mcimadamore@562 1476 Pair<Scope,Scope> mapping = getSyntheticScopeMapping(clazztype);
mcimadamore@537 1477 if (!TreeInfo.isDiamond(tree)) {
mcimadamore@537 1478 clazztype = chk.checkClassType(
mcimadamore@537 1479 tree.clazz.pos(), clazztype, true);
mcimadamore@537 1480 }
mcimadamore@122 1481 chk.validate(clazz, localEnv);
duke@1 1482 if (tree.encl != null) {
duke@1 1483 // We have to work in this case to store
duke@1 1484 // symbol + type back into the attributed tree.
duke@1 1485 tree.clazz.type = clazztype;
duke@1 1486 TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
duke@1 1487 clazzid.type = ((JCIdent) clazzid).sym.type;
duke@1 1488 if (!clazztype.isErroneous()) {
duke@1 1489 if (cdef != null && clazztype.tsym.isInterface()) {
duke@1 1490 log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new");
duke@1 1491 } else if (clazztype.tsym.isStatic()) {
duke@1 1492 log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym);
duke@1 1493 }
duke@1 1494 }
duke@1 1495 } else if (!clazztype.tsym.isInterface() &&
duke@1 1496 clazztype.getEnclosingType().tag == CLASS) {
duke@1 1497 // Check for the existence of an apropos outer instance
duke@1 1498 rs.resolveImplicitThis(tree.pos(), env, clazztype);
duke@1 1499 }
duke@1 1500
duke@1 1501 // Attribute constructor arguments.
duke@1 1502 List<Type> argtypes = attribArgs(tree.args, localEnv);
duke@1 1503 List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
duke@1 1504
mcimadamore@537 1505 if (TreeInfo.isDiamond(tree)) {
mcimadamore@537 1506 clazztype = attribDiamond(localEnv, tree, clazztype, mapping, argtypes, typeargtypes, true);
mcimadamore@537 1507 clazz.type = clazztype;
mcimadamore@537 1508 }
mcimadamore@537 1509
duke@1 1510 // If we have made no mistakes in the class type...
duke@1 1511 if (clazztype.tag == CLASS) {
duke@1 1512 // Enums may not be instantiated except implicitly
duke@1 1513 if (allowEnums &&
duke@1 1514 (clazztype.tsym.flags_field&Flags.ENUM) != 0 &&
duke@1 1515 (env.tree.getTag() != JCTree.VARDEF ||
duke@1 1516 (((JCVariableDecl) env.tree).mods.flags&Flags.ENUM) == 0 ||
duke@1 1517 ((JCVariableDecl) env.tree).init != tree))
duke@1 1518 log.error(tree.pos(), "enum.cant.be.instantiated");
duke@1 1519 // Check that class is not abstract
duke@1 1520 if (cdef == null &&
duke@1 1521 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
duke@1 1522 log.error(tree.pos(), "abstract.cant.be.instantiated",
duke@1 1523 clazztype.tsym);
duke@1 1524 } else if (cdef != null && clazztype.tsym.isInterface()) {
duke@1 1525 // Check that no constructor arguments are given to
duke@1 1526 // anonymous classes implementing an interface
duke@1 1527 if (!argtypes.isEmpty())
duke@1 1528 log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args");
duke@1 1529
duke@1 1530 if (!typeargtypes.isEmpty())
duke@1 1531 log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs");
duke@1 1532
duke@1 1533 // Error recovery: pretend no arguments were supplied.
duke@1 1534 argtypes = List.nil();
duke@1 1535 typeargtypes = List.nil();
duke@1 1536 }
duke@1 1537
duke@1 1538 // Resolve the called constructor under the assumption
duke@1 1539 // that we are referring to a superclass instance of the
duke@1 1540 // current instance (JLS ???).
duke@1 1541 else {
duke@1 1542 localEnv.info.selectSuper = cdef != null;
duke@1 1543 localEnv.info.varArgs = false;
duke@1 1544 tree.constructor = rs.resolveConstructor(
duke@1 1545 tree.pos(), localEnv, clazztype, argtypes, typeargtypes);
mcimadamore@186 1546 tree.constructorType = checkMethod(clazztype,
mcimadamore@537 1547 tree.constructor,
mcimadamore@537 1548 localEnv,
mcimadamore@537 1549 tree.args,
mcimadamore@537 1550 argtypes,
mcimadamore@537 1551 typeargtypes,
mcimadamore@537 1552 localEnv.info.varArgs);
duke@1 1553 if (localEnv.info.varArgs)
mcimadamore@186 1554 assert tree.constructorType.isErroneous() || tree.varargsElement != null;
duke@1 1555 }
duke@1 1556
duke@1 1557 if (cdef != null) {
duke@1 1558 // We are seeing an anonymous class instance creation.
duke@1 1559 // In this case, the class instance creation
duke@1 1560 // expression
duke@1 1561 //
duke@1 1562 // E.new <typeargs1>C<typargs2>(args) { ... }
duke@1 1563 //
duke@1 1564 // is represented internally as
duke@1 1565 //
duke@1 1566 // E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } ) .
duke@1 1567 //
duke@1 1568 // This expression is then *transformed* as follows:
duke@1 1569 //
duke@1 1570 // (1) add a STATIC flag to the class definition
duke@1 1571 // if the current environment is static
duke@1 1572 // (2) add an extends or implements clause
duke@1 1573 // (3) add a constructor.
duke@1 1574 //
duke@1 1575 // For instance, if C is a class, and ET is the type of E,
duke@1 1576 // the expression
duke@1 1577 //
duke@1 1578 // E.new <typeargs1>C<typargs2>(args) { ... }
duke@1 1579 //
duke@1 1580 // is translated to (where X is a fresh name and typarams is the
duke@1 1581 // parameter list of the super constructor):
duke@1 1582 //
duke@1 1583 // new <typeargs1>X(<*nullchk*>E, args) where
duke@1 1584 // X extends C<typargs2> {
duke@1 1585 // <typarams> X(ET e, args) {
duke@1 1586 // e.<typeargs1>super(args)
duke@1 1587 // }
duke@1 1588 // ...
duke@1 1589 // }
duke@1 1590 if (Resolve.isStatic(env)) cdef.mods.flags |= STATIC;
mcimadamore@536 1591
duke@1 1592 if (clazztype.tsym.isInterface()) {
duke@1 1593 cdef.implementing = List.of(clazz);
duke@1 1594 } else {
duke@1 1595 cdef.extending = clazz;
duke@1 1596 }
duke@1 1597
duke@1 1598 attribStat(cdef, localEnv);
duke@1 1599
duke@1 1600 // If an outer instance is given,
duke@1 1601 // prefix it to the constructor arguments
duke@1 1602 // and delete it from the new expression
duke@1 1603 if (tree.encl != null && !clazztype.tsym.isInterface()) {
duke@1 1604 tree.args = tree.args.prepend(makeNullCheck(tree.encl));
duke@1 1605 argtypes = argtypes.prepend(tree.encl.type);
duke@1 1606 tree.encl = null;
duke@1 1607 }
duke@1 1608
duke@1 1609 // Reassign clazztype and recompute constructor.
duke@1 1610 clazztype = cdef.sym.type;
duke@1 1611 Symbol sym = rs.resolveConstructor(
duke@1 1612 tree.pos(), localEnv, clazztype, argtypes,
duke@1 1613 typeargtypes, true, tree.varargsElement != null);
duke@1 1614 assert sym.kind < AMBIGUOUS || tree.constructor.type.isErroneous();
duke@1 1615 tree.constructor = sym;
mcimadamore@358 1616 if (tree.constructor.kind > ERRONEOUS) {
mcimadamore@358 1617 tree.constructorType = syms.errType;
mcimadamore@358 1618 }
mcimadamore@358 1619 else {
mcimadamore@358 1620 tree.constructorType = checkMethod(clazztype,
mcimadamore@358 1621 tree.constructor,
mcimadamore@358 1622 localEnv,
mcimadamore@358 1623 tree.args,
mcimadamore@358 1624 argtypes,
mcimadamore@358 1625 typeargtypes,
mcimadamore@358 1626 localEnv.info.varArgs);
mcimadamore@358 1627 }
duke@1 1628 }
duke@1 1629
duke@1 1630 if (tree.constructor != null && tree.constructor.kind == MTH)
duke@1 1631 owntype = clazztype;
duke@1 1632 }
duke@1 1633 result = check(tree, owntype, VAL, pkind, pt);
mcimadamore@122 1634 chk.validate(tree.typeargs, localEnv);
duke@1 1635 }
duke@1 1636
mcimadamore@537 1637 Type attribDiamond(Env<AttrContext> env,
mcimadamore@537 1638 JCNewClass tree,
mcimadamore@537 1639 Type clazztype,
mcimadamore@537 1640 Pair<Scope, Scope> mapping,
mcimadamore@537 1641 List<Type> argtypes,
mcimadamore@537 1642 List<Type> typeargtypes,
mcimadamore@537 1643 boolean reportErrors) {
mcimadamore@562 1644 if (clazztype.isErroneous() || mapping == erroneousMapping) {
mcimadamore@562 1645 //if the type of the instance creation expression is erroneous,
mcimadamore@562 1646 //or something prevented us to form a valid mapping, return the
mcimadamore@562 1647 //(possibly erroneous) type unchanged
mcimadamore@537 1648 return clazztype;
mcimadamore@537 1649 }
mcimadamore@537 1650 else if (clazztype.isInterface()) {
mcimadamore@537 1651 //if the type of the instance creation expression is an interface
mcimadamore@537 1652 //skip the method resolution step (JLS 15.12.2.7). The type to be
mcimadamore@537 1653 //inferred is of the kind <X1,X2, ... Xn>C<X1,X2, ... Xn>
mcimadamore@537 1654 clazztype = new ForAll(clazztype.tsym.type.allparams(),
mcimadamore@537 1655 clazztype.tsym.type);
mcimadamore@537 1656 } else {
mcimadamore@537 1657 //if the type of the instance creation expression is a class type
mcimadamore@537 1658 //apply method resolution inference (JLS 15.12.2.7). The return type
mcimadamore@537 1659 //of the resolved constructor will be a partially instantiated type
mcimadamore@537 1660 ((ClassSymbol) clazztype.tsym).members_field = mapping.snd;
mcimadamore@537 1661 Symbol constructor;
mcimadamore@537 1662 try {
mcimadamore@537 1663 constructor = rs.resolveDiamond(tree.pos(),
mcimadamore@537 1664 env,
mcimadamore@537 1665 clazztype.tsym.type,
mcimadamore@537 1666 argtypes,
mcimadamore@537 1667 typeargtypes, reportErrors);
mcimadamore@537 1668 } finally {
mcimadamore@537 1669 ((ClassSymbol) clazztype.tsym).members_field = mapping.fst;
mcimadamore@537 1670 }
mcimadamore@537 1671 if (constructor.kind == MTH) {
mcimadamore@537 1672 ClassType ct = new ClassType(clazztype.getEnclosingType(),
mcimadamore@537 1673 clazztype.tsym.type.getTypeArguments(),
mcimadamore@537 1674 clazztype.tsym);
mcimadamore@537 1675 clazztype = checkMethod(ct,
mcimadamore@537 1676 constructor,
mcimadamore@537 1677 env,
mcimadamore@537 1678 tree.args,
mcimadamore@537 1679 argtypes,
mcimadamore@537 1680 typeargtypes,
mcimadamore@537 1681 env.info.varArgs).getReturnType();
mcimadamore@537 1682 } else {
mcimadamore@537 1683 clazztype = syms.errType;
mcimadamore@537 1684 }
mcimadamore@537 1685 }
mcimadamore@537 1686 if (clazztype.tag == FORALL && !pt.isErroneous()) {
mcimadamore@537 1687 //if the resolved constructor's return type has some uninferred
mcimadamore@537 1688 //type-variables, infer them using the expected type and declared
mcimadamore@537 1689 //bounds (JLS 15.12.2.8).
mcimadamore@537 1690 try {
mcimadamore@537 1691 clazztype = infer.instantiateExpr((ForAll) clazztype,
mcimadamore@537 1692 pt.tag == NONE ? syms.objectType : pt,
mcimadamore@537 1693 Warner.noWarnings);
mcimadamore@537 1694 } catch (Infer.InferenceException ex) {
mcimadamore@537 1695 //an error occurred while inferring uninstantiated type-variables
mcimadamore@537 1696 //we need to optionally report an error
mcimadamore@537 1697 if (reportErrors) {
mcimadamore@537 1698 log.error(tree.clazz.pos(),
mcimadamore@537 1699 "cant.apply.diamond.1",
mcimadamore@537 1700 diags.fragment("diamond", clazztype.tsym),
mcimadamore@537 1701 ex.diagnostic);
mcimadamore@537 1702 }
mcimadamore@537 1703 }
mcimadamore@537 1704 }
mcimadamore@537 1705 if (reportErrors) {
mcimadamore@537 1706 clazztype = chk.checkClassType(tree.clazz.pos(),
mcimadamore@537 1707 clazztype,
mcimadamore@537 1708 true);
mcimadamore@537 1709 if (clazztype.tag == CLASS) {
mcimadamore@537 1710 List<Type> invalidDiamondArgs = chk.checkDiamond((ClassType)clazztype);
mcimadamore@537 1711 if (!clazztype.isErroneous() && invalidDiamondArgs.nonEmpty()) {
mcimadamore@537 1712 //one or more types inferred in the previous steps is either a
mcimadamore@537 1713 //captured type or an intersection type --- we need to report an error.
mcimadamore@537 1714 String subkey = invalidDiamondArgs.size() > 1 ?
mcimadamore@537 1715 "diamond.invalid.args" :
mcimadamore@537 1716 "diamond.invalid.arg";
mcimadamore@537 1717 //The error message is of the kind:
mcimadamore@537 1718 //
mcimadamore@537 1719 //cannot infer type arguments for {clazztype}<>;
mcimadamore@537 1720 //reason: {subkey}
mcimadamore@537 1721 //
mcimadamore@537 1722 //where subkey is a fragment of the kind:
mcimadamore@537 1723 //
mcimadamore@537 1724 //type argument(s) {invalidDiamondArgs} inferred for {clazztype}<> is not allowed in this context
mcimadamore@537 1725 log.error(tree.clazz.pos(),
mcimadamore@537 1726 "cant.apply.diamond.1",
mcimadamore@537 1727 diags.fragment("diamond", clazztype.tsym),
mcimadamore@537 1728 diags.fragment(subkey,
mcimadamore@537 1729 invalidDiamondArgs,
mcimadamore@537 1730 diags.fragment("diamond", clazztype.tsym)));
mcimadamore@537 1731 }
mcimadamore@537 1732 }
mcimadamore@537 1733 }
mcimadamore@537 1734 return clazztype;
mcimadamore@537 1735 }
mcimadamore@537 1736
mcimadamore@537 1737 /** Creates a synthetic scope containing fake generic constructors.
mcimadamore@537 1738 * Assuming that the original scope contains a constructor of the kind:
mcimadamore@537 1739 * Foo(X x, Y y), where X,Y are class type-variables declared in Foo,
mcimadamore@537 1740 * the synthetic scope is added a generic constructor of the kind:
mcimadamore@537 1741 * <X,Y>Foo<X,Y>(X x, Y y). This is crucial in order to enable diamond
mcimadamore@537 1742 * inference. The inferred return type of the synthetic constructor IS
mcimadamore@537 1743 * the inferred type for the diamond operator.
mcimadamore@537 1744 */
mcimadamore@562 1745 private Pair<Scope, Scope> getSyntheticScopeMapping(Type ctype) {
mcimadamore@562 1746 if (ctype.tag != CLASS) {
mcimadamore@562 1747 return erroneousMapping;
mcimadamore@562 1748 }
mcimadamore@537 1749 Pair<Scope, Scope> mapping =
mcimadamore@537 1750 new Pair<Scope, Scope>(ctype.tsym.members(), new Scope(ctype.tsym));
mcimadamore@537 1751 List<Type> typevars = ctype.tsym.type.getTypeArguments();
mcimadamore@537 1752 for (Scope.Entry e = mapping.fst.lookup(names.init);
mcimadamore@537 1753 e.scope != null;
mcimadamore@537 1754 e = e.next()) {
mcimadamore@537 1755 MethodSymbol newConstr = (MethodSymbol) e.sym.clone(ctype.tsym);
mcimadamore@537 1756 newConstr.name = names.init;
mcimadamore@537 1757 List<Type> oldTypeargs = List.nil();
mcimadamore@537 1758 if (newConstr.type.tag == FORALL) {
mcimadamore@537 1759 oldTypeargs = ((ForAll) newConstr.type).tvars;
mcimadamore@537 1760 }
mcimadamore@537 1761 newConstr.type = new MethodType(newConstr.type.getParameterTypes(),
mcimadamore@537 1762 new ClassType(ctype.getEnclosingType(), ctype.tsym.type.getTypeArguments(), ctype.tsym),
mcimadamore@537 1763 newConstr.type.getThrownTypes(),
mcimadamore@537 1764 syms.methodClass);
mcimadamore@537 1765 newConstr.type = new ForAll(typevars.prependList(oldTypeargs), newConstr.type);
mcimadamore@537 1766 mapping.snd.enter(newConstr);
mcimadamore@537 1767 }
mcimadamore@537 1768 return mapping;
mcimadamore@537 1769 }
mcimadamore@537 1770
mcimadamore@562 1771 private final Pair<Scope,Scope> erroneousMapping = new Pair<Scope,Scope>(null, null);
mcimadamore@562 1772
duke@1 1773 /** Make an attributed null check tree.
duke@1 1774 */
duke@1 1775 public JCExpression makeNullCheck(JCExpression arg) {
duke@1 1776 // optimization: X.this is never null; skip null check
duke@1 1777 Name name = TreeInfo.name(arg);
duke@1 1778 if (name == names._this || name == names._super) return arg;
duke@1 1779
duke@1 1780 int optag = JCTree.NULLCHK;
duke@1 1781 JCUnary tree = make.at(arg.pos).Unary(optag, arg);
duke@1 1782 tree.operator = syms.nullcheck;
duke@1 1783 tree.type = arg.type;
duke@1 1784 return tree;
duke@1 1785 }
duke@1 1786
duke@1 1787 public void visitNewArray(JCNewArray tree) {
jjg@110 1788 Type owntype = types.createErrorType(tree.type);
duke@1 1789 Type elemtype;
duke@1 1790 if (tree.elemtype != null) {
duke@1 1791 elemtype = attribType(tree.elemtype, env);
mcimadamore@122 1792 chk.validate(tree.elemtype, env);
duke@1 1793 owntype = elemtype;
duke@1 1794 for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
duke@1 1795 attribExpr(l.head, env, syms.intType);
duke@1 1796 owntype = new ArrayType(owntype, syms.arrayClass);
duke@1 1797 }
duke@1 1798 } else {
duke@1 1799 // we are seeing an untyped aggregate { ... }
duke@1 1800 // this is allowed only if the prototype is an array
duke@1 1801 if (pt.tag == ARRAY) {
duke@1 1802 elemtype = types.elemtype(pt);
duke@1 1803 } else {
duke@1 1804 if (pt.tag != ERROR) {
duke@1 1805 log.error(tree.pos(), "illegal.initializer.for.type",
duke@1 1806 pt);
duke@1 1807 }
jjg@110 1808 elemtype = types.createErrorType(pt);
duke@1 1809 }
duke@1 1810 }
duke@1 1811 if (tree.elems != null) {
duke@1 1812 attribExprs(tree.elems, env, elemtype);
duke@1 1813 owntype = new ArrayType(elemtype, syms.arrayClass);
duke@1 1814 }
duke@1 1815 if (!types.isReifiable(elemtype))
duke@1 1816 log.error(tree.pos(), "generic.array.creation");
duke@1 1817 result = check(tree, owntype, VAL, pkind, pt);
duke@1 1818 }
duke@1 1819
duke@1 1820 public void visitParens(JCParens tree) {
duke@1 1821 Type owntype = attribTree(tree.expr, env, pkind, pt);
duke@1 1822 result = check(tree, owntype, pkind, pkind, pt);
duke@1 1823 Symbol sym = TreeInfo.symbol(tree);
duke@1 1824 if (sym != null && (sym.kind&(TYP|PCK)) != 0)
duke@1 1825 log.error(tree.pos(), "illegal.start.of.type");
duke@1 1826 }
duke@1 1827
duke@1 1828 public void visitAssign(JCAssign tree) {
duke@1 1829 Type owntype = attribTree(tree.lhs, env.dup(tree), VAR, Type.noType);
duke@1 1830 Type capturedType = capture(owntype);
duke@1 1831 attribExpr(tree.rhs, env, owntype);
duke@1 1832 result = check(tree, capturedType, VAL, pkind, pt);
duke@1 1833 }
duke@1 1834
duke@1 1835 public void visitAssignop(JCAssignOp tree) {
duke@1 1836 // Attribute arguments.
duke@1 1837 Type owntype = attribTree(tree.lhs, env, VAR, Type.noType);
duke@1 1838 Type operand = attribExpr(tree.rhs, env);
duke@1 1839 // Find operator.
duke@1 1840 Symbol operator = tree.operator = rs.resolveBinaryOperator(
duke@1 1841 tree.pos(), tree.getTag() - JCTree.ASGOffset, env,
duke@1 1842 owntype, operand);
duke@1 1843
duke@1 1844 if (operator.kind == MTH) {
duke@1 1845 chk.checkOperator(tree.pos(),
duke@1 1846 (OperatorSymbol)operator,
duke@1 1847 tree.getTag() - JCTree.ASGOffset,
duke@1 1848 owntype,
duke@1 1849 operand);
jjg@9 1850 chk.checkDivZero(tree.rhs.pos(), operator, operand);
jjg@9 1851 chk.checkCastable(tree.rhs.pos(),
jjg@9 1852 operator.type.getReturnType(),
jjg@9 1853 owntype);
duke@1 1854 }
duke@1 1855 result = check(tree, owntype, VAL, pkind, pt);
duke@1 1856 }
duke@1 1857
duke@1 1858 public void visitUnary(JCUnary tree) {
duke@1 1859 // Attribute arguments.
duke@1 1860 Type argtype = (JCTree.PREINC <= tree.getTag() && tree.getTag() <= JCTree.POSTDEC)
duke@1 1861 ? attribTree(tree.arg, env, VAR, Type.noType)
duke@1 1862 : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
duke@1 1863
duke@1 1864 // Find operator.
duke@1 1865 Symbol operator = tree.operator =
duke@1 1866 rs.resolveUnaryOperator(tree.pos(), tree.getTag(), env, argtype);
duke@1 1867
jjg@110 1868 Type owntype = types.createErrorType(tree.type);
duke@1 1869 if (operator.kind == MTH) {
duke@1 1870 owntype = (JCTree.PREINC <= tree.getTag() && tree.getTag() <= JCTree.POSTDEC)
duke@1 1871 ? tree.arg.type
duke@1 1872 : operator.type.getReturnType();
duke@1 1873 int opc = ((OperatorSymbol)operator).opcode;
duke@1 1874
duke@1 1875 // If the argument is constant, fold it.
duke@1 1876 if (argtype.constValue() != null) {
duke@1 1877 Type ctype = cfolder.fold1(opc, argtype);
duke@1 1878 if (ctype != null) {
duke@1 1879 owntype = cfolder.coerce(ctype, owntype);
duke@1 1880
duke@1 1881 // Remove constant types from arguments to
duke@1 1882 // conserve space. The parser will fold concatenations
duke@1 1883 // of string literals; the code here also
duke@1 1884 // gets rid of intermediate results when some of the
duke@1 1885 // operands are constant identifiers.
duke@1 1886 if (tree.arg.type.tsym == syms.stringType.tsym) {
duke@1 1887 tree.arg.type = syms.stringType;
duke@1 1888 }
duke@1 1889 }
duke@1 1890 }
duke@1 1891 }
duke@1 1892 result = check(tree, owntype, VAL, pkind, pt);
duke@1 1893 }
duke@1 1894
duke@1 1895 public void visitBinary(JCBinary tree) {
duke@1 1896 // Attribute arguments.
duke@1 1897 Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
duke@1 1898 Type right = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.rhs, env));
duke@1 1899
duke@1 1900 // Find operator.
duke@1 1901 Symbol operator = tree.operator =
duke@1 1902 rs.resolveBinaryOperator(tree.pos(), tree.getTag(), env, left, right);
duke@1 1903
jjg@110 1904 Type owntype = types.createErrorType(tree.type);
duke@1 1905 if (operator.kind == MTH) {
duke@1 1906 owntype = operator.type.getReturnType();
duke@1 1907 int opc = chk.checkOperator(tree.lhs.pos(),
duke@1 1908 (OperatorSymbol)operator,
duke@1 1909 tree.getTag(),
duke@1 1910 left,
duke@1 1911 right);
duke@1 1912
duke@1 1913 // If both arguments are constants, fold them.
duke@1 1914 if (left.constValue() != null && right.constValue() != null) {
duke@1 1915 Type ctype = cfolder.fold2(opc, left, right);
duke@1 1916 if (ctype != null) {
duke@1 1917 owntype = cfolder.coerce(ctype, owntype);
duke@1 1918
duke@1 1919 // Remove constant types from arguments to
duke@1 1920 // conserve space. The parser will fold concatenations
duke@1 1921 // of string literals; the code here also
duke@1 1922 // gets rid of intermediate results when some of the
duke@1 1923 // operands are constant identifiers.
duke@1 1924 if (tree.lhs.type.tsym == syms.stringType.tsym) {
duke@1 1925 tree.lhs.type = syms.stringType;
duke@1 1926 }
duke@1 1927 if (tree.rhs.type.tsym == syms.stringType.tsym) {
duke@1 1928 tree.rhs.type = syms.stringType;
duke@1 1929 }
duke@1 1930 }
duke@1 1931 }
duke@1 1932
duke@1 1933 // Check that argument types of a reference ==, != are
duke@1 1934 // castable to each other, (JLS???).
duke@1 1935 if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
duke@1 1936 if (!types.isCastable(left, right, new Warner(tree.pos()))) {
duke@1 1937 log.error(tree.pos(), "incomparable.types", left, right);
duke@1 1938 }
duke@1 1939 }
duke@1 1940
duke@1 1941 chk.checkDivZero(tree.rhs.pos(), operator, right);
duke@1 1942 }
duke@1 1943 result = check(tree, owntype, VAL, pkind, pt);
duke@1 1944 }
duke@1 1945
duke@1 1946 public void visitTypeCast(JCTypeCast tree) {
duke@1 1947 Type clazztype = attribType(tree.clazz, env);
mcimadamore@122 1948 chk.validate(tree.clazz, env);
duke@1 1949 Type exprtype = attribExpr(tree.expr, env, Infer.anyPoly);
duke@1 1950 Type owntype = chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
duke@1 1951 if (exprtype.constValue() != null)
duke@1 1952 owntype = cfolder.coerce(exprtype, owntype);
duke@1 1953 result = check(tree, capture(owntype), VAL, pkind, pt);
duke@1 1954 }
duke@1 1955
duke@1 1956 public void visitTypeTest(JCInstanceOf tree) {
duke@1 1957 Type exprtype = chk.checkNullOrRefType(
duke@1 1958 tree.expr.pos(), attribExpr(tree.expr, env));
duke@1 1959 Type clazztype = chk.checkReifiableReferenceType(
duke@1 1960 tree.clazz.pos(), attribType(tree.clazz, env));
mcimadamore@122 1961 chk.validate(tree.clazz, env);
duke@1 1962 chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
duke@1 1963 result = check(tree, syms.booleanType, VAL, pkind, pt);
duke@1 1964 }
duke@1 1965
duke@1 1966 public void visitIndexed(JCArrayAccess tree) {
jjg@110 1967 Type owntype = types.createErrorType(tree.type);
duke@1 1968 Type atype = attribExpr(tree.indexed, env);
duke@1 1969 attribExpr(tree.index, env, syms.intType);
duke@1 1970 if (types.isArray(atype))
duke@1 1971 owntype = types.elemtype(atype);
duke@1 1972 else if (atype.tag != ERROR)
duke@1 1973 log.error(tree.pos(), "array.req.but.found", atype);
duke@1 1974 if ((pkind & VAR) == 0) owntype = capture(owntype);
duke@1 1975 result = check(tree, owntype, VAR, pkind, pt);
duke@1 1976 }
duke@1 1977
duke@1 1978 public void visitIdent(JCIdent tree) {
duke@1 1979 Symbol sym;
duke@1 1980 boolean varArgs = false;
duke@1 1981
duke@1 1982 // Find symbol
duke@1 1983 if (pt.tag == METHOD || pt.tag == FORALL) {
duke@1 1984 // If we are looking for a method, the prototype `pt' will be a
duke@1 1985 // method type with the type of the call's arguments as parameters.
duke@1 1986 env.info.varArgs = false;
duke@1 1987 sym = rs.resolveMethod(tree.pos(), env, tree.name, pt.getParameterTypes(), pt.getTypeArguments());
duke@1 1988 varArgs = env.info.varArgs;
duke@1 1989 } else if (tree.sym != null && tree.sym.kind != VAR) {
duke@1 1990 sym = tree.sym;
duke@1 1991 } else {
duke@1 1992 sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind);
duke@1 1993 }
duke@1 1994 tree.sym = sym;
duke@1 1995
duke@1 1996 // (1) Also find the environment current for the class where
duke@1 1997 // sym is defined (`symEnv').
duke@1 1998 // Only for pre-tiger versions (1.4 and earlier):
duke@1 1999 // (2) Also determine whether we access symbol out of an anonymous
duke@1 2000 // class in a this or super call. This is illegal for instance
duke@1 2001 // members since such classes don't carry a this$n link.
duke@1 2002 // (`noOuterThisPath').
duke@1 2003 Env<AttrContext> symEnv = env;
duke@1 2004 boolean noOuterThisPath = false;
duke@1 2005 if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
duke@1 2006 (sym.kind & (VAR | MTH | TYP)) != 0 &&
duke@1 2007 sym.owner.kind == TYP &&
duke@1 2008 tree.name != names._this && tree.name != names._super) {
duke@1 2009
duke@1 2010 // Find environment in which identifier is defined.
duke@1 2011 while (symEnv.outer != null &&
duke@1 2012 !sym.isMemberOf(symEnv.enclClass.sym, types)) {
duke@1 2013 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
duke@1 2014 noOuterThisPath = !allowAnonOuterThis;
duke@1 2015 symEnv = symEnv.outer;
duke@1 2016 }
duke@1 2017 }
duke@1 2018
duke@1 2019 // If symbol is a variable, ...
duke@1 2020 if (sym.kind == VAR) {
duke@1 2021 VarSymbol v = (VarSymbol)sym;
duke@1 2022
duke@1 2023 // ..., evaluate its initializer, if it has one, and check for
duke@1 2024 // illegal forward reference.
duke@1 2025 checkInit(tree, env, v, false);
duke@1 2026
duke@1 2027 // If symbol is a local variable accessed from an embedded
duke@1 2028 // inner class check that it is final.
duke@1 2029 if (v.owner.kind == MTH &&
duke@1 2030 v.owner != env.info.scope.owner &&
duke@1 2031 (v.flags_field & FINAL) == 0) {
duke@1 2032 log.error(tree.pos(),
duke@1 2033 "local.var.accessed.from.icls.needs.final",
duke@1 2034 v);
duke@1 2035 }
duke@1 2036
duke@1 2037 // If we are expecting a variable (as opposed to a value), check
duke@1 2038 // that the variable is assignable in the current environment.
duke@1 2039 if (pkind == VAR)
duke@1 2040 checkAssignable(tree.pos(), v, null, env);
duke@1 2041 }
duke@1 2042
duke@1 2043 // In a constructor body,
duke@1 2044 // if symbol is a field or instance method, check that it is
duke@1 2045 // not accessed before the supertype constructor is called.
duke@1 2046 if ((symEnv.info.isSelfCall || noOuterThisPath) &&
duke@1 2047 (sym.kind & (VAR | MTH)) != 0 &&
duke@1 2048 sym.owner.kind == TYP &&
duke@1 2049 (sym.flags() & STATIC) == 0) {
duke@1 2050 chk.earlyRefError(tree.pos(), sym.kind == VAR ? sym : thisSym(tree.pos(), env));
duke@1 2051 }
duke@1 2052 Env<AttrContext> env1 = env;
mcimadamore@28 2053 if (sym.kind != ERR && sym.kind != TYP && sym.owner != null && sym.owner != env1.enclClass.sym) {
duke@1 2054 // If the found symbol is inaccessible, then it is
duke@1 2055 // accessed through an enclosing instance. Locate this
duke@1 2056 // enclosing instance:
duke@1 2057 while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
duke@1 2058 env1 = env1.outer;
duke@1 2059 }
duke@1 2060 result = checkId(tree, env1.enclClass.sym.type, sym, env, pkind, pt, varArgs);
duke@1 2061 }
duke@1 2062
duke@1 2063 public void visitSelect(JCFieldAccess tree) {
duke@1 2064 // Determine the expected kind of the qualifier expression.
duke@1 2065 int skind = 0;
duke@1 2066 if (tree.name == names._this || tree.name == names._super ||
duke@1 2067 tree.name == names._class)
duke@1 2068 {
duke@1 2069 skind = TYP;
duke@1 2070 } else {
duke@1 2071 if ((pkind & PCK) != 0) skind = skind | PCK;
duke@1 2072 if ((pkind & TYP) != 0) skind = skind | TYP | PCK;
duke@1 2073 if ((pkind & (VAL | MTH)) != 0) skind = skind | VAL | TYP;
duke@1 2074 }
duke@1 2075
duke@1 2076 // Attribute the qualifier expression, and determine its symbol (if any).
duke@1 2077 Type site = attribTree(tree.selected, env, skind, Infer.anyPoly);
duke@1 2078 if ((pkind & (PCK | TYP)) == 0)
duke@1 2079 site = capture(site); // Capture field access
duke@1 2080
duke@1 2081 // don't allow T.class T[].class, etc
duke@1 2082 if (skind == TYP) {
duke@1 2083 Type elt = site;
duke@1 2084 while (elt.tag == ARRAY)
duke@1 2085 elt = ((ArrayType)elt).elemtype;
duke@1 2086 if (elt.tag == TYPEVAR) {
duke@1 2087 log.error(tree.pos(), "type.var.cant.be.deref");
jjg@110 2088 result = types.createErrorType(tree.type);
duke@1 2089 return;
duke@1 2090 }
duke@1 2091 }
duke@1 2092
duke@1 2093 // If qualifier symbol is a type or `super', assert `selectSuper'
duke@1 2094 // for the selection. This is relevant for determining whether
duke@1 2095 // protected symbols are accessible.
duke@1 2096 Symbol sitesym = TreeInfo.symbol(tree.selected);
duke@1 2097 boolean selectSuperPrev = env.info.selectSuper;
duke@1 2098 env.info.selectSuper =
duke@1 2099 sitesym != null &&
duke@1 2100 sitesym.name == names._super;
duke@1 2101
duke@1 2102 // If selected expression is polymorphic, strip
duke@1 2103 // type parameters and remember in env.info.tvars, so that
duke@1 2104 // they can be added later (in Attr.checkId and Infer.instantiateMethod).
duke@1 2105 if (tree.selected.type.tag == FORALL) {
duke@1 2106 ForAll pstype = (ForAll)tree.selected.type;
duke@1 2107 env.info.tvars = pstype.tvars;
duke@1 2108 site = tree.selected.type = pstype.qtype;
duke@1 2109 }
duke@1 2110
duke@1 2111 // Determine the symbol represented by the selection.
duke@1 2112 env.info.varArgs = false;
duke@1 2113 Symbol sym = selectSym(tree, site, env, pt, pkind);
duke@1 2114 if (sym.exists() && !isType(sym) && (pkind & (PCK | TYP)) != 0) {
duke@1 2115 site = capture(site);
duke@1 2116 sym = selectSym(tree, site, env, pt, pkind);
duke@1 2117 }
duke@1 2118 boolean varArgs = env.info.varArgs;
duke@1 2119 tree.sym = sym;
duke@1 2120
mcimadamore@27 2121 if (site.tag == TYPEVAR && !isType(sym) && sym.kind != ERR) {
mcimadamore@27 2122 while (site.tag == TYPEVAR) site = site.getUpperBound();
mcimadamore@27 2123 site = capture(site);
mcimadamore@27 2124 }
duke@1 2125
duke@1 2126 // If that symbol is a variable, ...
duke@1 2127 if (sym.kind == VAR) {
duke@1 2128 VarSymbol v = (VarSymbol)sym;
duke@1 2129
duke@1 2130 // ..., evaluate its initializer, if it has one, and check for
duke@1 2131 // illegal forward reference.
duke@1 2132 checkInit(tree, env, v, true);
duke@1 2133
duke@1 2134 // If we are expecting a variable (as opposed to a value), check
duke@1 2135 // that the variable is assignable in the current environment.
duke@1 2136 if (pkind == VAR)
duke@1 2137 checkAssignable(tree.pos(), v, tree.selected, env);
duke@1 2138 }
duke@1 2139
duke@1 2140 // Disallow selecting a type from an expression
duke@1 2141 if (isType(sym) && (sitesym==null || (sitesym.kind&(TYP|PCK)) == 0)) {
duke@1 2142 tree.type = check(tree.selected, pt,
duke@1 2143 sitesym == null ? VAL : sitesym.kind, TYP|PCK, pt);
duke@1 2144 }
duke@1 2145
duke@1 2146 if (isType(sitesym)) {
duke@1 2147 if (sym.name == names._this) {
duke@1 2148 // If `C' is the currently compiled class, check that
duke@1 2149 // C.this' does not appear in a call to a super(...)
duke@1 2150 if (env.info.isSelfCall &&
duke@1 2151 site.tsym == env.enclClass.sym) {
duke@1 2152 chk.earlyRefError(tree.pos(), sym);
duke@1 2153 }
duke@1 2154 } else {
duke@1 2155 // Check if type-qualified fields or methods are static (JLS)
duke@1 2156 if ((sym.flags() & STATIC) == 0 &&
duke@1 2157 sym.name != names._super &&
duke@1 2158 (sym.kind == VAR || sym.kind == MTH)) {
duke@1 2159 rs.access(rs.new StaticError(sym),
duke@1 2160 tree.pos(), site, sym.name, true);
duke@1 2161 }
duke@1 2162 }
jjg@505 2163 } else if (sym.kind != ERR && (sym.flags() & STATIC) != 0 && sym.name != names._class) {
jjg@505 2164 // If the qualified item is not a type and the selected item is static, report
jjg@505 2165 // a warning. Make allowance for the class of an array type e.g. Object[].class)
jjg@505 2166 chk.warnStatic(tree, "static.not.qualified.by.type", Kinds.kindName(sym.kind), sym.owner);
duke@1 2167 }
duke@1 2168
duke@1 2169 // If we are selecting an instance member via a `super', ...
duke@1 2170 if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
duke@1 2171
duke@1 2172 // Check that super-qualified symbols are not abstract (JLS)
duke@1 2173 rs.checkNonAbstract(tree.pos(), sym);
duke@1 2174
duke@1 2175 if (site.isRaw()) {
duke@1 2176 // Determine argument types for site.
duke@1 2177 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
duke@1 2178 if (site1 != null) site = site1;
duke@1 2179 }
duke@1 2180 }
duke@1 2181
duke@1 2182 env.info.selectSuper = selectSuperPrev;
duke@1 2183 result = checkId(tree, site, sym, env, pkind, pt, varArgs);
duke@1 2184 env.info.tvars = List.nil();
duke@1 2185 }
duke@1 2186 //where
duke@1 2187 /** Determine symbol referenced by a Select expression,
duke@1 2188 *
duke@1 2189 * @param tree The select tree.
duke@1 2190 * @param site The type of the selected expression,
duke@1 2191 * @param env The current environment.
duke@1 2192 * @param pt The current prototype.
duke@1 2193 * @param pkind The expected kind(s) of the Select expression.
duke@1 2194 */
duke@1 2195 private Symbol selectSym(JCFieldAccess tree,
duke@1 2196 Type site,
duke@1 2197 Env<AttrContext> env,
duke@1 2198 Type pt,
duke@1 2199 int pkind) {
duke@1 2200 DiagnosticPosition pos = tree.pos();
duke@1 2201 Name name = tree.name;
duke@1 2202
duke@1 2203 switch (site.tag) {
duke@1 2204 case PACKAGE:
duke@1 2205 return rs.access(
duke@1 2206 rs.findIdentInPackage(env, site.tsym, name, pkind),
duke@1 2207 pos, site, name, true);
duke@1 2208 case ARRAY:
duke@1 2209 case CLASS:
duke@1 2210 if (pt.tag == METHOD || pt.tag == FORALL) {
duke@1 2211 return rs.resolveQualifiedMethod(
duke@1 2212 pos, env, site, name, pt.getParameterTypes(), pt.getTypeArguments());
duke@1 2213 } else if (name == names._this || name == names._super) {
duke@1 2214 return rs.resolveSelf(pos, env, site.tsym, name);
duke@1 2215 } else if (name == names._class) {
duke@1 2216 // In this case, we have already made sure in
duke@1 2217 // visitSelect that qualifier expression is a type.
duke@1 2218 Type t = syms.classType;
duke@1 2219 List<Type> typeargs = allowGenerics
duke@1 2220 ? List.of(types.erasure(site))
duke@1 2221 : List.<Type>nil();
duke@1 2222 t = new ClassType(t.getEnclosingType(), typeargs, t.tsym);
duke@1 2223 return new VarSymbol(
duke@1 2224 STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
duke@1 2225 } else {
duke@1 2226 // We are seeing a plain identifier as selector.
duke@1 2227 Symbol sym = rs.findIdentInType(env, site, name, pkind);
duke@1 2228 if ((pkind & ERRONEOUS) == 0)
duke@1 2229 sym = rs.access(sym, pos, site, name, true);
duke@1 2230 return sym;
duke@1 2231 }
duke@1 2232 case WILDCARD:
duke@1 2233 throw new AssertionError(tree);
duke@1 2234 case TYPEVAR:
duke@1 2235 // Normally, site.getUpperBound() shouldn't be null.
duke@1 2236 // It should only happen during memberEnter/attribBase
duke@1 2237 // when determining the super type which *must* be
duke@1 2238 // done before attributing the type variables. In
duke@1 2239 // other words, we are seeing this illegal program:
duke@1 2240 // class B<T> extends A<T.foo> {}
duke@1 2241 Symbol sym = (site.getUpperBound() != null)
duke@1 2242 ? selectSym(tree, capture(site.getUpperBound()), env, pt, pkind)
duke@1 2243 : null;
mcimadamore@361 2244 if (sym == null) {
duke@1 2245 log.error(pos, "type.var.cant.be.deref");
duke@1 2246 return syms.errSymbol;
duke@1 2247 } else {
mcimadamore@155 2248 Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
mcimadamore@155 2249 rs.new AccessError(env, site, sym) :
mcimadamore@155 2250 sym;
mcimadamore@155 2251 rs.access(sym2, pos, site, name, true);
duke@1 2252 return sym;
duke@1 2253 }
duke@1 2254 case ERROR:
duke@1 2255 // preserve identifier names through errors
jjg@110 2256 return types.createErrorType(name, site.tsym, site).tsym;
duke@1 2257 default:
duke@1 2258 // The qualifier expression is of a primitive type -- only
duke@1 2259 // .class is allowed for these.
duke@1 2260 if (name == names._class) {
duke@1 2261 // In this case, we have already made sure in Select that
duke@1 2262 // qualifier expression is a type.
duke@1 2263 Type t = syms.classType;
duke@1 2264 Type arg = types.boxedClass(site).type;
duke@1 2265 t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym);
duke@1 2266 return new VarSymbol(
duke@1 2267 STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
duke@1 2268 } else {
duke@1 2269 log.error(pos, "cant.deref", site);
duke@1 2270 return syms.errSymbol;
duke@1 2271 }
duke@1 2272 }
duke@1 2273 }
duke@1 2274
duke@1 2275 /** Determine type of identifier or select expression and check that
duke@1 2276 * (1) the referenced symbol is not deprecated
duke@1 2277 * (2) the symbol's type is safe (@see checkSafe)
duke@1 2278 * (3) if symbol is a variable, check that its type and kind are
duke@1 2279 * compatible with the prototype and protokind.
duke@1 2280 * (4) if symbol is an instance field of a raw type,
duke@1 2281 * which is being assigned to, issue an unchecked warning if its
duke@1 2282 * type changes under erasure.
duke@1 2283 * (5) if symbol is an instance method of a raw type, issue an
duke@1 2284 * unchecked warning if its argument types change under erasure.
duke@1 2285 * If checks succeed:
duke@1 2286 * If symbol is a constant, return its constant type
duke@1 2287 * else if symbol is a method, return its result type
duke@1 2288 * otherwise return its type.
duke@1 2289 * Otherwise return errType.
duke@1 2290 *
duke@1 2291 * @param tree The syntax tree representing the identifier
duke@1 2292 * @param site If this is a select, the type of the selected
duke@1 2293 * expression, otherwise the type of the current class.
duke@1 2294 * @param sym The symbol representing the identifier.
duke@1 2295 * @param env The current environment.
duke@1 2296 * @param pkind The set of expected kinds.
duke@1 2297 * @param pt The expected type.
duke@1 2298 */
duke@1 2299 Type checkId(JCTree tree,
duke@1 2300 Type site,
duke@1 2301 Symbol sym,
duke@1 2302 Env<AttrContext> env,
duke@1 2303 int pkind,
duke@1 2304 Type pt,
duke@1 2305 boolean useVarargs) {
jjg@110 2306 if (pt.isErroneous()) return types.createErrorType(site);
duke@1 2307 Type owntype; // The computed type of this identifier occurrence.
duke@1 2308 switch (sym.kind) {
duke@1 2309 case TYP:
duke@1 2310 // For types, the computed type equals the symbol's type,
duke@1 2311 // except for two situations:
duke@1 2312 owntype = sym.type;
duke@1 2313 if (owntype.tag == CLASS) {
duke@1 2314 Type ownOuter = owntype.getEnclosingType();
duke@1 2315
duke@1 2316 // (a) If the symbol's type is parameterized, erase it
duke@1 2317 // because no type parameters were given.
duke@1 2318 // We recover generic outer type later in visitTypeApply.
duke@1 2319 if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
duke@1 2320 owntype = types.erasure(owntype);
duke@1 2321 }
duke@1 2322
duke@1 2323 // (b) If the symbol's type is an inner class, then
duke@1 2324 // we have to interpret its outer type as a superclass
duke@1 2325 // of the site type. Example:
duke@1 2326 //
duke@1 2327 // class Tree<A> { class Visitor { ... } }
duke@1 2328 // class PointTree extends Tree<Point> { ... }
duke@1 2329 // ...PointTree.Visitor...
duke@1 2330 //
duke@1 2331 // Then the type of the last expression above is
duke@1 2332 // Tree<Point>.Visitor.
duke@1 2333 else if (ownOuter.tag == CLASS && site != ownOuter) {
duke@1 2334 Type normOuter = site;
duke@1 2335 if (normOuter.tag == CLASS)
duke@1 2336 normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
duke@1 2337 if (normOuter == null) // perhaps from an import
duke@1 2338 normOuter = types.erasure(ownOuter);
duke@1 2339 if (normOuter != ownOuter)
duke@1 2340 owntype = new ClassType(
duke@1 2341 normOuter, List.<Type>nil(), owntype.tsym);
duke@1 2342 }
duke@1 2343 }
duke@1 2344 break;
duke@1 2345 case VAR:
duke@1 2346 VarSymbol v = (VarSymbol)sym;
duke@1 2347 // Test (4): if symbol is an instance field of a raw type,
duke@1 2348 // which is being assigned to, issue an unchecked warning if
duke@1 2349 // its type changes under erasure.
duke@1 2350 if (allowGenerics &&
duke@1 2351 pkind == VAR &&
duke@1 2352 v.owner.kind == TYP &&
duke@1 2353 (v.flags() & STATIC) == 0 &&
duke@1 2354 (site.tag == CLASS || site.tag == TYPEVAR)) {
duke@1 2355 Type s = types.asOuterSuper(site, v.owner);
duke@1 2356 if (s != null &&
duke@1 2357 s.isRaw() &&
duke@1 2358 !types.isSameType(v.type, v.erasure(types))) {
duke@1 2359 chk.warnUnchecked(tree.pos(),
duke@1 2360 "unchecked.assign.to.var",
duke@1 2361 v, s);
duke@1 2362 }
duke@1 2363 }
duke@1 2364 // The computed type of a variable is the type of the
duke@1 2365 // variable symbol, taken as a member of the site type.
duke@1 2366 owntype = (sym.owner.kind == TYP &&
duke@1 2367 sym.name != names._this && sym.name != names._super)
duke@1 2368 ? types.memberType(site, sym)
duke@1 2369 : sym.type;
duke@1 2370
duke@1 2371 if (env.info.tvars.nonEmpty()) {
duke@1 2372 Type owntype1 = new ForAll(env.info.tvars, owntype);
duke@1 2373 for (List<Type> l = env.info.tvars; l.nonEmpty(); l = l.tail)
duke@1 2374 if (!owntype.contains(l.head)) {
duke@1 2375 log.error(tree.pos(), "undetermined.type", owntype1);
jjg@110 2376 owntype1 = types.createErrorType(owntype1);
duke@1 2377 }
duke@1 2378 owntype = owntype1;
duke@1 2379 }
duke@1 2380
duke@1 2381 // If the variable is a constant, record constant value in
duke@1 2382 // computed type.
duke@1 2383 if (v.getConstValue() != null && isStaticReference(tree))
duke@1 2384 owntype = owntype.constType(v.getConstValue());
duke@1 2385
duke@1 2386 if (pkind == VAL) {
duke@1 2387 owntype = capture(owntype); // capture "names as expressions"
duke@1 2388 }
duke@1 2389 break;
duke@1 2390 case MTH: {
duke@1 2391 JCMethodInvocation app = (JCMethodInvocation)env.tree;
duke@1 2392 owntype = checkMethod(site, sym, env, app.args,
duke@1 2393 pt.getParameterTypes(), pt.getTypeArguments(),
duke@1 2394 env.info.varArgs);
duke@1 2395 break;
duke@1 2396 }
duke@1 2397 case PCK: case ERR:
duke@1 2398 owntype = sym.type;
duke@1 2399 break;
duke@1 2400 default:
duke@1 2401 throw new AssertionError("unexpected kind: " + sym.kind +
duke@1 2402 " in tree " + tree);
duke@1 2403 }
duke@1 2404
duke@1 2405 // Test (1): emit a `deprecation' warning if symbol is deprecated.
duke@1 2406 // (for constructors, the error was given when the constructor was
duke@1 2407 // resolved)
duke@1 2408 if (sym.name != names.init &&
duke@1 2409 (sym.flags() & DEPRECATED) != 0 &&
duke@1 2410 (env.info.scope.owner.flags() & DEPRECATED) == 0 &&
duke@1 2411 sym.outermostClass() != env.info.scope.owner.outermostClass())
duke@1 2412 chk.warnDeprecated(tree.pos(), sym);
duke@1 2413
jjg@377 2414 if ((sym.flags() & PROPRIETARY) != 0) {
jjg@377 2415 if (enableSunApiLintControl)
jjg@377 2416 chk.warnSunApi(tree.pos(), "sun.proprietary", sym);
jjg@377 2417 else
jjg@377 2418 log.strictWarning(tree.pos(), "sun.proprietary", sym);
jjg@377 2419 }
duke@1 2420
duke@1 2421 // Test (3): if symbol is a variable, check that its type and
duke@1 2422 // kind are compatible with the prototype and protokind.
duke@1 2423 return check(tree, owntype, sym.kind, pkind, pt);
duke@1 2424 }
duke@1 2425
duke@1 2426 /** Check that variable is initialized and evaluate the variable's
duke@1 2427 * initializer, if not yet done. Also check that variable is not
duke@1 2428 * referenced before it is defined.
duke@1 2429 * @param tree The tree making up the variable reference.
duke@1 2430 * @param env The current environment.
duke@1 2431 * @param v The variable's symbol.
duke@1 2432 */
duke@1 2433 private void checkInit(JCTree tree,
duke@1 2434 Env<AttrContext> env,
duke@1 2435 VarSymbol v,
duke@1 2436 boolean onlyWarning) {
duke@1 2437 // System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " +
duke@1 2438 // tree.pos + " " + v.pos + " " +
duke@1 2439 // Resolve.isStatic(env));//DEBUG
duke@1 2440
duke@1 2441 // A forward reference is diagnosed if the declaration position
duke@1 2442 // of the variable is greater than the current tree position
duke@1 2443 // and the tree and variable definition occur in the same class
duke@1 2444 // definition. Note that writes don't count as references.
duke@1 2445 // This check applies only to class and instance
duke@1 2446 // variables. Local variables follow different scope rules,
duke@1 2447 // and are subject to definite assignment checking.
mcimadamore@94 2448 if ((env.info.enclVar == v || v.pos > tree.pos) &&
duke@1 2449 v.owner.kind == TYP &&
duke@1 2450 canOwnInitializer(env.info.scope.owner) &&
duke@1 2451 v.owner == env.info.scope.owner.enclClass() &&
duke@1 2452 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
duke@1 2453 (env.tree.getTag() != JCTree.ASSIGN ||
duke@1 2454 TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
mcimadamore@94 2455 String suffix = (env.info.enclVar == v) ?
mcimadamore@94 2456 "self.ref" : "forward.ref";
mcimadamore@18 2457 if (!onlyWarning || isStaticEnumField(v)) {
mcimadamore@94 2458 log.error(tree.pos(), "illegal." + suffix);
duke@1 2459 } else if (useBeforeDeclarationWarning) {
mcimadamore@94 2460 log.warning(tree.pos(), suffix, v);
duke@1 2461 }
duke@1 2462 }
duke@1 2463
duke@1 2464 v.getConstValue(); // ensure initializer is evaluated
duke@1 2465
duke@1 2466 checkEnumInitializer(tree, env, v);
duke@1 2467 }
duke@1 2468
duke@1 2469 /**
duke@1 2470 * Check for illegal references to static members of enum. In
duke@1 2471 * an enum type, constructors and initializers may not
duke@1 2472 * reference its static members unless they are constant.
duke@1 2473 *
duke@1 2474 * @param tree The tree making up the variable reference.
duke@1 2475 * @param env The current environment.
duke@1 2476 * @param v The variable's symbol.
duke@1 2477 * @see JLS 3rd Ed. (8.9 Enums)
duke@1 2478 */
duke@1 2479 private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
duke@1 2480 // JLS 3rd Ed.:
duke@1 2481 //
duke@1 2482 // "It is a compile-time error to reference a static field
duke@1 2483 // of an enum type that is not a compile-time constant
duke@1 2484 // (15.28) from constructors, instance initializer blocks,
duke@1 2485 // or instance variable initializer expressions of that
duke@1 2486 // type. It is a compile-time error for the constructors,
duke@1 2487 // instance initializer blocks, or instance variable
duke@1 2488 // initializer expressions of an enum constant e to refer
duke@1 2489 // to itself or to an enum constant of the same type that
duke@1 2490 // is declared to the right of e."
mcimadamore@18 2491 if (isStaticEnumField(v)) {
duke@1 2492 ClassSymbol enclClass = env.info.scope.owner.enclClass();
duke@1 2493
duke@1 2494 if (enclClass == null || enclClass.owner == null)
duke@1 2495 return;
duke@1 2496
duke@1 2497 // See if the enclosing class is the enum (or a
duke@1 2498 // subclass thereof) declaring v. If not, this
duke@1 2499 // reference is OK.
duke@1 2500 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
duke@1 2501 return;
duke@1 2502
duke@1 2503 // If the reference isn't from an initializer, then
duke@1 2504 // the reference is OK.
duke@1 2505 if (!Resolve.isInitializer(env))
duke@1 2506 return;
duke@1 2507
duke@1 2508 log.error(tree.pos(), "illegal.enum.static.ref");
duke@1 2509 }
duke@1 2510 }
duke@1 2511
mcimadamore@18 2512 /** Is the given symbol a static, non-constant field of an Enum?
mcimadamore@18 2513 * Note: enum literals should not be regarded as such
mcimadamore@18 2514 */
mcimadamore@18 2515 private boolean isStaticEnumField(VarSymbol v) {
mcimadamore@18 2516 return Flags.isEnum(v.owner) &&
mcimadamore@18 2517 Flags.isStatic(v) &&
mcimadamore@18 2518 !Flags.isConstant(v) &&
mcimadamore@18 2519 v.name != names._class;
duke@1 2520 }
duke@1 2521
duke@1 2522 /** Can the given symbol be the owner of code which forms part
duke@1 2523 * if class initialization? This is the case if the symbol is
duke@1 2524 * a type or field, or if the symbol is the synthetic method.
duke@1 2525 * owning a block.
duke@1 2526 */
duke@1 2527 private boolean canOwnInitializer(Symbol sym) {
duke@1 2528 return
duke@1 2529 (sym.kind & (VAR | TYP)) != 0 ||
duke@1 2530 (sym.kind == MTH && (sym.flags() & BLOCK) != 0);
duke@1 2531 }
duke@1 2532
duke@1 2533 Warner noteWarner = new Warner();
duke@1 2534
duke@1 2535 /**
duke@1 2536 * Check that method arguments conform to its instantation.
duke@1 2537 **/
duke@1 2538 public Type checkMethod(Type site,
duke@1 2539 Symbol sym,
duke@1 2540 Env<AttrContext> env,
duke@1 2541 final List<JCExpression> argtrees,
duke@1 2542 List<Type> argtypes,
duke@1 2543 List<Type> typeargtypes,
duke@1 2544 boolean useVarargs) {
duke@1 2545 // Test (5): if symbol is an instance method of a raw type, issue
duke@1 2546 // an unchecked warning if its argument types change under erasure.
duke@1 2547 if (allowGenerics &&
duke@1 2548 (sym.flags() & STATIC) == 0 &&
duke@1 2549 (site.tag == CLASS || site.tag == TYPEVAR)) {
duke@1 2550 Type s = types.asOuterSuper(site, sym.owner);
duke@1 2551 if (s != null && s.isRaw() &&
duke@1 2552 !types.isSameTypes(sym.type.getParameterTypes(),
duke@1 2553 sym.erasure(types).getParameterTypes())) {
duke@1 2554 chk.warnUnchecked(env.tree.pos(),
duke@1 2555 "unchecked.call.mbr.of.raw.type",
duke@1 2556 sym, s);
duke@1 2557 }
duke@1 2558 }
duke@1 2559
duke@1 2560 // Compute the identifier's instantiated type.
duke@1 2561 // For methods, we need to compute the instance type by
duke@1 2562 // Resolve.instantiate from the symbol's type as well as
duke@1 2563 // any type arguments and value arguments.
duke@1 2564 noteWarner.warned = false;
duke@1 2565 Type owntype = rs.instantiate(env,
duke@1 2566 site,
duke@1 2567 sym,
duke@1 2568 argtypes,
duke@1 2569 typeargtypes,
duke@1 2570 true,
duke@1 2571 useVarargs,
duke@1 2572 noteWarner);
duke@1 2573 boolean warned = noteWarner.warned;
duke@1 2574
duke@1 2575 // If this fails, something went wrong; we should not have
duke@1 2576 // found the identifier in the first place.
duke@1 2577 if (owntype == null) {
duke@1 2578 if (!pt.isErroneous())
duke@1 2579 log.error(env.tree.pos(),
duke@1 2580 "internal.error.cant.instantiate",
duke@1 2581 sym, site,
duke@1 2582 Type.toString(pt.getParameterTypes()));
jjg@110 2583 owntype = types.createErrorType(site);
duke@1 2584 } else {
duke@1 2585 // System.out.println("call : " + env.tree);
duke@1 2586 // System.out.println("method : " + owntype);
duke@1 2587 // System.out.println("actuals: " + argtypes);
duke@1 2588 List<Type> formals = owntype.getParameterTypes();
duke@1 2589 Type last = useVarargs ? formals.last() : null;
duke@1 2590 if (sym.name==names.init &&
duke@1 2591 sym.owner == syms.enumSym)
duke@1 2592 formals = formals.tail.tail;
duke@1 2593 List<JCExpression> args = argtrees;
duke@1 2594 while (formals.head != last) {
duke@1 2595 JCTree arg = args.head;
duke@1 2596 Warner warn = chk.convertWarner(arg.pos(), arg.type, formals.head);
duke@1 2597 assertConvertible(arg, arg.type, formals.head, warn);
duke@1 2598 warned |= warn.warned;
duke@1 2599 args = args.tail;
duke@1 2600 formals = formals.tail;
duke@1 2601 }
duke@1 2602 if (useVarargs) {
duke@1 2603 Type varArg = types.elemtype(last);
duke@1 2604 while (args.tail != null) {
duke@1 2605 JCTree arg = args.head;
duke@1 2606 Warner warn = chk.convertWarner(arg.pos(), arg.type, varArg);
duke@1 2607 assertConvertible(arg, arg.type, varArg, warn);
duke@1 2608 warned |= warn.warned;
duke@1 2609 args = args.tail;
duke@1 2610 }
duke@1 2611 } else if ((sym.flags() & VARARGS) != 0 && allowVarargs) {
duke@1 2612 // non-varargs call to varargs method
duke@1 2613 Type varParam = owntype.getParameterTypes().last();
duke@1 2614 Type lastArg = argtypes.last();
duke@1 2615 if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) &&
duke@1 2616 !types.isSameType(types.erasure(varParam), types.erasure(lastArg)))
duke@1 2617 log.warning(argtrees.last().pos(), "inexact.non-varargs.call",
duke@1 2618 types.elemtype(varParam),
duke@1 2619 varParam);
duke@1 2620 }
duke@1 2621
duke@1 2622 if (warned && sym.type.tag == FORALL) {
duke@1 2623 chk.warnUnchecked(env.tree.pos(),
duke@1 2624 "unchecked.meth.invocation.applied",
mcimadamore@161 2625 kindName(sym),
mcimadamore@161 2626 sym.name,
mcimadamore@161 2627 rs.methodArguments(sym.type.getParameterTypes()),
mcimadamore@161 2628 rs.methodArguments(argtypes),
mcimadamore@161 2629 kindName(sym.location()),
mcimadamore@161 2630 sym.location());
duke@1 2631 owntype = new MethodType(owntype.getParameterTypes(),
duke@1 2632 types.erasure(owntype.getReturnType()),
duke@1 2633 owntype.getThrownTypes(),
duke@1 2634 syms.methodClass);
duke@1 2635 }
duke@1 2636 if (useVarargs) {
duke@1 2637 JCTree tree = env.tree;
mcimadamore@547 2638 if (owntype.getReturnType().tag != FORALL || warned) {
mcimadamore@547 2639 chk.checkVararg(env.tree.pos(), owntype.getParameterTypes());
mcimadamore@547 2640 }
mcimadamore@547 2641 Type elemtype = types.elemtype(owntype.getParameterTypes().last());
duke@1 2642 switch (tree.getTag()) {
duke@1 2643 case JCTree.APPLY:
duke@1 2644 ((JCMethodInvocation) tree).varargsElement = elemtype;
duke@1 2645 break;
duke@1 2646 case JCTree.NEWCLASS:
duke@1 2647 ((JCNewClass) tree).varargsElement = elemtype;
duke@1 2648 break;
duke@1 2649 default:
duke@1 2650 throw new AssertionError(""+tree);
duke@1 2651 }
duke@1 2652 }
duke@1 2653 }
duke@1 2654 return owntype;
duke@1 2655 }
duke@1 2656
duke@1 2657 private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) {
duke@1 2658 if (types.isConvertible(actual, formal, warn))
duke@1 2659 return;
duke@1 2660
duke@1 2661 if (formal.isCompound()
duke@1 2662 && types.isSubtype(actual, types.supertype(formal))
duke@1 2663 && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn))
duke@1 2664 return;
duke@1 2665
duke@1 2666 if (false) {
duke@1 2667 // TODO: make assertConvertible work
mcimadamore@89 2668 chk.typeError(tree.pos(), diags.fragment("incompatible.types"), actual, formal);
duke@1 2669 throw new AssertionError("Tree: " + tree
duke@1 2670 + " actual:" + actual
duke@1 2671 + " formal: " + formal);
duke@1 2672 }
duke@1 2673 }
duke@1 2674
duke@1 2675 public void visitLiteral(JCLiteral tree) {
duke@1 2676 result = check(
duke@1 2677 tree, litType(tree.typetag).constType(tree.value), VAL, pkind, pt);
duke@1 2678 }
duke@1 2679 //where
duke@1 2680 /** Return the type of a literal with given type tag.
duke@1 2681 */
duke@1 2682 Type litType(int tag) {
duke@1 2683 return (tag == TypeTags.CLASS) ? syms.stringType : syms.typeOfTag[tag];
duke@1 2684 }
duke@1 2685
duke@1 2686 public void visitTypeIdent(JCPrimitiveTypeTree tree) {
duke@1 2687 result = check(tree, syms.typeOfTag[tree.typetag], TYP, pkind, pt);
duke@1 2688 }
duke@1 2689
duke@1 2690 public void visitTypeArray(JCArrayTypeTree tree) {
duke@1 2691 Type etype = attribType(tree.elemtype, env);
duke@1 2692 Type type = new ArrayType(etype, syms.arrayClass);
duke@1 2693 result = check(tree, type, TYP, pkind, pt);
duke@1 2694 }
duke@1 2695
duke@1 2696 /** Visitor method for parameterized types.
duke@1 2697 * Bound checking is left until later, since types are attributed
duke@1 2698 * before supertype structure is completely known
duke@1 2699 */
duke@1 2700 public void visitTypeApply(JCTypeApply tree) {
jjg@110 2701 Type owntype = types.createErrorType(tree.type);
duke@1 2702
duke@1 2703 // Attribute functor part of application and make sure it's a class.
duke@1 2704 Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
duke@1 2705
duke@1 2706 // Attribute type parameters
duke@1 2707 List<Type> actuals = attribTypes(tree.arguments, env);
duke@1 2708
duke@1 2709 if (clazztype.tag == CLASS) {
duke@1 2710 List<Type> formals = clazztype.tsym.type.getTypeArguments();
duke@1 2711
mcimadamore@537 2712 if (actuals.length() == formals.length() || actuals.length() == 0) {
duke@1 2713 List<Type> a = actuals;
duke@1 2714 List<Type> f = formals;
duke@1 2715 while (a.nonEmpty()) {
duke@1 2716 a.head = a.head.withTypeVar(f.head);
duke@1 2717 a = a.tail;
duke@1 2718 f = f.tail;
duke@1 2719 }
duke@1 2720 // Compute the proper generic outer
duke@1 2721 Type clazzOuter = clazztype.getEnclosingType();
duke@1 2722 if (clazzOuter.tag == CLASS) {
duke@1 2723 Type site;
jjg@308 2724 JCExpression clazz = TreeInfo.typeIn(tree.clazz);
jjg@308 2725 if (clazz.getTag() == JCTree.IDENT) {
duke@1 2726 site = env.enclClass.sym.type;
jjg@308 2727 } else if (clazz.getTag() == JCTree.SELECT) {
jjg@308 2728 site = ((JCFieldAccess) clazz).selected.type;
duke@1 2729 } else throw new AssertionError(""+tree);
duke@1 2730 if (clazzOuter.tag == CLASS && site != clazzOuter) {
duke@1 2731 if (site.tag == CLASS)
duke@1 2732 site = types.asOuterSuper(site, clazzOuter.tsym);
duke@1 2733 if (site == null)
duke@1 2734 site = types.erasure(clazzOuter);
duke@1 2735 clazzOuter = site;
duke@1 2736 }
duke@1 2737 }
mcimadamore@536 2738 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym);
duke@1 2739 } else {
duke@1 2740 if (formals.length() != 0) {
duke@1 2741 log.error(tree.pos(), "wrong.number.type.args",
duke@1 2742 Integer.toString(formals.length()));
duke@1 2743 } else {
duke@1 2744 log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym);
duke@1 2745 }
jjg@110 2746 owntype = types.createErrorType(tree.type);
duke@1 2747 }
duke@1 2748 }
duke@1 2749 result = check(tree, owntype, TYP, pkind, pt);
duke@1 2750 }
duke@1 2751
mcimadamore@550 2752 public void visitTypeDisjoint(JCTypeDisjoint tree) {
mcimadamore@550 2753 List<Type> componentTypes = attribTypes(tree.components, env);
mcimadamore@550 2754 tree.type = result = check(tree, types.lub(componentTypes), TYP, pkind, pt);
mcimadamore@550 2755 }
mcimadamore@550 2756
duke@1 2757 public void visitTypeParameter(JCTypeParameter tree) {
duke@1 2758 TypeVar a = (TypeVar)tree.type;
duke@1 2759 Set<Type> boundSet = new HashSet<Type>();
duke@1 2760 if (a.bound.isErroneous())
duke@1 2761 return;
duke@1 2762 List<Type> bs = types.getBounds(a);
duke@1 2763 if (tree.bounds.nonEmpty()) {
duke@1 2764 // accept class or interface or typevar as first bound.
duke@1 2765 Type b = checkBase(bs.head, tree.bounds.head, env, false, false, false);
duke@1 2766 boundSet.add(types.erasure(b));
mcimadamore@159 2767 if (b.isErroneous()) {
mcimadamore@159 2768 a.bound = b;
mcimadamore@159 2769 }
mcimadamore@159 2770 else if (b.tag == TYPEVAR) {
duke@1 2771 // if first bound was a typevar, do not accept further bounds.
duke@1 2772 if (tree.bounds.tail.nonEmpty()) {
duke@1 2773 log.error(tree.bounds.tail.head.pos(),
duke@1 2774 "type.var.may.not.be.followed.by.other.bounds");
jjg@504 2775 log.unrecoverableError = true;
duke@1 2776 tree.bounds = List.of(tree.bounds.head);
mcimadamore@7 2777 a.bound = bs.head;
duke@1 2778 }
duke@1 2779 } else {
duke@1 2780 // if first bound was a class or interface, accept only interfaces
duke@1 2781 // as further bounds.
duke@1 2782 for (JCExpression bound : tree.bounds.tail) {
duke@1 2783 bs = bs.tail;
duke@1 2784 Type i = checkBase(bs.head, bound, env, false, true, false);
mcimadamore@159 2785 if (i.isErroneous())
mcimadamore@159 2786 a.bound = i;
mcimadamore@159 2787 else if (i.tag == CLASS)
duke@1 2788 chk.checkNotRepeated(bound.pos(), types.erasure(i), boundSet);
duke@1 2789 }
duke@1 2790 }
duke@1 2791 }
duke@1 2792 bs = types.getBounds(a);
duke@1 2793
duke@1 2794 // in case of multiple bounds ...
duke@1 2795 if (bs.length() > 1) {
duke@1 2796 // ... the variable's bound is a class type flagged COMPOUND
duke@1 2797 // (see comment for TypeVar.bound).
duke@1 2798 // In this case, generate a class tree that represents the
duke@1 2799 // bound class, ...
duke@1 2800 JCTree extending;
duke@1 2801 List<JCExpression> implementing;
duke@1 2802 if ((bs.head.tsym.flags() & INTERFACE) == 0) {
duke@1 2803 extending = tree.bounds.head;
duke@1 2804 implementing = tree.bounds.tail;
duke@1 2805 } else {
duke@1 2806 extending = null;
duke@1 2807 implementing = tree.bounds;
duke@1 2808 }
duke@1 2809 JCClassDecl cd = make.at(tree.pos).ClassDef(
duke@1 2810 make.Modifiers(PUBLIC | ABSTRACT),
duke@1 2811 tree.name, List.<JCTypeParameter>nil(),
duke@1 2812 extending, implementing, List.<JCTree>nil());
duke@1 2813
duke@1 2814 ClassSymbol c = (ClassSymbol)a.getUpperBound().tsym;
duke@1 2815 assert (c.flags() & COMPOUND) != 0;
duke@1 2816 cd.sym = c;
duke@1 2817 c.sourcefile = env.toplevel.sourcefile;
duke@1 2818
duke@1 2819 // ... and attribute the bound class
duke@1 2820 c.flags_field |= UNATTRIBUTED;
duke@1 2821 Env<AttrContext> cenv = enter.classEnv(cd, env);
duke@1 2822 enter.typeEnvs.put(c, cenv);
duke@1 2823 }
duke@1 2824 }
duke@1 2825
duke@1 2826
duke@1 2827 public void visitWildcard(JCWildcard tree) {
duke@1 2828 //- System.err.println("visitWildcard("+tree+");");//DEBUG
duke@1 2829 Type type = (tree.kind.kind == BoundKind.UNBOUND)
duke@1 2830 ? syms.objectType
duke@1 2831 : attribType(tree.inner, env);
duke@1 2832 result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
duke@1 2833 tree.kind.kind,
duke@1 2834 syms.boundClass),
duke@1 2835 TYP, pkind, pt);
duke@1 2836 }
duke@1 2837
duke@1 2838 public void visitAnnotation(JCAnnotation tree) {
duke@1 2839 log.error(tree.pos(), "annotation.not.valid.for.type", pt);
duke@1 2840 result = tree.type = syms.errType;
duke@1 2841 }
duke@1 2842
jjg@308 2843 public void visitAnnotatedType(JCAnnotatedType tree) {
jjg@308 2844 result = tree.type = attribType(tree.getUnderlyingType(), env);
jjg@308 2845 }
jjg@308 2846
duke@1 2847 public void visitErroneous(JCErroneous tree) {
duke@1 2848 if (tree.errs != null)
duke@1 2849 for (JCTree err : tree.errs)
duke@1 2850 attribTree(err, env, ERR, pt);
duke@1 2851 result = tree.type = syms.errType;
duke@1 2852 }
duke@1 2853
duke@1 2854 /** Default visitor method for all other trees.
duke@1 2855 */
duke@1 2856 public void visitTree(JCTree tree) {
duke@1 2857 throw new AssertionError();
duke@1 2858 }
duke@1 2859
duke@1 2860 /** Main method: attribute class definition associated with given class symbol.
duke@1 2861 * reporting completion failures at the given position.
duke@1 2862 * @param pos The source position at which completion errors are to be
duke@1 2863 * reported.
duke@1 2864 * @param c The class symbol whose definition will be attributed.
duke@1 2865 */
duke@1 2866 public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
duke@1 2867 try {
duke@1 2868 annotate.flush();
duke@1 2869 attribClass(c);
duke@1 2870 } catch (CompletionFailure ex) {
duke@1 2871 chk.completionError(pos, ex);
duke@1 2872 }
duke@1 2873 }
duke@1 2874
duke@1 2875 /** Attribute class definition associated with given class symbol.
duke@1 2876 * @param c The class symbol whose definition will be attributed.
duke@1 2877 */
duke@1 2878 void attribClass(ClassSymbol c) throws CompletionFailure {
duke@1 2879 if (c.type.tag == ERROR) return;
duke@1 2880
duke@1 2881 // Check for cycles in the inheritance graph, which can arise from
duke@1 2882 // ill-formed class files.
duke@1 2883 chk.checkNonCyclic(null, c.type);
duke@1 2884
duke@1 2885 Type st = types.supertype(c.type);
duke@1 2886 if ((c.flags_field & Flags.COMPOUND) == 0) {
duke@1 2887 // First, attribute superclass.
duke@1 2888 if (st.tag == CLASS)
duke@1 2889 attribClass((ClassSymbol)st.tsym);
duke@1 2890
duke@1 2891 // Next attribute owner, if it is a class.
duke@1 2892 if (c.owner.kind == TYP && c.owner.type.tag == CLASS)
duke@1 2893 attribClass((ClassSymbol)c.owner);
duke@1 2894 }
duke@1 2895
duke@1 2896 // The previous operations might have attributed the current class
duke@1 2897 // if there was a cycle. So we test first whether the class is still
duke@1 2898 // UNATTRIBUTED.
duke@1 2899 if ((c.flags_field & UNATTRIBUTED) != 0) {
duke@1 2900 c.flags_field &= ~UNATTRIBUTED;
duke@1 2901
duke@1 2902 // Get environment current at the point of class definition.
duke@1 2903 Env<AttrContext> env = enter.typeEnvs.get(c);
duke@1 2904
duke@1 2905 // The info.lint field in the envs stored in enter.typeEnvs is deliberately uninitialized,
duke@1 2906 // because the annotations were not available at the time the env was created. Therefore,
duke@1 2907 // we look up the environment chain for the first enclosing environment for which the
duke@1 2908 // lint value is set. Typically, this is the parent env, but might be further if there
duke@1 2909 // are any envs created as a result of TypeParameter nodes.
duke@1 2910 Env<AttrContext> lintEnv = env;
duke@1 2911 while (lintEnv.info.lint == null)
duke@1 2912 lintEnv = lintEnv.next;
duke@1 2913
duke@1 2914 // Having found the enclosing lint value, we can initialize the lint value for this class
duke@1 2915 env.info.lint = lintEnv.info.lint.augment(c.attributes_field, c.flags());
duke@1 2916
duke@1 2917 Lint prevLint = chk.setLint(env.info.lint);
duke@1 2918 JavaFileObject prev = log.useSource(c.sourcefile);
duke@1 2919
duke@1 2920 try {
duke@1 2921 // java.lang.Enum may not be subclassed by a non-enum
duke@1 2922 if (st.tsym == syms.enumSym &&
duke@1 2923 ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
duke@1 2924 log.error(env.tree.pos(), "enum.no.subclassing");
duke@1 2925
duke@1 2926 // Enums may not be extended by source-level classes
duke@1 2927 if (st.tsym != null &&
duke@1 2928 ((st.tsym.flags_field & Flags.ENUM) != 0) &&
mcimadamore@82 2929 ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0) &&
duke@1 2930 !target.compilerBootstrap(c)) {
duke@1 2931 log.error(env.tree.pos(), "enum.types.not.extensible");
duke@1 2932 }
duke@1 2933 attribClassBody(env, c);
duke@1 2934
duke@1 2935 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
duke@1 2936 } finally {
duke@1 2937 log.useSource(prev);
duke@1 2938 chk.setLint(prevLint);
duke@1 2939 }
duke@1 2940
duke@1 2941 }
duke@1 2942 }
duke@1 2943
duke@1 2944 public void visitImport(JCImport tree) {
duke@1 2945 // nothing to do
duke@1 2946 }
duke@1 2947
duke@1 2948 /** Finish the attribution of a class. */
duke@1 2949 private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
duke@1 2950 JCClassDecl tree = (JCClassDecl)env.tree;
duke@1 2951 assert c == tree.sym;
duke@1 2952
duke@1 2953 // Validate annotations
duke@1 2954 chk.validateAnnotations(tree.mods.annotations, c);
duke@1 2955
duke@1 2956 // Validate type parameters, supertype and interfaces.
mcimadamore@42 2957 attribBounds(tree.typarams);
mcimadamore@537 2958 if (!c.isAnonymous()) {
mcimadamore@537 2959 //already checked if anonymous
mcimadamore@537 2960 chk.validate(tree.typarams, env);
mcimadamore@537 2961 chk.validate(tree.extending, env);
mcimadamore@537 2962 chk.validate(tree.implementing, env);
mcimadamore@537 2963 }
duke@1 2964
duke@1 2965 // If this is a non-abstract class, check that it has no abstract
duke@1 2966 // methods or unimplemented methods of an implemented interface.
duke@1 2967 if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
duke@1 2968 if (!relax)
duke@1 2969 chk.checkAllDefined(tree.pos(), c);
duke@1 2970 }
duke@1 2971
duke@1 2972 if ((c.flags() & ANNOTATION) != 0) {
duke@1 2973 if (tree.implementing.nonEmpty())
duke@1 2974 log.error(tree.implementing.head.pos(),
duke@1 2975 "cant.extend.intf.annotation");
duke@1 2976 if (tree.typarams.nonEmpty())
duke@1 2977 log.error(tree.typarams.head.pos(),
duke@1 2978 "intf.annotation.cant.have.type.params");
duke@1 2979 } else {
duke@1 2980 // Check that all extended classes and interfaces
duke@1 2981 // are compatible (i.e. no two define methods with same arguments
duke@1 2982 // yet different return types). (JLS 8.4.6.3)
duke@1 2983 chk.checkCompatibleSupertypes(tree.pos(), c.type);
duke@1 2984 }
duke@1 2985
duke@1 2986 // Check that class does not import the same parameterized interface
duke@1 2987 // with two different argument lists.
duke@1 2988 chk.checkClassBounds(tree.pos(), c.type);
duke@1 2989
duke@1 2990 tree.type = c.type;
duke@1 2991
duke@1 2992 boolean assertsEnabled = false;
duke@1 2993 assert assertsEnabled = true;
duke@1 2994 if (assertsEnabled) {
duke@1 2995 for (List<JCTypeParameter> l = tree.typarams;
duke@1 2996 l.nonEmpty(); l = l.tail)
duke@1 2997 assert env.info.scope.lookup(l.head.name).scope != null;
duke@1 2998 }
duke@1 2999
duke@1 3000 // Check that a generic class doesn't extend Throwable
duke@1 3001 if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
duke@1 3002 log.error(tree.extending.pos(), "generic.throwable");
duke@1 3003
duke@1 3004 // Check that all methods which implement some
duke@1 3005 // method conform to the method they implement.
duke@1 3006 chk.checkImplementations(tree);
duke@1 3007
duke@1 3008 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
duke@1 3009 // Attribute declaration
duke@1 3010 attribStat(l.head, env);
duke@1 3011 // Check that declarations in inner classes are not static (JLS 8.1.2)
duke@1 3012 // Make an exception for static constants.
duke@1 3013 if (c.owner.kind != PCK &&
duke@1 3014 ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
duke@1 3015 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
duke@1 3016 Symbol sym = null;
duke@1 3017 if (l.head.getTag() == JCTree.VARDEF) sym = ((JCVariableDecl) l.head).sym;
duke@1 3018 if (sym == null ||
duke@1 3019 sym.kind != VAR ||
duke@1 3020 ((VarSymbol) sym).getConstValue() == null)
duke@1 3021 log.error(l.head.pos(), "icls.cant.have.static.decl");
duke@1 3022 }
duke@1 3023 }
duke@1 3024
duke@1 3025 // Check for cycles among non-initial constructors.
duke@1 3026 chk.checkCyclicConstructors(tree);
duke@1 3027
duke@1 3028 // Check for cycles among annotation elements.
duke@1 3029 chk.checkNonCyclicElements(tree);
duke@1 3030
duke@1 3031 // Check for proper use of serialVersionUID
duke@1 3032 if (env.info.lint.isEnabled(Lint.LintCategory.SERIAL) &&
duke@1 3033 isSerializable(c) &&
duke@1 3034 (c.flags() & Flags.ENUM) == 0 &&
duke@1 3035 (c.flags() & ABSTRACT) == 0) {
duke@1 3036 checkSerialVersionUID(tree, c);
duke@1 3037 }
jjg@308 3038
jjg@308 3039 // Check type annotations applicability rules
jjg@308 3040 validateTypeAnnotations(tree);
duke@1 3041 }
duke@1 3042 // where
duke@1 3043 /** check if a class is a subtype of Serializable, if that is available. */
duke@1 3044 private boolean isSerializable(ClassSymbol c) {
duke@1 3045 try {
duke@1 3046 syms.serializableType.complete();
duke@1 3047 }
duke@1 3048 catch (CompletionFailure e) {
duke@1 3049 return false;
duke@1 3050 }
duke@1 3051 return types.isSubtype(c.type, syms.serializableType);
duke@1 3052 }
duke@1 3053
duke@1 3054 /** Check that an appropriate serialVersionUID member is defined. */
duke@1 3055 private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
duke@1 3056
duke@1 3057 // check for presence of serialVersionUID
duke@1 3058 Scope.Entry e = c.members().lookup(names.serialVersionUID);
duke@1 3059 while (e.scope != null && e.sym.kind != VAR) e = e.next();
duke@1 3060 if (e.scope == null) {
duke@1 3061 log.warning(tree.pos(), "missing.SVUID", c);
duke@1 3062 return;
duke@1 3063 }
duke@1 3064
duke@1 3065 // check that it is static final
duke@1 3066 VarSymbol svuid = (VarSymbol)e.sym;
duke@1 3067 if ((svuid.flags() & (STATIC | FINAL)) !=
duke@1 3068 (STATIC | FINAL))
duke@1 3069 log.warning(TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c);
duke@1 3070
duke@1 3071 // check that it is long
duke@1 3072 else if (svuid.type.tag != TypeTags.LONG)
duke@1 3073 log.warning(TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c);
duke@1 3074
duke@1 3075 // check constant
duke@1 3076 else if (svuid.getConstValue() == null)
duke@1 3077 log.warning(TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c);
duke@1 3078 }
duke@1 3079
duke@1 3080 private Type capture(Type type) {
duke@1 3081 return types.capture(type);
duke@1 3082 }
jjg@308 3083
jjg@308 3084 private void validateTypeAnnotations(JCTree tree) {
jjg@308 3085 tree.accept(typeAnnotationsValidator);
jjg@308 3086 }
jjg@308 3087 //where
jjg@308 3088 private final JCTree.Visitor typeAnnotationsValidator =
jjg@308 3089 new TreeScanner() {
jjg@308 3090 public void visitAnnotation(JCAnnotation tree) {
jjg@308 3091 if (tree instanceof JCTypeAnnotation) {
jjg@308 3092 chk.validateTypeAnnotation((JCTypeAnnotation)tree, false);
jjg@308 3093 }
jjg@308 3094 super.visitAnnotation(tree);
jjg@308 3095 }
jjg@308 3096 public void visitTypeParameter(JCTypeParameter tree) {
jjg@308 3097 chk.validateTypeAnnotations(tree.annotations, true);
jjg@308 3098 // don't call super. skip type annotations
jjg@308 3099 scan(tree.bounds);
jjg@308 3100 }
jjg@308 3101 public void visitMethodDef(JCMethodDecl tree) {
jjg@308 3102 // need to check static methods
jjg@308 3103 if ((tree.sym.flags() & Flags.STATIC) != 0) {
jjg@308 3104 for (JCTypeAnnotation a : tree.receiverAnnotations) {
jjg@308 3105 if (chk.isTypeAnnotation(a, false))
jjg@308 3106 log.error(a.pos(), "annotation.type.not.applicable");
jjg@308 3107 }
jjg@308 3108 }
jjg@308 3109 super.visitMethodDef(tree);
jjg@308 3110 }
jjg@308 3111 };
duke@1 3112 }

mercurial