Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I build an AST using ANTLR4? [duplicate]

I have an ANTLR3 grammar that builds an abstract syntax tree. I'm looking into upgrading to ANTLR4. However, it appears that ANTLR4 only builds parse trees and not abstract syntax trees. For example, the output=AST option is no longer recognized. Furthermore neither "AST" nor "abstract syntax" appears in the text of "The Definitive ANTLR4 reference".

I'm wondering if I'm missing something.

My application currently knows how to crawl over the AST produced by ANTLR3. Changing it to process a parse tree isn't impossible but it will be a bit of work. I want to be sure it's necessary before I start down that road.

like image 492
Peter C. Chapin Avatar asked Apr 04 '13 23:04

Peter C. Chapin


1 Answers

ANTLR 4 produces parse trees based on the grammar instead of ASTs based on arbitrary AST operators and/or rewrite rules. This allows ANTLR 4 to automatically produce listener and visitor interfaces that you can implement in the code using your grammar.

The change can be dramatic for users upgrading existing applications from version 3, but as a whole the new system is much easier to use and (especially) maintain.

like image 158
Sam Harwell Avatar answered Sep 21 '22 16:09

Sam Harwell