alef 0.107.2

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
use super::*;
use crate::core::ir::{ParamDef, PrimitiveType, TypeRef};

pub(super) fn make_param(name: &str, ty: TypeRef) -> ParamDef {
    ParamDef {
        name: name.to_string(),
        ty,
        optional: false,
        default: None,
        sanitized: false,
        typed_default: None,
        is_ref: false,
        is_mut: false,
        newtype_wrapper: None,
        original_type: None,
        map_is_ahash: false,
        map_key_is_cow: false,
        vec_inner_is_ref: false,
        map_is_btree: false,
        core_wrapper: crate::core::ir::CoreWrapper::None,
    }
}

#[test]
fn test_params_require_marshal_for_named_non_opaque() {
    let params = vec![make_param("options", TypeRef::Named("Config".to_string()))];
    let opaque: std::collections::HashSet<&str> = std::collections::HashSet::new();
    assert!(params_require_marshal(&params, &opaque));
}

#[test]
fn test_params_require_marshal_false_for_opaque() {
    let params = vec![make_param("client", TypeRef::Named("Client".to_string()))];
    let opaque: std::collections::HashSet<&str> = ["Client"].into();
    assert!(!params_require_marshal(&params, &opaque));
}

#[test]
fn test_is_bridge_param_matches_by_name() {
    let param = make_param("visitor", TypeRef::Named("VisitorHandle".to_string()));
    let bridge_names: HashSet<String> = ["visitor".to_string()].into();
    let aliases: HashSet<String> = HashSet::new();
    assert!(is_bridge_param(&param, &bridge_names, &aliases));
}

#[test]
fn test_params_require_marshal_for_vec() {
    let params = vec![make_param(
        "items",
        TypeRef::Vec(Box::new(TypeRef::Primitive(PrimitiveType::U32))),
    )];
    let opaque: std::collections::HashSet<&str> = std::collections::HashSet::new();
    assert!(params_require_marshal(&params, &opaque));
}

pub(super) fn make_bytes_result_func(name: &str, with_bytes_param: bool) -> FunctionDef {
    let params = if with_bytes_param {
        vec![ParamDef {
            name: "data".to_string(),
            ty: TypeRef::Bytes,
            optional: false,
            default: None,
            sanitized: false,
            typed_default: None,
            is_ref: false,
            is_mut: false,
            newtype_wrapper: None,
            original_type: None,
            map_is_ahash: false,
            map_key_is_cow: false,
            vec_inner_is_ref: false,
            map_is_btree: false,
            core_wrapper: crate::core::ir::CoreWrapper::None,
        }]
    } else {
        vec![]
    };
    FunctionDef {
        name: name.to_string(),
        rust_path: String::new(),
        original_rust_path: String::new(),
        params,
        return_type: TypeRef::Bytes,
        is_async: false,
        error_type: Some("SampleCrateError".to_string()),
        doc: String::new(),
        cfg: None,
        sanitized: false,
        return_sanitized: false,
        returns_ref: false,
        returns_cow: false,
        return_newtype_wrapper: None,
        binding_excluded: false,
        binding_exclusion_reason: None,
        version: Default::default(),
    }
}

pub(super) fn make_bytes_result_method(name: &str) -> MethodDef {
    MethodDef {
        name: name.to_string(),
        doc: String::new(),
        params: vec![ParamDef {
            name: "data".to_string(),
            ty: TypeRef::Bytes,
            optional: false,
            default: None,
            sanitized: false,
            typed_default: None,
            is_ref: false,
            is_mut: false,
            newtype_wrapper: None,
            original_type: None,
            map_is_ahash: false,
            map_key_is_cow: false,
            vec_inner_is_ref: false,
            map_is_btree: false,
            core_wrapper: crate::core::ir::CoreWrapper::None,
        }],
        return_type: TypeRef::Bytes,
        is_static: false,
        is_async: false,
        error_type: Some("SampleCrateError".to_string()),
        receiver: None,
        cfg: None,
        sanitized: false,
        trait_source: None,
        returns_ref: false,
        returns_cow: false,
        return_newtype_wrapper: None,
        has_default_impl: false,
        binding_excluded: false,
        binding_exclusion_reason: None,
        version: Default::default(),
    }
}

#[test]
fn test_is_bytes_result_func_detects_bytes_with_error() {
    let func = make_bytes_result_func("process_image", true);
    assert!(is_bytes_result_func(&func));
}

#[test]
fn test_is_bytes_result_func_detects_bytes_without_error() {
    let mut func = make_bytes_result_func("get_data", false);
    func.error_type = None;
    assert!(is_bytes_result_func(&func));
}

