alef 0.115.12

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
use super::{FamilyInterfaceNames, default_interface_names, interface_name};
use crate::core::ir::ErrorDef;

use super::shared::{error_base_prefix, variant_display_message};

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, false);
    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::codegen::template_env::render(
        "error_gen/go_sentinel_errors.jinja",
        crate::alef_context! {
            sentinels => sentinels,
        },
    )
}

pub fn go_error_sentinel_name(errors: &[ErrorDef], error_name: &str, variant_name: &str) -> String {
    let collides = errors
        .iter()
        .flat_map(|error| &error.variants)
        .filter(|variant| variant.name == variant_name)
        .count()
        > 1;
    if collides {
        format!("Err{}{}", error_base_prefix(error_name), variant_name)
    } else {
        format!("Err{variant_name}")
    }
}

/// Generate the structured error type (struct + Error() method) for a single
/// error definition. Sentinel errors are emitted separately by
/// [`gen_go_sentinel_errors`].
///
/// When `error.methods` is non-empty, each whitelisted introspection method
/// produces an exported struct field of the matching Go type.
///
/// `carries_sentinel` adds an unexported sentinel and an `Unwrap` method so
/// `errors.Is(err, ErrX)` matches. Only the error type `lastError()` constructs sets
/// it, so the field is never dead.
pub fn gen_go_error_struct(error: &ErrorDef, pkg_name: &str, carries_sentinel: bool) -> String {
    let go_type_name = crate::codegen::naming::go_error_type_name(&error.name, pkg_name);

    let methods: Vec<serde_json::Value> = go_error_method_fields(error)
        .into_iter()
        .map(|field| {
            serde_json::json!({
                "field_name": field.field_name,
                "go_type": field.go_type,
            })
        })
        .collect();
    let has_methods = !methods.is_empty();

    crate::codegen::template_env::render(
        "error_gen/go_error_struct.jinja",
        crate::alef_context! {
            go_type_name => go_type_name.as_str(),
            methods => methods,
            has_methods => has_methods,
            carries_sentinel => carries_sentinel,
        },
    )
}

/// One exported Go struct field backed by a whitelisted error introspection method.
pub struct GoErrorMethodField {
    pub field_name: String,
    pub go_type: &'static str,
    pub method: String,
}

/// The struct fields `gen_go_error_struct` emits for `error.methods`, in declaration order.
///
/// Shared with the Go `lastError()` helper so the fields it populates are exactly the fields
/// the struct declares.
pub fn go_error_method_fields(error: &ErrorDef) -> Vec<GoErrorMethodField> {
    error
        .methods
        .iter()
        .map(|m| GoErrorMethodField {
            field_name: to_pascal_case(&m.name),
            go_type: typeref_to_go_type(&m.return_type),
            method: m.name.clone(),
        })
        .collect()
}

/// Map an IR `TypeRef` to a Go type string for error introspection method returns.
/// Only the primitive subset needed for the whitelisted methods is handled;
/// everything else falls back to `string`.
fn typeref_to_go_type(ty: &crate::core::ir::TypeRef) -> &'static str {
    use crate::core::ir::{PrimitiveType, TypeRef};
    match ty {
        TypeRef::Primitive(PrimitiveType::Bool) => "bool",
        TypeRef::Primitive(PrimitiveType::U8) => "uint8",
        TypeRef::Primitive(PrimitiveType::U16) => "uint16",
        TypeRef::Primitive(PrimitiveType::U32) => "uint32",
        TypeRef::Primitive(PrimitiveType::U64) => "uint64",
        TypeRef::Primitive(PrimitiveType::I8) => "int8",
        TypeRef::Primitive(PrimitiveType::I16) => "int16",
        TypeRef::Primitive(PrimitiveType::I32) => "int32",
        TypeRef::Primitive(PrimitiveType::I64) => "int64",
        TypeRef::Primitive(PrimitiveType::F32) => "float32",
        TypeRef::Primitive(PrimitiveType::F64) => "float64",
        TypeRef::String => "string",
        TypeRef::Duration => "DurationMillis",
        TypeRef::Optional(inner) if matches!(inner.as_ref(), TypeRef::Duration) => "*DurationMillis",
        _ => "string",
    }
}

/// Convert a snake_case or camelCase name to PascalCase.
pub(crate) fn to_pascal_case(s: &str) -> String {
    s.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()
}

