zerodds-idl-csharp 1.0.0-rc.6

OMG IDL4 → C# 10 code generator (idl4-csharp-1.0) for ZeroDDS.
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
// SPDX-License-Identifier: Apache-2.0
// Copyright 2026 ZeroDDS Contributors
//! AST walker that emits C# 12.0 source code.
//!
//! Phase 3.1 — Header layout: namespace hierarchy, using statements,
//! compiler pragmas.
//! Phase 3.2 — Type mapping (delegated to [`crate::type_map`]).
//! Phase 3.3 — Aggregate types: struct → record class, enum → enum,
//! union → discriminated record, typedef → using alias,
//! sequence → `IList<T>`, array → `T[]`, inheritance → `record class : Parent`.
//!
//! Emission is single-pass: all required `using` imports are collected
//! via a pre-walk, then the body is emitted.

use std::collections::BTreeSet;
use std::fmt::Write;

use zerodds_idl::ast::{
    Annotation, Case, CaseLabel, ConstExpr, ConstrTypeDecl, Declarator, Definition, EnumDef,
    ExceptDecl, Export, InterfaceDcl, InterfaceDef, Literal, LiteralKind, Member, ModuleDef,
    OpDecl, ParamAttribute, ScopedName, Specification, StateVisibility, StructDcl, StructDef,
    SwitchTypeSpec, TypeDecl, TypeSpec, TypedefDecl, UnionDcl, UnionDef, ValueDef, ValueElement,
};
use zerodds_idl::semantics::annotations::PlacementKind;

use crate::CsGenOptions;
use crate::annotations::{is_nested_type, member_attributes, type_attributes};
use crate::bitset::{emit_bitmask, emit_bitset};
use crate::error::CsGenError;
use crate::keywords::escape_identifier;
use crate::type_map::primitive_to_cs;
use crate::verbatim::emit_verbatim_at;

/// Known `using` imports. Order is stable-alphabetical.
#[derive(Debug, Default, Clone)]
struct Usings {
    imports: BTreeSet<&'static str>,
}

impl Usings {
    fn add(&mut self, h: &'static str) {
        self.imports.insert(h);
    }
}

/// Main entry point: produces a complete C# source text.
pub(crate) fn emit_source(spec: &Specification, opts: &CsGenOptions) -> Result<String, CsGenError> {
    // 1. Detect inheritance cycles.
    detect_inheritance_cycles(spec)?;

    // 1b. Build the type-kind resolver so the XCDR2 codec can tell a nested
    // struct (→ nested TypeSupport codec) from an enum (→ int32) / union
    // (→ gated) and resolve typedefs.
    crate::typesupport::build_type_registry(spec);

    // 2. Pre-walk: collect usings.
    let mut usings = Usings::default();
    usings.add("System");
    collect_usings(spec, &mut usings);

    // 3. Output buffer.
    let mut out = String::new();
    write_preamble(&mut out, &usings)?;

    // 4. Optional top-level namespace (`root_namespace`).
    let mut ctx = EmitCtx::new(opts);
    let outer_prefix: Option<&str> = opts.root_namespace.as_deref().filter(|p| !p.is_empty());
    if let Some(prefix) = outer_prefix {
        ctx.open_namespace(&mut out, prefix)?;
    }

    // 4b. §7.2.2.4.8 — `@verbatim(placement=BEGIN_FILE)` from all
    // top-level defs.
    for d in &spec.definitions {
        if let Some(anns) = top_level_annotations(d) {
            emit_verbatim_at(&mut out, "", anns, PlacementKind::BeginFile)?;
        }
    }

    // 5. Emit definitions.
    for d in &spec.definitions {
        emit_definition(&mut out, &mut ctx, d)?;
    }

    // 5b. §7.2.2.4.8 — `@verbatim(placement=END_FILE)`.
    for d in &spec.definitions {
        if let Some(anns) = top_level_annotations(d) {
            emit_verbatim_at(&mut out, "", anns, PlacementKind::EndFile)?;
        }
    }

    // 6. Close optional top-level namespace.
    if let Some(prefix) = outer_prefix {
        ctx.close_namespace(&mut out, prefix)?;
    }

    Ok(out)
}

/// Returns the annotation list of a top-level `Definition`, if
/// the variant carries one. Used for file-level verbatim.
fn top_level_annotations(d: &Definition) -> Option<&[Annotation]> {
    match d {
        Definition::Module(m) => Some(&m.annotations),
        Definition::Type(TypeDecl::Constr(c)) => match c {
            ConstrTypeDecl::Struct(StructDcl::Def(s)) => Some(&s.annotations),
            ConstrTypeDecl::Union(UnionDcl::Def(u)) => Some(&u.annotations),
            ConstrTypeDecl::Enum(e) => Some(&e.annotations),
            _ => None,
        },
        Definition::Type(TypeDecl::Typedef(t)) => Some(&t.annotations),
        Definition::Const(c) => Some(&c.annotations),
        Definition::Except(e) => Some(&e.annotations),
        _ => None,
    }
}

/// Writes the file header comment, `#nullable enable`, and `using` imports.
fn write_preamble(out: &mut String, usings: &Usings) -> Result<(), CsGenError> {
    writeln!(out, "// Generated by zerodds idl-csharp. Do not edit.").map_err(fmt_err)?;
    writeln!(out, "// Target: C# 12.0 / .NET 8+").map_err(fmt_err)?;
    writeln!(out, "#nullable enable").map_err(fmt_err)?;
    writeln!(out).map_err(fmt_err)?;
    for u in &usings.imports {
        writeln!(out, "using {u};").map_err(fmt_err)?;
    }
    writeln!(out).map_err(fmt_err)?;
    Ok(())
}

/// Walks the AST and collects required `using` imports.
fn collect_usings(spec: &Specification, u: &mut Usings) {
    for d in &spec.definitions {
        collect_in_def(d, u);
    }
}

