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        let ret = return_to_wit_with(ret_ty, &known)
175            .map_err(|e| format!("method `{}` return: {e}", f.sig.ident))?;
176        methods.push(WitMethod {
177            name: to_kebab_case(&f.sig.ident.to_string()),
178            params,
179            ret,
180        });
181    }
182
183    let wit = crate::render_wit_full(&iface_kebab, &type_defs, &methods);
184    let conversions = render_conversions(&iface_kebab, &acc.structs, &acc.enums, &known);
185
186    Ok(Generated {
187        interface_name,
188        iface_kebab,
189        user_types,
190        wit,
191        conversions,
192    })
193}
194
195/// `crate::<mod::path>::<Name>` — the author-side path for a type at `mod_path`.
196fn author_path(mod_path: &[String], name: &str) -> String {
197    if mod_path.is_empty() {
198        format!("crate::{name}")
199    } else {
200        format!("crate::{}::{name}", mod_path.join("::"))
201    }
202}
203
204/// Render `From` impls (both directions) between each user type and its
205/// wit-bindgen-generated mirror. Emitted into the adapter module, where the
206/// generated types live (flat) at `exports::fidius::<iface>::<iface>::<Type>`
207/// and the author types at `crate::<mod::path>::<Type>`.
208fn render_conversions(
209    iface_kebab: &str,
210    structs: &[(Vec<String>, syn::ItemStruct)],
211    enums: &[(Vec<String>, syn::ItemEnum)],
212    known: &BTreeSet<String>,
213) -> String {
214    if structs.is_empty() && enums.is_empty() {
215        return String::new();
216    }
217    let snake = iface_kebab.replace('-', "_");
218    let gen_path = format!("exports::fidius::{snake}::{snake}");
219    let mut out = String::new();
220    out.push_str("// Generated by fidius-wit: author <-> wit-bindgen conversions.\n");
221
222    for (path, s) in structs {
223        let name = s.ident.to_string();
224        let g = format!("{gen_path}::{name}");
225        let a = author_path(path, &name);
226        let fields: Vec<String> = match &s.fields {
227            syn::Fields::Named(f) => f
228                .named
229                .iter()
230                .map(|fl| fl.ident.as_ref().unwrap().to_string())
231                .collect(),
232            _ => Vec::new(),
233        };
234        let field_types: Vec<&Type> = match &s.fields {
235            syn::Fields::Named(f) => f.named.iter().map(|fl| &fl.ty).collect(),
236            _ => Vec::new(),
237        };
238        // generated -> author
239        let to_author: Vec<String> = fields
240            .iter()
241            .zip(&field_types)
242            .map(|(f, ty)| format!("{f}: {}", conv_expr(&format!("v.{f}"), ty, known)))
243            .collect();
244        out.push_str(&format!(
245            "impl ::core::convert::From<{g}> for {a} {{ fn from(v: {g}) -> Self {{ {a} {{ {} }} }} }}\n",
246            to_author.join(", ")
247        ));
248        // author -> generated
249        let to_gen: Vec<String> = fields
250            .iter()
251            .zip(&field_types)
252            .map(|(f, ty)| format!("{f}: {}", conv_expr(&format!("v.{f}"), ty, known)))
253            .collect();
254        out.push_str(&format!(
255            "impl ::core::convert::From<{a}> for {g} {{ fn from(v: {a}) -> Self {{ {g} {{ {} }} }} }}\n",
256            to_gen.join(", ")
257        ));
258    }
259
260    for (path, e) in enums {
261        let ename = e.ident.to_string();
262        let g = format!("{gen_path}::{ename}");
263        let a = author_path(path, &ename);
264
265        let mut g2a = Vec::new(); // generated -> author
266        let mut a2g = Vec::new(); // author -> generated
267        for v in &e.variants {
268            let case = v.ident.to_string();
269            match &v.fields {
270                syn::Fields::Unit => {
271                    g2a.push(format!("{g}::{case} => {a}::{case}"));
272                    a2g.push(format!("{a}::{case} => {g}::{case}"));
273                }
274                syn::Fields::Unnamed(u) if u.unnamed.len() == 1 => {
275                    let ty = &u.unnamed[0].ty;
276                    g2a.push(format!(
277                        "{g}::{case}(x) => {a}::{case}({})",
278                        conv_expr("x", ty, known)
279                    ));
280                    a2g.push(format!(
281                        "{a}::{case}(x) => {g}::{case}({})",
282                        conv_expr("x", ty, known)
283                    ));
284                }
285                syn::Fields::Named(f) => {
286                    // The gen side wraps the case payload in a synthesized record
287                    // (`<Enum><Case>`, e.g. `ShapeRect`); the author side is a
288                    // struct variant with inline fields.
289                    let gen_rec = format!("{gen_path}::{ename}{case}");
290                    let fnames: Vec<String> = f
291                        .named
292                        .iter()
293                        .map(|fl| fl.ident.as_ref().unwrap().to_string())
294                        .collect();
295                    let g2a_inits = fnames
296                        .iter()
297                        .zip(f.named.iter())
298                        .map(|(n, fl)| {
299                            format!("{n}: {}", conv_expr(&format!("__r.{n}"), &fl.ty, known))
300                        })
301                        .collect::<Vec<_>>()
302                        .join(", ");
303                    g2a.push(format!("{g}::{case}(__r) => {a}::{case} {{ {g2a_inits} }}"));
304
305                    let binds = fnames.join(", ");
306                    let a2g_inits = fnames
307                        .iter()
308                        .zip(f.named.iter())
309                        .map(|(n, fl)| format!("{n}: {}", conv_expr(n, &fl.ty, known)))
310                        .collect::<Vec<_>>()
311                        .join(", ");
312                    a2g.push(format!(
313                        "{a}::{case} {{ {binds} }} => {g}::{case}({gen_rec} {{ {a2g_inits} }})"
314                    ));
315                }
316                // Multi-field tuple cases are rejected by `enum_to_wit`.
317                syn::Fields::Unnamed(_) => unreachable!("rejected by enum_to_wit"),
318            }
319        }
320        out.push_str(&format!(
321            "impl ::core::convert::From<{g}> for {a} {{ fn from(v: {g}) -> Self {{ match v {{ {} }} }} }}\n",
322            g2a.join(", ")
323        ));
324        out.push_str(&format!(
325            "impl ::core::convert::From<{a}> for {g} {{ fn from(v: {a}) -> Self {{ match v {{ {} }} }} }}\n",
326            a2g.join(", ")
327        ));
328    }
329    out
330}
331
332/// Conversion expression for a field/payload `access` of type `ty`. Identity
333/// (move) when the type holds no user type (generated and author types are then
334/// identical); otherwise `.into()` (user type), or a `map`/`into_iter().map()`
335/// recursing through `Option`/`Vec`. Symmetric — works generated→author and
336/// author→generated, since `From` is generated both ways. Public so the macro's
337/// adapter reuses the exact same boundary conversions.
338pub fn conv_expr(access: &str, ty: &Type, known: &BTreeSet<String>) -> String {
339    if !contains_user_type(ty, known) {
340        return access.to_string();
341    }
342    if let Type::Path(p) = ty {
343        if let Some(seg) = p.path.segments.last() {
344            let ident = seg.ident.to_string();
345            if let Some(inner) = single_generic(seg) {
346                match ident.as_str() {
347                    "Vec" => {
348                        return format!(
349                            "{access}.into_iter().map(|w| {}).collect()",
350                            conv_expr("w", inner, known)
351                        );
352                    }
353                    "Option" => {
354                        return format!("{access}.map(|w| {})", conv_expr("w", inner, known));
355                    }
356                    _ => {}
357                }
358            }
359            if known.contains(&ident) {
360                return format!("{access}.into()");
361            }
362        }
363    }
364    access.to_string()
365}
366
367/// Whether `ty` is, or contains (through `Vec`/`Option`/`Box`), a user type in
368/// `known`. Public so the macro can classify args/returns.
369pub fn contains_user_type(ty: &Type, known: &BTreeSet<String>) -> bool {
370    if let Type::Path(p) = ty {
371        if let Some(seg) = p.path.segments.last() {
372            let ident = seg.ident.to_string();
373            if known.contains(&ident) {
374                return true;
375            }
376            if matches!(ident.as_str(), "Vec" | "Option" | "Box") {
377                if let Some(inner) = single_generic(seg) {
378                    return contains_user_type(inner, known);
379                }
380            }
381        }
382    }
383    false
384}
385
386fn single_generic(seg: &syn::PathSegment) -> Option<&Type> {
387    if let syn::PathArguments::AngleBracketed(ab) = &seg.arguments {
388        for a in &ab.args {
389            if let syn::GenericArgument::Type(t) = a {
390                return Some(t);
391            }
392        }
393    }
394    None
395}
396
397/// Does `attrs` contain `#[<name>(...)]` / `#[<path>::<name>]` (last segment match)?
398fn has_attr(attrs: &[syn::Attribute], name: &str) -> bool {
399    attrs.iter().any(|a| {
400        a.path()
401            .segments
402            .last()
403            .map(|s| s.ident == name)
404            .unwrap_or(false)
405    })
406}
407
408/// Does `attrs` contain a `#[derive(... <name> ...)]`?
409fn has_derive(attrs: &[syn::Attribute], name: &str) -> bool {
410    for a in attrs {
411        if !a.path().is_ident("derive") {
412            continue;
413        }
414        let mut found = false;
415        let _ = a.parse_nested_meta(|m| {
416            if m.path
417                .segments
418                .last()
419                .map(|s| s.ident == name)
420                .unwrap_or(false)
421            {
422                found = true;
423            }
424            Ok(())
425        });
426        if found {
427            return true;
428        }
429    }
430    false
431}
432
433#[cfg(test)]
434mod tests {
435    use super::*;
436
437    const SRC: &str = r#"
438        #[derive(WitType)]
439        pub struct Point { pub x: i32, pub y: i32 }
440
441        #[derive(WitType)]
442        pub enum Shape { Circle(u32), Rect(Point), Dot }
443
444        #[plugin_interface(version = 1, crate = "fidius_guest")]
445        pub trait Geo: Send + Sync {
446            fn midpoint(&self, a: Point, b: Point) -> Point;
447            fn classify(&self, pts: Vec<Point>) -> Shape;
448            fn name(&self, s: Shape) -> String;
449        }
450    "#;
451
452    #[test]
453    fn generates_wit_with_records_variants_and_funcs() {
454        let g = generate(SRC).unwrap();
455        assert_eq!(g.interface_name, "Geo");
456        assert_eq!(g.iface_kebab, "geo");
457        assert!(g.user_types.contains(&"Point".to_string()));
458        assert!(g.user_types.contains(&"Shape".to_string()));
459
460        assert!(g.wit.contains("record point {"));
461        assert!(g.wit.contains("variant shape {"));
462        assert!(g.wit.contains("rect(point),"));
463        assert!(g
464            .wit
465            .contains("midpoint: func(a: point, b: point) -> point;"));
466        assert!(g.wit.contains("classify: func(pts: list<point>) -> shape;"));
467        assert!(g.wit.contains("name: func(s: shape) -> string;"));
468        assert!(g.wit.contains("fidius-interface-hash: func() -> u64;"));
469    }
470
471    #[test]
472    fn generates_conversions_both_ways() {
473        let g = generate(SRC).unwrap();
474        let c = &g.conversions;
475        // struct record conversions
476        assert!(c.contains("From<exports::fidius::geo::geo::Point> for crate::Point"));
477        assert!(c.contains("From<crate::Point> for exports::fidius::geo::geo::Point"));
478        // enum variant conversions with nested .into() for Rect(Point)
479        assert!(c.contains("From<exports::fidius::geo::geo::Shape> for crate::Shape"));
480        assert!(
481            c.contains("Rect(x) => crate :: Shape :: Rect")
482                || c.contains("Rect(x) => crate::Shape::Rect")
483        );
484        assert!(c.contains(".into()"));
485    }
486
487    #[test]
488    fn primitive_only_interface_has_no_conversions() {
489        let src = r#"
490            #[plugin_interface(version = 1)]
491            pub trait Greeter { fn greet(&self, name: String) -> String; }
492        "#;
493        let g = generate(src).unwrap();
494        assert!(g.user_types.is_empty());
495        assert!(g.conversions.is_empty());
496        assert!(g.wit.contains("greet: func(name: string) -> string;"));
497    }
498
499    #[test]
500    fn unsupported_type_errors() {
501        let src = r#"
502            #[plugin_interface(version = 1)]
503            pub trait T { fn f(&self, x: std::collections::HashMap<String,String>) -> u32; }
504        "#;
505        assert!(generate(src).is_err());
506    }
507}