alef 0.67.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
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
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
//! Rust e2e test code generator.
//!
//! Generates `e2e/rust/Cargo.toml` and `tests/{category}_test.rs` files from
//! JSON fixtures, driven entirely by `E2eConfig` and `CallConfig`.

pub mod assertions;
pub mod cargo_config;
pub mod cargo_toml;
pub mod http;
pub mod mock_server;
pub mod test_file;

mod args;
#[cfg(test)]
mod assertion_containment_tests;
mod assertion_helpers;
mod assertion_synthetic;
#[cfg(test)]
mod collection_field_classification_tests;

pub use cargo_config::render_cargo_config;
pub use cargo_toml::render_cargo_toml;
pub use mock_server::{render_common_module, render_mock_server_binary, render_mock_server_module};

use crate::core::backend::GeneratedFile;
use crate::core::config::ResolvedCrateConfig;
use anyhow::Result;
use std::path::PathBuf;

use crate::e2e::config::E2eConfig;
use crate::e2e::escape::sanitize_filename;
use crate::e2e::fixture::{Fixture, FixtureGroup};

use super::E2eCodegen;
use test_file::{is_skipped, render_test_file};

/// Rust e2e test code generator.
pub struct RustE2eCodegen;

impl E2eCodegen for RustE2eCodegen {
    fn generate(
        &self,
        groups: &[FixtureGroup],
        e2e_config: &E2eConfig,
        config: &ResolvedCrateConfig,
        type_defs: &[crate::core::ir::TypeDef],
        enums: &[crate::core::ir::EnumDef],
        functions: &[crate::core::ir::FunctionDef],
        _errors: &[crate::core::ir::ErrorDef],
    ) -> Result<Vec<GeneratedFile>> {
        let mut files = Vec::new();
        let output_base = PathBuf::from(e2e_config.effective_output()).join("rust");

        // Resolve crate name and path from config.
        let crate_name = resolve_crate_name(e2e_config, config);
        let crate_path = resolve_crate_path(e2e_config, &crate_name);
        let dep_name = crate_name.replace('-', "_");

        // Cargo.toml
        // Check if any call config (default or named) uses json_object/handle args (needs serde_json dep).
        let all_call_configs = std::iter::once(&e2e_config.call).chain(e2e_config.calls.values());
        let needs_serde_json = all_call_configs
            .flat_map(|c| c.args.iter())
            .any(|a| a.arg_type == "json_object" || a.arg_type == "handle");

        // Check if any fixture in any group requires a mock HTTP server.
        // This includes both demo-client mock_response fixtures and sample_project http fixtures.
        let needs_mock_server = groups
            .iter()
            .flat_map(|g| g.fixtures.iter())
            .any(|f| !is_skipped(f, "rust") && f.needs_mock_server());

        // Check if any fixture uses the http integration test pattern (sample_project http fixtures).
        let needs_http_tests = groups
            .iter()
            .flat_map(|g| g.fixtures.iter())
            .any(|f| !is_skipped(f, "rust") && f.http.is_some());

        // Check if any http fixture uses CORS or static-files middleware (needs tower-http).
        let needs_tower_http = groups
            .iter()
            .flat_map(|g| g.fixtures.iter())
            .filter(|f| !is_skipped(f, "rust"))
            .filter_map(|f| f.http.as_ref())
            .filter_map(|h| h.handler.middleware.as_ref())
            .any(|m| m.cors.is_some() || m.static_files.is_some());

        // Tokio is needed when any test is async (mock server, http tests, or async call config).
        let any_async_call = std::iter::once(&e2e_config.call)
            .chain(e2e_config.calls.values())
            .any(|c| c.r#async);
        let needs_tokio = needs_mock_server || needs_http_tests || any_async_call;

        // anyhow is needed when any fixture uses a `test_backend` arg: the generated
        // Rust trait-bridge stubs reference `anyhow::Error` in their method signatures
        // because sample_core plugin traits declare `-> Result<T, anyhow::Error>`.
        // Without this direct dependency the stubs fail to compile with E0433.
        let all_call_args_for_anyhow = std::iter::once(&e2e_config.call)
            .chain(e2e_config.calls.values())
            .flat_map(|c| c.args.iter())
            .any(|a| a.arg_type == "test_backend");
        let any_fixture_test_backend = groups
            .iter()
            .flat_map(|g| g.fixtures.iter())
            .filter(|f| !is_skipped(f, "rust"))
            .any(|f| f.args.iter().any(|a| a.arg_type == "test_backend"));
        let needs_anyhow = all_call_args_for_anyhow || any_fixture_test_backend;

        // Emit `.cargo/config.toml` with an `[env]` block when `[e2e.env]`
        // is non-empty. Cargo's `[env]` table propagates these variables to
        // every test-binary process before any binding constructor runs,
        // with `force = false` so a parent shell can still override at
        // spawn time (setdefault semantics).
        if let Some(content) = render_cargo_config(&e2e_config.env) {
            files.push(GeneratedFile {
                path: output_base.join(".cargo").join("config.toml"),
                content,
                generated_header: false,
            });
        }

        let crate_version = resolve_crate_version(e2e_config).or_else(|| config.resolved_version());
        files.push(GeneratedFile {
            path: output_base.join("Cargo.toml"),
            content: render_cargo_toml(
                &crate_name,
                &dep_name,
                &crate_path,
                needs_serde_json,
                needs_mock_server,
                needs_http_tests,
                needs_tokio,
                needs_tower_http,
                needs_anyhow,
                e2e_config.dep_mode,
                crate_version.as_deref(),
                &config.features,
            ),
            generated_header: true,
        });

        // Generate mock_server.rs when at least one fixture uses mock_response.
        if needs_mock_server {
            files.push(GeneratedFile {
                path: output_base.join("tests").join("mock_server.rs"),
                content: render_mock_server_module(),
                generated_header: true,
            });
            // Generate common.rs module for spawning the standalone mock-server binary.
            files.push(GeneratedFile {
                path: output_base.join("tests").join("common.rs"),
                content: render_common_module(),
                generated_header: true,
            });
        }
        // Always generate standalone mock-server binary for cross-language e2e suites
        // when any fixture has http data (serves fixture responses for non-Rust tests).
        if needs_mock_server || needs_http_tests {
            files.push(GeneratedFile {
                path: output_base.join("src").join("main.rs"),
                content: render_mock_server_binary(),
                generated_header: true,
            });
        }

        // Per-category test files.
        for group in groups {
            let fixtures: Vec<&Fixture> = group.fixtures.iter().filter(|f| !is_skipped(f, "rust")).collect();

            if fixtures.is_empty() {
                continue;
            }

            let filename = format!("{}_test.rs", sanitize_filename(&group.category));
            let content = render_test_file(
                &group.category,
                &fixtures,
                e2e_config,
                config,
                type_defs,
                enums,
                functions,
                &dep_name,
                needs_mock_server,
                // The executable suite ignores every fixture's docs client: its own
                // client must reach the mock server. ~keep
                None,
                false,
            );

            files.push(GeneratedFile {
                path: output_base.join("tests").join(filename),
                content,
                generated_header: true,
            });
        }

        Ok(files)
    }

    fn render_snippet_body(
        &self,
        fixture: &Fixture,
        e2e_config: &E2eConfig,
        config: &ResolvedCrateConfig,
        type_defs: &[crate::core::ir::TypeDef],
        enums: &[crate::core::ir::EnumDef],
    ) -> Result<String> {
        let dep_name = resolve_crate_name(e2e_config, config).replace('-', "_");
        let mut call_fixture = fixture.docs_call_fixture();
        let expects_error = fixture
            .assertions
            .iter()
            .any(|assertion| assertion.assertion_type == "error");
        call_fixture.assertions.clear();
        call_fixture.mock_response = None;
        // This trait method carries no `functions: &[FunctionDef]` parameter (the free-function
        // registry), so a snippet whose call names a free function rather than an IR type's
        // method resolves no root type for IR-derived enum classification here — it still
        // falls back to the hand-maintained `fields_enum` config, exactly as before this
        // parameter existed. Method-based calls (`type_defs` alone) resolve fine.
        let test_file = render_test_file(
            &fixture.resolved_category(),
            &[&call_fixture],
            e2e_config,
            config,
            type_defs,
            enums,
            &[],
            &dep_name,
            call_fixture.needs_mock_server(),
            fixture.docs_client(),
            expects_error,
        );
        let (imports, body, is_async) = extract_rust_snippet(&test_file)?;
        let api_key_var = crate::e2e::fixture::FixtureEnv::api_key_var_or_default(fixture.env.as_ref());
        let body = body
            .into_iter()
            .map(|line| {
                line.replace(
                    "\"test-key\".to_string()",
                    &format!("std::env::var(\"{api_key_var}\").expect(\"{api_key_var} must be set\")"),
                )
            })
            .collect::<Vec<_>>();
        let presentation = super::presentation::resolve(&call_fixture, e2e_config, "rust", type_defs);
        let call = e2e_config.resolve_call_for_fixture(
            call_fixture.call.as_deref(),
            &call_fixture.id,
            &call_fixture.resolved_category(),
            &call_fixture.tags,
            &call_fixture.input,
        );
        // An error fixture renders the `Result` through the template's `match`, which both
        // reports the failure and consumes the value — a second unconditional `println!`
        // of `result_var` would then reference a moved binding. ~keep
        let display_result = !expects_error && presentation.is_empty() && !call.returns_void;
        let body = body
            .into_iter()
            .map(|line| {
                if display_result {
                    line.replacen("let _ =", &format!("let {} =", call.effective_result_var()), 1)
                } else {
                    line.to_string()
                }
            })
            .collect::<Vec<_>>();
        Ok(crate::e2e::template_env::render(
            "rust/snippet_body.rs.jinja",
            minijinja::context! {
                imports => imports, body => body, is_async => is_async, presentation => presentation,
                display_result => display_result, result_var => call.effective_result_var(),
                expects_error => expects_error, returns_void => call.returns_void,
            },
        ))
    }

    fn language_name(&self) -> &'static str {
        "rust"
    }
}

