This first part introduces the most basic WASM module in textual format (.wat) and several insights in the generated bytecode file (.wasm). Then a more elaborated wasm program with a simple computation is shown. This computation will be the square of a given natural number. And to conclude, two different options are explored for being capable of executing the compiled wasm programs. One of these is execution over the Node runtime and the other inside the browser via Javascript interoperability.
Most basic webassembly module
File: empty_module.wat
;; The most basic module possible to be created in webassembly textual format.(module);; This code needs to be compile to bytecode. Not currently understandable by any runtime.;; Text (.wat) -> Bytecode (.wasm). This is provided by wabt toolkit.;; wabt includes compilers to convert between WebAssembly’s text representation and wasm (wat2wasm),;; and vice versa, plus more besides.;; Location (github): https://github.com/webassembly/wabt;; Location (homebrew): https://formulae.brew.sh/formula/wabt#default
Compile the textual representation of a webassembly program to bytecode via wat2wasm compiler.
e.g:
Compiler flags:
-o output_filename : Specifies the target generated file.
$wat2wasmempty_module.wat-oempty_module.wasm
Inspect the contents of the wasm file to see what it looks like. UNIX command -> xxd
NOTE: The previously opcodes shown as examples are universally present in every wasm file as main headers.
A webassembly module with a simple computation
Name: math.wat Description: Take a number a compute its square. Then call it from the browser and exectue it.
(module
;; The string after the $ symbol specifies the name of the function.
;; Given a number compute its square.
;; Input
;; param i32
;;
;; Output
;; result i32
(func $square (param i32) (result i32)
local.get 0 ;; pull the input value and push it to the stack
local.get 0 ;; square function needs the same number twice
i32.mul ;; mul operation expects two numbers from the stack
;; Evaluation of arithmetic expressions using a stack
;;
;; (2 * 2)
;; would be written as
;;
;; 2 2 *
;; and evaluated like this
;;
;; Contents of the stack Program being evaluated
;;
;; [ ] | 2 2 *
;; [2] | 2 *
;; [2, 2] | *
;; [4] |
;;
;; The return value will be the final content of the stack after the execution.
)
;; export the previous function so javascript can run it.
(export "square" (func $square))
)