rustcall_julia_core 0.4.0

Shared Rust core for RustCall.jl: FFI manifest model, syn-based extraction, wrapper codegen, generic specialization
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
//! `#[cfg]`-disabled items must not be reported (follow-up of #264).

use rustcall_julia_core::cfg::CfgSet;
use rustcall_julia_core::expand::{expand, expand_with_cfg};
use rustcall_julia_core::extract::{extract_with_cfg, FilePosition};
use rustcall_julia_core::manifest::Mode;
use rustcall_julia_core::specialize::specialize;

const SRC: &str = r#"
#[cfg(unix)]
#[julia]
pub fn only_unix() -> i32 { 1 }

#[cfg(windows)]
#[julia]
pub fn only_windows() -> i32 { 2 }

#[cfg(all(unix, feature = "extra"))]
#[julia]
pub fn needs_feature() -> Result<i32, i32> { Ok(3) }

#[julia]
pub fn always() -> Option<i32> { Some(4) }

#[cfg(not(windows))]
#[julia]
pub struct Point { pub x: f64, #[cfg(windows)] pub win_only: f64 }

#[cfg(windows)]
#[julia]
pub struct WinPoint { pub x: f64 }

impl Point {
    pub fn x(&self) -> f64 { self.x }
    #[cfg(windows)]
    pub fn win(&self) -> f64 { 0.0 }
}

#[cfg(unix)]
mod nested {
    #[julia]
    pub fn in_unix_mod() -> i32 { 5 }
    #[cfg(windows)]
    #[julia]
    pub fn in_unix_mod_win() -> i32 { 6 }
}

#[cfg(windows)]
#[julia]
mod winmod {
    #[julia]
    pub fn gone() -> i32 { 7 }
}
"#;

fn names(m: &rustcall_julia_core::Manifest) -> Vec<String> {
    m.functions.iter().map(|f| f.name.clone()).collect()
}

#[test]
fn without_cfg_everything_is_reported_with_predicates() {
    let e = expand(SRC).unwrap();
    let f = |n: &str| e.manifest.functions.iter().find(|f| f.name == n).unwrap();
    assert_eq!(f("only_unix").cfg, "unix");
    assert_eq!(f("only_windows").cfg, "windows");
    assert_eq!(f("needs_feature").cfg, "all(unix, feature = \"extra\")");
    assert_eq!(f("always").cfg, "");
    assert!(names(&e.manifest).contains(&"gone".to_string()));
    let s = |n: &str| e.manifest.structs.iter().find(|s| s.name == n).unwrap();
    assert_eq!(s("Point").cfg, "not(windows)");
    assert_eq!(s("WinPoint").cfg, "windows");
}

#[test]
fn inline_mode_drops_disabled_items() {
    let set = CfgSet::default().with_name("unix");
    let e = expand_with_cfg(SRC, Some(&set)).unwrap();
    let n = names(&e.manifest);
    assert!(n.contains(&"only_unix".to_string()));
    assert!(n.contains(&"always".to_string()));
    assert!(n.contains(&"in_unix_mod".to_string()));
    assert!(!n.contains(&"only_windows".to_string()));
    assert!(
        !n.contains(&"needs_feature".to_string()),
        "feature not enabled"
    );
    assert!(!n.contains(&"in_unix_mod_win".to_string()));
    assert!(!n.contains(&"gone".to_string()));

    let structs: Vec<_> = e.manifest.structs.iter().map(|s| s.name.as_str()).collect();
    assert_eq!(structs, vec!["Point"]);
    let point = &e.manifest.structs[0];
    assert!(point.fields.iter().all(|f| f.name != "win_only"));
    assert!(point.methods.iter().any(|m| m.name == "x"));
    assert!(point.methods.iter().all(|m| m.name != "win"));

    // The expanded source contains no trace of the disabled items either.
    assert!(!e.source.contains("only_windows"));
    assert!(!e.source.contains("WinPoint"));
    assert!(!e.source.contains("winmod"));
    assert!(!e.source.contains("win_only"));
    // Decided predicates are dropped from the kept items, so the source no
    // longer depends on them; undecided ones (features) stay.
    assert!(!e.source.contains("#[cfg(unix)]"), "{}", e.source);
    assert!(!e.source.contains("#[cfg(not(windows))]"));

    // In lenient mode a feature predicate is undecided and therefore kept.
    let lenient = CfgSet::default().with_name("unix").lenient();
    let el = expand_with_cfg(SRC, Some(&lenient)).unwrap();
    assert!(el.source.contains("feature = \"extra\""), "{}", el.source);
    assert!(!el.source.contains("#[cfg(unix)]"));

    let with_feature = set.clone().with_pair("feature", "extra");
    let e2 = expand_with_cfg(SRC, Some(&with_feature)).unwrap();
    assert!(names(&e2.manifest).contains(&"needs_feature".to_string()));
}

#[test]
fn crate_mode_drops_disabled_items() {
    let set = CfgSet::default().with_name("windows");
    let m = extract_with_cfg(SRC, Mode::Crate, Some(&set)).unwrap();
    let n = names(&m);
    assert_eq!(n, vec!["only_windows", "always", "gone"]);
    let structs: Vec<_> = m.structs.iter().map(|s| s.name.as_str()).collect();
    assert_eq!(structs, vec!["WinPoint"]);
}

#[test]
fn result_wrappers_keep_cfg_attributes() {
    // The proc-macro sees `#[julia] #[cfg(...)] fn`: the generated items must
    // stay gated so an inactive function does not leak an exported symbol.
    let src = "#[julia]\n#[cfg(windows)]\npub fn r() -> Result<i32, i32> { Ok(1) }\n#[julia]\n#[cfg(windows)]\npub fn o() -> Option<i32> { None }";
    let e = expand(src).unwrap();
    let gated = e.source.matches("#[cfg(windows)]").count();
    // CResult struct + accessor impl + inner fn + extern fn + the panic
    // channel's two items (#244), twice.
    assert_eq!(gated, 12, "{}", e.source);
}

#[test]
fn unevaluable_predicate_fails_closed() {
    let set = CfgSet::default();
    let err = expand_with_cfg(
        "#[cfg(version(\"1.80\"))] #[julia] pub fn f() -> i32 { 0 }",
        Some(&set),
    )
    .err()
    .expect("unevaluable predicate must be an error");
    assert!(err.to_string().contains("cannot evaluate #[cfg]"), "{err}");
}

#[test]
fn specialize_keeps_predicate() {
    let src = "#[cfg(unix)] pub fn id<T: Copy>(x: T) -> T { x }";
    let sp = specialize(src, "id", &[("T".to_string(), "i32".to_string())], "id_i32").unwrap();
    assert_eq!(sp.manifest.functions[0].cfg, "unix");
    assert!(sp.source.contains("#[cfg(unix)]"));
}

/// A parameter can carry its own `#[cfg]`; rustc removes it, so the manifest
/// (and hence the generated wrapper's C ABI) must not report it either.
const PARAM_SRC: &str = r#"
#[julia]
pub fn takes(a: i32, #[cfg(any())] b: i32, #[cfg(all())] c: i32) -> i32 { a + c }

#[julia]
pub fn maybe(a: i32, #[cfg(feature = "extra")] b: i32) -> Result<i32, i32> { Ok(a) }

#[julia]
pub struct Holder { pub v: i32 }

impl Holder {
    pub fn sum(&self, a: i32, #[cfg(windows)] b: i32) -> i32 { self.v + a }
}
"#;

#[test]
fn prunes_disabled_function_parameters() {
    let set = CfgSet::default().with_name("unix");
    let e = expand_with_cfg(PARAM_SRC, Some(&set)).unwrap();

    let takes = e
        .manifest
        .functions
        .iter()
        .find(|f| f.name == "takes")
        .unwrap();
    let arg_names: Vec<&str> = takes.args.iter().map(|a| a.name.as_str()).collect();
    assert_eq!(arg_names, vec!["a", "c"], "{:?}", takes.args);

    // `feature = "extra"` is decided (strict set) and absent: the parameter goes.
    let maybe = e
        .manifest
        .functions
        .iter()
        .find(|f| f.name == "maybe")
        .unwrap();
    let arg_names: Vec<&str> = maybe.args.iter().map(|a| a.name.as_str()).collect();
    assert_eq!(arg_names, vec!["a"]);

    let holder = e
        .manifest
        .structs
        .iter()
        .find(|s| s.name == "Holder")
        .unwrap();
    let sum = holder.methods.iter().find(|m| m.name == "sum").unwrap();
    let arg_names: Vec<&str> = sum.args.iter().map(|a| a.name.as_str()).collect();
    assert_eq!(arg_names, vec!["a"], "{:?}", sum.args);

    // The expanded source carries neither the removed parameters nor the
    // predicates that were decided to be true.
    assert!(!e.source.contains("#[cfg(any())]"), "{}", e.source);
    assert!(!e.source.contains("#[cfg(all())]"), "{}", e.source);
    assert!(!e.source.contains("#[cfg(windows)]"), "{}", e.source);
}

#[test]
fn keeps_undecided_function_parameters_in_lenient_mode() {
    let set = CfgSet::default().with_name("unix").lenient();
    let e = expand_with_cfg(PARAM_SRC, Some(&set)).unwrap();

    // A feature predicate is undecided under Cargo, so the parameter stays and
    // its `#[cfg]` is preserved for rustc to decide.
    let maybe = e
        .manifest
        .functions
        .iter()
        .find(|f| f.name == "maybe")
        .unwrap();
    let arg_names: Vec<&str> = maybe.args.iter().map(|a| a.name.as_str()).collect();
    assert_eq!(arg_names, vec!["a", "b"], "{:?}", maybe.args);
    assert!(e.source.contains("feature = \"extra\""), "{}", e.source);

    // Target predicates are still decided, even leniently.
    let holder = e
        .manifest
        .structs
        .iter()
        .find(|s| s.name == "Holder")
        .unwrap();
    let sum = holder.methods.iter().find(|m| m.name == "sum").unwrap();
    assert_eq!(
        sum.args.iter().map(|a| a.name.as_str()).collect::<Vec<_>>(),
        vec!["a"]
    );
}

#[test]
fn unevaluable_parameter_predicate_fails_closed() {
    let set = CfgSet::default();
    let err = expand_with_cfg(
        "#[julia] pub fn f(a: i32, #[cfg(version(\"1.80\"))] b: i32) -> i32 { a }",
        Some(&set),
    )
    .err()
    .expect("unevaluable parameter predicate must be an error");
    assert!(err.to_string().contains("cannot evaluate #[cfg]"), "{err}");
}

/// A crate-level `#![cfg(...)]` decides the whole file: rustc keeps the
/// attribute and compiles nothing, so no item may be reported either.
#[test]
fn crate_level_cfg_disables_every_item() {
    let src = r#"
#![cfg(any())]
#[julia]
pub fn f() -> i32 { 1 }
#[julia]
pub struct S { pub x: i32 }
"#;
    let set = CfgSet::default().with_name("unix");

    let e = expand_with_cfg(src, Some(&set)).unwrap();
    assert!(
        e.manifest.functions.is_empty(),
        "{:?}",
        e.manifest.functions
    );
    assert!(e.manifest.structs.is_empty(), "{:?}", e.manifest.structs);
    assert!(!e.source.contains("fn f"), "{}", e.source);
    assert!(!e.source.contains("struct S"), "{}", e.source);

    let m = extract_with_cfg(src, Mode::Crate, Some(&set)).unwrap();
    assert!(m.functions.is_empty() && m.structs.is_empty());

    // An indirectly disabled crate (`cfg_attr`) is dropped just the same.
    let indirect = "#![cfg_attr(unix, cfg(any()))]\n#[julia]\npub fn f() -> i32 { 1 }\n";
    assert!(expand_with_cfg(indirect, Some(&set))
        .unwrap()
        .manifest
        .functions
        .is_empty());
}

#[test]
fn crate_level_cfg_that_holds_keeps_the_items() {
    let set = CfgSet::default().with_name("unix");
    let e = expand_with_cfg(
        "#![cfg(unix)]\n#[julia]\npub fn f() -> i32 { 1 }\n",
        Some(&set),
    )
    .unwrap();
    assert_eq!(names(&e.manifest), vec!["f"]);
    // The decided predicate is stripped, so a later rustc run cannot flip it.
    assert!(!e.source.contains("cfg(unix)"), "{}", e.source);

    // Undecided leniently (an external crate's feature): the items stay and
    // the crate attribute is preserved for rustc.
    let lenient = CfgSet::default().with_name("unix").lenient();
    let e = expand_with_cfg(
        "#![cfg(feature = \"x\")]\n#[julia]\npub fn f() -> i32 { 1 }\n",
        Some(&lenient),
    )
    .unwrap();
    assert_eq!(names(&e.manifest), vec!["f"]);
    assert!(e.source.contains("feature = \"x\""), "{}", e.source);
}

#[test]
fn unevaluable_crate_level_predicate_fails_closed() {
    let err = expand_with_cfg(
        "#![cfg(version(\"1.80\"))]\n#[julia]\npub fn f() -> i32 { 1 }\n",
        Some(&CfgSet::default()),
    )
    .err()
    .expect("unevaluable crate predicate must be an error");
    assert!(err.to_string().contains("cannot evaluate #[cfg]"), "{err}");
}

/// Generic parameters carry attributes too; rustc drops a `#[cfg]`-disabled one.
#[test]
fn prunes_disabled_generic_parameters() {
    let set = CfgSet::default().with_name("unix");
    let src = r#"
#[julia]
pub fn f<#[cfg(any())] T, U: Copy>(x: U) -> U { x }

#[julia]
pub fn g<#[cfg(any())] 'a, #[cfg(all())] T: Copy>(x: T) -> T { x }

#[julia]
pub fn h<#[cfg(windows)] const N: usize, T: Copy>(x: T) -> T { x }
"#;
    let e = expand_with_cfg(src, Some(&set)).unwrap();
    let params = |n: &str| -> Vec<String> {
        e.manifest
            .functions
            .iter()
            .find(|f| f.name == n)
            .unwrap()
            .type_params
            .iter()
            .map(|p| p.name.clone())
            .collect()
    };
    assert_eq!(params("f"), vec!["U"], "{}", e.source);
    assert_eq!(params("g"), vec!["T"], "{}", e.source);
    assert!(!e.source.contains("'a"), "{}", e.source);
    assert!(!e.source.contains("#[cfg(all())]"), "{}", e.source);
    // The disabled const parameter is gone, so the function is an ordinary
    // generic rather than an unsupported const-generic one.
    assert_eq!(params("h"), vec!["T"], "{}", e.source);
    assert!(!e.source.contains("const N"), "{}", e.source);
    assert!(!e.source.contains("compile_error"), "{}", e.source);

    // Struct and impl generics are pruned the same way.
    let src = r#"
#[julia]
pub struct W<#[cfg(any())] T, U: Copy> { pub v: U }
impl<#[cfg(any())] T, U: Copy> W<U> {
    pub fn v(&self) -> U { self.v }
}
"#;
    let e = expand_with_cfg(src, Some(&set)).unwrap();
    assert!(!e.source.contains("T,"), "{}", e.source);
    assert!(e.source.contains("W<U"), "{}", e.source);

    // Undecided leniently: kept, predicate preserved for rustc.
    let lenient = CfgSet::default().with_name("unix").lenient();
    let e = expand_with_cfg(
        "#[julia]\npub fn f<#[cfg(feature = \"x\")] T, U: Copy>(x: U) -> U { x }\n",
        Some(&lenient),
    )
    .unwrap();
    assert!(e.source.contains("feature = \"x\""), "{}", e.source);
}

#[test]
fn unevaluable_generic_parameter_predicate_fails_closed() {
    let err = expand_with_cfg(
        "#[julia]\npub fn f<#[cfg(version(\"1.80\"))] T: Copy>(x: T) -> T { x }\n",
        Some(&CfgSet::default()),
    )
    .err()
    .expect("unevaluable generic parameter predicate must be an error");
    assert!(err.to_string().contains("cannot evaluate #[cfg]"), "{err}");
}

/// Item-level pruning cannot resolve `#[cfg]` / `cfg!` inside a body, so the
/// manifest reports their presence for callers that would compile the source
/// under another configuration (lazy specialization of a Cargo-backed block).
#[test]
fn reports_cfg_inside_function_bodies() {
    let src = r#"
#[julia]
pub fn plain<T: Copy>(x: T) -> T { x }

#[julia]
pub fn uses_macro<T: Copy>(x: T) -> T { if cfg!(panic = "unwind") { x } else { x } }

#[julia]
pub fn uses_attr<T: Copy>(x: T) -> T {
    #[cfg(debug_assertions)]
    let _y = 1;
    x
}

#[julia]
pub fn uses_cfg_attr<T: Copy>(x: T) -> T {
    #[cfg_attr(unix, allow(unused))]
    let _y = 1;
    x
}

#[julia]
pub fn nested_item<T: Copy>(x: T) -> T {
    fn helper() -> i32 { std::cfg!(unix) as i32 }
    let _ = helper();
    x
}

#[julia]
pub fn not_generic() -> i32 { cfg!(unix) as i32 }
"#;
    let e = expand(src).unwrap();
    let has = |n: &str| {
        e.manifest
            .functions
            .iter()
            .find(|f| f.name == n)
            .unwrap()
            .body_has_cfg
    };
    assert!(!has("plain"));
    assert!(has("uses_macro"));
    assert!(has("uses_attr"));
    assert!(has("uses_cfg_attr"));
    assert!(has("nested_item"));
    assert!(has("not_generic"));
}

/// `#[cfg_attr(unix, cfg_attr(unix, ... cfg(any())))]` nested `depth` times.
fn nested_cfg_attr(depth: usize) -> String {
    let mut s = "cfg(any())".to_string();
    for _ in 0..depth {
        s = format!("cfg_attr(unix, {s})");
    }
    format!("#[{s}]\n#[julia]\npub fn deep() -> i32 {{ 1 }}\n")
}

/// Expansion runs until nothing changes, so a `cfg_attr` nested deeper than
/// the old fixed number of rounds still reaches its false `cfg`.
#[test]
fn deeply_nested_cfg_attr_is_fully_expanded() {
    let set = CfgSet::default().with_name("unix");
    for depth in [1usize, 8, 10, 32] {
        let e = expand_with_cfg(&nested_cfg_attr(depth), Some(&set)).unwrap();
        assert!(
            e.manifest.functions.is_empty(),
            "depth {depth}: {:?}",
            e.manifest.functions
        );
        assert!(!e.source.contains("deep"), "depth {depth}: {}", e.source);
    }
    // A true chain is expanded away entirely.
    let src = "#[cfg_attr(unix, cfg_attr(unix, cfg_attr(unix, cfg(all()))))]\n#[julia]\npub fn deep() -> i32 { 1 }\n";
    let e = expand_with_cfg(src, Some(&set)).unwrap();
    assert_eq!(names(&e.manifest), vec!["deep"]);
    assert!(!e.source.contains("cfg"), "{}", e.source);
}

/// The remaining depth limit is a safety net: exceeding it is an error, never
/// a partial expansion that hides a false predicate.
#[test]
fn absurdly_nested_cfg_attr_fails_closed() {
    let set = CfgSet::default().with_name("unix");
    let err = expand_with_cfg(&nested_cfg_attr(100), Some(&set))
        .err()
        .expect("nesting past the limit must be an error");
    let msg = err.to_string();
    assert!(
        msg.contains("cannot evaluate #[cfg]") && msg.contains("nested deeper"),
        "{msg}"
    );
}

/// `#[cfg_attr(pred, cfg(...))]` decides whether a function is compiled just
/// like a direct `#[cfg]`, so every generated item must carry it: otherwise the
/// helper type and the inner fn stay unconditional while the exported symbol
/// disappears, and the Julia binding fails at symbol lookup.
#[test]
fn generated_items_propagate_cfg_attr() {
    let src = r#"
#[julia]
#[cfg_attr(not(feature = "ffi"), cfg(any()))]
pub fn r() -> Result<i32, i32> { Ok(1) }

#[julia]
#[cfg_attr(not(feature = "ffi"), cfg(any()))]
pub fn o() -> Option<i32> { None }
"#;
    let e = expand(src).unwrap();
    // CResult/COption struct + accessor impl + inner fn + extern fn + the two
    // items of the panic channel (thread-local slot and reader, #244), twice.
    let gated = e.source.matches("cfg_attr(not(feature = \"ffi\")").count();
    assert_eq!(gated, 12, "{}", e.source);

    // Only the `cfg`-producing part is copied onto the generated items; an
    // unrelated attribute stays on the exported function alone.
    let mixed = r#"
#[julia]
#[cfg_attr(not(feature = "ffi"), cfg(any()), allow(dead_code))]
pub fn r() -> Result<i32, i32> { Ok(1) }
"#;
    let e = expand(mixed).unwrap();
    assert_eq!(
        e.source
            .matches("cfg_attr(not(feature = \"ffi\"), cfg(any()))")
            .count(),
        5,
        "{}",
        e.source
    );
    assert_eq!(
        e.source.matches("allow(dead_code)").count(),
        1,
        "{}",
        e.source
    );
}

/// A module's `#[cfg]` gates everything inside it, so every entry inherits the
/// predicates of its enclosing modules in `cfg` / `cfg_features` — otherwise a
/// lenient crate scan reports `a::run` as unconditional and a consumer binds
/// it in a build without the feature (#300 review). Checked on every walk that
/// records entries: crate extraction, inline expansion, and the PyO3 scan of an
/// inline module and of a file reached through a gated `mod` declaration.
#[test]
fn enclosing_module_cfg_is_inherited() {
    let src = r#"
        #[cfg(feature = "x")]
        #[julia]
        pub mod a {
            #[julia]
            pub fn run() -> i32 { 1 }
            #[cfg(unix)]
            #[julia]
            pub fn nix() -> i32 { 2 }
            #[julia]
            pub struct C { pub v: i32 }
            #[cfg(feature = "y")]
            #[julia]
            pub mod deep {
                #[julia]
                pub fn d() -> i32 { 3 }
            }
        }
        #[julia]
        pub fn root() -> i32 { 0 }
    "#;
    let check = |m: &rustcall_julia_core::Manifest| {
        let f = |name: &str| m.functions.iter().find(|f| f.name == name).unwrap();
        assert_eq!(f("root").cfg, "");
        assert_eq!(f("run").cfg, "feature = \"x\"");
        assert_eq!(f("run").cfg_features, vec!["x"]);
        assert_eq!(f("nix").cfg, "all(feature = \"x\", unix)");
        assert_eq!(f("nix").cfg_features, vec!["x"]);
        assert_eq!(f("d").cfg, "all(feature = \"x\", feature = \"y\")");
        assert_eq!(f("d").cfg_features, vec!["x", "y"]);
        let c = m.structs.iter().find(|s| s.name == "C").unwrap();
        assert_eq!(c.cfg, "feature = \"x\"");
        assert_eq!(c.cfg_features, vec!["x"]);
    };
    check(&extract_with_cfg(src, Mode::Crate, None).unwrap());
    check(&expand_with_cfg(src, None).unwrap().manifest);

    // PyO3 items: an inline gated module ...
    let py = r#"
        #[cfg(feature = "x")]
        pub mod a {
            #[pyfunction] pub fn run() -> i32 { 1 }
            #[pyclass] pub struct C { #[pyo3(get)] pub v: i32 }
        }
    "#;
    let m = extract_with_cfg(py, Mode::Crate, None).unwrap();
    assert_eq!(m.functions[0].cfg, "feature = \"x\"");
    assert_eq!(m.functions[0].cfg_features, vec!["x"]);
    assert_eq!(m.structs[0].cfg, "feature = \"x\"");
    // ... and a file reached through a gated `mod a;` declaration, whose
    // predicate the tree walk hands to the file's scan.
    let mut scan = rustcall_julia_core::extract::TreeScan::new();
    let mut manifest = rustcall_julia_core::Manifest::new(Mode::Crate);
    let pending = scan
        .file(
            "#[cfg(feature = \"x\")] pub mod a;",
            None,
            &FilePosition::module(&[], true, &[]),
            &mut manifest,
            "src/lib.rs",
        )
        .unwrap()
        .modules;
    assert_eq!(pending.len(), 1);
    assert_eq!(pending[0].cfg.len(), 1);
    let more = scan
        .file(
            "#[pyfunction] pub fn run() -> i32 { 1 }",
            None,
            &FilePosition::module(
                &pending[0].module_path,
                pending[0].reachable,
                &pending[0].cfg,
            ),
            &mut manifest,
            "src/a.rs",
        )
        .unwrap();
    assert!(more.modules.is_empty() && more.includes.is_empty());
    scan.finish(&mut manifest).unwrap();
    assert_eq!(manifest.functions[0].module_path, vec!["a"]);
    assert_eq!(manifest.functions[0].cfg, "feature = \"x\"");
    assert_eq!(manifest.functions[0].cfg_features, vec!["x"]);
}

/// A `#[pymethods]` block in a gated module, away from its class, gates its
/// methods: the block's and its modules' predicates reach `Method.cfg`, so a
/// wrapper generated from a lenient scan refuses them instead of calling a
/// method the build may not have (#300 review).
#[test]
fn pymethods_blocks_inherit_their_module_cfg() {
    let src = r#"
        pub mod shapes { #[pyclass] pub struct Circle { pub r: f64 } }
        #[cfg(feature = "x")]
        pub mod extra {
            #[pymethods]
            impl super::shapes::Circle {
                pub fn area(&self) -> f64 { 0.0 }
                #[cfg(unix)]
                pub fn nix(&self) -> f64 { 0.0 }
            }
        }
        #[cfg(feature = "y")]
        #[pymethods]
        impl shapes::Circle {
            pub fn perimeter(&self) -> f64 { 0.0 }
        }
    "#;
    let m = extract_with_cfg(src, Mode::Crate, None).unwrap();
    let circle = m.structs.iter().find(|s| s.name == "Circle").unwrap();
    let method = |name: &str| circle.methods.iter().find(|mm| mm.name == name).unwrap();
    assert_eq!(method("area").cfg, "feature = \"x\"");
    assert_eq!(method("nix").cfg, "all(feature = \"x\", unix)");
    assert_eq!(method("perimeter").cfg, "feature = \"y\"");
    // The class itself is unconditional.
    assert_eq!(circle.cfg, "");
}

/// Inside a `#[julia] mod` the module macro expands a gated struct or impl
/// before rustc evaluates the predicate, so the generated destructor,
/// accessors, string helpers and method wrappers must carry the same `#[cfg]`
/// as the item they refer to — otherwise turning the feature off leaves
/// functions that name a struct that is gone (#300 review).
#[test]
fn generated_struct_helpers_carry_the_struct_cfg() {
    let item: syn::ItemStruct =
        syn::parse_str("#[cfg(feature = \"x\")] pub struct C { pub v: i32, pub label: String }")
            .unwrap();
    let file: syn::File = syn::parse2(rustcall_julia_core::codegen::transform_struct_crate(
        item,
        &["a".to_string()],
    ))
    .unwrap();
    let has_cfg = |attrs: &[syn::Attribute]| {
        attrs
            .iter()
            .any(|a| a.path().is_ident("cfg") && quote::quote!(#a).to_string().contains("feature"))
    };
    let mut fns = 0;
    for it in &file.items {
        match it {
            syn::Item::Fn(f) => {
                fns += 1;
                assert!(
                    has_cfg(&f.attrs),
                    "helper `{}` lost the struct's cfg",
                    f.sig.ident
                );
            }
            syn::Item::Struct(s) => assert!(has_cfg(&s.attrs), "`{}` lost its cfg", s.ident),
            syn::Item::Macro(m) if m.mac.path.is_ident("thread_local") => {
                assert!(has_cfg(&m.attrs), "a helper panic slot lost its cfg");
            }
            _ => {}
        }
    }
    // free + four accessors, each with a reader, plus free_rust_string
    assert_eq!(fns, 11);

    let imp: syn::ItemImpl = syn::parse_str(
        "#[cfg(feature = \"x\")] impl C { #[julia] pub fn get(&self) -> i32 { self.v } }",
    )
    .unwrap();
    let file: syn::File = syn::parse2(rustcall_julia_core::codegen::transform_impl_crate(
        imp,
        &["a".to_string()],
    ))
    .unwrap();
    let wrappers: Vec<&syn::ItemFn> = file
        .items
        .iter()
        .filter_map(|it| match it {
            syn::Item::Fn(f) => Some(f),
            _ => None,
        })
        .collect();
    assert!(!wrappers.is_empty());
    for f in wrappers {
        assert!(
            has_cfg(&f.attrs),
            "wrapper `{}` lost the block's cfg",
            f.sig.ident
        );
    }
    // The method inside the block is left as written: its own attrs only.
    let imp_out = file
        .items
        .iter()
        .find_map(|it| match it {
            syn::Item::Impl(i) => Some(i),
            _ => None,
        })
        .unwrap();
    let syn::ImplItem::Fn(method) = &imp_out.items[0] else {
        panic!()
    };
    assert!(method.attrs.is_empty());
}