vers3 0.2.0

Explicit-state model checking library
Documentation
// SPDX-License-Identifier: Apache-2.0
// Copyright (C) 2026, Marco Elver <me@marcoelver.com>

//! Report generation.
//!
//! Output is coloured with ANSI escapes only when both stdout and stderr are
//! terminals and the `NO_COLOR` environment variable is unset or empty, so
//! redirected or piped output stays plain text.

use std::fmt;
use std::io::IsTerminal;
use std::process::ExitCode;
use std::sync::OnceLock;

use crate::search::{Counterexample, Stats, TraceEvidence};
use crate::ts::{CheckerError, State};

// --- Colours -----------------------------------------------------------------

/// An ANSI text style. Its `Display` writes the escape sequence when colour is
/// enabled (see the [module docs](self)) and nothing otherwise.
#[derive(Clone, Copy, Debug)]
pub struct Style(&'static str);

impl fmt::Display for Style {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        static ENABLED: OnceLock<bool> = OnceLock::new();
        let enabled = *ENABLED.get_or_init(|| {
            color_wanted(
                std::env::var_os("NO_COLOR"),
                std::io::stdout().is_terminal(),
                std::io::stderr().is_terminal(),
            )
        });
        if enabled { f.write_str(self.0) } else { Ok(()) }
    }
}

// Both streams must be terminals: the decision is global, so it must not emit
// escapes into whichever of them is redirected.
fn color_wanted(no_color: Option<std::ffi::OsString>, stdout_tty: bool, stderr_tty: bool) -> bool {
    no_color.is_none_or(|v| v.is_empty()) && stdout_tty && stderr_tty
}

/// Reset all attributes.
pub const RST: Style = Style("\x1b[0m");

/// Red text.
pub const RED: Style = Style("\x1b[0;31m");
/// Green text.
pub const GRN: Style = Style("\x1b[0;32m");
/// Yellow text.
pub const YLW: Style = Style("\x1b[0;33m");
/// Blue text.
pub const BLU: Style = Style("\x1b[0;34m");
/// Purple text.
pub const PUR: Style = Style("\x1b[0;35m");
/// Cyan text.
pub const CYN: Style = Style("\x1b[0;36m");

/// Bold red text.
pub const BRED: Style = Style("\x1b[1;31m");
/// Bold green text.
pub const BGRN: Style = Style("\x1b[1;32m");
/// Bold yellow text.
pub const BYLW: Style = Style("\x1b[1;33m");
/// Bold blue text.
pub const BBLU: Style = Style("\x1b[1;34m");
/// Bold purple text.
pub const BPUR: Style = Style("\x1b[1;35m");
/// Bold cyan text.
pub const BCYN: Style = Style("\x1b[1;36m");

/// Horizontal rule used to frame report headers.
pub const RULE: &str = "═════════════════════════════════════════════════════";

// --- Stats display -----------------------------------------------------------

/// Print search statistics to stdout.
pub fn print_stats<S: State>(stats: &Stats<S>) {
    println!("{BGRN}VERIFIED{RST} — {stats}");
}

// --- Counterexample display --------------------------------------------------

