Olov Lassus

C-style assertions in JavaScript via JSShaper

30 Mar 2011

Earlier today I created asserter, a new plugin for the JSShaper framework that provides you C-style assertions in JavaScript.

Here’s a common style of doing JS assertions:

function myfn(x) {
    assertTrue(x >= 0, "argument x must be positive or zero");
}

When failing (let’s say x is -1) it will print something like this, perhaps with some kind of cleaned up stack trace:

assertTrue() failed: argument x must be positive or zero

This is what you would write instead when using asserter:

function myfn(x) {
    Assert(x >= 0);
}

When failing, it will print this:

Assertion failed: x >= 0, function myfn, file prog.js, line 2

I know which version I prefer. Thanks to the JSShaper framework I was able to create the asserter plugin in no time, using only 34 29 (edit: shorter and easier with declarative matching) lines of code.

Here’s how it works. asserter searches the syntax tree for calls to the Assert function. It adds an extra string argument containing the assert condition expression (in text form), the enclosing function name (or <anonymous> or <script>), the filename and lineno. Here’s what it would be replaced with:

Assert(x >= 0, "x >= 0, function myfn, file prog.js, line 2");

The Assert function could look like this. Note that it will execute just fine even if you didn’t run your program through asserter, although in that case it will just print a falsy value.

function Assert(condition, str) {
    if (!condition) {
        log("Assertion failed: "+ (str || String(condition)));
        quit(-1);
    }
}

Asserting preconditions in JS has never been simpler, no?

In C you would disable assertions in your release-build (allowed since assertions mustn’t contain side effects). In JS we could do the same by simply creating another JSShaper pass that removes the Assert calls.

Show comments (reddit)


Follow me on Twitter

« The case for restrict mode    ↑ Home     »