alef 0.62.11

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
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
use crate::core::backend::GeneratedFile;
use crate::core::config::{AdapterPattern, FfiTargetDepOverride, Language, ResolvedCrateConfig};
use crate::core::ir::ApiSurface;
use crate::core::template_versions as tv;
use crate::{
    scaffold::cargo_package_header, scaffold::core_dep_features, scaffold::detect_workspace_inheritance_for_crate,
    scaffold::render_extra_deps, scaffold::scaffold_meta,
};
use std::path::PathBuf;

/// Render the core-crate dependency portion of the FFI Cargo.toml.
///
/// Returns a tuple of `(core_dep_line, target_blocks)` where:
/// - `core_dep_line` is the single TOML line that goes inside the main
///   `[dependencies]` table (empty string when target overrides are in use).
/// - `target_blocks` contains any `[target.'cfg(...)'.dependencies]` sections
///   that follow the main `[dependencies]` table (empty string by default).
///
/// When `overrides` is empty the behaviour matches the historical output:
/// a single `{crate} = { path = ..., features = [...] }` line lives next to
/// `serde_json` / `tokio` inside `[dependencies]`. When overrides are
/// present the core-crate dependency moves out into per-cfg target blocks;
/// the default branch is wrapped in `cfg(not(any(<cfg1>, <cfg2>, ...)))` so
/// that exactly one variant matches on any given build (most importantly
/// `x86_64-linux-android`, which has no ONNX Runtime prebuilt).
fn render_core_dep(
    crate_name: &str,
    rel_path: &str,
    version: &str,
    default_features: &str,
    overrides: &[FfiTargetDepOverride],
) -> (String, String) {
    if overrides.is_empty() {
        let line = format!("{crate_name} = {{ path = \"{rel_path}\", version = \"{version}\"{default_features} }}");
        return (line, String::new());
    }

    let cfgs: Vec<String> = overrides.iter().map(|o| o.cfg.clone()).collect();
    let combined_cfg = if cfgs.len() == 1 {
        cfgs[0].clone()
    } else {
        format!("any({})", cfgs.join(", "))
    };

    let mut entries: Vec<(String, String)> = vec![(
        format!("not({combined_cfg})"),
        format!("{crate_name} = {{ path = \"{rel_path}\", version = \"{version}\"{default_features} }}"),
    )];
    for override_ in overrides {
        let default_block = if override_.default_features {
            String::new()
        } else {
            ", default-features = false".to_string()
        };
        let features_str = if override_.features.is_empty() {
            String::new()
        } else {
            let quoted: Vec<String> = override_.features.iter().map(|f| format!("\"{f}\"")).collect();
            format!(", features = [{}]", quoted.join(", "))
        };
        entries.push((
            override_.cfg.clone(),
            format!("{crate_name} = {{ path = \"{rel_path}\", version = \"{version}\"{default_block}{features_str} }}"),
        ));
    }
    // See `crate::scaffold::join_sorted_target_dep_blocks`: cargo-sort orders
    // `[target.'cfg(...)'.dependencies]` tables alphabetically by the raw cfg
    // predicate string, so the default `not(...)` branch is not always first. ~keep
    (String::new(), crate::scaffold::join_sorted_target_dep_blocks(entries))
}

pub(crate) fn scaffold_ffi(api: &ApiSurface, config: &ResolvedCrateConfig) -> anyhow::Result<Vec<GeneratedFile>> {
    let meta = scaffold_meta(config);
    let version = &api.version;
    let core_crate_dir = config.core_crate_dir();
    let crate_dir = format!("crates/{core_crate_dir}-ffi");
    let ws = detect_workspace_inheritance_for_crate(config.workspace_root.as_deref(), &crate_dir);
    let pkg_header = cargo_package_header(&format!("{core_crate_dir}-ffi"), version, "2024", &meta, &ws);

    let rendered_extra_deps = render_extra_deps(config, Language::Ffi);
    let mut extra_dep_lines: Vec<String> = if rendered_extra_deps.is_empty() {
        Vec::new()
    } else {
        rendered_extra_deps.lines().map(str::to_string).collect()
    };
    let has_trait_bridges = !config.trait_bridges.is_empty();
    if has_trait_bridges && !extra_dep_lines.iter().any(|l| l.starts_with("async-trait")) {
        extra_dep_lines.push(format!("async-trait = \"{}\"", tv::cargo::ASYNC_TRAIT));
    }
    if has_trait_bridges && !extra_dep_lines.iter().any(|l| l.starts_with("tracing")) {
        extra_dep_lines.push(format!("tracing = \"{}\"", tv::cargo::TRACING));
    }
    let has_streaming = config
        .adapters
        .iter()
        .any(|a| matches!(a.pattern, AdapterPattern::Streaming));
    if has_streaming && !extra_dep_lines.iter().any(|l| l.starts_with("futures-util")) {
        extra_dep_lines.push("futures-util = \"0.3\"".to_string());
    }
    if let Some(ffi) = config.ffi.as_ref() {
        for capsule in ffi.capsule_types.values() {
            let (Some(package), Some(version)) = (capsule.package.as_ref(), capsule.package_version.as_ref()) else {
                continue;
            };
            let dep_prefix = format!("{package} ");
            if !extra_dep_lines.iter().any(|l| l.starts_with(&dep_prefix)) {
                extra_dep_lines.push(format!("{package} = \"{version}\""));
            }
        }
    }
    crate::scaffold::sort_dependency_lines(&mut extra_dep_lines);

    let mut machete_ignored: Vec<&str> = vec!["ahash", "serde", "serde_json", "tokio"];
    if has_trait_bridges {
        machete_ignored.push("async-trait");
        machete_ignored.push("tracing");
    }
    if has_streaming {
        machete_ignored.push("futures-util");
    }
    let machete_ignored_str = machete_ignored
        .iter()
        .map(|d| format!("\"{d}\""))
        .collect::<Vec<_>>()
        .join(", ");

    let target_overrides: &[FfiTargetDepOverride] = config
        .ffi
        .as_ref()
        .map(|c| c.target_dep_overrides.as_slice())
        .unwrap_or(&[]);
    let core_dep_path = config.core_crate_dep_path(std::path::Path::new(&crate_dir));
    let (core_dep_line, target_blocks) = render_core_dep(
        &config.name,
        &core_dep_path,
        version,
        &core_dep_features(config, Language::Ffi),
        target_overrides,
    );

    // FFI source uses `#[cfg(feature = "X")]` to gate code paths driven by core-crate
    let ffi_core_features = config.features_for_language(Language::Ffi);
    let passthrough_feature_names: Vec<&str> = ffi_core_features
        .iter()
        .map(|f| f.as_str())
        .filter(|f| *f != "serde")
        .collect();
    // Cargo features are per-crate: `full = ["<core>/full"]` enabling `X` on the dependency
    // does NOT create feature `X` here, so a `#[cfg(feature = "X")]` the codegen emits into
    // this crate is unsatisfiable unless this crate declares `X` itself. An undeclared gate is
    // never true, which silently drops the export from the cdylib while cbindgen still declares
    // it in the header -- a link failure for every C-ABI consumer. Declare every feature the
    // emitted surface actually gates on. ~keep
    let extra_declared: &[String] = config.ffi.as_ref().map(|c| c.extra_features.as_slice()).unwrap_or(&[]);
    let emitted_cfg_features: Vec<String> = crate::codegen::cfg::collect_cfg_features(api)
        .into_iter()
        .filter(|name| {
            !name.is_empty()
                && name != "serde"
                && !passthrough_feature_names.contains(&name.as_str())
                && !extra_declared.iter().any(|declared| declared == name)
        })
        .collect();
    // `extra_features` stays declare-only by design (mutually-exclusive alternatives such as
    // `wasm-http`); features discovered from emitted gates default ON, preserving the surface
    // the gate was written to expose while keeping it switchable. ~keep
    let default_feature_names: Vec<&str> = passthrough_feature_names
        .iter()
        .copied()
        .chain(emitted_cfg_features.iter().map(String::as_str))
        .collect();
    let core_features_default_list = default_feature_names
        .iter()
        .map(|f| format!("\"{f}\""))
        .collect::<Vec<_>>()
        .join(", ");
    let mut core_features_passthrough_block = if default_feature_names.is_empty() {
        String::new()
    } else {
        default_feature_names
            .iter()
            .map(|f| format!("{f} = [\"{}/{f}\"]", config.name))
            .collect::<Vec<_>>()
            .join("\n")
    };
    if let Some(line) = crate::scaffold::android_target_feature_line(config, &default_feature_names) {
        if core_features_passthrough_block.is_empty() {
            core_features_passthrough_block = line;
        } else {
            core_features_passthrough_block.push('\n');
            core_features_passthrough_block.push_str(&line);
        }
    }
    // feature in a `#[cfg(feature = "X")]` gate (e.g. a `wasm-http` backend that is
    if let Some(extra) = config.ffi.as_ref().map(|c| c.extra_features.as_slice()) {
        for feat in extra {
            if feat.is_empty() || passthrough_feature_names.contains(&feat.as_str()) {
                continue;
            }
            let line = format!("{feat} = [\"{}/{feat}\"]", config.name);
            if core_features_passthrough_block.is_empty() {
                core_features_passthrough_block = line;
            } else {
                core_features_passthrough_block.push('\n');
                core_features_passthrough_block.push_str(&line);
            }
        }
    }
    let target_blocks_section = if target_blocks.is_empty() {
        String::new()
    } else {
        format!("\n{target_blocks}\n")
    };

    let mut dep_entries: Vec<String> = vec![
        "ahash = \"0.8\"".to_string(),
        format!("serde = \"{}\"", tv::cargo::SERDE),
        "serde_json = \"1\"".to_string(),
        "tokio = { version = \"1\", features = [\"full\"] }".to_string(),
    ];
    if !core_dep_line.is_empty() {
        dep_entries.push(core_dep_line.clone());
    }
    for line in &extra_dep_lines {
        dep_entries.push(line.clone());
    }
    crate::scaffold::sort_dependency_lines(&mut dep_entries);
    let dep_block = dep_entries.join("\n");
    let repository_line = meta
        .configured_repository
        .as_deref()
        .map(|repository| format!("\nrepository = \"{repository}\""))
        .unwrap_or_default();
    let lints_section = crate::scaffold::cargo_lints_section(config);

    let content = format!(
        r#"{pkg_header}{repository_line}

# `serde`, `serde_json`, `ahash`, and `tokio` are emitted unconditionally above so the
# manifest is stable across regens (and so the C FFI codegen can pull them in
# when an async / Result-typed function appears in the API surface), but for
# umbrella crates with no async fns and no JSON-marshalled return types they
# are genuinely unused. The conditional `async-trait` / `futures-util` deps
# are similarly flagged when the umbrella has trait-bridge / streaming adapters
# configured but no actual async-trait / async-stream callsite in the generated
# FFI shim.
[package.metadata.cargo-machete]
ignored = [{machete_ignored_str}]

[lib]
crate-type = ["cdylib", "staticlib", "rlib"]

[features]
default = [{core_features_default_list}]
{core_features_passthrough_block}

[dependencies]
{dep_block}
{target_blocks_section}
[build-dependencies]
cbindgen = "{cbindgen}"

[dev-dependencies]
tempfile = "{tempfile}"
{lints_section}"#,
        pkg_header = pkg_header,
        repository_line = repository_line,
        lints_section = lints_section,
        dep_block = dep_block,
        target_blocks_section = target_blocks_section,
        cbindgen = tv::cargo::CBINDGEN,
        tempfile = tv::cargo::TEMPFILE,
        machete_ignored_str = machete_ignored_str,
        core_features_default_list = core_features_default_list,
        core_features_passthrough_block = core_features_passthrough_block,
    );

    let ffi_name = format!("{core_crate_dir}-ffi");
    let header_name = config.ffi_header_name();
    let lib_name = config.ffi_lib_name();
    let ffi_name_under = ffi_name.replace('-', "_");

    let cmake_content = format!(
        r#"# {ffi_name} CMake config-mode find module
#
# Defines the imported target:
#   {ffi_name}::{ffi_name}
#
# Usage:
#   find_package({ffi_name} REQUIRED)
#   target_link_libraries(myapp PRIVATE {ffi_name}::{ffi_name})

if(TARGET {ffi_name}::{ffi_name})
  return()
endif()

get_filename_component(_FFI_CMAKE_DIR "${{CMAKE_CURRENT_LIST_FILE}}" PATH)
get_filename_component(_FFI_PREFIX "${{_FFI_CMAKE_DIR}}/.." ABSOLUTE)

find_library(_FFI_LIBRARY
  NAMES {lib_name} lib{lib_name}
  PATHS "${{_FFI_PREFIX}}/lib"
  NO_DEFAULT_PATH
)
if(NOT _FFI_LIBRARY)
  find_library(_FFI_LIBRARY NAMES {lib_name} lib{lib_name})
endif()

find_path(_FFI_INCLUDE_DIR
  NAMES {header_name}
  PATHS "${{_FFI_PREFIX}}/include"
  NO_DEFAULT_PATH
)
if(NOT _FFI_INCLUDE_DIR)
  find_path(_FFI_INCLUDE_DIR NAMES {header_name})
endif()

include(FindPackageHandleStandardArgs)
find_package_handle_standard_args({ffi_name}
  REQUIRED_VARS _FFI_LIBRARY _FFI_INCLUDE_DIR
)

if({ffi_name_under}_FOUND)
  set(_FFI_LIB_TYPE UNKNOWN)
  if(_FFI_LIBRARY MATCHES "\\.(dylib|so)$" OR _FFI_LIBRARY MATCHES "\\.so\\.")
    set(_FFI_LIB_TYPE SHARED)
  elseif(_FFI_LIBRARY MATCHES "\\.dll$")
    set(_FFI_LIB_TYPE SHARED)
  elseif(_FFI_LIBRARY MATCHES "\\.(a|lib)$")
    set(_FFI_LIB_TYPE STATIC)
  endif()

  add_library({ffi_name}::{ffi_name} ${{_FFI_LIB_TYPE}} IMPORTED)
  set_target_properties({ffi_name}::{ffi_name} PROPERTIES
    IMPORTED_LOCATION "${{_FFI_LIBRARY}}"
    INTERFACE_INCLUDE_DIRECTORIES "${{_FFI_INCLUDE_DIR}}"
  )

  if(WIN32 AND _FFI_LIB_TYPE STREQUAL "SHARED")
    find_file(_FFI_DLL
      NAMES {lib_name}.dll lib{lib_name}.dll
      PATHS "${{_FFI_PREFIX}}/bin" "${{_FFI_PREFIX}}/lib"
      NO_DEFAULT_PATH
    )
    if(_FFI_DLL)
      set_target_properties({ffi_name}::{ffi_name} PROPERTIES
        IMPORTED_LOCATION "${{_FFI_DLL}}"
        IMPORTED_IMPLIB "${{_FFI_LIBRARY}}"
      )
    endif()
    unset(_FFI_DLL CACHE)
  endif()

  if(APPLE)
    set_property(TARGET {ffi_name}::{ffi_name} APPEND PROPERTY
      INTERFACE_LINK_LIBRARIES "-framework CoreFoundation" "-framework Security" pthread)
  elseif(UNIX)
    set_property(TARGET {ffi_name}::{ffi_name} APPEND PROPERTY
      INTERFACE_LINK_LIBRARIES pthread dl m)
  elseif(WIN32)
    set_property(TARGET {ffi_name}::{ffi_name} APPEND PROPERTY
      INTERFACE_LINK_LIBRARIES ws2_32 userenv bcrypt)
  endif()

  unset(_FFI_LIB_TYPE)
endif()

mark_as_advanced(_FFI_LIBRARY _FFI_INCLUDE_DIR)
unset(_FFI_CMAKE_DIR)
unset(_FFI_PREFIX)
"#,
        ffi_name = ffi_name,
        ffi_name_under = ffi_name_under,
        lib_name = lib_name,
        header_name = header_name,
    );

    Ok(vec![
        GeneratedFile {
            path: PathBuf::from(format!("crates/{}-ffi/Cargo.toml", core_crate_dir)),
            content,
            generated_header: true,
        },
        GeneratedFile {
            path: PathBuf::from(format!(
                "crates/{}-ffi/cmake/{}-ffi-config.cmake",
                core_crate_dir, core_crate_dir
            )),
            content: cmake_content,
            generated_header: true,
        },
    ])
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_render_core_dep_includes_version_in_default_line() {
        let (core_dep_line, target_blocks) =
            render_core_dep("my-lib", "../my-lib-core", "1.2.3", ", features = [\"foo\"]", &[]);

        assert!(!core_dep_line.is_empty(), "Expected non-empty core_dep_line");
        assert!(
            core_dep_line.contains("version = \"1.2.3\""),
            "Expected 'version = \"1.2.3\"' in core_dep_line: {}",
            core_dep_line
        );
        assert!(
            core_dep_line.contains("path = \"../my-lib-core\""),
            "Expected path reference in core_dep_line: {}",
            core_dep_line
        );
        assert!(target_blocks.is_empty(), "Expected empty target_blocks");
    }

    #[test]
    fn test_render_core_dep_includes_version_in_target_blocks() {
        let overrides = vec![FfiTargetDepOverride {
            cfg: "target_os = \"windows\"".to_string(),
            features: vec!["windows-feature".to_string()],
            default_features: true,
        }];
        let (core_dep_line, target_blocks) = render_core_dep("my-lib", "../my-lib-core", "2.0.0", "", &overrides);

        assert!(
            core_dep_line.is_empty(),
            "Expected empty core_dep_line when overrides present"
        );
        assert!(!target_blocks.is_empty(), "Expected non-empty target_blocks");
        assert!(
            target_blocks.contains("version = \"2.0.0\""),
            "Expected 'version = \"2.0.0\"' in target_blocks: {}",
            target_blocks
        );
        assert!(
            target_blocks.contains("path = \"../my-lib-core\""),
            "Expected path reference in target_blocks: {}",
            target_blocks
        );
        assert!(
            !target_blocks.contains("default-features"),
            "default_features: true must not emit a default-features key: {}",
            target_blocks
        );
    }

    /// Regression test for the dropped `default_features` config key on
    /// `[crates.ffi].target_dep_overrides` (see `FfiTargetDepOverride::default_features`):
    /// an override with `default_features = false` must emit `default-features = false`
    /// in its target block so the FFI crate can drop the core dep's own default feature set
    /// on a target that cannot support it.
    #[test]
    fn test_render_core_dep_emits_default_features_false_when_override_disables_it() {
        let overrides = vec![FfiTargetDepOverride {
            cfg: "target_os = \"windows\"".to_string(),
            features: vec!["windows-target".to_string()],
            default_features: false,
        }];
        let (core_dep_line, target_blocks) = render_core_dep("my-lib", "../my-lib-core", "2.0.0", "", &overrides);

        assert!(
            core_dep_line.is_empty(),
            "Expected empty core_dep_line when overrides present"
        );
        assert!(
            target_blocks.contains("default-features = false"),
            "default_features: false must emit default-features = false: {}",
            target_blocks
        );
        assert!(
            target_blocks.contains(r#"features = ["windows-target"]"#),
            "override block must still emit its feature list: {}",
            target_blocks
        );
    }

    /// Regression: the FFI scaffold emitted `repository = "…"\n` (trailing LF)
    /// into a format string that already had a separating blank line, producing
    /// two consecutive blank lines between `repository = "…"` and the
    /// `[package.metadata.cargo-machete]` comment block.  cargo-sort removes
    /// one of them, causing prek to oscillate on every run.
    #[test]
    fn ffi_cargo_toml_repository_line_has_no_double_blank_line() {
        let repository = "https://github.com/example/my-lib";
        let repository_line = format!("\nrepository = \"{repository}\"");
        let pkg_header = "[package]\nname = \"my-lib-ffi\"\nversion = \"1.0.0\"";

        let content = format!("{pkg_header}{repository_line}\n\n# comment\n");

        assert!(
            !content.contains("repository = \"https://github.com/example/my-lib\"\n\n\n"),
            "double blank line found after repository — cargo-sort will remove one, causing prek oscillation:\n{content}"
        );
        assert!(
            content.contains("repository = \"https://github.com/example/my-lib\"\n\n# comment"),
            "expected exactly one blank line between repository and comment:\n{content}"
        );
    }

    fn resolve_config(toml_text: &str) -> ResolvedCrateConfig {
        let cfg: crate::core::config::NewAlefConfig = toml::from_str(toml_text).expect("valid config");
        cfg.resolve().expect("resolve").remove(0)
    }

    /// A capsule type that declares `package`/`package_version` must add that
    /// crate as a direct FFI dependency so the capsule shim can name the pointee
    /// type (the core crate's transitive dep is not in scope for generated code).
    #[test]
    fn ffi_cargo_toml_injects_capsule_package_dependency() {
        let config = resolve_config(
            r#"
[workspace]
languages = ["ffi"]
[[crates]]
name = "my-lib"
sources = []
[crates.ffi.capsule_types.Language]
into_raw_type = "tree_sitter::ffi::TSLanguage"
c_return_type = "TSLanguage"
package = "tree-sitter"
package_version = "0.26"
"#,
        );
        let api = crate::core::ir::ApiSurface::default();
        let files = scaffold_ffi(&api, &config).expect("scaffold");
        let cargo = files
            .iter()
            .find(|f| f.path.ends_with("Cargo.toml"))
            .expect("ffi Cargo.toml emitted");
        assert!(
            cargo.content.contains("tree-sitter = \"0.26\""),
            "capsule package dep must be injected into FFI Cargo.toml, got:\n{}",
            cargo.content
        );
    }

    /// A capsule type without `package` must not inject any dependency.
    #[test]
    fn ffi_cargo_toml_omits_capsule_dep_when_package_unset() {
        let config = resolve_config(
            r#"
[workspace]
languages = ["ffi"]
[[crates]]
name = "my-lib"
sources = []
[crates.ffi.capsule_types.Language]
into_raw_type = "tree_sitter::ffi::TSLanguage"
c_return_type = "TSLanguage"
"#,
        );
        let api = crate::core::ir::ApiSurface::default();
        let files = scaffold_ffi(&api, &config).expect("scaffold");
        let cargo = files
            .iter()
            .find(|f| f.path.ends_with("Cargo.toml"))
            .expect("ffi Cargo.toml emitted");
        assert!(
            !cargo.content.contains("tree-sitter ="),
            "no capsule dep should be injected when package is unset, got:\n{}",
            cargo.content
        );
    }

    fn features_section(cargo: &str) -> &str {
        let start = cargo.find("[features]").expect("features table emitted");
        let rest = &cargo[start..];
        rest.find("\n[").map(|end| &rest[..end]).unwrap_or(rest)
    }

    fn minimal_config() -> ResolvedCrateConfig {
        resolve_config(
            r#"
[workspace]
languages = ["ffi"]
[[crates]]
name = "my-lib"
sources = []
"#,
        )
    }

    /// A `#[cfg(feature = "X")]` on an emitted type must make the FFI crate declare `X`.
    /// Cargo features are per-crate, so an undeclared gate can never be satisfied and the
    /// export is silently dropped from the cdylib while cbindgen still declares it.
    #[test]
    fn ffi_cargo_toml_declares_features_named_by_emitted_type_cfg_gates() {
        let api = ApiSurface {
            crate_name: "my-lib".to_string(),
            types: vec![crate::core::ir::TypeDef {
                name: "BudgetConfig".to_string(),
                rust_path: "my_lib::BudgetConfig".to_string(),
                cfg: Some(r#"feature = "tower""#.to_string()),
                ..Default::default()
            }],
            ..Default::default()
        };
        let files = scaffold_ffi(&api, &minimal_config()).expect("scaffold");
        let cargo = &files
            .iter()
            .find(|f| f.path.ends_with("Cargo.toml"))
            .expect("ffi Cargo.toml emitted")
            .content;
        let features = features_section(cargo);
        assert!(
            features.contains(r#"tower = ["my-lib/tower"]"#),
            "gate feature must be declared as a passthrough, got:\n{features}"
        );
        assert!(
            features.contains("default = [") && features.contains("\"tower\""),
            "gate feature must default ON so the gated export survives, got:\n{features}"
        );
    }

    /// Same invariant for a gate on a function rather than a type -- the regression that
    /// deleted `count_tokens`-style exports came in through the function path.
    #[test]
    fn ffi_cargo_toml_declares_features_named_by_emitted_function_cfg_gates() {
        let api = ApiSurface {
            crate_name: "my-lib".to_string(),
            functions: vec![crate::core::ir::FunctionDef {
                name: "count_tokens".to_string(),
                cfg: Some(r#"feature = "tokenizer""#.to_string()),
                ..Default::default()
            }],
            ..Default::default()
        };
        let files = scaffold_ffi(&api, &minimal_config()).expect("scaffold");
        let cargo = &files
            .iter()
            .find(|f| f.path.ends_with("Cargo.toml"))
            .expect("ffi Cargo.toml emitted")
            .content;
        let features = features_section(cargo);
        assert!(
            features.contains(r#"tokenizer = ["my-lib/tokenizer"]"#),
            "function gate feature must be declared as a passthrough, got:\n{features}"
        );
    }

    /// `extra_features` is documented as declare-but-do-not-enable, for mutually-exclusive
    /// alternatives such as a `wasm-http` backend. Discovering the same name in an emitted
    /// gate must not promote it into `default`.
    #[test]
    fn ffi_cargo_toml_keeps_extra_features_out_of_default_even_when_gated() {
        let config = resolve_config(
            r#"
[workspace]
languages = ["ffi"]
[[crates]]
name = "my-lib"
sources = []
[crates.ffi]
extra_features = ["wasm-http"]
"#,
        );
        let api = ApiSurface {
            crate_name: "my-lib".to_string(),
            functions: vec![crate::core::ir::FunctionDef {
                name: "fetch".to_string(),
                cfg: Some(r#"feature = "wasm-http""#.to_string()),
                ..Default::default()
            }],
            ..Default::default()
        };
        let files = scaffold_ffi(&api, &config).expect("scaffold");
        let cargo = &files
            .iter()
            .find(|f| f.path.ends_with("Cargo.toml"))
            .expect("ffi Cargo.toml emitted")
            .content;
        let features = features_section(cargo);
        assert!(
            features.contains(r#"wasm-http = ["my-lib/wasm-http"]"#),
            "extra_features entry must still be declared, got:\n{features}"
        );
        let default_line = features
            .lines()
            .find(|line| line.starts_with("default = ["))
            .expect("default line emitted");
        assert!(
            !default_line.contains("wasm-http"),
            "extra_features must stay opt-in, got: {default_line}"
        );
    }

    /// Parity invariant, stated without reference to any consumer: every feature named by a
    /// `#[cfg(feature = ...)]` in the emitted surface appears in this crate's `[features]`.
    #[test]
    fn ffi_cargo_toml_declares_every_feature_named_by_any_emitted_gate() {
        let api = ApiSurface {
            crate_name: "my-lib".to_string(),
            types: vec![crate::core::ir::TypeDef {
                name: "CacheConfig".to_string(),
                rust_path: "my_lib::CacheConfig".to_string(),
                cfg: Some(r#"any(feature = "tower", feature = "opendal-cache")"#.to_string()),
                ..Default::default()
            }],
            functions: vec![crate::core::ir::FunctionDef {
                name: "record_cost_usd".to_string(),
                cfg: Some(r#"feature = "metrics""#.to_string()),
                ..Default::default()
            }],
            ..Default::default()
        };
        let files = scaffold_ffi(&api, &minimal_config()).expect("scaffold");
        let cargo = &files
            .iter()
            .find(|f| f.path.ends_with("Cargo.toml"))
            .expect("ffi Cargo.toml emitted")
            .content;
        let features = features_section(cargo);
        for name in ["tower", "opendal-cache", "metrics"] {
            assert!(
                features.contains(&format!(r#"{name} = ["my-lib/{name}"]"#)),
                "feature `{name}` is gated on but never declared, got:\n{features}"
            );
        }
    }

    /// `[crates.cargo_lints]` must round-trip into the emitted FFI `Cargo.toml` as a
    /// `[lints.rust]` / `[lints.clippy]` block, and produce valid TOML.
    #[test]
    fn ffi_cargo_toml_emits_configured_cargo_lints() {
        let config = resolve_config(
            r#"
[workspace]
languages = ["ffi"]
[[crates]]
name = "my-lib"
sources = []

[crates.cargo_lints.rust]
unused_must_use = "deny"

[crates.cargo_lints.clippy]
print_stdout = "deny"
"#,
        );
        let api = crate::core::ir::ApiSurface::default();
        let files = scaffold_ffi(&api, &config).expect("scaffold");
        let cargo = &files
            .iter()
            .find(|f| f.path.ends_with("Cargo.toml"))
            .expect("ffi Cargo.toml emitted")
            .content;
        // Exactly one blank line must precede the spliced `[lints.rust]` block. This is asserted
        // without naming the table before it: cargo-sort's canonical order puts every lints table
        // last, so pinning the preceding table would re-break this test the next time a table is
        // added at the tail. The check deliberately does not look at the whole file, because the
        // `[features]` block's `{core_features_passthrough_block}` slot is independently blank
        // whenever no cfg-gated feature is emitted (true for this test's empty API surface), which
        // pre-existingly leaves a double blank line before `[dependencies]` regardless of
        // cargo_lints. ~keep
        assert!(
            cargo.contains("\n\n[lints.rust]\nunused_must_use = \"deny\""),
            "expected a blank line before [lints.rust], got:\n{cargo}"
        );
        assert!(
            !cargo.contains("\n\n\n[lints.rust]"),
            "expected exactly one blank line before [lints.rust], not more, got:\n{cargo}"
        );
        assert!(
            cargo.contains(
                "[lints.rust]\nunused_must_use = \"deny\"\n\n\
                 # This crate deliberately does not use `[lints]` / `workspace = true`"
            ),
            "expected exactly one blank line between [lints.rust] and the [lints.clippy] rationale \
             comment, got:\n{cargo}"
        );
        assert!(
            cargo.contains(
                "can actually satisfy. ~keep\n\
                 [lints.clippy]\ndbg_macro = \"deny\"\nprint_stderr = \"deny\"\nprint_stdout = \"deny\""
            ),
            "expected the rationale comment to attach directly to [lints.clippy] (no blank line), and the \
             configured print_stdout to merge with the builtin dbg_macro/print_stderr defaults, got:\n{cargo}"
        );
        // `[lints.clippy]` is last under cargo-sort's canonical table order, so there is no
        // following section to be separated from -- this previously pinned the `# `serde`` comment
        // that used to follow it. What still matters is that the file ends cleanly: the clippy
        // block is the final table and the tail does not accumulate blank lines. A global
        // "no triple newline" check would be wrong here, because the `[features]` block leaves a
        // documented double blank before `[dependencies]` on an empty API surface. ~keep
        assert!(
            cargo.trim_end().ends_with("print_stdout = \"deny\""),
            "expected [lints.clippy] to be the final table, got:\n{cargo}"
        );
        assert!(
            cargo.len() - cargo.trim_end_matches('\n').len() <= 2,
            "expected at most one trailing blank line after [lints.clippy], got:\n{cargo}"
        );
        toml::from_str::<toml::Value>(cargo).expect("generated Cargo.toml with cargo_lints must be valid TOML");
    }

    /// Absence of `[crates.cargo_lints]` must still emit the built-in `[lints.clippy]` deny
    /// block (`dbg_macro` / `print_stderr` / `print_stdout`) — this is the regression cover
    /// for the coverage-loss bug where four generated binding crates lost that exact block
    /// on a full regen because it lived only as hand-added content the generator didn't know
    /// to reproduce. No `[lints.rust]` table is emitted, since nothing configures it.
    #[test]
    fn ffi_cargo_toml_emits_builtin_clippy_denies_when_cargo_lints_unset() {
        let files = scaffold_ffi(&crate::core::ir::ApiSurface::default(), &minimal_config()).expect("scaffold");
        let cargo = &files
            .iter()
            .find(|f| f.path.ends_with("Cargo.toml"))
            .expect("ffi Cargo.toml emitted")
            .content;
        assert!(
            !cargo.contains("[lints.rust]"),
            "no [lints.rust] table should be emitted when cargo_lints.rust is unset, got:\n{cargo}"
        );
        assert!(
            cargo.contains("[lints.clippy]\ndbg_macro = \"deny\"\nprint_stderr = \"deny\"\nprint_stdout = \"deny\""),
            "the builtin [lints.clippy] deny block must survive even when cargo_lints is unset, got:\n{cargo}"
        );
        toml::from_str::<toml::Value>(cargo).expect("generated Cargo.toml must be valid TOML");
    }

    #[test]
    fn ffi_manifest_reconciliation_adds_runtime_dependencies_and_cfg_features() {
        let api = ApiSurface {
            crate_name: "my-lib".to_string(),
            types: vec![crate::core::ir::TypeDef {
                name: "BudgetConfig".to_string(),
                rust_path: "my_lib::BudgetConfig".to_string(),
                cfg: Some(r#"feature = "tower""#.to_string()),
                ..Default::default()
            }],
            functions: vec![crate::core::ir::FunctionDef {
                name: "count_tokens".to_string(),
                cfg: Some(r#"feature = "tokenizer""#.to_string()),
                ..Default::default()
            }],
            ..Default::default()
        };
        let files = scaffold_ffi(&api, &minimal_config()).expect("scaffold");
        let directory = tempfile::tempdir().expect("temporary repository");
        let manifest_path = directory.path().join("crates/my-lib-ffi/Cargo.toml");
        std::fs::create_dir_all(manifest_path.parent().expect("manifest parent")).expect("create manifest parent");
        std::fs::write(
            &manifest_path,
            "# This file is auto-generated by alef — DO NOT EDIT.\n# alef:hash:old\n\
             [features]\ndefault = [\"full\"]\nfull = [\"my-lib/full\"]\n\
             [dependencies]\nserde_json = \"1\"\n",
        )
        .expect("write stale generated manifest");

        crate::cli::pipeline::reconcile_managed_scaffold_manifests(&files, directory.path())
            .expect("reconcile generated FFI manifest");
        let reconciled = std::fs::read_to_string(manifest_path).expect("read reconciled manifest");

        assert!(reconciled.contains("serde = \"1\""), "{reconciled}");
        assert!(reconciled.contains(r#"tower = ["my-lib/tower"]"#), "{reconciled}");
        assert!(
            reconciled.contains(r#"tokenizer = ["my-lib/tokenizer"]"#),
            "{reconciled}"
        );
        let parsed: toml::Value = toml::from_str(&reconciled).expect("valid reconciled TOML");
        let defaults = parsed["features"]["default"].as_array().expect("default feature array");
        for feature in ["tower", "tokenizer"] {
            assert!(
                defaults.iter().any(|value| value.as_str() == Some(feature)),
                "{reconciled}"
            );
        }
    }

    /// Regression cover for the reported coverage-loss bug: a consumer's on-disk `-ffi`
    /// manifest carries a hand-added `[lints.clippy]` deny block (with no
    /// `[crates.cargo_lints]` entry in `alef.toml` describing it — exactly the
    /// tree-sitter-language-pack scenario) and a full reconciliation pass must still leave
    /// that block in place afterward, because the builtin now regenerates it itself rather
    /// than relying on the consumer's hand-added copy surviving untouched.
    #[test]
    fn ffi_manifest_reconciliation_keeps_the_clippy_deny_block_with_no_cargo_lints_configured() {
        let files = scaffold_ffi(&crate::core::ir::ApiSurface::default(), &minimal_config()).expect("scaffold");
        let directory = tempfile::tempdir().expect("temporary repository");
        let manifest_path = directory.path().join("crates/my-lib-ffi/Cargo.toml");
        std::fs::create_dir_all(manifest_path.parent().expect("manifest parent")).expect("create manifest parent");
        std::fs::write(
            &manifest_path,
            "# This file is auto-generated by alef — DO NOT EDIT.\n# alef:hash:old\n\
             [lints.clippy]\nprint_stdout = \"deny\"\nprint_stderr = \"deny\"\ndbg_macro = \"deny\"\n",
        )
        .expect("write stale generated manifest carrying a hand-added clippy deny block");

        crate::cli::pipeline::reconcile_managed_scaffold_manifests(&files, directory.path())
            .expect("reconcile generated FFI manifest");
        let reconciled = std::fs::read_to_string(manifest_path).expect("read reconciled manifest");

        assert!(
            reconciled
                .contains("[lints.clippy]\ndbg_macro = \"deny\"\nprint_stderr = \"deny\"\nprint_stdout = \"deny\""),
            "the clippy deny block must survive reconciliation even though alef.toml never \
             configured [crates.cargo_lints]:\n{reconciled}"
        );
        toml::from_str::<toml::Value>(&reconciled).expect("valid reconciled TOML");
    }

    /// Regression: the `~keep`-worthy rationale explaining why this crate does not use
    /// `[lints]\nworkspace = true` (it would drag in `[workspace.lints.rust]
    /// unsafe_code = "deny"`, which a C-ABI crate cannot satisfy) must appear directly
    /// above `[lints.clippy]` on every regeneration -- including reconciliation against
    /// an on-disk manifest that never had it (a stale manifest generated before this
    /// comment existed, or hand-edited to remove it). The comment is emitted by alef
    /// itself rather than left for a consumer to add, since these are `generated_header:
    /// true` manifests rewritten in full and no `~keep` marker protects hand-added
    /// content against that.
    #[test]
    fn ffi_manifest_reconciliation_restores_the_clippy_workspace_lints_rationale_comment() {
        let files = scaffold_ffi(&crate::core::ir::ApiSurface::default(), &minimal_config()).expect("scaffold");
        let directory = tempfile::tempdir().expect("temporary repository");
        let manifest_path = directory.path().join("crates/my-lib-ffi/Cargo.toml");
        std::fs::create_dir_all(manifest_path.parent().expect("manifest parent")).expect("create manifest parent");
        std::fs::write(
            &manifest_path,
            "# This file is auto-generated by alef — DO NOT EDIT.\n# alef:hash:old\n\
             [lints.clippy]\nprint_stdout = \"deny\"\nprint_stderr = \"deny\"\ndbg_macro = \"deny\"\n",
        )
        .expect("write stale generated manifest with no rationale comment");

        crate::cli::pipeline::reconcile_managed_scaffold_manifests(&files, directory.path())
            .expect("reconcile generated FFI manifest");
        let reconciled = std::fs::read_to_string(manifest_path).expect("read reconciled manifest");

        assert!(
            reconciled.contains("# This crate deliberately does not use `[lints]` / `workspace = true`"),
            "the [lints.clippy] rationale comment must be (re)emitted on regeneration, not just the \
             block itself:\n{reconciled}"
        );
        assert!(
            reconciled.contains("can actually satisfy. ~keep\n[lints.clippy]"),
            "the rationale comment must attach directly above [lints.clippy] with no blank line, \
             got:\n{reconciled}"
        );
        toml::from_str::<toml::Value>(&reconciled).expect("valid reconciled TOML");
    }
}