PARSER_BEGIN(Q3) public class Q3 { public static void main(String args[]) throws ParseException { Q3 parser = new Q3(System.in); try { String c_prog = parser.prog(); if (c_prog != null) System.out.println(c_prog); } catch (ParseException x) { System.out.println("Exiting."); throw x; } } } PARSER_END(Q3) /*** Ignoring whitespace ***/ SKIP : { " " | "\n" | "\r" | "\f" | "\t" } /******************/ /***** TOKENS *****/ /******************/ TOKEN : /* Keywords NB - this must be placed before defn of identifiers */ { < WHILE : "while" > | < DO : "do" > | < BEGIN : "begin" > | < END : "end" > | < ASSIGN : ":=" > } TOKEN : { < IDENT : ()+ > | < #LETTER : ["a" - "z", "A" - "Z"] > } TOKEN : /* Punctuation */ { < SEMI : ";" > } /*************************/ /***** GRAMMAR RULES *****/ /*************************/ /***** Program *****/ String prog() : { String ans=null; } { ans=stat() { return ans; } } /***** Statements *****/ String stat() : { String statement=null, expression=null; Token id; } { statement=statseq() { return "{ " + statement + " }"; } | expression=expr() statement=stat() { return "while (" + expression + ") " + statement; } | id= expression=expr() { return id.image + " = " + expression + ";"; } } /***** Sequence of statements *****/ String statseq() : { String statement=null, rest=null; } { statement=stat() [ rest=statseq() ] { if (rest==null) return statement; else return statement + rest; } } /***** Expressions *****/ String expr() : {} { { return new String(token.image); } }