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

Mon, 11 Nov 2013 17:26:09 +0100

author
jfranck
date
Mon, 11 Nov 2013 17:26:09 +0100
changeset 2188
f3ca12d680f3
parent 2136
7f6481e5fe3a
child 2525
2eb010b6cb22
permissions
-rw-r--r--

8027375: javac asserts on nested erroneous annotations
Summary: make sure JCAnnotation trees have type != null before annotation processing
Reviewed-by: jjg

duke@1 1 /*
jjg@1492 2 * Copyright (c) 2003, 2013, 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
jfranck@1313 28 import java.util.Map;
jjg@1521 29
duke@1 30 import com.sun.tools.javac.util.*;
jfranck@1313 31 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
duke@1 32 import com.sun.tools.javac.code.*;
duke@1 33 import com.sun.tools.javac.code.Symbol.*;
duke@1 34 import com.sun.tools.javac.tree.*;
duke@1 35 import com.sun.tools.javac.tree.JCTree.*;
duke@1 36
jjg@1374 37 import static com.sun.tools.javac.code.TypeTag.ARRAY;
jjg@1374 38 import static com.sun.tools.javac.code.TypeTag.CLASS;
jjg@1127 39 import static com.sun.tools.javac.tree.JCTree.Tag.*;
jlahoda@2108 40 import javax.lang.model.type.ErrorType;
jjg@1127 41
duke@1 42 /** Enter annotations on symbols. Annotations accumulate in a queue,
duke@1 43 * which is processed at the top level of any set of recursive calls
duke@1 44 * requesting it be processed.
duke@1 45 *
jjg@581 46 * <p><b>This is NOT part of any supported API.
jjg@581 47 * If you write code that depends on this, you do so at your own risk.
duke@1 48 * This code and its internal interfaces are subject to change or
duke@1 49 * deletion without notice.</b>
duke@1 50 */
duke@1 51 public class Annotate {
duke@1 52 protected static final Context.Key<Annotate> annotateKey =
duke@1 53 new Context.Key<Annotate>();
duke@1 54
duke@1 55 public static Annotate instance(Context context) {
duke@1 56 Annotate instance = context.get(annotateKey);
duke@1 57 if (instance == null)
duke@1 58 instance = new Annotate(context);
duke@1 59 return instance;
duke@1 60 }
duke@1 61
duke@1 62 final Attr attr;
duke@1 63 final TreeMaker make;
duke@1 64 final Log log;
duke@1 65 final Symtab syms;
jjg@113 66 final Names names;
duke@1 67 final Resolve rs;
duke@1 68 final Types types;
duke@1 69 final ConstFold cfolder;
duke@1 70 final Check chk;
duke@1 71
duke@1 72 protected Annotate(Context context) {
duke@1 73 context.put(annotateKey, this);
duke@1 74 attr = Attr.instance(context);
duke@1 75 make = TreeMaker.instance(context);
duke@1 76 log = Log.instance(context);
duke@1 77 syms = Symtab.instance(context);
jjg@113 78 names = Names.instance(context);
duke@1 79 rs = Resolve.instance(context);
duke@1 80 types = Types.instance(context);
duke@1 81 cfolder = ConstFold.instance(context);
duke@1 82 chk = Check.instance(context);
duke@1 83 }
duke@1 84
duke@1 85 /* ********************************************************************
duke@1 86 * Queue maintenance
duke@1 87 *********************************************************************/
duke@1 88
duke@1 89 private int enterCount = 0;
duke@1 90
jlahoda@2133 91 ListBuffer<Worker> q = new ListBuffer<Worker>();
jlahoda@2133 92 ListBuffer<Worker> typesQ = new ListBuffer<Worker>();
jlahoda@2133 93 ListBuffer<Worker> repeatedQ = new ListBuffer<Worker>();
jlahoda@2133 94 ListBuffer<Worker> afterRepeatedQ = new ListBuffer<Worker>();
jlahoda@2133 95 ListBuffer<Worker> validateQ = new ListBuffer<Worker>();
jjg@1521 96
jlahoda@2133 97 public void earlier(Worker a) {
jjg@1521 98 q.prepend(a);
jjg@1521 99 }
duke@1 100
jlahoda@2133 101 public void normal(Worker a) {
duke@1 102 q.append(a);
duke@1 103 }
duke@1 104
jlahoda@2133 105 public void typeAnnotation(Worker a) {
jjg@1521 106 typesQ.append(a);
duke@1 107 }
duke@1 108
jlahoda@2133 109 public void repeated(Worker a) {
jfranck@1313 110 repeatedQ.append(a);
jfranck@1313 111 }
jfranck@1313 112
jlahoda@2133 113 public void afterRepeated(Worker a) {
jjg@1521 114 afterRepeatedQ.append(a);
jjg@1521 115 }
jjg@1521 116
jlahoda@2133 117 public void validate(Worker a) {
jlahoda@2111 118 validateQ.append(a);
jlahoda@2111 119 }
jlahoda@2111 120
duke@1 121 /** Called when the Enter phase starts. */
duke@1 122 public void enterStart() {
duke@1 123 enterCount++;
duke@1 124 }
duke@1 125
duke@1 126 /** Called after the Enter phase completes. */
duke@1 127 public void enterDone() {
duke@1 128 enterCount--;
duke@1 129 flush();
duke@1 130 }
duke@1 131
emc@2136 132 /** Variant which allows for a delayed flush of annotations.
emc@2136 133 * Needed by ClassReader */
emc@2136 134 public void enterDoneWithoutFlush() {
emc@2136 135 enterCount--;
emc@2136 136 }
emc@2136 137
duke@1 138 public void flush() {
duke@1 139 if (enterCount != 0) return;
duke@1 140 enterCount++;
duke@1 141 try {
jjg@1521 142 while (q.nonEmpty()) {
jlahoda@2133 143 q.next().run();
jjg@1521 144 }
jjg@1521 145 while (typesQ.nonEmpty()) {
jlahoda@2133 146 typesQ.next().run();
jjg@1521 147 }
jfranck@1313 148 while (repeatedQ.nonEmpty()) {
jlahoda@2133 149 repeatedQ.next().run();
jfranck@1313 150 }
jjg@1521 151 while (afterRepeatedQ.nonEmpty()) {
jlahoda@2133 152 afterRepeatedQ.next().run();
jjg@1521 153 }
jlahoda@2111 154 while (validateQ.nonEmpty()) {
jlahoda@2133 155 validateQ.next().run();
jlahoda@2111 156 }
duke@1 157 } finally {
duke@1 158 enterCount--;
duke@1 159 }
duke@1 160 }
duke@1 161
jlahoda@2133 162 /** A client that needs to run during {@link #flush()} registers an worker
jlahoda@2133 163 * into one of the queues defined in this class. The queues are: {@link #earlier(Worker)},
jlahoda@2133 164 * {@link #normal(Worker)}, {@link #typeAnnotation(Worker)}, {@link #repeated(Worker)},
jlahoda@2133 165 * {@link #afterRepeated(Worker)}, {@link #validate(Worker)}.
jlahoda@2133 166 * The {@link Worker#run()} method will called inside the {@link #flush()}
jlahoda@2133 167 * call. Queues are empties in the abovementioned order.
duke@1 168 */
jlahoda@2133 169 public interface Worker {
jlahoda@2133 170 void run();
duke@1 171 String toString();
duke@1 172 }
duke@1 173
jfranck@1313 174 /**
jfranck@1313 175 * This context contains all the information needed to synthesize new
jfranck@1313 176 * annotations trees by the completer for repeating annotations.
jfranck@1313 177 */
jjg@1521 178 public class AnnotateRepeatedContext<T extends Attribute.Compound> {
jfranck@1313 179 public final Env<AttrContext> env;
jjg@1521 180 public final Map<Symbol.TypeSymbol, ListBuffer<T>> annotated;
jjg@1521 181 public final Map<T, JCDiagnostic.DiagnosticPosition> pos;
jfranck@1313 182 public final Log log;
jjg@1521 183 public final boolean isTypeCompound;
jfranck@1313 184
jfranck@1313 185 public AnnotateRepeatedContext(Env<AttrContext> env,
jjg@1521 186 Map<Symbol.TypeSymbol, ListBuffer<T>> annotated,
jjg@1521 187 Map<T, JCDiagnostic.DiagnosticPosition> pos,
jjg@1521 188 Log log,
jjg@1521 189 boolean isTypeCompound) {
jjg@1322 190 Assert.checkNonNull(env);
jjg@1322 191 Assert.checkNonNull(annotated);
jjg@1322 192 Assert.checkNonNull(pos);
jjg@1322 193 Assert.checkNonNull(log);
jfranck@1313 194
jfranck@1313 195 this.env = env;
jfranck@1313 196 this.annotated = annotated;
jfranck@1313 197 this.pos = pos;
jfranck@1313 198 this.log = log;
jjg@1521 199 this.isTypeCompound = isTypeCompound;
jfranck@1313 200 }
jfranck@1313 201
jfranck@1313 202 /**
jfranck@1313 203 * Process a list of repeating annotations returning a new
jfranck@1313 204 * Attribute.Compound that is the attribute for the synthesized tree
jfranck@1313 205 * for the container.
jfranck@1313 206 *
jfranck@1313 207 * @param repeatingAnnotations a List of repeating annotations
jfranck@1313 208 * @return a new Attribute.Compound that is the container for the repeatingAnnotations
jfranck@1313 209 */
jjg@1521 210 public T processRepeatedAnnotations(List<T> repeatingAnnotations, Symbol sym) {
jfranck@1445 211 return Annotate.this.processRepeatedAnnotations(repeatingAnnotations, this, sym);
jfranck@1313 212 }
jfranck@1313 213
jfranck@1313 214 /**
jlahoda@2133 215 * Queue the Worker a on the repeating annotations queue of the
jfranck@1313 216 * Annotate instance this context belongs to.
jfranck@1313 217 *
jlahoda@2133 218 * @param a the Worker to enqueue for repeating annotation annotating
jfranck@1313 219 */
jlahoda@2133 220 public void annotateRepeated(Worker a) {
jfranck@1313 221 Annotate.this.repeated(a);
jfranck@1313 222 }
jfranck@1313 223 }
duke@1 224
duke@1 225 /* ********************************************************************
duke@1 226 * Compute an attribute from its annotation.
duke@1 227 *********************************************************************/
duke@1 228
duke@1 229 /** Process a single compound annotation, returning its
duke@1 230 * Attribute. Used from MemberEnter for attaching the attributes
duke@1 231 * to the annotated symbol.
duke@1 232 */
duke@1 233 Attribute.Compound enterAnnotation(JCAnnotation a,
duke@1 234 Type expected,
duke@1 235 Env<AttrContext> env) {
jjg@1755 236 return enterAnnotation(a, expected, env, false);
jjg@1755 237 }
jjg@1755 238
jjg@1755 239 Attribute.TypeCompound enterTypeAnnotation(JCAnnotation a,
jjg@1755 240 Type expected,
jjg@1755 241 Env<AttrContext> env) {
jjg@1755 242 return (Attribute.TypeCompound) enterAnnotation(a, expected, env, true);
jjg@1755 243 }
jjg@1755 244
jjg@1755 245 // boolean typeAnnotation determines whether the method returns
jjg@1755 246 // a Compound (false) or TypeCompound (true).
jjg@1755 247 Attribute.Compound enterAnnotation(JCAnnotation a,
jjg@1755 248 Type expected,
jjg@1755 249 Env<AttrContext> env,
jjg@1755 250 boolean typeAnnotation) {
duke@1 251 // The annotation might have had its type attributed (but not checked)
duke@1 252 // by attr.attribAnnotationTypes during MemberEnter, in which case we do not
duke@1 253 // need to do it again.
duke@1 254 Type at = (a.annotationType.type != null ? a.annotationType.type
duke@1 255 : attr.attribType(a.annotationType, env));
duke@1 256 a.type = chk.checkType(a.annotationType.pos(), at, expected);
jjg@1755 257 if (a.type.isErroneous()) {
jfranck@2188 258 // Need to make sure nested (anno)trees does not have null as .type
jfranck@2188 259 attr.postAttr(a);
jfranck@2188 260
jjg@1755 261 if (typeAnnotation) {
jjg@2134 262 return new Attribute.TypeCompound(a.type, List.<Pair<MethodSymbol,Attribute>>nil(),
jjg@2134 263 new TypeAnnotationPosition());
jjg@1755 264 } else {
jjg@1755 265 return new Attribute.Compound(a.type, List.<Pair<MethodSymbol,Attribute>>nil());
jjg@1755 266 }
jjg@1755 267 }
duke@1 268 if ((a.type.tsym.flags() & Flags.ANNOTATION) == 0) {
duke@1 269 log.error(a.annotationType.pos(),
duke@1 270 "not.annotation.type", a.type.toString());
jfranck@2188 271
jfranck@2188 272 // Need to make sure nested (anno)trees does not have null as .type
jfranck@2188 273 attr.postAttr(a);
jfranck@2188 274
jjg@1755 275 if (typeAnnotation) {
jjg@1755 276 return new Attribute.TypeCompound(a.type, List.<Pair<MethodSymbol,Attribute>>nil(), null);
jjg@1755 277 } else {
jjg@1755 278 return new Attribute.Compound(a.type, List.<Pair<MethodSymbol,Attribute>>nil());
jjg@1755 279 }
duke@1 280 }
duke@1 281 List<JCExpression> args = a.args;
jjg@1127 282 if (args.length() == 1 && !args.head.hasTag(ASSIGN)) {
duke@1 283 // special case: elided "value=" assumed
duke@1 284 args.head = make.at(args.head.pos).
duke@1 285 Assign(make.Ident(names.value), args.head);
duke@1 286 }
duke@1 287 ListBuffer<Pair<MethodSymbol,Attribute>> buf =
jfranck@2188 288 new ListBuffer<>();
duke@1 289 for (List<JCExpression> tl = args; tl.nonEmpty(); tl = tl.tail) {
duke@1 290 JCExpression t = tl.head;
jjg@1127 291 if (!t.hasTag(ASSIGN)) {
duke@1 292 log.error(t.pos(), "annotation.value.must.be.name.value");
duke@1 293 continue;
duke@1 294 }
duke@1 295 JCAssign assign = (JCAssign)t;
jjg@1127 296 if (!assign.lhs.hasTag(IDENT)) {
duke@1 297 log.error(t.pos(), "annotation.value.must.be.name.value");
duke@1 298 continue;
duke@1 299 }
duke@1 300 JCIdent left = (JCIdent)assign.lhs;
ksrini@1914 301 Symbol method = rs.resolveQualifiedMethod(assign.rhs.pos(),
mcimadamore@992 302 env,
mcimadamore@992 303 a.type,
mcimadamore@992 304 left.name,
mcimadamore@992 305 List.<Type>nil(),
mcimadamore@992 306 null);
duke@1 307 left.sym = method;
duke@1 308 left.type = method.type;
duke@1 309 if (method.owner != a.type.tsym)
duke@1 310 log.error(left.pos(), "no.annotation.member", left.name, a.type);
duke@1 311 Type result = method.type.getReturnType();
duke@1 312 Attribute value = enterAttributeValue(result, assign.rhs, env);
duke@1 313 if (!method.type.isErroneous())
jfranck@2188 314 buf.append(new Pair<>((MethodSymbol)method, value));
mcimadamore@676 315 t.type = result;
duke@1 316 }
jjg@1755 317 if (typeAnnotation) {
jjg@1755 318 if (a.attribute == null || !(a.attribute instanceof Attribute.TypeCompound)) {
jjg@1755 319 // Create a new TypeCompound
jjg@1755 320 Attribute.TypeCompound tc = new Attribute.TypeCompound(a.type, buf.toList(), new TypeAnnotationPosition());
jjg@1755 321 a.attribute = tc;
jjg@1755 322 return tc;
jjg@1755 323 } else {
jjg@1755 324 // Use an existing TypeCompound
jjg@1755 325 return a.attribute;
jjg@1755 326 }
jjg@1755 327 } else {
jjg@1755 328 Attribute.Compound ac = new Attribute.Compound(a.type, buf.toList());
jjg@1755 329 a.attribute = ac;
jjg@1755 330 return ac;
jjg@1755 331 }
duke@1 332 }
duke@1 333
duke@1 334 Attribute enterAttributeValue(Type expected,
duke@1 335 JCExpression tree,
duke@1 336 Env<AttrContext> env) {
mcimadamore@992 337 //first, try completing the attribution value sym - if a completion
mcimadamore@992 338 //error is thrown, we should recover gracefully, and display an
mcimadamore@992 339 //ordinary resolution diagnostic.
mcimadamore@992 340 try {
mcimadamore@992 341 expected.tsym.complete();
mcimadamore@992 342 } catch(CompletionFailure e) {
mcimadamore@992 343 log.error(tree.pos(), "cant.resolve", Kinds.kindName(e.sym), e.sym);
jlahoda@2070 344 expected = syms.errType;
jlahoda@2070 345 }
jlahoda@2070 346 if (expected.hasTag(ARRAY)) {
jlahoda@2070 347 if (!tree.hasTag(NEWARRAY)) {
jlahoda@2070 348 tree = make.at(tree.pos).
jlahoda@2070 349 NewArray(null, List.<JCExpression>nil(), List.of(tree));
jlahoda@2070 350 }
jlahoda@2070 351 JCNewArray na = (JCNewArray)tree;
jlahoda@2070 352 if (na.elemtype != null) {
jlahoda@2070 353 log.error(na.elemtype.pos(), "new.not.allowed.in.annotation");
jlahoda@2070 354 }
jlahoda@2070 355 ListBuffer<Attribute> buf = new ListBuffer<Attribute>();
jlahoda@2070 356 for (List<JCExpression> l = na.elems; l.nonEmpty(); l=l.tail) {
jlahoda@2070 357 buf.append(enterAttributeValue(types.elemtype(expected),
jlahoda@2070 358 l.head,
jlahoda@2070 359 env));
jlahoda@2070 360 }
jlahoda@2070 361 na.type = expected;
jlahoda@2070 362 return new Attribute.
jlahoda@2070 363 Array(expected, buf.toArray(new Attribute[buf.length()]));
jlahoda@2070 364 }
jlahoda@2070 365 if (tree.hasTag(NEWARRAY)) { //error recovery
jlahoda@2070 366 if (!expected.isErroneous())
jlahoda@2070 367 log.error(tree.pos(), "annotation.value.not.allowable.type");
jlahoda@2070 368 JCNewArray na = (JCNewArray)tree;
jlahoda@2070 369 if (na.elemtype != null) {
jlahoda@2070 370 log.error(na.elemtype.pos(), "new.not.allowed.in.annotation");
jlahoda@2070 371 }
jlahoda@2070 372 for (List<JCExpression> l = na.elems; l.nonEmpty(); l=l.tail) {
jlahoda@2070 373 enterAttributeValue(syms.errType,
jlahoda@2070 374 l.head,
jlahoda@2070 375 env);
jlahoda@2070 376 }
jlahoda@2108 377 return new Attribute.Error(syms.errType);
jlahoda@2070 378 }
jlahoda@2070 379 if ((expected.tsym.flags() & Flags.ANNOTATION) != 0) {
jlahoda@2070 380 if (tree.hasTag(ANNOTATION)) {
jlahoda@2070 381 return enterAnnotation((JCAnnotation)tree, expected, env);
jlahoda@2070 382 } else {
jlahoda@2070 383 log.error(tree.pos(), "annotation.value.must.be.annotation");
jlahoda@2070 384 expected = syms.errType;
jlahoda@2070 385 }
jlahoda@2070 386 }
jlahoda@2070 387 if (tree.hasTag(ANNOTATION)) { //error recovery
jlahoda@2070 388 if (!expected.isErroneous())
jlahoda@2070 389 log.error(tree.pos(), "annotation.not.valid.for.type", expected);
jlahoda@2070 390 enterAnnotation((JCAnnotation)tree, syms.errType, env);
jlahoda@2108 391 return new Attribute.Error(((JCAnnotation)tree).annotationType.type);
mcimadamore@992 392 }
duke@1 393 if (expected.isPrimitive() || types.isSameType(expected, syms.stringType)) {
duke@1 394 Type result = attr.attribExpr(tree, env, expected);
duke@1 395 if (result.isErroneous())
jlahoda@2108 396 return new Attribute.Error(result.getOriginalType());
duke@1 397 if (result.constValue() == null) {
duke@1 398 log.error(tree.pos(), "attribute.value.must.be.constant");
duke@1 399 return new Attribute.Error(expected);
duke@1 400 }
duke@1 401 result = cfolder.coerce(result, expected);
duke@1 402 return new Attribute.Constant(expected, result.constValue());
duke@1 403 }
duke@1 404 if (expected.tsym == syms.classType.tsym) {
duke@1 405 Type result = attr.attribExpr(tree, env, expected);
jfranck@1960 406 if (result.isErroneous()) {
jlahoda@2108 407 // Does it look like an unresolved class literal?
jlahoda@2108 408 if (TreeInfo.name(tree) == names._class &&
jlahoda@2108 409 ((JCFieldAccess) tree).selected.type.isErroneous()) {
jfranck@1960 410 Name n = (((JCFieldAccess) tree).selected).type.tsym.flatName();
jfranck@1960 411 return new Attribute.UnresolvedClass(expected,
jfranck@1960 412 types.createErrorType(n,
jfranck@1960 413 syms.unknownSymbol, syms.classType));
jfranck@1960 414 } else {
jlahoda@2108 415 return new Attribute.Error(result.getOriginalType());
jfranck@1960 416 }
jfranck@1960 417 }
jfranck@1960 418
jfranck@1960 419 // Class literals look like field accesses of a field named class
jfranck@1960 420 // at the tree level
duke@1 421 if (TreeInfo.name(tree) != names._class) {
duke@1 422 log.error(tree.pos(), "annotation.value.must.be.class.literal");
jlahoda@2108 423 return new Attribute.Error(syms.errType);
duke@1 424 }
duke@1 425 return new Attribute.Class(types,
duke@1 426 (((JCFieldAccess) tree).selected).type);
duke@1 427 }
jjg@1374 428 if (expected.hasTag(CLASS) &&
duke@1 429 (expected.tsym.flags() & Flags.ENUM) != 0) {
jlahoda@2108 430 Type result = attr.attribExpr(tree, env, expected);
duke@1 431 Symbol sym = TreeInfo.symbol(tree);
duke@1 432 if (sym == null ||
duke@1 433 TreeInfo.nonstaticSelect(tree) ||
duke@1 434 sym.kind != Kinds.VAR ||
duke@1 435 (sym.flags() & Flags.ENUM) == 0) {
duke@1 436 log.error(tree.pos(), "enum.annotation.must.be.enum.constant");
jlahoda@2108 437 return new Attribute.Error(result.getOriginalType());
duke@1 438 }
duke@1 439 VarSymbol enumerator = (VarSymbol) sym;
duke@1 440 return new Attribute.Enum(expected, enumerator);
duke@1 441 }
jlahoda@2070 442 //error recovery:
duke@1 443 if (!expected.isErroneous())
duke@1 444 log.error(tree.pos(), "annotation.value.not.allowable.type");
duke@1 445 return new Attribute.Error(attr.attribExpr(tree, env, expected));
duke@1 446 }
jfranck@1313 447
jfranck@1313 448 /* *********************************
jfranck@1313 449 * Support for repeating annotations
jfranck@1313 450 ***********************************/
jfranck@1313 451
jfranck@1313 452 /* Process repeated annotations. This method returns the
jfranck@1313 453 * synthesized container annotation or null IFF all repeating
jfranck@1313 454 * annotation are invalid. This method reports errors/warnings.
jfranck@1313 455 */
jjg@1521 456 private <T extends Attribute.Compound> T processRepeatedAnnotations(List<T> annotations,
jjg@1521 457 AnnotateRepeatedContext<T> ctx,
jjg@1521 458 Symbol on) {
jjg@1521 459 T firstOccurrence = annotations.head;
jfranck@1313 460 List<Attribute> repeated = List.nil();
jfranck@1445 461 Type origAnnoType = null;
jfranck@1313 462 Type arrayOfOrigAnnoType = null;
jfranck@1313 463 Type targetContainerType = null;
jfranck@1313 464 MethodSymbol containerValueSymbol = null;
jfranck@1313 465
jfranck@1313 466 Assert.check(!annotations.isEmpty() &&
jfranck@1313 467 !annotations.tail.isEmpty()); // i.e. size() > 1
jfranck@1313 468
jfranck@1629 469 int count = 0;
jjg@1521 470 for (List<T> al = annotations;
jfranck@1313 471 !al.isEmpty();
jfranck@1313 472 al = al.tail)
jfranck@1313 473 {
jfranck@1629 474 count++;
jfranck@1629 475
jfranck@1629 476 // There must be more than a single anno in the annotation list
jfranck@1629 477 Assert.check(count > 1 || !al.tail.isEmpty());
jfranck@1629 478
jjg@1521 479 T currentAnno = al.head;
jfranck@1313 480
jfranck@1313 481 origAnnoType = currentAnno.type;
jfranck@1313 482 if (arrayOfOrigAnnoType == null) {
jfranck@1313 483 arrayOfOrigAnnoType = types.makeArrayType(origAnnoType);
jjg@1521 484 }
jfranck@1313 485
jfranck@1629 486 // Only report errors if this isn't the first occurrence I.E. count > 1
jfranck@1629 487 boolean reportError = count > 1;
jfranck@1629 488 Type currentContainerType = getContainingType(currentAnno, ctx.pos.get(currentAnno), reportError);
jfranck@1313 489 if (currentContainerType == null) {
jfranck@1313 490 continue;
jfranck@1313 491 }
jfranck@1313 492 // Assert that the target Container is == for all repeated
jfranck@1313 493 // annos of the same annotation type, the types should
jfranck@1313 494 // come from the same Symbol, i.e. be '=='
jfranck@1313 495 Assert.check(targetContainerType == null || currentContainerType == targetContainerType);
jfranck@1313 496 targetContainerType = currentContainerType;
jfranck@1313 497
jfranck@1313 498 containerValueSymbol = validateContainer(targetContainerType, origAnnoType, ctx.pos.get(currentAnno));
jfranck@1313 499
jfranck@1313 500 if (containerValueSymbol == null) { // Check of CA type failed
jfranck@1313 501 // errors are already reported
jfranck@1313 502 continue;
jfranck@1313 503 }
jfranck@1313 504
jfranck@1313 505 repeated = repeated.prepend(currentAnno);
jfranck@1313 506 }
jfranck@1313 507
jfranck@1313 508 if (!repeated.isEmpty()) {
jfranck@1313 509 repeated = repeated.reverse();
jfranck@1313 510 TreeMaker m = make.at(ctx.pos.get(firstOccurrence));
jfranck@1313 511 Pair<MethodSymbol, Attribute> p =
jfranck@1313 512 new Pair<MethodSymbol, Attribute>(containerValueSymbol,
jfranck@1313 513 new Attribute.Array(arrayOfOrigAnnoType, repeated));
jjg@1521 514 if (ctx.isTypeCompound) {
jjg@1521 515 /* TODO: the following code would be cleaner:
jjg@1521 516 Attribute.TypeCompound at = new Attribute.TypeCompound(targetContainerType, List.of(p),
jjg@1521 517 ((Attribute.TypeCompound)annotations.head).position);
jjg@1521 518 JCTypeAnnotation annoTree = m.TypeAnnotation(at);
jjg@1521 519 at = enterTypeAnnotation(annoTree, targetContainerType, ctx.env);
jjg@1521 520 */
jjg@1521 521 // However, we directly construct the TypeCompound to keep the
jjg@1521 522 // direct relation to the contained TypeCompounds.
jjg@1521 523 Attribute.TypeCompound at = new Attribute.TypeCompound(targetContainerType, List.of(p),
jjg@1521 524 ((Attribute.TypeCompound)annotations.head).position);
jfranck@1445 525
jjg@1521 526 // TODO: annotation applicability checks from below?
jfranck@1445 527
jjg@1521 528 at.setSynthesized(true);
jfranck@1445 529
jjg@1521 530 @SuppressWarnings("unchecked")
jjg@1521 531 T x = (T) at;
jjg@1521 532 return x;
jjg@1521 533 } else {
jjg@1521 534 Attribute.Compound c = new Attribute.Compound(targetContainerType, List.of(p));
jjg@1521 535 JCAnnotation annoTree = m.Annotation(c);
jjg@1521 536
jjg@1521 537 if (!chk.annotationApplicable(annoTree, on))
jjg@1521 538 log.error(annoTree.pos(), "invalid.repeatable.annotation.incompatible.target", targetContainerType, origAnnoType);
jjg@1521 539
jjg@1521 540 if (!chk.validateAnnotationDeferErrors(annoTree))
jjg@1521 541 log.error(annoTree.pos(), "duplicate.annotation.invalid.repeated", origAnnoType);
jjg@1521 542
jjg@1521 543 c = enterAnnotation(annoTree, targetContainerType, ctx.env);
jjg@1521 544 c.setSynthesized(true);
jjg@1521 545
jjg@1521 546 @SuppressWarnings("unchecked")
jjg@1521 547 T x = (T) c;
jjg@1521 548 return x;
jjg@1521 549 }
jfranck@1313 550 } else {
jfranck@1313 551 return null; // errors should have been reported elsewhere
jfranck@1313 552 }
jfranck@1313 553 }
jfranck@1313 554
jfranck@1313 555 /** Fetches the actual Type that should be the containing annotation. */
jfranck@1313 556 private Type getContainingType(Attribute.Compound currentAnno,
jfranck@1629 557 DiagnosticPosition pos,
jfranck@1629 558 boolean reportError)
jfranck@1313 559 {
jfranck@1313 560 Type origAnnoType = currentAnno.type;
jfranck@1313 561 TypeSymbol origAnnoDecl = origAnnoType.tsym;
jfranck@1313 562
jjg@1492 563 // Fetch the Repeatable annotation from the current
jfranck@1313 564 // annotation's declaration, or null if it has none
jjg@1492 565 Attribute.Compound ca = origAnnoDecl.attribute(syms.repeatableType.tsym);
jjg@1492 566 if (ca == null) { // has no Repeatable annotation
jfranck@1629 567 if (reportError)
jfranck@1629 568 log.error(pos, "duplicate.annotation.missing.container", origAnnoType, syms.repeatableType);
jfranck@1313 569 return null;
jfranck@1313 570 }
jfranck@1313 571
jfranck@1313 572 return filterSame(extractContainingType(ca, pos, origAnnoDecl),
jfranck@1313 573 origAnnoType);
jfranck@1313 574 }
jfranck@1313 575
jfranck@1313 576 // returns null if t is same as 's', returns 't' otherwise
jfranck@1313 577 private Type filterSame(Type t, Type s) {
jfranck@1313 578 if (t == null || s == null) {
jfranck@1313 579 return t;
jfranck@1313 580 }
jfranck@1313 581
jfranck@1313 582 return types.isSameType(t, s) ? null : t;
jfranck@1313 583 }
jfranck@1313 584
jfranck@1313 585 /** Extract the actual Type to be used for a containing annotation. */
jfranck@1313 586 private Type extractContainingType(Attribute.Compound ca,
jfranck@1313 587 DiagnosticPosition pos,
jfranck@1313 588 TypeSymbol annoDecl)
jfranck@1313 589 {
jjg@1492 590 // The next three checks check that the Repeatable annotation
jfranck@1313 591 // on the declaration of the annotation type that is repeating is
jfranck@1313 592 // valid.
jfranck@1313 593
jjg@1492 594 // Repeatable must have at least one element
jfranck@1313 595 if (ca.values.isEmpty()) {
jjg@1492 596 log.error(pos, "invalid.repeatable.annotation", annoDecl);
jfranck@1313 597 return null;
jfranck@1313 598 }
jfranck@1313 599 Pair<MethodSymbol,Attribute> p = ca.values.head;
jfranck@1313 600 Name name = p.fst.name;
jfranck@1313 601 if (name != names.value) { // should contain only one element, named "value"
jjg@1492 602 log.error(pos, "invalid.repeatable.annotation", annoDecl);
jfranck@1313 603 return null;
jfranck@1313 604 }
jfranck@1313 605 if (!(p.snd instanceof Attribute.Class)) { // check that the value of "value" is an Attribute.Class
jjg@1492 606 log.error(pos, "invalid.repeatable.annotation", annoDecl);
jfranck@1313 607 return null;
jfranck@1313 608 }
jfranck@1313 609
jfranck@1313 610 return ((Attribute.Class)p.snd).getValue();
jfranck@1313 611 }
jfranck@1313 612
jfranck@1313 613 /* Validate that the suggested targetContainerType Type is a valid
jfranck@1313 614 * container type for repeated instances of originalAnnoType
jfranck@1313 615 * annotations. Return null and report errors if this is not the
jfranck@1313 616 * case, return the MethodSymbol of the value element in
jfranck@1313 617 * targetContainerType if it is suitable (this is needed to
jfranck@1313 618 * synthesize the container). */
jfranck@1313 619 private MethodSymbol validateContainer(Type targetContainerType,
jfranck@1313 620 Type originalAnnoType,
jfranck@1313 621 DiagnosticPosition pos) {
jfranck@1313 622 MethodSymbol containerValueSymbol = null;
jfranck@1313 623 boolean fatalError = false;
jfranck@1313 624
jfranck@1313 625 // Validate that there is a (and only 1) value method
jfranck@1313 626 Scope scope = targetContainerType.tsym.members();
jfranck@1313 627 int nr_value_elems = 0;
jfranck@1313 628 boolean error = false;
jfranck@1313 629 for(Symbol elm : scope.getElementsByName(names.value)) {
jfranck@1313 630 nr_value_elems++;
jfranck@1313 631
jfranck@1313 632 if (nr_value_elems == 1 &&
jfranck@1313 633 elm.kind == Kinds.MTH) {
jfranck@1313 634 containerValueSymbol = (MethodSymbol)elm;
jfranck@1313 635 } else {
jfranck@1313 636 error = true;
jfranck@1313 637 }
jfranck@1313 638 }
jfranck@1313 639 if (error) {
jfranck@1313 640 log.error(pos,
jjg@1492 641 "invalid.repeatable.annotation.multiple.values",
jfranck@1313 642 targetContainerType,
jfranck@1313 643 nr_value_elems);
jfranck@1313 644 return null;
jfranck@1313 645 } else if (nr_value_elems == 0) {
jfranck@1313 646 log.error(pos,
jjg@1492 647 "invalid.repeatable.annotation.no.value",
jfranck@1313 648 targetContainerType);
jfranck@1313 649 return null;
jfranck@1313 650 }
jfranck@1313 651
jfranck@1313 652 // validate that the 'value' element is a method
jfranck@1313 653 // probably "impossible" to fail this
jfranck@1313 654 if (containerValueSymbol.kind != Kinds.MTH) {
jfranck@1313 655 log.error(pos,
jjg@1492 656 "invalid.repeatable.annotation.invalid.value",
jfranck@1313 657 targetContainerType);
jfranck@1313 658 fatalError = true;
jfranck@1313 659 }
jfranck@1313 660
jfranck@1313 661 // validate that the 'value' element has the correct return type
jfranck@1313 662 // i.e. array of original anno
jfranck@1313 663 Type valueRetType = containerValueSymbol.type.getReturnType();
jfranck@1313 664 Type expectedType = types.makeArrayType(originalAnnoType);
jfranck@1313 665 if (!(types.isArray(valueRetType) &&
jfranck@1313 666 types.isSameType(expectedType, valueRetType))) {
jfranck@1313 667 log.error(pos,
jjg@1492 668 "invalid.repeatable.annotation.value.return",
jfranck@1313 669 targetContainerType,
jfranck@1313 670 valueRetType,
jfranck@1313 671 expectedType);
jfranck@1313 672 fatalError = true;
jfranck@1313 673 }
jfranck@1313 674 if (error) {
jfranck@1313 675 fatalError = true;
jfranck@1313 676 }
jfranck@1313 677
jjg@1492 678 // The conditions for a valid containing annotation are made
jfranck@1313 679 // in Check.validateRepeatedAnnotaton();
jfranck@1313 680
jfranck@1313 681 return fatalError ? null : containerValueSymbol;
jfranck@1313 682 }
jfranck@1313 683 }

mercurial