1
//! The inverse of `decode`: builds the guest value of an [`EvalValue`] for a host fn
2
//! declared to return `any`.
3

            
4
use std::future::Future;
5
use std::pin::Pin;
6

            
7
use wasmtime::{AnyRef, AsContextMut, Caller, I31, Rooted, Val};
8

            
9
use super::abi::{alloc_pair_chain, alloc_ratio_ref, alloc_string_ref};
10
use super::decode::EvalValue;
11

            
12
type 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.
19
213400
pub fn alloc_value<'a, T: Send + 'a>(
20
213400
    caller: &'a mut Caller<'_, T>,
21
213400
    value: &'a EvalValue,
22
213400
) -> Pin<Box<dyn Future<Output = Encoded> + Send + 'a>> {
23
213400
    Box::pin(async move {
24
213400
        match value {
25
6302
            EvalValue::Nil => Ok(None),
26
4654
            EvalValue::T => t_singleton_of(caller).map(Some),
27
2422
            EvalValue::I32(n) => index_ref(caller, *n).map(Some),
28
            EvalValue::Ratio { numer, denom } => {
29
207
                Ok(Some(alloc_ratio_ref(caller, *numer, *denom)?.to_anyref()))
30
            }
31
            EvalValue::String(text) => {
32
93675
                Ok(Some(alloc_string_ref(caller, text.as_bytes())?.to_anyref()))
33
            }
34
78168
            EvalValue::Symbol(name) => alloc_symbol(caller, name).await.map(Some),
35
27968
            EvalValue::List(items) => alloc_list(caller, items).await,
36
3
            EvalValue::Bytes(_) | EvalValue::Commodity { .. } => Err(wasmtime::Error::msg(
37
3
                "a host fn cannot return bytes or a commodity as an `any` value",
38
3
            )),
39
            EvalValue::Closure { .. }
40
            | EvalValue::Condition
41
            | EvalValue::Opaque
42
            | EvalValue::Instance { .. }
43
1
            | EvalValue::Struct(_) => Err(wasmtime::Error::msg(
44
1
                "a host fn cannot return an opaque value as an `any` value",
45
1
            )),
46
        }
47
213400
    })
48
213400
}
49

            
50
4654
fn t_singleton_of<T>(caller: &mut Caller<'_, T>) -> wasmtime::Result<Rooted<AnyRef>> {
51
4654
    let global = caller
52
4654
        .get_export("t")
53
4654
        .and_then(wasmtime::Extern::into_global)
54
1
        .ok_or_else(|| wasmtime::Error::msg("module does not export the `t` global"))?;
55
4653
    match global.get(caller.as_context_mut()) {
56
4652
        Val::AnyRef(Some(t)) => Ok(t),
57
1
        _ => Err(wasmtime::Error::msg(
58
1
            "`t` global is not a non-null internal reference",
59
1
        )),
60
    }
61
4654
}
62

            
63
2422
fn index_ref<T>(caller: &mut Caller<'_, T>, n: i32) -> wasmtime::Result<Rooted<AnyRef>> {
64
2422
    let i31 = I31::new_i32(n)
65
1
        .ok_or_else(|| wasmtime::Error::msg(format!("index {n} exceeds 31 bits")))?;
66
2421
    Ok(AnyRef::from_i31(caller.as_context_mut(), i31))
67
2422
}
68

            
69
78168
async fn alloc_symbol<T: Send>(
70
78168
    caller: &mut Caller<'_, T>,
71
78168
    name: &str,
72
78168
) -> wasmtime::Result<Rooted<AnyRef>> {
73
78168
    let symbol_new = caller
74
78168
        .get_export("symbol_new")
75
78168
        .and_then(wasmtime::Extern::into_func)
76
1
        .ok_or_else(|| wasmtime::Error::msg("module does not export `symbol_new`"))?;
77
78167
    let text = alloc_string_ref(caller, name.as_bytes())?;
78
78167
    let mut results = [Val::AnyRef(None)];
79
78167
    symbol_new
80
78167
        .call_async(
81
78167
            caller.as_context_mut(),
82
78167
            &[Val::AnyRef(Some(text.to_anyref()))],
83
78167
            &mut results,
84
78167
        )
85
78167
        .await?;
86
78167
    match results {
87
78166
        [Val::AnyRef(Some(symbol))] => Ok(symbol),
88
1
        _ => Err(wasmtime::Error::msg("symbol_new returned no symbol")),
89
    }
90
78168
}
91

            
92
27968
async fn alloc_list<T: Send>(caller: &mut Caller<'_, T>, items: &[EvalValue]) -> Encoded {
93
27968
    let mut cars = Vec::with_capacity(items.len());
94
27968
    for item in items {
95
158800
        cars.push(alloc_value(caller, item).await?);
96
    }
97
27968
    Ok(alloc_pair_chain(caller, cars)
98
27968
        .await?
99
26684
        .map(|head| head.to_anyref()))
100
27968
}