Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can non-associative operators like "<" be specified in ANTLR4 grammars?

Tags:

antlr4

In a rule expr : expr '<' expr | ...; the ANTLR parser will accept expressions like 1 < 2 < 3 (and construct left-associative trees corrsponding to brackets (1 < 2) < 3.

You can tell ANTLR to treat operators as right associative, e.g.

expr : expr '<'<assoc=right> expr | ...; 

to yield parse trees 1 < (2 < 3).

However, in many languages, relational operators are non-associative, i.e., an expression 1 < 2 < 3 is forbidden. This can be specified in YACC and its derivates.

Can it also be specified in ANTLR? E.g., as expr : expr '<'<assoc=no> expr | ...;

I was unable to find something in the ANTLR4-book so far.

like image 240
user2818521 Avatar asked Sep 26 '13 08:09

user2818521


1 Answers

How about the following approach. Basically the "result" of a < b has a type not compatible for another application of operator < or >:

expression
    :   boolExpression
    |   nonBoolExpression
    ;

boolExpression
    :   nonBoolExpression '<' nonBoolExpression
    |   nonBoolExpression '>' nonBoolExpression
    |   ...
    ;

nonBoolExpression
    :   expression '*' expression
    |   expression '+' expression
    |   ...
    ;

Although personally I'd go with Darien and rather detect the error after parsing.

like image 148
Onur Avatar answered Oct 25 '22 06:10

Onur