zerodds-corba-rust 1.0.0-rc.3

IDL → Rust code generator for CORBA service constructs (interfaces, valuetypes, components, homes) — analogous to zerodds-idl-cpp/-csharp/-java but for Rust output.
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
// SPDX-License-Identifier: Apache-2.0
// Copyright 2026 ZeroDDS Contributors
//! IDL `interface` → Rust trait + stub + skeleton.
//!
//! Mapping:
//! - `interface I { ... };` → `pub trait I { fn op(...) -> Result<...>; }`
//!   plus `pub struct IStub { ... }` (client) and `pub fn dispatch_<i>(...)`
//!   (server skeleton).
//! - `attribute T x` → trait method `fn x(&self) -> ...` and (when not
//!   readonly) `fn set_x(&mut self, value: T) -> ...`.
//! - `op(in T x, out T y, inout T z)` → trait method with
//!   `&self`/`&mut self` receiver, `in` params as value, `out`/`inout`
//!   as `&mut`.
//! - `oneway op(...)` → trait method without reply body.
//! - `raises (E1, E2)` → method return type is Result<T, CorbaException>.

extern crate alloc;
use zerodds_idl::ast::types::{Export, InterfaceDef, OpDecl, ParamAttribute, ParamDecl, TypeSpec};

use crate::error::Result;

/// Emits a complete Rust trait + stub + skeleton dispatch
/// for an IDL interface definition.
pub fn emit_interface(
    out: &mut String,
    i: &InterfaceDef,
    registry: &crate::emitter::InterfaceRegistry<'_>,
) -> Result<()> {
    emit_interface_trait(out, i)?;
    out.push('\n');
    emit_interface_stub(out, i, registry)?;
    out.push('\n');
    // Client AMI (CORBA Messaging §22): only for `@ami`-marked interfaces/ops.
    crate::ami_emit::emit_ami(out, i)?;
    emit_interface_skeleton(out, i)?;
    Ok(())
}

fn emit_interface_trait(out: &mut String, i: &InterfaceDef) -> Result<()> {
    let name = &i.name.text;
    out.push_str("/// Generated by `zerodds-corba-rust` from IDL interface.\n");
    // §3.5 raises: emit an exception enum per interface (based on the
    // raises annotations of all operations).
    emit_interface_exceptions_enum(out, i)?;
    // §6.1 Repository ID as a const in the trait — via the spec-conformant
    // builder from `zerodds-corba-codegen::build_repository_id`
    // (CORBA 3.3 §10.7.3.1 format `IDL:<scoped-name>:<major>.<minor>`).
    let repo_id = zerodds_corba_codegen::build_repository_id(&[], name, 1, 0);
    let mut bases_iter = i.bases.iter().map(|s| {
        s.parts
            .iter()
            .map(|p| p.text.as_str())
            .collect::<Vec<_>>()
            .join("::")
    });
    let bases_clause = if let Some(first) = bases_iter.next() {
        let mut s = format!(": {first} + ::core::marker::Send + ::core::marker::Sync");
        for base in bases_iter {
            s.push_str(&format!(" + {base}"));
        }
        s
    } else {
        ": ::core::marker::Send + ::core::marker::Sync".to_string()
    };
    // Repository ID as a free pub const (not as a trait const, so that
    // the trait stays dyn-compatible — skeleton dispatch uses
    // `&dyn {name}`).
    let repo_const = name.to_ascii_uppercase();
    out.push_str(&format!(
        "/// CORBA Repository-ID for `{name}` (spec §10.7.3.1).\npub const {repo_const}_REPOSITORY_ID: &str = \"{repo_id}\";\n"
    ));
    out.push_str(&format!("pub trait {name}{bases_clause} {{\n"));
    for export in &i.exports {
        emit_export_trait_method(out, name, export)?;
    }
    out.push_str("}\n");
    Ok(())
}

