alef 0.32.5

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
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
use super::helpers::{capitalize, gen_param_conversion, rust_to_c_type};
use crate::core::ir::{MethodDef, TypeRef};
use heck::ToPascalCase;

/// Emit a deferred `recover()` guard at the top of an exported cgo callback.
///
/// A Go panic must not unwind across the cgo boundary into the Rust caller —
/// that aborts the whole process. The trampoline signatures use a named return
/// value (`ret`) so the deferred closure can substitute a result: fallible
/// slots surface the panic through `outError` (status 1), infallible slots log
/// to stderr and return the zero value.
fn gen_panic_recovery(out: &mut String, trait_pascal: &str, method_pascal: &str, fallible: bool) {
    out.push_str("\tdefer func() {\n");
    out.push_str("\t\tif r := recover(); r != nil {\n");
    if fallible {
        out.push_str(&format!(
            "\t\t\tfmt.Fprintln(os.Stderr, \"[{trait_pascal}Bridge] host '{method_pascal}' panicked:\", r)\n"
        ));
        out.push_str("\t\t\t*outError = C.CString(fmt.Sprint(r))\n");
        out.push_str("\t\t\tret = 1\n");
    } else {
        out.push_str(&format!(
            "\t\t\tfmt.Fprintln(os.Stderr, \"[{trait_pascal}Bridge] host '{method_pascal}' panicked; returning default:\", r)\n"
        ));
        out.push_str("\t\t\tret = 0\n");
    }
    out.push_str("\t\t}\n");
    out.push_str("\t}()\n");
    out.push('\n');
}

