alef-backend-zig 0.15.5

Zig backend for alef
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
use alef_core::ir::{FunctionDef, ParamDef, TypeRef};

use super::errors::resolve_zig_error_type;
use super::helpers::emit_cleaned_zig_doc;
use super::types::zig_field_type;

/// Returns true if `ty` (or its `Optional<>` inner) is a struct named in
/// `struct_names`. Struct parameters are passed across the FFI as opaque
/// handles, so the wrapper accepts a JSON `[]const u8` and converts to the
/// handle via the FFI's `<prefix>_<snake>_from_json` helper.
fn is_struct_named(ty: &TypeRef, struct_names: &std::collections::HashSet<String>) -> bool {
    match ty {
        TypeRef::Named(name) => struct_names.contains(name),
        TypeRef::Optional(inner) => is_struct_named(inner, struct_names),
        _ => false,
    }
}

/// Return the inner `Named(name)` for a struct parameter type.
fn struct_named_inner(ty: &TypeRef) -> Option<&str> {
    match ty {
        TypeRef::Named(name) => Some(name.as_str()),
        TypeRef::Optional(inner) => struct_named_inner(inner),
        _ => None,
    }
}

fn snake_case(name: &str) -> String {
    heck::AsSnakeCase(name).to_string()
}

pub(crate) fn emit_function(
    f: &FunctionDef,
    prefix: &str,
    declared_errors: &[String],
    top_level_names: &std::collections::HashSet<String>,
    struct_names: &std::collections::HashSet<String>,
    out: &mut String,
) {
    emit_cleaned_zig_doc(out, &f.doc, "");

    // Rename param names that would shadow a top-level decl (Zig 0.16+ rejects
    // shadowing of file-scope identifiers by function parameters).
    let renamed_params: Vec<ParamDef> = f
        .params
        .iter()
        .map(|p| {
            let mut p2 = p.clone();
            if top_level_names.contains(&p2.name) {
                p2.name = format!("{}_arg", p2.name);
            }
            p2
        })
        .collect();
    let f_local = FunctionDef {
        params: renamed_params,
        ..f.clone()
    };
    let f = &f_local;

    // Build the wrapper-level parameter list (Zig-idiomatic types, not raw C types).
    let params: Vec<String> = f.params.iter().map(|p| format_param_wrapper(p, struct_names)).collect();

    let zig_error_type = f
        .error_type
        .as_ref()
        .map(|e| resolve_zig_error_type(e, declared_errors));

    let return_ty = if let Some(error_type) = &zig_error_type {
        format!(
            "({}||error{{OutOfMemory}})!{}",
            error_type,
            zig_return_type(&f.return_type, struct_names)
        )
    } else {
        zig_return_type(&f.return_type, struct_names)
    };

    out.push_str(&crate::template_env::render(
        "function_signature.jinja",
        minijinja::context! {
            func_name => &f.name,
            params => params.join(", "),
            return_ty => &return_ty,
        },
    ));

    // Emit allocation/conversion boilerplate for each parameter.
    for p in &f.params {
        emit_param_conversion(p, prefix, struct_names, out);
    }

    // Build the C argument list.
    let c_args: Vec<String> = f.params.iter().flat_map(|p| c_arg_names(p, struct_names)).collect();
    let c_call = format!("c.{prefix}_{}({})", f.name, c_args.join(", "));

    if let Some(error_type) = &zig_error_type {
        // Fallible function: call C, then check last_error_code(). Zig requires `_`
        // (single underscore) to discard a value; named locals must be used.
        if matches!(f.return_type, TypeRef::Unit) {
            out.push_str(&crate::template_env::render(
                "function_call_unit.jinja",
                minijinja::context! {
                    c_call => &c_call,
                },
            ));
        } else {
            out.push_str(&crate::template_env::render(
                "function_call_result.jinja",
                minijinja::context! {
                    c_call => &c_call,
                },
            ));
        }
        out.push_str(&crate::template_env::render(
            "function_error_check.jinja",
            minijinja::context! {
                prefix => prefix,
            },
        ));
        out.push_str(&crate::template_env::render(
            "function_error_return.jinja",
            minijinja::context! {
                error_type => error_type,
            },
        ));
        out.push_str("    }\n");

        // Free owned C strings after the error check.
        for p in &f.params {
            emit_param_free(p, prefix, struct_names, out);
        }

        // Produce the Zig return value from `_result`.
        if matches!(f.return_type, TypeRef::Unit) {
            out.push_str("    return;\n");
        } else {
            let ret_expr = unwrap_return_expr("_result", &f.return_type, prefix, struct_names);
            out.push_str(&crate::template_env::render(
                "function_return.jinja",
                minijinja::context! {
                    ret_expr => ret_expr,
                },
            ));
        }
    } else {
        // Infallible function: free params, return directly.
        for p in &f.params {
            emit_param_free(p, prefix, struct_names, out);
        }
        if matches!(f.return_type, TypeRef::Unit) {
            out.push_str(&crate::template_env::render(
                "function_call_unit.jinja",
                minijinja::context! {
                    c_call => &c_call,
                },
            ));
        } else {
            out.push_str(&crate::template_env::render(
                "function_call_result.jinja",
                minijinja::context! {
                    c_call => &c_call,
                },
            ));
            let ret_expr = unwrap_return_expr("_result", &f.return_type, prefix, struct_names);
            out.push_str(&crate::template_env::render(
                "function_return.jinja",
                minijinja::context! {
                    ret_expr => ret_expr,
                },
            ));
        }
    }

    out.push_str("}\n");
}

/// Return the Zig-wrapper parameter type string for a function parameter.
fn format_param_wrapper(p: &ParamDef, struct_names: &std::collections::HashSet<String>) -> String {
    let ty_str = zig_param_type(&p.ty, p.optional, struct_names);
    format!("{}: {}", p.name, ty_str)
}

/// Zig type used at the wrapper boundary for a function parameter.
///
/// - `String`, `Path` → `[]const u8`  (body allocates null-terminated copy)
/// - `Bytes`          → `[]const u8`  (body passes `.ptr` + `.len`)
/// - `Vec`, `Map`     → `[]const u8`  (caller supplies JSON; body passes as C string)
/// - `Named` struct   → `[]const u8`  (caller supplies JSON; body converts to opaque
///   handle via the FFI `<prefix>_<snake>_from_json` helper)
/// - Everything else  → same as struct-field type
fn zig_param_type(ty: &TypeRef, optional: bool, struct_names: &std::collections::HashSet<String>) -> String {
    let inner = match ty {
        TypeRef::String | TypeRef::Path | TypeRef::Bytes | TypeRef::Vec(_) | TypeRef::Map(_, _) => {
            "[]const u8".to_string()
        }
        TypeRef::Named(name) if struct_names.contains(name) => "[]const u8".to_string(),
        TypeRef::Optional(inner) => {
            let inner_str = zig_param_type(inner, false, struct_names);
            return format!("?{inner_str}");
        }
        other => zig_field_type(other, false),
    };
    if optional { format!("?{inner}") } else { inner }
}

