Thu, 22 Aug 2013 13:12:43 +0100
8023112: javac should not use lazy constant evaluation approach for method references
Reviewed-by: jjg, 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(assign.rhs.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 // Does it look like a class literal?
337 if (TreeInfo.name(tree) == names._class) {
338 Name n = (((JCFieldAccess) tree).selected).type.tsym.flatName();
339 return new Attribute.UnresolvedClass(expected,
340 types.createErrorType(n,
341 syms.unknownSymbol, syms.classType));
342 } else {
343 return new Attribute.Error(expected);
344 }
345 }
347 // Class literals look like field accesses of a field named class
348 // at the tree level
349 if (TreeInfo.name(tree) != names._class) {
350 log.error(tree.pos(), "annotation.value.must.be.class.literal");
351 return new Attribute.Error(expected);
352 }
353 return new Attribute.Class(types,
354 (((JCFieldAccess) tree).selected).type);
355 }
356 if ((expected.tsym.flags() & Flags.ANNOTATION) != 0) {
357 if (!tree.hasTag(ANNOTATION)) {
358 log.error(tree.pos(), "annotation.value.must.be.annotation");
359 expected = syms.errorType;
360 }
361 return enterAnnotation((JCAnnotation)tree, expected, env);
362 }
363 if (expected.hasTag(ARRAY)) { // should really be isArray()
364 if (!tree.hasTag(NEWARRAY)) {
365 tree = make.at(tree.pos).
366 NewArray(null, List.<JCExpression>nil(), List.of(tree));
367 }
368 JCNewArray na = (JCNewArray)tree;
369 if (na.elemtype != null) {
370 log.error(na.elemtype.pos(), "new.not.allowed.in.annotation");
371 return new Attribute.Error(expected);
372 }
373 ListBuffer<Attribute> buf = new ListBuffer<Attribute>();
374 for (List<JCExpression> l = na.elems; l.nonEmpty(); l=l.tail) {
375 buf.append(enterAttributeValue(types.elemtype(expected),
376 l.head,
377 env));
378 }
379 na.type = expected;
380 return new Attribute.
381 Array(expected, buf.toArray(new Attribute[buf.length()]));
382 }
383 if (expected.hasTag(CLASS) &&
384 (expected.tsym.flags() & Flags.ENUM) != 0) {
385 attr.attribExpr(tree, env, expected);
386 Symbol sym = TreeInfo.symbol(tree);
387 if (sym == null ||
388 TreeInfo.nonstaticSelect(tree) ||
389 sym.kind != Kinds.VAR ||
390 (sym.flags() & Flags.ENUM) == 0) {
391 log.error(tree.pos(), "enum.annotation.must.be.enum.constant");
392 return new Attribute.Error(expected);
393 }
394 VarSymbol enumerator = (VarSymbol) sym;
395 return new Attribute.Enum(expected, enumerator);
396 }
397 if (!expected.isErroneous())
398 log.error(tree.pos(), "annotation.value.not.allowable.type");
399 return new Attribute.Error(attr.attribExpr(tree, env, expected));
400 }
402 /* *********************************
403 * Support for repeating annotations
404 ***********************************/
406 /* Process repeated annotations. This method returns the
407 * synthesized container annotation or null IFF all repeating
408 * annotation are invalid. This method reports errors/warnings.
409 */
410 private <T extends Attribute.Compound> T processRepeatedAnnotations(List<T> annotations,
411 AnnotateRepeatedContext<T> ctx,
412 Symbol on) {
413 T firstOccurrence = annotations.head;
414 List<Attribute> repeated = List.nil();
415 Type origAnnoType = null;
416 Type arrayOfOrigAnnoType = null;
417 Type targetContainerType = null;
418 MethodSymbol containerValueSymbol = null;
420 Assert.check(!annotations.isEmpty() &&
421 !annotations.tail.isEmpty()); // i.e. size() > 1
423 int count = 0;
424 for (List<T> al = annotations;
425 !al.isEmpty();
426 al = al.tail)
427 {
428 count++;
430 // There must be more than a single anno in the annotation list
431 Assert.check(count > 1 || !al.tail.isEmpty());
433 T currentAnno = al.head;
435 origAnnoType = currentAnno.type;
436 if (arrayOfOrigAnnoType == null) {
437 arrayOfOrigAnnoType = types.makeArrayType(origAnnoType);
438 }
440 // Only report errors if this isn't the first occurrence I.E. count > 1
441 boolean reportError = count > 1;
442 Type currentContainerType = getContainingType(currentAnno, ctx.pos.get(currentAnno), reportError);
443 if (currentContainerType == null) {
444 continue;
445 }
446 // Assert that the target Container is == for all repeated
447 // annos of the same annotation type, the types should
448 // come from the same Symbol, i.e. be '=='
449 Assert.check(targetContainerType == null || currentContainerType == targetContainerType);
450 targetContainerType = currentContainerType;
452 containerValueSymbol = validateContainer(targetContainerType, origAnnoType, ctx.pos.get(currentAnno));
454 if (containerValueSymbol == null) { // Check of CA type failed
455 // errors are already reported
456 continue;
457 }
459 repeated = repeated.prepend(currentAnno);
460 }
462 if (!repeated.isEmpty()) {
463 repeated = repeated.reverse();
464 TreeMaker m = make.at(ctx.pos.get(firstOccurrence));
465 Pair<MethodSymbol, Attribute> p =
466 new Pair<MethodSymbol, Attribute>(containerValueSymbol,
467 new Attribute.Array(arrayOfOrigAnnoType, repeated));
468 if (ctx.isTypeCompound) {
469 /* TODO: the following code would be cleaner:
470 Attribute.TypeCompound at = new Attribute.TypeCompound(targetContainerType, List.of(p),
471 ((Attribute.TypeCompound)annotations.head).position);
472 JCTypeAnnotation annoTree = m.TypeAnnotation(at);
473 at = enterTypeAnnotation(annoTree, targetContainerType, ctx.env);
474 */
475 // However, we directly construct the TypeCompound to keep the
476 // direct relation to the contained TypeCompounds.
477 Attribute.TypeCompound at = new Attribute.TypeCompound(targetContainerType, List.of(p),
478 ((Attribute.TypeCompound)annotations.head).position);
480 // TODO: annotation applicability checks from below?
482 at.setSynthesized(true);
484 @SuppressWarnings("unchecked")
485 T x = (T) at;
486 return x;
487 } else {
488 Attribute.Compound c = new Attribute.Compound(targetContainerType, List.of(p));
489 JCAnnotation annoTree = m.Annotation(c);
491 if (!chk.annotationApplicable(annoTree, on))
492 log.error(annoTree.pos(), "invalid.repeatable.annotation.incompatible.target", targetContainerType, origAnnoType);
494 if (!chk.validateAnnotationDeferErrors(annoTree))
495 log.error(annoTree.pos(), "duplicate.annotation.invalid.repeated", origAnnoType);
497 c = enterAnnotation(annoTree, targetContainerType, ctx.env);
498 c.setSynthesized(true);
500 @SuppressWarnings("unchecked")
501 T x = (T) c;
502 return x;
503 }
504 } else {
505 return null; // errors should have been reported elsewhere
506 }
507 }
509 /** Fetches the actual Type that should be the containing annotation. */
510 private Type getContainingType(Attribute.Compound currentAnno,
511 DiagnosticPosition pos,
512 boolean reportError)
513 {
514 Type origAnnoType = currentAnno.type;
515 TypeSymbol origAnnoDecl = origAnnoType.tsym;
517 // Fetch the Repeatable annotation from the current
518 // annotation's declaration, or null if it has none
519 Attribute.Compound ca = origAnnoDecl.attribute(syms.repeatableType.tsym);
520 if (ca == null) { // has no Repeatable annotation
521 if (reportError)
522 log.error(pos, "duplicate.annotation.missing.container", origAnnoType, syms.repeatableType);
523 return null;
524 }
526 return filterSame(extractContainingType(ca, pos, origAnnoDecl),
527 origAnnoType);
528 }
530 // returns null if t is same as 's', returns 't' otherwise
531 private Type filterSame(Type t, Type s) {
532 if (t == null || s == null) {
533 return t;
534 }
536 return types.isSameType(t, s) ? null : t;
537 }
539 /** Extract the actual Type to be used for a containing annotation. */
540 private Type extractContainingType(Attribute.Compound ca,
541 DiagnosticPosition pos,
542 TypeSymbol annoDecl)
543 {
544 // The next three checks check that the Repeatable annotation
545 // on the declaration of the annotation type that is repeating is
546 // valid.
548 // Repeatable must have at least one element
549 if (ca.values.isEmpty()) {
550 log.error(pos, "invalid.repeatable.annotation", annoDecl);
551 return null;
552 }
553 Pair<MethodSymbol,Attribute> p = ca.values.head;
554 Name name = p.fst.name;
555 if (name != names.value) { // should contain only one element, named "value"
556 log.error(pos, "invalid.repeatable.annotation", annoDecl);
557 return null;
558 }
559 if (!(p.snd instanceof Attribute.Class)) { // check that the value of "value" is an Attribute.Class
560 log.error(pos, "invalid.repeatable.annotation", annoDecl);
561 return null;
562 }
564 return ((Attribute.Class)p.snd).getValue();
565 }
567 /* Validate that the suggested targetContainerType Type is a valid
568 * container type for repeated instances of originalAnnoType
569 * annotations. Return null and report errors if this is not the
570 * case, return the MethodSymbol of the value element in
571 * targetContainerType if it is suitable (this is needed to
572 * synthesize the container). */
573 private MethodSymbol validateContainer(Type targetContainerType,
574 Type originalAnnoType,
575 DiagnosticPosition pos) {
576 MethodSymbol containerValueSymbol = null;
577 boolean fatalError = false;
579 // Validate that there is a (and only 1) value method
580 Scope scope = targetContainerType.tsym.members();
581 int nr_value_elems = 0;
582 boolean error = false;
583 for(Symbol elm : scope.getElementsByName(names.value)) {
584 nr_value_elems++;
586 if (nr_value_elems == 1 &&
587 elm.kind == Kinds.MTH) {
588 containerValueSymbol = (MethodSymbol)elm;
589 } else {
590 error = true;
591 }
592 }
593 if (error) {
594 log.error(pos,
595 "invalid.repeatable.annotation.multiple.values",
596 targetContainerType,
597 nr_value_elems);
598 return null;
599 } else if (nr_value_elems == 0) {
600 log.error(pos,
601 "invalid.repeatable.annotation.no.value",
602 targetContainerType);
603 return null;
604 }
606 // validate that the 'value' element is a method
607 // probably "impossible" to fail this
608 if (containerValueSymbol.kind != Kinds.MTH) {
609 log.error(pos,
610 "invalid.repeatable.annotation.invalid.value",
611 targetContainerType);
612 fatalError = true;
613 }
615 // validate that the 'value' element has the correct return type
616 // i.e. array of original anno
617 Type valueRetType = containerValueSymbol.type.getReturnType();
618 Type expectedType = types.makeArrayType(originalAnnoType);
619 if (!(types.isArray(valueRetType) &&
620 types.isSameType(expectedType, valueRetType))) {
621 log.error(pos,
622 "invalid.repeatable.annotation.value.return",
623 targetContainerType,
624 valueRetType,
625 expectedType);
626 fatalError = true;
627 }
628 if (error) {
629 fatalError = true;
630 }
632 // The conditions for a valid containing annotation are made
633 // in Check.validateRepeatedAnnotaton();
635 return fatalError ? null : containerValueSymbol;
636 }
637 }