Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ jobs:
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
# moonbit removed from language matrix for now - causing CI failures
lang: [c, rust, csharp, cpp, go, d]
lang: [c, rust, csharp, cpp, go, d, zig]
exclude:
# For now csharp doesn't work on macos, so exclude it from testing.
- os: macos-latest
Expand Down Expand Up @@ -127,6 +127,25 @@ jobs:
compiler: ldc-1.42
if: matrix.lang == 'd'

- name: Setup Zig (Linux)
run: |
curl --retry 5 --retry-all-errors -sL https://ziglang.org/download/0.16.0/zig-x86_64-linux-0.16.0.tar.xz | tar -xJ
echo "$(pwd)/zig-x86_64-linux-0.16.0" >> $GITHUB_PATH
if: matrix.lang == 'zig' && matrix.os == 'ubuntu-latest'

- name: Setup Zig (macOS)
run: |
curl --retry 5 --retry-all-errors -sL https://ziglang.org/download/0.16.0/zig-aarch64-macos-0.16.0.tar.xz | tar -xJ
echo "$(pwd)/zig-aarch64-macos-0.16.0" >> $GITHUB_PATH
if: matrix.lang == 'zig' && matrix.os == 'macos-latest'

- name: Setup Zig (Windows)
run: |
curl --retry 5 --retry-all-errors -sLO https://ziglang.org/download/0.16.0/zig-x86_64-windows-0.16.0.zip
unzip -q zig-x86_64-windows-0.16.0.zip
echo "$(pwd)/zig-x86_64-windows-0.16.0" >> $GITHUB_PATH
if: matrix.lang == 'zig' && matrix.os == 'windows-latest'

# Hacky work-around for https://github.com/dotnet/runtime/issues/80619
- run: dotnet new console -o /tmp/foo
if: matrix.os != 'windows-latest' && matrix.lang == 'csharp'
Expand Down Expand Up @@ -206,6 +225,7 @@ jobs:
- run: cargo build --no-default-features --features csharp
- run: cargo build --no-default-features --features markdown
- run: cargo build --no-default-features --features moonbit
- run: cargo build --no-default-features --features zig

# Feature combos of the `wit-bindgen` crate
- run: cargo build --target wasm32-wasip1 -p wit-bindgen --no-default-features
Expand Down
11 changes: 11 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ wit-bindgen-markdown = { path = 'crates/markdown', version = '0.63.0' }
wit-bindgen-moonbit = { path = 'crates/moonbit', version = '0.63.0' }
wit-bindgen-go = { path = 'crates/go', version = '0.63.0' }
wit-bindgen-d = { path = 'crates/d', version = '0.63.0' }
wit-bindgen-zig = { path = 'crates/zig', version = '0.63.0' }
wit-bindgen-test = { path = 'crates/test', version = '0.63.0' }

[workspace.lints.clippy]
Expand Down Expand Up @@ -96,6 +97,7 @@ wit-bindgen-moonbit = { workspace = true, features = ['clap'], optional = true }
wit-bindgen-csharp = { workspace = true, features = ['clap'], optional = true }
wit-bindgen-go = { workspace = true, features = ['clap'], optional = true }
wit-bindgen-d = { workspace = true, features = ['clap'], optional = true }
wit-bindgen-zig = { workspace = true, features = ['clap'], optional = true }
wit-bindgen-test = { workspace = true }
wit-component = { workspace = true }
wasm-encoder = { workspace = true }
Expand All @@ -111,6 +113,7 @@ default = [
'cpp',
'moonbit',
'd',
'zig',
'async'
]
c = ['dep:wit-bindgen-c']
Expand All @@ -122,4 +125,5 @@ csharp = ['dep:wit-bindgen-csharp']
csharp-mono = ['csharp']
moonbit = ['dep:wit-bindgen-moonbit']
d = ['dep:wit-bindgen-d']
zig = ['dep:wit-bindgen-zig']
async = []
57 changes: 56 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ between bindings definitions.

