Antlr4 Listeners and Visitors - which to implement?

KevinY picture KevinY · Dec 21, 2013 · Viewed 15.3k times · Source

I'm reading "The Definitive Antlr 4 Reference" and get the idea in relation to how Listeners and Visitors work. The book explains particularly well how Listeners relate to SAX parsers and makes it obvious when methods are going to be called during the implementation of each. I can see also that listeners are quite good for transforming input to output but I would appreciate a short explanation/example as to when to use a Listener and when to use a Visitor (or should they both be used in certain cases?).

My particular intention is to create an interpreter (Cucumber-style / TinyBasic Interpreter with some custom calls) that will check for syntax errors and stop executing on an error from a custom function without recovering - would love to see a complete implementation of such a thing in antlr - if anyone happens to know of one.

Thanks in advance for any advice.

Answer

Evgeni Petrov picture Evgeni Petrov · Jun 10, 2015

Here is quote from the book that I think is relevant:

The biggest difference between the listener and visitor mechanisms is that listener methods are called by the ANTLR-provided walker object, whereas visitor methods must walk their children with explicit visit calls. Forgetting to invoke visit() on a node’s children means those subtrees don’t get visited.

In visitor pattern you have the ability to direct tree walking while in listener you are only reacting to the tree walker.