#[test]
fn test_gen_function_wrapper_named_handle_error_path_uses_zero_sentinel() {
    let mut func = make_bytes_result_func("load_config", true);
    func.return_type = TypeRef::Named("Config".to_string());
    let empty_refs = HashSet::new();
    let empty_strings = HashSet::new();
    let out = gen_function_wrapper(
        &func,
        "sample",
        &empty_refs,
        &empty_strings,
        &empty_strings,
        &empty_strings,
        &empty_strings,
        &empty_strings,
        &empty_strings,
    );

    assert!(out.contains("if ptr != 0"));
    assert!(!out.contains("if ptr != nil"));
}

#[test]
fn test_is_bytes_result_func_false_for_string_with_error() {
    let func = FunctionDef {
        name: "get_text".to_string(),
        rust_path: String::new(),
        original_rust_path: String::new(),
        params: vec![],
        return_type: TypeRef::String,
        is_async: false,
        error_type: Some("SampleCrateError".to_string()),
        doc: String::new(),
        cfg: None,
        sanitized: false,
        return_sanitized: false,
        returns_ref: false,
        returns_cow: false,
        return_newtype_wrapper: None,
        binding_excluded: false,
        binding_exclusion_reason: None,
        version: Default::default(),
    };
    assert!(!is_bytes_result_func(&func));
}

#[test]
fn test_is_bytes_result_method_detects_correctly() {
    let method = make_bytes_result_method("render_page");
    assert!(is_bytes_result_method(&method));
}

#[test]
fn test_gen_function_wrapper_bytes_result_emits_out_params() {
    let func = make_bytes_result_func("process_image", true);
    let opaque: std::collections::HashSet<&str> = std::collections::HashSet::new();
    let bridge_names: HashSet<String> = HashSet::new();
    let bridge_aliases: HashSet<String> = HashSet::new();
    let value_only_types: HashSet<String> = HashSet::new();
    let enum_names: HashSet<String> = HashSet::new();
    let ffi_param_enum_names: HashSet<String> = HashSet::new();
    let reserved_type_names: HashSet<String> = HashSet::new();
    let out = gen_function_wrapper(
        &func,
        "krz",
        &opaque,
        &bridge_names,
        &bridge_aliases,
        &value_only_types,
        &enum_names,
        &ffi_param_enum_names,
        &reserved_type_names,
    );
    assert!(out.contains("([]byte, error)"), "missing bytes return type in:\n{out}");
    assert!(out.contains("var outPtr"), "missing outPtr in:\n{out}");
    assert!(out.contains("outLen"), "missing outLen in:\n{out}");
    assert!(out.contains("outCap"), "missing outCap in:\n{out}");
    assert!(out.contains("&outPtr"), "missing &outPtr in:\n{out}");
    assert!(out.contains("&outLen"), "missing &outLen in:\n{out}");
    assert!(out.contains("&outCap"), "missing &outCap in:\n{out}");
    assert!(out.contains("C.GoBytes"), "missing C.GoBytes in:\n{out}");
    assert!(out.contains("krz_free_bytes"), "missing krz_free_bytes in:\n{out}");
}

/// Regression: `bytes_result_call.jinja` used to free the native buffer inline, after
/// `C.GoBytes`, with no `defer` at all — a panic during `C.GoBytes` (e.g. an allocation
/// failure) skipped the free and leaked the buffer. The free must now be `defer`-registered
/// before the fallible conversion runs, matching every other free in this backend's templates
/// (`free_string.jinja`, `free_type.jinja`, `c_result_defer_free.jinja`). ~keep
#[test]
fn test_gen_function_wrapper_bytes_result_defers_free_before_conversion() {
    let func = make_bytes_result_func("process_image", true);
    let opaque: std::collections::HashSet<&str> = std::collections::HashSet::new();
    let bridge_names: HashSet<String> = HashSet::new();
    let bridge_aliases: HashSet<String> = HashSet::new();
    let value_only_types: HashSet<String> = HashSet::new();
    let enum_names: HashSet<String> = HashSet::new();
    let ffi_param_enum_names: HashSet<String> = HashSet::new();
    let reserved_type_names: HashSet<String> = HashSet::new();
    let out = gen_function_wrapper(
        &func,
        "krz",
        &opaque,
        &bridge_names,
        &bridge_aliases,
        &value_only_types,
        &enum_names,
        &ffi_param_enum_names,
        &reserved_type_names,
    );

    let defer_pos = match out.find("defer C.krz_free_bytes") {
        Some(pos) => pos,
        None => panic!("free must be `defer`-registered, not called inline, in:\n{out}"),
    };
    let gobytes_pos = out.find("C.GoBytes").expect("missing C.GoBytes");
    assert!(
        defer_pos < gobytes_pos,
        "the buffer free must be deferred before the fallible C.GoBytes conversion runs, so a \
         panic during conversion still frees the native buffer, got:\n{out}"
    );
}

