Tue, 28 May 2013 12:46:10 +0100
6970173: Debug pointer at bad position
Reviewed-by: mcimadamore
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 return enterAnnotation(a, expected, env, false);
220 }
222 Attribute.TypeCompound enterTypeAnnotation(JCAnnotation a,
223 Type expected,
224 Env<AttrContext> env) {
225 return (Attribute.TypeCompound) enterAnnotation(a, expected, env, true);
226 }
228 // boolean typeAnnotation determines whether the method returns
229 // a Compound (false) or TypeCompound (true).
230 Attribute.Compound enterAnnotation(JCAnnotation a,
231 Type expected,
232 Env<AttrContext> env,
233 boolean typeAnnotation) {
234 // The annotation might have had its type attributed (but not checked)
235 // by attr.attribAnnotationTypes during MemberEnter, in which case we do not
236 // need to do it again.
237 Type at = (a.annotationType.type != null ? a.annotationType.type
238 : attr.attribType(a.annotationType, env));
239 a.type = chk.checkType(a.annotationType.pos(), at, expected);
240 if (a.type.isErroneous()) {
241 if (typeAnnotation) {
242 return new Attribute.TypeCompound(a.type, List.<Pair<MethodSymbol,Attribute>>nil(), null);
243 } else {
244 return new Attribute.Compound(a.type, List.<Pair<MethodSymbol,Attribute>>nil());
245 }
246 }
247 if ((a.type.tsym.flags() & Flags.ANNOTATION) == 0) {
248 log.error(a.annotationType.pos(),
249 "not.annotation.type", a.type.toString());
250 if (typeAnnotation) {
251 return new Attribute.TypeCompound(a.type, List.<Pair<MethodSymbol,Attribute>>nil(), null);
252 } else {
253 return new Attribute.Compound(a.type, List.<Pair<MethodSymbol,Attribute>>nil());
254 }
255 }
256 List<JCExpression> args = a.args;
257 if (args.length() == 1 && !args.head.hasTag(ASSIGN)) {
258 // special case: elided "value=" assumed
259 args.head = make.at(args.head.pos).
260 Assign(make.Ident(names.value), args.head);
261 }
262 ListBuffer<Pair<MethodSymbol,Attribute>> buf =
263 new ListBuffer<Pair<MethodSymbol,Attribute>>();
264 for (List<JCExpression> tl = args; tl.nonEmpty(); tl = tl.tail) {
265 JCExpression t = tl.head;
266 if (!t.hasTag(ASSIGN)) {
267 log.error(t.pos(), "annotation.value.must.be.name.value");
268 continue;
269 }
270 JCAssign assign = (JCAssign)t;
271 if (!assign.lhs.hasTag(IDENT)) {
272 log.error(t.pos(), "annotation.value.must.be.name.value");
273 continue;
274 }
275 JCIdent left = (JCIdent)assign.lhs;
276 Symbol method = rs.resolveQualifiedMethod(left.pos(),
277 env,
278 a.type,
279 left.name,
280 List.<Type>nil(),
281 null);
282 left.sym = method;
283 left.type = method.type;
284 if (method.owner != a.type.tsym)
285 log.error(left.pos(), "no.annotation.member", left.name, a.type);
286 Type result = method.type.getReturnType();
287 Attribute value = enterAttributeValue(result, assign.rhs, env);
288 if (!method.type.isErroneous())
289 buf.append(new Pair<MethodSymbol,Attribute>
290 ((MethodSymbol)method, value));
291 t.type = result;
292 }
293 if (typeAnnotation) {
294 if (a.attribute == null || !(a.attribute instanceof Attribute.TypeCompound)) {
295 // Create a new TypeCompound
296 Attribute.TypeCompound tc = new Attribute.TypeCompound(a.type, buf.toList(), new TypeAnnotationPosition());
297 a.attribute = tc;
298 return tc;
299 } else {
300 // Use an existing TypeCompound
301 return a.attribute;
302 }
303 } else {
304 Attribute.Compound ac = new Attribute.Compound(a.type, buf.toList());
305 a.attribute = ac;
306 return ac;
307 }
308 }
310 Attribute enterAttributeValue(Type expected,
311 JCExpression tree,
312 Env<AttrContext> env) {
313 //first, try completing the attribution value sym - if a completion
314 //error is thrown, we should recover gracefully, and display an
315 //ordinary resolution diagnostic.
316 try {
317 expected.tsym.complete();
318 } catch(CompletionFailure e) {
319 log.error(tree.pos(), "cant.resolve", Kinds.kindName(e.sym), e.sym);
320 return new Attribute.Error(expected);
321 }
322 if (expected.isPrimitive() || types.isSameType(expected, syms.stringType)) {
323 Type result = attr.attribExpr(tree, env, expected);
324 if (result.isErroneous())
325 return new Attribute.Error(expected);
326 if (result.constValue() == null) {
327 log.error(tree.pos(), "attribute.value.must.be.constant");
328 return new Attribute.Error(expected);
329 }
330 result = cfolder.coerce(result, expected);
331 return new Attribute.Constant(expected, result.constValue());
332 }
333 if (expected.tsym == syms.classType.tsym) {
334 Type result = attr.attribExpr(tree, env, expected);
335 if (result.isErroneous())
336 return new Attribute.Error(expected);
337 if (TreeInfo.name(tree) != names._class) {
338 log.error(tree.pos(), "annotation.value.must.be.class.literal");
339 return new Attribute.Error(expected);
340 }
341 return new Attribute.Class(types,
342 (((JCFieldAccess) tree).selected).type);
343 }
344 if ((expected.tsym.flags() & Flags.ANNOTATION) != 0) {
345 if (!tree.hasTag(ANNOTATION)) {
346 log.error(tree.pos(), "annotation.value.must.be.annotation");
347 expected = syms.errorType;
348 }
349 return enterAnnotation((JCAnnotation)tree, expected, env);
350 }
351 if (expected.hasTag(ARRAY)) { // should really be isArray()
352 if (!tree.hasTag(NEWARRAY)) {
353 tree = make.at(tree.pos).
354 NewArray(null, List.<JCExpression>nil(), List.of(tree));
355 }
356 JCNewArray na = (JCNewArray)tree;
357 if (na.elemtype != null) {
358 log.error(na.elemtype.pos(), "new.not.allowed.in.annotation");
359 return new Attribute.Error(expected);
360 }
361 ListBuffer<Attribute> buf = new ListBuffer<Attribute>();
362 for (List<JCExpression> l = na.elems; l.nonEmpty(); l=l.tail) {
363 buf.append(enterAttributeValue(types.elemtype(expected),
364 l.head,
365 env));
366 }
367 na.type = expected;
368 return new Attribute.
369 Array(expected, buf.toArray(new Attribute[buf.length()]));
370 }
371 if (expected.hasTag(CLASS) &&
372 (expected.tsym.flags() & Flags.ENUM) != 0) {
373 attr.attribExpr(tree, env, expected);
374 Symbol sym = TreeInfo.symbol(tree);
375 if (sym == null ||
376 TreeInfo.nonstaticSelect(tree) ||
377 sym.kind != Kinds.VAR ||
378 (sym.flags() & Flags.ENUM) == 0) {
379 log.error(tree.pos(), "enum.annotation.must.be.enum.constant");
380 return new Attribute.Error(expected);
381 }
382 VarSymbol enumerator = (VarSymbol) sym;
383 return new Attribute.Enum(expected, enumerator);
384 }
385 if (!expected.isErroneous())
386 log.error(tree.pos(), "annotation.value.not.allowable.type");
387 return new Attribute.Error(attr.attribExpr(tree, env, expected));
388 }
390 /* *********************************
391 * Support for repeating annotations
392 ***********************************/
394 /* Process repeated annotations. This method returns the
395 * synthesized container annotation or null IFF all repeating
396 * annotation are invalid. This method reports errors/warnings.
397 */
398 private <T extends Attribute.Compound> T processRepeatedAnnotations(List<T> annotations,
399 AnnotateRepeatedContext<T> ctx,
400 Symbol on) {
401 T firstOccurrence = annotations.head;
402 List<Attribute> repeated = List.nil();
403 Type origAnnoType = null;
404 Type arrayOfOrigAnnoType = null;
405 Type targetContainerType = null;
406 MethodSymbol containerValueSymbol = null;
408 Assert.check(!annotations.isEmpty() &&
409 !annotations.tail.isEmpty()); // i.e. size() > 1
411 int count = 0;
412 for (List<T> al = annotations;
413 !al.isEmpty();
414 al = al.tail)
415 {
416 count++;
418 // There must be more than a single anno in the annotation list
419 Assert.check(count > 1 || !al.tail.isEmpty());
421 T currentAnno = al.head;
423 origAnnoType = currentAnno.type;
424 if (arrayOfOrigAnnoType == null) {
425 arrayOfOrigAnnoType = types.makeArrayType(origAnnoType);
426 }
428 // Only report errors if this isn't the first occurrence I.E. count > 1
429 boolean reportError = count > 1;
430 Type currentContainerType = getContainingType(currentAnno, ctx.pos.get(currentAnno), reportError);
431 if (currentContainerType == null) {
432 continue;
433 }
434 // Assert that the target Container is == for all repeated
435 // annos of the same annotation type, the types should
436 // come from the same Symbol, i.e. be '=='
437 Assert.check(targetContainerType == null || currentContainerType == targetContainerType);
438 targetContainerType = currentContainerType;
440 containerValueSymbol = validateContainer(targetContainerType, origAnnoType, ctx.pos.get(currentAnno));
442 if (containerValueSymbol == null) { // Check of CA type failed
443 // errors are already reported
444 continue;
445 }
447 repeated = repeated.prepend(currentAnno);
448 }
450 if (!repeated.isEmpty()) {
451 repeated = repeated.reverse();
452 TreeMaker m = make.at(ctx.pos.get(firstOccurrence));
453 Pair<MethodSymbol, Attribute> p =
454 new Pair<MethodSymbol, Attribute>(containerValueSymbol,
455 new Attribute.Array(arrayOfOrigAnnoType, repeated));
456 if (ctx.isTypeCompound) {
457 /* TODO: the following code would be cleaner:
458 Attribute.TypeCompound at = new Attribute.TypeCompound(targetContainerType, List.of(p),
459 ((Attribute.TypeCompound)annotations.head).position);
460 JCTypeAnnotation annoTree = m.TypeAnnotation(at);
461 at = enterTypeAnnotation(annoTree, targetContainerType, ctx.env);
462 */
463 // However, we directly construct the TypeCompound to keep the
464 // direct relation to the contained TypeCompounds.
465 Attribute.TypeCompound at = new Attribute.TypeCompound(targetContainerType, List.of(p),
466 ((Attribute.TypeCompound)annotations.head).position);
468 // TODO: annotation applicability checks from below?
470 at.setSynthesized(true);
472 @SuppressWarnings("unchecked")
473 T x = (T) at;
474 return x;
475 } else {
476 Attribute.Compound c = new Attribute.Compound(targetContainerType, List.of(p));
477 JCAnnotation annoTree = m.Annotation(c);
479 if (!chk.annotationApplicable(annoTree, on))
480 log.error(annoTree.pos(), "invalid.repeatable.annotation.incompatible.target", targetContainerType, origAnnoType);
482 if (!chk.validateAnnotationDeferErrors(annoTree))
483 log.error(annoTree.pos(), "duplicate.annotation.invalid.repeated", origAnnoType);
485 c = enterAnnotation(annoTree, targetContainerType, ctx.env);
486 c.setSynthesized(true);
488 @SuppressWarnings("unchecked")
489 T x = (T) c;
490 return x;
491 }
492 } else {
493 return null; // errors should have been reported elsewhere
494 }
495 }
497 /** Fetches the actual Type that should be the containing annotation. */
498 private Type getContainingType(Attribute.Compound currentAnno,
499 DiagnosticPosition pos,
500 boolean reportError)
501 {
502 Type origAnnoType = currentAnno.type;
503 TypeSymbol origAnnoDecl = origAnnoType.tsym;
505 // Fetch the Repeatable annotation from the current
506 // annotation's declaration, or null if it has none
507 Attribute.Compound ca = origAnnoDecl.attribute(syms.repeatableType.tsym);
508 if (ca == null) { // has no Repeatable annotation
509 if (reportError)
510 log.error(pos, "duplicate.annotation.missing.container", origAnnoType, syms.repeatableType);
511 return null;
512 }
514 return filterSame(extractContainingType(ca, pos, origAnnoDecl),
515 origAnnoType);
516 }
518 // returns null if t is same as 's', returns 't' otherwise
519 private Type filterSame(Type t, Type s) {
520 if (t == null || s == null) {
521 return t;
522 }
524 return types.isSameType(t, s) ? null : t;
525 }
527 /** Extract the actual Type to be used for a containing annotation. */
528 private Type extractContainingType(Attribute.Compound ca,
529 DiagnosticPosition pos,
530 TypeSymbol annoDecl)
531 {
532 // The next three checks check that the Repeatable annotation
533 // on the declaration of the annotation type that is repeating is
534 // valid.
536 // Repeatable must have at least one element
537 if (ca.values.isEmpty()) {
538 log.error(pos, "invalid.repeatable.annotation", annoDecl);
539 return null;
540 }
541 Pair<MethodSymbol,Attribute> p = ca.values.head;
542 Name name = p.fst.name;
543 if (name != names.value) { // should contain only one element, named "value"
544 log.error(pos, "invalid.repeatable.annotation", annoDecl);
545 return null;
546 }
547 if (!(p.snd instanceof Attribute.Class)) { // check that the value of "value" is an Attribute.Class
548 log.error(pos, "invalid.repeatable.annotation", annoDecl);
549 return null;
550 }
552 return ((Attribute.Class)p.snd).getValue();
553 }
555 /* Validate that the suggested targetContainerType Type is a valid
556 * container type for repeated instances of originalAnnoType
557 * annotations. Return null and report errors if this is not the
558 * case, return the MethodSymbol of the value element in
559 * targetContainerType if it is suitable (this is needed to
560 * synthesize the container). */
561 private MethodSymbol validateContainer(Type targetContainerType,
562 Type originalAnnoType,
563 DiagnosticPosition pos) {
564 MethodSymbol containerValueSymbol = null;
565 boolean fatalError = false;
567 // Validate that there is a (and only 1) value method
568 Scope scope = targetContainerType.tsym.members();
569 int nr_value_elems = 0;
570 boolean error = false;
571 for(Symbol elm : scope.getElementsByName(names.value)) {
572 nr_value_elems++;
574 if (nr_value_elems == 1 &&
575 elm.kind == Kinds.MTH) {
576 containerValueSymbol = (MethodSymbol)elm;
577 } else {
578 error = true;
579 }
580 }
581 if (error) {
582 log.error(pos,
583 "invalid.repeatable.annotation.multiple.values",
584 targetContainerType,
585 nr_value_elems);
586 return null;
587 } else if (nr_value_elems == 0) {
588 log.error(pos,
589 "invalid.repeatable.annotation.no.value",
590 targetContainerType);
591 return null;
592 }
594 // validate that the 'value' element is a method
595 // probably "impossible" to fail this
596 if (containerValueSymbol.kind != Kinds.MTH) {
597 log.error(pos,
598 "invalid.repeatable.annotation.invalid.value",
599 targetContainerType);
600 fatalError = true;
601 }
603 // validate that the 'value' element has the correct return type
604 // i.e. array of original anno
605 Type valueRetType = containerValueSymbol.type.getReturnType();
606 Type expectedType = types.makeArrayType(originalAnnoType);
607 if (!(types.isArray(valueRetType) &&
608 types.isSameType(expectedType, valueRetType))) {
609 log.error(pos,
610 "invalid.repeatable.annotation.value.return",
611 targetContainerType,
612 valueRetType,
613 expectedType);
614 fatalError = true;
615 }
616 if (error) {
617 fatalError = true;
618 }
620 // The conditions for a valid containing annotation are made
621 // in Check.validateRepeatedAnnotaton();
623 return fatalError ? null : containerValueSymbol;
624 }
625 }