alef 0.84.2

Opinionated polyglot binding generator for Rust libraries
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
//! Zig package — archives the source code + FFI shared library for distribution.

use super::PackageArtifact;
use super::util::copy_dir_recursive;
use crate::core::config::ResolvedCrateConfig;
use crate::publish::platform::RustTarget;
use anyhow::{Context, Result};
use std::fs;
use std::path::Path;

/// Package Zig bindings as a source distribution with bundled FFI library.
///
/// Produces: `{name}-zig-v{version}-{platform}.tar.gz` containing:
/// - `src/` — Zig source code
/// - `lib/` — FFI shared library (.so/.dylib)
/// - `include/` — C header
/// - `build.zig`, `build.zig.zon` — Zig build files
pub fn package_zig(
    config: &ResolvedCrateConfig,
    target: &RustTarget,
    workspace_root: &Path,
    output_dir: &Path,
    version: &str,
) -> Result<PackageArtifact> {
    let lib_name = config.ffi_lib_name();
    let header_name = config.ffi_header_name();
    let module_name = config.zig_module_name();
    let crate_name = &config.name;
    let pkg_dir = config.package_dir(crate::core::config::extras::Language::Zig);
    let platform = target.platform_for(crate::core::config::extras::Language::Zig);

    let pkg_name = format!("{crate_name}-zig-v{version}-{platform}");
    let staging = output_dir.join(&pkg_name);

    if staging.exists() {
        fs::remove_dir_all(&staging)?;
    }
    fs::create_dir_all(&staging)?;

    let pkg_src = workspace_root.join(&pkg_dir);
    if !pkg_src.exists() {
        anyhow::bail!("Zig package directory not found: {}", pkg_dir);
    }

    copy_dir_recursive(&pkg_src, &staging).context("copying Zig package")?;

    let lib_dir = staging.join("lib");
    let include_dir = staging.join("include");
    fs::create_dir_all(&lib_dir)?;
    fs::create_dir_all(&include_dir)?;

    // Packaging always ships a `--release` build -- nothing here is publishable in `debug`. ~keep
    let shared_lib = target.shared_lib_name(&lib_name);
    let shared_src = super::find_built_artifact(workspace_root, target, &shared_lib, super::BuildProfile::Release)
        .with_context(|| format!("locating built FFI artifact `{shared_lib}` for Zig package"))?;
    let shared_dst = lib_dir.join(&shared_lib);
    fs::copy(&shared_src, &shared_dst).context("copying FFI .so into Zig package")?;

    super::util::fix_macos_dylib_id(target, &shared_dst, &shared_lib)?;

    let ffi_crate_dir = crate::publish::ffi_stage::find_ffi_crate_dir_pub(config, workspace_root);
    let header_src = ffi_crate_dir.join("include").join(&header_name);
    if !header_src.exists() {
        anyhow::bail!(
            "FFI C header not found at {} — run `alef build --lang=ffi` first",
            header_src.display()
        );
    }
    fs::copy(&header_src, include_dir.join(&header_name)).context("copying FFI header into Zig package")?;

    add_bundled_paths_to_manifest(&staging.join("build.zig.zon"))?;

    fs::write(
        staging.join("build.zig"),
        render_distributable_build_zig(&module_name, &lib_name, config),
    )
    .context("writing distributable build.zig into Zig package")?;

    let archive_name = format!("{pkg_name}.tar.gz");
    let archive_path = output_dir.join(&archive_name);
    super::create_tar_gz(&staging, &archive_path)?;

    fs::remove_dir_all(&staging).ok();

    Ok(PackageArtifact {
        path: archive_path,
        name: archive_name,
        checksum: None,
    })
}

