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};
#[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(()) }
}
}
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
}
pub const RST: Style = Style("\x1b[0m");
pub const RED: Style = Style("\x1b[0;31m");
pub const GRN: Style = Style("\x1b[0;32m");
pub const YLW: Style = Style("\x1b[0;33m");
pub const BLU: Style = Style("\x1b[0;34m");
pub const PUR: Style = Style("\x1b[0;35m");
pub const CYN: Style = Style("\x1b[0;36m");
pub const BRED: Style = Style("\x1b[1;31m");
pub const BGRN: Style = Style("\x1b[1;32m");
pub const BYLW: Style = Style("\x1b[1;33m");
pub const BBLU: Style = Style("\x1b[1;34m");
pub const BPUR: Style = Style("\x1b[1;35m");
pub const BCYN: Style = Style("\x1b[1;36m");
pub const RULE: &str = "═════════════════════════════════════════════════════";
pub fn print_stats<S: State>(stats: &Stats<S>) {
println!("{BGRN}VERIFIED{RST} — {stats}");
}
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!();
}
#[derive(Debug, PartialEq, Eq)]
pub enum DiffLine<'a> {
Removed(&'a str),
Added(&'a str),
Unchanged(&'a str),
}
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!(),
}
}
}
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, ¤t_lines, |event| match event {
DiffLine::Removed(line) => eprintln!("{RED}- {line}{RST}"),
DiffLine::Added(line) => eprintln!("{BGRN}+ {line}{RST}"),
DiffLine::Unchanged(line) => eprintln!(" {line}"),
});
}
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() {
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")]
);
}
}