/// 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.
///
/// `main_class` is the generated FFI class name (e.g. `Sample` for `SampleException`). The base
/// exception extends `{main_class}Exception` rather than bare `Exception` so that every generated
/// method's trailing `catch ({main_class}Exception e) { throw e; }` guard -- see
/// `ffi_class::error_catch::emit_method_catch_chain` -- actually matches a typed error the enum
/// throws, instead of falling through to the `catch (Throwable e)` clause that replaces it with
/// the placeholder "FFI call failed" message and demotes the real detail to a nested cause. ~keep
///
/// When `error.methods` is non-empty, the base exception class gains private
/// final fields, an extended constructor, and public getter methods for each
/// whitelisted introspection method.  Variant classes delegate via `super(…)`.
///
pub fn gen_java_error_types(error: &ErrorDef, package: &str, main_class: &str) -> Vec<(String, String)> {
    gen_java_error_types_with_parent(error, package, main_class, None)
}

pub fn gen_java_error_types_with_parent(
    error: &ErrorDef,
    package: &str,
    main_class: &str,
    parent: Option<&str>,
) -> Vec<(String, String)> {
    gen_java_error_types_with_interfaces(
        error,
        std::slice::from_ref(error),
        package,
        main_class,
        parent,
        &FamilyInterfaceNames::new(),
    )
}

pub fn gen_java_error_types_with_errors(
    error: &ErrorDef,
    errors: &[ErrorDef],
    package: &str,
    main_class: &str,
) -> Vec<(String, String)> {
    gen_java_error_types_with_parent_and_errors(error, errors, package, main_class, None)
}

pub fn gen_java_error_types_with_parent_and_errors(
    error: &ErrorDef,
    errors: &[ErrorDef],
    package: &str,
    main_class: &str,
    parent: Option<&str>,
) -> Vec<(String, String)> {
    let names = default_interface_names(errors, family_interface_type_name);
    gen_java_error_types_with_interfaces(error, errors, package, main_class, parent, &names)
}

pub(crate) fn gen_java_error_types_with_interfaces(
    error: &ErrorDef,
    errors: &[ErrorDef],
    package: &str,
    main_class: &str,
    parent: Option<&str>,
    names: &FamilyInterfaceNames,
) -> Vec<(String, String)> {
    let mut files = Vec::with_capacity(error.variants.len() + 1);

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

    let method_infos: Vec<serde_json::Value> = error
        .methods
        .iter()
        .map(|m| {
            let java_type = typeref_to_java_type(&m.return_type);
            let getter_name = java_getter_name(&m.name);
            let field_name = java_field_name(&m.name);
            let default_value = java_default_value(&m.return_type);
            serde_json::json!({
                "field_name": field_name,
                "java_type": java_type,
                "getter_name": getter_name,
                "default_value": default_value,
                "nullable": duration_shape(&m.return_type) == Some(DurationShape::Optional),
                "is_duration": duration_shape(&m.return_type).is_some(),
                "doc": m.doc,
            })
        })
        .collect();
    let has_methods = !method_infos.is_empty();
    let (legacy_ctor_methods, has_duration_methods) = split_duration_methods(&method_infos);

    let base = crate::codegen::template_env::render(
        "error_gen/java_error_base.jinja",
        crate::alef_context! {
            package => package,
            base_name => base_name.as_str(),
            main_class => main_class,
            base_parent => parent.map(|parent| format!("{parent}Exception")).unwrap_or_else(|| format!("{main_class}Exception")),
            interfaces => names.get(&error.name).cloned().into_iter().collect::<Vec<_>>(),
            doc => !error.doc.is_empty(),
            doc_lines => doc_lines,
            methods => method_infos.clone(),
            has_methods => has_methods,
            legacy_ctor_methods => legacy_ctor_methods,
            has_duration_methods => has_duration_methods,
        },
    );
    files.push((base_name.clone(), base));

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

        let content = crate::codegen::template_env::render(
            "error_gen/java_error_variant.jinja",
            crate::alef_context! {
                package => package,
                class_name => class_name.as_str(),
                base_name => base_name.as_str(),
                interfaces => shared_family_interfaces(errors, error, variant, names),
                doc => !variant.doc.is_empty(),
                doc_lines => doc_lines,
                has_methods => has_methods,
                methods => method_infos.clone(),
                extra_methods => shared_extra_methods(errors, &class_name)
                    .iter()
                    .map(|m| serde_json::json!({
                        "java_type": java_boxed_type(typeref_to_java_type(&m.return_type)),
                        "field_name": java_field_name(&m.name),
                        "getter_name": java_getter_name(&m.name),
                    }))
                    .collect::<Vec<_>>(),
            },
        );
        files.push((class_name, content));
    }

    files
}

