简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM