alef 0.36.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
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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
use super::*;

#[test]
fn test_scaffold_csharp_omits_repository_when_unconfigured() {
    let config = minimal_config_from_toml("");
    let api = test_api();
    let all_files = scaffold(&api, &config, &[Language::Csharp]).unwrap();
    let files = language_files(&all_files);
    let csproj = files
        .iter()
        .find(|f| f.path.to_string_lossy().ends_with(".csproj"))
        .expect("C# project file must be emitted");

    assert!(
        !csproj.content.contains("<RepositoryUrl>"),
        "unconfigured C# scaffold must not invent repository metadata:\n{}",
        csproj.content
    );
}

#[test]
fn test_scaffold_wasm_omits_repository_when_unconfigured() {
    let config = minimal_config_from_toml("");
    let api = test_api();
    let all_files = scaffold(&api, &config, &[Language::Wasm]).unwrap();
    let files = language_files(&all_files);
    let package_json = files
        .iter()
        .find(|f| f.path == Path::new("crates/my-lib-wasm/package.json"))
        .expect("WASM package.json must be emitted");
    let parsed: serde_json::Value =
        serde_json::from_str(&package_json.content).expect("emitted package.json must be valid JSON");

    assert!(
        parsed.get("repository").is_none(),
        "unconfigured WASM manifest must not invent repository metadata:\n{}",
        package_json.content
    );
    assert_eq!(parsed["engines"]["node"], ">= 22");
}

fn wasm_package_json(toml: &str) -> serde_json::Value {
    let config = minimal_config_from_toml(toml);
    let api = test_api();
    let all_files = scaffold(&api, &config, &[Language::Wasm]).unwrap();
    let files = language_files(&all_files);
    let package_json = files
        .iter()
        .find(|f| f.path == Path::new("crates/my-lib-wasm/package.json"))
        .expect("WASM package.json must be emitted");
    serde_json::from_str(&package_json.content).expect("emitted package.json must be valid JSON")
}

#[test]
fn wasm_targets_default_to_all_four_wasm_pack_targets() {
    let parsed = wasm_package_json("");
    // Default: every wasm-pack target ships, broad file glob, nodejs entry points.
    assert_eq!(
        parsed["files"],
        serde_json::json!(["pkg", "*.wasm", "*.d.ts", "README.md"])
    );
    assert_eq!(parsed["main"], "pkg/nodejs/my_lib_wasm.js");
    assert_eq!(parsed["module"], "pkg/web/my_lib_wasm.js");
    assert_eq!(parsed["types"], "pkg/nodejs/my_lib_wasm.d.ts");
    let scripts = &parsed["scripts"];
    for t in ["web", "bundler", "nodejs", "deno"] {
        assert!(
            scripts.get(format!("build:wasm:{t}")).is_some(),
            "missing build:wasm:{t}"
        );
    }
    assert_eq!(
        scripts["build:all"],
        "npm run build:wasm:web && npm run build:wasm:bundler && npm run build:wasm:nodejs && npm run build:wasm:deno && find pkg -name .gitignore -delete"
    );
}

#[test]
fn wasm_targets_web_only_ships_single_target() {
    let parsed = wasm_package_json("[crates.wasm]\ntargets = [\"web\"]\n");
    // Single target: publish only pkg/web, entry points and build all point at web.
    assert_eq!(parsed["files"], serde_json::json!(["pkg/web", "README.md"]));
    assert_eq!(parsed["main"], "pkg/web/my_lib_wasm.js");
    assert_eq!(parsed["module"], "pkg/web/my_lib_wasm.js");
    assert_eq!(parsed["types"], "pkg/web/my_lib_wasm.d.ts");
    let scripts = &parsed["scripts"];
    assert!(scripts.get("build:wasm:web").is_some());
    for t in ["bundler", "nodejs", "deno"] {
        assert!(
            scripts.get(format!("build:wasm:{t}")).is_none(),
            "unexpected build:wasm:{t}"
        );
    }
    assert_eq!(
        scripts["build:all"],
        "npm run build:wasm:web && find pkg -name .gitignore -delete"
    );
    assert_eq!(scripts["build"], "wasm-pack build --target web --out-dir pkg/web");
}

#[test]
fn wasm_targets_rejects_unknown_target() {
    let config = minimal_config_from_toml("[crates.wasm]\ntargets = [\"webxr\"]\n");
    let api = test_api();
    let err = scaffold(&api, &config, &[Language::Wasm]).expect_err("unknown wasm target must error");
    assert!(
        err.to_string().contains("unknown target 'webxr'"),
        "unexpected error: {err}"
    );
}

