alef 0.25.37

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
use crate::backends::go::type_map::go_type;
use crate::core::ir::{MethodDef, TypeRef};
use std::collections::HashSet;

/// Recursively substitute `TypeRef::Named(n)` references where `n` is explicitly excluded
/// from the binding's public surface (collected from `ApiSurface::excluded_type_paths` and
/// any `binding_excluded` types) with `TypeRef::Json`. This lets trait-bridge interface
/// signatures and trampolines fall back to `json.RawMessage`, since the named Go type was
/// never emitted into `binding.go` and would otherwise produce `undefined: <Name>` build
/// errors.
pub(super) fn substitute_excluded_types(ty: &TypeRef, excluded: &HashSet<&str>) -> TypeRef {
    match ty {
        TypeRef::Named(name) if excluded.contains(name.as_str()) => TypeRef::Json,
        TypeRef::Optional(inner) => TypeRef::Optional(Box::new(substitute_excluded_types(inner, excluded))),
        TypeRef::Vec(inner) => TypeRef::Vec(Box::new(substitute_excluded_types(inner, excluded))),
        TypeRef::Map(k, v) => TypeRef::Map(
            Box::new(substitute_excluded_types(k, excluded)),
            Box::new(substitute_excluded_types(v, excluded)),
        ),
        other => other.clone(),
    }
}

/// Clone a `MethodDef`, substituting any excluded named-type references in its
/// parameters and return type with `TypeRef::Json`. See [`substitute_excluded_types`].
pub(super) fn method_with_excluded_substituted(method: &MethodDef, excluded: &HashSet<&str>) -> MethodDef {
    let mut m = method.clone();
    for p in &mut m.params {
        p.ty = substitute_excluded_types(&p.ty, excluded);
    }
    m.return_type = substitute_excluded_types(&m.return_type, excluded);
    m
}
/// Build the C trampoline function signature for extern declaration in the CGo preamble.
/// Uses actual C types (not Go CGo types like `C.int32_t`).
///
/// For simple primitives (bool, i32, etc.), the function returns the value directly
/// and does not use an out_result parameter. For complex types, uses the out_result + out_error pattern.
#[allow(dead_code)]
pub(super) fn c_trampoline_signature(_export_name: &str, method: &MethodDef) -> String {
    let mut params = vec!["void* user_data".to_string()];
    for p in &method.params {
        let cty = rust_to_plain_c_type(&p.ty);
        params.push(format!("{} {}", cty, p.name));
        // Bytes params carry a companion length so the trampoline can read the full
        // buffer without NUL-truncation (mirrors vtable.rs / call_body.rs pattern).
        if matches!(p.ty, TypeRef::Bytes) {
            params.push(format!("size_t {}_len", p.name));
        }
    }

    // Determine if this is a simple primitive return
    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: only out_error parameter, return the value directly
        params.push("char** out_error".to_string());
    } else if !matches!(method.return_type, TypeRef::Unit) {
        // Complex return type: use out_result + out_error
        params.push("char** out_result".to_string());
        params.push("char** out_error".to_string());
    } else {
        // Unit return: only out_error
        params.push("char** out_error".to_string());
    }

    params.join(", ")
}

/// Determine the C return type for a callback function.
/// Simple primitives return their value directly. Complex types return int32_t (status code).
#[allow(dead_code)]
pub(super) fn c_callback_return_type(method: &MethodDef) -> String {
    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 {
        // Return the actual primitive type
        match &method.return_type {
            TypeRef::Primitive(crate::core::ir::PrimitiveType::Bool) => "int32_t".to_string(),
            TypeRef::Primitive(crate::core::ir::PrimitiveType::I32) => "int32_t".to_string(),
            TypeRef::Primitive(crate::core::ir::PrimitiveType::U32) => "uint32_t".to_string(),
            TypeRef::Primitive(crate::core::ir::PrimitiveType::I64) => "int64_t".to_string(),
            TypeRef::Primitive(crate::core::ir::PrimitiveType::U64) => "uint64_t".to_string(),
            TypeRef::Primitive(crate::core::ir::PrimitiveType::Usize) => "size_t".to_string(),
            TypeRef::Primitive(crate::core::ir::PrimitiveType::Isize) => "intptr_t".to_string(),
            _ => "int32_t".to_string(),
        }
    } else {
        // All other types return int32_t status code (0 success, 1 error)
        "int32_t".to_string()
    }
}

