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 */ { < CASE : "case" > | < OF : "of" > | < END : "end" > | < ASSIGN : ":=" > } TOKEN : { < IDENT : ()+ > | < #LETTER : ["a" - "z", "A" - "Z"] > } TOKEN : /* Punctuation */ { < SEMI : ";" > | < COLON : ":" > } /*************************/ /***** GRAMMAR RULES *****/ /*************************/ /***** Program *****/ String prog() : { String ans=null; } { ans=stat() { return ans; } } /***** Statements *****/ String stat() : { String expression=null, caselist=null; Token id; } { expression=expr() caselist=caselist() { return "switch (" + expression + ") { " + caselist + "}"; } | id= expression=expr() { return id.image + " = " + expression + ";"; } } /***** Sequence of statements *****/ String caselist() : { String cas=null, rest=null; } { cas=cas() [ rest=caselist() ] { if (rest==null) return cas; else return cas + rest; } } String cas() : { Token id; String stat; } { id= stat=stat() { return "case " + id.image + " : " + stat + " break; "; } } String expr() : {} { { return new String(token.image); } }