Skip to main content

fidius_wit/
generate.rs

1// Copyright 2026 Colliery, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Source-parsing WIT generator (FIDIUS-I-0023).
16//!
17//! Parses a plugin crate's Rust source, finds the `#[plugin_interface]` trait and
18//! every `#[derive(WitType)]` `struct`/`enum`, and produces (a) a complete `.wit`
19//! document (records/variants + funcs) and (b) the Rust source for
20//! generated↔author `From` conversions the wasm adapter includes. A proc-macro
21//! can't see external type definitions, so this runs from a `build.rs` helper and
22//! the `fidius wit` CLI, which read the source files.
23
24use std::collections::BTreeSet;
25
26use syn::{FnArg, Item, Pat, ReturnType, TraitItem, Type};
27
28use crate::{
29    enum_to_wit, return_to_wit_with, struct_to_record, to_kebab_case, wit_type_with, WitMethod,
30};
31
32/// The product of generating from a plugin crate's source.
33pub struct Generated {
34    /// The interface's Rust trait name (e.g. `Greeter`).
35    pub interface_name: String,
36    /// kebab-case interface name (the WIT package + interface name).
37    pub iface_kebab: String,
38    /// Rust idents of the `#[derive(WitType)]` user types found.
39    pub user_types: Vec<String>,
40    /// The complete `.wit` document.
41    pub wit: String,
42    /// Rust source for the generated↔author `From` conversions (to be `include!`d
43    /// inside the wasm adapter module). Empty when there are no user types.
44    pub conversions: String,
45}
46
47/// Generate WIT + conversions from a crate's source string (`lib.rs`). Inline
48/// modules (`mod m { .. }`) are walked; external `mod m;` files cannot be read
49/// from a bare string — use [`generate_from_path`] (the `build.rs` helper does).
50pub fn generate(src: &str) -> Result<Generated, String> {
51    let file = syn::parse_file(src).map_err(|e| format!("parse error: {e}"))?;
52    let mut acc = Collected::default();
53    collect(&file.items, &[], None, &mut acc)?;
54    assemble(acc)
55}
56
57/// Like [`generate`], but reads `lib_rs` and follows external `mod m;` files
58/// (resolving `m.rs` / `m/mod.rs`), so `#[derive(WitType)]` types and the
59/// `#[plugin_interface]` trait may live in submodules.
60pub fn generate_from_path(lib_rs: &std::path::Path) -> Result<Generated, String> {
61    let src = std::fs::read_to_string(lib_rs)
62        .map_err(|e| format!("reading {}: {e}", lib_rs.display()))?;
63    let file = syn::parse_file(&src).map_err(|e| format!("parse {}: {e}", lib_rs.display()))?;
64    let dir = lib_rs.parent().unwrap_or_else(|| std::path::Path::new("."));
65    let mut acc = Collected::default();
66    collect(&file.items, &[], Some(dir), &mut acc)?;
67    assemble(acc)
68}
69
70/// `#[derive(WitType)]` types (tagged with their Rust module path) + the
71/// `#[plugin_interface]` trait, gathered across the module tree.
72#[derive(Default)]
73struct Collected {
74    structs: Vec<(Vec<String>, syn::ItemStruct)>,
75    enums: Vec<(Vec<String>, syn::ItemEnum)>,
76    the_trait: Option<syn::ItemTrait>,
77}
78
79/// Recursively gather items, descending into inline `mod m { .. }` and (when
80/// `dir` is `Some`) external `mod m;` files (`m.rs` / `m/mod.rs`).
81fn collect(
82    items: &[Item],
83    mod_path: &[String],
84    dir: Option<&std::path::Path>,
85    acc: &mut Collected,
86) -> Result<(), String> {
87    for item in items {
88        match item {
89            Item::Struct(s) if has_derive(&s.attrs, "WitType") => {
90                acc.structs.push((mod_path.to_vec(), s.clone()));
91            }
92            Item::Enum(e) if has_derive(&e.attrs, "WitType") => {
93                acc.enums.push((mod_path.to_vec(), e.clone()));
94            }
95            Item::Trait(t) if has_attr(&t.attrs, "plugin_interface") => {
96                if acc.the_trait.is_some() {
97                    return Err("multiple #[plugin_interface] traits found".into());
98                }
99                acc.the_trait = Some(t.clone());
100            }
101            Item::Mod(m) => {
102                let mut child = mod_path.to_vec();
103                child.push(m.ident.to_string());
104                if let Some((_, items)) = &m.content {
105                    let sub = dir.map(|d| d.join(m.ident.to_string()));
106                    collect(items, &child, sub.as_deref(), acc)?;
107                } else if let Some(d) = dir {
108                    let name = m.ident.to_string();
109                    let candidates = [d.join(format!("{name}.rs")), d.join(&name).join("mod.rs")];
110                    let file = candidates.iter().find(|p| p.exists()).ok_or_else(|| {
111                        format!(
112                            "cannot find module file for `mod {name};` near {}",
113                            d.display()
114                        )
115                    })?;
116                    let src = std::fs::read_to_string(file)
117                        .map_err(|e| format!("reading {}: {e}", file.display()))?;
118                    let parsed = syn::parse_file(&src)
119                        .map_err(|e| format!("parse {}: {e}", file.display()))?;
120                    collect(&parsed.items, &child, Some(&d.join(&name)), acc)?;
121                }
122            }
123            _ => {}
124        }
125    }
126    Ok(())
127}
128
129/// Build the `.wit` + conversions from the collected items.
130fn assemble(acc: Collected) -> Result<Generated, String> {
131    let the_trait = acc
132        .the_trait
133        .ok_or("no #[plugin_interface] trait found in source")?;
134    let interface_name = the_trait.ident.to_string();
135    let iface_kebab = to_kebab_case(&interface_name);
136
137    let mut user_types: Vec<String> = Vec::new();
138    user_types.extend(acc.structs.iter().map(|(_, s)| s.ident.to_string()));
139    user_types.extend(acc.enums.iter().map(|(_, e)| e.ident.to_string()));
140    let known: BTreeSet<String> = user_types.iter().cloned().collect();
141
142    // Type defs: records (struct records + synthetic struct-variant payload
143    // records) before variants, so forward references resolve cleanly.
144    let mut type_defs: Vec<String> = Vec::new();
145    let mut variant_defs: Vec<String> = Vec::new();
146    for (_, s) in &acc.structs {
147        type_defs.push(struct_to_record(s, &known)?);
148    }
149    for (_, e) in &acc.enums {
150        let (synthetic, variant) = enum_to_wit(e, &known)?;
151        type_defs.extend(synthetic);
152        variant_defs.push(variant);
153    }
154    type_defs.extend(variant_defs);
155
156    let mut methods: Vec<WitMethod> = Vec::new();
157    for item in &the_trait.items {
158        let TraitItem::Fn(f) = item else { continue };
159        let mut params = Vec::new();
160        for arg in &f.sig.inputs {
161            let FnArg::Typed(pt) = arg else { continue }; // skip &self
162            let name = match pt.pat.as_ref() {
163                Pat::Ident(id) => to_kebab_case(&id.ident.to_string()),
164                _ => "arg".to_string(),
165            };
166            let wt = wit_type_with(&pt.ty, &known)
167                .map_err(|e| format!("method `{}` arg `{name}`: {e}", f.sig.ident))?;
168            params.push((name, wt));
169        }
170        let ret_ty: Option<&Type> = match &f.sig.output {
171            ReturnType::Type(_, t) => Some(t.as_ref()),
172            ReturnType::Default => None,
173        };
174        // Server-streaming (`-> fidius::Stream<T>`): the func renders as a
175        // resource-returning export, not a value return (FIDIUS-I-0026).
176        let stream_item = ret_ty.and_then(crate::stream_item_type);
177        let (ret, stream_item) = match stream_item {
178            Some(item_ty) => {
179                let item_wit = wit_type_with(item_ty, &known)
180                    .map_err(|e| format!("method `{}` stream item: {e}", f.sig.ident))?;
181                (None, Some(item_wit))
182            }
183            None => {
184                let ret = return_to_wit_with(ret_ty, &known)
185                    .map_err(|e| format!("method `{}` return: {e}", f.sig.ident))?;
186                (ret, None)
187            }
188        };
189        methods.push(WitMethod {
190            name: to_kebab_case(&f.sig.ident.to_string()),
191            params,
192            ret,
193            stream_item,
194        });
195    }
196
197    let wit = crate::render_wit_full(&iface_kebab, &type_defs, &methods);
198    let conversions = render_conversions(&iface_kebab, &acc.structs, &acc.enums, &known);
199
200    Ok(Generated {
201        interface_name,
202        iface_kebab,
203        user_types,
204        wit,
205        conversions,
206    })
207}
208
209/// `crate::<mod::path>::<Name>` — the author-side path for a type at `mod_path`.
210fn author_path(mod_path: &[String], name: &str) -> String {
211    if mod_path.is_empty() {
212        format!("crate::{name}")
213    } else {
214        format!("crate::{}::{name}", mod_path.join("::"))
215    }
216}
217
218/// Render `From` impls (both directions) between each user type and its
219/// wit-bindgen-generated mirror. Emitted into the adapter module, where the
220/// generated types live (flat) at `exports::fidius::<iface>::<iface>::<Type>`
221/// and the author types at `crate::<mod::path>::<Type>`.
222fn render_conversions(
223    iface_kebab: &str,
224    structs: &[(Vec<String>, syn::ItemStruct)],
225    enums: &[(Vec<String>, syn::ItemEnum)],
226    known: &BTreeSet<String>,
227) -> String {
228    if structs.is_empty() && enums.is_empty() {
229        return String::new();
230    }
231    let snake = iface_kebab.replace('-', "_");
232    let gen_path = format!("exports::fidius::{snake}::{snake}");
233    let mut out = String::new();
234    out.push_str("// Generated by fidius-wit: author <-> wit-bindgen conversions.\n");
235
236    for (path, s) in structs {
237        let name = s.ident.to_string();
238        let g = format!("{gen_path}::{name}");
239        let a = author_path(path, &name);
240        let fields: Vec<String> = match &s.fields {
241            syn::Fields::Named(f) => f
242                .named
243                .iter()
244                .map(|fl| fl.ident.as_ref().unwrap().to_string())
245                .collect(),
246            _ => Vec::new(),
247        };
248        let field_types: Vec<&Type> = match &s.fields {
249            syn::Fields::Named(f) => f.named.iter().map(|fl| &fl.ty).collect(),
250            _ => Vec::new(),
251        };
252        // generated -> author
253        let to_author: Vec<String> = fields
254            .iter()
255            .zip(&field_types)
256            .map(|(f, ty)| format!("{f}: {}", conv_expr(&format!("v.{f}"), ty, known)))
257            .collect();
258        out.push_str(&format!(
259            "impl ::core::convert::From<{g}> for {a} {{ fn from(v: {g}) -> Self {{ {a} {{ {} }} }} }}\n",
260            to_author.join(", ")
261        ));
262        // author -> generated
263        let to_gen: Vec<String> = fields
264            .iter()
265            .zip(&field_types)
266            .map(|(f, ty)| format!("{f}: {}", conv_expr(&format!("v.{f}"), ty, known)))
267            .collect();
268        out.push_str(&format!(
269            "impl ::core::convert::From<{a}> for {g} {{ fn from(v: {a}) -> Self {{ {g} {{ {} }} }} }}\n",
270            to_gen.join(", ")
271        ));
272    }
273
274    for (path, e) in enums {
275        let ename = e.ident.to_string();
276        let g = format!("{gen_path}::{ename}");
277        let a = author_path(path, &ename);
278
279        let mut g2a = Vec::new(); // generated -> author
280        let mut a2g = Vec::new(); // author -> generated
281        for v in &e.variants {
282            let case = v.ident.to_string();
283            match &v.fields {
284                syn::Fields::Unit => {
285                    g2a.push(format!("{g}::{case} => {a}::{case}"));
286                    a2g.push(format!("{a}::{case} => {g}::{case}"));
287                }
288                syn::Fields::Unnamed(u) if u.unnamed.len() == 1 => {
289                    let ty = &u.unnamed[0].ty;
290                    g2a.push(format!(
291                        "{g}::{case}(x) => {a}::{case}({})",
292                        conv_expr("x", ty, known)
293                    ));
294                    a2g.push(format!(
295                        "{a}::{case}(x) => {g}::{case}({})",
296                        conv_expr("x", ty, known)
297                    ));
298                }
299                syn::Fields::Named(f) => {
300                    // The gen side wraps the case payload in a synthesized record
301                    // (`<Enum><Case>`, e.g. `ShapeRect`); the author side is a
302                    // struct variant with inline fields.
303                    let gen_rec = format!("{gen_path}::{ename}{case}");
304                    let fnames: Vec<String> = f
305                        .named
306                        .iter()
307                        .map(|fl| fl.ident.as_ref().unwrap().to_string())
308                        .collect();
309                    let g2a_inits = fnames
310                        .iter()
311                        .zip(f.named.iter())
312                        .map(|(n, fl)| {
313                            format!("{n}: {}", conv_expr(&format!("__r.{n}"), &fl.ty, known))
314                        })
315                        .collect::<Vec<_>>()
316                        .join(", ");
317                    g2a.push(format!("{g}::{case}(__r) => {a}::{case} {{ {g2a_inits} }}"));
318
319                    let binds = fnames.join(", ");
320                    let a2g_inits = fnames
321                        .iter()
322                        .zip(f.named.iter())
323                        .map(|(n, fl)| format!("{n}: {}", conv_expr(n, &fl.ty, known)))
324                        .collect::<Vec<_>>()
325                        .join(", ");
326                    a2g.push(format!(
327                        "{a}::{case} {{ {binds} }} => {g}::{case}({gen_rec} {{ {a2g_inits} }})"
328                    ));
329                }
330                // Multi-field tuple cases are rejected by `enum_to_wit`.
331                syn::Fields::Unnamed(_) => unreachable!("rejected by enum_to_wit"),
332            }
333        }
334        out.push_str(&format!(
335            "impl ::core::convert::From<{g}> for {a} {{ fn from(v: {g}) -> Self {{ match v {{ {} }} }} }}\n",
336            g2a.join(", ")
337        ));
338        out.push_str(&format!(
339            "impl ::core::convert::From<{a}> for {g} {{ fn from(v: {a}) -> Self {{ match v {{ {} }} }} }}\n",
340            a2g.join(", ")
341        ));
342    }
343    out
344}
345
346/// Conversion expression for a field/payload `access` of type `ty`. Identity
347/// (move) when the type holds no user type (generated and author types are then
348/// identical); otherwise `.into()` (user type), or a `map`/`into_iter().map()`
349/// recursing through `Option`/`Vec`. Symmetric — works generated→author and
350/// author→generated, since `From` is generated both ways. Public so the macro's
351/// adapter reuses the exact same boundary conversions.
352pub fn conv_expr(access: &str, ty: &Type, known: &BTreeSet<String>) -> String {
353    if !contains_user_type(ty, known) {
354        return access.to_string();
355    }
356    if let Type::Path(p) = ty {
357        if let Some(seg) = p.path.segments.last() {
358            let ident = seg.ident.to_string();
359            if let Some(inner) = single_generic(seg) {
360                match ident.as_str() {
361                    "Vec" => {
362                        return format!(
363                            "{access}.into_iter().map(|w| {}).collect()",
364                            conv_expr("w", inner, known)
365                        );
366                    }
367                    "Option" => {
368                        return format!("{access}.map(|w| {})", conv_expr("w", inner, known));
369                    }
370                    _ => {}
371                }
372            }
373            if known.contains(&ident) {
374                return format!("{access}.into()");
375            }
376        }
377    }
378    access.to_string()
379}
380
381/// Whether `ty` is, or contains (through `Vec`/`Option`/`Box`), a user type in
382/// `known`. Public so the macro can classify args/returns.
383pub fn contains_user_type(ty: &Type, known: &BTreeSet<String>) -> bool {
384    if let Type::Path(p) = ty {
385        if let Some(seg) = p.path.segments.last() {
386            let ident = seg.ident.to_string();
387            if known.contains(&ident) {
388                return true;
389            }
390            if matches!(ident.as_str(), "Vec" | "Option" | "Box") {
391                if let Some(inner) = single_generic(seg) {
392                    return contains_user_type(inner, known);
393                }
394            }
395        }
396    }
397    false
398}
399
400fn single_generic(seg: &syn::PathSegment) -> Option<&Type> {
401    if let syn::PathArguments::AngleBracketed(ab) = &seg.arguments {
402        for a in &ab.args {
403            if let syn::GenericArgument::Type(t) = a {
404                return Some(t);
405            }
406        }
407    }
408    None
409}
410
411/// Does `attrs` contain `#[<name>(...)]` / `#[<path>::<name>]` (last segment match)?
412fn has_attr(attrs: &[syn::Attribute], name: &str) -> bool {
413    attrs.iter().any(|a| {
414        a.path()
415            .segments
416            .last()
417            .map(|s| s.ident == name)
418            .unwrap_or(false)
419    })
420}
421
422/// Does `attrs` contain a `#[derive(... <name> ...)]`?
423fn has_derive(attrs: &[syn::Attribute], name: &str) -> bool {
424    for a in attrs {
425        if !a.path().is_ident("derive") {
426            continue;
427        }
428        let mut found = false;
429        let _ = a.parse_nested_meta(|m| {
430            if m.path
431                .segments
432                .last()
433                .map(|s| s.ident == name)
434                .unwrap_or(false)
435            {
436                found = true;
437            }
438            Ok(())
439        });
440        if found {
441            return true;
442        }
443    }
444    false
445}
446
447#[cfg(test)]
448mod tests {
449    use super::*;
450
451    const SRC: &str = r#"
452        #[derive(WitType)]
453        pub struct Point { pub x: i32, pub y: i32 }
454
455        #[derive(WitType)]
456        pub enum Shape { Circle(u32), Rect(Point), Dot }
457
458        #[plugin_interface(version = 1, crate = "fidius_guest")]
459        pub trait Geo: Send + Sync {
460            fn midpoint(&self, a: Point, b: Point) -> Point;
461            fn classify(&self, pts: Vec<Point>) -> Shape;
462            fn name(&self, s: Shape) -> String;
463        }
464    "#;
465
466    #[test]
467    fn generates_wit_with_records_variants_and_funcs() {
468        let g = generate(SRC).unwrap();
469        assert_eq!(g.interface_name, "Geo");
470        assert_eq!(g.iface_kebab, "geo");
471        assert!(g.user_types.contains(&"Point".to_string()));
472        assert!(g.user_types.contains(&"Shape".to_string()));
473
474        assert!(g.wit.contains("record point {"));
475        assert!(g.wit.contains("variant shape {"));
476        assert!(g.wit.contains("rect(point),"));
477        assert!(g
478            .wit
479            .contains("midpoint: func(a: point, b: point) -> point;"));
480        assert!(g.wit.contains("classify: func(pts: list<point>) -> shape;"));
481        assert!(g.wit.contains("name: func(s: shape) -> string;"));
482        assert!(g.wit.contains("fidius-interface-hash: func() -> u64;"));
483    }
484
485    #[test]
486    fn generates_conversions_both_ways() {
487        let g = generate(SRC).unwrap();
488        let c = &g.conversions;
489        // struct record conversions
490        assert!(c.contains("From<exports::fidius::geo::geo::Point> for crate::Point"));
491        assert!(c.contains("From<crate::Point> for exports::fidius::geo::geo::Point"));
492        // enum variant conversions with nested .into() for Rect(Point)
493        assert!(c.contains("From<exports::fidius::geo::geo::Shape> for crate::Shape"));
494        assert!(
495            c.contains("Rect(x) => crate :: Shape :: Rect")
496                || c.contains("Rect(x) => crate::Shape::Rect")
497        );
498        assert!(c.contains(".into()"));
499    }
500
501    #[test]
502    fn primitive_only_interface_has_no_conversions() {
503        let src = r#"
504            #[plugin_interface(version = 1)]
505            pub trait Greeter { fn greet(&self, name: String) -> String; }
506        "#;
507        let g = generate(src).unwrap();
508        assert!(g.user_types.is_empty());
509        assert!(g.conversions.is_empty());
510        assert!(g.wit.contains("greet: func(name: string) -> string;"));
511    }
512
513    #[test]
514    fn unsupported_type_errors() {
515        let src = r#"
516            #[plugin_interface(version = 1)]
517            pub trait T { fn f(&self, x: std::collections::HashMap<String,String>) -> u32; }
518        "#;
519        assert!(generate(src).is_err());
520    }
521}