/// Emit the allocation / conversion lines needed before the C call for `p`.
///
/// String/Path: allocate a null-terminated copy via `std.heap.c_allocator`.
/// Vec/Map:     same — caller supplies a JSON `[]const u8`; we need a sentinel-
///              terminated copy to pass to `*const c_char` parameters.
/// Named struct (opt or required): caller supplies JSON `[]const u8`; we
///              allocate a sentinel-terminated copy and convert it to an
///              opaque FFI handle via `<prefix>_<snake>_from_json`. The
///              optional variant unwraps the optional first and substitutes
///              `null` for the C handle when the wrapper arg is `null`.
/// Bytes:       nothing needed; `.ptr` and `.len` are used directly in `c_arg_names`.
fn emit_param_conversion(
    p: &ParamDef,
    prefix: &str,
    struct_names: &std::collections::HashSet<String>,
    out: &mut String,
) {
    let name = &p.name;
    if let Some(inner_name) = struct_named_inner(&p.ty) {
        if struct_names.contains(inner_name) {
            let snake = snake_case(inner_name);
            // Determine if the wrapper-level type is optional (either the
            // outer TypeRef is Optional, or the param itself is marked optional).
            let is_optional = p.optional || matches!(p.ty, TypeRef::Optional(_));
            if is_optional {
                // Allocate `_z` only when caller passed a value, then convert to
                // an opaque handle. When caller passed null, the C handle is null.
                out.push_str(&format!(
                    "    const {name}_z: ?[:0]u8 = if ({name}) |v| try std.fmt.allocPrintSentinel(\n"
                ));
                out.push_str("        std.heap.c_allocator, \"{s}\", .{v}, 0) else null;\n");
                out.push_str(&format!(
                    "    const {name}_handle = if ({name}_z) |z| c.{prefix}_{snake}_from_json(z) else null;\n",
                ));
            } else {
                out.push_str(&crate::template_env::render(
                    "param_string_line1.jinja",
                    minijinja::context! { name => name },
                ));
                out.push_str(&crate::template_env::render(
                    "param_string_line2.jinja",
                    minijinja::context! { name => name },
                ));
                out.push_str(&format!(
                    "    const {name}_handle = c.{prefix}_{snake}_from_json({name}_z);\n",
                ));
            }
            return;
        }
    }
    // Optional `String`/`Path` parameters arrive as `?[]const u8` and cannot
    // be passed straight to `allocPrintSentinel("{s}", ...)` (Zig's writer
    // refuses to format an optional). Emit conditional allocation that maps
    // `null` → `null` and a value → an owned sentinel-terminated copy.
    let is_optional_string = p.optional
        || matches!(
            &p.ty,
            TypeRef::Optional(inner)
                if matches!(inner.as_ref(), TypeRef::String | TypeRef::Path)
        );
    if is_optional_string && matches!(unwrap_optional(&p.ty), TypeRef::String | TypeRef::Path) {
        out.push_str(&format!(
            "    const {name}_z: ?[:0]u8 = if ({name}) |v| try std.fmt.allocPrintSentinel(\n"
        ));
        out.push_str("        std.heap.c_allocator, \"{s}\", .{v}, 0) else null;\n");
        return;
    }
    match &p.ty {
        TypeRef::String | TypeRef::Path => {
            out.push_str(&crate::template_env::render(
                "param_string_line1.jinja",
                minijinja::context! {
                    name => name,
                },
            ));
            out.push_str(&crate::template_env::render(
                "param_string_line2.jinja",
                minijinja::context! {
                    name => name,
                },
            ));
        }
        TypeRef::Vec(_) | TypeRef::Map(_, _) => {
            // Caller supplies JSON bytes; we need a null-terminated C string copy.
            out.push_str("    // Vec/Map parameters are passed as JSON strings across the FFI boundary.\n");
            out.push_str(&crate::template_env::render(
                "param_string_line1.jinja",
                minijinja::context! {
                    name => name,
                },
            ));
            out.push_str(&crate::template_env::render(
                "param_string_line2.jinja",
                minijinja::context! {
                    name => name,
                },
            ));
        }
        _ => {
            // No conversion needed — Bytes uses .ptr/.len directly, primitives pass through.
        }
    }
}

/// Strip a single `Optional<>` layer if present.
fn unwrap_optional(ty: &TypeRef) -> &TypeRef {
    match ty {
        TypeRef::Optional(inner) => inner,
        other => other,
    }
}

/// Emit the deallocation lines for allocations made in `emit_param_conversion`.
///
/// These are emitted after the C call (and after the error check) so the
/// allocations are always freed even when an error is returned.
fn emit_param_free(p: &ParamDef, prefix: &str, struct_names: &std::collections::HashSet<String>, out: &mut String) {
    let name = &p.name;
    if let Some(inner_name) = struct_named_inner(&p.ty) {
        if struct_names.contains(inner_name) {
            let snake = snake_case(inner_name);
            let is_optional = p.optional || matches!(p.ty, TypeRef::Optional(_));
            if is_optional {
                // Free both the JSON sentinel copy and the opaque handle, but
                // only if the caller actually supplied a value.
                out.push_str(&format!("    if ({name}_z) |z| std.heap.c_allocator.free(z);\n"));
                out.push_str(&format!("    if ({name}_handle) |h| c.{prefix}_{snake}_free(h);\n"));
            } else {
                out.push_str(&crate::template_env::render(
                    "param_free.jinja",
                    minijinja::context! { name => name },
                ));
                out.push_str(&format!("    if ({name}_handle) |h| c.{prefix}_{snake}_free(h);\n"));
            }
            return;
        }
    }
    let is_optional_string = p.optional
        || matches!(
            &p.ty,
            TypeRef::Optional(inner)
                if matches!(inner.as_ref(), TypeRef::String | TypeRef::Path)
        );
    if is_optional_string && matches!(unwrap_optional(&p.ty), TypeRef::String | TypeRef::Path) {
        out.push_str(&format!("    if ({name}_z) |z| std.heap.c_allocator.free(z);\n"));
        return;
    }
    match &p.ty {
        TypeRef::String | TypeRef::Path | TypeRef::Vec(_) | TypeRef::Map(_, _) => {
            out.push_str(&crate::template_env::render(
                "param_free.jinja",
                minijinja::context! {
                    name => name,
                },
            ));
        }
        _ => {}
    }
}

