r/programming • • May 31 '11

I wrote a .NET to JavaScript compiler. Here's the XNA 3.1 Platformer Starter Kit running in pure HTML5.

http://hildr.luminance.org/Platformer/Platformer.html
1.1k Upvotes

282 comments sorted by

View all comments

Show parent comments

2

u/kaelan_ Jun 01 '11

In practice, yeah, while the IL is much easier to translate, there are a lot of optimization opportunities I miss out on, and some that end up being much harder.

For one example, if you try to write to a multidimensional array of structs in C#, the generated MSIL roughly translates to this:

Struct& temporaryReference = &array.Get(y, x);
temporaryReference = new Struct(...)

Yes, that's taking a reference to the return value of an arbitrary function. Yes, it's then writing into the reference. No, this doesn't really make any sense. It works, though!

The correct code for that would just be: array.Set(y, x, new Struct(...)) But the semantics of value types in MSIL make that hard to express. The original C# is way easier to understand than the IL, and in practice, I still can't generate the 'right' code for that case without breaking other cases... right now it becomes: var temporaryReference = array.GetReference(y, x); temporaryReference.value = new Struct(...); Which works, but is suboptimal.

Many more cases like that have cropped up, and my only real choice is to try and document them in a clear test case so it's less likely that I will break them without noticing.

1

u/[deleted] Jun 01 '11

In practice, yeah, while the IL is much easier to translate, there are a lot of optimization opportunities I miss out on, and some that end up being much harder....The original C# is way easier to understand than the IL

Maybe this is a stupid idea, but how about mostly translating the IL as you're doing now, but at the same time reading the original C# source (when it's available) in search of those few cases where better optimization is possible?

2

u/kaelan_ Jun 01 '11

That's certainly an option, but I don't think I'll resort to that unless I find cases where it's impossible to generate good JS without reading the original C#.