zerodds-ami4ccm 1.0.0-rc.1

OMG AMI4CCM 1.1 (formal/2015-08-03) — Async-Method-Invocation fuer CCM: Implied-IDL-Transformation (§7.3 + §7.5), ReplyHandler/ExceptionHolder-Modell (§7.4), Pragma-Parsing (§7.7). no_std + alloc.
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
// SPDX-License-Identifier: Apache-2.0
// Copyright 2026 ZeroDDS Contributors

//! Implied-IDL-Transformation — Spec §7.3 + §7.5.
//!
//! Eingabe: [`InterfaceDef`] eines normalen IDL-Interfaces.
//! Ausgabe: zwei `InterfaceKind::Local` Interfaces (Spec §7.3 + §7.5):
//!
//! 1. `AMI4CCM_<Iface>ReplyHandler` (Spec §7.5) — Type-spezifische
//!    Reply-Handler mit normal-reply + `_excep`-Operations.
//! 2. `AMI4CCM_<Iface>` (Spec §7.3) — Async-Operations mit
//!    `sendc_`-Praefix.
//!
//! Spec §7.3.1 (S. 7) — Naming-Conflict-Aufloesung: wenn der generierte
//! `sendc_<op>`-Name bereits im Interface existiert, werden `ami_`-
//! Praefixe zwischen `sendc_` und `<op>` eingefuegt, bis der Name
//! eindeutig ist. Dieselbe Regel gilt fuer `<op>_excep` im
//! ReplyHandler (Spec §7.5.2, S. 10).

use alloc::collections::BTreeSet;
use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec::Vec;

use zerodds_idl::ast::{
    AttrDecl, Export, Identifier, InterfaceDef, InterfaceKind, OpDecl, ParamAttribute, ParamDecl,
    ScopedName, TypeSpec,
};
use zerodds_idl::errors::Span;

/// Ergebnis der Transformation: zwei zusaetzliche Local-Interfaces.
#[derive(Debug, Clone, PartialEq)]
pub struct Ami4CcmInterfaces {
    /// `AMI4CCM_<Iface>ReplyHandler` (Spec §7.5).
    pub reply_handler: InterfaceDef,
    /// `AMI4CCM_<Iface>` (Spec §7.3 + §7.6 ami4ccm_provides).
    pub ami_interface: InterfaceDef,
}

/// Compilation-Kontext fuer den AMI4CCM-Transform.
///
/// Spec-Referenzen:
/// * §7.5 — abgeleitete Interfaces erben ihren ReplyHandler vom
///   ReplyHandler des Base-Interfaces (`AMI4CCM_<Base>ReplyHandler`).
///   Dazu braucht der Transformer eine Map der bereits transformierten
///   Bases (`known_bases`).
/// * §7.5 / §7.3.1 — wenn der naive `AMI4CCM_<Iface>`-/-`ReplyHandler`-
///   Name mit einem bestehenden Identifier im Compilation-Unit
///   kollidiert, muessen `AMI_`-Prefixe ergaenzt werden, bis der Name
///   eindeutig ist (`known_symbols`).
#[derive(Debug, Clone, Default)]
pub struct TransformContext {
    /// Set von Original-Interface-Namen, deren ReplyHandler bereits
    /// generiert wurde. Wird bei `transform_interface` einer Iface mit
    /// `iface.bases = [Base]` konsultiert: ist `Base.text` enthalten,
    /// erbt der neue ReplyHandler von `AMI4CCM_<Base>ReplyHandler`
    /// statt vom generischen `CCM_AMI::ReplyHandler`.
    pub known_bases: BTreeSet<String>,
    /// Set aller Identifier im aktuellen Compilation-Scope. Wird vor
    /// dem Emittieren der AMI4CCM-Interface-Namen gegen den
    /// Konflikt-Resolver gepruescht (`AMI_AMI4CCM_<Iface>` etc.).
    pub known_symbols: BTreeSet<String>,
}

impl TransformContext {
    /// Neuer leerer Kontext (gleichbedeutend mit `default()`).
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Markiert einen Iface-Namen als bereits-transformiert, sodass
    /// abgeleitete Interfaces ihren ReplyHandler korrekt erben.
    pub fn mark_transformed(&mut self, iface_name: &str) {
        self.known_bases.insert(iface_name.to_string());
        self.known_symbols.insert(format!("AMI4CCM_{iface_name}"));
        self.known_symbols
            .insert(format!("AMI4CCM_{iface_name}ReplyHandler"));
    }

    /// Registriert einen bereits-existierenden Identifier, gegen den
    /// der AMI4CCM-Naming-Resolver pruefen muss.
    pub fn add_known_symbol(&mut self, name: &str) {
        self.known_symbols.insert(name.to_string());
    }
}

/// Transformiert ein normales [`InterfaceDef`] in das implied AMI4CCM-
/// Paar. Spec §7.3 + §7.5.
///
/// Convenience-Wrapper ohne Kontext (kein Inheritance-Lookup, keine
/// Symbol-Tabelle). Fuer voll spec-konforme Transformation aufrufen
/// von `transform_interface_in_context`.
#[must_use]
pub fn transform_interface(iface: &InterfaceDef) -> Ami4CcmInterfaces {
    transform_interface_in_context(iface, &TransformContext::default())
}