/// Generate one trampoline function (implementation without //export).
/// The //export declaration is in binding.go to avoid duplicate definitions.
pub(super) fn gen_trampoline(out: &mut String, trait_name: &str, trait_pascal: &str, method: &MethodDef) {
    let method_pascal = method.name.to_pascal_case();
    let export_name = format!("go{}{}", trait_pascal, method_pascal);

    let mut params = vec!["userData unsafe.Pointer".to_string()];
    for p in &method.params {
        let c_type = rust_to_c_type(&p.ty);
        params.push(format!("{} {}", p.name, c_type));
        // Bytes params carry a companion length so the trampoline can convert via
        // unsafe.Slice rather than C.GoString (which stops at NUL bytes).
        if matches!(p.ty, TypeRef::Bytes) {
            params.push(format!("{}Len C.size_t", p.name));
        }
    }

    // Determine the return type signature based on the method's return type.
    // Simple primitives (bool, i32, u32, usize, isize, etc.) return directly and do NOT use out-result parameter.
    // Complex types (String, Vec, struct, etc.) use out-result + out-error pattern.
    let is_simple_primitive = matches!(
        &method.return_type,
        TypeRef::Primitive(crate::core::ir::PrimitiveType::Bool)
            | TypeRef::Primitive(crate::core::ir::PrimitiveType::I32)
            | TypeRef::Primitive(crate::core::ir::PrimitiveType::U32)
            | TypeRef::Primitive(crate::core::ir::PrimitiveType::I64)
            | TypeRef::Primitive(crate::core::ir::PrimitiveType::U64)
            | TypeRef::Primitive(crate::core::ir::PrimitiveType::Usize)
            | TypeRef::Primitive(crate::core::ir::PrimitiveType::Isize)
    );

    if is_simple_primitive {
        // Simple primitive: return the value directly, only out_error for error context.
        // No out_result parameter needed.
        params.push("outError **C.char".to_string());
    } else if !matches!(method.return_type, TypeRef::Unit) {
        // Complex return type: use out_result for the value
        params.push("outResult **C.char".to_string());
        params.push("outError **C.char".to_string());
    } else {
        // Unit return: only out_error
        params.push("outError **C.char".to_string());
    }

    // Determine the Go C type for the return value
    let go_return_type = if is_simple_primitive {
        match &method.return_type {
            TypeRef::Primitive(crate::core::ir::PrimitiveType::Bool) => "int32_t",
            TypeRef::Primitive(crate::core::ir::PrimitiveType::I32) => "int32_t",
            TypeRef::Primitive(crate::core::ir::PrimitiveType::U32) => "uint32_t",
            TypeRef::Primitive(crate::core::ir::PrimitiveType::I64) => "int64_t",
            TypeRef::Primitive(crate::core::ir::PrimitiveType::U64) => "uint64_t",
            TypeRef::Primitive(crate::core::ir::PrimitiveType::Usize) => "uintptr_t",
            TypeRef::Primitive(crate::core::ir::PrimitiveType::Isize) => "intptr_t",
            _ => "int32_t",
        }
    } else {
        "int32_t"
    };

    out.push_str(&crate::backends::go::template_env::render(
        "trampoline_signature.jinja",
        minijinja::context! {
            name => export_name,
            params => params,
            return_type => go_return_type,
        },
    ));
    out.push('\n');

    let fallible = method.error_type.is_some();
    gen_panic_recovery(out, trait_pascal, &method_pascal, fallible);

    // Retrieve the Go object from the handle
    out.push_str("\thandle := cgo.Handle(uintptr(unsafe.Pointer(userData)))\n");
    out.push_str(&crate::backends::go::template_env::render(
        "handle_type_assertion.jinja",
        minijinja::context! {
            type_name => trait_name,
        },
    ));
    out.push('\n');
    out.push_str("\tif !ok {\n");
    if fallible {
        out.push_str(&format!(
            "\t\tfmt.Fprintln(os.Stderr, \"[{trait_pascal}Bridge] host '{method_pascal}' called with an invalid handle\")\n"
        ));
        out.push_str("\t\t*outError = C.CString(\"invalid handle\")\n");
        out.push_str("\t\treturn 1\n");
    } else {
        // For direct-value slots a nonzero status here would fabricate a real
        // return value; log and return the zero value instead.
        out.push_str(&format!(
            "\t\tfmt.Fprintln(os.Stderr, \"[{trait_pascal}Bridge] host '{method_pascal}' called with an invalid handle; returning default\")\n"
        ));
        out.push_str("\t\treturn 0\n");
    }
    out.push_str("\t}\n");
    out.push('\n');

    // Convert C parameters to Go
    for p in &method.params {
        gen_param_conversion(out, p);
    }

    // Call the method
    let mut call_args = Vec::new();
    for p in &method.params {
        call_args.push(format!("go{}", capitalize(&p.name)));
    }

    out.push_str("\t// Call the method\n");
    if method.error_type.is_some() {
        // Method returns (value?, error)
        match &method.return_type {
            TypeRef::Unit => {
                // Just returns error
                out.push_str(&crate::backends::go::template_env::render(
                    "impl_method_call_err.jinja",
                    minijinja::context! {
                        method => method.name.to_pascal_case(),
                        args => call_args.join(", "),
                    },
                ));
                out.push('\n');
            }
            _ => {
                // Returns (value, error)
                out.push_str(&crate::backends::go::template_env::render(
                    "impl_method_call_result_err.jinja",
                    minijinja::context! {
                        method => method.name.to_pascal_case(),
                        args => call_args.join(", "),
                    },
                ));
                out.push('\n');
            }
        }
        out.push_str("\tif err != nil {\n");
        out.push_str("\t\tcErr := C.CString(err.Error())\n");
        out.push_str("\t\t*outError = cErr\n");
        out.push_str("\t\treturn 1\n");
        out.push_str("\t}\n");

        // Encode result if not Unit
        if !matches!(&method.return_type, TypeRef::Unit) {
            gen_result_conversion(out, &method.return_type, is_simple_primitive);
        }
    } else {
        // Method returns only value (no error)
        out.push_str(&crate::backends::go::template_env::render(
            "impl_method_call_result.jinja",
            minijinja::context! {
                method => method.name.to_pascal_case(),
                args => call_args.join(", "),
            },
        ));
        out.push('\n');

        // Encode result if not Unit
        if !matches!(&method.return_type, TypeRef::Unit) {
            gen_result_conversion(out, &method.return_type, is_simple_primitive);
        }
    }

    // Simple-primitive conversions return the value directly (every path above
    // ends in an unconditional return), so only status-slot trampolines need
    // the trailing success return.
    if !is_simple_primitive {
        out.push_str("\treturn 0  // success\n");
    }
    out.push_str("}\n");
    out.push('\n');
}

