;; sample-module.wat: the source of sample-module.wasm, in WebAssembly text format. ;; Free sample from 99helpers.com/file-types/wasm ;; Build it with: wat2wasm --enable-annotations sample-module.wat -o sample-module.wasm (module ;; 1. An import: the module asks its host for a function called env.log. ;; In a browser, JavaScript supplies it; the module cannot print by itself. (import "env" "log" (func $log (param i32 i32))) ;; 2. Linear memory: 1 page of 64 KiB, exported so JavaScript can read it. (memory (export "memory") 1) ;; 3. A data segment: these bytes are copied into memory at offset 0 ;; when the module is instantiated. (data (i32.const 0) "Hello from 99helpers.com/file-types/wasm") ;; 4. A global: a constant other code can read, here the message length. (global $msgLen i32 (i32.const 40)) ;; 5. A function with two 32-bit integer parameters and one result. ;; Wasm is a stack machine: push a, push b, add them. (func $add (export "add") (param $a i32) (param $b i32) (result i32) local.get $a local.get $b i32.add) ;; 6. A loop with 64-bit integers: n! for n up to 20. (func $factorial (export "factorial") (param $n i64) (result i64) (local $acc i64) i64.const 1 local.set $acc (block $done (loop $next ;; stop when n <= 1 local.get $n i64.const 1 i64.le_s br_if $done ;; acc = acc * n local.get $acc local.get $n i64.mul local.set $acc ;; n = n - 1, then go round again local.get $n i64.const 1 i64.sub local.set $n br $next)) local.get $acc) ;; 7. Calling the import: pass the message's address and length to env.log, ;; and JavaScript decodes the bytes from memory into a string. (func $greet (export "greet") i32.const 0 global.get $msgLen call $log) ;; 8. A custom section: extra bytes engines ignore, written with the ;; custom annotation syntax that Wasm 3.0 added to the text format. (@custom "about" (after data) "Free sample from 99helpers.com/file-types/wasm") )