Search code examples
javascriptparsingantlrinject

Need to instrument Javascript: function calls / args - ANTLR?


I need to take a load of Javascript and instrument it automatically: specifically I want to log every call to a function, and provide a list of arguments that the function was invoked with.

I have a half-baked way of doing this with Python : using 're' to match 'function' keywords - but it's really quite primitive (doesn't deal with comments and so on).

I'm no expert (very far from it) with ANTLR: but how easy could I leverage a already built Javascript Parser to perform this ? (Can we 'hook' out to standard java to dynamically create the code I need at the right point?)

BTW: the actually logging will (probably) be done with log4javascript; but I might also just use 'alerts' - the hard bit is getting the code-injection working....

So for example, I need to turn something like:

function foo(bar) {
...
}

into:

function foo(bar) {
alert("<scriptname.js>: foo was called with arguments: [bar="+bar+"]");
...
}

Solution

  • Regular expressions won't do it. If you want to instrument code reliably, you need reliable parsers and trustworthy mechanisms for inserting the instrumentation.

    See my paper on building test coverage tools by instrumenting code. It describes how to instrument code in very general way, using source-to-source program transformations, to do the kinds of things such as what you want to do.

    My company builds a line of robust test coverage tools this way.

    You can do this kind of thing with ANTLR but it is a lot clumsier; you have write the transformations procedurally, and then you have to regenerate the source code from the parse tree. That's a lot harder than it looks.