Skip to main content

fidius_wit/
lib.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//! WIT generation for the Fidius WASM backend (FIDIUS-I-0023).
16//!
17//! Maps the Rust types in a `#[plugin_interface]` to WIT, per
18//! `docs/explanation/wasm-component-abi.md`. Primitives, `String`, `Vec<T>`,
19//! `Option<T>`, and `Result<T, PluginError>` map directly; user types that
20//! carry `#[derive(WitType)]` map to WIT `record`s (structs) and `variant`s
21//! (enums), referenced by their kebab-case name.
22//!
23//! This is a plain library (not a proc-macro), so `fidius-macro`, the `build.rs`
24//! helper, and the `fidius wit` CLI can all share one implementation.
25
26use std::collections::BTreeSet;
27
28use syn::{Fields, GenericArgument, ItemEnum, ItemStruct, PathArguments, Type};
29
30mod generate;
31pub use generate::{contains_user_type, conv_expr, generate, generate_from_path, Generated};
32
33/// Convert a Rust identifier (CamelCase or snake_case) to kebab-case, the WIT
34/// naming convention. `BytePipe` → `byte-pipe`, `echo_bytes` → `echo-bytes`.
35pub fn to_kebab_case(s: &str) -> String {
36    let mut out = String::new();
37    for (i, ch) in s.chars().enumerate() {
38        if ch == '_' {
39            out.push('-');
40        } else if ch.is_uppercase() {
41            if i != 0 {
42                out.push('-');
43            }
44            out.extend(ch.to_lowercase());
45        } else {
46            out.push(ch);
47        }
48    }
49    out
50}
51
52/// Extract the `T` from `Result<T, _>`, if `ty` is a `Result`.
53pub fn result_ok_type(ty: &Type) -> Option<&Type> {
54    if let Type::Path(p) = ty {
55        if let Some(seg) = p.path.segments.last() {
56            if seg.ident == "Result" {
57                return first_generic(seg);
58            }
59        }
60    }
61    None
62}
63
64/// One method projected to WIT (already-mapped strings).
65pub struct WitMethod {
66    /// kebab-case export name.
67    pub name: String,
68    /// `(param-name, wit-type)` pairs, in order.
69    pub params: Vec<(String, String)>,
70    /// WIT return type, or `None` for no return.
71    pub ret: Option<String>,
72    /// For a **server-streaming** method (`-> fidius::Stream<T>`): the WIT item
73    /// type `T` (FIDIUS-I-0026). When `Some`, the method renders as an exported
74    /// `resource <name>-stream { next: func() -> result<option<T>, plugin-error>; }`
75    /// and the func returns that resource (`-> <name>-stream`). `None` for a
76    /// normal func.
77    pub stream_item: Option<String>,
78}
79
80/// If `ty` is `fidius::Stream<T>` (final path segment `Stream`, exactly one type
81/// argument), return `T`. The server-streaming marker (FIDIUS-I-0026, D4). Public
82/// so the macro's WASM adapter shares the same detection.
83pub fn stream_item_type(ty: &Type) -> Option<&Type> {
84    if let Type::Path(p) = ty {
85        if let Some(seg) = p.path.segments.last() {
86            if seg.ident == "Stream" {
87                return first_generic(seg);
88            }
89        }
90    }
91    None
92}
93
94/// Map a Rust argument/return type to its WIT spelling, where `known` holds the
95/// Rust identifiers of `#[derive(WitType)]` user types (mapped to their
96/// kebab-case record/variant name). Returns `Err(msg)` for unsupported types.
97pub fn wit_type_with(ty: &Type, known: &BTreeSet<String>) -> Result<String, String> {
98    match ty {
99        // Peel references: `&str` → string, `&[u8]` → list<u8>, `&T` → wit(T).
100        Type::Reference(r) => {
101            if let Type::Path(p) = r.elem.as_ref() {
102                if path_is(p, "str") {
103                    return Ok("string".to_string());
104                }
105            }
106            if let Type::Slice(s) = r.elem.as_ref() {
107                let inner = wit_type_with(&s.elem, known)?;
108                return Ok(format!("list<{inner}>"));
109            }
110            wit_type_with(&r.elem, known)
111        }
112        Type::Path(p) => {
113            let seg = p
114                .path
115                .segments
116                .last()
117                .ok_or_else(|| "empty type path".to_string())?;
118            let ident = seg.ident.to_string();
119            match ident.as_str() {
120                "bool" => Ok("bool".into()),
121                "i8" => Ok("s8".into()),
122                "i16" => Ok("s16".into()),
123                "i32" => Ok("s32".into()),
124                "i64" => Ok("s64".into()),
125                "u8" => Ok("u8".into()),
126                "u16" => Ok("u16".into()),
127                "u32" => Ok("u32".into()),
128                "u64" => Ok("u64".into()),
129                "f32" => Ok("f32".into()),
130                "f64" => Ok("f64".into()),
131                "char" => Ok("char".into()),
132                "String" => Ok("string".into()),
133                "Vec" => {
134                    let inner = single_generic(seg, "Vec")?;
135                    Ok(format!("list<{}>", wit_type_with(inner, known)?))
136                }
137                "Option" => {
138                    let inner = single_generic(seg, "Option")?;
139                    Ok(format!("option<{}>", wit_type_with(inner, known)?))
140                }
141                // A user type with `#[derive(WitType)]` → its kebab record/variant name.
142                other if known.contains(other) => Ok(to_kebab_case(other)),
143                other => Err(format!(
144                    "type `{other}` is not supported in a WASM fidius interface \
145                     (supported: bool, i8..i64, u8..u64, f32/f64, char, String, Vec<T>, \
146                     Option<T>, Result<T, PluginError>, and #[derive(WitType)] structs/enums)"
147                )),
148            }
149        }
150        Type::Tuple(t) if t.elems.is_empty() => {
151            Err("unit `()` is not a valid argument type".to_string())
152        }
153        _ => Err("unsupported type in a WASM fidius interface".to_string()),
154    }
155}
156
157/// Primitive/std-only mapping (no user types) — the form `fidius-macro` uses for
158/// the descriptor/method tables.
159pub fn rust_type_to_wit(ty: &Type) -> Result<String, String> {
160    wit_type_with(ty, &BTreeSet::new())
161}
162
163/// Map a method's return type to an optional WIT return, with user types in
164/// `known`. `Result<T, PluginError>` → `result<T, plugin-error>` (or
165/// `result<_, plugin-error>` for `T = ()`); `()`/none → no return.
166pub fn return_to_wit_with(
167    ret: Option<&Type>,
168    known: &BTreeSet<String>,
169) -> Result<Option<String>, String> {
170    let Some(ty) = ret else { return Ok(None) };
171    if is_unit(ty) {
172        return Ok(None);
173    }
174    if let Type::Path(p) = ty {
175        if let Some(seg) = p.path.segments.last() {
176            if seg.ident == "Result" {
177                let ok = first_generic(seg).ok_or_else(|| "Result needs type args".to_string())?;
178                let ok_wit = if is_unit(ok) {
179                    "_".to_string()
180                } else {
181                    wit_type_with(ok, known)?
182                };
183                return Ok(Some(format!("result<{ok_wit}, plugin-error>")));
184            }
185        }
186    }
187    Ok(Some(wit_type_with(ty, known)?))
188}
189
190/// Primitive/std-only return mapping (no user types).
191pub fn return_to_wit(ret: Option<&Type>) -> Result<Option<String>, String> {
192    return_to_wit_with(ret, &BTreeSet::new())
193}
194
195/// Render a `record <name> { ... }` WIT block from a Rust struct (named fields
196/// only). Field types are mapped with `known` so they may reference other user
197/// types.
198pub fn struct_to_record(item: &ItemStruct, known: &BTreeSet<String>) -> Result<String, String> {
199    let name = to_kebab_case(&item.ident.to_string());
200    let Fields::Named(fields) = &item.fields else {
201        return Err(format!(
202            "WitType struct `{}` must have named fields (tuple/unit structs are not supported)",
203            item.ident
204        ));
205    };
206    let mut out = format!("    record {name} {{\n");
207    for f in &fields.named {
208        let fname = to_kebab_case(&f.ident.as_ref().unwrap().to_string());
209        let fty = wit_type_with(&f.ty, known)
210            .map_err(|e| format!("field `{}` of `{}`: {e}", fname, item.ident))?;
211        out.push_str(&format!("        {fname}: {fty},\n"));
212    }
213    out.push_str("    }\n");
214    Ok(out)
215}
216
217/// Render a Rust enum to WIT: a `variant <name> { ... }` plus any **synthetic
218/// records** for struct-shaped cases. Returns `(synthetic_records, variant)`.
219///
220/// Case shapes: unit → `case`; single tuple field → `case(type)`; named fields
221/// (`Case { .. }`) → a synthesized `record <enum>-<case>` and `case(<enum>-<case>)`.
222/// A multi-field *tuple* case is rejected: WIT cases take one payload, and a
223/// multi-field tuple serializes as a sequence (not a record) via serde, so it
224/// can't round-trip — use a struct variant `Case { .. }` instead.
225pub fn enum_to_wit(
226    item: &ItemEnum,
227    known: &BTreeSet<String>,
228) -> Result<(Vec<String>, String), String> {
229    let ename = item.ident.to_string();
230    let name = to_kebab_case(&ename);
231    let mut records = Vec::new();
232    let mut out = format!("    variant {name} {{\n");
233    for v in &item.variants {
234        let case = to_kebab_case(&v.ident.to_string());
235        match &v.fields {
236            Fields::Unit => out.push_str(&format!("        {case},\n")),
237            Fields::Unnamed(u) if u.unnamed.len() == 1 => {
238                let payload = wit_type_with(&u.unnamed[0].ty, known)
239                    .map_err(|e| format!("variant `{ename}::{}`: {e}", v.ident))?;
240                out.push_str(&format!("        {case}({payload}),\n"));
241            }
242            Fields::Named(f) => {
243                // Synthesize `record <enum>-<case> { .. }` for the case payload.
244                let rec_name = format!("{name}-{case}");
245                let mut rec = format!("    record {rec_name} {{\n");
246                for fl in &f.named {
247                    let fname = to_kebab_case(&fl.ident.as_ref().unwrap().to_string());
248                    let fty = wit_type_with(&fl.ty, known)
249                        .map_err(|e| format!("field `{fname}` of `{ename}::{}`: {e}", v.ident))?;
250                    rec.push_str(&format!("        {fname}: {fty},\n"));
251                }
252                rec.push_str("    }\n");
253                records.push(rec);
254                out.push_str(&format!("        {case}({rec_name}),\n"));
255            }
256            Fields::Unnamed(_) => {
257                return Err(format!(
258                    "WitType enum `{ename}` variant `{}` has multiple tuple fields; \
259                     a WIT variant case takes one payload — use a struct variant \
260                     `{} {{ .. }}` (or a single field)",
261                    v.ident, v.ident
262                ));
263            }
264        }
265    }
266    out.push_str("    }\n");
267    Ok((records, out))
268}
269
270/// Render a complete `.wit` document: package + interface (the `plugin-error`
271/// record, any user `type_defs` (records/variants), the funcs, and the
272/// `fidius-interface-hash` carrier) + the `<iface>-plugin` world. `type_defs`
273/// are pre-rendered (see [`struct_to_record`] / [`enum_to_variant`]).
274pub fn render_wit_full(iface_kebab: &str, type_defs: &[String], methods: &[WitMethod]) -> String {
275    let mut s = String::new();
276    s.push_str(&format!("package fidius:{iface_kebab}@0.1.0;\n\n"));
277    s.push_str(&format!("interface {iface_kebab} {{\n"));
278    s.push_str("    record plugin-error {\n");
279    s.push_str("        code: string,\n");
280    s.push_str("        message: string,\n");
281    s.push_str("        details: option<string>,\n");
282    s.push_str("    }\n");
283    for def in type_defs {
284        s.push_str(def);
285    }
286    // Resource declarations for streaming methods, before the funcs that return
287    // them (FIDIUS-I-0026): `resource <m>-stream { next: ... }`.
288    for m in methods {
289        if let Some(item) = &m.stream_item {
290            s.push_str(&format!("    resource {}-stream {{\n", m.name));
291            s.push_str(&format!(
292                "        next: func() -> result<option<{item}>, plugin-error>;\n"
293            ));
294            s.push_str("    }\n");
295        }
296    }
297    for m in methods {
298        let params = m
299            .params
300            .iter()
301            .map(|(n, t)| format!("{n}: {t}"))
302            .collect::<Vec<_>>()
303            .join(", ");
304        if m.stream_item.is_some() {
305            // Streaming: the func returns the owned stream resource.
306            s.push_str(&format!(
307                "    {}: func({params}) -> {}-stream;\n",
308                m.name, m.name
309            ));
310        } else {
311            match &m.ret {
312                Some(r) => s.push_str(&format!("    {}: func({params}) -> {r};\n", m.name)),
313                None => s.push_str(&format!("    {}: func({params});\n", m.name)),
314            }
315        }
316    }
317    s.push_str("    fidius-interface-hash: func() -> u64;\n");
318    s.push_str("}\n\n");
319    s.push_str(&format!(
320        "world {iface_kebab}-plugin {{\n    export {iface_kebab};\n}}\n"
321    ));
322    s
323}
324
325/// Convenience: render a WIT document with no user type defs (the primitives-only
326/// form `fidius-macro` emits inline today).
327pub fn render_wit(iface_kebab: &str, methods: &[WitMethod]) -> String {
328    render_wit_full(iface_kebab, &[], methods)
329}
330
331// ── helpers ─────────────────────────────────────────────────────────────────
332
333fn is_unit(ty: &Type) -> bool {
334    matches!(ty, Type::Tuple(t) if t.elems.is_empty())
335}
336
337fn path_is(p: &syn::TypePath, name: &str) -> bool {
338    p.path
339        .segments
340        .last()
341        .map(|s| s.ident == name)
342        .unwrap_or(false)
343}
344
345fn single_generic<'a>(seg: &'a syn::PathSegment, what: &str) -> Result<&'a Type, String> {
346    first_generic(seg).ok_or_else(|| format!("`{what}` needs one type argument"))
347}
348
349fn first_generic(seg: &syn::PathSegment) -> Option<&Type> {
350    if let PathArguments::AngleBracketed(ab) = &seg.arguments {
351        for a in &ab.args {
352            if let GenericArgument::Type(t) = a {
353                return Some(t);
354            }
355        }
356    }
357    None
358}
359
360#[cfg(test)]
361mod tests {
362    use super::*;
363
364    fn known(names: &[&str]) -> BTreeSet<String> {
365        names.iter().map(|s| s.to_string()).collect()
366    }
367    fn wit(s: &str) -> String {
368        rust_type_to_wit(&syn::parse_str::<Type>(s).unwrap()).unwrap()
369    }
370
371    #[test]
372    fn primitives_strings_containers() {
373        assert_eq!(wit("i64"), "s64");
374        assert_eq!(wit("u32"), "u32");
375        assert_eq!(wit("String"), "string");
376        assert_eq!(wit("& str"), "string");
377        assert_eq!(wit("Vec<u8>"), "list<u8>");
378        assert_eq!(wit("Option<i32>"), "option<s32>");
379        assert_eq!(wit("&[u8]"), "list<u8>");
380    }
381
382    #[test]
383    fn returns() {
384        let ret = |s: &str| return_to_wit(Some(&syn::parse_str::<Type>(s).unwrap())).unwrap();
385        assert_eq!(ret("()"), None);
386        assert_eq!(
387            ret("Result<i64, PluginError>"),
388            Some("result<s64, plugin-error>".into())
389        );
390        assert_eq!(
391            ret("Result<(), PluginError>"),
392            Some("result<_, plugin-error>".into())
393        );
394    }
395
396    #[test]
397    fn user_types_need_the_known_set() {
398        let ty: Type = syn::parse_str("Point").unwrap();
399        assert!(rust_type_to_wit(&ty).is_err()); // unknown without the set
400        let k = known(&["Point"]);
401        assert_eq!(wit_type_with(&ty, &k).unwrap(), "point");
402        // nested in containers
403        let v: Type = syn::parse_str("Vec<Point>").unwrap();
404        assert_eq!(wit_type_with(&v, &k).unwrap(), "list<point>");
405        let o: Type = syn::parse_str("Option<BytePipe>").unwrap();
406        assert_eq!(
407            wit_type_with(&o, &known(&["BytePipe"])).unwrap(),
408            "option<byte-pipe>"
409        );
410    }
411
412    #[test]
413    fn struct_renders_to_record() {
414        let item: ItemStruct = syn::parse_str("struct Point { x: i32, y_pos: u64 }").unwrap();
415        let rec = struct_to_record(&item, &BTreeSet::new()).unwrap();
416        assert!(rec.contains("record point {"));
417        assert!(rec.contains("x: s32,"));
418        assert!(rec.contains("y-pos: u64,"));
419    }
420
421    #[test]
422    fn struct_with_nested_user_type() {
423        let item: ItemStruct = syn::parse_str("struct Line { from: Point, to: Point }").unwrap();
424        let rec = struct_to_record(&item, &known(&["Point"])).unwrap();
425        assert!(rec.contains("from: point,"));
426        assert!(rec.contains("to: point,"));
427    }
428
429    #[test]
430    fn enum_renders_to_variant() {
431        let item: ItemEnum =
432            syn::parse_str("enum Shape { Circle(u32), Rect(Point), Dot }").unwrap();
433        let (records, var) = enum_to_wit(&item, &known(&["Point"])).unwrap();
434        assert!(records.is_empty());
435        assert!(var.contains("variant shape {"));
436        assert!(var.contains("circle(u32),"));
437        assert!(var.contains("rect(point),"));
438        assert!(var.contains("dot,"));
439    }
440
441    #[test]
442    fn struct_variant_synthesizes_a_record() {
443        let item: ItemEnum = syn::parse_str("enum Shape { Rect { w: u32, h: u32 }, Dot }").unwrap();
444        let (records, var) = enum_to_wit(&item, &BTreeSet::new()).unwrap();
445        assert_eq!(records.len(), 1);
446        assert!(records[0].contains("record shape-rect {"));
447        assert!(records[0].contains("w: u32,"));
448        assert!(records[0].contains("h: u32,"));
449        assert!(var.contains("rect(shape-rect),"));
450        assert!(var.contains("dot,"));
451    }
452
453    #[test]
454    fn multifield_tuple_variant_is_rejected() {
455        let item: ItemEnum = syn::parse_str("enum E { Pair(u32, u32) }").unwrap();
456        assert!(enum_to_wit(&item, &BTreeSet::new()).is_err());
457    }
458
459    #[test]
460    fn full_document_places_type_defs_before_funcs() {
461        let recs = vec![struct_to_record(
462            &syn::parse_str("struct Point { x: i32, y: i32 }").unwrap(),
463            &BTreeSet::new(),
464        )
465        .unwrap()];
466        let methods = vec![WitMethod {
467            name: "midpoint".into(),
468            params: vec![("a".into(), "point".into()), ("b".into(), "point".into())],
469            ret: Some("point".into()),
470            stream_item: None,
471        }];
472        let doc = render_wit_full("geo", &recs, &methods);
473        assert!(doc.contains("package fidius:geo@0.1.0;"));
474        let rec_at = doc.find("record point {").unwrap();
475        let fn_at = doc.find("midpoint: func").unwrap();
476        assert!(
477            rec_at < fn_at,
478            "records must precede funcs in the interface"
479        );
480        assert!(doc.contains("midpoint: func(a: point, b: point) -> point;"));
481        assert!(doc.contains("fidius-interface-hash: func() -> u64;"));
482        assert!(doc.contains("world geo-plugin {"));
483    }
484
485    #[test]
486    fn streaming_method_renders_a_resource() {
487        let methods = vec![WitMethod {
488            name: "tick".into(),
489            params: vec![("count".into(), "u32".into())],
490            ret: None,
491            stream_item: Some("u64".into()),
492        }];
493        let doc = render_wit("ticker", &methods);
494        // Resource declared, with the poll method...
495        assert!(doc.contains("resource tick-stream {"));
496        assert!(doc.contains("next: func() -> result<option<u64>, plugin-error>;"));
497        // ...and the func returns the owned resource.
498        assert!(doc.contains("tick: func(count: u32) -> tick-stream;"));
499        // Resource precedes the func that returns it.
500        assert!(doc.find("resource tick-stream").unwrap() < doc.find("tick: func").unwrap());
501    }
502
503    #[test]
504    fn stream_item_type_detects_marker() {
505        let ty: Type = syn::parse_str("fidius::Stream<u64>").unwrap();
506        let item = stream_item_type(&ty).unwrap();
507        assert_eq!(rust_type_to_wit(item).unwrap(), "u64");
508        let bare: Type = syn::parse_str("Stream<String>").unwrap();
509        assert!(stream_item_type(&bare).is_some());
510        let not: Type = syn::parse_str("Vec<u64>").unwrap();
511        assert!(stream_item_type(&not).is_none());
512    }
513}