Temporary chapter name for all chapters
walk-wat-lines

A compiler needs to write machine instructions. When faced with the problem of adding 3 and 4, a machine writes 3 at some specific place (a register), then 4 to some other place, then adds them, and puts the result somewhere.

Dealing with that many steps just for 3+4 is annoying, and this is why we want higher level programming languages (but not too high -- we want to know what the machine is doing).

Assembly languages such as x86_64 are full of weird register and instruction names to memorize.

There is also WASM, which is a "binary instruction format for a stack-based virtual machine". You put the 2 values on the stack, and then one add instruction pops the 2 numbers, adds them, and puts the result back on the stack.

A stack is just a pile -- things go on top, come off the top. To compute 3 + 4:

                                  []
push 3:                           [3]
push 4:                           [3, 4]
add (pops 4, pops 3, pushes 7):   [7]

WASM is functionally equivalent to other assembly languages, so virtual machines can be fast on any hardware. WASM is binary, but there is WebAssembly text, which is the readable version.

wat woman meme

We'll compile our 3+4 to three lines of WebAssembly text:

i64.const 3
i64.const 4
i64.add

Each line is one instruction. Before we run them, let's just walk through the string and slice it up by \n. Print each line back to confirm it works.

pub fn main() void {
    // (interpreter section unchanged)

    const wat: [:0]const u8 =
        \\i64.const 3
        \\i64.const 4
        \\i64.add
    ;

    var wat_pos: usize = 0;
    while (wat_pos < wat.len) {
        var wat_line_end: usize = wat_pos;

        // YOU: advance wat_line_end until '\n' or end of wat.
        // YOU: print the slice wat[wat_pos..wat_line_end], then a newline.

        wat_pos = wat_line_end + 1;
    }
}
while (wat_line_end < wat.len and wat[wat_line_end] != '\n') {
    wat_line_end += 1;
}
printString(wat[wat_pos..wat_line_end]);
printChar('\n');

wat[wat_pos..wat_line_end] is a slice -- a view into the multi-line string. No copying.