/// Emits an exception enum per interface based on all `raises`
/// lists of all operations. Spec §3.5.
fn emit_interface_exceptions_enum(out: &mut String, i: &InterfaceDef) -> Result<()> {
    let name = &i.name.text;
    let mut all_raises: alloc::collections::BTreeSet<String> = alloc::collections::BTreeSet::new();
    for export in &i.exports {
        if let Export::Op(op) = export {
            for raise in &op.raises {
                let r = raise
                    .parts
                    .iter()
                    .map(|p| p.text.as_str())
                    .collect::<Vec<_>>()
                    .join("::");
                all_raises.insert(r);
            }
        }
    }
    if all_raises.is_empty() {
        return Ok(());
    }
    out.push_str(&format!(
        "/// Exception enum for `{name}` — unifies all user exceptions referenced in `raises` lists plus the system exception (spec §3.5).\n"
    ));
    out.push_str("#[derive(Debug, Clone)]\n");
    out.push_str(&format!("pub enum {name}Error {{\n"));
    out.push_str(
        "    /// CORBA-System-Exception (BAD_OPERATION, MARSHAL, OBJECT_NOT_EXIST, ...).\n",
    );
    out.push_str("    System(zerodds_corba_rust::CorbaException),\n");
    for raise in &all_raises {
        let variant = raise.split("::").last().unwrap_or(raise);
        out.push_str(&format!(
            "    /// User-Exception `{raise}` (raised by `{name}`-Operations).\n"
        ));
        out.push_str(&format!("    {variant}({raise}),\n"));
    }
    out.push_str("}\n\n");
    Ok(())
}

fn emit_export_trait_method(out: &mut String, iface: &str, export: &Export) -> Result<()> {
    match export {
        Export::Op(op) => emit_op_trait_method(out, iface, op),
        Export::Attr(attr) => emit_attr_trait_method(out, attr),
        // Const/Type/Except in an interface — emitted separately in idl-rust
        // as type decls. No-op here.
        _ => Ok(()),
    }
}

/// Public wrapper for valuetype reuse. `owner` is the name of the
/// interface/valuetype (for the typed `{owner}Error` enum on raises).
pub fn emit_op_trait_method_pub(out: &mut String, owner: &str, op: &OpDecl) -> Result<()> {
    emit_op_trait_method(out, owner, op)
}

/// Public wrapper for valuetype reuse.
pub fn emit_attr_trait_method_pub(
    out: &mut String,
    attr: &zerodds_idl::ast::types::AttrDecl,
) -> Result<()> {
    emit_attr_trait_method(out, attr)
}

fn emit_op_trait_method(out: &mut String, iface: &str, op: &OpDecl) -> Result<()> {
    let method = &op.name.text;
    // Receiver is always `&self`: the skeleton dispatches over `&dyn Iface`
    // (shared), `out`/`inout` params are `&mut T` PARAMETERS (not self).
    // Servants with state use interior mutability.
    let params_str = render_params(&op.params)?;
    let return_str = render_return(iface, &op.return_type, &op.raises)?;
    let comma = if params_str.is_empty() { "" } else { ", " };
    out.push_str(&format!(
        "    /// IDL operation `{method}`.\n    fn {method}(&self{comma}{params_str}) -> {return_str};\n"
    ));
    Ok(())
}

fn emit_attr_trait_method(
    out: &mut String,
    attr: &zerodds_idl::ast::types::AttrDecl,
) -> Result<()> {
    let name = &attr.name.text;
    let ty = zerodds_idl_rust::type_map::rust_type_for(&attr.type_spec)?;

    out.push_str(&format!("    /// IDL attribute `{name}` getter.\n"));
    out.push_str(&format!(
        "    fn {name}(&self) -> ::core::result::Result<{ty}, zerodds_corba_rust::CorbaException>;\n"
    ));
    if !attr.readonly {
        out.push_str(&format!("    /// IDL attribute `{name}` setter.\n"));
        out.push_str(&format!(
            "    fn set_{name}(&self, value: {ty}) -> ::core::result::Result<(), zerodds_corba_rust::CorbaException>;\n"
        ));
    }
    Ok(())
}

