Handling exception in antlr4 parser

Viewed 27

I have a grammar that should allow a parametrized 'cast' but not a parametrized 'literal'. This is just a way of saying:

  • VARCHAR(5) "Hello There" --> BAD
  • "Hello There"::VARCHAR(5) --> GOOD

My thought is actually that I should allow the literal parametrization within the antlr4 grammar, so that it can accurately be caught and provide a good error message, such as:

Direct literal parametrization is not supported, did you mean "Hello There"::VARCHAR(5)? If so, click here and we'll make the adjustment for you.

Or, should I just not allow it in my grammar rules at all? In other words, should the rule be:

literal_loose
  : TYPE ( "(" Params? ")" )? STRING_LITERAL
  ;

And the error messaging is done beyond that, or should the rule be:

literal_strict
  : TYPE STRING_LITERAL
  ;

My thought is the first way would be a much better experience, but then again, it's almost like "adding bad syntax" to the grammar just as a sort of work-around (unless maybe that's how production parsers work in the real world...).

0 Answers
Related