/* This wasn't part of the question, but it provides an interesting * contrast to the infix-to-prefix version... * Notice how here we don't have to store anything in a string as * we go along - instead we can just print it out directly, expression * by expression */ options { LOOKAHEAD=1; } PARSER_BEGIN(Q3post) public class Q3post { /*** Main routine - just call parser ***/ public static void main(String args[]) throws ParseException { Q3post parser = new Q3post(System.in); try { parser.inp_line(); System.out.flush(); } catch (ParseException x) { System.out.println("Exiting due to parse error."); throw x; } } } PARSER_END(Q3post) SKIP : /*** Ignoring spaces/tabs ***/ { " " | "\t" } TOKEN : { < NUMBER : ( ["0"-"9"] )+ > } /*************************/ /***** GRAMMAR RULES *****/ /*************************/ void inp_line() : {} { expr() ( | "\n" | "\r") } void expr() : {} { term() ( "+" term() { System.out.print("+ "); } )* } void term() : {} { factor() ( "*" factor() { System.out.print("* "); } )* } void factor() : {} { { System.out.print(token.image+" "); } | "(" expr() ")" }