use std::process::ExitCode;
use spock_engine::trace::{Options, Outcome};
use spock_report::{Sources, TraceFile};
use crate::{SPEC_ERROR, in_color, json, load, location};
const DIVERGES: u8 = 14;
#[derive(clap::Args)]
pub struct TraceArgs {
spec: String,
trace: String,
#[arg(long, value_name = "NAME")]
model: Option<String>,
#[arg(long, value_name = "N", value_parser = clap::value_parser!(u64).range(1..))]
max_states: Option<u64>,
#[arg(long)]
json: bool,
}
pub fn run(args: TraceArgs) -> ExitCode {
let (spec, model, path) = (args.spec.as_str(), args.model.as_deref(), 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(¬.message, not.location, ¬.text),
};
let text = 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 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));
} else {
print!("{}", spock_report::trace(&sources, &file, &report));
}
ExitCode::from(match report.outcome {
Outcome::Matches { .. } => 0,
Outcome::InvariantViolated { .. } => 12,
Outcome::PropertyViolated { .. } => 13,
Outcome::Diverges { .. } => DIVERGES,
Outcome::Error { .. } => SPEC_ERROR,
})
}