use std::{
fs,
path::{Path, PathBuf},
process::ExitCode,
sync::{
Mutex,
atomic::{AtomicUsize, Ordering},
},
time::Instant,
};
use serde::Serialize;
use spock_check::{Cache, Source};
use spock_engine::{Options, Outcome};
use spock_ir::{Program, TypeDefKind};
use spock_report::Sources;
use spock_smt::{ObligationKind, ProveOptions, ProveOutcome, ProveReport};
use spock_types::{Expect, Loaded};
use crate::{SPEC_ERROR, in_color};
#[derive(clap::Args)]
pub struct TestArgs {
paths: Vec<PathBuf>,
#[arg(long, value_name = "SUBSTR")]
filter: Option<String>,
#[arg(long, value_name = "N", value_parser = clap::value_parser!(u64).range(1..))]
workers: Option<u64>,
#[arg(long, value_name = "N")]
max_distinct: Option<u64>,
#[arg(long)]
json: bool,
#[arg(long)]
no_cache: bool,
#[arg(long, value_name = "DIR")]
cache_dir: Option<PathBuf>,
}
enum Task {
FileError { spec: String, message: String, detail: String },
Model { spec: String, source: String, model: String },
}
struct CaseResult {
spec: String,
model: String,
passed: bool,
expected: Option<String>,
actual: String,
distinct: u64,
generated: u64,
depth: u32,
obligations: Option<usize>,
proved: Option<usize>,
seconds: f64,
cached: bool,
detail: Option<String>,
}
#[derive(Serialize)]
struct JsonReport {
version: u32,
passed: usize,
failed: usize,
seconds: f64,
results: Vec<JsonCase>,
}
#[derive(Serialize)]
struct JsonCase {
spec: String,
model: String,
passed: bool,
#[serde(skip_serializing_if = "Option::is_none")]
expected: Option<String>,
actual: String,
distinct: u64,
generated: u64,
depth: u32,
#[serde(skip_serializing_if = "Option::is_none")]
obligations: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
proved: Option<usize>,
seconds: f64,
cached: bool,
}
pub fn run(args: TestArgs) -> ExitCode {
let start = Instant::now();
let roots = if args.paths.is_empty() { vec![PathBuf::from(".")] } else { args.paths };
let files = match discover_files(&roots) {
Ok(files) => files,
Err(message) => {
eprintln!("error: {message}");
return ExitCode::from(SPEC_ERROR);
}
};
let color = in_color(&std::io::stdout());
let tasks = collect_tasks(&files, args.filter.as_deref(), color);
if tasks.is_empty() {
match &args.filter {
Some(f) => eprintln!("no models match `{f}`"),
None => eprintln!("no models found"),
}
return ExitCode::from(SPEC_ERROR);
}
let total_workers =
args.workers.map_or_else(|| Options::default().workers, |n| n as usize).max(1);
let jobs = tasks.len().min(total_workers);
let per_model = (total_workers / jobs).max(1);
let options = Options { workers: per_model, progress: false, max_distinct: args.max_distinct };
let cache_path = if args.no_cache { None } else { args.cache_dir.or_else(Cache::default_path) };
let cache = cache_path.as_deref().and_then(Cache::open);
let next = AtomicUsize::new(0);
let results: Vec<Mutex<Option<CaseResult>>> =
(0..tasks.len()).map(|_| Mutex::new(None)).collect();
std::thread::scope(|scope| {
for _ in 0..jobs {
scope.spawn(|| {
loop {
let i = next.fetch_add(1, Ordering::Relaxed);
if i >= tasks.len() {
break;
}
let res = run_task(&tasks[i], &options, cache.as_ref(), color);
*results[i].lock().expect("slot lock") = Some(res);
}
});
}
});
let results: Vec<CaseResult> = results
.into_iter()
.map(|slot| slot.into_inner().expect("slot").expect("task ran"))
.collect();
let elapsed = start.elapsed().as_secs_f64();
let passed = results.iter().filter(|r| r.passed).count();
let failed = results.len() - passed;
if args.json {
let json = JsonReport {
version: 1,
passed,
failed,
seconds: elapsed,
results: results
.into_iter()
.map(|r| JsonCase {
spec: r.spec,
model: r.model,
passed: r.passed,
expected: r.expected,
actual: r.actual,
distinct: r.distinct,
generated: r.generated,
depth: r.depth,
obligations: r.obligations,
proved: r.proved,
seconds: r.seconds,
cached: r.cached,
})
.collect(),
};
println!("{}", serde_json::to_string_pretty(&json).expect("JSON report serializes"));
} else {
print_human(&results, passed, failed, elapsed, color);
}
if failed == 0 { ExitCode::SUCCESS } else { ExitCode::FAILURE }
}
fn discover_files(roots: &[PathBuf]) -> Result<Vec<(PathBuf, bool)>, String> {
let mut found = Vec::new();
for root in roots {
if !root.exists() {
return Err(format!("{}: no such file or directory", root.display()));
}
if root.is_file() {
found.push((root.clone(), true));
} else if root.is_dir() {
let mut in_dir = Vec::new();
walk_dir(root, &mut in_dir)?;
in_dir.sort();
found.extend(in_dir.into_iter().map(|p| (p, false)));
}
}
Ok(found)
}
fn walk_dir(dir: &Path, out: &mut Vec<PathBuf>) -> Result<(), String> {
let entries = fs::read_dir(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
for entry in entries {
let entry = entry.map_err(|e| format!("{}: {e}", dir.display()))?;
let path = entry.path();
let name = entry.file_name();
let name = name.to_string_lossy();
if path.is_dir() {
if name.starts_with('.') || matches!(name.as_ref(), "target" | "node_modules" | "dist")
{
continue;
}
walk_dir(&path, out)?;
} else if path.extension().and_then(|e| e.to_str()) == Some("spock") {
out.push(path);
}
}
Ok(())
}
fn collect_tasks(files: &[(PathBuf, bool)], filter: Option<&str>, color: bool) -> Vec<Task> {
let mut tasks = Vec::new();
for (path, explicit) in files {
let spec = display_path(path);
let source = match fs::read_to_string(path) {
Ok(s) => s,
Err(err) => {
tasks.push(Task::FileError {
spec: spec.clone(),
message: err.to_string(),
detail: format!("{spec}: {err}\n"),
});
continue;
}
};
let parsed = match spock_syntax::parse(&source) {
Ok(f) => f,
Err(diag) => {
let detail =
spock_report::diagnostics(std::slice::from_ref(&diag), &spec, &source, color);
tasks.push(Task::FileError { spec, message: diag.message, detail });
continue;
}
};
let models = spock_types::models(&parsed);
if models.is_empty() {
if *explicit {
tasks.push(Task::FileError {
spec: spec.clone(),
message: "this file has no model".into(),
detail: format!("{spec}: this file has no model\n"),
});
}
continue;
}
for model in models {
let label = format!("{spec} {model}");
if filter.is_some_and(|f| !label.contains(f)) {
continue;
}
tasks.push(Task::Model { spec: spec.clone(), source: source.clone(), model });
}
}
tasks
}
fn display_path(path: &Path) -> String {
let s = path.to_string_lossy();
s.strip_prefix("./").unwrap_or(&s).to_owned()
}
fn load_error(spec: &str, model: &str, message: String, detail: String) -> CaseResult {
CaseResult {
spec: spec.to_owned(),
model: model.to_owned(),
passed: false,
expected: None,
actual: format!("error: {message}"),
distinct: 0,
generated: 0,
depth: 0,
obligations: None,
proved: None,
seconds: 0.0,
cached: false,
detail: Some(detail),
}
}
fn is_abstract(program: &Program) -> bool {
program.types.iter().any(|t| matches!(t.kind, TypeDefKind::Abstract))
|| program.consts.iter().any(|c| c.value.is_none())
}
fn has_proof_obligations(program: &Program) -> bool {
let m = &program.model;
if !m.invariants.is_empty() || !m.inductive.is_empty() || !m.step_properties.is_empty() {
return true;
}
let unchecked = spock_report::smt_unchecked(program);
m.properties.iter().any(|p| !unchecked.contains(&p.name))
}
fn run_task(task: &Task, options: &Options, cache: Option<&Cache>, color: bool) -> CaseResult {
match task {
Task::FileError { spec, message, detail } => {
load_error(spec, "", message.clone(), detail.clone())
}
Task::Model { spec, source, model } => {
let loaded = match spock_types::load_with_expect_abstract(spec, source, Some(model)) {
Ok(loaded) => loaded,
Err(diagnostics) => {
let message = diagnostics[0].message.clone();
let detail = spock_report::diagnostics(&diagnostics, spec, source, color);
return load_error(spec, model, message, detail);
}
};
if is_abstract(&loaded.program) {
if has_proof_obligations(&loaded.program) {
return run_prove_task(spec, source, model, &loaded, options.workers, color);
}
if let Err(diagnostics) = spock_types::load_with_expect(spec, source, Some(model)) {
let message = diagnostics[0].message.clone();
let detail = spock_report::diagnostics(&diagnostics, spec, source, color);
return load_error(spec, model, message, detail);
}
}
let checked = spock_check::check(&loaded.program, options, cache);
let cached = matches!(checked.source, Source::Cache { .. });
let report = checked.report;
let passed = matches_expect(&loaded.expect, &report.outcome);
let actual = describe_outcome(&report.outcome);
let detail = if passed {
None
} else {
let sources = Sources { spec, source, program: &loaded.program, color };
Some(spock_report::check(&sources, &report))
};
CaseResult {
spec: spec.clone(),
model: model.clone(),
passed,
expected: Some(loaded.expect.to_string()),
actual,
distinct: report.distinct,
generated: report.generated,
depth: report.depth,
obligations: None,
proved: None,
seconds: report.elapsed.as_secs_f64(),
cached,
detail,
}
}
}
}
fn run_prove_task(
spec: &str,
source: &str,
model: &str,
loaded: &Loaded,
workers: usize,
color: bool,
) -> CaseResult {
let prove_opts = ProveOptions { workers, ..ProveOptions::default() };
let report = spock_smt::prove(&loaded.program, &prove_opts);
let unchecked = spock_report::smt_unchecked(&loaded.program);
let passed = matches_prove_expect(&loaded.expect, &report.outcome, &unchecked);
let actual = describe_prove_outcome(&report, &unchecked, &loaded.expect);
let detail = if passed {
None
} else {
let sources = Sources { spec, source, program: &loaded.program, color };
let mut msg = spock_report::prove(&sources, &report);
if matches!(report.outcome, ProveOutcome::Proved) && !unchecked.is_empty() {
msg += &format!(
"hint: `spock prove` didn't check {}; bind atoms/constants to check them \
finitely (or set `deadlock = false;` if deadlock isn't checked)\n",
unchecked.join(", ")
);
}
Some(msg)
};
CaseResult {
spec: spec.to_owned(),
model: model.to_owned(),
passed,
expected: Some(loaded.expect.to_string()),
actual,
distinct: 0,
generated: 0,
depth: 0,
obligations: Some(report.obligations),
proved: Some(report.proved),
seconds: report.elapsed.as_secs_f64(),
cached: false,
detail,
}
}
fn base_target(target: &str) -> &str {
target.split_once('#').map_or(target, |(base, _)| base)
}
fn is_cti_only(kind: ObligationKind) -> bool {
matches!(
kind,
ObligationKind::StepType
| ObligationKind::StepInductive
| ObligationKind::SafetyInvariant
| ObligationKind::StepProperty
)
}
fn matches_prove_expect(expect: &Expect, outcome: &ProveOutcome, unchecked: &[String]) -> bool {
match (expect, outcome) {
(Expect::Ok, ProveOutcome::Proved) => unchecked.is_empty(),
(Expect::Assumption(want), ProveOutcome::Failed { failures }) => failures.iter().any(|f| {
f.kind == ObligationKind::Vacuity
&& want.as_deref().is_none_or(|w| base_target(&f.target) == w)
}),
(Expect::Invariant(want), ProveOutcome::Failed { failures }) => failures.iter().any(|f| {
matches!(f.kind, ObligationKind::InitType | ObligationKind::InitInductive)
&& want.as_deref().is_none_or(|w| base_target(&f.target) == w)
}),
_ => false,
}
}
fn describe_prove_outcome(report: &ProveReport, unchecked: &[String], expect: &Expect) -> String {
match &report.outcome {
ProveOutcome::Proved if !unchecked.is_empty() => format!(
"unchecked: {} (proved {}/{} obligations)",
unchecked.join(", "),
report.proved,
report.obligations
),
ProveOutcome::Proved => {
format!("proved {}/{} obligations", report.proved, report.obligations)
}
ProveOutcome::Failed { failures } => match failures.first() {
Some(f) if f.kind == ObligationKind::Vacuity => "assumption".into(),
Some(f)
if matches!(f.kind, ObligationKind::InitType | ObligationKind::InitInductive) =>
{
format!("invariant({})", base_target(&f.target))
}
Some(f) if f.kind == ObligationKind::InitProperty => {
format!("property({})", base_target(&f.target))
}
Some(f) if is_cti_only(f.kind) => {
let target = base_target(&f.target);
if matches!(expect, Expect::Invariant(_) | Expect::StepProperty(_)) {
format!("counterexample to induction for {target}, not a reachable violation")
} else {
format!("{target} is not inductive")
}
}
Some(f) => format!("failed({})", base_target(&f.target)),
None => format!("failed ({}/{})", report.proved, report.obligations),
},
ProveOutcome::Unknown { .. } => {
format!(
"unknown ({}/{} proved, {} unknown)",
report.proved, report.obligations, report.unknown
)
}
ProveOutcome::Error { message, .. } => format!("error: {message}"),
}
}
fn matches_expect(expect: &Expect, outcome: &Outcome) -> bool {
match (expect, outcome) {
(Expect::Ok, Outcome::Ok) => true,
(Expect::Deadlock, Outcome::Deadlock { .. }) => true,
(Expect::Assumption(want), Outcome::AssumptionViolated { name }) => {
want.as_deref().is_none_or(|w| w == name)
}
(Expect::Invariant(want), Outcome::InvariantViolated { name, .. }) => {
want.as_deref().is_none_or(|w| w == name)
}
(Expect::StepProperty(want), Outcome::PropertyViolated { name, .. }) => {
want.as_deref().is_none_or(|w| w == name)
}
(Expect::Property(want), Outcome::TemporalViolated { name, .. }) => {
want.as_deref().is_none_or(|w| w == name)
}
_ => false,
}
}
fn describe_outcome(outcome: &Outcome) -> String {
match outcome {
Outcome::Ok => "ok".into(),
Outcome::Deadlock { .. } => "deadlock".into(),
Outcome::AssumptionViolated { name } => format!("assumption({name})"),
Outcome::InvariantViolated { name, .. } => format!("invariant({name})"),
Outcome::PropertyViolated { name, .. } => format!("step_property({name})"),
Outcome::TemporalViolated { name, .. } => format!("property({name})"),
Outcome::Error { message, .. } => format!("error: {message}"),
}
}
fn print_human(results: &[CaseResult], passed: usize, failed: usize, elapsed: f64, color: bool) {
let ok = if color { "\x1b[32mok\x1b[0m " } else { "ok " };
let fail = if color { "\x1b[31mFAIL\x1b[0m " } else { "FAIL " };
for r in results {
let name =
if r.model.is_empty() { r.spec.clone() } else { format!("{} {}", r.spec, r.model) };
if r.passed {
let note = if r.actual == "ok" {
format!("{} distinct, {:.2} s", r.distinct, r.seconds)
} else {
format!("{}, {:.2} s", r.actual, r.seconds)
};
let cached = if r.cached { ", cached" } else { "" };
println!("{ok} {name} ({note}{cached})");
} else {
match &r.expected {
Some(expected) => println!("{fail} {name}: expected {expected}, got {}", r.actual),
None => println!("{fail} {name}: {}", r.actual),
}
if let Some(detail) = &r.detail {
for line in detail.lines() {
println!(" {line}");
}
}
}
}
let noun = if results.len() == 1 { "model" } else { "models" };
if failed == 0 {
println!("🖖 {} {noun}: {passed} passed, 0 failed ({elapsed:.2} s)", results.len());
} else {
println!("{} {noun}: {passed} passed, {failed} failed ({elapsed:.2} s)", results.len());
}
}