/// Convert a Rust TypeRef to a plain C type string (for CGo preamble extern declarations).
#[allow(dead_code)]
fn rust_to_plain_c_type(ty: &TypeRef) -> String {
    match ty {
        TypeRef::Primitive(p) => {
            use crate::core::ir::PrimitiveType::*;
            match p {
                Bool => "int32_t",
                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 => "size_t",
                Isize => "intptr_t",
            }
            .to_string()
        }
        TypeRef::String | TypeRef::Char | TypeRef::Path => "char*".to_string(),
        TypeRef::Bytes => "uint8_t*".to_string(),
        TypeRef::Optional(_) | TypeRef::Vec(_) | TypeRef::Map(_, _) | TypeRef::Named(_) => "char*".to_string(),
        TypeRef::Unit => "void".to_string(),
        TypeRef::Duration => "uint64_t".to_string(),
        _ => "char*".to_string(),
    }
}

/// Convert a Rust TypeRef to a Go type string.
/// Uses the type_map module for consistent type resolution, which handles Named types correctly.
pub(super) fn rust_to_go_type(ty: &TypeRef) -> String {
    go_type(ty).into_owned()
}

/// Convert a Rust TypeRef to a C type string.
pub(super) fn rust_to_c_type(ty: &TypeRef) -> String {
    match ty {
        TypeRef::Primitive(p) => {
            use crate::core::ir::PrimitiveType::*;
            match p {
                Bool => "C.int32_t",
                U8 => "C.uint8_t",
                U16 => "C.uint16_t",
                U32 => "C.uint32_t",
                U64 => "C.uint64_t",
                I8 => "C.int8_t",
                I16 => "C.int16_t",
                I32 => "C.int32_t",
                I64 => "C.int64_t",
                F32 => "C.float",
                F64 => "C.double",
                Usize => "C.size_t",
                Isize => "C.intptr_t",
            }
            .to_string()
        }
        TypeRef::String | TypeRef::Char | TypeRef::Path => "*C.char".to_string(),
        TypeRef::Bytes => "*C.uint8_t".to_string(),
        TypeRef::Optional(_) => "*C.char".to_string(), // JSON-encoded
        TypeRef::Vec(_) => "*C.char".to_string(),      // JSON-encoded
        TypeRef::Map(_, _) => "*C.char".to_string(),   // JSON-encoded
        TypeRef::Unit => "C.void".to_string(),
        TypeRef::Duration => "C.uint64_t".to_string(),
        TypeRef::Named(_) => "*C.char".to_string(), // JSON-encoded
        _ => "*C.char".to_string(),
    }
}

