var foo = function (a) {First step was to adapt Crockford's parser to dojo, my preferred Javascript framework. Feeding the parser with the sample Javascript snippet form above results in an object, which can be JSON serialized to a pure AST representation:
var b = a + 1;
return b;
};
{{"value",<<"=">>},On the Erlang side, now comes the tricky part. The JSON tuple this needs to be translated into a tuple which represents an Erlang AST. For the example above my translator produces the following:
{"arity",<<"binary">>},
{"first",{{"value",<<"foo">>},{"arity",<<"name">>}}},
{"second",
{{"value",<<"function">>},
{"arity",<<"function">>},
{"first",[{{"value",<<"a">>},{"arity",<<"name">>}}]},
{"second",
[{{"value",<<"=">>},
{"arity",<<"binary">>},
{"first",
{{"value",<<"b">>},{"arity",<<"name">>}}},
{"second",
{{"value",<<"+">>},
{"arity",<<"binary">>},
{"first",
{{"value",<<"a">>},{"arity",<<"name">>}}},
{"second",
{{"value",1},{"arity",<<"literal">>}}}}}},
{{"value",<<"return">>},
{"arity",<<"statement">>},
{"first",
{{"value",<<"b">>},{"arity",<<"name">>}}}}]}}}}
{function,1,Next, this tuple needs to be wrapped with some meta data attributes, such as module name and function exports:
foo,
1,
[{clause,1,
[{var,1,'A'}],
[],
[{match,1,
{var,1,'B'},
{op,1,'+',{var,1,'A'},{integer,1,1}}},
{var,1,'B'}]}]}
[{attribute,1,module,footest},Now we have the complete module representation, and with compile:forms/1 it can be turned into byte code for directly loading into the VM (code:load_binary/3) or writing to a .beam file. It is even possible to get the Erlang representation of the source code with erl_prettypr:format/1:
{attribute,1,compile,export_all},
{function,1,
foo,
1,
[{clause,1,
[{var,1,'A'}],
[],
[{match,1,
{var,1,'B'},
{op,1,'+',{var,1,'A'},{integer,1,1}}},
{var,1,'B'}]}]},
{eof,1}]
What's next ?
"-module(footest)."
"-compile(export_all)."
"foo(A) -> B = A + 1, B."
Parser and translator currently only support a subset of the Javascript language. Here there is a lot to do. Another issue is the functional nature of Erlang. As long as I write functional Javascript, everything is fine. But somehow I also need to handle the non-functional aspects of Javascript. And setting up a project at googlecode for this.
2 comments:
Hi. Nice work. Out of curiosity, did you ever put this up as a project on Google Code?
Thanks,
mac01021
Who knows where to download XRumer 5.0 Palladium?
Help, please. All recommend this program to effectively advertise on the Internet, this is the best program!
Post a Comment