/******************************* ***** SECTION 1 - OPTIONS ***** *******************************/ options { JAVA_UNICODE_ESCAPE = true; } /********************************* ***** SECTION 2 - USER CODE ***** *********************************/ PARSER_BEGIN(SLPParser) public class SLPParser { public static void main(String args[]) { SLPParser parser; if (args.length == 0) { System.out.println("SLP Parser: Reading from standard input . . ."); parser = new SLPParser(System.in); } else if (args.length == 1) { System.out.println("SLP Parser: Reading from file " + args[0] + " . . ."); try { parser = new SLPParser(new java.io.FileInputStream(args[0])); } catch (java.io.FileNotFoundException e) { System.out.println("SLP Parser: File " + args[0] + " not found."); return; } } else { System.out.println("SLP Parser: Usage is one of:"); System.out.println(" java SLPParser < inputfile"); System.out.println("OR"); System.out.println(" java SLPParser inputfile"); return; } try { parser.Prog(); System.out.println("SLP Parser: SLP program parsed successfully."); } catch (ParseException e) { System.out.println(e.getMessage()); System.out.println("SLP Parser: Encountered errors during parse."); } } } PARSER_END(SLPParser) /***************************************** ***** SECTION 3 - TOKEN DEFINITIONS ***** *****************************************/ TOKEN_MGR_DECLS : { static int commentNesting=0; } SKIP : /*** Ignoring spaces/tabs/newlines ***/ { " " | "\t" | "\n" | "\r" | "\f" } SKIP : /* COMMENTS */ { "/*" { commentNesting++; } : IN_COMMENT } SKIP : { "/*" { commentNesting++; } | "*/" { commentNesting--; if (commentNesting == 0) SwitchTo(DEFAULT); } | <~[]> } TOKEN : /* Keywords and punctuation */ { < SEMIC : ";" > | < ASSIGN : ":=" > | < PRINT : "print" > | < LBR : "(" > | < RBR : ")" > | < COMMA : "," > | < PLUS_SIGN : "+" > | < MINUS_SIGN : "-" > | < MULT_SIGN : "*" > | < DIV_SIGN : "/" > } TOKEN : /* Numbers and identifiers */ { < NUM : ()+ > | < #DIGIT : ["0" - "9"] > | < ID : ()+ > | < #LETTER : ["a" - "z", "A" - "Z"] > } TOKEN : /* Anything not recognised so far */ { < OTHER : ~[] > } /*************************** * SECTION 4 - THE GRAMMAR * ***************************/ void Prog() : {} { Stm() } void Stm() : {} { (SimpleStm() [ Stm()] ) } void SimpleStm() : {} { (Ident() Exp()) | ( ExpList() ) } void Exp() : {} { (SimpleExp() [BinOp() Exp()] ) } void SimpleExp() : {} { IdExp() | NumExp() | ( Stm() Exp() ) } void Ident() : {} { } void IdExp() : {} { } void NumExp() : {} { } void ExpList() : {} { (Exp() [ ExpList()] ) } void BinOp() : {} { | | | }