alef 0.103.6

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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
use super::Pyo3Backend;
use super::config::cfg_present_for_pyo3;
use super::mutex::{rewrite_to_tokio_mutex_impl, rewrite_to_tokio_mutex_struct};
use crate::backends::pyo3::type_map::Pyo3Mapper;
use crate::codegen::generators::gen_pyo3_data_enum_with_mapper;
use crate::core::backend::Backend;
use crate::core::config::Language;
use crate::core::ir::{EnumDef, EnumVariant, FieldDef, PrimitiveType, TypeRef};

#[test]
fn unit_enum_supports_map_keys_and_required_record_has_no_invented_default() {
    let cfg = super::config::binding_config("core", true);
    let role = EnumDef {
        name: "Role".into(),
        variants: vec![EnumVariant {
            name: "Source".into(),
            ..Default::default()
        }],
        ..Default::default()
    };
    let generated = crate::codegen::generators::gen_enum(&role, &cfg, None);
    // PyO3's `eq_int` support needs PartialEq, while the Python-facing hash is
    // supplied by the generated __hash__ method below; Rust Eq/Hash derives are
    // neither required nor emitted for this wrapper.
    assert!(generated.contains("PartialEq"), "{generated}");
    assert!(generated.contains("fn __hash__(&self) -> isize"), "{generated}");
    assert!(generated.contains("self.clone() as isize"), "{generated}");
    let request = crate::core::ir::TypeDef {
        name: "Request".into(),
        fields: vec![FieldDef {
            name: "policy".into(),
            ty: TypeRef::Named("RequiredPolicy".into()),
            ..Default::default()
        }],
        has_default: false,
        ..Default::default()
    };
    let generated = crate::codegen::generators::gen_struct(&request, &Pyo3Mapper::new(), &cfg);
    assert!(!generated.contains("Default"), "{generated}");
}

#[test]
fn tuple_variant_factory_accepts_typed_payload_without_shadowing_getter() {
    let def = EnumDef {
        name: "Policy".into(),
        rust_path: "core::Policy".into(),
        serde_tag: Some("operation".into()),
        serde_content: Some("policy".into()),
        variants: vec![EnumVariant {
            name: "Analyze".into(),
            is_tuple: true,
            fields: vec![FieldDef {
                name: "_0".into(),
                ty: TypeRef::Named("AnalyzePolicy".into()),
                ..Default::default()
            }],
            ..Default::default()
        }],
        ..Default::default()
    };
    let generated = gen_pyo3_data_enum_with_mapper(&def, "core", Some(&Pyo3Mapper::new()));
    assert!(
        generated.contains("_factory_from_analyze(value: AnalyzePolicy)"),
        "{generated}"
    );
    assert!(generated.contains("Policy::Analyze(value.into())"), "{generated}");
    assert!(generated.contains("fn analyze(&self)"), "{generated}");
    syn::parse_file(&generated).expect("factory and accessor must form valid Rust");
}

