G -> S $$ S -> A M | A M -> S A -> a E | b A A | a E -> a B | B A B -> b E | a B B | b
For each production in the above grammar for declarations, list
You should still use an interactive interpreter that reads lines one at a time. Instead of having your code parse the input it should now call your Antlr parser to parse the input. Your Antlr parser should build an expression tree as it recognizes productions and then store the expression tree in an appropriate instance variable in your expression tree class.
You will need to create a new instance of your parser for each line of input since the parser wants to read to the end of the input in order to fully recognize a string. To get the parser and lexer to read from your string instead of from stdin you will need to pass an instance of a StringReader class to your lexer. Here is an example of how your interactive interpreter might look (you will need to insert this method into a driver class):
void execute() { java.util.Scanner input = new java.util.Scanner(System.in); PrefixParser expParser; PrefixLexer lex; Exp tree; // My top-level class for expression trees was // called Exp while (true) { try { System.out.print(">>> "); // 1. Read a line of input, wrap it in a StringReader object, and // wrap the StringReader object in an ANTLRReaderStream object. // 2. Finally create a lexer for that one line of input. // 3. Note that nextLine() removes the newline character so we // must add it back so that our parser can determine when // an expression has legitimately ended lex = new PrefixLexer(new ANTLRReaderStream(new StringReader(input.nextLine() + "\n"))); CommonTokenStream tokens = new CommonTokenStream(lex); // Parse the one line of input and return an expression tree expParser = new PrefixParser(tokens); // my grammar had pgm as the start non-terminal tree = expParser.pgm(); // Evaluate the expression tree System.out.printf("%3.2f\n", tree.eval()); } catch (RecognitionException e) { e.printStackTrace(); } catch (java.util.NoSuchElementException e) { break; } catch (Exception e) {System.out.println(e);} } }
When you have completed this exercise your code should be much simpler than it was when you hand-parsed each statement.
Hints
You should submit a jar file named hw6.jar that contains the following files:
Main-Class: Your Problem 8 Driver Class Name Class-Path: /usr/share/java/antlr3.jar