How to separate precedence and expression in ANTLR4

I've specified precedence and associativity like this:

expr
    : LB expr RB
    | <assoc=right> (SUB | NOT) expr
    | expr op=(MULTI | DIV | MOD | AND) expr      
    | expr op=(ADD | SUB | OR) expr          
    | expr comparator expr    
    | expr op=(ANDTHEN | ORELSE) expr                   
    | INTLIT                                
    ;

But it also works on ( 1 and 2 ). I want to represent the expression only for integer (i.e., only work on + - * /) or boolean (AND OR). How can I do that?

Upvotes: 0

Views: 58

Answers (1)

sepp2k
sepp2k

Reputation: 370162

That's not a precedence issue, it's a type issue and should thus be handled by the type checker.

You might be tempted to separate your grammar into rules such as integerExpression and booleanExpression and it's certainly possibe to create a grammar that rejects 1 and 2 this way. But this approach makes your grammar needlessly complicated and will reach its limits once your language becomes even slightly more powerful. When you introduce variables, for example, you'd want to allow a and b if and only if a and b are both Boolean variables, but that's not something you can tell just by looking at the expression. So in that scenario (and many others), you'll need Java (or whichever language you're using) code to check the types anyway.

So in conclusion, you should leave your grammar as-is and reject 1 and 2 in the type checker.

Upvotes: 1

Related Questions