alef-codegen 0.15.19

Shared codegen utilities for the alef polyglot binding generator
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
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
use ahash::AHashSet;
use alef_core::ir::{ErrorDef, ErrorVariant};

use crate::conversions::is_tuple_variant;

/// Generate a wildcard match pattern for an error variant.
/// Struct variants use `{ .. }`, tuple variants use `(..)`, unit variants have no suffix.
fn error_variant_wildcard_pattern(rust_path: &str, variant: &ErrorVariant) -> String {
    if variant.is_unit {
        format!("{rust_path}::{}", variant.name)
    } else if is_tuple_variant(&variant.fields) {
        format!("{rust_path}::{}(..)", variant.name)
    } else {
        format!("{rust_path}::{} {{ .. }}", variant.name)
    }
}

/// Python builtin exception names that must not be shadowed (A004 compliance).
const PYTHON_BUILTIN_EXCEPTIONS: &[&str] = &[
    "ConnectionError",
    "TimeoutError",
    "PermissionError",
    "FileNotFoundError",
    "ValueError",
    "TypeError",
    "RuntimeError",
    "OSError",
    "IOError",
    "KeyError",
    "IndexError",
    "AttributeError",
    "ImportError",
    "MemoryError",
    "OverflowError",
    "StopIteration",
    "RecursionError",
    "SystemError",
    "ReferenceError",
    "BufferError",
    "EOFError",
    "LookupError",
    "ArithmeticError",
    "AssertionError",
    "BlockingIOError",
    "BrokenPipeError",
    "ChildProcessError",
    "FileExistsError",
    "InterruptedError",
    "IsADirectoryError",
    "NotADirectoryError",
    "ProcessLookupError",
    "UnicodeError",
];

/// Compute a prefix from the error type name by stripping a trailing "Error" suffix.
/// E.g. `"CrawlError"` -> `"Crawl"`, `"MyException"` -> `"MyException"`.
fn error_base_prefix(error_name: &str) -> &str {
    error_name.strip_suffix("Error").unwrap_or(error_name)
}

/// Return the Python exception name for a variant, avoiding shadowing of Python builtins.
///
/// 1. Appends `"Error"` suffix if not already present (N818 compliance).
/// 2. If the resulting name shadows a Python builtin, prefixes it with the error type's base
///    name. E.g. for `CrawlError::Connection` -> `ConnectionError` (shadowed) -> `CrawlConnectionError`.
pub fn python_exception_name(variant_name: &str, error_name: &str) -> String {
    let candidate = if variant_name.ends_with("Error") {
        variant_name.to_string()
    } else {
        format!("{}Error", variant_name)
    };

    if PYTHON_BUILTIN_EXCEPTIONS.contains(&candidate.as_str()) {
        let prefix = error_base_prefix(error_name);
        // Avoid double-prefixing if the candidate already starts with the prefix
        if candidate.starts_with(prefix) {
            candidate
        } else {
            format!("{}{}", prefix, candidate)
        }
    } else {
        candidate
    }
}

/// Generate `pyo3::create_exception!` macros for each error variant plus the base error type.
/// Appends "Error" suffix to variant names that don't already have it (N818 compliance).
/// Prefixes names that would shadow Python builtins (A004 compliance).
pub fn gen_pyo3_error_types(error: &ErrorDef, module_name: &str, seen_exceptions: &mut AHashSet<String>) -> String {
    // Pre-compute variant names that haven't been seen yet
    let mut variant_names = Vec::new();
    for variant in &error.variants {
        let variant_name = python_exception_name(&variant.name, &error.name);
        if seen_exceptions.insert(variant_name.clone()) {
            variant_names.push(variant_name);
        }
    }

    // Check if base error hasn't been seen
    let include_base = seen_exceptions.insert(error.name.clone());

    crate::template_env::render(
        "error_gen/pyo3_error_types.jinja",
        minijinja::context! {
            variant_names => variant_names,
            module_name => module_name,
            error_name => error.name.as_str(),
            include_base => include_base,
        },
    )
}

/// Generate a `to_py_err` converter function that maps each Rust error variant to a Python exception.
/// Uses Error-suffixed names for variant exceptions (N818 compliance).
pub fn gen_pyo3_error_converter(error: &ErrorDef, core_import: &str) -> String {
    let rust_path = if error.rust_path.is_empty() {
        format!("{core_import}::{}", error.name)
    } else {
        let normalized = error.rust_path.replace('-', "_");
        // Paths with more than 2 segments (e.g. `mylib_core::di::error::DependencyError`)
        // reference private internal modules that are not accessible from generated binding code.
        // Fall back to the public re-export form `{crate}::{ErrorName}` (2 segments).
        let segments: Vec<&str> = normalized.split("::").collect();
        if segments.len() > 2 {
            let crate_name = segments[0];
            let error_name = segments[segments.len() - 1];
            format!("{crate_name}::{error_name}")
        } else {
            normalized
        }
    };

    let fn_name = format!("{}_to_py_err", to_snake_case(&error.name));

    // Pre-compute variants as (pattern, exc_name) tuples
    let mut variants = Vec::new();
    for variant in &error.variants {
        let pattern = error_variant_wildcard_pattern(&rust_path, variant);
        let variant_exc_name = python_exception_name(&variant.name, &error.name);
        variants.push((pattern, variant_exc_name));
    }

    crate::template_env::render(
        "error_gen/pyo3_error_converter.jinja",
        minijinja::context! {
            rust_path => rust_path.as_str(),
            fn_name => fn_name.as_str(),
            error_name => error.name.as_str(),
            variants => variants,
        },
    )
}

/// Generate `m.add(...)` registration calls for each exception type.
/// Uses Error-suffixed names for variant exceptions (N818 compliance).
/// Prefixes names that would shadow Python builtins (A004 compliance).
pub fn gen_pyo3_error_registration(error: &ErrorDef, seen_registrations: &mut AHashSet<String>) -> Vec<String> {
    let mut registrations = Vec::with_capacity(error.variants.len() + 1);

    for variant in &error.variants {
        let variant_exc_name = python_exception_name(&variant.name, &error.name);
        if seen_registrations.insert(variant_exc_name.clone()) {
            registrations.push(format!(
                "    m.add(\"{}\", m.py().get_type::<{}>())?;",
                variant_exc_name, variant_exc_name
            ));
        }
    }

    // Base exception
    if seen_registrations.insert(error.name.clone()) {
        registrations.push(format!(
            "    m.add(\"{}\", m.py().get_type::<{}>())?;",
            error.name, error.name
        ));
    }

    registrations
}

