Search code examples
antlrantlr3antlrworks

Antlr error 'no viable alternative at character'


I am using the Objective C grammar available here, and trying to parse this code:

int main()
{   
    int k=0;
}

this is an objective c code and it should get parsed but it is giving me the following errors when i call the function translation_unit. errors are :

line 1:0 no viable alternative at character 'main'
line 1:0 no viable alternative at character '('
line 1:0 no viable alternative at character ')'

Solution

  • It goes wrong because the rule direct_declarator:

    direct_declarator 
     : identifier declarator_suffix*
     | '(' declarator ')' declarator_suffix* 
     ;
    

    mandates that there should be something inside the parenthesis of the main function. But if you make that optional:

    direct_declarator 
     : identifier declarator_suffix*
     | '(' declarator? ')' declarator_suffix* 
     ;
    

    I am pretty sure other problems will arise. To be frank, that grammar is pretty lousy: I wouldn't use it if I were you. And no, I don't know of a better one :). Because the grammar is posted on the antlr-site does not mean it's a proper grammar. It's posted on the Wiki where anyone can post their work: keep that in mind when using stuff from it.