use elinvar_als::{AlsModel, Evaluable};
use elinvar_engine::logic::{Error, Instance, Relation, Trace, Universe};
use elinvar_engine::sat::Budget;
use elinvar_engine::{
DiagramFormat, DiffVerdict, Options, Report, Verdict, diff_functions,
diff_models_with_bitwidth, render_instance, render_instance_sql_with_values, render_model,
render_report_sql_with_values, render_states, render_states_sql_with_values, story_brief,
};
use serde_json::{Value, json};
pub struct Output {
pub json: Value,
pub text: String,
pub status: u8,
}
#[derive(Clone, Copy, Debug, Default)]
pub struct Overrides {
pub scope: Option<usize>,
pub steps: Option<usize>,
pub budget: Option<u64>,
pub timeout_ms: Option<u64>,
pub explain: bool,
pub brief: bool,
pub inductive: Option<usize>,
pub climb: bool,
pub summary: bool,
pub shrink: bool,
pub ignore_unread: bool,
pub from_any: bool,
pub from_empty: bool,
pub no_slicing: bool,
pub default_bitwidth: Option<u32>,
}
pub fn parse_duration_ms(raw: &str) -> Result<u64, String> {
let s = raw.trim();
if s.is_empty() {
return Err("timeout duration cannot be empty".to_string());
}
let (num_str, mult) = if let Some(n) = s.strip_suffix("ms") {
(n, 1u64)
} else if let Some(n) = s.strip_suffix('s') {
(n, 1_000u64)
} else if let Some(n) = s.strip_suffix('m') {
(n, 60_000u64)
} else if let Some(n) = s.strip_suffix('h') {
(n, 3_600_000u64)
} else {
(s, 1_000u64)
};
let n: u64 = num_str.trim().parse().map_err(|_| {
format!("invalid duration `{raw}` (use e.g. `500ms`, `30s`, `2m`, or seconds)")
})?;
n.checked_mul(mult)
.ok_or_else(|| format!("duration `{raw}` is too large"))
}
pub(crate) fn budget_from_overrides(over: Overrides, default_conflicts: u64) -> Option<Budget> {
if over.budget.is_none() && over.timeout_ms.is_none() {
return None;
}
let mut b = Budget::conflicts(over.budget.unwrap_or(default_conflicts));
if let Some(ms) = over.timeout_ms {
b = b.with_time(std::time::Duration::from_millis(ms));
}
Some(b)
}
fn status_of(r: &Report) -> u8 {
if !r.errors.is_empty() {
return 3;
}
if r.expect.is_some() {
return match r.expect_met {
Some(true) => 0,
Some(false) => 1,
None => 2,
};
}
match r.verdict {
Some(Verdict::Holds | Verdict::Proved | Verdict::Found) => 0,
Some(Verdict::Counterexample | Verdict::None) => 1,
Some(Verdict::Unknown | Verdict::Vacuous) => 2,
Some(_) | None => 3,
}
}
fn from_reports(reports: Vec<Report>, brief: bool) -> Output {
let status = reports.iter().map(status_of).max().unwrap_or(0);
let text = reports
.iter()
.map(|r| {
if brief {
story_brief(r)
} else {
r.story.clone()
}
})
.collect::<Vec<_>>()
.join("\n");
let json = if reports.len() == 1 {
serde_json::to_value(&reports[0]).unwrap_or(Value::Null)
} else {
serde_json::to_value(&reports).unwrap_or(Value::Null)
};
Output { json, text, status }
}
pub(crate) fn error_output(verb: &'static str, mut errors: Vec<Error>) -> Output {
for e in &mut errors {
if e.place.as_ref().is_some_and(|p| p.file.ends_with(".rs")) {
e.place = None;
}
}
if matches!(verb, "check" | "run") {
return from_reports(vec![Report::of_errors(verb, "", errors)], false);
}
let text = errors
.iter()
.map(|e| format!("{e}\n fix: {}\n", e.fix))
.collect::<String>();
Output {
json: json!({
"elinvar": 1,
"command": verb,
"errors": errors,
"story": text,
}),
text,
status: 3,
}
}
fn coded(code: &'static str, message: String) -> Error {
let fix = all_codes()
.into_iter()
.find(|c| c.code == code)
.map(|c| c.fix)
.expect("every code the command line gives is listed");
Error::with_fix(code, message, fix)
}
fn read_model(
verb: &'static str,
file: &str,
text: &str,
allow_local_modules: bool,
) -> Result<AlsModel, Output> {
read_model_with_bw(verb, file, text, allow_local_modules, None)
}
fn read_model_with_bw(
verb: &'static str,
file: &str,
text: &str,
allow_local_modules: bool,
default_bitwidth: Option<u32>,
) -> Result<AlsModel, Output> {
let mut opts = elinvar_als::ReadOptions::default();
if let Some(bw) = default_bitwidth {
opts = opts.default_bitwidth(bw);
}
if !allow_local_modules {
return elinvar_als::read_with(file, text, opts)
.map_err(|errors| error_output(verb, errors));
}
let loader =
|module: &str| std::fs::read_to_string(elinvar_als::module_file(file, text, module)).ok();
elinvar_als::read_with_loader(file, text, opts, &loader)
.map_err(|errors| error_output(verb, errors))
}
pub fn solve(
verb: &'static str,
file: &str,
text: &str,
name: Option<&str>,
over: Overrides,
) -> Output {
solve_with_modules(verb, file, text, name, over, true, None)
}
pub fn solve_inline(
verb: &'static str,
file: &str,
text: &str,
name: Option<&str>,
over: Overrides,
) -> Output {
solve_with_modules(verb, file, text, name, over, false, None)
}
pub fn solve_with_progress(
verb: &'static str,
file: &str,
text: &str,
name: Option<&str>,
over: Overrides,
allow_local_modules: bool,
on_progress: &(dyn Fn(&str) + Sync),
) -> Output {
solve_with_modules(
verb,
file,
text,
name,
over,
allow_local_modules,
Some(on_progress),
)
}
fn solve_with_modules(
verb: &'static str,
file: &str,
text: &str,
name: Option<&str>,
over: Overrides,
allow_local_modules: bool,
on_progress: Option<&(dyn Fn(&str) + Sync)>,
) -> Output {
let model =
match read_model_with_bw(verb, file, text, allow_local_modules, over.default_bitwidth) {
Ok(m) => m,
Err(out) => return out,
};
let check = verb == "check";
let chosen: Vec<_> = model
.commands
.iter()
.filter(|c| c.check == check && name.is_none_or(|n| c.name == n))
.collect();
if chosen.is_empty() {
let what = match name {
Some(n) => format!("the file has no {verb} command named `{n}`"),
None => format!("the file has no {verb} command"),
};
return error_output(verb, vec![coded("als.no_command", what)]);
}
use rayon::prelude::*;
let reports: Vec<Report> = chosen
.into_par_iter()
.map(|spec| {
if check && over.climb {
return climb_check(&model, spec, over, on_progress);
}
let scope_label = over.scope.unwrap_or_else(|| spec.default_scope());
if let Some(cb) = on_progress {
cb(&format!("{verb} `{}` (scope {scope_label})", spec.name));
}
let mut cmd = model.command(spec);
if let Some(k) = over.scope {
cmd = cmd.scope(k);
}
cmd = with_steps(cmd, &model, over.steps);
if let Some(b) = budget_from_overrides(over, 10_000_000) {
cmd = cmd.budget(b);
}
if over.no_slicing {
cmd = cmd.slicing(false);
}
if let Some(k) = over.inductive
&& check
{
cmd = cmd.by_induction(k);
}
if !check && over.shrink {
cmd = cmd.shrink(true);
}
if over.explain {
cmd.report_explained()
} else {
cmd.report()
}
})
.collect();
let never_used: Vec<String> = if over.explain && check && reports.len() >= 2 {
let cores: Vec<_> = reports.iter().filter_map(|r| r.core.as_ref()).collect();
if cores.len() >= 2 {
cores[0]
.unused
.iter()
.filter(|rule| {
cores[1..]
.iter()
.all(|c| c.unused.iter().any(|u| u == *rule))
})
.cloned()
.collect()
} else {
Vec::new()
}
} else {
Vec::new()
};
if check && over.summary {
return summary_output(&reports, &never_used);
}
let mut out = from_reports(reports, over.brief);
if !never_used.is_empty() {
out.text.push_str(&format!(
"\nunused by any check: {}\n",
never_used.join(", ")
));
}
out
}
fn with_steps<'m>(
cmd: elinvar_engine::Command<'m>,
model: &AlsModel,
steps: Option<usize>,
) -> elinvar_engine::Command<'m> {
let Some(n) = steps else { return cmd };
if model.model.relations().iter().any(|r| r.is_changing()) {
return cmd.steps(n);
}
cmd.with_warning(coded(
"cli.steps_ignored",
format!(
"`--steps {n}` was not used: nothing in the model changes, so no trace is searched"
),
))
}
fn climb_check(
model: &AlsModel,
spec: &elinvar_als::CommandSpec,
over: Overrides,
on_progress: Option<&(dyn Fn(&str) + Sync)>,
) -> Report {
let start = over.scope.unwrap_or_else(|| spec.default_scope());
let mut remaining = over.budget.unwrap_or(1_000_000);
let deadline = over
.timeout_ms
.map(|ms| std::time::Instant::now() + std::time::Duration::from_millis(ms));
let max_scope = start.saturating_add(12).min(24);
let mut s = start;
let mut last_holds: Option<(usize, Report)> = None;
loop {
if let Some(cb) = on_progress {
cb(&format!("climb `{}` (scope {s})", spec.name));
}
let mut budget = Budget::conflicts(remaining.max(1));
if let Some(d) = deadline {
let Some(rem) = d.checked_duration_since(std::time::Instant::now()) else {
if let Some((hi, mut best)) = last_holds {
let note = format!(
"holds up to scope {hi}; scope {s} was not started (time limit reached)"
);
best.note = Some(note.clone());
best.story.push_str(&format!(" note: {note}\n"));
return best;
}
budget = budget.with_time(std::time::Duration::ZERO);
return model
.command(spec)
.scope(s)
.budget(budget)
.slicing(!over.no_slicing)
.report();
};
budget = budget.with_time(rem);
}
let mut cmd = model
.command(spec)
.scope(s)
.budget(budget)
.slicing(!over.no_slicing);
cmd = with_steps(cmd, model, over.steps);
if let Some(k) = over.inductive {
cmd = cmd.by_induction(k);
}
let rep = if over.explain {
cmd.report_explained()
} else {
cmd.report()
};
let spent = rep.stats.conflicts.max(1);
remaining = remaining.saturating_sub(spent);
match rep.verdict {
Some(Verdict::Holds) => {
last_holds = Some((s, rep));
let timed_out = deadline.is_some_and(|d| std::time::Instant::now() >= d);
if remaining == 0 || timed_out || s >= max_scope {
let (hi, mut best) = last_holds.expect("just stored");
let note = if timed_out {
format!(
"holds up to scope {hi}; scope {} was not started (time limit reached)",
hi + 1
)
} else if remaining == 0 {
format!(
"holds up to scope {hi}; scope {} was not started (conflict budget exhausted)",
hi + 1
)
} else {
format!("holds up to scope {hi} (reached climb ceiling)")
};
best.note = Some(note.clone());
best.story.push_str(&format!(" note: {note}\n"));
return best;
}
s += 1;
}
Some(Verdict::Unknown) => {
if let Some((hi, mut best)) = last_holds {
let why = rep
.note
.as_deref()
.filter(|n| n.contains("time limit"))
.map(|_| "time limit")
.unwrap_or("conflict budget");
let note =
format!("holds up to scope {hi}; scope {s} did not finish within {why}");
best.note = Some(note.clone());
best.story.push_str(&format!(" note: {note}\n"));
return best;
}
return rep;
}
_ => return rep,
}
}
}
fn summary_output(reports: &[Report], never_used: &[String]) -> Output {
let status = reports.iter().map(status_of).max().unwrap_or(0);
let mut text = String::from(
"| Check | Verdict | Scope | Expect | Warnings | Needed rules |\n\
| --- | --- | --- | --- | --- | --- |\n",
);
let mut rows = Vec::with_capacity(reports.len());
for r in reports {
let verdict = r
.verdict
.map(|v| format!("{v}"))
.unwrap_or_else(|| "error".to_string());
let scope_str = {
let parts: Vec<String> = r.scope.0.iter().map(|(k, v)| format!("{k}={v}")).collect();
if parts.is_empty() {
"-".to_string()
} else {
parts.join(", ")
}
};
let expect_str = match (r.expect, r.expect_met) {
(Some(_), Some(true)) => "ok",
(Some(_), Some(false)) => "FAILED",
(Some(_), None) => "unknown",
(None, _) => "-",
};
let warn_count = r.warnings.len();
let needed: Vec<String> = r.core.as_ref().map(|c| c.used.clone()).unwrap_or_default();
let needed_str = if needed.is_empty() {
"-".to_string()
} else {
needed.join(", ")
};
text.push_str(&format!(
"| {} | {} | {} | {} | {} | {} |\n",
r.name, verdict, scope_str, expect_str, warn_count, needed_str
));
rows.push(json!({
"name": r.name,
"verdict": r.verdict,
"scope": r.scope,
"expect": r.expect,
"expect_met": r.expect_met,
"warnings": r.warnings,
"needed_rules": needed,
}));
}
if !never_used.is_empty() {
text.push_str(&format!(
"\nunused by any check: {}\n",
never_used.join(", ")
));
}
let json = json!({
"elinvar": 1,
"command": "check",
"summary": rows,
"unused_by_any": never_used,
});
Output { json, text, status }
}
fn eval_error(message: String) -> Output {
let e = coded("eval.result", message);
Output {
json: json!({ "elinvar": 1, "errors": [e] }),
text: format!("error[{}]: {}\n fix: {}\n", e.code, e.message, e.fix),
status: 3,
}
}
fn sql_script_error(message: String) -> Output {
let e = coded("sql.script", message);
let text = format!("error[{}]: {}\n fix: {}\n", e.code, e.message, e.fix);
Output {
json: json!({
"elinvar": 1,
"command": "accepts",
"errors": [e],
"story": text,
}),
text,
status: 3,
}
}
fn atom_names<'v>(v: &'v Value, missing: &str) -> Result<Vec<&'v str>, String> {
v.as_array()
.ok_or(missing)?
.iter()
.map(|a| {
a.as_str()
.ok_or_else(|| format!("an atom name that is not a string: {a}"))
})
.collect()
}
fn tuple_rows(r: &Value) -> Result<Vec<Vec<&str>>, String> {
r["tuples"]
.as_array()
.ok_or("a relation without tuples")?
.iter()
.map(|t| {
t.as_array()
.ok_or_else(|| format!("a tuple that is not a list of atom names: {t}"))?
.iter()
.map(|a| {
a.as_str()
.ok_or_else(|| format!("a tuple that is not a list of atom names: {t}"))
})
.collect()
})
.collect()
}
fn instance(u: &Universe, v: &Value, relations: &[Relation]) -> Result<Instance, String> {
let mut i = Instance::new(u);
for r in v["relations"]
.as_array()
.ok_or("an instance without relations")?
{
let name = r["name"].as_str().ok_or("a relation without a name")?;
let Some(rel) = relations.iter().find(|x| x.name() == name) else {
continue;
};
let tuples = tuple_rows(r)?;
let refs: Vec<&[&str]> = tuples.iter().map(Vec::as_slice).collect();
let set = u
.tuple_set(rel.arity(), &refs)
.map_err(|e| e.message.clone())?;
i.set(rel, set).map_err(|e| e.message)?;
}
Ok(i)
}
pub fn trace_of(result: &Value, relations: &[Relation]) -> Result<Trace, String> {
let (atoms_of, fixed_v, states_v, loop_to) = if result["trace"].is_object() {
let t = &result["trace"];
(
&t["fixed"]["atoms"],
&t["fixed"],
t["states"].as_array().cloned().unwrap_or_default(),
t["loop_to"].as_u64().unwrap_or(0) as usize,
)
} else if result["instance"].is_object() {
let i = &result["instance"];
(&i["atoms"], i, Vec::new(), 0)
} else if result["fixed"].is_object() && result["states"].is_array() {
(
&result["fixed"]["atoms"],
&result["fixed"],
result["states"].as_array().cloned().unwrap_or_default(),
result["loop_to"].as_u64().unwrap_or(0) as usize,
)
} else if result["atoms"].is_array() && result["relations"].is_array() {
(&result["atoms"], result, Vec::new(), 0)
} else {
return Err("the result has no instance and no trace".to_string());
};
let atoms = atom_names(atoms_of, "the result has no atoms")?;
let mut u = Universe::new(atoms).map_err(|e| e.message)?;
if let Some(map) = fixed_v.get("ints").and_then(Value::as_object) {
let width = fixed_v["bitwidth"].as_u64().unwrap_or(4) as u32;
let pairs: Vec<(&str, i64)> = map
.iter()
.filter_map(|(k, v)| v.as_i64().map(|i| (k.as_str(), i)))
.collect();
u = u.with_ints(width, &pairs).map_err(|e| e.message)?;
}
let mut fixed = instance(&u, fixed_v, relations)?;
if let Some(int_rel) = relations
.iter()
.find(|r| r.name() == "Int" && r.arity() == 1 && !r.is_changing())
&& fixed.get(int_rel).is_none()
{
let empty = u.tuple_set(1, &[]).map_err(|e| e.message)?;
fixed.set(int_rel, empty).map_err(|e| e.message)?;
}
if states_v.is_empty() {
return Ok(Trace::of_instance(&fixed));
}
let states = states_v
.iter()
.map(|s| instance(&u, s, relations))
.collect::<Result<Vec<_>, _>>()?;
Trace::new(fixed, states, loop_to).map_err(|e| e.message)
}
type CanonKey = (usize, Vec<Vec<Vec<Vec<usize>>>>);
fn canonical_key(insts: &[&Instance], loop_to: usize, sym_parts: &[Vec<usize>]) -> CanonKey {
use std::collections::BTreeMap;
let Some(first) = insts.first() else {
return (loop_to, Vec::new());
};
let u = first.universe();
let n = u.size();
let mut rel_data: Vec<Vec<(usize, Vec<Vec<usize>>)>> = Vec::with_capacity(insts.len());
let mut active = vec![false; n];
for inst in insts {
let mut per_inst = Vec::new();
for (r, ts) in inst.entries() {
if r.name().starts_with('$') {
continue;
}
let arity = r.arity();
let mut tuples: Vec<Vec<usize>> = Vec::with_capacity(ts.len());
for flat in ts.indices() {
let mut t = vec![0usize; arity];
let mut rem = flat;
let base = n as u64;
for slot in t.iter_mut().rev() {
let a = (rem % base) as usize;
*slot = a;
active[a] = true;
rem /= base;
}
tuples.push(t);
}
per_inst.push((arity, tuples));
}
rel_data.push(per_inst);
}
let mut part_of = vec![0usize; n];
for (pi, part) in sym_parts.iter().enumerate() {
for &a in part {
if a < n {
part_of[a] = pi;
}
}
}
let mut colors: Vec<usize> = vec![0; n];
{
type AtomInitSig = (
usize,
Vec<(usize, usize, usize, usize)>,
Vec<(usize, usize)>,
);
let mut sigs: Vec<AtomInitSig> = (0..n)
.map(|a| (part_of[a], Vec::new(), Vec::new()))
.collect();
for (ii, per_inst) in rel_data.iter().enumerate() {
for (ri, (arity, tuples)) in per_inst.iter().enumerate() {
let mut counts: Vec<Vec<usize>> = vec![vec![0; *arity]; n];
let mut self_loops: Vec<bool> = vec![false; n];
for t in tuples {
for (pos, &a) in t.iter().enumerate() {
counts[a][pos] += 1;
}
if *arity == 2 && t[0] == t[1] {
self_loops[t[0]] = true;
}
}
for a in 0..n {
for (pos, &c) in counts[a].iter().enumerate() {
if c > 0 {
sigs[a].1.push((ii, ri, pos, c));
}
}
if self_loops[a] {
sigs[a].2.push((ii, ri));
}
}
}
}
let unique: std::collections::BTreeSet<_> = sigs.iter().cloned().collect();
let palette: BTreeMap<_, usize> = unique
.into_iter()
.enumerate()
.map(|(id, sig)| (sig, id))
.collect();
for a in 0..n {
colors[a] = palette[&sigs[a]];
}
}
for _ in 0..2 {
type AtomWlSig = (usize, Vec<(usize, usize, usize, Vec<usize>)>);
let mut refined: Vec<AtomWlSig> = (0..n).map(|a| (colors[a], Vec::new())).collect();
for (ii, per_inst) in rel_data.iter().enumerate() {
for (ri, (_, tuples)) in per_inst.iter().enumerate() {
for t in tuples {
let t_colors: Vec<usize> = t.iter().map(|&x| colors[x]).collect();
for (pos, &a) in t.iter().enumerate() {
refined[a].1.push((ii, ri, pos, t_colors.clone()));
}
}
}
}
for (_, nbrs) in &mut refined {
nbrs.sort();
}
let unique: std::collections::BTreeSet<_> = refined.iter().cloned().collect();
let palette: BTreeMap<_, usize> = unique
.into_iter()
.enumerate()
.map(|(id, sig)| (sig, id))
.collect();
for a in 0..n {
colors[a] = palette[&refined[a]];
}
}
let mut base_perm: Vec<usize> = (0..n).collect();
let mut perm_blocks: Vec<(Vec<usize>, Vec<usize>)> = Vec::new();
for part in sym_parts {
let mut by_color: BTreeMap<usize, Vec<usize>> = BTreeMap::new();
for &a in part {
if a < n {
by_color.entry(colors[a]).or_default().push(a);
}
}
let mut cursor = 0usize;
for (_, group) in by_color {
let slots: Vec<usize> = part[cursor..cursor + group.len()].to_vec();
cursor += group.len();
let is_active = group.iter().any(|&a| active[a]);
if is_active && group.len() > 1 {
perm_blocks.push((group, slots));
} else {
for (&a, &s) in group.iter().zip(&slots) {
base_perm[a] = s;
}
}
}
}
let apply_perm = |perm: &[usize]| -> Vec<Vec<Vec<Vec<usize>>>> {
rel_data
.iter()
.map(|per_inst| {
per_inst
.iter()
.map(|(_, tuples)| {
let mut mapped: Vec<Vec<usize>> = tuples
.iter()
.map(|t| t.iter().map(|&a| perm[a]).collect())
.collect();
mapped.sort();
mapped
})
.collect()
})
.collect()
};
let total_perms: usize = perm_blocks
.iter()
.try_fold(1usize, |acc, (g, _)| {
let fact = (1..=g.len()).try_fold(1usize, |f, k| f.checked_mul(k))?;
acc.checked_mul(fact)
})
.unwrap_or(usize::MAX);
if total_perms > 4096 || perm_blocks.is_empty() {
for (group, slots) in &perm_blocks {
for (&a, &s) in group.iter().zip(slots) {
base_perm[a] = s;
}
}
return (loop_to, apply_perm(&base_perm));
}
fn next_permutation(a: &mut [usize]) -> bool {
if a.len() < 2 {
return false;
}
let mut i = a.len() - 2;
while a[i] >= a[i + 1] {
if i == 0 {
return false;
}
i -= 1;
}
let mut j = a.len() - 1;
while a[j] <= a[i] {
j -= 1;
}
a.swap(i, j);
a[i + 1..].reverse();
true
}
let mut best: Option<Vec<Vec<Vec<Vec<usize>>>>> = None;
let mut cur_perm = base_perm;
fn search_blocks(
bi: usize,
blocks: &[(Vec<usize>, Vec<usize>)],
cur_perm: &mut [usize],
apply_perm: &impl Fn(&[usize]) -> Vec<Vec<Vec<Vec<usize>>>>,
best: &mut Option<Vec<Vec<Vec<Vec<usize>>>>>,
) {
if bi == blocks.len() {
let cand = apply_perm(cur_perm);
if best.as_ref().is_none_or(|b| cand < *b) {
*best = Some(cand);
}
return;
}
let (group, slots) = &blocks[bi];
let mut order: Vec<usize> = slots.clone();
order.sort();
loop {
for (&a, &s) in group.iter().zip(&order) {
cur_perm[a] = s;
}
search_blocks(bi + 1, blocks, cur_perm, apply_perm, best);
if !next_permutation(&mut order) {
break;
}
}
}
search_blocks(0, &perm_blocks, &mut cur_perm, &apply_perm, &mut best);
(loop_to, best.unwrap_or_default())
}
pub fn run_all(
file: &str,
text: &str,
name: Option<&str>,
over: Overrides,
as_sql: bool,
limit: usize,
allow_local_modules: bool,
) -> Output {
let model = match read_model_with_bw(
"run",
file,
text,
allow_local_modules,
over.default_bitwidth,
) {
Ok(m) => m,
Err(out) => return out,
};
let chosen: Vec<_> = model
.commands
.iter()
.filter(|c| !c.check && name.is_none_or(|n| c.name == n))
.collect();
if chosen.is_empty() {
let what = match name {
Some(n) => format!("the file has no run command named `{n}`"),
None => "the file has no run command".to_string(),
};
return error_output("run", vec![coded("als.no_command", what)]);
}
let spec = chosen[0];
let mut cmd = model.command(spec);
if let Some(k) = over.scope {
cmd = cmd.scope(k);
}
cmd = with_steps(cmd, &model, over.steps);
if let Some(b) = budget_from_overrides(over, 10_000_000) {
cmd = cmd.budget(b);
}
let sym_parts: Vec<Vec<usize>> = match cmd.bounds() {
Ok(b) => elinvar_engine::symmetry_partition(&b)
.into_iter()
.map(|p| p.into_iter().map(|a| a as usize).collect())
.collect(),
Err(errors) => return error_output("run", errors),
};
let mut iter = match cmd.iter_instances() {
Ok(it) => it,
Err(errors) => return error_output("run", errors),
};
let mut seen_keys: std::collections::BTreeSet<CanonKey> = std::collections::BTreeSet::new();
let mut items_json = Vec::new();
let mut sql_scripts = Vec::new();
let mut text = String::new();
let mut truncated = false;
for next in iter.by_ref() {
let key = match &next {
elinvar_engine::Next::Instance(inst) => canonical_key(&[inst], 0, &sym_parts),
elinvar_engine::Next::Trace(tr) => {
let mut refs: Vec<&Instance> = Vec::with_capacity(1 + tr.states().len());
refs.push(tr.fixed());
for s in tr.states() {
refs.push(s);
}
canonical_key(&refs, tr.loop_to(), &sym_parts)
}
_ => break,
};
if !seen_keys.insert(key) {
continue;
}
if items_json.len() >= limit {
truncated = true;
break;
}
let idx = items_json.len() + 1;
match next {
elinvar_engine::Next::Instance(inst) => {
if as_sql {
let s = render_instance(&inst, DiagramFormat::Sql);
sql_scripts.push(s.clone());
text.push_str(&format!("-- instance {idx}\n{s}\n"));
} else {
text.push_str(&format!("instance {idx}:\n"));
for (r, ts) in inst.entries() {
if !ts.is_empty() && !r.name().starts_with('$') {
text.push_str(&format!(" {} = {ts}\n", r.name()));
}
}
}
items_json.push(serde_json::to_value(&inst).unwrap_or(Value::Null));
}
elinvar_engine::Next::Trace(tr) => {
if as_sql {
let s = render_states(tr.fixed(), tr.states(), None, DiagramFormat::Sql);
sql_scripts.push(s.clone());
text.push_str(&format!("-- trace {idx}\n{s}\n"));
} else {
text.push_str(&format!(
"trace {idx}: {} state(s), loop to {}\n",
tr.states().len(),
tr.loop_to()
));
}
items_json.push(serde_json::to_value(&tr).unwrap_or(Value::Null));
}
_ => break,
}
}
let complete = !truncated && !iter.hit_budget();
let count = items_json.len();
let status = if iter.hit_budget() {
2
} else if count == 0 {
1
} else {
0
};
let tail = if complete {
format!("enumerated all {count} instance(s) for `{}`.\n", spec.name)
} else if truncated {
format!(
"enumerated {count} instance(s) for `{}` (stopped at --limit {limit}).\n",
spec.name
)
} else {
format!(
"enumerated {count} instance(s) for `{}` (solver budget ran out before finishing).\n",
spec.name
)
};
text.push_str(&tail);
let mut obj = json!({
"elinvar": 1,
"command": "run",
"name": spec.name,
"count": count,
"complete": complete,
"instances": items_json,
});
if as_sql {
obj["sql"] = json!(sql_scripts);
}
Output {
json: obj,
text,
status,
}
}
#[derive(Clone, Debug, Default)]
pub struct TestsOptions {
pub as_sql: bool,
pub tables: Vec<String>,
pub with_referencing: bool,
pub sample_values: std::collections::BTreeMap<String, Vec<String>>,
pub allow_dead: Vec<String>,
pub extra_als: Option<String>,
}
fn parse_expect_dead_pragmas(text: &str) -> Vec<String> {
let mut out = Vec::new();
for line in text.lines() {
let t = line.trim();
let rest = t
.strip_prefix("--")
.or_else(|| t.strip_prefix("//"))
.map(str::trim);
if let Some(r) = rest
&& let Some(after) = r
.strip_prefix("expect-dead:")
.or_else(|| r.strip_prefix("expect_dead:"))
{
for item in after.split(',') {
let s = item.trim();
if !s.is_empty() && !out.iter().any(|x| x == s) {
out.push(s.to_string());
}
}
}
}
out
}
fn format_test_case(n: usize, c: &elinvar_engine::TestCase, expected_dead: bool) -> String {
let mut s = String::new();
match c.kind {
elinvar_engine::TestKind::Allowed => {
let len = c.trace.as_ref().map_or(0, |t| t.states.len());
s.push_str(&format!(
"test {n}: ALLOWED step `{}` ({len} states)\n",
c.step
));
if let Some(sql) = &c.sql {
s.push_str(sql);
s.push('\n');
}
}
elinvar_engine::TestKind::Refused => {
let rule = c.rule.as_deref().unwrap_or("");
let len = c.trace.as_ref().map_or(0, |t| t.states.len());
s.push_str(&format!(
"test {n}: REFUSED step `{}` by `{rule}` ({len} states)\n",
c.step
));
if let Some(sql) = &c.sql {
s.push_str(sql);
s.push('\n');
}
}
elinvar_engine::TestKind::DeadStep => {
let tag = if expected_dead {
"DEAD STEP (expected)"
} else {
"DEAD STEP"
};
s.push_str(&format!(
"test {n}: {tag} `{}` ({})\n",
c.step,
c.note.as_deref().unwrap_or("unreachable")
));
}
elinvar_engine::TestKind::UnreachableGuard => {
let rule = c.rule.as_deref().unwrap_or("");
s.push_str(&format!(
"test {n}: UNREACHABLE GUARD `{}`: `{rule}` ({})\n",
c.step,
c.note.as_deref().unwrap_or("never decides")
));
}
elinvar_engine::TestKind::NotReached => {
let what = match &c.rule {
Some(r) => format!("`{}`: `{r}`", c.step),
None => format!("`{}`", c.step),
};
s.push_str(&format!(
"test {n}: NOT REACHED {what} ({})\n",
c.note.as_deref().unwrap_or("not reached within step bound")
));
}
elinvar_engine::TestKind::Unknown => {
let what = match &c.rule {
Some(r) => format!("`{}`: `{r}`", c.step),
None => format!("`{}`", c.step),
};
s.push_str(&format!(
"test {n}: UNKNOWN {what} ({})\n",
c.note.as_deref().unwrap_or("budget ran out")
));
}
_ => {}
}
s
}
pub fn tests(file: &str, text: &str, over: Overrides, as_sql: bool) -> Output {
tests_with_options(
file,
text,
over,
&TestsOptions {
as_sql,
..Default::default()
},
true,
None,
)
}
pub fn tests_inline(file: &str, text: &str, over: Overrides, as_sql: bool) -> Output {
tests_with_options(
file,
text,
over,
&TestsOptions {
as_sql,
..Default::default()
},
false,
None,
)
}
pub fn tests_with_options(
file: &str,
text: &str,
over: Overrides,
opts: &TestsOptions,
allow_local_modules: bool,
mut stream: Option<&mut dyn FnMut(&str)>,
) -> Output {
let mut sample_values = std::collections::BTreeMap::new();
let mut trigger_targets: std::collections::BTreeMap<String, Vec<String>> =
std::collections::BTreeMap::new();
let mut max_fk_depth = 0usize;
let is_sql = file.ends_with(".sql");
let model = if is_sql {
let imp = match elinvar_als::import_sql_with(
file,
text,
&elinvar_als::SqlImportOptions::new()
.temporal(true)
.from_empty(true)
.tables(opts.tables.clone())
.with_referencing(opts.with_referencing),
) {
Ok(i) => i,
Err(errors) => return error_output("tests", errors),
};
sample_values = imp.sample_values;
max_fk_depth = imp.max_fk_depth;
let mut sql_to_alloy: std::collections::BTreeMap<String, String> =
std::collections::BTreeMap::new();
for (a, s) in &imp.alloy_to_sql_table {
sql_to_alloy.insert(s.clone(), a.clone());
}
for tr in &imp.after_triggers {
let src_alloy = sql_to_alloy
.get(&tr.source_table)
.cloned()
.unwrap_or_else(|| tr.source_table.clone());
let tgt_alloy = sql_to_alloy
.get(&tr.target_table)
.cloned()
.unwrap_or_else(|| tr.target_table.clone());
let entry = trigger_targets.entry(src_alloy).or_default();
if !entry.contains(&tgt_alloy) {
entry.push(tgt_alloy);
}
}
let combined_als = match &opts.extra_als {
Some(extra) if !extra.trim().is_empty() => format!("{}\n{extra}\n", imp.model),
_ => imp.model,
};
match read_model_with_bw("tests", file, &combined_als, false, Some(imp.bitwidth)) {
Ok(m) => m,
Err(out) => return out,
}
} else {
let combined_als = match &opts.extra_als {
Some(extra) if !extra.trim().is_empty() => format!("{text}\n{extra}\n"),
_ => text.to_string(),
};
match read_model("tests", file, &combined_als, allow_local_modules) {
Ok(m) => m,
Err(out) => return out,
}
};
for (k, v) in &opts.sample_values {
sample_values.insert(k.to_ascii_lowercase(), v.clone());
}
let mut allow_dead = parse_expect_dead_pragmas(text);
if let Some(extra) = &opts.extra_als {
for d in parse_expect_dead_pragmas(extra) {
if !allow_dead.iter().any(|x| x == &d) {
allow_dead.push(d);
}
}
}
for d in &opts.allow_dead {
if !allow_dead.iter().any(|x| x == d) {
allow_dead.push(d.clone());
}
}
let scope = over.scope.unwrap_or(3);
let default_steps = if is_sql { (max_fk_depth + 3).max(5) } else { 4 };
let steps = over.steps.unwrap_or(default_steps);
let budget = budget_from_overrides(over, 10_000_000).unwrap_or_default();
let mut out_text = String::new();
let mut idx = 0usize;
let cases = match model.model.generate_tests_for_tables(
scope,
steps,
budget,
opts.as_sql,
&sample_values,
&opts.tables,
&trigger_targets,
|c| {
idx += 1;
let expected_dead = c.kind == elinvar_engine::TestKind::DeadStep
&& allow_dead.iter().any(|d| d == &c.step);
let chunk = format_test_case(idx, c, expected_dead);
out_text.push_str(&chunk);
if let Some(cb) = stream.as_deref_mut() {
cb(&chunk);
}
},
) {
Ok(c) => c,
Err(errors) => return error_output("tests", errors),
};
let mut dead_steps = Vec::new();
let mut expected_dead_steps = Vec::new();
let mut unreachable_guards = Vec::new();
let mut not_reached = Vec::new();
let mut unfinished = Vec::new();
for c in &cases {
match c.kind {
elinvar_engine::TestKind::DeadStep => {
if allow_dead.iter().any(|d| d == &c.step) {
expected_dead_steps.push(c.step.clone());
} else {
dead_steps.push(c.step.clone());
}
}
elinvar_engine::TestKind::UnreachableGuard => {
let rule = c.rule.as_deref().unwrap_or("");
unreachable_guards.push(format!("{}: `{rule}`", c.step));
}
elinvar_engine::TestKind::NotReached => {
let label = match &c.rule {
Some(r) => format!("{}: `{r}`", c.step),
None => c.step.clone(),
};
not_reached.push(label);
}
elinvar_engine::TestKind::Unknown => {
let label = match &c.rule {
Some(r) => format!("{}: `{r}`", c.step),
None => c.step.clone(),
};
unfinished.push(label);
}
_ => {}
}
}
if cases.is_empty() {
let msg = "no step predicates found in model.\n";
out_text.push_str(msg);
if let Some(cb) = stream.as_deref_mut() {
cb(msg);
}
}
if !not_reached.is_empty() {
let tail = format!(
"not reached within {steps} steps (raise --steps): {}\n",
not_reached.join(", ")
);
out_text.push_str(&tail);
if let Some(cb) = stream.as_deref_mut() {
cb(&tail);
}
}
if !unfinished.is_empty() {
let tail = format!("unfinished (budget ran out): {}\n", unfinished.join(", "));
out_text.push_str(&tail);
if let Some(cb) = stream {
cb(&tail);
}
}
let status = if !unfinished.is_empty() || !not_reached.is_empty() {
2
} else if !dead_steps.is_empty() || !unreachable_guards.is_empty() {
1
} else {
0
};
let json = json!({
"elinvar": 1,
"command": "tests",
"scope": scope,
"steps": steps,
"cases": cases,
"dead_steps": dead_steps,
"expected_dead_steps": expected_dead_steps,
"unreachable_guards": unreachable_guards,
"not_reached": not_reached,
"unfinished": unfinished,
});
Output {
json,
text: out_text,
status,
}
}
pub fn accepts(file: &str, text: &str, trace_text: &str) -> Output {
accepts_with_modules(file, text, trace_text, true, None, &[], false)
}
pub fn accepts_with_options(
file: &str,
text: &str,
trace_text: &str,
allow_local_modules: bool,
extra_als: Option<&str>,
tables: &[String],
with_referencing: bool,
) -> Output {
accepts_with_modules(
file,
text,
trace_text,
allow_local_modules,
extra_als,
tables,
with_referencing,
)
}
#[derive(Default)]
struct SqlAcceptsMeta {
alloy_to_sql_table: std::collections::BTreeMap<String, String>,
alloy_retired_to_sql_table: std::collections::BTreeMap<String, String>,
alloy_to_sql_col: std::collections::BTreeMap<(String, String), String>,
after_triggers: Vec<elinvar_als::SqlAfterTrigger>,
fk_targets: std::collections::BTreeMap<(String, String), elinvar_als::SqlFkTarget>,
col_defaults: std::collections::BTreeMap<(String, String), elinvar_als::SqlDefault>,
enum_values: std::collections::BTreeMap<(String, String), Vec<String>>,
before_update_of_triggers: Vec<elinvar_als::SqlBeforeUpdateOfTrigger>,
date_format: Option<String>,
date_shifts: Vec<elinvar_als::SqlDateShift>,
ord_shifts: Vec<elinvar_als::SqlOrdShift>,
int_regions: std::collections::BTreeMap<String, elinvar_als::SqlIntRegion>,
text_checks: Vec<elinvar_als::SqlTextCheck>,
table_columns: std::collections::BTreeMap<String, Vec<String>>,
unread_rules: usize,
}
pub(crate) struct CompiledSqlModel {
pub import: elinvar_als::SqlImport,
pub model: AlsModel,
meta: SqlAcceptsMeta,
}
pub(crate) fn compile_sql_for_fuzz(
file: &str,
sql_text: &str,
extra_als: Option<&str>,
tables: &[String],
with_referencing: bool,
) -> Result<CompiledSqlModel, Output> {
let imp = elinvar_als::import_sql_with(
file,
sql_text,
&elinvar_als::SqlImportOptions::new()
.temporal(true)
.tables(tables.to_vec())
.with_referencing(with_referencing),
)
.map_err(|errors| error_output("fuzz", errors))?;
let combined = match extra_als {
Some(extra) if !extra.trim().is_empty() => format!("{}\n{extra}\n", imp.model),
_ => imp.model.clone(),
};
let model = read_model_with_bw("fuzz", file, &combined, false, Some(imp.bitwidth))?;
let table_columns: std::collections::BTreeMap<String, Vec<String>> = imp
.table_columns
.iter()
.map(|(t, cols)| {
(
t.to_ascii_lowercase(),
cols.iter()
.map(|c| c.sql_name.to_ascii_lowercase())
.collect(),
)
})
.collect();
let meta = SqlAcceptsMeta {
alloy_to_sql_table: imp.alloy_to_sql_table.clone(),
alloy_retired_to_sql_table: imp.alloy_retired_to_sql_table.clone(),
alloy_to_sql_col: imp.alloy_to_sql_col.clone(),
after_triggers: imp.after_triggers.clone(),
fk_targets: imp.fk_targets.clone(),
col_defaults: imp.col_defaults.clone(),
enum_values: imp.enum_values.clone(),
before_update_of_triggers: imp.before_update_of_triggers.clone(),
date_format: imp.date_format.clone(),
date_shifts: imp.date_shifts.clone(),
ord_shifts: imp.ord_shifts.clone(),
int_regions: imp
.int_regions
.iter()
.map(|r| (r.sig_name.clone(), r.clone()))
.collect(),
text_checks: imp.text_checks.clone(),
table_columns,
unread_rules: imp.skipped.len(),
};
Ok(CompiledSqlModel {
import: imp,
model,
meta,
})
}
pub(crate) fn eval_sql_script_on_compiled(
compiled: &CompiledSqlModel,
script: &str,
) -> Result<(bool, Vec<String>), String> {
match evaluate_sql_script(&compiled.model, script, &compiled.meta) {
Ok((_, _, failed_rules, refused_by_stmt)) => {
let allowed = failed_rules.is_empty();
let reasons = refused_by_stmt
.values()
.next_back()
.cloned()
.unwrap_or(failed_rules);
Ok((allowed, reasons))
}
Err(SqlScriptEvalError::Parse(m)) => Err(m),
Err(SqlScriptEvalError::Logic(errs)) => Err(errs
.into_iter()
.map(|e| e.message)
.collect::<Vec<_>>()
.join("; ")),
}
}
fn accepts_with_modules(
file: &str,
text: &str,
trace_text: &str,
allow_local_modules: bool,
extra_als: Option<&str>,
tables: &[String],
with_referencing: bool,
) -> Output {
let (model, meta) = if file.ends_with(".sql") {
let imp = match elinvar_als::import_sql_with(
file,
text,
&elinvar_als::SqlImportOptions::new()
.temporal(true)
.tables(tables.to_vec())
.with_referencing(with_referencing),
) {
Ok(i) => i,
Err(errors) => return error_output("accepts", errors),
};
let combined = match extra_als {
Some(extra) if !extra.trim().is_empty() => format!("{}\n{extra}\n", imp.model),
_ => imp.model,
};
let m = match read_model_with_bw("accepts", file, &combined, false, Some(imp.bitwidth)) {
Ok(m) => m,
Err(out) => return out,
};
let table_columns: std::collections::BTreeMap<String, Vec<String>> = imp
.table_columns
.iter()
.map(|(t, cols)| {
(
t.to_ascii_lowercase(),
cols.iter()
.map(|c| c.sql_name.to_ascii_lowercase())
.collect(),
)
})
.collect();
let meta = SqlAcceptsMeta {
alloy_to_sql_table: imp.alloy_to_sql_table,
alloy_retired_to_sql_table: imp.alloy_retired_to_sql_table,
alloy_to_sql_col: imp.alloy_to_sql_col,
after_triggers: imp.after_triggers,
fk_targets: imp.fk_targets,
col_defaults: imp.col_defaults,
enum_values: imp.enum_values,
before_update_of_triggers: imp.before_update_of_triggers,
date_format: imp.date_format,
date_shifts: imp.date_shifts,
ord_shifts: imp.ord_shifts,
int_regions: imp
.int_regions
.into_iter()
.map(|r| (r.sig_name.clone(), r))
.collect(),
text_checks: imp.text_checks,
table_columns,
unread_rules: imp.skipped.len(),
};
(m, meta)
} else {
let combined = match extra_als {
Some(extra) if !extra.trim().is_empty() => format!("{text}\n{extra}\n"),
_ => text.to_string(),
};
let m = match read_model("accepts", file, &combined, allow_local_modules) {
Ok(m) => m,
Err(out) => return out,
};
(m, SqlAcceptsMeta::default())
};
let relations = model.model.relations();
let trimmed = trace_text.trim();
let (trace, dml_stmts, failed_rules, refused_by_stmt) = if trimmed.starts_with('{') {
let val: Value = match serde_json::from_str(trimmed) {
Ok(v) => v,
Err(e) => return eval_error(format!("trace JSON could not be parsed: {e}")),
};
let trace = match trace_of(&val, &relations) {
Ok(t) => t,
Err(m) => return eval_error(m),
};
let mut failed_rules = Vec::new();
for (rname, rformula) in model.model.all_facts_named() {
match elinvar_engine::logic::evaluate_trace(&trace, &rformula) {
Ok(true) => {}
Ok(false) => failed_rules.push(rname),
Err(errors) => return error_output("accepts", errors),
}
}
(
trace,
Vec::new(),
failed_rules,
std::collections::BTreeMap::new(),
)
} else {
match evaluate_sql_script(&model, trace_text, &meta) {
Ok(res) => res,
Err(SqlScriptEvalError::Parse(m)) => return sql_script_error(m),
Err(SqlScriptEvalError::Logic(errors)) => return error_output("accepts", errors),
}
};
let allowed = failed_rules.is_empty();
let mut checks_json = Vec::new();
let mut all_checks_hold = true;
let mut out_text = String::new();
if allowed {
out_text.push_str(&format!(
"accepts: ALLOWED ({} state(s))\n",
trace.states().len()
));
} else {
out_text.push_str(&format!(
"accepts: REFUSED ({} state(s))\n",
trace.states().len()
));
for (si, reasons) in &refused_by_stmt {
let st = &dml_stmts[*si];
out_text.push_str(&format!(
" line {}: `{}`: refused by {}\n",
st.line,
st.sql,
reasons.join(", ")
));
}
out_text.push_str(&format!(" failed rules: {}\n", failed_rules.join(", ")));
}
if meta.unread_rules > 0 {
let (noun, verb) = if meta.unread_rules == 1 {
("rule", "is")
} else {
("rules", "are")
};
out_text.push_str(&format!(
"warning: {} {noun} of the schema {verb} not read; a statement they refuse is allowed here\n",
meta.unread_rules
));
}
for spec in &model.commands {
if !spec.check {
continue;
}
let cmd = model.command(spec);
match elinvar_engine::logic::evaluate_trace(&trace, cmd.formula()) {
Ok(holds) => {
if !holds {
all_checks_hold = false;
}
let word = if holds { "holds" } else { "BROKEN" };
out_text.push_str(&format!(" check {}: {word}\n", spec.name));
checks_json.push(json!({ "name": spec.name, "holds": holds }));
}
Err(errors) => return error_output("accepts", errors),
}
}
let refused_json: Vec<Value> = refused_by_stmt
.iter()
.map(|(&si, reasons)| {
let st = &dml_stmts[si];
json!({
"line": st.line,
"statement": st.sql,
"rules": reasons,
})
})
.collect();
let status = if allowed && all_checks_hold { 0 } else { 1 };
let mut json = json!({
"elinvar": 1,
"command": "accepts",
"allowed": allowed,
"failed_rules": failed_rules,
"checks": checks_json,
"all_checks_hold": all_checks_hold,
});
if meta.unread_rules > 0 {
json["unread_rules"] = json!(meta.unread_rules);
}
if !refused_json.is_empty() {
json["refused_statements"] = json!(refused_json);
}
Output {
json,
text: out_text,
status,
}
}
fn diagnose_refused_guards(model: &AlsModel, trace: &Trace, k: usize) -> Vec<String> {
let mut out = Vec::new();
for spec in model.model.step_specs() {
if spec.guards.is_empty() {
continue;
}
let mut domains: Vec<Vec<usize>> = Vec::with_capacity(spec.vars.len());
let mut empty = false;
for r in &spec.ranges {
let atoms: Vec<usize> = match elinvar_engine::logic::evaluate_trace_expr_at(trace, r, k)
{
Ok(ts) => ts.indices().map(|i| i as usize).collect(),
Err(_) => Vec::new(),
};
if atoms.is_empty() {
empty = true;
break;
}
domains.push(atoms);
}
if empty {
continue;
}
let total: usize = domains
.iter()
.try_fold(1usize, |acc, d| acc.checked_mul(d.len()))
.unwrap_or(0);
if total == 0 || total > 256 {
continue;
}
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<(elinvar_engine::logic::Variable, usize)> = spec
.vars
.iter()
.cloned()
.zip(atoms.iter().copied())
.collect();
if elinvar_engine::logic::evaluate_trace_at(trace, &spec.effect, k, &bindings)
== Ok(true)
{
for g in &spec.guards {
if elinvar_engine::logic::evaluate_trace_at(trace, &g.formula, k, &bindings)
== Ok(false)
{
let label = format!("{}: `{}`", spec.name, g.label);
if !out.contains(&label) {
out.push(label);
}
}
}
}
}
}
out
}
#[derive(Clone, Debug)]
struct DmlStmt {
line: usize,
sql: String,
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
enum DmlVal {
Null,
Bool(bool),
Int(i64),
Str(String),
}
fn parse_dml_val_strict(raw: &str, line: usize) -> Result<DmlVal, String> {
let t = raw.trim();
if t.eq_ignore_ascii_case("null") {
Ok(DmlVal::Null)
} else if t.eq_ignore_ascii_case("true") {
Ok(DmlVal::Bool(true))
} else if t.eq_ignore_ascii_case("false") {
Ok(DmlVal::Bool(false))
} else if t.starts_with('\'') && t.ends_with('\'') && t.len() >= 2 {
let inner = &t[1..t.len() - 1];
let mut chars = inner.chars().peekable();
let mut out = String::new();
while let Some(c) = chars.next() {
if c == '\'' {
if chars.peek() == Some(&'\'') {
chars.next();
out.push('\'');
} else {
return Err(format!(
"line {line}: unsupported value expression `{t}` in SQL script"
));
}
} else {
out.push(c);
}
}
Ok(DmlVal::Str(out))
} else if (t.starts_with("x'") || t.starts_with("X'")) && t.ends_with('\'') && t.len() >= 3 {
let hex = &t[2..t.len() - 1];
if hex.len().is_multiple_of(2) && hex.bytes().all(|b| b.is_ascii_hexdigit()) {
Ok(DmlVal::Str(format!("x'{}'", hex.to_ascii_lowercase())))
} else {
Err(format!(
"line {line}: invalid hex BLOB literal `{t}` in SQL script"
))
}
} else if let Ok(n) = t.parse::<i64>() {
Ok(DmlVal::Int(n))
} else {
Err(format!(
"line {line}: unsupported value expression `{t}` in SQL script"
))
}
}
#[derive(Clone, Debug)]
enum DmlSetExpr {
Lit(DmlVal),
Col(String),
Add(Box<DmlSetExpr>, Box<DmlSetExpr>),
Sub(Box<DmlSetExpr>, Box<DmlSetExpr>),
Mul(Box<DmlSetExpr>, Box<DmlSetExpr>),
}
impl DmlSetExpr {
fn eval(
&self,
row: &std::collections::BTreeMap<String, DmlVal>,
line: usize,
) -> Result<DmlVal, String> {
match self {
DmlSetExpr::Lit(v) => Ok(v.clone()),
DmlSetExpr::Col(c) => Ok(row.get(c).cloned().unwrap_or(DmlVal::Null)),
DmlSetExpr::Add(a, b) | DmlSetExpr::Sub(a, b) | DmlSetExpr::Mul(a, b) => {
let lv = a.eval(row, line)?;
let rv = b.eval(row, line)?;
if matches!(lv, DmlVal::Null) || matches!(rv, DmlVal::Null) {
return Ok(DmlVal::Null);
}
let (DmlVal::Int(x), DmlVal::Int(y)) = (lv, rv) else {
return Err(format!(
"line {line}: arithmetic in SET requires integer operands"
));
};
let res = match self {
DmlSetExpr::Add(_, _) => x.checked_add(y),
DmlSetExpr::Sub(_, _) => x.checked_sub(y),
DmlSetExpr::Mul(_, _) => x.checked_mul(y),
_ => unreachable!(),
};
res.map(DmlVal::Int)
.ok_or_else(|| format!("line {line}: integer overflow in SET expression"))
}
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
enum SetTok {
Ident(String),
Num(i64),
Plus,
Minus,
Star,
LParen,
RParen,
}
fn tokenize_set_arith(raw: &str) -> Option<Vec<SetTok>> {
let bytes = raw.as_bytes();
let mut i = 0;
let mut out = Vec::new();
while i < bytes.len() {
let b = bytes[i];
if b.is_ascii_whitespace() {
i += 1;
continue;
}
match b {
b'+' => {
out.push(SetTok::Plus);
i += 1;
}
b'-' => {
out.push(SetTok::Minus);
i += 1;
}
b'*' => {
out.push(SetTok::Star);
i += 1;
}
b'(' => {
out.push(SetTok::LParen);
i += 1;
}
b')' => {
out.push(SetTok::RParen);
i += 1;
}
b'"' => {
i += 1;
let start = i;
while i < bytes.len() && bytes[i] != b'"' {
i += 1;
}
if i >= bytes.len() || i == start {
return None;
}
out.push(SetTok::Ident(raw[start..i].to_ascii_lowercase()));
i += 1;
}
_ if b.is_ascii_digit() => {
let start = i;
while i < bytes.len() && bytes[i].is_ascii_digit() {
i += 1;
}
let n = raw[start..i].parse::<i64>().ok()?;
out.push(SetTok::Num(n));
}
_ if b.is_ascii_alphabetic() || b == b'_' => {
let start = i;
while i < bytes.len() && (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_') {
i += 1;
}
out.push(SetTok::Ident(raw[start..i].to_ascii_lowercase()));
}
_ => return None,
}
}
if out.is_empty() { None } else { Some(out) }
}
fn parse_set_add(toks: &[SetTok], pos: &mut usize) -> Option<DmlSetExpr> {
let mut lhs = parse_set_mul(toks, pos)?;
while let Some(tok) = toks.get(*pos) {
match tok {
SetTok::Plus => {
*pos += 1;
let rhs = parse_set_mul(toks, pos)?;
lhs = DmlSetExpr::Add(Box::new(lhs), Box::new(rhs));
}
SetTok::Minus => {
*pos += 1;
let rhs = parse_set_mul(toks, pos)?;
lhs = DmlSetExpr::Sub(Box::new(lhs), Box::new(rhs));
}
_ => break,
}
}
Some(lhs)
}
fn parse_set_mul(toks: &[SetTok], pos: &mut usize) -> Option<DmlSetExpr> {
let mut lhs = parse_set_primary(toks, pos)?;
while matches!(toks.get(*pos), Some(SetTok::Star)) {
*pos += 1;
let rhs = parse_set_primary(toks, pos)?;
lhs = DmlSetExpr::Mul(Box::new(lhs), Box::new(rhs));
}
Some(lhs)
}
fn parse_set_primary(toks: &[SetTok], pos: &mut usize) -> Option<DmlSetExpr> {
match toks.get(*pos)? {
SetTok::Minus => {
*pos += 1;
let inner = parse_set_primary(toks, pos)?;
Some(DmlSetExpr::Sub(
Box::new(DmlSetExpr::Lit(DmlVal::Int(0))),
Box::new(inner),
))
}
SetTok::Num(n) => {
*pos += 1;
Some(DmlSetExpr::Lit(DmlVal::Int(*n)))
}
SetTok::Ident(name) => {
if matches!(toks.get(*pos + 1), Some(SetTok::LParen)) {
return None;
}
*pos += 1;
Some(DmlSetExpr::Col(name.clone()))
}
SetTok::LParen => {
*pos += 1;
let inner = parse_set_add(toks, pos)?;
if !matches!(toks.get(*pos), Some(SetTok::RParen)) {
return None;
}
*pos += 1;
Some(inner)
}
_ => None,
}
}
fn parse_dml_set_expr(raw: &str, line: usize) -> Result<DmlSetExpr, String> {
if let Ok(lit) = parse_dml_val_strict(raw, line) {
return Ok(DmlSetExpr::Lit(lit));
}
if let Some(toks) = tokenize_set_arith(raw) {
let mut pos = 0;
if let Some(expr) = parse_set_add(&toks, &mut pos)
&& pos == toks.len()
{
return Ok(expr);
}
}
Err(format!(
"line {line}: unsupported SET expression `{}` in SQL script",
raw.trim()
))
}
fn split_once_kw<'a>(s: &'a str, kw: &str) -> Option<(&'a str, &'a str)> {
let bytes = s.as_bytes();
let klen = kw.len();
let mut i = 0;
let mut in_str = false;
let mut depth = 0usize;
while i < bytes.len() {
let b = bytes[i];
if in_str {
if b == b'\'' {
if bytes.get(i + 1) == Some(&b'\'') {
i += 2;
continue;
}
in_str = false;
}
i += 1;
continue;
}
if b == b'\'' {
in_str = true;
i += 1;
continue;
}
if b == b'(' {
depth += 1;
i += 1;
continue;
}
if b == b')' {
depth = depth.saturating_sub(1);
i += 1;
continue;
}
if depth == 0 && i + klen <= bytes.len() {
let before_ok =
i == 0 || !(bytes[i - 1].is_ascii_alphanumeric() || bytes[i - 1] == b'_');
let after_ok = i + klen == bytes.len()
|| !(bytes[i + klen].is_ascii_alphanumeric() || bytes[i + klen] == b'_');
if before_ok && after_ok && s[i..i + klen].eq_ignore_ascii_case(kw) {
return Some((&s[..i], &s[i + klen..]));
}
}
i += 1;
}
None
}
fn split_value_tuples(s: &str) -> Option<Vec<&str>> {
let bytes = s.as_bytes();
let mut i = 0;
let mut out = Vec::new();
while i < bytes.len() {
while i < bytes.len() && bytes[i].is_ascii_whitespace() {
i += 1;
}
if i >= bytes.len() {
break;
}
if bytes[i] != b'(' {
return None;
}
let start = i + 1;
let mut depth = 1usize;
let mut in_str = false;
i += 1;
while i < bytes.len() && depth > 0 {
let b = bytes[i];
if in_str {
if b == b'\'' {
if bytes.get(i + 1) == Some(&b'\'') {
i += 2;
continue;
}
in_str = false;
}
i += 1;
continue;
}
if b == b'\'' {
in_str = true;
} else if b == b'(' {
depth += 1;
} else if b == b')' {
depth -= 1;
if depth == 0 {
out.push(&s[start..i]);
i += 1;
break;
}
}
i += 1;
}
if depth != 0 {
return None;
}
while i < bytes.len() && bytes[i].is_ascii_whitespace() {
i += 1;
}
if i < bytes.len() {
if bytes[i] == b',' {
i += 1;
} else {
return None;
}
}
}
Some(out)
}
fn split_csv_values(s: &str) -> Vec<String> {
let mut out = Vec::new();
let mut cur = String::new();
let mut in_str = false;
let mut depth = 0usize;
let mut chars = s.chars().peekable();
while let Some(c) = chars.next() {
if in_str {
cur.push(c);
if c == '\'' {
if chars.peek() == Some(&'\'') {
cur.push(chars.next().expect("peeked"));
} else {
in_str = false;
}
}
} else if c == '\'' {
in_str = true;
cur.push(c);
} else if c == '(' {
depth += 1;
cur.push(c);
} else if c == ')' {
depth = depth.saturating_sub(1);
cur.push(c);
} else if c == ',' && depth == 0 {
out.push(cur.trim().to_string());
cur.clear();
} else {
cur.push(c);
}
}
if !cur.trim().is_empty() {
out.push(cur.trim().to_string());
}
out
}
enum SqlScriptEvalError {
Parse(String),
Logic(Vec<Error>),
}
enum BuildSqlError {
Refused(String),
Parse(String),
}
#[derive(Clone, Debug, PartialEq, Eq)]
enum DmlFilterOp {
Eq,
Neq,
Lt,
Lte,
Gt,
Gte,
IsNull,
IsNotNull,
}
#[derive(Clone, Debug)]
struct DmlFilter {
col: String,
op: DmlFilterOp,
val: DmlVal,
}
enum ParsedDml {
Insert {
table: String,
cols: Vec<String>,
vals: Vec<DmlVal>,
},
Update {
line: usize,
table: String,
assigns: Vec<(String, DmlSetExpr)>,
filters: Vec<DmlFilter>,
},
Delete {
table: String,
filters: Vec<DmlFilter>,
},
}
fn parse_dml_stmt(
dstmt: &DmlStmt,
table_columns: &std::collections::BTreeMap<String, Vec<String>>,
) -> Result<ParsedDml, String> {
let stmt = dstmt.sql.as_str();
let up = stmt.to_ascii_uppercase();
if up.starts_with("INSERT") {
let Some((before_into, after_into_raw)) = split_once_kw(stmt, "INTO") else {
return Err(format!(
"line {}: malformed INSERT statement: `{stmt}`",
dstmt.line
));
};
if !before_into.trim().eq_ignore_ascii_case("INSERT") {
return Err(format!(
"line {}: `{}` conflict clauses are not supported; write plain `INSERT INTO`",
dstmt.line,
before_into.trim()
));
}
let after_into = after_into_raw.trim();
let Some((before_vals, vals_part)) = split_once_kw(after_into, "VALUES") else {
if split_once_kw(after_into, "SELECT").is_some() {
return Err(format!(
"line {}: INSERT ... SELECT is not supported; write explicit INSERT ... VALUES (...) statements",
dstmt.line
));
}
return Err(format!(
"line {}: INSERT is missing VALUES: `{stmt}`",
dstmt.line
));
};
let (tname, cols) = if let Some((tn, rest)) = before_vals.split_once('(') {
let clist = rest
.trim()
.trim_end_matches(')')
.split(',')
.map(|c| c.trim().trim_matches('"').to_ascii_lowercase())
.filter(|c| !c.is_empty())
.collect::<Vec<_>>();
(tn.trim().trim_matches('"').to_ascii_lowercase(), clist)
} else {
let tname = before_vals.trim().trim_matches('"').to_ascii_lowercase();
let Some(schema_cols) = table_columns.get(&tname) else {
return Err(format!(
"line {}: INSERT must name its column list: `{stmt}`",
dstmt.line
));
};
(tname, schema_cols.clone())
};
let tuples = split_value_tuples(vals_part.trim())
.ok_or_else(|| format!("line {}: malformed VALUES(...) in `{stmt}`", dstmt.line))?;
if tuples.len() > 1 {
return Err(format!(
"line {}: multi-row INSERT ... VALUES (...), (...) is not supported; split into one INSERT per row",
dstmt.line
));
}
let Some(vinner) = tuples.first() else {
return Err(format!(
"line {}: malformed VALUES(...) in `{stmt}`",
dstmt.line
));
};
let vals: Vec<DmlVal> = split_csv_values(vinner)
.into_iter()
.map(|v| parse_dml_val_strict(&v, dstmt.line))
.collect::<Result<_, _>>()?;
if cols.len() != vals.len() {
return Err(format!(
"line {}: INSERT column count != VALUES count in `{stmt}`",
dstmt.line
));
}
Ok(ParsedDml::Insert {
table: tname,
cols,
vals,
})
} else if up.starts_with("UPDATE") {
let rest = stmt[6..].trim();
let (tname_raw, after_set) = split_once_kw(rest, "SET")
.ok_or_else(|| format!("line {}: UPDATE is missing SET: `{stmt}`", dstmt.line))?;
let tname = tname_raw.trim().trim_matches('"').to_ascii_lowercase();
let (set_part, where_part) = split_once_kw(after_set, "WHERE")
.map_or((after_set.trim(), None), |(a, b)| {
(a.trim(), Some(b.trim()))
});
let assigns: Vec<(String, DmlSetExpr)> = split_csv_values(set_part)
.into_iter()
.map(|a| {
let (k, v) = a.split_once('=').ok_or_else(|| {
format!("line {}: malformed SET assignment `{a}`", dstmt.line)
})?;
Ok((
k.trim().trim_matches('"').to_ascii_lowercase(),
parse_dml_set_expr(v, dstmt.line)?,
))
})
.collect::<Result<_, String>>()?;
let filters = parse_simple_where(where_part, dstmt.line)?;
Ok(ParsedDml::Update {
line: dstmt.line,
table: tname,
assigns,
filters,
})
} else if up.starts_with("DELETE") {
let after_from = split_once_kw(stmt, "FROM")
.map(|(_, r)| r.trim())
.ok_or_else(|| format!("line {}: DELETE is missing FROM: `{stmt}`", dstmt.line))?;
let (tname_raw, where_part) = split_once_kw(after_from, "WHERE")
.map_or((after_from.trim(), None), |(a, b)| {
(a.trim(), Some(b.trim()))
});
let tname = tname_raw.trim().trim_matches('"').to_ascii_lowercase();
let filters = parse_simple_where(where_part, dstmt.line)?;
Ok(ParsedDml::Delete {
table: tname,
filters,
})
} else {
Err(format!(
"line {}: unsupported SQL trace statement (expected INSERT, UPDATE, or DELETE): `{stmt}`",
dstmt.line
))
}
}
fn eval_trigger_value(
v: &elinvar_als::SqlTriggerValue,
old_row: Option<&std::collections::BTreeMap<String, DmlVal>>,
new_row: Option<&std::collections::BTreeMap<String, DmlVal>>,
) -> DmlVal {
match v {
elinvar_als::SqlTriggerValue::NewCol(c) => new_row
.and_then(|r| r.get(c))
.cloned()
.unwrap_or(DmlVal::Null),
elinvar_als::SqlTriggerValue::OldCol(c) => old_row
.and_then(|r| r.get(c))
.cloned()
.unwrap_or(DmlVal::Null),
elinvar_als::SqlTriggerValue::Int(n) => DmlVal::Int(*n),
elinvar_als::SqlTriggerValue::Str(s) => DmlVal::Str(s.clone()),
elinvar_als::SqlTriggerValue::Bool(b) => DmlVal::Bool(*b),
elinvar_als::SqlTriggerValue::Null | _ => DmlVal::Null,
}
}
fn dml_cmp(lhs: &DmlVal, op: &str, rhs: &DmlVal) -> bool {
if op == "IS" {
return lhs == rhs;
}
if op == "IS NOT" {
return lhs != rhs;
}
if matches!(lhs, DmlVal::Null) || matches!(rhs, DmlVal::Null) {
return false;
}
match op {
"=" => lhs == rhs,
"!=" | "<>" => lhs != rhs,
"<" | "<=" | ">" | ">=" => match (lhs, rhs) {
(DmlVal::Int(a), DmlVal::Int(b)) => match op {
"<" => a < b,
"<=" => a <= b,
">" => a > b,
">=" => a >= b,
_ => false,
},
(DmlVal::Str(a), DmlVal::Str(b)) => match op {
"<" => a < b,
"<=" => a <= b,
">" => a > b,
">=" => a >= b,
_ => false,
},
_ => false,
},
_ => false,
}
}
fn trigger_when_holds(
when: &elinvar_als::SqlTriggerWhen,
old_row: Option<&std::collections::BTreeMap<String, DmlVal>>,
new_row: Option<&std::collections::BTreeMap<String, DmlVal>>,
unknown_value: bool,
) -> bool {
match when {
elinvar_als::SqlTriggerWhen::Always => true,
elinvar_als::SqlTriggerWhen::Unknown => unknown_value,
elinvar_als::SqlTriggerWhen::NewNeqOld(c) => {
new_row.and_then(|r| r.get(c)).unwrap_or(&DmlVal::Null)
!= old_row.and_then(|r| r.get(c)).unwrap_or(&DmlVal::Null)
}
elinvar_als::SqlTriggerWhen::NewIsNotNull(c) => new_row
.and_then(|r| r.get(c))
.is_some_and(|v| !matches!(v, DmlVal::Null)),
elinvar_als::SqlTriggerWhen::NewIsNull(c) => new_row
.and_then(|r| r.get(c))
.is_none_or(|v| matches!(v, DmlVal::Null)),
elinvar_als::SqlTriggerWhen::OldIsNotNull(c) => old_row
.and_then(|r| r.get(c))
.is_some_and(|v| !matches!(v, DmlVal::Null)),
elinvar_als::SqlTriggerWhen::OldIsNull(c) => old_row
.and_then(|r| r.get(c))
.is_none_or(|v| matches!(v, DmlVal::Null)),
elinvar_als::SqlTriggerWhen::Cmp { lhs, op, rhs } => {
let lv = eval_trigger_value(lhs, old_row, new_row);
let rv = eval_trigger_value(rhs, old_row, new_row);
dml_cmp(&lv, op, &rv)
}
elinvar_als::SqlTriggerWhen::And(parts) => parts
.iter()
.all(|p| trigger_when_holds(p, old_row, new_row, unknown_value)),
elinvar_als::SqlTriggerWhen::Or(parts) => parts
.iter()
.any(|p| trigger_when_holds(p, old_row, new_row, unknown_value)),
elinvar_als::SqlTriggerWhen::Not(inner) => {
!trigger_when_holds(inner, old_row, new_row, !unknown_value)
}
_ => unknown_value,
}
}
fn sql_default_to_dml_val(d: &elinvar_als::SqlDefault) -> DmlVal {
match d {
elinvar_als::SqlDefault::Int(n) => DmlVal::Int(*n),
elinvar_als::SqlDefault::Str(s) => DmlVal::Str(s.clone()),
elinvar_als::SqlDefault::Bool(b) => DmlVal::Bool(*b),
elinvar_als::SqlDefault::Null | _ => DmlVal::Null,
}
}
fn apply_col_defaults(
table: &str,
row: &mut std::collections::BTreeMap<String, DmlVal>,
col_defaults: &std::collections::BTreeMap<(String, String), elinvar_als::SqlDefault>,
) {
for ((t, c), def) in col_defaults {
if t == table && !row.contains_key(c) {
row.insert(c.clone(), sql_default_to_dml_val(def));
}
}
}
#[allow(clippy::too_many_arguments)]
fn fire_after_triggers(
state: &mut DmlSnap,
source_table: &str,
event: elinvar_als::SqlTriggerEvent,
updated_cols: &[String],
old_row: Option<&std::collections::BTreeMap<String, DmlVal>>,
new_row: Option<&std::collections::BTreeMap<String, DmlVal>>,
meta: &SqlAcceptsMeta,
next_row_id: &mut std::collections::BTreeMap<String, usize>,
sql_to_alloy_table: &std::collections::BTreeMap<String, String>,
table_row_pool: &std::collections::BTreeMap<String, Vec<String>>,
) {
for tr in &meta.after_triggers {
if tr.source_table != source_table || tr.event != event {
continue;
}
if event == elinvar_als::SqlTriggerEvent::Update
&& !tr.update_cols.is_empty()
&& !tr
.update_cols
.iter()
.any(|c| updated_cols.iter().any(|u| u == c))
{
continue;
}
if !trigger_when_holds(&tr.when, old_row, new_row, true) {
continue;
}
let target = &tr.target_table;
let idx = *next_row_id.entry(target.clone()).or_insert(0);
next_row_id.insert(target.clone(), idx + 1);
let t_alloy = sql_to_alloy_table
.get(target)
.map(String::as_str)
.unwrap_or(target.as_str());
let atom = table_row_pool
.get(t_alloy)
.and_then(|pool| pool.get(idx))
.cloned()
.unwrap_or_else(|| format!("{t_alloy}_row{idx}"));
let mut row = std::collections::BTreeMap::new();
for (col, val_expr) in &tr.assignments {
row.insert(col.clone(), eval_trigger_value(val_expr, old_row, new_row));
}
apply_col_defaults(target, &mut row, &meta.col_defaults);
let has_id = meta
.table_columns
.get(&target.to_ascii_lowercase())
.is_some_and(|cols| cols.iter().any(|c| c == "id"));
if has_id && !row.contains_key("id") {
let max_id = state
.get(target)
.map(|rows| {
rows.iter()
.filter_map(|(_, r)| match r.get("id") {
Some(DmlVal::Int(n)) => Some(*n),
_ => None,
})
.max()
.unwrap_or(0)
})
.unwrap_or(0);
row.insert("id".to_string(), DmlVal::Int(max_id + 1));
}
state.entry(target.clone()).or_default().push((atom, row));
}
}
fn propagate_on_delete(
state: &mut DmlSnap,
retired: &mut std::collections::BTreeMap<String, Vec<String>>,
deleted_table: &str,
deleted_rows: &[std::collections::BTreeMap<String, DmlVal>],
fk_targets: &std::collections::BTreeMap<(String, String), elinvar_als::SqlFkTarget>,
) {
if deleted_rows.is_empty() {
return;
}
let mut cascade_queue: Vec<(String, Vec<std::collections::BTreeMap<String, DmlVal>>)> =
vec![(deleted_table.to_string(), deleted_rows.to_vec())];
while let Some((parent_table, parent_rows)) = cascade_queue.pop() {
for ((child_table, child_col), fk) in fk_targets {
if fk.target_table != parent_table {
continue;
}
let deleted_keys: Vec<&DmlVal> = parent_rows
.iter()
.filter_map(|r| r.get(&fk.target_col))
.filter(|v| !matches!(v, DmlVal::Null))
.collect();
if deleted_keys.is_empty() {
continue;
}
match fk.on_delete {
elinvar_als::SqlOnDelete::Cascade => {
let mut cascaded = Vec::new();
if let Some(crows) = state.get_mut(child_table) {
crows.retain(|(catom, crow)| {
let hit = crow
.get(child_col)
.is_some_and(|v| deleted_keys.contains(&v));
if hit {
retired
.entry(child_table.clone())
.or_default()
.push(catom.clone());
cascaded.push(crow.clone());
false
} else {
true
}
});
}
if !cascaded.is_empty() {
cascade_queue.push((child_table.clone(), cascaded));
}
}
elinvar_als::SqlOnDelete::SetNull => {
if let Some(crows) = state.get_mut(child_table) {
for (_, crow) in crows.iter_mut() {
if crow
.get(child_col)
.is_some_and(|v| deleted_keys.contains(&v))
{
crow.insert(child_col.clone(), DmlVal::Null);
}
}
}
}
elinvar_als::SqlOnDelete::Restrict | _ => {}
}
}
}
}
#[allow(clippy::type_complexity, clippy::too_many_arguments)]
fn apply_parsed_dml(
state: &mut DmlSnap,
retired: &mut std::collections::BTreeMap<String, Vec<String>>,
parsed: &ParsedDml,
next_row_id: &mut std::collections::BTreeMap<String, usize>,
sql_to_alloy_table: &std::collections::BTreeMap<String, String>,
table_row_pool: &std::collections::BTreeMap<String, Vec<String>>,
meta: &SqlAcceptsMeta,
only_atom: Option<&str>,
) -> Result<
Vec<(
String,
std::collections::BTreeMap<String, DmlVal>,
std::collections::BTreeMap<String, DmlVal>,
)>,
String,
> {
match parsed {
ParsedDml::Insert { table, cols, vals } => {
let idx = *next_row_id.entry(table.clone()).or_insert(0);
next_row_id.insert(table.clone(), idx + 1);
let t_alloy = sql_to_alloy_table
.get(table)
.map(String::as_str)
.unwrap_or(table.as_str());
let atom = table_row_pool
.get(t_alloy)
.and_then(|pool| pool.get(idx))
.cloned()
.unwrap_or_else(|| format!("{t_alloy}_row{idx}"));
let mut row = std::collections::BTreeMap::new();
for (c, v) in cols.iter().zip(vals.iter()) {
row.insert(c.clone(), v.clone());
}
apply_col_defaults(table, &mut row, &meta.col_defaults);
let new_row = row.clone();
state.entry(table.clone()).or_default().push((atom, row));
fire_after_triggers(
state,
table,
elinvar_als::SqlTriggerEvent::Insert,
&[],
None,
Some(&new_row),
meta,
next_row_id,
sql_to_alloy_table,
table_row_pool,
);
Ok(Vec::new())
}
ParsedDml::Update {
line,
table,
assigns,
filters,
} => {
let mut changed_rows = Vec::new();
let updated_cols: Vec<String> = assigns.iter().map(|(k, _)| k.clone()).collect();
if let Some(rows) = state.get_mut(table) {
for (ratom, row) in rows.iter_mut() {
if only_atom.is_some_and(|a| ratom != a) {
continue;
}
if row_matches(row, filters) {
let old_row = row.clone();
let mut evaluated = Vec::with_capacity(assigns.len());
for (k, expr) in assigns {
evaluated.push((k.clone(), expr.eval(&old_row, *line)?));
}
for (k, v) in evaluated {
row.insert(k, v);
}
changed_rows.push((ratom.clone(), old_row, row.clone()));
}
}
}
for (_, old_row, new_row) in &changed_rows {
fire_after_triggers(
state,
table,
elinvar_als::SqlTriggerEvent::Update,
&updated_cols,
Some(old_row),
Some(new_row),
meta,
next_row_id,
sql_to_alloy_table,
table_row_pool,
);
}
Ok(changed_rows)
}
ParsedDml::Delete { table, filters } => {
let mut deleted_rows = Vec::new();
if let Some(rows) = state.get_mut(table) {
rows.retain(|(ratom, row)| {
if only_atom.is_some_and(|a| ratom != a) {
return true;
}
if row_matches(row, filters) {
retired
.entry(table.clone())
.or_default()
.push(ratom.clone());
deleted_rows.push(row.clone());
false
} else {
true
}
});
}
propagate_on_delete(state, retired, table, &deleted_rows, &meta.fk_targets);
for old_row in &deleted_rows {
fire_after_triggers(
state,
table,
elinvar_als::SqlTriggerEvent::Delete,
&[],
Some(old_row),
None,
meta,
next_row_id,
sql_to_alloy_table,
table_row_pool,
);
}
Ok(Vec::new())
}
}
}
struct SqlScriptUniverseMaps {
field_range_sig: std::collections::BTreeMap<String, String>,
ordered_aliases: std::collections::BTreeMap<String, String>,
ordered_atom_map: std::collections::BTreeMap<(String, DmlVal), String>,
domain_atom_map: std::collections::BTreeMap<(String, String), String>,
singleton_atoms: std::collections::BTreeMap<String, String>,
sql_to_alloy_table: std::collections::BTreeMap<String, String>,
field_owner_table: std::collections::BTreeMap<String, String>,
}
fn build_sql_instance(
snap: &DmlSnap,
retired: &std::collections::BTreeMap<String, Vec<String>>,
u: &elinvar_engine::logic::Universe,
relations: &[elinvar_engine::logic::Relation],
maps: &SqlScriptUniverseMaps,
meta: &SqlAcceptsMeta,
) -> Result<Instance, BuildSqlError> {
use std::collections::BTreeMap;
let mut st = Instance::new(u);
let mut active_by_table: BTreeMap<String, Vec<&str>> = BTreeMap::new();
for (tname, rows) in snap {
let atoms: Vec<&str> = rows.iter().map(|(a, _)| a.as_str()).collect();
active_by_table.insert(tname.clone(), atoms);
}
for rel in relations {
if !rel.is_changing() {
continue;
}
let rname = rel.name();
let rname_low = rname.to_ascii_lowercase();
if rel.arity() == 1 {
let atoms: Vec<&str> =
if let Some(sql_tname) = meta.alloy_retired_to_sql_table.get(&rname_low) {
retired
.get(sql_tname)
.map(|v| v.iter().map(String::as_str).collect())
.unwrap_or_default()
} else {
let sql_tname = meta
.alloy_to_sql_table
.get(&rname_low)
.map(String::as_str)
.unwrap_or(rname_low.as_str());
active_by_table.get(sql_tname).cloned().unwrap_or_default()
};
let refs: Vec<&[&str]> = atoms.iter().map(std::slice::from_ref).collect();
let ts = u
.tuple_set(1, &refs)
.map_err(|e| BuildSqlError::Parse(e.message))?;
st.set(rel, ts)
.map_err(|e| BuildSqlError::Parse(e.message))?;
} else if rel.arity() == 2 {
let (owner_hint, col_alloy) = match rname_low.rsplit_once('.') {
Some((owner, col)) => (Some(owner), col),
None => (
maps.field_owner_table.get(rname).map(String::as_str),
rname_low.as_str(),
),
};
let range_sig = maps
.field_range_sig
.get(rname)
.map(String::as_str)
.unwrap_or("");
let mut pairs: Vec<(String, String)> = Vec::new();
for (t_sql, rows) in snap {
let t_alloy = maps
.sql_to_alloy_table
.get(t_sql)
.map(String::as_str)
.unwrap_or(t_sql.as_str());
if let Some(oh) = owner_hint
&& oh != t_alloy
&& oh != t_sql.as_str()
{
continue;
}
for (row_atom, cols) in rows {
let col_sql = meta
.alloy_to_sql_col
.get(&(t_alloy.to_string(), col_alloy.to_string()))
.map(String::as_str)
.or_else(|| {
if cols.contains_key(col_alloy) {
Some(col_alloy)
} else {
col_alloy.strip_suffix("_sql")
}
})
.unwrap_or(col_alloy);
let Some(val) = cols.get(col_sql) else {
continue;
};
if matches!(val, DmlVal::Null) {
continue;
}
if u.index_of(row_atom).is_none() {
continue;
}
let fk_key = (t_sql.clone(), col_sql.to_string());
let val_atom = if let Some(fk) = meta.fk_targets.get(&fk_key) {
let matched = snap.get(&fk.target_table).and_then(|trows| {
trows.iter().find_map(|(ratom, rcols)| {
(rcols.get(&fk.target_col) == Some(val)).then(|| ratom.clone())
})
});
match matched {
Some(atom) => atom,
None => {
return Err(BuildSqlError::Refused(format!(
"foreign key {t_sql}.{col_sql} -> {}.{}",
fk.target_table, fk.target_col
)));
}
}
} else if let Some(allowed) = meta.enum_values.get(&fk_key) {
let text = match val {
DmlVal::Str(s) => s.clone(),
DmlVal::Int(n) => n.to_string(),
DmlVal::Bool(b) => b.to_string(),
DmlVal::Null => unreachable!("filtered above"),
};
if !allowed.iter().any(|a| a == &text) {
return Err(BuildSqlError::Refused(format!(
"fact {t_alloy}_checks ({t_sql}.{col_sql} = '{text}' not in allowed list)"
)));
}
maps.domain_atom_map
.get(&(range_sig.to_string(), text.clone()))
.cloned()
.ok_or_else(|| {
BuildSqlError::Parse(format!(
"enum value `{text}` for `{t_sql}.{col_sql}` has no atom in `{range_sig}`"
))
})?
} else if let Some(region) = meta.int_regions.get(range_sig) {
match val {
DmlVal::Int(n) => region
.intervals
.iter()
.find(|(lo, hi, _)| {
lo.is_none_or(|l| *n >= l) && hi.is_none_or(|h| *n <= h)
})
.and_then(|(_, _, atom_sig)| maps.singleton_atoms.get(atom_sig))
.cloned()
.ok_or_else(|| {
BuildSqlError::Parse(format!(
"integer `{n}` for `{t_sql}.{col_sql}` has no interval in `{range_sig}`"
))
})?,
_ => {
return Err(BuildSqlError::Parse(format!(
"expected integer for `{t_sql}.{col_sql}`"
)));
}
}
} else if range_sig == "Int" {
match val {
DmlVal::Int(n) => u
.atom_of_int(*n)
.and_then(|i| u.atom(i).map(str::to_string))
.ok_or_else(|| {
BuildSqlError::Parse(format!(
"integer `{n}` for `{t_sql}.{col_sql}` does not fit Int"
))
})?,
_ => {
return Err(BuildSqlError::Parse(format!(
"non-integer value `{val:?}` for Int column `{t_sql}.{col_sql}`"
)));
}
}
} else if range_sig == "SqlBool" {
let is_true = match val {
DmlVal::Bool(b) => *b,
DmlVal::Int(n) => *n != 0,
DmlVal::Str(s) => s == "1" || s.eq_ignore_ascii_case("true"),
DmlVal::Null => false,
};
let key = if is_true { "SqlTrue" } else { "SqlFalse" };
maps.singleton_atoms.get(key).cloned().ok_or_else(|| {
BuildSqlError::Parse(format!(
"boolean value has no atom for `{t_sql}.{col_sql}`"
))
})?
} else if maps.ordered_aliases.contains_key(range_sig) {
maps.ordered_atom_map
.get(&(range_sig.to_string(), val.clone()))
.cloned()
.ok_or_else(|| {
BuildSqlError::Parse(format!(
"ordered value `{val:?}` for `{t_sql}.{col_sql}` was not pre-allocated"
))
})?
} else if range_sig.ends_with("_row")
|| meta
.alloy_to_sql_table
.contains_key(&range_sig.to_ascii_lowercase())
{
let target_alloy = range_sig
.strip_suffix("_row")
.unwrap_or(range_sig)
.to_ascii_lowercase();
let target_sql = meta
.alloy_to_sql_table
.get(&target_alloy)
.map(String::as_str)
.unwrap_or(target_alloy.as_str());
snap.get(target_sql)
.and_then(|trows| {
trows.iter().find_map(|(ratom, rcols)| {
(rcols.get("id") == Some(val)).then(|| ratom.clone())
})
})
.ok_or_else(|| {
BuildSqlError::Refused(format!(
"foreign key {t_sql}.{col_sql} -> {target_sql}.id"
))
})?
} else {
let sval = match val {
DmlVal::Str(s) => s.clone(),
DmlVal::Int(n) => n.to_string(),
DmlVal::Bool(b) => b.to_string(),
DmlVal::Null => unreachable!("filtered above"),
};
maps.domain_atom_map
.get(&(range_sig.to_string(), sval.clone()))
.cloned()
.ok_or_else(|| {
BuildSqlError::Parse(format!(
"value `{sval}` for `{t_sql}.{col_sql}` could not be mapped to an atom"
))
})?
};
pairs.push((row_atom.clone(), val_atom));
}
}
let slices: Vec<[&str; 2]> = pairs
.iter()
.map(|(a, b)| [a.as_str(), b.as_str()])
.collect();
let refs: Vec<&[&str]> = slices.iter().map(|p| p.as_slice()).collect();
let ts = u
.tuple_set(2, &refs)
.map_err(|e| BuildSqlError::Parse(e.message))?;
st.set(rel, ts)
.map_err(|e| BuildSqlError::Parse(e.message))?;
}
}
Ok(st)
}
#[allow(clippy::type_complexity)]
fn evaluate_sql_script(
model: &AlsModel,
script: &str,
meta: &SqlAcceptsMeta,
) -> Result<
(
Trace,
Vec<DmlStmt>,
Vec<String>,
std::collections::BTreeMap<usize, Vec<String>>,
),
SqlScriptEvalError,
> {
use std::collections::{BTreeMap, BTreeSet};
let mut stmts: Vec<DmlStmt> = Vec::new();
let mut cur = String::new();
let mut cur_line: Option<usize> = None;
let mut in_str = false;
for (line_idx, raw_line) in script.lines().enumerate() {
let line_no = line_idx + 1;
let mut chars = raw_line.chars().peekable();
while let Some(c) = chars.next() {
if in_str {
cur.push(c);
if c == '\'' {
if chars.peek() == Some(&'\'') {
cur.push(chars.next().expect("peeked"));
} else {
in_str = false;
}
}
continue;
}
if c == '-' && chars.peek() == Some(&'-') {
break;
}
if c == '\'' {
if cur_line.is_none() {
cur_line = Some(line_no);
}
in_str = true;
cur.push(c);
} else if c == ';' {
let s = cur.trim().to_string();
if !s.is_empty() {
stmts.push(DmlStmt {
line: cur_line.unwrap_or(line_no),
sql: s,
});
}
cur.clear();
cur_line = None;
} else {
if !c.is_whitespace() && cur_line.is_none() {
cur_line = Some(line_no);
}
cur.push(c);
}
}
if !cur.is_empty() {
cur.push(' ');
}
}
let tail = cur.trim().to_string();
if !tail.is_empty() {
stmts.push(DmlStmt {
line: cur_line.unwrap_or(1),
sql: tail,
});
}
if stmts.is_empty() {
return Err(SqlScriptEvalError::Parse(
"SQL trace script contains no INSERT, UPDATE, or DELETE statements".to_string(),
));
}
let mut parsed_stmts: Vec<ParsedDml> = Vec::with_capacity(stmts.len());
let mut inserts_per_table: BTreeMap<String, usize> = BTreeMap::new();
for dstmt in &stmts {
let p = parse_dml_stmt(dstmt, &meta.table_columns).map_err(SqlScriptEvalError::Parse)?;
let (src_table, ev) = match &p {
ParsedDml::Insert { table, .. } => {
*inserts_per_table.entry(table.clone()).or_insert(0) += 1;
(table.as_str(), elinvar_als::SqlTriggerEvent::Insert)
}
ParsedDml::Update { table, .. } => {
(table.as_str(), elinvar_als::SqlTriggerEvent::Update)
}
ParsedDml::Delete { table, .. } => {
(table.as_str(), elinvar_als::SqlTriggerEvent::Delete)
}
};
for tr in &meta.after_triggers {
if tr.source_table == src_table && tr.event == ev {
*inserts_per_table
.entry(tr.target_table.clone())
.or_insert(0) += 1;
}
}
parsed_stmts.push(p);
}
let schema_bounds = model
.model
.run(&elinvar_engine::logic::Formula::truth())
.scope(2)
.bounds()
.map_err(|es| {
SqlScriptEvalError::Parse(
es.into_iter()
.map(|e| e.message)
.collect::<Vec<_>>()
.join("; "),
)
})?;
let su = schema_bounds.universe();
let relations = model.model.relations();
let mut sql_to_alloy_table: BTreeMap<String, String> = BTreeMap::new();
for (a, s) in &meta.alloy_to_sql_table {
sql_to_alloy_table.insert(s.clone(), a.clone());
}
let is_parent_container = |rname: &str| {
rname == "SqlBool"
|| rname.ends_with("_enum")
|| rname.ends_with("_val")
|| rname.ends_with("_row")
|| rname.ends_with("_ord")
|| rname.starts_with("time_ord_")
|| rname.starts_with("date_ord_")
};
let mut atom_sig_name: BTreeMap<String, String> = BTreeMap::new();
let mut container_atoms: Vec<(String, BTreeSet<String>)> = Vec::new();
for rel in &relations {
if rel.is_changing() || rel.arity() != 1 {
continue;
}
let rname = rel.name();
if rname == "Int" || rname == "first" || rname.ends_with("/first") {
continue;
}
if is_parent_container(rname)
&& let Some(up) = schema_bounds.upper(rel)
{
let mut set = BTreeSet::new();
for idx in up.indices() {
if let Some(aname) = su.atom(idx as usize) {
atom_sig_name.insert(aname.to_string(), rname.to_string());
set.insert(aname.to_string());
}
}
container_atoms.push((rname.to_string(), set));
}
}
let text_check_sig_names: BTreeSet<&str> = meta
.text_checks
.iter()
.map(|tc| tc.sig_name.as_str())
.collect();
let mut singleton_rel_names: BTreeSet<String> = BTreeSet::new();
let mut sig_children: BTreeMap<String, Vec<String>> = BTreeMap::new();
for rel in &relations {
if rel.is_changing() || rel.arity() != 1 {
continue;
}
let rname = rel.name();
if rname == "Int"
|| rname == "first"
|| rname.ends_with("/first")
|| is_parent_container(rname)
|| text_check_sig_names.contains(rname)
{
continue;
}
let Some(up) = schema_bounds.upper(rel) else {
continue;
};
let up_atoms: Vec<String> = up
.indices()
.filter_map(|idx| su.atom(idx as usize).map(str::to_string))
.collect();
let parent_match = container_atoms
.iter()
.find(|(_, cset)| !up_atoms.is_empty() && up_atoms.iter().all(|a| cset.contains(a)))
.map(|(pname, _)| pname.clone());
let is_one = up_atoms.len() == 1
|| schema_bounds.lower(rel).is_some_and(|lo| lo.len() == 1)
|| parent_match.is_some();
if is_one {
singleton_rel_names.insert(rname.to_string());
if let Some(pname) = parent_match {
sig_children
.entry(pname)
.or_default()
.push(rname.to_string());
} else {
for a in &up_atoms {
atom_sig_name
.entry(a.clone())
.or_insert_with(|| rname.to_string());
}
}
} else {
for a in &up_atoms {
atom_sig_name
.entry(a.clone())
.or_insert_with(|| rname.to_string());
}
}
}
let mut ordered_aliases: BTreeMap<String, String> = BTreeMap::new();
let mut enum_order_aliases: BTreeMap<String, String> = BTreeMap::new();
for rel in &relations {
if !rel.is_changing()
&& rel.arity() == 1
&& let Some(alias) = rel.name().strip_suffix("/first")
&& let Some(up) = schema_bounds.upper(rel)
&& let Some(idx) = up.indices().next()
&& let Some(aname) = su.atom(idx as usize)
&& let Some(parent_sig) = atom_sig_name.get(aname)
{
if sig_children.contains_key(parent_sig) {
enum_order_aliases.insert(parent_sig.clone(), alias.to_string());
} else {
ordered_aliases.insert(parent_sig.clone(), alias.to_string());
}
}
}
let mut field_range_sig: BTreeMap<String, String> = BTreeMap::new();
let mut field_owner_table: BTreeMap<String, String> = BTreeMap::new();
let sn = su.size() as u64;
for rel in &relations {
if rel.arity() < 2 || rel.name().ends_with("/next") || rel.name() == "next" {
continue;
}
if let Some(up) = schema_bounds.upper(rel)
&& let Some(flat) = up.indices().next()
{
let ran_idx = (flat % sn) as usize;
if let Some(ran_atom) = su.atom(ran_idx) {
let range_sig = if su.int_of(ran_idx).is_some() {
"Int".to_string()
} else {
atom_sig_name
.get(ran_atom)
.cloned()
.unwrap_or_else(|| "Unknown".to_string())
};
field_range_sig.insert(rel.name().to_string(), range_sig);
}
if rel.arity() == 2
&& rel.is_changing()
&& let Some(dom_atom) = su.atom((flat / sn) as usize)
&& let Some(dom_sig) = atom_sig_name.get(dom_atom)
{
let owner_alloy = dom_sig
.strip_suffix("_row")
.unwrap_or(dom_sig)
.to_ascii_lowercase();
field_owner_table.insert(rel.name().to_string(), owner_alloy);
}
}
}
let mut table_row_pool: BTreeMap<String, Vec<String>> = BTreeMap::new();
let mut all_atoms: Vec<String> = Vec::new();
let mut atom_seen: BTreeSet<String> = BTreeSet::new();
let mut add_atom = |a: String| {
if atom_seen.insert(a.clone()) {
all_atoms.push(a);
}
};
for rel in &relations {
if rel.is_changing() && rel.arity() == 1 {
let rlow = rel.name().to_ascii_lowercase();
if meta.alloy_retired_to_sql_table.contains_key(&rlow) {
continue;
}
let t_sql = meta
.alloy_to_sql_table
.get(&rlow)
.map(String::as_str)
.unwrap_or(rlow.as_str());
let count = inserts_per_table.get(t_sql).copied().unwrap_or(0).max(1);
let mut pool = Vec::with_capacity(count);
for i in 0..count {
let a = format!("{rlow}_row{i}");
add_atom(a.clone());
pool.push(a);
}
table_row_pool.insert(rlow, pool);
}
}
let mut singleton_atoms: BTreeMap<String, String> = BTreeMap::new();
for srel in &singleton_rel_names {
let a = format!("{srel}0");
add_atom(a.clone());
singleton_atoms.insert(srel.clone(), a);
}
let mut vals_by_col: BTreeMap<(String, String), BTreeSet<DmlVal>> = BTreeMap::new();
for ((dt, dc), def) in &meta.col_defaults {
vals_by_col
.entry((dt.clone(), dc.clone()))
.or_default()
.insert(sql_default_to_dml_val(def));
}
for p in &parsed_stmts {
match p {
ParsedDml::Insert { table, cols, vals } => {
for (c, v) in cols.iter().zip(vals.iter()) {
if !matches!(v, DmlVal::Null) {
vals_by_col
.entry((table.clone(), c.clone()))
.or_default()
.insert(v.clone());
}
}
}
ParsedDml::Update { table, assigns, .. } => {
for (c, expr) in assigns {
if let DmlSetExpr::Lit(v) = expr
&& !matches!(v, DmlVal::Null)
{
vals_by_col
.entry((table.clone(), c.clone()))
.or_default()
.insert(v.clone());
}
}
}
ParsedDml::Delete { .. } => {}
}
}
{
let mut dry_snap: DmlSnap = BTreeMap::new();
let mut dry_retired: BTreeMap<String, Vec<String>> = BTreeMap::new();
let mut dry_next: BTreeMap<String, usize> = BTreeMap::new();
for p in &parsed_stmts {
let _ = apply_parsed_dml(
&mut dry_snap,
&mut dry_retired,
p,
&mut dry_next,
&sql_to_alloy_table,
&table_row_pool,
meta,
None,
);
for (t_sql, rows) in &dry_snap {
for (_, rcols) in rows {
for (c, v) in rcols {
if !matches!(v, DmlVal::Null) {
vals_by_col
.entry((t_sql.clone(), c.clone()))
.or_default()
.insert(v.clone());
}
}
}
}
}
}
let mut ordered_vals: BTreeMap<String, BTreeSet<DmlVal>> = BTreeMap::new();
let mut domain_vals: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
let mut int_vals: BTreeSet<i64> = BTreeSet::from([0]);
for rel in &relations {
if !rel.is_changing() || rel.arity() != 2 {
continue;
}
let rname = rel.name();
let Some(range_sig) = field_range_sig.get(rname) else {
continue;
};
let rname_low = rname.to_ascii_lowercase();
let (owner_hint, col_alloy) = match rname_low.rsplit_once('.') {
Some((o, c)) => (Some(o), c),
None => (
field_owner_table.get(rname).map(String::as_str),
rname_low.as_str(),
),
};
for ((t_sql, col_sql), vals) in &vals_by_col {
let t_alloy = sql_to_alloy_table
.get(t_sql)
.map(String::as_str)
.unwrap_or(t_sql.as_str());
if let Some(oh) = owner_hint
&& oh != t_alloy
&& oh != t_sql.as_str()
{
continue;
}
let expected_sql = meta
.alloy_to_sql_col
.get(&(t_alloy.to_string(), col_alloy.to_string()))
.map(String::as_str)
.or_else(|| col_alloy.strip_suffix("_sql"))
.unwrap_or(col_alloy);
if col_sql != expected_sql && col_sql != col_alloy {
continue;
}
for v in vals {
if range_sig == "Int" {
if let DmlVal::Int(n) = v {
int_vals.insert(*n);
}
} else if ordered_aliases.contains_key(range_sig) {
ordered_vals
.entry(range_sig.clone())
.or_default()
.insert(v.clone());
} else if range_sig != "SqlBool"
&& !meta.int_regions.contains_key(range_sig)
&& !range_sig.ends_with("_row")
&& !meta
.alloy_to_sql_table
.contains_key(&range_sig.to_ascii_lowercase())
{
let sval = match v {
DmlVal::Str(s) => s.clone(),
DmlVal::Int(n) => n.to_string(),
DmlVal::Bool(b) => b.to_string(),
DmlVal::Null => continue,
};
domain_vals
.entry(range_sig.clone())
.or_default()
.insert(sval);
}
}
}
}
let date_sig_opt =
crate::cli::dates::detect_date_sig_from_relations(&relations, &field_range_sig);
let date_fmt = meta.date_format.as_deref().unwrap_or("%Y-%m");
if let Some(date_sig) = &date_sig_opt {
let mut src_unix_vals: Vec<i64> = Vec::new();
let mut ord_shift_vals: BTreeMap<String, Vec<i64>> = BTreeMap::new();
for rel in &relations {
let short = rel.name().rsplit('.').next().unwrap_or(rel.name());
if let Some(src_sig) = short.strip_prefix("to_date_") {
if src_sig == "Int" {
src_unix_vals.extend(int_vals.iter().copied());
} else if let Some(vs) = ordered_vals.get(src_sig) {
for v in vs {
if let DmlVal::Int(n) = v {
src_unix_vals.push(*n);
}
}
}
} else if let Some(ord_sig) = short.strip_prefix("add_")
&& rel.arity() == 4
&& ord_sig != "Int"
&& let Some(vs) = ordered_vals.get(ord_sig)
{
let nums: Vec<i64> = vs
.iter()
.filter_map(|v| match v {
DmlVal::Int(n) => Some(*n),
_ => None,
})
.collect();
ord_shift_vals.insert(ord_sig.to_string(), nums);
}
}
let mut base_dates: BTreeSet<String> = ordered_vals
.get(date_sig)
.map(|vs| {
vs.iter()
.filter_map(|v| match v {
DmlVal::Str(s) => Some(s.clone()),
_ => None,
})
.collect()
})
.unwrap_or_default();
crate::cli::dates::expand_date_domain(
date_fmt,
&meta.date_shifts,
&src_unix_vals,
&int_vals,
&ord_shift_vals,
&mut base_dates,
);
let entry = ordered_vals.entry(date_sig.clone()).or_default();
for d in base_dates {
entry.insert(DmlVal::Str(d));
}
}
for sh in &meta.ord_shifts {
let base_ints: Vec<i64> = ordered_vals
.get(&sh.ordered_sig)
.map(|vals| {
vals.iter()
.filter_map(|v| match v {
DmlVal::Int(n) => Some(*n),
_ => None,
})
.collect()
})
.unwrap_or_default();
let entry = ordered_vals.entry(sh.ordered_sig.clone()).or_default();
for n in base_ints {
entry.insert(DmlVal::Int(n.saturating_add(sh.delta)));
}
}
for osig in ordered_aliases.keys() {
let entry = ordered_vals.entry(osig.clone()).or_default();
if entry.is_empty() {
entry.insert(DmlVal::Int(0));
}
}
let mut ordered_atom_map: BTreeMap<(String, DmlVal), String> = BTreeMap::new();
let mut ordered_chain: BTreeMap<String, Vec<String>> = BTreeMap::new();
let mut ordered_int_pairs: BTreeMap<String, Vec<(String, i64)>> = BTreeMap::new();
let mut ordered_str_values: BTreeMap<String, Vec<String>> = BTreeMap::new();
for (osig, vals) in &ordered_vals {
let mut chain = Vec::with_capacity(vals.len());
let mut ipairs = Vec::new();
let mut svals = Vec::new();
for (i, v) in vals.iter().enumerate() {
let atom = format!("{osig}_v{i}");
add_atom(atom.clone());
ordered_atom_map.insert((osig.clone(), v.clone()), atom.clone());
match v {
DmlVal::Int(n) => ipairs.push((atom.clone(), *n)),
DmlVal::Str(s) => svals.push(s.clone()),
_ => {}
}
chain.push(atom);
}
if !ipairs.is_empty() {
ordered_int_pairs.insert(osig.clone(), ipairs);
}
if !svals.is_empty() {
ordered_str_values.insert(osig.clone(), svals);
}
ordered_chain.insert(osig.clone(), chain);
}
let mut domain_atom_map: BTreeMap<(String, String), String> = BTreeMap::new();
let mut domain_extra_atoms: BTreeMap<String, Vec<String>> = BTreeMap::new();
for (dsig, vals) in &domain_vals {
let children = sig_children.get(dsig).cloned().unwrap_or_default();
let mut extra = Vec::new();
for (i, v) in vals.iter().enumerate() {
let v_low = v.to_ascii_lowercase();
let clean: String = v_low
.chars()
.map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
.collect();
let matched_child = children.iter().find(|ch| {
let ch_low = ch.to_ascii_lowercase();
let ch_trimmed = ch_low.strip_suffix("_sql").unwrap_or(&ch_low);
ch_low == v_low
|| ch_trimmed == v_low
|| ch_low.ends_with(&format!("_{v_low}"))
|| ch_trimmed.ends_with(&format!("_{v_low}"))
|| ch_low.ends_with(&format!("_{clean}"))
|| ch_trimmed.ends_with(&format!("_{clean}"))
});
if let Some(ch) = matched_child
&& let Some(satom) = singleton_atoms.get(ch)
{
domain_atom_map.insert((dsig.clone(), v.clone()), satom.clone());
} else {
let atom = format!("{dsig}_d{i}");
add_atom(atom.clone());
domain_atom_map.insert((dsig.clone(), v.clone()), atom.clone());
extra.push(atom);
}
}
domain_extra_atoms.insert(dsig.clone(), extra);
}
let has_int_rel = relations.iter().any(|r| r.name() == "Int");
let mut int_atom_pairs: Vec<(String, i64)> = Vec::new();
if has_int_rel {
for &n in &int_vals {
if (i32::MIN as i64..=i32::MAX as i64).contains(&n) {
let name = n.to_string();
add_atom(name.clone());
int_atom_pairs.push((name, n));
}
}
}
if all_atoms.is_empty() {
all_atoms.push("_empty".to_string());
}
let base_u = elinvar_engine::logic::Universe::new(all_atoms.iter().map(String::as_str))
.map_err(|e| SqlScriptEvalError::Parse(e.message))?;
let u = if has_int_rel && !int_atom_pairs.is_empty() {
let refs: Vec<(&str, i64)> = int_atom_pairs
.iter()
.map(|(s, n)| (s.as_str(), *n))
.collect();
base_u
.with_ints(32, &refs)
.map_err(|e| SqlScriptEvalError::Parse(e.message))?
} else {
base_u
};
let text_check_sig_names: std::collections::BTreeSet<&str> = meta
.text_checks
.iter()
.map(|tc| tc.sig_name.as_str())
.collect();
let mut fixed = Instance::new(&u);
for rel in &relations {
if rel.is_changing() {
continue;
}
let rname = rel.name();
if rel.arity() == 1 && text_check_sig_names.contains(rname) {
continue;
}
if rel.arity() == 1 {
let atoms: Vec<String> = if rname == "Int" {
int_atom_pairs.iter().map(|(s, _)| s.clone()).collect()
} else if let Some(t_alloy) = rname.to_ascii_lowercase().strip_suffix("_row")
&& let Some(pool) = table_row_pool.get(t_alloy)
{
pool.clone()
} else if let Some(satom) = singleton_atoms.get(rname) {
vec![satom.clone()]
} else if let Some(chain) = ordered_chain.get(rname) {
chain.clone()
} else if let Some(alias) = rname.strip_suffix("/first") {
if let Some((osig, _)) = ordered_aliases.iter().find(|(_, a)| a.as_str() == alias) {
ordered_chain
.get(osig)
.and_then(|c| c.first())
.cloned()
.into_iter()
.collect()
} else if let Some((esig, _)) =
enum_order_aliases.iter().find(|(_, a)| a.as_str() == alias)
{
sig_children
.get(esig)
.and_then(|chs| chs.first())
.and_then(|ch| singleton_atoms.get(ch))
.cloned()
.into_iter()
.collect()
} else {
Vec::new()
}
} else {
let mut combined = Vec::new();
if let Some(chs) = sig_children.get(rname) {
for ch in chs {
if let Some(a) = singleton_atoms.get(ch) {
combined.push(a.clone());
}
}
}
if let Some(ex) = domain_extra_atoms.get(rname) {
combined.extend(ex.iter().cloned());
}
combined
};
let slices: Vec<[&str; 1]> = atoms.iter().map(|a| [a.as_str()]).collect();
let refs: Vec<&[&str]> = slices.iter().map(|s| s.as_slice()).collect();
let ts = u
.tuple_set(1, &refs)
.map_err(|e| SqlScriptEvalError::Parse(e.message))?;
fixed
.set(rel, ts)
.map_err(|e| SqlScriptEvalError::Parse(e.message))?;
} else if rel.arity() == 2 {
let pairs: Vec<(String, String)> = if let Some(alias) = rname.strip_suffix("/next") {
if let Some((osig, _)) = ordered_aliases.iter().find(|(_, a)| a.as_str() == alias) {
ordered_chain
.get(osig)
.map(|chain| {
chain
.windows(2)
.map(|w| (w[0].clone(), w[1].clone()))
.collect()
})
.unwrap_or_default()
} else if let Some((esig, _)) =
enum_order_aliases.iter().find(|(_, a)| a.as_str() == alias)
{
sig_children
.get(esig)
.map(|chs| {
chs.windows(2)
.filter_map(|w| {
Some((
singleton_atoms.get(&w[0])?.clone(),
singleton_atoms.get(&w[1])?.clone(),
))
})
.collect()
})
.unwrap_or_default()
} else {
Vec::new()
}
} else {
Vec::new()
};
let slices: Vec<[&str; 2]> = pairs
.iter()
.map(|(a, b)| [a.as_str(), b.as_str()])
.collect();
let refs: Vec<&[&str]> = slices.iter().map(|p| p.as_slice()).collect();
let ts = u
.tuple_set(2, &refs)
.map_err(|e| SqlScriptEvalError::Parse(e.message))?;
fixed
.set(rel, ts)
.map_err(|e| SqlScriptEvalError::Parse(e.message))?;
} else {
let short = rname.rsplit('.').next().unwrap_or(rname);
let is_date_fn_rel = date_sig_opt.is_some()
&& singleton_atoms.contains_key("SqlDateFn")
&& (rel.arity() == 3 || rel.arity() == 4)
&& (short.starts_with("to_date_") || short.starts_with("add_"));
let is_ord_fn_rel = singleton_atoms.contains_key("SqlOrdFn")
&& rel.arity() == 3
&& meta.ord_shifts.iter().any(|s| s.field == short);
if !is_date_fn_rel && !is_ord_fn_rel {
let ts = u
.tuple_set(rel.arity(), &[])
.map_err(|e| SqlScriptEvalError::Parse(e.message))?;
fixed
.set(rel, ts)
.map_err(|e| SqlScriptEvalError::Parse(e.message))?;
}
}
}
if let Some(date_sig) = &date_sig_opt
&& let Some(fn_atom) = singleton_atoms.get("SqlDateFn")
{
let date_strings = ordered_str_values
.get(date_sig)
.map(Vec::as_slice)
.unwrap_or(&[]);
let date_atoms = ordered_chain
.get(date_sig)
.map(Vec::as_slice)
.unwrap_or(&[]);
crate::cli::dates::populate_sql_date_fn(
&mut fixed,
&u,
&relations,
fn_atom,
date_fmt,
&meta.date_shifts,
date_strings,
date_atoms,
&ordered_int_pairs,
&int_atom_pairs,
)
.map_err(|e| SqlScriptEvalError::Parse(e.message))?;
}
if !meta.ord_shifts.is_empty()
&& let Some(fn_atom) = singleton_atoms.get("SqlOrdFn")
{
crate::cli::dates::populate_sql_ord_fn(
&mut fixed,
&u,
&relations,
fn_atom,
&meta.ord_shifts,
&ordered_int_pairs,
)
.map_err(|e| SqlScriptEvalError::Parse(e.message))?;
}
for tc in &meta.text_checks {
let Some(rel) = relations.iter().find(|r| r.name() == tc.sig_name) else {
continue;
};
let mut matched: Vec<String> = Vec::new();
for ((dsig, raw), atom) in &domain_atom_map {
if dsig == &tc.domain_sig && elinvar_als::eval_sql_text_check(raw, &tc.kind) {
matched.push(atom.clone());
}
}
if let (Some(strs), Some(atoms)) = (
ordered_str_values.get(&tc.domain_sig),
ordered_chain.get(&tc.domain_sig),
) {
for (raw, atom) in strs.iter().zip(atoms.iter()) {
if elinvar_als::eval_sql_text_check(raw, &tc.kind) {
matched.push(atom.clone());
}
}
}
for lsig in &tc.literal_sigs {
if let Some(atom) = singleton_atoms.get(lsig) {
matched.push(atom.clone());
}
}
matched.sort();
matched.dedup();
let slices: Vec<[&str; 1]> = matched.iter().map(|a| [a.as_str()]).collect();
let refs: Vec<&[&str]> = slices.iter().map(|s| s.as_slice()).collect();
let ts = u
.tuple_set(1, &refs)
.map_err(|e| SqlScriptEvalError::Parse(e.message))?;
fixed
.set(rel, ts)
.map_err(|e| SqlScriptEvalError::Parse(e.message))?;
}
let populated_date_fn = date_sig_opt.is_some() && singleton_atoms.contains_key("SqlDateFn");
let maps = SqlScriptUniverseMaps {
field_range_sig,
ordered_aliases,
ordered_atom_map,
domain_atom_map,
singleton_atoms,
sql_to_alloy_table: sql_to_alloy_table.clone(),
field_owner_table,
};
let mut accepted_snap: DmlSnap = BTreeMap::new();
let mut accepted_retired: BTreeMap<String, Vec<String>> = BTreeMap::new();
let mut next_row_id: BTreeMap<String, usize> = BTreeMap::new();
let mut accepted_inst = match build_sql_instance(
&accepted_snap,
&accepted_retired,
&u,
&relations,
&maps,
meta,
) {
Ok(inst) => inst,
Err(BuildSqlError::Parse(m) | BuildSqlError::Refused(m)) => {
return Err(SqlScriptEvalError::Parse(m));
}
};
let mut accepted_states: Vec<Instance> = vec![accepted_inst.clone()];
let all_facts = model.model.all_facts_named();
let mut failed_rules: Vec<String> = Vec::new();
let mut refused_by_stmt: BTreeMap<usize, Vec<String>> = BTreeMap::new();
for (si, parsed) in parsed_stmts.iter().enumerate() {
let target_atoms: Vec<Option<String>> = match parsed {
ParsedDml::Update { table, filters, .. } | ParsedDml::Delete { table, filters } => {
let matched: Vec<String> = accepted_snap
.get(table)
.map(|rows| {
rows.iter()
.filter(|(_, row)| row_matches(row, filters))
.map(|(ratom, _)| ratom.clone())
.collect()
})
.unwrap_or_default();
if matched.len() > 1 {
matched.into_iter().map(Some).collect()
} else {
vec![None]
}
}
ParsedDml::Insert { .. } => vec![None],
};
let mut tx_snap = accepted_snap.clone();
let mut tx_retired = accepted_retired.clone();
let mut tx_next_row = next_row_id.clone();
let mut tx_inst = accepted_inst.clone();
let mut tx_states: Vec<Instance> = Vec::new();
let mut stmt_reasons: Vec<String> = Vec::new();
for target_atom in &target_atoms {
let mut cand_snap = tx_snap.clone();
let mut cand_retired = tx_retired.clone();
let mut cand_next_row = tx_next_row.clone();
let updated_rows = apply_parsed_dml(
&mut cand_snap,
&mut cand_retired,
parsed,
&mut cand_next_row,
&sql_to_alloy_table,
&table_row_pool,
meta,
target_atom.as_deref(),
)
.map_err(SqlScriptEvalError::Parse)?;
let cand_inst =
match build_sql_instance(&cand_snap, &cand_retired, &u, &relations, &maps, meta) {
Ok(inst) => inst,
Err(BuildSqlError::Refused(reason)) => {
if !failed_rules.contains(&reason) {
failed_rules.push(reason.clone());
}
if !stmt_reasons.contains(&reason) {
stmt_reasons.push(reason);
}
break;
}
Err(BuildSqlError::Parse(m)) => return Err(SqlScriptEvalError::Parse(m)),
};
let step_trace = Trace::new(fixed.clone(), vec![tx_inst.clone(), cand_inst.clone()], 1)
.map_err(|e| SqlScriptEvalError::Parse(e.message))?;
if let ParsedDml::Update { table, assigns, .. } = parsed
&& !updated_rows.is_empty()
{
let t_alloy = sql_to_alloy_table
.get(table)
.map(String::as_str)
.unwrap_or(table.as_str());
for tr in &meta.before_update_of_triggers {
if tr.table != *table {
continue;
}
let touches_col = tr.cols.is_empty()
|| tr
.cols
.iter()
.any(|c| assigns.iter().any(|(ac, _)| ac == c));
if !touches_col {
continue;
}
let same_inst = tx_inst
.entries()
.all(|(r, ts)| cand_inst.get(r) == Some(ts));
let fires_on_noop = updated_rows.iter().any(|(_, old_row, new_row)| {
let unchanged = same_inst
|| if tr.cols.is_empty() {
old_row.keys().chain(new_row.keys()).all(|k| {
old_row.get(k).unwrap_or(&DmlVal::Null)
== new_row.get(k).unwrap_or(&DmlVal::Null)
})
} else {
tr.cols.iter().all(|c| {
old_row.get(c).unwrap_or(&DmlVal::Null)
== new_row.get(c).unwrap_or(&DmlVal::Null)
})
};
unchanged
&& trigger_when_holds(&tr.when, Some(old_row), Some(new_row), false)
});
if fires_on_noop {
let desc = format!("update_{t_alloy}: `{}`", tr.name);
if !failed_rules.contains(&desc) {
failed_rules.push(desc.clone());
}
if !stmt_reasons.contains(&desc) {
stmt_reasons.push(desc);
}
}
}
}
for (rname, rformula) in &all_facts {
if let elinvar_engine::logic::FormulaKind::Temporal(
elinvar_engine::logic::TemporalOp::Always,
inner,
) = rformula.kind()
{
let is_transition = rname == "fact trace"
|| rname.starts_with("fact Steps")
|| inner.is_temporal();
let eval_state = if is_transition { 0 } else { 1 };
match elinvar_engine::logic::evaluate_trace_at(
&step_trace,
inner,
eval_state,
&[],
) {
Ok(true) => {}
Ok(false) => {
if !failed_rules.contains(rname) {
failed_rules.push(rname.clone());
}
let mut desc = rname.clone();
if is_transition {
let guards = diagnose_refused_guards(model, &step_trace, 0);
if !guards.is_empty() {
desc = format!("{rname} ({})", guards.join(", "));
}
}
if !stmt_reasons.contains(&desc) {
stmt_reasons.push(desc);
}
}
Err(errors) => return Err(SqlScriptEvalError::Logic(errors)),
}
}
}
if !stmt_reasons.is_empty() {
break;
}
tx_snap = cand_snap;
tx_retired = cand_retired;
tx_next_row = cand_next_row;
tx_inst = cand_inst;
tx_states.push(tx_inst.clone());
}
if stmt_reasons.is_empty() {
accepted_snap = tx_snap;
accepted_retired = tx_retired;
next_row_id = tx_next_row;
accepted_inst = tx_inst;
accepted_states.extend(tx_states);
} else {
refused_by_stmt.insert(si, stmt_reasons);
}
}
let last = accepted_states.len().saturating_sub(1);
let trace = Trace::new(fixed, accepted_states, last)
.map_err(|e| SqlScriptEvalError::Parse(e.message))?;
for (rname, rformula) in &all_facts {
if populated_date_fn && crate::cli::dates::is_synthetic_date_fn_rule(rname) {
continue;
}
let is_always = matches!(
rformula.kind(),
elinvar_engine::logic::FormulaKind::Temporal(
elinvar_engine::logic::TemporalOp::Always,
_
)
);
if !is_always || refused_by_stmt.is_empty() {
match elinvar_engine::logic::evaluate_trace(&trace, rformula) {
Ok(true) => {}
Ok(false) => {
if !failed_rules.contains(rname) {
failed_rules.push(rname.clone());
}
}
Err(errors) => return Err(SqlScriptEvalError::Logic(errors)),
}
}
}
Ok((trace, stmts, failed_rules, refused_by_stmt))
}
fn parse_simple_where(clause: Option<&str>, line: usize) -> Result<Vec<DmlFilter>, String> {
let Some(w) = clause else {
return Ok(Vec::new());
};
let mut out = Vec::new();
let mut rest = w;
loop {
let (part, next) = match split_once_kw(rest, "AND") {
Some((a, b)) => (a.trim(), Some(b.trim())),
None => (rest.trim(), None),
};
if !part.is_empty() {
let cmp_hit = ["!=", "<>", "<=", ">=", "=", "<", ">"]
.into_iter()
.find_map(|op| {
part.split_once(op).map(|(l, r)| {
let kind = match op {
"!=" | "<>" => DmlFilterOp::Neq,
"<=" => DmlFilterOp::Lte,
">=" => DmlFilterOp::Gte,
"<" => DmlFilterOp::Lt,
">" => DmlFilterOp::Gt,
_ => DmlFilterOp::Eq,
};
(l, kind, r)
})
});
if let Some((col_raw, op, rhs_raw)) = cmp_hit {
let col = col_raw.trim().trim_matches('"').to_ascii_lowercase();
if col.is_empty() || !col.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
return Err(format!(
"line {line}: unsupported WHERE condition `{part}` in SQL trace"
));
}
out.push(DmlFilter {
col,
op,
val: parse_dml_val_strict(rhs_raw, line)?,
});
} else if let Some((col_raw, rhs_raw)) = split_once_kw(part, "IS") {
let rhs_t = rhs_raw.trim();
let col = col_raw.trim().trim_matches('"').to_ascii_lowercase();
if rhs_t.eq_ignore_ascii_case("null") {
out.push(DmlFilter {
col,
op: DmlFilterOp::IsNull,
val: DmlVal::Null,
});
} else if let Some((_, after_not)) = split_once_kw(rhs_t, "NOT")
&& after_not.trim().eq_ignore_ascii_case("null")
{
out.push(DmlFilter {
col,
op: DmlFilterOp::IsNotNull,
val: DmlVal::Null,
});
} else {
return Err(format!(
"line {line}: unsupported WHERE condition `{part}` in SQL trace"
));
}
} else {
return Err(format!(
"line {line}: unsupported WHERE condition `{part}` in SQL trace"
));
}
}
match next {
Some(n) => rest = n,
None => break,
}
}
Ok(out)
}
fn row_matches(row: &std::collections::BTreeMap<String, DmlVal>, filters: &[DmlFilter]) -> bool {
filters.iter().all(|f| {
let rv = row.get(&f.col).unwrap_or(&DmlVal::Null);
match f.op {
DmlFilterOp::IsNull => matches!(rv, DmlVal::Null),
DmlFilterOp::IsNotNull => !matches!(rv, DmlVal::Null),
DmlFilterOp::Eq => {
!matches!(rv, DmlVal::Null) && !matches!(f.val, DmlVal::Null) && rv == &f.val
}
DmlFilterOp::Neq => {
!matches!(rv, DmlVal::Null) && !matches!(f.val, DmlVal::Null) && rv != &f.val
}
DmlFilterOp::Lt => dml_cmp(rv, "<", &f.val),
DmlFilterOp::Lte => dml_cmp(rv, "<=", &f.val),
DmlFilterOp::Gt => dml_cmp(rv, ">", &f.val),
DmlFilterOp::Gte => dml_cmp(rv, ">=", &f.val),
}
})
}
type DmlRow = (String, std::collections::BTreeMap<String, DmlVal>);
type DmlSnap = std::collections::BTreeMap<String, Vec<DmlRow>>;
pub fn eval(file: &str, text: &str, result: &Value, expression: &str, state: usize) -> Output {
eval_with_options(
file,
text,
result,
expression,
state,
None,
&[],
false,
true,
)
}
#[allow(clippy::too_many_arguments)]
pub fn eval_with_options(
file: &str,
text: &str,
result: &Value,
expression: &str,
state: usize,
extra_als: Option<&str>,
tables: &[String],
with_referencing: bool,
allow_local_modules: bool,
) -> Output {
let effective_text: std::borrow::Cow<'_, str> = if is_sql_path(file) {
let is_trace = result["trace"].is_object();
let imp = match elinvar_als::import_sql_with(
file,
text,
&elinvar_als::SqlImportOptions::new()
.temporal(is_trace)
.tables(tables.to_vec())
.with_referencing(with_referencing),
) {
Ok(i) => i,
Err(errors) => return error_output("eval", errors),
};
let combined = match extra_als {
Some(extra) if !extra.trim().is_empty() => format!("{}\n{extra}\n", imp.model),
_ => imp.model,
};
std::borrow::Cow::Owned(combined)
} else if let Some(extra) = extra_als
&& !extra.trim().is_empty()
{
std::borrow::Cow::Owned(format!("{text}\n{extra}\n"))
} else {
std::borrow::Cow::Borrowed(text)
};
let parsed = if allow_local_modules && !is_sql_path(file) {
let loader = |module: &str| {
std::fs::read_to_string(elinvar_als::module_file(file, &effective_text, module)).ok()
};
elinvar_als::read_with_expression_loader(file, &effective_text, expression, &loader)
} else {
elinvar_als::read_with_expression(file, &effective_text, expression)
};
let (model, term) = match parsed {
Ok(x) => x,
Err(errors) => return error_output("eval", errors),
};
let relations = model.model.relations();
let trace = match trace_of(result, &relations) {
Ok(t) => t,
Err(m) => return eval_error(m),
};
let value = match &term {
Evaluable::Expr(e) => elinvar_engine::logic::evaluate_trace_expr_at(&trace, e, state)
.map(|t| serde_json::to_value(&t).unwrap_or(Value::Null)),
Evaluable::Formula(f) => {
elinvar_engine::logic::evaluate_trace_at(&trace, f, state, &[]).map(Value::Bool)
}
Evaluable::Int(n) => {
elinvar_engine::logic::evaluate_trace_int_at(&trace, n, state).map(|v| json!(v))
}
_ => return eval_error("unsupported evaluable term".to_string()),
};
match value {
Ok(v) => {
let text = match &v {
Value::Bool(b) => format!("{b}\n"),
Value::Array(tuples) => {
let parts: Vec<String> = tuples
.iter()
.map(|t| {
t.as_array()
.map(|a| {
a.iter()
.filter_map(Value::as_str)
.collect::<Vec<_>>()
.join(" -> ")
})
.unwrap_or_default()
})
.collect();
format!("{{{}}}\n", parts.join(", "))
}
other => format!("{other}\n"),
};
let mut json =
json!({ "elinvar": 1, "expression": expression, "state": state, "value": v });
let mut text = text;
let len = trace.states().len();
if state >= len {
let shown = trace.state_at(state);
let w = coded(
"cli.state_past_end",
format!(
"state {state} is past the trace's {len} state(s); the trace loops, \
so it is state {shown}"
),
);
text.push_str(&format!("warning[{}]: {}\n", w.code, w.message));
json["warnings"] = json!([w]);
}
Output {
json,
text,
status: 0,
}
}
Err(errors) => error_output("eval", errors),
}
}
pub fn diff(
old_file: &str,
old_text: &str,
new_file: &str,
new_text: &str,
over: Overrides,
) -> Output {
diff_with_modules(old_file, old_text, true, new_file, new_text, true, over)
}
pub fn diff_inline(
old_file: &str,
old_text: &str,
new_file: &str,
new_text: &str,
over: Overrides,
) -> Output {
diff_with_modules(old_file, old_text, false, new_file, new_text, false, over)
}
pub fn compose_sql_model_text(
verb: &'static str,
file: &str,
sql: &str,
extra_als: Option<&str>,
tables: &[String],
with_referencing: bool,
) -> Result<String, Output> {
compose_sql_model_text_with_start(verb, file, sql, extra_als, tables, with_referencing, true)
}
pub fn compose_sql_model_text_with_start(
verb: &'static str,
file: &str,
sql: &str,
extra_als: Option<&str>,
tables: &[String],
with_referencing: bool,
from_empty: bool,
) -> Result<String, Output> {
compose_sql_model_with_bitwidth(
verb,
file,
sql,
extra_als,
tables,
with_referencing,
from_empty,
)
.map(|(text, _)| text)
}
pub fn compose_sql_model_with_bitwidth(
verb: &'static str,
file: &str,
sql: &str,
extra_als: Option<&str>,
tables: &[String],
with_referencing: bool,
from_empty: bool,
) -> Result<(String, u32), Output> {
let als_uses_time = extra_als.is_some_and(alloy_uses_time);
let temporal = sql_has_triggers(sql) || als_uses_time;
let imp = elinvar_als::import_sql_with(
file,
sql,
&elinvar_als::SqlImportOptions::new()
.temporal(temporal)
.from_empty(temporal && from_empty)
.tables(tables.to_vec())
.with_referencing(with_referencing),
)
.map_err(|e| error_output(verb, e))?;
let bw = imp.bitwidth;
let mut body = imp.model;
if let Some(extra) = extra_als
&& !extra.trim().is_empty()
{
if extra.contains("run ") || extra.contains("check ") {
let trimmed: Vec<&str> = body
.lines()
.filter(|l| !l.trim_start().starts_with("run Show {"))
.collect();
body = trimmed.join("\n");
body.push('\n');
}
body.push('\n');
body.push_str(extra);
body.push('\n');
}
Ok((body, bw))
}
fn is_sql_path(path: &str) -> bool {
path.rsplit('.')
.next()
.is_some_and(|ext| ext.eq_ignore_ascii_case("sql"))
}
fn normalize_sql_rule(sql: &str) -> String {
sql.split_whitespace().collect::<Vec<_>>().join(" ")
}
fn words_outside_comments(text: &str, sql: bool) -> (Vec<(String, Option<u8>)>, bool) {
let b = text.as_bytes();
let (mut words, mut quote, mut i) = (Vec::new(), false, 0);
let mut word = String::new();
while i < b.len() {
let rest = &b[i..];
let skip_to = |end: &[u8], from: usize| {
b[from..]
.windows(end.len())
.position(|w| w == end)
.map_or(b.len(), |k| from + k + end.len())
};
let next = if rest.starts_with(b"--") || (!sql && rest.starts_with(b"//")) {
Some(skip_to(b"\n", i))
} else if rest.starts_with(b"/*") {
Some(skip_to(b"*/", i + 2))
} else if sql && b[i] == b'\'' {
Some(skip_to(b"'", i + 1))
} else if b[i] == b'"' {
Some(skip_to(b"\"", i + 1))
} else {
None
};
let c = b[i];
if next.is_none() && (c.is_ascii_alphanumeric() || c == b'_') {
word.push(c as char);
i += 1;
continue;
}
if !word.is_empty() {
let after = b[i..].iter().copied().find(|c| !c.is_ascii_whitespace());
words.push((std::mem::take(&mut word), after));
}
match next {
Some(n) => i = n.max(i + 1),
None => {
quote |= c == b'\'';
i += 1;
}
}
}
if !word.is_empty() {
words.push((word, None));
}
(words, quote)
}
fn sql_has_triggers(sql: &str) -> bool {
let (words, _) = words_outside_comments(sql, true);
words.iter().enumerate().any(|(i, (w, _))| {
w.eq_ignore_ascii_case("CREATE")
&& words[i + 1..]
.iter()
.take(4)
.any(|(x, _)| x.eq_ignore_ascii_case("TRIGGER"))
})
}
fn alloy_uses_time(als: &str) -> bool {
const TEMPORAL: [&str; 12] = [
"always",
"eventually",
"after",
"before",
"historically",
"once",
"until",
"releases",
"since",
"triggered",
"steps",
"induction",
];
let (words, primed) = words_outside_comments(als, false);
primed
|| words.iter().any(|(w, after)| {
TEMPORAL.contains(&w.as_str())
|| (*after == Some(b'[')
&& ["insert_", "update_", "delete_"]
.iter()
.any(|p| w.starts_with(p)))
})
}
#[allow(clippy::type_complexity, clippy::too_many_arguments)]
fn import_sql_pair_for_diff(
old_file: &str,
old_sql: &str,
new_file: &str,
new_sql: &str,
tables: &[String],
with_referencing: bool,
extra_als: Option<&str>,
ignore_unread: bool,
from_empty: bool,
) -> Result<
(
AlsModel,
AlsModel,
Vec<String>,
Vec<String>,
std::collections::BTreeMap<String, Vec<String>>,
Vec<String>,
Vec<(String, String)>,
u32,
),
Output,
> {
let temporal = sql_has_triggers(old_sql) || sql_has_triggers(new_sql);
let make_opts = |tlist: Vec<String>, with_ref: bool| {
elinvar_als::SqlImportOptions::new()
.temporal(temporal)
.from_empty(temporal && from_empty)
.tables(tlist)
.with_referencing(with_ref)
};
let mut effective_tables = tables.to_vec();
let mut effective_with_ref = with_referencing;
let mut auto_sliced = false;
let mut identical_full_unchanged: Option<Vec<String>> = None;
let mut changed_trigger_steps: Vec<(String, String)> = Vec::new();
if let Ok(Some(plan)) = elinvar_als::diff_sql_plan(old_file, old_sql, new_file, new_sql) {
changed_trigger_steps = plan.changed_trigger_steps;
if effective_tables.is_empty() {
if !plan.changed_tables.is_empty() {
effective_tables = plan.changed_tables;
effective_with_ref = with_referencing || plan.needs_referencing;
auto_sliced = true;
} else {
let full_opts = make_opts(Vec::new(), false);
if let Ok((of, nf)) =
elinvar_als::import_sql_pair(old_file, old_sql, new_file, new_sql, &full_opts)
&& of.tables.len() > 1
{
let mut unch = Vec::new();
for s in &of.skipped {
let key = normalize_sql_rule(&s.sql);
if !unch.contains(&key) {
unch.push(key);
}
}
if of.skipped.len() == nf.skipped.len() {
identical_full_unchanged = Some(unch);
effective_tables = vec![of.tables[0].clone()];
effective_with_ref = false;
auto_sliced = true;
}
}
}
}
}
let imp_opts = make_opts(effective_tables.clone(), effective_with_ref);
let (mut old_imp, mut new_imp) =
elinvar_als::import_sql_pair(old_file, old_sql, new_file, new_sql, &imp_opts)
.map_err(|e| error_output("diff", e))?;
if !effective_tables.is_empty() && old_imp.tables != new_imp.tables {
let mut union_tables: Vec<String> = old_imp.tables.clone();
for t in &new_imp.tables {
if !union_tables.iter().any(|x| x.eq_ignore_ascii_case(t)) {
union_tables.push(t.clone());
}
}
let u_opts = make_opts(union_tables, effective_with_ref);
if let Ok((o2, n2)) =
elinvar_als::import_sql_pair(old_file, old_sql, new_file, new_sql, &u_opts)
{
old_imp = o2;
new_imp = n2;
}
}
let mut old_counts: std::collections::BTreeMap<String, usize> =
std::collections::BTreeMap::new();
for s in &old_imp.skipped {
*old_counts.entry(normalize_sql_rule(&s.sql)).or_insert(0) += 1;
}
let mut new_counts: std::collections::BTreeMap<String, usize> =
std::collections::BTreeMap::new();
for s in &new_imp.skipped {
*new_counts.entry(normalize_sql_rule(&s.sql)).or_insert(0) += 1;
}
let mut unchanged_skipped = identical_full_unchanged.unwrap_or_default();
let mut differing_errors = Vec::new();
let mut matched_old = new_counts.clone();
for s in &old_imp.skipped {
let key = normalize_sql_rule(&s.sql);
if let Some(rem) = matched_old.get_mut(&key)
&& *rem > 0
{
*rem -= 1;
if !unchanged_skipped.contains(&key) {
unchanged_skipped.push(key);
}
} else {
differing_errors.push(
Error::with_fix(
"sql.skipped",
format!("unread rule in old differs from new: {} ({})", s.sql, s.reason),
"rewrite or remove the changed unsupported SQL rule before diffing schemas, or pass `--ignore-unread` to compare what is read",
)
.at(s.place.clone()),
);
}
}
let mut matched_new = old_counts;
for s in &new_imp.skipped {
let key = normalize_sql_rule(&s.sql);
if let Some(rem) = matched_new.get_mut(&key)
&& *rem > 0
{
*rem -= 1;
} else {
differing_errors.push(
Error::with_fix(
"sql.skipped",
format!("unread rule in new differs from old: {} ({})", s.sql, s.reason),
"rewrite or remove the changed unsupported SQL rule before diffing schemas, or pass `--ignore-unread` to compare what is read",
)
.at(s.place.clone()),
);
}
}
let not_compared: Vec<String> = if !differing_errors.is_empty() {
if !ignore_unread {
return Err(error_output("diff", differing_errors));
}
differing_errors.into_iter().map(|e| e.message).collect()
} else {
Vec::new()
};
let old_als = match extra_als {
Some(ex) if !ex.trim().is_empty() => format!("{}\n{ex}\n", old_imp.model),
_ => old_imp.model,
};
let new_als = match extra_als {
Some(ex) if !ex.trim().is_empty() => format!("{}\n{ex}\n", new_imp.model),
_ => new_imp.model,
};
let sql_bw = old_imp.bitwidth.max(new_imp.bitwidth);
let read_opts = elinvar_als::ReadOptions::default().default_bitwidth(sql_bw);
let old_model = elinvar_als::read_with(old_file, &old_als, read_opts)
.map_err(|e| error_output("diff", e))?;
let new_model = elinvar_als::read_with(new_file, &new_als, read_opts)
.map_err(|e| error_output("diff", e))?;
let mut sample_values = old_imp.sample_values;
for (k, v) in new_imp.sample_values {
sample_values.entry(k).or_insert(v);
}
let sliced_tables = if auto_sliced {
old_imp.tables
} else {
Vec::new()
};
Ok((
old_model,
new_model,
unchanged_skipped,
not_compared,
sample_values,
sliced_tables,
changed_trigger_steps,
sql_bw,
))
}
pub fn diff_with_modules(
old_file: &str,
old_text: &str,
old_local: bool,
new_file: &str,
new_text: &str,
new_local: bool,
over: Overrides,
) -> Output {
diff_with_options(
old_file,
old_text,
old_local,
new_file,
new_text,
new_local,
&[],
false,
over,
)
}
#[allow(clippy::too_many_arguments)]
pub fn diff_with_options(
old_file: &str,
old_text: &str,
old_local: bool,
new_file: &str,
new_text: &str,
new_local: bool,
tables: &[String],
with_referencing: bool,
over: Overrides,
) -> Output {
diff_with_options_and_extra(
old_file,
old_text,
old_local,
new_file,
new_text,
new_local,
tables,
with_referencing,
None,
over,
)
}
#[allow(clippy::too_many_arguments)]
pub fn diff_with_options_and_extra(
old_file: &str,
old_text: &str,
old_local: bool,
new_file: &str,
new_text: &str,
new_local: bool,
tables: &[String],
with_referencing: bool,
extra_als: Option<&str>,
over: Overrides,
) -> Output {
let sql_mode = is_sql_path(old_file) && is_sql_path(new_file);
let diff_from_empty = over.from_empty;
let (
old_model,
new_model,
unchanged_skipped,
not_compared,
sample_values,
sliced_tables,
changed_trigger_steps,
sql_min_bw,
) = if sql_mode {
match import_sql_pair_for_diff(
old_file,
old_text,
new_file,
new_text,
tables,
with_referencing,
extra_als,
over.ignore_unread,
diff_from_empty,
) {
Ok(res) => res,
Err(out) => return out,
}
} else {
let o_src = match extra_als {
Some(ex) if !ex.trim().is_empty() => format!("{old_text}\n{ex}\n"),
_ => old_text.to_string(),
};
let n_src = match extra_als {
Some(ex) if !ex.trim().is_empty() => format!("{new_text}\n{ex}\n"),
_ => new_text.to_string(),
};
let om = match read_model("diff", old_file, &o_src, old_local) {
Ok(m) => m,
Err(out) => return out,
};
let nm = match read_model("diff", new_file, &n_src, new_local) {
Ok(m) => m,
Err(out) => return out,
};
(
om,
nm,
Vec::new(),
Vec::new(),
std::collections::BTreeMap::new(),
Vec::new(),
Vec::new(),
elinvar_engine::logic::DEFAULT_BITWIDTH,
)
};
let scope = over.scope.unwrap_or(3);
let mut opts = Options::default().slicing(!over.no_slicing);
let has_changing = old_model
.model
.relations()
.iter()
.any(Relation::is_changing)
|| new_model
.model
.relations()
.iter()
.any(Relation::is_changing);
if let Some(n) = over.steps {
opts = opts.steps(n);
} else if sql_mode && has_changing {
opts = opts.steps(if diff_from_empty { 4 } else { 2 });
}
if let Some(b) = budget_from_overrides(over, 10_000_000) {
opts = opts.budget(b);
}
let old_bw = old_model
.commands
.iter()
.filter_map(|c| c.bitwidth())
.max()
.unwrap_or(elinvar_engine::logic::DEFAULT_BITWIDTH);
let new_bw = new_model
.commands
.iter()
.filter_map(|c| c.bitwidth())
.max()
.unwrap_or(elinvar_engine::logic::DEFAULT_BITWIDTH);
let bw = old_bw.max(new_bw).max(sql_min_bw);
let report = diff_models_with_bitwidth(&old_model.model, &new_model.model, scope, bw, &opts);
let mut unreached_rules: Vec<String> = Vec::new();
if sql_mode
&& has_changing
&& report.errors.is_empty()
&& report.verdict == Some(DiffVerdict::Equivalent)
&& !changed_trigger_steps.is_empty()
{
for (rule_name, step_name) in &changed_trigger_steps {
let old_spec = old_model
.model
.step_specs()
.iter()
.find(|s| s.name.eq_ignore_ascii_case(step_name));
let new_spec = new_model
.model
.step_specs()
.iter()
.find(|s| s.name.eq_ignore_ascii_case(step_name));
let reached_old = old_spec.is_some_and(|spec| {
let reach = spec.full_arm().eventually();
old_model
.model
.run(&reach)
.scope(scope)
.bitwidth(bw)
.options(opts)
.report()
.verdict
== Some(Verdict::Found)
});
let reached_new = !reached_old
&& new_spec.is_some_and(|spec| {
let reach = spec.full_arm().eventually();
new_model
.model
.run(&reach)
.scope(scope)
.bitwidth(bw)
.options(opts)
.report()
.verdict
== Some(Verdict::Found)
});
if !reached_old && !reached_new {
unreached_rules.push(format!(
"`{rule_name}` (step `{step_name}`) was not reached in {} steps",
opts.steps
));
}
}
}
let mut status = if !report.errors.is_empty() {
3
} else if !unreached_rules.is_empty() {
2
} else {
match report.verdict {
Some(DiffVerdict::Equivalent) => 0,
Some(DiffVerdict::Tightened | DiffVerdict::Loosened | DiffVerdict::Diverged) => 1,
Some(DiffVerdict::Unknown | DiffVerdict::Vacuous) => 2,
Some(_) | None => 3,
}
};
if !not_compared.is_empty() && status != 3 {
status = 2;
}
let mut text = if !unreached_rules.is_empty() {
let mut s = String::from("diff: unknown\n");
for u in &unreached_rules {
s.push_str(&format!(" {u}\n"));
}
s.push_str(" hint: pass --from-any or raise --steps to reach the changed rule(s)\n");
s
} else {
report.story.clone()
};
if !sliced_tables.is_empty() {
text.push_str(&format!(
"\nsliced to changed table(s) and dependencies: {}\n",
sliced_tables.join(", ")
));
}
if !not_compared.is_empty() {
text.push_str("\nnot compared (unread rule changes):\n");
for nc in ¬_compared {
text.push_str(&format!(" {nc}\n"));
}
}
if !unchanged_skipped.is_empty() {
text.push_str("\nunchanged unread rules (identical in both schemas):\n");
for u in &unchanged_skipped {
text.push_str(&format!(" {u}\n"));
}
}
if sql_mode && report.errors.is_empty() {
if let Some(r) = &report.only_in_old
&& let Ok(sql_out) = render_report_sql_with_values(r, None, &sample_values)
{
text.push_str("\n-- SQL rows allowed by old, refused by new:\n");
text.push_str(&sql_out);
}
if let Some(r) = &report.only_in_new
&& let Ok(sql_out) = render_report_sql_with_values(r, None, &sample_values)
{
text.push_str("\n-- SQL rows allowed by new, refused by old:\n");
text.push_str(&sql_out);
}
}
let mut json = serde_json::to_value(&report).unwrap_or(Value::Null);
if let Some(obj) = json.as_object_mut() {
if !unreached_rules.is_empty() {
obj.insert("verdict".to_string(), json!("unknown"));
obj.insert("unreached_rules".to_string(), json!(unreached_rules));
}
if !sliced_tables.is_empty() {
obj.insert("sliced_tables".to_string(), json!(sliced_tables));
}
if !not_compared.is_empty() {
obj.insert("not_compared".to_string(), json!(not_compared));
}
if !unchanged_skipped.is_empty() {
obj.insert("unchanged_skipped".to_string(), json!(unchanged_skipped));
}
obj.insert("story".to_string(), json!(text));
}
Output { json, text, status }
}
#[allow(clippy::too_many_arguments)]
pub fn diff_of_with_modules(
old_file: &str,
old_text: &str,
old_local: bool,
new_file: &str,
new_text: &str,
new_local: bool,
fun_name: &str,
over: Overrides,
) -> Output {
diff_of_with_extra(
old_file, old_text, old_local, new_file, new_text, new_local, fun_name, None, over,
)
}
#[allow(clippy::too_many_arguments)]
pub fn diff_of_with_extra(
old_file: &str,
old_text: &str,
old_local: bool,
new_file: &str,
new_text: &str,
new_local: bool,
fun_name: &str,
extra_als: Option<&str>,
over: Overrides,
) -> Output {
let sql_mode = is_sql_path(old_file) && is_sql_path(new_file);
let mut sample_values = std::collections::BTreeMap::new();
let mut sql_min_bw = elinvar_engine::logic::DEFAULT_BITWIDTH;
let (old_model, old_expr, new_model, new_expr) = if sql_mode {
let temporal = sql_has_triggers(old_text) || sql_has_triggers(new_text);
let imp_opts = elinvar_als::SqlImportOptions::new()
.temporal(temporal)
.from_empty(temporal && over.from_empty);
let (old_imp, new_imp) =
match elinvar_als::import_sql_pair(old_file, old_text, new_file, new_text, &imp_opts) {
Ok(pair) => pair,
Err(e) => return error_output("diff", e),
};
sql_min_bw = old_imp.bitwidth.max(new_imp.bitwidth);
sample_values = old_imp.sample_values;
for (k, v) in new_imp.sample_values {
sample_values.entry(k).or_insert(v);
}
let o_src = match extra_als {
Some(ex) if !ex.trim().is_empty() => format!("{}\n{ex}\n", old_imp.model),
_ => old_imp.model,
};
let n_src = match extra_als {
Some(ex) if !ex.trim().is_empty() => format!("{}\n{ex}\n", new_imp.model),
_ => new_imp.model,
};
let (om, oe) = match elinvar_als::read_with_function(old_file, &o_src, fun_name) {
Ok(pair) => pair,
Err(e) => return error_output("diff", e),
};
let (nm, ne) = match elinvar_als::read_with_function(new_file, &n_src, fun_name) {
Ok(pair) => pair,
Err(e) => return error_output("diff", e),
};
(om, oe, nm, ne)
} else {
let o_src = match extra_als {
Some(ex) if !ex.trim().is_empty() => format!("{old_text}\n{ex}\n"),
_ => old_text.to_string(),
};
let n_src = match extra_als {
Some(ex) if !ex.trim().is_empty() => format!("{new_text}\n{ex}\n"),
_ => new_text.to_string(),
};
let read_side = |file: &str, text: &str, local: bool| {
if local {
let loader = |module: &str| {
std::fs::read_to_string(elinvar_als::module_file(file, text, module)).ok()
};
elinvar_als::read_with_function_loader(file, text, fun_name, &loader)
.map_err(|e| error_output("diff", e))
} else {
elinvar_als::read_with_function(file, text, fun_name)
.map_err(|e| error_output("diff", e))
}
};
let (om, oe) = match read_side(old_file, &o_src, old_local) {
Ok(pair) => pair,
Err(out) => return out,
};
let (nm, ne) = match read_side(new_file, &n_src, new_local) {
Ok(pair) => pair,
Err(out) => return out,
};
(om, oe, nm, ne)
};
let scope = over.scope.unwrap_or(3);
let mut opts = Options::default().slicing(!over.no_slicing);
if let Some(n) = over.steps {
opts = opts.steps(n);
} else if sql_mode
&& (old_model
.model
.relations()
.iter()
.any(Relation::is_changing)
|| new_model
.model
.relations()
.iter()
.any(Relation::is_changing))
{
opts = opts.steps(4);
}
if let Some(b) = budget_from_overrides(over, 10_000_000) {
opts = opts.budget(b);
}
let old_bw = old_model
.commands
.iter()
.filter_map(|c| c.bitwidth())
.max()
.unwrap_or(elinvar_engine::logic::DEFAULT_BITWIDTH);
let new_bw = new_model
.commands
.iter()
.filter_map(|c| c.bitwidth())
.max()
.unwrap_or(elinvar_engine::logic::DEFAULT_BITWIDTH);
let bw = old_bw.max(new_bw).max(sql_min_bw);
let report = diff_functions(
&old_model.model,
&old_expr,
&new_model.model,
&new_expr,
scope,
bw,
&opts,
);
let status = if !report.errors.is_empty() {
3
} else {
match report.verdict {
Some(DiffVerdict::Equivalent) => 0,
Some(DiffVerdict::Tightened | DiffVerdict::Loosened | DiffVerdict::Diverged) => 1,
Some(DiffVerdict::Unknown | DiffVerdict::Vacuous) => 2,
Some(_) | None => 3,
}
};
let mut text = report.story.clone();
if sql_mode && report.errors.is_empty() {
if let Some(r) = &report.only_in_old
&& let Ok(sql_out) = render_report_sql_with_values(r, None, &sample_values)
{
text.push_str("\n-- SQL database where old query returns an extra tuple:\n");
text.push_str(&sql_out);
}
if let Some(r) = &report.only_in_new
&& let Ok(sql_out) = render_report_sql_with_values(r, None, &sample_values)
{
text.push_str("\n-- SQL database where new query returns an extra tuple:\n");
text.push_str(&sql_out);
}
}
let json = serde_json::to_value(&report).unwrap_or(Value::Null);
Output { json, text, status }
}
pub fn diff_of_inline(
old_file: &str,
old_text: &str,
new_file: &str,
new_text: &str,
fun_name: &str,
over: Overrides,
) -> Output {
diff_of_with_modules(
old_file, old_text, false, new_file, new_text, false, fun_name, over,
)
}
pub fn import_sql(file: &str, sql: &str) -> Output {
import_sql_with(file, sql, &elinvar_als::SqlImportOptions::default(), false).0
}
pub fn import_sql_with(
file: &str,
sql: &str,
opts: &elinvar_als::SqlImportOptions,
strict: bool,
) -> (Output, Option<String>) {
import_sql_with_extra(file, sql, opts, strict, None)
}
pub fn import_sql_with_extra(
file: &str,
sql: &str,
opts: &elinvar_als::SqlImportOptions,
strict: bool,
extra_als: Option<&str>,
) -> (Output, Option<String>) {
match elinvar_als::import_sql_with(file, sql, opts) {
Ok(mut imp) => {
if let Some(extra) = extra_als
&& !extra.trim().is_empty()
{
if extra.contains("run ") || extra.contains("check ") {
let trimmed: Vec<&str> = imp
.model
.lines()
.filter(|l| !l.trim_start().starts_with("run Show {"))
.collect();
imp.model = trimmed.join("\n");
imp.model.push('\n');
}
imp.model.push('\n');
imp.model.push_str(extra);
if !imp.model.ends_with('\n') {
imp.model.push('\n');
}
}
if strict && !imp.skipped.is_empty() {
let errors: Vec<Error> = imp
.skipped
.iter()
.map(|s| {
Error::with_fix(
"sql.skipped",
format!("not read: {} ({})", s.sql, s.reason),
"rewrite or remove the unsupported SQL rule, or drop `--strict` to inspect the skipped comments",
)
.at(s.place.clone())
})
.collect();
return (error_output("import", errors), None);
}
let skipped_json: Vec<Value> = imp
.skipped
.iter()
.map(|s| {
json!({
"place": s.place,
"sql": s.sql,
"reason": s.reason,
})
})
.collect();
let ignored_json: Vec<Value> = imp
.ignored
.iter()
.map(|s| {
json!({
"place": s.place,
"sql": s.sql,
"reason": s.reason,
})
})
.collect();
let mut note_parts = Vec::new();
if !imp.skipped.is_empty() {
let n = imp.skipped.len();
let word = if n == 1 { "rule" } else { "rules" };
let extra = if imp.ignored.is_empty() {
String::new()
} else {
format!(", {} non-rule statement(s) ignored", imp.ignored.len())
};
note_parts.push(format!("skipped {n} {word}{extra}"));
}
if !imp.outside_referencing_tables.is_empty() {
note_parts.push(format!(
"slice left out referencing table(s): {}",
imp.outside_referencing_tables.join(", ")
));
}
if !imp.dropped_triggers.is_empty() {
note_parts.push(format!(
"slice dropped {} trigger(s)",
imp.dropped_triggers.len()
));
}
let note = if note_parts.is_empty() {
None
} else {
Some(format!(
"elinvar import: {} (see comments or --json)",
note_parts.join("; ")
))
};
let mut json = json!({
"elinvar": 1,
"tables": imp.tables,
"skipped": skipped_json,
"ignored": ignored_json,
"outside_referencing_tables": imp.outside_referencing_tables,
"dropped_triggers": imp.dropped_triggers,
"sample_values": imp.sample_values,
"model": imp.model,
});
if !imp.views.is_empty() {
json["views"] = json!(imp.views);
}
(
Output {
json,
text: imp.model,
status: 0,
},
note,
)
}
Err(errors) => (error_output("import", errors), None),
}
}
fn instance_from_json(v: &Value) -> Result<Instance, String> {
let atoms = atom_names(&v["atoms"], "an instance without atoms")?;
let u = Universe::new(atoms).map_err(|e| e.message)?;
let mut inst = Instance::new(&u);
for r in v["relations"]
.as_array()
.ok_or("an instance without relations")?
{
let name = r["name"].as_str().ok_or("a relation without a name")?;
let arity = r["arity"].as_u64().ok_or("a relation without arity")? as usize;
let rel = Relation::new(name, arity);
let tuples = tuple_rows(r)?;
let refs: Vec<&[&str]> = tuples.iter().map(Vec::as_slice).collect();
let set = u.tuple_set(arity, &refs).map_err(|e| e.message)?;
inst.set(&rel, set).map_err(|e| e.message)?;
}
Ok(inst)
}
pub fn diagram_format(name: &str) -> Option<DiagramFormat> {
match name {
"dot" => Some(DiagramFormat::Dot),
"mermaid" => Some(DiagramFormat::Mermaid),
"sql" => Some(DiagramFormat::Sql),
_ => None,
}
}
fn format_name(format: DiagramFormat) -> &'static str {
match format {
DiagramFormat::Mermaid => "mermaid",
DiagramFormat::Sql => "sql",
_ => "dot",
}
}
pub fn render(result: &Value, format: DiagramFormat, state: Option<usize>) -> Output {
render_with_values(result, format, state, &std::collections::BTreeMap::new())
}
pub fn render_with_values(
result: &Value,
format: DiagramFormat,
state: Option<usize>,
sample_values: &std::collections::BTreeMap<String, Vec<String>>,
) -> Output {
let rendered = if result["instance"].is_object() {
instance_from_json(&result["instance"]).map(|i| {
if format == DiagramFormat::Sql && !sample_values.is_empty() {
render_instance_sql_with_values(&i, sample_values)
} else {
render_instance(&i, format)
}
})
} else if result["trace"].is_object() {
let t = &result["trace"];
let states_v = t["states"].as_array().cloned().unwrap_or_default();
if let Some(k) = state
&& k >= states_v.len()
{
Err(format!(
"state {k} is out of range (trace has {} states)",
states_v.len()
))
} else {
(|| -> Result<String, String> {
let fixed = instance_from_json(&t["fixed"])?;
let mut states = Vec::with_capacity(states_v.len());
for s in &states_v {
states.push(instance_from_json(s)?);
}
if format == DiagramFormat::Sql && !sample_values.is_empty() {
Ok(render_states_sql_with_values(
&fixed,
&states,
state,
sample_values,
))
} else {
Ok(render_states(&fixed, &states, state, format))
}
})()
}
} else {
Err("the result has no instance and no trace to render".to_string())
};
match rendered {
Ok(diagram) => Output {
json: json!({
"elinvar": 1,
"format": format_name(format),
"state": state,
"diagram": diagram,
}),
text: diagram,
status: 0,
},
Err(m) => eval_error(m),
}
}
pub fn render_model_text(
file: &str,
text: &str,
format: DiagramFormat,
allow_local_modules: bool,
) -> Output {
if format == DiagramFormat::Sql {
return eval_error(
"`--sql` renders an instance or trace from a result JSON, not a model schema; use `--dot` or `--mermaid` for a model".to_string(),
);
}
let model = if is_sql_path(file) {
let imp = match elinvar_als::import_sql_with(
file,
text,
&elinvar_als::SqlImportOptions::new().temporal(true),
) {
Ok(i) => i,
Err(errors) => return error_output("render", errors),
};
match read_model("render", file, &imp.model, false) {
Ok(m) => m,
Err(out) => return out,
}
} else {
match read_model("render", file, text, allow_local_modules) {
Ok(m) => m,
Err(out) => return out,
}
};
let diagram = render_model(&model.model, format);
Output {
json: json!({
"elinvar": 1,
"format": format_name(format),
"diagram": diagram,
}),
text: diagram,
status: 0,
}
}
pub const CLI_CODES: &[elinvar_engine::logic::Code] = &[
elinvar_engine::logic::Code::new(
"cli.usage",
"a verb was given a flag, argument, or value it does not take, or a verb that does not exist",
"read the verb's `--help` (or `elinvar --help` for the verbs), and pass what it lists",
),
elinvar_engine::logic::Code::new(
"cli.steps_ignored",
"warning: `--steps` (or the `steps` argument) was given for a model where nothing changes, so there is no trace for it to bound",
"drop `--steps`, or declare what changes with `var`",
),
elinvar_engine::logic::Code::new(
"cli.state_past_end",
"warning: `--state K` (or `state`) is at or past the number of states in the trace; the trace loops, so K is read as the state the loop reaches there (LOGIC.md section 13.1)",
"give a state from 0 to one less than the number of states; a static instance has only state 0",
),
elinvar_engine::logic::Code::new(
"cli.input",
"an input named on the command line cannot be read: a missing or unreadable file, a directory with no `.sql` files, stdin that fails, or a result that is not JSON",
"check the path and its permissions; `-` reads stdin, and a directory is read as its `.sql` files in name order",
),
elinvar_engine::logic::Code::new(
"audit.parse",
"a SQL data dump passed to `elinvar audit --data` has an unreadable INSERT statement or value",
"check the SQL dump syntax and pass INSERT statements from `sqlite3 .dump` or `pg_dump --inserts`",
),
elinvar_engine::logic::Code::new(
"audit.dropped_rows",
"a SQL dump passed to `elinvar audit --data` inserts rows into a table that is not in the audited schema, or not in its `--tables` slice; those rows are not audited",
"add the table to the schema or to `--tables`, or remove its rows from the dump if they do not belong to this database",
),
elinvar_engine::logic::Code::new(
"audit.ignored_statement",
"a SQL dump passed to `elinvar audit --data` has a statement that is neither an INSERT nor one that carries no rows (such as `COPY`, `UPDATE`, or text that is not SQL); it is not read",
"dump with `sqlite3 DB .dump` or `pg_dump --inserts`, which write every row as an INSERT",
),
elinvar_engine::logic::Code::new(
"audit.no_rows",
"a SQL dump passed to `elinvar audit --data` has no INSERT statement, so the audit read no row and its `clean` says nothing about any data",
"check that the file is the dump of the database meant; an empty database needs no audit",
),
elinvar_engine::logic::Code::new(
"ci.manifest",
"a CI manifest passed to `elinvar ci` cannot be parsed or has an invalid entry",
"check the manifest TOML fields (`[[check]]`, `[[run]]`, `[[accepts]]`, `[[diff]]`, `[[discover]]`, `[[tests]]`) and referenced file paths",
),
];
fn all_codes() -> Vec<&'static elinvar_engine::logic::Code> {
elinvar_engine::codes()
.chain(elinvar_als::ALS_CODES)
.chain(CLI_CODES)
.collect()
}
pub const SKILL: &str = include_str!("SKILL.md");
pub fn explain(subject: Option<&str>) -> Output {
match subject {
None => {
let codes = all_codes();
let text = codes
.iter()
.map(|c| format!("{:<32} {}\n", c.code, c.when))
.collect::<String>();
Output {
json: serde_json::to_value(&codes).unwrap_or(Value::Null),
text,
status: 0,
}
}
Some("schema") => {
let list: Vec<Value> = crate::cli::schemas::SCHEMAS
.iter()
.map(|s| {
json!({
"subject": s.subject,
"uri": s.uri,
"file": s.file,
"description": s.description,
})
})
.collect();
let text = crate::cli::schemas::SCHEMAS
.iter()
.map(|s| format!("{:<20} {}\n", s.subject, s.description))
.collect::<String>();
Output {
json: json!({ "elinvar": 1, "schemas": list }),
text,
status: 0,
}
}
Some(subject) if subject.starts_with("schema:") => {
match crate::cli::schemas::by_subject(subject) {
Some(spec) => Output {
json: serde_json::from_str(spec.text).unwrap_or(Value::Null),
text: spec.text.to_string(),
status: 0,
},
None => {
let names: Vec<&str> = crate::cli::schemas::SCHEMAS
.iter()
.map(|s| s.subject)
.collect();
Output {
json: json!({ "elinvar": 1, "error": format!("no schema `{subject}`") }),
text: format!(
"no schema `{subject}`; available schemas: {}\n",
names.join(", ")
),
status: 3,
}
}
}
}
Some("skill") => Output {
json: json!({
"elinvar": 1,
"subject": "skill",
"content": SKILL,
}),
text: SKILL.to_string(),
status: 0,
},
Some(code) => match all_codes().into_iter().find(|c| c.code == code) {
Some(c) => Output {
json: serde_json::to_value(c).unwrap_or(Value::Null),
text: format!("{}\n when: {}\n fix: {}\n", c.code, c.when, c.fix),
status: 0,
},
None => {
let schema_list = crate::cli::schemas::SCHEMAS
.iter()
.map(|s| format!("`{}`", s.subject))
.collect::<Vec<_>>()
.join(", ");
Output {
json: json!({ "elinvar": 1, "error": format!("no code or subject `{code}`") }),
text: format!(
"no code or subject `{code}`; `elinvar explain` lists every code, \
`elinvar explain schema` lists every JSON Schema ({schema_list}), and \
`elinvar explain skill` prints the agent guide\n"
),
status: 3,
}
}
},
}
}
pub fn replay(file: &str, text: &str, name: &str, result: &Value) -> Result<bool, String> {
let model = elinvar_als::read(file, text).map_err(|e| format!("{e:?}"))?;
let spec = model
.find(name)
.ok_or_else(|| format!("the reference has no command `{name}`"))?;
if result["verdict"] != "counterexample" && result["verdict"] != "found" {
return Ok(false);
}
let trace = trace_of(result, &model.model.relations())?;
model
.command(spec)
.witnessed_by(&trace)
.map_err(|e| format!("{e:?}"))
}
#[cfg(test)]
mod tests {
use super::{alloy_uses_time, sql_has_triggers};
#[test]
fn temporal_mode_is_decided_by_words() {
assert!(sql_has_triggers(
"CREATE TABLE t (id INT);\ncreate or replace trigger t_ins after insert on t begin select 1; end;"
));
assert!(!sql_has_triggers(
"-- CREATE TRIGGER later\nCREATE TABLE trigger_log (note TEXT DEFAULT 'CREATE TRIGGER');"
));
assert!(alloy_uses_time("check C { always some t_sql }"));
assert!(alloy_uses_time("check C { all r: t_sql | r.v' = r.v }"));
assert!(alloy_uses_time("run { some r: t_sql | insert_t[r] }"));
assert!(!alloy_uses_time(
"// always\ncheck C { all r: t_sql | some r.afterwards and r.update_count = r.update_count }"
));
}
}