1use 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
33pub 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
52pub 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
64pub struct WitMethod {
66 pub name: String,
68 pub params: Vec<(String, String)>,
70 pub ret: Option<String>,
72 pub stream_item: Option<String>,
78}
79
80pub 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
94pub fn wit_type_with(ty: &Type, known: &BTreeSet<String>) -> Result<String, String> {
98 match ty {
99 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 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
157pub fn rust_type_to_wit(ty: &Type) -> Result<String, String> {
160 wit_type_with(ty, &BTreeSet::new())
161}
162
163pub 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
190pub fn return_to_wit(ret: Option<&Type>) -> Result<Option<String>, String> {
192 return_to_wit_with(ret, &BTreeSet::new())
193}
194
195pub 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
217pub 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 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
270pub 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 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 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
325pub fn render_wit(iface_kebab: &str, methods: &[WitMethod]) -> String {
328 render_wit_full(iface_kebab, &[], methods)
329}
330
331fn 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()); let k = known(&["Point"]);
401 assert_eq!(wit_type_with(&ty, &k).unwrap(), "point");
402 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 assert!(doc.contains("resource tick-stream {"));
496 assert!(doc.contains("next: func() -> result<option<u64>, plugin-error>;"));
497 assert!(doc.contains("tick: func(count: u32) -> tick-stream;"));
499 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(¬).is_none());
512 }
513}