spock-cli 0.9.0

A modern, statically typed, natively compiled model checking and proof language
//! `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::{collections::BTreeSet, io::Read as _, process::ExitCode};

use spock_engine::trace::{Matched, Options, Outcome};
use spock_ir::{ActionId, Program, Seen, Step, Trace, TypeDefKind};
use spock_report::{Sources, TraceFile};

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

/// The exit code for a trace that no behavior of the model matches.
const DIVERGES: u8 = 14;
/// The exit code for a trace that conforms to the model but fails a coverage gate.
const COVERAGE: u8 = 16;

#[derive(clap::Args)]
pub struct TraceArgs {
    /// The `.spock` file.
    spec: String,
    /// The trace: JSON lines, a behavior as `spock check` prints one, or `-` for stdin.
    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>,
    /// Fail unless every leaf action reachable from `next` is exercised by the trace.
    #[arg(long)]
    require_all_actions: bool,
    /// Require specific action names (`State::foo` or `foo`, comma-separated or repeatable).
    #[arg(long, value_name = "ACTION", value_delimiter = ',')]
    require_actions: Vec<String>,
    /// Fail unless every `State` field is observed at least once in the trace.
    #[arg(long)]
    require_all_fields: bool,
    /// Require specific `State` field names (comma-separated or repeatable).
    #[arg(long, value_name = "FIELD", value_delimiter = ',')]
    require_fields: Vec<String>,
    /// Fail if pure-stutter observations exceed N.
    #[arg(long, value_name = "N")]
    max_stutters: Option<usize>,
    /// Print the report as JSON (RFD0003).
    #[arg(long)]
    json: bool,
}

pub fn run(args: TraceArgs) -> ExitCode {
    let spec = args.spec.as_str();
    let model = args.model.as_deref();
    let from_stdin = args.trace == "-";
    let path = if from_stdin { "<stdin>" } else { 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 = if from_stdin {
        let mut buf = String::new();
        match std::io::stdin().read_to_string(&mut buf) {
            Ok(_) => buf,
            Err(err) => return cannot(&err.to_string(), None, &format!("{path}: {err}\n")),
        }
    } else {
        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 coverage = match &report.outcome {
        Outcome::Matches { behavior } => Some(compute_coverage(&program, &trace, behavior)),
        _ => None,
    };
    let coverage_errors =
        coverage.as_ref().map_or_else(Vec::new, |cov| check_coverage_gates(cov, &args));
    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,
                coverage.as_ref(),
                &coverage_errors,
            )
        );
    } else {
        print!("{}", spock_report::trace(&sources, &file, &report));
        if !coverage_errors.is_empty() {
            println!("error: trace coverage failed:");
            for err in &coverage_errors {
                println!("  {err}");
            }
        }
    }
    ExitCode::from(match report.outcome {
        Outcome::Matches { .. } if !coverage_errors.is_empty() => COVERAGE,
        Outcome::Matches { .. } => 0,
        Outcome::InvariantViolated { .. } => 12,
        Outcome::PropertyViolated { .. } => 13,
        Outcome::Diverges { .. } => DIVERGES,
        Outcome::Error { .. } => SPEC_ERROR,
    })
}

fn compute_coverage(program: &Program, trace: &Trace, behavior: &[Matched]) -> TraceCoverage {
    let mut actions = BTreeSet::new();
    let mut stutters = 0usize;
    for (idx, step) in behavior.iter().enumerate() {
        if let Some(id) = step.state.action {
            actions.insert(program.actions[id.index()].name.clone());
        } else if idx > 0 {
            stutters += 1;
        }
    }
    let leaf_actions = leaf_spec_actions(program);
    let missing_actions = leaf_actions.iter().filter(|a| !actions.contains(*a)).cloned().collect();
    let spec_fields: Vec<String> = match &program.types[program.state.index()].kind {
        TypeDefKind::Struct(fields) => fields.iter().map(|f| f.name.clone()).collect(),
        _ => Vec::new(),
    };
    let mut observed = BTreeSet::new();
    for ev in &trace.events {
        match &ev.state {
            Seen::Is(_) => observed.extend(spec_fields.iter().cloned()),
            Seen::Fields(fields) => {
                for (i, seen) in fields.iter().enumerate() {
                    if !matches!(seen, Seen::Unknown)
                        && let Some(name) = spec_fields.get(i)
                    {
                        observed.insert(name.clone());
                    }
                }
            }
            _ => {}
        }
    }
    let missing_fields = spec_fields.iter().filter(|f| !observed.contains(*f)).cloned().collect();
    TraceCoverage {
        actions: actions.into_iter().collect(),
        leaf_actions,
        missing_actions,
        observed_fields: observed.into_iter().collect(),
        spec_fields,
        missing_fields,
        stutters,
    }
}