/// Generate parameter conversion code (C to Go).
pub(super) fn gen_param_conversion(out: &mut String, param: &crate::core::ir::ParamDef) {
    let var_name = format!("go{}", capitalize(&param.name));
    match &param.ty {
        TypeRef::String | TypeRef::Char | TypeRef::Path => {
            out.push_str(&crate::backends::go::template_env::render(
                "go_string_cast.jinja",
                minijinja::context! {
                    name => capitalize(&param.name),
                    param => param.name.as_str(),
                },
            ));
            out.push('\n');
        }
        TypeRef::Bytes => {
            // Use unsafe.Slice(ptr, len) so the full byte slice is available even
            // when the data contains embedded NUL bytes (fixes issue #114).
            // The companion {name}Len parameter is emitted alongside the pointer.
            let name = &param.name;
            let len_name = format!("{name}Len");
            out.push_str(&crate::backends::go::template_env::render(
                "trampoline_bytes_param_decode.jinja",
                minijinja::context! {
                    var_name => &var_name,
                    name => name,
                    len_name => &len_name,
                },
            ));
        }
        TypeRef::Vec(_) => {
            // Vec types unmarshal directly from JSON array
            let go_type = rust_to_go_type(&param.ty);
            out.push_str(&crate::backends::go::template_env::render(
                "var_type_decl.jinja",
                minijinja::context! {
                    var_name => &var_name,
                    type_name => &go_type,
                },
            ));
            out.push_str(&crate::backends::go::template_env::render(
                "if_nil_check.jinja",
                minijinja::context! {
                    param => param.name.as_str(),
                },
            ));
            out.push_str(&crate::backends::go::template_env::render(
                "json_unmarshal_simple.jinja",
                minijinja::context! {
                    param => param.name.as_str(),
                    var_name => &var_name,
                },
            ));
            out.push('\n');
            out.push_str("\t}\n");
            out.push('\n');
        }
        TypeRef::Named(_) => {
            // Named types (structs/config types) unmarshal directly into concrete type
            let go_type = rust_to_go_type(&param.ty);
            out.push_str(&crate::backends::go::template_env::render(
                "var_type_decl.jinja",
                minijinja::context! {
                    var_name => &var_name,
                    type_name => &go_type,
                },
            ));
            out.push_str(&crate::backends::go::template_env::render(
                "if_nil_check.jinja",
                minijinja::context! {
                    param => param.name.as_str(),
                },
            ));
            // Unmarshal directly into the concrete Go type
            out.push_str(&crate::backends::go::template_env::render(
                "json_unmarshal_simple.jinja",
                minijinja::context! {
                    param => param.name.as_str(),
                    var_name => &var_name,
                },
            ));
            out.push('\n');
            out.push_str("\t}\n");
            out.push('\n');
        }
        TypeRef::Map(_, _) => {
            // Map types unmarshal as map[string]interface{}
            let go_type = rust_to_go_type(&param.ty);
            out.push_str(&crate::backends::go::template_env::render(
                "var_type_decl.jinja",
                minijinja::context! {
                    var_name => &var_name,
                    type_name => &go_type,
                },
            ));
            out.push_str(&crate::backends::go::template_env::render(
                "if_nil_check.jinja",
                minijinja::context! {
                    param => param.name.as_str(),
                },
            ));
            out.push_str("\t\tvar rawData interface{}\n");
            out.push_str(&crate::backends::go::template_env::render(
                "json_unmarshal_rawdata.jinja",
                minijinja::context! {
                    param => param.name.as_str(),
                },
            ));
            out.push('\n');
            out.push_str("\t\tif m, ok := rawData.(map[string]interface{}); ok {\n");
            out.push_str(&crate::backends::go::template_env::render(
                "var_assign_m.jinja",
                minijinja::context! {
                    var => &var_name,
                },
            ));
            out.push('\n');
            out.push_str("\t\t}\n");
            out.push_str("\t}\n");
            out.push('\n');
        }
        TypeRef::Optional(_) => {
            // Optional types
            let go_type = rust_to_go_type(&param.ty);
            out.push_str(&crate::backends::go::template_env::render(
                "var_type_decl.jinja",
                minijinja::context! {
                    var_name => &var_name,
                    type_name => &go_type,
                },
            ));
            out.push_str(&crate::backends::go::template_env::render(
                "if_nil_check.jinja",
                minijinja::context! {
                    param => param.name.as_str(),
                },
            ));
            out.push_str("\t\tvar rawData interface{}\n");
            out.push_str(&crate::backends::go::template_env::render(
                "json_unmarshal_rawdata.jinja",
                minijinja::context! {
                    param => param.name.as_str(),
                },
            ));
            out.push('\n');
            out.push_str("\t\tif m, ok := rawData.(map[string]interface{}); ok {\n");
            out.push_str(&crate::backends::go::template_env::render(
                "var_assign_m.jinja",
                minijinja::context! {
                    var => &var_name,
                },
            ));
            out.push('\n');
            out.push_str("\t\t}\n");
            out.push_str("\t}\n");
            out.push('\n');
        }
        TypeRef::Json => {
            // Trait-bridge fallback for binding-excluded named types. The Go-side type is
            // `json.RawMessage`; the C-side carries the JSON payload as a NUL-terminated
            // string. Copy the bytes through so the user gets the raw JSON document
            // without forcing them to unmarshal into a Go type that was never emitted.
            out.push_str(&crate::backends::go::template_env::render(
                "trampoline_raw_message_decode.jinja",
                minijinja::context! {
                    var_name => &var_name,
                    param => param.name.as_str(),
                },
            ));
        }
        TypeRef::Primitive(p) => {
            use crate::core::ir::PrimitiveType::*;
            let cast = match p {
                Bool => format!("{} != 0", param.name),
                _ => {
                    // Get the Go type for this primitive
                    let go_type = match p {
                        U8 => "uint8",
                        U16 => "uint16",
                        U32 => "uint32",
                        U64 => "uint64",
                        I8 => "int8",
                        I16 => "int16",
                        I32 => "int32",
                        I64 => "int64",
                        F32 => "float32",
                        F64 => "float64",
                        Usize => "uint",
                        Isize => "int",
                        _ => "",
                    };
                    format!("{}({})", go_type, param.name)
                }
            };
            out.push_str(&crate::backends::go::template_env::render(
                "var_assign_cast.jinja",
                minijinja::context! {
                    var_name => &var_name,
                    cast => &cast,
                },
            ));
            out.push('\n');
            out.push('\n');
        }
        _ => {
            out.push_str(&crate::backends::go::template_env::render(
                "var_assign_cast.jinja",
                minijinja::context! {
                    var_name => &var_name,
                    cast => param.name.as_str(),
                },
            ));
            out.push('\n');
            out.push('\n');
        }
    }
}

/// Capitalize the first character of a string.
pub(super) fn capitalize(s: &str) -> String {
    let mut chars = s.chars();
    match chars.next() {
        None => String::new(),
        Some(c) => c.to_uppercase().collect::<String>() + chars.as_str(),
    }
}