options { LOOKAHEAD=1; } PARSER_BEGIN(Q2) public class Q2 { /*** Main routine - call parser, print answer ***/ public static void main(String args[]) throws ParseException { int decimal_val = 0; Q2 parser = new Q2(System.in); try { decimal_val = parser.bcd_num(); System.out.println("Decimal Equivalent:" + decimal_val); } catch (ParseException x) { System.out.println("Exiting due to parse error."); throw x; } } } PARSER_END(Q2) SKIP : /*** Ignoring spaces/tabs ***/ { " " | "\t" } /*************************/ /***** GRAMMAR RULES *****/ /*************************/ int bcd_num() : { int digit_val=0; int scale=1; // Power of 10 to raise number to... int ans=0; } { ( digit_val=bcd_digit() { ans = ans + (digit_val * scale); scale = scale * 10; } )+ ( | "\n" | "\r") { return ans; } } int bcd_digit() : { int n1, n2, n3, n4; } { // Four binary numbers - n1=numeral() n2=numeral() n3=numeral() n4=numeral() { int val = (n1*8) + (n2*4) + (n3*2) + (n4); if (val > 9) { // A little semantic checking... System.err.println("BCD number too large: " +n1+n2+n3+n4+ " is " + val); throw new ParseException(); } else return val; } } int numeral() : {} { "0" { return 0; } | "1" { return 1; } }