/// zerodds-lint: recursion-depth 64 (Parser/AST-Walk; bounded by IDL nesting)
fn collect_in_def(d: &Definition, u: &mut Usings) {
    match d {
        Definition::Module(m) => {
            for sub in &m.definitions {
                collect_in_def(sub, u);
            }
        }
        Definition::Type(td) => collect_in_typedecl(td, u),
        Definition::Const(_) => {}
        Definition::Except(e) => {
            for m in &e.members {
                collect_in_typespec(&m.type_spec, u);
                if !member_attributes(&m.annotations).attrs.is_empty() {
                    u.add("Omg.Types");
                }
            }
        }
        Definition::Interface(zerodds_idl::ast::InterfaceDcl::Def(i)) => {
            // Embedded type/exception declarations inside an interface are
            // emitted nested (see emit_interface_stub) and need the same
            // runtime usings as their top-level counterparts.
            for export in &i.exports {
                match export {
                    zerodds_idl::ast::Export::Type(td) => collect_in_typedecl(td, u),
                    zerodds_idl::ast::Export::Except(e) => {
                        for m in &e.members {
                            collect_in_typespec(&m.type_spec, u);
                            if !member_attributes(&m.annotations).attrs.is_empty() {
                                u.add("Omg.Types");
                            }
                        }
                    }
                    zerodds_idl::ast::Export::Op(_)
                    | zerodds_idl::ast::Export::Attr(_)
                    | zerodds_idl::ast::Export::Const(_) => {}
                }
            }
        }
        Definition::Interface(_) // forward decl: nothing to collect
        | Definition::ValueBox(_)
        | Definition::ValueForward(_)
        | Definition::ValueDef(_)
        | Definition::TypeId(_)
        | Definition::TypePrefix(_)
        | Definition::Import(_)
        | Definition::Component(_)
        | Definition::Home(_)
        | Definition::Event(_)
        | Definition::Porttype(_)
        | Definition::Connector(_)
        | Definition::TemplateModule(_)
        | Definition::TemplateModuleInst(_)
        | Definition::Annotation(_)
        | Definition::VendorExtension(_) => {
            // Outside the current scope.
        }
    }
}

fn collect_in_typedecl(td: &TypeDecl, u: &mut Usings) {
    match td {
        TypeDecl::Constr(c) => match c {
            ConstrTypeDecl::Struct(StructDcl::Def(s)) => {
                // Top-level struct that is not @nested → ITopicType<T>
                // → needs using Omg.Types.
                if !is_nested_type(&s.annotations) {
                    u.add("Omg.Types");
                    // Spec zerodds-xcdr2-csharp-1.0 §3: TypeSupport class
                    // needs ZeroDDS.Cdr imports (IDdsTopicType, Xcdr2Writer,
                    // Xcdr2Reader, ExtensibilityKind, EndianMode, Md5).
                    u.add("ZeroDDS.Cdr");
                }
                if !type_attributes(&s.annotations).attrs.is_empty() {
                    u.add("Omg.Types");
                }
                for m in &s.members {
                    collect_in_typespec(&m.type_spec, u);
                    if !member_attributes(&m.annotations).attrs.is_empty() {
                        u.add("Omg.Types");
                    }
                }
            }
            ConstrTypeDecl::Struct(StructDcl::Forward(_)) => {}
            ConstrTypeDecl::Union(UnionDcl::Def(u_def)) => {
                // Top-level union is topic-capable → ITopicType<Self>.
                if !is_nested_type(&u_def.annotations) {
                    u.add("Omg.Types");
                    // CS-cluster #3: the union TypeSupport class needs the
                    // ZeroDDS.Cdr imports (IDdsTopicType, Xcdr2Writer/Reader,
                    // ExtensibilityKind, EndianMode).
                    if crate::typesupport::union_xcdr2_codecable(u_def) {
                        u.add("ZeroDDS.Cdr");
                    }
                }
                if !type_attributes(&u_def.annotations).attrs.is_empty() {
                    u.add("Omg.Types");
                }
                for c in &u_def.cases {
                    collect_in_typespec(&c.element.type_spec, u);
                }
            }
            ConstrTypeDecl::Union(UnionDcl::Forward(_)) => {}
            ConstrTypeDecl::Enum(_) | ConstrTypeDecl::Bitset(_) | ConstrTypeDecl::Bitmask(_) => {}
        },
        TypeDecl::Typedef(t) => {
            collect_in_typespec(&t.type_spec, u);
        }
        // `native X;` — opaque type, no usings.
        TypeDecl::Native(_) => {}
    }
}

/// zerodds-lint: recursion-depth 64 (Parser/AST-Walk; bounded by IDL nesting)
fn collect_in_typespec(ts: &TypeSpec, u: &mut Usings) {
    match ts {
        TypeSpec::Primitive(_) => {}
        TypeSpec::Scoped(_) => {}
        TypeSpec::Sequence(s) => {
            // ISequence<T> / IBoundedSequence<T> comes from Omg.Types,
            // IList<T> from System.Collections.Generic (base interface).
            u.add("System.Collections.Generic");
            u.add("Omg.Types");
            collect_in_typespec(&s.elem, u);
        }
        TypeSpec::String(_) => {
            // string is in the implicit "System" using.
        }
        TypeSpec::Map(m) => {
            u.add("System.Collections.Generic");
            collect_in_typespec(&m.key, u);
            collect_in_typespec(&m.value, u);
        }
        TypeSpec::Fixed(_) => {
            // `decimal` is built-in; no additional `using` needed.
        }
        TypeSpec::Any => {
            // `Omg.Types.Any` requires the Omg.Types namespace.
            // (shared runtime library with the annotations.)
        }
    }
}

/// Emit context (indentation, output, options).
struct EmitCtx<'o> {
    opts: &'o CsGenOptions,
    indent_level: usize,
    /// Stack of enclosing IDL module names (root → deepest).
    /// Used by the TypeSupport emitter to build the DDS type name
    /// (spec `zerodds-xcdr2-bindings-conformance-1.0` §5).
    module_path: Vec<String>,
}

impl<'o> EmitCtx<'o> {
    fn new(opts: &'o CsGenOptions) -> Self {
        Self {
            opts,
            indent_level: 0,
            module_path: Vec::new(),
        }
    }

    fn indent(&self) -> String {
        " ".repeat(self.indent_level * self.opts.indent_width)
    }

