tRuEsAtM
tRuEsAtM

Reputation: 3668

Antlr4 grammar accepting a number of closing parentheses

I have my Antlr4 grammar file looking like the below,

myVal : '(' myVal ')'                                               
     | MINUS myVal                                                 
     | NOT myVal                                                   
     | '$' IDENTIFIER '(' ')'                                     
     | '$' IDENTIFIER '(' myVal (',' myVal)* ')'                    
     | myVal op=(MULT | DIVIDE) myVal                               
     | myVal op=(PLUS | MINUS) myVal                                
     | myVal op=(EQ | NE | GT | GTE | LT | LTE) myVal               
     | myVal IN '[' myVal (',' myVal)* ']'                           
     | myVal '~' myVal                                              
     | myVal op=(AND | OR) myVal                                    
     | myVal '?' myVal ':' myVal                                     
     | IF myVal THEN myVal (ELSEIF myVal THEN myVal)* ELSE myVal       
     | IDENTIFIER DOT IDENTIFIER                                  
     | STRINGLIT                                                  
     | '[' myVal (',' myVal)* ']'                                   
     | TRUE                                                       
     | FALSE                                                      
     | IDENTIFIER                                                 
     | NUMBER                                                     
     | INTEGER                                                    
     ;

I am expecting an error for the following condition, but instead, it doesn't give any.

(3+4)))

The last two parentheses should be errored out.

How can I achieve this?

Upvotes: 0

Views: 144

Answers (1)

Bart Kiers
Bart Kiers

Reputation: 170158

As already mentioned by Kaby as a comment: make sure you test the input with a rule that has the EOF (end of file) at the end.

If you test myVal with the input (3+4))), it will gladly parse (3+4) and leave the trailing 2 )'s in the token stream. After all, the input (3+4) is successfully parsed my the parser rule myVal.

So if you want to make sure all tokens are consumed, you need to tell the parser it has to consume all tokens until the EOF is encountered:

testMyVal
 : myVal EOF
 ;

Upvotes: 2

Related Questions