splicer 2.4.1

Plan and generate middleware splice operations for WebAssembly component composition graphs.
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
//! Resolve-driven IR for the typed codegen pipeline.
//!
//! Each user-declared WIT type produces a [`NamedType`] carrying both
//! the WIT-side kind (record / variant / enum / flags) and the Rust
//! ident wit-bindgen emitted for it, recovered by probing the
//! [`BindingsIndex`]. Per-method args structs are synthesized into
//! the same IR so the emitter dispatches on a single [`NamedKind`]
//! match.
//!
//! Scope is value-typed WIT — resources, futures, streams, and
//! handles get rejected loudly at build time.

use std::collections::HashSet;

use anyhow::{anyhow, bail, Context, Result};
use heck::{ToShoutySnakeCase, ToSnakeCase, ToUpperCamelCase};
use proc_macro2::{Span, TokenStream};
use quote::quote;
use wit_parser::{
    Function, Handle, Interface, InterfaceId, Resolve, Type, TypeDefKind, TypeId, TypeOwner,
    WorldId, WorldItem,
};

use super::bindings_index::{bindings_path_tokens, BindingsItem, BindingsPath, WrapperBindings};

/// Per-interface metadata collected from the world: WIT InterfaceId,
/// the Rust module path wit-bindgen emits the iface under, and which
/// side (export/import) it lives on.
///
/// An interface present in both sides of a world is classified as
/// exported — wit-bindgen puts shared types under `exports::` and
/// `pub use`s them on the import side, so the export path is canonical.
struct IfaceEntry {
    id: InterfaceId,
    path: BindingsPath,
    is_export: bool,
}

/// Walk the world and build the IR.
pub fn build_ir(
    resolve: &Resolve,
    world_id: WorldId,
    bindings: &WrapperBindings,
) -> Result<WrapperIR> {
    let world = &resolve.worlds[world_id];

    // Walk exports first, then imports — when an interface is on
    // both sides, the export entry is canonical (wit-bindgen puts
    // shared types under `exports::` and `pub use`s them on the
    // import side). `seen_iface_ids.insert` both records and dedupes.
    let mut ifaces: Vec<IfaceEntry> = Vec::new();
    let mut seen_iface_ids: HashSet<InterfaceId> = HashSet::new();
    let exports = world.exports.iter().map(|(_, item)| (item, true));
    let imports = world.imports.iter().map(|(_, item)| (item, false));
    for (item, is_export) in exports.chain(imports) {
        let id = require_iface(item)?;
        if !seen_iface_ids.insert(id) {
            continue;
        }
        let path = module_path_for_interface(resolve, id, is_export).with_context(|| {
            let side = if is_export { "exported" } else { "imported" };
            format!("could not derive module path for {side} interface")
        })?;
        ifaces.push(IfaceEntry {
            id,
            path,
            is_export,
        });
    }

    // Build the user-declared types list. Dedupe by (path, ident) —
    // a type referenced from multiple interfaces that wit-bindgen
    // `pub use`s under the same Rust path emits once.
    let mut types: Vec<NamedType> = Vec::new();
    let mut seen: HashSet<(BindingsPath, String)> = HashSet::new();
    for entry in &ifaces {
        let iface = &resolve.interfaces[entry.id];
        for (wit_name, type_id) in &iface.types {
            let nt = build_named_type(resolve, &ifaces, *type_id, wit_name, &entry.path, bindings)?;
            if let Some(nt) = nt {
                let key = (
                    match &nt.location {
                        TypeLocation::InBindings { path } => path.clone(),
                        TypeLocation::TopLevel => Vec::new(),
                    },
                    nt.rust_ident.to_string(),
                );
                if seen.insert(key) {
                    types.push(nt);
                }
            }
        }
    }

    // Synthesize one args record per exported method. The Rust ident
    // must match the args struct decl emit_method later produces so
    // the WitTyped impl lines up with the struct it impls.
    let mut args_records: Vec<NamedType> = Vec::new();
    for entry in ifaces.iter().filter(|e| e.is_export) {
        let iface = &resolve.interfaces[entry.id];
        let iface_pascal = iface
            .name
            .as_ref()
            .ok_or_else(|| anyhow!("exported interface has no name"))?
            .to_upper_camel_case();
        for (fn_name, func) in &iface.functions {
            let args = synth_args_record(resolve, &iface_pascal, fn_name, func, &ifaces)?;
            args_records.push(args);
        }
    }

    Ok(WrapperIR {
        types,
        args_records,
    })
}

