View Javadoc
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   */
25  
26  package com.sun.tools.javac.code;
27  
28  import java.util.LinkedHashMap;
29  import java.util.Map;
30  import javax.lang.model.element.AnnotationMirror;
31  import javax.lang.model.element.AnnotationValue;
32  import javax.lang.model.element.AnnotationValueVisitor;
33  import javax.lang.model.type.DeclaredType;
34  import com.sun.tools.javac.code.Symbol.*;
35  import com.sun.tools.javac.util.*;
36  
37  /** An annotation value.
38   *
39   *  <p><b>This is NOT part of any supported API.
40   *  If you write code that depends on this, you do so at your own risk.
41   *  This code and its internal interfaces are subject to change or
42   *  deletion without notice.</b>
43   */
44  public abstract class Attribute implements AnnotationValue {
45  
46      /** The type of the annotation element. */
47      public Type type;
48  
49      public Attribute(Type type) {
50          this.type = type;
51      }
52  
53      public abstract void accept(Visitor v);
54  
55      public Object getValue() {
56          throw new UnsupportedOperationException();
57      }
58  
59      public <R, P> R accept(AnnotationValueVisitor<R, P> v, P p) {
60          throw new UnsupportedOperationException();
61      }
62  
63      public boolean isSynthesized() {
64          return false;
65      }
66  
67      public TypeAnnotationPosition getPosition() { return null; };
68  
69      /** The value for an annotation element of primitive type or String. */
70      public static class Constant extends Attribute {
71          public final Object value;
72          public void accept(Visitor v) { v.visitConstant(this); }
73          public Constant(Type type, Object value) {
74              super(type);
75              this.value = value;
76          }
77          public String toString() {
78              return Constants.format(value, type);
79          }
80          public Object getValue() {
81              return Constants.decode(value, type);
82          }
83          public <R, P> R accept(AnnotationValueVisitor<R, P> v, P p) {
84              if (value instanceof String)
85                  return v.visitString((String) value, p);
86              if (value instanceof Integer) {
87                  int i = (Integer) value;
88                  switch (type.getTag()) {
89                  case BOOLEAN:   return v.visitBoolean(i != 0, p);
90                  case CHAR:      return v.visitChar((char) i, p);
91                  case BYTE:      return v.visitByte((byte) i, p);
92                  case SHORT:     return v.visitShort((short) i, p);
93                  case INT:       return v.visitInt(i, p);
94                  }
95              }
96              switch (type.getTag()) {
97              case LONG:          return v.visitLong((Long) value, p);
98              case FLOAT:         return v.visitFloat((Float) value, p);
99              case DOUBLE:        return v.visitDouble((Double) value, p);
100             }
101             throw new AssertionError("Bad annotation element value: " + value);
102         }
103     }
104 
105     /** The value for an annotation element of type java.lang.Class,
106      *  represented as a ClassSymbol.
107      */
108     public static class Class extends Attribute {
109         public final Type classType;
110         public void accept(Visitor v) { v.visitClass(this); }
111         public Class(Types types, Type type) {
112             super(makeClassType(types, type));
113             this.classType = type;
114         }
115         static Type makeClassType(Types types, Type type) {
116             Type arg = type.isPrimitive()
117                 ? types.boxedClass(type).type
118                 : types.erasure(type);
119             return new Type.ClassType(types.syms.classType.getEnclosingType(),
120                                       List.of(arg),
121                                       types.syms.classType.tsym);
122         }
123         public String toString() {
124             return classType + ".class";
125         }
126         public Type getValue() {
127             return classType;
128         }
129         public <R, P> R accept(AnnotationValueVisitor<R, P> v, P p) {
130             return v.visitType(classType, p);
131         }
132     }
133 
134     /** A compound annotation element value, the type of which is an
135      *  attribute interface.
136      */
137     public static class Compound extends Attribute implements AnnotationMirror {
138         /** The attributes values, as pairs.  Each pair contains a
139          *  reference to the accessing method in the attribute interface
140          *  and the value to be returned when that method is called to
141          *  access this attribute.
142          */
143         public final List<Pair<MethodSymbol,Attribute>> values;
144 
145         private boolean synthesized = false;
146 
147         @Override
148         public boolean isSynthesized() {
149             return synthesized;
150         }
151 
152         public void setSynthesized(boolean synthesized) {
153             this.synthesized = synthesized;
154         }
155 
156         public Compound(Type type,
157                         List<Pair<MethodSymbol,Attribute>> values) {
158             super(type);
159             this.values = values;
160         }
161         public void accept(Visitor v) { v.visitCompound(this); }
162 
163         /**
164          * Returns a string representation of this annotation.
165          * String is of one of the forms:
166          *     @com.example.foo(name1=val1, name2=val2)
167          *     @com.example.foo(val)
168          *     @com.example.foo
169          * Omit parens for marker annotations, and omit "value=" when allowed.
170          */
171         public String toString() {
172             StringBuilder buf = new StringBuilder();
173             buf.append("@");
174             buf.append(type);
175             int len = values.length();
176             if (len > 0) {
177                 buf.append('(');
178                 boolean first = true;
179                 for (Pair<MethodSymbol, Attribute> value : values) {
180                     if (!first) buf.append(", ");
181                     first = false;
182 
183                     Name name = value.fst.name;
184                     if (len > 1 || name != name.table.names.value) {
185                         buf.append(name);
186                         buf.append('=');
187                     }
188                     buf.append(value.snd);
189                 }
190                 buf.append(')');
191             }
192             return buf.toString();
193         }
194 
195         public Attribute member(Name member) {
196             Pair<MethodSymbol,Attribute> res = getElemPair(member);
197             return res == null ? null : res.snd;
198         }
199 
200         private Pair<MethodSymbol, Attribute> getElemPair(Name member) {
201             for (Pair<MethodSymbol,Attribute> pair : values)
202                 if (pair.fst.name == member) return pair;
203             return null;
204         }
205 
206         public Attribute.Compound getValue() {
207             return this;
208         }
209 
210         public <R, P> R accept(AnnotationValueVisitor<R, P> v, P p) {
211             return v.visitAnnotation(this, p);
212         }
213 
214         public DeclaredType getAnnotationType() {
215             return (DeclaredType) type;
216         }
217 
218         @Override
219         public TypeAnnotationPosition getPosition() {
220             if (values.size() != 0) {
221                 Name valueName = values.head.fst.name.table.names.value;
222                 Pair<MethodSymbol, Attribute> res = getElemPair(valueName);
223                     return res == null ? null : res.snd.getPosition();
224             }
225             return null;
226         }
227 
228         public Map<MethodSymbol, Attribute> getElementValues() {
229             Map<MethodSymbol, Attribute> valmap =
230                 new LinkedHashMap<MethodSymbol, Attribute>();
231             for (Pair<MethodSymbol, Attribute> value : values)
232                 valmap.put(value.fst, value.snd);
233             return valmap;
234         }
235     }
236 
237     public static class TypeCompound extends Compound {
238         public TypeAnnotationPosition position;
239 
240         public TypeCompound(Compound compound,
241                 TypeAnnotationPosition position) {
242             this(compound.type, compound.values, position);
243         }
244         public TypeCompound(Type type,
245                 List<Pair<MethodSymbol, Attribute>> values,
246                 TypeAnnotationPosition position) {
247             super(type, values);
248             this.position = position;
249         }
250 
251         @Override
252         public TypeAnnotationPosition getPosition() {
253             if (hasUnknownPosition()) {
254                 position = super.getPosition();
255             }
256             return position;
257         }
258 
259         public boolean hasUnknownPosition() {
260             return position.type == TargetType.UNKNOWN;
261         }
262 
263         public boolean isContainerTypeCompound() {
264             if (isSynthesized() && values.size() == 1)
265                 return getFirstEmbeddedTC() != null;
266             return false;
267         }
268 
269         private TypeCompound getFirstEmbeddedTC() {
270             if (values.size() == 1) {
271                 Pair<MethodSymbol, Attribute> val = values.get(0);
272                 if (val.fst.getSimpleName().contentEquals("value")
273                         && val.snd instanceof Array) {
274                     Array arr = (Array) val.snd;
275                     if (arr.values.length != 0
276                             && arr.values[0] instanceof Attribute.TypeCompound)
277                         return (Attribute.TypeCompound) arr.values[0];
278                 }
279             }
280             return null;
281         }
282 
283         public boolean tryFixPosition() {
284             if (!isContainerTypeCompound())
285                 return false;
286 
287             TypeCompound from = getFirstEmbeddedTC();
288             if (from != null && from.position != null &&
289                     from.position.type != TargetType.UNKNOWN) {
290                 position = from.position;
291                 return true;
292             }
293             return false;
294         }
295     }
296 
297     /** The value for an annotation element of an array type.
298      */
299     public static class Array extends Attribute {
300         public final Attribute[] values;
301         public Array(Type type, Attribute[] values) {
302             super(type);
303             this.values = values;
304         }
305 
306         public Array(Type type, List<Attribute> values) {
307             super(type);
308             this.values = values.toArray(new Attribute[values.size()]);
309         }
310 
311         public void accept(Visitor v) { v.visitArray(this); }
312         public String toString() {
313             StringBuilder buf = new StringBuilder();
314             buf.append('{');
315             boolean first = true;
316             for (Attribute value : values) {
317                 if (!first)
318                     buf.append(", ");
319                 first = false;
320                 buf.append(value);
321             }
322             buf.append('}');
323             return buf.toString();
324         }
325         public List<Attribute> getValue() {
326             return List.from(values);
327         }
328         public <R, P> R accept(AnnotationValueVisitor<R, P> v, P p) {
329             return v.visitArray(getValue(), p);
330         }
331 
332         @Override
333         public TypeAnnotationPosition getPosition() {
334             if (values.length != 0)
335                 return values[0].getPosition();
336             else
337                 return null;
338         }
339     }
340 
341     /** The value for an annotation element of an enum type.
342      */
343     public static class Enum extends Attribute {
344         public VarSymbol value;
345         public Enum(Type type, VarSymbol value) {
346             super(type);
347             this.value = Assert.checkNonNull(value);
348         }
349         public void accept(Visitor v) { v.visitEnum(this); }
350         public String toString() {
351             return value.enclClass() + "." + value;     // qualified name
352         }
353         public VarSymbol getValue() {
354             return value;
355         }
356         public <R, P> R accept(AnnotationValueVisitor<R, P> v, P p) {
357             return v.visitEnumConstant(value, p);
358         }
359     }
360 
361     public static class Error extends Attribute {
362         public Error(Type type) {
363             super(type);
364         }
365         public void accept(Visitor v) { v.visitError(this); }
366         public String toString() {
367             return "<error>";
368         }
369         public String getValue() {
370             return toString();
371         }
372         public <R, P> R accept(AnnotationValueVisitor<R, P> v, P p) {
373             return v.visitString(toString(), p);
374         }
375     }
376 
377     public static class UnresolvedClass extends Error {
378         public Type classType;
379         public UnresolvedClass(Type type, Type classType) {
380             super(type);
381             this.classType = classType;
382         }
383     }
384 
385     /** A visitor type for dynamic dispatch on the kind of attribute value. */
386     public static interface Visitor {
387         void visitConstant(Attribute.Constant value);
388         void visitClass(Attribute.Class clazz);
389         void visitCompound(Attribute.Compound compound);
390         void visitArray(Attribute.Array array);
391         void visitEnum(Attribute.Enum e);
392         void visitError(Attribute.Error e);
393     }
394 
395     /** A mirror of java.lang.annotation.RetentionPolicy. */
396     public static enum RetentionPolicy {
397         SOURCE,
398         CLASS,
399         RUNTIME
400     }
401 }