/// Spec-konforme Variante mit Compilation-Kontext.
///
/// **Naming Convention (Spec §7.3.1 + §7.5):**
/// * Reply-Handler-Name: `AMI4CCM_<original-iface-name>ReplyHandler`,
///   bei Konflikt mit `ctx.known_symbols`: `AMI_AMI4CCM_<...>` etc.
/// * Async-Interface-Name: `AMI4CCM_<original-iface-name>`.
///
/// **Reply-Handler-Inheritance (Spec §7.5):**
/// Wenn `iface.bases` einen Eintrag hat, dessen `last`-Identifier in
/// `ctx.known_bases` enthalten ist, erbt der ReplyHandler von
/// `AMI4CCM_<Base>ReplyHandler`. Andernfalls von
/// `CCM_AMI::ReplyHandler` (Default).
///
/// **`InterfaceKind::Local`** (Spec §7.3 + Annex A): beide generierten
/// Interfaces sind `local interface` (nicht remotable).
#[must_use]
pub fn transform_interface_in_context(
    iface: &InterfaceDef,
    ctx: &TransformContext,
) -> Ami4CcmInterfaces {
    let span = Span::SYNTHETIC;
    let original_name = iface.name.text.clone();

    // Sammle alle Original-Operation-Namen + Attribute-Setter/Getter-
    // Namen, um Naming-Conflicts (Spec §7.3.1) aufzuloesen.
    let mut original_op_names: Vec<String> = Vec::new();
    for export in &iface.exports {
        match export {
            Export::Op(op) => original_op_names.push(op.name.text.clone()),
            Export::Attr(attr) => {
                original_op_names.push(format!("get_{}", attr.name.text));
                if !attr.readonly {
                    original_op_names.push(format!("set_{}", attr.name.text));
                }
            }
            _ => {}
        }
    }

    // Spec §7.5 — Reply-Handler-Inheritance fuer abgeleitete Interfaces.
    // Wir konsultieren ctx.known_bases: der erste base in iface.bases,
    // dessen letzter Identifier-Part in ctx.known_bases enthalten ist,
    // bestimmt den Parent-ReplyHandler.
    let reply_handler_base = iface
        .bases
        .iter()
        .find_map(|b| {
            b.parts
                .last()
                .map(|i| &i.text)
                .filter(|n| ctx.known_bases.contains(n.as_str()))
                .cloned()
        })
        .map_or_else(
            || scoped_name(&["CCM_AMI", "ReplyHandler"], span),
            |base| ScopedName::single(Identifier::new(format!("AMI4CCM_{base}ReplyHandler"), span)),
        );

    // Spec §7.3.1 / §7.5 — Naming-Conflict mit dem Compilation-Scope:
    // wenn AMI4CCM_<Iface>[ReplyHandler] bereits in ctx.known_symbols
    // ist, prefix mit AMI_ (rekursiv).
    let ami_iface_name =
        resolve_unique_iface_name(&format!("AMI4CCM_{original_name}"), &ctx.known_symbols);
    let reply_handler_name = resolve_unique_iface_name(
        &format!("AMI4CCM_{original_name}ReplyHandler"),
        &ctx.known_symbols,
    );

    let reply_handler = build_reply_handler(
        &original_name,
        &reply_handler_name,
        reply_handler_base,
        &iface.exports,
        &original_op_names,
        span,
    );
    let ami_interface = build_ami_interface(
        &original_name,
        &ami_iface_name,
        &iface.exports,
        &original_op_names,
        span,
    );

    Ami4CcmInterfaces {
        reply_handler,
        ami_interface,
    }
}

/// Resolver fuer den Naming-Konflikt aus Spec §7.3.1 / §7.5.
///
/// Wenn `name` in `known` enthalten ist, schiebt einen `AMI_`-Prefix
/// vor und versucht erneut. Im pathologischen Fall (alle Varianten
/// belegt) liefert die Funktion den letzten kandidaten zurueck — der
/// Caller faellt dann auf die unvermeidbare Doublette zurueck.
fn resolve_unique_iface_name(base: &str, known: &BTreeSet<String>) -> String {
    let mut candidate = base.to_string();
    for _ in 0..16 {
        if !known.contains(&candidate) {
            return candidate;
        }
        candidate = format!("AMI_{candidate}");
    }
    candidate
}

/// Spec §7.3 (S. 6-7) — `AMI4CCM_<Iface>` Async-Interface mit
/// `sendc_<op>` Operations.
fn build_ami_interface(
    original_name: &str,
    iface_name: &str,
    exports: &[Export],
    original_op_names: &[String],
    span: Span,
) -> InterfaceDef {
    let handler_type = handler_type_spec(original_name);
    // Verfolge bereits ausgegebene Namen, um interne Kollisionen
    // (z.B. zwei "ami_..."-Aufstockungen) zu vermeiden.
    let mut emitted: Vec<String> = Vec::new();
    let mut new_exports: Vec<Export> = Vec::new();

    for export in exports {
        match export {
            Export::Op(op) => {
                let name = resolve_sendc_name(&op.name.text, original_op_names, &emitted);
                emitted.push(name.clone());
                new_exports.push(Export::Op(build_sendc_op(&name, &handler_type, op, span)));
            }
            Export::Attr(attr) => {
                // Getter — Spec §7.3.1.2 (S. 7).
                let getter_name = resolve_sendc_name(
                    &format!("get_{}", attr.name.text),
                    original_op_names,
                    &emitted,
                );
                emitted.push(getter_name.clone());
                new_exports.push(Export::Op(build_sendc_attr_get(
                    &getter_name,
                    &handler_type,
                    span,
                )));
                if !attr.readonly {
                    let setter_name = resolve_sendc_name(
                        &format!("set_{}", attr.name.text),
                        original_op_names,
                        &emitted,
                    );
                    emitted.push(setter_name.clone());
                    new_exports.push(Export::Op(build_sendc_attr_set(
                        &setter_name,
                        &handler_type,
                        attr,
                        span,
                    )));
                }
            }
            // Spec §7.3 — types/consts/exceptions sind im Async-
            // Interface nicht relevant; sie bleiben im Original-Iface
            // sichtbar.
            _ => {}
        }
    }

    InterfaceDef {
        kind: InterfaceKind::Local,
        name: Identifier::new(iface_name, span),
        bases: Vec::new(),
        exports: new_exports,
        annotations: Vec::new(),
        span,
    }
}

