Gabe Johnson
Gabe Johnson

Reputation: 1431

How to set up and invoke ANTLR4 Javascript Visitor

Can anybody explain or point me to a working example of an ANTLR4 Javascript Visitor implementation in use? The documentation for the ANTLR4 Javascript Target shows how to implement a Listener, but not a Visitor.

This question isn't about ANTLR grammars, or even the tool itself. I can use the tool to happily generate the visitor JS file. I just have no idea how to invoke it.

Upvotes: 4

Views: 2427

Answers (1)

Gabe Johnson
Gabe Johnson

Reputation: 1431

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

Upvotes: 5

Related Questions