Testing JavaCC on a File?

60 Views Asked by At

So after I compile my code, I want it to read input from a file instead of the command line.

So instead of doing this:

javacc Ex.jj
javac *.java
java Ex "x+2"

I want to do this:

javacc Ex.jj
javac *.java
java test.txt

Where test.txt has this in it:

"x+4"
1

There are 1 best solutions below

0
Maurice Perry On

You can declare a class with a main method in your syntax file:

options {
    STATIC = false;
    IGNORE_CASE = false;
}

PARSER_BEGIN(Ex)
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.IOException;

public class Ex {
    public static void main(String[] args) {
        try (InputStream in = new FileInputStream(args[0])) {
            Ex parser = new Ex(in, "UTF-8");
            double r = parser.expr();
            System.out.println("Result: " + r);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}
PARSER_END(Ex)

...


SKIP : { " " | "\r" | "\n" | "\t" }

TOKEN: {
...
}

double expr(): {
}
{
    ...
}