#[test]
fn test_scaffold_java_requires_publish_metadata() {
    let config = minimal_config_from_toml("");
    let api = test_api();
    let err = scaffold(&api, &config, &[Language::Java]).expect_err("Java scaffold must require publish metadata");

    assert!(
        err.to_string()
            .contains("Java scaffold requires package metadata repository"),
        "unexpected error: {err}"
    );
}

#[test]
fn test_scaffold_kotlin_requires_publish_metadata() {
    let config = minimal_config_from_toml("");
    let api = test_api();
    let err = scaffold(&api, &config, &[Language::Kotlin]).expect_err("Kotlin scaffold must require publish metadata");

    assert!(
        err.to_string()
            .contains("Kotlin scaffold requires package metadata repository"),
        "unexpected error: {err}"
    );
}

#[test]
fn test_scaffold_r_requires_authors() {
    let config = minimal_config_from_toml("");
    let api = test_api();
    let err = scaffold(&api, &config, &[Language::R]).expect_err("R scaffold must require authors");

    assert!(
        err.to_string().contains("R scaffold requires package metadata authors"),
        "unexpected error: {err}"
    );
}

#[test]
fn test_scaffold_multiple() {
    let config = test_config();
    let api = test_api();
    let all_files = scaffold(&api, &config, &[Language::Python, Language::Node]).unwrap();
    let files = language_files(&all_files);
    assert_eq!(files.len(), 14);
}

#[test]
fn test_scaffold_gitattributes_covers_all_generated_dirs() {
    let config = test_config();
    let api = test_api();

    let all_files = scaffold(&api, &config, &[Language::Python, Language::Node]).unwrap();
    let ga = all_files
        .iter()
        .find(|f| f.path == std::path::Path::new(".gitattributes"))
        .expect(".gitattributes must be emitted by scaffold");

    assert!(
        !ga.generated_header,
        "generated_header must be false — create-once seed"
    );

    let content = &ga.content;
    assert!(content.contains("packages/python/**"), "must cover Python package dir");
    assert!(content.contains("crates/my-lib-node/**"), "must cover Node crate dir");
    assert!(content.contains("crates/my-lib-py/**"), "must cover PyO3 binding crate");
    assert!(content.contains("e2e/**"), "must cover e2e test output");
    for line in content.lines().filter(|l| !l.starts_with('#') && !l.is_empty()) {
        assert!(
            line.ends_with("linguist-generated=true"),
            "every non-comment line must set linguist-generated=true, got: {line}"
        );
    }
}

#[test]
fn test_scaffold_gitattributes_ffi_and_jni_use_crate_dirs() {
    let config = test_config();
    let api = test_api();

    let all_files = scaffold(&api, &config, &[Language::Ffi, Language::Jni]).unwrap();
    let ga = all_files
        .iter()
        .find(|f| f.path == std::path::Path::new(".gitattributes"))
        .expect(".gitattributes must be emitted");

    let content = &ga.content;
    assert!(content.contains("crates/my-lib-ffi/**"), "must cover FFI crate dir");
    assert!(content.contains("crates/my-lib-jni/**"), "must cover JNI crate dir");
    assert!(!content.contains("packages/ffi"), "must not emit bogus packages/ffi");
    assert!(!content.contains("packages/jni"), "must not emit bogus packages/jni");
}

#[test]
fn test_scaffold_gitattributes_kotlin_native_uses_kotlin_native_dir() {
    use crate::core::config::NewAlefConfig;

    let cfg: NewAlefConfig = toml::from_str(
        r#"
[workspace]
languages = ["kotlin"]

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

[crates.scaffold]
description = "Test"
license = "MIT"
repository = "https://github.com/test/my-lib"

[crates.kotlin]
target = "native"
"#,
    )
    .unwrap();
    let config = cfg.resolve().unwrap().remove(0);
    let api = test_api();

    let all_files = scaffold(&api, &config, &[Language::Kotlin]).unwrap();
    let ga = all_files
        .iter()
        .find(|f| f.path == std::path::Path::new(".gitattributes"))
        .expect(".gitattributes must be emitted");

    assert!(
        ga.content.contains("packages/kotlin-native/**"),
        "native target must use packages/kotlin-native, got:\n{}",
        ga.content
    );
    assert!(
        !ga.content.contains("packages/kotlin/**"),
        "native target must not emit JVM dir, got:\n{}",
        ga.content
    );
}

