Eternal21
Eternal21

Reputation: 4664

How to change ANTLR boolean precedence?

I have the following antler g file that works fine:

grammar BoolTest;

LEFT_PAREN : '(' ;
RIGHT_PAREN : ')' ;
AND : 'AND';
OR : 'OR';
WHITESPACE  :   ( ' '
        | '\t'
        | '\r'
        | '\n'
        ) {$channel=HIDDEN;}
    ;    
WORD :  (~( ' ' | '\t' | '\r' | '\n' | '(' | ')' ))*;

expression : and_expression;
and_expression : or_expression (AND^ or_expression)*;
or_expression : atom (OR^ atom)*;
atom : WORD | LEFT_PAREN! expression RIGHT_PAREN!;

The problem is that I need AND to have a higher precedence than OR. So I modified the last four lines as the following:

expression : or_expression;
or_expression : and_expression (OR^ and_expression)*;
and_expression : atom (AND^ atom)*;
atom : WORD | LEFT_PAREN! expression RIGHT_PAREN!;

But for some reason it doesn't work properly. And the following expression:

a AND b OR c

produces the following tree, which is completely missing the OR branch:

enter image description here

What am I doing wrong?

Upvotes: 1

Views: 183

Answers (1)

Eternal21
Eternal21

Reputation: 4664

Found the bug, it was actually a problem with the me using ANTLRWorks IDE. When you run debug mode, and it asks you for text, one of the drop-downs states Start Rule:. It was set to 'and_expression'. After I changed it to just 'expression', the program works fine, and I get the following tree:

enter image description here

Upvotes: 1

Related Questions