/// Spec §7.5 (S. 9-10) — `AMI4CCM_<Iface>ReplyHandler` mit normal-
/// Reply + `_excep`-Operations.
fn build_reply_handler(
    original_name: &str,
    handler_name: &str,
    handler_base: ScopedName,
    exports: &[Export],
    original_op_names: &[String],
    span: Span,
) -> InterfaceDef {
    let _ = original_name; // unused now; reserved for future extensions
    let exc_holder_type = exception_holder_type_spec();
    let mut emitted: Vec<String> = Vec::new();
    let mut new_exports: Vec<Export> = Vec::new();

    for export in exports {
        match export {
            Export::Op(op) => {
                // Normal-Reply (Spec §7.5.1).
                let normal_name = op.name.text.clone();
                emitted.push(normal_name.clone());
                new_exports.push(Export::Op(build_handler_normal_op(&normal_name, op, span)));
                // Exception-Reply (Spec §7.5.2).
                let excep_name = resolve_excep_name(&op.name.text, original_op_names, &emitted);
                emitted.push(excep_name.clone());
                new_exports.push(Export::Op(build_handler_excep_op(
                    &excep_name,
                    &exc_holder_type,
                    span,
                )));
            }
            Export::Attr(attr) => {
                // Getter normal — `void get_<attr>(in <type> ami_return_val);`.
                let get_name = format!("get_{}", attr.name.text);
                emitted.push(get_name.clone());
                new_exports.push(Export::Op(build_handler_attr_get(
                    &get_name,
                    &attr.type_spec,
                    span,
                )));
                // Getter excep.
                let get_excep = resolve_excep_name(&get_name, original_op_names, &emitted);
                emitted.push(get_excep.clone());
                new_exports.push(Export::Op(build_handler_excep_op(
                    &get_excep,
                    &exc_holder_type,
                    span,
                )));
                if !attr.readonly {
                    // Setter normal — `void set_<attr>();` (no args).
                    let set_name = format!("set_{}", attr.name.text);
                    emitted.push(set_name.clone());
                    new_exports.push(Export::Op(build_handler_attr_set_ack(&set_name, span)));
                    // Setter excep.
                    let set_excep = resolve_excep_name(&set_name, original_op_names, &emitted);
                    emitted.push(set_excep.clone());
                    new_exports.push(Export::Op(build_handler_excep_op(
                        &set_excep,
                        &exc_holder_type,
                        span,
                    )));
                }
            }
            _ => {}
        }
    }

    InterfaceDef {
        kind: InterfaceKind::Local,
        name: Identifier::new(handler_name, span),
        // Spec §7.5 (S. 9): "is derived from the generic CCM_AMI::ReplyHandler"
        // — bei abgeleiteten Interfaces mit bekannter Base wird der Parent-
        // Handler des Base-Interfaces eingesetzt (siehe TransformContext).
        bases: alloc::vec![handler_base],
        exports: new_exports,
        annotations: Vec::new(),
        span,
    }
}

/// Spec §7.3.1.1 (S. 7) — `void sendc_<op>(in handler, in/inout-args)`.
fn build_sendc_op(name: &str, handler_type: &TypeSpec, op: &OpDecl, span: Span) -> OpDecl {
    let mut params = Vec::new();
    params.push(handler_param(handler_type, span));
    for p in &op.params {
        // Spec §7.3.1.1: "Each of the in and inout arguments [...] all
        // with a parameter attribute of in [...]. out arguments are
        // ignored."
        if matches!(p.attribute, ParamAttribute::In | ParamAttribute::InOut) {
            params.push(ParamDecl {
                attribute: ParamAttribute::In,
                type_spec: p.type_spec.clone(),
                name: p.name.clone(),
                annotations: Vec::new(),
                span,
            });
        }
    }
    OpDecl {
        name: Identifier::new(name, span),
        oneway: false,
        return_type: None,
        params,
        // Spec §7.3 (S. 5/6) — async-Operations werfen keine User-
        // Exceptions; nur `INV_OBJREF` System-Exception, die nicht in
        // `raises()` kommt.
        raises: Vec::new(),
        annotations: Vec::new(),
        span,
    }
}

/// Spec §7.3.1.2 (S. 7) — `void sendc_get_<attr>(in handler);`.
fn build_sendc_attr_get(name: &str, handler_type: &TypeSpec, span: Span) -> OpDecl {
    OpDecl {
        name: Identifier::new(name, span),
        oneway: false,
        return_type: None,
        params: alloc::vec![handler_param(handler_type, span)],
        raises: Vec::new(),
        annotations: Vec::new(),
        span,
    }
}