fn render_params(params: &[ParamDecl]) -> Result<String> {
    let mut out = String::new();
    for (idx, p) in params.iter().enumerate() {
        if idx > 0 {
            out.push_str(", ");
        }
        let ty = zerodds_idl_rust::type_map::rust_type_for(&p.type_spec)?;
        let name = &p.name.text;
        match p.attribute {
            ParamAttribute::In => {
                out.push_str(&format!("{name}: {ty}"));
            }
            ParamAttribute::Out | ParamAttribute::InOut => {
                out.push_str(&format!("{name}: &mut {ty}"));
            }
        }
    }
    Ok(out)
}

thread_local! {
    /// Fully resolved exception RepositoryIds (simple name → `IDL:…:1.0`),
    /// collected by the emitter including the definition scope
    /// (module/interface path) and `typeprefix` (e.g. `omg.org`). Thread-local
    /// (per codegen run) so that parallel runs do not clobber each other.
    static EXCEPTION_REPO_IDS: core::cell::RefCell<
        std::collections::BTreeMap<alloc::string::String, alloc::string::String>,
    > = const { core::cell::RefCell::new(std::collections::BTreeMap::new()) };
}

/// Registers the scope-resolved exception RepositoryIds for the run.
pub fn set_exception_repo_ids(
    map: std::collections::BTreeMap<alloc::string::String, alloc::string::String>,
) {
    EXCEPTION_REPO_IDS.with(|r| *r.borrow_mut() = map);
}

/// Repository ID of a raised exception (`IDL:<scoped>:1.0`, §10.7.3.1) — must
/// match byte-exactly what foreign ORBs emit for the same exception.
/// Primarily uses the scope-resolved map (definition scope + typeprefix);
/// otherwise falls back to the path from the raises reference.
fn exc_repo_id(raise: &zerodds_idl::ast::types::ScopedName) -> String {
    let parts: alloc::vec::Vec<&str> = raise.parts.iter().map(|p| p.text.as_str()).collect();
    if let Some(simple) = parts.last() {
        if let Some(full) = EXCEPTION_REPO_IDS.with(|r| r.borrow().get(*simple).cloned()) {
            return full;
        }
    }
    match parts.split_last() {
        Some((name, modules)) => zerodds_corba_codegen::build_repository_id(modules, name, 1, 0),
        None => String::new(),
    }
}

/// Rust type path of a raised exception (scoped → `A::B`).
fn exc_rust_type(raise: &zerodds_idl::ast::types::ScopedName) -> String {
    raise
        .parts
        .iter()
        .map(|p| p.text.as_str())
        .collect::<alloc::vec::Vec<_>>()
        .join("::")
}

/// Enum variant name of a raised exception (= simple name).
fn exc_variant(raise: &zerodds_idl::ast::types::ScopedName) -> String {
    raise
        .parts
        .last()
        .map(|p| p.text.clone())
        .unwrap_or_default()
}

/// Error type of an operation: for a non-empty `raises` list the typed
/// per-interface enum `{iface}Error` (§3.5), otherwise the generic
/// `CorbaException` (only system exceptions possible).
fn op_error_type(iface: &str, raises: &[zerodds_idl::ast::types::ScopedName]) -> String {
    if raises.is_empty() {
        "zerodds_corba_rust::CorbaException".to_string()
    } else {
        format!("{iface}Error")
    }
}

fn render_return(
    iface: &str,
    return_type: &Option<TypeSpec>,
    raises: &[zerodds_idl::ast::types::ScopedName],
) -> Result<String> {
    let inner = match return_type {
        None => "()".to_string(),
        Some(ts) => zerodds_idl_rust::type_map::rust_type_for(ts)?,
    };
    // raises → typed `{iface}Error`, otherwise `CorbaException` (§3.5).
    let err = op_error_type(iface, raises);
    Ok(format!("::core::result::Result<{inner}, {err}>"))
}

