How can I disambiguate the following rules?

146 views Asked by At

I am having trouble with a no viable alternative at input sqr( with the following rules.

function_invocation : ID LPAREN term (',' term)* RPAREN ;

function_signature : ID LPAREN ID (',' ID)* RPAREN ;

term : function_invocation #functionTerm
     | number              #numberTerm
     | string              #stringTerm
     | ID                  #idTerm
     ;

 ID : ('a'..'z')('a'..'z'|'A'..'Z'|'0'..'9'|'_')* ;

I use function_signature in other rules where I only want ID to be valid such as:

function_definition : function_signature '=>' expression (','NL expression)* '.'NL ;

should parse:

sqr(x) => x * x,
          x + 1.

And I use function_invocation where I want to allow more than just ID.

function_assignment : ID '=>' function_invocation ;

should parse:

z = sqr(3)

The problem is that ID is a valid term.

How do I tell ANTLR4 tell the different between the two?

1

There are 1 answers

0
Mephy On BEST ANSWER

Make it so function_signature can only be used when inside a function_definition. In other words, drop that rule altogether, and write

function_definition : ID '(' ID (',' ID)* ')' '=>' expression (',' NL expression)* '.' NL ;

This way, the => terminal can be used to avoid the ambiguity. Alternatively, just put the => terminal in the function_signature:

function_signature : ID '(' ID (',' ID)* ')' '=>' ;
function_definition : function_signature expression (',' NL expression)* '.' NL ;

Of course, I'm assuming here there's no other place in your grammar that allows a function_invocation followed by a =>, but that would probably make the whole language ambiguous.