Skip to main content

scripting/runtime/
log_value.rs

1//! The text behind `env.log_value`: the argument list a PRINT / DISPLAY /
2//! DEBUG call builds at run time, decoded with the eval decoder and printed
3//! like the compile-time path prints constants.
4
5use nomiscript::{PairElement, Value, format_value_plain};
6use wasmtime::{AnyRef, AsContextMut, Caller, Rooted};
7
8use super::decode::EvalValue;
9use super::structure::{InstanceMode, decode_cars};
10use super::type_handles::resolve_caller_type_handles;
11
12/// The one log message for `args`, a `$pair` list of the printed values:
13/// each printed `princ`-style, joined by a space. `None` when a value in it
14/// cannot be read (compound money, a value of no known kind): the caller
15/// reports that to the guest, never as text.
16pub fn logged_values<T>(
17    caller: &mut Caller<'_, T>,
18    args: Option<Rooted<AnyRef>>,
19) -> wasmtime::Result<Option<String>> {
20    let Some(head) = args else {
21        return Ok(Some(String::new()));
22    };
23    let handles = resolve_caller_type_handles(caller)?;
24    let Ok(items) = decode_cars(
25        caller.as_context_mut(),
26        head,
27        PairElement::AnyRef,
28        &handles,
29        InstanceMode::Contents,
30        0,
31    ) else {
32        return Ok(None);
33    };
34    Ok(printed(items))
35}
36
37fn printed(items: Vec<EvalValue>) -> Option<String> {
38    if items.iter().any(has_opaque) {
39        return None;
40    }
41    let texts: Vec<_> = items
42        .into_iter()
43        .map(|item| format_value_plain(&Value::from(item)))
44        .collect();
45    Some(texts.join(" "))
46}
47
48fn has_opaque(value: &EvalValue) -> bool {
49    match value {
50        EvalValue::Opaque => true,
51        EvalValue::List(items) => items.iter().any(has_opaque),
52        EvalValue::Struct(view) => view.fields.iter().any(|(_, field)| has_opaque(field)),
53        _ => false,
54    }
55}
56
57#[cfg(test)]
58#[path = "log_value_tests.rs"]
59mod tests;