Write a line-trimming helper. Our WAT lines have leading spaces. We need to strip them to compare against instruction names.
fn vm_trim(line: []const u8) []const u8 {
var s: usize = 0;
while (s < line.len and (line[s] == ' ' or line[s] == '\t')) {
s += 1;
}
return line[s..];
}
And a helper to check if a line starts with a given prefix:
fn starts_with(hay: []const u8, needle: []const u8) bool {
if (hay.len < needle.len) {
return false;
}
for (needle, 0..) |c, i| {
if (hay[i] != c) {
return false;
}
}
return true;
}
We'll use starts_with constantly -- starts_with(line, "i64.const "), starts_with(line, "local.get $"), etc. Each instruction has a recognizable prefix, and the operand (a number or a name) follows it.