In the past few days I have been plugging away at writing a language that compiles directly to WASM.
You might say, there are many languages that compile to WASM, what makes this one special?
And the answer is "nothing". Yet, anyway.
All I have is a few binary expressions and loops.
There is only one type: int, which is i32.
I have not even implemented function calls yet!
Nonetheless, I passed today a tiny milestone. My language can now calculate Fibonacci sequences!
Here is the full module:
export fn fibonacci(n: int) int {
if (n <= 0) return 0;
var a, b, i = 0, 1, 1;
while (i < n) {
const next = a + b;
a, b = b, next;
i += 1;
};
return b;
}
Which is given to my compiler producing WASM in text format, which is then passed to Binaryen's wasm-as and wasm-opt tools to give us this binary, with a break where the code section (0A) begins.
00000000 | 00 61 73 6D 01 00 00 00 01 06 01 60 01 7F 01 7F | ▁asm•▁▁▁•••`••••
00000010 | 03 02 01 00 07 0D 01 09 66 69 62 6F 6E 61 63 63 | •••▁•←•→fibonacc
00000020 | 69 00 00 | i▁▁
00000023 | 0A 38 01 36 01 03 7F 20 00 41 00 4C 04 40 41 00 | ↵8•6•••␣▁A▁L•@A▁
00000033 | 0F 0B 41 01 21 01 41 01 21 02 03 40 20 00 20 01 | ••A•!•A•!••@␣▁␣•
00000043 | 4A 04 40 20 03 20 02 22 03 6A 21 02 20 01 41 01 | J•@␣•␣•"•j!•␣•A•
00000053 | 6A 21 01 0C 01 0B 0B 20 02 0B | j!•••••␣••
Which is then invoked with the exported function name of fibonacci in any WASM runtime to give you the result you need!
% ❭ just invoke fibonacci 10
| fibonacci 10
> 55
Nifty, hah?
Three Days Leter
I can do function calls now! Here is the naive Fibonacci:
export fn fibonacci(n: int) int {
if (n <= 1) return n;
return fibonacci(n: n - 1) + fibonacci(n: n - 2);
}00000000 | 00 61 73 6D 01 00 00 00 01 06 01 60 01 7F 01 7F | ▁asm•▁▁▁•••`••••
00000010 | 03 02 01 00 07 0D 01 09 66 69 62 6F 6E 61 63 63 | •••▁•←•→fibonacc
00000020 | 69 00 00 0A 1E 01 1C 00 20 00 41 01 4C 04 40 20 | i▁▁↵•••▁␣▁A•L•@␣
00000030 | 00 0F 0B 20 00 41 01 6B 10 00 20 00 41 02 6B 10 | ▁••␣▁A•k•▁␣▁A•k•
00000040 | 00 6A 0B | ▁j•
Takes a bit longet to compute than the loop, though.