fn extract_rust_snippet(rendered: &str) -> Result<(Vec<&str>, Vec<&str>, bool)> {
    let lines = rendered.lines().collect::<Vec<_>>();
    let signature = lines
        .iter()
        .position(|line| line.starts_with("async fn test_") || line.starts_with("fn test_"))
        .ok_or_else(|| anyhow::anyhow!("generated Rust test did not contain a fixture function"))?;
    let imports = lines[..signature]
        .iter()
        .copied()
        .filter(|line| line.starts_with("use ") && !line.contains("common::"))
        .collect();
    let function_end = find_function_end(&lines, signature + 1)
        .ok_or_else(|| anyhow::anyhow!("generated Rust fixture function was not closed"))?;
    let body = lines[signature + 1..function_end]
        .iter()
        .copied()
        .filter(|line| !line.trim_start().starts_with("//"))
        .collect();
    Ok((imports, body, lines[signature].starts_with("async fn ")))
}

/// Locate the line index of the `}` that closes the function whose body begins at `start`
/// (the line after the signature line, which itself contributed one unmatched `{`).
///
/// Tracks brace depth across `"..."` strings (with backslash escapes) and `r"..."` /
/// `r#"..."#` / `r##"..."##` raw strings (any number of hashes), and skips `//` line
/// comments, so a `}` embedded in a fixture's raw-string body — including one sitting alone
/// on its own line — is never mistaken for the function's closing brace.
///
/// ~keep: does not model block comments (`/* */`) or char literals (`'x'`); this codegen
/// path never emits either, so a full lexer would be unjustified complexity here.
fn find_function_end(lines: &[&str], start: usize) -> Option<usize> {
    #[derive(Clone, Copy)]
    enum State {
        Code,
        Str,
        RawStr(usize),
    }

    let mut depth: i32 = 1;
    let mut state = State::Code;

    for (offset, line) in lines[start..].iter().enumerate() {
        let chars: Vec<char> = line.chars().collect();
        let mut i = 0;
        while i < chars.len() {
            match state {
                State::Code => {
                    if chars[i] == '/' && chars.get(i + 1) == Some(&'/') {
                        break; // rest of the line is a line comment
                    } else if chars[i] == '"' {
                        state = State::Str;
                    } else if let Some(hashes) = raw_string_open(&chars, i) {
                        state = State::RawStr(hashes);
                        i += 1 + hashes; // skip `r` and the hashes; loop's `i += 1` covers the opening quote
                    } else if chars[i] == '{' {
                        depth += 1;
                    } else if chars[i] == '}' {
                        depth -= 1;
                        if depth == 0 {
                            return Some(start + offset);
                        }
                    }
                }
                State::Str => {
                    if chars[i] == '\\' {
                        i += 1; // skip the escaped character
                    } else if chars[i] == '"' {
                        state = State::Code;
                    }
                }
                State::RawStr(hashes) => {
                    if chars[i] == '"' && raw_string_close_matches(&chars, i + 1, hashes) {
                        i += hashes; // skip the closing hashes; loop's `i += 1` covers the closing quote
                        state = State::Code;
                    }
                }
            }
            i += 1;
        }
    }
    None
}

