TestProcessor.java revision 487:4c844e609d81
1/*
2 * Copyright 2010 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
20 * CA 95054 USA or visit www.sun.com if you need additional information or
21 * have any questions.
22 */
23
24import java.io.*;
25import java.util.*;
26import javax.annotation.processing.*;
27import javax.lang.model.*;
28import javax.lang.model.element.*;
29import javax.lang.model.util.*;
30import javax.tools.*;
31
32import com.sun.source.util.*;
33import com.sun.tools.javac.code.BoundKind;
34import com.sun.tools.javac.tree.JCTree.*;
35import com.sun.tools.javac.tree.TreeScanner;
36import com.sun.tools.javac.tree.*;
37import 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"})
52public class TestProcessor extends AbstractProcessor {
53    public SourceVersion getSupportedSourceVersion() {
54        return SourceVersion.latest();
55    }
56
57    /** Process trees for elements annotated with the @Test(n) annotation. */
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. */
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. */
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. */
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. */
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     */
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. */
141        TestScanner(JavaFileObject file) {
142            this.file = file;
143        }
144
145        /** Check the annotations in a given tree. */
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
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
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
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. */
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         */
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         */
205        String getStringValue(JCExpression e) {
206            if (e.getTag() == JCTree.ASSIGN)  {
207                JCAssign a = (JCAssign) e;
208                JCExpression rhs = a.rhs;
209                if (rhs.getTag() == JCTree.LITERAL) {
210                    JCLiteral l = (JCLiteral) rhs;
211                    return (String) l.value;
212                }
213            }
214            throw new IllegalArgumentException(e.toString());
215        }
216
217        /** The file for the tree. Used to locate errors. */
218        JavaFileObject file;
219        /** The number of annotations that have been found. @see #check */
220        int foundCount;
221    }
222
223    /** Convert a type or decl tree to a reference string used by the @DA and @TA annotations. */
224    class TypePrinter extends Visitor {
225        /** Convert a type or decl tree to a string. */
226        String print(JCTree tree) {
227            if (tree == null)
228                return null;
229            tree.accept(this);
230            return result;
231        }
232
233        String print(List<? extends JCTree> list) {
234            return print(list, ", ");
235        }
236
237        String print(List<? extends JCTree> list, String sep) {
238            StringBuilder sb = new StringBuilder();
239            if (list.nonEmpty()) {
240                sb.append(print(list.head));
241                for (List<? extends JCTree> l = list.tail; l.nonEmpty(); l = l.tail) {
242                    sb.append(sep);
243                    sb.append(print(l.head));
244                }
245            }
246            return sb.toString();
247        }
248
249        @Override
250        public void visitClassDef(JCClassDecl tree) {
251            result = tree.name.toString();
252        }
253
254        @Override
255        public void visitMethodDef(JCMethodDecl tree) {
256            result = tree.name.toString();
257        }
258
259        @Override
260        public void visitVarDef(JCVariableDecl tree) {
261            tree.vartype.accept(this);
262        }
263
264        @Override
265        public void visitAnnotatedType(JCAnnotatedType tree) {
266            tree.underlyingType.accept(this);
267        }
268
269        @Override
270        public void visitTypeIdent(JCPrimitiveTypeTree tree) {
271            result = tree.toString();
272        }
273
274        @Override
275        public void visitTypeArray(JCArrayTypeTree tree) {
276            result = print(tree.elemtype) + "[]";
277        }
278
279        @Override
280        public void visitTypeApply(JCTypeApply tree) {
281            result = print(tree.clazz) + "<" + print(tree.arguments) + ">";
282        }
283
284        @Override
285        public void visitTypeParameter(JCTypeParameter tree) {
286            if (tree.bounds.isEmpty())
287                result = tree.name.toString();
288            else
289                result = tree.name + " extends " + print(tree.bounds, "&");
290        }
291
292        @Override
293        public void visitWildcard(JCWildcard tree) {
294            if (tree.kind.kind == BoundKind.UNBOUND)
295                result = tree.kind.toString();
296            else
297                result = tree.kind + " " + print(tree.inner);
298        }
299
300        private String result;
301    }
302}
303