1 /*
2  * Copyright (c) 2010, 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.
8  *
9  * This code is distributed in the hope that it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12  * version 2 for more details (a copy is included in the LICENSE file that
13  * accompanied this code).
14  *
15  * You should have received a copy of the GNU General Public License version
16  * 2 along with this work; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18  *
19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20  * or visit www.oracle.com if you need additional information or have any
21  * questions.
22  */
23 
24 import java.io.*;
25 import java.util.*;
26 import javax.annotation.processing.*;
27 import javax.lang.model.*;
28 import javax.lang.model.element.*;
29 import javax.lang.model.util.*;
30 import javax.tools.*;
31 
32 import com.sun.source.util.*;
33 import com.sun.tools.javac.code.BoundKind;
34 import com.sun.tools.javac.tree.JCTree.*;
35 import com.sun.tools.javac.tree.TreeScanner;
36 import com.sun.tools.javac.tree.*;
37 import com.sun.tools.javac.util.List;
38 
39 /**
40  * Test processor used to check test programs using the @Test, @DA, and @TA
41  * annotations.
42  *
43  * The processor looks for elements annotated with @Test, and analyzes the
44  * syntax trees for those elements. Within such trees, the processor looks
45  * for the DA annotations on decls and TA annotations on types.
46  * The value of these annotations should be a simple string rendition of
47  * the tree node to which it is attached.
48  * The expected number of annotations is given by the parameter to the
49  * @Test annotation itself.
50  */
51 @SupportedAnnotationTypes({"Test"})
52 public class TestProcessor extends AbstractProcessor {
getSupportedSourceVersion()53     public SourceVersion getSupportedSourceVersion() {
54         return SourceVersion.latest();
55     }
56 
57     /** Process trees for elements annotated with the @Test(n) annotation. */
process(Set<? extends TypeElement> annos, RoundEnvironment renv)58     public boolean process(Set<? extends TypeElement> annos, RoundEnvironment renv) {
59         if (renv.processingOver())
60             return true;
61 
62         Elements elements = processingEnv.getElementUtils();
63         Trees trees = Trees.instance(processingEnv);
64 
65         TypeElement testAnno = elements.getTypeElement("Test");
66         for (Element elem: renv.getElementsAnnotatedWith(testAnno)) {
67             System.err.println("ELEM: " + elem);
68             int count = getValue(getAnnoMirror(elem, testAnno), Integer.class);
69             System.err.println("count: " + count);
70             TreePath p = trees.getPath(elem);
71             JavaFileObject file = p.getCompilationUnit().getSourceFile();
72             JCTree tree = (JCTree) p.getLeaf();
73             System.err.println("tree: " + tree);
74             new TestScanner(file).check(tree, count);
75         }
76         return true;
77     }
78 
79     /** Get the AnnotationMirror on an element for a given annotation. */
getAnnoMirror(Element e, TypeElement anno)80     AnnotationMirror getAnnoMirror(Element e, TypeElement anno) {
81         Types types = processingEnv.getTypeUtils();
82         for (AnnotationMirror m: e.getAnnotationMirrors()) {
83             if (types.isSameType(m.getAnnotationType(), anno.asType()))
84                 return m;
85         }
86         return null;
87     }
88 
89     /** Get the value of the value element of an annotation mirror. */
getValue(AnnotationMirror m, Class<T> type)90     <T> T getValue(AnnotationMirror m, Class<T> type) {
91         for (Map.Entry<? extends ExecutableElement,? extends AnnotationValue> e: m.getElementValues().entrySet()) {
92             ExecutableElement ee = e.getKey();
93             if (ee.getSimpleName().contentEquals("value")) {
94                 AnnotationValue av = e.getValue();
95                 return type.cast(av.getValue());
96             }
97         }
98         return null;
99     }
100 
101     /** Report an error to the annotation processing system. */
error(String msg)102     void error(String msg) {
103         Messager messager = processingEnv.getMessager();
104         messager.printMessage(Diagnostic.Kind.ERROR, msg);
105     }
106 
107     /** Report an error to the annotation processing system. */
error(JavaFileObject file, JCTree tree, String msg)108     void error(JavaFileObject file, JCTree tree, String msg) {
109         // need better API for reporting tree position errors to the messager
110         Messager messager = processingEnv.getMessager();
111         String text = file.getName() + ":" + getLine(file, tree) + ": " + msg;
112         messager.printMessage(Diagnostic.Kind.ERROR, text);
113     }
114 
115     /** Get the line number for the primary position for a tree.
116      * The code is intended to be simple, although not necessarily efficient.
117      * However, note that a file manager such as JavacFileManager is likely
118      * to cache the results of file.getCharContent, avoiding the need to read
119      * the bits from disk each time this method is called.
120      */
getLine(JavaFileObject file, JCTree tree)121     int getLine(JavaFileObject file, JCTree tree) {
122         try {
123             CharSequence cs = file.getCharContent(true);
124             int line = 1;
125             for (int i = 0; i < tree.pos; i++) {
126                 if (cs.charAt(i) == '\n') // jtreg tests always use Unix line endings
127                     line++;
128             }
129             return line;
130         } catch (IOException e) {
131             return -1;
132         }
133     }
134 
135     /** Scan a tree, looking for @DA and @TA annotations, and verifying that such
136      * annotations are attached to the expected tree node matching the string
137      * parameter of the annotation.
138      */
139     class TestScanner extends TreeScanner {
140         /** Create a scanner for a given file. */
TestScanner(JavaFileObject file)141         TestScanner(JavaFileObject file) {
142             this.file = file;
143         }
144 
145         /** Check the annotations in a given tree. */
check(JCTree tree, int expectCount)146         void check(JCTree tree, int expectCount) {
147             foundCount = 0;
148             scan(tree);
149             if (foundCount != expectCount)
150                 error(file, tree, "Wrong number of annotations found: " + foundCount + ", expected: " + expectCount);
151         }
152 
153         /** Check @DA annotations on a class declaration. */
154         @Override
visitClassDef(JCClassDecl tree)155         public void visitClassDef(JCClassDecl tree) {
156             super.visitClassDef(tree);
157             check(tree.mods.annotations, "DA", tree);
158         }
159 
160         /** Check @DA annotations on a method declaration. */
161         @Override
visitMethodDef(JCMethodDecl tree)162         public void visitMethodDef(JCMethodDecl tree) {
163             super.visitMethodDef(tree);
164             check(tree.mods.annotations, "DA", tree);
165         }
166 
167         /** Check @DA annotations on a field, parameter or local variable declaration. */
168         @Override
visitVarDef(JCVariableDecl tree)169         public void visitVarDef(JCVariableDecl tree) {
170             super.visitVarDef(tree);
171             check(tree.mods.annotations, "DA", tree);
172         }
173 
174         /** Check @TA annotations on a type. */
visitAnnotatedType(JCAnnotatedType tree)175         public void visitAnnotatedType(JCAnnotatedType tree) {
176             super.visitAnnotatedType(tree);
177             check(tree.annotations, "TA", tree);
178         }
179 
180         /** Check to see if a list of annotations contains a named annotation, and
181          * if so, verify the annotation is expected by comparing the value of the
182          * annotation's argument against the string rendition of the reference tree
183          * node.
184          * @param annos the list of annotations to be checked
185          * @param name  the name of the annotation to be checked
186          * @param tree  the tree against which to compare the annotations's argument
187          */
check(List<? extends JCAnnotation> annos, String name, JCTree tree)188         void check(List<? extends JCAnnotation> annos, String name, JCTree tree) {
189             for (List<? extends JCAnnotation> l = annos; l.nonEmpty(); l = l.tail) {
190                 JCAnnotation anno = l.head;
191                 if (anno.annotationType.toString().equals(name) && (anno.args.size() == 1)) {
192                     String expect = getStringValue(anno.args.head);
193                     foundCount++;
194                     System.err.println("found: " + name + " " + expect);
195                     String found = new TypePrinter().print(tree);
196                     if (!found.equals(expect))
197                         error(file, anno, "Unexpected result: expected: \"" + expect + "\", found: \"" + found + "\"");
198                 }
199             }
200         }
201 
202         /** Get the string value of an annotation argument, which is given by the
203          * expression <i>name</i>=<i>value</i>.
204          */
getStringValue(JCExpression e)205         String getStringValue(JCExpression e) {
206             if (e.hasTag(JCTree.Tag.ASSIGN)) {
207                 JCAssign a = (JCAssign) e;
208                 JCExpression rhs = a.rhs;
209                 if (rhs.hasTag(JCTree.Tag.LITERAL)) {
210                     JCLiteral l = (JCLiteral) rhs;
211                     return (String) l.value;
212                 }
213             } else if (e.hasTag(JCTree.Tag.LITERAL)) {
214                 JCLiteral l = (JCLiteral) e;
215                 return (String) l.value;
216             }
217             throw new IllegalArgumentException(e.toString());
218         }
219 
220         /** The file for the tree. Used to locate errors. */
221         JavaFileObject file;
222         /** The number of annotations that have been found. @see #check */
223         int foundCount;
224     }
225 
226     /** Convert a type or decl tree to a reference string used by the @DA and @TA annotations. */
227     class TypePrinter extends Visitor {
228         /** Convert a type or decl tree to a string. */
print(JCTree tree)229         String print(JCTree tree) {
230             if (tree == null)
231                 return null;
232             tree.accept(this);
233             return result;
234         }
235 
print(List<? extends JCTree> list)236         String print(List<? extends JCTree> list) {
237             return print(list, ", ");
238         }
239 
print(List<? extends JCTree> list, String sep)240         String print(List<? extends JCTree> list, String sep) {
241             StringBuilder sb = new StringBuilder();
242             if (list.nonEmpty()) {
243                 sb.append(print(list.head));
244                 for (List<? extends JCTree> l = list.tail; l.nonEmpty(); l = l.tail) {
245                     sb.append(sep);
246                     sb.append(print(l.head));
247                 }
248             }
249             return sb.toString();
250         }
251 
252         @Override
visitClassDef(JCClassDecl tree)253         public void visitClassDef(JCClassDecl tree) {
254             result = tree.name.toString();
255         }
256 
257         @Override
visitMethodDef(JCMethodDecl tree)258         public void visitMethodDef(JCMethodDecl tree) {
259             result = tree.name.toString();
260         }
261 
262         @Override
visitVarDef(JCVariableDecl tree)263         public void visitVarDef(JCVariableDecl tree) {
264             tree.vartype.accept(this);
265         }
266 
267         @Override
visitAnnotatedType(JCAnnotatedType tree)268         public void visitAnnotatedType(JCAnnotatedType tree) {
269             tree.underlyingType.accept(this);
270         }
271 
272         @Override
visitTypeIdent(JCPrimitiveTypeTree tree)273         public void visitTypeIdent(JCPrimitiveTypeTree tree) {
274             result = tree.toString();
275         }
276 
277         @Override
visitTypeArray(JCArrayTypeTree tree)278         public void visitTypeArray(JCArrayTypeTree tree) {
279             result = print(tree.elemtype) + "[]";
280         }
281 
282         @Override
visitTypeApply(JCTypeApply tree)283         public void visitTypeApply(JCTypeApply tree) {
284             result = print(tree.clazz) + "<" + print(tree.arguments) + ">";
285         }
286 
287         @Override
visitTypeParameter(JCTypeParameter tree)288         public void visitTypeParameter(JCTypeParameter tree) {
289             if (tree.bounds.isEmpty())
290                 result = tree.name.toString();
291             else
292                 result = tree.name + " extends " + print(tree.bounds, "&");
293         }
294 
295         @Override
visitWildcard(JCWildcard tree)296         public void visitWildcard(JCWildcard tree) {
297             if (tree.kind.kind == BoundKind.UNBOUND)
298                 result = tree.kind.toString();
299             else
300                 result = tree.kind + " " + print(tree.inner);
301         }
302 
303         private String result;
304     }
305 }
306