alef 0.30.16

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

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

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

    let lib = files.iter().find(|f| f.path.ends_with("lib.rs")).unwrap();
    assert!(lib.content.contains("extern \"C\""));
    assert!(lib.content.contains("my_lib_last_error_code"));
    assert!(lib.content.contains("my_lib_config_from_json"));
    assert!(lib.content.contains("my_lib_config_free"));
    assert!(lib.content.contains("my_lib_config_timeout"));
    assert!(lib.content.contains("my_lib_config_name"));
    assert!(lib.content.contains("my_lib_free_string"));
    assert!(lib.content.contains("my_lib_version"));
    assert!(lib.content.contains("my_lib_extract"));
    assert!(lib.content.contains("my_lib_output_format_from_i32"));
    assert!(lib.content.contains("my_lib_output_format_from_str"));
}

/// Build an `ApiSurface` whose only function returns the unit-variant enum
/// `Color` (`has_serde: true`) by pointer. Used to exercise emission of
/// `_to_string` accessors alongside `_free` / `_to_json`.
fn enum_return_api() -> ApiSurface {
    ApiSurface {
        crate_name: "my-lib".to_string(),
        version: "1.0.0".to_string(),
        types: vec![],
        functions: vec![FunctionDef {
            name: "current_color".to_string(),
            rust_path: "my_lib::current_color".to_string(),
            original_rust_path: String::new(),
            params: vec![],
            return_type: TypeRef::Named("Color".to_string()),
            is_async: false,
            error_type: None,
            doc: "Currently selected color.".to_string(),
            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(),
        }],
        enums: vec![EnumDef {
            name: "Color".to_string(),
            rust_path: "my_lib::Color".to_string(),
            original_rust_path: String::new(),
            variants: vec![
                EnumVariant {
                    name: "Red".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: "Green".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: "Colors.".to_string(),
            cfg: None,
            is_copy: false,
            has_serde: true,
            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_enum_to_string_for_pointer_return_enum() {
    let api = enum_return_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();

    // Sanity: pointer-return enum lifecycle helpers are emitted.
    assert!(
        lib.content.contains("my_lib_color_free"),
        "expected my_lib_color_free in emitted lib.rs"
    );
    assert!(
        lib.content.contains("my_lib_color_to_json"),
        "expected my_lib_color_to_json in emitted lib.rs"
    );

    // The new accessor: takes *const Color, returns *mut c_char.
    assert!(
        lib.content
            .contains("pub unsafe extern \"C\" fn my_lib_color_to_string("),
        "expected pub unsafe extern \"C\" fn my_lib_color_to_string in emitted lib.rs"
    );
    assert!(
        lib.content.contains("ptr: *const my_lib::Color)"),
        "to_string should accept *const Color"
    );
    assert!(
        lib.content.contains("-> *mut c_char"),
        "to_string should return *mut c_char"
    );
    // Body should extract the unit-variant name via serde, not via JSON-with-quotes.
    assert!(
        lib.content.contains("serde_json::to_value(val)"),
        "to_string should use serde_json::to_value"
    );
    assert!(
        lib.content.contains(".as_str()"),
        "to_string should call .as_str() to strip JSON quotes"
    );
}

#[test]
fn test_omits_enum_to_string_when_enum_not_returned() {
    // The default sample_api() uses `OutputFormat` only as a non-return enum
    // (no function returns it, no struct field has it), so neither _free nor
    // _to_string should be emitted.
    let api = sample_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("my_lib_output_format_to_string"),
        "expected NO my_lib_output_format_to_string when enum is not returned by pointer"
    );
    assert!(
        !lib.content.contains("my_lib_output_format_free"),
        "expected NO my_lib_output_format_free when enum is not returned by pointer"
    );
}

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

    let files = backend.generate_bindings(&api, &config).unwrap();
    let cbindgen = files.iter().find(|f| f.path.ends_with("cbindgen.toml")).unwrap();
    assert!(cbindgen.content.contains("MY_LIB_H"));
    assert!(cbindgen.content.contains("language = \"C\""));
    assert!(cbindgen.content.contains("style = \"both\""));
}

#[test]
fn test_cbindgen_toml_omits_excluded_forward_declarations() {
    let mut api = sample_api();

    let mut hidden_config = api.types[0].clone();
    hidden_config.name = "HiddenConfig".to_string();
    hidden_config.rust_path = "my_lib::HiddenConfig".to_string();
    hidden_config.doc = "Hidden config.".to_string();
    api.types.push(hidden_config);

    let mut binding_excluded_config = api.types[0].clone();
    binding_excluded_config.name = "BindingExcludedConfig".to_string();
    binding_excluded_config.rust_path = "my_lib::BindingExcludedConfig".to_string();
    binding_excluded_config.binding_excluded = true;
    binding_excluded_config.binding_exclusion_reason = Some("alef skip".to_string());
    api.types.push(binding_excluded_config);

    let mut hidden_enum = api.enums[0].clone();
    hidden_enum.name = "HiddenEnum".to_string();
    hidden_enum.rust_path = "my_lib::HiddenEnum".to_string();
    hidden_enum.doc = "Hidden enum.".to_string();
    api.enums.push(hidden_enum);

    let mut binding_excluded_enum = api.enums[0].clone();
    binding_excluded_enum.name = "BindingExcludedEnum".to_string();
    binding_excluded_enum.rust_path = "my_lib::BindingExcludedEnum".to_string();
    binding_excluded_enum.binding_excluded = true;
    binding_excluded_enum.binding_exclusion_reason = Some("alef skip".to_string());
    api.enums.push(binding_excluded_enum);

    let config = resolved_one(
        r#"
[workspace]
languages = ["ffi"]

[[crates]]
name = "my-lib"
sources = ["src/lib.rs"]

[crates.ffi]
exclude_types = ["HiddenConfig", "HiddenEnum"]
"#,
    );
    let backend = FfiBackend;

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

    assert!(cbindgen.content.contains("typedef struct MY_LIBConfig MY_LIBConfig;"));
    assert!(
        cbindgen
            .content
            .contains("typedef struct MY_LIBOutputFormat MY_LIBOutputFormat;")
    );
    assert!(!cbindgen.content.contains("MY_LIBHiddenConfig"));
    assert!(!cbindgen.content.contains("MY_LIBHiddenEnum"));
    assert!(!cbindgen.content.contains("MY_LIBBindingExcludedConfig"));
    assert!(!cbindgen.content.contains("MY_LIBBindingExcludedEnum"));
}

#[test]
fn test_cbindgen_toml_forward_declares_service_owner() {
    // A service owner (e.g. `App`) is emitted as the opaque `inner` pointer of its
    // `{PREFIX}{Service}Opaque` handle but lives in `api.services`, not `api.types`.
    // It must still be forward-declared or cbindgen reports "unknown type name".
    let mut api = sample_api();
    // Mirror reality: the owner is ALSO present in `types` as a `binding_excluded`
    // opaque, so it lands in the cbindgen exclude set. The forward declaration must
    // still be emitted (regression guard: the naive `!exclude_types.contains` filter
    // would wrongly drop it).
    let mut owner_type = api.types[0].clone();
    owner_type.name = "App".to_string();
    owner_type.rust_path = "my_lib::App".to_string();
    owner_type.binding_excluded = true;
    owner_type.is_opaque = true;
    owner_type.fields = vec![];
    api.types.push(owner_type);
    api.services.push(ServiceDef {
        name: "App".to_string(),
        rust_path: "my_lib::App".to_string(),
        constructor: MethodDef {
            name: "new".to_string(),
            ..Default::default()
        },
        configurators: vec![],
        registrations: vec![],
        entrypoints: vec![],
        doc: "Application builder.".to_string(),
        cfg: None,
    });

    let config = sample_config();
    let files = FfiBackend.generate_bindings(&api, &config).unwrap();
    let cbindgen = files.iter().find(|f| f.path.ends_with("cbindgen.toml")).unwrap();

    assert!(
        cbindgen.content.contains("typedef struct MY_LIBApp MY_LIBApp;"),
        "cbindgen.toml must forward-declare the service owner referenced as the opaque `inner` pointer, got:\n{}",
        cbindgen.content
    );
}

#[test]
fn test_cbindgen_toml_keeps_live_type_with_excluded_path_duplicate() {
    let mut api = sample_api();
    api.excluded_type_paths
        .insert("Config".to_string(), "my_lib::cfg_gated_stub::Config".to_string());

    let config = sample_config();
    let backend = FfiBackend;

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

    assert!(
        cbindgen.content.contains("typedef struct MY_LIBConfig MY_LIBConfig;"),
        "live binding DTO must still be forward-declared when a skipped cfg duplicate exists, got:\n{}",
        cbindgen.content
    );
    assert!(
        !cbindgen.content.contains(r#"exclude = ["Config"]"#),
        "live binding DTO must not be added to cbindgen export excludes, got:\n{}",
        cbindgen.content
    );
}

#[test]
fn test_cbindgen_toml_honors_ffi_exclude_types() {
    let mut api = sample_api();
    api.types.push(TypeDef {
        name: "HiddenOptions".to_string(),
        rust_path: "my_lib::internal::HiddenOptions".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: true,
        has_stripped_cfg_fields: false,
        is_return_type: false,
        serde_rename_all: None,
        has_serde: true,
        super_traits: vec![],
        doc: "Rust-only helper options.".to_string(),
        cfg: None,
        binding_excluded: false,
        binding_exclusion_reason: None,
        is_variant_wrapper: false,
        has_lifetime_params: false,
        has_private_fields: false,
        version: Default::default(),
    });
    api.enums.push(EnumDef {
        name: "HiddenStatus".to_string(),
        rust_path: "my_lib::internal::HiddenStatus".to_string(),
        original_rust_path: String::new(),
        variants: vec![],
        methods: vec![],
        doc: "Rust-only helper status.".to_string(),
        has_serde: true,
        cfg: None,
        is_copy: 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(),
    });
    let config = resolved_one(
        r#"
[workspace]
languages = ["ffi"]

[[crates]]
name = "my-lib"
sources = ["src/lib.rs"]

[crates.ffi]
prefix = "my_lib"
exclude_types = ["HiddenOptions", "my_lib::internal::HiddenStatus"]
"#,
    );
    let backend = FfiBackend;

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

    assert!(
        cbindgen
            .content
            .contains(r#"exclude = ["HiddenOptions", "HiddenStatus"]"#),
        "expected cbindgen export excludes for bare type names, got:\n{}",
        cbindgen.content
    );
    assert!(
        !cbindgen
            .content
            .contains("typedef struct MY_LIBHiddenOptions MY_LIBHiddenOptions;"),
        "excluded struct must not be forward-declared, got:\n{}",
        cbindgen.content
    );
    assert!(
        !cbindgen
            .content
            .contains("typedef struct MY_LIBHiddenStatus MY_LIBHiddenStatus;"),
        "excluded enum must not be forward-declared, got:\n{}",
        cbindgen.content
    );
}