spock-cli 0.2.0

A model checker for specs that read like Rust: TLA's logic of actions, checked on every core in machine code
//! `spock trace`: a trace of a system's run, checked against a model (RFD0008), and what the
//! check found, for people or as RFD0003's JSON report.

use std::process::ExitCode;

use spock_engine::trace::{Options, Outcome};
use spock_report::{Sources, TraceFile};

use crate::{SPEC_ERROR, in_color, json, load, location};

/// The exit code for a trace that no behavior of the model matches.
const DIVERGES: u8 = 14;

#[derive(clap::Args)]
pub struct TraceArgs {
    /// The `.spock` file.
    spec: String,
    /// The trace: JSON lines, or a behavior as `spock check` prints one.
    trace: String,
    /// The model to check the trace against, which a file with one model needn't name.
    #[arg(long, value_name = "NAME")]
    model: Option<String>,
    /// Stop with an error when the run could be in more than N states at one of the trace's
    /// [default: 1000000].
    #[arg(long, value_name = "N", value_parser = clap::value_parser!(u64).range(1..))]
    max_states: Option<u64>,
    /// Print the report as JSON (RFD0003).
    #[arg(long)]
    json: bool,
}

pub fn run(args: TraceArgs) -> ExitCode {
    let (spec, model, path) = (args.spec.as_str(), args.model.as_deref(), args.trace.as_str());
    let cannot = |message: &str, location: Option<json::Location>, text: &str| {
        if args.json {
            println!("{}", json::trace_error(spec, model, path, message, location));
        }
        eprint!("{text}");
        ExitCode::from(SPEC_ERROR)
    };
    let (source, program) = match load(spec, model) {
        Ok(loaded) => loaded,
        Err(not) => return cannot(&not.message, not.location, &not.text),
    };
    let text = match std::fs::read_to_string(path) {
        Ok(text) => text,
        Err(err) => return cannot(&err.to_string(), None, &format!("{path}: {err}\n")),
    };
    let trace = match spock_types::trace(&program, path, &text) {
        Ok(trace) => trace,
        Err(diagnostics) => {
            let out =
                spock_report::diagnostics(&diagnostics, path, &text, in_color(&std::io::stderr()));
            let first = &diagnostics[0];
            return cannot(&first.message, Some(location(path, &text, first.span)), &out);
        }
    };
    let defaults = Options::default();
    let options =
        Options { max_states: args.max_states.map_or(defaults.max_states, |n| n as usize) };
    let report = spock_engine::validate(&program, &trace, &options);
    let color = in_color(&std::io::stdout());
    let sources = Sources { spec, source: &source, program: &program, color };
    let file = TraceFile { path, text: &text, trace: &trace };
    if args.json {
        let location = match &report.outcome {
            Outcome::Error { span: Some(span), .. } => crate::span_location(&sources, *span),
            Outcome::Error { span: None, at: Some(at), .. } => {
                Some(location(path, &text, file.line_span(*at)))
            }
            _ => None,
        };
        let lines: Vec<u32> = trace.events.iter().map(|e| e.line).collect();
        println!("{}", json::trace_report(spec, path, &program, &lines, &report, location));
    } else {
        print!("{}", spock_report::trace(&sources, &file, &report));
    }
    ExitCode::from(match report.outcome {
        Outcome::Matches { .. } => 0,
        Outcome::Diverges { .. } => DIVERGES,
        Outcome::Error { .. } => SPEC_ERROR,
    })
}