Thu, 20 Jun 2013 08:45:43 +0100
8016613: javac should avoid source 8 only analysis when compiling for source 7
Reviewed-by: jjg
Contributed-by: maurizio.cimadamore@oracle.com
1 /*
2 * Copyright (c) 2005, 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 */
25 package com.sun.tools.javac.model;
27 import java.lang.annotation.Annotation;
28 import java.lang.annotation.Inherited;
29 import java.lang.reflect.InvocationTargetException;
30 import java.lang.reflect.Method;
32 import com.sun.tools.javac.code.Attribute;
33 import com.sun.tools.javac.code.Kinds;
34 import com.sun.tools.javac.code.Symbol;
35 import com.sun.tools.javac.code.Symbol.ClassSymbol;
36 import com.sun.tools.javac.code.Symbol.TypeVariableSymbol;
37 import com.sun.tools.javac.code.TargetType;
38 import com.sun.tools.javac.code.Type;
39 import com.sun.tools.javac.code.Type.AnnotatedType;
40 import com.sun.tools.javac.util.ListBuffer;
41 import static com.sun.tools.javac.code.TypeTag.CLASS;
42 import com.sun.tools.javac.util.List;
44 /**
45 * Utility methods for operating on annotated constructs.
46 *
47 * <p><b>This is NOT part of any supported API.
48 * If you write code that depends on this, you do so at your own
49 * risk. This code and its internal interfaces are subject to change
50 * or deletion without notice.</b></p>
51 */
52 public class JavacAnnoConstructs {
54 // <editor-fold defaultstate="collapsed" desc="Symbols">
56 /**
57 * An internal-use utility that creates a runtime view of an
58 * annotation. This is the implementation of
59 * Element.getAnnotation(Class).
60 */
61 public static <A extends Annotation> A getAnnotation(Symbol annotated,
62 Class<A> annoType) {
63 if (!annoType.isAnnotation())
64 throw new IllegalArgumentException("Not an annotation type: "
65 + annoType);
66 Attribute.Compound c;
67 if (annotated.kind == Kinds.TYP &&
68 annotated instanceof ClassSymbol) {
69 c = getAttributeOnClass((ClassSymbol)annotated, annoType);
70 } else if (annotated.kind == Kinds.TYP &&
71 annotated instanceof TypeVariableSymbol) {
72 c = getAttributeOnTypeVariable((TypeVariableSymbol)annotated, annoType);
73 } else {
74 c = getAttribute(annotated, annoType);
75 }
76 return c == null ? null : AnnotationProxyMaker.generateAnnotation(c, annoType);
77 }
79 // Helper to getAnnotation[s]
80 private static <A extends Annotation> Attribute.Compound getAttribute(Symbol annotated,
81 Class<A> annoType) {
82 String name = annoType.getName();
84 for (Attribute.Compound anno : annotated.getRawAttributes()) {
85 if (name.equals(anno.type.tsym.flatName().toString()))
86 return anno;
87 }
89 return null;
90 }
92 // Helper to getAnnotation[s]
93 private static <A extends Annotation> Attribute.Compound
94 getAttributeOnTypeVariable(TypeVariableSymbol annotated, Class<A> annoType) {
95 String name = annoType.getName();
97 // Declaration annotations on type variables are stored in type attributes
98 // on the owner of the TypeVariableSymbol
99 List<Attribute.Compound> res = List.nil();
100 List<Attribute.TypeCompound> candidates = annotated.owner.getRawTypeAttributes();
101 for (Attribute.TypeCompound anno : candidates)
102 if (anno.position.type == TargetType.CLASS_TYPE_PARAMETER ||
103 anno.position.type == TargetType.METHOD_TYPE_PARAMETER)
104 if (name.equals(anno.type.tsym.flatName().toString()))
105 return anno;
107 return null;
108 }
110 // Helper to getAnnotation[s]
111 private static <A extends Annotation> Attribute.Compound getAttributeOnClass(ClassSymbol annotated,
112 Class<A> annoType) {
113 boolean inherited = annoType.isAnnotationPresent(Inherited.class);
114 Attribute.Compound result = null;
115 while (annotated.name != annotated.name.table.names.java_lang_Object) {
116 result = getAttribute(annotated, annoType);
117 if (result != null || !inherited)
118 break;
119 Type sup = annotated.getSuperclass();
120 if (!sup.hasTag(CLASS) || sup.isErroneous())
121 break;
122 annotated = (ClassSymbol) sup.tsym;
123 }
124 return result;
125 }
127 /**
128 * An internal-use utility that creates a runtime view of
129 * annotations. This is the implementation of
130 * Element.getAnnotations(Class).
131 */
132 public static <A extends Annotation> A[] getAnnotations(Symbol annotated,
133 Class<A> annoType) {
134 if (!annoType.isAnnotation())
135 throw new IllegalArgumentException("Not an annotation type: "
136 + annoType);
137 // If annoType does not declare a container this is equivalent to wrapping
138 // getAnnotation(...) in an array.
139 Class <? extends Annotation> containerType = getContainer(annoType);
140 if (containerType == null) {
141 A res = getAnnotation(annotated, annoType);
142 int size;
143 if (res == null) {
144 size = 0;
145 } else {
146 size = 1;
147 }
148 @SuppressWarnings("unchecked") // annoType is the Class for A
149 A[] arr = (A[])java.lang.reflect.Array.newInstance(annoType, size);
150 if (res != null)
151 arr[0] = res;
152 return arr;
153 }
155 // So we have a containing type
156 String name = annoType.getName();
157 String annoTypeName = annoType.getSimpleName();
158 String containerTypeName = containerType.getSimpleName();
159 int directIndex = -1, containerIndex = -1;
160 Attribute.Compound direct = null, container = null;
161 Attribute.Compound[] rawAttributes = annotated.getRawAttributes().toArray(new Attribute.Compound[0]);
163 // Find directly present annotations
164 for (int i = 0; i < rawAttributes.length; i++) {
165 if (annoTypeName.equals(rawAttributes[i].type.tsym.flatName().toString())) {
166 directIndex = i;
167 direct = rawAttributes[i];
168 } else if(containerTypeName != null &&
169 containerTypeName.equals(rawAttributes[i].type.tsym.flatName().toString())) {
170 containerIndex = i;
171 container = rawAttributes[i];
172 }
173 }
175 // Deal with inherited annotations
176 if (annotated.kind == Kinds.TYP &&
177 (annotated instanceof ClassSymbol)) {
178 ClassSymbol s = (ClassSymbol)annotated;
179 if (direct == null && container == null) {
180 direct = getAttributeOnClass(s, annoType);
181 container = getAttributeOnClass(s, containerType);
183 // both are inherited and found, put container last
184 if (direct != null && container != null) {
185 directIndex = 0;
186 containerIndex = 1;
187 } else if (direct != null) {
188 directIndex = 0;
189 } else {
190 containerIndex = 0;
191 }
192 } else if (direct == null) {
193 direct = getAttributeOnClass(s, annoType);
194 if (direct != null)
195 directIndex = containerIndex + 1;
196 } else if (container == null) {
197 container = getAttributeOnClass(s, containerType);
198 if (container != null)
199 containerIndex = directIndex + 1;
200 }
201 }
203 // Pack them in an array
204 Attribute[] contained0 = new Attribute[0];
205 if (container != null)
206 contained0 = unpackAttributes(container);
207 ListBuffer<Attribute.Compound> compounds = ListBuffer.lb();
208 for (Attribute a : contained0)
209 if (a instanceof Attribute.Compound)
210 compounds = compounds.append((Attribute.Compound)a);
211 Attribute.Compound[] contained = compounds.toArray(new Attribute.Compound[0]);
213 int size = (direct == null ? 0 : 1) + contained.length;
214 @SuppressWarnings("unchecked") // annoType is the Class for A
215 A[] arr = (A[])java.lang.reflect.Array.newInstance(annoType, size);
217 // if direct && container, which is first?
218 int insert = -1;
219 int length = arr.length;
220 if (directIndex >= 0 && containerIndex >= 0) {
221 if (directIndex < containerIndex) {
222 arr[0] = AnnotationProxyMaker.generateAnnotation(direct, annoType);
223 insert = 1;
224 } else {
225 arr[arr.length - 1] = AnnotationProxyMaker.generateAnnotation(direct, annoType);
226 insert = 0;
227 length--;
228 }
229 } else if (directIndex >= 0) {
230 arr[0] = AnnotationProxyMaker.generateAnnotation(direct, annoType);
231 return arr;
232 } else {
233 // Only container
234 insert = 0;
235 }
237 for (int i = 0; i + insert < length; i++)
238 arr[insert + i] = AnnotationProxyMaker.generateAnnotation(contained[i], annoType);
240 return arr;
241 }
243 // </editor-fold>
245 // <editor-fold defaultstate="collapsed" desc="Types">
247 /**
248 * An internal-use utility that creates a runtime view of an
249 * annotation. This is the implementation of
250 * TypeMirror.getAnnotation(Class).
251 */
252 public static <A extends Annotation> A getAnnotation(AnnotatedType annotated, Class<A> annoType) {
253 if (!annoType.isAnnotation())
254 throw new IllegalArgumentException("Not an annotation type: "
255 + annoType);
256 Attribute.Compound c = getAttribute(annotated, annoType);
257 return c == null ? null : AnnotationProxyMaker.generateAnnotation(c, annoType);
258 }
260 // Helper to getAnnotation[s]
261 private static <A extends Annotation> Attribute.Compound getAttribute(Type annotated,
262 Class<A> annoType) {
263 String name = annoType.getName();
265 for (Attribute.Compound anno : annotated.getAnnotationMirrors()) {
266 if (name.equals(anno.type.tsym.flatName().toString()))
267 return anno;
268 }
270 return null;
271 }
273 /**
274 * An internal-use utility that creates a runtime view of
275 * annotations. This is the implementation of
276 * TypeMirror.getAnnotationsByType(Class).
277 */
278 public static <A extends Annotation> A[] getAnnotationsByType(AnnotatedType annotated, Class<A> annoType) {
279 if (!annoType.isAnnotation())
280 throw new IllegalArgumentException("Not an annotation type: "
281 + annoType);
282 // If annoType does not declare a container this is equivalent to wrapping
283 // getAnnotation(...) in an array.
284 Class <? extends Annotation> containerType = getContainer(annoType);
285 if (containerType == null) {
286 A res = getAnnotation(annotated, annoType);
287 int size;
288 if (res == null) {
289 size = 0;
290 } else {
291 size = 1;
292 }
293 @SuppressWarnings("unchecked") // annoType is the Class for A
294 A[] arr = (A[])java.lang.reflect.Array.newInstance(annoType, size);
295 if (res != null)
296 arr[0] = res;
297 return arr;
298 }
300 // So we have a containing type
301 String name = annoType.getName();
302 String annoTypeName = annoType.getSimpleName();
303 String containerTypeName = containerType.getSimpleName();
304 int directIndex = -1, containerIndex = -1;
305 Attribute.Compound direct = null, container = null;
306 Attribute.Compound[] rawAttributes = annotated.getAnnotationMirrors().toArray(new Attribute.Compound[0]);
308 // Find directly present annotations
309 for (int i = 0; i < rawAttributes.length; i++) {
310 if (annoTypeName.equals(rawAttributes[i].type.tsym.flatName().toString())) {
311 directIndex = i;
312 direct = rawAttributes[i];
313 } else if(containerTypeName != null &&
314 containerTypeName.equals(rawAttributes[i].type.tsym.flatName().toString())) {
315 containerIndex = i;
316 container = rawAttributes[i];
317 }
318 }
320 // Pack them in an array
321 Attribute[] contained0 = new Attribute[0];
322 if (container != null)
323 contained0 = unpackAttributes(container);
324 ListBuffer<Attribute.Compound> compounds = ListBuffer.lb();
325 for (Attribute a : contained0) {
326 if (a instanceof Attribute.Compound)
327 compounds = compounds.append((Attribute.Compound)a);
328 }
329 Attribute.Compound[] contained = compounds.toArray(new Attribute.Compound[0]);
331 int size = (direct == null ? 0 : 1) + contained.length;
332 @SuppressWarnings("unchecked") // annoType is the Class for A
333 A[] arr = (A[])java.lang.reflect.Array.newInstance(annoType, size);
335 // if direct && container, which is first?
336 int insert = -1;
337 int length = arr.length;
338 if (directIndex >= 0 && containerIndex >= 0) {
339 if (directIndex < containerIndex) {
340 arr[0] = AnnotationProxyMaker.generateAnnotation(direct, annoType);
341 insert = 1;
342 } else {
343 arr[arr.length - 1] = AnnotationProxyMaker.generateAnnotation(direct, annoType);
344 insert = 0;
345 length--;
346 }
347 } else if (directIndex >= 0) {
348 arr[0] = AnnotationProxyMaker.generateAnnotation(direct, annoType);
349 return arr;
350 } else {
351 // Only container
352 insert = 0;
353 }
355 for (int i = 0; i + insert < length; i++)
356 arr[insert + i] = AnnotationProxyMaker.generateAnnotation(contained[i], annoType);
358 return arr;
359 }
361 // </editor-fold>
363 // <editor-fold defaultstate="collapsed" desc="Container support">
365 // Needed to unpack the runtime view of containing annotations
366 private static final Class<? extends Annotation> REPEATABLE_CLASS = initRepeatable();
367 private static final Method VALUE_ELEMENT_METHOD = initValueElementMethod();
369 private static Class<? extends Annotation> initRepeatable() {
370 try {
371 // Repeatable will not be available when bootstrapping on
372 // JDK 7 so use a reflective lookup instead of a class
373 // literal for Repeatable.class.
374 return Class.forName("java.lang.annotation.Repeatable").asSubclass(Annotation.class);
375 } catch (ClassNotFoundException e) {
376 return null;
377 } catch (SecurityException e) {
378 return null;
379 }
380 }
382 private static Method initValueElementMethod() {
383 if (REPEATABLE_CLASS == null)
384 return null;
386 Method m = null;
387 try {
388 m = REPEATABLE_CLASS.getMethod("value");
389 if (m != null)
390 m.setAccessible(true);
391 return m;
392 } catch (NoSuchMethodException e) {
393 return null;
394 }
395 }
397 // Helper to getAnnotations
398 private static Class<? extends Annotation> getContainer(Class<? extends Annotation> annoType) {
399 // Since we can not refer to java.lang.annotation.Repeatable until we are
400 // bootstrapping with java 8 we need to get the Repeatable annotation using
401 // reflective invocations instead of just using its type and element method.
402 if (REPEATABLE_CLASS != null &&
403 VALUE_ELEMENT_METHOD != null) {
404 // Get the Repeatable instance on the annotations declaration
405 Annotation repeatable = (Annotation)annoType.getAnnotation(REPEATABLE_CLASS);
406 if (repeatable != null) {
407 try {
408 // Get the value element, it should be a class
409 // indicating the containing annotation type
410 @SuppressWarnings("unchecked")
411 Class<? extends Annotation> containerType = (Class)VALUE_ELEMENT_METHOD.invoke(repeatable);
412 if (containerType == null)
413 return null;
415 return containerType;
416 } catch (ClassCastException e) {
417 return null;
418 } catch (IllegalAccessException e) {
419 return null;
420 } catch (InvocationTargetException e ) {
421 return null;
422 }
423 }
424 }
425 return null;
426 }
428 // Helper to getAnnotations
429 private static Attribute[] unpackAttributes(Attribute.Compound container) {
430 // We now have an instance of the container,
431 // unpack it returning an instance of the
432 // contained type or null
433 return ((Attribute.Array)container.member(container.type.tsym.name.table.names.value)).values;
434 }
436 // </editor-fold>
437 }