1. A Simple Add Function
Here’s a minimal WAT module that exports a functionadd taking two 32-bit integers and returning their sum:
(module …)wraps the entire definition.(func $add …)declares a function named$add.(param $a i32),(param $b i32)specify two 32-bit integer inputs.(result i32)marks the return type.- Instructions:
get_local $a,get_local $bpush parameters onto the stack.i32.addpops both values, adds them, and pushes the result.
(export "add" (func $add))makes the function available to the host environment.
2. Grammar & Whitespace
WAT uses S-expressions; parentheses define hierarchy and whitespace (spaces, newlines) separates tokens for readability:3. Adding Comments
Inline comments start with;;:
4. Lexical Structure
- Identifiers begin with
$(e.g.,$add,$ptr). - Types include
i32,f32,v128, etc. - Tokens are keywords, numbers, or symbols.
- Whitespace and comments separate tokens but do not affect execution.
5. Numeric and Vector Types
WAT supports multiple primitive types. Below is a quick reference:5.1 Floating-Point Addition
5.2 SIMD Vector Addition
SIMD operations require a WebAssembly engine with the SIMD extension enabled.
6. Control Flow
6.1 Conditional Branching
Useif, else, and end to branch based on a condition:
6.2 Loops and Breaks
Accumulate the sum of an array ofi32 values:
Deeply nested loops may impact performance in some WASM runtimes. Benchmark before optimizing.