Instrumenting code with generators in JavaScript

I saw a really cool demo by James Long using Firefoxes implementation of Generators to instrument code so you can stop the execution and step through it like your in the dev tools using break points.

Unfortunately Fx’s implementation isn’t on par with the ES6 spec which has shipped in Chrome canary* and Opera Developer behind the experimental JavaScript flag. So I converted the demo to work in Chrome & Opera and match the current ES6 specification.

Make sure you’ve enabled experimental JavaScript in Chrome Canary or Opera Developer otherwise this demo will just throw errors.

It was really simple to update, the only changes were as follows:

– Adding the * token to the function declaration to indicate it’s a Generator function.
– Removing the send method to use next and looking at the value property on the returned object
– Finally, removing the special script type needed for Firefox to interpret newer JavaScript.

Check out the commit on github for more info.

function* foo() {
  var foo = 1;
  yield foo++;
}

var baz = foo();

foo.next(); // { value: 2, done: false }

The above is a simple example of creating a Generator which returns an Iterator. Our Generator halts the code when it hits the yield keyword. To continue the execution until the next yield or return keyword we call the next method on the returned Iterator object. Check out Generators in v8 article to learn more about ES6 Generators.

The use of yield keyword is still valid throughout both implementations to halt code execution.

The original demo has a compiler written in node that’ll instrument input source code and output the special version so you can have a UI interface to step through it and highlight the current execution state of your program.

I plan to update the compiler to handle both forms of generators. Also making it work in browser would be awesome too. It uses Esprima and friends to instrument code so getting to run in the browser shouldn’t be an issue.

* Note: Chrome stable supports Generators with the flag enabled but still supports the deprecated send method so the demo won’t work without some modification.

Uses

The biggest usage right off the bat would be education, seeing how JavaScript is executed. Visualising the code step by step as a browser would flow through it is very enlightening.

As browser support increases for these awesome new ES6 features more interesting uses like this will pop up.