/// Spec §7.3.1.2 (S. 7) — `void sendc_set_<attr>(in handler, in
/// <attrType> attr_<attrName>);`.
fn build_sendc_attr_set(
    name: &str,
    handler_type: &TypeSpec,
    attr: &AttrDecl,
    span: Span,
) -> OpDecl {
    let arg_name = format!("attr_{}", attr.name.text);
    OpDecl {
        name: Identifier::new(name, span),
        oneway: false,
        return_type: None,
        params: alloc::vec![
            handler_param(handler_type, span),
            ParamDecl {
                attribute: ParamAttribute::In,
                type_spec: attr.type_spec.clone(),
                name: Identifier::new(arg_name, span),
                annotations: Vec::new(),
                span,
            },
        ],
        raises: Vec::new(),
        annotations: Vec::new(),
        span,
    }
}

/// Spec §7.5.1 (S. 9-10) — `void <op>(in <ret> ami_return_val,
/// in/inout-args)`.
fn build_handler_normal_op(name: &str, op: &OpDecl, span: Span) -> OpDecl {
    let mut params = Vec::new();
    if let Some(ret) = &op.return_type {
        params.push(ParamDecl {
            attribute: ParamAttribute::In,
            type_spec: ret.clone(),
            name: Identifier::new("ami_return_val", span),
            annotations: Vec::new(),
            span,
        });
    }
    for p in &op.params {
        // Spec §7.5.1: "Each inout/out type name and argument name as
        // they were declared in IDL." — alle als `in`.
        if matches!(p.attribute, ParamAttribute::InOut | ParamAttribute::Out) {
            params.push(ParamDecl {
                attribute: ParamAttribute::In,
                type_spec: p.type_spec.clone(),
                name: p.name.clone(),
                annotations: Vec::new(),
                span,
            });
        }
    }
    OpDecl {
        name: Identifier::new(name, span),
        oneway: false,
        return_type: None,
        params,
        // Spec §7.5.1 (S. 10): "These operations do not raise any
        // exceptions because they are never invoked by a client and
        // have no client to respond to such an exception."
        raises: Vec::new(),
        annotations: Vec::new(),
        span,
    }
}

/// Spec §7.5.1 (S. 10) — `void get_<attr>(in <attrType> ami_return_val);`.
fn build_handler_attr_get(name: &str, attr_type: &TypeSpec, span: Span) -> OpDecl {
    OpDecl {
        name: Identifier::new(name, span),
        oneway: false,
        return_type: None,
        params: alloc::vec![ParamDecl {
            attribute: ParamAttribute::In,
            type_spec: attr_type.clone(),
            name: Identifier::new("ami_return_val", span),
            annotations: Vec::new(),
            span,
        }],
        raises: Vec::new(),
        annotations: Vec::new(),
        span,
    }
}

/// Spec §7.5.1 (S. 10) — `void set_<attr>();` (Setter-Acknowledgement,
/// keine Argumente).
fn build_handler_attr_set_ack(name: &str, span: Span) -> OpDecl {
    OpDecl {
        name: Identifier::new(name, span),
        oneway: false,
        return_type: None,
        params: Vec::new(),
        raises: Vec::new(),
        annotations: Vec::new(),
        span,
    }
}

/// Spec §7.5.2 (S. 10) — `void <op>_excep(in CCM_AMI::ExceptionHolder
/// excep_holder);`.
fn build_handler_excep_op(name: &str, exc_holder_type: &TypeSpec, span: Span) -> OpDecl {
    OpDecl {
        name: Identifier::new(name, span),
        oneway: false,
        return_type: None,
        params: alloc::vec![ParamDecl {
            attribute: ParamAttribute::In,
            type_spec: exc_holder_type.clone(),
            name: Identifier::new("excep_holder", span),
            annotations: Vec::new(),
            span,
        }],
        raises: Vec::new(),
        annotations: Vec::new(),
        span,
    }
}

/// Spec §7.3.1 (S. 7) — Naming-Conflict-Aufloesung fuer `sendc_<op>`:
/// "If this implied-IDL operation name conflicts with existing
/// operations on the interface or any of the interface's base
/// interfaces, `ami_` strings are inserted between `sendc_` and the
/// original operation name until the implied-IDL operation name is
/// unique."
fn resolve_sendc_name(
    original_op_name: &str,
    forbidden_in_iface: &[String],
    already_emitted: &[String],
) -> String {
    let mut prefix = String::from("sendc_");
    loop {
        let candidate = format!("{prefix}{original_op_name}");
        if !forbidden_in_iface.iter().any(|n| n == &candidate)
            && !already_emitted.iter().any(|n| n == &candidate)
        {
            return candidate;
        }
        prefix.push_str("ami_");
    }
}

/// Spec §7.5.2 (S. 10) — Analog fuer `<op>_excep` im ReplyHandler:
/// "If the name generated by the method described above clashes with
/// a name that already exists in the interface, `_ami` strings are
/// inserted immediately preceding the `_excep` repeatedly, until
/// generated IDL operation name is unique in the interface."
fn resolve_excep_name(
    original_op_name: &str,
    forbidden_in_iface: &[String],
    already_emitted: &[String],
) -> String {
    let mut suffix = String::from("_excep");
    loop {
        let candidate = format!("{original_op_name}{suffix}");
        if !forbidden_in_iface.iter().any(|n| n == &candidate)
            && !already_emitted.iter().any(|n| n == &candidate)
        {
            return candidate;
        }
        // Spec sagt "_ami" (kein "ami_" wie bei sendc) — hier
        // Spec-getreu beibehalten.
        suffix = format!("_ami{suffix}");
    }
}