/// The production pyo3 data-enum path emits one `#[staticmethod]` constructor per data-carrying
/// struct variant, mapped through the real `Pyo3Mapper`. Proves the wiring at `gen_bindings/mod.rs`,
/// not just the generator helper.
#[test]
fn data_enum_emits_variant_constructors_through_pyo3_mapper() {
    let str_field = |name: &str| FieldDef {
        name: name.to_string(),
        ty: TypeRef::String,
        ..Default::default()
    };
    let def = EnumDef {
        name: "EmbeddingModelType".to_string(),
        rust_path: "crate::EmbeddingModelType".to_string(),
        serde_content: None,
        serde_tag: Some("type".to_string()),
        has_serde: true,
        variants: vec![
            EnumVariant {
                name: "Preset".to_string(),
                fields: vec![str_field("name")],
                ..Default::default()
            },
            EnumVariant {
                name: "Custom".to_string(),
                fields: vec![
                    str_field("model_id"),
                    FieldDef {
                        name: "dimensions".to_string(),
                        ty: TypeRef::Primitive(PrimitiveType::U32),
                        ..Default::default()
                    },
                ],
                ..Default::default()
            },
        ],
        ..Default::default()
    };

    let generated = gen_pyo3_data_enum_with_mapper(&def, "core", Some(&Pyo3Mapper::new()));

    assert!(generated.contains("#[staticmethod]"), "{generated}");
    assert!(generated.contains(r#"#[pyo3(name = "preset")]"#), "{generated}");
    assert!(
        generated.contains("pub fn _factory_preset(name: String) -> Self"),
        "{generated}"
    );
    assert!(
        generated.contains("Self { inner: crate::EmbeddingModelType::Preset { name } }"),
        "{generated}"
    );
    assert!(generated.contains(r#"#[pyo3(name = "custom")]"#), "{generated}");
    assert!(
        generated.contains("pub fn _factory_custom(model_id: String, dimensions: u32) -> Self"),
        "{generated}"
    );
    assert!(
        generated.contains("Self { inner: crate::EmbeddingModelType::Custom { model_id, dimensions } }"),
        "{generated}"
    );
}

/// Pyo3Backend::name returns "pyo3".
#[test]
fn pyo3_backend_name_is_pyo3() {
    let b = Pyo3Backend;
    assert_eq!(b.name(), "pyo3");
}

/// Pyo3Backend::language returns Language::Python.
#[test]
fn pyo3_backend_language_is_python() {
    let b = Pyo3Backend;
    assert_eq!(b.language(), Language::Python);
}

/// rewrite_to_tokio_mutex_struct replaces std::sync::Mutex with tokio::sync::Mutex in struct.
#[test]
fn rewrite_tokio_mutex_struct_replaces_std_mutex() {
    let input = "pub inner: Arc<std::sync::Mutex<MyType>>";
    let result = rewrite_to_tokio_mutex_struct(input);
    assert_eq!(result, "pub inner: Arc<tokio::sync::Mutex<MyType>>");
}

/// rewrite_to_tokio_mutex_struct is a no-op when no std::sync::Mutex is present.
#[test]
fn rewrite_tokio_mutex_struct_noop_when_no_std_mutex() {
    let input = "pub inner: Arc<tokio::sync::Mutex<MyType>>";
    let result = rewrite_to_tokio_mutex_struct(input);
    assert_eq!(result, input);
}

/// rewrite_to_tokio_mutex_impl replaces all three patterns in impl block.
#[test]
fn rewrite_tokio_mutex_impl_replaces_all_patterns() {
    let input = concat!(
        "pub inner: Arc<std::sync::Mutex<MyType>>,\n",
        "Self { inner: Arc::new(std::sync::Mutex::new(val)) }\n",
        "let guard = self.inner.lock().unwrap();\n",
    );
    let result = rewrite_to_tokio_mutex_impl(input);
    assert!(result.contains("Arc<tokio::sync::Mutex<MyType>>"));
    assert!(result.contains("Arc::new(tokio::sync::Mutex::new(val))"));
    assert!(result.contains("self.inner.lock().await"));
}

/// rewrite_to_tokio_mutex_impl is a no-op when no std patterns are present.
#[test]
fn rewrite_tokio_mutex_impl_noop_when_already_tokio() {
    let input = concat!(
        "pub inner: Arc<tokio::sync::Mutex<MyType>>,\n",
        "Self { inner: Arc::new(tokio::sync::Mutex::new(val)) }\n",
        "let guard = self.inner.lock().await;\n",
    );
    let result = rewrite_to_tokio_mutex_impl(input);
    assert_eq!(result, input);
}

/// `cfg_present_for_pyo3` accepts `not(target_arch = "wasm32")` gates.
#[test]
fn cfg_present_for_pyo3_accepts_non_wasm_gate() {
    assert!(cfg_present_for_pyo3("not(target_arch = \"wasm32\")"));
    assert!(cfg_present_for_pyo3("not (target_arch = \"wasm32\")"));
}

/// `cfg_present_for_pyo3` accepts feature gates since pyo3 compiles with known features.
#[test]
fn cfg_present_for_pyo3_accepts_feature_gates() {
    assert!(cfg_present_for_pyo3("feature = \"pdf\""));
    assert!(cfg_present_for_pyo3("feature = \"html\""));
    assert!(cfg_present_for_pyo3("feature=\"tree-sitter\""));
    assert!(cfg_present_for_pyo3(
        "any(feature=\"keywords-yake\", feature=\"keywords-rake\")"
    ));
}

/// `cfg_present_for_pyo3` rejects unsupported gates.
#[test]
fn cfg_present_for_pyo3_rejects_unsupported_gates() {
    assert!(!cfg_present_for_pyo3("target_arch = \"wasm32\""));
    assert!(!cfg_present_for_pyo3("any(unix, windows)"));
    assert!(!cfg_present_for_pyo3("any(unix, feature=\"pdf\")"));
}

fn python_config() -> crate::core::config::ResolvedCrateConfig {
    let cfg: crate::core::config::new_config::NewAlefConfig = toml::from_str(
        r#"
[workspace]
languages = ["python"]

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

[crates.python]
module_name = "test_lib"
"#,
    )
    .unwrap();
    cfg.resolve().unwrap().remove(0)
}

/// A `#[pyo3(get)]` field getter and a `#[pymethods]` wrapper with the same Python name both
/// bind that name on the class. pyo3 registers the method last, which silently kills the getter
/// and turns the documented attribute into a bound method. The field wins; the wrapper is
/// dropped, matching the ffi/wasm/go/ruby resolution.
#[test]
fn struct_impl_block_skips_method_colliding_with_a_field_getter() {
    use crate::core::ir::{ApiSurface, MethodDef, ReceiverKind, TypeDef};

    let api = ApiSurface {
        crate_name: "test-lib".to_string(),
        version: "0.1.0".to_string(),
        types: vec![TypeDef {
            name: "LlmConfig".to_string(),
            rust_path: "test_lib::LlmConfig".to_string(),
            has_serde: true,
            fields: vec![FieldDef {
                name: "providers".to_string(),
                ty: TypeRef::String,
                optional: true,
                ..Default::default()
            }],
            methods: vec![MethodDef {
                name: "providers".to_string(),
                return_type: TypeRef::String,
                receiver: Some(ReceiverKind::Ref),
                cfg: None,
                ..Default::default()
            }],
            ..Default::default()
        }],
        ..Default::default()
    };

    let files = Pyo3Backend.generate_bindings(&api, &python_config()).unwrap();
    let content = &files[0].content;

    assert!(
        content.contains("pub providers:"),
        "the struct field must still be emitted:\n{content}"
    );
    let wrappers = content.matches("fn providers(&self)").count();
    assert_eq!(
        wrappers, 0,
        "the same-named #[pymethods] wrapper must be skipped, found {wrappers}:\n{content}"
    );
}

#[test]
fn from_json_deserializes_the_core_type_before_conversion() {
    use crate::core::ir::{ApiSurface, TypeDef};

    let temporary_directory = tempfile::tempdir().unwrap();
    let binding_directory = temporary_directory.path().join("test-lib-py");
    std::fs::create_dir_all(binding_directory.join("src")).unwrap();
    std::fs::write(
        binding_directory.join("Cargo.toml"),
        "[dependencies]\nserde = { version = \"1\", features = [\"derive\"] }\nserde_json = \"1\"\n",
    )
    .unwrap();
    let mut config = python_config();
    config
        .output_paths
        .insert("python".to_string(), binding_directory.join("src"));

    let api = ApiSurface {
        crate_name: "test-lib".to_string(),
        version: "0.1.0".to_string(),
        types: vec![
            TypeDef {
                name: "ExtractionConfig".to_string(),
                rust_path: "test-lib::config::ExtractionConfig".to_string(),
                has_serde: true,
                fields: vec![FieldDef {
                    name: "chunking".to_string(),
                    ty: TypeRef::String,
                    ..Default::default()
                }],
                ..Default::default()
            },
            TypeDef {
                name: "BorrowedConfig".to_string(),
                rust_path: "test-lib::config::BorrowedConfig".to_string(),
                has_serde: true,
                has_lifetime_params: true,
                fields: vec![FieldDef {
                    name: "label".to_string(),
                    ty: TypeRef::String,
                    ..Default::default()
                }],
                ..Default::default()
            },
        ],
        ..Default::default()
    };

    let files = Pyo3Backend.generate_bindings(&api, &config).unwrap();
    let content = &files[0].content;

    assert!(
        content.contains("serde_json::from_str::<test_lib::config::ExtractionConfig>(&json_str)"),
        "from_json must preserve the core serde contract before converting to the binding: {content}"
    );
    assert!(
        content.contains("serde_json::from_str::<test_lib::config::BorrowedConfig<'_>>(&json_str)"),
        "from_json must specialize lifetime-bearing core DTOs before deserializing: {content}"
    );
    assert!(
        content.contains(".map(Into::into)"),
        "from_json must convert the deserialized core value into the pyo3 wrapper: {content}"
    );
}

#[test]
fn nested_data_enum_records_are_not_skipped_as_opaque() {
    use crate::core::ir::{ApiSurface, TypeDef};
    let record = |name: &str, field: &str, ty: TypeRef| TypeDef {
        name: name.into(),
        rust_path: format!("test_lib::{name}"),
        has_serde: true,
        fields: vec![FieldDef {
            name: field.into(),
            ty,
            ..Default::default()
        }],
        ..Default::default()
    };
    let api = ApiSurface {
        crate_name: "test-lib".into(),
        version: "0.1.0".into(),
        enums: vec![EnumDef {
            name: "Policy".into(),
            rust_path: "test_lib::Policy".into(),
            has_serde: true,
            variants: vec![EnumVariant {
                name: "Analyze".into(),
                fields: vec![FieldDef {
                    name: "label".into(),
                    ty: TypeRef::String,
                    ..Default::default()
                }],
                ..Default::default()
            }],
            ..Default::default()
        }],
        types: vec![
            record("Request", "policy", TypeRef::Named("Policy".into())),
            record("Prepared", "request", TypeRef::Named("Request".into())),
            record(
                "Batch",
                "items",
                TypeRef::Vec(Box::new(TypeRef::Named("Prepared".into()))),
            ),
        ],
        ..Default::default()
    };
    let files = Pyo3Backend.generate_bindings(&api, &python_config()).unwrap();
    let content = &files[0].content;
    assert!(content.contains("pub request: Request"));
    assert!(content.contains("pub items: Vec<Prepared>"));
    assert!(!content.contains("#[serde(skip)]"), "{content}");
    syn::parse_file(content).unwrap();
}

#[test]
fn lifetime_from_json_compiles_for_a_borrowing_core_dto() {
    use crate::core::ir::{ApiSurface, CoreWrapper, TypeDef};

    let temporary_directory = tempfile::tempdir().unwrap();
    let core_directory = temporary_directory.path().join("test-lib");
    let binding_directory = temporary_directory.path().join("test-lib-py");
    std::fs::create_dir_all(core_directory.join("src")).unwrap();
    std::fs::create_dir_all(binding_directory.join("src")).unwrap();
    std::fs::write(
        core_directory.join("Cargo.toml"),
        "[package]\nname = \"test-lib\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\
         [dependencies]\nserde = { version = \"1\", features = [\"derive\"] }\n",
    )
    .unwrap();
    std::fs::write(
        core_directory.join("src/lib.rs"),
        "use std::borrow::Cow;\n\
         #[derive(Clone, serde::Deserialize)]\n\
         pub struct BorrowedConfig<'a> {\n\
             #[serde(borrow)]\n\
             pub label: Cow<'a, str>,\n\
         }\n",
    )
    .unwrap();
    std::fs::write(
        binding_directory.join("Cargo.toml"),
        "[package]\nname = \"test-lib-py\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\
         [dependencies]\npyo3 = \"=0.29.2\"\nserde = { version = \"1\", features = [\"derive\"] }\n\
         serde_json = \"1\"\ntest-lib = { path = \"../test-lib\" }\n",
    )
    .unwrap();

    let mut config = python_config();
    config.python.as_mut().unwrap().module_name = Some("_test_lib".to_string());
    config
        .output_paths
        .insert("python".to_string(), binding_directory.join("src"));
    let api = ApiSurface {
        crate_name: "test-lib".to_string(),
        version: "0.1.0".to_string(),
        types: vec![TypeDef {
            name: "BorrowedConfig".to_string(),
            rust_path: "test-lib::BorrowedConfig".to_string(),
            has_serde: true,
            has_lifetime_params: true,
            fields: vec![FieldDef {
                name: "label".to_string(),
                ty: TypeRef::String,
                core_wrapper: CoreWrapper::Cow,
                ..Default::default()
            }],
            ..Default::default()
        }],
        ..Default::default()
    };
    let generated = Pyo3Backend.generate_bindings(&api, &config).unwrap();
    std::fs::write(binding_directory.join("src/lib.rs"), &generated[0].content).unwrap();

    let output = std::process::Command::new("cargo")
        .args(["check", "--quiet", "--manifest-path"])
        .arg(binding_directory.join("Cargo.toml"))
        .env("CARGO_TARGET_DIR", temporary_directory.path().join("target"))
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "generated borrowing DTO binding must compile:\n{}",
        String::from_utf8_lossy(&output.stderr)
    );
}

/// Regression test for issue #380, exercised through the real `Pyo3Backend::generate_bindings`
/// path (not just the `gen_function` unit): a `&mut T` DTO parameter on a unit-returning free
/// function must render as a binding that returns the mutated intermediate.
#[test]
fn generate_bindings_writeback_free_function_returns_mutated_dto() {
    use crate::core::ir::{ApiSurface, FunctionDef, ParamDef};

    let api = ApiSurface {
        crate_name: "test-lib".to_string(),
        version: "0.1.0".to_string(),
        types: vec![crate::core::ir::TypeDef {
            name: "Record".to_string(),
            rust_path: "test_lib::Record".to_string(),
            has_serde: true,
            fields: vec![FieldDef {
                name: "score".to_string(),
                ty: TypeRef::Primitive(PrimitiveType::U32),
                ..Default::default()
            }],
            ..Default::default()
        }],
        functions: vec![FunctionDef {
            name: "tag_record".to_string(),
            rust_path: "test_lib::tag_record".to_string(),
            params: vec![ParamDef {
                name: "record".to_string(),
                ty: TypeRef::Named("Record".to_string()),
                is_ref: true,
                is_mut: true,
                ..Default::default()
            }],
            return_type: TypeRef::Unit,
            ..Default::default()
        }],
        ..Default::default()
    };

    let files = Pyo3Backend.generate_bindings(&api, &python_config()).unwrap();
    let content = &files[0].content;

    assert!(
        content.contains("record_core.into()"),
        "expected the write-back tail through the real generate_bindings path:\n{content}"
    );
}

/// `reject_unsupported_writeback` must fire through the real `Pyo3Backend::generate_bindings`
/// path: a `&mut T` DTO param on a function that ALSO returns a value has no free return slot
/// for the write-back value, so generation must fail loudly (naming the function).
#[test]
fn generate_bindings_rejects_mut_dto_param_with_non_unit_return() {
    use crate::core::ir::{ApiSurface, FunctionDef, ParamDef};

    let api = ApiSurface {
        crate_name: "test-lib".to_string(),
        version: "0.1.0".to_string(),
        types: vec![crate::core::ir::TypeDef {
            name: "Record".to_string(),
            rust_path: "test_lib::Record".to_string(),
            has_serde: true,
            fields: vec![FieldDef {
                name: "score".to_string(),
                ty: TypeRef::Primitive(PrimitiveType::U32),
                ..Default::default()
            }],
            ..Default::default()
        }],
        functions: vec![FunctionDef {
            name: "tag_and_count".to_string(),
            rust_path: "test_lib::tag_and_count".to_string(),
            params: vec![ParamDef {
                name: "record".to_string(),
                ty: TypeRef::Named("Record".to_string()),
                is_ref: true,
                is_mut: true,
                ..Default::default()
            }],
            return_type: TypeRef::Primitive(PrimitiveType::U32),
            ..Default::default()
        }],
        ..Default::default()
    };

    let error = Pyo3Backend
        .generate_bindings(&api, &python_config())
        .expect_err("a `&mut` DTO param plus a non-unit return must be rejected at generation time");
    let message = error.to_string();
    assert!(
        message.contains("tag_and_count"),
        "diagnostic must name the offending function:\n{message}"
    );
}