/// The introspection methods a shared C# or Java variant class carries beyond those its base
/// family declares or inherits: the other declaring families' methods, nullable on the class because the
/// families without them leave them unset.
pub(crate) fn shared_extra_methods(errors: &[ErrorDef], class: &str) -> Vec<crate::core::ir::MethodDef> {
    let shared = super::shared_exception_classes(errors, super::ExceptionNaming::Nominal);
    let Some(members) = shared.get(class) else {
        return Vec::new();
    };
    let inherited = super::lineage_methods(errors, &members.families[0]);
    super::shared_introspection(errors, class, members)
        .unwrap_or_default()
        .into_iter()
        .map(|(method, _)| method)
        .filter(|method| inherited.iter().all(|own| own.name != method.name))
        .collect()
}

/// The boxed Java type of `java_type`, so a shared class can hold `null` for a family that lacks
/// the value.
pub(crate) fn java_boxed_type(java_type: &str) -> &str {
    match java_type {
        "int" => "Integer",
        "long" => "Long",
        "boolean" => "Boolean",
        "float" => "Float",
        "double" => "Double",
        other => other,
    }
}

/// The C# and Java marker interface of `family`: `I{family}`, the prefix both backends give the
/// interfaces they generate.
pub fn family_interface_type_name(family: &str) -> String {
    format!("I{family}")
}

/// The marker interfaces of the other families a shared variant class also belongs to.
fn shared_family_interfaces(
    errors: &[ErrorDef],
    error: &ErrorDef,
    variant: &crate::core::ir::ErrorVariant,
    names: &FamilyInterfaceNames,
) -> Vec<String> {
    super::additional_exception_families(errors, &error.name, &variant.name, super::ExceptionNaming::Nominal)
        .iter()
        .map(|family| interface_name(names, family))
        .collect()
}

/// `(type name, file content)` of the C# marker interface of `family`, which extends the
/// interface of its `exception_base` parent.
pub fn gen_csharp_family_interface(family: &str, parent: Option<&str>, namespace: &str) -> (String, String) {
    let mut names = FamilyInterfaceNames::new();
    names.insert(family.into(), family_interface_type_name(family));
    if let Some(parent) = parent {
        names.insert(parent.into(), family_interface_type_name(parent));
    }
    gen_csharp_family_interface_with_names(family, parent, namespace, &names)
}

pub(crate) fn gen_csharp_family_interface_with_names(
    family: &str,
    parent: Option<&str>,
    namespace: &str,
    names: &FamilyInterfaceNames,
) -> (String, String) {
    let name = interface_name(names, family);
    let extends = parent
        .map(|parent| format!(" : {}", interface_name(names, parent)))
        .unwrap_or_default();
    let content = format!(
        "// This file is auto-generated by alef. DO NOT EDIT.\n\nnamespace {namespace};\n\n/// <summary>\n\
         /// Implemented by every exception of the <c>{family}</c> family, including a variant exception it\n\
         /// shares with another family and so does not derive from. C# catches only exception types, so\n\
         /// filter on it: <c>catch (Exception e) when (e is {name})</c>.\n/// </summary>\n\
         public interface {name}{extends}\n{{\n}}\n"
    );
    (name, content)
}

/// `(type name, file content)` of the Java marker interface of `family`, which extends the
/// interface of its `exception_base` parent.
pub fn gen_java_family_interface(family: &str, parent: Option<&str>, package: &str) -> (String, String) {
    let mut names = FamilyInterfaceNames::new();
    names.insert(family.into(), family_interface_type_name(family));
    if let Some(parent) = parent {
        names.insert(parent.into(), family_interface_type_name(parent));
    }
    gen_java_family_interface_with_names(family, parent, package, &names)
}

