Packages
zig_barnacle
0.1.0
Zig-first BEAM NIF toolkit (Mix compiler, generator, and cement Zig runtime)
Current section
Files
Jump to
Current section
Files
zig_barnacle
README.md
README.md
# Barnacle
Write BEAM NIFs as Zig projects and load them from Elixir.
## Why this exists
Barnacle keeps your native code as a Zig package with its own `build.zig`, `build.zig.zon`, and unit tests. Mix calls `zig build` and loads the resulting shared library, so `zls` works on your zig files, `zig build test` runs without booting the BEAM, and you can pull in whatever Zig libraries you want.
The repository ships two halves:
- `cement` is a Zig module with `erl_nif` bindings, a comptime `nif_init` exporter, BEAM allocators, typed GC resources, and small helpers for zero-copy binaries and Erlang errors.
- `Barnacle` is the Mix side: a compiler that runs `zig build`, a tiny `@on_load` loader, and `mix barnacle.new` to scaffold a NIF folder.
## Requirements
- Elixir >= 1.18 (tested on 1.18, 1.19, and 1.20.5)
- Erlang/OTP 27, 28, or 29
- Zig 0.17 (on `PATH`, via `ZIG_EXECUTABLE_PATH`, or downloaded into a local `.barnacle/` folder)
## Installation
Add `:zig_barnacle` to `deps` and wire the compiler in `mix.exs`:
```elixir
def project do
[
app: :my_app,
version: "0.1.0",
compilers: [:barnacle | Mix.compilers()],
barnacle: [
hasher: [path: "native/hasher"]
],
deps: [
{:zig_barnacle, "~> 0.1.0"}
]
]
end
```
## Usage
### 1. Scaffold a NIF
```sh
mix barnacle.new hasher --elixir-stub
```
This creates a Zig project in `native/hasher/` and an Elixir module in `lib/my_app/hasher.ex`. Run it again to add more NIF packages to the same app, or pass `--here` / `--dir PATH` to pick where it lands.
### 2. Write Zig and load it from Elixir
Put your Zig code in `native/hasher/src/root.zig` and keep the BEAM glue in `native/hasher/src/nif.zig`:
```zig
const cement = @import("cement");
const e = @import("erl_nif");
const hasher = @import("hasher");
fn addNif(env: cement.env, argc: c_int, args: [*c]const e.ErlNifTerm) callconv(.c) e.ErlNifTerm {
if (argc != 2) return cement.badarg(env);
var a: i64 = 0;
var b: i64 = 0;
if (e.enif_get_int64(env, args[0], &a) == 0) return cement.badarg(env);
if (e.enif_get_int64(env, args[1], &b) == 0) return cement.badarg(env);
return e.enif_make_int64(env, hasher.add(a, b));
}
const exported_nifs = [_]e.ErlNifFunc{
.{ .name = "add", .arity = 2, .fptr = addNif, .flags = 0 },
};
comptime {
cement.entry.exportNifs(.{
.name = "Elixir.MyApp.Hasher",
.funcs = &exported_nifs,
});
}
```
Load it in `lib/my_app/hasher.ex`:
```elixir
defmodule MyApp.Hasher do
use Barnacle.Nif, otp_app: :my_app, nif: :hasher
def add(_a, _b), do: :erlang.nif_error(:nif_not_loaded)
end
```
### 3. Build and test
```sh
# Test the Zig code directly (no BEAM required)
cd native/hasher && zig build test
# Build all configured NIFs and run ExUnit
mix test
```
## What's in `cement`
| API | Purpose |
|---|---|
| `cement.entry.exportNifs` | Exports `ErlNifEntry` and `nif_init` with optional `load`/`upgrade`/`unload` callbacks |
| `cement.inspectBinary` / `cement.allocBinary` | Zero-copy binary inspection and BEAM-owned binary allocation (process heap or shared refc) |
| `cement.okTuple` / `cement.errorTuple` / `cement.raiseError` / `cement.badarg` | Return `{:ok, val}`, `{:error, :ZigError}`, raise `%ErlangError{original: :ZigError}`, or raise `ArgumentError` |
| `cement.allocator` / `cement.raw_allocator` | `std.mem.Allocator` backed by `enif_alloc`/`enif_free` (works with `ArenaAllocator`, `ArrayList`, etc.) |
| `cement.ResourceType(T)` | Typed BEAM GC-managed NIF resource with optional `deinit` destructor and automatic alignment padding |
| `cement.make` / `cement.get` | Optional helpers for converting Zig structs, slices, and primitives to and from BEAM terms |
| `erl_nif` / `erl_nif.c` | Direct access to all `enif_*` functions, dirty scheduler flags (`ERL_NIF_DIRTY_JOB_CPU_BOUND`), sub-binaries, and resource binaries |
## Examples
[`examples/`](https://github.com/physarella/barnacle/tree/main/examples) holds the current library showcase (`zig build examples`) and `mix.exs` (compiled only in `:test`):
- [`examples/showcase_core.zig`](https://github.com/physarella/barnacle/blob/main/examples/showcase_core.zig): Zig logic and unit tests
- [`examples/showcase_nif.zig`](https://github.com/physarella/barnacle/blob/main/examples/showcase_nif.zig): NIF entrypoints using `cement` (binaries, error helpers, `cement.allocator`, `ResourceType`, and `cement.make`)
- [`examples/showcase.ex`](https://github.com/physarella/barnacle/blob/main/examples/showcase.ex) and [`test/showcase_test.exs`](https://github.com/physarella/barnacle/blob/main/test/showcase_test.exs): Elixir loader and ExUnit tests
## Configuration
Options supported per entry under `barnacle: [...]` in `mix.exs`:
| Option | Default | Description |
|---|---|---|
| `path` | `"native/<name>"` | Directory containing `build.zig` |
| `step` | default install | Optional `zig build <step>` name |
| `optimize` | `:auto` | `Debug` in dev/test and `ReleaseFast` in prod, or `:debug`, `:safe`, `:fast`, `:small` |
| `otp` | host OTP release | Passed as `-Dotp=<major>` to `zig build` |
| `target` | host | Optional `-Dtarget=...` for cross-compilation |
| `flags` | `[]` | Extra arguments passed to `zig build` |
| `prefix` | `app_path/priv` | Install prefix for compiled libraries |
| `zig` | auto-resolved | Explicit path to the `zig` binary |
| `zig_version` | `"0.17.1"` | Version fetched if downloading standalone Zig |
## Zig toolchain and Nix
Barnacle checks for `zig` in this order: `:zig` in `mix.exs`, `ZIG_EXECUTABLE_PATH`, `PATH`, then a project-local `.barnacle/` directory.
If no `zig` binary is found, it asks before downloading the official standalone release (verified against the upstream SHA-256) into `.barnacle/` inside your project. add `.barnacle/` to `.gitignore` if you use it.
If you use Nix, we have a template [`flake.nix`](https://github.com/physarella/barnacle/blob/main/flake.nix) fully set up just copy and or paste in root of project and run `nix develop` to get Elixir, Zig, and ZLS in one dev shell.
## Platform and OTP support
`cement` ships pre-translated `erl_nif` bindings selected with `-Dotp=<major>` for OTP 27, 28, and 29 (including OTP 29's NIF 2.18 additions like `enif_term_size`). Releases are tagged in Git so `build.zig.zon` pins a `cement` version independently of the OTP target.
Verified combinations: OTP 27 + Elixir 1.18, OTP 28 + Elixir 1.19, and OTP 29 + Elixir 1.20.5 on Linux (`aarch64`). macOS shares the same Unix NIF ABI. Basic Windows path and `.zip` handling are wired up on the Mix side, though Windows `TWinDynNifCallbacks` bindings in `cement` are untested and open for PRs.
## Maintainer workflow
To generate and diff `erl_nif` bindings for a new OTP major release without vendoring `translate-c` in the package:
```sh
./tools/gen_erl_nif.sh 29
# or against a custom Erlang build:
./tools/gen_erl_nif.sh 29 --header /path/to/erts-X/include/erl_nif.h
```
Add the new `otp_<major>.zig` entry to `OtpVersion` in `build.zig`, then run:
```sh
nix develop
zig build test -Dotp=27
zig build test -Dotp=28
zig build test -Dotp=29
mix test --warnings-as-errors
```
## Acknowledgments
Portions of `src/` are adapted from [Zigler](https://github.com/E-xyza/zigler) under the MIT license.
## License
MIT. See [LICENSE](LICENSE).