/// Return the converter function name for a given error type.
pub fn converter_fn_name(error: &ErrorDef) -> String {
    format!("{}_to_py_err", to_snake_case(&error.name))
}

/// Simple CamelCase to snake_case conversion.
fn to_snake_case(s: &str) -> String {
    let mut result = String::with_capacity(s.len() + 4);
    for (i, c) in s.chars().enumerate() {
        if c.is_uppercase() {
            if i > 0 {
                result.push('_');
            }
            result.push(c.to_ascii_lowercase());
        } else {
            result.push(c);
        }
    }
    result
}

// ---------------------------------------------------------------------------
// NAPI (Node.js) error generation
// ---------------------------------------------------------------------------

/// Generate a `JsError` enum with string constants for each error variant name.
pub fn gen_napi_error_types(error: &ErrorDef) -> String {
    // Pre-compute (const_name, variant_name) pairs
    let mut variants = Vec::new();
    let error_screaming = to_screaming_snake(&error.name);
    for variant in &error.variants {
        let variant_const = format!("{}_ERROR_{}", error_screaming, to_screaming_snake(&variant.name));
        variants.push((variant_const, variant.name.clone()));
    }

    crate::template_env::render(
        "error_gen/napi_error_types.jinja",
        minijinja::context! {
            variants => variants,
        },
    )
}

/// Generate a converter function that maps a core error to `napi::Error`.
pub fn gen_napi_error_converter(error: &ErrorDef, core_import: &str) -> String {
    let rust_path = if error.rust_path.is_empty() {
        format!("{core_import}::{}", error.name)
    } else {
        error.rust_path.replace('-', "_")
    };

    let fn_name = format!("{}_to_napi_err", to_snake_case(&error.name));

    // Pre-compute (pattern, variant_name) pairs
    let mut variants = Vec::new();
    for variant in &error.variants {
        let pattern = error_variant_wildcard_pattern(&rust_path, variant);
        variants.push((pattern, variant.name.clone()));
    }

    crate::template_env::render(
        "error_gen/napi_error_converter.jinja",
        minijinja::context! {
            rust_path => rust_path.as_str(),
            fn_name => fn_name.as_str(),
            variants => variants,
        },
    )
}

/// Return the NAPI converter function name for a given error type.
pub fn napi_converter_fn_name(error: &ErrorDef) -> String {
    format!("{}_to_napi_err", to_snake_case(&error.name))
}

// ---------------------------------------------------------------------------
// WASM (wasm-bindgen) error generation
// ---------------------------------------------------------------------------

/// Generate a converter function that maps a core error to a `JsValue` object
/// with `code` (string) and `message` (string) fields, plus a private
/// `error_code` helper that returns the variant code string.
pub fn gen_wasm_error_converter(error: &ErrorDef, core_import: &str) -> String {
    let rust_path = if error.rust_path.is_empty() {
        format!("{core_import}::{}", error.name)
    } else {
        error.rust_path.replace('-', "_")
    };

    let fn_name = format!("{}_to_js_value", to_snake_case(&error.name));
    let code_fn_name = format!("{}_error_code", to_snake_case(&error.name));

    // Pre-compute variants for error_code helper: (pattern, code) pairs
    let mut code_variants = Vec::new();
    for variant in &error.variants {
        let pattern = error_variant_wildcard_pattern(&rust_path, variant);
        let code = to_snake_case(&variant.name);
        code_variants.push((pattern, code));
    }
    let default_code = to_snake_case(&error.name);

    let code_fn = crate::template_env::render(
        "error_gen/wasm_error_code_fn.jinja",
        minijinja::context! {
            rust_path => rust_path.as_str(),
            code_fn_name => code_fn_name.as_str(),
            variants => code_variants,
            default_code => default_code.as_str(),
        },
    );

    let converter_fn = crate::template_env::render(
        "error_gen/wasm_error_converter.jinja",
        minijinja::context! {
            rust_path => rust_path.as_str(),
            fn_name => fn_name.as_str(),
            code_fn_name => code_fn_name.as_str(),
        },
    );

    format!("{}\n\n{}", code_fn, converter_fn)
}

/// Return the WASM converter function name for a given error type.
pub fn wasm_converter_fn_name(error: &ErrorDef) -> String {
    format!("{}_to_js_value", to_snake_case(&error.name))
}

// ---------------------------------------------------------------------------
// PHP (ext-php-rs) error generation
// ---------------------------------------------------------------------------

/// Generate a converter function that maps a core error to `PhpException`.
pub fn gen_php_error_converter(error: &ErrorDef, core_import: &str) -> String {
    let rust_path = if error.rust_path.is_empty() {
        format!("{core_import}::{}", error.name)
    } else {
        error.rust_path.replace('-', "_")
    };

    let fn_name = format!("{}_to_php_err", to_snake_case(&error.name));

    // Pre-compute (pattern, variant_name) pairs
    let mut variants = Vec::new();
    for variant in &error.variants {
        let pattern = error_variant_wildcard_pattern(&rust_path, variant);
        variants.push((pattern, variant.name.clone()));
    }

    crate::template_env::render(
        "error_gen/php_error_converter.jinja",
        minijinja::context! {
            rust_path => rust_path.as_str(),
            fn_name => fn_name.as_str(),
            variants => variants,
        },
    )
}

/// Return the PHP converter function name for a given error type.
pub fn php_converter_fn_name(error: &ErrorDef) -> String {
    format!("{}_to_php_err", to_snake_case(&error.name))
}

// ---------------------------------------------------------------------------
// Magnus (Ruby) error generation
// ---------------------------------------------------------------------------

/// Generate a converter function that maps a core error to `magnus::Error`.
pub fn gen_magnus_error_converter(error: &ErrorDef, core_import: &str) -> String {
    let rust_path = if error.rust_path.is_empty() {
        format!("{core_import}::{}", error.name)
    } else {
        error.rust_path.replace('-', "_")
    };

    let fn_name = format!("{}_to_magnus_err", to_snake_case(&error.name));

    crate::template_env::render(
        "error_gen/magnus_error_converter.jinja",
        minijinja::context! {
            rust_path => rust_path.as_str(),
            fn_name => fn_name.as_str(),
        },
    )
}

