Wednesday, October 5, 2011

From vala to js - with emscripten.

Stumbling over emscripten again. A fun tool to compile llvm bytecode to JavaScript.
After installing some basic dependencies via
$ sudo yum install vala clang js
and a bit of glue (see below) and you can quickly run code written in vala using a JavaScript interpreter. All this can be done with all code clang compiles, so there is no more magic than normal involved.

$ cd /tmp
$ git clone https://github.com/kripken/emscripten.git
$ wget http://closure-compiler.googlecode.com/files/compiler-latest.zip
$ unzip compiler-latest.zip

Now that all software is in place, do some configurations by editing ~/.emscripten:

$ cat <<EOF ~/.emscripten
# path where you cloned emscripten
EMSCRIPTEN_ROOT=os.path.expanduser("~/tmp/emscripten") 
# I needed to link EMSCRIPTEN_ROOT/src/tmp to this path e.g. 
TEMP_DIR='/tmp' 

LLVM_ROOT=os.path.expanduser('/usr/bin/')
#LLVM_GCC=... # we don't have that on fedora
COMPILER_OPTS = ['-m64'] # Change to your arch!

SPIDERMONKEY_ENGINE = [os.path.expanduser('/usr/bin/js'), '-m']
COMPILER_ENGINE=SPIDERMONKEY_ENGINE
JS_ENGINE=SPIDERMONKEY_ENGINE
CLOSURE_COMPILER = os.path.expanduser('~/tmp/emscripten/closure-compiler.jar')

TIMEOUT=None
EOF

Basically now everything is in place. Using the following snippet
struct FooBar
{
	int m;
	public void wtf ()
	{
		stdout.printf ("Wtf!\n"); // The \n is important.
	}
}

void main()
{
	FooBar f = FooBar ();
	f.wtf ();
}

... we can compile and execute the whoole thing using the following lines:

$ valac --profile=posix --ccode vaem.vala
$ clang -emit-llvm -S -o vaem.ll vaem.c
$ ./emscripten.py va/vaem.ll -o vaem.js
$ js -m vaem.js
Wtf!
$

We need to use the posix profile, otherwise we need to compile the whole glib/gobject system using emscripten. Another way of creating JavaScript from vala code is using maja.

No comments:

Post a Comment