alef 0.25.60

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
use super::super::FfiBackend;
use super::common::*;
use crate::core::backend::Backend;
use crate::core::ir::*;

// -----------------------------------------------------------------------
// Tests for opaque static constructor emission (Part B)
// -----------------------------------------------------------------------

/// Build an ApiSurface with an opaque type that has a static `new` constructor.
fn opaque_with_constructor_api() -> ApiSurface {
    ApiSurface {
        crate_name: "my-lib".to_string(),
        version: "1.0.0".to_string(),
        types: vec![
            // Enum used as parameter in the constructor
            TypeDef {
                name: "Method".to_string(),
                rust_path: "my_lib::Method".to_string(),
                original_rust_path: String::new(),
                fields: vec![],
                methods: vec![],
                is_opaque: false,
                is_clone: true,
                is_copy: false,
                is_trait: false,
                has_default: false,
                has_stripped_cfg_fields: false,
                is_return_type: false,
                serde_rename_all: None,
                has_serde: false,
                super_traits: vec![],
                doc: "HTTP method enum.".to_string(),
                cfg: None,
                binding_excluded: false,
                binding_exclusion_reason: None,
                is_variant_wrapper: false,
                has_lifetime_params: false,
                version: Default::default(),
            },
            // Opaque RouteBuilder with static new constructor
            TypeDef {
                name: "RouteBuilder".to_string(),
                rust_path: "my_lib::RouteBuilder".to_string(),
                original_rust_path: String::new(),
                fields: vec![],
                methods: vec![MethodDef {
                    name: "new".to_string(),
                    params: vec![
                        ParamDef {
                            name: "method".to_string(),
                            ty: TypeRef::Named("Method".to_string()),
                            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,
                        },
                        ParamDef {
                            name: "path".to_string(),
                            ty: TypeRef::String,
                            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::Named("RouteBuilder".to_string()),
                    is_async: false,
                    is_static: true,
                    error_type: None,
                    doc: "Create a new route builder.".to_string(),
                    receiver: 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(),
                }],
                is_opaque: true,
                is_clone: false,
                is_copy: false,
                is_trait: false,
                has_default: false,
                has_stripped_cfg_fields: false,
                is_return_type: false,
                serde_rename_all: None,
                has_serde: false,
                super_traits: vec![],
                doc: "Opaque route builder.".to_string(),
                cfg: None,
                binding_excluded: false,
                binding_exclusion_reason: None,
                is_variant_wrapper: false,
                has_lifetime_params: false,
                version: Default::default(),
            },
        ],
        functions: vec![],
        enums: vec![EnumDef {
            name: "Method".to_string(),
            rust_path: "my_lib::Method".to_string(),
            original_rust_path: String::new(),
            variants: vec![
                EnumVariant {
                    name: "Get".to_string(),
                    fields: vec![],
                    doc: String::new(),
                    is_default: false,
                    serde_rename: None,
                    binding_excluded: false,
                    binding_exclusion_reason: None,
                    is_tuple: false,
                    originally_had_data_fields: false,
                    cfg: None,
                    version: Default::default(),
                },
                EnumVariant {
                    name: "Post".to_string(),
                    fields: vec![],
                    doc: String::new(),
                    is_default: false,
                    serde_rename: None,
                    binding_excluded: false,
                    binding_exclusion_reason: None,
                    is_tuple: false,
                    originally_had_data_fields: false,
                    cfg: None,
                    version: Default::default(),
                },
            ],
            methods: vec![],
            doc: "HTTP method.".to_string(),
            cfg: None,
            is_copy: true,
            has_serde: false,
            has_default: false,
            serde_tag: None,
            serde_untagged: false,
            serde_rename_all: None,
            binding_excluded: false,
            binding_exclusion_reason: None,
            excluded_variants: vec![],
            version: Default::default(),
        }],
        errors: vec![],
        excluded_type_paths: ::std::collections::HashMap::new(),
        excluded_trait_names: ::std::collections::HashSet::new(),
        services: vec![],
        handler_contracts: vec![],
        unsupported_public_items: Vec::new(),
    }
}

#[test]
fn test_emits_opaque_static_constructor_as_c_symbol() {
    let api = opaque_with_constructor_api();
    let config = sample_config();
    let backend = FfiBackend;

    let files = backend.generate_bindings(&api, &config).unwrap();
    let lib = files.iter().find(|f| f.path.ends_with("lib.rs")).unwrap();

    // Check that the extern "C" fn symbol is emitted
    assert!(
        lib.content
            .contains("pub unsafe extern \"C\" fn my_lib_route_builder_new("),
        "expected opaque constructor symbol my_lib_route_builder_new, got:\n{}",
        lib.content
    );
}

#[test]
fn test_opaque_constructor_signature_has_enum_by_value_as_i32() {
    let api = opaque_with_constructor_api();
    let config = sample_config();
    let backend = FfiBackend;

    let files = backend.generate_bindings(&api, &config).unwrap();
    let lib = files.iter().find(|f| f.path.ends_with("lib.rs")).unwrap();

    // Check that enum parameter is passed as i32, not *const
    assert!(
        lib.content.contains("method: i32"),
        "expected enum parameter 'method: i32', got:\n{}",
        lib.content
    );
    // Verify it's NOT emitted as a pointer
    assert!(
        !lib.content.contains("method: *const my_lib::Method"),
        "enum parameter should not be passed as pointer"
    );
}

#[test]
fn test_opaque_constructor_marshals_enum_from_i32() {
    let api = opaque_with_constructor_api();
    let config = sample_config();
    let backend = FfiBackend;

    let files = backend.generate_bindings(&api, &config).unwrap();
    let lib = files.iter().find(|f| f.path.ends_with("lib.rs")).unwrap();

    // Check that the constructor body reconstructs the enum using from_i32
    assert!(
        lib.content.contains("method_from_i32"),
        "constructor should use method_from_i32 to reconstruct enum from discriminant"
    );
}

#[test]
fn test_opaque_constructor_returns_mut_opaque_pointer() {
    let api = opaque_with_constructor_api();
    let config = sample_config();
    let backend = FfiBackend;

    let files = backend.generate_bindings(&api, &config).unwrap();
    let lib = files.iter().find(|f| f.path.ends_with("lib.rs")).unwrap();

    // Constructor returns *mut to the inner type (matching the legacy `_free()`
    // signature) — no separate wrapper struct is emitted. The fixture's crate
    // name varies; just check for a `-> *mut <something>RouteBuilder {` body.
    let has_mut_return = lib
        .content
        .lines()
        .any(|line| line.contains("-> *mut") && line.contains("RouteBuilder") && !line.contains("RouteBuilderOpaque"));
    assert!(
        has_mut_return,
        "constructor should return *mut <core>::RouteBuilder (not a wrapper); got:\n{}",
        lib.content
    );
}

#[test]
fn test_opaque_constructor_only_for_opaque_types() {
    let api = opaque_with_constructor_api();
    let config = sample_config();
    let backend = FfiBackend;

    let files = backend.generate_bindings(&api, &config).unwrap();
    let lib = files.iter().find(|f| f.path.ends_with("lib.rs")).unwrap();

    // The Method type is NOT opaque, so its constructor should NOT be emitted
    // (if it had one). Only RouteBuilder's constructor should be in the output.
    // Should have RouteBuilder's _new, but not Method's
    assert!(
        lib.content.contains("my_lib_route_builder_new"),
        "RouteBuilder (opaque) should have _new constructor"
    );
}

// -----------------------------------------------------------------------
// Regression: named static Result<Self> constructors (not "new")
//
// Prior to the fix, `is_static_constructor` only matched methods named
// "new".  A method like `MetaSchema::compile` — static, returns Self,
// error_type set — was silently dropped from FFI output: `should_skip_
// method_wrapper` routed it away from the generic wrapper path, while
// `is_static_constructor` refused to emit it as a constructor.  Net
// result: no C export at all, causing Java <clinit> to crash with
// NoSuchElementException on the missing symbol.
// -----------------------------------------------------------------------

/// Build an ApiSurface with an opaque type whose sole constructor is named
/// `compile` (not `new`) and is fallible (`error_type` is set, representing
/// `Result<Self, E>`).  This mirrors `kreuzberg::MetaSchema::compile`.
fn opaque_with_named_constructor_api() -> ApiSurface {
    ApiSurface {
        crate_name: "my-lib".to_string(),
        version: "1.0.0".to_string(),
        types: vec![TypeDef {
            name: "Schema".to_string(),
            rust_path: "my_lib::Schema".to_string(),
            original_rust_path: String::new(),
            fields: vec![],
            methods: vec![MethodDef {
                name: "compile".to_string(),
                params: vec![ParamDef {
                    name: "json_text".to_string(),
                    ty: TypeRef::String,
                    optional: false,
                    default: None,
                    sanitized: false,
                    typed_default: None,
                    is_ref: true,
                    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::Named("Schema".to_string()),
                is_async: false,
                is_static: true,
                // error_type set → Result<Self, SchemaError>
                error_type: Some("SchemaError".to_string()),
                doc: "Compile the given JSON text as a schema.".to_string(),
                receiver: 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(),
            }],
            is_opaque: true,
            is_clone: false,
            is_copy: false,
            is_trait: false,
            has_default: false,
            has_stripped_cfg_fields: false,
            is_return_type: false,
            serde_rename_all: None,
            has_serde: false,
            super_traits: vec![],
            doc: "Opaque compiled schema.".to_string(),
            cfg: None,
            binding_excluded: false,
            binding_exclusion_reason: None,
            is_variant_wrapper: false,
            has_lifetime_params: false,
            version: Default::default(),
        }],
        functions: vec![],
        enums: vec![],
        errors: vec![],
        excluded_type_paths: ::std::collections::HashMap::new(),
        excluded_trait_names: ::std::collections::HashSet::new(),
        services: vec![],
        handler_contracts: vec![],
        unsupported_public_items: Vec::new(),
    }
}

/// A named static constructor (`compile`) on an opaque type must emit a C
/// export whose symbol is `{prefix}_{type_snake}_compile`, NOT `_new`.
#[test]
fn test_named_static_constructor_emits_compile_symbol() {
    let api = opaque_with_named_constructor_api();
    let config = sample_config();
    let backend = FfiBackend;

    let files = backend.generate_bindings(&api, &config).unwrap();
    let lib = files.iter().find(|f| f.path.ends_with("lib.rs")).unwrap();

    assert!(
        lib.content
            .contains("pub unsafe extern \"C\" fn my_lib_schema_compile("),
        "named static constructor must emit _compile symbol, got:\n{}",
        lib.content
    );
}

/// The compile symbol must NOT produce a `_new` alias — the C export name
/// must faithfully reflect the Rust method name.
#[test]
fn test_named_static_constructor_does_not_emit_new_symbol() {
    let api = opaque_with_named_constructor_api();
    let config = sample_config();
    let backend = FfiBackend;

    let files = backend.generate_bindings(&api, &config).unwrap();
    let lib = files.iter().find(|f| f.path.ends_with("lib.rs")).unwrap();

    assert!(
        !lib.content.contains("pub unsafe extern \"C\" fn my_lib_schema_new("),
        "named static constructor must NOT emit a _new symbol, got:\n{}",
        lib.content
    );
}

/// A fallible named constructor (`error_type` set) must clear the thread-local
/// error state at entry (`clear_last_error`) and propagate errors by calling
/// `set_last_error` + returning null rather than panicking.
#[test]
fn test_named_static_constructor_is_fallible() {
    let api = opaque_with_named_constructor_api();
    let config = sample_config();
    let backend = FfiBackend;

    let files = backend.generate_bindings(&api, &config).unwrap();
    let lib = files.iter().find(|f| f.path.ends_with("lib.rs")).unwrap();

    // Fallible path: clear_last_error at entry, set_last_error on Err branch
    assert!(
        lib.content.contains("clear_last_error"),
        "fallible constructor must call clear_last_error(); got:\n{}",
        lib.content
    );
    assert!(
        lib.content.contains("set_last_error"),
        "fallible constructor must call set_last_error() on error; got:\n{}",
        lib.content
    );
    // Returns null on failure
    assert!(
        lib.content.contains("std::ptr::null_mut()"),
        "fallible constructor must return null_mut() on error; got:\n{}",
        lib.content
    );
}