A Listener is something you implement and is called by an ANTLR walker. You have to set up the walker, give it your parse tree, and your listener implementation.
A Visitor is just a class that you call yourself. The function you call corresponds with the relevant AST node and is named something like visitStatement
or visitProgram
. The name is based on the ANTLR grammar parser rule, or if you've given subrules names (using the #alternativeNameForThisSubrule
syntax), it is based on the name you give it. But it will have visit
prepended.
This is what tripped me up, because the examples I saw blithely used visit
as a standin for the actual function to use.
Either way, using a Visitor is completely manual.
var chars = new antlr4.InputStream(input)
var lexer = new FancyLexer(chars)
var tokens = new antlr4.CommonTokenStream(lexer)
var parser = new FancyParser(tokens)
parser.buildParseTrees = true
var tree = parser.block() // 'block' is the start rule
var visitor = new FancyVisitor()
return visitor.visitBlock(tree) // 'visitBlock' since that was the start rule