Write zig code in a <textarea>
, format it with WebAssembly. Try me.
Clone the repo and jump into it:
git clone git@github.com:jackdbd/zigfmt-web.git
cd zigfmt-web
Install JS dev dependencies (prettier, eslint, etc):
npm install
Use zigup to fetch and manage zig compilers:
zigup fetch master
zigup default master
Double check the version of the zig compiler:
zig version
Compile the wasm module and move it to the public
directory:
npm run build
Note: the wasm module is generated compiling src/lib.zig
with wasm32-freestanding-musl
as the compilation target, and with the release-small build mode.
Serve the public
directory:
npm run serve
The public
directory will be deployed to GitHub pages, so each git push
automatically triggers a new deploy.
The src/main.zig
file can be compiled for wasm32-wasi-musl and run on any WebAssembly runtime. You can compile for WASI with:
zig build-exe src/main.zig \
-target wasm32-wasi-musl \
-O Debug && \
mv main.wasm wasi-demo
Note: compile the WASI demo using -O Debug
so you can see the print statements from std.log.debug
and std.log.info
.
You can execute the demo with a WASI runtime like wasmtime:
wasmtime run wasi-demo/main.wasm 'const answer: u8 = 42;'
wasmtime run wasi-demo/main.wasm 'this is not valid zig code'
In alternative, you can run this script that uses the Node.js wasi module:
node --experimental-wasi-unstable-preview1 wasi-demo/main.mjs \
'const answer: u8 = 42;'
node --experimental-wasi-unstable-preview1 wasi-demo/main.mjs \
'this is not valid zig code'
Note: the --experimental-wasi-unstable-preview1
flag should no longer be required from Node.js 20 onwards.
zig uses wasm-ld, a LLVM-based linker. You can see it when passing the --verbose-link
flag:
zig build-lib src/lib.zig \
-target wasm32-freestanding-musl \
-dynamic \
--verbose-link
If you have some issues related to the wasm linker, see these links:
- https://gist.github.com/josephg/873a21d4558fd69aeccea19c3df96672
- ziglang/zig#11209
- https://lld.llvm.org/WebAssembly.html
- https://github.com/WebAssembly/tool-conventions/blob/main/Linking.md
You can debug the generated wasm module using a few tools from the WebAssembly Binary Toolkit:
See the generated WebAssemly Text Format (WAT):
wasm2wat public/lib.wasm
Inspect the symbols in the wasm binary:
wasm-objdump public/lib.wasm --headers
wasm-objdump public/lib.wasm --details
wasm-objdump public/lib.wasm --full-contents
Decompile the wasm file to a pseudo C-like language:
wasm-decompile public/lib.wasm
Decompile the wasm file to C:
wasm2c public/lib.wasm
count opcode usage for instructions:
wasm-opcodecnt public/lib.wasm