    fn open_namespace(&mut self, out: &mut String, name: &str) -> Result<(), CsGenError> {
        let escaped = escape_identifier(name)?;
        writeln!(out, "{}namespace {escaped}", self.indent()).map_err(fmt_err)?;
        writeln!(out, "{}{{", self.indent()).map_err(fmt_err)?;
        self.indent_level += 1;
        Ok(())
    }

    fn close_namespace(&mut self, out: &mut String, name: &str) -> Result<(), CsGenError> {
        self.indent_level = self.indent_level.saturating_sub(1);
        writeln!(out, "{}}} // namespace {name}", self.indent()).map_err(fmt_err)?;
        Ok(())
    }
}

/// zerodds-lint: recursion-depth 64 (Parser/AST-Walk; bounded by IDL nesting)
fn emit_definition(
    out: &mut String,
    ctx: &mut EmitCtx<'_>,
    def: &Definition,
) -> Result<(), CsGenError> {
    match def {
        Definition::Module(m) => emit_module(out, ctx, m),
        Definition::Type(td) => emit_type_decl(out, ctx, td),
        Definition::Const(c) => emit_const_decl(out, ctx, c),
        Definition::Except(e) => emit_exception(out, ctx, e),
        Definition::Interface(InterfaceDcl::Def(iface)) => {
            // Spec idl4-csharp §7.4: IDL interface -> C# interface.
            emit_interface_stub(out, ctx, iface)
        }
        Definition::Interface(InterfaceDcl::Forward(_)) => Ok(()),
        Definition::ValueDef(v) => emit_value_type(out, ctx, v),
        Definition::ValueBox(_) | Definition::ValueForward(_) => Ok(()),
        Definition::TypeId(_)
        | Definition::TypePrefix(_)
        | Definition::Import(_)
        | Definition::Component(_)
        | Definition::Home(_)
        | Definition::Event(_)
        | Definition::Porttype(_)
        | Definition::Connector(_)
        | Definition::TemplateModule(_)
        | Definition::TemplateModuleInst(_) => Err(CsGenError::UnsupportedConstruct {
            construct: "corba/ccm/template construct".into(),
            context: None,
        }),
        Definition::Annotation(_) => Ok(()), // §7.4.15: no direct C# mapping
        Definition::VendorExtension(v) => Err(CsGenError::UnsupportedConstruct {
            construct: format!("vendor-extension:{}", v.production_name),
            context: None,
        }),
    }
}

/// zerodds-lint: recursion-depth 64 (Parser/AST-Walk; bounded by IDL nesting)
fn emit_module(out: &mut String, ctx: &mut EmitCtx<'_>, m: &ModuleDef) -> Result<(), CsGenError> {
    ctx.open_namespace(out, &m.name.text)?;
    ctx.module_path.push(m.name.text.clone());
    for d in &m.definitions {
        emit_definition(out, ctx, d)?;
    }
    ctx.module_path.pop();
    ctx.close_namespace(out, &m.name.text)?;
    Ok(())
}

fn emit_type_decl(
    out: &mut String,
    ctx: &mut EmitCtx<'_>,
    td: &TypeDecl,
) -> Result<(), CsGenError> {
    match td {
        TypeDecl::Constr(c) => match c {
            ConstrTypeDecl::Struct(StructDcl::Def(s)) => emit_struct(out, ctx, s),
            ConstrTypeDecl::Struct(StructDcl::Forward(f)) => {
                let name = escape_identifier(&f.name.text)?;
                writeln!(out, "{}public partial record class {name};", ctx.indent())
                    .map_err(fmt_err)?;
                Ok(())
            }
            ConstrTypeDecl::Union(UnionDcl::Def(u)) => emit_union(out, ctx, u),
            ConstrTypeDecl::Union(UnionDcl::Forward(f)) => {
                let name = escape_identifier(&f.name.text)?;
                writeln!(out, "{}public partial record class {name};", ctx.indent())
                    .map_err(fmt_err)?;
                Ok(())
            }
            ConstrTypeDecl::Enum(e) => emit_enum(out, ctx, e),
            ConstrTypeDecl::Bitset(b) => {
                let ind = ctx.indent();
                let inner = " ".repeat((ctx.indent_level + 1) * ctx.opts.indent_width);
                emit_bitset(out, &ind, &inner, b)
            }
            ConstrTypeDecl::Bitmask(b) => {
                let ind = ctx.indent();
                let inner = " ".repeat((ctx.indent_level + 1) * ctx.opts.indent_width);
                emit_bitmask(out, &ind, &inner, b)
            }
        },
        TypeDecl::Typedef(t) => emit_typedef(out, ctx, t),
        // `native X;` — opaque, platform-specific type with no XCDR2 wire
        // representation; not emitted in DataType codegen.
        TypeDecl::Native(_) => Ok(()),
    }
}

fn emit_struct(out: &mut String, ctx: &mut EmitCtx<'_>, s: &StructDef) -> Result<(), CsGenError> {
    let _name = escape_identifier(&s.name.text)?;
    let _ = _name;
    emit_struct_inner(out, ctx, s)?;
    // Spec zerodds-xcdr2-csharp-1.0 §3 / §4: each `struct` with an XCDR2 wire
    // codec MUST have a `*TypeSupport` class emitted — INCLUDING a `@nested`
    // struct: a nested type is never a standalone topic (no `ITopicType<T>`
    // marker, see `emit_struct_inner`), but a struct that USES it as a member
    // generates `<Name>TypeSupport.Instance.EncodeInto/DecodeFrom` calls, so the
    // TypeSupport class must exist or the parent's codec fails to compile
    // (e.g. `@nested @final NestedKey` inside `OuterKey`). The `IDdsTopicType<T>`
    // surface it carries (Encode/Decode/KeyHash) is harmless for a nested type —
    // it is simply never registered as a topic.
    // A struct with a map/fixed/any member has no XCDR2 wire codec yet (see
    // `struct_xcdr2_codecable`); emit the data type but skip the TypeSupport
    // rather than a codec that throws `XcdrException` at runtime.
    if crate::typesupport::struct_xcdr2_codecable(s) {
        let ind = ctx.indent();
        let inner = " ".repeat((ctx.indent_level + 1) * ctx.opts.indent_width);
        let deeper = " ".repeat((ctx.indent_level + 2) * ctx.opts.indent_width);
        let tctx = crate::typesupport::TsEmitContext {
            module_path: &ctx.module_path,
            indent: &ind,
            inner_indent: &inner,
            deeper_indent: &deeper,
        };
        crate::typesupport::emit_typesupport_class(out, &tctx, s)?;
    } else if !is_nested_type(&s.annotations) {
        writeln!(
            out,
            "{}// {}: no XCDR2 TypeSupport — contains a map/fixed/any member (no wire codec yet).",
            ctx.indent(),
            escape_identifier(&s.name.text)?,
        )
        .map_err(fmt_err)?;
    }
    // §7.2.2.4.8 verbatim AFTER_DECLARATION is emitted after the TypeSupport
    // so that trailer markers land outside the record block AND
    // outside the TypeSupport class.
    emit_verbatim_at(
        out,
        &ctx.indent(),
        &s.annotations,
        PlacementKind::AfterDeclaration,
    )?;
    Ok(())
}

