spock-cli 0.4.0

A model checker for specs that read like Rust: TLA's logic of actions, checked on every core in machine code
//! The `spock` command.
//!
//! `spock check X.spock [--model NAME] [--workers N] [--max-distinct N] [--json]` checks a model
//! of a `.spock` file with the compiled engine (RFD0001, RFD0004), and prints what it found:
//! for people, or as RFD0003's JSON report. `--ir` prints the model's IR instead, for working on
//! the engine. The exit codes are TLC's: 0 when nothing is violated, 10 a false assumption, 11
//! a deadlock, 12 an invariant, 13 a property, 150 an error in the spec or while checking it.
//!
//! `spock trace X.spock RUN [--model NAME] [--json]` checks a trace of a system's run against
//! the model (RFD0008): whether some behavior of the model matches it, and if none does, the
//! first state of the trace no behavior explains, and why. It exits 0 when one matches, 14
//! when none does, and 150 for an error in the spec or the trace, or while checking it.
//!
//! `spock skill` prints spock's skill for coding agents, `SKILL.md`: how to write, check and
//! trace specs, with when to use them.
//!
//! A check is answered from the cache when the same build checked the same model with the same
//! options before (RFD0002): the output and exit code are the same, and a line on stderr says
//! so. `--no-cache` checks without it, and `--cache-dir DIR` (or `SPOCK_CACHE_DIR`) moves
//! it from the user's cache directory.

mod json;
mod trace;

use std::{path::PathBuf, process::ExitCode};

use clap::Parser as _;
use spock_check::Cache;
use spock_engine::{Options, Outcome};
use spock_ir::Program;
use spock_report::Sources;
use spock_syntax::{Span, line_col};

/// The exit code for an error in the spec, as TLC's.
const SPEC_ERROR: u8 = 150;

/// spock's skill for coding agents, which `spock skill` prints.
const SKILL: &str = include_str!("../SKILL.md");

/// Spock checks models of `.spock` files: TLA's logic of actions, in a small Rust.
#[derive(clap::Parser)]
#[command(name = "spock", version)]
enum Command {
    /// Check a model of a `.spock` file.
    ///
    /// The exit code is TLC's: 0 when nothing is violated, 10 a false assumption, 11 a
    /// deadlock, 12 an invariant, 13 a property, 150 an error in the spec or while checking it.
    /// A check is answered from the cache when the same build checked the same model with the
    /// same options before (RFD0002).
    Check(CheckArgs),
    /// Check a trace of a system's run against a model of a `.spock` file (RFD0008).
    ///
    /// The trace is JSON lines, as `spock check --json` writes a behavior's steps, or a
    /// behavior as `spock check` prints one. What a state of the trace leaves out is unknown,
    /// and so is `_` (`null` in JSON). The exit code is 0 when a behavior of the model matches
    /// the trace, 14 when none does, and 150 for an error in the spec or the trace, or while
    /// checking it.
    Trace(trace::TraceArgs),
    /// Print spock's skill for coding agents: how to write, check and trace specs.
    ///
    /// It is a SKILL.md, whose name and description tell an agent when to read it. To install
    /// it: mkdir -p ~/.agents/skills/spock && spock skill > ~/.agents/skills/spock/SKILL.md
    Skill,
}

#[derive(clap::Args)]
struct CheckArgs {
    /// The `.spock` file.
    spec: String,
    /// The model to check, which a file with one model needn't name.
    #[arg(long, value_name = "NAME")]
    model: Option<String>,
    /// Search with N threads [default: one per core].
    #[arg(long, value_name = "N", value_parser = clap::value_parser!(u64).range(1..))]
    workers: Option<u64>,
    /// Stop with an error once N distinct states are found.
    #[arg(long, value_name = "N")]
    max_distinct: Option<u64>,
    /// Print the report as JSON (RFD0003).
    #[arg(long)]
    json: bool,
    /// Print the model's IR instead of checking it.
    #[arg(long)]
    ir: bool,
    /// Check without the cache.
    #[arg(long)]
    no_cache: bool,
    /// Keep the cache in DIR [default: $SPOCK_CACHE_DIR, else the user's cache directory].
    #[arg(long, value_name = "DIR")]
    cache_dir: Option<PathBuf>,
}

