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 `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.
//!
//! 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 show;

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

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

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

/// 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),
}

#[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),
    }
}

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 = match std::fs::read_to_string(spec) {
        Ok(source) => source,
        Err(err) => {
            let message = err.to_string();
            if args.json {
                println!("{}", json::spec_error(spec, args.model.as_deref(), &message, None));
            }
            eprintln!("{spec}: {message}");
            return ExitCode::from(SPEC_ERROR);
        }
    };
    let program = match spock_types::load_all(spec, &source, args.model.as_deref()) {
        Ok(program) => program,
        Err(diagnostics) => {
            // An error is in the file checked, or in a file it uses.
            let file_of = |d: &Diagnostic| -> (String, String) {
                match &d.file {
                    Some(path) => {
                        let text = std::fs::read_to_string(path).unwrap_or_default();
                        (path.clone(), text)
                    }
                    None => (spec.to_owned(), source.clone()),
                }
            };
            // The report has one outcome, the first error; the text has every one.
            if let (true, Some(first)) = (args.json, diagnostics.first()) {
                let (path, text) = file_of(first);
                let location = location(&path, &text, first.span);
                let json =
                    json::spec_error(spec, args.model.as_deref(), &first.message, Some(location));
                println!("{json}");
            }
            let color = in_color(&std::io::stderr());
            let rendered: Vec<String> = diagnostics
                .iter()
                .map(|d| {
                    let (path, text) = file_of(d);
                    if color { d.render_in_color(&path, &text) } else { d.render(&path, &text) }
                })
                .collect();
            eprint!("{}", rendered.join("\n"));
            if diagnostics.len() > 1 {
                eprintln!("\n{} errors", diagnostics.len());
            }
            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 files = Files { spec, source: &source, program: &program, color };
    if args.json {
        let location = match &report.outcome {
            Outcome::Error { span: Some(span), .. } => files.location(*span),
            _ => None,
        };
        println!("{}", json::report(spec, &program, &report, location));
    } else {
        print!("{}", text(&files, &report));
    }
    ExitCode::from(u8::try_from(report.outcome.exit_code()).unwrap_or(SPEC_ERROR))
}

/// The source of each file a program's spans point into.
struct Files<'a> {
    spec: &'a str,
    source: &'a str,
    program: &'a Program,
    /// Whether errors print in a terminal's colors.
    color: bool,
}

impl Files<'_> {
    fn source(&self, span: spock_ir::Span) -> Option<(String, String)> {
        let path = self.program.files.get(span.file as usize)?;
        if path == self.spec {
            return Some((path.clone(), self.source.to_owned()));
        }
        Some((path.clone(), std::fs::read_to_string(path).ok()?))
    }

    fn location(&self, span: spock_ir::Span) -> Option<json::Location> {
        let (path, source) = self.source(span)?;
        Some(location(&path, &source, Span { lo: span.lo, hi: span.hi }))
    }

    /// `error: {message}`, and where, if `span` says.
    fn error(&self, message: String, span: Option<spock_ir::Span>) -> String {
        match span.and_then(|span| Some((span, self.source(span)?))) {
            Some((span, (path, source))) => {
                let diagnostic = Diagnostic::new(Span { lo: span.lo, hi: span.hi }, message);
                match self.color {
                    true => diagnostic.render_in_color(&path, &source),
                    false => diagnostic.render(&path, &source),
                }
            }
            None => format!("error: {message}\n"),
        }
    }

    /// Where the assumption, invariant or property `name` is declared: a function's name in its
    /// declaration, a temporal property's declaration, or for a field's range check,
    /// `State.x: 0..=N - 1`, the field.
    fn function(&self, name: &str) -> Option<spock_ir::Span> {
        let Some(function) = self.program.fns.iter().find(|f| f.name == name) else {
            // A part of a temporal property is checked under the property's name.
            let properties = &self.program.model.properties;
            if let Some(property) = properties.iter().find(|p| p.name == name) {
                return Some(property.span);
            }
            let (field, _) = name.split_once(": ")?;
            let (state, field) = field.split_once('.')?;
            if state != self.program.def(self.program.state).name {
                return None;
            }
            return Some(self.program.state_fields().iter().find(|f| f.name == field)?.span);
        };
        let span = function.span;
        let short = name.rsplit("::").next()?;
        let (_, source) = self.source(span)?;
        let declaration = source.get(span.lo as usize..span.hi as usize)?;
        match declaration.find(&format!("fn {short}")) {
            Some(at) => {
                let lo = span.lo + at as u32 + 3;
                Some(spock_ir::Span { lo, hi: lo + short.len() as u32, ..span })
            }
            None => Some(span),
        }
    }
}

/// 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 }
}

/// The report for people.
fn text(files: &Files, report: &Report) -> String {
    let program = files.program;
    let model = &program.model.name;
    let behavior = |what: &str, trace: &[spock_engine::State]| {
        let states =
            if trace.len() == 1 { "1 state".to_owned() } else { format!("{} states", trace.len()) };
        format!("{what}, {states}:\n{}", show::trace(program, trace))
    };
    let mut out = match &report.outcome {
        Outcome::Ok => String::new(),
        Outcome::AssumptionViolated { name } => {
            files.error(format!("assumption {name} is false"), files.function(name))
        }
        Outcome::InvariantViolated { name, trace } => {
            files.error(format!("invariant {name} is violated"), files.function(name))
                + &behavior("a shortest behavior to a state that violates it", trace)
        }
        Outcome::PropertyViolated { name, trace } => {
            files.error(format!("step property {name} is violated"), files.function(name))
                + &behavior("a shortest behavior whose last step violates it", trace)
        }
        Outcome::TemporalViolated { name, trace, ending } => {
            let then = match ending {
                Ending::Prefix => String::new(),
                Ending::Stutters => ", then stutters forever".to_owned(),
                Ending::Back { to, .. } => format!(", then back to state {} forever", to + 1),
            };
            let back = match ending {
                Ending::Back { to, step } => show::back(program, *to, step),
                Ending::Prefix | Ending::Stutters => String::new(),
            };
            let states = if trace.len() == 1 {
                "1 state".to_owned()
            } else {
                format!("{} states", trace.len())
            };
            files.error(format!("temporal property {name} is violated"), files.function(name))
                + &format!(
                    "a behavior that violates it, {states}{then}:\n{}{back}",
                    show::trace(program, trace)
                )
        }
        Outcome::Deadlock { trace } => {
            files.error("deadlock".to_owned(), None)
                + &behavior("a shortest behavior to a state with no successor", trace)
        }
        Outcome::Error { message, span, trace } => {
            let mut out = files.error(message.clone(), *span);
            if !trace.is_empty() {
                out += &behavior("while exploring the last state of", trace);
            }
            out
        }
    };
    out += &format!("{model}: {}\n", show::summary(report));
    if !report.unchecked.is_empty() {
        out += &format!(
            "warning: the check stopped before liveness, so it didn't check all of {}\n",
            report.unchecked.join(", ")
        );
    }
    out
}