/* We store the output expression in a string as it's built up, and then * print this out when we're finished parsing */ options { LOOKAHEAD=1; } PARSER_BEGIN(Q3pre) public class Q3pre { /*** Main routine - just call parser ***/ public static void main(String args[]) throws ParseException { Q3pre parser = new Q3pre(System.in); try { parser.inp_line(); System.out.flush(); } catch (ParseException x) { System.out.println("Exiting due to parse error."); throw x; } } } PARSER_END(Q3pre) SKIP : /*** Ignoring spaces/tabs ***/ { " " | "\t" } TOKEN : { < NUMBER : ( ["0"-"9"] )+ > } /*************************/ /***** GRAMMAR RULES *****/ /*************************/ void inp_line() : { String e; } { e=expr() ( | "\n" | "\r") { System.out.println(e); } } String expr() : { String t1, t2; } { t1=term() ( "+" t2=term() { t1="+ "+t1+t2; } )* { return t1; } } String term() : { String f1, f2; } { f1=factor() ( "*" f2=factor() { f1="* "+f1+f2; } )* { return f1; } } String factor() : { String e; } { { return (token.image+" "); } | "(" e=expr() ")" { return e; } }