WebAssembly: The Stack Machine
The stack machine is the way WebAssembly runs its steps. Each step takes values from the top of a stack and puts its answer back on top.
Push 2
This step pushes 2 onto the stack.
i32.const 2Push 3
This step pushes 3 on top of 2.
i32.const 3Add them
This step pops 2 and 3 and pushes 5.
i32.addTrace 2 + 3 by hand
First 2 goes on, then 3. Add pops both and pushes 5.
i32.const 2
i32.const 3
i32.addThe same sum from a page
This call runs the add function with 2 and 3.
console.log(instance.exports.add(2, 3));Example
const B64 = "AGFzbQEAAAABBwFgAn9/AX8DAgEABwcBA2FkZAAACgkBBwAgACABags=";
(async () => {
const bytes = Uint8Array.from(atob(B64), c => c.charCodeAt(0));
const { instance } = await WebAssembly.instantiate(bytes, {});
console.log('2 + 3 =', instance.exports.add(2, 3));
console.log('10 + 20 =', instance.exports.add(10, 20));
})();Key points
- Stack: a pile of values where only the top value is used next.
- Push: to put one value on top of the stack.
- Pop: to take one value off the top of the stack.
- Use local.get to push one input value onto the stack.
- Use i32.add to pop two values and push their sum.
- Use i32.const to push one fixed number onto the stack.
In this example, the first line holds the module bytes as text. The next line turns that text into bytes. Then the code builds the module and waits for it. Then it calls add with 2 and 3. Then it calls add with 10 and 20. The two lines print 5 and 30. Each call pushes its inputs, adds them, and hands back the sum.
Note
WebAssembly keeps values on the stack, not in named variables.
Try it Yourself
Edit the code, then press Run.
Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What is on the stack after i32.const 2, i32.const 3, i32.add?