Skip to main content

alef_backend_zig/gen_bindings/
mod.rs

1use alef_core::backend::{Backend, BuildConfig, BuildDependency, Capabilities, GeneratedFile};
2use alef_core::config::{AdapterPattern, Language, ResolvedCrateConfig, resolve_output_dir};
3use alef_core::ir::{ApiSurface, TypeRef};
4use std::fmt::Write as FmtWrite;
5use std::path::PathBuf;
6
7use crate::trait_bridge::emit_trait_bridge;
8
9mod errors;
10mod functions;
11mod helpers;
12mod opaque_handles;
13mod types;
14
15use errors::emit_error_set;
16use functions::emit_function;
17use helpers::emit_helpers;
18use opaque_handles::emit_opaque_handle;
19use types::{emit_enum, emit_type};
20
21fn zig_module_name(crate_name: &str) -> String {
22    crate_name.replace('-', "_")
23}
24
25pub struct ZigBackend;
26
27fn type_references_excluded(ty: &TypeRef, exclude_types: &std::collections::HashSet<String>) -> bool {
28    exclude_types.iter().any(|name| ty.references_named(name))
29}
30
31fn signature_references_excluded(
32    params: &[alef_core::ir::ParamDef],
33    return_type: &TypeRef,
34    exclude_types: &std::collections::HashSet<String>,
35) -> bool {
36    type_references_excluded(return_type, exclude_types)
37        || params
38            .iter()
39            .any(|param| type_references_excluded(&param.ty, exclude_types))
40}
41
42impl Backend for ZigBackend {
43    fn name(&self) -> &str {
44        "zig"
45    }
46
47    fn language(&self) -> Language {
48        Language::Zig
49    }
50
51    fn capabilities(&self) -> Capabilities {
52        Capabilities {
53            supports_async: false,
54            supports_classes: true,
55            supports_enums: true,
56            supports_option: true,
57            supports_result: true,
58            supports_callbacks: false,
59            supports_streaming: false,
60        }
61    }
62
63    fn generate_bindings(&self, api: &ApiSurface, config: &ResolvedCrateConfig) -> anyhow::Result<Vec<GeneratedFile>> {
64        let module_name = zig_module_name(&config.name);
65        let header = config.ffi_header_name();
66        let prefix = config.ffi_prefix();
67
68        let mut exclude_functions: std::collections::HashSet<String> = config
69            .zig
70            .as_ref()
71            .map(|c| c.exclude_functions.iter().cloned().collect())
72            .unwrap_or_default();
73        let mut exclude_types: std::collections::HashSet<String> = config
74            .ffi
75            .as_ref()
76            .map(|c| c.exclude_types.iter().cloned().collect())
77            .unwrap_or_default();
78        if let Some(zig) = &config.zig {
79            exclude_types.extend(zig.exclude_types.iter().cloned());
80        }
81        if let Some(ffi) = &config.ffi {
82            exclude_functions.extend(ffi.exclude_functions.iter().cloned());
83        }
84
85        let type_is_visible = |name: &str| !exclude_types.contains(name);
86        let method_is_visible = |method: &alef_core::ir::MethodDef| {
87            !signature_references_excluded(&method.params, &method.return_type, &exclude_types)
88        };
89
90        let visible_api;
91        let api = if exclude_types.is_empty() {
92            api
93        } else {
94            visible_api = {
95                let mut filtered = api.clone();
96                filtered.types.retain(|typ| type_is_visible(&typ.name));
97                for typ in &mut filtered.types {
98                    typ.fields
99                        .retain(|field| !type_references_excluded(&field.ty, &exclude_types));
100                    typ.methods.retain(method_is_visible);
101                }
102                filtered.enums.retain(|en| !exclude_types.contains(&en.name));
103                filtered
104                    .functions
105                    .retain(|func| !signature_references_excluded(&func.params, &func.return_type, &exclude_types));
106                filtered
107            };
108            &visible_api
109        };
110
111        let mut content = String::new();
112        content.push_str("// Generated by alef. Do not edit by hand.\n");
113        content.push('\n');
114        content.push_str("const std = @import(\"std\");\n");
115        content.push_str(&crate::template_env::render(
116            "c_import.jinja",
117            minijinja::context! {
118                header => header,
119            },
120        ));
121        content.push('\n');
122
123        // Emit helper wrappers for FFI error introspection and string ownership.
124        emit_helpers(&prefix, &mut content);
125        content.push('\n');
126
127        // Z1 fix: emit opaque pointer type aliases for every configured trait bridge
128        // that declares a `type_alias`. These aliases are referenced in struct fields
129        // (e.g. `visitor: ?VisitorHandle`) but the Zig backend previously never declared
130        // them, causing "use of undeclared identifier" errors in Zig 0.16+.
131        for bridge in &config.trait_bridges {
132            if bridge.exclude_languages.iter().any(|lang| lang == "zig") {
133                continue;
134            }
135            if let Some(alias) = &bridge.type_alias {
136                let _ = writeln!(content, "/// Opaque handle for a `{alias}` trait-bridge instance.",);
137                let _ = writeln!(content, "pub const {alias} = *anyopaque;");
138                content.push('\n');
139            }
140        }
141
142        for error in &api.errors {
143            emit_error_set(error, &mut content);
144            content.push('\n');
145        }
146
147        for ty in api
148            .types
149            .iter()
150            .filter(|t| !exclude_types.contains(&t.name) && !t.is_opaque && t.has_serde)
151        {
152            emit_type(ty, &mut content);
153            content.push('\n');
154        }
155
156        for en in api.enums.iter().filter(|e| !exclude_types.contains(&e.name)) {
157            emit_enum(en, &mut content);
158            content.push('\n');
159        }
160
161        let declared_errors: Vec<String> = api.errors.iter().map(|e| e.name.clone()).collect();
162        // Collect all top-level decl names so we can rename param names that would
163        // shadow them. Zig 0.16 forbids parameter shadowing of file-scope decls.
164        let mut top_level_names: std::collections::HashSet<String> = std::collections::HashSet::new();
165        for f in &api.functions {
166            top_level_names.insert(f.name.clone());
167        }
168        for ty in &api.types {
169            top_level_names.insert(ty.name.clone());
170        }
171        for en in &api.enums {
172            top_level_names.insert(en.name.clone());
173        }
174        // Set of struct (non-enum, non-trait) type names. Function parameters
175        // typed as `Named(name)` where `name ∈ struct_names` are passed across
176        // the FFI as opaque handles via JSON, since cbindgen emits them as
177        // opaque types in the generated header.
178        let struct_names: std::collections::HashSet<String> = api
179            .types
180            .iter()
181            .filter(|t| !t.is_trait && !t.is_opaque && t.has_serde)
182            .map(|t| t.name.clone())
183            .collect();
184        // For opaque handle types (is_opaque = true or has_serde = false), find the
185        // creator function in api.functions that returns that type. The map stores:
186        //   opaque_type_name -> (creator_fn_name, config_type_snake_case)
187        // Used by emit_function to generate create+use+free patterns for handle params.
188        let opaque_creator_map: std::collections::HashMap<String, (String, String)> = {
189            let mut map = std::collections::HashMap::new();
190            for opaque_ty in api
191                .types
192                .iter()
193                .filter(|t| !t.is_trait && (t.is_opaque || !t.has_serde))
194            {
195                if let Some(creator) = api
196                    .functions
197                    .iter()
198                    .find(|f| matches!(&f.return_type, alef_core::ir::TypeRef::Named(n) if n == &opaque_ty.name))
199                {
200                    if let Some(config_param) = creator.params.first() {
201                        if let Some(config_name) = functions::opaque_type_name_inner(&config_param.ty) {
202                            map.insert(
203                                opaque_ty.name.clone(),
204                                (creator.name.clone(), heck::AsSnakeCase(config_name).to_string()),
205                            );
206                        }
207                    }
208                }
209            }
210            map
211        };
212
213        // Functions matching `register_{trait_snake}` / `unregister_{trait_snake}` for
214        // any configured trait bridge are emitted by `emit_trait_bridge` with a
215        // proper vtable signature. Skip the regular C-FFI shim to avoid duplicate
216        // function definitions.
217        let trait_bridge_fn_names: std::collections::HashSet<String> = config
218            .trait_bridges
219            .iter()
220            .filter(|b| !b.exclude_languages.iter().any(|lang| lang == "zig"))
221            .filter_map(|b| {
222                api.types
223                    .iter()
224                    .find(|t| t.name == b.trait_name && t.is_trait)
225                    .map(|t| heck::AsSnakeCase(&t.name).to_string())
226            })
227            .flat_map(|snake| [format!("register_{snake}"), format!("unregister_{snake}")])
228            .collect();
229        for f in api.functions.iter().filter(|f| !exclude_functions.contains(&f.name)) {
230            if trait_bridge_fn_names.contains(&f.name) {
231                continue;
232            }
233            emit_function(
234                f,
235                &prefix,
236                &declared_errors,
237                &top_level_names,
238                &struct_names,
239                &opaque_creator_map,
240                &mut content,
241            );
242            content.push('\n');
243        }
244
245        // Emit C-vtable structs and registration shims for every configured trait bridge.
246        // Zig has no inheritance; trait bridges use an `extern struct` of function pointers.
247        for bridge_cfg in &config.trait_bridges {
248            // Skip if "zig" is listed in exclude_languages for this bridge.
249            if bridge_cfg.exclude_languages.iter().any(|lang| lang == "zig") {
250                continue;
251            }
252            if let Some(trait_def) = api.types.iter().find(|t| t.name == bridge_cfg.trait_name && t.is_trait) {
253                emit_trait_bridge(&prefix, bridge_cfg, trait_def, &mut content);
254                content.push('\n');
255            }
256        }
257
258        // Build a map of method_name -> item_type for Streaming adapters.
259        // Used by emit_opaque_handle to emit iterator-based bodies instead of
260        // the generic method wrapper (which would call the callback-based C symbol
261        // with the wrong argument count).
262        let streaming_item_types: std::collections::HashMap<String, String> = config
263            .adapters
264            .iter()
265            .filter(|a| matches!(a.pattern, AdapterPattern::Streaming))
266            .filter_map(|a| a.item_type.as_ref().map(|item| (a.name.clone(), item.clone())))
267            .collect();
268
269        // Emit Zig struct wrappers for opaque handle types that have methods.
270        // These types are pointer-wrapped C handles; they are not JSON-serializable
271        // and require method dispatch via the FFI symbol naming convention
272        // `{prefix}_{snake_type}_{snake_method}`.
273        for ty in api
274            .types
275            .iter()
276            .filter(|t| !t.is_trait && (t.is_opaque || !t.has_serde) && !t.methods.is_empty())
277            .filter(|t| !exclude_types.contains(&t.name))
278        {
279            emit_opaque_handle(
280                ty,
281                &prefix,
282                &declared_errors,
283                &struct_names,
284                &streaming_item_types,
285                &mut content,
286            );
287            content.push('\n');
288        }
289
290        let dir = resolve_output_dir(None, &config.name, "packages/zig/src");
291        let path = PathBuf::from(dir).join(format!("{module_name}.zig"));
292
293        Ok(vec![GeneratedFile {
294            path,
295            content,
296            generated_header: false,
297        }])
298    }
299
300    fn build_config(&self) -> Option<BuildConfig> {
301        Some(BuildConfig {
302            tool: "zig",
303            crate_suffix: "",
304            build_dep: BuildDependency::Ffi,
305            post_build: vec![],
306        })
307    }
308}