fn emit_struct_inner(
    out: &mut String,
    ctx: &mut EmitCtx<'_>,
    s: &StructDef,
) -> Result<(), CsGenError> {
    let name = escape_identifier(&s.name.text)?;
    let ind = ctx.indent();

    emit_verbatim_at(out, &ind, &s.annotations, PlacementKind::BeforeDeclaration)?;

    // C5.3-b: Type-level annotations as C# attributes before the record class.
    let type_attrs = type_attributes(&s.annotations);
    for a in &type_attrs.attrs {
        writeln!(out, "{ind}{a}").map_err(fmt_err)?;
    }

    // C5.3-b: ITopicType<Self> marker for top-level structs.
    // `@nested` (regardless of type-level annotation, default false for
    // top-level structs) marks nested types that MUST NOT be a topic.
    // We build the marker list from base inheritance + ITopicType<Self>.
    let topic_marker = !is_nested_type(&s.annotations);
    let mut bases: Vec<String> = Vec::new();
    if let Some(base) = &s.base {
        bases.push(scoped_to_cs(base)?);
    }
    if topic_marker {
        bases.push(format!("ITopicType<{name}>"));
    }

    if bases.is_empty() {
        writeln!(out, "{ind}public partial record class {name}").map_err(fmt_err)?;
    } else {
        let joined = bases.join(", ");
        writeln!(out, "{ind}public partial record class {name} : {joined}").map_err(fmt_err)?;
    }
    writeln!(out, "{ind}{{").map_err(fmt_err)?;

    let inner = " ".repeat((ctx.indent_level + 1) * ctx.opts.indent_width);
    emit_verbatim_at(out, &inner, &s.annotations, PlacementKind::BeginDeclaration)?;

    // Properties (init-only) — Reference-Pattern per Spec.
    for m in &s.members {
        emit_struct_member_property(out, &inner, m)?;
    }

    emit_verbatim_at(out, &inner, &s.annotations, PlacementKind::EndDeclaration)?;
    writeln!(out, "{ind}}}").map_err(fmt_err)?;
    writeln!(out).map_err(fmt_err)?;
    Ok(())
}

fn emit_struct_member_property(
    out: &mut String,
    inner: &str,
    m: &Member,
) -> Result<(), CsGenError> {
    let attrs = member_attributes(&m.annotations);
    for decl in &m.declarators {
        let cs_ty = type_for_declarator(&m.type_spec, decl)?;
        let name = escape_identifier(&decl.name().text)?;
        let pascal = pascal_case(&decl.name().text);
        let prop_name = if name == pascal { name.clone() } else { pascal };
        let storage_ty = if attrs.optional {
            format!("{cs_ty}?")
        } else {
            cs_ty
        };
        for a in &attrs.attrs {
            writeln!(out, "{inner}{a}").map_err(fmt_err)?;
        }
        writeln!(
            out,
            "{inner}public {storage_ty} {prop_name} {{ get; init; }} = default!;"
        )
        .map_err(fmt_err)?;
    }
    Ok(())
}

fn emit_union(out: &mut String, ctx: &mut EmitCtx<'_>, u: &UnionDef) -> Result<(), CsGenError> {
    let name = escape_identifier(&u.name.text)?;
    let ind = ctx.indent();
    let inner = " ".repeat((ctx.indent_level + 1) * ctx.opts.indent_width);

    let disc_ty = switch_type_to_cs(&u.switch_type)?;

    emit_verbatim_at(out, &ind, &u.annotations, PlacementKind::BeforeDeclaration)?;

    // C5.3-b: Type-level annotations before the union record class.
    let type_attrs = type_attributes(&u.annotations);
    for a in &type_attrs.attrs {
        writeln!(out, "{ind}{a}").map_err(fmt_err)?;
    }

    // Discriminated record class: one Discriminator + one object Value.
    // Unions are also topic-capable in C# (DDS allows unions as topics).
    let topic_marker = !is_nested_type(&u.annotations);
    if topic_marker {
        writeln!(
            out,
            "{ind}public partial record class {name} : ITopicType<{name}>"
        )
        .map_err(fmt_err)?;
    } else {
        writeln!(out, "{ind}public partial record class {name}").map_err(fmt_err)?;
    }
    writeln!(out, "{ind}{{").map_err(fmt_err)?;
    emit_verbatim_at(out, &inner, &u.annotations, PlacementKind::BeginDeclaration)?;
    writeln!(
        out,
        "{inner}public {disc_ty} Discriminator {{ get; init; }} = default!;"
    )
    .map_err(fmt_err)?;
    writeln!(
        out,
        "{inner}public object? Value {{ get; init; }} = default;"
    )
    .map_err(fmt_err)?;
    writeln!(out).map_err(fmt_err)?;

    // Branch markers as comments.
    let mut has_default = false;
    for c in &u.cases {
        emit_union_case_comment(out, &inner, c, &mut has_default)?;
    }
    if !has_default {
        writeln!(out, "{inner}// no explicit 'default:' branch").map_err(fmt_err)?;
    }

    emit_verbatim_at(out, &inner, &u.annotations, PlacementKind::EndDeclaration)?;
    writeln!(out, "{ind}}}").map_err(fmt_err)?;
    writeln!(out).map_err(fmt_err)?;

    // CS-cluster #3: a top-level (non-@nested) union gets a real *TypeSupport
    // class with a working XCDR2 encode/decode — provided every case element
    // type is codecable.
    if !is_nested_type(&u.annotations) && crate::typesupport::union_xcdr2_codecable(u) {
        let deeper = " ".repeat((ctx.indent_level + 2) * ctx.opts.indent_width);
        let tctx = crate::typesupport::TsEmitContext {
            module_path: &ctx.module_path,
            indent: &ind,
            inner_indent: &inner,
            deeper_indent: &deeper,
        };
        crate::typesupport::emit_union_typesupport_class(out, &tctx, u)?;
    }

    emit_verbatim_at(out, &ind, &u.annotations, PlacementKind::AfterDeclaration)?;
    writeln!(out).map_err(fmt_err)?;
    Ok(())
}

