/* Just an an extra, this program also leaves some keywords unchanged, * and handles commments and constants */ options { LOOKAHEAD=1; } PARSER_BEGIN(Q1) public class Q1 { /*** List of some common Prolog built-in predicates ***/ static String built_ins = "assert assertz bagof fail is module nl read repeat retract retractall see seen setof tell told true write"; /*** Main routine - just call parser ***/ public static void main(String args[]) throws ParseException { Q1 parser = new Q1(System.in); try { parser.prolog(); } catch (ParseException x) { System.out.println("Exiting due to parse error."); throw x; } } } PARSER_END(Q1) SKIP : /*** Ignoring spaces/tabs/newlines ***/ { " " | "\t" | "\n" | "\r" } SPECIAL_TOKEN : /* COMMENTS */ { | } TOKEN : /* Predicates and variables */ { < PRED : ["a" - "z"]()* > | < VAR : (["A" - "Z"]()*) | (["_"]()+) > | < #LETDIG : ["a" - "z", "A" - "Z", "_", "0"-"9"] > | < FSTOP : "." > } TOKEN : /* Some extra ones, just for fun */ { < STRING_CONST : "\""(~["\""])+"\"" > | < CHAR_CONST : "\'"(~["\'"])+"\'" > | < NUM_CONST : (["0"-"9"])+ > } TOKEN : /* Anything not recognised so far */ { < OTHER : ~[] > } /*************************/ /***** GRAMMAR RULES *****/ /*************************/ void prolog() : {} { ( tok() )+ } void tok() : {} { { if (built_ins.indexOf(token.image) != -1) // Is a built_in predicate System.out.print(token.image); else System.out.print("p"); } | { System.out.print("V"); } | { System.out.println("."); } | { System.out.print("S"); } | { System.out.print("C"); } | { System.out.print("N"); } | { System.out.print(token.image); } }