/// Marshal a Go callback result into the C out-result slot, or return it directly.
///
/// For simple primitives (bool, i32, etc.), return the value directly as a C type.
/// For complex types (String, Path, Vec, struct, etc.), marshal into the out_result slot.
///
/// The Rust FFI side decodes String/Path/Char callback returns as raw UTF-8 C strings,
/// while Json/Named/Vec/Map returns are parsed as JSON payloads. Keep those contracts
/// separate so string-like returns are not accidentally JSON-quoted and raw JSON payloads
/// are not double-encoded.
fn gen_result_conversion(out: &mut String, return_type: &TypeRef, is_simple_primitive: bool) {
    if is_simple_primitive {
        // For simple primitives (bool, i32, u64, etc.), cast and return directly
        match return_type {
            TypeRef::Primitive(crate::core::ir::PrimitiveType::Bool) => {
                out.push_str("\tif callbackResult {\n");
                out.push_str("\t\treturn 1\n");
                out.push_str("\t}\n");
                out.push_str("\treturn 0\n");
            }
            TypeRef::Primitive(p) => {
                // Map primitive type to correct C casting
                use crate::core::ir::PrimitiveType::*;
                let c_type = match p {
                    Bool => "int32_t", // Handled above
                    U8 => "uint8_t",
                    U16 => "uint16_t",
                    U32 => "uint32_t",
                    U64 => "uint64_t",
                    I8 => "int8_t",
                    I16 => "int16_t",
                    I32 => "int32_t",
                    I64 => "int64_t",
                    F32 => "float",
                    F64 => "double",
                    Usize => "uintptr_t",
                    Isize => "intptr_t",
                };
                out.push_str(&format!("\treturn C.{}(callbackResult)\n", c_type));
            }
            _ => {
                // Should not happen if is_simple_primitive is correctly set
                out.push_str("\treturn 0  // error: unexpected type for simple primitive path\n");
            }
        }
    } else {
        // Complex type: marshal into out_result
        match return_type {
            TypeRef::String | TypeRef::Char | TypeRef::Path => {
                out.push_str("\tcResult := C.CString(callbackResult)\n");
                out.push_str("\t*outResult = cResult\n");
            }
            TypeRef::Json => {
                out.push_str("\tcResult := C.CString(string(callbackResult))\n");
                out.push_str("\t*outResult = cResult\n");
            }
            _ => {
                out.push_str("\tjsonBytes, _ := json.Marshal(callbackResult)\n");
                out.push_str("\tcResult := C.CString(string(jsonBytes))\n");
                out.push_str("\t*outResult = cResult\n");
            }
        }
    }
}