fn emit_interface_stub(
    out: &mut String,
    i: &InterfaceDef,
    registry: &crate::emitter::InterfaceRegistry<'_>,
) -> Result<()> {
    let name = &i.name.text;
    let stub_name = format!("{name}Stub");
    out.push_str(&format!(
        "/// Client stub for `{name}` (sends GIOP requests to a remote object).\n"
    ));
    out.push_str(&format!("pub struct {stub_name} {{\n"));
    out.push_str("    /// Object reference (IOR) of the remote servant.\n");
    out.push_str("    pub object_ref: zerodds_corba_rust::ObjectReference,\n");
    out.push_str("    /// Connection handle for sending the GIOP request.\n");
    out.push_str(
        "    pub connection: ::std::sync::Arc<dyn zerodds_corba_rust::CorbaConnection + ::core::marker::Send + ::core::marker::Sync>,\n",
    );
    out.push_str("}\n\n");

    out.push_str(&format!("impl {stub_name} {{\n"));
    out.push_str("    /// Constructs a stub from an ObjectReference + connection.\n");
    out.push_str("    #[must_use]\n");
    out.push_str(
        "    pub fn new(object_ref: zerodds_corba_rust::ObjectReference, connection: ::std::sync::Arc<dyn zerodds_corba_rust::CorbaConnection + ::core::marker::Send + ::core::marker::Sync>) -> Self {\n",
    );
    out.push_str("        Self { object_ref, connection }\n");
    out.push_str("    }\n");
    out.push_str("}\n\n");

    // Implement the trait via GIOP-marshalling stubs.
    out.push_str(&format!("impl {name} for {stub_name} {{\n"));
    for export in &i.exports {
        emit_export_stub_impl(out, name, export)?;
    }
    out.push_str("}\n");

    // §3.6 Inheritance: emit `impl Base for {stub_name}` for all
    // transitively reachable bases, so that the trait inheritance bound
    // (`pub trait Derived: Base`) is satisfied on the stub.
    let mut visited = alloc::collections::BTreeSet::new();
    for base in &i.bases {
        emit_base_impls_recursive(out, &stub_name, base, registry, &mut visited)?;
    }
    Ok(())
}

/// zerodds-lint: recursion-depth 16
fn emit_base_impls_recursive(
    out: &mut String,
    stub_name: &str,
    base_path: &zerodds_idl::ast::types::ScopedName,
    registry: &crate::emitter::InterfaceRegistry<'_>,
    visited: &mut alloc::collections::BTreeSet<String>,
) -> Result<()> {
    let base_simple = base_path
        .parts
        .last()
        .map(|p| p.text.clone())
        .unwrap_or_default();
    if base_simple.is_empty() || !visited.insert(base_simple.clone()) {
        return Ok(());
    }
    let Some(base_def) = registry.get(&base_simple) else {
        // Base not in the same spec file — phase 2 cross-file resolution.
        return Ok(());
    };
    let base_full_path = base_path
        .parts
        .iter()
        .map(|p| p.text.as_str())
        .collect::<Vec<_>>()
        .join("::");
    out.push_str(&format!(
        "\n/// Base inheritance: `{base_simple}` methods on `{stub_name}` (Spec §3.6).\n"
    ));
    out.push_str(&format!("impl {base_full_path} for {stub_name} {{\n"));
    for export in &base_def.exports {
        emit_export_stub_impl(out, &base_simple, export)?;
    }
    out.push_str("}\n");
    for grandbase in &base_def.bases {
        emit_base_impls_recursive(out, stub_name, grandbase, registry, visited)?;
    }
    Ok(())
}

fn emit_export_stub_impl(out: &mut String, iface: &str, export: &Export) -> Result<()> {
    match export {
        Export::Op(op) => emit_op_stub_impl(out, iface, op),
        Export::Attr(attr) => emit_attr_stub_impl(out, attr),
        _ => Ok(()),
    }
}

/// Inline Rust literal for a CORBA MARSHAL system exception (CDR error).
const MARSHAL_EXC: &str = "zerodds_corba_rust::CorbaException::SystemException { minor: 0u32, message: \"CORBA MARSHAL: CDR error\" }";

