Valerio Coretti
Valerio Coretti

Reputation: 177

ANTLR4 problem with balanced parentheses grammar

I'm doing some experiments with ANTLR4 with this grammar:

srule   
    :  '(' srule ')'
    | srule srule
    | '(' ')';

this grammar is for the language of balanced parentheses. The problem is that when I run antlr with this string: (()))(

This string is obviously wrong but antlr simply return this AST:

AST

It seems to stop when it finds the wrong parenthesis, but no error message returns. I would like to know more about this behavior. Thank you

Upvotes: 1

Views: 383

Answers (1)

Bart Kiers
Bart Kiers

Reputation: 170158

The parser recognises (())) and then stops. If you want to force the parser to consume all tokens, "anchor" your test rule with the EOF token:

parse_all
 : srule EOF
 ;

Btw, it's always a good idea to include the EOF token in the entry point (entry rule) of your grammar.

Upvotes: 2

Related Questions