/// The complete IR for one wrapper crate.
pub struct WrapperIR {
    /// User-declared WIT types reachable from the world. Type
    /// aliases are transparent and not listed.
    pub types: Vec<NamedType>,
    /// One synthesized args record per exported Guest method.
    pub args_records: Vec<NamedType>,
}

/// A named entity that gets a `WitTyped` impl: either a WIT-declared
/// type or a synthesized args record.
pub struct NamedType {
    pub location: TypeLocation,
    pub rust_ident: syn::Ident,
    pub kind: NamedKind,
}

pub enum TypeLocation {
    /// Inside `mod bindings::<path>` (wit-bindgen output).
    InBindings { path: BindingsPath },
    /// Top-level in the wrapper crate.
    TopLevel,
}

impl NamedType {
    /// Fully-qualified Rust path the emitter writes to refer to this
    /// type. E.g. `bindings::exports::pkg::ops::Point` for a user
    /// type, or `OpsAddArgs` for a top-level synthesized args struct.
    pub fn rust_path_tokens(&self) -> TokenStream {
        let ident = &self.rust_ident;
        match &self.location {
            TypeLocation::InBindings { path } => bindings_path_tokens(path, Some(ident)),
            TypeLocation::TopLevel => quote!(#ident),
        }
    }
}

pub enum NamedKind {
    Record { fields: Vec<RecordField> },
    Variant { cases: Vec<VariantCase> },
    Enum { cases: Vec<EnumCase> },
    Flags { members: Vec<FlagMember> },
}

pub struct RecordField {
    /// Kebab-cased WIT field name (e.g. `"pet-name"`).
    pub wit_name: String,
    /// snake_case Rust ident, with a trailing `_` for Rust-keyword
    /// collisions (wit-bindgen's convention; pinned in bindgen tests).
    pub rust_ident: syn::Ident,
    pub ty: WitTypeRef,
}

pub struct VariantCase {
    pub wit_name: String,
    pub rust_ident: syn::Ident,
    pub payload: Option<WitTypeRef>,
}

pub struct EnumCase {
    pub wit_name: String,
    pub rust_ident: syn::Ident,
}

pub struct FlagMember {
    pub wit_name: String,
    /// SHOUTING_SNAKE_CASE const ident inside the `bitflags!` body.
    pub rust_ident: syn::Ident,
}

pub struct NamedRef {
    pub path: BindingsPath,
    pub rust_ident: syn::Ident,
}

/// A reference to a WIT type at a field, arg, or return position.
pub enum WitTypeRef {
    Primitive(Prim),
    List(Box<WitTypeRef>),
    Option(Box<WitTypeRef>),
    Result {
        ok: Option<Box<WitTypeRef>>,
        err: Option<Box<WitTypeRef>>,
    },
    Tuple(Vec<WitTypeRef>),
    Named(NamedRef),
}
impl WitTypeRef {
    /// Render as Rust source. E.g. `u32`, `Vec<u32>`,
    /// `Option<String>`, `Result<u32, String>`, `(u32, String)`,
    /// `bindings::pkg::ops::Point`.
    pub fn to_tokens(&self) -> TokenStream {
        match self {
            WitTypeRef::Primitive(p) => p.to_tokens(),
            WitTypeRef::List(inner) => {
                let t = inner.to_tokens();
                quote!(::std::vec::Vec<#t>)
            }
            WitTypeRef::Option(inner) => {
                let t = inner.to_tokens();
                quote!(::core::option::Option<#t>)
            }
            WitTypeRef::Result { ok, err } => {
                let ok_ty = match ok {
                    Some(t) => t.to_tokens(),
                    None => quote!(()),
                };
                let err_ty = match err {
                    Some(t) => t.to_tokens(),
                    None => quote!(()),
                };
                quote!(::core::result::Result<#ok_ty, #err_ty>)
            }
            WitTypeRef::Tuple(elems) => {
                let ts: Vec<_> = elems.iter().map(|t| t.to_tokens()).collect();
                if ts.len() == 1 {
                    let t = &ts[0];
                    quote!((#t,))
                } else {
                    quote!((#(#ts),*))
                }
            }
            WitTypeRef::Named(NamedRef { path, rust_ident }) => {
                bindings_path_tokens(path, Some(rust_ident))
            }
        }
    }
}

#[derive(Copy, Clone)]
pub enum Prim {
    Bool,
    U8,
    U16,
    U32,
    U64,
    S8,
    S16,
    S32,
    S64,
    F32,
    F64,
    Char,
    String,
}
impl Prim {
    fn to_tokens(self) -> TokenStream {
        match self {
            Prim::Bool => quote!(bool),
            Prim::U8 => quote!(u8),
            Prim::U16 => quote!(u16),
            Prim::U32 => quote!(u32),
            Prim::U64 => quote!(u64),
            Prim::S8 => quote!(i8),
            Prim::S16 => quote!(i16),
            Prim::S32 => quote!(i32),
            Prim::S64 => quote!(i64),
            Prim::F32 => quote!(f32),
            Prim::F64 => quote!(f64),
            Prim::Char => quote!(char),
            Prim::String => quote!(::std::string::String),
        }
    }
}

fn build_named_type(
    resolve: &Resolve,
    ifaces: &[IfaceEntry],
    type_id: TypeId,
    wit_name: &str,
    bindings_path: &BindingsPath,
    bindings: &WrapperBindings,
) -> Result<Option<NamedType>> {
    let td = &resolve.types[type_id];
    let rust_ident_str = wit_name.to_upper_camel_case();
    let rust_ident = syn::Ident::new(&rust_ident_str, Span::call_site());

    let kind = match &td.kind {
        TypeDefKind::Record(r) => {
            let item = bindings.index.get(bindings_path, &rust_ident_str);
            match item {
                Some(BindingsItem::Struct) => {}
                _ => bail!(
                    "wit-bindgen did not emit a struct for WIT record {wit_name:?} at \
                     bindings::{} (got {})",
                    bindings_path.join("::"),
                    describe_item(item),
                ),
            };
            let fields = record_fields_from(
                resolve,
                ifaces,
                r.fields.iter().map(|f| (f.name.as_str(), f.ty)),
            )?;
            NamedKind::Record { fields }
        }
        TypeDefKind::Variant(v) => {
            let item = bindings.index.get(bindings_path, &rust_ident_str);
            match item {
                Some(BindingsItem::Enum) => {}
                _ => bail!(
                    "wit-bindgen did not emit an enum for WIT variant {wit_name:?} at \
                     bindings::{} (got {})",
                    bindings_path.join("::"),
                    describe_item(item),
                ),
            };
            let cases = v
                .cases
                .iter()
                .map(|c| {
                    let pascal = c.name.to_upper_camel_case();
                    Ok(VariantCase {
                        wit_name: c.name.clone(),
                        rust_ident: syn::Ident::new(&pascal, Span::call_site()),
                        payload: c
                            .ty
                            .as_ref()
                            .map(|t| type_to_ref(resolve, ifaces, t))
                            .transpose()?,
                    })
                })
                .collect::<Result<_>>()?;
            NamedKind::Variant { cases }
        }
        TypeDefKind::Enum(e) => {
            let item = bindings.index.get(bindings_path, &rust_ident_str);
            match item {
                Some(BindingsItem::Enum) => {}
                _ => bail!(
                    "wit-bindgen did not emit an enum for WIT enum {wit_name:?} at \
                     bindings::{} (got {})",
                    bindings_path.join("::"),
                    describe_item(item),
                ),
            };
            let cases = e
                .cases
                .iter()
                .map(|c| EnumCase {
                    wit_name: c.name.clone(),
                    rust_ident: syn::Ident::new(&c.name.to_upper_camel_case(), Span::call_site()),
                })
                .collect();
            NamedKind::Enum { cases }
        }
        TypeDefKind::Flags(f) => {
            let item = bindings.index.get(bindings_path, &rust_ident_str);
            match item {
                Some(BindingsItem::BitflagsMacro) => {}
                _ => bail!(
                    "wit-bindgen did not emit a bitflags! macro for WIT flags {wit_name:?} \
                     at bindings::{} (got {})",
                    bindings_path.join("::"),
                    describe_item(item),
                ),
            };
            let members = f
                .flags
                .iter()
                .map(|flag| FlagMember {
                    wit_name: flag.name.clone(),
                    rust_ident: syn::Ident::new(
                        &flag.name.to_shouty_snake_case(),
                        Span::call_site(),
                    ),
                })
                .collect();
            NamedKind::Flags { members }
        }
        // Type aliases are transparent: emit no NamedType for the
        // alias, let `<Alias as WitTyped>::…` resolve through the
        // underlying impl.
        TypeDefKind::Type(_) => return Ok(None),
        TypeDefKind::Resource | TypeDefKind::Handle(_) => {
            bail!("resource and handle types are not supported (encountered {wit_name:?})")
        }
        TypeDefKind::Future(_) | TypeDefKind::Stream(_) => {
            bail!("future and stream types are not supported (encountered {wit_name:?})")
        }
        TypeDefKind::Map(..) | TypeDefKind::FixedLengthList(..) => bail!(
            "{} types are not supported (encountered {wit_name:?})",
            td.kind.as_str()
        ),
        // Structural composites only appear at field/arg position;
        // they're not given a top-level NamedKind.
        TypeDefKind::List(_)
        | TypeDefKind::Option(_)
        | TypeDefKind::Result(_)
        | TypeDefKind::Tuple(_) => bail!(
            "top-level named {} types are not supported (encountered {wit_name:?})",
            td.kind.as_str()
        ),
        TypeDefKind::Unknown => bail!("unresolved WIT type {wit_name:?}"),
    };

    Ok(Some(NamedType {
        location: TypeLocation::InBindings {
            path: bindings_path.clone(),
        },
        rust_ident,
        kind,
    }))
}

fn describe_item(item: Option<&BindingsItem>) -> &'static str {
    match item {
        None => "nothing",
        Some(BindingsItem::Struct) => "Struct",
        Some(BindingsItem::Enum) => "Enum",
        Some(BindingsItem::BitflagsMacro) => "BitflagsMacro",
    }
}

fn type_to_ref(resolve: &Resolve, ifaces: &[IfaceEntry], ty: &Type) -> Result<WitTypeRef> {
    Ok(match ty {
        Type::Bool => WitTypeRef::Primitive(Prim::Bool),
        Type::U8 => WitTypeRef::Primitive(Prim::U8),
        Type::U16 => WitTypeRef::Primitive(Prim::U16),
        Type::U32 => WitTypeRef::Primitive(Prim::U32),
        Type::U64 => WitTypeRef::Primitive(Prim::U64),
        Type::S8 => WitTypeRef::Primitive(Prim::S8),
        Type::S16 => WitTypeRef::Primitive(Prim::S16),
        Type::S32 => WitTypeRef::Primitive(Prim::S32),
        Type::S64 => WitTypeRef::Primitive(Prim::S64),
        Type::F32 => WitTypeRef::Primitive(Prim::F32),
        Type::F64 => WitTypeRef::Primitive(Prim::F64),
        Type::Char => WitTypeRef::Primitive(Prim::Char),
        Type::String => WitTypeRef::Primitive(Prim::String),
        Type::ErrorContext => bail!("error-context type not supported"),
        Type::Id(id) => {
            let td = &resolve.types[*id];
            // Structural composites are rendered inline; named WIT
            // types resolve to a NamedRef pointing at the
            // wit-bindgen-emitted ident.
            match &td.kind {
                TypeDefKind::List(t) => {
                    WitTypeRef::List(Box::new(type_to_ref(resolve, ifaces, t)?))
                }
                TypeDefKind::Option(t) => {
                    WitTypeRef::Option(Box::new(type_to_ref(resolve, ifaces, t)?))
                }
                TypeDefKind::Result(r) => WitTypeRef::Result {
                    ok: r
                        .ok
                        .as_ref()
                        .map(|t| type_to_ref(resolve, ifaces, t).map(Box::new))
                        .transpose()?,
                    err: r
                        .err
                        .as_ref()
                        .map(|t| type_to_ref(resolve, ifaces, t).map(Box::new))
                        .transpose()?,
                },
                TypeDefKind::Tuple(t) => WitTypeRef::Tuple(
                    t.types
                        .iter()
                        .map(|ty| type_to_ref(resolve, ifaces, ty))
                        .collect::<Result<_>>()?,
                ),
                TypeDefKind::Type(inner) => return type_to_ref(resolve, ifaces, inner),
                TypeDefKind::Record(_)
                | TypeDefKind::Variant(_)
                | TypeDefKind::Enum(_)
                | TypeDefKind::Flags(_) => {
                    let (path, rust_ident) = named_ref_for(resolve, ifaces, *id)?;
                    WitTypeRef::Named(NamedRef { path, rust_ident })
                }
                TypeDefKind::Resource
                | TypeDefKind::Handle(Handle::Own(_))
                | TypeDefKind::Handle(Handle::Borrow(_)) => {
                    bail!("resource/handle in field position not supported")
                }
                TypeDefKind::Future(_) | TypeDefKind::Stream(_) => {
                    bail!("future/stream in field position not supported")
                }
                TypeDefKind::Map(..) | TypeDefKind::FixedLengthList(..) => {
                    bail!("{} in field position not supported", td.kind.as_str())
                }
                TypeDefKind::Unknown => bail!("unresolved type in field position"),
            }
        }
    })
}

fn named_ref_for(
    resolve: &Resolve,
    ifaces: &[IfaceEntry],
    type_id: TypeId,
) -> Result<(BindingsPath, syn::Ident)> {
    let td = &resolve.types[type_id];
    let name = td
        .name
        .as_ref()
        .ok_or_else(|| anyhow!("named-WIT type at field position has no name"))?;
    let path = match td.owner {
        TypeOwner::Interface(iface_id) => ifaces
            .iter()
            .find(|e| e.id == iface_id)
            .ok_or_else(|| {
                anyhow!(
                    "type {name:?} is owned by an interface not reachable from the world's \
                     imports or exports"
                )
            })?
            .path
            .clone(),
        TypeOwner::World(_) => bail!("world-owned types not supported"),
        TypeOwner::None => Vec::new(),
    };
    Ok((
        path,
        syn::Ident::new(&name.to_upper_camel_case(), Span::call_site()),
    ))
}

fn require_iface(item: &WorldItem) -> Result<InterfaceId> {
    match item {
        WorldItem::Interface { id, .. } => Ok(*id),
        WorldItem::Function(_) => {
            bail!("world-level functions (outside an interface) are not supported")
        }
        WorldItem::Type { .. } => bail!("world-level type aliases are not supported"),
    }
}

/// Derive the [`BindingsPath`] wit-bindgen-rust uses for an interface:
/// kebab-case package / namespace / iface segments lower to
/// snake_case, exports nest under an `exports::` prefix, imports
/// don't.
fn module_path_for_interface(
    resolve: &Resolve,
    interface_id: InterfaceId,
    is_export: bool,
) -> Result<BindingsPath> {
    let iface: &Interface = &resolve.interfaces[interface_id];
    let iface_name = iface
        .name
        .as_ref()
        .ok_or_else(|| anyhow!("interface has no name"))?;
    let pkg_id = iface
        .package
        .ok_or_else(|| anyhow!("interface {iface_name:?} has no package"))?;
    let pkg = &resolve.packages[pkg_id];
    let mut path = Vec::new();
    if is_export {
        path.push("exports".to_string());
    }
    path.push(pkg.name.namespace.to_snake_case());
    path.push(pkg.name.name.to_snake_case());
    path.push(iface_name.to_snake_case());
    Ok(path)
}

fn synth_args_record(
    resolve: &Resolve,
    iface_pascal: &str,
    fn_name: &str,
    func: &Function,
    ifaces: &[IfaceEntry],
) -> Result<NamedType> {
    let rust_ident = args_struct_ident(iface_pascal, fn_name);
    let fields = record_fields_from(
        resolve,
        ifaces,
        func.params.iter().map(|p| (p.name.as_str(), p.ty)),
    )?;
    Ok(NamedType {
        location: TypeLocation::TopLevel,
        rust_ident,
        kind: NamedKind::Record { fields },
    })
}

/// Map an iterator of `(wit_name, ty)` pairs onto a `Vec<RecordField>`.
/// Used by both user-record construction and per-method args
/// synthesis — same shape, two source-of-truth WIT types.
fn record_fields_from<'a, I>(
    resolve: &Resolve,
    ifaces: &[IfaceEntry],
    pairs: I,
) -> Result<Vec<RecordField>>
where
    I: IntoIterator<Item = (&'a str, Type)>,
{
    pairs
        .into_iter()
        .map(|(name, ty)| {
            Ok(RecordField {
                wit_name: name.to_string(),
                rust_ident: mirror_field_ident(name),
                ty: type_to_ref(resolve, ifaces, &ty)?,
            })
        })
        .collect()
}

/// Canonical name for the splicer-synthesized args struct of one
/// Guest method: `<InterfacePascal><MethodPascal>Args`.
///
/// Single source of truth: both the IR builder and the method-emitter
/// derive the same ident from this helper, so the two walks can't
/// silently disagree on what to look up.
pub(super) fn args_struct_ident(interface_pascal: &str, method_name: &str) -> syn::Ident {
    let method_pascal = method_name.to_upper_camel_case();
    syn::Ident::new(
        &format!("{interface_pascal}{method_pascal}Args"),
        Span::call_site(),
    )
}

/// Mirror a WIT field/param name onto wit-bindgen's emitted Rust
/// ident: kebab → snake_case, with a trailing `_` for Rust-keyword
/// collisions.
fn mirror_field_ident(wit_name: &str) -> syn::Ident {
    let snake = wit_name.to_snake_case();
    let final_name = if is_rust_keyword(&snake) {
        format!("{snake}_")
    } else {
        snake
    };
    syn::Ident::new(&final_name, Span::call_site())
}

/// True if `s` would collide with a Rust keyword if used unescaped
/// as an identifier. Defers to `syn`, which maintains the keyword set
/// and tracks Rust grammar evolution.
///
/// Precondition: `s` is already syntactically valid identifier text
/// (letters / digits / underscore, no leading digit). heck's
/// snake-case output satisfies this; other inputs would also return
/// `true` here since `syn::Ident::parse` rejects non-ident strings.
pub(super) fn is_rust_keyword(s: &str) -> bool {
    syn::parse_str::<syn::Ident>(s).is_err()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::adapter::typed::bindgen::run_wit_bindgen_rust;
    use crate::adapter::typed::bindings_index::build_bindings_index;

    fn build(wit: &str, world: &str) -> WrapperIR {
        let (resolve, world_id, src) = run_wit_bindgen_rust(wit, Some(world)).unwrap();
        let bindings = build_bindings_index(&src).unwrap();
        build_ir(&resolve, world_id, &bindings).unwrap()
    }

    #[test]
    fn record_field_types_capture_primitives_and_compositions() {
        let wit = r#"
            package test:pkg@0.1.0;
            interface ops {
                record point { x: u32, y: u32, label: string }
                record blob { bytes: list<u8>, tag: option<string> }
                use-p: func(p: point) -> blob;
            }
            world w { export ops; }
        "#;
        let ir = build(wit, "w");
        let point = ir
            .types
            .iter()
            .find(|t| t.rust_ident == "Point")
            .expect("Point in IR");
        match &point.kind {
            NamedKind::Record { fields } => {
                assert_eq!(fields.len(), 3);
                assert_eq!(fields[0].wit_name, "x");
                assert!(matches!(fields[0].ty, WitTypeRef::Primitive(Prim::U32)));
                assert_eq!(fields[2].wit_name, "label");
                assert!(matches!(fields[2].ty, WitTypeRef::Primitive(Prim::String)));
            }
            _ => panic!("expected Record"),
        }
        let blob = ir
            .types
            .iter()
            .find(|t| t.rust_ident == "Blob")
            .expect("Blob in IR");
        match &blob.kind {
            NamedKind::Record { fields } => {
                assert_eq!(fields[0].wit_name, "bytes");
                assert!(
                    matches!(&fields[0].ty, WitTypeRef::List(inner)
                        if matches!(**inner, WitTypeRef::Primitive(Prim::U8))),
                    "expected list<u8>"
                );
                assert_eq!(fields[1].wit_name, "tag");
                assert!(
                    matches!(&fields[1].ty, WitTypeRef::Option(inner)
                        if matches!(**inner, WitTypeRef::Primitive(Prim::String))),
                    "expected option<string>"
                );
            }
            _ => panic!("expected Record"),
        }
    }

    #[test]
    fn flags_kind_recovers_kebab_and_shouting_snake_idents() {
        let wit = r#"
            package test:pkg@0.1.0;
            interface ops {
                flags perms { read, write, exec-x }
                check: func(p: perms);
            }
            world w { export ops; }
        "#;
        let ir = build(wit, "w");
        let perms = ir
            .types
            .iter()
            .find(|t| t.rust_ident == "Perms")
            .expect("Perms in IR");
        match &perms.kind {
            NamedKind::Flags { members } => {
                assert_eq!(members.len(), 3);
                assert_eq!(members[0].wit_name, "read");
                assert_eq!(members[0].rust_ident, "READ");
                assert_eq!(members[2].wit_name, "exec-x");
                assert_eq!(members[2].rust_ident, "EXEC_X");
            }
            _ => panic!("expected Flags"),
        }
    }

    #[test]
    fn variant_kind_captures_unit_and_payload_cases() {
        let wit = r#"
            package test:pkg@0.1.0;
            interface ops {
                variant outcome { miss, hit(u32), report(string) }
                go: func() -> outcome;
            }
            world w { export ops; }
        "#;
        let ir = build(wit, "w");
        let outcome = ir
            .types
            .iter()
            .find(|t| t.rust_ident == "Outcome")
            .expect("Outcome in IR");
        match &outcome.kind {
            NamedKind::Variant { cases } => {
                assert_eq!(cases.len(), 3);
                assert!(cases[0].payload.is_none());
                assert!(
                    matches!(cases[1].payload, Some(WitTypeRef::Primitive(Prim::U32))),
                    "hit should carry u32"
                );
                assert_eq!(cases[2].rust_ident, "Report");
            }
            _ => panic!("expected Variant"),
        }
    }

    #[test]
    fn enum_kind_collects_unit_cases() {
        let wit = r#"
            package test:pkg@0.1.0;
            interface ops {
                enum color { red, green, blue }
                tag: func(c: color);
            }
            world w { export ops; }
        "#;
        let ir = build(wit, "w");
        let color = ir
            .types
            .iter()
            .find(|t| t.rust_ident == "Color")
            .expect("Color in IR");
        match &color.kind {
            NamedKind::Enum { cases } => {
                assert_eq!(cases.len(), 3);
                assert_eq!(cases[0].wit_name, "red");
                assert_eq!(cases[0].rust_ident, "Red");
            }
            _ => panic!("expected Enum"),
        }
    }

    #[test]
    fn args_records_synthesized_per_method() {
        let wit = r#"
            package test:pkg@0.1.0;
            interface ops {
                add: func(a: u32, b: u32) -> u32;
                noop: func();
            }
            world w { export ops; }
        "#;
        let ir = build(wit, "w");
        assert_eq!(ir.args_records.len(), 2);
        let add_args = ir
            .args_records
            .iter()
            .find(|t| t.rust_ident == "OpsAddArgs")
            .expect("OpsAddArgs in args_records");
        match &add_args.kind {
            NamedKind::Record { fields } => assert_eq!(fields.len(), 2),
            _ => panic!("args should be Records"),
        }
        let noop_args = ir
            .args_records
            .iter()
            .find(|t| t.rust_ident == "OpsNoopArgs")
            .expect("OpsNoopArgs in args_records");
        match &noop_args.kind {
            NamedKind::Record { fields } => assert_eq!(fields.len(), 0),
            _ => panic!("args should be Records"),
        }
    }

    #[test]
    fn keyword_field_idents_get_trailing_underscore() {
        let wit = r#"
            package test:pkg@0.1.0;
            interface ops {
                record %type {
                    %loop: u32,
                    %match: u32,
                }
                use-t: func(t: %type);
            }
            world w { export ops; }
        "#;
        let ir = build(wit, "w");
        let t = ir.types.iter().find(|t| t.rust_ident == "Type").unwrap();
        match &t.kind {
            NamedKind::Record { fields } => {
                let names: Vec<String> = fields.iter().map(|f| f.rust_ident.to_string()).collect();
                assert!(names.contains(&"loop_".to_string()));
                assert!(names.contains(&"match_".to_string()));
            }
            _ => panic!("expected Record"),
        }
    }

    #[test]
    fn resources_are_rejected_loudly() {
        let wit = r#"
            package test:pkg@0.1.0;
            interface ops {
                resource thing { }
                make: func() -> thing;
            }
            world w { export ops; }
        "#;
        let (resolve, world_id, src) = run_wit_bindgen_rust(wit, Some("w")).unwrap();
        let bindings = build_bindings_index(&src).unwrap();
        let err = match build_ir(&resolve, world_id, &bindings) {
            Ok(_) => panic!("expected resource rejection"),
            Err(e) => e,
        };
        let msg = format!("{err:#}");
        assert!(
            msg.contains("resource"),
            "expected resource rejection; got: {msg}"
        );
    }

    #[test]
    fn type_alias_is_transparent() {
        let wit = r#"
            package test:pkg@0.1.0;
            interface ops {
                type %id = u32;
                fetch: func(i: %id) -> %id;
            }
            world w { export ops; }
        "#;
        let ir = build(wit, "w");
        // No NamedType is emitted for the alias.
        assert!(!ir.types.iter().any(|t| t.rust_ident == "Id"));
        // Args record uses u32 directly (the alias is transparent).
        let args = ir
            .args_records
            .iter()
            .find(|t| t.rust_ident == "OpsFetchArgs")
            .unwrap();
        match &args.kind {
            NamedKind::Record { fields } => {
                assert_eq!(fields.len(), 1);
                assert!(matches!(fields[0].ty, WitTypeRef::Primitive(Prim::U32)));
            }
            _ => panic!(),
        }
    }
}