use dive_model::Model;
use dive_value::Value;
use crate::format::Ending;
use crate::trace::Trace;
pub const MUTANT_MODEL_VALUE: &str = "TRUE";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ControlMode {
ShortestBfs,
Counterexample,
}
#[derive(Clone, Debug)]
pub struct Mutant {
pub name: String,
pub trace: Trace,
}
#[must_use]
pub fn mutants(model: &Model, trace: &Trace) -> Vec<Mutant> {
mutants_with_mode(model, trace, ControlMode::ShortestBfs)
}
#[must_use]
#[allow(
clippy::too_many_lines,
reason = "the table in the module documentation, one block per row"
)]
pub fn mutants_with_mode(model: &Model, trace: &Trace, mode: ControlMode) -> Vec<Mutant> {
let n = trace.states.len();
let mut out = Vec::new();
let base = Trace {
length: None,
..trace.clone()
};
let mut push = |name: String, t: Trace| out.push(Mutant { name, trace: t });
if mode == ControlMode::ShortestBfs && n >= 3 {
let k = n / 2;
let mut t = base.clone();
t.states.remove(k);
t.labels.remove(k);
t.labels[k] = None;
push(format!("drop-state-{k}"), t);
}
if mode == ControlMode::ShortestBfs && n >= 2 {
let mut t = base.clone();
t.states.remove(0);
t.labels.remove(0);
t.labels[0] = None;
push("drop-first".to_owned(), t);
}
if mode == ControlMode::ShortestBfs && n >= 2 {
let k = if n >= 3 { (n - 1) / 2 } else { 0 };
if trace.states[k] != trace.states[k + 1] {
let mut t = base.clone();
t.states.swap(k, k + 1);
for j in k..(k + 3).min(n) {
t.labels[j] = None;
}
push(format!("swap-{k}"), t);
}
}
if n != 0
&& let Some(atom) = model.names.get(MUTANT_MODEL_VALUE)
&& (atom.tok() as usize) < model.evaluator.startup_names()
{
let k = if n >= 3 { n / 2 } else { 0 };
let vars = crate::trace::variables(model);
let fresh = Value::Model(atom);
for (i, name) in vars.iter().enumerate() {
let mut t = base.clone();
let mut s: Vec<Option<Value>> = t.states[k].to_vec();
s[i] = Some(fresh.clone());
t.states[k] = s.into();
t.labels[k] = None;
if k + 1 < n {
t.labels[k + 1] = None;
}
push(format!("change-{k}-{name}"), t);
}
}
if n >= 2
&& matches!(
trace.ending,
Ending::Invariant(_) | Ending::Property(_) | Ending::InvariantError { .. }
)
{
let mut t = base.clone();
t.states.pop();
t.labels.pop();
push("truncate".to_owned(), t);
}
let names =
|list: &[dive_model::Named]| list.iter().map(|x| x.name.clone()).collect::<Vec<_>>();
let claims: Vec<Ending> = match &trace.ending {
Ending::InvariantError { name, ec } => names(&model.invariants)
.into_iter()
.filter(|other| other != name)
.chain(std::iter::once(format!("{name}_dive_trace_mutant")))
.map(|name| Ending::InvariantError {
name,
ec: ec.clone(),
})
.chain(std::iter::once(Ending::InvariantError {
name: name.clone(),
ec: if ec == "TLC_MODULE_DIVISION_BY_ZERO" {
"TLC_VALUE_ASSERT_FAILED"
} else {
"TLC_MODULE_DIVISION_BY_ZERO"
}
.to_owned(),
}))
.collect(),
Ending::Invariant(p) => names(&model.invariants)
.into_iter()
.filter(|q| q != p)
.map(Ending::Invariant)
.chain(std::iter::once(Ending::Invariant(format!(
"{p}_dive_trace_mutant"
))))
.collect(),
Ending::Property(p) => {
let list = if n == 1 {
&model.implied_inits
} else {
&model.implied_actions
};
names(list)
.into_iter()
.filter(|q| q != p)
.map(Ending::Property)
.chain(std::iter::once(Ending::Property(format!(
"{p}_dive_trace_mutant"
))))
.collect()
}
_ => names(&model.invariants)
.into_iter()
.take(1)
.map(Ending::Invariant)
.collect(),
};
for c in claims {
let label = match &c {
Ending::Invariant(q) | Ending::Property(q) => q.clone(),
other => format!("{other:?}"),
};
push(
format!("claim-{label}"),
Trace {
ending: c,
..base.clone()
},
);
}
if let Some(t) = relabel(model, &base) {
out.push(t);
}
out
}
fn relabel(model: &Model, trace: &Trace) -> Option<Mutant> {
let ev = &model.evaluator;
let mut names: Vec<&str> = trace
.labels
.iter()
.flatten()
.map(|l| l.name.as_str())
.collect();
names.sort_unstable();
names.dedup();
let checkable = |name: &str| {
model
.ir
.root_def(name)
.map(|d| ev.redirected(d))
.filter(|&d| {
model.ir.def(d).params.is_empty()
&& !ev.is_value_override(d)
&& !model.ir.def(d).effects.intersects(dive_ir::Effects::IMPURE)
})
};
for k in 1..trace.states.len() {
let Some(current) = &trace.labels[k] else {
continue;
};
for other in &names {
if *other == current.name {
continue;
}
if checkable(other).is_some() {
let mut t = trace.clone();
t.labels[k] = Some(crate::format::Label {
name: (*other).to_owned(),
location: None,
});
if matches!(crate::validate(model, &t).validation,
crate::Validation::Invalid(ref failure)
if failure.state == k && failure.check == crate::Check::Label)
{
return Some(Mutant {
name: format!("relabel-{k}-{other}"),
trace: t,
});
}
}
}
}
None
}