javascriptcode-generationabstract-syntax-treeesprimababel-babylon

How can I transform a custom AST into JS code


I am currently generating a custom AST from a new language specification I have designed. This custom AST contains different nodes that I have designed with all the information I need in order to now generate JavaScript code. For example:

Say I have a customExpressionNode which I wish to translate into a JavaScript function which contains a couple of if conditions.

I am currently looking into libraries like Babylon and Esprima for generating a new Javascript AST from my Custom AST, but from what I've seen there is quite a lot of complexity in the AST that these libraries use. I would also like to avoid printing js code into a few files and then parsing and compiling them, so my question is:

Is there a better way of generating programmatically a JavaScript compliant AST that I can use to generate JavaScript code?


Solution

  • Something like this? https://github.com/estools/escodegen

    A simple example: the program

    escodegen.generate({
        type: 'BinaryExpression',
        operator: '+',
        left: { type: 'Literal', value: 40 },
        right: { type: 'Literal', value: 2 }
    })
    

    produces the string '40 + 2'.