pub(crate) fn gen_java_family_interface_with_names(
    family: &str,
    parent: Option<&str>,
    package: &str,
    names: &FamilyInterfaceNames,
) -> (String, String) {
    let name = interface_name(names, family);
    let extends = parent
        .map(|parent| format!(" extends {}", interface_name(names, parent)))
        .unwrap_or_default();
    let content = format!(
        "// DO NOT EDIT - auto-generated by alef\npackage {package};\n\n/**\n\
         \x20* Implemented by every exception of the {{@code {family}}} family, including a variant exception\n\
         \x20* it shares with another family and so does not extend. Java catches only exception types, so\n\
         \x20* test for it: {{@code catch (Exception e) {{ if (e instanceof {name}) ... }}}}.\n */\n\
         public interface {name}{extends} {{}}\n"
    );
    (name, content)
}

/// Map an IR `TypeRef` to a Java type string for error introspection getters.
pub(crate) fn typeref_to_java_type(ty: &crate::core::ir::TypeRef) -> &'static str {
    use crate::core::ir::{PrimitiveType, TypeRef};
    if duration_shape(ty).is_some() {
        return "java.time.Duration";
    }
    match ty {
        TypeRef::Primitive(PrimitiveType::Bool) => "boolean",
        TypeRef::Primitive(
            PrimitiveType::U8
            | PrimitiveType::I8
            | PrimitiveType::I16
            | PrimitiveType::U16
            | PrimitiveType::I32
            | PrimitiveType::U32,
        ) => "int",
        TypeRef::Primitive(PrimitiveType::I64 | PrimitiveType::U64 | PrimitiveType::Usize | PrimitiveType::Isize) => {
            "long"
        }
        TypeRef::Primitive(PrimitiveType::F32) => "float",
        TypeRef::Primitive(PrimitiveType::F64) => "double",
        TypeRef::String => "String",
        _ => "String",
    }
}

/// Convert a snake_case method name to a Java getter name.
/// E.g. `status_code` → `getStatusCode`, `is_transient` → `isTransient`.
pub(crate) fn java_getter_name(snake: &str) -> String {
    if let Some(rest) = snake.strip_prefix("is_") {
        let pascal = to_pascal_case(rest);
        format!("is{pascal}")
    } else {
        let pascal = to_pascal_case(snake);
        format!("get{pascal}")
    }
}

/// Convert a snake_case method name to a Java field name (camelCase).
/// E.g. `status_code` → `statusCode`, `is_transient` → `isTransientFlag`.
/// Fields that conflict with Serializable interface methods get a suffix.
pub(crate) fn java_field_name(snake: &str) -> String {
    let parts: Vec<&str> = snake.split('_').collect();
    if parts.is_empty() {
        return snake.to_string();
    }
    let mut out = parts[0].to_string();
    for part in &parts[1..] {
        let mut chars = part.chars();
        match chars.next() {
            None => {}
            Some(first) => {
                out.push_str(&first.to_uppercase().to_string());
                out.push_str(chars.as_str());
            }
        }
    }

    if out == "isTransient" {
        out.push_str("Flag");
    }

    out
}

/// Return the Java zero-value literal for a type (used in the no-args default constructor).
pub(crate) fn java_default_value(ty: &crate::core::ir::TypeRef) -> &'static str {
    use crate::core::ir::{PrimitiveType, TypeRef};
    match duration_shape(ty) {
        Some(DurationShape::Optional) => return "null",
        Some(DurationShape::Bare) => return "java.time.Duration.ZERO",
        None => {}
    }
    match ty {
        TypeRef::Primitive(PrimitiveType::Bool) => "false",
        TypeRef::Primitive(_) => "0",
        _ => "\"\"",
    }
}

/// 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.
/// `SampleLanguagePackException`) that the base error class should extend so that
/// callers can `catch` the general library exception and catch all typed errors.
///
/// When `error.methods` is non-empty, the base exception class gains get-only
/// properties for each whitelisted introspection method.  Variant classes
/// delegate via `base(…)` and inherit the properties.
///
pub fn gen_csharp_error_types(
    error: &ErrorDef,
    namespace: &str,
    fallback_class: Option<&str>,
    last_error_getters: &[super::LastErrorField],
) -> Vec<(String, String)> {
    gen_csharp_error_types_with_interfaces(
        error,
        std::slice::from_ref(error),
        namespace,
        fallback_class,
        last_error_getters,
        &FamilyInterfaceNames::new(),
    )
}

pub fn gen_csharp_error_types_with_errors(
    error: &ErrorDef,
    errors: &[ErrorDef],
    namespace: &str,
    fallback_class: Option<&str>,
    last_error_getters: &[super::LastErrorField],
) -> Vec<(String, String)> {
    let names = default_interface_names(errors, family_interface_type_name);
    gen_csharp_error_types_with_interfaces(error, errors, namespace, fallback_class, last_error_getters, &names)
}

