Saturday, October 16, 2010

Generating JavaScript Code with JavaScript Code Model

JavaScript Code Model (JSCM for short) is a Java library which precisely models JavaScript grammar as defined in ECMAScript specification. JSCM allows you to programmatically create, analyze and manipulate JavaScript code.

This post demonstrates usage of JSCM to generate JavaScript code from a Java program.

Here's a code snippet which creates a factorial function:

// Instantiate the code model
JSCodeModel codeModel = new CodeModelImpl();
// Create the program
JSProgram program = codeModel.program();
// Add a function declaration
JSFunctionDeclaration factorial = program
.functionDeclaration("factorial");
// Add a function parameter
JSVariable x = factorial.parameter("x");
// Create an integer literal
JSDecimalIntegerLiteral one = codeModel.integer(1);
// Add a return statement to the function body
factorial.getBody()._return(
x.le(one).cond(
one,
x.mul(factorial.getFunctionExpression().i()
.args(x.minus(one)))));

// Write the program code to the System.out
new CodeWriter(System.out).program(program);

This produces the following JavaScript code:

function factorial(x) {
return x <= 1 ? 1 : x * factorial(x - 1); }


In this example we first produce the code model by creating expressions, statements, function declarations and so on and then use code writer to serialize the created program into the System.out. This process almost guarantees that the resulting code is syntactically and grammatically correct - and well-formatted as well. And I hope the API is very convenient - especially if you compare it to the "good old" string concatenation.

In the future I'll also provide a parser which parses JavaScript code and builds its model. It will then be possible to analyze existing JavaScript code and manipulate it - for instance add profiling statements, reformat, restructure, refactor, optimize or obfuscate.

0 Comments:

Post a Comment

<< Home