fn emit_union_case_comment(
    out: &mut String,
    inner: &str,
    c: &Case,
    has_default: &mut bool,
) -> Result<(), CsGenError> {
    for label in &c.labels {
        match label {
            CaseLabel::Default => {
                *has_default = true;
                writeln!(
                    out,
                    "{inner}// case default -> {}",
                    declarator_name(&c.element.declarator)
                )
                .map_err(fmt_err)?;
            }
            CaseLabel::Value(expr) => {
                let val = const_expr_to_cs(expr);
                writeln!(
                    out,
                    "{inner}// case {val} -> {}",
                    declarator_name(&c.element.declarator)
                )
                .map_err(fmt_err)?;
            }
        }
    }
    Ok(())
}

fn declarator_name(d: &Declarator) -> &str {
    &d.name().text
}

fn emit_enum(out: &mut String, ctx: &mut EmitCtx<'_>, e: &EnumDef) -> Result<(), CsGenError> {
    let name = escape_identifier(&e.name.text)?;
    let ind = ctx.indent();
    emit_verbatim_at(out, &ind, &e.annotations, PlacementKind::BeforeDeclaration)?;
    writeln!(out, "{ind}public enum {name} : int").map_err(fmt_err)?;
    writeln!(out, "{ind}{{").map_err(fmt_err)?;
    let inner = " ".repeat((ctx.indent_level + 1) * ctx.opts.indent_width);
    emit_verbatim_at(out, &inner, &e.annotations, PlacementKind::BeginDeclaration)?;
    for en in &e.enumerators {
        let en_name = escape_identifier(&en.name.text)?;
        writeln!(out, "{inner}{en_name},").map_err(fmt_err)?;
    }
    emit_verbatim_at(out, &inner, &e.annotations, PlacementKind::EndDeclaration)?;
    writeln!(out, "{ind}}}").map_err(fmt_err)?;
    emit_verbatim_at(out, &ind, &e.annotations, PlacementKind::AfterDeclaration)?;
    writeln!(out).map_err(fmt_err)?;
    Ok(())
}

fn emit_interface_stub(
    out: &mut String,
    ctx: &mut EmitCtx<'_>,
    iface: &InterfaceDef,
) -> Result<(), CsGenError> {
    let name = escape_identifier(&iface.name.text)?;
    let ind = ctx.indent();
    let inner = " ".repeat((ctx.indent_level + 1) * ctx.opts.indent_width);

    // Spec idl4-csharp §7.4: Bases via `: Base1, Base2`.
    let bases: Vec<String> = iface
        .bases
        .iter()
        .map(scoped_to_cs)
        .collect::<Result<Vec<_>, _>>()?;
    if bases.is_empty() {
        writeln!(out, "{ind}public interface {name}").map_err(fmt_err)?;
    } else {
        writeln!(out, "{ind}public interface {name} : {}", bases.join(", ")).map_err(fmt_err)?;
    }
    writeln!(out, "{ind}{{").map_err(fmt_err)?;

    for export in &iface.exports {
        match export {
            zerodds_idl::ast::Export::Op(op) => emit_interface_op_cs(out, &inner, op)?,
            zerodds_idl::ast::Export::Attr(attr) => emit_interface_attr_cs(out, &inner, attr)?,
            // Embedded type/const/exception declarations (IDL allows them inside
            // an interface). C# 8+ permits nested types and constants inside an
            // interface, so we emit them nested one level in — reusing the same
            // emitters as the top-level path.
            zerodds_idl::ast::Export::Type(td) => {
                ctx.indent_level += 1;
                let r = emit_type_decl(out, ctx, td);
                ctx.indent_level -= 1;
                r?;
            }
            zerodds_idl::ast::Export::Const(c) => {
                ctx.indent_level += 1;
                let r = emit_const_decl(out, ctx, c);
                ctx.indent_level -= 1;
                r?;
            }
            zerodds_idl::ast::Export::Except(e) => {
                ctx.indent_level += 1;
                let r = emit_exception(out, ctx, e);
                ctx.indent_level -= 1;
                r?;
            }
        }
    }

    writeln!(out, "{ind}}}").map_err(fmt_err)?;
    writeln!(out).map_err(fmt_err)?;
    Ok(())
}

fn emit_interface_op_cs(out: &mut String, inner: &str, op: &OpDecl) -> Result<(), CsGenError> {
    let name = escape_identifier(&op.name.text)?;
    let ret = match &op.return_type {
        None => "void".to_string(),
        Some(t) => typespec_to_cs(t)?,
    };
    let params: Vec<String> = op
        .params
        .iter()
        .map(|p| -> Result<String, CsGenError> {
            let ty = typespec_to_cs(&p.type_spec)?;
            // C# in/out/ref Modifier per Spec idl4-csharp §7.4.5.
            let modifier = match p.attribute {
                ParamAttribute::In => "",
                ParamAttribute::Out => "out ",
                ParamAttribute::InOut => "ref ",
            };
            let pname = escape_identifier(&p.name.text)?;
            Ok(format!("{modifier}{ty} {pname}"))
        })
        .collect::<Result<_, _>>()?;
    writeln!(out, "{inner}{ret} {name}({});", params.join(", ")).map_err(fmt_err)?;
    Ok(())
}

