use crate::model::Command;
use crate::sat::{Budget, Cdcl, Solver};
use crate::solve::{HoldsCore, Next, Outcome, Stats, StepLabel, Verdict, shrink_tuples};
use elinvar_logic::{
Error, Formula, FormulaKind, Instance, Quantifier, TemporalOp, Trace, TupleSet, Variable,
evaluate_trace_at, evaluate_trace_expr_at,
};
use serde::Serialize;
use serde::ser::{SerializeMap, Serializer};
use std::collections::BTreeMap;
use std::fmt::Write as _;
pub const RESULT_VERSION: u32 = 1;
pub const RESULT_SCHEMA: &str = r##"{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://github.com/rustborg/elinvar/docs/schema/result-v1.json",
"title": "Elinvar result, version 1",
"description": "The result of a run or check command (LOGIC.md section 14.1).",
"type": "object",
"required": ["elinvar", "command", "name", "verdict", "scope", "shrunk_to", "fully_shrunk",
"instance", "trace", "broken_at", "note", "errors", "stats", "story"],
"additionalProperties": false,
"properties": {
"elinvar": { "const": 1 },
"command": { "enum": ["run", "check"] },
"name": { "type": "string" },
"verdict": {
"description": "null when there are errors",
"enum": ["found", "none", "counterexample", "holds", "proved", "vacuous", "unknown", null]
},
"scope": { "$ref": "#/$defs/sizes" },
"shrunk_to": { "oneOf": [{ "$ref": "#/$defs/sizes" }, { "type": "null" }] },
"fully_shrunk": { "type": "boolean" },
"instance": { "oneOf": [{ "$ref": "#/$defs/instance" }, { "type": "null" }] },
"trace": { "oneOf": [{ "$ref": "#/$defs/trace" }, { "type": "null" }] },
"broken_at": { "type": ["integer", "null"], "minimum": 0 },
"broken_witness": {
"description": "for a broken always-all promise, the variable bindings at broken_at that falsify the body",
"type": "array",
"items": {
"type": "array",
"prefixItems": [{ "type": "string" }, { "type": "string" }],
"minItems": 2,
"maxItems": 2
}
},
"expect": { "type": "integer", "minimum": 0 },
"expect_met": { "type": ["boolean", "null"] },
"note": { "type": ["string", "null"] },
"errors": { "type": "array", "items": { "$ref": "#/$defs/error" } },
"warnings": { "type": "array", "items": { "$ref": "#/$defs/error" } },
"stats": {
"type": "object",
"required": ["primary_variables", "gates", "conflicts"],
"additionalProperties": false,
"properties": {
"primary_variables": { "type": "integer", "minimum": 0 },
"gates": { "type": "integer", "minimum": 0 },
"conflicts": { "type": "integer", "minimum": 0 }
}
},
"core": {
"description": "when --explain is requested on a holds or vacuous check, the minimal subset of rules that suffices to rule out counterexamples; on a run with no instance, the minimal subset that, with the run's constraint, allows no instance",
"type": "object",
"required": ["used", "unused"],
"additionalProperties": false,
"properties": {
"used": { "type": "array", "items": { "type": "string" } },
"unused": { "type": "array", "items": { "type": "string" } }
}
},
"story": { "type": "string" }
},
"$defs": {
"sizes": {
"description": "atoms per top-level set, in declaration order, and steps for a model with changing relations",
"type": "object",
"additionalProperties": { "type": "integer", "minimum": 0 }
},
"tuples": {
"type": "array",
"items": { "type": "array", "items": { "type": "string" }, "minItems": 1 }
},
"instance": {
"type": "object",
"required": ["atoms", "relations"],
"additionalProperties": false,
"properties": {
"atoms": { "type": "array", "items": { "type": "string" } },
"bitwidth": {
"description": "the bitwidth of the integers, present only with integer atoms (LOGIC.md 16.1)",
"type": "integer", "minimum": 1, "maximum": 32
},
"ints": {
"description": "each integer atom's integer, by atom name; present only with integer atoms",
"type": "object",
"additionalProperties": { "type": "integer" }
},
"relations": {
"type": "array",
"items": {
"type": "object",
"required": ["name", "arity", "tuples"],
"additionalProperties": false,
"properties": {
"name": { "type": "string" },
"arity": { "type": "integer", "minimum": 1 },
"tuples": { "$ref": "#/$defs/tuples" }
}
}
}
}
},
"trace": {
"type": "object",
"required": ["fixed", "states", "loop_to", "steps"],
"additionalProperties": false,
"properties": {
"fixed": { "$ref": "#/$defs/instance" },
"states": { "type": "array", "items": { "$ref": "#/$defs/instance" }, "minItems": 1 },
"loop_to": { "type": "integer", "minimum": 0 },
"steps": {
"type": "array",
"items": {
"type": "object",
"required": ["step", "to", "action", "args", "changes"],
"additionalProperties": false,
"properties": {
"step": { "type": "integer", "minimum": 0 },
"to": { "type": "integer", "minimum": 0 },
"action": { "type": ["string", "null"] },
"args": { "type": "array", "items": { "type": "string" } },
"changes": {
"type": "array",
"items": {
"type": "object",
"required": ["relation", "gained", "lost"],
"additionalProperties": false,
"properties": {
"relation": { "type": "string" },
"gained": { "$ref": "#/$defs/tuples" },
"lost": { "$ref": "#/$defs/tuples" }
}
}
}
}
}
}
}
},
"error": {
"type": "object",
"required": ["code", "message", "fix", "place"],
"additionalProperties": false,
"properties": {
"code": { "type": "string", "pattern": "^[a-z]+\\.[a-z_]+$" },
"message": { "type": "string" },
"fix": { "type": "string" },
"place": {
"oneOf": [
{
"type": "object",
"required": ["file", "line", "column"],
"additionalProperties": false,
"properties": {
"file": { "type": "string" },
"line": { "type": "integer", "minimum": 1 },
"column": { "type": "integer", "minimum": 1 }
}
},
{ "type": "null" }
]
}
}
}
}
}
"##;
pub const SHRINK_CONFLICTS: u64 = 1_000_000;
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Sizes(pub Vec<(String, usize)>);
impl Serialize for Sizes {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
let mut map = s.serialize_map(Some(self.0.len()))?;
for (k, v) in &self.0 {
map.serialize_entry(k, v)?;
}
map.end()
}
}
#[derive(Clone, Debug, Serialize)]
#[non_exhaustive]
pub struct Change {
pub relation: String,
pub gained: TupleSet,
pub lost: TupleSet,
}
#[derive(Clone, Debug, Serialize)]
#[non_exhaustive]
pub struct StepReport {
pub step: usize,
pub to: usize,
pub action: Option<String>,
pub args: Vec<String>,
pub changes: Vec<Change>,
}
#[derive(Clone, Debug, Serialize)]
#[non_exhaustive]
pub struct TraceReport {
pub fixed: Instance,
pub states: Vec<Instance>,
pub loop_to: usize,
pub steps: Vec<StepReport>,
}
#[derive(Clone, Debug, Serialize)]
#[non_exhaustive]
#[must_use]
pub struct Report {
pub elinvar: u32,
pub command: &'static str,
pub name: String,
pub verdict: Option<Verdict>,
pub scope: Sizes,
pub shrunk_to: Option<Sizes>,
pub fully_shrunk: bool,
pub instance: Option<Instance>,
pub trace: Option<TraceReport>,
pub broken_at: Option<usize>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub broken_witness: Vec<(String, String)>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub expect: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub expect_met: Option<bool>,
pub note: Option<String>,
pub errors: Vec<Error>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub warnings: Vec<Error>,
pub stats: Stats,
#[serde(skip_serializing_if = "Option::is_none")]
pub core: Option<HoldsCore>,
pub story: String,
}
impl std::fmt::Display for Report {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.story)
}
}
fn difference(a: &TupleSet, b: &TupleSet) -> TupleSet {
let mut out = TupleSet::empty(a.universe(), a.arity())
.expect("a tuple set's own arity and universe are valid");
for i in a.indices().filter(|&i| !b.contains_index(i)) {
out.insert_index(i)
.expect("an index of a tuple set is an index of its arity");
}
out
}
pub(crate) fn trace_report(trace: &Trace, labels: &[StepLabel]) -> TraceReport {
let states = trace.states();
let steps = (0..states.len())
.map(|k| {
let to = if k + 1 < states.len() {
k + 1
} else {
trace.loop_to()
};
let changes = states[k]
.entries()
.filter_map(|(r, now)| {
let next = states[to].get(r)?;
let gained = difference(next, now);
let lost = difference(now, next);
(!gained.is_empty() || !lost.is_empty()).then(|| Change {
relation: r.name().to_string(),
gained,
lost,
})
})
.collect();
let label = labels.get(k);
StepReport {
step: k,
to,
action: label.and_then(|l| l.action.clone()),
args: label.map(|l| l.args.clone()).unwrap_or_default(),
changes,
}
})
.collect();
TraceReport {
fixed: trace.fixed().clone(),
states: states.to_vec(),
loop_to: trace.loop_to(),
steps,
}
}
fn broken_at_with_witness(
assertion: &Formula,
trace: &Trace,
) -> (Option<usize>, Vec<(String, String)>) {
let mut a = assertion;
loop {
match a.kind() {
FormulaKind::And(fs) if fs.len() == 1 => a = &fs[0],
FormulaKind::Implies(_, rhs) => a = rhs,
_ => break,
}
}
let FormulaKind::Temporal(TemporalOp::Always, p) = a.kind() else {
return (None, Vec::new());
};
let Some(k) =
(0..trace.states().len()).find(|&k| evaluate_trace_at(trace, p, k, &[]) == Ok(false))
else {
return (None, Vec::new());
};
let witness = find_all_witness(p, trace, k);
(Some(k), witness)
}
fn find_all_witness(formula: &Formula, trace: &Trace, k: usize) -> Vec<(String, String)> {
let mut cur = formula;
let mut vars: Vec<Variable> = Vec::new();
let mut ranges = Vec::new();
loop {
match cur.kind() {
FormulaKind::And(fs) if fs.len() == 1 => cur = &fs[0],
FormulaKind::Quantified(Quantifier::All, decls, body) => {
for d in decls {
if d.expr.arity() != Some(1) {
return Vec::new();
}
vars.push(d.var.clone());
ranges.push(d.expr.clone());
}
cur = body;
}
_ => break,
}
}
if vars.is_empty() {
return Vec::new();
}
let mut domains: Vec<Vec<usize>> = Vec::with_capacity(ranges.len());
for r in &ranges {
let Ok(ts) = evaluate_trace_expr_at(trace, r, k) else {
return Vec::new();
};
let atoms: Vec<usize> = ts.indices().map(|i| i as usize).collect();
if atoms.is_empty() {
return Vec::new();
}
domains.push(atoms);
}
let total: usize = domains
.iter()
.try_fold(1usize, |acc, d| acc.checked_mul(d.len()))
.unwrap_or(0);
if total == 0 || total > 4096 {
return Vec::new();
}
for code in 0..total {
let mut atoms = vec![0usize; domains.len()];
let mut c = code;
for (slot, dom) in atoms.iter_mut().zip(&domains).rev() {
*slot = dom[c % dom.len()];
c /= dom.len();
}
let bindings: Vec<(Variable, usize)> =
vars.iter().cloned().zip(atoms.iter().copied()).collect();
if evaluate_trace_at(trace, cur, k, &bindings) == Ok(false) {
return vars
.iter()
.zip(atoms)
.map(|(v, idx)| {
let atom = trace
.universe()
.atom(idx)
.expect("atom index from trace universe")
.to_string();
(v.name().to_string(), atom)
})
.collect();
}
}
Vec::new()
}
fn check_expect_met(expect: Option<u64>, verdict: Option<Verdict>) -> Option<bool> {
let e = expect?;
let v = verdict?;
match v {
Verdict::Unknown => None,
Verdict::Found | Verdict::Counterexample => Some(e >= 1),
Verdict::Holds | Verdict::Proved | Verdict::Vacuous | Verdict::None => Some(e == 0),
}
}
impl Report {
pub fn of_errors(command: &'static str, name: &str, errors: Vec<Error>) -> Report {
let mut report = Report::empty(command, name.to_string(), Sizes::default());
report.errors = errors;
report.story = story(&report);
report
}
fn empty(command: &'static str, name: String, scope: Sizes) -> Report {
Report {
elinvar: RESULT_VERSION,
command,
name,
verdict: None,
scope,
shrunk_to: None,
fully_shrunk: true,
instance: None,
trace: None,
broken_at: None,
broken_witness: Vec::new(),
expect: None,
expect_met: None,
note: None,
errors: Vec::new(),
warnings: Vec::new(),
stats: Stats::default(),
core: None,
story: String::new(),
}
}
}
impl Command<'_> {
fn scope_sizes(&self) -> Sizes {
let mut sizes: Vec<(String, usize)> = self
.top_sizes()
.into_iter()
.map(|(_, name, k, _)| (name, k))
.collect();
if self.model.has_changing() {
sizes.push(("steps".to_string(), self.options.steps));
}
Sizes(sizes)
}
pub fn report(&self) -> Report {
self.report_with(Cdcl::new)
}
pub fn report_with<S, F>(&self, mut make_solver: F) -> Report
where
S: Solver + 'static,
F: FnMut() -> S,
{
let mut report = Report::empty(
if self.is_check { "check" } else { "run" },
self.name.clone(),
self.scope_sizes(),
);
report.warnings = self.warnings.clone();
report.expect = self.expect;
match self.solve_with(&mut make_solver) {
Err(errors) => report.errors = errors,
Ok(out) => {
let out = if self.shrink
&& matches!(out.verdict, Verdict::Counterexample | Verdict::Found)
{
let (out, shrunk_to, fully) = self.shrink_with(out, &mut make_solver);
report.shrunk_to = Some(shrunk_to);
report.fully_shrunk = fully;
out
} else {
out
};
report.verdict = Some(out.verdict);
report.expect_met = check_expect_met(report.expect, report.verdict);
report.note = out.note.clone();
report.stats = out.stats;
report.instance = out.instance.clone();
if self.is_check
&& !self.skip_holds_warnings
&& matches!(out.verdict, Verdict::Holds | Verdict::Proved)
{
report
.warnings
.extend(self.holds_warnings(&mut make_solver));
}
if let Some(trace) = &out.trace {
if self.is_check {
let (at, witness) = broken_at_with_witness(&self.formula, trace);
report.broken_at = at;
report.broken_witness = witness;
}
report.trace = Some(trace_report(trace, &out.labels));
}
}
}
report.story = story(&report);
report
}
pub fn report_explained(&self) -> Report {
let mut report = self.report();
let total_budget = self
.options
.budget
.conflicts
.unwrap_or(crate::solve::DEFAULT_CONFLICTS);
let mut remaining = total_budget.saturating_sub(report.stats.conflicts);
let res = match report.verdict {
Some(Verdict::Vacuous) => self.explain_vacuous_budgeted(&mut remaining).ok(),
Some(Verdict::Holds | Verdict::Proved) => {
self.explain_assertion_budgeted(&mut remaining).ok()
}
Some(Verdict::None) => match self.explain_no_instance_budgeted(&mut remaining) {
Ok((res, alone)) => {
if alone && !matches!(res, crate::solve::CoreResult::NotUnsat) {
report.note = Some(
"the rules allow no case at all, whatever the run asks".to_string(),
);
}
Some(res)
}
Err(_) => None,
},
_ => None,
};
match res {
Some(crate::solve::CoreResult::Complete(core)) => {
report.core = Some(core);
report.story = story(&report);
}
Some(crate::solve::CoreResult::Incomplete { core, note }) => {
report.core = core;
report.note = Some(match report.note.take() {
Some(prev) => format!("{prev}; {note}"),
None => note,
});
report.story = story(&report);
}
Some(crate::solve::CoreResult::NotUnsat) | None => {}
}
report
}
fn shrink_with<S, F>(&self, found: Outcome, make_solver: &mut F) -> (Outcome, Sizes, bool)
where
S: Solver + 'static,
F: FnMut() -> S,
{
let mut best = found;
let mut cmd = self.clone();
let mut spent = 0u64;
let mut fully = true;
let left = |spent: u64| Budget::conflicts(SHRINK_CONFLICTS.saturating_sub(spent).max(1));
let target_verdict = if self.is_check {
Verdict::Counterexample
} else {
Verdict::Found
};
let sets = cmd.top_sizes();
let can_fast_skip_unused = !formula_mentions_univ_or_iden(&cmd.facts_for(None))
&& !formula_mentions_univ_or_iden(&cmd.formula);
'sets: for (set, _, start, exact) in sets {
if exact {
continue;
}
let mut k = start;
if can_fast_skip_unused
&& start > 0
&& used_atoms_for_top_set(&cmd, &best, &set, start) == 0
{
cmd = cmd.with_scope(&set, 0);
continue 'sets;
}
while k > 0 {
let budget = left(spent);
let mut trial = cmd.with_scope(&set, k - 1);
trial.options = trial.options.budget(budget);
match trial.solve_with(&mut *make_solver) {
Ok(out) => {
spent += out.stats.conflicts;
if out.verdict == target_verdict {
best = out;
cmd = trial;
k -= 1;
} else if out.verdict == Verdict::Unknown {
fully = false;
break 'sets;
} else {
break;
}
}
Err(_) => break,
}
if spent >= SHRINK_CONFLICTS {
fully = false;
break 'sets;
}
}
}
if fully && let Ok(bounds) = cmd.bounds() {
let full_facts = cmd.facts_for(Some(&bounds));
let tuple_formula = if self.is_check {
full_facts.and(&self.formula.not())
} else {
full_facts.and(&self.formula)
};
let (states, loop_to) = best
.trace
.as_ref()
.map_or((1, 0), |t| (t.states().len(), t.loop_to()));
let (shrink_bounds, shrink_formula) = crate::coi::prepare_tuple_shrink(
&bounds,
&full_facts,
&self.formula,
self.is_check,
states,
loop_to,
best.instance.as_ref(),
best.trace.as_ref(),
)
.unwrap_or_else(|| (bounds.clone(), tuple_formula.clone()));
let budget = SHRINK_CONFLICTS.saturating_sub(spent);
match shrink_tuples(
&bounds,
&tuple_formula,
&shrink_bounds,
&shrink_formula,
states,
loop_to,
budget,
Box::new(make_solver()),
) {
Some((next, used, finished)) => {
spent += used;
fully = finished;
match next {
Next::Instance(i) => best.instance = Some(i),
Next::Trace(t) => {
best.labels = self.model.labels_with(&t, &self.extra_step_labels);
best.trace = Some(t);
}
Next::Done | Next::Unknown => {}
}
}
None => fully = false,
}
}
best.stats.conflicts += spent;
let sizes = Sizes(
cmd.top_sizes()
.into_iter()
.map(|(_, name, k, _)| (name, k))
.collect(),
);
(best, sizes, fully)
}
#[track_caller]
pub fn assert_holds(&self) {
let report = self.report();
if !matches!(report.verdict, Some(Verdict::Holds | Verdict::Proved)) {
panic!("{}", report.story);
}
}
}
fn singleton_aliases(instance: &Instance) -> BTreeMap<String, String> {
let mut counts: BTreeMap<String, Vec<String>> = BTreeMap::new();
for (r, t) in instance.entries() {
if r.arity() != 1
|| r.name().starts_with('$')
|| is_ordering_relation(r.name())
|| (r.name().contains("_chk_")
&& (r.name().contains("_val") || r.name().contains("_ord")))
{
continue;
}
if t.len() != 1 {
continue;
}
let Some(tup) = t.iter().next() else { continue };
let Some(&atom) = tup.names().first() else {
continue;
};
if let Some(rest) = atom.strip_prefix(r.name())
&& !rest.is_empty()
&& rest.bytes().all(|b| b.is_ascii_digit())
{
continue;
}
if atom.parse::<i64>().is_ok() {
continue;
}
counts
.entry(atom.to_string())
.or_default()
.push(r.name().to_string());
}
let mut aliases = BTreeMap::new();
for (atom, names) in counts {
if names.len() == 1 {
aliases.insert(atom, names.into_iter().next().expect("len is 1"));
}
}
aliases
}
fn display_atom<'a>(atom: &'a str, aliases: &'a BTreeMap<String, String>) -> &'a str {
aliases.get(atom).map(String::as_str).unwrap_or(atom)
}
fn tuples_text(t: &TupleSet, aliases: &BTreeMap<String, String>) -> String {
let parts: Vec<String> = t
.iter()
.map(|x| {
x.names()
.iter()
.map(|a| display_atom(a, aliases))
.collect::<Vec<_>>()
.join(" -> ")
})
.collect();
format!("{{{}}}", parts.join(", "))
}
fn is_ordering_relation(name: &str) -> bool {
name == "first" || name == "next" || name.ends_with("/first") || name.ends_with("/next")
}
fn instance_lines(
out: &mut String,
instance: &Instance,
indent: &str,
brief: bool,
aliases: &BTreeMap<String, String>,
) {
let mut empty_names: Vec<&str> = Vec::new();
let mut order_lines: Vec<(&str, &TupleSet)> = Vec::new();
for (r, t) in instance.entries() {
if let Some(name) = r.name().strip_prefix('$') {
let atoms: Vec<String> = t
.iter()
.map(|x| {
x.names()
.iter()
.map(|a| display_atom(a, aliases))
.collect::<Vec<_>>()
.join(" -> ")
})
.collect();
let _ = writeln!(out, "{indent}witness {name} = {}", atoms.join(", "));
} else if is_ordering_relation(r.name()) {
if !brief && !t.is_empty() {
order_lines.push((r.name(), t));
}
} else if t.is_empty() {
if !brief {
empty_names.push(r.name());
}
} else {
if r.arity() == 1
&& t.len() == 1
&& let Some(tup) = t.iter().next()
&& let Some(&atom) = tup.names().first()
&& aliases.get(atom).map(String::as_str) == Some(r.name())
{
continue;
}
let _ = writeln!(out, "{indent}{} = {}", r.name(), tuples_text(t, aliases));
}
}
if !order_lines.is_empty() {
let parts: Vec<String> = order_lines
.into_iter()
.map(|(n, t)| format!("{n} = {}", tuples_text(t, aliases)))
.collect();
let _ = writeln!(out, "{indent}order: {}", parts.join("; "));
}
if !empty_names.is_empty() {
let _ = writeln!(out, "{indent}empty: {}", empty_names.join(", "));
}
}
fn sizes_text(sizes: &Sizes) -> String {
sizes
.0
.iter()
.map(|(k, v)| format!("{k}: {v}"))
.collect::<Vec<_>>()
.join(", ")
}
pub fn story(r: &Report) -> String {
format_story(r, false)
}
pub fn story_brief(r: &Report) -> String {
format_story(r, true)
}
fn format_story(r: &Report, brief: bool) -> String {
let mut out = String::new();
let title = if r.name.is_empty() {
r.command.to_string()
} else {
format!("{} {}", r.command, r.name)
};
if !r.errors.is_empty() {
let _ = writeln!(out, "{title}: ERRORS");
for e in &r.errors {
let place = e
.place
.as_ref()
.map(|p| format!("{p}: "))
.unwrap_or_default();
let _ = writeln!(out, " {place}error[{}]: {}", e.code, e.message);
let _ = writeln!(out, " fix: {}", e.fix);
}
return out;
}
let searched = format!("searched every case up to {}", sizes_text(&r.scope));
let expect_tag = match (r.expect, r.expect_met) {
(Some(e), Some(true)) => format!(" [expect {e}: met]"),
(Some(e), Some(false)) => format!(" [expect {e}: NOT MET]"),
(Some(e), None) => format!(" [expect {e}: unknown]"),
_ => String::new(),
};
match r.verdict {
Some(Verdict::Holds) => {
let _ = writeln!(out, "{title}: holds{expect_tag}");
let _ = writeln!(out, " {searched}; a larger case might still break it.");
if let Some(n) = &r.note {
let _ = writeln!(out, " note: {n}");
}
if let Some(core) = &r.core {
let used = if core.used.is_empty() {
"(none: assertion holds from bounds alone)".to_string()
} else {
core.used.join(", ")
};
let _ = writeln!(out, " used rules: {used}");
if !core.unused.is_empty() {
let _ = writeln!(out, " unused rules: {}", core.unused.join(", "));
}
}
}
Some(Verdict::Proved) => {
let _ = writeln!(out, "{title}: PROVED{expect_tag}");
let scope_only: Vec<(String, usize)> = r
.scope
.0
.iter()
.filter(|(k, _)| k != "steps")
.cloned()
.collect();
let scope_text = sizes_text(&Sizes(scope_only));
let reason = r
.note
.as_deref()
.unwrap_or("proved for any number of steps by induction");
let _ = writeln!(out, " {reason}, for all cases up to {scope_text}.");
if let Some(core) = &r.core {
let used = if core.used.is_empty() {
"(none: assertion holds from bounds alone)".to_string()
} else {
core.used.join(", ")
};
let _ = writeln!(out, " used rules: {used}");
if !core.unused.is_empty() {
let _ = writeln!(out, " unused rules: {}", core.unused.join(", "));
}
}
}
Some(Verdict::Vacuous) => {
let _ = writeln!(out, "{title}: VACUOUS{expect_tag}");
let _ = writeln!(
out,
" the rules allow no case at all up to {}, so nothing can break the promise.",
sizes_text(&r.scope)
);
if let Some(n) = &r.note {
let _ = writeln!(out, " note: {n}");
}
if let Some(core) = &r.core
&& !core.used.is_empty()
{
let _ = writeln!(out, " conflicting rules: {}", core.used.join(", "));
}
}
Some(Verdict::None) => {
let _ = writeln!(out, "{title}: no instance{expect_tag}");
let _ = writeln!(out, " {searched}.");
if let Some(core) = &r.core {
if let Some(n) = &r.note {
let _ = writeln!(out, " note: {n}");
}
let used = if core.used.is_empty() {
"(none: the run's own constraint allows no case)".to_string()
} else {
core.used.join(", ")
};
let _ = writeln!(out, " used rules: {used}");
if !core.unused.is_empty() {
let _ = writeln!(out, " unused rules: {}", core.unused.join(", "));
}
}
}
Some(Verdict::Unknown) | None => {
let _ = writeln!(out, "{title}: UNKNOWN{expect_tag}");
if let Some(n) = &r.note {
let _ = writeln!(out, " {n}");
}
}
Some(Verdict::Found) | Some(Verdict::Counterexample) => {
let word = if r.verdict == Some(Verdict::Found) {
"found"
} else {
"COUNTEREXAMPLE"
};
let (prep, size) = match &r.shrunk_to {
Some(s) => ("with", s),
None => ("in scope", &r.scope),
};
match &r.trace {
None => {
let _ = writeln!(
out,
"{title}: {word} {prep} {}{expect_tag}",
sizes_text(size)
);
if let Some(i) = &r.instance {
let aliases = singleton_aliases(i);
instance_lines(&mut out, i, " ", brief, &aliases);
}
}
Some(t) => {
let aliases = singleton_aliases(&t.fixed);
let _ = writeln!(
out,
"{title}: {word} in {} states, {prep} {}{expect_tag}",
t.states.len(),
sizes_text(size)
);
let _ = writeln!(out, " start");
instance_lines(&mut out, &t.fixed, " ", brief, &aliases);
if let Some(s0) = t.states.first() {
for (r, ts) in s0.entries().filter(|(_, ts)| !ts.is_empty()) {
let _ =
writeln!(out, " {} = {}", r.name(), tuples_text(ts, &aliases));
}
}
for s in &t.steps {
let action = match &s.action {
Some(a) if s.args.is_empty() => format!(" {a}"),
Some(a) => {
let args: Vec<&str> =
s.args.iter().map(|x| display_atom(x, &aliases)).collect();
format!(" {a}({})", args.join(", "))
}
None if s.changes.is_empty() => " nothing changes".to_string(),
None => String::new(),
};
let changes: Vec<String> = s
.changes
.iter()
.map(|c| {
let mut parts = Vec::new();
if !c.gained.is_empty() {
parts.push(format!(
"{} gains {}",
c.relation,
tuples_text(&c.gained, &aliases)
));
}
if !c.lost.is_empty() {
parts.push(format!(
"{} loses {}",
c.relation,
tuples_text(&c.lost, &aliases)
));
}
parts.join(", ")
})
.collect();
let loops = if s.to <= s.step {
format!(", back to state {}", s.to)
} else {
String::new()
};
let _ = writeln!(
out,
" step {}{action}{}{loops}",
s.step + 1,
if changes.is_empty() {
String::new()
} else {
format!(" {}", changes.join("; "))
}
);
}
if let Some(k) = r.broken_at {
let who = if r.broken_witness.is_empty() {
String::new()
} else {
let pairs: Vec<String> = r
.broken_witness
.iter()
.map(|(v, a)| format!("{v} = {}", display_atom(a, &aliases)))
.collect();
format!(" (for {})", pairs.join(", "))
};
let _ =
writeln!(out, " broken at state {k}, as step {} begins{who}", k + 1);
}
}
}
if r.verdict == Some(Verdict::Counterexample) {
let _ = writeln!(out, " {searched}.");
if !r.fully_shrunk {
let _ = writeln!(out, " (not fully shrunk: shrinking ran out of its budget)");
}
}
}
}
for w in &r.warnings {
let place = w
.place
.as_ref()
.map(|p| format!("{p}: "))
.unwrap_or_default();
let _ = writeln!(out, " {place}warning[{}]: {}", w.code, w.message);
let _ = writeln!(out, " fix: {}", w.fix);
}
out
}
fn expr_mentions_univ_or_iden(e: &elinvar_logic::Expr) -> bool {
use elinvar_logic::ExprKind as K;
match e.kind() {
K::Univ | K::Iden => true,
K::Relation(_) | K::Variable(_) | K::None => false,
K::Unary(_, a) | K::Prime(a) => expr_mentions_univ_or_iden(a),
K::Binary(_, a, b) => expr_mentions_univ_or_iden(a) || expr_mentions_univ_or_iden(b),
K::Comprehension(ds, body) => {
ds.iter().any(|d| expr_mentions_univ_or_iden(&d.expr))
|| formula_mentions_univ_or_iden(body)
}
K::IfThenElse(c, a, b) => {
formula_mentions_univ_or_iden(c)
|| expr_mentions_univ_or_iden(a)
|| expr_mentions_univ_or_iden(b)
}
K::IntToSet(i) => int_mentions_univ_or_iden(i),
}
}
fn int_mentions_univ_or_iden(i: &elinvar_logic::IntExpr) -> bool {
use elinvar_logic::IntExprKind as K;
match i.kind() {
K::Constant(_) => false,
K::Count(e) | K::Sum(e) => expr_mentions_univ_or_iden(e),
K::Binary(_, a, b) => int_mentions_univ_or_iden(a) || int_mentions_univ_or_iden(b),
K::Negate(a) => int_mentions_univ_or_iden(a),
K::IfThenElse(c, a, b) => {
formula_mentions_univ_or_iden(c)
|| int_mentions_univ_or_iden(a)
|| int_mentions_univ_or_iden(b)
}
K::SumOver(ds, body) => {
ds.iter().any(|d| expr_mentions_univ_or_iden(&d.expr))
|| int_mentions_univ_or_iden(body)
}
}
}
fn formula_mentions_univ_or_iden(f: &elinvar_logic::Formula) -> bool {
use elinvar_logic::FormulaKind as K;
match f.kind() {
K::Constant(_) => false,
K::Subset(a, b) | K::Equal(a, b) => {
expr_mentions_univ_or_iden(a) || expr_mentions_univ_or_iden(b)
}
K::Multiplicity(_, a) => expr_mentions_univ_or_iden(a),
K::Not(g) | K::Temporal(_, g) => formula_mentions_univ_or_iden(g),
K::And(fs) | K::Or(fs) => fs.iter().any(formula_mentions_univ_or_iden),
K::Implies(a, b) | K::Iff(a, b) | K::TemporalBinary(_, a, b) => {
formula_mentions_univ_or_iden(a) || formula_mentions_univ_or_iden(b)
}
K::Quantified(_, ds, body) => {
ds.iter().any(|d| expr_mentions_univ_or_iden(&d.expr))
|| formula_mentions_univ_or_iden(body)
}
K::IntCompare(_, a, b) => int_mentions_univ_or_iden(a) || int_mentions_univ_or_iden(b),
}
}
fn used_atoms_for_top_set(
cmd: &Command<'_>,
best: &Outcome,
set: &elinvar_logic::Expr,
fallback: usize,
) -> usize {
let elinvar_logic::ExprKind::Relation(set_rel) = set.kind() else {
return fallback;
};
let Ok(bounds) = cmd.bounds() else {
return fallback;
};
let Some(up) = bounds.upper(set_rel) else {
return fallback;
};
let bu = bounds.universe();
let pool_names: std::collections::BTreeSet<&str> = up
.indices()
.filter_map(|idx| bu.atom(idx as usize))
.collect();
if pool_names.is_empty() {
return 0;
}
let mut used_names: std::collections::BTreeSet<&str> = std::collections::BTreeSet::new();
let mut scan_inst = |inst: &elinvar_logic::Instance| {
let u = inst.universe();
let n = u.size() as u64;
if n == 0 {
return;
}
for (rel, ts) in inst.entries() {
let arity = rel.arity();
for mut idx in ts.indices() {
for _ in 0..arity {
let a = (idx % n) as usize;
if let Some(name) = u.atom(a)
&& let Some(&pname) = pool_names.get(name)
{
used_names.insert(pname);
}
idx /= n;
}
}
}
};
if let Some(inst) = &best.instance {
scan_inst(inst);
} else if let Some(tr) = &best.trace {
scan_inst(tr.fixed());
for st in tr.states() {
scan_inst(st);
}
} else {
return fallback;
}
used_names.len()
}