001package jtb;
002
003import java.io.*;
004import jtb.JavaParser;
005import jtb.ParseException;
006import jtb.syntaxtree.*;
007import jtb.visitor.*;
008
009public class JavaParserTest {
010
011  /**
012   * Reads the {@code .java} file given on the command line, and writes a
013   * {@code .java-parsed} file that should be identical.
014   */
015  public static void main(String args[]) {
016    JavaParser parser = null;
017    Node root;
018    if (args.length == 0) {
019      System.out.println("Java Parser Version 1.1:  Reading from standard input . . .");
020      parser = new JavaParser(System.in);
021    } else {
022      if (args.length == 1) {
023        System.out.println("Java Parser Version 1.1:  Reading from file " + args[0] + " . . .");
024        try {
025          parser = new JavaParser(new java.io.FileInputStream(args[0]));
026        } catch (java.io.FileNotFoundException e) {
027          System.out.println("Java Parser Version 1.1:  File " + args[0] + " not found.");
028          System.exit(1);
029        }
030      } else {
031        System.out.println("Java Parser Version 1.1:  Usage is one of:");
032        System.out.println("         java JavaParser < inputfile");
033        System.out.println("OR");
034        System.out.println("         java JavaParser inputfile");
035        System.exit(1);
036      }
037    }
038    try {
039      root = parser.CompilationUnit();
040      root.accept(
041          new DepthFirstVisitor() {
042            public void visit(NodeToken n) {
043              //System.out.println("{" + ((n.getParent()).getClass()).getName() +"}: " + n.tokenImage);
044            }
045          });
046
047      try {
048        Writer output = new FileWriter(args[0] + "-parsed");
049        root.accept(new TreeFormatter(2, 80));
050        root.accept(new TreeDumper(output));
051        output.close();
052      } catch (IOException e) {
053        System.err.println(
054            "While trying to write file "
055                + args[0]
056                + "-parsed"
057                + ", an IOException "
058                + "occurred. Here is the message and stack trace: "
059                + e.getMessage());
060        e.printStackTrace();
061        throw new Error(e);
062      }
063
064      System.out.println("Java Parser Version 1.1:  Java program parsed successfully.");
065    } catch (ParseException e) {
066      System.out.println(e.getMessage());
067      System.out.println("Java Parser Version 1.1:  Encountered errors during parse.");
068      System.exit(1);
069    }
070  }
071}