fn emit_interface_attr_cs(
    out: &mut String,
    inner: &str,
    attr: &zerodds_idl::ast::AttrDecl,
) -> Result<(), CsGenError> {
    let name = escape_identifier(&attr.name.text)?;
    let pascal = pascal_case(&attr.name.text);
    let prop_name = if name == pascal { name.clone() } else { pascal };
    let ty = typespec_to_cs(&attr.type_spec)?;
    if attr.readonly {
        writeln!(out, "{inner}{ty} {prop_name} {{ get; }}").map_err(fmt_err)?;
    } else {
        writeln!(out, "{inner}{ty} {prop_name} {{ get; set; }}").map_err(fmt_err)?;
    }
    Ok(())
}

fn emit_value_type(
    out: &mut String,
    ctx: &mut EmitCtx<'_>,
    v: &ValueDef,
) -> Result<(), CsGenError> {
    let name = escape_identifier(&v.name.text)?;
    let ind = ctx.indent();
    let inner = " ".repeat((ctx.indent_level + 1) * ctx.opts.indent_width);

    // Spec idl4-csharp §7.6: valuetype -> 2 C#-Klassen:
    // <Name>Abstract (abstract class) + <Name> (concrete subclass).
    // Public state -> public abstract property (with get; set;).
    // Private state -> protected abstract Property.
    // Factory -> public abstract Method (returns void per Spec).
    let mut bases: Vec<String> = Vec::new();
    if let Some(inh) = &v.inheritance {
        for b in &inh.bases {
            bases.push(format!("{}Abstract", scoped_to_cs(b)?));
        }
        for s in &inh.supports {
            bases.push(scoped_to_cs(s)?);
        }
    }
    let abstract_name = format!("{name}Abstract");
    if bases.is_empty() {
        writeln!(out, "{ind}public abstract class {abstract_name}").map_err(fmt_err)?;
    } else {
        writeln!(
            out,
            "{ind}public abstract class {abstract_name} : {}",
            bases.join(", ")
        )
        .map_err(fmt_err)?;
    }
    writeln!(out, "{ind}{{").map_err(fmt_err)?;

    for el in &v.elements {
        match el {
            ValueElement::State(s) => {
                let ty = typespec_to_cs(&s.type_spec)?;
                let visibility = match s.visibility {
                    StateVisibility::Public => "public",
                    StateVisibility::Private => "protected",
                };
                for d in &s.declarators {
                    let pname = pascal_case(&d.name().text);
                    writeln!(
                        out,
                        "{inner}{visibility} abstract {ty} {pname} {{ get; set; }}"
                    )
                    .map_err(fmt_err)?;
                }
            }
            ValueElement::Init(i) => {
                let params: Vec<String> = i
                    .params
                    .iter()
                    .map(|p| -> Result<String, CsGenError> {
                        let ty = typespec_to_cs(&p.type_spec)?;
                        let pname = escape_identifier(&p.name.text)?;
                        Ok(format!("{ty} {pname}"))
                    })
                    .collect::<Result<_, _>>()?;
                let fname = escape_identifier(&i.name.text)?;
                writeln!(
                    out,
                    "{inner}public abstract void {fname}({});",
                    params.join(", ")
                )
                .map_err(fmt_err)?;
            }
            ValueElement::Export(Export::Op(op)) => {
                emit_interface_op_cs(out, &inner, op)?;
            }
            ValueElement::Export(Export::Attr(a)) => {
                emit_interface_attr_cs(out, &inner, a)?;
            }
            _ => {}
        }
    }
    writeln!(out, "{ind}}}").map_err(fmt_err)?;
    writeln!(out).map_err(fmt_err)?;

    // Concrete-Subclass-Skelett (app-fillung).
    writeln!(
        out,
        "{ind}public class {name} : {abstract_name} {{ /* user impl */ }}"
    )
    .map_err(fmt_err)?;
    writeln!(out).map_err(fmt_err)?;
    Ok(())
}

fn emit_typedef(
    out: &mut String,
    ctx: &mut EmitCtx<'_>,
    t: &TypedefDecl,
) -> Result<(), CsGenError> {
    let ind = ctx.indent();
    for decl in &t.declarators {
        let alias = escape_identifier(&decl.name().text)?;
        let target_ty = type_for_declarator(&t.type_spec, decl)?;
        // C# 12.0: `using <Alias> = <Type>;` — File-Level using-alias-Syntax.
        // Inside a namespace the alias must be hoisted;
        // foundation approximation: emit as a comment + property-less
        // record class as a wrapper. The spec-conformant variant comes with
        // C5.3-b (file-scoped namespace + top-level using).
        writeln!(out, "{ind}// typedef {target_ty} {alias};").map_err(fmt_err)?;
        writeln!(
            out,
            "{ind}public sealed record class {alias}({target_ty} Value);"
        )
        .map_err(fmt_err)?;
    }
    writeln!(out).map_err(fmt_err)?;
    Ok(())
}

fn emit_const_decl(
    out: &mut String,
    ctx: &mut EmitCtx<'_>,
    c: &zerodds_idl::ast::ConstDecl,
) -> Result<(), CsGenError> {
    let name = escape_identifier(&c.name.text)?;
    let ind = ctx.indent();
    let cs_ty = match &c.type_ {
        zerodds_idl::ast::ConstType::Integer(i) => crate::type_map::integer_to_cs(*i).to_string(),
        zerodds_idl::ast::ConstType::Floating(f) => crate::type_map::floating_to_cs(*f).to_string(),
        zerodds_idl::ast::ConstType::Boolean => "bool".into(),
        zerodds_idl::ast::ConstType::Char => "char".into(),
        zerodds_idl::ast::ConstType::WideChar => "char".into(),
        zerodds_idl::ast::ConstType::Octet => "byte".into(),
        zerodds_idl::ast::ConstType::String { wide: false } => "string".into(),
        zerodds_idl::ast::ConstType::String { wide: true } => "string".into(),
        zerodds_idl::ast::ConstType::Scoped(s) => scoped_to_cs(s)?,
        zerodds_idl::ast::ConstType::Fixed => "decimal".into(),
    };
    let val = const_expr_to_cs(&c.value);
    // `const` in C# is only allowed for compile-time-constant primitives.
    // Foundation approximation: emit as `public const <T> NAME = <val>;`.
    writeln!(out, "{ind}public const {cs_ty} {name} = {val};").map_err(fmt_err)?;
    Ok(())
}