fn leaf_spec_actions(program: &Program) -> Vec<String> {
    fn walk_binds(step: &Step, out: &mut Vec<ActionId>) {
        match step {
            Step::Yield(_) | Step::Stop => {}
            Step::Let { then, .. } | Step::OneOf { then, .. } => walk_binds(then, out),
            Step::Any(branches) => {
                for b in branches {
                    walk_binds(b, out);
                }
            }
            Step::If { then, otherwise, .. } => {
                walk_binds(then, out);
                walk_binds(otherwise, out);
            }
            Step::Match { arms, .. } => {
                for (_, arm) in arms {
                    walk_binds(arm, out);
                }
            }
            Step::Bind { action, then, .. } => {
                out.push(*action);
                walk_binds(then, out);
            }
        }
    }

    fn collect_leaves(
        program: &Program,
        id: ActionId,
        visiting: &mut BTreeSet<u32>,
        leaves: &mut BTreeSet<u32>,
    ) {
        if !visiting.insert(id.0) {
            return;
        }
        let mut children = Vec::new();
        walk_binds(&program.actions[id.index()].body, &mut children);
        if children.is_empty() {
            leaves.insert(id.0);
        } else {
            for child in children {
                collect_leaves(program, child, visiting, leaves);
            }
        }
        visiting.remove(&id.0);
    }

    let mut visiting = BTreeSet::new();
    let mut leaves = BTreeSet::new();
    collect_leaves(program, program.model.next, &mut visiting, &mut leaves);
    leaves.into_iter().map(|id| program.actions[id as usize].name.clone()).collect()
}

fn action_matches(observed: &[String], req: &str) -> bool {
    if observed.iter().any(|name| name == req) {
        return true;
    }
    let suffix = format!("::{req}");
    observed.iter().any(|name| name.ends_with(&suffix))
}

fn check_coverage_gates(cov: &TraceCoverage, args: &TraceArgs) -> Vec<String> {
    let mut errors = Vec::new();
    let mut missing_actions = Vec::new();
    if args.require_all_actions {
        for a in &cov.missing_actions {
            if !missing_actions.contains(a) {
                missing_actions.push(a.clone());
            }
        }
    }
    for wanted in &args.require_actions {
        if !action_matches(&cov.actions, wanted) && !missing_actions.contains(wanted) {
            missing_actions.push(wanted.clone());
        }
    }
    if !missing_actions.is_empty() {
        let covered = cov.leaf_actions.len().saturating_sub(cov.missing_actions.len());
        errors.push(format!(
            "actions covered {covered}/{}: missing {}",
            cov.leaf_actions.len(),
            missing_actions.join(", ")
        ));
    }

    let mut missing_fields = Vec::new();
    if args.require_all_fields {
        for f in &cov.missing_fields {
            if !missing_fields.contains(f) {
                missing_fields.push(f.clone());
            }
        }
    }
    for wanted in &args.require_fields {
        if !cov.observed_fields.iter().any(|f| f == wanted) && !missing_fields.contains(wanted) {
            missing_fields.push(wanted.clone());
        }
    }
    if !missing_fields.is_empty() {
        let covered = cov.spec_fields.len().saturating_sub(cov.missing_fields.len());
        errors.push(format!(
            "state fields observed {covered}/{}: never observed {}",
            cov.spec_fields.len(),
            missing_fields.join(", ")
        ));
    }

    if let Some(max) = args.max_stutters
        && cov.stutters > max
    {
        errors.push(format!("stutters {} exceeded --max-stutters {max}", cov.stutters));
    }
    errors
}