JavaScript Code Model
I was recently looking for a JAXB-like API for JavaScript which would allow converting between XML and JavaScript objects on the client. Such tool would be extremely useful when working with schema-based XML documents in JavaScript clients.
Apparently, there's no such thing. So I've started thinking about writing one. To put it frankly, the idea fascinated me so much that I simply could not help starting experimenting.
Today I've started with a code model for JavaScript. I'm writing an API which would allow generating syntactically correct JavaScript from Java. This will be somewhat similar to the code model library used in JAXB/XJC, only implemented for JavaScript. I took the ECMAScript specification and a couple of grammars and wrote over 50 interfaces which model the grammar of the JavaScript code. Here's a couple of examples of what I got so far:
JSProgram program = codeModel.program();
JSNumericLiteral one = codeModel.lit(1);
JSFunctionDeclaration factorial =
program.declare("factorial");
JSVariable x = factorial.parameter("x");
factorial.body()._return(
x.le(one).cond(one,
x.mul(codeModel.call(factorial).args(x.minus(one)))));
This should produce the code of the factorial function like:
function factorial(x)
{ return x <= 1 ? 1 : x * factorial(x - 1); }
JSIfStatement _if = factorial.body()._if(x.le(one));
_if._then()._return(one);
_if._else()._return(
x.mul(codeModel.call(factorial).args(x.minus(one))));
I need this to be able to generate XML-JSON mappings in correct JavaScript syntax. String concatenation just does not feel right.
But what's probably the most important is that it's great fun to work on this. :)
Labels: jaxb javascript ecmascript codemodel xml programmatic
0 Comments:
Post a Comment
<< Home