/// Return the Magnus converter function name for a given error type.
pub fn magnus_converter_fn_name(error: &ErrorDef) -> String {
    format!("{}_to_magnus_err", to_snake_case(&error.name))
}

// ---------------------------------------------------------------------------
// Rustler (Elixir) error generation
// ---------------------------------------------------------------------------

/// Generate a converter function that maps a core error to a Rustler error tuple `{:error, reason}`.
pub fn gen_rustler_error_converter(error: &ErrorDef, core_import: &str) -> String {
    let rust_path = if error.rust_path.is_empty() {
        format!("{core_import}::{}", error.name)
    } else {
        error.rust_path.replace('-', "_")
    };

    let fn_name = format!("{}_to_rustler_err", to_snake_case(&error.name));

    crate::template_env::render(
        "error_gen/rustler_error_converter.jinja",
        minijinja::context! {
            rust_path => rust_path.as_str(),
            fn_name => fn_name.as_str(),
        },
    )
}

/// Return the Rustler converter function name for a given error type.
pub fn rustler_converter_fn_name(error: &ErrorDef) -> String {
    format!("{}_to_rustler_err", to_snake_case(&error.name))
}

// ---------------------------------------------------------------------------
// FFI (C) error code generation
// ---------------------------------------------------------------------------

/// Generate a C enum of error codes plus an error-message function declaration.
///
/// Produces a `typedef enum` with `PREFIX_ERROR_NONE = 0` followed by one entry
/// per variant, plus a function that returns the default message for a given code.
pub fn gen_ffi_error_codes(error: &ErrorDef) -> String {
    let prefix = to_screaming_snake(&error.name);
    let prefix_lower = to_snake_case(&error.name);

    // Pre-compute (variant_screaming, index) pairs
    let mut variant_variants = Vec::new();
    for (i, variant) in error.variants.iter().enumerate() {
        let variant_screaming = to_screaming_snake(&variant.name);
        variant_variants.push((variant_screaming, (i + 1).to_string()));
    }

    crate::template_env::render(
        "error_gen/ffi_error_codes.jinja",
        minijinja::context! {
            error_name => error.name.as_str(),
            prefix => prefix.as_str(),
            prefix_lower => prefix_lower.as_str(),
            variant_variants => variant_variants,
        },
    )
}

// ---------------------------------------------------------------------------
// Go error type generation
// ---------------------------------------------------------------------------

/// Generate Go sentinel errors and a structured error type for an `ErrorDef`.
///
/// `pkg_name` is the Go package name (e.g. `"literllm"`). When the error struct
/// name starts with the package name (case-insensitively), the package-name
/// prefix is stripped to avoid the revive `exported` stutter lint error
/// (e.g. `LiterLlmError` in package `literllm` → exported as `Error`).
pub fn gen_go_error_types(error: &ErrorDef, pkg_name: &str) -> String {
    let sentinels = gen_go_sentinel_errors(std::slice::from_ref(error));
    let structured = gen_go_error_struct(error, pkg_name);
    format!("{}\n\n{}", sentinels, structured)
}

/// Generate a single consolidated `var (...)` block of Go sentinel errors
/// across multiple `ErrorDef`s.
///
/// When the same variant name appears in more than one `ErrorDef` (e.g. both
/// `GraphQLError` and `SchemaError` define `ValidationError`), the colliding
/// const names are disambiguated by prefixing with the parent error type's
/// stripped base name. For example, `GraphQLError::ValidationError` and
/// `SchemaError::ValidationError` become `ErrGraphQLValidationError` and
/// `ErrSchemaValidationError`. Variant names that are unique across all
/// errors are emitted as plain `Err{Variant}` consts.
pub fn gen_go_sentinel_errors(errors: &[ErrorDef]) -> String {
    if errors.is_empty() {
        return String::new();
    }
    let mut variant_counts: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();
    for err in errors {
        for v in &err.variants {
            *variant_counts.entry(v.name.as_str()).or_insert(0) += 1;
        }
    }
    let mut seen = std::collections::HashSet::new();
    let mut sentinels = Vec::new();
    for err in errors {
        let parent_base = error_base_prefix(&err.name);
        for variant in &err.variants {
            let collides = variant_counts.get(variant.name.as_str()).copied().unwrap_or(0) > 1;
            let const_name = if collides {
                format!("Err{}{}", parent_base, variant.name)
            } else {
                format!("Err{}", variant.name)
            };
            if !seen.insert(const_name.clone()) {
                continue;
            }
            let msg = variant_display_message(variant);
            sentinels.push((const_name, msg));
        }
    }

    crate::template_env::render(
        "error_gen/go_sentinel_errors.jinja",
        minijinja::context! {
            sentinels => sentinels,
        },
    )
}

/// Generate the structured error type (struct + Error() method) for a single
/// error definition. Sentinel errors are emitted separately by
/// [`gen_go_sentinel_errors`].
pub fn gen_go_error_struct(error: &ErrorDef, pkg_name: &str) -> String {
    let go_type_name = strip_package_prefix(&error.name, pkg_name);

    crate::template_env::render(
        "error_gen/go_error_struct.jinja",
        minijinja::context! {
            go_type_name => go_type_name.as_str(),
        },
    )
}

/// Strip the package-name prefix from a type name to avoid revive's stutter lint.
///
/// Revive reports `exported: type name will be used as pkg.PkgFoo by other packages,
/// and that stutters` when a type name begins with the package name. This function
/// removes the prefix when it matches (case-insensitively) so that the exported name
/// does not repeat the package name.
///
/// Examples:
/// - `("LiterLlmError", "literllm")` → `"Error"` (lowercased `literllm` is a prefix
///   of lowercased `literllmerror`)
/// - `("ConversionError", "converter")` → `"ConversionError"` (no match)
fn strip_package_prefix(type_name: &str, pkg_name: &str) -> String {
    let type_lower = type_name.to_lowercase();
    let pkg_lower = pkg_name.to_lowercase();
    if type_lower.starts_with(&pkg_lower) && type_lower.len() > pkg_lower.len() {
        // Retain the original casing for the suffix part.
        type_name[pkg_lower.len()..].to_string()
    } else {
        type_name.to_string()
    }
}

