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

            
5
use nomiscript::{PairElement, Value, format_value_plain};
6
use wasmtime::{AnyRef, AsContextMut, Caller, Rooted};
7

            
8
use super::decode::EvalValue;
9
use super::structure::{InstanceMode, decode_cars};
10
use 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.
16
58343
pub fn logged_values<T>(
17
58343
    caller: &mut Caller<'_, T>,
18
58343
    args: Option<Rooted<AnyRef>>,
19
58343
) -> wasmtime::Result<Option<String>> {
20
58343
    let Some(head) = args else {
21
        return Ok(Some(String::new()));
22
    };
23
58343
    let handles = resolve_caller_type_handles(caller)?;
24
58343
    let Ok(items) = decode_cars(
25
58343
        caller.as_context_mut(),
26
58343
        head,
27
58343
        PairElement::AnyRef,
28
58343
        &handles,
29
58343
        InstanceMode::Contents,
30
58343
        0,
31
58343
    ) else {
32
1520
        return Ok(None);
33
    };
34
56823
    Ok(printed(items))
35
58343
}
36

            
37
59283
fn printed(items: Vec<EvalValue>) -> Option<String> {
38
59283
    if items.iter().any(has_opaque) {
39
1
        return None;
40
59282
    }
41
59282
    let texts: Vec<_> = items
42
59282
        .into_iter()
43
66315
        .map(|item| format_value_plain(&Value::from(item)))
44
        .collect();
45
59282
    Some(texts.join(" "))
46
59283
}
47

            
48
203506
fn has_opaque(value: &EvalValue) -> bool {
49
203506
    match value {
50
2
        EvalValue::Opaque => true,
51
46365
        EvalValue::List(items) => items.iter().any(has_opaque),
52
73530
        EvalValue::Struct(view) => view.fields.iter().any(|(_, field)| has_opaque(field)),
53
83609
        _ => false,
54
    }
55
203506
}
56

            
57
#[cfg(test)]
58
#[path = "log_value_tests.rs"]
59
mod tests;