JavaScript parser in JavaScript [closed]

2019-01-02 17:27发布

I need to add some lightweight syntactic sugar to JavaScript source code, and process it using a JavaScript-based build system. Are there any open source JavaScript parsers written in JavaScript? And are they reasonably fast when run on top of V8 or a similar high-performance JavaScript implementation?

Thank you for any pointers you can provide!

9条回答
明月照影归
2楼-- · 2019-01-02 18:01

UglifyJS (JS compressor/beautifier in JavaScript) contains a complete JavaScript parser that exposes a simple API. It's heavily tested and used in some big projects (WebKit).

查看更多
刘海飞了
3楼-- · 2019-01-02 18:02

Crescent Fresh answered this question in the comments:

JSLint contains a JavaScript parser written in JavaScript. See JSlint by Douglas Crockford Around line 2712 begins the parser. JSLint is written to also handle html so you'd have to gloss over those parts

查看更多
一个人的天荒地老
4楼-- · 2019-01-02 18:04

https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API:

Recent builds of the standalone SpiderMonkey shell include a reflection of the SpiderMonkey parser, made available as a JavaScript API.

Note that this is only an API in JavaScript, the parser is C++.

查看更多
还给你的自由
5楼-- · 2019-01-02 18:09

The fastest Javascript parser in Javascript was esprima.

It also gives you

Sensible format for the abstract syntax tree (AST), compatible with Mozilla Parser API

查看更多
长期被迫恋爱
6楼-- · 2019-01-02 18:13

acorn is a really fast JavaScript parser written in JavaScript. It's even faster than esprima now. The results I got in Chrome form esprima's speed comparison page:

Source            Esprima    UglifyJS2    Traceur    Acorn
Underscore 1.4.1  15.1       23.8         14.2       7.6
Backbone 1.0.0    17.1       30.2         16.7       7.9
jQuery 1.9.1      241.1      247.2        125.4      81.4
Total             273.3 ms   301.2 ms     156.3 ms   96.9 ms

It's compatible with Mozilla's Parser API, so you can use escodegen to generate JavaScript from the parse trees.

查看更多
长期被迫恋爱
7楼-- · 2019-01-02 18:15

The only metacircular interpreter that I have seen implemented in JavaScript is the Narcissus Engine.

It was developed also by Brendan Eich, they used a lot of non-standard extensions that are specific to SpiderMonkey, I think it will not work on V8.

查看更多
登录 后发表回答