fn emit_op_stub_impl(out: &mut String, iface: &str, op: &OpDecl) -> Result<()> {
    let method = &op.name.text;
    let params_str = render_params(&op.params)?;
    let return_str = render_return(iface, &op.return_type, &op.raises)?;
    let comma = if params_str.is_empty() { "" } else { ", " };
    let has_raises = !op.raises.is_empty();
    // Error constructors depending on the operation's error type. On raises the
    // error is `{iface}Error`; a marshal/transport error is the System variant.
    let marshal_err = if has_raises {
        format!("{iface}Error::System({MARSHAL_EXC})")
    } else {
        MARSHAL_EXC.to_string()
    };
    // Lifts a `CorbaException` (from the connection) to the op error type.
    let wrap_sys = |inner: &str| -> String {
        if has_raises {
            format!("{iface}Error::System({inner})")
        } else {
            inner.to_string()
        }
    };
    out.push_str(&format!(
        "    fn {method}(&self{comma}{params_str}) -> {return_str} {{\n"
    ));

    // 1. In/InOut params → CDR request body (classic, declaration order).
    out.push_str("        let __e = zerodds_cdr::Endianness::Big;\n");
    out.push_str("        let mut __w = zerodds_cdr::BufferWriter::new(__e);\n");
    for p in &op.params {
        let pname = &p.name.text;
        match p.attribute {
            ParamAttribute::In => out.push_str(&format!(
                "        <_ as zerodds_cdr::CdrEncode>::encode(&{pname}, &mut __w).map_err(|_| {marshal_err})?;\n"
            )),
            ParamAttribute::InOut => out.push_str(&format!(
                "        <_ as zerodds_cdr::CdrEncode>::encode(&*{pname}, &mut __w).map_err(|_| {marshal_err})?;\n"
            )),
            ParamAttribute::Out => {}
        }
    }

    if op.oneway {
        let inv = wrap_sys("__oe");
        out.push_str(&format!(
            "        self.connection.invoke_oneway(&self.object_ref, \"{method}\", __e, &__w.into_bytes()).map_err(|__oe| {inv})?;\n"
        ));
        out.push_str("        ::core::result::Result::Ok(())\n        }\n");
        return Ok(());
    }

    // invoke: on raises, resolve the UserException variant in a typed way.
    if has_raises {
        out.push_str(&format!(
            "        let (__reply, __re) = match self.connection.invoke(&self.object_ref, \"{method}\", __e, &__w.into_bytes()) {{\n"
        ));
        out.push_str("            ::core::result::Result::Ok(__v) => __v,\n");
        out.push_str(
            "            ::core::result::Result::Err(zerodds_corba_rust::CorbaException::UserException { repository_id: __rid, body: __body, endianness: __xe }) => {\n",
        );
        for raise in &op.raises {
            let repo = exc_repo_id(raise);
            let ty = exc_rust_type(raise);
            let variant = exc_variant(raise);
            out.push_str(&format!("                if __rid == \"{repo}\" {{\n"));
            out.push_str(
                "                    let mut __xr = zerodds_cdr::BufferReader::new(&__body, __xe);\n",
            );
            // consume repo-id → positions the reader at the members
            // (alignment relative to the body start).
            out.push_str("                    let _ = __xr.read_string();\n");
            out.push_str(&format!(
                "                    return match <{ty} as zerodds_cdr::CdrDecode>::decode(&mut __xr) {{\n"
            ));
            out.push_str(&format!(
                "                        ::core::result::Result::Ok(__exc) => ::core::result::Result::Err({iface}Error::{variant}(__exc)),\n"
            ));
            out.push_str(&format!(
                "                        ::core::result::Result::Err(_) => ::core::result::Result::Err({iface}Error::System({MARSHAL_EXC})),\n"
            ));
            out.push_str("                    };\n");
            out.push_str("                }\n");
        }
        out.push_str(&format!(
            "                return ::core::result::Result::Err({iface}Error::System(zerodds_corba_rust::CorbaException::UserException {{ repository_id: __rid, body: __body, endianness: __xe }}));\n"
        ));
        out.push_str("            }\n");
        out.push_str(&format!(
            "            ::core::result::Result::Err(__other) => return ::core::result::Result::Err({iface}Error::System(__other)),\n"
        ));
        out.push_str("        };\n");
    } else {
        out.push_str(&format!(
            "        let (__reply, __re) = self.connection.invoke(&self.object_ref, \"{method}\", __e, &__w.into_bytes())?;\n"
        ));
    }
    out.push_str("        let mut __r = zerodds_cdr::BufferReader::new(&__reply, __re);\n");

    // 2. Reply: return value (if non-void), then out/inout params (decl order).
    if let Some(ts) = &op.return_type {
        let ty = zerodds_idl_rust::type_map::rust_type_for(ts)?;
        out.push_str(&format!(
            "        let __ret = <{ty} as zerodds_cdr::CdrDecode>::decode(&mut __r).map_err(|_| {marshal_err})?;\n"
        ));
    }
    for p in &op.params {
        if matches!(p.attribute, ParamAttribute::Out | ParamAttribute::InOut) {
            let ty = zerodds_idl_rust::type_map::rust_type_for(&p.type_spec)?;
            let pname = &p.name.text;
            out.push_str(&format!(
                "        *{pname} = <{ty} as zerodds_cdr::CdrDecode>::decode(&mut __r).map_err(|_| {marshal_err})?;\n"
            ));
        }
    }
    if op.return_type.is_some() {
        out.push_str("        ::core::result::Result::Ok(__ret)\n");
    } else {
        out.push_str("        ::core::result::Result::Ok(())\n");
    }
    out.push_str("    }\n");
    Ok(())
}

