Mon, 18 Mar 2013 18:33:13 -0700
8007803: Implement javax.lang.model API for Type Annotations
Reviewed-by: darcy
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 */
26 package com.sun.tools.javac.model;
28 import java.util.Collections;
29 import java.util.EnumSet;
30 import java.util.LinkedHashSet;
31 import java.util.List;
32 import java.util.Set;
34 import javax.lang.model.element.*;
35 import javax.lang.model.type.*;
37 import com.sun.tools.javac.code.*;
38 import com.sun.tools.javac.code.Symbol.*;
39 import com.sun.tools.javac.util.*;
41 /**
42 * Utility methods for operating on types.
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
46 * risk. This code and its internal interfaces are subject to change
47 * or deletion without notice.</b></p>
48 */
49 public class JavacTypes implements javax.lang.model.util.Types {
51 private Symtab syms;
52 private Types types;
54 public static JavacTypes instance(Context context) {
55 JavacTypes instance = context.get(JavacTypes.class);
56 if (instance == null)
57 instance = new JavacTypes(context);
58 return instance;
59 }
61 /**
62 * Public for use only by JavacProcessingEnvironment
63 */
64 protected JavacTypes(Context context) {
65 setContext(context);
66 }
68 /**
69 * Use a new context. May be called from outside to update
70 * internal state for a new annotation-processing round.
71 */
72 public void setContext(Context context) {
73 context.put(JavacTypes.class, this);
74 syms = Symtab.instance(context);
75 types = Types.instance(context);
76 }
78 public Element asElement(TypeMirror t) {
79 switch (t.getKind()) {
80 case DECLARED:
81 case INTERSECTION:
82 case ERROR:
83 case TYPEVAR:
84 Type type = cast(Type.class, t);
85 return type.asElement();
86 default:
87 return null;
88 }
89 }
91 public boolean isSameType(TypeMirror t1, TypeMirror t2) {
92 return types.isSameType((Type) t1, (Type) t2);
93 }
95 public boolean isSubtype(TypeMirror t1, TypeMirror t2) {
96 validateTypeNotIn(t1, EXEC_OR_PKG);
97 validateTypeNotIn(t2, EXEC_OR_PKG);
98 return types.isSubtype((Type) t1, (Type) t2);
99 }
101 public boolean isAssignable(TypeMirror t1, TypeMirror t2) {
102 validateTypeNotIn(t1, EXEC_OR_PKG);
103 validateTypeNotIn(t2, EXEC_OR_PKG);
104 return types.isAssignable((Type) t1, (Type) t2);
105 }
107 public boolean contains(TypeMirror t1, TypeMirror t2) {
108 validateTypeNotIn(t1, EXEC_OR_PKG);
109 validateTypeNotIn(t2, EXEC_OR_PKG);
110 return types.containsType((Type) t1, (Type) t2);
111 }
113 public boolean isSubsignature(ExecutableType m1, ExecutableType m2) {
114 return types.isSubSignature((Type) m1, (Type) m2);
115 }
117 public List<Type> directSupertypes(TypeMirror t) {
118 validateTypeNotIn(t, EXEC_OR_PKG);
119 Type type = (Type) t;
120 Type sup = types.supertype(type);
121 return (sup == Type.noType || sup == type || sup == null)
122 ? types.interfaces(type)
123 : types.interfaces(type).prepend(sup);
124 }
126 public TypeMirror erasure(TypeMirror t) {
127 if (t.getKind() == TypeKind.PACKAGE)
128 throw new IllegalArgumentException(t.toString());
129 return types.erasure((Type) t);
130 }
132 public TypeElement boxedClass(PrimitiveType p) {
133 return types.boxedClass((Type) p);
134 }
136 public PrimitiveType unboxedType(TypeMirror t) {
137 if (t.getKind() != TypeKind.DECLARED)
138 throw new IllegalArgumentException(t.toString());
139 Type unboxed = types.unboxedType((Type) t);
140 if (! unboxed.isPrimitive()) // only true primitives, not void
141 throw new IllegalArgumentException(t.toString());
142 return unboxed;
143 }
145 public TypeMirror capture(TypeMirror t) {
146 validateTypeNotIn(t, EXEC_OR_PKG);
147 return types.capture((Type) t);
148 }
150 public PrimitiveType getPrimitiveType(TypeKind kind) {
151 switch (kind) {
152 case BOOLEAN: return syms.booleanType;
153 case BYTE: return syms.byteType;
154 case SHORT: return syms.shortType;
155 case INT: return syms.intType;
156 case LONG: return syms.longType;
157 case CHAR: return syms.charType;
158 case FLOAT: return syms.floatType;
159 case DOUBLE: return syms.doubleType;
160 default:
161 throw new IllegalArgumentException("Not a primitive type: " + kind);
162 }
163 }
165 public NullType getNullType() {
166 return (NullType) syms.botType;
167 }
169 public NoType getNoType(TypeKind kind) {
170 switch (kind) {
171 case VOID: return syms.voidType;
172 case NONE: return Type.noType;
173 default:
174 throw new IllegalArgumentException(kind.toString());
175 }
176 }
178 public ArrayType getArrayType(TypeMirror componentType) {
179 switch (componentType.getKind()) {
180 case VOID:
181 case EXECUTABLE:
182 case WILDCARD: // heh!
183 case PACKAGE:
184 throw new IllegalArgumentException(componentType.toString());
185 }
186 return new Type.ArrayType((Type) componentType, syms.arrayClass);
187 }
189 public WildcardType getWildcardType(TypeMirror extendsBound,
190 TypeMirror superBound) {
191 BoundKind bkind;
192 Type bound;
193 if (extendsBound == null && superBound == null) {
194 bkind = BoundKind.UNBOUND;
195 bound = syms.objectType;
196 } else if (superBound == null) {
197 bkind = BoundKind.EXTENDS;
198 bound = (Type) extendsBound;
199 } else if (extendsBound == null) {
200 bkind = BoundKind.SUPER;
201 bound = (Type) superBound;
202 } else {
203 throw new IllegalArgumentException(
204 "Extends and super bounds cannot both be provided");
205 }
206 switch (bound.getKind()) {
207 case ARRAY:
208 case DECLARED:
209 case ERROR:
210 case TYPEVAR:
211 return new Type.WildcardType(bound, bkind, syms.boundClass);
212 default:
213 throw new IllegalArgumentException(bound.toString());
214 }
215 }
217 public DeclaredType getDeclaredType(TypeElement typeElem,
218 TypeMirror... typeArgs) {
219 ClassSymbol sym = (ClassSymbol) typeElem;
221 if (typeArgs.length == 0)
222 return (DeclaredType) sym.erasure(types);
223 if (sym.type.getEnclosingType().isParameterized())
224 throw new IllegalArgumentException(sym.toString());
226 return getDeclaredType0(sym.type.getEnclosingType(), sym, typeArgs);
227 }
229 public DeclaredType getDeclaredType(DeclaredType enclosing,
230 TypeElement typeElem,
231 TypeMirror... typeArgs) {
232 if (enclosing == null)
233 return getDeclaredType(typeElem, typeArgs);
235 ClassSymbol sym = (ClassSymbol) typeElem;
236 Type outer = (Type) enclosing;
238 if (outer.tsym != sym.owner.enclClass())
239 throw new IllegalArgumentException(enclosing.toString());
240 if (!outer.isParameterized())
241 return getDeclaredType(typeElem, typeArgs);
243 return getDeclaredType0(outer, sym, typeArgs);
244 }
245 // where
246 private DeclaredType getDeclaredType0(Type outer,
247 ClassSymbol sym,
248 TypeMirror... typeArgs) {
249 if (typeArgs.length != sym.type.getTypeArguments().length())
250 throw new IllegalArgumentException(
251 "Incorrect number of type arguments");
253 ListBuffer<Type> targs = new ListBuffer<Type>();
254 for (TypeMirror t : typeArgs) {
255 if (!(t instanceof ReferenceType || t instanceof WildcardType))
256 throw new IllegalArgumentException(t.toString());
257 targs.append((Type) t);
258 }
259 // TODO: Would like a way to check that type args match formals.
261 return (DeclaredType) new Type.ClassType(outer, targs.toList(), sym);
262 }
264 /**
265 * Returns the type of an element when that element is viewed as
266 * a member of, or otherwise directly contained by, a given type.
267 * For example,
268 * when viewed as a member of the parameterized type {@code Set<String>},
269 * the {@code Set.add} method is an {@code ExecutableType}
270 * whose parameter is of type {@code String}.
271 *
272 * @param containing the containing type
273 * @param element the element
274 * @return the type of the element as viewed from the containing type
275 * @throws IllegalArgumentException if the element is not a valid one
276 * for the given type
277 */
278 public TypeMirror asMemberOf(DeclaredType containing, Element element) {
279 Type site = (Type)containing;
280 Symbol sym = (Symbol)element;
281 if (types.asSuper(site, sym.getEnclosingElement()) == null)
282 throw new IllegalArgumentException(sym + "@" + site);
283 return types.memberType(site, sym);
284 }
287 private static final Set<TypeKind> EXEC_OR_PKG =
288 EnumSet.of(TypeKind.EXECUTABLE, TypeKind.PACKAGE);
290 /**
291 * Throws an IllegalArgumentException if a type's kind is one of a set.
292 */
293 private void validateTypeNotIn(TypeMirror t, Set<TypeKind> invalidKinds) {
294 if (invalidKinds.contains(t.getKind()))
295 throw new IllegalArgumentException(t.toString());
296 }
298 /**
299 * Returns an object cast to the specified type.
300 * @throws NullPointerException if the object is {@code null}
301 * @throws IllegalArgumentException if the object is of the wrong type
302 */
303 private static <T> T cast(Class<T> clazz, Object o) {
304 if (! clazz.isInstance(o))
305 throw new IllegalArgumentException(o.toString());
306 return clazz.cast(o);
307 }
309 public Set<MethodSymbol> getOverriddenMethods(Element elem) {
310 if (elem.getKind() != ElementKind.METHOD
311 || elem.getModifiers().contains(Modifier.STATIC)
312 || elem.getModifiers().contains(Modifier.PRIVATE))
313 return Collections.emptySet();
315 if (!(elem instanceof MethodSymbol))
316 throw new IllegalArgumentException();
318 MethodSymbol m = (MethodSymbol) elem;
319 ClassSymbol origin = (ClassSymbol) m.owner;
321 Set<MethodSymbol> results = new LinkedHashSet<MethodSymbol>();
322 for (Type t : types.closure(origin.type)) {
323 if (t != origin.type) {
324 ClassSymbol c = (ClassSymbol) t.tsym;
325 for (Scope.Entry e = c.members().lookup(m.name); e.scope != null; e = e.next()) {
326 if (e.sym.kind == Kinds.MTH && m.overrides(e.sym, origin, types, true)) {
327 results.add((MethodSymbol) e.sym);
328 }
329 }
330 }
331 }
333 return results;
334 }
335 }