commit 1f7abe49ab216aca578a20d8de541288eb21b3fa
Author: James Halliday
Date: Thu Jul 7 05:58:29 2011 +0000

Uglify is a pretty nifty javascript minifier but it also has the lesser-known ability to generate and walk the AST.

Unfortunately, uglify's traverser is a bit cumbersome to use so I wrote a library using my own traverser to make it easy!

Introducing burrito, a crazy new library to make AST traversals and manipulations crazy easy.

Given this snippet of code:

f() && g(h());

foo();

It's super easy to wrap all the function calls in another function call, qqq():

var burrito = require('burrito');

var src = burrito('f() && g(h())\nfoo()', function (node) {
    if (node.name === 'call') node.wrap('qqq(%s)');
});

console.log(src);

$ node wrap.js 
qqq(f()) && qqq(g(qqq(h())));

qqq(foo());

Or maybe dive in and surgically replace that && with a ||, how about!

var burrito = require('burrito');

var src = burrito('f() && g(h())\nfoo()', function (node) {
    if (node.name === 'binary') node.wrap('%a || %b');
});

console.log(src);

$ node wrap.js 
f() || g(h());

foo();

Plus you can .microwave() your burrito too, which evals the code using node's vm.runInNewContext() (which even runs in the browser thanks to browserify).

var burrito = require('burrito');

var res = burrito.microwave('Math.sin(2)', function (node) {
    if (node.name === 'num') node.wrap('Math.PI / %s');
});

console.log(res);

This snippet takes the expression Math.sin(2) and replaces the 2 with Math.PI / 2 thanks to some %s interpolation. And since Math.sin(Math.PI / 2) evaluates at 1, the code should print as much...

$ node microwave.js
1

And it does! Hooray!

This craziness makes an amazing number of things possible, like stack traces that work in all the browsers without relying on a stack trace API or code coverage tools without any binary extensions!

Give burrito a spin!

<a href="http://npmjs.org">npm</a> install burrito

or get the code on github!

more
git clone http://substack.net/blog.git