/// Print a counterexample trace to stderr, with per-step state diffs.
///
/// Each step shows the rule that fired and highlights lines in the state
/// `Display` that differ from the previous state.
pub fn print_counterexample<S: State>(cex: &Counterexample<S>) {
    eprintln!();
    eprintln!("{BRED}═══ COUNTEREXAMPLE ══════════════════════════════════{RST}");
    eprintln!("{BRED}Error:{RST} {}", cex.error);
    if let CheckerError::PropertyViolation {
        detail: Some(d), ..
    } = &cex.error
    {
        eprintln!("{BRED}Detail:{RST} {d}");
    }
    eprintln!(
        "{BRED}Search stats:{RST} visited={} queued={}",
        cex.states_visited, cex.states_queued
    );
    eprintln!();

    let (trace, truncated) = match &cex.evidence {
        TraceEvidence::None => {
            eprintln!(
                "{YLW}(no trace available — violation detected at final property check){RST}"
            );
            eprintln!();
            return;
        }
        TraceEvidence::Hashes(ht) => {
            eprintln!(
                "{YLW}Hash trace ({} steps, error state first; with_verbose(true) reconstructs full states):{RST}",
                ht.len().saturating_sub(1)
            );
            for h in ht {
                eprintln!("  {h}");
            }
            eprintln!();
            return;
        }
        TraceEvidence::PartialStates(t) if t.is_empty() => {
            eprintln!("{YLW}(no trace available — replay failed to reconstruct the path){RST}");
            eprintln!();
            return;
        }
        TraceEvidence::States(t) => (t, false),
        TraceEvidence::PartialStates(t) => (t, true),
    };

    eprintln!(
        "{BRED}Trace length:{RST} {} steps",
        trace.len().saturating_sub(1)
    );
    eprintln!();

    for (i, (state, rule_name)) in trace.iter().enumerate() {
        let prev = if i > 0 { Some(&trace[i - 1].0) } else { None };

        eprintln!(
            "{CYN}── Step {i}{RST} {}",
            if rule_name.is_empty() {
                "(initial)".to_owned()
            } else {
                format!("{YLW}via rule:{RST} {BLU}{rule_name}{RST}")
            }
        );

        print_state_diff(state, prev);
        eprintln!();
    }

    if truncated {
        eprintln!(
            "{BYLW}WARNING:{RST} trace is truncated — the steps above do not reach the erroring state."
        );
        eprintln!();
    }

    eprintln!("{BRED}{RULE}{RST}");
    eprintln!();
}

// --- Line diff ---------------------------------------------------------------

