Wed, 13 Feb 2013 17:04:21 +0000
8006345: Report Synthesized Parameters in java.lang.reflect.Parameter API
8006896: ClassReader doesn't see MethodParameters attr for method of anon inner class
8007098: Output Synthesized Parameters to MethodParameters Attributes
Summary: Correctly report synthesized and mandated parameters
Reviewed-by: mcimadamore, jjg
Contributed-by: eric.mccorkle@oracle.com
1 /*
2 * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
26 package com.sun.tools.javac.comp;
28 import java.util.Map;
30 import com.sun.tools.javac.util.*;
31 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
32 import com.sun.tools.javac.code.*;
33 import com.sun.tools.javac.code.Symbol.*;
34 import com.sun.tools.javac.tree.*;
35 import com.sun.tools.javac.tree.JCTree.*;
37 import static com.sun.tools.javac.code.TypeTag.ARRAY;
38 import static com.sun.tools.javac.code.TypeTag.CLASS;
39 import static com.sun.tools.javac.tree.JCTree.Tag.*;
41 /** Enter annotations on symbols. Annotations accumulate in a queue,
42 * which is processed at the top level of any set of recursive calls
43 * requesting it be processed.
44 *
45 * <p><b>This is NOT part of any supported API.
46 * If you write code that depends on this, you do so at your own risk.
47 * This code and its internal interfaces are subject to change or
48 * deletion without notice.</b>
49 */
50 public class Annotate {
51 protected static final Context.Key<Annotate> annotateKey =
52 new Context.Key<Annotate>();
54 public static Annotate instance(Context context) {
55 Annotate instance = context.get(annotateKey);
56 if (instance == null)
57 instance = new Annotate(context);
58 return instance;
59 }
61 final Attr attr;
62 final TreeMaker make;
63 final Log log;
64 final Symtab syms;
65 final Names names;
66 final Resolve rs;
67 final Types types;
68 final ConstFold cfolder;
69 final Check chk;
71 protected Annotate(Context context) {
72 context.put(annotateKey, this);
73 attr = Attr.instance(context);
74 make = TreeMaker.instance(context);
75 log = Log.instance(context);
76 syms = Symtab.instance(context);
77 names = Names.instance(context);
78 rs = Resolve.instance(context);
79 types = Types.instance(context);
80 cfolder = ConstFold.instance(context);
81 chk = Check.instance(context);
82 }
84 /* ********************************************************************
85 * Queue maintenance
86 *********************************************************************/
88 private int enterCount = 0;
90 ListBuffer<Annotator> q = new ListBuffer<Annotator>();
91 ListBuffer<Annotator> typesQ = new ListBuffer<Annotator>();
92 ListBuffer<Annotator> repeatedQ = new ListBuffer<Annotator>();
93 ListBuffer<Annotator> afterRepeatedQ = new ListBuffer<Annotator>();
95 public void earlier(Annotator a) {
96 q.prepend(a);
97 }
99 public void normal(Annotator a) {
100 q.append(a);
101 }
103 public void typeAnnotation(Annotator a) {
104 typesQ.append(a);
105 }
107 public void repeated(Annotator a) {
108 repeatedQ.append(a);
109 }
111 public void afterRepeated(Annotator a) {
112 afterRepeatedQ.append(a);
113 }
115 /** Called when the Enter phase starts. */
116 public void enterStart() {
117 enterCount++;
118 }
120 /** Called after the Enter phase completes. */
121 public void enterDone() {
122 enterCount--;
123 flush();
124 }
126 public void flush() {
127 if (enterCount != 0) return;
128 enterCount++;
129 try {
130 while (q.nonEmpty()) {
131 q.next().enterAnnotation();
132 }
133 while (typesQ.nonEmpty()) {
134 typesQ.next().enterAnnotation();
135 }
136 while (repeatedQ.nonEmpty()) {
137 repeatedQ.next().enterAnnotation();
138 }
139 while (afterRepeatedQ.nonEmpty()) {
140 afterRepeatedQ.next().enterAnnotation();
141 }
142 } finally {
143 enterCount--;
144 }
145 }
147 /** A client that has annotations to add registers an annotator,
148 * the method it will use to add the annotation. There are no
149 * parameters; any needed data should be captured by the
150 * Annotator.
151 */
152 public interface Annotator {
153 void enterAnnotation();
154 String toString();
155 }
157 /**
158 * This context contains all the information needed to synthesize new
159 * annotations trees by the completer for repeating annotations.
160 */
161 public class AnnotateRepeatedContext<T extends Attribute.Compound> {
162 public final Env<AttrContext> env;
163 public final Map<Symbol.TypeSymbol, ListBuffer<T>> annotated;
164 public final Map<T, JCDiagnostic.DiagnosticPosition> pos;
165 public final Log log;
166 public final boolean isTypeCompound;
168 public AnnotateRepeatedContext(Env<AttrContext> env,
169 Map<Symbol.TypeSymbol, ListBuffer<T>> annotated,
170 Map<T, JCDiagnostic.DiagnosticPosition> pos,
171 Log log,
172 boolean isTypeCompound) {
173 Assert.checkNonNull(env);
174 Assert.checkNonNull(annotated);
175 Assert.checkNonNull(pos);
176 Assert.checkNonNull(log);
178 this.env = env;
179 this.annotated = annotated;
180 this.pos = pos;
181 this.log = log;
182 this.isTypeCompound = isTypeCompound;
183 }
185 /**
186 * Process a list of repeating annotations returning a new
187 * Attribute.Compound that is the attribute for the synthesized tree
188 * for the container.
189 *
190 * @param repeatingAnnotations a List of repeating annotations
191 * @return a new Attribute.Compound that is the container for the repeatingAnnotations
192 */
193 public T processRepeatedAnnotations(List<T> repeatingAnnotations, Symbol sym) {
194 return Annotate.this.processRepeatedAnnotations(repeatingAnnotations, this, sym);
195 }
197 /**
198 * Queue the Annotator a on the repeating annotations queue of the
199 * Annotate instance this context belongs to.
200 *
201 * @param a the Annotator to enqueue for repeating annotation annotating
202 */
203 public void annotateRepeated(Annotator a) {
204 Annotate.this.repeated(a);
205 }
206 }
208 /* ********************************************************************
209 * Compute an attribute from its annotation.
210 *********************************************************************/
212 /** Process a single compound annotation, returning its
213 * Attribute. Used from MemberEnter for attaching the attributes
214 * to the annotated symbol.
215 */
216 Attribute.Compound enterAnnotation(JCAnnotation a,
217 Type expected,
218 Env<AttrContext> env) {
219 // The annotation might have had its type attributed (but not checked)
220 // by attr.attribAnnotationTypes during MemberEnter, in which case we do not
221 // need to do it again.
222 Type at = (a.annotationType.type != null ? a.annotationType.type
223 : attr.attribType(a.annotationType, env));
224 a.type = chk.checkType(a.annotationType.pos(), at, expected);
225 if (a.type.isErroneous())
226 return new Attribute.Compound(a.type, List.<Pair<MethodSymbol,Attribute>>nil());
227 if ((a.type.tsym.flags() & Flags.ANNOTATION) == 0) {
228 log.error(a.annotationType.pos(),
229 "not.annotation.type", a.type.toString());
230 return new Attribute.Compound(a.type, List.<Pair<MethodSymbol,Attribute>>nil());
231 }
232 List<JCExpression> args = a.args;
233 if (args.length() == 1 && !args.head.hasTag(ASSIGN)) {
234 // special case: elided "value=" assumed
235 args.head = make.at(args.head.pos).
236 Assign(make.Ident(names.value), args.head);
237 }
238 ListBuffer<Pair<MethodSymbol,Attribute>> buf =
239 new ListBuffer<Pair<MethodSymbol,Attribute>>();
240 for (List<JCExpression> tl = args; tl.nonEmpty(); tl = tl.tail) {
241 JCExpression t = tl.head;
242 if (!t.hasTag(ASSIGN)) {
243 log.error(t.pos(), "annotation.value.must.be.name.value");
244 continue;
245 }
246 JCAssign assign = (JCAssign)t;
247 if (!assign.lhs.hasTag(IDENT)) {
248 log.error(t.pos(), "annotation.value.must.be.name.value");
249 continue;
250 }
251 JCIdent left = (JCIdent)assign.lhs;
252 Symbol method = rs.resolveQualifiedMethod(left.pos(),
253 env,
254 a.type,
255 left.name,
256 List.<Type>nil(),
257 null);
258 left.sym = method;
259 left.type = method.type;
260 if (method.owner != a.type.tsym)
261 log.error(left.pos(), "no.annotation.member", left.name, a.type);
262 Type result = method.type.getReturnType();
263 Attribute value = enterAttributeValue(result, assign.rhs, env);
264 if (!method.type.isErroneous())
265 buf.append(new Pair<MethodSymbol,Attribute>
266 ((MethodSymbol)method, value));
267 t.type = result;
268 }
269 // TODO: this should be a TypeCompound if "a" is a JCTypeAnnotation.
270 // However, how do we find the correct position?
271 Attribute.Compound ac = new Attribute.Compound(a.type, buf.toList());
272 // TODO: is this something we want? Who would use it?
273 // a.attribute = ac;
274 return ac;
275 }
277 Attribute enterAttributeValue(Type expected,
278 JCExpression tree,
279 Env<AttrContext> env) {
280 //first, try completing the attribution value sym - if a completion
281 //error is thrown, we should recover gracefully, and display an
282 //ordinary resolution diagnostic.
283 try {
284 expected.tsym.complete();
285 } catch(CompletionFailure e) {
286 log.error(tree.pos(), "cant.resolve", Kinds.kindName(e.sym), e.sym);
287 return new Attribute.Error(expected);
288 }
289 if (expected.isPrimitive() || types.isSameType(expected, syms.stringType)) {
290 Type result = attr.attribExpr(tree, env, expected);
291 if (result.isErroneous())
292 return new Attribute.Error(expected);
293 if (result.constValue() == null) {
294 log.error(tree.pos(), "attribute.value.must.be.constant");
295 return new Attribute.Error(expected);
296 }
297 result = cfolder.coerce(result, expected);
298 return new Attribute.Constant(expected, result.constValue());
299 }
300 if (expected.tsym == syms.classType.tsym) {
301 Type result = attr.attribExpr(tree, env, expected);
302 if (result.isErroneous())
303 return new Attribute.Error(expected);
304 if (TreeInfo.name(tree) != names._class) {
305 log.error(tree.pos(), "annotation.value.must.be.class.literal");
306 return new Attribute.Error(expected);
307 }
308 return new Attribute.Class(types,
309 (((JCFieldAccess) tree).selected).type);
310 }
311 if ((expected.tsym.flags() & Flags.ANNOTATION) != 0) {
312 if (!tree.hasTag(ANNOTATION)) {
313 log.error(tree.pos(), "annotation.value.must.be.annotation");
314 expected = syms.errorType;
315 }
316 return enterAnnotation((JCAnnotation)tree, expected, env);
317 }
318 if (expected.hasTag(ARRAY)) { // should really be isArray()
319 if (!tree.hasTag(NEWARRAY)) {
320 tree = make.at(tree.pos).
321 NewArray(null, List.<JCExpression>nil(), List.of(tree));
322 }
323 JCNewArray na = (JCNewArray)tree;
324 if (na.elemtype != null) {
325 log.error(na.elemtype.pos(), "new.not.allowed.in.annotation");
326 return new Attribute.Error(expected);
327 }
328 ListBuffer<Attribute> buf = new ListBuffer<Attribute>();
329 for (List<JCExpression> l = na.elems; l.nonEmpty(); l=l.tail) {
330 buf.append(enterAttributeValue(types.elemtype(expected),
331 l.head,
332 env));
333 }
334 na.type = expected;
335 return new Attribute.
336 Array(expected, buf.toArray(new Attribute[buf.length()]));
337 }
338 if (expected.hasTag(CLASS) &&
339 (expected.tsym.flags() & Flags.ENUM) != 0) {
340 attr.attribExpr(tree, env, expected);
341 Symbol sym = TreeInfo.symbol(tree);
342 if (sym == null ||
343 TreeInfo.nonstaticSelect(tree) ||
344 sym.kind != Kinds.VAR ||
345 (sym.flags() & Flags.ENUM) == 0) {
346 log.error(tree.pos(), "enum.annotation.must.be.enum.constant");
347 return new Attribute.Error(expected);
348 }
349 VarSymbol enumerator = (VarSymbol) sym;
350 return new Attribute.Enum(expected, enumerator);
351 }
352 if (!expected.isErroneous())
353 log.error(tree.pos(), "annotation.value.not.allowable.type");
354 return new Attribute.Error(attr.attribExpr(tree, env, expected));
355 }
357 Attribute.TypeCompound enterTypeAnnotation(JCAnnotation a,
358 Type expected,
359 Env<AttrContext> env) {
360 Attribute.Compound c = enterAnnotation(a, expected, env);
361 Attribute.TypeCompound tc = new Attribute.TypeCompound(c.type, c.values, new TypeAnnotationPosition());
362 a.attribute = tc;
363 return tc;
364 }
366 /* *********************************
367 * Support for repeating annotations
368 ***********************************/
370 /* Process repeated annotations. This method returns the
371 * synthesized container annotation or null IFF all repeating
372 * annotation are invalid. This method reports errors/warnings.
373 */
374 private <T extends Attribute.Compound> T processRepeatedAnnotations(List<T> annotations,
375 AnnotateRepeatedContext<T> ctx,
376 Symbol on) {
377 T firstOccurrence = annotations.head;
378 List<Attribute> repeated = List.nil();
379 Type origAnnoType = null;
380 Type arrayOfOrigAnnoType = null;
381 Type targetContainerType = null;
382 MethodSymbol containerValueSymbol = null;
384 Assert.check(!annotations.isEmpty() &&
385 !annotations.tail.isEmpty()); // i.e. size() > 1
387 for (List<T> al = annotations;
388 !al.isEmpty();
389 al = al.tail)
390 {
391 T currentAnno = al.head;
393 origAnnoType = currentAnno.type;
394 if (arrayOfOrigAnnoType == null) {
395 arrayOfOrigAnnoType = types.makeArrayType(origAnnoType);
396 }
398 Type currentContainerType = getContainingType(currentAnno, ctx.pos.get(currentAnno));
399 if (currentContainerType == null) {
400 continue;
401 }
402 // Assert that the target Container is == for all repeated
403 // annos of the same annotation type, the types should
404 // come from the same Symbol, i.e. be '=='
405 Assert.check(targetContainerType == null || currentContainerType == targetContainerType);
406 targetContainerType = currentContainerType;
408 containerValueSymbol = validateContainer(targetContainerType, origAnnoType, ctx.pos.get(currentAnno));
410 if (containerValueSymbol == null) { // Check of CA type failed
411 // errors are already reported
412 continue;
413 }
415 repeated = repeated.prepend(currentAnno);
416 }
418 if (!repeated.isEmpty()) {
419 repeated = repeated.reverse();
420 TreeMaker m = make.at(ctx.pos.get(firstOccurrence));
421 Pair<MethodSymbol, Attribute> p =
422 new Pair<MethodSymbol, Attribute>(containerValueSymbol,
423 new Attribute.Array(arrayOfOrigAnnoType, repeated));
424 if (ctx.isTypeCompound) {
425 /* TODO: the following code would be cleaner:
426 Attribute.TypeCompound at = new Attribute.TypeCompound(targetContainerType, List.of(p),
427 ((Attribute.TypeCompound)annotations.head).position);
428 JCTypeAnnotation annoTree = m.TypeAnnotation(at);
429 at = enterTypeAnnotation(annoTree, targetContainerType, ctx.env);
430 */
431 // However, we directly construct the TypeCompound to keep the
432 // direct relation to the contained TypeCompounds.
433 Attribute.TypeCompound at = new Attribute.TypeCompound(targetContainerType, List.of(p),
434 ((Attribute.TypeCompound)annotations.head).position);
436 // TODO: annotation applicability checks from below?
438 at.setSynthesized(true);
440 @SuppressWarnings("unchecked")
441 T x = (T) at;
442 return x;
443 } else {
444 Attribute.Compound c = new Attribute.Compound(targetContainerType, List.of(p));
445 JCAnnotation annoTree = m.Annotation(c);
447 if (!chk.annotationApplicable(annoTree, on))
448 log.error(annoTree.pos(), "invalid.repeatable.annotation.incompatible.target", targetContainerType, origAnnoType);
450 if (!chk.validateAnnotationDeferErrors(annoTree))
451 log.error(annoTree.pos(), "duplicate.annotation.invalid.repeated", origAnnoType);
453 c = enterAnnotation(annoTree, targetContainerType, ctx.env);
454 c.setSynthesized(true);
456 @SuppressWarnings("unchecked")
457 T x = (T) c;
458 return x;
459 }
460 } else {
461 return null; // errors should have been reported elsewhere
462 }
463 }
465 /** Fetches the actual Type that should be the containing annotation. */
466 private Type getContainingType(Attribute.Compound currentAnno,
467 DiagnosticPosition pos)
468 {
469 Type origAnnoType = currentAnno.type;
470 TypeSymbol origAnnoDecl = origAnnoType.tsym;
472 // Fetch the Repeatable annotation from the current
473 // annotation's declaration, or null if it has none
474 Attribute.Compound ca = origAnnoDecl.attribute(syms.repeatableType.tsym);
475 if (ca == null) { // has no Repeatable annotation
476 log.error(pos, "duplicate.annotation.missing.container", origAnnoType, syms.repeatableType);
477 return null;
478 }
480 return filterSame(extractContainingType(ca, pos, origAnnoDecl),
481 origAnnoType);
482 }
484 // returns null if t is same as 's', returns 't' otherwise
485 private Type filterSame(Type t, Type s) {
486 if (t == null || s == null) {
487 return t;
488 }
490 return types.isSameType(t, s) ? null : t;
491 }
493 /** Extract the actual Type to be used for a containing annotation. */
494 private Type extractContainingType(Attribute.Compound ca,
495 DiagnosticPosition pos,
496 TypeSymbol annoDecl)
497 {
498 // The next three checks check that the Repeatable annotation
499 // on the declaration of the annotation type that is repeating is
500 // valid.
502 // Repeatable must have at least one element
503 if (ca.values.isEmpty()) {
504 log.error(pos, "invalid.repeatable.annotation", annoDecl);
505 return null;
506 }
507 Pair<MethodSymbol,Attribute> p = ca.values.head;
508 Name name = p.fst.name;
509 if (name != names.value) { // should contain only one element, named "value"
510 log.error(pos, "invalid.repeatable.annotation", annoDecl);
511 return null;
512 }
513 if (!(p.snd instanceof Attribute.Class)) { // check that the value of "value" is an Attribute.Class
514 log.error(pos, "invalid.repeatable.annotation", annoDecl);
515 return null;
516 }
518 return ((Attribute.Class)p.snd).getValue();
519 }
521 /* Validate that the suggested targetContainerType Type is a valid
522 * container type for repeated instances of originalAnnoType
523 * annotations. Return null and report errors if this is not the
524 * case, return the MethodSymbol of the value element in
525 * targetContainerType if it is suitable (this is needed to
526 * synthesize the container). */
527 private MethodSymbol validateContainer(Type targetContainerType,
528 Type originalAnnoType,
529 DiagnosticPosition pos) {
530 MethodSymbol containerValueSymbol = null;
531 boolean fatalError = false;
533 // Validate that there is a (and only 1) value method
534 Scope scope = targetContainerType.tsym.members();
535 int nr_value_elems = 0;
536 boolean error = false;
537 for(Symbol elm : scope.getElementsByName(names.value)) {
538 nr_value_elems++;
540 if (nr_value_elems == 1 &&
541 elm.kind == Kinds.MTH) {
542 containerValueSymbol = (MethodSymbol)elm;
543 } else {
544 error = true;
545 }
546 }
547 if (error) {
548 log.error(pos,
549 "invalid.repeatable.annotation.multiple.values",
550 targetContainerType,
551 nr_value_elems);
552 return null;
553 } else if (nr_value_elems == 0) {
554 log.error(pos,
555 "invalid.repeatable.annotation.no.value",
556 targetContainerType);
557 return null;
558 }
560 // validate that the 'value' element is a method
561 // probably "impossible" to fail this
562 if (containerValueSymbol.kind != Kinds.MTH) {
563 log.error(pos,
564 "invalid.repeatable.annotation.invalid.value",
565 targetContainerType);
566 fatalError = true;
567 }
569 // validate that the 'value' element has the correct return type
570 // i.e. array of original anno
571 Type valueRetType = containerValueSymbol.type.getReturnType();
572 Type expectedType = types.makeArrayType(originalAnnoType);
573 if (!(types.isArray(valueRetType) &&
574 types.isSameType(expectedType, valueRetType))) {
575 log.error(pos,
576 "invalid.repeatable.annotation.value.return",
577 targetContainerType,
578 valueRetType,
579 expectedType);
580 fatalError = true;
581 }
582 if (error) {
583 fatalError = true;
584 }
586 // The conditions for a valid containing annotation are made
587 // in Check.validateRepeatedAnnotaton();
589 return fatalError ? null : containerValueSymbol;
590 }
591 }