spock-cli 0.1.0

A model checker for specs that read like Rust: TLA's logic of actions, checked on every core in machine code
//! A report as people read it: values as spock writes them, and each state of a trace as the
//! updates that reached it.

use std::{fmt::Write as _, time::Duration};

use spock_engine::{Outcome, Report, State, Value};
use spock_ir::{Program, TypeDefKind};

/// `value` as a spock literal.
pub fn value(program: &Program, value: &Value) -> String {
    let mut out = String::new();
    write_value(&mut out, program, value);
    out
}

fn write_value(out: &mut String, program: &Program, value: &Value) {
    let list = |out: &mut String, open: &str, items: &[Value], close: &str| {
        out.push_str(open);
        for (i, item) in items.iter().enumerate() {
            if i > 0 {
                out.push_str(", ");
            }
            write_value(out, program, item);
        }
        out.push_str(close);
    };
    match value {
        Value::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
        Value::Int(n) => {
            let _ = write!(out, "{n}");
        }
        Value::Atom(ty, index) => match &program.def(*ty).kind {
            TypeDefKind::Atoms(atoms) => out.push_str(&atoms[*index as usize]),
            _ => {
                let _ = write!(out, "{}#{index}", program.def(*ty).name);
            }
        },
        Value::Struct(ty, values) => {
            let def = program.def(*ty);
            let names = match &def.kind {
                TypeDefKind::Struct(fields) => fields.iter().map(|f| f.name.as_str()).collect(),
                _ => Vec::new(),
            };
            out.push_str(&def.name);
            write_fields(out, program, &names, values);
        }
        Value::Ctor(ty, index, values) => {
            let ctor = match &program.def(*ty).kind {
                TypeDefKind::Variant(ctors) => ctors.get(*index as usize),
                _ => None,
            };
            let Some(ctor) = ctor else {
                let _ = write!(out, "{}#{index}", program.def(*ty).name);
                return;
            };
            out.push_str(&ctor.name);
            if ctor.fields.is_empty() {
                return;
            }
            if positional(&ctor.fields) {
                list(out, "(", values, ")");
            } else {
                let names: Vec<&str> = ctor.fields.iter().map(|f| f.name.as_str()).collect();
                write_fields(out, program, &names, values);
            }
        }
        Value::Tuple(items) if items.len() == 1 => list(out, "(", items, ",)"),
        Value::Tuple(items) => list(out, "(", items, ")"),
        Value::Set(items) => list(out, "{", items, "}"),
        Value::Seq(items) => list(out, "[", items, "]"),
        Value::Map(pairs) => {
            out.push('{');
            for (i, (k, v)) in pairs.iter().enumerate() {
                if i > 0 {
                    out.push_str(", ");
                }
                write_value(out, program, k);
                out.push_str(" -> ");
                write_value(out, program, v);
            }
            out.push('}');
        }
    }
}

fn write_fields(out: &mut String, program: &Program, names: &[&str], values: &[Value]) {
    if values.is_empty() {
        out.push_str(" {}");
        return;
    }
    out.push_str(" { ");
    for (i, v) in values.iter().enumerate() {
        if i > 0 {
            out.push_str(", ");
        }
        let _ = write!(out, "{}: ", names.get(i).copied().unwrap_or("?"));
        write_value(out, program, v);
    }
    out.push_str(" }");
}

/// Whether a constructor's fields are positional, `Some(Int)`, rather than named.
pub fn positional(fields: &[spock_ir::Field]) -> bool {
    fields.iter().all(|f| f.name.bytes().all(|b| b.is_ascii_digit()))
}

/// The updates that take `before` to `after`, as `with` writes them: `path = value`. A struct
/// or a map with the same keys is updated part by part; anything else is replaced.
fn diff(program: &Program, path: String, before: &Value, after: &Value, out: &mut Vec<String>) {
    if before == after {
        return;
    }
    match (before, after) {
        (Value::Struct(a, xs), Value::Struct(b, ys)) if a == b => {
            if let TypeDefKind::Struct(fields) = &program.def(*a).kind {
                for ((f, x), y) in fields.iter().zip(xs).zip(ys) {
                    diff(program, format!("{path}.{}", f.name), x, y, out);
                }
                return;
            }
        }
        (Value::Map(xs), Value::Map(ys))
            if xs.len() == ys.len() && xs.iter().zip(ys).all(|(x, y)| x.0 == y.0) =>
        {
            for ((k, x), (_, y)) in xs.iter().zip(ys) {
                diff(program, format!("{path}[{}]", value(program, k)), x, y, out);
            }
            return;
        }
        (Value::Seq(xs), Value::Seq(ys)) if xs.len() == ys.len() => {
            for (i, (x, y)) in xs.iter().zip(ys).enumerate() {
                diff(program, format!("{path}[{i}]"), x, y, out);
            }
            return;
        }
        _ => {}
    }
    out.push(format!("{path} = {}", value(program, after)));
}

/// A trace, numbered, each state after the first as the updates that reached it, under the
/// action that took them when the engine knows it.
pub fn trace(program: &Program, trace: &[State]) -> String {
    let fields = program.state_fields();
    let mut out = String::new();
    let width = trace.len().to_string().len();
    let blank = " ".repeat(width);
    for (i, state) in trace.iter().enumerate() {
        let action = match state.action {
            Some(id) => Some(call(program, &program.actions[id.index()].name, &state.args)),
            None if i == 0 => Some(program.actions[program.model.init.index()].name.clone()),
            None => None,
        };
        let mut updates = Vec::new();
        for (j, (f, v)) in fields.iter().zip(&state.fields).enumerate() {
            match i.checked_sub(1).and_then(|before| trace[before].fields.get(j)) {
                Some(before) => diff(program, f.name.clone(), before, v, &mut updates),
                None => updates.push(format!("{} = {}", f.name, value(program, v))),
            }
        }
        if updates.is_empty() {
            updates.push("(no change)".to_owned());
        }
        let number = format!("{:>width$}", i + 1);
        let mut updates = updates.into_iter();
        match action {
            Some(action) => {
                let _ = writeln!(out, "  {number}  {action}");
            }
            None => {
                let _ = writeln!(out, "  {number}    {}", updates.next().unwrap_or_default());
            }
        }
        for update in updates {
            let _ = writeln!(out, "  {blank}    {update}");
        }
    }
    out
}

/// The last line of a behavior that loops: `  back to 2: State::execute(n3)`, with `to`
/// counted from 0 and shown from 1, as the trace's states are.
pub fn back(program: &Program, to: usize, step: &State) -> String {
    let action = match step.action {
        Some(id) => call(program, &program.actions[id.index()].name, &step.args),
        None => "a step".to_owned(),
    };
    format!("  back to {}: {action}\n", to + 1)
}

/// An action with its arguments after `self`: `State::read(a)`, or `State::next` without any.
fn call(program: &Program, name: &str, args: &[Value]) -> String {
    if args.is_empty() {
        return name.to_owned();
    }
    let args: Vec<String> = args.iter().map(|a| value(program, a)).collect();
    format!("{name}({})", args.join(", "))
}

/// `n` with its thousands separated: 1,146.
pub fn count(n: u64) -> String {
    let digits = n.to_string();
    let mut out = String::new();
    for (i, c) in digits.chars().enumerate() {
        if i > 0 && (digits.len() - i).is_multiple_of(3) {
            out.push(',');
        }
        out.push(c);
    }
    out
}

pub fn seconds(elapsed: Duration) -> String {
    format!("{:.2} s", elapsed.as_secs_f64())
}

/// How much a check explored: `288 distinct states, depth 11 (1,146 generated in 0.01 s)`.
pub fn summary(report: &Report) -> String {
    let ok = if report.outcome == Outcome::Ok { "ok, " } else { "" };
    format!(
        "{ok}{} distinct states, depth {} ({} generated in {})",
        count(report.distinct),
        report.depth,
        count(report.generated),
        seconds(report.elapsed)
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn counts_have_thousands_separators() {
        assert_eq!(count(7), "7");
        assert_eq!(count(1146), "1,146");
        assert_eq!(count(16959159), "16,959,159");
        assert_eq!(count(100000), "100,000");
    }
}