Search code examples
antlrgrammarxtext

rule has non-LL(*) decision due to recursive rule invocations


I have an error (like said in the title) with one rule that i dont know how resolve.

i have written the following rule :

FunctionArguments returns FunctionArgs::IFunctionArguments :
    FunctionArgumentsNormal
    | FunctionArgumentsForIter
    ;

FunctionArgumentsNormal returns FunctionArgs::IFunctionArguments :
    {FunctionArgs::FunctionArguments} args+=Expression (',' args+=Expression)* 
    | {FunctionArgs::FunctionArguments} argNames+=NamedArguments (',' argNames+=NamedArguments)*
    ;

FunctionArgumentsForIter returns FunctionArgs::IFunctionArguments :
    {FunctionArgs::FunctionArgumentsIterator} exp=Expression 'for' iterators=ForIterator
    ;

Could you help me to resolve it by left-factoring this expression or give any others solutions please ?


Solution

  • In a LL grammar you can have no left-recursion. The problem is that a LL parser can choose to make a derivation like this: FunctionArguments -> FunctionArgumentsNormal -> FunctionArguments -> FunctionArgumentsNormal ... Your grammar contains what is called indirect left recursion. You can find an example in this wikipedia-article which also contains a solution as to how you can fix it: Left-Recursion. A good place to start is by (I suppose you already have done this) writing your grammar in a very simple way without all the annotations and things included in your example. If you have the grammar on the simple form:

    S -> A | B
    B -> "terminal1" B
      |  b
    A -> a "terminal2"
    

    it is much easier to do the necessary rewriting.