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);
}
});
expr.addProduction(exprProd);
rest.addProduction(restProd);
rest.addProduction(new EmptyProduction(){
@Override
public Object evaluate(List childResults) {
return new Integer(0);
}
});
additonGrammer.addProductionElement(expr);
additonGrammer.addProductionElement(rest);
additonGrammer.addProductionElement(terminal);
The grammar is actually defined as
E -> TE'
E' -> +TE' | e
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.
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