- Just 43%
- Gleam 31%
- JavaScript 26%
gleam_porffor #
Since Gleam can output JavaScript, that means we get access to a bunch of JavaScript tooling including Porffor which can compile your JavaScript to native code. I've setup both a script in this repo to do this, as well as a patch for the gleam cli that adds a gleam export porffor command.
Regardless, you'll need at least gleam and porffor installed (globally). If you're running a Porffor version older than Alpha 9 then you'll also need esbuild. I've tested this with Gleam 1.18 and Porffor versions including and above Alpha 5.
How it works #
Both the script and the cli patch work by first compiling your Gleam to JavaScript, then creating a new file that just imports the generated main function and calls it. We then use esbuild to bundle this all into a single file, including any imports you make (e.g. the gleam standard library), as porffor doesn't support modules. Finally, we then either run porf run, porf native, or porf c depending on what you need - they all just build your code into C, optionally compile it for you to a binary, and then optionally run it.
Build Script #
I set this up to use just instead of a bash script as it's cleaner, so you'll need to install it first if you haven't already. If you don't want to then you can just run the commands from the Justfile directly.
# Build and run
just --timestamp run
# Only build
just --timestamp build
gleam export porffor #
You should clone my fork of gleam and the porffor branch, then build it from source.
# Clone to /tmp and build
git clone https://github.com/ghostdevv/gleam --branch porffor --depth 1 /tmp/gleam-porffor
cd /tmp/gleam-porffor
cargo build --release
# Setup the alias to your build binary and switch back
alias gleam="/tmp/gleam-porffor/target/release/gleam"
cd -
When you run gleam build all the work happens in the build/dev/javascript directory, so similarly all the output files will be in the build/dev/porffor directory.
Native #
gleam export porffor
./build/dev/porffor/gleam_porffor
Web Assembly #
Since Porffor outputs C code, you can compile it to WASM using a toolchain like the wasi-sdk or emscripten. Currently I'm using wasi-sdk so you'll need to install that, as well as something to run the wasm with such as wasmer or wasmtime. It follows the same build process as the native build, but instead of asking Porffor to compile to native directly it asks for a C file which it then passes to wasi-sdk's clang build.
Note
Wasm is currently only found to be working on Porffor Alpha versions 2 to 6 inclusive. On newer versions you can remove | MAP_NORESERVE from the generated C code, but I'm not sure what effect this has other than allowing this small example to run.
gleam export porffor --target=wasm
wasmer run build/dev/porffor/gleam_porffor.wasm