rpc/natives/
catch_each.rs1use scripting::checked_ref::CheckedAnyRef;
30use scripting::runtime::{
31 EngineError, EvalValue, alloc_pair_chain, alloc_string_ref, alloc_value,
32 classify_runtime_error, err_code_and_message,
33};
34use wasmtime::{AnyRef, AsContextMut, Caller, Func, Linker, Rooted, StructRef, Val};
35
36use crate::host_failure::is_host_failure;
37use crate::natives::native::register_native;
38use crate::session::SessionData;
39
40pub fn register(linker: &mut Linker<SessionData>) -> wasmtime::Result<()> {
41 register_native(
42 linker,
43 "__nomi_catch_each",
44 |caller,
45 (cb, env, items): (
46 Option<Func>,
47 Option<Rooted<AnyRef>>,
48 Option<Rooted<StructRef>>,
49 )| {
50 Box::pin(async move {
51 let cb =
52 cb.ok_or_else(|| wasmtime::Error::msg("catch-each: closure funcref is null"))?;
53 let item_anyrefs = collect_items(caller, items)?;
54 let mut result_cells: Vec<Option<Rooted<AnyRef>>> =
55 Vec::with_capacity(item_anyrefs.len());
56 for item in item_anyrefs {
57 let cell = invoke_one(caller, &cb, env, item).await?;
58 result_cells.push(Some(cell));
59 }
60 alloc_pair_chain(caller, result_cells).await
61 })
62 },
63 )?;
64 Ok(())
65}
66
67fn collect_items(
74 caller: &mut Caller<'_, SessionData>,
75 head: Option<Rooted<StructRef>>,
76) -> wasmtime::Result<Vec<Option<Rooted<AnyRef>>>> {
77 let mut out: Vec<Option<Rooted<AnyRef>>> = Vec::new();
78 let mut cursor = head;
79 while let Some(node) = cursor {
80 let car_val = node.field(caller.as_context_mut(), 0)?;
81 let car = match car_val {
82 Val::AnyRef(any) => any,
83 _ => {
84 return Err(wasmtime::Error::msg(
85 "catch-each: items list car field is not anyref",
86 ));
87 }
88 };
89 out.push(car);
90 let cdr_val = node.field(caller.as_context_mut(), 1)?;
91 cursor = match cdr_val {
92 Val::AnyRef(Some(any)) => Some(any.checked_struct(caller.as_context_mut())?),
93 _ => None,
94 };
95 }
96 Ok(out)
97}
98
99async fn invoke_one(
105 caller: &mut Caller<'_, SessionData>,
106 cb: &Func,
107 env: Option<Rooted<AnyRef>>,
108 item: Option<Rooted<AnyRef>>,
109) -> wasmtime::Result<Rooted<AnyRef>> {
110 let mut results = [Val::AnyRef(None)];
111 let outcome = cb
112 .call_async(
113 caller.as_context_mut(),
114 &[Val::AnyRef(env), Val::AnyRef(item)],
115 &mut results,
116 )
117 .await;
118 match outcome {
119 Ok(()) => {
120 let value_any = match results[0] {
121 Val::AnyRef(any) => any,
122 _ => {
123 return Err(wasmtime::Error::msg(
124 "catch-each: closure returned non-anyref Val variant",
125 ));
126 }
127 };
128 build_ok_cell(caller, value_any).await
129 }
130 Err(err) if is_host_failure(&err) => Err(err),
131 Err(err) => match classify_runtime_error(&err) {
132 EngineError::OutOfFuel | EngineError::EpochInterrupt | EngineError::FiberLimit => {
133 Err(err)
134 }
135 classified => build_err_cell(caller, &classified).await,
136 },
137 }
138}
139
140async fn build_ok_cell(
146 caller: &mut Caller<'_, SessionData>,
147 value: Option<Rooted<AnyRef>>,
148) -> wasmtime::Result<Rooted<AnyRef>> {
149 let tag = symbol_anyref(caller, "OK").await?;
150 pair_chain_to_anyref(caller, vec![Some(tag), value]).await
151}
152
153async fn build_err_cell(
157 caller: &mut Caller<'_, SessionData>,
158 classified: &EngineError,
159) -> wasmtime::Result<Rooted<AnyRef>> {
160 let tag = symbol_anyref(caller, "ERR").await?;
161 let (code, message) = err_code_and_message(classified);
162 let code_any = symbol_anyref(caller, &code.to_uppercase()).await?;
163 let message_any = string_anyref(caller, message.as_bytes())?;
164 pair_chain_to_anyref(caller, vec![Some(tag), Some(code_any), Some(message_any)]).await
165}
166
167async fn pair_chain_to_anyref(
168 caller: &mut Caller<'_, SessionData>,
169 elems: Vec<Option<Rooted<AnyRef>>>,
170) -> wasmtime::Result<Rooted<AnyRef>> {
171 let head = alloc_pair_chain(caller, elems)
172 .await?
173 .ok_or_else(|| wasmtime::Error::msg("catch-each: built an empty result cell"))?;
174 Ok(head.to_anyref())
175}
176
177async fn symbol_anyref(
178 caller: &mut Caller<'_, SessionData>,
179 name: &str,
180) -> wasmtime::Result<Rooted<AnyRef>> {
181 alloc_value(caller, &EvalValue::Symbol(name.to_string()))
182 .await?
183 .ok_or_else(|| wasmtime::Error::msg("catch-each: symbol allocation returned nil"))
184}
185
186fn string_anyref(
187 caller: &mut Caller<'_, SessionData>,
188 bytes: &[u8],
189) -> wasmtime::Result<Rooted<AnyRef>> {
190 Ok(alloc_string_ref(caller, bytes)?.to_anyref())
191}