What is JavaScript AST, how to play with it?

2019-01-16 07:49发布

问题:

Abstract Syntax Tree.. I always heard that compile to SpiderMonkey AST on Github.
So, is that a actual standard of JS syntax tree? And there's V8, is V8 using the same kind of AST?

How can I play with that?

回答1:

SpiderMonkey offers the parser api. This is probably the easiest way to get your hands on the syntax objects.

There's also open js-js parsers like Esprima (which is ECMAScript, really, but it's right up the alley)



回答2:

1.You can take a look at AST explorer. An online tool to explore the ASTs generated by more than 10 parsers. It is a good tool to learn AST tree of a language.
AST explorer source at Github.com.


2.Also you can paste your js code into JavaScript AST visualizer and click "show ast" button, you will see the AST visully.

demo js code:

function foo(d) {
  d += 3;
    return d+999
}
function bar(d) {
    return d*100
}



回答3:

If you would like to try out the acron parser from professor Marijnh https://github.com/marijnh try out this link: https://astexplorer.net/

This is a tiny, fast JavaScript parser, written completely in JavaScript.

The above-mentioned JavaScript AST visualizer uses Esprima engine and has been also written in JavaScrpt.

JavaScript dominates in parsing AST because JavaScript engines are super optimized today. https://en.wikipedia.org/wiki/JavaScript_engine

SpiderMonkey AST standard of JS syntax tree? Is V8 using the same kind of AST?

Both of these web browser engines do have AST processing inside written in C++. This is why JavaScrpt code will run fast in most cases except for eval.