fn emit_attr_stub_impl(out: &mut String, attr: &zerodds_idl::ast::types::AttrDecl) -> Result<()> {
    let name = &attr.name.text;
    let ty = zerodds_idl_rust::type_map::rust_type_for(&attr.type_spec)?;

    // Getter: empty request body, decode return.
    out.push_str(&format!(
        "    fn {name}(&self) -> ::core::result::Result<{ty}, zerodds_corba_rust::CorbaException> {{\n"
    ));
    out.push_str("        let __e = zerodds_cdr::Endianness::Big;\n");
    out.push_str("        let __w = zerodds_cdr::BufferWriter::new(__e);\n");
    out.push_str(&format!(
        "        let (__reply, __re) = self.connection.invoke(&self.object_ref, \"_get_{name}\", __e, &__w.into_bytes())?;\n"
    ));
    out.push_str("        let mut __r = zerodds_cdr::BufferReader::new(&__reply, __re);\n");
    out.push_str(&format!(
        "        ::core::result::Result::Ok(<{ty} as zerodds_cdr::CdrDecode>::decode(&mut __r).map_err(|_| {MARSHAL_EXC})?)\n"
    ));
    out.push_str("    }\n");

    if !attr.readonly {
        out.push_str(&format!(
            "    fn set_{name}(&self, value: {ty}) -> ::core::result::Result<(), zerodds_corba_rust::CorbaException> {{\n"
        ));
        out.push_str("        let __e = zerodds_cdr::Endianness::Big;\n");
        out.push_str("        let mut __w = zerodds_cdr::BufferWriter::new(__e);\n");
        out.push_str(&format!(
            "        <_ as zerodds_cdr::CdrEncode>::encode(&value, &mut __w).map_err(|_| {MARSHAL_EXC})?;\n"
        ));
        out.push_str(&format!(
            "        self.connection.invoke(&self.object_ref, \"_set_{name}\", __e, &__w.into_bytes())?;\n"
        ));
        out.push_str("        ::core::result::Result::Ok(())\n");
        out.push_str("    }\n");
    }
    Ok(())
}

fn emit_interface_skeleton(out: &mut String, i: &InterfaceDef) -> Result<()> {
    let name = &i.name.text;
    out.push_str(&format!("/// Server skeleton dispatch for `{name}`.\n"));
    out.push_str("/// Decodes the GIOP request body (in `__endianness`), calls the servant,\n");
    out.push_str("/// Encodes return + out/inout into the reply body (same order).\n");
    let name_lower = name.to_lowercase();
    out.push_str(&format!(
        "pub fn dispatch_{name_lower}(servant: &dyn {name}, operation: &str, __payload: &[u8], __endianness: zerodds_cdr::Endianness) -> zerodds_corba_rust::SkeletonResult {{\n"
    ));
    out.push_str("    match operation {\n");
    for export in &i.exports {
        emit_export_skeleton_arm(out, name, export)?;
    }
    out.push_str("        _ => zerodds_corba_rust::SkeletonResult::BadOperation,\n");
    out.push_str("    }\n");
    out.push_str("}\n");
    Ok(())
}