fn handler_param(handler_type: &TypeSpec, span: Span) -> ParamDecl {
    ParamDecl {
        attribute: ParamAttribute::In,
        type_spec: handler_type.clone(),
        name: Identifier::new("ami_handler", span),
        annotations: Vec::new(),
        span,
    }
}

fn handler_type_spec(original_name: &str) -> TypeSpec {
    TypeSpec::Scoped(scoped_name(
        &[&format!("AMI4CCM_{original_name}ReplyHandler")],
        Span::SYNTHETIC,
    ))
}

fn exception_holder_type_spec() -> TypeSpec {
    TypeSpec::Scoped(scoped_name(
        &["CCM_AMI", "ExceptionHolder"],
        Span::SYNTHETIC,
    ))
}

fn scoped_name(parts: &[&str], span: Span) -> ScopedName {
    ScopedName {
        absolute: false,
        parts: parts
            .iter()
            .map(|p| Identifier::new((*p).to_string(), span))
            .collect(),
        span,
    }
}

/// Helper fuer `void`-Type Pruefung in Tests.
#[cfg(test)]
fn assert_void_return(op: &OpDecl) {
    assert!(
        op.return_type.is_none(),
        "expected void return on {}",
        op.name.text
    );
}

#[cfg(test)]
#[allow(clippy::panic, clippy::expect_used)]
mod tests {
    use super::*;
    use zerodds_idl::ast::{IntegerType, PrimitiveType, StringType};

    fn primitive(p: PrimitiveType) -> TypeSpec {
        TypeSpec::Primitive(p)
    }

    fn op(
        name: &str,
        return_type: Option<TypeSpec>,
        params: Vec<(ParamAttribute, TypeSpec, &str)>,
    ) -> Export {
        let span = Span::SYNTHETIC;
        Export::Op(OpDecl {
            name: Identifier::new(name, span),
            oneway: false,
            return_type,
            params: params
                .into_iter()
                .map(|(attr, ty, n)| ParamDecl {
                    attribute: attr,
                    type_spec: ty,
                    name: Identifier::new(n, span),
                    annotations: Vec::new(),
                    span,
                })
                .collect(),
            raises: Vec::new(),
            annotations: Vec::new(),
            span,
        })
    }

    fn attr(name: &str, ty: TypeSpec, readonly: bool) -> Export {
        let span = Span::SYNTHETIC;
        Export::Attr(AttrDecl {
            name: Identifier::new(name, span),
            type_spec: ty,
            readonly,
            get_raises: Vec::new(),
            set_raises: Vec::new(),
            annotations: Vec::new(),
            span,
        })
    }

    fn iface(name: &str, exports: Vec<Export>) -> InterfaceDef {
        InterfaceDef {
            kind: InterfaceKind::Plain,
            name: Identifier::new(name, Span::SYNTHETIC),
            bases: Vec::new(),
            exports,
            annotations: Vec::new(),
            span: Span::SYNTHETIC,
        }
    }

    fn string_ty() -> TypeSpec {
        TypeSpec::String(StringType {
            wide: false,
            bound: None,
            span: Span::SYNTHETIC,
        })
    }

    fn double_ty() -> TypeSpec {
        primitive(PrimitiveType::Floating(
            zerodds_idl::ast::FloatingType::Double,
        ))
    }

    fn boolean_ty() -> TypeSpec {
        primitive(PrimitiveType::Boolean)
    }

    fn long_ty() -> TypeSpec {
        primitive(PrimitiveType::Integer(IntegerType::Long))
    }

    #[test]
    fn produces_two_local_interfaces_with_correct_names() {
        // Spec §7.3 + §7.5 — Naming.
        let i = iface("StockManager", alloc::vec![]);
        let out = transform_interface(&i);
        assert_eq!(out.ami_interface.name.text, "AMI4CCM_StockManager");
        assert_eq!(
            out.reply_handler.name.text,
            "AMI4CCM_StockManagerReplyHandler"
        );
        assert_eq!(out.ami_interface.kind, InterfaceKind::Local);
        assert_eq!(out.reply_handler.kind, InterfaceKind::Local);
    }

    #[test]
    fn reply_handler_inherits_from_ccm_ami_replyhandler() {
        // Spec §7.5 (S. 9): "is derived from the generic CCM_AMI::
        // ReplyHandler".
        let i = iface("Foo", alloc::vec![]);
        let out = transform_interface(&i);
        assert_eq!(out.reply_handler.bases.len(), 1);
        let base = &out.reply_handler.bases[0];
        assert_eq!(
            base.parts
                .iter()
                .map(|p| p.text.as_str())
                .collect::<Vec<_>>(),
            alloc::vec!["CCM_AMI", "ReplyHandler"]
        );
    }

    #[test]
    fn sendc_op_has_handler_first_then_in_inout_only() {
        // Spec §7.3.1.1 — out-Args werden ignoriert; inout wird zu in.
        let i = iface(
            "I",
            alloc::vec![op(
                "remove_stock",
                None,
                alloc::vec![
                    (ParamAttribute::In, string_ty(), "symbol"),
                    (ParamAttribute::Out, double_ty(), "quote"),
                ],
            )],
        );
        let out = transform_interface(&i);
        let Export::Op(o) = &out.ami_interface.exports[0] else {
            panic!("expected op");
        };
        assert_eq!(o.name.text, "sendc_remove_stock");
        assert_void_return(o);
        // Erwartet: ami_handler + symbol; out-arg "quote" ist gedroppt.
        assert_eq!(o.params.len(), 2);
        assert_eq!(o.params[0].name.text, "ami_handler");
        assert_eq!(o.params[0].attribute, ParamAttribute::In);
        assert_eq!(o.params[1].name.text, "symbol");
        assert_eq!(o.params[1].attribute, ParamAttribute::In);
    }