/// Render the `build.zig` shipped inside the distributed Zig tarball.
///
/// Unlike the in-tree `packages/zig/build.zig` (which links the FFI library from
/// the Cargo workspace `target/` dir for local development), this build script
/// links the prebuilt shared library and C header bundled in the package's own
/// `lib/` and `include/` directories — resolved package-relative via `b.path`,
/// so they work from the global Zig cache when consumed via `zig fetch`. It
/// exports the `{module_name}` module; a consumer links it with
/// `b.dependency("<pkg>", .{ ... }).module("{module_name}")`.
fn render_distributable_build_zig(module_name: &str, ffi_lib_name: &str, config: &ResolvedCrateConfig) -> String {
    let capsule_imports_block: String = config
        .zig
        .as_ref()
        .map(|c| {
            let import_names = crate::core::config::languages::zig_capsule_import_names(&c.capsule_types);
            let mut block = String::new();
            for name in &import_names {
                block.push_str(&format!(
                    "    const {name}_dep = b.dependency(\"{name}\", .{{\n        \
                     .target = target,\n        .optimize = optimize,\n    }});\n    \
                     module.addImport(\"{name}\", {name}_dep.module(\"{name}\"));\n"
                ));
            }
            block
        })
        .unwrap_or_default();
    format!(
        r#"const std = @import("std");

// alef-generated for distribution. The prebuilt FFI library (lib/) and C header
// (include/) ship inside this package; link them package-relative so consumers
// resolve the native library from the fetched package itself.
pub fn build(b: *std.Build) void {{
    const target = b.standardTargetOptions(.{{}});
    const optimize = b.standardOptimizeOption(.{{}});

    const module = b.addModule("{module_name}", .{{
        .root_source_file = b.path("src/{module_name}.zig"),
        .target = target,
        .optimize = optimize,
        .link_libc = true,
    }});
    module.addLibraryPath(b.path("lib"));
    module.addIncludePath(b.path("include"));
    module.linkSystemLibrary("{ffi_lib_name}", .{{}});
{capsule_imports_block}}}
"#
    )
}

/// Directories bundled into the Zig tarball that the manifest's `.paths` allowlist must
/// name for a fetched consumer to resolve them.
const BUNDLED_MANIFEST_PATHS: [&str; 2] = ["lib", "include"];

const PATHS_MARKER: &str = ".paths = .{";

/// Insert the bundled `lib` and `include` directories into a `build.zig.zon`
/// `.paths` allowlist so a fetched consumer can resolve the prebuilt FFI library
/// and header via `b.path("lib")` / `b.path("include")`.
///
/// Idempotence is decided from the `.paths` block alone, not from a substring search over the
/// whole manifest: a `"lib"` or `"include"` literal anywhere else (a dependency name, a URL, a
/// comment) used to satisfy the check and skip the patch entirely, shipping a package whose
/// `b.path("lib")` resolves to nothing. Each entry is also added only when that entry is
/// missing, so a manifest already listing one of them does not end up with it twice. ~keep
fn add_bundled_paths_to_manifest(manifest: &Path) -> Result<()> {
    let zon = fs::read_to_string(manifest).context("reading staged build.zig.zon")?;
    let Some(pos) = zon.find(PATHS_MARKER) else {
        anyhow::bail!("build.zig.zon is missing a `.paths` block: {}", manifest.display());
    };
    let insert_at = pos + PATHS_MARKER.len();
    let paths_block = paths_block_body(&zon[insert_at..]).with_context(|| {
        format!(
            "build.zig.zon has an unterminated `.paths` block: {}",
            manifest.display()
        )
    })?;

    let missing: Vec<&str> = BUNDLED_MANIFEST_PATHS
        .iter()
        .copied()
        .filter(|entry| !paths_block.contains(&format!("\"{entry}\"")))
        .collect();
    if missing.is_empty() {
        return Ok(());
    }

    let mut patched = String::with_capacity(zon.len() + 32);
    patched.push_str(&zon[..insert_at]);
    for entry in missing {
        patched.push_str("\n        \"");
        patched.push_str(entry);
        patched.push_str("\",");
    }
    patched.push_str(&zon[insert_at..]);
    fs::write(manifest, patched).context("writing patched build.zig.zon")?;
    Ok(())
}

