fidius-wit 0.5.6

WIT generation for the Fidius WASM backend: maps Rust interface types (incl. #[derive(WitType)] structs/enums) to WIT records/variants, and emits the generated↔author conversions. Shared by fidius-macro, the build helper, and the CLI.
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
// Copyright 2026 Colliery, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Source-parsing WIT generator (FIDIUS-I-0023).
//!
//! Parses a plugin crate's Rust source, finds the `#[plugin_interface]` trait and
//! every `#[derive(WitType)]` `struct`/`enum`, and produces (a) a complete `.wit`
//! document (records/variants + funcs) and (b) the Rust source for
//! generated↔author `From` conversions the wasm adapter includes. A proc-macro
//! can't see external type definitions, so this runs from a `build.rs` helper and
//! the `fidius wit` CLI, which read the source files.

use std::collections::BTreeSet;

use syn::{FnArg, Item, Pat, ReturnType, TraitItem, Type};

use crate::{
    enum_to_wit, return_to_wit_with, struct_to_record, to_kebab_case, wit_type_with, WitMethod,
};

/// The product of generating from a plugin crate's source.
pub struct Generated {
    /// The interface's Rust trait name (e.g. `Greeter`).
    pub interface_name: String,
    /// kebab-case interface name (the WIT package + interface name).
    pub iface_kebab: String,
    /// Rust idents of the `#[derive(WitType)]` user types found.
    pub user_types: Vec<String>,
    /// The complete `.wit` document.
    pub wit: String,
    /// Rust source for the generated↔author `From` conversions (to be `include!`d
    /// inside the wasm adapter module). Empty when there are no user types.
    pub conversions: String,
}

/// Generate WIT + conversions from a crate's source string (`lib.rs`). Inline
/// modules (`mod m { .. }`) are walked; external `mod m;` files cannot be read
/// from a bare string — use [`generate_from_path`] (the `build.rs` helper does).
pub fn generate(src: &str) -> Result<Generated, String> {
    let file = syn::parse_file(src).map_err(|e| format!("parse error: {e}"))?;
    let mut acc = Collected::default();
    collect(&file.items, &[], None, &mut acc)?;
    assemble(acc)
}

/// Like [`generate`], but reads `lib_rs` and follows external `mod m;` files
/// (resolving `m.rs` / `m/mod.rs`), so `#[derive(WitType)]` types and the
/// `#[plugin_interface]` trait may live in submodules.
pub fn generate_from_path(lib_rs: &std::path::Path) -> Result<Generated, String> {
    let src = std::fs::read_to_string(lib_rs)
        .map_err(|e| format!("reading {}: {e}", lib_rs.display()))?;
    let file = syn::parse_file(&src).map_err(|e| format!("parse {}: {e}", lib_rs.display()))?;
    let dir = lib_rs.parent().unwrap_or_else(|| std::path::Path::new("."));
    let mut acc = Collected::default();
    collect(&file.items, &[], Some(dir), &mut acc)?;
    assemble(acc)
}

/// `#[derive(WitType)]` types (tagged with their Rust module path) + the
/// `#[plugin_interface]` trait, gathered across the module tree.
#[derive(Default)]
struct Collected {
    structs: Vec<(Vec<String>, syn::ItemStruct)>,
    enums: Vec<(Vec<String>, syn::ItemEnum)>,
    the_trait: Option<syn::ItemTrait>,
}

/// Recursively gather items, descending into inline `mod m { .. }` and (when
/// `dir` is `Some`) external `mod m;` files (`m.rs` / `m/mod.rs`).
fn collect(
    items: &[Item],
    mod_path: &[String],
    dir: Option<&std::path::Path>,
    acc: &mut Collected,
) -> Result<(), String> {
    for item in items {
        match item {
            Item::Struct(s) if has_derive(&s.attrs, "WitType") => {
                acc.structs.push((mod_path.to_vec(), s.clone()));
            }
            Item::Enum(e) if has_derive(&e.attrs, "WitType") => {
                acc.enums.push((mod_path.to_vec(), e.clone()));
            }
            Item::Trait(t) if has_attr(&t.attrs, "plugin_interface") => {
                if acc.the_trait.is_some() {
                    return Err("multiple #[plugin_interface] traits found".into());
                }
                acc.the_trait = Some(t.clone());
            }
            Item::Mod(m) => {
                let mut child = mod_path.to_vec();
                child.push(m.ident.to_string());
                if let Some((_, items)) = &m.content {
                    let sub = dir.map(|d| d.join(m.ident.to_string()));
                    collect(items, &child, sub.as_deref(), acc)?;
                } else if let Some(d) = dir {
                    let name = m.ident.to_string();
                    let candidates = [d.join(format!("{name}.rs")), d.join(&name).join("mod.rs")];
                    let file = candidates.iter().find(|p| p.exists()).ok_or_else(|| {
                        format!(
                            "cannot find module file for `mod {name};` near {}",
                            d.display()
                        )
                    })?;
                    let src = std::fs::read_to_string(file)
                        .map_err(|e| format!("reading {}: {e}", file.display()))?;
                    let parsed = syn::parse_file(&src)
                        .map_err(|e| format!("parse {}: {e}", file.display()))?;
                    collect(&parsed.items, &child, Some(&d.join(&name)), acc)?;
                }
            }
            _ => {}
        }
    }
    Ok(())
}

/// Build the `.wit` + conversions from the collected items.
fn assemble(acc: Collected) -> Result<Generated, String> {
    let the_trait = acc
        .the_trait
        .ok_or("no #[plugin_interface] trait found in source")?;
    let interface_name = the_trait.ident.to_string();
    let iface_kebab = to_kebab_case(&interface_name);

    let mut user_types: Vec<String> = Vec::new();
    user_types.extend(acc.structs.iter().map(|(_, s)| s.ident.to_string()));
    user_types.extend(acc.enums.iter().map(|(_, e)| e.ident.to_string()));
    let known: BTreeSet<String> = user_types.iter().cloned().collect();

    // Type defs: records (struct records + synthetic struct-variant payload
    // records) before variants, so forward references resolve cleanly.
    let mut type_defs: Vec<String> = Vec::new();
    let mut variant_defs: Vec<String> = Vec::new();
    for (_, s) in &acc.structs {
        type_defs.push(struct_to_record(s, &known)?);
    }
    for (_, e) in &acc.enums {
        let (synthetic, variant) = enum_to_wit(e, &known)?;
        type_defs.extend(synthetic);
        variant_defs.push(variant);
    }
    type_defs.extend(variant_defs);

    let mut methods: Vec<WitMethod> = Vec::new();
    for item in &the_trait.items {
        let TraitItem::Fn(f) = item else { continue };
        let mut params = Vec::new();
        for arg in &f.sig.inputs {
            let FnArg::Typed(pt) = arg else { continue }; // skip &self

            // Client-/bidi-streaming: the `Stream<T>` input arg crosses as bincode via the
            // `fidius:stream-pull` import, not a WIT param — exclude it (FIDIUS-T-0175). The
            // return-side handling below renders a `Stream` *return* as a resource (bidi).
            if crate::stream_item_type(&pt.ty).is_some() {
                continue;
            }
            let name = match pt.pat.as_ref() {
                Pat::Ident(id) => to_kebab_case(&id.ident.to_string()),
                _ => "arg".to_string(),
            };
            let wt = wit_type_with(&pt.ty, &known)
                .map_err(|e| format!("method `{}` arg `{name}`: {e}", f.sig.ident))?;
            params.push((name, wt));
        }
        let ret_ty: Option<&Type> = match &f.sig.output {
            ReturnType::Type(_, t) => Some(t.as_ref()),
            ReturnType::Default => None,
        };
        // Server-streaming (`-> fidius::Stream<T>`): the func renders as a
        // resource-returning export, not a value return (FIDIUS-I-0026).
        let stream_item = ret_ty.and_then(crate::stream_item_type);
        let (ret, stream_item) = match stream_item {
            Some(item_ty) => {
                let item_wit = wit_type_with(item_ty, &known)
                    .map_err(|e| format!("method `{}` stream item: {e}", f.sig.ident))?;
                (None, Some(item_wit))
            }
            None => {
                let ret = return_to_wit_with(ret_ty, &known)
                    .map_err(|e| format!("method `{}` return: {e}", f.sig.ident))?;
                (ret, None)
            }
        };
        methods.push(WitMethod {
            name: to_kebab_case(&f.sig.ident.to_string()),
            params,
            ret,
            stream_item,
        });
    }

    let wit = crate::render_wit_full(&iface_kebab, &type_defs, &methods);
    let conversions = render_conversions(&iface_kebab, &acc.structs, &acc.enums, &known);

    Ok(Generated {
        interface_name,
        iface_kebab,
        user_types,
        wit,
        conversions,
    })
}

/// `crate::<mod::path>::<Name>` — the author-side path for a type at `mod_path`.
fn author_path(mod_path: &[String], name: &str) -> String {
    if mod_path.is_empty() {
        format!("crate::{name}")
    } else {
        format!("crate::{}::{name}", mod_path.join("::"))
    }
}

/// The keywords wit-bindgen's `to_rust_ident` escapes with a trailing `_` (its
/// `wit-bindgen-rust` source, in turn the Rust reference keyword list). When a
/// WIT field name collides with one of these, wit-bindgen names the generated
/// struct field `<kw>_` (e.g. `type` → `type_`) — *not* the raw ident `r#type`
/// the author wrote. The conversion code must address the generated field by
/// that mangled name, or it fails to compile (FIDIUS-T-0177).
const RUST_KEYWORDS: &[&str] = &[
    "as", "break", "const", "continue", "crate", "else", "enum", "extern", "false", "fn", "for",
    "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref", "return",
    "self", "static", "struct", "super", "trait", "true", "type", "unsafe", "use", "where",
    "while", "async", "await", "dyn", "abstract", "become", "box", "do", "final", "macro",
    "override", "priv", "typeof", "unsized", "virtual", "yield", "try",
];

/// The author's field ident (`record`, or the raw `r#type`) paired with the name
/// wit-bindgen gives the *generated* mirror field. They differ only when the
/// field name is a Rust keyword: the author writes `r#type`, wit-bindgen emits
/// `type_`. For every other name the two are identical (the author field is
/// already snake_case, which is what wit-bindgen produces).
fn field_idents(fl: &syn::Field) -> (String, String) {
    let author = fl.ident.as_ref().unwrap().to_string();
    let bare = author.strip_prefix("r#").unwrap_or(&author);
    let generated = if RUST_KEYWORDS.contains(&bare) {
        format!("{bare}_")
    } else {
        author.clone()
    };
    (author, generated)
}

/// Render `From` impls (both directions) between each user type and its
/// wit-bindgen-generated mirror. Emitted into the adapter module, where the
/// generated types live (flat) at `exports::fidius::<iface>::<iface>::<Type>`
/// and the author types at `crate::<mod::path>::<Type>`.
fn render_conversions(
    iface_kebab: &str,
    structs: &[(Vec<String>, syn::ItemStruct)],
    enums: &[(Vec<String>, syn::ItemEnum)],
    known: &BTreeSet<String>,
) -> String {
    if structs.is_empty() && enums.is_empty() {
        return String::new();
    }
    let snake = iface_kebab.replace('-', "_");
    let gen_path = format!("exports::fidius::{snake}::{snake}");
    let mut out = String::new();
    out.push_str("// Generated by fidius-wit: author <-> wit-bindgen conversions.\n");

    for (path, s) in structs {
        let name = s.ident.to_string();
        let g = format!("{gen_path}::{name}");
        let a = author_path(path, &name);
        // (author-name, generated-name, type) per named field. The two names
        // differ only for Rust-keyword fields (`r#type` vs `type_`).
        let fields: Vec<(String, String, &Type)> = match &s.fields {
            syn::Fields::Named(f) => f
                .named
                .iter()
                .map(|fl| {
                    let (au, gen) = field_idents(fl);
                    (au, gen, &fl.ty)
                })
                .collect(),
            _ => Vec::new(),
        };
        // generated -> author: build the author struct, reading the generated `v`.
        let to_author: Vec<String> = fields
            .iter()
            .map(|(au, gen, ty)| format!("{au}: {}", conv_expr(&format!("v.{gen}"), ty, known)))
            .collect();
        out.push_str(&format!(
            "impl ::core::convert::From<{g}> for {a} {{ fn from(v: {g}) -> Self {{ {a} {{ {} }} }} }}\n",
            to_author.join(", ")
        ));
        // author -> generated: build the generated struct, reading the author `v`.
        let to_gen: Vec<String> = fields
            .iter()
            .map(|(au, gen, ty)| format!("{gen}: {}", conv_expr(&format!("v.{au}"), ty, known)))
            .collect();
        out.push_str(&format!(
            "impl ::core::convert::From<{a}> for {g} {{ fn from(v: {a}) -> Self {{ {g} {{ {} }} }} }}\n",
            to_gen.join(", ")
        ));
    }

    for (path, e) in enums {
        let ename = e.ident.to_string();
        let g = format!("{gen_path}::{ename}");
        let a = author_path(path, &ename);

        let mut g2a = Vec::new(); // generated -> author
        let mut a2g = Vec::new(); // author -> generated
        for v in &e.variants {
            let case = v.ident.to_string();
            match &v.fields {
                syn::Fields::Unit => {
                    g2a.push(format!("{g}::{case} => {a}::{case}"));
                    a2g.push(format!("{a}::{case} => {g}::{case}"));
                }
                syn::Fields::Unnamed(u) if u.unnamed.len() == 1 => {
                    let ty = &u.unnamed[0].ty;
                    g2a.push(format!(
                        "{g}::{case}(x) => {a}::{case}({})",
                        conv_expr("x", ty, known)
                    ));
                    a2g.push(format!(
                        "{a}::{case}(x) => {g}::{case}({})",
                        conv_expr("x", ty, known)
                    ));
                }
                syn::Fields::Named(f) => {
                    // The gen side wraps the case payload in a synthesized record
                    // (`<Enum><Case>`, e.g. `ShapeRect`); the author side is a
                    // struct variant with inline fields.
                    let gen_rec = format!("{gen_path}::{ename}{case}");
                    // (author-name, generated-name, type) per payload field.
                    let fnames: Vec<(String, String, &Type)> = f
                        .named
                        .iter()
                        .map(|fl| {
                            let (au, gen) = field_idents(fl);
                            (au, gen, &fl.ty)
                        })
                        .collect();
                    // generated -> author: read the generated record `__r`, build
                    // the author struct variant.
                    let g2a_inits = fnames
                        .iter()
                        .map(|(au, gen, ty)| {
                            format!("{au}: {}", conv_expr(&format!("__r.{gen}"), ty, known))
                        })
                        .collect::<Vec<_>>()
                        .join(", ");
                    g2a.push(format!("{g}::{case}(__r) => {a}::{case} {{ {g2a_inits} }}"));

                    // author -> generated: destructure the author variant (author
                    // field names bind the locals), build the generated record.
                    let binds = fnames
                        .iter()
                        .map(|(au, ..)| au.clone())
                        .collect::<Vec<_>>()
                        .join(", ");
                    let a2g_inits = fnames
                        .iter()
                        .map(|(au, gen, ty)| format!("{gen}: {}", conv_expr(au, ty, known)))
                        .collect::<Vec<_>>()
                        .join(", ");
                    a2g.push(format!(
                        "{a}::{case} {{ {binds} }} => {g}::{case}({gen_rec} {{ {a2g_inits} }})"
                    ));
                }
                // Multi-field tuple cases are rejected by `enum_to_wit`.
                syn::Fields::Unnamed(_) => unreachable!("rejected by enum_to_wit"),
            }
        }
        out.push_str(&format!(
            "impl ::core::convert::From<{g}> for {a} {{ fn from(v: {g}) -> Self {{ match v {{ {} }} }} }}\n",
            g2a.join(", ")
        ));
        out.push_str(&format!(
            "impl ::core::convert::From<{a}> for {g} {{ fn from(v: {a}) -> Self {{ match v {{ {} }} }} }}\n",
            a2g.join(", ")
        ));
    }
    out
}

/// Conversion expression for a field/payload `access` of type `ty`. Identity
/// (move) when the type holds no user type (generated and author types are then
/// identical); otherwise `.into()` (user type), or a `map`/`into_iter().map()`
/// recursing through `Option`/`Vec`. Symmetric — works generated→author and
/// author→generated, since `From` is generated both ways. Public so the macro's
/// adapter reuses the exact same boundary conversions.
pub fn conv_expr(access: &str, ty: &Type, known: &BTreeSet<String>) -> String {
    // Maps cross as `list<tuple<k, v>>` — a `Vec<(K, V)>` binding. Convert with
    // `collect()` (bidirectional via type inference: `Vec`↔`HashMap`/`BTreeMap`).
    // Handle before the user-type short-circuit so a `HashMap<String, u32>` (no
    // `#[derive(WitType)]` inside) still converts to/from its binding.
    if let Type::Path(p) = ty {
        if let Some(seg) = p.path.segments.last() {
            if matches!(seg.ident.to_string().as_str(), "HashMap" | "BTreeMap") {
                if let Some((k, v)) = two_generics(seg) {
                    let kc = conv_expr("k", k, known);
                    let vc = conv_expr("v", v, known);
                    if kc == "k" && vc == "v" {
                        return format!("{access}.into_iter().collect()");
                    }
                    return format!("{access}.into_iter().map(|(k, v)| ({kc}, {vc})).collect()");
                }
            }
        }
    }
    if !contains_user_type(ty, known) {
        return access.to_string();
    }
    if let Type::Path(p) = ty {
        if let Some(seg) = p.path.segments.last() {
            let ident = seg.ident.to_string();
            if let Some(inner) = single_generic(seg) {
                match ident.as_str() {
                    "Vec" => {
                        return format!(
                            "{access}.into_iter().map(|w| {}).collect()",
                            conv_expr("w", inner, known)
                        );
                    }
                    "Option" => {
                        return format!("{access}.map(|w| {})", conv_expr("w", inner, known));
                    }
                    _ => {}
                }
            }
            if known.contains(&ident) {
                return format!("{access}.into()");
            }
        }
    }
    access.to_string()
}

/// Whether `ty` is, or contains (through `Vec`/`Option`/`Box`), a user type in
/// `known`. Public so the macro can classify args/returns.
pub fn contains_user_type(ty: &Type, known: &BTreeSet<String>) -> bool {
    if let Type::Path(p) = ty {
        if let Some(seg) = p.path.segments.last() {
            let ident = seg.ident.to_string();
            if known.contains(&ident) {
                return true;
            }
            if matches!(ident.as_str(), "Vec" | "Option" | "Box") {
                if let Some(inner) = single_generic(seg) {
                    return contains_user_type(inner, known);
                }
            }
            if matches!(ident.as_str(), "HashMap" | "BTreeMap") {
                if let Some((k, v)) = two_generics(seg) {
                    return contains_user_type(k, known) || contains_user_type(v, known);
                }
            }
        }
    }
    false
}

fn single_generic(seg: &syn::PathSegment) -> Option<&Type> {
    if let syn::PathArguments::AngleBracketed(ab) = &seg.arguments {
        for a in &ab.args {
            if let syn::GenericArgument::Type(t) = a {
                return Some(t);
            }
        }
    }
    None
}

fn two_generics(seg: &syn::PathSegment) -> Option<(&Type, &Type)> {
    if let syn::PathArguments::AngleBracketed(ab) = &seg.arguments {
        let types: Vec<&Type> = ab
            .args
            .iter()
            .filter_map(|a| match a {
                syn::GenericArgument::Type(t) => Some(t),
                _ => None,
            })
            .collect();
        if types.len() >= 2 {
            return Some((types[0], types[1]));
        }
    }
    None
}

/// Does `attrs` contain `#[<name>(...)]` / `#[<path>::<name>]` (last segment match)?
fn has_attr(attrs: &[syn::Attribute], name: &str) -> bool {
    attrs.iter().any(|a| {
        a.path()
            .segments
            .last()
            .map(|s| s.ident == name)
            .unwrap_or(false)
    })
}

/// Does `attrs` contain a `#[derive(... <name> ...)]`?
fn has_derive(attrs: &[syn::Attribute], name: &str) -> bool {
    for a in attrs {
        if !a.path().is_ident("derive") {
            continue;
        }
        let mut found = false;
        let _ = a.parse_nested_meta(|m| {
            if m.path
                .segments
                .last()
                .map(|s| s.ident == name)
                .unwrap_or(false)
            {
                found = true;
            }
            Ok(())
        });
        if found {
            return true;
        }
    }
    false
}

#[cfg(test)]
mod tests {
    use super::*;

    const SRC: &str = r#"
        #[derive(WitType)]
        pub struct Point { pub x: i32, pub y: i32 }

        #[derive(WitType)]
        pub enum Shape { Circle(u32), Rect(Point), Dot }

        #[plugin_interface(version = 1, crate = "fidius_guest")]
        pub trait Geo: Send + Sync {
            fn midpoint(&self, a: Point, b: Point) -> Point;
            fn classify(&self, pts: Vec<Point>) -> Shape;
            fn name(&self, s: Shape) -> String;
        }
    "#;

    #[test]
    fn generates_wit_with_records_variants_and_funcs() {
        let g = generate(SRC).unwrap();
        assert_eq!(g.interface_name, "Geo");
        assert_eq!(g.iface_kebab, "geo");
        assert!(g.user_types.contains(&"Point".to_string()));
        assert!(g.user_types.contains(&"Shape".to_string()));

        assert!(g.wit.contains("record point {"));
        assert!(g.wit.contains("variant shape {"));
        assert!(g.wit.contains("rect(point),"));
        assert!(g
            .wit
            .contains("midpoint: func(a: point, b: point) -> point;"));
        assert!(g.wit.contains("classify: func(pts: list<point>) -> shape;"));
        assert!(g.wit.contains("name: func(s: shape) -> string;"));
        assert!(g.wit.contains("fidius-interface-hash: func() -> u64;"));
    }

    #[test]
    fn generates_conversions_both_ways() {
        let g = generate(SRC).unwrap();
        let c = &g.conversions;
        // struct record conversions
        assert!(c.contains("From<exports::fidius::geo::geo::Point> for crate::Point"));
        assert!(c.contains("From<crate::Point> for exports::fidius::geo::geo::Point"));
        // enum variant conversions with nested .into() for Rect(Point)
        assert!(c.contains("From<exports::fidius::geo::geo::Shape> for crate::Shape"));
        assert!(
            c.contains("Rect(x) => crate :: Shape :: Rect")
                || c.contains("Rect(x) => crate::Shape::Rect")
        );
        assert!(c.contains(".into()"));
    }

    #[test]
    fn primitive_only_interface_has_no_conversions() {
        let src = r#"
            #[plugin_interface(version = 1)]
            pub trait Greeter { fn greet(&self, name: String) -> String; }
        "#;
        let g = generate(src).unwrap();
        assert!(g.user_types.is_empty());
        assert!(g.conversions.is_empty());
        assert!(g.wit.contains("greet: func(name: string) -> string;"));
    }

    #[test]
    fn unsupported_type_errors() {
        // `Box<T>` has no WIT projection (maps/tuples are now supported, so use a
        // type that genuinely isn't).
        let src = r#"
            #[plugin_interface(version = 1)]
            pub trait T { fn f(&self, x: Box<String>) -> u32; }
        "#;
        assert!(generate(src).is_err());
    }

    /// FIDIUS-T-0177: a guest interface whose types, fields, cases, methods, and
    /// params all use WIT reserved keywords. Before escaping, the generated WIT
    /// is rejected by the parser (the `emit_wit` build failure); after escaping,
    /// it both contains the `%`-escaped identifiers and round-trips through the
    /// same parser wit-bindgen uses — without the wasm toolchain.
    const KEYWORD_SRC: &str = r#"
        #[derive(WitType)]
        pub struct DeadLetter { pub record: String, pub stream: u64, pub from: bool, pub r#type: u8 }

        #[derive(WitType)]
        pub enum Variant { Stream, Record(u32), List { from: u8 } }

        #[plugin_interface(version = 1, crate = "fidius_guest")]
        pub trait Stream: Send + Sync {
            fn record(&self, list: DeadLetter, option: Variant) -> DeadLetter;
        }
    "#;

    #[test]
    fn keyword_heavy_interface_escapes_every_identifier() {
        let g = generate(KEYWORD_SRC).unwrap();
        // interface name (trait `Stream`) is a keyword.
        assert!(g.wit.contains("interface %stream {"), "{}", g.wit);
        assert!(g.wit.contains("package fidius:%stream@0.1.0;"));
        assert!(g.wit.contains("export %stream;"));
        // record + keyword fields (`record`, `stream`, `from`, `r#type`).
        assert!(g.wit.contains("record dead-letter {"));
        assert!(g.wit.contains("%record: string,"));
        assert!(g.wit.contains("%stream: u64,"));
        assert!(g.wit.contains("%from: bool,"));
        assert!(g.wit.contains("%type: u8,"));
        // variant (type named `Variant`) + keyword cases; the synthetic struct-
        // variant payload record (`variant-list`) is compound so it is not escaped.
        assert!(g.wit.contains("variant %variant {"));
        assert!(g.wit.contains("%stream,"));
        assert!(g.wit.contains("%record(u32),"));
        assert!(g.wit.contains("%list(variant-list),"));
        assert!(g.wit.contains("record variant-list {"));
        // method name + param names that are keywords, with a keyword type ref.
        assert!(g
            .wit
            .contains("%record: func(%list: dead-letter, %option: %variant) -> dead-letter;"));
    }

    #[test]
    fn keyword_field_conversions_use_wit_bindgen_mangling() {
        // A Rust-keyword field (`r#type`) is named `type_` on the wit-bindgen
        // side but `r#type` on the author side; the `From` impls must bridge the
        // two (regression for the missing-`type` keyword bug).
        let c = &generate(KEYWORD_SRC).unwrap().conversions;
        // generated -> author: author field `r#type` reads generated `v.type_`.
        assert!(c.contains("r#type: v.type_"), "{c}");
        // author -> generated: generated field `type_` reads author `v.r#type`.
        assert!(c.contains("type_: v.r#type"), "{c}");
        // non-keyword fields stay identical on both sides.
        assert!(c.contains("record: v.record") && c.contains("stream: v.stream"));
    }

    #[test]
    fn keyword_heavy_interface_parses() {
        let g = generate(KEYWORD_SRC).unwrap();
        // Syntactic parse only (no dep resolution): exactly what fails today when
        // the keywords are emitted bare.
        wit_parser::UnresolvedPackageGroup::parse("keyword.wit", &g.wit)
            .unwrap_or_else(|e| panic!("generated WIT must parse: {e}\n---\n{}", g.wit));
    }
}