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
//! The report `spock check --json` prints (RFD0003, The report). Objects keep declared order:
//! a state's fields are in the order the state struct declares them.

use serde::{Serialize, Serializer, ser::SerializeMap as _};
use spock_engine::{Ending, Outcome, Report, State, Value};
use spock_ir::{Field, Program, TypeDefKind};

use crate::show::positional;

/// Where an error is: a file, and a 1-based line and column.
#[derive(Serialize)]
pub struct Location {
    pub file: String,
    pub line: usize,
    pub column: usize,
}

#[derive(Serialize)]
struct Json<'a> {
    version: u32,
    spec: &'a str,
    model: Option<&'a str>,
    outcome: Kind<'a>,
    distinct: u64,
    generated: u64,
    depth: u32,
    seconds: f64,
    unchecked: &'a [String],
    trace: Vec<Step<'a>>,
    /// For a temporal property's violation by a behavior: the index in `trace` of the state
    /// the last state steps back to forever.
    #[serde(skip_serializing_if = "Option::is_none")]
    back_to: Option<usize>,
    /// The action and arguments of that step, unless it is a stutter.
    #[serde(skip_serializing_if = "Option::is_none")]
    back_step: Option<BackStep<'a>>,
}

#[derive(Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
enum Kind<'a> {
    Ok,
    /// TLA+'s `ASSUME`.
    Assumption {
        name: &'a str,
    },
    Invariant {
        name: &'a str,
    },
    StepProperty {
        name: &'a str,
    },
    /// A temporal property.
    Property {
        name: &'a str,
    },
    Deadlock,
    Error {
        message: &'a str,
        location: Option<Location>,
    },
}

/// The report of a check that ran.
pub fn report(
    spec: &str,
    program: &Program,
    report: &Report,
    location: Option<Location>,
) -> String {
    let outcome = match &report.outcome {
        Outcome::Ok => Kind::Ok,
        Outcome::AssumptionViolated { name } => Kind::Assumption { name },
        Outcome::InvariantViolated { name, .. } => Kind::Invariant { name },
        Outcome::PropertyViolated { name, .. } => Kind::StepProperty { name },
        Outcome::TemporalViolated { name, .. } => Kind::Property { name },
        Outcome::Deadlock { .. } => Kind::Deadlock,
        Outcome::Error { message, .. } => Kind::Error { message, location },
    };
    let (back_to, back_step) = match &report.outcome {
        Outcome::TemporalViolated { trace, ending, .. } => {
            let step = match ending {
                Ending::Back { step, .. } => Some(BackStep { program, state: step }),
                Ending::Prefix | Ending::Stutters => None,
            };
            (ending.back_to(trace.len()), step)
        }
        _ => (None, None),
    };
    let json = Json {
        version: 1,
        spec,
        model: Some(&program.model.name),
        outcome,
        distinct: report.distinct,
        generated: report.generated,
        depth: report.depth,
        seconds: report.elapsed.as_secs_f64(),
        unchecked: &report.unchecked,
        trace: report.outcome.trace().iter().map(|state| Step { program, state }).collect(),
        back_to,
        back_step,
    };
    to_string(&json)
}

/// One line, or indented for a terminal.
fn to_string(json: &impl Serialize) -> String {
    use std::io::IsTerminal as _;
    let text = if std::io::stdout().is_terminal() {
        serde_json::to_string_pretty(json)
    } else {
        serde_json::to_string(json)
    };
    text.expect("a report is JSON")
}

/// The report of a check that couldn't run, since the spec has an error.
pub fn spec_error(
    spec: &str,
    model: Option<&str>,
    message: &str,
    location: Option<Location>,
) -> String {
    let json = Json {
        version: 1,
        spec,
        model,
        outcome: Kind::Error { message, location },
        distinct: 0,
        generated: 0,
        depth: 0,
        seconds: 0.0,
        unchecked: &[],
        trace: Vec::new(),
        back_to: None,
        back_step: None,
    };
    to_string(&json)
}