/// Generate trampolines for plugin methods: Name, Version, Initialize, Shutdown.
pub(super) fn gen_plugin_trampolines(out: &mut String, trait_name: &str, trait_pascal: &str) {
    // Name trampoline
    out.push_str(&crate::backends::go::template_env::render(
        "export_marker.jinja",
        minijinja::context! {
            name => format!("go{trait_pascal}Name"),
        },
    ));
    out.push_str(&crate::backends::go::template_env::render(
        "plugin_method_trampoline_header.jinja",
        minijinja::context! {
            pascal => &trait_pascal,
            method => "Name",
            params => "userData unsafe.Pointer, outResult **C.char, outError **C.char",
        },
    ));
    out.push('\n');
    gen_panic_recovery(out, trait_pascal, "Name", true);
    out.push_str("\thandle := cgo.Handle(uintptr(unsafe.Pointer(userData)))\n");
    out.push_str(&crate::backends::go::template_env::render(
        "handle_type_assertion.jinja",
        minijinja::context! {
            type_name => trait_name,
        },
    ));
    out.push('\n');
    out.push_str("\tif !ok {\n");
    out.push_str(&format!(
        "\t\tfmt.Fprintln(os.Stderr, \"[{trait_pascal}Bridge] host 'Name' called with an invalid handle\")\n"
    ));
    out.push_str("\t\t*outError = C.CString(\"invalid handle\")\n");
    out.push_str("\t\treturn 1\n");
    out.push_str("\t}\n");
    out.push_str("\tname := impl.Name()\n");
    out.push_str("\tcName := C.CString(name)\n");
    out.push_str("\t*outResult = cName\n");
    out.push_str("\treturn 0\n");
    out.push_str("}\n");
    out.push('\n');

    // Version trampoline
    out.push_str(&crate::backends::go::template_env::render(
        "export_marker.jinja",
        minijinja::context! {
            name => format!("go{trait_pascal}Version"),
        },
    ));
    out.push_str(&crate::backends::go::template_env::render(
        "plugin_method_trampoline_header.jinja",
        minijinja::context! {
            pascal => &trait_pascal,
            method => "Version",
            params => "userData unsafe.Pointer, outResult **C.char, outError **C.char",
        },
    ));
    out.push('\n');
    gen_panic_recovery(out, trait_pascal, "Version", true);
    out.push_str("\thandle := cgo.Handle(uintptr(unsafe.Pointer(userData)))\n");
    out.push_str(&crate::backends::go::template_env::render(
        "handle_type_assertion.jinja",
        minijinja::context! {
            type_name => trait_name,
        },
    ));
    out.push('\n');
    out.push_str("\tif !ok {\n");
    out.push_str(&format!(
        "\t\tfmt.Fprintln(os.Stderr, \"[{trait_pascal}Bridge] host 'Version' called with an invalid handle\")\n"
    ));
    out.push_str("\t\t*outError = C.CString(\"invalid handle\")\n");
    out.push_str("\t\treturn 1\n");
    out.push_str("\t}\n");
    out.push_str("\tversion := impl.Version()\n");
    out.push_str("\tcVersion := C.CString(version)\n");
    out.push_str("\t*outResult = cVersion\n");
    out.push_str("\treturn 0\n");
    out.push_str("}\n");
    out.push('\n');

    // Initialize trampoline
    out.push_str(&crate::backends::go::template_env::render(
        "export_marker.jinja",
        minijinja::context! {
            name => format!("go{trait_pascal}Initialize"),
        },
    ));
    out.push_str(&crate::backends::go::template_env::render(
        "plugin_method_trampoline_header.jinja",
        minijinja::context! {
            pascal => &trait_pascal,
            method => "Initialize",
            params => "userData unsafe.Pointer, outError **C.char",
        },
    ));
    out.push('\n');
    gen_panic_recovery(out, trait_pascal, "Initialize", true);
    out.push_str("\thandle := cgo.Handle(uintptr(unsafe.Pointer(userData)))\n");
    out.push_str(&crate::backends::go::template_env::render(
        "handle_type_assertion.jinja",
        minijinja::context! {
            type_name => trait_name,
        },
    ));
    out.push('\n');
    out.push_str("\tif !ok {\n");
    out.push_str(&format!(
        "\t\tfmt.Fprintln(os.Stderr, \"[{trait_pascal}Bridge] host 'Initialize' called with an invalid handle\")\n"
    ));
    out.push_str("\t\t*outError = C.CString(\"invalid handle\")\n");
    out.push_str("\t\treturn 1\n");
    out.push_str("\t}\n");
    out.push_str("\terr := impl.Initialize()\n");
    out.push_str("\tif err != nil {\n");
    out.push_str("\t\tcErr := C.CString(err.Error())\n");
    out.push_str("\t\t*outError = cErr\n");
    out.push_str("\t\treturn 1\n");
    out.push_str("\t}\n");
    out.push_str("\treturn 0\n");
    out.push_str("}\n");
    out.push('\n');

    // Shutdown trampoline
    out.push_str(&crate::backends::go::template_env::render(
        "export_marker.jinja",
        minijinja::context! {
            name => format!("go{trait_pascal}Shutdown"),
        },
    ));
    out.push_str(&crate::backends::go::template_env::render(
        "plugin_method_trampoline_header.jinja",
        minijinja::context! {
            pascal => &trait_pascal,
            method => "Shutdown",
            params => "userData unsafe.Pointer, outError **C.char",
        },
    ));
    out.push('\n');
    gen_panic_recovery(out, trait_pascal, "Shutdown", true);
    out.push_str("\thandle := cgo.Handle(uintptr(unsafe.Pointer(userData)))\n");
    out.push_str(&crate::backends::go::template_env::render(
        "handle_type_assertion.jinja",
        minijinja::context! {
            type_name => trait_name,
        },
    ));
    out.push('\n');
    out.push_str("\tif !ok {\n");
    out.push_str(&format!(
        "\t\tfmt.Fprintln(os.Stderr, \"[{trait_pascal}Bridge] host 'Shutdown' called with an invalid handle\")\n"
    ));
    out.push_str("\t\t*outError = C.CString(\"invalid handle\")\n");
    out.push_str("\t\treturn 1\n");
    out.push_str("\t}\n");
    out.push_str("\terr := impl.Shutdown()\n");
    out.push_str("\tif err != nil {\n");
    out.push_str("\t\tcErr := C.CString(err.Error())\n");
    out.push_str("\t\t*outError = cErr\n");
    out.push_str("\t\treturn 1\n");
    out.push_str("\t}\n");
    out.push_str("\treturn 0\n");
    out.push_str("}\n");
    out.push('\n');

    // FreeUserData trampoline — called by Rust Drop (Go 1.26+ cleanup-queue).
    // DO NOT call cgo.Handle.Delete() here: Go's cleanup-queue runs finalizers in a
    // context where they may panic if the handle is invalid or already deleted.
    // Instead, rely on explicit Unregister() calls for proper cleanup.
    out.push_str(&crate::backends::go::template_env::render(
        "export_marker.jinja",
        minijinja::context! {
            name => format!("go{trait_pascal}FreeUserData"),
        },
    ));
    out.push_str(&crate::backends::go::template_env::render(
        "plugin_free_user_data_func.jinja",
        minijinja::context! {
            pascal => &trait_pascal,
        },
    ));
    out.push('\n');
    out.push_str("\t// No-op to avoid cleanup-queue panics. Handles cleaned in Unregister().\n");
    out.push_str("}\n");
    out.push('\n');

    out.push_str(&crate::backends::go::template_env::render(
        "export_marker.jinja",
        minijinja::context! {
            name => format!("go{trait_pascal}FreeString"),
        },
    ));
    out.push_str(&crate::backends::go::template_env::render(
        "trait_free_string_func.jinja",
        minijinja::context! {
            trait_pascal => &trait_pascal,
        },
    ));
}