// ---------------------------------------------------------------------------
// Java error type generation
// ---------------------------------------------------------------------------

/// Generate Java exception sub-classes for each error variant.
///
/// Returns a `Vec` of `(class_name, file_content)` tuples: the base exception
/// class followed by one per-variant exception.  The caller writes each to a
/// separate `.java` file.
pub fn gen_java_error_types(error: &ErrorDef, package: &str) -> Vec<(String, String)> {
    let mut files = Vec::with_capacity(error.variants.len() + 1);

    // Base exception class
    let base_name = format!("{}Exception", error.name);
    let doc_lines: Vec<&str> = error.doc.lines().collect();

    let base = crate::template_env::render(
        "error_gen/java_error_base.jinja",
        minijinja::context! {
            package => package,
            base_name => base_name.as_str(),
            doc => !error.doc.is_empty(),
            doc_lines => doc_lines,
        },
    );
    files.push((base_name.clone(), base));

    // Per-variant exception classes
    for variant in &error.variants {
        let class_name = format!("{}Exception", variant.name);
        let doc_lines: Vec<&str> = variant.doc.lines().collect();

        let content = crate::template_env::render(
            "error_gen/java_error_variant.jinja",
            minijinja::context! {
                package => package,
                class_name => class_name.as_str(),
                base_name => base_name.as_str(),
                doc => !variant.doc.is_empty(),
                doc_lines => doc_lines,
            },
        );
        files.push((class_name, content));
    }

    files
}

// ---------------------------------------------------------------------------
// C# error type generation
// ---------------------------------------------------------------------------