#[test]
fn test_scaffold_gitattributes_kotlin_mpp_uses_kotlin_mpp_dir() {
    use crate::core::config::NewAlefConfig;

    let cfg: NewAlefConfig = toml::from_str(
        r#"
[workspace]
languages = ["kotlin"]

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

[crates.scaffold]
description = "Test"
license = "MIT"
repository = "https://github.com/test/my-lib"

[crates.kotlin]
mode = "kmp"
"#,
    )
    .unwrap();
    let config = cfg.resolve().unwrap().remove(0);
    let api = test_api();

    let all_files = scaffold(&api, &config, &[Language::Kotlin]).unwrap();
    let ga = all_files
        .iter()
        .find(|f| f.path == std::path::Path::new(".gitattributes"))
        .expect(".gitattributes must be emitted");

    assert!(
        ga.content.contains("packages/kotlin-mpp/**"),
        "kmp mode must use packages/kotlin-mpp, got:\n{}",
        ga.content
    );
    assert!(
        !ga.content.contains("packages/kotlin/**"),
        "kmp mode must not emit JVM dir, got:\n{}",
        ga.content
    );
}

#[test]
fn test_scaffold_gitattributes_kotlin_multiplatform_target_uses_kotlin_mpp_dir() {
    use crate::core::config::NewAlefConfig;

    let cfg: NewAlefConfig = toml::from_str(
        r#"
[workspace]
languages = ["kotlin"]

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

[crates.scaffold]
description = "Test"
license = "MIT"
repository = "https://github.com/test/my-lib"

[crates.kotlin]
target = "multiplatform"
"#,
    )
    .unwrap();
    let config = cfg.resolve().unwrap().remove(0);
    let api = test_api();

    let all_files = scaffold(&api, &config, &[Language::Kotlin]).unwrap();
    let ga = all_files
        .iter()
        .find(|f| f.path == std::path::Path::new(".gitattributes"))
        .expect(".gitattributes must be emitted");

    assert!(
        ga.content.contains("packages/kotlin-mpp/**"),
        "target=multiplatform must use packages/kotlin-mpp, got:\n{}",
        ga.content
    );
}

#[test]
fn test_scaffold_gitattributes_kotlin_android_uses_kotlin_android_dir() {
    let config = test_config();
    let api = test_api();

    let all_files = scaffold(&api, &config, &[Language::KotlinAndroid]).unwrap();
    let ga = all_files
        .iter()
        .find(|f| f.path == std::path::Path::new(".gitattributes"))
        .expect(".gitattributes must be emitted");

    assert!(
        ga.content.contains("packages/kotlin-android/**"),
        "KotlinAndroid must use packages/kotlin-android, got:\n{}",
        ga.content
    );
}

#[test]
fn wasm_package_name_strips_node_suffix_from_scoped_package() {
    let config = test_config_from_toml(
        r#"
[crates.node]
package_name = "@scope/foo-node"
"#,
    );
    let api = test_api();
    let files = scaffold(&api, &config, &[Language::Wasm]).unwrap();
    let pkg_json = files
        .iter()
        .find(|f| f.path.ends_with("package.json"))
        .expect("wasm scaffold must emit package.json");
    assert!(
        pkg_json.content.contains("\"@scope/foo-wasm\""),
        "expected @scope/foo-wasm, got:\n{}",
        pkg_json.content
    );
    assert!(
        !pkg_json.content.contains("foo-node-wasm"),
        "must not emit foo-node-wasm, got:\n{}",
        pkg_json.content
    );
}

#[test]
fn wasm_package_name_strips_node_suffix_from_unscoped_package() {
    let config = test_config_from_toml(
        r#"
[crates.node]
package_name = "foo-node"
"#,
    );
    let api = test_api();
    let files = scaffold(&api, &config, &[Language::Wasm]).unwrap();
    let pkg_json = files
        .iter()
        .find(|f| f.path.ends_with("package.json"))
        .expect("wasm scaffold must emit package.json");
    assert!(
        pkg_json.content.contains("\"foo-wasm\""),
        "expected foo-wasm, got:\n{}",
        pkg_json.content
    );
}

