Mahes
Mahes

Reputation: 57

Visitor and Listener at a time in Antlr 4

In Antlr 4 we can call our visitor or Listener class separately. But I want to call it at a time, I mean when i visit a Tree using Visitor My Listener class also needs to get executed. Look at my sample code below MXLVisitor.

ANTLRFileStream reader = new ANTLRFileStream(input.toString());
        Xml_formatLexer lexer = new Xml_formatLexer(reader);
        Xml_formatParser parser = new Xml_formatParser(new CommonTokenStream(lexer));
        ParseTree tree = parser.main_rule();
        MXLVisitor visitor = new MXLVisitor(xmlBuilder, pojo);

        Value result = visitor.visit(tree);

        ParseTreeWalker walker = new ParseTreeWalker(); // create standard walker
        MXLlistener extractor = new MXLlistener();
        walker.walk(extractor, tree);

while I run this above code It obviosly executed visit(tree) method first and then walker.walk(extractor, tree) as per my coding .

My Question is Is it possible to call both the methods at a time?

Upvotes: 1

Views: 1061

Answers (2)

Matthew
Matthew

Reputation: 11347

I've noticed that the presto project uses a Listener and a Visitor at the same time, exactly for the usecase you describe!

The rough idea is:

MyBaseParser parser = new MyBaseParser(tokenStream);

//First setup the listener.
parser.addParseListener(new MyListener());
ParseTree tree = parser.main_rule();

//Then setup the visitor
MyVisitor visitor = new MyVisitor(...);
Value result = visitor.visit(tree);

Here's their code: https://github.com/prestodb/presto/blob/8d5d5e67e1e2276e9e2a1fc02f471e6d0a020c89/presto-parser/src/main/java/com/facebook/presto/sql/parser/SqlParser.java#L138

Upvotes: 2

Bart Kiers
Bart Kiers

Reputation: 170158

My Question is Is it possible to call both the methods at a time?

No, you either use a listener or a visitor. Not both at the same time.

Upvotes: 0

Related Questions