pub(crate) fn gen_csharp_error_types_with_interfaces(
    error: &ErrorDef,
    errors: &[ErrorDef],
    namespace: &str,
    fallback_class: Option<&str>,
    last_error_getters: &[super::LastErrorField],
    names: &FamilyInterfaceNames,
) -> Vec<(String, String)> {
    let mut files = Vec::with_capacity(error.variants.len() + 1);

    let base_name = format!("{}Exception", error.name);
    let base_parent = fallback_class.unwrap_or("Exception");
    let sanitized_error_doc = crate::codegen::doc_emission::sanitize_rust_idioms(
        &error.doc,
        crate::codegen::doc_emission::DocTarget::CSharpDoc,
    );
    let error_doc_lines: Vec<&str> = sanitized_error_doc.lines().collect();
    let error_has_doc = !sanitized_error_doc.trim().is_empty();

    let method_infos: Vec<serde_json::Value> = error
        .methods
        .iter()
        .map(|m| {
            let cs_type = typeref_to_csharp_type(&m.return_type);
            let prop_name = to_pascal_case(&m.name);
            let param_name = java_field_name(&m.name);
            let default_value = csharp_default_value(&m.return_type);
            let sanitized_method_doc = crate::codegen::doc_emission::sanitize_rust_idioms(
                &m.doc,
                crate::codegen::doc_emission::DocTarget::CSharpDoc,
            );
            let inline_doc = sanitized_method_doc
                .lines()
                .map(str::trim)
                .filter(|l| !l.is_empty())
                .collect::<Vec<_>>()
                .join(" ");
            let apply_lines = csharp_last_error_apply_lines(m, &prop_name, last_error_getters);
            serde_json::json!({
                "prop_name": prop_name,
                "cs_type": cs_type,
                "param_name": param_name,
                "default_value": default_value,
                "is_duration": duration_shape(&m.return_type).is_some(),
                "wired": !apply_lines.is_empty(),
                "apply_lines": apply_lines,
                "doc": inline_doc,
            })
        })
        .collect();
    let has_methods = !method_infos.is_empty();
    let has_last_error_fields = method_infos.iter().any(|m| m["wired"] == serde_json::Value::Bool(true));
    let (legacy_ctor_methods, has_duration_methods) = split_duration_methods(&method_infos);

    {
        let out = crate::codegen::template_env::render(
            "error_gen/csharp_error_base.jinja",
            crate::alef_context! {
                namespace => namespace,
                base_name => base_name.as_str(),
                base_parent => base_parent,
                interfaces => names.get(&error.name).cloned().into_iter().collect::<Vec<_>>(),
                doc => error_has_doc,
                doc_lines => error_doc_lines,
                methods => method_infos,
                has_methods => has_methods,
                has_last_error_fields => has_last_error_fields,
                legacy_ctor_methods => legacy_ctor_methods,
                has_duration_methods => has_duration_methods,
            },
        );
        files.push((base_name.clone(), out));
    }

    for variant in &error.variants {
        let class_name = format!("{}Exception", variant.name);
        let sanitized_variant_doc = crate::codegen::doc_emission::sanitize_rust_idioms(
            &variant.doc,
            crate::codegen::doc_emission::DocTarget::CSharpDoc,
        );
        let variant_doc_lines: Vec<&str> = sanitized_variant_doc.lines().collect();
        let variant_has_doc = !sanitized_variant_doc.trim().is_empty();

        let out = crate::codegen::template_env::render(
            "error_gen/csharp_error_variant.jinja",
            crate::alef_context! {
                namespace => namespace,
                class_name => class_name.as_str(),
                base_name => base_name.as_str(),
                interfaces => shared_family_interfaces(errors, error, variant, names),
                doc => variant_has_doc,
                doc_lines => variant_doc_lines,
                has_methods => has_methods,
                extra_methods => csharp_extra_methods(errors, &class_name, last_error_getters),
                hides_apply => csharp_owner_applies_last_error(errors, &class_name, last_error_getters),
            },
        );
        files.push((class_name, out));
    }

    files
}