The `wit-bindgen` repository is currently focused on **guest** programs which
are those compiled to WebAssembly. Languages developed in this repository are
Rust, C, C++, C#, and Go. For other languages see the [documentation
Rust, C, C++, C#, Go, D, and Zig. For other languages see the [documentation
below](#guest-other-languages).

Executing a component in a host is not
Expand Down Expand Up @@ -431,6 +431,61 @@ To avoid touching the files during regeneration (including `moon.pkg` or `moon.m

/!\ MoonBit is still evolving, so please check out the [Weekly Updates](https://www.moonbitlang.com/weekly-updates/) for any breaking changes or deprecations.

### Guest: Zig

See the [`wit-bindgen-zig` README.md](crates/zig/README.md) for complete documentation on type mappings, memory and resource lifetimes, and `build.zig` integration.

Generate the Zig bindings for `wit/host.wit` using the [`wit-bindgen` CLI][cli-install]:

```sh
wit-bindgen zig ./wit --out-dir src/bindings
# Generating "src/bindings/wit.zig"
# Generating "src/bindings/wit/abi.zig"
# Generating "src/bindings/wit/exports.zig"
# Generating "src/bindings/wit/root.zig"
```

Implement the guest component by importing the generated `wit` module and registering your export functions in a `comptime` block:

```zig
// src/guest.zig
const wit = @import("wit");

comptime {
wit.exports.run(run);
}

fn run() void {
wit.root.print("Hello, world!");
}
```

Compile the guest as a WebAssembly reactor module with `zig` (0.16.0 or newer), embed the WIT metadata, and produce a component with [`wasm-tools`]:

```sh
zig build-exe \
-target wasm32-wasi \
-O ReleaseSmall \
-fno-entry \
-rdynamic \
-mexec-model=reactor \
--dep wit \
-Mroot=src/guest.zig \
-Mwit=src/bindings/wit.zig \
-femit-bin=my-core.wasm

wasm-tools component embed ./wit my-core.wasm -o my-embedded.wasm
wasm-tools component new my-embedded.wasm \
--adapt wasi_snapshot_preview1.reactor.wasm \
-o my-component.wasm
```

You can then inspect the resulting component's WIT interface with:

```sh
wasm-tools component wit ./my-component.wasm
```

### Guest: Other Languages

A (non-exhaustive) list of other languages known to support components are:
Expand Down
1 change: 1 addition & 0 deletions ci/publish.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ const CRATES_TO_PUBLISH: &[&str] = &[
"wit-bindgen-moonbit",
"wit-bindgen-go",
"wit-bindgen-d",
"wit-bindgen-zig",
"wit-bindgen-rust-macro",
"wit-bindgen-rt",
"wit-bindgen",
Expand Down
5 changes: 5 additions & 0 deletions crates/test/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ mod moonbit;
mod runner;
mod rust;
mod wat;
mod zig;

/// Tool to run tests that exercise the `wit-bindgen` bindings generator.
///
Expand Down Expand Up @@ -231,6 +232,7 @@ enum Language {
MoonBit,
Go,
D,
Zig,
Custom(custom::Language),
}

Expand Down Expand Up @@ -454,6 +456,7 @@ impl Runner {
"mbt" => Language::MoonBit,
"go" => Language::Go,
"d" => Language::D,
"zig" => Language::Zig,
other => Language::Custom(custom::Language::lookup(self, other)?),
};

Expand Down Expand Up @@ -1357,6 +1360,7 @@ impl Language {
Language::MoonBit,
Language::Go,
Language::D,
Language::Zig,
];

fn obj(&self) -> &dyn LanguageMethods {
Expand All @@ -1369,6 +1373,7 @@ impl Language {
Language::MoonBit => &moonbit::MoonBit,
Language::Go => &go::Go,
Language::D => &d::D,
Language::Zig => &zig::Zig,
Language::Custom(custom) => custom,
}
}
Expand Down
143 changes: 143 additions & 0 deletions crates/test/src/zig.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
use crate::{Compile, LanguageMethods, Runner, Verify};
use anyhow::{Context, Result, bail};
use std::fs;
use std::process::Command;

pub struct Zig;

impl LanguageMethods for Zig {
fn display(&self) -> &str {
"zig"
}

fn comment_prefix_for_test_config(&self) -> Option<&str> {
Some("//@")
}

fn should_fail_verify(
&self,
_runner: &Runner,
name: &str,
config: &crate::config::WitConfig,
_args: &[String],
) -> bool {
config.async_
|| config.error_context

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

async_ should cover future and stream already.

And that I believe that resource-borrow-in-record error should be fixed, not ignored.

|| name.contains("future")
|| name.contains("stream")
|| name.contains("map")
|| name.contains("resource-borrow-in-record")
// Guest-exported resources and borrowed handles inside aggregates
// are not yet supported by `wit-bindgen-zig`.
|| matches!(
name,
"import-and-export-resource.wit"
| "import-and-export-resource-alias.wit"
| "issue929.wit"
| "issue929-no-import.wit"
| "issue929-only-methods.wit"
| "issue1466.wit"
| "issue1658.wit"
| "issue-1658.wit"
| "issue1703.wit"
| "issue1731.wit"
| "resource-alias.wit"
| "resource-fallible-constructor.wit"
| "resource-local-alias.wit"
| "resource-local-alias-borrow.wit"
| "resources.wit"
| "resources-in-aggregates.wit"
| "resources-with-lists.wit"
)
}

fn prepare(&self, runner: &mut Runner) -> Result<()> {
println!("Testing if `zig` toolchain exists...");
if runner
.run_command(Command::new("zig").arg("version"))
.is_err()
{
bail!("`zig` toolchain not found");
}
Ok(())
}

fn compile(&self, runner: &Runner, compile: &Compile<'_>) -> Result<()> {
let output = compile.output.with_extension("core.wasm");
let wit_root = compile.bindings_dir.join("wit.zig");

let mut cmd = Command::new("zig");
cmd.arg("build-exe")
.arg("-target")
.arg("wasm32-wasi")
.arg("-O")
.arg("ReleaseSafe")
.arg("-fno-entry")
.arg("-rdynamic")
.arg("-mexec-model=reactor")
.arg("--dep")
.arg("wit")
.arg(format!("-Mroot={}", compile.component.path.display()))
.arg(format!("-Mwit={}", wit_root.display()))
.arg(format!("-femit-bin={}", output.display()));

runner.run_command(&mut cmd)?;

runner
.convert_core_module_to_component(&output, compile)
.with_context(|| format!("failed to convert {output:?}"))?;

Ok(())
}

fn verify(&self, runner: &Runner, verify: &Verify<'_>) -> Result<()> {
let check_zig = verify.artifacts_dir.join("check.zig");
let wit_root = verify.bindings_dir.join("wit.zig");
let tmp_obj = verify.artifacts_dir.join("check.o");

let check_src = r#"const std = @import("std");
const wit = @import("wit");

fn collect(comptime T: type) []const *const anyopaque {
var out: []const *const anyopaque = &.{};
for (std.meta.declarations(T)) |decl| {
const Decl = @TypeOf(@field(T, decl.name));
if (Decl == type) {
const Inner = @field(T, decl.name);
switch (@typeInfo(Inner)) {
.@"struct", .@"enum", .@"union" => out = out ++ collect(Inner),
else => {},
}
} else if (@typeInfo(Decl) == .@"fn" and !@typeInfo(Decl).@"fn".is_generic) {
out = out ++ [1]*const anyopaque{@ptrCast(&@field(T, decl.name))};
}
}
return out;
}

const all = blk: {
@setEvalBranchQuota(10_000_000);
const list = collect(wit);
break :blk list[0..list.len].*;
};

export const table: [all.len]*const anyopaque = all;
"#;
fs::write(&check_zig, check_src)?;

let mut cmd = Command::new("zig");
cmd.arg("build-obj")
.arg("-target")
.arg("wasm32-wasi")
.arg("-O")
.arg("ReleaseSmall")
.arg("--dep")
.arg("wit")
.arg(format!("-Mroot={}", check_zig.display()))
.arg(format!("-Mwit={}", wit_root.display()))
.arg(format!("-femit-bin={}", tmp_obj.display()));

runner.run_command(&mut cmd)?;
Ok(())
}
}
27 changes: 27 additions & 0 deletions crates/zig/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
[package]
name = "wit-bindgen-zig"
version = { workspace = true }
edition = { workspace = true }
repository = { workspace = true }
license = { workspace = true }
rust-version = { workspace = true }
description = """
Zig bindings generator for WIT and the component model, typically used through
the `wit-bindgen-cli` crate.
"""

[lints]
workspace = true

[lib]
doctest = false
test = false

[dependencies]
anyhow = { workspace = true }
clap = { workspace = true, optional = true }
indexmap = { workspace = true }
wit-bindgen-core = { workspace = true }

[features]
clap = ['dep:clap', 'wit-bindgen-core/clap']
Loading
Loading