    #[test]
    fn sendc_inout_becomes_in() {
        // Spec §7.3.1.1 — "all with a parameter attribute of in".
        let i = iface(
            "I",
            alloc::vec![op(
                "find_closest_symbol",
                Some(boolean_ty()),
                alloc::vec![(ParamAttribute::InOut, string_ty(), "symbol")],
            )],
        );
        let out = transform_interface(&i);
        let Export::Op(o) = &out.ami_interface.exports[0] else {
            panic!()
        };
        assert_eq!(o.params.len(), 2);
        // Original inout -> in.
        assert_eq!(o.params[1].attribute, ParamAttribute::In);
        assert_eq!(o.params[1].name.text, "symbol");
    }

    #[test]
    fn handler_op_has_return_value_then_inout_out() {
        // Spec §7.5.1 (S. 9-10): ami_return_val first, dann inout/out.
        let i = iface(
            "I",
            alloc::vec![op(
                "remove_stock",
                Some(double_ty()),
                alloc::vec![
                    (ParamAttribute::In, string_ty(), "symbol"),
                    (ParamAttribute::Out, double_ty(), "quote"),
                ],
            )],
        );
        let out = transform_interface(&i);
        // Erstes Reply-Handler-Op = "remove_stock" (normal), zweites =
        // "remove_stock_excep".
        let Export::Op(o) = &out.reply_handler.exports[0] else {
            panic!()
        };
        assert_eq!(o.name.text, "remove_stock");
        // ami_return_val + quote (out wird zu in im Handler).
        assert_eq!(o.params.len(), 2);
        assert_eq!(o.params[0].name.text, "ami_return_val");
        assert_eq!(o.params[0].attribute, ParamAttribute::In);
        assert_eq!(o.params[1].name.text, "quote");
        assert_eq!(o.params[1].attribute, ParamAttribute::In);
    }

    #[test]
    fn handler_excep_op_takes_exception_holder() {
        // Spec §7.5.2 (S. 10): `void <op>_excep(in CCM_AMI::
        // ExceptionHolder excep_holder);`.
        let i = iface(
            "I",
            alloc::vec![op("get_quote", Some(double_ty()), alloc::vec![])],
        );
        let out = transform_interface(&i);
        // Index 0 = get_quote, Index 1 = get_quote_excep.
        let Export::Op(o) = &out.reply_handler.exports[1] else {
            panic!()
        };
        assert_eq!(o.name.text, "get_quote_excep");
        assert_eq!(o.params.len(), 1);
        assert_eq!(o.params[0].name.text, "excep_holder");
        let TypeSpec::Scoped(sn) = &o.params[0].type_spec else {
            panic!("expected ScopedName for ExceptionHolder")
        };
        assert_eq!(
            sn.parts.iter().map(|p| p.text.as_str()).collect::<Vec<_>>(),
            alloc::vec!["CCM_AMI", "ExceptionHolder"]
        );
    }

    #[test]
    fn attribute_get_set_generated_in_both_interfaces() {
        // Spec §7.3.1.2 (S. 7) + §7.5.1 (S. 10) — getter+setter Pfad
        // fuer writable Attribute.
        let i = iface(
            "I",
            alloc::vec![attr("stock_exchange_name", string_ty(), false)],
        );
        let out = transform_interface(&i);

        // AMI-Iface: sendc_get_..., sendc_set_...
        let names: Vec<String> = out
            .ami_interface
            .exports
            .iter()
            .map(|e| match e {
                Export::Op(o) => o.name.text.clone(),
                _ => String::new(),
            })
            .collect();
        assert!(names.contains(&String::from("sendc_get_stock_exchange_name")));
        assert!(names.contains(&String::from("sendc_set_stock_exchange_name")));

        // Reply-Handler: get_x, get_x_excep, set_x, set_x_excep.
        let h_names: Vec<String> = out
            .reply_handler
            .exports
            .iter()
            .map(|e| match e {
                Export::Op(o) => o.name.text.clone(),
                _ => String::new(),
            })
            .collect();
        assert!(h_names.contains(&String::from("get_stock_exchange_name")));
        assert!(h_names.contains(&String::from("get_stock_exchange_name_excep")));
        assert!(h_names.contains(&String::from("set_stock_exchange_name")));
        assert!(h_names.contains(&String::from("set_stock_exchange_name_excep")));
    }

    #[test]
    fn readonly_attribute_only_generates_getter() {
        // Spec §7.3.1.2 (S. 7): "Setter operations are only generated
        // for attributes that are not defined readonly".
        let i = iface("I", alloc::vec![attr("price", double_ty(), true)]);
        let out = transform_interface(&i);
        let names: Vec<String> = out
            .ami_interface
            .exports
            .iter()
            .map(|e| match e {
                Export::Op(o) => o.name.text.clone(),
                _ => String::new(),
            })
            .collect();
        assert!(names.contains(&String::from("sendc_get_price")));
        assert!(!names.iter().any(|n| n.starts_with("sendc_set_")));
    }

