13/9/10

An API for parsing JavaScript

In new builds of the SpiderMonkey shell we’re introducing an experimental API for parsing JavaScript source code, which landed this week. For now, you have to download and build SpiderMonkey from source to use it, but hopefully we’ll include it in future versions of Firefox.

The parser API provides a single function:
Reflect.parse(src[, filename=null[, lineno=1]])

Reflect.parse takes a source string (and optionally, a filename and starting line number for source location metadata), and produces a JavaScript object representing the abstract syntax tree of the parsed source code, using the built-in parser of SpiderMonkey itself. Straightforward enough, but behind this simple entry point is a thorough API that covers the entirety of SpiderMonkey’s abstract syntax. In short, anything that SpiderMonkey can parse, you can parse, too. Developer tools generally need a parse tree, and JavaScript isn’t an easy language to parse. With this API, it becomes much easier to write tools like syntax highlighters, static analyses, style checkers, etc. And because Reflect.parse uses the same parser that SpiderMonkey uses, it’s guaranteed to be compatible.

Here’s a simple example:
js> var ast = Reflect.parse("obj.foo + 42");
js> var expr = ast.body[0].expression;
js> expr.left.property
({loc:null, type:"Identifier", name:"foo"})
js> expr.right
({
loc: {
source: null,
start: {
line: 1,
column: 10
},
end: {
line: 1,
column: 12
}
},
type: "Literal",
value: 42
})

Try it out, and feel free to give me feedback!

This entry was posted on Wednesday, August 25th, 2010 at 11:00 am and is filed under Announcements, SpiderMonkey. You can follow any comments to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

PS: SpiderMonkey Build Documentation Sphere: Related Content

No hay comentarios: