1
//! The reader of PERSIST rows: a row is `(label, units)`, and what each unit
2
//! of it prints is compared with the row's pinned values.
3

            
4
use nms::interpreter::Interpreter;
5
use scripting::nomiscript::Value;
6

            
7
pub type Row = (&'static str, Vec<String>);
8

            
9
1218
pub fn row(label: &'static str, units: &[&str]) -> Row {
10
1218
    (label, units.iter().map(ToString::to_string).collect())
11
1218
}
12

            
13
1887
fn show(value: &Value) -> String {
14
1887
    match value {
15
34
        Value::Nil => "nil".to_string(),
16
24
        Value::T => "t".to_string(),
17
994
        Value::Number(n) => n.to_string(),
18
26
        Value::String(text) => format!("{text:?}"),
19
577
        Value::Symbol(name) => name.to_lowercase(),
20
        Value::Struct { .. } | Value::Closure(_) | Value::Condition => {
21
31
            scripting::nomiscript::format_value(value)
22
        }
23
201
        other => match scripting::nomiscript::list_to_vec(other) {
24
201
            Some(items) => format!("({})", items.iter().map(show).collect::<Vec<_>>().join(" ")),
25
            None => format!("{other:?}"),
26
        },
27
    }
28
1887
}
29

            
30
1195
fn shown(units: &[String], width: usize) -> Vec<String> {
31
1195
    let mut interp = Interpreter::new(false).unwrap();
32
1195
    units
33
1195
        .iter()
34
2346
        .map(|unit| match interp.eval(unit) {
35
1878
            Ok(values) => values.last().map_or("-".to_string(), show),
36
            Err(err) => {
37
468
                let text = err.to_string();
38
468
                let text: Vec<&str> = text.split_whitespace().collect();
39
468
                format!(
40
                    "err: {}",
41
468
                    text.join(" ").chars().take(width).collect::<String>()
42
                )
43
            }
44
2346
        })
45
        .collect()
46
1195
}
47

            
48
/// Asserts that every row reads as `pinned`, naming each row that moved.
49
84
pub fn assert_pinned(rows: &[Row], pinned: &[(&str, &[&str])]) {
50
84
    assert_pinned_wide(rows, pinned, 44);
51
84
}
52

            
53
/// [`assert_pinned`] with an error text kept to `width` characters.
54
96
pub fn assert_pinned_wide(rows: &[Row], pinned: &[(&str, &[&str])], width: usize) {
55
96
    assert_eq!(rows.len(), pinned.len());
56
96
    let mut moved = Vec::new();
57
96
    for ((label, units), (pinned_label, values)) in rows.iter().zip(pinned) {
58
1195
        assert_eq!(label, pinned_label);
59
1195
        let now = shown(units, width);
60
1195
        if now != *values {
61
            moved.push(format!("{label}: {now:?}"));
62
1195
        }
63
    }
64
96
    assert!(moved.is_empty(), "{}", moved.join("\n"));
65
96
}