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.

Robert
  • 5,278
  • 43
  • 65
  • 115
user2818521
  • 111
  • 3
  • 1
    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. – Darien Sep 27 '13 at 01:22
  • 1
    Hmm, still no answer? Well, what would you do anyway if someone **did** put A – Darien Oct 08 '13 at 22:46

1 Answers1

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.

Community
  • 1
  • 1
Onur
  • 5,017
  • 5
  • 38
  • 54