Search code examples
c#antlr4antlr4cs

Antlr4: Generating a Lisp s-expression style output from an expression


Referring to this link. It shows how to create a lisp style s-expression from any infix expression on Antlr3.

I am using Antlr4 and it doesn't seem to work on it.

Can someone please suggest me some way to achieve it ?

2x+3x^5 to (+ (* 2 x) (* 3 (^ x 5)))


Solution

  • Rewrite Rules are no longer available in ANTLR4 so you will have to do some other way. A possible approach is the the following:

    1. define a class hierarchy that models the entities of your (new) tree: this will be the object model of your alternative Abstract Syntax Tree;
    2. implement a visitor (or a listener) that traverses the parse tree created by the ANTLR4 parser and generates an instance of your AST;

    Here there's an example of this process