#[test]
fn wasm_package_name_fallback_when_no_node_suffix() {
    let config = test_config();
    let api = test_api();
    let files = scaffold(&api, &config, &[Language::Wasm]).unwrap();
    let pkg_json = files
        .iter()
        .find(|f| f.path.ends_with("package.json"))
        .expect("wasm scaffold must emit package.json");
    assert!(
        pkg_json.content.contains("\"my-lib-wasm\""),
        "expected my-lib-wasm, got:\n{}",
        pkg_json.content
    );
}

#[test]
fn wasm_package_name_uses_explicit_wasm_config() {
    let config = test_config_from_toml(
        r#"
[crates.node]
package_name = "@scope/foo-node"

[crates.wasm]
package_name = "@scope/foo-web"
"#,
    );
    let api = test_api();
    let files = scaffold(&api, &config, &[Language::Wasm]).unwrap();
    let pkg_json = files
        .iter()
        .find(|f| f.path.ends_with("package.json"))
        .expect("wasm scaffold must emit package.json");
    let parsed: serde_json::Value = serde_json::from_str(&pkg_json.content).expect("valid wasm package.json");
    assert_eq!(parsed["name"], "@scope/foo-web");
    assert_eq!(parsed["publishConfig"]["access"], "public");
    assert_eq!(parsed["main"], "pkg/nodejs/my_lib_wasm.js");
    assert_eq!(parsed["types"], "pkg/nodejs/my_lib_wasm.d.ts");
}

