About Me

I am a computer programmer. I do programming professionally and for a laugh.

Technical stuff on programming, java, DSLs, etc...

Tuesday, 30 March 2010

Another DSL Framework - tutorial 2

The BNF like language we used to define the calculator is a language created in the Language Processor itself. Actually you can define your language in the object model. This is what you would do to define E -> E + E

            Terminal terminal = digit();
            Terminal plus = new RegExpTerminal("\\+");
            Grammer additonGrammer = new Grammer();
            NonTerminal expr = new NonTerminal("E");
            NonTerminal rest = new NonTerminal("T");
            Production exprProd = new Production(new ProductionElement[] { terminal, rest }, new Semantic() {
                  public Object evaluate(List<Object> childEvals) { 
                        if (childEvals.get(1).equals(Collections.EMPTY_LIST)) 
                              return childEvals.get(0); 
                        return new Integer(((Integer) childEvals.get(0)).intValue() + ((Integer) childEvals.get(1)).intValue()); 
            Production restProd = new Production(new ProductionElement[] { plus, expr }, new Semantic() { 
                  public Object evaluate(List<Object> childEvals) { 
                        return childEvals.get(1); 
            rest.addProduction(new EmptyProduction(){ 
                  public Object evaluate(List childResults) {
                        return new Integer(0);

The grammar is actually defined as

E -> TE'
E' -> +TE' | e
as the Language Processor is a recursive descent parser and you need to left factorize your grammar to consume tokens as you recurse.

This is a boring subject and the BNF like grammar sorts it out for you. If anyone is really interested, buy me a beer, I will tell you all about it.

No comments:

Post a Comment