/// A single event from a positional line-by-line diff.
///
/// Passed to the callback of [`diff_lines`]. Useful for building custom
/// trace formatters without depending on the printing functions in this module.
#[derive(Debug, PartialEq, Eq)]
pub enum DiffLine<'a> {
    /// Line present in `prev` at this position but absent (or changed) in `current`.
    Removed(&'a str),
    /// Line present in `current` at this position but absent (or changed) in `prev`.
    Added(&'a str),
    /// Line identical at this position in both `prev` and `current`.
    Unchanged(&'a str),
}

/// Compute a positional line-by-line diff between `prev` and `current`,
/// invoking `emit` for each [`DiffLine`] event in order.
///
/// Comparison is positional (line *i* of `prev` vs line *i* of `current`),
/// which correctly handles duplicate line values — unlike a set-membership
/// check, which would miss a removal when the same value still appears
/// elsewhere.
pub fn diff_lines<'a>(
    prev: &'a [String],
    current: &'a [String],
    mut emit: impl FnMut(DiffLine<'a>),
) {
    let n = prev.len().max(current.len());
    for i in 0..n {
        match (
            prev.get(i).map(String::as_str),
            current.get(i).map(String::as_str),
        ) {
            (Some(p), Some(c)) if p == c => emit(DiffLine::Unchanged(p)),
            (Some(p), Some(c)) => {
                emit(DiffLine::Removed(p));
                emit(DiffLine::Added(c));
            }
            (Some(p), None) => emit(DiffLine::Removed(p)),
            (None, Some(c)) => emit(DiffLine::Added(c)),
            (None, None) => unreachable!(),
        }
    }
}

/// Print `state` to stderr, highlighting lines that differ from `prev`.
///
/// Removed lines are shown in red (–), added lines in green (+),
/// unchanged lines without colour.
fn print_state_diff<S: State>(state: &S, prev: Option<&S>) {
    let current_lines: Vec<String> = state.to_string().lines().map(|l| l.to_owned()).collect();
    let prev_lines: Vec<String> = prev
        .map(|p| p.to_string().lines().map(|l| l.to_owned()).collect())
        .unwrap_or_default();
    diff_lines(&prev_lines, &current_lines, |event| match event {
        DiffLine::Removed(line) => eprintln!("{RED}- {line}{RST}"),
        DiffLine::Added(line) => eprintln!("{BGRN}+ {line}{RST}"),
        DiffLine::Unchanged(line) => eprintln!("  {line}"),
    });
}

// --- Main helper -------------------------------------------------------------

/// Report BFS results and return an appropriate exit code.
///
/// On success, prints stats to stdout and returns [`ExitCode::SUCCESS`].
/// On violation, prints the counterexample to stderr and returns
/// [`ExitCode::FAILURE`].
///
/// Idiomatic entry point for model-checker binaries:
///
/// ```
/// use vers3::{TransitionSystem, rule, search::BfsHashing};
///
/// #[derive(Clone, Hash, PartialEq, Eq, Debug)]
/// struct Tick(u8);
/// vers3::display_via_debug!(Tick);
///
/// fn main() -> std::process::ExitCode {
///     let mut ts = TransitionSystem::new();
///     ts.add_rule(rule("tick", |_: &Tick| true, |s: &mut Tick| {
///         s.0 = s.0.wrapping_add(1);
///         true
///     }));
///     vers3::report::main_report(BfsHashing::new().run(vec![Tick(0)], ts))
/// }
/// ```
pub fn main_report<S: State>(result: Result<Stats<S>, Counterexample<S>>) -> ExitCode {
    match result {
        Ok(stats) => {
            print_stats(&stats);
            ExitCode::SUCCESS
        }
        Err(cex) => {
            print_counterexample(&cex);
            ExitCode::FAILURE
        }
    }
}

// -----------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn color_only_on_terminals_without_no_color() {
        assert!(color_wanted(None, true, true));
        assert!(color_wanted(Some("".into()), true, true));
        assert!(!color_wanted(Some("1".into()), true, true));
        assert!(!color_wanted(None, false, true));
        assert!(!color_wanted(None, true, false));
    }

    fn lines(s: &[&str]) -> Vec<String> {
        s.iter().map(|&l| l.to_owned()).collect()
    }

    fn collect_diff<'a>(prev: &'a [String], curr: &'a [String]) -> Vec<DiffLine<'a>> {
        let mut out = vec![];
        diff_lines(prev, curr, |e| out.push(e));
        out
    }

    #[test]
    fn diff_all_unchanged() {
        let p = lines(&["a=0", "b=1"]);
        let c = lines(&["a=0", "b=1"]);
        assert_eq!(
            collect_diff(&p, &c),
            vec![DiffLine::Unchanged("a=0"), DiffLine::Unchanged("b=1")]
        );
    }

    #[test]
    fn diff_changed_line() {
        let p = lines(&["a=0", "b=0"]);
        let c = lines(&["a=0", "b=1"]);
        assert_eq!(
            collect_diff(&p, &c),
            vec![
                DiffLine::Unchanged("a=0"),
                DiffLine::Removed("b=0"),
                DiffLine::Added("b=1"),
            ]
        );
    }

    #[test]
    fn diff_line_removed_at_end() {
        let p = lines(&["a=0", "b=0"]);
        let c = lines(&["a=0"]);
        assert_eq!(
            collect_diff(&p, &c),
            vec![DiffLine::Unchanged("a=0"), DiffLine::Removed("b=0")]
        );
    }

    #[test]
    fn diff_line_added_at_end() {
        let p = lines(&["a=0"]);
        let c = lines(&["a=0", "b=1"]);
        assert_eq!(
            collect_diff(&p, &c),
            vec![DiffLine::Unchanged("a=0"), DiffLine::Added("b=1")]
        );
    }

    #[test]
    fn diff_empty_prev() {
        let p = lines(&[]);
        let c = lines(&["a=0", "b=1"]);
        assert_eq!(
            collect_diff(&p, &c),
            vec![DiffLine::Added("a=0"), DiffLine::Added("b=1")]
        );
    }

    #[test]
    fn diff_duplicate_value_removal() {
        // A set-based diff would find "x=0" still present and report nothing removed.
        // The positional algorithm correctly reports one removal.
        let p = lines(&["x=0", "x=0"]);
        let c = lines(&["x=0"]);
        assert_eq!(
            collect_diff(&p, &c),
            vec![DiffLine::Unchanged("x=0"), DiffLine::Removed("x=0")]
        );
    }
}