test/tools/javac/tree/TreeScannerTest.java

changeset 685
fd2579b80b83
parent 554
9d9f26857129
equal deleted inserted replaced
653:7ad86852c38a 685:fd2579b80b83
1 /*
2 * Copyright (c) 2010, 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
25 /**
26 * Utility and test program to check javac's internal TreeScanner class.
27 * The program can be run standalone, or as a jtreg test. For info on
28 * command line args, run program with no args.
29 *
30 * <p>
31 * jtreg: Note that by using the -r switch in the test description below, this test
32 * will process all java files in the langtools/test directory, thus implicitly
33 * covering any new language features that may be tested in this test suite.
34 */
35
36 /*
37 * @test
38 * @bug 6923080
39 * @summary TreeScanner.visitNewClass should scan tree.typeargs
40 * @run main TreeScannerTest -q -r .
41 */
42
43 import java.io.*;
44 import java.lang.reflect.*;
45 import java.util.*;
46 import javax.tools.*;
47
48 import com.sun.source.tree.CompilationUnitTree;
49 import com.sun.source.util.JavacTask;
50 import com.sun.tools.javac.api.JavacTool;
51 import com.sun.tools.javac.tree.*;
52 import com.sun.tools.javac.tree.JCTree.*;
53 import com.sun.tools.javac.util.List;
54
55 public class TreeScannerTest {
56 /**
57 * Main entry point.
58 * If test.src is set, program runs in jtreg mode, and will throw an Error
59 * if any errors arise, otherwise System.exit will be used. In jtreg mode,
60 * the default base directory for file args is the value of ${test.src}.
61 * In jtreg mode, the -r option can be given to change the default base
62 * directory to the root test directory.
63 */
64 public static void main(String... args) {
65 String testSrc = System.getProperty("test.src");
66 File baseDir = (testSrc == null) ? null : new File(testSrc);
67 boolean ok = new TreeScannerTest().run(baseDir, args);
68 if (!ok) {
69 if (testSrc != null) // jtreg mode
70 throw new Error("failed");
71 else
72 System.exit(1);
73 }
74 }
75
76 /**
77 * Run the program. A base directory can be provided for file arguments.
78 * In jtreg mode, the -r option can be given to change the default base
79 * directory to the test root directory. For other options, see usage().
80 * @param baseDir base directory for any file arguments.
81 * @param args command line args
82 * @return true if successful or in gui mode
83 */
84 boolean run(File baseDir, String... args) {
85 if (args.length == 0) {
86 usage(System.out);
87 return true;
88 }
89
90 ArrayList<File> files = new ArrayList<File>();
91 for (int i = 0; i < args.length; i++) {
92 String arg = args[i];
93 if (arg.equals("-q"))
94 quiet = true;
95 else if (arg.equals("-v"))
96 verbose = true;
97 else if (arg.equals("-r")) {
98 File d = baseDir;
99 while (!new File(d, "TEST.ROOT").exists()) {
100 d = d.getParentFile();
101 if (d == null)
102 throw new Error("cannot find TEST.ROOT");
103 }
104 baseDir = d;
105 }
106 else if (arg.startsWith("-"))
107 throw new Error("unknown option: " + arg);
108 else {
109 while (i < args.length)
110 files.add(new File(baseDir, args[i++]));
111 }
112 }
113
114 for (File file: files) {
115 if (file.exists())
116 test(file);
117 else
118 error("File not found: " + file);
119 }
120
121 if (fileCount != 1)
122 System.err.println(fileCount + " files read");
123 if (errors > 0)
124 System.err.println(errors + " errors");
125
126 return (errors == 0);
127 }
128
129 /**
130 * Print command line help.
131 * @param out output stream
132 */
133 void usage(PrintStream out) {
134 out.println("Usage:");
135 out.println(" java TreeScannerTest options... files...");
136 out.println("");
137 out.println("where options include:");
138 out.println("-q Quiet: don't report on inapplicable files");
139 out.println("-v Verbose: report on files as they are being read");
140 out.println("");
141 out.println("files may be directories or files");
142 out.println("directories will be scanned recursively");
143 out.println("non java files, or java files which cannot be parsed, will be ignored");
144 out.println("");
145 }
146
147 /**
148 * Test a file. If the file is a directory, it will be recursively scanned
149 * for java files.
150 * @param file the file or directory to test
151 */
152 void test(File file) {
153 if (file.isDirectory()) {
154 for (File f: file.listFiles()) {
155 test(f);
156 }
157 return;
158 }
159
160 if (file.isFile() && file.getName().endsWith(".java")) {
161 try {
162 if (verbose)
163 System.err.println(file);
164 fileCount++;
165 ScanTester t = new ScanTester();
166 t.test(read(file));
167 } catch (ParseException e) {
168 if (!quiet) {
169 error("Error parsing " + file + "\n" + e.getMessage());
170 }
171 } catch (IOException e) {
172 error("Error reading " + file + ": " + e);
173 }
174 return;
175 }
176
177 if (!quiet)
178 error("File " + file + " ignored");
179 }
180
181 /**
182 * Read a file.
183 * @param file the file to be read
184 * @return the tree for the content of the file
185 * @throws IOException if any IO errors occur
186 * @throws TreePosTest.ParseException if any errors occur while parsing the file
187 */
188 JCCompilationUnit read(File file) throws IOException, ParseException {
189 StringWriter sw = new StringWriter();
190 PrintWriter pw = new PrintWriter(sw);
191 Reporter r = new Reporter(pw);
192 JavacTool tool = JavacTool.create();
193 StandardJavaFileManager fm = tool.getStandardFileManager(r, null, null);
194 Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(file);
195 JavacTask task = tool.getTask(pw, fm, r, Collections.<String>emptyList(), null, files);
196 Iterable<? extends CompilationUnitTree> trees = task.parse();
197 pw.flush();
198 if (r.errors > 0)
199 throw new ParseException(sw.toString());
200 Iterator<? extends CompilationUnitTree> iter = trees.iterator();
201 if (!iter.hasNext())
202 throw new Error("no trees found");
203 JCCompilationUnit t = (JCCompilationUnit) iter.next();
204 if (iter.hasNext())
205 throw new Error("too many trees found");
206 return t;
207 }
208
209 /**
210 * Report an error. When the program is complete, the program will either
211 * exit or throw an Error if any errors have been reported.
212 * @param msg the error message
213 */
214 void error(String msg) {
215 System.err.println(msg);
216 errors++;
217 }
218
219 /**
220 * Report an error for a specific tree node.
221 * @param file the source file for the tree
222 * @param t the tree node
223 * @param label an indication of the error
224 */
225 void error(JavaFileObject file, JCTree t, String msg) {
226 error(file.getName() + ":" + getLine(file, t) + ": " + msg + " " + trim(t, 64));
227 }
228
229 /**
230 * Get a trimmed string for a tree node, with normalized white space and limited length.
231 */
232 String trim(JCTree t, int len) {
233 String s = t.toString().replaceAll("[\r\n]+", " ").replaceAll(" +", " ");
234 return (s.length() < len) ? s : s.substring(0, len);
235 }
236
237 /** Number of files that have been analyzed. */
238 int fileCount;
239 /** Number of errors reported. */
240 int errors;
241 /** Flag: don't report irrelevant files. */
242 boolean quiet;
243 /** Flag: report files as they are processed. */
244 boolean verbose;
245
246 /**
247 * Main class for testing operation of tree scanner.
248 * The set of nodes found by the scanner are compared
249 * against the set of nodes found by reflection.
250 */
251 private class ScanTester extends TreeScanner {
252 /** Main entry method for the class. */
253 void test(JCCompilationUnit tree) {
254 sourcefile = tree.sourcefile;
255 found = new HashSet<JCTree>();
256 scan(tree);
257 expect = new HashSet<JCTree>();
258 reflectiveScan(tree);
259 if (found.equals(expect))
260 return;
261
262 error("Differences found for " + tree.sourcefile.getName());
263
264 if (found.size() != expect.size())
265 error("Size mismatch; found: " + found.size() + ", expected: " + expect.size());
266
267 Set<JCTree> missing = new HashSet<JCTree>();
268 missing.addAll(expect);
269 missing.removeAll(found);
270 for (JCTree t: missing)
271 error(tree.sourcefile, t, "missing");
272
273 Set<JCTree> excess = new HashSet<JCTree>();
274 excess.addAll(found);
275 excess.removeAll(expect);
276 for (JCTree t: excess)
277 error(tree.sourcefile, t, "unexpected");
278 }
279
280 /** Record all tree nodes found by scanner. */
281 @Override
282 public void scan(JCTree tree) {
283 if (tree == null)
284 return;
285 System.err.println("FOUND: " + tree.getTag() + " " + trim(tree, 64));
286 found.add(tree);
287 super.scan(tree);
288 }
289
290 /** record all tree nodes found by reflection. */
291 public void reflectiveScan(Object o) {
292 if (o == null)
293 return;
294 if (o instanceof JCTree) {
295 JCTree tree = (JCTree) o;
296 System.err.println("EXPECT: " + tree.getTag() + " " + trim(tree, 64));
297 expect.add(tree);
298 for (Field f: getFields(tree)) {
299 try {
300 //System.err.println("FIELD: " + f.getName());
301 reflectiveScan(f.get(tree));
302 } catch (IllegalAccessException e) {
303 error(e.toString());
304 }
305 }
306 } else if (o instanceof List) {
307 List<?> list = (List<?>) o;
308 for (Object item: list)
309 reflectiveScan(item);
310 } else
311 error("unexpected item: " + o);
312 }
313
314 JavaFileObject sourcefile;
315 Set<JCTree> found;
316 Set<JCTree> expect;
317 }
318
319 /**
320 * Thrown when errors are found parsing a java file.
321 */
322 private static class ParseException extends Exception {
323 ParseException(String msg) {
324 super(msg);
325 }
326 }
327
328 /**
329 * DiagnosticListener to report diagnostics and count any errors that occur.
330 */
331 private static class Reporter implements DiagnosticListener<JavaFileObject> {
332 Reporter(PrintWriter out) {
333 this.out = out;
334 }
335
336 public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
337 out.println(diagnostic);
338 switch (diagnostic.getKind()) {
339 case ERROR:
340 errors++;
341 }
342 }
343 int errors;
344 PrintWriter out;
345 }
346
347 /**
348 * Get the set of fields for a tree node that may contain child tree nodes.
349 * These are the fields that are subtypes of JCTree or List.
350 * The results are cached, based on the tree's tag.
351 */
352 Set<Field> getFields(JCTree tree) {
353 Set<Field> fields = map.get(tree.getTag());
354 if (fields == null) {
355 fields = new HashSet<Field>();
356 for (Field f: tree.getClass().getFields()) {
357 Class<?> fc = f.getType();
358 if (JCTree.class.isAssignableFrom(fc) || List.class.isAssignableFrom(fc))
359 fields.add(f);
360 }
361 map.put(tree.getTag(), fields);
362 }
363 return fields;
364 }
365 // where
366 Map<Integer, Set<Field>> map = new HashMap<Integer,Set<Field>>();
367
368 /** Get the line number for the primary position for a tree.
369 * The code is intended to be simple, although not necessarily efficient.
370 * However, note that a file manager such as JavacFileManager is likely
371 * to cache the results of file.getCharContent, avoiding the need to read
372 * the bits from disk each time this method is called.
373 */
374 int getLine(JavaFileObject file, JCTree tree) {
375 try {
376 CharSequence cs = file.getCharContent(true);
377 int line = 1;
378 for (int i = 0; i < tree.pos; i++) {
379 if (cs.charAt(i) == '\n') // jtreg tests always use Unix line endings
380 line++;
381 }
382 return line;
383 } catch (IOException e) {
384 return -1;
385 }
386 }
387 }

mercurial