tinywasm_cli/
value_parse.rs1use eyre::{Result, bail};
2use tinywasm::types::{FuncType, WasmType, WasmValue};
3
4use crate::output::format_wasm_type;
5
6pub fn parse_invocation_args(ty: &FuncType, args: &[String]) -> Result<Vec<WasmValue>> {
7 if args.len() != ty.params().len() {
8 bail!("wrong number of arguments: expected {}, got {}", ty.params().len(), args.len())
9 }
10
11 ty.params().iter().enumerate().map(|(idx, param_ty)| parse_arg(idx, *param_ty, &args[idx])).collect()
12}
13
14fn parse_arg(index: usize, ty: WasmType, value: &str) -> Result<WasmValue> {
15 let parsed = match ty {
16 WasmType::I32 => value.parse::<i32>().map(WasmValue::from).map_err(|e| format_error(index, ty, value, e))?,
17 WasmType::I64 => value.parse::<i64>().map(WasmValue::from).map_err(|e| format_error(index, ty, value, e))?,
18 WasmType::F32 => value.parse::<f32>().map(WasmValue::from).map_err(|e| format_error(index, ty, value, e))?,
19 WasmType::F64 => value.parse::<f64>().map(WasmValue::from).map_err(|e| format_error(index, ty, value, e))?,
20 WasmType::V128 => value.parse::<i128>().map(WasmValue::from).map_err(|e| format_error(index, ty, value, e))?,
21 WasmType::RefFunc | WasmType::RefExtern => {
22 bail!(
23 "unsupported CLI argument type at position {}: {}; use the embedding API for reference values",
24 index + 1,
25 format_wasm_type(ty)
26 )
27 }
28 };
29
30 Ok(parsed)
31}
32
33fn format_error(index: usize, ty: WasmType, value: &str, error: impl core::fmt::Display) -> eyre::Report {
34 eyre::eyre!("failed to parse argument {} as {} from `{value}`: {error}", index + 1, format_wasm_type(ty))
35}
36
37#[cfg(test)]
38mod tests {
39 use super::*;
40
41 #[test]
42 fn parses_numeric_args() {
43 let ty = FuncType::new(&[WasmType::I32, WasmType::F64], &[WasmType::I32]);
44 let args = vec!["1".to_string(), "2.5".to_string()];
45 let parsed = parse_invocation_args(&ty, &args).unwrap();
46 assert_eq!(parsed, vec![WasmValue::I32(1), WasmValue::F64(2.5)]);
47 }
48
49 #[test]
50 fn rejects_wrong_arity() {
51 let ty = FuncType::new(&[WasmType::I32], &[]);
52 let err = parse_invocation_args(&ty, &[]).unwrap_err();
53 assert!(err.to_string().contains("wrong number of arguments"));
54 }
55}