I am recently learning javacc releated concepts and writing tokens and parser. I was able to write a parser and it works perfectly when I run in the terminal using the commands javacc BusParser.jj //BusParser is file name javac *.java java Calculator //Calculator is parser name //and then type input
Here I am passing an input file when running the parser file
Here I want to know how to call this parser file from the another separate java class, so that we can verify the user input matches with the expected format.
The parser file is given here:
options { LOOKAHEAD=2; } PARSER_BEGIN(Calculator) public class Calculator { public static void main(String args[]) throws ParseException { Calculator parser = new Calculator(System.in); while (true) { parser.parseOneLine(); } } } PARSER_END(Calculator) SKIP : { " " | "r" | "t" } TOKEN: { < NUMBER: (<DIGIT>)+ ( "." (<DIGIT>)+ )? > | < DIGIT: ["0"-"9"] > | < EOL: "n" > } void parseOneLine(): { double a; } { a=expr() <EOL> { System.out.println(a); } | <EOL> | <EOF> { System.exit(-1); } } double expr(): { double a; double b; } { a=term() ( "+" b=expr() { a += b; } | "-" b=expr() { a -= b; } )* { return a; } } double term(): { double a; double b; } { a=unary() ( "*" b=term() { a *= b; } | "/" b=term() { a /= b; } )* { return a; } } double unary(): { double a; } { "-" a=element() { return -a; } | a=element() { return a; } } double element(): { Token t; double a; } { t=<NUMBER> { return Double.parseDouble(t.toString()); } | "(" a=expr() ")" { return a; } }
The java class
import java.io.ByteArrayInputStream; import java.io.InputStream; import java.nio.charset.StandardCharsets; public class test { static Calculator parser = null ; public static void main(String args[]) throws ParseException //static method { String toAnalyze = "2+3"; InputStream is = new ByteArrayInputStream(toAnalyze.getBytes()); if( parser==null) { parser = new Calculator(is); }else parser.ReInit(is) ; parser.parseOneLine(); } }
I tried simply running the java file. It was throwing the below exception
Therefore I want to know what the correct way of doing this, that is connecting the parser file and java file. Is there any build configurations to be added if it’s a gradle project?
Further, If using a gradle project, how to compile both javacc and java when entering gradle build and ./gradlew run
Advertisement
Answer
Your grammar requires an EOL after an expression, so try "2+3n"
.