#[test]
fn test_scaffold_r_authors_r_parses_name_and_email() {
    let config = test_config_from_toml(
        r#"
[crates.package_metadata]
authors = ["Ada Lovelace <ada@example.com>"]
"#,
    );
    let api = test_api();
    let all_files = scaffold(&api, &config, &[Language::R]).unwrap();
    let files = language_files(&all_files);
    let description = files.iter().find(|f| f.path.ends_with("DESCRIPTION")).unwrap();

    assert!(
        description
            .content
            .contains(r#"Authors@R: person("Ada", "Lovelace", email = "ada@example.com", role = c("aut", "cre"))"#),
        "DESCRIPTION must split Authors@R name/email; content:\n{}",
        description.content
    );
}

/// The extendr backend emits `#[cfg(feature = "X")]` gates on cfg-gated functions
/// into the R crate's `lib.rs`. The generated `packages/r/src/rust/Cargo.toml` must
/// therefore declare a forwarding `[features]` table so those gates do not produce
/// `error: unexpected cfg condition value: X` under `RUSTFLAGS=-D warnings`.
#[test]
fn test_scaffold_r_cargo_forwards_cfg_features() {
    use crate::core::ir::{FunctionDef, TypeRef};

    let config = test_config_from_toml(
        r#"
[crates.package_metadata]
authors = ["Ada Lovelace <ada@example.com>"]
"#,
    );
    let mut api = test_api();
    api.functions = vec![
        FunctionDef {
            name: "extract_file_sync".to_string(),
            rust_path: "my_lib::extract_file_sync".to_string(),
            return_type: TypeRef::String,
            cfg: Some("feature = \"tokio-runtime\"".to_string()),
            ..Default::default()
        },
        FunctionDef {
            name: "analyze_document".to_string(),
            rust_path: "my_lib::analyze_document".to_string(),
            return_type: TypeRef::String,
            cfg: Some("feature = \"heuristics\"".to_string()),
            ..Default::default()
        },
    ];

    let all_files = scaffold(&api, &config, &[Language::R]).unwrap();
    let files = language_files(&all_files);
    let cargo = files
        .iter()
        .find(|f| f.path.ends_with("packages/r/src/rust/Cargo.toml"))
        .expect("R rust crate Cargo.toml must be emitted");

    assert!(
        cargo.content.contains("[features]"),
        "R Cargo.toml must contain a [features] block when cfg-gated items exist; content:\n{}",
        cargo.content
    );
    assert!(
        cargo.content.contains(r#"tokio-runtime = ["my-lib/tokio-runtime"]"#),
        "R Cargo.toml must forward `tokio-runtime` to the core dep; content:\n{}",
        cargo.content
    );
    assert!(
        cargo.content.contains(r#"heuristics = ["my-lib/heuristics"]"#),
        "R Cargo.toml must forward `heuristics` to the core dep; content:\n{}",
        cargo.content
    );
    let default_line = cargo
        .content
        .lines()
        .find(|l| l.starts_with("default = ["))
        .expect("R Cargo.toml [features] must declare a `default` list");
    assert!(
        default_line.contains("\"tokio-runtime\"") && default_line.contains("\"heuristics\""),
        "default feature list must include every cfg-forwarded feature; got: {default_line}"
    );
    toml::from_str::<toml::Value>(&cargo.content).expect("generated R Cargo.toml must be valid TOML");
}

#[test]
fn test_scaffold_r_cargo_explicit_features_match_wasm_defaults() {
    use crate::core::ir::{FunctionDef, TypeDef, TypeRef};

    let config = test_config_from_toml(
        r#"
[crates.package_metadata]
authors = ["Ada Lovelace <ada@example.com>"]

[crates.r]
features = ["wasm-target"]
default_features = false
"#,
    );
    let mut api = test_api();
    api.types = vec![TypeDef {
        name: "GatedType".to_string(),
        rust_path: "my_lib::GatedType".to_string(),
        cfg: Some(r#"any(feature = "wasm-target", feature = "extra")"#.to_string()),
        ..Default::default()
    }];
    api.functions = vec![FunctionDef {
        name: "extract".to_string(),
        rust_path: "my_lib::extract".to_string(),
        return_type: TypeRef::String,
        cfg: Some("feature = \"url-ingestion\"".to_string()),
        ..Default::default()
    }];

    let all_files = scaffold(&api, &config, &[Language::R]).unwrap();
    let files = language_files(&all_files);
    let cargo = files
        .iter()
        .find(|f| f.path.ends_with("packages/r/src/rust/Cargo.toml"))
        .expect("R rust crate Cargo.toml must be emitted");

    assert!(
        cargo.content.contains(
            r#"my-lib = { version = "0.1.0", path = "../../../../crates/my-lib", default-features = false, features = ["wasm-target"] }"#,
        ),
        "R core dependency must disable defaults when explicit features are configured; content:\n{}",
        cargo.content
    );
    assert!(
        cargo.content.contains(r#"wasm-target = ["my-lib/wasm-target"]"#),
        "R Cargo.toml must declare cfg passthrough features; content:\n{}",
        cargo.content
    );
    assert!(
        !cargo.content.contains("default = ["),
        "R Cargo.toml must not auto-enable cfg passthrough features with explicit configured features; content:\n{}",
        cargo.content
    );
    toml::from_str::<toml::Value>(&cargo.content).expect("generated R Cargo.toml must be valid TOML");
}

/// When the API surface has no cfg-gated items the R Cargo.toml must omit the
/// `[features]` block entirely (no empty table).
#[test]
fn test_scaffold_r_cargo_omits_features_block_when_no_cfg() {
    let config = test_config_from_toml(
        r#"
[crates.package_metadata]
authors = ["Ada Lovelace <ada@example.com>"]
"#,
    );
    let api = test_api();
    let all_files = scaffold(&api, &config, &[Language::R]).unwrap();
    let files = language_files(&all_files);
    let cargo = files
        .iter()
        .find(|f| f.path.ends_with("packages/r/src/rust/Cargo.toml"))
        .expect("R rust crate Cargo.toml must be emitted");

    assert!(
        !cargo.content.contains("[features]"),
        "R Cargo.toml must not emit a [features] block when no cfg-gated items exist; content:\n{}",
        cargo.content
    );
    toml::from_str::<toml::Value>(&cargo.content).expect("generated R Cargo.toml must be valid TOML");
}

#[test]
fn test_scaffold_r_cargo_no_workspace_inheritance() {
    let config = test_config_from_toml(
        r#"
[crates.package_metadata]
authors = ["Ada Lovelace <ada@example.com>"]
"#,
    );
    let api = test_api();
    let all_files = scaffold(&api, &config, &[Language::R]).unwrap();
    let files = language_files(&all_files);
    let cargo = files
        .iter()
        .find(|f| f.path.ends_with("packages/r/src/rust/Cargo.toml"))
        .expect("R rust crate Cargo.toml must be emitted");

    assert!(
        !cargo.content.contains("version.workspace"),
        "R Cargo.toml must NOT use workspace inheritance for version (excluded from workspace); content:\n{}",
        cargo.content
    );
    assert!(
        !cargo.content.contains("license.workspace"),
        "R Cargo.toml must NOT use workspace inheritance for license (excluded from workspace); content:\n{}",
        cargo.content
    );

    assert!(
        cargo.content.contains(r#"version = "0.1.0""#),
        "R Cargo.toml must have concrete version field; content:\n{}",
        cargo.content
    );

    toml::from_str::<toml::Value>(&cargo.content).expect("generated R Cargo.toml must be valid TOML");
}