Search code examples
antlrantlrworks

ANTLR decision can match input such as "ID ID" using multiple alternatives


I am having a problem with the disambiguation of this parser. I would like to mention that i am using antlrworks 1.4.3(it's a must i use it, homework assignment). I also must not use backtrack=true

It should match inputs like

main Int a, Char b, MyClass c -> Int : 
   expr ';' 
   .
   .
   .
   expr ';'
end';' 

I also comented the parser after ':' because this problem did not let me generate the code

program 
:   classDef+ -> ^(PROGRAM classDef+)
;

classDef 
:  CLASS name=ID (INHERITS parent=ID)? classBlock* END ';' -> 
    ^(CLASS $name ^(INHERITS $parent)? classBlock*)
;

classBlock
: VAR assigmentBlock* END ';'-> ^(VAR assigmentBlock*) 
| methodDecl  -> ^(METHOD methodDecl)
;

methodDecl
//: name=ID methodVar* ('->' type=ID)? ':' methodBlock* END ';'
//  -> ^($name methodVar* ^(RETURN $type) methodBlock*)
: name=ID methodVar* -> ^($name methodVar*)
;

methodVar
: type=ID  name=ID ','? -> ^(PARAMS $type $name)
;

This is what antlrworks shows antlrworks syntax diagram

If anyone could help me i would be much obliged.


Solution

  • Don't do:

    methodDecl
     : name=ID methodVar* ('->' type=ID)? ':' methodBlock* END ';'
     ;
    
    methodVar
     : type=ID  name=ID ','?
     ;
    

    rather do:

    methodDecl
     : name=ID (methodVar (',' methodVar)*)? ('->' type=ID)? ':' methodBlock* END ';'
     ;
    
    methodVar
     : type=ID  name=ID
     ;
    

    I.e. the comma should be mandatory, not optional as you defined it did.