/// The step back of a behavior that loops: its action and arguments.
struct BackStep<'a> {
    program: &'a Program,
    state: &'a State,
}

impl Serialize for BackStep<'_> {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        let program = self.program;
        let action = self.state.action.map(|id| program.actions[id.index()].name.as_str());
        let args: Vec<JsonValue> = each(program, &self.state.args).collect();
        let mut map = s.serialize_map(Some(2))?;
        map.serialize_entry("action", &action)?;
        map.serialize_entry("args", &args)?;
        map.end()
    }
}

/// A state of a trace, and the action that reached it.
struct Step<'a> {
    program: &'a Program,
    state: &'a State,
}

impl Serialize for Step<'_> {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        let program = self.program;
        let action = self.state.action.map(|id| program.actions[id.index()].name.as_str());
        let args: Vec<JsonValue> = each(program, &self.state.args).collect();
        let mut map = s.serialize_map(Some(3))?;
        map.serialize_entry("action", &action)?;
        map.serialize_entry("args", &args)?;
        let fields = Fields {
            program: self.program,
            fields: self.program.state_fields(),
            values: &self.state.fields,
        };
        map.serialize_entry("state", &fields)?;
        map.end()
    }
}

struct Fields<'a> {
    program: &'a Program,
    fields: &'a [Field],
    values: &'a [Value],
}

impl Serialize for Fields<'_> {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        let mut map = s.serialize_map(Some(self.values.len()))?;
        for (f, v) in self.fields.iter().zip(self.values) {
            map.serialize_entry(&f.name, &JsonValue { program: self.program, value: v })?;
        }
        map.end()
    }
}

/// A value as serde writes the Rust type it would be: a struct is an object, a tuple, a set or
/// a sequence an array, a map an array of `[key, value]`, an atom or a constructor without
/// fields its name, and a constructor with fields `{ "Name": payload }`.
struct JsonValue<'a> {
    program: &'a Program,
    value: &'a Value,
}

impl Serialize for JsonValue<'_> {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        let program = self.program;
        match self.value {
            Value::Bool(b) => s.serialize_bool(*b),
            Value::Int(n) => s.serialize_i64(*n),
            Value::Atom(ty, index) => match &program.def(*ty).kind {
                TypeDefKind::Atoms(atoms) => s.serialize_str(&atoms[*index as usize]),
                _ => s.serialize_u32(*index),
            },
            Value::Struct(ty, values) => match &program.def(*ty).kind {
                TypeDefKind::Struct(fields) => Fields { program, fields, values }.serialize(s),
                _ => s.collect_seq(each(program, values)),
            },
            Value::Ctor(ty, index, values) => {
                let TypeDefKind::Variant(ctors) = &program.def(*ty).kind else {
                    return s.collect_seq(each(program, values));
                };
                let ctor = &ctors[*index as usize];
                if values.is_empty() {
                    return s.serialize_str(&ctor.name);
                }
                let mut map = s.serialize_map(Some(1))?;
                match values.as_slice() {
                    [value] if positional(&ctor.fields) => {
                        map.serialize_entry(&ctor.name, &JsonValue { program, value })?
                    }
                    _ if positional(&ctor.fields) => {
                        map.serialize_entry(&ctor.name, &each(program, values).collect::<Vec<_>>())?
                    }
                    _ => map.serialize_entry(
                        &ctor.name,
                        &Fields { program, fields: &ctor.fields, values },
                    )?,
                }
                map.end()
            }
            Value::Tuple(items) | Value::Set(items) | Value::Seq(items) => {
                s.collect_seq(each(program, items))
            }
            Value::Map(pairs) => {
                s.collect_seq(pairs.iter().map(|(k, v)| {
                    (JsonValue { program, value: k }, JsonValue { program, value: v })
                }))
            }
        }
    }
}

fn each<'a>(program: &'a Program, values: &'a [Value]) -> impl Iterator<Item = JsonValue<'a>> {
    values.iter().map(move |value| JsonValue { program, value })
}