#[test]
fn test_gen_function_wrapper_infallible_bytes_uses_owned_buffer_abi() {
    let mut func = make_bytes_result_func("read_file", false);
    func.error_type = None;
    let empty_refs = HashSet::new();
    let empty_strings = HashSet::new();
    let out = gen_function_wrapper(
        &func,
        "sample",
        &empty_refs,
        &empty_strings,
        &empty_strings,
        &empty_strings,
        &empty_strings,
        &empty_strings,
        &empty_strings,
    );

    assert!(out.contains("&outPtr, &outLen, &outCap"));
    assert!(out.contains("C.GoBytes"));
    assert!(!out.contains("unmarshalBytes"));
}

pub(super) fn make_capsule_func(name: &str, fallible: bool) -> FunctionDef {
    FunctionDef {
        name: name.to_string(),
        rust_path: String::new(),
        original_rust_path: String::new(),
        params: vec![make_param("name", TypeRef::String)],
        return_type: TypeRef::Named("Language".to_string()),
        is_async: false,
        error_type: if fallible {
            Some("SampleCrateError".to_string())
        } else {
            None
        },
        doc: String::new(),
        cfg: None,
        sanitized: false,
        return_sanitized: false,
        returns_ref: false,
        returns_cow: false,
        return_newtype_wrapper: None,
        binding_excluded: false,
        binding_exclusion_reason: None,
        version: Default::default(),
    }
}

pub(super) fn capsule_cfg() -> crate::core::config::HostCapsuleTypeConfig {
    crate::core::config::HostCapsuleTypeConfig {
        host_type: "*my_pkg.Language".to_string(),
        package: "github.com/example/go-my-lib".to_string(),
        package_version: "v1.0.0".to_string(),
        construct_expr: "my_pkg.NewLanguage(unsafe.Pointer({ptr}))".to_string(),
        ..Default::default()
    }
}

#[test]
fn test_capsule_fallible_returns_error_tuple_and_checks_last_error() {
    let func = make_capsule_func("get_language", true);
    let empty: std::collections::HashSet<&str> = std::collections::HashSet::new();
    let empty_s: std::collections::HashSet<String> = std::collections::HashSet::new();
    let out = gen_capsule_function_wrapper(&func, "krz", &empty, &empty_s, &capsule_cfg(), &empty_s);
    assert!(
        out.contains("(*my_pkg.Language, error)"),
        "fallible capsule must return (host, error):\n{out}"
    );
    assert!(
        out.contains("lastError()"),
        "fallible capsule must check lastError():\n{out}"
    );
    assert!(
        out.contains("return nil, err"),
        "fallible capsule must propagate the error:\n{out}"
    );
}

#[test]
fn test_capsule_infallible_returns_bare_host_type() {
    let func = make_capsule_func("builtin_language", false);
    let empty: std::collections::HashSet<&str> = std::collections::HashSet::new();
    let empty_s: std::collections::HashSet<String> = std::collections::HashSet::new();
    let out = gen_capsule_function_wrapper(&func, "krz", &empty, &empty_s, &capsule_cfg(), &empty_s);
    assert!(
        !out.contains(", error)"),
        "infallible capsule must not return an error:\n{out}"
    );
    assert!(
        !out.contains("lastError()"),
        "infallible capsule must not check lastError():\n{out}"
    );
}

#[test]
fn test_capsule_errors_when_construct_expr_empty() {
    let func = make_capsule_func("get_language", false);
    let empty: std::collections::HashSet<&str> = std::collections::HashSet::new();
    let empty_s: std::collections::HashSet<String> = std::collections::HashSet::new();
    let cfg = crate::core::config::HostCapsuleTypeConfig {
        host_type: "*my_pkg.Language".to_string(),
        package: String::new(),
        package_version: String::new(),
        construct_expr: String::new(),
        ..Default::default()
    };
    let out = gen_capsule_function_wrapper(&func, "krz", &empty, &empty_s, &cfg, &empty_s);
    assert!(
        out.contains("ALEF ERROR"),
        "empty construct_expr must produce an ALEF ERROR comment. Got:\n{out}"
    );
    assert!(
        out.contains("construct_expr"),
        "error must mention the missing field. Got:\n{out}"
    );
}

#[test]
fn test_capsule_errors_when_host_type_empty() {
    let func = make_capsule_func("get_language", false);
    let empty: std::collections::HashSet<&str> = std::collections::HashSet::new();
    let empty_s: std::collections::HashSet<String> = std::collections::HashSet::new();
    let cfg = crate::core::config::HostCapsuleTypeConfig {
        host_type: String::new(),
        package: String::new(),
        package_version: String::new(),
        construct_expr: "my_pkg.NewLanguage(unsafe.Pointer({ptr}))".to_string(),
        ..Default::default()
    };
    let out = gen_capsule_function_wrapper(&func, "krz", &empty, &empty_s, &cfg, &empty_s);
    assert!(
        out.contains("ALEF ERROR"),
        "empty host_type must produce an ALEF ERROR comment. Got:\n{out}"
    );
    assert!(
        out.contains("host_type"),
        "error must mention the missing field. Got:\n{out}"
    );
}