Bananasmoothii
Bananasmoothii

Reputation: 170

ANTLR4: what design pattern to follow?

I have a ANTR4 rule "expression" that can be either "maths" or "comparison", but "comparison" can contain "maths". Here a concrete code:

expression
    : ID
    | maths
    | comparison
    ;

maths
    : maths_atom ((PLUS | MINUS) maths_atom) ? // "?" because in fact there is first multiplication then pow and I don't want to force a multiplication to make an addition
    ;

maths_atom
    : NUMBER
    | ID
    | OPEN_PAR expression CLOSE_PAR
    ;

comparison
    : comp_atom ((EQUALS | NOT_EQUALS) comp_atom) ?
    ;

comp_atom
    : ID
    | maths // here is the expression of interest
    | OPEN_PAR expression CLOSE_PAR
    ;
    

If I give, for instance, 6 as input, this is fine for the parse tree, because it detects maths. But in the ANTLR4 plugin for Intellij Idea, it mark my expression rule as red - ambiguity. Should I say goodbye to a short parse tree and allow only maths trough comparison in expression so it is not so ambiguous anymore ?

Upvotes: 1

Views: 144

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726569

The problem is that when the parser sees 6, which is a NUMBER, it has two paths of reaching it through your grammar:

 expression - maths - maths_atom - NUMBER

or

 expression - comparison - comp_atom - NUMBER

This ambiguity triggers the error that you see.

You can fix this by flattening your parser grammar as shown in this tutorial:

start
    : expr | <EOF>
    ;
    
expr
    : expr (PLUS | MINUS) expr         # ADDGRP
    | expr (EQUALS | NOT_EQUALS) expr  # COMPGRP
    | OPEN_PAR expression CLOSE_PAR    # PARENGRP
    | NUMBER                           # NUM
    | ID                               # IDENT
    ;

Upvotes: 1

Related Questions