Giuseppe Santoro
Giuseppe Santoro

Reputation: 303

Source to source translation in Antlr4

I'm trying to translate PLSQL code to JavaScript code. I'm using Antlr4 with this grammar: https://github.com/developeron29/PLSQLParser.

I've used the listener to translate pieces of code, something like this:

@Override
public void enterBody(BodyContext ctx) {
    functionBody += "function " + funcName + "{\n;
}

@Override
public void exitBody(BodyContext ctx) {
    functionBody += "}\n;
}

...

It is working pretty good but the code is growing fast and it is becoming unmaintainable.

Is there a better/cleaner way to do this kind of translation?

Upvotes: 3

Views: 1012

Answers (1)

CoronA
CoronA

Reputation: 8075

The ANTLR-Listener approach is fine if you can translate the language elements one by one.

Alternatively you can consider the ANTLR-Visitor approach. I think is is suitable if you expect several compiler passes with different parse tree traversal Strategies, or different intermediate results:

  • code for one node must not be split between enter and exit
  • you can prune the parse tree or even construct an AST (the AST-Builder would be a Visitor)
  • You can easily delegate the evaluation of nodes to other parse tree visitors

Upvotes: 4

Related Questions