Skip to main content

alef_backend_zig/gen_bindings/
mod.rs

1use alef_core::backend::{Backend, BuildConfig, BuildDependency, Capabilities, GeneratedFile};
2use alef_core::config::{Language, ResolvedCrateConfig, resolve_output_dir};
3use alef_core::ir::ApiSurface;
4use std::path::PathBuf;
5
6use crate::trait_bridge::emit_trait_bridge;
7
8mod errors;
9mod functions;
10mod helpers;
11mod types;
12
13use errors::emit_error_set;
14use functions::emit_function;
15use helpers::emit_helpers;
16use types::{emit_enum, emit_type};
17
18fn zig_module_name(crate_name: &str) -> String {
19    crate_name.replace('-', "_")
20}
21
22pub struct ZigBackend;
23
24impl Backend for ZigBackend {
25    fn name(&self) -> &str {
26        "zig"
27    }
28
29    fn language(&self) -> Language {
30        Language::Zig
31    }
32
33    fn capabilities(&self) -> Capabilities {
34        Capabilities {
35            supports_async: false,
36            supports_classes: false,
37            supports_enums: true,
38            supports_option: true,
39            supports_result: true,
40            supports_callbacks: false,
41            supports_streaming: false,
42        }
43    }
44
45    fn generate_bindings(&self, api: &ApiSurface, config: &ResolvedCrateConfig) -> anyhow::Result<Vec<GeneratedFile>> {
46        let module_name = zig_module_name(&config.name);
47        let header = config.ffi_header_name();
48        let prefix = config.ffi_prefix();
49
50        let exclude_functions: std::collections::HashSet<&str> = config
51            .zig
52            .as_ref()
53            .map(|c| c.exclude_functions.iter().map(String::as_str).collect())
54            .unwrap_or_default();
55        let exclude_types: std::collections::HashSet<&str> = config
56            .zig
57            .as_ref()
58            .map(|c| c.exclude_types.iter().map(String::as_str).collect())
59            .unwrap_or_default();
60
61        let has_async = api
62            .functions
63            .iter()
64            .filter(|f| !exclude_functions.contains(f.name.as_str()))
65            .any(|f| f.is_async);
66
67        let mut content = String::new();
68        content.push_str("// Generated by alef. Do not edit by hand.\n");
69        if has_async {
70            content.push_str("// Async functions are not supported in this backend.\n");
71        }
72        content.push('\n');
73        content.push_str("const std = @import(\"std\");\n");
74        content.push_str(&format!("pub const c = @cImport(@cInclude(\"{header}\"));\n\n"));
75
76        // Emit helper wrappers for FFI error introspection and string ownership.
77        emit_helpers(&prefix, &mut content);
78        content.push('\n');
79
80        for error in &api.errors {
81            emit_error_set(error, &mut content);
82            content.push('\n');
83        }
84
85        for ty in api.types.iter().filter(|t| !exclude_types.contains(t.name.as_str())) {
86            emit_type(ty, &mut content);
87            content.push('\n');
88        }
89
90        for en in api.enums.iter().filter(|e| !exclude_types.contains(e.name.as_str())) {
91            emit_enum(en, &mut content);
92            content.push('\n');
93        }
94
95        let declared_errors: Vec<String> = api.errors.iter().map(|e| e.name.clone()).collect();
96        // Collect all top-level decl names so we can rename param names that would
97        // shadow them. Zig 0.16 forbids parameter shadowing of file-scope decls.
98        let mut top_level_names: std::collections::HashSet<String> = std::collections::HashSet::new();
99        for f in &api.functions {
100            top_level_names.insert(f.name.clone());
101        }
102        for ty in &api.types {
103            top_level_names.insert(ty.name.clone());
104        }
105        for en in &api.enums {
106            top_level_names.insert(en.name.clone());
107        }
108        // Functions matching `register_{trait_snake}` / `unregister_{trait_snake}` for
109        // any configured trait bridge are emitted by `emit_trait_bridge` with a
110        // proper vtable signature. Skip the regular C-FFI shim to avoid duplicate
111        // function definitions.
112        let trait_bridge_fn_names: std::collections::HashSet<String> = config
113            .trait_bridges
114            .iter()
115            .filter(|b| !b.exclude_languages.iter().any(|lang| lang == "zig"))
116            .filter_map(|b| {
117                api.types
118                    .iter()
119                    .find(|t| t.name == b.trait_name && t.is_trait)
120                    .map(|t| heck::AsSnakeCase(&t.name).to_string())
121            })
122            .flat_map(|snake| [format!("register_{snake}"), format!("unregister_{snake}")])
123            .collect();
124        for f in api
125            .functions
126            .iter()
127            .filter(|f| !exclude_functions.contains(f.name.as_str()))
128        {
129            // Async functions are not supported — skip silently.
130            if f.is_async {
131                continue;
132            }
133            if trait_bridge_fn_names.contains(&f.name) {
134                continue;
135            }
136            emit_function(f, &prefix, &declared_errors, &top_level_names, &mut content);
137            content.push('\n');
138        }
139
140        // Emit C-vtable structs and registration shims for every configured trait bridge.
141        // Zig has no inheritance; trait bridges use an `extern struct` of function pointers.
142        for bridge_cfg in &config.trait_bridges {
143            // Skip if "zig" is listed in exclude_languages for this bridge.
144            if bridge_cfg.exclude_languages.iter().any(|lang| lang == "zig") {
145                continue;
146            }
147            if let Some(trait_def) = api.types.iter().find(|t| t.name == bridge_cfg.trait_name && t.is_trait) {
148                emit_trait_bridge(&prefix, bridge_cfg, trait_def, &mut content);
149                content.push('\n');
150            }
151        }
152
153        let dir = resolve_output_dir(None, &config.name, "packages/zig/src");
154        let path = PathBuf::from(dir).join(format!("{module_name}.zig"));
155
156        Ok(vec![GeneratedFile {
157            path,
158            content,
159            generated_header: false,
160        }])
161    }
162
163    fn build_config(&self) -> Option<BuildConfig> {
164        Some(BuildConfig {
165            tool: "zig",
166            crate_suffix: "",
167            build_dep: BuildDependency::Ffi,
168            post_build: vec![],
169        })
170    }
171}