Monday 9 May 2011

(Almost) Translate the InChI code into JavaScript

If you follow Rich Apodaca's Signals blog (for example), you will be aware that more and more chemistry applications are being implemented in JavaScript. Wouldn't it be nice to be able to take an existing Java or C++ cheminformatics library and convert it to JavaScript?

Well, guess what - in Oct of last year, a project appeared called emscripten that will do just that for C/C++. So without further ado, let's convert the InChI code.

Actually, maybe it'd make more sense to begin with "Hello World":
#include <stdio.h>

int main()
{
   printf("Hello World!\n");
   return 0;
}
To start with, compile llvm, clang, spidermonkey and v8 as described in the install instructions.

Then convert to javascript as follows:
#!/bin/sh
LLVM_BINDIR=~/Tools/llvm-2.9/cbuild/Release/bin
EMSCRIPTEN=~/Tools/emscripten-git
V8=~/Tools/v8-repo

$LLVM_BINDIR/clang hello.c -o hello
$LLVM_BINDIR/clang hello.c -S -emit-llvm

$LLVM_BINDIR/llvm-as hello.s
$LLVM_BINDIR/llvm-dis hello.s.bc -show-annotations

# Run emscripten
$EMSCRIPTEN/emscripten.py hello.s.ll $V8/d8 > hello.js

# Run the Javascript using v8
$V8/d8 hello.js
After some trivial edits to the code, we can run hello.js in the browser.

Part II shows my attempt to repeat this procedure with the InChI code.

4 comments:

Ed Cannon said...

Does it scale up to larger code bases?

Noel O'Boyle said...

Well, the demo on the emscripten page is where he compiled the whole of Python. Unfortunately, he forgot to include a simple example so it took me an hour or two to figure out the example above. :-)

Anonymous said...

Can you post the generated version of hello.js, which is modified to hello_edit.js to use from webpage?

Noel O'Boyle said...

@Anon: To create hello_edit.js, I commented out "run(args);" so that I could call it instead from the HTML page.