/// If `chars[i..]` opens a raw string (`r"`, `r#"`, `r##"`, ...), return its hash count.
fn raw_string_open(chars: &[char], i: usize) -> Option<usize> {
    if chars.get(i) != Some(&'r') {
        return None;
    }
    let mut hashes = 0;
    while chars.get(i + 1 + hashes) == Some(&'#') {
        hashes += 1;
    }
    if chars.get(i + 1 + hashes) == Some(&'"') {
        Some(hashes)
    } else {
        None
    }
}

/// True when `chars[from..]` has at least `hashes` consecutive `#` characters, i.e. a raw
/// string opened with `hashes` hashes closes at the `"` immediately preceding `from`.
fn raw_string_close_matches(chars: &[char], from: usize, hashes: usize) -> bool {
    (0..hashes).all(|offset| chars.get(from + offset) == Some(&'#'))
}

// ---------------------------------------------------------------------------
// Config resolution helpers
// ---------------------------------------------------------------------------

fn resolve_crate_name(_e2e_config: &E2eConfig, config: &ResolvedCrateConfig) -> String {
    // Always use the Cargo package name (with hyphens) from alef.toml [crate].
    // The `crate_name` override in [e2e.call.overrides.rust] is for the Rust
    // import identifier, not the Cargo package name.
    config.name.clone()
}

fn resolve_crate_path(e2e_config: &E2eConfig, crate_name: &str) -> String {
    e2e_config
        .resolve_package("rust")
        .and_then(|p| p.path.clone())
        .unwrap_or_else(|| format!("../../crates/{crate_name}"))
}

fn resolve_crate_version(e2e_config: &E2eConfig) -> Option<String> {
    e2e_config.resolve_package("rust").and_then(|p| p.version.clone())
}

/// Emit a Rust test backend stub for a trait-bridge fixture.
///
/// Generates a minimal `struct TestStub<fixture_id_pascalcase>` with a `_name` field and
/// a concrete `impl <trait_name> for TestStub<fixture_id_pascalcase>` block where every
/// required method returns a language-default value. When the bridge config
/// declares a `super_trait`, a `name()` method is also emitted returning the
/// fixture's name string extracted from `fixture.input`.
///
/// The returned `arg_expr` wraps the stub in `std::sync::Arc::new(...)`, which
/// is the form expected by the generated `register_<trait>` function.
///
/// The `type_imports` field on the returned emission lists short symbol names
/// (trait name plus any named types referenced in method signatures) that the
/// caller must import from the crate under test so the stub compiles.
pub fn emit_test_backend(
    trait_bridge: &crate::core::config::TraitBridgeConfig,
    methods: &[&crate::core::ir::MethodDef],
    fixture: &Fixture,
) -> super::TestBackendEmission {
    use crate::codegen::defaults::language_defaults;
    use std::fmt::Write as FmtWrite;

    let stub_name = format!("TestStub{}", fixture_id_to_pascal_case(&fixture.id));
    let trait_name = &trait_bridge.trait_name;
    let backend_name = extract_backend_name_from_input(&fixture.input, &fixture.id);
    let defaults = language_defaults("rust");

    // Collect named types that must be imported (trait name + return/param types).
    let mut type_imports: Vec<String> = Vec::new();
    // The trait itself must be in scope for `impl TraitName for ...` to resolve.
    type_imports.push(trait_name.clone());

    let mut setup = String::new();

    // Derive the crate module name from the super_trait path (e.g. "sample_core::plugins::Plugin"
    // → "sample_core"). Used to qualify single-arg `Result<T>` return types so that stub method
    // signatures match the trait declaration (which uses a crate-level `Result` alias).
    let crate_module: Option<&str> = trait_bridge
        .super_trait
        .as_deref()
        .and_then(|s| s.split("::").next())
        .filter(|s| !s.is_empty());

    // Struct definition with a cached name field.
    let _ = writeln!(setup, "struct {stub_name} {{ _name: &'static str }}");

    // When the trait has a super-trait (e.g. Plugin), emit a separate impl block
    // for it first.  Putting super-trait methods inside `impl TraitName for ...`
    // is a compile error (E0407).
    if let Some(super_trait) = &trait_bridge.super_trait {
        // Derive a short import alias: take the last path segment.
        let super_short = super_trait.split("::").last().unwrap_or(super_trait.as_str());
        // Use the fully-qualified path in the impl header so it resolves without
        // an extra `use` import.
        let _ = writeln!(setup, "impl {super_trait} for {stub_name} {{");
        let _ = writeln!(setup, "    fn name(&self) -> &str {{ self._name }}");
        let _ = writeln!(setup, "}}");
        // Track the short name for import, but only if it's not already qualified.
        if !super_short.is_empty() && !super_trait.contains("::") {
            type_imports.push(super_short.to_string());
        }
    }

    // Determine if any required method is async so we know whether to add #[async_trait].
    let has_async_methods = methods
        .iter()
        .any(|m| !(m.has_default_impl || trait_bridge.super_trait.is_some() && m.name == "name") && m.is_async);

    // When the trait has async methods (decorated with #[async_trait] in Rust), the
    // impl block must also carry `#[async_trait]`.  Without it the async fn signatures
    // won't match the trait's `BoxFuture`-transformed signatures and the compiler
    // emits E0195 (lifetime bounds mismatch).
    if has_async_methods {
        let _ = writeln!(setup, "#[async_trait::async_trait]");
    }

    // Impl block for the main trait.
    let _ = writeln!(setup, "impl {trait_name} for {stub_name} {{");

    // Required methods only (skip those with a default implementation).
    for method in methods {
        if method.has_default_impl {
            continue;
        }
        // Skip Plugin supertrait methods — already emitted in the Plugin impl block above.
        if trait_bridge.super_trait.is_some() && method.name == "name" {
            continue;
        }
        emit_rust_stub_method(&mut setup, method, &*defaults, &mut type_imports, crate_module);
    }

    let _ = writeln!(setup, "}}");

    // Deduplicate imports (stable order for deterministic output).
    type_imports.sort();
    type_imports.dedup();

    // arg_expr: wrapped in Arc for the register call.
    let arg_expr = format!("std::sync::Arc::new({stub_name} {{ _name: \"{backend_name}\" }})");

    // Filter type_imports: skip Rust primitives and std types that are always in scope.
    let type_imports = type_imports
        .into_iter()
        .filter(|s| {
            !matches!(
                s.as_str(),
                "bool"
                    | "u8"
                    | "u16"
                    | "u32"
                    | "u64"
                    | "i8"
                    | "i16"
                    | "i32"
                    | "i64"
                    | "f32"
                    | "f64"
                    | "usize"
                    | "isize"
                    | "String"
                    | "str"
                    | "Vec"
                    | "Option"
                    | "Result"
                    | "()"
            )
        })
        .collect();

    super::TestBackendEmission {
        setup_block: setup,
        arg_expr,
        type_imports,
        // Rust cargo integration tests run each `tests/*.rs` file in its own
        // process, so the global registry resets between files and no
        // teardown is required.
        teardown_block: String::new(),
    }
}

