Mon, 17 Dec 2012 07:47:05 -0800
8004832: Add new doclint package
Reviewed-by: mcimadamore
1 /*
2 * Copyright (c) 2003, 2012, 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;
29 import com.sun.tools.javac.util.*;
30 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
31 import com.sun.tools.javac.code.*;
32 import com.sun.tools.javac.code.Symbol.*;
33 import com.sun.tools.javac.tree.*;
34 import com.sun.tools.javac.tree.JCTree.*;
36 import static com.sun.tools.javac.code.TypeTag.ARRAY;
37 import static com.sun.tools.javac.code.TypeTag.CLASS;
38 import static com.sun.tools.javac.tree.JCTree.Tag.*;
40 /** Enter annotations on symbols. Annotations accumulate in a queue,
41 * which is processed at the top level of any set of recursive calls
42 * requesting it be processed.
43 *
44 * <p><b>This is NOT part of any supported API.
45 * If you write code that depends on this, you do so at your own risk.
46 * This code and its internal interfaces are subject to change or
47 * deletion without notice.</b>
48 */
49 public class Annotate {
50 protected static final Context.Key<Annotate> annotateKey =
51 new Context.Key<Annotate>();
53 public static Annotate instance(Context context) {
54 Annotate instance = context.get(annotateKey);
55 if (instance == null)
56 instance = new Annotate(context);
57 return instance;
58 }
60 final Attr attr;
61 final TreeMaker make;
62 final Log log;
63 final Symtab syms;
64 final Names names;
65 final Resolve rs;
66 final Types types;
67 final ConstFold cfolder;
68 final Check chk;
70 protected Annotate(Context context) {
71 context.put(annotateKey, this);
72 attr = Attr.instance(context);
73 make = TreeMaker.instance(context);
74 log = Log.instance(context);
75 syms = Symtab.instance(context);
76 names = Names.instance(context);
77 rs = Resolve.instance(context);
78 types = Types.instance(context);
79 cfolder = ConstFold.instance(context);
80 chk = Check.instance(context);
81 }
83 /* ********************************************************************
84 * Queue maintenance
85 *********************************************************************/
87 private int enterCount = 0;
89 ListBuffer<Annotator> q = new ListBuffer<Annotator>();
90 ListBuffer<Annotator> repeatedQ = new ListBuffer<Annotator>();
92 public void normal(Annotator a) {
93 q.append(a);
94 }
96 public void earlier(Annotator a) {
97 q.prepend(a);
98 }
100 public void repeated(Annotator a) {
101 repeatedQ.append(a);
102 }
104 /** Called when the Enter phase starts. */
105 public void enterStart() {
106 enterCount++;
107 }
109 /** Called after the Enter phase completes. */
110 public void enterDone() {
111 enterCount--;
112 flush();
113 }
115 public void flush() {
116 if (enterCount != 0) return;
117 enterCount++;
118 try {
119 while (q.nonEmpty())
120 q.next().enterAnnotation();
122 while (repeatedQ.nonEmpty()) {
123 repeatedQ.next().enterAnnotation();
124 }
125 } finally {
126 enterCount--;
127 }
128 }
130 /** A client that has annotations to add registers an annotator,
131 * the method it will use to add the annotation. There are no
132 * parameters; any needed data should be captured by the
133 * Annotator.
134 */
135 public interface Annotator {
136 void enterAnnotation();
137 String toString();
138 }
140 /**
141 * This context contains all the information needed to synthesize new
142 * annotations trees by the completer for repeating annotations.
143 */
144 public class AnnotateRepeatedContext {
145 public final Env<AttrContext> env;
146 public final Map<Symbol.TypeSymbol, ListBuffer<Attribute.Compound>> annotated;
147 public final Map<Attribute.Compound, JCDiagnostic.DiagnosticPosition> pos;
148 public final Log log;
150 public AnnotateRepeatedContext(Env<AttrContext> env,
151 Map<Symbol.TypeSymbol, ListBuffer<Attribute.Compound>> annotated,
152 Map<Attribute.Compound, JCDiagnostic.DiagnosticPosition> pos,
153 Log log) {
154 Assert.checkNonNull(env);
155 Assert.checkNonNull(annotated);
156 Assert.checkNonNull(pos);
157 Assert.checkNonNull(log);
159 this.env = env;
160 this.annotated = annotated;
161 this.pos = pos;
162 this.log = log;
163 }
165 /**
166 * Process a list of repeating annotations returning a new
167 * Attribute.Compound that is the attribute for the synthesized tree
168 * for the container.
169 *
170 * @param repeatingAnnotations a List of repeating annotations
171 * @return a new Attribute.Compound that is the container for the repeatingAnnotations
172 */
173 public Attribute.Compound processRepeatedAnnotations(List<Attribute.Compound> repeatingAnnotations, Symbol sym) {
174 return Annotate.this.processRepeatedAnnotations(repeatingAnnotations, this, sym);
175 }
177 /**
178 * Queue the Annotator a on the repeating annotations queue of the
179 * Annotate instance this context belongs to.
180 *
181 * @param a the Annotator to enqueue for repeating annotation annotating
182 */
183 public void annotateRepeated(Annotator a) {
184 Annotate.this.repeated(a);
185 }
186 }
188 /* ********************************************************************
189 * Compute an attribute from its annotation.
190 *********************************************************************/
192 /** Process a single compound annotation, returning its
193 * Attribute. Used from MemberEnter for attaching the attributes
194 * to the annotated symbol.
195 */
196 Attribute.Compound enterAnnotation(JCAnnotation a,
197 Type expected,
198 Env<AttrContext> env) {
199 // The annotation might have had its type attributed (but not checked)
200 // by attr.attribAnnotationTypes during MemberEnter, in which case we do not
201 // need to do it again.
202 Type at = (a.annotationType.type != null ? a.annotationType.type
203 : attr.attribType(a.annotationType, env));
204 a.type = chk.checkType(a.annotationType.pos(), at, expected);
205 if (a.type.isErroneous())
206 return new Attribute.Compound(a.type, List.<Pair<MethodSymbol,Attribute>>nil());
207 if ((a.type.tsym.flags() & Flags.ANNOTATION) == 0) {
208 log.error(a.annotationType.pos(),
209 "not.annotation.type", a.type.toString());
210 return new Attribute.Compound(a.type, List.<Pair<MethodSymbol,Attribute>>nil());
211 }
212 List<JCExpression> args = a.args;
213 if (args.length() == 1 && !args.head.hasTag(ASSIGN)) {
214 // special case: elided "value=" assumed
215 args.head = make.at(args.head.pos).
216 Assign(make.Ident(names.value), args.head);
217 }
218 ListBuffer<Pair<MethodSymbol,Attribute>> buf =
219 new ListBuffer<Pair<MethodSymbol,Attribute>>();
220 for (List<JCExpression> tl = args; tl.nonEmpty(); tl = tl.tail) {
221 JCExpression t = tl.head;
222 if (!t.hasTag(ASSIGN)) {
223 log.error(t.pos(), "annotation.value.must.be.name.value");
224 continue;
225 }
226 JCAssign assign = (JCAssign)t;
227 if (!assign.lhs.hasTag(IDENT)) {
228 log.error(t.pos(), "annotation.value.must.be.name.value");
229 continue;
230 }
231 JCIdent left = (JCIdent)assign.lhs;
232 Symbol method = rs.resolveQualifiedMethod(left.pos(),
233 env,
234 a.type,
235 left.name,
236 List.<Type>nil(),
237 null);
238 left.sym = method;
239 left.type = method.type;
240 if (method.owner != a.type.tsym)
241 log.error(left.pos(), "no.annotation.member", left.name, a.type);
242 Type result = method.type.getReturnType();
243 Attribute value = enterAttributeValue(result, assign.rhs, env);
244 if (!method.type.isErroneous())
245 buf.append(new Pair<MethodSymbol,Attribute>
246 ((MethodSymbol)method, value));
247 t.type = result;
248 }
249 return new Attribute.Compound(a.type, buf.toList());
250 }
252 Attribute enterAttributeValue(Type expected,
253 JCExpression tree,
254 Env<AttrContext> env) {
255 //first, try completing the attribution value sym - if a completion
256 //error is thrown, we should recover gracefully, and display an
257 //ordinary resolution diagnostic.
258 try {
259 expected.tsym.complete();
260 } catch(CompletionFailure e) {
261 log.error(tree.pos(), "cant.resolve", Kinds.kindName(e.sym), e.sym);
262 return new Attribute.Error(expected);
263 }
264 if (expected.isPrimitive() || types.isSameType(expected, syms.stringType)) {
265 Type result = attr.attribExpr(tree, env, expected);
266 if (result.isErroneous())
267 return new Attribute.Error(expected);
268 if (result.constValue() == null) {
269 log.error(tree.pos(), "attribute.value.must.be.constant");
270 return new Attribute.Error(expected);
271 }
272 result = cfolder.coerce(result, expected);
273 return new Attribute.Constant(expected, result.constValue());
274 }
275 if (expected.tsym == syms.classType.tsym) {
276 Type result = attr.attribExpr(tree, env, expected);
277 if (result.isErroneous())
278 return new Attribute.Error(expected);
279 if (TreeInfo.name(tree) != names._class) {
280 log.error(tree.pos(), "annotation.value.must.be.class.literal");
281 return new Attribute.Error(expected);
282 }
283 return new Attribute.Class(types,
284 (((JCFieldAccess) tree).selected).type);
285 }
286 if ((expected.tsym.flags() & Flags.ANNOTATION) != 0) {
287 if (!tree.hasTag(ANNOTATION)) {
288 log.error(tree.pos(), "annotation.value.must.be.annotation");
289 expected = syms.errorType;
290 }
291 return enterAnnotation((JCAnnotation)tree, expected, env);
292 }
293 if (expected.hasTag(ARRAY)) { // should really be isArray()
294 if (!tree.hasTag(NEWARRAY)) {
295 tree = make.at(tree.pos).
296 NewArray(null, List.<JCExpression>nil(), List.of(tree));
297 }
298 JCNewArray na = (JCNewArray)tree;
299 if (na.elemtype != null) {
300 log.error(na.elemtype.pos(), "new.not.allowed.in.annotation");
301 return new Attribute.Error(expected);
302 }
303 ListBuffer<Attribute> buf = new ListBuffer<Attribute>();
304 for (List<JCExpression> l = na.elems; l.nonEmpty(); l=l.tail) {
305 buf.append(enterAttributeValue(types.elemtype(expected),
306 l.head,
307 env));
308 }
309 na.type = expected;
310 return new Attribute.
311 Array(expected, buf.toArray(new Attribute[buf.length()]));
312 }
313 if (expected.hasTag(CLASS) &&
314 (expected.tsym.flags() & Flags.ENUM) != 0) {
315 attr.attribExpr(tree, env, expected);
316 Symbol sym = TreeInfo.symbol(tree);
317 if (sym == null ||
318 TreeInfo.nonstaticSelect(tree) ||
319 sym.kind != Kinds.VAR ||
320 (sym.flags() & Flags.ENUM) == 0) {
321 log.error(tree.pos(), "enum.annotation.must.be.enum.constant");
322 return new Attribute.Error(expected);
323 }
324 VarSymbol enumerator = (VarSymbol) sym;
325 return new Attribute.Enum(expected, enumerator);
326 }
327 if (!expected.isErroneous())
328 log.error(tree.pos(), "annotation.value.not.allowable.type");
329 return new Attribute.Error(attr.attribExpr(tree, env, expected));
330 }
332 /* *********************************
333 * Support for repeating annotations
334 ***********************************/
336 /* Process repeated annotations. This method returns the
337 * synthesized container annotation or null IFF all repeating
338 * annotation are invalid. This method reports errors/warnings.
339 */
340 private Attribute.Compound processRepeatedAnnotations(List<Attribute.Compound> annotations,
341 AnnotateRepeatedContext ctx,
342 Symbol on) {
343 Attribute.Compound firstOccurrence = annotations.head;
344 List<Attribute> repeated = List.nil();
345 Type origAnnoType = null;
346 Type arrayOfOrigAnnoType = null;
347 Type targetContainerType = null;
348 MethodSymbol containerValueSymbol = null;
350 Assert.check(!annotations.isEmpty() &&
351 !annotations.tail.isEmpty()); // i.e. size() > 1
353 for (List<Attribute.Compound> al = annotations;
354 !al.isEmpty();
355 al = al.tail)
356 {
357 Attribute.Compound currentAnno = al.head;
359 origAnnoType = currentAnno.type;
360 if (arrayOfOrigAnnoType == null) {
361 arrayOfOrigAnnoType = types.makeArrayType(origAnnoType);
362 }
364 Type currentContainerType = getContainingType(currentAnno, ctx.pos.get(currentAnno));
365 if (currentContainerType == null) {
366 continue;
367 }
368 // Assert that the target Container is == for all repeated
369 // annos of the same annotation type, the types should
370 // come from the same Symbol, i.e. be '=='
371 Assert.check(targetContainerType == null || currentContainerType == targetContainerType);
372 targetContainerType = currentContainerType;
374 containerValueSymbol = validateContainer(targetContainerType, origAnnoType, ctx.pos.get(currentAnno));
376 if (containerValueSymbol == null) { // Check of CA type failed
377 // errors are already reported
378 continue;
379 }
381 repeated = repeated.prepend(currentAnno);
382 }
384 if (!repeated.isEmpty()) {
385 repeated = repeated.reverse();
386 JCAnnotation annoTree;
387 TreeMaker m = make.at(ctx.pos.get(firstOccurrence));
388 Pair<MethodSymbol, Attribute> p =
389 new Pair<MethodSymbol, Attribute>(containerValueSymbol,
390 new Attribute.Array(arrayOfOrigAnnoType, repeated));
391 annoTree = m.Annotation(new Attribute.Compound(targetContainerType,
392 List.of(p)));
394 if (!chk.annotationApplicable(annoTree, on))
395 log.error(annoTree.pos(), "invalid.containedby.annotation.incompatible.target", targetContainerType, origAnnoType);
397 if (!chk.validateAnnotationDeferErrors(annoTree))
398 log.error(annoTree.pos(), "duplicate.annotation.invalid.repeated", origAnnoType);
400 Attribute.Compound c = enterAnnotation(annoTree,
401 targetContainerType,
402 ctx.env);
403 return c;
404 } else {
405 return null; // errors should have been reported elsewhere
406 }
407 }
409 /** Fetches the actual Type that should be the containing annotation. */
410 private Type getContainingType(Attribute.Compound currentAnno,
411 DiagnosticPosition pos)
412 {
413 Type origAnnoType = currentAnno.type;
414 TypeSymbol origAnnoDecl = origAnnoType.tsym;
416 // Fetch the ContainedBy annotation from the current
417 // annotation's declaration, or null if it has none
418 Attribute.Compound ca = origAnnoDecl.attribute(syms.containedByType.tsym);
419 if (ca == null) { // has no ContainedBy annotation
420 log.error(pos, "duplicate.annotation.missing.container", origAnnoType, syms.containedByType);
421 return null;
422 }
424 return filterSame(extractContainingType(ca, pos, origAnnoDecl),
425 origAnnoType);
426 }
428 // returns null if t is same as 's', returns 't' otherwise
429 private Type filterSame(Type t, Type s) {
430 if (t == null || s == null) {
431 return t;
432 }
434 return types.isSameType(t, s) ? null : t;
435 }
437 /** Extract the actual Type to be used for a containing annotation. */
438 private Type extractContainingType(Attribute.Compound ca,
439 DiagnosticPosition pos,
440 TypeSymbol annoDecl)
441 {
442 // The next three checks check that the ContainedBy annotation
443 // on the declaration of the annotation type that is repeating is
444 // valid.
446 // ContainedBy must have at least one element
447 if (ca.values.isEmpty()) {
448 log.error(pos, "invalid.containedby.annotation", annoDecl);
449 return null;
450 }
451 Pair<MethodSymbol,Attribute> p = ca.values.head;
452 Name name = p.fst.name;
453 if (name != names.value) { // should contain only one element, named "value"
454 log.error(pos, "invalid.containedby.annotation", annoDecl);
455 return null;
456 }
457 if (!(p.snd instanceof Attribute.Class)) { // check that the value of "value" is an Attribute.Class
458 log.error(pos, "invalid.containedby.annotation", annoDecl);
459 return null;
460 }
462 return ((Attribute.Class)p.snd).getValue();
463 }
465 /* Validate that the suggested targetContainerType Type is a valid
466 * container type for repeated instances of originalAnnoType
467 * annotations. Return null and report errors if this is not the
468 * case, return the MethodSymbol of the value element in
469 * targetContainerType if it is suitable (this is needed to
470 * synthesize the container). */
471 private MethodSymbol validateContainer(Type targetContainerType,
472 Type originalAnnoType,
473 DiagnosticPosition pos) {
474 MethodSymbol containerValueSymbol = null;
475 boolean fatalError = false;
477 // Validate that there is a (and only 1) value method
478 Scope scope = targetContainerType.tsym.members();
479 int nr_value_elems = 0;
480 boolean error = false;
481 for(Symbol elm : scope.getElementsByName(names.value)) {
482 nr_value_elems++;
484 if (nr_value_elems == 1 &&
485 elm.kind == Kinds.MTH) {
486 containerValueSymbol = (MethodSymbol)elm;
487 } else {
488 error = true;
489 }
490 }
491 if (error) {
492 log.error(pos,
493 "invalid.containedby.annotation.multiple.values",
494 targetContainerType,
495 nr_value_elems);
496 return null;
497 } else if (nr_value_elems == 0) {
498 log.error(pos,
499 "invalid.containedby.annotation.no.value",
500 targetContainerType);
501 return null;
502 }
504 // validate that the 'value' element is a method
505 // probably "impossible" to fail this
506 if (containerValueSymbol.kind != Kinds.MTH) {
507 log.error(pos,
508 "invalid.containedby.annotation.invalid.value",
509 targetContainerType);
510 fatalError = true;
511 }
513 // validate that the 'value' element has the correct return type
514 // i.e. array of original anno
515 Type valueRetType = containerValueSymbol.type.getReturnType();
516 Type expectedType = types.makeArrayType(originalAnnoType);
517 if (!(types.isArray(valueRetType) &&
518 types.isSameType(expectedType, valueRetType))) {
519 log.error(pos,
520 "invalid.containedby.annotation.value.return",
521 targetContainerType,
522 valueRetType,
523 expectedType);
524 fatalError = true;
525 }
526 if (error) {
527 fatalError = true;
528 }
530 // Explicitly no check for/validity of @ContainerFor. That is
531 // done on declaration of the container, and at reflect time.
533 // The rest of the conditions for a valid containing annotation are made
534 // in Check.validateRepeatedAnnotaton();
536 return fatalError ? null : containerValueSymbol;
537 }
538 }