Thu, 31 Aug 2017 15:18:52 +0800
merge
1 /*
2 * Copyright (c) 1997, 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.internal.jxc.model.nav;
28 import com.sun.source.tree.CompilationUnitTree;
29 import com.sun.source.util.TreePath;
30 import com.sun.source.util.Trees;
31 import com.sun.xml.internal.bind.v2.model.nav.Navigator;
32 import com.sun.xml.internal.bind.v2.runtime.Location;
34 import javax.annotation.processing.ProcessingEnvironment;
35 import javax.lang.model.element.AnnotationMirror;
36 import javax.lang.model.element.Element;
37 import javax.lang.model.element.ElementKind;
38 import javax.lang.model.element.ExecutableElement;
39 import javax.lang.model.element.Modifier;
40 import javax.lang.model.element.TypeElement;
41 import javax.lang.model.element.TypeParameterElement;
42 import javax.lang.model.element.VariableElement;
43 import javax.lang.model.type.ArrayType;
44 import javax.lang.model.type.DeclaredType;
45 import javax.lang.model.type.PrimitiveType;
46 import javax.lang.model.type.TypeKind;
47 import javax.lang.model.type.TypeMirror;
48 import javax.lang.model.type.TypeVariable;
49 import javax.lang.model.type.TypeVisitor;
50 import javax.lang.model.type.WildcardType;
51 import javax.lang.model.util.ElementFilter;
52 import javax.lang.model.util.Elements;
53 import javax.lang.model.util.SimpleTypeVisitor6;
54 import javax.lang.model.util.Types;
55 import java.lang.annotation.Annotation;
56 import java.util.Collection;
57 import java.util.HashMap;
58 import java.util.HashSet;
59 import java.util.List;
60 import java.util.Map;
62 /**
63 * {@link Navigator} implementation for annotation processing.
64 * TODO: check the spec on how generics are supposed to be handled
65 *
66 * @author Kohsuke Kawaguchi (kk@kohsuke.org)
67 */
68 public final class ApNavigator implements Navigator<TypeMirror, TypeElement, VariableElement, ExecutableElement> {
70 private final ProcessingEnvironment env;
72 private final PrimitiveType primitiveByte;
74 public ApNavigator(ProcessingEnvironment env) {
75 this.env = env;
76 this.primitiveByte = env.getTypeUtils().getPrimitiveType(TypeKind.BYTE);
77 }
79 public TypeElement getSuperClass(TypeElement typeElement) {
80 if (typeElement.getKind().equals(ElementKind.CLASS)) {
81 TypeMirror sup = typeElement.getSuperclass();
82 if (!sup.getKind().equals(TypeKind.NONE))
83 return (TypeElement) ((DeclaredType) sup).asElement();
84 else
85 return null;
86 }
87 return env.getElementUtils().getTypeElement(Object.class.getName());
88 }
90 public TypeMirror getBaseClass(TypeMirror type, TypeElement sup) {
91 return baseClassFinder.visit(type, sup);
92 }
94 public String getClassName(TypeElement t) {
95 return t.getQualifiedName().toString();
96 }
98 public String getTypeName(TypeMirror typeMirror) {
99 return typeMirror.toString();
100 }
102 public String getClassShortName(TypeElement t) {
103 return t.getSimpleName().toString();
104 }
106 public Collection<VariableElement> getDeclaredFields(TypeElement typeElement) {
107 return ElementFilter.fieldsIn(typeElement.getEnclosedElements());
108 }
110 public VariableElement getDeclaredField(TypeElement clazz, String fieldName) {
111 for (VariableElement fd : ElementFilter.fieldsIn(clazz.getEnclosedElements())) {
112 if (fd.getSimpleName().toString().equals(fieldName))
113 return fd;
114 }
115 return null;
116 }
118 public Collection<ExecutableElement> getDeclaredMethods(TypeElement typeElement) {
119 return ElementFilter.methodsIn(typeElement.getEnclosedElements());
120 }
122 public TypeElement getDeclaringClassForField(VariableElement f) {
123 return (TypeElement) f.getEnclosingElement();
124 }
126 public TypeElement getDeclaringClassForMethod(ExecutableElement m) {
127 return (TypeElement) m.getEnclosingElement();
128 }
130 public TypeMirror getFieldType(VariableElement f) {
131 return f.asType();
132 }
134 public String getFieldName(VariableElement f) {
135 return f.getSimpleName().toString();
136 }
138 public String getMethodName(ExecutableElement m) {
139 return m.getSimpleName().toString();
140 }
142 public TypeMirror getReturnType(ExecutableElement m) {
143 return m.getReturnType();
144 }
146 public TypeMirror[] getMethodParameters(ExecutableElement m) {
147 Collection<? extends VariableElement> ps = m.getParameters();
148 TypeMirror[] r = new TypeMirror[ps.size()];
149 int i=0;
150 for (VariableElement p : ps)
151 r[i++] = p.asType();
152 return r;
153 }
155 public boolean isStaticMethod(ExecutableElement m) {
156 return hasModifier(m, Modifier.STATIC);
157 }
159 public boolean isFinalMethod(ExecutableElement m) {
160 return hasModifier(m, Modifier.FINAL);
161 }
163 private boolean hasModifier(Element d, Modifier mod) {
164 return d.getModifiers().contains(mod);
165 }
167 public boolean isSubClassOf(TypeMirror sub, TypeMirror sup) {
168 if(sup==DUMMY)
169 // see ref(). if the sub type is known to Annotation Processing,
170 // its base class must be known. Thus if the sup is DUMMY,
171 // it cannot possibly be the super type.
172 return false;
173 return env.getTypeUtils().isSubtype(sub,sup);
174 }
176 private String getSourceClassName(Class clazz) {
177 Class<?> d = clazz.getDeclaringClass();
178 if(d==null)
179 return clazz.getName();
180 else {
181 String shortName = clazz.getName().substring(d.getName().length()+1/*for $*/);
182 return getSourceClassName(d)+'.'+shortName;
183 }
184 }
186 public TypeMirror ref(Class c) {
187 if(c.isArray())
188 return env.getTypeUtils().getArrayType( ref(c.getComponentType()) );
189 if(c.isPrimitive())
190 return getPrimitive(c);
191 TypeElement t = env.getElementUtils().getTypeElement(getSourceClassName(c));
192 // Annotation Processing only operates on a set of classes used in the compilation,
193 // and it won't recognize additional classes (even if they are visible from javac)
194 // and return null.
195 //
196 // this is causing a problem where we check if a type is collection.
197 // so until the problem is fixed in Annotation Processing, work around the issue
198 // by returning a dummy token
199 // TODO: check if this is still valid
200 if(t==null)
201 return DUMMY;
202 return env.getTypeUtils().getDeclaredType(t);
203 }
205 public TypeMirror use(TypeElement t) {
206 assert t != null;
207 return env.getTypeUtils().getDeclaredType(t);
208 }
210 public TypeElement asDecl(TypeMirror m) {
211 m = env.getTypeUtils().erasure(m);
212 if (m.getKind().equals(TypeKind.DECLARED)) {
213 DeclaredType d = (DeclaredType) m;
214 return (TypeElement) d.asElement();
215 } else
216 return null;
217 }
219 public TypeElement asDecl(Class c) {
220 return env.getElementUtils().getTypeElement(getSourceClassName(c));
221 }
223 public TypeMirror erasure(TypeMirror t) {
224 Types tu = env.getTypeUtils();
225 t = tu.erasure(t);
226 if (t.getKind().equals(TypeKind.DECLARED)) {
227 DeclaredType dt = (DeclaredType)t;
228 if (!dt.getTypeArguments().isEmpty())
229 return tu.getDeclaredType((TypeElement) dt.asElement());
230 }
231 return t;
232 }
234 public boolean isAbstract(TypeElement clazz) {
235 return hasModifier(clazz,Modifier.ABSTRACT);
236 }
238 public boolean isFinal(TypeElement clazz) {
239 return hasModifier(clazz, Modifier.FINAL);
240 }
242 public VariableElement[] getEnumConstants(TypeElement clazz) {
243 List<? extends Element> elements = env.getElementUtils().getAllMembers(clazz);
244 Collection<VariableElement> constants = new HashSet<VariableElement>();
245 for (Element element : elements) {
246 if (element.getKind().equals(ElementKind.ENUM_CONSTANT)) {
247 constants.add((VariableElement) element);
248 }
249 }
250 return constants.toArray(new VariableElement[constants.size()]);
251 }
253 public TypeMirror getVoidType() {
254 return env.getTypeUtils().getNoType(TypeKind.VOID);
255 }
257 public String getPackageName(TypeElement clazz) {
258 return env.getElementUtils().getPackageOf(clazz).getQualifiedName().toString();
259 }
261 @Override
262 public TypeElement loadObjectFactory(TypeElement referencePoint, String packageName) {
263 return env.getElementUtils().getTypeElement(packageName + ".ObjectFactory");
264 }
266 public boolean isBridgeMethod(ExecutableElement method) {
267 return method.getModifiers().contains(Modifier.VOLATILE);
268 }
270 public boolean isOverriding(ExecutableElement method, TypeElement base) {
271 Elements elements = env.getElementUtils();
273 while (true) {
274 for (ExecutableElement m : ElementFilter.methodsIn(elements.getAllMembers(base))) {
275 if (elements.overrides(method, m, base))
276 return true;
277 }
279 if (base.getSuperclass().getKind().equals(TypeKind.NONE))
280 return false;
281 base = (TypeElement) env.getTypeUtils().asElement(base.getSuperclass());
282 }
283 }
285 public boolean isInterface(TypeElement clazz) {
286 return clazz.getKind().isInterface();
287 }
289 public boolean isTransient(VariableElement f) {
290 return f.getModifiers().contains(Modifier.TRANSIENT);
291 }
293 public boolean isInnerClass(TypeElement clazz) {
294 return clazz.getEnclosingElement() != null && !clazz.getModifiers().contains(Modifier.STATIC);
295 }
297 @Override
298 public boolean isSameType(TypeMirror t1, TypeMirror t2) {
299 return env.getTypeUtils().isSameType(t1, t2);
300 }
302 public boolean isArray(TypeMirror type) {
303 return type != null && type.getKind().equals(TypeKind.ARRAY);
304 }
306 public boolean isArrayButNotByteArray(TypeMirror t) {
307 if(!isArray(t))
308 return false;
310 ArrayType at = (ArrayType) t;
311 TypeMirror ct = at.getComponentType();
313 return !ct.equals(primitiveByte);
314 }
316 public TypeMirror getComponentType(TypeMirror t) {
317 if (isArray(t)) {
318 ArrayType at = (ArrayType) t;
319 return at.getComponentType();
320 }
322 throw new IllegalArgumentException();
323 }
325 public TypeMirror getTypeArgument(TypeMirror typeMirror, int i) {
326 if (typeMirror != null && typeMirror.getKind().equals(TypeKind.DECLARED)) {
327 DeclaredType declaredType = (DeclaredType) typeMirror;
328 TypeMirror[] args = declaredType.getTypeArguments().toArray(new TypeMirror[declaredType.getTypeArguments().size()]);
329 return args[i];
330 } else throw new IllegalArgumentException();
331 }
333 public boolean isParameterizedType(TypeMirror typeMirror) {
334 if (typeMirror != null && typeMirror.getKind().equals(TypeKind.DECLARED)) {
335 DeclaredType d = (DeclaredType) typeMirror;
336 return !d.getTypeArguments().isEmpty();
337 }
338 return false;
339 }
341 public boolean isPrimitive(TypeMirror t) {
342 return t.getKind().isPrimitive();
343 }
345 private static final Map<Class, TypeKind> primitives = new HashMap<Class, TypeKind>();
347 static {
348 primitives.put(Integer.TYPE, TypeKind.INT);
349 primitives.put(Byte.TYPE, TypeKind.BYTE);
350 primitives.put(Float.TYPE, TypeKind.FLOAT);
351 primitives.put(Boolean.TYPE, TypeKind.BOOLEAN);
352 primitives.put(Short.TYPE, TypeKind.SHORT);
353 primitives.put(Long.TYPE, TypeKind.LONG);
354 primitives.put(Double.TYPE, TypeKind.DOUBLE);
355 primitives.put(Character.TYPE, TypeKind.CHAR);
356 }
358 public TypeMirror getPrimitive(Class primitiveType) {
359 assert primitiveType.isPrimitive();
360 if(primitiveType==void.class)
361 return getVoidType();
362 return env.getTypeUtils().getPrimitiveType(primitives.get(primitiveType));
363 }
365 /**
366 * see {@link #ref(Class)}.
367 */
368 private static final TypeMirror DUMMY = new TypeMirror() {
369 @Override
370 public <R, P> R accept(TypeVisitor<R, P> v, P p) {
371 throw new IllegalStateException();
372 }
374 @Override
375 public TypeKind getKind() {
376 throw new IllegalStateException();
377 }
379 // @Override
380 public List<? extends AnnotationMirror> getAnnotationMirrors() {
381 throw new IllegalStateException();
382 }
384 // @Override
385 public <A extends Annotation> A getAnnotation(Class<A> annotationType) {
386 throw new IllegalStateException();
387 }
389 // @Override
390 public <A extends Annotation> A[] getAnnotationsByType(Class<A> annotationType) {
391 throw new IllegalStateException();
392 }
393 };
395 public Location getClassLocation(TypeElement typeElement) {
396 Trees trees = Trees.instance(env);
397 return getLocation(typeElement.getQualifiedName().toString(), trees.getPath(typeElement));
398 }
400 public Location getFieldLocation(VariableElement variableElement) {
401 return getLocation(variableElement);
402 }
404 public Location getMethodLocation(ExecutableElement executableElement) {
405 return getLocation(executableElement);
406 }
408 public boolean hasDefaultConstructor(TypeElement t) {
409 if (t == null || !t.getKind().equals(ElementKind.CLASS))
410 return false;
412 for (ExecutableElement init : ElementFilter.constructorsIn(env.getElementUtils().getAllMembers(t))) {
413 if (init.getParameters().isEmpty())
414 return true;
415 }
416 return false;
417 }
419 public boolean isStaticField(VariableElement f) {
420 return hasModifier(f,Modifier.STATIC);
421 }
423 public boolean isPublicMethod(ExecutableElement m) {
424 return hasModifier(m,Modifier.PUBLIC);
425 }
427 public boolean isPublicField(VariableElement f) {
428 return hasModifier(f,Modifier.PUBLIC);
429 }
431 public boolean isEnum(TypeElement t) {
432 return t != null && t.getKind().equals(ElementKind.ENUM);
433 }
435 private Location getLocation(Element element) {
436 Trees trees = Trees.instance(env);
437 return getLocation(
438 ((TypeElement) element.getEnclosingElement()).getQualifiedName() + "." + element.getSimpleName(),
439 trees.getPath(element)
440 );
441 }
443 private Location getLocation(final String name, final TreePath treePath) {
444 return new Location() {
445 public String toString() {
446 if (treePath == null)
447 return name + " (Unknown Source)";
448 // just like stack trace, we just print the file name and
449 // not the whole path. The idea is that the package name should
450 // provide enough clue on which directory it lives.
451 CompilationUnitTree compilationUnit = treePath.getCompilationUnit();
452 Trees trees = Trees.instance(env);
453 long startPosition = trees.getSourcePositions().getStartPosition(compilationUnit, treePath.getLeaf());
454 return name + "(" +
455 compilationUnit.getSourceFile().getName() + ":" + compilationUnit.getLineMap().getLineNumber(startPosition) +
456 ")";
457 }
458 };
459 }
461 /**
462 * Implements {@link #getBaseClass}.
463 */
464 private final SimpleTypeVisitor6<TypeMirror, TypeElement> baseClassFinder = new SimpleTypeVisitor6<TypeMirror, TypeElement>() {
465 @Override
466 public TypeMirror visitDeclared(DeclaredType t, TypeElement sup) {
467 if (t.asElement().equals(sup))
468 return t;
470 for (TypeMirror i : env.getTypeUtils().directSupertypes(t)) {
471 TypeMirror r = visitDeclared((DeclaredType) i, sup);
472 if (r != null)
473 return r;
474 }
476 // otherwise recursively apply super class and base types
477 TypeMirror superclass = ((TypeElement) t.asElement()).getSuperclass();
478 if (!superclass.getKind().equals(TypeKind.NONE)) {
479 TypeMirror r = visitDeclared((DeclaredType) superclass, sup);
480 if (r != null)
481 return r;
482 }
483 return null;
484 }
486 @Override
487 public TypeMirror visitTypeVariable(TypeVariable t, TypeElement typeElement) {
488 // we are checking if T (declared as T extends A&B&C) is assignable to sup.
489 // so apply bounds recursively.
490 for (TypeMirror typeMirror : ((TypeParameterElement) t.asElement()).getBounds()) {
491 TypeMirror m = visit(typeMirror, typeElement);
492 if (m != null)
493 return m;
494 }
495 return null;
496 }
498 @Override
499 public TypeMirror visitArray(ArrayType t, TypeElement typeElement) {
500 // we are checking if t=T[] is assignable to sup.
501 // the only case this is allowed is sup=Object,
502 // and Object isn't parameterized.
503 return null;
504 }
506 @Override
507 public TypeMirror visitWildcard(WildcardType t, TypeElement typeElement) {
508 // we are checking if T (= ? extends A&B&C) is assignable to sup.
509 // so apply bounds recursively.
510 return visit(t.getExtendsBound(), typeElement);
511 }
513 @Override
514 protected TypeMirror defaultAction(TypeMirror e, TypeElement typeElement) {
515 return e;
516 }
517 };
518 }