/// The nullable properties a shared C# variant class declares for the introspection methods only
/// its other families have, with the `ApplyLastError` statements that fill them.
///
/// The native last-error getters report a slot the raising error lacks as 0, an empty string or
/// -1, never as absent, so each assignment runs only for the native codes of the variants whose
/// family reports the value. When a raising variant has no stable `error_code` the family cannot
/// be told from the code; the assignment then runs for every code and the property documents the
/// native default instead of `null`.
fn csharp_extra_methods(errors: &[ErrorDef], class: &str, getters: &[super::LastErrorField]) -> Vec<serde_json::Value> {
    let raisers: Vec<(&ErrorDef, Option<u32>)> = errors
        .iter()
        .flat_map(|error| {
            error
                .variants
                .iter()
                .filter(|variant| format!("{}Exception", variant.name) == class)
                .map(move |variant| (error, variant.error_code))
        })
        .collect();
    let coded = raisers.iter().all(|(_, code)| code.is_some());
    shared_extra_methods(errors, class)
        .iter()
        .map(|method| {
            let cs_type = typeref_to_csharp_type(&method.return_type);
            let prop_name = to_pascal_case(&method.name);
            let codes: Vec<String> = raisers
                .iter()
                .filter(|(error, _)| {
                    super::lineage_methods(errors, &error.name)
                        .iter()
                        .any(|own| own.name == method.name)
                })
                .filter_map(|(_, code)| code.map(|code| format!("Code == {code}")))
                .collect();
            serde_json::json!({
                "cs_type": if cs_type.ends_with('?') { cs_type.to_string() } else { format!("{cs_type}?") },
                "prop_name": prop_name,
                "apply_lines": csharp_last_error_apply_lines(method, &prop_name, getters),
                "condition": if coded { codes.join(" || ") } else { String::new() },
            })
        })
        .collect()
}

/// Whether the base family of the shared class `class`, or a family it inherits from, has an
/// `ApplyLastError`, which the class's method for its additional properties then hides.
fn csharp_owner_applies_last_error(errors: &[ErrorDef], class: &str, getters: &[super::LastErrorField]) -> bool {
    super::shared_exception_classes(errors, super::ExceptionNaming::Nominal)
        .get(class)
        .and_then(|members| errors.iter().find(|error| error.name == members.families[0]))
        .is_some_and(|owner| {
            super::lineage_methods(errors, &owner.name)
                .iter()
                .any(|m| csharp_last_error_getter(m, getters).is_some())
        })
}

/// Map an IR `TypeRef` to a C# type string for error introspection properties.
pub(crate) fn typeref_to_csharp_type(ty: &crate::core::ir::TypeRef) -> &'static str {
    use crate::core::ir::{PrimitiveType, TypeRef};
    match duration_shape(ty) {
        Some(DurationShape::Optional) => return "TimeSpan?",
        Some(DurationShape::Bare) => return "TimeSpan",
        None => {}
    }
    match ty {
        TypeRef::Primitive(PrimitiveType::Bool) => "bool",
        TypeRef::Primitive(PrimitiveType::U8) => "byte",
        TypeRef::Primitive(PrimitiveType::I8) => "sbyte",
        TypeRef::Primitive(PrimitiveType::I16) => "short",
        TypeRef::Primitive(PrimitiveType::U16) => "ushort",
        TypeRef::Primitive(PrimitiveType::I32) => "int",
        TypeRef::Primitive(PrimitiveType::U32) => "uint",
        TypeRef::Primitive(PrimitiveType::I64 | PrimitiveType::Isize) => "long",
        TypeRef::Primitive(PrimitiveType::U64 | PrimitiveType::Usize) => "ulong",
        TypeRef::Primitive(PrimitiveType::F32) => "float",
        TypeRef::Primitive(PrimitiveType::F64) => "double",
        TypeRef::String => "string",
        _ => "string",
    }
}

/// Return the C# zero-value literal for a type (used in the default constructor).
pub(crate) fn csharp_default_value(ty: &crate::core::ir::TypeRef) -> &'static str {
    use crate::core::ir::{PrimitiveType, TypeRef};
    match duration_shape(ty) {
        Some(DurationShape::Optional) => return "null",
        Some(DurationShape::Bare) => return "TimeSpan.Zero",
        None => {}
    }
    match ty {
        TypeRef::Primitive(PrimitiveType::Bool) => "false",
        TypeRef::Primitive(_) => "0",
        _ => "string.Empty",
    }
}

/// Whether an error introspection method returns a `Duration`, and if so whether it is optional.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum DurationShape {
    Bare,
    Optional,
}