/// The C argument name(s) to use for a given wrapper parameter.
///
/// Bytes expand to two arguments: `.ptr` and `.len`.
/// String/Path/Vec/Map expand to the `_z` null-terminated copy.
/// Optional String/Path expand to a conditional unwrap of the optional slice
/// to its `.ptr`, substituting `null` when the wrapper arg was null — Zig
/// does not auto-coerce `?[:0]u8` into `?[*:0]const u8`.
/// Named structs expand to the `_handle` opaque pointer produced by the
/// JSON-to-handle helper in `emit_param_conversion`.
/// Everything else passes the parameter directly.
fn c_arg_names(p: &ParamDef, struct_names: &std::collections::HashSet<String>) -> Vec<String> {
    if is_struct_named(&p.ty, struct_names) {
        return vec![format!("{}_handle", p.name)];
    }
    let is_optional_string = p.optional
        || matches!(
            &p.ty,
            TypeRef::Optional(inner)
                if matches!(inner.as_ref(), TypeRef::String | TypeRef::Path)
        );
    if is_optional_string && matches!(unwrap_optional(&p.ty), TypeRef::String | TypeRef::Path) {
        return vec![format!("if ({0}_z) |z| z.ptr else null", p.name)];
    }
    match &p.ty {
        TypeRef::String | TypeRef::Path | TypeRef::Vec(_) | TypeRef::Map(_, _) => {
            vec![format!("{}_z", p.name)]
        }
        TypeRef::Bytes => {
            vec![format!("{}.ptr", p.name), format!("{}.len", p.name)]
        }
        _ => vec![p.name.clone()],
    }
}

/// Produce the Zig expression that converts a raw C return value (`raw`) to the
/// wrapper return type.
///
/// String/Path/Json/Vec/Map: copy the C string to an owned Zig slice, then free
/// the FFI allocation via `_free_string`.
/// Named struct (opaque handle): serialize to JSON via `<prefix>_<snake>_to_json`,
/// copy the JSON string to an owned Zig slice, then free both the JSON string and
/// the opaque handle.
/// Everything else: pass through unchanged.
fn unwrap_return_expr(
    raw: &str,
    ty: &TypeRef,
    prefix: &str,
    struct_names: &std::collections::HashSet<String>,
) -> String {
    match ty {
        TypeRef::String | TypeRef::Path | TypeRef::Json | TypeRef::Vec(_) | TypeRef::Map(_, _) => {
            // Copy the null-terminated C string to an owned Zig allocation, then free the C copy.
            let mut s = String::new();
            s.push_str("blk: {\n");
            s.push_str(&crate::template_env::render(
                "return_unwrap_slice.jinja",
                minijinja::context! {
                    raw => raw,
                },
            ));
            s.push_str("        const owned = try std.heap.c_allocator.dupe(u8, slice);\n");
            s.push_str(&crate::template_env::render(
                "return_unwrap_free.jinja",
                minijinja::context! {
                    raw => raw,
                },
            ));
            s.push_str("        break :blk owned;\n");
            s.push_str("    }");
            s
        }
        TypeRef::Named(name) if struct_names.contains(name) => {
            // The C function returned an opaque handle (*KREUZBERGFoo). Serialize
            // it to JSON via the FFI `<prefix>_<snake>_to_json` helper, copy the
            // JSON string into a Zig-owned buffer, then free both the JSON string
            // and the opaque handle. The wrapper returns `[]u8` (JSON).
            let snake = snake_case(name);
            let mut s = String::new();
            s.push_str("blk: {\n");
            s.push_str(&format!(
                "        const _json_ptr = c.{prefix}_{snake}_to_json({raw}.?);\n"
            ));
            s.push_str("        defer _free_string(_json_ptr);\n");
            s.push_str(&format!("        c.{prefix}_{snake}_free({raw}.?);\n"));
            s.push_str("        const slice = std.mem.sliceTo(_json_ptr, 0);\n");
            s.push_str("        const owned = try std.heap.c_allocator.dupe(u8, slice);\n");
            s.push_str("        break :blk owned;\n");
            s.push_str("    }");
            s
        }
        _ => raw.to_string(),
    }
}

/// Build the Zig return type for a function (not for struct fields).
///
/// Owned string/JSON/collection returns are `[]u8` (allocated slice).
/// Named struct returns (opaque C handles) are also serialized to `[]u8` (JSON).
/// Everything else matches the struct-field mapping.
pub(crate) fn zig_return_type(ty: &TypeRef, struct_names: &std::collections::HashSet<String>) -> String {
    match ty {
        TypeRef::String | TypeRef::Path | TypeRef::Json | TypeRef::Vec(_) | TypeRef::Map(_, _) => "[]u8".to_string(),
        TypeRef::Named(name) if struct_names.contains(name) => "[]u8".to_string(),
        other => zig_field_type(other, false),
    }
}