    #[test]
    fn sendc_attr_setter_takes_attr_prefixed_arg() {
        // Spec §7.3.1.2: "in <attrType> attr_<attributeName>".
        let i = iface(
            "I",
            alloc::vec![attr("stock_exchange_name", string_ty(), false)],
        );
        let out = transform_interface(&i);
        // Index 1 = sendc_set_stock_exchange_name (Index 0 = getter).
        let Export::Op(o) = &out.ami_interface.exports[1] else {
            panic!()
        };
        assert_eq!(o.name.text, "sendc_set_stock_exchange_name");
        assert_eq!(o.params.len(), 2);
        assert_eq!(o.params[1].name.text, "attr_stock_exchange_name");
    }

    #[test]
    fn handler_attr_setter_ack_has_no_args() {
        // Spec §7.5.1 (Beispiel S. 10): "void set_stock_exchange_name();".
        let i = iface(
            "I",
            alloc::vec![attr("stock_exchange_name", string_ty(), false)],
        );
        let out = transform_interface(&i);
        // Reihenfolge: get_x, get_x_excep, set_x, set_x_excep.
        let Export::Op(o) = &out.reply_handler.exports[2] else {
            panic!()
        };
        assert_eq!(o.name.text, "set_stock_exchange_name");
        assert!(o.params.is_empty());
    }

    #[test]
    fn naming_conflict_resolved_with_ami_prefix() {
        // Spec §7.3.1 (S. 7) — wenn `sendc_<op>` schon im Iface
        // existiert, "ami_" einfuegen bis eindeutig.
        let i = iface(
            "I",
            alloc::vec![
                op("foo", None, alloc::vec![]),
                op("sendc_foo", None, alloc::vec![]),
            ],
        );
        let out = transform_interface(&i);
        let names: Vec<String> = out
            .ami_interface
            .exports
            .iter()
            .map(|e| match e {
                Export::Op(o) => o.name.text.clone(),
                _ => String::new(),
            })
            .collect();
        // "sendc_foo" existiert -> "sendc_ami_foo" wird benutzt.
        assert!(names.contains(&String::from("sendc_ami_foo")));
        assert!(names.contains(&String::from("sendc_sendc_foo")));
    }

    #[test]
    fn excep_naming_conflict_resolved_with_ami_suffix() {
        // Spec §7.5.2 (S. 10) — `_ami_excep` etc.
        let i = iface(
            "I",
            alloc::vec![
                op("foo", None, alloc::vec![]),
                op("foo_excep", None, alloc::vec![]),
            ],
        );
        let out = transform_interface(&i);
        let h_names: Vec<String> = out
            .reply_handler
            .exports
            .iter()
            .map(|e| match e {
                Export::Op(o) => o.name.text.clone(),
                _ => String::new(),
            })
            .collect();
        // "foo_excep" existiert -> "foo_ami_excep" wird verwendet.
        assert!(h_names.contains(&String::from("foo_ami_excep")));
        // foo_excep_excep wird NICHT (das waere ein Original-_excep
        // ohne Konflikt fuer das Original-foo_excep).
        assert!(h_names.contains(&String::from("foo_excep_excep")));
    }

    #[test]
    fn full_stockmanager_running_example_yields_spec_signatures() {
        // Spec §7.2 (S. 5-6) Running Example -> §7.3.1.3 (S. 8) +
        // §7.5.3 (S. 11) erwartete Signaturen.
        let i = iface(
            "StockManager",
            alloc::vec![
                attr("stock_exchange_name", string_ty(), false),
                op(
                    "set_stock",
                    None,
                    alloc::vec![
                        (ParamAttribute::In, string_ty(), "symbol"),
                        (ParamAttribute::In, double_ty(), "new_quote"),
                    ],
                ),
                op(
                    "remove_stock",
                    None,
                    alloc::vec![
                        (ParamAttribute::In, string_ty(), "symbol"),
                        (ParamAttribute::Out, double_ty(), "quote"),
                    ],
                ),
                op(
                    "find_closest_symbol",
                    Some(boolean_ty()),
                    alloc::vec![(ParamAttribute::InOut, string_ty(), "symbol")],
                ),
                op(
                    "get_quote",
                    Some(double_ty()),
                    alloc::vec![(ParamAttribute::In, string_ty(), "symbol")],
                ),
            ],
        );
        let out = transform_interface(&i);

        // §7.3.1.3 (S. 8) — AMI-Interface enthaelt diese sendc_-Ops.
        let ami_names: Vec<String> = out
            .ami_interface
            .exports
            .iter()
            .map(|e| match e {
                Export::Op(o) => o.name.text.clone(),
                _ => String::new(),
            })
            .collect();
        for expected in [
            "sendc_get_stock_exchange_name",
            "sendc_set_stock_exchange_name",
            "sendc_set_stock",
            "sendc_remove_stock",
            "sendc_find_closest_symbol",
            "sendc_get_quote",
        ] {
            assert!(
                ami_names.contains(&String::from(expected)),
                "missing {expected} in {ami_names:?}"
            );
        }

        // §7.5.3 (S. 11) — ReplyHandler-Signaturen.
        let h_names: Vec<String> = out
            .reply_handler
            .exports
            .iter()
            .map(|e| match e {
                Export::Op(o) => o.name.text.clone(),
                _ => String::new(),
            })
            .collect();
        for expected in [
            "get_stock_exchange_name",
            "get_stock_exchange_name_excep",
            "set_stock_exchange_name",
            "set_stock_exchange_name_excep",
            "set_stock",
            "set_stock_excep",
            "remove_stock",
            "remove_stock_excep",
            "find_closest_symbol",
            "find_closest_symbol_excep",
            "get_quote",
            "get_quote_excep",
        ] {
            assert!(
                h_names.contains(&String::from(expected)),
                "missing {expected} in {h_names:?}"
            );
        }
    }