/// Body of the `.paths` block, given everything after its opening `.{`.
///
/// Returns `None` when the block is never closed, so a truncated manifest is reported instead
/// of being treated as an empty allowlist.
fn paths_block_body(after_marker: &str) -> Option<&str> {
    let mut depth = 1usize;
    for (index, ch) in after_marker.char_indices() {
        match ch {
            '{' => depth += 1,
            '}' => {
                depth -= 1;
                if depth == 0 {
                    return Some(&after_marker[..index]);
                }
            }
            _ => {}
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::config::NewAlefConfig;

    fn resolve_config(toml_text: &str) -> ResolvedCrateConfig {
        let cfg: NewAlefConfig = toml::from_str(toml_text).expect("valid config");
        cfg.resolve().expect("resolve").remove(0)
    }

    fn config_no_capsule() -> ResolvedCrateConfig {
        resolve_config(
            r#"
[workspace]
languages = ["zig"]
[[crates]]
name = "sample-lib"
sources = []
"#,
        )
    }

    #[test]
    fn distributable_build_zig_links_bundled_lib() {
        let s = render_distributable_build_zig("sample_router", "sample_router_ffi", &config_no_capsule());
        assert!(
            s.contains("b.addModule(\"sample_router\""),
            "must export the module:\n{s}"
        );
        assert!(
            s.contains("module.addLibraryPath(b.path(\"lib\"))"),
            "must link bundled lib/:\n{s}"
        );
        assert!(
            s.contains("module.addIncludePath(b.path(\"include\"))"),
            "must add bundled include/:\n{s}"
        );
        assert!(
            s.contains("module.linkSystemLibrary(\"sample_router_ffi\""),
            "must link the FFI lib:\n{s}"
        );
        assert!(
            s.contains(".link_libc = true"),
            "must link libc for FFI header symbols:\n{s}"
        );
        assert!(!s.contains("cwd_relative"), "must not use cwd_relative paths:\n{s}");
        assert!(
            !s.contains("../../target/release"),
            "must not reference the workspace target dir:\n{s}"
        );
    }

    #[test]
    fn bundled_paths_added_to_manifest_idempotently() {
        let dir = tempfile::tempdir().expect("tempdir");
        let manifest = dir.path().join("build.zig.zon");
        fs::write(
            &manifest,
            ".{\n    .name = .sample_router,\n    .paths = .{\n        \"build.zig\",\n        \"src\",\n    },\n}\n",
        )
        .expect("write manifest");

        add_bundled_paths_to_manifest(&manifest).expect("first patch");
        let once = fs::read_to_string(&manifest).expect("read");
        assert!(once.contains("\"lib\""), "lib added:\n{once}");
        assert!(once.contains("\"include\""), "include added:\n{once}");

        add_bundled_paths_to_manifest(&manifest).expect("second patch");
        let twice = fs::read_to_string(&manifest).expect("read");
        assert_eq!(
            once.matches("\"lib\"").count(),
            twice.matches("\"lib\"").count(),
            "second call must be a no-op"
        );
    }

    /// A `"lib"` / `"include"` literal outside the `.paths` block (here two dependency names)
    /// must not be mistaken for the bundled entries: treating it as "already patched" silently
    /// ships a package whose `b.path("lib")` resolves to nothing.
    #[test]
    fn bundled_paths_added_despite_unrelated_lib_literals_elsewhere() {
        let dir = tempfile::tempdir().expect("tempdir");
        let manifest = dir.path().join("build.zig.zon");
        fs::write(
            &manifest,
            r#".{
    .name = .sample_router,
    .dependencies = .{
        .@"lib" = .{},
        .@"include" = .{},
    },
    .paths = .{
        "build.zig",
        "src",
    },
}
"#,
        )
        .expect("write manifest");

        add_bundled_paths_to_manifest(&manifest).expect("patch");

        let patched = fs::read_to_string(&manifest).expect("read");
        let body = paths_block_body(patched.split_once(PATHS_MARKER).expect("paths block").1).expect("closed block");
        assert!(body.contains("\"lib\""), "lib must be listed in .paths:\n{patched}");
        assert!(
            body.contains("\"include\""),
            "include must be listed in .paths:\n{patched}"
        );
    }

    /// Patching a manifest that already lists one bundled entry must add only the other one --
    /// a blind insert of both duplicates the entry already present.
    #[test]
    fn bundled_paths_adds_only_the_missing_entry() {
        let dir = tempfile::tempdir().expect("tempdir");
        let manifest = dir.path().join("build.zig.zon");
        fs::write(
            &manifest,
            r#".{
    .name = .sample_router,
    .paths = .{
        "build.zig",
        "lib",
    },
}
"#,
        )
        .expect("write manifest");

        add_bundled_paths_to_manifest(&manifest).expect("patch");

        let patched = fs::read_to_string(&manifest).expect("read");
        assert_eq!(
            patched.matches("\"lib\"").count(),
            1,
            "lib must not be duplicated:\n{patched}"
        );
        assert_eq!(
            patched.matches("\"include\"").count(),
            1,
            "include must be added:\n{patched}"
        );
    }

    /// An unterminated `.paths` block is a corrupt manifest, not an empty allowlist.
    #[test]
    fn unterminated_paths_block_is_an_error() {
        let dir = tempfile::tempdir().expect("tempdir");
        let manifest = dir.path().join("build.zig.zon");
        fs::write(&manifest, ".{\n    .paths = .{\n        \"build.zig\",\n").expect("write manifest");

        let error = add_bundled_paths_to_manifest(&manifest).unwrap_err().to_string();
        assert!(
            error.contains("unterminated `.paths` block"),
            "unexpected error: {error}"
        );
    }

    #[test]
    fn packaged_tarball_includes_rewritten_build_zig_and_ffis() {
        let s = render_distributable_build_zig("sample_lib", "sample_lib_ffi", &config_no_capsule());

        assert!(
            !s.contains("../../target/release"),
            "rewritten build.zig must not reference workspace target dir:\n{s}"
        );
        assert!(
            !s.contains("../../crates/sample-lib-ffi"),
            "rewritten build.zig must not reference workspace crate dir:\n{s}"
        );
        assert!(
            !s.contains("cwd_relative"),
            "rewritten build.zig must use package-relative paths only:\n{s}"
        );

        assert!(s.contains("b.path(\"lib\")"), "must link bundled lib/ directory:\n{s}");
        assert!(
            s.contains("b.path(\"include\")"),
            "must link bundled include/ directory:\n{s}"
        );

        assert!(s.contains(".link_libc = true"), "must enable libc linking:\n{s}");
    }

    #[test]
    fn distributable_build_zig_wires_capsule_imports() {
        let config = resolve_config(
            r#"
[workspace]
languages = ["zig"]
[[crates]]
name = "sample-lib"
sources = []

[crates.zig.capsule_types.Language]
host_type = "?*const tree_sitter.Language"
package = "https://github.com/tree-sitter/zig-tree-sitter/archive/refs/tags/v0.26.0.tar.gz"
package_version = "tree_sitter-0.26.0-deadbeef"
"#,
        );
        let s = render_distributable_build_zig("sample_lib", "sample_lib_ffi", &config);

        assert!(
            s.contains("b.dependency(\"tree_sitter\""),
            "distributable build.zig must resolve the capsule dependency:\n{s}"
        );
        assert!(
            s.contains("module.addImport(\"tree_sitter\", tree_sitter_dep.module(\"tree_sitter\"))"),
            "distributable build.zig must import the capsule module:\n{s}"
        );
        assert!(
            !s.contains("test_module"),
            "distributable build.zig must not reference a test module:\n{s}"
        );
    }
}