fn emit_export_skeleton_arm(out: &mut String, iface: &str, export: &Export) -> Result<()> {
    match export {
        Export::Op(op) => emit_op_skeleton_arm(out, iface, op),
        Export::Attr(attr) => emit_attr_skeleton_arm(out, attr),
        _ => Ok(()),
    }
}

fn emit_op_skeleton_arm(out: &mut String, iface: &str, op: &OpDecl) -> Result<()> {
    let method = &op.name.text;
    out.push_str(&format!("        \"{method}\" => {{\n"));
    out.push_str(
        "            let mut __r = zerodds_cdr::BufferReader::new(__payload, __endianness);\n",
    );
    // decode in/inout; pre-initialize out with its default.
    let mut call_args: Vec<String> = Vec::new();
    for p in &op.params {
        let pname = &p.name.text;
        let ty = zerodds_idl_rust::type_map::rust_type_for(&p.type_spec)?;
        match p.attribute {
            ParamAttribute::In => {
                out.push_str(&format!(
                    "            let {pname} = match <{ty} as zerodds_cdr::CdrDecode>::decode(&mut __r) {{ Ok(__v) => __v, Err(_) => return zerodds_corba_rust::SkeletonResult::Exception({MARSHAL_EXC}) }};\n"
                ));
                call_args.push(pname.clone());
            }
            ParamAttribute::InOut => {
                out.push_str(&format!(
                    "            let mut {pname} = match <{ty} as zerodds_cdr::CdrDecode>::decode(&mut __r) {{ Ok(__v) => __v, Err(_) => return zerodds_corba_rust::SkeletonResult::Exception({MARSHAL_EXC}) }};\n"
                ));
                call_args.push(format!("&mut {pname}"));
            }
            ParamAttribute::Out => {
                out.push_str(&format!(
                    "            let mut {pname} = <{ty} as ::core::default::Default>::default();\n"
                ));
                call_args.push(format!("&mut {pname}"));
            }
        }
    }
    let args = call_args.join(", ");
    out.push_str(&format!("            match servant.{method}({args}) {{\n"));
    // Success arm: build the reply body.
    out.push_str("                ::core::result::Result::Ok(__ret) => {\n");
    if op.oneway {
        // oneway: no reply body.
        out.push_str("                    let _ = __ret;\n");
        out.push_str("                    zerodds_corba_rust::SkeletonResult::Reply(::std::vec::Vec::new())\n");
    } else {
        out.push_str(
            "                    let mut __w = zerodds_cdr::BufferWriter::new(__endianness);\n",
        );
        if op.return_type.is_some() {
            out.push_str(&format!(
                "                    if <_ as zerodds_cdr::CdrEncode>::encode(&__ret, &mut __w).is_err() {{ return zerodds_corba_rust::SkeletonResult::Exception({MARSHAL_EXC}); }}\n"
            ));
        } else {
            out.push_str("                    let _ = __ret;\n");
        }
        for p in &op.params {
            if matches!(p.attribute, ParamAttribute::Out | ParamAttribute::InOut) {
                let pname = &p.name.text;
                out.push_str(&format!(
                    "                    if <_ as zerodds_cdr::CdrEncode>::encode(&{pname}, &mut __w).is_err() {{ return zerodds_corba_rust::SkeletonResult::Exception({MARSHAL_EXC}); }}\n"
                ));
            }
        }
        out.push_str(
            "                    zerodds_corba_rust::SkeletonResult::Reply(__w.into_bytes())\n",
        );
    }
    out.push_str("                }\n");
    if op.raises.is_empty() {
        // Only system exceptions possible — pass through directly.
        out.push_str("                ::core::result::Result::Err(__exc) => zerodds_corba_rust::SkeletonResult::Exception(__exc),\n");
    } else {
        // Typed `{iface}Error`: System directly, user exceptions encoded as an
        // IOR-conformant UserException body (repo_id + members, contiguously
        // in __endianness — ends up 8-aligned at the reply body start).
        out.push_str("                ::core::result::Result::Err(__err) => match __err {\n");
        out.push_str(&format!(
            "                    {iface}Error::System(__e) => zerodds_corba_rust::SkeletonResult::Exception(__e),\n"
        ));
        for raise in &op.raises {
            let repo = exc_repo_id(raise);
            let variant = exc_variant(raise);
            out.push_str(&format!(
                "                    {iface}Error::{variant}(__exc) => {{\n"
            ));
            out.push_str(
                "                        let mut __xw = zerodds_cdr::BufferWriter::new(__endianness);\n",
            );
            out.push_str(&format!(
                "                        if __xw.write_string(\"{repo}\").is_err() {{ return zerodds_corba_rust::SkeletonResult::Exception({MARSHAL_EXC}); }}\n"
            ));
            out.push_str(
                "                        if <_ as zerodds_cdr::CdrEncode>::encode(&__exc, &mut __xw).is_err() { return zerodds_corba_rust::SkeletonResult::Exception(",
            );
            out.push_str(MARSHAL_EXC);
            out.push_str("); }\n");
            out.push_str(&format!(
                "                        zerodds_corba_rust::SkeletonResult::Exception(zerodds_corba_rust::CorbaException::UserException {{ repository_id: \"{repo}\".to_string(), body: __xw.into_bytes(), endianness: __endianness }})\n"
            ));
            out.push_str("                    }\n");
        }
        // The shared `{iface}Error` enum can carry variants of other operations;
        // this op never produces them, but the match must be exhaustive
        // → defensive System catch-all (unreachable in the normal case).
        out.push_str(&format!(
            "                    _ => zerodds_corba_rust::SkeletonResult::Exception({MARSHAL_EXC}),\n"
        ));
        out.push_str("                },\n");
    }
    out.push_str("            }\n        }\n");
    Ok(())
}

