D Template based paser generator in 137 loc

Chris Nicholson-Sauls ibisbasenji at gmail.com
Thu Jan 4 20:17:57 PST 2007


BCS wrote:
> This is a totaly template based system. No external utilities are 
> needed. (* the 137 loc is after removal of all unneeded line)
> 
> Here is a slightly compressed use case:
> 
> struct set
> {
> /******* action code ********/
> static PObject Action(char[] string : "MULTIPLY")(PObject[3] set)
>    {...}
> static PObject Action(char[] string : "SUM"     )(PObject[3] set)
>    {...}
> static PObject Action(char[] string : "PASS"    )(PObject[1] set)
>    {...}
> 
> /******** Terminal code *********/
> static PObject Terminal(char[] name : "NUM")(IParser p)  {...}
> static PObject Terminal(char[] name : "PLUS")(IParser p) {...}
> static PObject Terminal(char[] name : "TIMES")(IParser p){...}
> 
> // "ADD" indecates the root rule
> 
> mixin Parser!("ADD",
>     "PRIMARY:PASS/NUM;
>      MUL:MULTIPLY/PRIMARY TIMES MUL|PASS/PRIMARY;
>      ADD:SUM/MUL PLUS ADD|PASS/MUL;");
> }
> 
> void main()
> {
>    auto a = new ExpGrammer;
>    a.data = "1 + 3 * 4 + 5 * 5 ";
> 
>    Value v = cast(Value)set.Parser(a);
> 
>    assert(v !is null);
>    writef("%d\n", v.value);
> }
> 
> 
> full example here:
> 
> http://www.webpages.uidaho.edu/~shro8822/exp_grammer.d
> 
> full code here:
> 
> http://www.webpages.uidaho.edu/~shro8822/dparse.d

Quite impressive!  Find a way to implement optional/repeated items, and grouping, and 
you've got one heck of a tool there.  (It's useful now, mind you, for simple grammars.)

-- Chris Nicholson-Sauls



More information about the Digitalmars-d-announce mailing list