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

1

11

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.

Heterodox answered 26/9, 2013 at 8:26 Comment(2)
IANAGuru, but it may be that you can't (sanely) enforce it except by either (A) adding predicates/action-code to the grammar or (B) doing a post-parse validation step.Tenpins
Hmm, still no answer? Well, what would you do anyway if someone did put A<B<C? You make it sound like an unrecoverable flaw in the input. I'd post-process the parse-tree (with a listener) and generate an error whenever directly nested < operations are found.Tenpins
H
1

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.

Hal answered 10/4, 2014 at 12:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.