Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 950
oskar132 Avatar asked Apr 03 '18 12:04

oskar132


2 Answers

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'.

like image 181
Dara Java Avatar answered Nov 12 '22 14:11

Dara Java


install @babel/generator

npm install --save-dev @babel/generator
const { default: generate } = require("@babel/generator");

Identifier(path) {
  console.log(generate(path.node).code); // code string
},


like image 21
januw a Avatar answered Nov 12 '22 14:11

januw a