The following ANTLR grammar:
parse
: exp EOF
;
exp
: add_exp
;
add_exp
: mul_exp ('+' mul_exp)*
;
mul_exp
: atom ('*' atom)*
;
atom
: Number
| '(' exp ')'
;
Number
: 'a'..'z'
;
parses the input a + b * c + d + e
as:
As you can see, the mul_exp
is the furthest away in the tree and (using an appropriate "walk" through your tree) will be evaluated first.
and the input a + b * (c + d) + e
is parsed as:
The images were generated with ANTLRWorks.
EDIT:
A tool like ANTLRWorks makes debugging a grammar a breeze! For example, if I click on the atom
rule in the grammar above, the following is automatically generated and displayed at the bottom of the screen:
Of course, that rule isn't complex at all, but when you do get to work with more complex rules, it's pretty darn easy to visualize them like that.
HTH.