简体   繁体   中英

How to generate JavaScript code from AST in SpiderMonkey?

I am using SpiderMonkey for a project and I need it for 2 tasks:

  1. Getting AST node information given a JavaScript string.
  2. Writing JavaScript from an AST node.

The first task is accomplished by means of js Reflect.parse('var a = 13;'); which returns me the AST, fine!

From AST to JavaScript

The second task is what I need. I want to instruct js (or probably the Reflect object, I suppose) to take a node:

{
  type:"Program", 
  body:[
    {
      type:"VariableDeclaration", 
      kind:"var", 
      declarations:[
        {
          type:"VariableDeclarator", 
          id:{type:"Identifier", name:"a"}, 
          init:{type:"Literal", value:13}
        }
      ]
    }
  ]
}

And write down: var a = 13; .

How can I achieve this which is sort of a reverse process to Reflect.parse ? Thanks

If Spidermonkey hasn't got a built-in module to do this, you'll have to build one yourself.

All the details you need to do that are here: Compiling an AST back to source code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM