[antlr-interest] Creating a simple expression language

Ivar Refsdal refsdal.ivar at gmail.com
Sun Nov 23 14:20:27 PST 2008


I'm also a newbie (thus everything could be wrong) so I can't help that 
much... But anyway:
Here is a edited Expr grammar:

grammar Expr;

options {
    k = 1;

prog    :    (stat {System.out.println($stat.tree.toStringTree());} )+ ;

stat    :    expr    -> expr;
expr    :    multExpr (('+' ^  | '-'^) multExpr)*
multExpr    :    atom ('*'^ atom)*
atom    :    INT
    |    function
    /* We don't want nodes for the parentheses */
    |    '('! expr ')'!

/* We don't want nodes for the paretheses or commas. */   
function    :    fname^ '('! variable_list? ')'! ;

    :    (variable ( ','! variable )* )

variable    :    FUNCNAME;

fname    :    FUNCNAME;
FUNCNAME    :    ( 'a' .. 'z' | 'A' .. 'Z')+  ;
INT    :    '0' .. '9'+ ;
WS    :    ( ' ' | '\t' | '\n' | '\r' ) + {skip(); };

It makes it a little bit easier to debug..
Lexer rules (upper case) will not be included/"named" in the parse tree, 
but parser rules  (lower case) will, so it's easier to have an overview 
like this.

Note also: You don't need to bother with using WS i parser rules as they 
will already have
been skipped on the lexer level.

Here is a screenshot of debugging the input with (almost) the orginal 
showing the parse tree:

The input was:

So as you can see it's not quite generating what you're expecting.
The same holds for using the interactive interpreter, but I prefer the 
debugger at the moment.

It works more or less like expected with the revised grammar..

Also, are you sure you want k=1? Check out the backtrack=true option 
also, that helped me
for grammars that wasn't easily determined (multiple alternatives). If 
you ever run into that.

I've read just a little bit of the Dragon book (new edition), that 
helped me a little bit..

Well, good luck,

(first post, hope this works.)

More information about the antlr-interest mailing list