Since your AND rule has the optional AND keyword, you must create an imaginary AND token and use the rewrite rule to βinsertβ this token into your tree. In this case, you cannot use ANTLR short-hand ^ root-operator. You will need to use the rewrite operator -> .
Your andExpression should look like this:
andExpression : (andnotExpression -> andnotExpression) (AND? a=andnotExpression -> ^(AndNode $andExpression $a))* ;
A detailed description of this (possibly critical) notation is given in chapter 7, section Rewrite Rules in Substrings , pages 173-174 ANTLR Final Reference from Terence Parr.
I checked a quick test to see if the grammar creates the correct AST with the new andExpression rule. After parsing the line cat dog "potbelly and pig" and FOO , the generated parser produced the following AST:
alt text http://img580.imageshack.us/img580/7370/andtree.png
Note that AndNode and Root are imaginary tokens .
If you want to learn how to create an AST image above, see this topic: Visualizing an AST Created Using ANTLR (.NET)
EDIT
When analyzing both one two three and (one two) three , the following AST is created:
alt text http://img203.imageshack.us/img203/2558/69551879.png
And when analyzing (one two) OR three , AST is created:
alt text http://img340.imageshack.us/img340/8779/73390353.png
which, apparently, is the right way in all cases.