AST, Javascript and the logging framework

Was recently looking to the ruby abstract syntax tree capabilities, after seeing this. The AST's is a tree representation of the structure of source code, normally created by the compiler/interpreter, as an intermediate step of executing your code. Having access to this allows you to do some heavy transformations, that normally the default language does not allow. So much power comes with a price, the language safety sandboxes go away, so handle with care.

When looking at this I found that Javascript, the super widespread browser language, also has couple capabilities in this field, directly from the the core language.

Specifically with the:
- toString() - creates a string with the body of a method (except the ones defined natively in C on the browser)
- eval(); - executes the code passed as a string.

Try in the Firebug console:


var one = function()
{
/* some logic */
return 1;
}

/* the function code */
console.log(one.toString());
// > "function () { return 1; }"

/* get the code of method and update it, adding a log message to top */
eval("var one = "+ one.toString().replace("{", "{ console.log(\"method one called\");"));

one();
// > method one called



See that the method "one" got re-defined with the eval, and we added a "console.log()" for debugging purposes. This can be useful to add debugging code without having to edit the original code.


Extending this idea, imagine a logging framework where instead of having your code explicitly calling logging methods from within your code, thus having your code sprinkled everywhere with alien logging code like it is usual, this framework would know how to attach itself onto your code and do the logging by itself.

And this is useful for all languages not only for Javascript.

No comments: