alef 0.62.1

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
//! Shared cfg-expression utilities for language binding backends.
//!
//! Provides recursive parsing of Rust `#[cfg(...)]` condition strings and
//! full-surface feature collection so every backend can forward core-crate
//! features into its own Cargo.toml `[features]` table — preventing
//! `unexpected cfg condition value` errors when items are emitted behind
//! `#[cfg(feature = "X")]` guards.

use crate::core::config::{Language, ResolvedCrateConfig};
use crate::core::ir::ApiSurface;
use std::collections::BTreeSet;
use std::path::Path;

/// Extract every `feature = "X"` name referenced by a cfg expression.
///
/// Recursively descends through `any(...)`, `all(...)`, and `not(...)` so that
/// callers can declare a passthrough Cargo feature for every feature the
/// generated source references. Without this, items emitted behind
/// `#[cfg(feature = "X")]` produce
/// `error: unexpected cfg condition value: X` when the binding crate's
/// `Cargo.toml` only declares an unrelated feature list.
///
/// The IR encodes cfgs via `proc_macro2::TokenStream::to_string()`, which
/// inserts whitespace between tokens (e.g. `any (feature = "a" , ...)`); the
/// evaluator normalises that before parsing.
///
/// Unknown cfg patterns (`target_arch`, `target_os`, ...) yield no features
/// — those are recognised by Cargo directly and don't need passthroughs.
pub fn collect_cfg_feature_names(cfg_str: &str, out: &mut BTreeSet<String>) {
    let normalized = cfg_str.trim().replace(" (", "(");
    let cfg_str = normalized.as_str();

    if let Some(feature) = cfg_str.strip_prefix("feature = \"").and_then(|s| s.strip_suffix('"')) {
        out.insert(feature.to_string());
        return;
    }
    if let Some(inner) = cfg_str
        .strip_prefix("any(")
        .and_then(|s| s.strip_suffix(')'))
        .or_else(|| cfg_str.strip_prefix("all(").and_then(|s| s.strip_suffix(')')))
    {
        for cond in parse_cfg_list(inner) {
            collect_cfg_feature_names(&cond, out);
        }
        return;
    }
    if let Some(inner) = cfg_str.strip_prefix("not(").and_then(|s| s.strip_suffix(')')) {
        collect_cfg_feature_names(inner.trim(), out);
    }
}

/// Walk the full [`ApiSurface`] and return the set of feature names referenced
/// by any cfg attribute on a type, field, method, enum variant, service, or
/// top-level function.
///
/// Methods count: a Rust-emitting backend re-emits a gated method's `#[cfg(feature = "X")]`
/// verbatim into its binding crate, so `X` must exist in that crate's `[features]` table or
/// the build fails with `unexpected cfg condition value: X`. ~keep
///
/// Services count for the same reason: `ServiceDef` carries its own `cfg`, and its
/// `constructor`/`configurators` are `MethodDef`s that carry theirs — see
/// `ApiSurface::with_cfg_filtered_deep`, which drops a cfg-gated service the same way it drops a
/// cfg-gated type/enum/function/method, and `backends::ffi::gen_bindings::helpers::cbindgen_feature_defines`,
/// which reads `ServiceDef::cfg` for the FFI header's `#if` guards. A backend that re-emits a
/// gated service's constructor or configurator gate into its own binding crate needs `X` declared
/// here for the same reason a gated method does. ~keep
///
/// `errors[].methods[].cfg` is deliberately NOT walked, unlike in
/// `backends::ffi::gen_bindings::helpers::cbindgen_feature_defines`: no backend re-emits an error
/// method's gate. Every error-introspection wrapper (`codegen::error_gen::gen_ffi_error_methods`
/// and its per-language siblings) is emitted ungated, and `ApiSurface::with_cfg_filtered_deep`
/// drops the method instead when the feature is off, so no crate needs the feature declared. Teach
/// one of those emitters to re-emit `MethodDef::rust_cfg_attribute` and this walk must grow the
/// position with it. ~keep
///
/// The position-by-position coverage of this walk and of `cbindgen_feature_defines` — including
/// the `is_host` asymmetry, which is intentional and must not be collapsed — is pinned by
/// `backends::ffi::gen_bindings::tests::feature_defines`. ~keep
///
/// The set is sorted (via `BTreeSet`) so the resulting Cargo.toml is stable
/// across regenerations.
pub fn collect_cfg_features(api: &ApiSurface) -> BTreeSet<String> {
    let mut out = BTreeSet::new();
    // Forwarding features (`<feat> = ["<core>/<feat>"]`) are only valid for the HOST crate's own ~keep
    // features. Types merged from `[[crates.source_crates]]` carry the foreign crate's cfg gates ~keep
    // (e.g. a variant gated on a feature only the source crate defines); forwarding those to the ~keep
    // core dep references a feature the core crate does not define and breaks `cargo` resolution. ~keep
    // Skip any type/enum whose rust_path is not owned by the host crate. ~keep
    let host_crate = api.crate_name.replace('-', "_");
    let is_host = |rust_path: &str| -> bool {
        // Unknown host (empty crate name) or an unqualified path → keep the old, permissive ~keep
        // behavior; only skip a type whose leading path segment names a *different* crate. ~keep
        if host_crate.is_empty() {
            return true;
        }
        match rust_path.split("::").next() {
            Some(first) if !first.is_empty() => first == host_crate,
            _ => true,
        }
    };
    for typ in &api.types {
        if !is_host(&typ.rust_path) {
            continue;
        }
        if let Some(cfg) = &typ.cfg {
            collect_cfg_feature_names(cfg, &mut out);
        }
        for field in &typ.fields {
            if let Some(cfg) = &field.cfg {
                collect_cfg_feature_names(cfg, &mut out);
            }
        }
        for method in &typ.methods {
            if let Some(cfg) = &method.cfg {
                collect_cfg_feature_names(cfg, &mut out);
            }
        }
    }
    for enum_def in &api.enums {
        if !is_host(&enum_def.rust_path) {
            continue;
        }
        if let Some(cfg) = &enum_def.cfg {
            collect_cfg_feature_names(cfg, &mut out);
        }
        for variant in &enum_def.variants {
            if let Some(cfg) = &variant.cfg {
                collect_cfg_feature_names(cfg, &mut out);
            }
        }
        for method in &enum_def.methods {
            if let Some(cfg) = &method.cfg {
                collect_cfg_feature_names(cfg, &mut out);
            }
        }
    }
    for func in &api.functions {
        if let Some(cfg) = &func.cfg {
            collect_cfg_feature_names(cfg, &mut out);
        }
    }
    for service in &api.services {
        if !is_host(&service.rust_path) {
            continue;
        }
        if let Some(cfg) = &service.cfg {
            collect_cfg_feature_names(cfg, &mut out);
        }
        if let Some(cfg) = &service.constructor.cfg {
            collect_cfg_feature_names(cfg, &mut out);
        }
        for configurator in &service.configurators {
            if let Some(cfg) = &configurator.cfg {
                collect_cfg_feature_names(cfg, &mut out);
            }
        }
    }
    out
}

/// Feature names [`collect_cfg_features`] finds referenced in `api` that `declared` does not
/// contain.
///
/// A Rust-emitting backend (Magnus/Ruby, Rustler/Elixir) copies a source item's
/// `#[cfg(feature = "X")]` verbatim into the binding crate; that gate then resolves against the
/// *binding* crate's own `[features]` table, not the core crate's. A name this returns means the
/// binding crate's manifest does not declare `X` as its own passthrough feature, so every
/// definition (and, if the backend also re-emits the gate on a registration statement, every
/// registration) behind that gate silently compiles out of the binding crate even though the core
/// crate has `X` on.
#[must_use]
pub fn undeclared_cfg_features(api: &ApiSurface, declared: &BTreeSet<String>) -> BTreeSet<String> {
    collect_cfg_features(api).difference(declared).cloned().collect()
}

/// Read the `[features]` table keys of the Cargo.toml at `manifest_path`.
///
/// Returns `None` when the file cannot be read or parsed as TOML -- e.g. the binding crate has
/// not been scaffolded yet -- so callers can tell "nothing to check" apart from "checked and the
/// table is empty". Returns `Some(<empty set>)` when the file parses but declares no `[features]`
/// table at all, which is the exact shape a manifest has before its first cfg-gated symbol ever
/// existed.
#[must_use]
pub fn read_declared_cargo_features(manifest_path: &Path) -> Option<BTreeSet<String>> {
    let content = std::fs::read_to_string(manifest_path).ok()?;
    // `toml` 1.x's `FromStr for Value` parses a bare value, not a document; use `from_str` or
    // every real Cargo.toml silently yields `None` here. ~keep
    let manifest = toml::from_str::<toml::Value>(&content).ok()?;
    let features = manifest
        .get("features")
        .and_then(toml::Value::as_table)
        .map(|table| table.keys().cloned().collect())
        .unwrap_or_default();
    Some(features)
}

/// Resolve a `GeneratedFile`-style path (relative to the project root) against
/// `config.workspace_root`, falling back to the process's current directory.
///
/// Mirrors the resolution `scaffold::languages::elixir::get_core_crate_features` already uses to
/// read a sibling crate's manifest back off disk, so a caller that has a `resolve_output_dir()`
/// result (itself already relative to the project root) can locate a file next to it on disk.
#[must_use]
pub fn resolve_against_workspace_root(config: &ResolvedCrateConfig, relative: &Path) -> std::path::PathBuf {
    let root = config
        .workspace_root
        .clone()
        .unwrap_or_else(|| std::env::current_dir().unwrap_or_default());
    root.join(relative)
}

/// Warn when the binding crate's own (already-scaffolded) Cargo.toml at `manifest_path` does not
/// declare every feature the generated Rust source for `language` references via a forwarded
/// `#[cfg(feature = "X")]`.
///
/// `alef scaffold` writes this manifest's `[features]` table once, from
/// [`collect_cfg_features`] evaluated at scaffold time (see `scaffold::languages::ruby` and
/// `scaffold::languages::elixir`); `alef build` does not regenerate it. A cfg-gated item added to
/// the core crate after that scaffold run is therefore referenced by the next `alef build`'s
/// generated source without the manifest ever being told about it -- the exact condition that
/// turned a compiling Ruby extension into one that fails with `E0425: cannot find value`, and an
/// Elixir NIF into one whose function silently returns `:nif_not_loaded` at runtime while the
/// generated docs and type stubs keep advertising it. This is a best-effort, read-only check: a
/// missing or unparseable manifest is treated as "nothing to verify yet", not an error, mirroring
/// `scaffold::languages::elixir::get_core_crate_features`'s same permissive philosophy for the
/// same class of file. ~keep
pub fn warn_on_undeclared_binding_cfg_features(api: &ApiSurface, language: Language, manifest_path: &Path) {
    let Some(declared) = read_declared_cargo_features(manifest_path) else {
        return;
    };
    let missing = undeclared_cfg_features(api, &declared);
    if missing.is_empty() {
        return;
    }
    tracing::warn!(
        language = %language,
        manifest = %manifest_path.display(),
        missing_features = ?missing,
        "generated bindings reference #[cfg(feature = \"...\")] gates this crate's own Cargo.toml \
         does not declare; the affected definitions (and their registrations) will silently \
         compile out of this binding even though the core crate has the feature on -- re-run \
         `alef scaffold` to add the missing features to this crate's [features] table"
    );
}

/// Warn when a single-surface binding language's configured feature set (used to decide which
/// `#[cfg(feature = "...")]`-gated FFI exports get glue via [`ApiSurface::with_cfg_filtered_deep`])
/// diverges from the FFI crate's own configured feature set.
///
/// The FFI cdylib is built once, shared by every language binding (`cargo build -p
/// {ffi_crate}` runs with no `--features` override — see `cli::pipeline::commands::build`), and
/// its `[features] default = [...]` list is populated from `features_for_language(Language::Ffi)`
/// (see `scaffold::languages::ffi`). A binding language's own `with_cfg_filtered_deep` call
/// assumes its configured feature set describes that same compiled artifact; if the two lists
/// differ, the omission-based filter is filtering against the wrong assumption — the generated
/// glue can still reference a symbol the shipped library doesn't export, or omit one it does.
/// alef cannot detect the actual mismatch (it doesn't run `cargo build` here), so this only
/// flags the config-level drift that would cause it, naming the assumption so it is a visible,
/// documented constraint rather than a silent landmine. ~keep
pub fn warn_on_ffi_feature_drift(config: &ResolvedCrateConfig, lang: Language) {
    if lang == Language::Ffi {
        return;
    }
    let lang_features: BTreeSet<&str> = config.features_for_language(lang).iter().map(String::as_str).collect();
    let ffi_features: BTreeSet<&str> = config
        .features_for_language(Language::Ffi)
        .iter()
        .map(String::as_str)
        .collect();
    if lang_features != ffi_features {
        tracing::warn!(
            language = %lang,
            lang_features = ?lang_features,
            ffi_features = ?ffi_features,
            "configured feature set for this binding differs from [crates.ffi]'s; cfg-gated FFI \
             exports are included/omitted based on this binding's own feature list, but the \
             linked native library is built once using the FFI crate's feature list — keep them \
             in sync (or set them explicitly to the same value) or generated glue may reference \
             symbols the shipped library doesn't export"
        );
    }
}

/// A parsed `#[cfg(...)]` predicate, preserving `any`/`all`/`not` structure instead of
/// flattening straight to a name set. Needed by callers that must decide what to *do* about an
/// unsatisfied predicate (e.g. which single feature to request to satisfy an `any(...)`) rather
/// than just enumerate every name it mentions — [`collect_cfg_feature_names`] remains the right
/// tool for the latter.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CfgPredicate {
    /// `feature = "X"`.
    Feature(String),
    /// `all(...)`: every arm must hold.
    All(Vec<CfgPredicate>),
    /// `any(...)`: at least one arm must hold.
    Any(Vec<CfgPredicate>),
    /// `not(...)`.
    Not(Box<CfgPredicate>),
    /// Anything this parser doesn't recognise (`target_arch = "..."`, `windows`, ...).
    Other,
}

/// Parse a `#[cfg(...)]` condition string into a [`CfgPredicate`] tree.
pub fn parse_cfg_predicate(cfg_str: &str) -> CfgPredicate {
    let normalized = cfg_str.trim().replace(" (", "(");
    let cfg_str = normalized.as_str();

    if let Some(feature) = cfg_str.strip_prefix("feature = \"").and_then(|s| s.strip_suffix('"')) {
        return CfgPredicate::Feature(feature.to_string());
    }
    if let Some(inner) = cfg_str.strip_prefix("any(").and_then(|s| s.strip_suffix(')')) {
        return CfgPredicate::Any(parse_cfg_list(inner).iter().map(|c| parse_cfg_predicate(c)).collect());
    }
    if let Some(inner) = cfg_str.strip_prefix("all(").and_then(|s| s.strip_suffix(')')) {
        return CfgPredicate::All(parse_cfg_list(inner).iter().map(|c| parse_cfg_predicate(c)).collect());
    }
    if let Some(inner) = cfg_str.strip_prefix("not(").and_then(|s| s.strip_suffix(')')) {
        return CfgPredicate::Not(Box::new(parse_cfg_predicate(inner.trim())));
    }
    CfgPredicate::Other
}

/// The gate for an item that sits behind both `owner_cfg` and its own `member_cfg`.
///
/// Returns `member_cfg` alone when satisfying it already guarantees `owner_cfg`. A member declared
/// inside `#[cfg(X)] impl T` inherits `X` into its own gate at extraction time, so combining
/// textually yields `all(X, all(X, Y))` — logically right, but it churns the gate line of every
/// affected item on every regen and reads as a generator bug in the diff. ~keep
#[must_use]
pub fn combine_gates(owner_cfg: &str, member_cfg: &str) -> String {
    let (owner, member) = (owner_cfg.trim(), member_cfg.trim());
    if predicate_implies(&parse_cfg_predicate(member), &parse_cfg_predicate(owner)) {
        return member.to_string();
    }
    format!("all({owner}, {member})")
}

/// Whether `predicate` holding guarantees `required` holds.
///
/// Deliberately incomplete: it recognises only conjunction, which is the shape gate inheritance
/// produces. Anything it cannot prove is reported as "does not imply", so the caller keeps both
/// operands — a redundant gate is noise, a dropped one silently compiles the wrong code out.
fn predicate_implies(predicate: &CfgPredicate, required: &CfgPredicate) -> bool {
    // `Other` is the parser's catch-all, so two unrecognised predicates compare equal without
    // being the same condition. Implication must never be inferred from one. ~keep
    if matches!(required, CfgPredicate::Other) {
        return false;
    }
    if predicate == required {
        return true;
    }
    match predicate {
        CfgPredicate::All(arms) => arms.iter().any(|arm| predicate_implies(arm, required)),
        _ => false,
    }
}

fn parse_cfg_list(s: &str) -> Vec<String> {
    let mut result = Vec::new();
    let mut depth = 0usize;
    let mut current = String::new();
    for ch in s.chars() {
        match ch {
            '(' => {
                depth += 1;
                current.push(ch);
            }
            ')' => {
                depth = depth.saturating_sub(1);
                current.push(ch);
            }
            ',' if depth == 0 => {
                let trimmed = current.trim().to_string();
                if !trimmed.is_empty() {
                    result.push(trimmed);
                }
                current.clear();
            }
            _ => current.push(ch),
        }
    }
    let trimmed = current.trim().to_string();
    if !trimmed.is_empty() {
        result.push(trimmed);
    }
    result
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::ir::{ApiSurface, EnumDef, EnumVariant, TypeDef};
    use tracing_test::traced_test;

    #[test]
    fn combine_gates_drops_an_owner_the_member_already_requires() {
        assert_eq!(
            combine_gates(
                r#"feature = "client""#,
                r#"all(feature = "client", feature = "streaming")"#
            ),
            r#"all(feature = "client", feature = "streaming")"#
        );
    }

    #[test]
    fn combine_gates_keeps_both_operands_when_the_member_does_not_imply_the_owner() {
        assert_eq!(
            combine_gates(r#"feature = "client""#, r#"feature = "streaming""#),
            r#"all(feature = "client", feature = "streaming")"#
        );
    }

    #[test]
    fn combine_gates_does_not_collapse_two_predicates_the_parser_cannot_read() {
        // Both sides parse to `CfgPredicate::Other`, which compares equal without being the same
        // condition. Collapsing here would compile the member in on a target the owner excludes.
        assert_eq!(
            combine_gates("target_os = \"macos\"", "target_os = \"linux\""),
            "all(target_os = \"macos\", target_os = \"linux\")"
        );
    }

    #[test]
    fn combine_gates_does_not_treat_a_disjunct_as_implying_the_owner() {
        // `any(a, b)` holding does not guarantee `a`; only conjunction licenses the drop.
        assert_eq!(
            combine_gates(
                r#"feature = "client""#,
                r#"any(feature = "client", feature = "server")"#
            ),
            r#"all(feature = "client", any(feature = "client", feature = "server"))"#
        );
    }

    #[test]
    fn collect_cfg_feature_names_simple_feature() {
        let mut out = BTreeSet::new();
        collect_cfg_feature_names(r#"feature = "pdf""#, &mut out);
        assert_eq!(out, BTreeSet::from(["pdf".to_string()]));
    }

    #[test]
    fn collect_cfg_feature_names_any_compound() {
        let mut out = BTreeSet::new();
        collect_cfg_feature_names(r#"any(feature = "html", feature = "xml")"#, &mut out);
        let want: BTreeSet<String> = ["html", "xml"].into_iter().map(String::from).collect();
        assert_eq!(out, want);
    }

    #[test]
    fn collect_cfg_feature_names_all_compound() {
        let mut out = BTreeSet::new();
        collect_cfg_feature_names(
            r#"all(feature = "layout-types", not(feature = "wasm-target"))"#,
            &mut out,
        );
        let want: BTreeSet<String> = ["layout-types", "wasm-target"].into_iter().map(String::from).collect();
        assert_eq!(out, want);
    }

    #[test]
    fn parse_cfg_predicate_simple_feature() {
        assert_eq!(
            parse_cfg_predicate(r#"feature = "tokenizer""#),
            CfgPredicate::Feature("tokenizer".to_string())
        );
    }

    #[test]
    fn parse_cfg_predicate_any_preserves_arms() {
        assert_eq!(
            parse_cfg_predicate(r#"any(feature = "native-http", feature = "wasm-http")"#),
            CfgPredicate::Any(vec![
                CfgPredicate::Feature("native-http".to_string()),
                CfgPredicate::Feature("wasm-http".to_string()),
            ])
        );
    }

    #[test]
    fn parse_cfg_predicate_all_preserves_arms() {
        assert_eq!(
            parse_cfg_predicate(r#"all(feature = "layout-types", not(feature = "wasm-target"))"#),
            CfgPredicate::All(vec![
                CfgPredicate::Feature("layout-types".to_string()),
                CfgPredicate::Not(Box::new(CfgPredicate::Feature("wasm-target".to_string()))),
            ])
        );
    }

    #[test]
    fn parse_cfg_predicate_not() {
        assert_eq!(
            parse_cfg_predicate(r#"not(feature = "wasm-target")"#),
            CfgPredicate::Not(Box::new(CfgPredicate::Feature("wasm-target".to_string())))
        );
    }

    #[test]
    fn parse_cfg_predicate_unrecognised_is_other() {
        assert_eq!(parse_cfg_predicate(r#"target_arch = "wasm32""#), CfgPredicate::Other);
    }

    #[test]
    fn collect_cfg_feature_names_ignores_non_feature_cfg() {
        let mut out = BTreeSet::new();
        collect_cfg_feature_names(r#"target_arch = "wasm32""#, &mut out);
        assert!(out.is_empty());
    }

    #[test]
    fn collect_cfg_feature_names_whitespace_normalisation() {
        let mut out = BTreeSet::new();
        collect_cfg_feature_names(r#"any (feature = "a" , feature = "b")"#, &mut out);
        let want: BTreeSet<String> = ["a", "b"].into_iter().map(String::from).collect();
        assert_eq!(out, want);
    }

    #[test]
    fn collect_cfg_features_walks_types_enums_functions() {
        let mut out = BTreeSet::new();
        collect_cfg_feature_names(r#"feature = "pdf""#, &mut out);
        collect_cfg_feature_names(r#"any(feature = "html", feature = "xml")"#, &mut out);
        collect_cfg_feature_names(
            r#"all(feature = "layout-types", not(feature = "wasm-target"))"#,
            &mut out,
        );
        collect_cfg_feature_names(r#"target_arch = "wasm32""#, &mut out);
        let want: BTreeSet<String> = ["html", "layout-types", "pdf", "wasm-target", "xml"]
            .into_iter()
            .map(String::from)
            .collect();
        assert_eq!(out, want);
    }

    #[test]
    fn collect_cfg_features_full_surface_walk() {
        let api = ApiSurface {
            types: vec![TypeDef {
                name: "PdfDoc".to_string(),
                rust_path: "mylib::PdfDoc".to_string(),
                cfg: Some(r#"feature = "pdf""#.to_string()),
                ..Default::default()
            }],
            enums: vec![EnumDef {
                name: "ImageOutputFormat".to_string(),
                variants: vec![
                    EnumVariant {
                        name: "Native".to_string(),
                        cfg: None,
                        ..Default::default()
                    },
                    EnumVariant {
                        name: "Heic".to_string(),
                        cfg: Some(r#"feature = "heic""#.to_string()),
                        ..Default::default()
                    },
                ],
                ..Default::default()
            }],
            ..Default::default()
        };
        let features = collect_cfg_features(&api);
        let want: BTreeSet<String> = ["heic", "pdf"].into_iter().map(String::from).collect();
        assert_eq!(features, want);
    }

    #[test]
    fn collect_cfg_features_includes_method_gates() {
        // A Rust-emitting backend re-emits a gated method's `#[cfg(feature = "X")]` into its own
        // crate, so `X` must reach that crate's `[features]` table or the build fails with
        // `unexpected cfg condition value`. ~keep
        use crate::core::ir::MethodDef;

        let api = ApiSurface {
            crate_name: "mylib".to_string(),
            types: vec![TypeDef {
                name: "Client".to_string(),
                rust_path: "mylib::Client".to_string(),
                methods: vec![
                    MethodDef {
                        name: "ping".to_string(),
                        ..Default::default()
                    },
                    MethodDef {
                        name: "stream".to_string(),
                        cfg: Some(r#"feature = "streaming""#.to_string()),
                        ..Default::default()
                    },
                ],
                ..Default::default()
            }],
            enums: vec![EnumDef {
                name: "Format".to_string(),
                rust_path: "mylib::Format".to_string(),
                methods: vec![MethodDef {
                    name: "from_mime".to_string(),
                    cfg: Some(r#"all(feature = "mime", feature = "sniff")"#.to_string()),
                    ..Default::default()
                }],
                ..Default::default()
            }],
            ..Default::default()
        };

        let want: BTreeSet<String> = ["mime", "sniff", "streaming"].into_iter().map(String::from).collect();
        assert_eq!(collect_cfg_features(&api), want);
    }

    /// A Rust-emitting backend that re-emits a gated service's constructor or configurator gate
    /// (mirroring how it already re-emits a gated method's) needs `X` declared in the manifest for
    /// the same `unexpected cfg condition value` reason `collect_cfg_features_includes_method_gates`
    /// covers for methods. `ServiceDef` and its `constructor`/`configurators` `MethodDef`s were
    /// previously not walked at all, unlike `backends::ffi::gen_bindings::helpers::cbindgen_feature_defines`,
    /// which already reads `ServiceDef::cfg` for the FFI header's `#if` guards — this test pins the
    /// shared helper to the same coverage. ~keep
    #[test]
    fn collect_cfg_features_includes_service_and_configurator_gates() {
        use crate::core::ir::{MethodDef, ServiceDef};

        let api = ApiSurface {
            crate_name: "mylib".to_string(),
            services: vec![ServiceDef {
                name: "ClientConfig".to_string(),
                rust_path: "mylib::client::ClientConfig".to_string(),
                constructor: MethodDef {
                    name: "new".to_string(),
                    ..Default::default()
                },
                configurators: vec![
                    MethodDef {
                        name: "with_timeout".to_string(),
                        ..Default::default()
                    },
                    MethodDef {
                        name: "with_tower_layer".to_string(),
                        cfg: Some(r#"feature = "tower""#.to_string()),
                        ..Default::default()
                    },
                ],
                registrations: vec![],
                entrypoints: vec![],
                doc: String::new(),
                cfg: None,
            }],
            ..Default::default()
        };

        let want: BTreeSet<String> = ["tower".to_string()].into_iter().collect();
        assert_eq!(collect_cfg_features(&api), want);
    }

    /// A service merged from a foreign `[[crates.source_crates]]` crate must not forward its cfg
    /// to the host crate's `[features]` table, for the same reason a merged type/enum doesn't
    /// (see `collect_cfg_features_excludes_external_source_crate_cfgs`) — forwarding would
    /// reference a feature the host crate does not define.
    #[test]
    fn collect_cfg_features_excludes_external_source_crate_service_cfgs() {
        use crate::core::ir::{MethodDef, ServiceDef};

        let api = ApiSurface {
            crate_name: "hostlib".to_string(),
            services: vec![ServiceDef {
                name: "OtherService".to_string(),
                rust_path: "otherlib::OtherService".to_string(),
                constructor: MethodDef::default(),
                configurators: vec![],
                registrations: vec![],
                entrypoints: vec![],
                doc: String::new(),
                cfg: Some(r#"feature = "foreign-only""#.to_string()),
            }],
            ..Default::default()
        };

        assert!(
            collect_cfg_features(&api).is_empty(),
            "a foreign-owned service's cfg must not forward to the host crate"
        );
    }

    #[test]
    fn collect_cfg_features_excludes_external_source_crate_cfgs() {
        // A type/enum merged from `[[crates.source_crates]]` carries the foreign crate's rust_path ~keep
        // and cfg gates. Its features must NOT be forwarded to the host crate (they'd map to ~keep
        // `<host>/<feat>` for a feature the host does not define, breaking cargo resolution). ~keep
        let api = ApiSurface {
            crate_name: "hostlib".to_string(),
            types: vec![TypeDef {
                name: "HostDoc".to_string(),
                rust_path: "hostlib::HostDoc".to_string(),
                cfg: Some(r#"feature = "pdf""#.to_string()),
                ..Default::default()
            }],
            enums: vec![EnumDef {
                name: "Strategy".to_string(),
                rust_path: "otherlib::Strategy".to_string(),
                variants: vec![
                    EnumVariant {
                        name: "Auto".to_string(),
                        cfg: None,
                        ..Default::default()
                    },
                    EnumVariant {
                        name: "Advanced".to_string(),
                        cfg: Some(r#"any(test, feature = "foreign-only")"#.to_string()),
                        ..Default::default()
                    },
                ],
                ..Default::default()
            }],
            ..Default::default()
        };
        let features = collect_cfg_features(&api);
        assert_eq!(
            features,
            BTreeSet::from(["pdf".to_string()]),
            "host `pdf` must forward; the foreign `foreign-only` feature must not leak into host passthrough"
        );
    }

    fn api_with_gated_functions(names_and_cfgs: &[(&str, Option<&str>)]) -> ApiSurface {
        use crate::core::ir::FunctionDef;
        ApiSurface {
            crate_name: "test_lib".to_string(),
            functions: names_and_cfgs
                .iter()
                .map(|(name, cfg)| FunctionDef {
                    name: (*name).to_string(),
                    rust_path: format!("test_lib::{name}"),
                    cfg: cfg.map(|s| s.to_string()),
                    ..Default::default()
                })
                .collect(),
            ..Default::default()
        }
    }

    #[test]
    fn undeclared_cfg_features_returns_only_missing_names() {
        let api = api_with_gated_functions(&[
            ("count_tokens", Some(r#"feature = "tokenizer""#)),
            ("with_tower_layer", Some(r#"feature = "tower""#)),
            ("completion_cost", None),
        ]);
        let declared: BTreeSet<String> = ["tower".to_string()].into_iter().collect();
        assert_eq!(
            undeclared_cfg_features(&api, &declared),
            BTreeSet::from(["tokenizer".to_string()]),
            "only the feature missing from `declared` should be reported"
        );
    }

    #[test]
    fn undeclared_cfg_features_empty_when_everything_declared() {
        let api = api_with_gated_functions(&[("count_tokens", Some(r#"feature = "tokenizer""#))]);
        let declared: BTreeSet<String> = ["tokenizer".to_string()].into_iter().collect();
        assert!(undeclared_cfg_features(&api, &declared).is_empty());
    }

    #[test]
    fn read_declared_cargo_features_none_when_file_missing() {
        let dir = tempfile::tempdir().expect("tempdir");
        let manifest = dir.path().join("Cargo.toml");
        assert!(
            read_declared_cargo_features(&manifest).is_none(),
            "an unscaffolded crate has nothing to verify against yet"
        );
    }

    #[test]
    fn read_declared_cargo_features_reads_features_table() {
        let dir = tempfile::tempdir().expect("tempdir");
        let manifest = dir.path().join("Cargo.toml");
        std::fs::write(
            &manifest,
            "[package]\nname = \"x\"\n\n[features]\ndefault = [\"native-http\"]\nnative-http = [\"core/native-http\"]\n",
        )
        .expect("write manifest");
        assert_eq!(
            read_declared_cargo_features(&manifest),
            Some(BTreeSet::from(["default".to_string(), "native-http".to_string()]))
        );
    }

    #[test]
    fn read_declared_cargo_features_empty_set_when_no_features_table() {
        let dir = tempfile::tempdir().expect("tempdir");
        let manifest = dir.path().join("Cargo.toml");
        std::fs::write(&manifest, "[package]\nname = \"x\"\n").expect("write manifest");
        assert_eq!(
            read_declared_cargo_features(&manifest),
            Some(BTreeSet::new()),
            "a manifest scaffolded before any cfg-gated symbol existed has no [features] table at \
             all, which must still be distinguishable from a missing file"
        );
    }

    /// Reproduces the liter-llm incident: the binding crate's Cargo.toml declares only the
    /// features it had at scaffold time (`native-http`), but the generated source now references
    /// `tokenizer` because the core crate gained a cfg-gated function since then.
    #[traced_test]
    #[test]
    fn warn_on_undeclared_binding_cfg_features_warns_on_stale_manifest() {
        let dir = tempfile::tempdir().expect("tempdir");
        let manifest = dir.path().join("Cargo.toml");
        std::fs::write(
            &manifest,
            "[package]\nname = \"x\"\n\n[features]\ndefault = [\"native-http\"]\nnative-http = [\"core/native-http\"]\n",
        )
        .expect("write manifest");
        let api = api_with_gated_functions(&[("count_tokens", Some(r#"feature = "tokenizer""#))]);

        warn_on_undeclared_binding_cfg_features(&api, Language::Ruby, &manifest);

        assert!(
            logs_contain("does not declare"),
            "a stale manifest missing a referenced feature must produce a warning"
        );
    }

    #[traced_test]
    #[test]
    fn warn_on_undeclared_binding_cfg_features_silent_when_manifest_declares_everything() {
        let dir = tempfile::tempdir().expect("tempdir");
        let manifest = dir.path().join("Cargo.toml");
        std::fs::write(
            &manifest,
            "[package]\nname = \"x\"\n\n[features]\ndefault = [\"tokenizer\"]\ntokenizer = [\"core/tokenizer\"]\n",
        )
        .expect("write manifest");
        let api = api_with_gated_functions(&[("count_tokens", Some(r#"feature = "tokenizer""#))]);

        warn_on_undeclared_binding_cfg_features(&api, Language::Ruby, &manifest);

        assert!(
            !logs_contain("does not declare"),
            "a fully up-to-date manifest must not warn"
        );
    }

    #[traced_test]
    #[test]
    fn warn_on_undeclared_binding_cfg_features_silent_when_manifest_missing() {
        let dir = tempfile::tempdir().expect("tempdir");
        let manifest = dir.path().join("Cargo.toml");
        let api = api_with_gated_functions(&[("count_tokens", Some(r#"feature = "tokenizer""#))]);

        warn_on_undeclared_binding_cfg_features(&api, Language::Ruby, &manifest);

        assert!(
            !logs_contain("does not declare"),
            "an unscaffolded crate (no manifest on disk yet) must not warn -- there is nothing to \
             verify against"
        );
    }
}