1use uuid::Uuid;
4
5use super::decode::checked_pair;
6
7use crate::checked_ref::CheckedAnyRef;
8
9use wasmtime::{
10 AnyRef, AsContextMut, Caller, FieldType, Mutability, Rooted, StorageType, StructRef,
11 StructRefPre, StructType, Val, ValType,
12};
13
14pub async fn alloc_commodity_ref<T>(
22 caller: &mut Caller<'_, T>,
23 numer: i64,
24 denom: i64,
25 commodity_id: Uuid,
26) -> wasmtime::Result<Rooted<StructRef>>
27where
28 T: Send,
29{
30 let commodity_new = caller
31 .get_export("commodity_new")
32 .and_then(|e| e.into_func())
33 .ok_or_else(|| {
34 wasmtime::Error::msg(
35 "module missing 'commodity_new' export — host commodity allocation \
36 requires the nomiscript compiler skeleton's exported commodity_new",
37 )
38 })?;
39 let (hi, lo) = commodity_id.as_u64_pair();
40 let mut results = [Val::AnyRef(None)];
41 commodity_new
42 .call_async(
43 caller.as_context_mut(),
44 &[
45 Val::I64(numer),
46 Val::I64(denom),
47 Val::I64(hi as i64),
48 Val::I64(lo as i64),
49 ],
50 &mut results,
51 )
52 .await?;
53 match &results[0] {
54 Val::AnyRef(Some(any)) => any.checked_struct(caller.as_context_mut()),
55 Val::AnyRef(None) => Err(wasmtime::Error::msg("commodity_new returned null")),
56 _ => Err(wasmtime::Error::msg(
57 "commodity_new returned non-anyref Val variant",
58 )),
59 }
60}
61
62pub fn alloc_string_ref<T>(
69 caller: &mut Caller<'_, T>,
70 bytes: &[u8],
71) -> wasmtime::Result<Rooted<wasmtime::ArrayRef>> {
72 let engine = caller.engine().clone();
73 let ty = wasmtime::ArrayType::new(&engine, FieldType::new(Mutability::Var, StorageType::I8));
78 let pre = wasmtime::ArrayRefPre::new(caller.as_context_mut(), ty);
79 let vals: Vec<Val> = bytes.iter().map(|b| Val::I32(i32::from(*b))).collect();
80 wasmtime::ArrayRef::new_fixed(caller.as_context_mut(), &pre, &vals)
81}
82
83pub fn alloc_ratio_ref<T>(
88 caller: &mut Caller<'_, T>,
89 numer: i64,
90 denom: i64,
91) -> wasmtime::Result<Rooted<StructRef>> {
92 let engine = caller.engine().clone();
93 let ty = StructType::new(
94 &engine,
95 std::iter::repeat_n(
96 FieldType::new(Mutability::Const, StorageType::ValType(ValType::I64)),
97 2,
98 ),
99 )?;
100 let pre = StructRefPre::new(caller.as_context_mut(), ty);
101 StructRef::new(
102 caller.as_context_mut(),
103 &pre,
104 &[Val::I64(numer), Val::I64(denom)],
105 )
106}
107
108pub async fn alloc_entity_via_export<T>(
122 caller: &mut Caller<'_, T>,
123 export_name: &str,
124 args: &[Val],
125) -> wasmtime::Result<Rooted<StructRef>>
126where
127 T: Send,
128{
129 let alloc = caller
130 .get_export(export_name)
131 .and_then(|e| e.into_func())
132 .ok_or_else(|| {
133 wasmtime::Error::msg(format!(
134 "module missing '{export_name}' export — host entity allocation requires \
135 the nomiscript compiler skeleton's exported alloc_<kind> function"
136 ))
137 })?;
138 let mut results = [Val::AnyRef(None)];
139 alloc
140 .call_async(caller.as_context_mut(), args, &mut results)
141 .await?;
142 let new_entity_any = match &results[0] {
143 Val::AnyRef(any) => *any,
144 _ => {
145 return Err(wasmtime::Error::msg(format!(
146 "{export_name} returned non-anyref Val variant"
147 )));
148 }
149 };
150 new_entity_any
151 .ok_or_else(|| {
152 wasmtime::Error::msg(format!(
153 "{export_name} returned null when allocating entity"
154 ))
155 })?
156 .checked_struct(caller.as_context_mut())
157}
158
159pub fn read_string_arg<T>(
166 caller: &mut Caller<'_, T>,
167 arg: Option<Rooted<wasmtime::ArrayRef>>,
168) -> wasmtime::Result<Option<String>> {
169 let Some(arr) = arg else {
170 return Ok(None);
171 };
172 let len = arr.len(caller.as_context_mut())?;
173 let mut bytes = Vec::with_capacity(len as usize);
174 for i in 0..len {
175 let val = arr.get(caller.as_context_mut(), i)?;
176 let byte_i32 = val
177 .i32()
178 .ok_or_else(|| wasmtime::Error::msg("string arg element is not i32"))?;
179 bytes.push(byte_i32 as u8);
180 }
181 String::from_utf8(bytes)
182 .map(Some)
183 .map_err(|err| wasmtime::Error::msg(format!("string arg is not valid UTF-8: {err}")))
184}
185
186pub fn read_commodity_arg<T>(
191 caller: &mut Caller<'_, T>,
192 arg: Option<Rooted<StructRef>>,
193) -> wasmtime::Result<Option<(i64, i64, Uuid)>> {
194 let Some(s) = arg else {
195 return Ok(None);
196 };
197 let read_i64 = |c: &mut Caller<'_, T>, idx: usize| -> wasmtime::Result<i64> {
198 let v = s.field(c.as_context_mut(), idx)?;
199 v.i64()
200 .ok_or_else(|| wasmtime::Error::msg(format!("commodity field {idx} is not i64")))
201 };
202 let (numer, denom) = checked_pair(read_i64(caller, 0)?, read_i64(caller, 1)?, "commodity")?;
203 let hi = read_i64(caller, 2)?;
204 let lo = read_i64(caller, 3)?;
205 let raw = ((hi as u64 as u128) << 64) | (lo as u64 as u128);
206 Ok(Some((numer, denom, Uuid::from_u128(raw))))
207}
208
209pub fn read_ratio_arg<T>(
214 caller: &mut Caller<'_, T>,
215 arg: Option<Rooted<StructRef>>,
216) -> wasmtime::Result<Option<(i64, i64)>> {
217 let Some(s) = arg else {
218 return Ok(None);
219 };
220 let numer = s
221 .field(caller.as_context_mut(), 0)?
222 .i64()
223 .ok_or_else(|| wasmtime::Error::msg("ratio field 0 (numer) is not i64"))?;
224 let denom = s
225 .field(caller.as_context_mut(), 1)?
226 .i64()
227 .ok_or_else(|| wasmtime::Error::msg("ratio field 1 (denom) is not i64"))?;
228 checked_pair(numer, denom, "ratio").map(Some)
229}
230
231pub fn read_entity_string_field<T>(
238 caller: &mut Caller<'_, T>,
239 arg: Option<Rooted<StructRef>>,
240 kind: nomiscript::EntityKind,
241 field_name: &str,
242) -> wasmtime::Result<Option<String>> {
243 let Some(s) = arg else {
244 return Ok(None);
245 };
246 read_entity_string_field_ctx(caller.as_context_mut(), s, kind, field_name).map(Some)
247}
248
249pub fn read_entity_string_field_ctx(
253 mut store: impl AsContextMut,
254 entity: Rooted<StructRef>,
255 kind: nomiscript::EntityKind,
256 field_name: &str,
257) -> wasmtime::Result<String> {
258 let layout = nomiscript::entity_layout(kind)
259 .ok_or_else(|| wasmtime::Error::msg(format!("no entity layout for {kind:?}")))?;
260 let idx = layout
261 .fields
262 .iter()
263 .position(|f| f.name == field_name && f.kind == nomiscript::EntityFieldKind::String)
264 .ok_or_else(|| {
265 wasmtime::Error::msg(format!(
266 "entity {kind:?} has no String field named '{field_name}'"
267 ))
268 })?;
269 let arr = match entity.field(store.as_context_mut(), idx)? {
270 Val::AnyRef(Some(any)) => any.checked_array(store.as_context_mut())?,
271 _ => {
272 return Err(wasmtime::Error::msg(format!(
273 "entity {kind:?} field '{field_name}' (slot {idx}) is not an i8_array"
274 )));
275 }
276 };
277 let len = arr.len(store.as_context_mut())?;
278 let mut bytes = Vec::with_capacity(len as usize);
279 for i in 0..len {
280 let byte = arr
281 .get(store.as_context_mut(), i)?
282 .i32()
283 .ok_or_else(|| wasmtime::Error::msg("entity string element is not i32"))?;
284 bytes.push(byte as u8);
285 }
286 String::from_utf8(bytes)
287 .map_err(|err| wasmtime::Error::msg(format!("entity string field not utf-8: {err}")))
288}
289
290pub async fn alloc_pair_chain<T>(
312 caller: &mut Caller<'_, T>,
313 items: impl IntoIterator<Item = Option<Rooted<AnyRef>>>,
314) -> wasmtime::Result<Option<Rooted<StructRef>>>
315where
316 T: Send,
317{
318 let pair_new = caller
319 .get_export("pair_new")
320 .and_then(|e| e.into_func())
321 .ok_or_else(|| {
322 wasmtime::Error::msg(
323 "module missing 'pair_new' export — host pair allocation requires \
324 the nomiscript compiler skeleton's exported pair_new",
325 )
326 })?;
327
328 let items: Vec<Option<Rooted<AnyRef>>> = items.into_iter().collect();
329 let mut head: Option<Rooted<StructRef>> = None;
330 for item in items.into_iter().rev() {
331 let cdr_any = head.map(|p| p.to_anyref());
332 let mut results = [Val::AnyRef(None)];
333 pair_new
334 .call_async(
335 caller.as_context_mut(),
336 &[Val::AnyRef(item), Val::AnyRef(cdr_any)],
337 &mut results,
338 )
339 .await?;
340 let new_pair_any = match &results[0] {
341 Val::AnyRef(any) => *any,
342 _ => {
343 return Err(wasmtime::Error::msg(
344 "pair_new returned non-anyref Val variant",
345 ));
346 }
347 };
348 head = Some(
349 new_pair_any
350 .ok_or_else(|| {
351 wasmtime::Error::msg("pair_new returned null when chaining elements")
352 })?
353 .checked_struct(caller.as_context_mut())?,
354 );
355 }
356 Ok(head)
357}