Skip to main content

scripting/runtime/
encode.rs

1//! The inverse of `decode`: builds the guest value of an [`EvalValue`] for a host fn
2//! declared to return `any`.
3
4use std::future::Future;
5use std::pin::Pin;
6
7use wasmtime::{AnyRef, AsContextMut, Caller, I31, Rooted, Val};
8
9use super::abi::{alloc_pair_chain, alloc_ratio_ref, alloc_string_ref};
10use super::decode::EvalValue;
11
12type Encoded = wasmtime::Result<Option<Rooted<AnyRef>>>;
13
14/// The guest value of `value`: strings, numbers, `t`, `nil`, symbols and lists of them.
15///
16/// # Errors
17/// A value kind with no host-built form (bytes, commodity), an index beyond 31 bits, or a
18/// module without the exports the compiler always emits.
19pub fn alloc_value<'a, T: Send + 'a>(
20    caller: &'a mut Caller<'_, T>,
21    value: &'a EvalValue,
22) -> Pin<Box<dyn Future<Output = Encoded> + Send + 'a>> {
23    Box::pin(async move {
24        match value {
25            EvalValue::Nil => Ok(None),
26            EvalValue::T => t_singleton_of(caller).map(Some),
27            EvalValue::I32(n) => index_ref(caller, *n).map(Some),
28            EvalValue::Ratio { numer, denom } => {
29                Ok(Some(alloc_ratio_ref(caller, *numer, *denom)?.to_anyref()))
30            }
31            EvalValue::String(text) => {
32                Ok(Some(alloc_string_ref(caller, text.as_bytes())?.to_anyref()))
33            }
34            EvalValue::Symbol(name) => alloc_symbol(caller, name).await.map(Some),
35            EvalValue::List(items) => alloc_list(caller, items).await,
36            EvalValue::Bytes(_) | EvalValue::Commodity { .. } => Err(wasmtime::Error::msg(
37                "a host fn cannot return bytes or a commodity as an `any` value",
38            )),
39            EvalValue::Closure { .. }
40            | EvalValue::Condition
41            | EvalValue::Opaque
42            | EvalValue::Instance { .. }
43            | EvalValue::Struct(_) => Err(wasmtime::Error::msg(
44                "a host fn cannot return an opaque value as an `any` value",
45            )),
46        }
47    })
48}
49
50fn t_singleton_of<T>(caller: &mut Caller<'_, T>) -> wasmtime::Result<Rooted<AnyRef>> {
51    let global = caller
52        .get_export("t")
53        .and_then(wasmtime::Extern::into_global)
54        .ok_or_else(|| wasmtime::Error::msg("module does not export the `t` global"))?;
55    match global.get(caller.as_context_mut()) {
56        Val::AnyRef(Some(t)) => Ok(t),
57        _ => Err(wasmtime::Error::msg(
58            "`t` global is not a non-null internal reference",
59        )),
60    }
61}
62
63fn index_ref<T>(caller: &mut Caller<'_, T>, n: i32) -> wasmtime::Result<Rooted<AnyRef>> {
64    let i31 = I31::new_i32(n)
65        .ok_or_else(|| wasmtime::Error::msg(format!("index {n} exceeds 31 bits")))?;
66    Ok(AnyRef::from_i31(caller.as_context_mut(), i31))
67}
68
69async fn alloc_symbol<T: Send>(
70    caller: &mut Caller<'_, T>,
71    name: &str,
72) -> wasmtime::Result<Rooted<AnyRef>> {
73    let symbol_new = caller
74        .get_export("symbol_new")
75        .and_then(wasmtime::Extern::into_func)
76        .ok_or_else(|| wasmtime::Error::msg("module does not export `symbol_new`"))?;
77    let text = alloc_string_ref(caller, name.as_bytes())?;
78    let mut results = [Val::AnyRef(None)];
79    symbol_new
80        .call_async(
81            caller.as_context_mut(),
82            &[Val::AnyRef(Some(text.to_anyref()))],
83            &mut results,
84        )
85        .await?;
86    match results {
87        [Val::AnyRef(Some(symbol))] => Ok(symbol),
88        _ => Err(wasmtime::Error::msg("symbol_new returned no symbol")),
89    }
90}
91
92async fn alloc_list<T: Send>(caller: &mut Caller<'_, T>, items: &[EvalValue]) -> Encoded {
93    let mut cars = Vec::with_capacity(items.len());
94    for item in items {
95        cars.push(alloc_value(caller, item).await?);
96    }
97    Ok(alloc_pair_chain(caller, cars)
98        .await?
99        .map(|head| head.to_anyref()))
100}