yegor256
yegor256

Reputation: 105133

How to avoid post-token code execution in ANTLR, when token is absent?

This is my ANTLR script:

greeting:
  'hello'
  NAME
  { /* do something with $NAME.text */ }
  ;

This input causes an NPE because NAME is null:

hello

I understand that I can check whether $NAME is not null and only then do my manipulations with $NAME.text, but I have that problem in many places in the script. Should I always do if ($NAME != null) or maybe there is some other more elegant mechanism?

Upvotes: 0

Views: 99

Answers (1)

Sam Harwell
Sam Harwell

Reputation: 99949

In ANTLR 4, you should relocate the embedded actions to a listener or visitor which you separately execute after the parsing phase is complete. You can use the Parser.getNumberOfSyntaxErrors method prior to starting that phase to see if any parse errors occurred, and if so, stop processing at that point.

This covers all actions associated with the parser at once and results in a much cleaner overall code structure.

Upvotes: 1

Related Questions