[cfe-dev] How to use Clang to translate from C++ to another language

David Chisnall csdavec at swan.ac.uk
Wed Mar 28 10:32:16 PDT 2012


On 28 Mar 2012, at 17:23, Tim Stowell wrote:

> I'm curious, sounds like Clang worked well to translate Objective-C to Javascript, since Javascript is similar to Actionscript, any gotchas to look out for? Yes I agree multiple inheritance would be a nightmare, I'm going to cheat by only converting C++ code that doesn't use it.

A few, yes.

- JavaScript numbers are really horrible to work with.  To support correct truncation / overflow behaviour you need to jump through a lot of hoops.  64-bit arithmetic... I still haven't done yet.

- Pointers.  Object pointers were easy, but generic pointers are really hard.  I am using an ArrayBuffer for all allocations (heap or stack).  When you store a pointer in memory, it stores a number in the buffer and it also stores the JavaScript reference as a property on the array.  This lets you read back the value as either a pointer or a number.

- Pointer arithmetic requires wrapping in something that does address calculation.  I just emit these as a call to a pointerAdd() function which returns a new reference object.  This contains a pointer and an offset.  When you try to dereference it, you get an error if it's out of range, but this lets you do things like &a + b - b for arbitrary values of b without breaking things.

- Weak references are impossible in JavaScript.  This sucks.  It's probable even worse in C++ if you use smart pointers, because you can easily create something that's cyclic and never freed, even though you only have owning pointers going in one direction.

On the plus side, you can do stuff like:

int *thisIsSoWrong(void) {
   int a = 42;
   return &a;
}

And have it actually work, and not crash when you dereference the pointer in my current implementation.  I could probably get better performance by reusing a large ArrayBuffer for the whole stack, rather than a separate one for each variable, but I don't really care about performance in this - if you care about performance then JavaScript is the wrong tool for the job. 

Have fun!

David





More information about the cfe-dev mailing list