fn emit_exception(
    out: &mut String,
    ctx: &mut EmitCtx<'_>,
    e: &ExceptDecl,
) -> Result<(), CsGenError> {
    let name = escape_identifier(&e.name.text)?;
    let ind = ctx.indent();
    let inner = " ".repeat((ctx.indent_level + 1) * ctx.opts.indent_width);
    writeln!(out, "{ind}public sealed class {name} : Exception").map_err(fmt_err)?;
    writeln!(out, "{ind}{{").map_err(fmt_err)?;
    writeln!(out, "{inner}public {name}() : base() {{ }}").map_err(fmt_err)?;
    writeln!(
        out,
        "{inner}public {name}(string message) : base(message) {{ }}"
    )
    .map_err(fmt_err)?;
    for m in &e.members {
        for decl in &m.declarators {
            let cs_ty = type_for_declarator(&m.type_spec, decl)?;
            let prop_name = pascal_case(&decl.name().text);
            writeln!(
                out,
                "{inner}public {cs_ty} {prop_name} {{ get; init; }} = default!;"
            )
            .map_err(fmt_err)?;
        }
    }
    writeln!(out, "{ind}}}").map_err(fmt_err)?;
    writeln!(out).map_err(fmt_err)?;
    Ok(())
}

// ---------------------------------------------------------------------------
// TypeSpec → C# type expression
// ---------------------------------------------------------------------------

/// Returns the C# type expression for a member (TypeSpec + Declarator).
/// Array declarators are nested as jagged `T[]` (`int[][]` for 2D),
/// because C# has two conventions for multi-dim arrays; jagged is the spec default.
fn type_for_declarator(ts: &TypeSpec, decl: &Declarator) -> Result<String, CsGenError> {
    let base = typespec_to_cs(ts)?;
    match decl {
        Declarator::Simple(_) => Ok(base),
        Declarator::Array(arr) => {
            // arr.sizes[0] = outermost dimension. Jagged mapping:
            // `int x[2][3]` → `int[][]` (bound check in the setter; the foundation
            // emits no setters, that comes with C5.3-b).
            let mut out = base;
            for _ in &arr.sizes {
                out = format!("{out}[]");
            }
            Ok(out)
        }
    }
}

/// zerodds-lint: recursion-depth 64 (Parser/AST-Walk; bounded by IDL nesting)
fn typespec_to_cs(ts: &TypeSpec) -> Result<String, CsGenError> {
    match ts {
        TypeSpec::Primitive(p) => Ok(primitive_to_cs(*p).to_string()),
        TypeSpec::Scoped(s) => scoped_to_cs(s),
        TypeSpec::Sequence(s) => {
            let inner = typespec_to_cs(&s.elem)?;
            // C5.3-b §7.4: bounded → IBoundedSequence<T>, unbounded → ISequence<T>.
            if s.bound.is_some() {
                Ok(format!("IBoundedSequence<{inner}>"))
            } else {
                Ok(format!("ISequence<{inner}>"))
            }
        }
        TypeSpec::String(_) => Ok("string".into()),
        TypeSpec::Map(m) => {
            let k = typespec_to_cs(&m.key)?;
            let v = typespec_to_cs(&m.value)?;
            Ok(format!("IDictionary<{k}, {v}>"))
        }
        TypeSpec::Fixed(_) => {
            // Spec idl4-csharp §7.2.4.2.4: fixed<digits,scale> ->
            // C# `decimal` (28-29 digit decimal precision, range-
            // exceeding values throw System.OverflowException).
            // Digits/scale are documented in the codegen output via an
            // XML doc comment (a comment suffices, the decimal built-in has
            // no generic parameters).
            Ok("decimal".into())
        }
        TypeSpec::Any => {
            // Spec idl4-csharp §7.3: any -> `Omg.Types.Any` (reflective
            // container, runtime implementation in the Omg.Types library).
            // Cross-ref CORBA migration; the ZeroDDS default mapping is
            // C# `object` (nullable reference, runtime-typed).
            Ok("Omg.Types.Any".into())
        }
    }
}

fn switch_type_to_cs(s: &SwitchTypeSpec) -> Result<String, CsGenError> {
    Ok(match s {
        SwitchTypeSpec::Integer(i) => crate::type_map::integer_to_cs(*i).to_string(),
        SwitchTypeSpec::Char => "char".into(),
        SwitchTypeSpec::Boolean => "bool".into(),
        SwitchTypeSpec::Octet => "byte".into(),
        SwitchTypeSpec::Scoped(s) => scoped_to_cs(s)?,
    })
}

fn scoped_to_cs(s: &ScopedName) -> Result<String, CsGenError> {
    let mut parts: Vec<String> = Vec::with_capacity(s.parts.len());
    for p in &s.parts {
        parts.push(escape_identifier(&p.text)?);
    }
    let joined = parts.join(".");
    if s.absolute {
        Ok(format!("global::{joined}"))
    } else {
        Ok(joined)
    }
}

// ---------------------------------------------------------------------------
// ConstExpr → C#-Literal-String
// ---------------------------------------------------------------------------