    #[test]
    fn operation_with_no_return_no_args_yields_handler_op_with_no_params() {
        // Spec §7.5.1 (S. 10) "first case" — void return + no params.
        let i = iface("I", alloc::vec![op("acknowledge", None, alloc::vec![])]);
        let out = transform_interface(&i);
        let Export::Op(o) = &out.reply_handler.exports[0] else {
            panic!()
        };
        assert_eq!(o.name.text, "acknowledge");
        assert!(o.params.is_empty());
    }

    #[test]
    fn long_typed_attribute_propagates_type_to_handler_param() {
        let i = iface("I", alloc::vec![attr("counter", long_ty(), true)]);
        let out = transform_interface(&i);
        let Export::Op(o) = &out.reply_handler.exports[0] else {
            panic!()
        };
        assert_eq!(o.name.text, "get_counter");
        assert_eq!(o.params[0].type_spec, long_ty());
    }

    // ---- Phase-B Cluster 3 — Spec §7.5 ReplyHandler-Inheritance ----

    fn iface_with_base(name: &str, base: &str, exports: Vec<Export>) -> InterfaceDef {
        InterfaceDef {
            kind: InterfaceKind::Plain,
            name: Identifier::new(name, Span::SYNTHETIC),
            bases: alloc::vec![ScopedName::single(Identifier::new(base, Span::SYNTHETIC))],
            exports,
            annotations: Vec::new(),
            span: Span::SYNTHETIC,
        }
    }

    #[test]
    fn derived_iface_handler_inherits_from_base_handler_when_known() {
        // Spec §7.5: ReplyHandler eines abgeleiteten Interfaces erbt
        // von AMI4CCM_<Base>ReplyHandler statt von CCM_AMI::ReplyHandler.
        let mut ctx = TransformContext::new();
        ctx.mark_transformed("Base");
        let derived = iface_with_base(
            "Derived",
            "Base",
            alloc::vec![op(
                "ping",
                Some(long_ty()),
                alloc::vec![(ParamAttribute::In, long_ty(), "v")]
            )],
        );
        let out = transform_interface_in_context(&derived, &ctx);
        assert_eq!(out.reply_handler.bases.len(), 1);
        let parts = out.reply_handler.bases[0]
            .parts
            .iter()
            .map(|i| i.text.as_str())
            .collect::<Vec<_>>();
        assert_eq!(
            parts,
            alloc::vec!["AMI4CCM_BaseReplyHandler"],
            "expected derived ReplyHandler to inherit from AMI4CCM_BaseReplyHandler, got {parts:?}"
        );
    }

    #[test]
    fn derived_iface_falls_back_to_ccm_ami_when_base_unknown() {
        // Wenn die Base nicht in known_bases vermerkt ist, behaelt
        // die Default-Inheritance-Regel.
        let ctx = TransformContext::new();
        let derived = iface_with_base("Derived", "UnknownBase", alloc::vec![]);
        let out = transform_interface_in_context(&derived, &ctx);
        let parts = out.reply_handler.bases[0]
            .parts
            .iter()
            .map(|i| i.text.as_str())
            .collect::<Vec<_>>();
        assert_eq!(parts, alloc::vec!["CCM_AMI", "ReplyHandler"]);
    }

    // ---- Phase-B Cluster 3 — Spec §7.5 AMI_-Prefix Naming-Resolver ----

    #[test]
    fn ami4ccm_prefix_collision_inserts_ami_prefix() {
        // Spec §7.5 / §7.3.1: wenn AMI4CCM_<Iface> oder AMI4CCM_<Iface>
        // ReplyHandler bereits als Identifier im Compilation-Scope
        // existiert, prefix mit AMI_ rekursiv.
        let mut ctx = TransformContext::new();
        ctx.add_known_symbol("AMI4CCM_Order");
        ctx.add_known_symbol("AMI4CCM_OrderReplyHandler");
        let i = iface("Order", alloc::vec![op("submit", None, alloc::vec![])]);
        let out = transform_interface_in_context(&i, &ctx);
        assert_eq!(out.ami_interface.name.text, "AMI_AMI4CCM_Order");
        assert_eq!(out.reply_handler.name.text, "AMI_AMI4CCM_OrderReplyHandler");
    }

    #[test]
    fn ami4ccm_prefix_collision_recurses_until_unique() {
        // Wenn auch die ersten Prefix-Stufen belegt sind, immer weiter
        // rekursiv prefixen.
        let mut ctx = TransformContext::new();
        for layer in [
            "AMI4CCM_Order",
            "AMI_AMI4CCM_Order",
            "AMI_AMI_AMI4CCM_Order",
        ] {
            ctx.add_known_symbol(layer);
        }
        let i = iface("Order", alloc::vec![op("submit", None, alloc::vec![])]);
        let out = transform_interface_in_context(&i, &ctx);
        assert_eq!(out.ami_interface.name.text, "AMI_AMI_AMI_AMI4CCM_Order");
    }

    #[test]
    fn transform_context_mark_transformed_sets_known_symbols_and_bases() {
        let mut ctx = TransformContext::new();
        ctx.mark_transformed("Foo");
        assert!(ctx.known_bases.contains("Foo"));
        assert!(ctx.known_symbols.contains("AMI4CCM_Foo"));
        assert!(ctx.known_symbols.contains("AMI4CCM_FooReplyHandler"));
    }
}