/// Collect all `Named` type identifiers referenced anywhere in `ty` into `out`.
///
/// Only the short identifier is collected (not the fully qualified path),
/// since stub method signatures use short names and callers emit the `use` import.
fn collect_named_types(ty: &crate::core::ir::TypeRef, out: &mut Vec<String>) {
    use crate::core::ir::TypeRef;
    match ty {
        TypeRef::Named(name) => out.push(name.clone()),
        TypeRef::Optional(inner) | TypeRef::Vec(inner) => collect_named_types(inner, out),
        TypeRef::Map(k, v) => {
            collect_named_types(k, out);
            collect_named_types(v, out);
        }
        _ => {}
    }
}

/// Emit the Rust type name for a `TypeRef` using the standard identity mapping.
///
/// Produces valid Rust type syntax: `String`, `Vec<u8>`, `Option<T>`,
/// `HashMap<K, V>`, etc.  Named types pass through as-is — they must be in
/// scope at the call site (usually via a `use` import).
fn rust_type_name(ty: &crate::core::ir::TypeRef) -> String {
    use crate::codegen::type_mapper::{IdentityMapper, TypeMapper};
    IdentityMapper.map_type(ty)
}

/// Format a single Rust stub method with a correctly typed signature.
///
/// Emits `fn name(&self, _p0: T0, _p1: T1, ...) -> ReturnType { body }`.
/// Parameters use `_p{i}` names (underscore-prefixed to silence unused-variable
/// warnings) with explicit types so the impl block compiles.  The return type
/// arrow is emitted for every non-unit return type.  For `Result`-returning
/// methods (`error_type` is `Some`), the return type is `Result<T, error_type>`
/// and the body is `Ok(default_for_T)`.
///
/// For reference-returning methods (`returns_ref = true`), the IR collapses
/// `&[T]` into `Vec<T>` + flag.  Slice and string references use empty literals.
/// Other reference returns emit an explicit compile-time diagnostic because the
/// e2e stub cannot synthesize an owned backing value safely.
/// Emit a single method body inside a `impl Trait for Stub` block.
///
/// `crate_module`: when `Some`, used to qualify single-arg `Result<T>` return types
/// as `{crate_module}::Result<T>`.  Pass the crate root name (e.g. `"sample_core"`) when
/// the trait's return type uses a crate-level `Result` type alias rather than the
/// stdlib two-arg `Result<T, E>`.
fn emit_rust_stub_method(
    out: &mut String,
    method: &crate::core::ir::MethodDef,
    defaults: &dyn crate::codegen::defaults::LanguageDefaults,
    type_imports: &mut Vec<String>,
    crate_module: Option<&str>,
) {
    use crate::core::ir::TypeRef;
    use std::fmt::Write as FmtWrite;

    // Build the parameter list: `_p0: TypeName, _p1: TypeName, ...`
    // Underscore-prefix silences unused-variable warnings; explicit types are
    // required by the Rust compiler in trait impl method signatures.
    let params_typed: Vec<String> = method
        .params
        .iter()
        .enumerate()
        .map(|(i, param)| {
            // Collect named types referenced in this parameter for import tracking.
            collect_named_types(&param.ty, type_imports);
            // Emit `&T` for reference params (is_ref = true) to match the trait signature.
            // The IR stores the inner type without the `&`; we re-add it here.
            // Use idiomatic Rust slice/str types for common reference forms:
            //   &Vec<u8>       → &[u8]      (byte slices)
            //   &String        → &str       (string slices)
            //   &mut Vec<u8>   → &mut [u8]
            //   &mut String    → &mut str
            //   &T / &mut T    → &T / &mut T
            if param.is_ref {
                use crate::core::ir::TypeRef;
                let mut_kw = if param.is_mut { "mut " } else { "" };
                let ref_str = match &param.ty {
                    TypeRef::Bytes => format!("&{mut_kw}[u8]"),
                    TypeRef::String => format!("&{mut_kw}str"),
                    other => format!("&{}{}", mut_kw, rust_type_name(other)),
                };
                format!("_p{i}: {ref_str}")
            } else {
                let ty_str = rust_type_name(&param.ty);
                format!("_p{i}: {ty_str}")
            }
        })
        .collect();
    let params_str = if params_typed.is_empty() {
        String::new()
    } else {
        format!(", {}", params_typed.join(", "))
    };

    // Build the return type annotation.  Unit returns need no arrow; all others
    // get `-> ReturnType` or `-> Result<ReturnType, ErrorType>`.
    let return_type_str = if method.returns_ref {
        // Reference-returning methods: derive the reference return type from the IR.
        // The IR stores the owned form; map common owned types to their reference forms.
        //   Vec<u8>      → &[u8]
        //   Vec<String>  → &[&str]
        //   String       → &str
        //   Vec<T>       → &[T]
        //   T            → &T
        use crate::core::ir::TypeRef;
        let ref_type = match &method.return_type {
            TypeRef::String => "&str".to_string(),
            TypeRef::Bytes => "&[u8]".to_string(),
            TypeRef::Vec(inner) => match inner.as_ref() {
                TypeRef::String => "&[&str]".to_string(),
                TypeRef::Bytes => "&[u8]".to_string(),
                other => format!("&[{}]", rust_type_name(other)),
            },
            other => format!("&{}", rust_type_name(other)),
        };
        Some(ref_type)
    } else {
        match &method.return_type {
            TypeRef::Unit if method.error_type.is_none() => None,
            _ => {
                let base = rust_type_name(&method.return_type);
                collect_named_types(&method.return_type, type_imports);
                let full = if let Some(err) = &method.error_type {
                    // When `error_type` is `"anyhow::Error"` it signals the IR fallback
                    // for a single-arg `Result<T>` alias (like `sample_core::Result<T>`),
                    // not a literal `anyhow::Error` in the trait signature.
                    // Use `{crate}::Result<T>` so the stub method type matches the trait.
                    if err == "anyhow::Error" {
                        if let Some(module) = crate_module {
                            format!("{module}::Result<{base}>")
                        } else {
                            // No module context — keep the fallback form.
                            format!("Result<{base}, {err}>")
                        }
                    } else {
                        // Collect the error type name for import tracking only when it is a
                        // simple identifier (no path separators).  Fully-qualified names like
                        // `anyhow::Error` are already usable as-is in the signature without
                        // a `use` import; only bare names like `SampleCrateError` need one.
                        if !err.contains("::") {
                            type_imports.push(err.clone());
                        }
                        format!("Result<{base}, {err}>")
                    }
                } else {
                    base
                };
                Some(full)
            }
        }
    };

    // Build the method body.
    let body = if method.returns_ref {
        // Reference-returning methods: return the cheapest valid reference that
        // satisfies the return type without requiring a named binding.
        //   &str, &[u8], &[&str], &[T]  → use an empty literal (&[], "")
        //   &T (other)                   → emit an unsupported-generation diagnostic
        use crate::core::ir::TypeRef;
        match &method.return_type {
            TypeRef::String => "\"\"".to_string(),
            TypeRef::Bytes | TypeRef::Vec(_) => "&[]".to_string(),
            _ => format!(
                "compile_error!(\"alef cannot generate Rust e2e test_backend method `{}` because it returns an \
                 unsupported reference type\")",
                method.name
            ),
        }
    } else {
        let raw = match &method.return_type {
            TypeRef::Unit => "()".to_string(),
            _ => defaults.emit_default(&method.return_type),
        };
        if method.error_type.is_some() {
            format!("Ok({raw})")
        } else {
            raw
        }
    };

    let async_kw = if method.is_async { "async " } else { "" };
    let return_annotation = match &return_type_str {
        Some(rt) => format!(" -> {rt}"),
        None => String::new(),
    };
    let _ = writeln!(
        out,
        "    {async_kw}fn {name}(&self{params_str}){return_annotation} {{ {body} }}",
        name = method.name
    );
}