pub(crate) fn const_expr_to_cs(e: &ConstExpr) -> String {
    match e {
        ConstExpr::Literal(l) => literal_to_cs(l),
        ConstExpr::Scoped(s) => match scoped_to_cs(s) {
            Ok(v) => v,
            Err(_) => s
                .parts
                .iter()
                .map(|p| p.text.clone())
                .collect::<Vec<_>>()
                .join("."),
        },
        ConstExpr::Unary { op, operand, .. } => {
            let prefix = match op {
                zerodds_idl::ast::UnaryOp::Plus => "+",
                zerodds_idl::ast::UnaryOp::Minus => "-",
                zerodds_idl::ast::UnaryOp::BitNot => "~",
            };
            format!("{prefix}{}", const_expr_to_cs(operand))
        }
        ConstExpr::Binary { op, lhs, rhs, .. } => {
            let opstr = match op {
                zerodds_idl::ast::BinaryOp::Or => "|",
                zerodds_idl::ast::BinaryOp::Xor => "^",
                zerodds_idl::ast::BinaryOp::And => "&",
                zerodds_idl::ast::BinaryOp::Shl => "<<",
                zerodds_idl::ast::BinaryOp::Shr => ">>",
                zerodds_idl::ast::BinaryOp::Add => "+",
                zerodds_idl::ast::BinaryOp::Sub => "-",
                zerodds_idl::ast::BinaryOp::Mul => "*",
                zerodds_idl::ast::BinaryOp::Div => "/",
                zerodds_idl::ast::BinaryOp::Mod => "%",
            };
            format!(
                "({} {opstr} {})",
                const_expr_to_cs(lhs),
                const_expr_to_cs(rhs)
            )
        }
    }
}

fn literal_to_cs(l: &Literal) -> String {
    match l.kind {
        LiteralKind::Boolean => l.raw.clone(),
        LiteralKind::Integer | LiteralKind::Floating => l.raw.clone(),
        LiteralKind::Char => l.raw.clone(),
        LiteralKind::WideChar => l.raw.clone(),
        LiteralKind::String => l.raw.clone(),
        LiteralKind::WideString => l.raw.clone(),
        LiteralKind::Fixed => l.raw.clone(),
    }
}

// ---------------------------------------------------------------------------
// Annotation helpers — see `crate::annotations` for the bridge to the
// typed BuiltinAnnotation lower forms.
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// Naming-Helpers
// ---------------------------------------------------------------------------

/// Converts `snake_case` → `PascalCase`, for the C# property convention.
/// IDL-Member-Name `sensor_id` → C#-Property `SensorId`.
fn pascal_case(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut upper_next = true;
    for c in s.chars() {
        if c == '_' {
            upper_next = true;
            continue;
        }
        if upper_next {
            for u in c.to_uppercase() {
                out.push(u);
            }
            upper_next = false;
        } else {
            out.push(c);
        }
    }
    if out.is_empty() {
        return s.to_string();
    }
    out
}

// ---------------------------------------------------------------------------
// Inheritance-Cycle-Detection
// ---------------------------------------------------------------------------

/// zerodds-lint: recursion-depth 64 (Parser/AST-Walk; bounded by IDL nesting)
fn collect_inheritance_edges(
    defs: &[Definition],
    parents: &mut std::collections::HashMap<String, String>,
    prefix: &str,
) {
    for d in defs {
        match d {
            Definition::Module(m) => {
                let new_prefix = if prefix.is_empty() {
                    m.name.text.clone()
                } else {
                    format!("{prefix}.{}", m.name.text)
                };
                collect_inheritance_edges(&m.definitions, parents, &new_prefix);
            }
            Definition::Type(TypeDecl::Constr(ConstrTypeDecl::Struct(StructDcl::Def(s)))) => {
                let key = if prefix.is_empty() {
                    s.name.text.clone()
                } else {
                    format!("{prefix}.{}", s.name.text)
                };
                if let Some(b) = &s.base {
                    let base_str = b
                        .parts
                        .iter()
                        .map(|p| p.text.clone())
                        .collect::<Vec<_>>()
                        .join(".");
                    parents.insert(key, base_str);
                }
            }
            _ => {}
        }
    }
}

fn detect_inheritance_cycles(spec: &Specification) -> Result<(), CsGenError> {
    use std::collections::HashMap;

    let mut parents: HashMap<String, String> = HashMap::new();
    collect_inheritance_edges(&spec.definitions, &mut parents, "");

    for start in parents.keys() {
        let mut current = start.clone();
        let mut visited: BTreeSet<String> = BTreeSet::new();
        visited.insert(current.clone());
        while let Some(p) = parents.get(&current) {
            let resolved = parents
                .keys()
                .find(|k| *k == p || k.ends_with(&format!(".{p}")))
                .cloned()
                .unwrap_or_else(|| p.clone());
            if visited.contains(&resolved) {
                return Err(CsGenError::InheritanceCycle {
                    type_name: short_name(&resolved),
                });
            }
            visited.insert(resolved.clone());
            if resolved == current {
                return Err(CsGenError::InheritanceCycle {
                    type_name: short_name(&resolved),
                });
            }
            current = resolved;
            if !parents.contains_key(&current) {
                break;
            }
        }
    }
    Ok(())
}

fn short_name(s: &str) -> String {
    s.rsplit('.').next().unwrap_or(s).to_string()
}

// ---------------------------------------------------------------------------
// fmt-Error-Bridge
// ---------------------------------------------------------------------------

fn fmt_err(_: core::fmt::Error) -> CsGenError {
    CsGenError::Internal("string formatting failed".into())
}

#[cfg(test)]
mod tests {
    #![allow(clippy::expect_used, clippy::panic)]
    use super::*;

    #[test]
    fn pascal_case_simple() {
        assert_eq!(pascal_case("foo"), "Foo");
    }

    #[test]
    fn pascal_case_snake() {
        assert_eq!(pascal_case("sensor_id"), "SensorId");
    }

    #[test]
    fn pascal_case_already_pascal() {
        assert_eq!(pascal_case("SensorId"), "SensorId");
    }

    #[test]
    fn pascal_case_empty() {
        assert_eq!(pascal_case(""), "");
    }

    #[test]
    fn pascal_case_multi_underscore() {
        assert_eq!(pascal_case("a_b_c"), "ABC");
    }

    #[test]
    fn short_name_strips_namespace() {
        assert_eq!(short_name("A.B.C"), "C");
        assert_eq!(short_name("Foo"), "Foo");
    }
}