488N/A/*
553N/A * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
488N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
488N/A *
488N/A * This code is free software; you can redistribute it and/or modify it
488N/A * under the terms of the GNU General Public License version 2 only, as
488N/A * published by the Free Software Foundation.
488N/A *
488N/A * This code is distributed in the hope that it will be useful, but WITHOUT
488N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
488N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
488N/A * version 2 for more details (a copy is included in the LICENSE file that
488N/A * accompanied this code).
488N/A *
488N/A * You should have received a copy of the GNU General Public License version
488N/A * 2 along with this work; if not, write to the Free Software Foundation,
488N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
488N/A *
553N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
553N/A * or visit www.oracle.com if you need additional information or have any
553N/A * questions.
488N/A */
488N/A
488N/Aimport java.io.*;
488N/Aimport java.lang.reflect.*;
488N/Aimport java.util.*;
488N/Aimport javax.tools.*;
488N/A
488N/Aimport com.sun.source.tree.CompilationUnitTree;
678N/Aimport com.sun.source.tree.Tree;
488N/Aimport com.sun.source.util.JavacTask;
488N/Aimport com.sun.tools.javac.api.JavacTool;
678N/Aimport com.sun.tools.javac.tree.JCTree;
678N/Aimport com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
488N/Aimport com.sun.tools.javac.util.List;
488N/A
678N/Apublic abstract class AbstractTreeScannerTest {
488N/A
488N/A /**
488N/A * Run the program. A base directory can be provided for file arguments.
488N/A * In jtreg mode, the -r option can be given to change the default base
488N/A * directory to the test root directory. For other options, see usage().
488N/A * @param baseDir base directory for any file arguments.
488N/A * @param args command line args
488N/A * @return true if successful or in gui mode
488N/A */
488N/A boolean run(File baseDir, String... args) {
488N/A if (args.length == 0) {
488N/A usage(System.out);
488N/A return true;
488N/A }
488N/A
488N/A ArrayList<File> files = new ArrayList<File>();
488N/A for (int i = 0; i < args.length; i++) {
488N/A String arg = args[i];
488N/A if (arg.equals("-q"))
488N/A quiet = true;
488N/A else if (arg.equals("-v"))
488N/A verbose = true;
488N/A else if (arg.equals("-r")) {
488N/A File d = baseDir;
488N/A while (!new File(d, "TEST.ROOT").exists()) {
488N/A d = d.getParentFile();
488N/A if (d == null)
488N/A throw new Error("cannot find TEST.ROOT");
488N/A }
488N/A baseDir = d;
488N/A }
488N/A else if (arg.startsWith("-"))
488N/A throw new Error("unknown option: " + arg);
488N/A else {
488N/A while (i < args.length)
488N/A files.add(new File(baseDir, args[i++]));
488N/A }
488N/A }
488N/A
488N/A for (File file: files) {
488N/A if (file.exists())
488N/A test(file);
488N/A else
488N/A error("File not found: " + file);
488N/A }
488N/A
488N/A if (fileCount != 1)
488N/A System.err.println(fileCount + " files read");
678N/A System.err.println(treeCount + " tree nodes compared");
488N/A if (errors > 0)
488N/A System.err.println(errors + " errors");
488N/A
488N/A return (errors == 0);
488N/A }
488N/A
488N/A /**
488N/A * Print command line help.
488N/A * @param out output stream
488N/A */
488N/A void usage(PrintStream out) {
488N/A out.println("Usage:");
678N/A out.println(" java " + getClass().getName() + " options... files...");
488N/A out.println("");
488N/A out.println("where options include:");
488N/A out.println("-q Quiet: don't report on inapplicable files");
488N/A out.println("-v Verbose: report on files as they are being read");
488N/A out.println("");
488N/A out.println("files may be directories or files");
488N/A out.println("directories will be scanned recursively");
488N/A out.println("non java files, or java files which cannot be parsed, will be ignored");
488N/A out.println("");
488N/A }
488N/A
488N/A /**
488N/A * Test a file. If the file is a directory, it will be recursively scanned
488N/A * for java files.
488N/A * @param file the file or directory to test
488N/A */
488N/A void test(File file) {
488N/A if (file.isDirectory()) {
488N/A for (File f: file.listFiles()) {
488N/A test(f);
488N/A }
488N/A return;
488N/A }
488N/A
488N/A if (file.isFile() && file.getName().endsWith(".java")) {
488N/A try {
488N/A if (verbose)
488N/A System.err.println(file);
488N/A fileCount++;
678N/A treeCount += test(read(file));
488N/A } catch (ParseException e) {
488N/A if (!quiet) {
488N/A error("Error parsing " + file + "\n" + e.getMessage());
488N/A }
488N/A } catch (IOException e) {
488N/A error("Error reading " + file + ": " + e);
488N/A }
488N/A return;
488N/A }
488N/A
488N/A if (!quiet)
488N/A error("File " + file + " ignored");
488N/A }
488N/A
678N/A abstract int test(JCCompilationUnit t);
678N/A
807N/A // See CR: 6982992 Tests CheckAttributedTree.java, JavacTreeScannerTest.java, and SourceTreeeScannerTest.java timeout
807N/A StringWriter sw = new StringWriter();
807N/A PrintWriter pw = new PrintWriter(sw);
807N/A Reporter r = new Reporter(pw);
807N/A JavacTool tool = JavacTool.create();
807N/A StandardJavaFileManager fm = tool.getStandardFileManager(r, null, null);
807N/A
488N/A /**
488N/A * Read a file.
488N/A * @param file the file to be read
488N/A * @return the tree for the content of the file
488N/A * @throws IOException if any IO errors occur
488N/A * @throws TreePosTest.ParseException if any errors occur while parsing the file
488N/A */
488N/A JCCompilationUnit read(File file) throws IOException, ParseException {
488N/A JavacTool tool = JavacTool.create();
807N/A r.errors = 0;
488N/A Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(file);
488N/A JavacTask task = tool.getTask(pw, fm, r, Collections.<String>emptyList(), null, files);
488N/A Iterable<? extends CompilationUnitTree> trees = task.parse();
488N/A pw.flush();
488N/A if (r.errors > 0)
488N/A throw new ParseException(sw.toString());
488N/A Iterator<? extends CompilationUnitTree> iter = trees.iterator();
488N/A if (!iter.hasNext())
488N/A throw new Error("no trees found");
488N/A JCCompilationUnit t = (JCCompilationUnit) iter.next();
488N/A if (iter.hasNext())
488N/A throw new Error("too many trees found");
488N/A return t;
488N/A }
488N/A
488N/A /**
488N/A * Report an error. When the program is complete, the program will either
488N/A * exit or throw an Error if any errors have been reported.
488N/A * @param msg the error message
488N/A */
488N/A void error(String msg) {
488N/A System.err.println(msg);
488N/A errors++;
488N/A }
488N/A
488N/A /**
682N/A * Report an error. When the program is complete, the program will either
682N/A * exit or throw an Error if any errors have been reported.
682N/A * @param msg the error message
682N/A */
682N/A void error(JavaFileObject file, String msg) {
682N/A System.err.println(file.getName() + ": " + msg);
682N/A errors++;
682N/A }
682N/A
682N/A /**
488N/A * Report an error for a specific tree node.
488N/A * @param file the source file for the tree
488N/A * @param t the tree node
488N/A * @param label an indication of the error
488N/A */
678N/A void error(JavaFileObject file, Tree tree, String msg) {
678N/A JCTree t = (JCTree) tree;
488N/A error(file.getName() + ":" + getLine(file, t) + ": " + msg + " " + trim(t, 64));
488N/A }
488N/A
488N/A /**
488N/A * Get a trimmed string for a tree node, with normalized white space and limited length.
488N/A */
678N/A String trim(Tree tree, int len) {
678N/A JCTree t = (JCTree) tree;
682N/A String s = t.toString().replaceAll("\\s+", " ");
488N/A return (s.length() < len) ? s : s.substring(0, len);
488N/A }
488N/A
488N/A /** Number of files that have been analyzed. */
488N/A int fileCount;
678N/A /** Number of trees that have been successfully compared. */
678N/A int treeCount;
488N/A /** Number of errors reported. */
488N/A int errors;
488N/A /** Flag: don't report irrelevant files. */
488N/A boolean quiet;
488N/A /** Flag: report files as they are processed. */
488N/A boolean verbose;
488N/A
488N/A
488N/A /**
488N/A * Thrown when errors are found parsing a java file.
488N/A */
488N/A private static class ParseException extends Exception {
488N/A ParseException(String msg) {
488N/A super(msg);
488N/A }
488N/A }
488N/A
488N/A /**
488N/A * DiagnosticListener to report diagnostics and count any errors that occur.
488N/A */
488N/A private static class Reporter implements DiagnosticListener<JavaFileObject> {
488N/A Reporter(PrintWriter out) {
488N/A this.out = out;
488N/A }
488N/A
488N/A public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
488N/A out.println(diagnostic);
488N/A switch (diagnostic.getKind()) {
488N/A case ERROR:
488N/A errors++;
488N/A }
488N/A }
488N/A int errors;
488N/A PrintWriter out;
488N/A }
488N/A
488N/A /**
488N/A * Get the set of fields for a tree node that may contain child tree nodes.
488N/A * These are the fields that are subtypes of JCTree or List.
488N/A * The results are cached, based on the tree's tag.
488N/A */
488N/A Set<Field> getFields(JCTree tree) {
488N/A Set<Field> fields = map.get(tree.getTag());
488N/A if (fields == null) {
488N/A fields = new HashSet<Field>();
488N/A for (Field f: tree.getClass().getFields()) {
488N/A Class<?> fc = f.getType();
488N/A if (JCTree.class.isAssignableFrom(fc) || List.class.isAssignableFrom(fc))
488N/A fields.add(f);
488N/A }
488N/A map.put(tree.getTag(), fields);
488N/A }
488N/A return fields;
488N/A }
488N/A // where
488N/A Map<Integer, Set<Field>> map = new HashMap<Integer,Set<Field>>();
488N/A
488N/A /** Get the line number for the primary position for a tree.
488N/A * The code is intended to be simple, although not necessarily efficient.
488N/A * However, note that a file manager such as JavacFileManager is likely
488N/A * to cache the results of file.getCharContent, avoiding the need to read
488N/A * the bits from disk each time this method is called.
488N/A */
488N/A int getLine(JavaFileObject file, JCTree tree) {
488N/A try {
488N/A CharSequence cs = file.getCharContent(true);
488N/A int line = 1;
488N/A for (int i = 0; i < tree.pos; i++) {
488N/A if (cs.charAt(i) == '\n') // jtreg tests always use Unix line endings
488N/A line++;
488N/A }
488N/A return line;
488N/A } catch (IOException e) {
488N/A return -1;
488N/A }
488N/A }
488N/A}