/// Convert a fixture ID (snake_case) to PascalCase for use in Rust struct names.
///
/// Transforms `register_embedding_backend_trait_bridge` → `RegisterEmbeddingBackendTraitBridge`.
fn fixture_id_to_pascal_case(id: &str) -> String {
    id.split('_')
        .map(|word| {
            let mut chars = word.chars();
            match chars.next() {
                None => String::new(),
                Some(first) => first.to_uppercase().to_string() + chars.as_str(),
            }
        })
        .collect()
}

/// Extract a backend name string from the fixture input JSON.
///
/// Searches the top-level input object for the first string value at any depth
/// under keys commonly used for names (`name`, or the first string field found).
/// Falls back to the fixture id when no string is found.
fn extract_backend_name_from_input(input: &serde_json::Value, fallback: &str) -> String {
    // Walk the top-level object, then one level deeper, looking for "name".
    if let Some(obj) = input.as_object() {
        // Direct "name" key.
        if let Some(s) = obj.get("name").and_then(|v| v.as_str()) {
            return s.to_string();
        }
        // One level deeper in any nested object.
        for v in obj.values() {
            if let Some(inner) = v.as_object()
                && let Some(s) = inner.get("name").and_then(|v| v.as_str())
            {
                return s.to_string();
            }
        }
        // First string value at the top level.
        for v in obj.values() {
            if let Some(s) = v.as_str() {
                return s.to_string();
            }
        }
    }
    fallback.to_string()
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

/// Build a minimal `MethodDef` for use in unit tests.
#[cfg(test)]
fn test_method(
    name: &str,
    return_type: crate::core::ir::TypeRef,
    is_async: bool,
    error_type: Option<&str>,
) -> crate::core::ir::MethodDef {
    crate::core::ir::MethodDef {
        name: name.to_string(),
        params: Vec::new(),
        return_type,
        is_async,
        is_static: false,
        error_type: error_type.map(str::to_string),
        doc: String::new(),
        receiver: Some(crate::core::ir::ReceiverKind::Ref),
        cfg: None,
        sanitized: false,
        trait_source: None,
        returns_ref: false,
        returns_cow: false,
        return_newtype_wrapper: None,
        has_default_impl: false,
        binding_excluded: false,
        binding_exclusion_reason: None,
        version: Default::default(),
    }
}

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

    fn make_fixture(id: &str, input: serde_json::Value) -> crate::e2e::fixture::Fixture {
        serde_json::from_value(serde_json::json!({
            "id": id,
            "description": "test fixture",
            "input": input,
            "assertions": []
        }))
        .expect("minimal fixture JSON must parse")
    }

    #[test]
    fn resolve_crate_name_uses_config_name() {
        use crate::core::config::NewAlefConfig;
        let cfg: NewAlefConfig = toml::from_str(
            r#"
[workspace]
languages = ["rust"]

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

[crates.e2e]
fixtures = "fixtures"
output = "e2e"
[crates.e2e.call]
function = "process"
module = "my_lib"
result_var = "result"
"#,
        )
        .unwrap();
        let e2e = cfg.crates[0].e2e.clone().unwrap();
        let resolved = cfg.resolve().unwrap().remove(0);
        let name = resolve_crate_name(&e2e, &resolved);
        assert_eq!(name, "my-lib");
    }

    #[test]
    fn snippet_body_matches_rust_client_json_and_async_rendering() {
        use crate::core::config::NewAlefConfig;
        use crate::e2e::codegen::E2eCodegen;

        let cfg: NewAlefConfig = toml::from_str(
            r#"
[workspace]
languages = ["rust"]
[[crates]]
name = "example-core"
sources = ["src/lib.rs"]
[crates.e2e]
fixtures = "fixtures"
[crates.e2e.call]
function = "chat"
module = "example_core"
async = true
args = [{ name = "request", field = "input", type = "json_object", owned = true }]
[crates.e2e.call.overrides.rust]
client_factory = "create_client"
options_type = "ChatRequest"
"#,
        )
        .expect("snippet config must parse");
        let e2e = cfg.crates[0].e2e.clone().expect("e2e config");
        let resolved = cfg.resolve().expect("config resolves").remove(0);
        let fixture: Fixture = serde_json::from_value(serde_json::json!({
            "id": "client_chat",
            "description": "send a request",
            "input": {"model": "example-model", "url": "$mock_url/guide", "messages": []},
            "mock_response": {"status": 200},
            "docs": {
                "topic": "guides",
                "presentation": {
                    "input": {"model": "example-model", "url": "https://api.example.com/guide", "messages": []},
                    "operations": [{"op": "show", "path": "message"}]
                }
            },
            "assertions": [{"type": "not_error"}]
        }))
        .expect("fixture must parse");

        let rendered = RustE2eCodegen
            .render_snippet_body(&fixture, &e2e, &resolved, &[], &[])
            .expect("snippet renders");

        assert!(rendered.contains("let request: ChatRequest"), "{rendered}");
        assert!(rendered.contains("example_core::create_client"), "{rendered}");
        assert!(rendered.contains("client.chat(request).await"), "{rendered}");
        assert!(rendered.contains(".await.expect(\"call failed\")"), "{rendered}");
        assert!(rendered.contains("println!(\"{:?}\", result.message);"), "{rendered}");
        assert!(rendered.contains("#[tokio::main]"), "{rendered}");
        assert!(!rendered.contains("#[tokio::test]"), "{rendered}");
        assert!(!rendered.contains("fn test_"), "{rendered}");
        assert!(rendered.contains("https://api.example.com/guide"), "{rendered}");
        assert!(!rendered.contains("MOCK_SERVER"), "{rendered}");
        assert!(!rendered.contains("E2E_ALLOW_PRIVATE_NETWORK"), "{rendered}");
        assert!(!rendered.contains("$mock_url"), "{rendered}");
    }

    #[test]
    fn successful_snippet_binds_and_displays_the_call_result() {
        use crate::e2e::codegen::E2eCodegen;

        let fixture = make_fixture("list_widgets", serde_json::Value::Null);
        let mut e2e = crate::e2e::config::E2eConfig::default();
        e2e.call.function = "list_widgets".into();
        e2e.call.result_var = "widgets".into();

        let rendered = RustE2eCodegen
            .render_snippet_body(&fixture, &e2e, &ResolvedCrateConfig::default(), &[], &[])
            .expect("Rust snippet renders");

        assert!(rendered.contains("let widgets = list_widgets()"), "{rendered}");
        assert!(rendered.contains("println!(\"{:?}\", widgets)"), "{rendered}");
        assert!(!rendered.contains("let _ = list_widgets()"), "{rendered}");
        assert!(
            !rendered.contains("match widgets {"),
            "a fixture with no error assertion must not get the error branch:\n{rendered}"
        );
    }

    #[test]
    fn error_fixture_snippet_matches_the_result_instead_of_panicking() {
        use crate::e2e::codegen::E2eCodegen;

        let fixture: Fixture = serde_json::from_value(serde_json::json!({
            "id": "rate_limit_429",
            "description": "Surface a rate-limit failure",
            "input": null,
            "assertions": [{"type": "error"}]
        }))
        .expect("fixture must parse");
        let mut e2e = crate::e2e::config::E2eConfig::default();
        e2e.call.function = "chat".into();
        e2e.call.result_var = "result".into();

        let rendered = RustE2eCodegen
            .render_snippet_body(&fixture, &e2e, &ResolvedCrateConfig::default(), &[], &[])
            .expect("Rust snippet renders");

        assert!(rendered.contains("let result = chat()"), "{rendered}");
        assert!(rendered.contains("match result {"), "{rendered}");
        assert!(
            rendered.contains("Ok(value) => println!(\"{:?}\", value),"),
            "{rendered}"
        );
        assert!(rendered.contains("Err(error) => println!(\"{error}\"),"), "{rendered}");
        assert!(
            !rendered.contains(".expect(\"call failed\")"),
            "the error branch must not panic on the failure it documents:\n{rendered}"
        );
        assert!(
            !rendered.contains("println!(\"{:?}\", result);"),
            "the moved result must not be printed after the match:\n{rendered}"
        );
    }

    /// Pins that a `client_factory` fixture's Rust documentation snippet reads its credential
    /// via `std::env::var(...)` — the substitution `render_snippet_body` applies over the
    /// harness's hardcoded `"test-key".to_string()` literal (mod.rs ~line 220-229) — and never
    /// carries the e2e mock-server env vars, fixture route, or literal credential.
    #[test]
    fn client_factory_snippet_never_points_the_reader_at_the_mock_server() {
        use crate::core::config::NewAlefConfig;
        use crate::e2e::codegen::E2eCodegen;

        let cfg: NewAlefConfig = toml::from_str(
            r#"
[workspace]
languages = ["rust"]
[[crates]]
name = "sample-core"
sources = ["src/lib.rs"]
[crates.e2e]
fixtures = "fixtures"
[crates.e2e.call]
function = "chat"
result_var = "result"
[crates.e2e.call.overrides.rust]
client_factory = "create_client"
"#,
        )
        .expect("snippet config must parse");
        let e2e = cfg.crates[0].e2e.clone().expect("e2e config");
        let resolved = cfg.resolve().expect("config resolves").remove(0);
        let fixture: Fixture = serde_json::from_value(serde_json::json!({
            "id": "rate_limit_429",
            "description": "Rate limited",
            "input": null,
            "mock_response": {"status": 429}
        }))
        .expect("fixture must parse");

        let rendered = RustE2eCodegen
            .render_snippet_body(&fixture, &e2e, &resolved, &[], &[])
            .expect("Rust snippet renders");

        assert!(
            !rendered.contains("MOCK_SERVER"),
            "mock-server env var leaked:\n{rendered}"
        );
        assert!(
            !rendered.contains("/fixtures/rate_limit_429"),
            "mock-server fixture route leaked:\n{rendered}"
        );
        assert!(
            !rendered.contains("\"test-key\""),
            "literal credential leaked:\n{rendered}"
        );
        assert!(
            rendered.contains("std::env::var(\"API_KEY\").expect(\"API_KEY must be set\")"),
            "credential is not read from the environment:\n{rendered}"
        );
        assert!(
            rendered.contains(
                "sample_core::create_client(std::env::var(\"API_KEY\").expect(\"API_KEY must be set\"), \
                 None, None, None, None).unwrap();"
            ),
            "client is not constructed the way a reader would:\n{rendered}"
        );
    }

    #[test]
    fn raw_literal_handles_backticks_and_blank_line_after_fence() {
        let input = "<pre><code>```rust\nlet value = r#\"sample\"#;\n```\n\nnext</code></pre>";
        let literal = crate::e2e::escape::rust_raw_string(input);
        let expression = syn::parse_str::<syn::Expr>(&literal).expect("generated raw literal parses");
        assert!(matches!(expression, syn::Expr::Lit(_)), "{literal}");
        assert!(literal.starts_with("r##\""), "{literal}");
    }

    #[test]
    fn snippet_extraction_preserves_multiline_raw_literal_contents() {
        let rendered = concat!(
            "use sample::process;\n",
            "\n",
            "fn test_multiline() {\n",
            "    let source = r#\"# A comment\n",
            "def greet(name):\n",
            "    return name\n",
            "\n",
            "import os\n",
            "\"#;\n",
            "    let _ = process(source);\n",
            "}\n",
            "}\n",
        );

        let (_, body, _) = extract_rust_snippet(rendered).expect("snippet extracts");
        let body = body.join("\n");

        assert!(body.contains("def greet(name):"), "{body}");
        assert!(body.contains("import os"), "{body}");
        assert!(body.contains("\ndef greet(name):"), "{body}");
        assert!(!body.lines().any(|line| line == "}"), "{body}");
        syn::parse_file(&format!("fn main() {{\n{body}\n}}")).expect("generated snippet body parses");
    }

    #[test]
    fn snippet_extraction_survives_a_bare_closing_brace_inside_a_raw_string() {
        let rendered = concat!(
            "use sample::process;\n",
            "\n",
            "fn test_brace_in_literal() {\n",
            "    let source = r#\"fn example() {\n",
            "}\n",
            "let after = 1;\n",
            "\"#;\n",
            "    let _ = process(source);\n",
            "}\n",
        );

        let (_, body, _) = extract_rust_snippet(rendered).expect("snippet extracts");
        let body = body.join("\n");

        assert!(body.contains("fn example() {"), "{body}");
        assert!(body.contains("let after = 1;"), "{body}");
        assert!(body.contains("let _ = process(source);"), "{body}");
    }

    #[test]
    fn emit_test_backend_rust_generates_struct_and_arc_expr() {
        use crate::core::config::TraitBridgeConfig;
        use crate::core::ir::TypeRef;

        let bridge = TraitBridgeConfig {
            trait_name: "TestTrait".to_string(),
            super_trait: Some("Plugin".to_string()),
            register_fn: Some("register_test_trait".to_string()),
            ..Default::default()
        };

        let m1 = test_method("do_work", TypeRef::String, false, None);
        let m2 = test_method(
            "process_async",
            TypeRef::Named("WorkResult".to_string()),
            true,
            Some("WorkError"),
        );
        let methods = [&m1, &m2];

        let fixture = make_fixture("my_test_fixture", serde_json::json!({ "name": "my-test-backend" }));

        let emission = emit_test_backend(&bridge, &methods, &fixture);

        // setup_block must contain the stub struct and impl.
        assert!(
            emission.setup_block.contains("TestStubMyTestFixture"),
            "setup_block should contain stub name, got: {}",
            emission.setup_block
        );
        assert!(
            emission.setup_block.contains("TestTrait"),
            "setup_block should reference trait by name, got: {}",
            emission.setup_block
        );
        // Must NOT hardcode any sample_core-domain trait name.
        assert!(
            !emission.setup_block.contains("OcrBackend"),
            "setup_block must not hardcode OcrBackend"
        );
        assert!(
            !emission.setup_block.contains("DocumentExtractor"),
            "setup_block must not hardcode DocumentExtractor"
        );

        // name() emitted because super_trait is Some.
        assert!(
            emission.setup_block.contains("fn name("),
            "setup_block should emit name() when super_trait is set"
        );

        // Required methods emitted.
        assert!(
            emission.setup_block.contains("fn do_work("),
            "required method do_work should be in setup_block"
        );
        assert!(
            emission.setup_block.contains("fn process_async("),
            "required async method process_async should be in setup_block"
        );

        // arg_expr wraps in Arc::new.
        assert!(
            emission.arg_expr.contains("Arc::new"),
            "arg_expr should use Arc::new, got: {}",
            emission.arg_expr
        );
        assert!(
            emission.arg_expr.contains("TestStubMyTestFixture"),
            "arg_expr should reference stub struct, got: {}",
            emission.arg_expr
        );
    }

    #[test]
    fn emit_test_backend_rust_skips_default_impl_methods() {
        use crate::core::config::TraitBridgeConfig;
        use crate::core::ir::TypeRef;

        let bridge = TraitBridgeConfig {
            trait_name: "TestTrait".to_string(),
            ..Default::default()
        };

        let required = test_method("required_method", TypeRef::String, false, None);
        let mut optional = test_method("optional_method", TypeRef::String, false, None);
        optional.has_default_impl = true;
        let methods = [&required, &optional];

        let fixture = make_fixture("skip_defaults_fixture", serde_json::json!({}));
        let emission = emit_test_backend(&bridge, &methods, &fixture);

        assert!(
            emission.setup_block.contains("fn required_method("),
            "required method should be emitted"
        );
        assert!(
            !emission.setup_block.contains("fn optional_method("),
            "method with default impl should be skipped"
        );
    }

    #[test]
    fn emit_test_backend_rust_name_extracted_from_input() {
        use crate::core::config::TraitBridgeConfig;

        let bridge = TraitBridgeConfig {
            trait_name: "TestTrait".to_string(),
            super_trait: Some("Plugin".to_string()),
            ..Default::default()
        };

        let fixture = make_fixture(
            "name_extraction_fixture",
            serde_json::json!({ "backend": { "name": "extracted-name" } }),
        );

        let emission = emit_test_backend(&bridge, &[], &fixture);

        assert!(
            emission.arg_expr.contains("extracted-name"),
            "arg_expr should contain the name from input.backend.name, got: {}",
            emission.arg_expr
        );
    }

    /// The stub's `Result<_, E>` and its `use` import both come from the method's own
    /// `error_type`. Emitting any other `*Error` the crate happens to declare produces an
    /// unresolvable import (E0432) because module-private error types are not re-exported.
    #[test]
    fn emit_test_backend_rust_pins_error_type_to_the_method_signature() {
        use crate::core::config::TraitBridgeConfig;
        use crate::core::ir::TypeRef;

        let bridge = TraitBridgeConfig {
            trait_name: "TestTrait".to_string(),
            super_trait: Some("Plugin".to_string()),
            ..Default::default()
        };

        let method = test_method(
            "embed",
            TypeRef::Vec(Box::new(TypeRef::String)),
            true,
            Some("SampleCrateError"),
        );
        let methods = [&method];

        let fixture = make_fixture("error_type_fixture", serde_json::json!({ "name": "backend" }));
        let emission = emit_test_backend(&bridge, &methods, &fixture);

        assert!(
            emission
                .setup_block
                .contains("async fn embed(&self) -> Result<Vec<String>, SampleCrateError>"),
            "stub signature must use the method's declared error type, got: {}",
            emission.setup_block
        );
        assert!(
            emission.type_imports.contains(&"SampleCrateError".to_string()),
            "the declared error type must be imported, got: {:?}",
            emission.type_imports
        );
        assert_eq!(
            emission
                .type_imports
                .iter()
                .filter(|import| import.ends_with("Error"))
                .collect::<Vec<_>>(),
            vec![&"SampleCrateError".to_string()],
            "no error type other than the declared one may be imported, got: {:?}",
            emission.type_imports
        );
    }

    /// A single-argument `Result<T>` alias reaches the emitter as the `anyhow::Error` sentinel and
    /// must render as the crate's own `Result` alias, never as a bare `anyhow::Error` import.
    #[test]
    fn emit_test_backend_rust_renders_alias_result_through_the_crate_module() {
        use crate::core::config::TraitBridgeConfig;
        use crate::core::ir::TypeRef;

        let bridge = TraitBridgeConfig {
            trait_name: "TestTrait".to_string(),
            super_trait: Some("sample_core::plugins::Plugin".to_string()),
            ..Default::default()
        };

        let method = test_method("validate", TypeRef::Unit, true, Some("anyhow::Error"));
        let methods = [&method];

        let fixture = make_fixture("alias_result_fixture", serde_json::json!({ "name": "backend" }));
        let emission = emit_test_backend(&bridge, &methods, &fixture);

        assert!(
            emission
                .setup_block
                .contains("async fn validate(&self) -> sample_core::Result<()>"),
            "single-arg Result alias must render through the crate module, got: {}",
            emission.setup_block
        );
        assert!(
            !emission.type_imports.iter().any(|import| import.contains("Error")),
            "the alias sentinel must not become an error-type import, got: {:?}",
            emission.type_imports
        );
    }
}