fn main() -> ExitCode {
    match Command::parse() {
        Command::Check(args) => check(args),
        Command::Trace(args) => trace::run(args),
        Command::Skill => {
            print!("{SKILL}");
            ExitCode::SUCCESS
        }
    }
}

/// A spec that didn't load: what to print for people, and the first error, for a report.
struct NotLoaded {
    /// Every error, rendered.
    text: String,
    message: String,
    location: Option<json::Location>,
}

/// The spec at `spec`, and its `model` (or its only model) as a program.
fn load(spec: &str, model: Option<&str>) -> Result<(String, Program), NotLoaded> {
    let source = std::fs::read_to_string(spec).map_err(|err| NotLoaded {
        text: format!("{spec}: {err}\n"),
        message: err.to_string(),
        location: None,
    })?;
    let diagnostics = match spock_types::load_all(spec, &source, model) {
        Ok(program) => return Ok((source, program)),
        Err(diagnostics) => diagnostics,
    };
    let text = spock_report::diagnostics(&diagnostics, spec, &source, in_color(&std::io::stderr()));
    // A report has one outcome, the first error; the text has every one.
    let first = &diagnostics[0];
    let location = Some(match &first.file {
        Some(path) if path != spec => {
            location(path, &std::fs::read_to_string(path).unwrap_or_default(), first.span)
        }
        _ => location(spec, &source, first.span),
    });
    Err(NotLoaded { text, message: first.message.clone(), location })
}

fn check(args: CheckArgs) -> ExitCode {
    let defaults = Options::default();
    let options = Options {
        workers: args.workers.map_or(defaults.workers, |n| n as usize),
        progress: true,
        max_distinct: args.max_distinct,
    };
    let cache = if args.no_cache { None } else { args.cache_dir.or_else(Cache::default_path) };
    let spec = args.spec.as_str();
    let (source, program) = match load(spec, args.model.as_deref()) {
        Ok(loaded) => loaded,
        Err(not) => {
            if args.json {
                let json =
                    json::spec_error(spec, args.model.as_deref(), &not.message, not.location);
                println!("{json}");
            }
            eprint!("{}", not.text);
            return ExitCode::from(SPEC_ERROR);
        }
    };
    if args.ir {
        println!("{program:#?}");
        return ExitCode::SUCCESS;
    }
    let cache = cache.as_deref().and_then(Cache::open);
    let checked = spock_check::check(&program, &options, cache.as_ref());
    if let Some(note) = checked.source.note() {
        eprintln!("spock: {note}");
    }
    let report = checked.report;
    let color = in_color(&std::io::stdout());
    let sources = Sources { spec, source: &source, program: &program, color };
    if args.json {
        let location = match &report.outcome {
            Outcome::Error { span: Some(span), .. } => span_location(&sources, *span),
            _ => None,
        };
        println!("{}", json::report(spec, &program, &report, location));
    } else {
        print!("{}", spock_report::check(&sources, &report));
    }
    ExitCode::from(u8::try_from(report.outcome.exit_code()).unwrap_or(SPEC_ERROR))
}

/// Where `span` is in the spec or a file it uses, for a report.
fn span_location(sources: &Sources, span: spock_ir::Span) -> Option<json::Location> {
    let (path, source) = sources.source(span)?;
    Some(location(&path, &source, Span { lo: span.lo, hi: span.hi }))
}

/// Whether to print to `stream` in color: when it's a terminal, unless `NO_COLOR` is set.
fn in_color(stream: &impl std::io::IsTerminal) -> bool {
    stream.is_terminal() && std::env::var_os("NO_COLOR").is_none()
}

fn location(path: &str, source: &str, span: Span) -> json::Location {
    let (line, column) = line_col(source, span.lo);
    json::Location { file: path.to_owned(), line, column }
}