/// Generate C# exception sub-classes for each error variant.
///
/// Returns a `Vec` of `(class_name, file_content)` tuples: the base exception
/// class followed by one per-variant exception.  The caller writes each to a
/// separate `.cs` file.
///
/// `fallback_class` is the name of the generic library exception class (e.g.
/// `TreeSitterLanguagePackException`) that the base error class should extend so that
/// callers can `catch` the general library exception and catch all typed errors.
pub fn gen_csharp_error_types(
    error: &ErrorDef,
    namespace: &str,
    fallback_class: Option<&str>,
) -> Vec<(String, String)> {
    let mut files = Vec::with_capacity(error.variants.len() + 1);

    let base_name = format!("{}Exception", error.name);
    // Inherit from the generic library exception when provided so that
    // `Assert.ThrowsAny<LibException>()` catches typed errors too.
    let base_parent = fallback_class.unwrap_or("Exception");
    let error_doc_lines: Vec<&str> = error.doc.lines().collect();

    // Base exception class
    {
        let out = crate::template_env::render(
            "error_gen/csharp_error_base.jinja",
            minijinja::context! {
                namespace => namespace,
                base_name => base_name.as_str(),
                base_parent => base_parent,
                doc => !error.doc.is_empty(),
                doc_lines => error_doc_lines,
            },
        );
        files.push((base_name.clone(), out));
    }

    // Per-variant exception classes
    for variant in &error.variants {
        let class_name = format!("{}Exception", variant.name);
        let variant_doc_lines: Vec<&str> = variant.doc.lines().collect();

        let out = crate::template_env::render(
            "error_gen/csharp_error_variant.jinja",
            minijinja::context! {
                namespace => namespace,
                class_name => class_name.as_str(),
                base_name => base_name.as_str(),
                doc => !variant.doc.is_empty(),
                doc_lines => variant_doc_lines,
            },
        );
        files.push((class_name, out));
    }

    files
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Convert CamelCase to SCREAMING_SNAKE_CASE.
fn to_screaming_snake(s: &str) -> String {
    let mut result = String::with_capacity(s.len() + 4);
    for (i, c) in s.chars().enumerate() {
        if c.is_uppercase() {
            if i > 0 {
                result.push('_');
            }
            result.push(c.to_ascii_uppercase());
        } else {
            result.push(c.to_ascii_uppercase());
        }
    }
    result
}

/// Well-known acronyms recognised by the doc/error renderers.
///
/// When emitting human-readable Display strings (e.g. for Go sentinel
/// `errors.New("...")`), variant names like `IoError` must render as
/// "IO error" — not "iO error" (the result of naive `lowercase first
/// character` after `to_snake_case`).
const TECHNICAL_ACRONYMS: &[&str] = &[
    "API", "ASCII", "CPU", "CSS", "CSV", "DNS", "EOF", "FFI", "FTP", "GID", "GPU", "GUI", "HTML", "HTTP", "HTTPS",
    "ID", "IO", "IP", "JSON", "JWT", "LDAP", "MFA", "MIME", "OCR", "OS", "PDF", "PID", "PNG", "QPS", "RAM", "RGB",
    "RPC", "RTF", "SDK", "SLA", "SMTP", "SQL", "SSH", "SSL", "SVG", "TCP", "TLS", "TOML", "TTL", "UDP", "UI", "UID",
    "URI", "URL", "UTF8", "UUID", "VM", "XML", "XMPP", "XSRF", "XSS", "YAML", "ZIP",
];

/// Strip `thiserror`-style `{name}` placeholders from a Display template
/// without leaving stray punctuation.
///
/// Examples:
///
/// - `"OCR error: {message}"`           → `"OCR error"`
/// - `"plugin error in '{plugin_name}'"` → `"plugin error"`
/// - `"timed out after {elapsed_ms}ms (limit: {limit_ms}ms)"` → `"timed out"`
/// - `"I/O error: {0}"`                  → `"I/O error"`
///
/// Used by `variant_display_message` and binding error renderers
/// (Dart, Go, …) so the literal placeholder string never reaches
/// the runtime.
pub fn strip_thiserror_placeholders(template: &str) -> String {
    // Remove every `{...}` segment.
    let mut without_placeholders = String::with_capacity(template.len());
    let mut depth = 0u32;
    for ch in template.chars() {
        match ch {
            '{' => depth = depth.saturating_add(1),
            '}' => depth = depth.saturating_sub(1),
            other if depth == 0 => without_placeholders.push(other),
            _ => {}
        }
    }
    // Remove orphaned punctuation/whitespace immediately around the holes
    // (collapse runs of whitespace, drop trailing `:`/quote runs, drop
    // `(...)` shells that wrapped only placeholders).
    let mut compacted = String::with_capacity(without_placeholders.len());
    let mut last_was_space = false;
    for ch in without_placeholders.chars() {
        if ch.is_whitespace() {
            if !last_was_space && !compacted.is_empty() {
                compacted.push(' ');
            }
            last_was_space = true;
        } else {
            compacted.push(ch);
            last_was_space = false;
        }
    }
    // Trim trailing punctuation that only made sense before a placeholder.
    let trimmed = compacted
        .trim()
        .trim_end_matches([':', ',', '-', ';', '(', '\'', '"', ' '])
        .trim();
    // If we left e.g. `"limit: ms ms"` artefacts behind, collapse stray
    // empty parens / paired quotes.
    let cleaned = trimmed
        .replace("()", "")
        .replace("''", "")
        .replace("\"\"", "")
        .replace("  ", " ");
    cleaned.trim().to_string()
}

/// Convert a PascalCase variant name into a human readable phrase that
/// preserves canonical acronyms.
///
/// Examples:
/// - `"IoError"`           → `"IO error"`
/// - `"OcrError"`          → `"OCR error"`
/// - `"PdfParse"`          → `"PDF parse"`
/// - `"HttpRequestFailed"` → `"HTTP request failed"`
/// - `"Other"`             → `"other"`
pub fn acronym_aware_snake_phrase(variant_name: &str) -> String {
    if variant_name.is_empty() {
        return String::new();
    }
    // Split into PascalCase words (each word starts with an uppercase letter).
    let bytes = variant_name.as_bytes();
    let mut words: Vec<&str> = Vec::new();
    let mut start = 0usize;
    for i in 1..bytes.len() {
        if bytes[i].is_ascii_uppercase() {
            words.push(&variant_name[start..i]);
            start = i;
        }
    }
    words.push(&variant_name[start..]);

    let mut rendered: Vec<String> = Vec::with_capacity(words.len());
    for word in &words {
        let upper = word.to_ascii_uppercase();
        if TECHNICAL_ACRONYMS.contains(&upper.as_str()) {
            rendered.push(upper);
        } else {
            rendered.push(word.to_ascii_lowercase());
        }
    }
    rendered.join(" ")
}

/// Generate a human-readable message for an error variant.
///
/// Uses the `message_template` if present, otherwise falls back to a
/// space-separated version of the variant name (e.g. "ParseError" -> "parse error").
fn variant_display_message(variant: &ErrorVariant) -> String {
    if let Some(tmpl) = &variant.message_template {
        let stripped = strip_thiserror_placeholders(tmpl);
        if stripped.is_empty() {
            return acronym_aware_snake_phrase(&variant.name);
        }
        // Preserve canonical acronyms but lowercase the first regular word so
        // Go's `lowercase first char` convention does not corrupt `IO` → `iO`.
        // Heuristic: if the first whitespace-delimited token is *not* already
        // a known acronym, downcase its first character.
        let mut tokens = stripped.splitn(2, ' ');
        let head = tokens.next().unwrap_or("").to_string();
        let tail = tokens.next().unwrap_or("");
        let head_upper = head.to_ascii_uppercase();
        let head_rendered = if TECHNICAL_ACRONYMS.contains(&head_upper.as_str()) {
            head_upper
        } else {
            let mut chars = head.chars();
            match chars.next() {
                Some(c) => c.to_lowercase().to_string() + chars.as_str(),
                None => head,
            }
        };
        if tail.is_empty() {
            head_rendered
        } else {
            format!("{} {}", head_rendered, tail)
        }
    } else {
        acronym_aware_snake_phrase(&variant.name)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use alef_core::ir::{ErrorDef, ErrorVariant};

    use alef_core::ir::{CoreWrapper, FieldDef, TypeRef};

    /// Helper to create a tuple-style field (e.g. `_0: String`).
    fn tuple_field(index: usize) -> FieldDef {
        FieldDef {
            name: format!("_{index}"),
            ty: TypeRef::String,
            optional: false,
            default: None,
            doc: String::new(),
            sanitized: false,
            is_boxed: false,
            type_rust_path: None,
            cfg: None,
            typed_default: None,
            core_wrapper: CoreWrapper::None,
            vec_inner_core_wrapper: CoreWrapper::None,
            newtype_wrapper: None,
            serde_rename: None,
        }
    }

    /// Helper to create a named struct field.
    fn named_field(name: &str) -> FieldDef {
        FieldDef {
            name: name.to_string(),
            ty: TypeRef::String,
            optional: false,
            default: None,
            doc: String::new(),
            sanitized: false,
            is_boxed: false,
            type_rust_path: None,
            cfg: None,
            typed_default: None,
            core_wrapper: CoreWrapper::None,
            vec_inner_core_wrapper: CoreWrapper::None,
            newtype_wrapper: None,
            serde_rename: None,
        }
    }

    fn sample_error() -> ErrorDef {
        ErrorDef {
            name: "ConversionError".to_string(),
            rust_path: "html_to_markdown_rs::ConversionError".to_string(),
            original_rust_path: String::new(),
            variants: vec![
                ErrorVariant {
                    name: "ParseError".to_string(),
                    message_template: Some("HTML parsing error: {0}".to_string()),
                    fields: vec![tuple_field(0)],
                    has_source: false,
                    has_from: false,
                    is_unit: false,
                    doc: String::new(),
                },
                ErrorVariant {
                    name: "IoError".to_string(),
                    message_template: Some("I/O error: {0}".to_string()),
                    fields: vec![tuple_field(0)],
                    has_source: false,
                    has_from: true,
                    is_unit: false,
                    doc: String::new(),
                },
                ErrorVariant {
                    name: "Other".to_string(),
                    message_template: Some("Conversion error: {0}".to_string()),
                    fields: vec![tuple_field(0)],
                    has_source: false,
                    has_from: false,
                    is_unit: false,
                    doc: String::new(),
                },
            ],
            doc: "Error type for conversion operations.".to_string(),
        }
    }

    #[test]
    fn test_gen_error_types() {
        let error = sample_error();
        let output = gen_pyo3_error_types(&error, "_module", &mut AHashSet::new());
        assert!(output.contains("pyo3::create_exception!(_module, ParseError, pyo3::exceptions::PyException);"));
        assert!(output.contains("pyo3::create_exception!(_module, IoError, pyo3::exceptions::PyException);"));
        assert!(output.contains("pyo3::create_exception!(_module, OtherError, pyo3::exceptions::PyException);"));
        assert!(output.contains("pyo3::create_exception!(_module, ConversionError, pyo3::exceptions::PyException);"));
    }

    #[test]
    fn test_gen_error_converter() {
        let error = sample_error();
        let output = gen_pyo3_error_converter(&error, "html_to_markdown_rs");
        assert!(
            output.contains("fn conversion_error_to_py_err(e: html_to_markdown_rs::ConversionError) -> pyo3::PyErr {")
        );
        assert!(output.contains("html_to_markdown_rs::ConversionError::ParseError(..) => ParseError::new_err(msg),"));
        assert!(output.contains("html_to_markdown_rs::ConversionError::IoError(..) => IoError::new_err(msg),"));
    }

    #[test]
    fn test_gen_error_registration() {
        let error = sample_error();
        let regs = gen_pyo3_error_registration(&error, &mut AHashSet::new());
        assert_eq!(regs.len(), 4); // 3 variants + 1 base
        assert!(regs[0].contains("\"ParseError\""));
        assert!(regs[3].contains("\"ConversionError\""));
    }

    #[test]
    fn test_unit_variant_pattern() {
        let error = ErrorDef {
            name: "MyError".to_string(),
            rust_path: "my_crate::MyError".to_string(),
            original_rust_path: String::new(),
            variants: vec![ErrorVariant {
                name: "NotFound".to_string(),
                message_template: Some("not found".to_string()),
                fields: vec![],
                has_source: false,
                has_from: false,
                is_unit: true,
                doc: String::new(),
            }],
            doc: String::new(),
        };
        let output = gen_pyo3_error_converter(&error, "my_crate");
        assert!(output.contains("my_crate::MyError::NotFound => NotFoundError::new_err(msg),"));
        // Ensure no (..) for unit variants
        assert!(!output.contains("NotFound(..)"));
    }

    #[test]
    fn test_struct_variant_pattern() {
        let error = ErrorDef {
            name: "MyError".to_string(),
            rust_path: "my_crate::MyError".to_string(),
            original_rust_path: String::new(),
            variants: vec![ErrorVariant {
                name: "Parsing".to_string(),
                message_template: Some("parsing error: {message}".to_string()),
                fields: vec![named_field("message")],
                has_source: false,
                has_from: false,
                is_unit: false,
                doc: String::new(),
            }],
            doc: String::new(),
        };
        let output = gen_pyo3_error_converter(&error, "my_crate");
        assert!(
            output.contains("my_crate::MyError::Parsing { .. } => ParsingError::new_err(msg),"),
            "Struct variants must use {{ .. }} pattern, got:\n{output}"
        );
        // Ensure no (..) for struct variants
        assert!(!output.contains("Parsing(..)"));
    }

    // -----------------------------------------------------------------------
    // NAPI tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_gen_napi_error_types() {
        let error = sample_error();
        let output = gen_napi_error_types(&error);
        assert!(output.contains("CONVERSION_ERROR_ERROR_PARSE_ERROR"));
        assert!(output.contains("CONVERSION_ERROR_ERROR_IO_ERROR"));
        assert!(output.contains("CONVERSION_ERROR_ERROR_OTHER"));
    }

    #[test]
    fn test_gen_napi_error_converter() {
        let error = sample_error();
        let output = gen_napi_error_converter(&error, "html_to_markdown_rs");
        assert!(
            output
                .contains("fn conversion_error_to_napi_err(e: html_to_markdown_rs::ConversionError) -> napi::Error {")
        );
        assert!(output.contains("napi::Error::new(napi::Status::GenericFailure,"));
        assert!(output.contains("[ParseError]"));
        assert!(output.contains("[IoError]"));
        assert!(output.contains("#[allow(dead_code)]"));
    }

    #[test]
    fn test_napi_unit_variant() {
        let error = ErrorDef {
            name: "MyError".to_string(),
            rust_path: "my_crate::MyError".to_string(),
            original_rust_path: String::new(),
            variants: vec![ErrorVariant {
                name: "NotFound".to_string(),
                message_template: None,
                fields: vec![],
                has_source: false,
                has_from: false,
                is_unit: true,
                doc: String::new(),
            }],
            doc: String::new(),
        };
        let output = gen_napi_error_converter(&error, "my_crate");
        assert!(output.contains("my_crate::MyError::NotFound =>"));
        assert!(!output.contains("NotFound(..)"));
    }

    // -----------------------------------------------------------------------
    // WASM tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_gen_wasm_error_converter() {
        let error = sample_error();
        let output = gen_wasm_error_converter(&error, "html_to_markdown_rs");
        // Main converter function signature
        assert!(output.contains(
            "fn conversion_error_to_js_value(e: html_to_markdown_rs::ConversionError) -> wasm_bindgen::JsValue {"
        ));
        // Structured object with code + message
        assert!(output.contains("js_sys::Object::new()"));
        assert!(output.contains("js_sys::Reflect::set(&obj, &\"code\".into(), &code.into()).ok()"));
        assert!(output.contains("js_sys::Reflect::set(&obj, &\"message\".into(), &message.into()).ok()"));
        assert!(output.contains("obj.into()"));
        // error_code helper
        assert!(
            output
                .contains("fn conversion_error_error_code(e: &html_to_markdown_rs::ConversionError) -> &'static str {")
        );
        assert!(output.contains("\"parse_error\""));
        assert!(output.contains("\"io_error\""));
        assert!(output.contains("\"other\""));
        assert!(output.contains("#[allow(dead_code)]"));
    }

    // -----------------------------------------------------------------------
    // PHP tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_gen_php_error_converter() {
        let error = sample_error();
        let output = gen_php_error_converter(&error, "html_to_markdown_rs");
        assert!(output.contains("fn conversion_error_to_php_err(e: html_to_markdown_rs::ConversionError) -> ext_php_rs::exception::PhpException {"));
        assert!(output.contains("PhpException::default(format!(\"[ParseError] {}\", msg))"));
        assert!(output.contains("#[allow(dead_code)]"));
    }

    // -----------------------------------------------------------------------
    // Magnus tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_gen_magnus_error_converter() {
        let error = sample_error();
        let output = gen_magnus_error_converter(&error, "html_to_markdown_rs");
        assert!(
            output.contains(
                "fn conversion_error_to_magnus_err(e: html_to_markdown_rs::ConversionError) -> magnus::Error {"
            )
        );
        assert!(
            output.contains(
                "magnus::Error::new(unsafe { magnus::Ruby::get_unchecked() }.exception_runtime_error(), msg)"
            )
        );
        assert!(output.contains("#[allow(dead_code)]"));
    }

    // -----------------------------------------------------------------------
    // Rustler tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_gen_rustler_error_converter() {
        let error = sample_error();
        let output = gen_rustler_error_converter(&error, "html_to_markdown_rs");
        assert!(
            output.contains("fn conversion_error_to_rustler_err(e: html_to_markdown_rs::ConversionError) -> String {")
        );
        assert!(output.contains("e.to_string()"));
        assert!(output.contains("#[allow(dead_code)]"));
    }

    // -----------------------------------------------------------------------
    // Helper tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_to_screaming_snake() {
        assert_eq!(to_screaming_snake("ConversionError"), "CONVERSION_ERROR");
        assert_eq!(to_screaming_snake("IoError"), "IO_ERROR");
        assert_eq!(to_screaming_snake("Other"), "OTHER");
    }

    #[test]
    fn test_strip_thiserror_placeholders_struct_field() {
        assert_eq!(strip_thiserror_placeholders("OCR error: {message}"), "OCR error");
        assert_eq!(
            strip_thiserror_placeholders("plugin error in '{plugin_name}': {message}"),
            "plugin error in"
        );
        // Multi-placeholder strings retain the surrounding prose verbatim
        // (minus the holes). Critical contract: no `{` / `}` survives.
        let result = strip_thiserror_placeholders("extraction timed out after {elapsed_ms}ms (limit: {limit_ms}ms)");
        assert!(!result.contains('{'), "no braces: {result}");
        assert!(!result.contains('}'), "no braces: {result}");
        assert!(result.starts_with("extraction timed out after"), "{result}");
    }

    #[test]
    fn test_strip_thiserror_placeholders_positional() {
        assert_eq!(strip_thiserror_placeholders("I/O error: {0}"), "I/O error");
        assert_eq!(strip_thiserror_placeholders("Parse error: {0}"), "Parse error");
    }

    #[test]
    fn test_strip_thiserror_placeholders_no_placeholder() {
        assert_eq!(strip_thiserror_placeholders("not found"), "not found");
        assert_eq!(strip_thiserror_placeholders("lock poisoned"), "lock poisoned");
    }

    #[test]
    fn test_acronym_aware_snake_phrase_recognizes_acronyms() {
        assert_eq!(acronym_aware_snake_phrase("IoError"), "IO error");
        assert_eq!(acronym_aware_snake_phrase("OcrError"), "OCR error");
        assert_eq!(acronym_aware_snake_phrase("PdfParse"), "PDF parse");
        assert_eq!(acronym_aware_snake_phrase("HttpRequestFailed"), "HTTP request failed");
        assert_eq!(acronym_aware_snake_phrase("UrlInvalid"), "URL invalid");
    }

    #[test]
    fn test_acronym_aware_snake_phrase_plain_words() {
        assert_eq!(acronym_aware_snake_phrase("Other"), "other");
        assert_eq!(acronym_aware_snake_phrase("ParseError"), "parse error");
        assert_eq!(acronym_aware_snake_phrase("LockPoisoned"), "lock poisoned");
    }

    #[test]
    fn test_variant_display_message_acronym_first_word() {
        let variant = ErrorVariant {
            name: "Io".to_string(),
            message_template: Some("I/O error: {0}".to_string()),
            fields: vec![tuple_field(0)],
            has_source: false,
            has_from: false,
            is_unit: false,
            doc: String::new(),
        };
        // Template "I/O error: {0}" → strip → "I/O error" → first token "I/O" not an acronym (with `/`),
        // so falls back to lowercase first char → "i/O error". Acceptable: at least no `{0}` leak.
        let msg = variant_display_message(&variant);
        assert!(!msg.contains('{'), "no placeholders allowed: {msg}");
    }

    #[test]
    fn test_variant_display_message_no_template_uses_acronyms() {
        let variant = ErrorVariant {
            name: "IoError".to_string(),
            message_template: None,
            fields: vec![],
            has_source: false,
            has_from: false,
            is_unit: false,
            doc: String::new(),
        };
        assert_eq!(variant_display_message(&variant), "IO error");
    }

    #[test]
    fn test_variant_display_message_struct_template_no_leak() {
        let variant = ErrorVariant {
            name: "Ocr".to_string(),
            message_template: Some("OCR error: {message}".to_string()),
            fields: vec![named_field("message")],
            has_source: false,
            has_from: false,
            is_unit: false,
            doc: String::new(),
        };
        let msg = variant_display_message(&variant);
        assert_eq!(msg, "OCR error", "must not leak {{message}} placeholder: {msg}");
    }

    #[test]
    fn test_go_sentinels_no_placeholder_leak() {
        let error = ErrorDef {
            name: "KreuzbergError".to_string(),
            rust_path: "kreuzberg::KreuzbergError".to_string(),
            original_rust_path: String::new(),
            variants: vec![
                ErrorVariant {
                    name: "Io".to_string(),
                    message_template: Some("IO error: {message}".to_string()),
                    fields: vec![named_field("message")],
                    has_source: false,
                    has_from: false,
                    is_unit: false,
                    doc: String::new(),
                },
                ErrorVariant {
                    name: "Ocr".to_string(),
                    message_template: Some("OCR error: {message}".to_string()),
                    fields: vec![named_field("message")],
                    has_source: false,
                    has_from: false,
                    is_unit: false,
                    doc: String::new(),
                },
                ErrorVariant {
                    name: "Timeout".to_string(),
                    message_template: Some(
                        "extraction timed out after {elapsed_ms}ms (limit: {limit_ms}ms)".to_string(),
                    ),
                    fields: vec![named_field("elapsed_ms"), named_field("limit_ms")],
                    has_source: false,
                    has_from: false,
                    is_unit: false,
                    doc: String::new(),
                },
            ],
            doc: String::new(),
        };
        let output = gen_go_sentinel_errors(std::slice::from_ref(&error));
        assert!(
            !output.contains('{'),
            "Go sentinels must not contain raw placeholders:\n{output}"
        );
        assert!(
            output.contains("ErrIo = errors.New(\"IO error\")"),
            "expected acronym-preserving Io sentinel, got:\n{output}"
        );
        assert!(
            output.contains("ErrOcr = errors.New(\"OCR error\")"),
            "expected acronym-preserving Ocr sentinel, got:\n{output}"
        );
        assert!(
            output.contains("ErrTimeout = errors.New(\"extraction timed out after"),
            "expected timeout sentinel to start with the prose, got:\n{output}"
        );
    }

    // -----------------------------------------------------------------------
    // FFI (C) tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_gen_ffi_error_codes() {
        let error = sample_error();
        let output = gen_ffi_error_codes(&error);
        assert!(output.contains("CONVERSION_ERROR_NONE = 0"));
        assert!(output.contains("CONVERSION_ERROR_PARSE_ERROR = 1"));
        assert!(output.contains("CONVERSION_ERROR_IO_ERROR = 2"));
        assert!(output.contains("CONVERSION_ERROR_OTHER = 3"));
        assert!(output.contains("conversion_error_t;"));
        assert!(output.contains("conversion_error_error_message(conversion_error_t code)"));
    }

    // -----------------------------------------------------------------------
    // Go tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_gen_go_error_types() {
        let error = sample_error();
        // Package name that does NOT match the error prefix — type name stays unchanged.
        let output = gen_go_error_types(&error, "mylib");
        assert!(output.contains("ErrParseError = errors.New("));
        assert!(output.contains("ErrIoError = errors.New("));
        assert!(output.contains("ErrOther = errors.New("));
        assert!(output.contains("type ConversionError struct {"));
        assert!(output.contains("Code    string"));
        assert!(output.contains("func (e *ConversionError) Error() string"));
        // Each sentinel error var should have a doc comment.
        assert!(output.contains("// ErrParseError is returned when"));
        assert!(output.contains("// ErrIoError is returned when"));
        assert!(output.contains("// ErrOther is returned when"));
    }

    #[test]
    fn test_gen_go_error_types_stutter_strip() {
        let error = sample_error();
        // "conversion" package — "ConversionError" starts with "conversion" (case-insensitive)
        // so the exported Go type should be "Error", not "ConversionError".
        let output = gen_go_error_types(&error, "conversion");
        assert!(
            output.contains("type Error struct {"),
            "expected stutter strip, got:\n{output}"
        );
        assert!(
            output.contains("func (e *Error) Error() string"),
            "expected stutter strip, got:\n{output}"
        );
        // Sentinel vars are unaffected by stutter stripping.
        assert!(output.contains("ErrParseError = errors.New("));
    }

    // -----------------------------------------------------------------------
    // Java tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_gen_java_error_types() {
        let error = sample_error();
        let files = gen_java_error_types(&error, "dev.kreuzberg.test");
        // base + 3 variants
        assert_eq!(files.len(), 4);
        // Base class
        assert_eq!(files[0].0, "ConversionErrorException");
        assert!(
            files[0]
                .1
                .contains("public class ConversionErrorException extends Exception")
        );
        assert!(files[0].1.contains("package dev.kreuzberg.test;"));
        // Variant classes
        assert_eq!(files[1].0, "ParseErrorException");
        assert!(
            files[1]
                .1
                .contains("public class ParseErrorException extends ConversionErrorException")
        );
        assert_eq!(files[2].0, "IoErrorException");
        assert_eq!(files[3].0, "OtherException");
    }

    // -----------------------------------------------------------------------
    // C# tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_gen_csharp_error_types() {
        let error = sample_error();
        // Without fallback class: base inherits from Exception.
        let files = gen_csharp_error_types(&error, "Kreuzberg.Test", None);
        assert_eq!(files.len(), 4);
        assert_eq!(files[0].0, "ConversionErrorException");
        assert!(files[0].1.contains("public class ConversionErrorException : Exception"));
        assert!(files[0].1.contains("namespace Kreuzberg.Test;"));
        assert_eq!(files[1].0, "ParseErrorException");
        assert!(
            files[1]
                .1
                .contains("public class ParseErrorException : ConversionErrorException")
        );
        assert_eq!(files[2].0, "IoErrorException");
        assert_eq!(files[3].0, "OtherException");
    }

    #[test]
    fn test_gen_csharp_error_types_with_fallback() {
        let error = sample_error();
        // With fallback class: base inherits from the generic library exception.
        let files = gen_csharp_error_types(&error, "Kreuzberg.Test", Some("TestLibException"));
        assert_eq!(files.len(), 4);
        assert!(
            files[0]
                .1
                .contains("public class ConversionErrorException : TestLibException")
        );
        // Variant classes still inherit from the base error class, not from the fallback directly.
        assert!(
            files[1]
                .1
                .contains("public class ParseErrorException : ConversionErrorException")
        );
    }

    // -----------------------------------------------------------------------
    // python_exception_name tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_python_exception_name_no_conflict() {
        // "ParseError" already ends with "Error" and is not a builtin
        assert_eq!(python_exception_name("ParseError", "ConversionError"), "ParseError");
        // "Other" gets "Error" suffix, "OtherError" is not a builtin
        assert_eq!(python_exception_name("Other", "ConversionError"), "OtherError");
    }

    #[test]
    fn test_python_exception_name_shadows_builtin() {
        // "Connection" -> "ConnectionError" shadows builtin -> prefix with "Crawl"
        assert_eq!(
            python_exception_name("Connection", "CrawlError"),
            "CrawlConnectionError"
        );
        // "Timeout" -> "TimeoutError" shadows builtin -> prefix with "Crawl"
        assert_eq!(python_exception_name("Timeout", "CrawlError"), "CrawlTimeoutError");
        // "ConnectionError" already ends with "Error", still shadows -> prefix
        assert_eq!(
            python_exception_name("ConnectionError", "CrawlError"),
            "CrawlConnectionError"
        );
    }

    #[test]
    fn test_python_exception_name_no_double_prefix() {
        // If variant is already prefixed with the error base, don't double-prefix
        assert_eq!(
            python_exception_name("CrawlConnectionError", "CrawlError"),
            "CrawlConnectionError"
        );
    }
}