About Talks Articles

JavaScript syntax tree visualization with Esprima

2 min read

One little feature I added to Esprima parser demo was syntax tree visualization (using YUI TreeView). While it is already possible to see the JSON version of the parsed AST, often a much more visual representation improves the syntax analysis workflow. It is also more educational. An example code that follows:

answer = 42

will produce this view:

Neat, isn’t it? Since Esprima AST is compatible to Mozilla Reflect API, which also uses the same terminologies as in the official ECMAScript specification, this makes it easy to follow if you learn the language grammar.

Even though Esprima only parses the code and does not actually evaluate it, the tree version of the syntax can be useful to decipher a mysterious construct. Take a look at something that Stoyan Stefanov tweeted some time ago:

{1 + ""} + 10;

Pasting the snippet into Esprima parser demo yields (make sure you tick the raw checkbox):

That should explain a lot. Apparently here the curly braces have nothing to do with an object literal, which what people usually expect, but it’s just a simple block statement. The code can be treated as two statements, the block statement is the first and another expression statement follows.

Another tweet from Joe Armstrong (of Erlang fame):

"a" + + + + 10

This did happen because he missed the two +’s in a row. From the parse tree, this is easy to spot. Once we collapse the whole unary subexpressions (i.e. +(+x) is just x), the entire expression is essentially the same as:

"a" + 10

which gets executed as a string concatenation with the addition operator.

Interested in? Go to Esprima live parser demo and give it a go!

Related posts:

♡ this article? Explore more articles and follow me Twitter.

Share this on Twitter Facebook

comments powered by Disqus