1use crate::checked_ref::CheckedAnyRef;
4
5pub use scripting_format::MAX_WIRE_LIST_DEPTH;
6
7use super::structure::{
8 InstanceMode, decode_closure, decode_dynamic_anyref, decode_entity, decode_pair, decode_struct,
9};
10use super::type_handles::TypeHandles;
11use wasmtime::{AnyRef, AsContextMut, Rooted, Val};
12
13#[derive(Debug, Clone, PartialEq)]
20pub enum EvalValue {
21 Nil,
22 T,
23 I32(i32),
24 Ratio {
25 numer: i64,
26 denom: i64,
27 },
28 Commodity {
33 numer: i64,
34 denom: i64,
35 commodity_hi: i64,
36 commodity_lo: i64,
37 },
38 String(String),
39 Bytes(Vec<u8>),
40 List(Vec<EvalValue>),
42 Symbol(String),
44 Instance {
46 serial: u32,
47 layout: u32,
48 },
49 Struct(Box<StructView>),
52 Closure {
55 site: Option<u32>,
56 },
57 Condition,
59 Opaque,
61}
62
63#[derive(Debug, Clone, PartialEq)]
66pub struct StructView {
67 pub name: String,
68 pub fields: Vec<(String, EvalValue)>,
69}
70
71impl From<EvalValue> for nomiscript::Value {
72 fn from(value: EvalValue) -> Self {
73 match value {
74 EvalValue::Nil => nomiscript::Value::Nil,
75 EvalValue::T => nomiscript::Value::T,
76 EvalValue::I32(n) => nomiscript::Value::Number(nomiscript::Number::Index(i64::from(n))),
77 EvalValue::Ratio { numer, denom } => nomiscript::Value::Number(
78 nomiscript::Number::Scalar(nomiscript::Fraction::new(numer, denom)),
79 ),
80 EvalValue::Commodity {
81 numer,
82 denom,
83 commodity_hi,
84 commodity_lo,
85 } => {
86 let raw = ((commodity_hi as u64 as u128) << 64) | (commodity_lo as u64 as u128);
90 nomiscript::Value::Commodity {
91 amount: nomiscript::Fraction::new(numer, denom),
92 commodity_id: uuid::Uuid::from_u128(raw),
93 }
94 }
95 EvalValue::String(s) => nomiscript::Value::String(s),
96 EvalValue::Symbol(s) => nomiscript::Value::Symbol(s),
97 EvalValue::Struct(view) => nomiscript::Value::Struct {
98 name: view.name,
99 fields: view
100 .fields
101 .into_iter()
102 .map(|(key, value)| (key, nomiscript::Value::from(value)))
103 .collect(),
104 },
105 EvalValue::Closure { site } => nomiscript::Value::Closure(
106 site.map_or_else(nomiscript::Closure::siteless, |site| {
107 nomiscript::Closure::new(site, Vec::new())
108 }),
109 ),
110 EvalValue::Condition => nomiscript::Value::Condition,
111 EvalValue::Opaque | EvalValue::Instance { .. } => {
112 nomiscript::Value::String("<anyref>".into())
113 }
114 EvalValue::Bytes(b) => nomiscript::Value::Bytes(b),
115 EvalValue::List(items) => {
116 nomiscript::vec_to_list(items.into_iter().map(nomiscript::Value::from).collect())
117 }
118 }
119 }
120}
121
122pub fn decode_eval_result(
135 mut store: impl AsContextMut,
136 value: Option<Rooted<AnyRef>>,
137 result_ty: Option<nomiscript::WasmType>,
138 handles: &TypeHandles,
139) -> wasmtime::Result<EvalValue> {
140 let Some(ty) = result_ty else {
141 return Ok(EvalValue::Nil);
142 };
143 let Some(any) = value else {
149 return match ty {
150 nomiscript::WasmType::I32 => Err(wasmtime::Error::msg(
151 "nomi-eval returned null for declared result type i32",
152 )),
153 _ => Ok(EvalValue::Nil),
154 };
155 };
156 decode_anyref(&mut store, any, ty, handles, InstanceMode::Wire)
157}
158
159fn decode_index(mut store: impl AsContextMut, any: &Rooted<AnyRef>) -> wasmtime::Result<EvalValue> {
162 let numer = any
163 .checked_struct(&mut store)?
164 .field(&mut store, 0)?
165 .i64()
166 .ok_or_else(|| wasmtime::Error::msg("index result field 0 (numer) is not i64"))?;
167 i32::try_from(numer)
168 .map(EvalValue::I32)
169 .map_err(|_| wasmtime::Error::msg(format!("index result {numer} exceeds i32")))
170}
171
172pub(super) fn decode_anyref(
173 mut store: impl AsContextMut,
174 any: Rooted<AnyRef>,
175 ty: nomiscript::WasmType,
176 handles: &TypeHandles,
177 mode: InstanceMode,
178) -> wasmtime::Result<EvalValue> {
179 use nomiscript::WasmType;
180 match ty {
181 WasmType::I32 => decode_index(&mut store, &any),
182 WasmType::Bool => decode_bool(&mut store, &any, &handles.t),
183 WasmType::Ratio => decode_ratio(&mut store, &any),
184 WasmType::Commodity => decode_commodity(&mut store, &any),
185 WasmType::StringRef => decode_string_ref(&mut store, &any),
186 WasmType::SymbolRef => decode_symbol(&mut store, &any),
187 WasmType::PairRef(elem) => decode_pair(store.as_context_mut(), any, elem, handles, mode, 0),
188 WasmType::EntityRef(kind) => decode_entity(store.as_context_mut(), &any, kind, 0),
189 WasmType::StructRef(_) => decode_struct(store.as_context_mut(), &any, handles, mode, 0),
190 WasmType::Closure(_) => decode_closure(store.as_context_mut(), &any),
191 WasmType::AnyRef => decode_dynamic_anyref(store.as_context_mut(), any, handles, mode, 0),
195 }
196}
197
198fn decode_bool(
202 store: impl AsContextMut,
203 any: &Rooted<AnyRef>,
204 t: &Rooted<AnyRef>,
205) -> wasmtime::Result<EvalValue> {
206 if Rooted::<AnyRef>::ref_eq(&store, any, t)? {
207 Ok(EvalValue::T)
208 } else {
209 Err(wasmtime::Error::msg(
210 "boxed bool result is neither null nor the `t` singleton",
211 ))
212 }
213}
214
215pub(crate) fn guest_fraction(numer: i64, denom: i64) -> Option<nomiscript::Fraction> {
219 (denom > 0).then(|| nomiscript::Fraction::new(numer, denom))
220}
221
222pub(super) fn checked_pair(numer: i64, denom: i64, what: &str) -> wasmtime::Result<(i64, i64)> {
223 guest_fraction(numer, denom)
224 .map(|_| (numer, denom))
225 .ok_or_else(|| wasmtime::Error::msg(format!("{what} has a non-positive denominator")))
226}
227
228pub(super) fn decode_ratio(
229 mut store: impl AsContextMut,
230 any: &Rooted<AnyRef>,
231) -> wasmtime::Result<EvalValue> {
232 let s = any.checked_struct(&mut store)?;
233 let numer = s
234 .field(&mut store, 0)?
235 .i64()
236 .ok_or_else(|| wasmtime::Error::msg("ratio field 0 (numer) is not i64"))?;
237 let denom = s
238 .field(&mut store, 1)?
239 .i64()
240 .ok_or_else(|| wasmtime::Error::msg("ratio field 1 (denom) is not i64"))?;
241 let (numer, denom) = checked_pair(numer, denom, "ratio")?;
242 Ok(EvalValue::Ratio { numer, denom })
243}
244
245pub(super) fn decode_commodity(
250 mut store: impl AsContextMut,
251 any: &Rooted<AnyRef>,
252) -> wasmtime::Result<EvalValue> {
253 let s = any.checked_struct(&mut store)?;
254 let numer = commodity_i64(&mut store, &s, 0)?;
255 let denom = commodity_i64(&mut store, &s, 1)?;
256 let (numer, denom) = checked_pair(numer, denom, "commodity amount")?;
257 match s.field(&mut store, 4)? {
258 Val::AnyRef(None) => {
259 let hi = commodity_i64(&mut store, &s, 2)?;
260 let lo = commodity_i64(&mut store, &s, 3)?;
261 Ok(EvalValue::Commodity {
262 numer,
263 denom,
264 commodity_hi: hi,
265 commodity_lo: lo,
266 })
267 }
268 Val::AnyRef(Some(term)) => {
269 let arr = term.checked_array(&mut store)?;
270 if arr.len(&mut store)? == 0 {
271 Ok(EvalValue::Ratio { numer, denom })
272 } else {
273 Err(wasmtime::Error::msg(
274 "compound commodity (e.g. money × money) has no host \
275 representation yet",
276 ))
277 }
278 }
279 _ => Err(wasmtime::Error::msg(
280 "commodity field 4 (unit term) is not a ref",
281 )),
282 }
283}
284
285fn commodity_i64(
286 store: impl AsContextMut,
287 s: &Rooted<wasmtime::StructRef>,
288 slot: usize,
289) -> wasmtime::Result<i64> {
290 s.field(store, slot)?
291 .i64()
292 .ok_or_else(|| wasmtime::Error::msg(format!("commodity field {slot} is not i64")))
293}
294
295pub(super) fn decode_string_ref(
296 mut store: impl AsContextMut,
297 any: &Rooted<AnyRef>,
298) -> wasmtime::Result<EvalValue> {
299 array_text(&mut store, any).map(EvalValue::String)
300}
301
302pub(super) fn decode_symbol(
303 mut store: impl AsContextMut,
304 any: &Rooted<AnyRef>,
305) -> wasmtime::Result<EvalValue> {
306 symbol_name(&mut store, any).map(EvalValue::Symbol)
307}
308
309pub(super) fn symbol_name(
311 mut store: impl AsContextMut,
312 any: &Rooted<AnyRef>,
313) -> wasmtime::Result<String> {
314 match any.checked_struct(&mut store)?.field(&mut store, 0)? {
315 Val::AnyRef(Some(name)) => array_text(&mut store, &name),
316 _ => Err(wasmtime::Error::msg("symbol name is not a reference")),
317 }
318}
319
320fn array_text(mut store: impl AsContextMut, any: &Rooted<AnyRef>) -> wasmtime::Result<String> {
321 let arr = any.checked_array(&mut store)?;
322 let len = arr.len(&mut store)?;
323 let mut bytes = Vec::with_capacity(len as usize);
324 for i in 0..len {
325 let v = arr.get(&mut store, i)?;
326 let byte = v
327 .i32()
328 .ok_or_else(|| wasmtime::Error::msg("string element is not i32"))?;
329 bytes.push(byte as u8);
330 }
331 String::from_utf8(bytes).map_err(|err| wasmtime::Error::msg(format!("not valid utf-8: {err}")))
332}