fn emit_attr_skeleton_arm(
    out: &mut String,
    attr: &zerodds_idl::ast::types::AttrDecl,
) -> Result<()> {
    let name = &attr.name.text;
    // Getter: no request body, encode return.
    out.push_str(&format!("        \"_get_{name}\" => {{\n"));
    out.push_str(&format!("            match servant.{name}() {{\n"));
    out.push_str("                ::core::result::Result::Ok(__ret) => {\n");
    out.push_str(
        "                    let mut __w = zerodds_cdr::BufferWriter::new(__endianness);\n",
    );
    out.push_str(&format!(
        "                    if <_ as zerodds_cdr::CdrEncode>::encode(&__ret, &mut __w).is_err() {{ return zerodds_corba_rust::SkeletonResult::Exception({MARSHAL_EXC}); }}\n"
    ));
    out.push_str(
        "                    zerodds_corba_rust::SkeletonResult::Reply(__w.into_bytes())\n",
    );
    out.push_str("                }\n");
    out.push_str("                ::core::result::Result::Err(__exc) => zerodds_corba_rust::SkeletonResult::Exception(__exc),\n");
    out.push_str("            }\n        }\n");

    if !attr.readonly {
        let ty = zerodds_idl_rust::type_map::rust_type_for(&attr.type_spec)?;
        out.push_str(&format!("        \"_set_{name}\" => {{\n"));
        out.push_str(
            "            let mut __r = zerodds_cdr::BufferReader::new(__payload, __endianness);\n",
        );
        out.push_str(&format!(
            "            let __value = match <{ty} as zerodds_cdr::CdrDecode>::decode(&mut __r) {{ Ok(__v) => __v, Err(_) => return zerodds_corba_rust::SkeletonResult::Exception({MARSHAL_EXC}) }};\n"
        ));
        out.push_str(&format!(
            "            match servant.set_{name}(__value) {{\n"
        ));
        out.push_str("                ::core::result::Result::Ok(()) => zerodds_corba_rust::SkeletonResult::Reply(::std::vec::Vec::new()),\n");
        out.push_str("                ::core::result::Result::Err(__exc) => zerodds_corba_rust::SkeletonResult::Exception(__exc),\n");
        out.push_str("            }\n        }\n");
    }
    Ok(())
}