pub(crate) fn duration_shape(ty: &crate::core::ir::TypeRef) -> Option<DurationShape> {
    use crate::core::ir::TypeRef;
    match ty {
        TypeRef::Duration => Some(DurationShape::Bare),
        TypeRef::Optional(inner) if matches!(inner.as_ref(), TypeRef::Duration) => Some(DurationShape::Optional),
        _ => None,
    }
}

/// The methods the pre-`Duration` constructor overload keeps, plus whether any `Duration` method
/// exists at all.
///
/// Java and C# overload their base exception constructor with one parameter per introspection
/// method. A `Duration`-valued method such as `retry_after` was added after that signature
/// shipped, so the original overload keeps taking only the non-`Duration` methods and a second
/// overload takes them all; changing the existing signature would break every caller that
/// constructs the exception directly. ~keep
fn split_duration_methods(methods: &[serde_json::Value]) -> (Vec<serde_json::Value>, bool) {
    let legacy: Vec<serde_json::Value> = methods
        .iter()
        .filter(|m| m["is_duration"] != serde_json::Value::Bool(true))
        .cloned()
        .collect();
    let has_duration = legacy.len() != methods.len();
    (legacy, has_duration)
}

/// Name of the `NativeMethods` P/Invoke wrapping `<prefix>_last_error_<method>`.
pub(crate) fn csharp_last_error_getter_name(method_name: &str) -> String {
    format!("LastError{}", to_pascal_case(method_name))
}

/// Whether `error`'s `method` is populated from a `<prefix>_last_error_<method>` getter: the FFI
/// layer exports one only for a method of a capturable kind, and when two errors declare the same
/// name with different kinds it keeps the first, so a later error's differing method stays at its
/// default instead of reading a getter of the wrong type.
fn csharp_last_error_getter<'a>(
    method: &crate::core::ir::MethodDef,
    getters: &'a [super::LastErrorField],
) -> Option<&'a super::LastErrorField> {
    let kind = super::last_error_field_kind(method)?;
    getters
        .iter()
        .find(|field| field.name == method.name && field.kind == kind)
}

/// The `ApplyLastError` statements assigning one introspection property from its native getter,
/// empty when the method has none.
fn csharp_last_error_apply_lines(
    method: &crate::core::ir::MethodDef,
    prop_name: &str,
    getters: &[super::LastErrorField],
) -> Vec<String> {
    use super::LastErrorFieldKind;
    let Some(field) = csharp_last_error_getter(method, getters) else {
        return Vec::new();
    };
    let call = format!("NativeMethods.{}()", csharp_last_error_getter_name(&method.name));
    let local = java_field_name(&method.name);
    match &field.kind {
        LastErrorFieldKind::Scalar(_) => vec![format!("{prop_name} = {call};")],
        LastErrorFieldKind::Text => vec![
            format!("var {local}Ptr = {call};"),
            format!(
                "{prop_name} = {local}Ptr == IntPtr.Zero ? string.Empty : global::System.Runtime.InteropServices.Marshal.PtrToStringUTF8({local}Ptr) ?? string.Empty;"
            ),
        ],
        LastErrorFieldKind::DurationMillis => {
            let value = if matches!(method.return_type, crate::core::ir::TypeRef::Optional(_)) {
                format!("{local}Millis < 0 ? null : TimeSpan.FromMilliseconds({local}Millis)")
            } else {
                format!("TimeSpan.FromMilliseconds(Math.Max({local}Millis, 0L))")
            };
            vec![
                format!("var {local}Millis = {call};"),
                format!("{prop_name} = {value};"),
            ]
        }
    }
}

/// The base exception classes that carry an `ApplyLastError` method.
pub(crate) fn csharp_error_bases_with_last_error_fields(
    errors: &[ErrorDef],
    getters: &[super::LastErrorField],
) -> Vec<String> {
    errors
        .iter()
        .filter(|error| {
            error
                .methods
                .iter()
                .any(|m| csharp_last_error_getter(m, getters).is_some())
        })
        .map(|error| format!("{}Exception", error.name))
        .chain(
            super::shared_exception_classes(errors, super::ExceptionNaming::Nominal)
                .into_keys()
                .filter(|class| {
                    shared_extra_methods(errors, class)
                        .iter()
                        .any(|m| csharp_last_error_getter(m, getters).is_some())
                }),
        )
        .collect()
}