use indexmap::IndexMap;
use lemma::{DateTimeValue, Engine, EvaluateDataValue, RuleResult, SourceType};
use std::collections::BTreeSet;
fn load(code: &str) -> Engine {
let mut engine = Engine::new();
engine
.load([(SourceType::Volatile, code.to_string())])
.unwrap_or_else(|e| panic!("specs must load: {e:?}\n{code}"));
engine
}
type Inputs<'a> = &'a [(&'a str, &'a str)];
fn data(inputs: Inputs) -> IndexMap<String, EvaluateDataValue> {
inputs
.iter()
.map(|(name, value)| (name.to_string(), EvaluateDataValue::string(*value)))
.collect()
}
fn evaluate(
engine: &Engine,
spec: &str,
data: IndexMap<String, EvaluateDataValue>,
rules: Option<&[&str]>,
explain: bool,
) -> lemma::Response {
let rules: Option<Vec<String>> =
rules.map(|rules| rules.iter().map(|rule| rule.to_string()).collect());
let now = DateTimeValue::now();
engine
.evaluate(None, spec, Some(&now), data, rules.as_deref(), explain)
.expect("evaluation must succeed")
}
fn rule<'a>(response: &'a lemma::Response, name: &str) -> &'a RuleResult {
response
.results
.get(name)
.unwrap_or_else(|| panic!("rule '{name}' missing from results"))
}
fn assert_missing(code: &str, inputs: Inputs, expected: &[&str]) {
let engine = load(code);
for (rules, explain) in [
(Some(&["r"][..]), false),
(None, false),
(Some(&["r"][..]), true),
] {
let response = evaluate(&engine, "main", data(inputs), rules, explain);
let result = rule(&response, "r");
assert_eq!(
result.missing_data(),
expected,
"rules {rules:?}, explain {explain}, given {inputs:?}, result {:?}",
result.result()
);
for key in result.missing_data_options().keys() {
assert!(
expected.contains(&key.as_str()),
"options of '{key}', which is not missing"
);
}
}
}
fn assert_result(code: &str, inputs: Inputs, expected: &str) {
let engine = load(code);
let response = evaluate(&engine, "main", data(inputs), Some(&["r"]), false);
let result = rule(&response, "r");
assert_eq!(
result.result(),
Some(expected),
"given {inputs:?}: missing {:?}, veto {:?}",
result.missing_data(),
result.veto_reason
);
}
fn main_spec(rules: &str) -> String {
format!(
"spec main\ndata x: number\ndata y: number\ndata z: number\ndata a: boolean\ndata b: boolean\ndata c: boolean\nrule stop: veto \"stop\"\n{rules}\n"
)
}
#[test]
fn a_true_condition_below_rules_out_the_default() {
assert_missing(
&main_spec("rule r: x\n unless c then 5\n unless b then 7"),
&[("c", "true")],
&["b"],
);
}
#[test]
fn a_false_condition_below_keeps_the_default() {
assert_missing(
&main_spec("rule r: x\n unless c then 5\n unless b then 7"),
&[("c", "false")],
&["b", "x"],
);
}
#[test]
fn a_negated_condition_below_rules_out_the_default() {
assert_missing(
&main_spec("rule r: x\n unless not(c) then 5\n unless b then 7"),
&[("c", "false")],
&["b"],
);
}
#[test]
fn a_comparison_below_rules_out_the_default() {
assert_missing(
&main_spec("rule r: x\n unless y > 1 then 5\n unless b then 7"),
&[("y", "3")],
&["b"],
);
}
#[test]
fn a_conjunction_below_rules_out_the_default() {
assert_missing(
&main_spec("rule r: x\n unless c and a then 5\n unless b then 7"),
&[("c", "true"), ("a", "true")],
&["b"],
);
}
#[test]
fn a_disjunction_below_rules_out_the_default() {
assert_missing(
&main_spec("rule r: x\n unless c or a then 5\n unless b then 7"),
&[("c", "true")],
&["b"],
);
}
#[test]
fn a_rule_below_rules_out_the_default() {
assert_missing(
&main_spec("rule g: c\nrule r: x\n unless g then 5\n unless b then 7"),
&[("c", "true")],
&["b"],
);
}
#[test]
fn a_constant_rule_below_rules_out_the_default() {
assert_missing(
&main_spec("rule g: 2 > 1\nrule r: x\n unless g then 5\n unless b then 7"),
&[],
&["b"],
);
}
#[test]
fn a_branch_below_that_wins_keeps_its_own_data() {
assert_missing(
&main_spec("rule r: x\n unless c then z\n unless b then 7"),
&[("c", "true")],
&["b", "z"],
);
}
#[test]
fn a_branch_below_that_wins_rules_out_the_arms_under_it() {
assert_missing(
&main_spec("rule r: x\n unless a then y\n unless c then 5\n unless b then 7"),
&[("c", "true")],
&["b"],
);
}
#[test]
fn an_open_condition_between_stays_needed() {
assert_missing(
&main_spec("rule r: x\n unless c then 5\n unless a then 6\n unless b then 7"),
&[("c", "true")],
&["b", "a"],
);
}
#[test]
fn a_branch_below_that_wins_with_a_veto_rules_out_the_default() {
assert_missing(
&main_spec("rule r: x\n unless c then veto \"closed\"\n unless b then 7"),
&[("c", "true")],
&["b"],
);
}
#[test]
fn a_vetoed_condition_below_rules_out_the_default() {
assert_missing(
&main_spec("rule r: x\n unless stop > 1 then 5\n unless b then 7"),
&[],
&["b"],
);
}
#[test]
fn a_vetoed_condition_below_rules_out_its_own_branch() {
assert_missing(
&main_spec("rule r: x\n unless stop > 1 then z\n unless b then 7"),
&[],
&["b"],
);
}
#[test]
fn a_condition_that_fails_its_type_below_rules_out_the_default() {
assert_missing(
&main_spec(
"data n: number\n -> maximum 9\nrule r: x\n unless n > 1 then 5\n unless b then 7",
),
&[("n", "99")],
&["b"],
);
}
#[test]
fn an_open_branch_that_is_a_veto_anyway_rules_out_its_data() {
for body in [
"x + stop",
"stop + x",
"x * stop",
"x - stop",
"stop / x",
"(x + y) * stop",
] {
assert_missing(
&main_spec(&format!("rule r: 1\n unless b then {body}")),
&[],
&["b"],
);
}
}
#[test]
fn an_open_branch_that_has_its_value_rules_out_the_rest() {
assert_missing(
&main_spec("rule q: a and c\nrule r: 1\n unless b then 2\n unless y > 1 and q then 3"),
&[("a", "false")],
&["b"],
);
assert_missing(
&main_spec("rule q: x\n unless c then 5\nrule r: q\n unless b then q + 1"),
&[("c", "true")],
&["b"],
);
}
#[test]
fn a_branch_below_that_is_a_veto_anyway_rules_out_its_data() {
assert_missing(
&main_spec("rule q: 1\n unless c then x\n unless stop > 1 then x\nrule p: 2\n unless y > 1 then 3\nrule r: p + q\n unless b then 1"),
&[],
&["b"],
);
}
const DECIDED: &str = "rule q: x\n unless c then 5\n unless b then 7\n";
#[test]
fn a_reference_to_the_rule_misses_the_same() {
let code = main_spec(&format!("{DECIDED}rule r: q"));
assert_missing(&code, &[("c", "true")], &["b"]);
}
#[test]
fn arithmetic_on_the_rule_misses_the_same() {
let code = main_spec(&format!("{DECIDED}rule r: q + z"));
assert_missing(&code, &[("c", "true"), ("z", "1")], &["b"]);
}
#[test]
fn a_condition_on_the_rule_misses_the_same() {
let code = main_spec(&format!("{DECIDED}rule r: 1\n unless q is z then 2"));
assert_missing(&code, &[("c", "true"), ("z", "1")], &["b"]);
}
#[test]
fn a_branch_that_is_the_rule_misses_the_same() {
let code = main_spec(&format!("{DECIDED}rule r: z\n unless a then q"));
assert_missing(&code, &[("c", "true"), ("a", "true")], &["b"]);
}
#[test]
fn folded_arithmetic_on_the_rule_misses_the_same() {
let code = main_spec(&format!("{DECIDED}rule r: q + 0"));
assert_missing(&code, &[("c", "true")], &["b"]);
}
#[test]
fn a_used_spec_misses_the_same() {
assert_missing(
"spec inner\ndata x: number\ndata b: boolean\ndata c: boolean\nrule q: x\n unless c then 5\n unless b then 7\n\nspec main\nuses inner\nrule r: inner.q\n",
&[("inner.c", "true")],
&["inner.b"],
);
}
#[test]
fn a_spec_two_uses_deep_misses_the_same() {
assert_missing(
"spec inner\ndata x: number\ndata b: boolean\ndata c: boolean\nrule q: x\n unless c then 5\n unless b then 7\n\nspec middle\nuses inner\nrule q: inner.q\n\nspec main\nuses middle\nrule r: middle.q\n",
&[("middle.inner.c", "true")],
&["middle.inner.b"],
);
}
#[test]
fn a_global_misses_the_same() {
assert_missing(
"spec inner\ndata x: number\ndata b: boolean\ndata c: boolean\nrule q: x\n unless c then 5\n unless b then 7\n\nspec main\nuses global inner\nrule r: inner.q\n",
&[("global.inner.c", "true")],
&["global.inner.b"],
);
}
const WIRED: &str = "spec inner\ndata x: number\ndata b: boolean\ndata c: boolean\nrule q: x\n unless c then 5\n unless b then 7\n\nspec main\nuses inner\n -> with x: worth\n -> with c: known\ndata n: number\ndata known: boolean\nrule worth: n + 1\nrule r: inner.q\n";
#[test]
fn a_slot_bound_to_a_rule_misses_the_same() {
assert_missing(WIRED, &[("known", "true")], &["inner.b"]);
}
#[test]
fn a_slot_bound_to_a_rule_that_is_read_names_its_data() {
assert_missing(WIRED, &[("known", "false")], &["inner.b", "n"]);
}
#[test]
fn a_slot_bound_to_a_condition_that_misses_data_names_that_data() {
assert_missing(
"spec inner\ndata x: number\ndata b: boolean\ndata c: boolean\nrule q: x\n unless c then 5\n unless b then 7\n\nspec main\nuses inner\n -> with b: open\ndata n: number\nrule open: n > 1\nrule r: inner.q\n",
&[("inner.c", "true")],
&["n"],
);
}
const ROW: &str = "spec row\ndata x: number\ndata b: boolean\ndata c: boolean\nrule q: x\n unless c then 5\n unless b then 7\n\n";
fn one_row(pairs: Inputs) -> IndexMap<String, EvaluateDataValue> {
let row = pairs
.iter()
.map(|(name, value)| (name.to_string(), EvaluateDataValue::string(*value)))
.collect();
IndexMap::from([(
"rows".to_string(),
EvaluateDataValue::List(vec![EvaluateDataValue::Map(row)]),
)])
}
#[test]
fn a_request_row_misses_the_same() {
let engine = load(&format!(
"{ROW}spec main\nuses row\ndata rows: row list\nrule r: rows -> sum rows.q\n"
));
let response = evaluate(&engine, "main", one_row(&[("c", "true")]), None, false);
assert_eq!(rule(&response, "r").missing_data(), ["rows.1.b"]);
}
#[test]
fn a_member_read_of_a_request_row_misses_the_same() {
let engine = load(&format!(
"{ROW}spec main\nuses row\ndata rows: row list\nrule r: (rows -> first).q\n"
));
let response = evaluate(&engine, "main", one_row(&[("c", "true")]), None, false);
assert_eq!(rule(&response, "r").missing_data(), ["rows.1.b"]);
}
#[test]
fn a_spec_written_row_misses_the_same() {
assert_missing(
&format!("{ROW}spec main\nuses row\ndata n: number\ndata open: boolean\ndata rows: row list\n -> with x: n, b: open, c: true\nrule r: rows -> sum rows.q\n"),
&[],
&["open"],
);
}
#[test]
fn rows_a_rule_makes_miss_every_field_it_writes() {
let code = format!("{ROW}spec main\nuses row\ndata n: number\ndata open: boolean\nrule rows: row list\n -> with x: n, b: open, c: true\nrule r: rows -> sum q\n");
assert_missing(&code, &[], &["n", "open"]);
assert_missing(&code, &[("open", "true")], &["n"]);
assert_missing(&code, &[("n", "1")], &["open"]);
}
const KEYED: &str = "rule r: x\n unless y is 1 and c then 5\n unless y is 2 and c then 6";
#[test]
fn a_false_operand_decides_conditions_on_one_value() {
assert_result(&main_spec(KEYED), &[("c", "false"), ("x", "1")], "1");
}
#[test]
fn a_false_operand_decides_conditions_on_one_value_in_either_order() {
assert_result(
&main_spec("rule r: x\n unless c and y is 1 then 5\n unless c and y is 2 then 6"),
&[("c", "false"), ("x", "1")],
"1",
);
}
#[test]
fn a_false_operand_decides_conditions_on_one_vetoed_value() {
assert_result(
&main_spec("rule r: x\n unless stop is 1 and c then 5\n unless stop is 2 and c then 6"),
&[("c", "false"), ("x", "1")],
"1",
);
}
#[test]
fn different_false_operands_decide_conditions_on_one_value() {
assert_result(
&main_spec("rule r: x\n unless y is 1 and c then 5\n unless y is 2 and b then 6"),
&[("c", "false"), ("b", "false"), ("x", "1")],
"1",
);
}
#[test]
fn decided_conditions_on_one_value_miss_only_the_default() {
assert_missing(&main_spec(KEYED), &[("c", "false")], &["x"]);
}
#[test]
fn a_decided_branch_on_one_value_rules_out_its_data() {
assert_missing(
&main_spec("rule r: x\n unless y is 1 and c then z\n unless y is 2 and b then 6"),
&[("c", "false"), ("x", "1"), ("b", "true")],
&["y"],
);
}
#[test]
fn a_decided_condition_under_conditions_on_one_value_rules_out_the_default() {
assert_missing(
&main_spec("rule r: x\n unless c then 5\n unless y is 1 and b then 6\n unless y is 2 and b then 7"),
&[("c", "true"), ("b", "true")],
&["y"],
);
}
const DOMAINS: &[(&str, &[&str])] = &[
("x", &["3"]),
("y", &["0", "2"]),
("z", &["4"]),
("a", &["true", "false"]),
("b", &["true", "false"]),
("c", &["true", "false"]),
];
fn choices<'a>(domains: &[(&'a str, &'a [&'a str])]) -> Vec<Vec<(&'a str, &'a str)>> {
domains
.iter()
.fold(vec![Vec::new()], |chosen, (name, values)| {
chosen
.iter()
.flat_map(|prefix| {
values.iter().map(move |value| {
let mut next = prefix.clone();
next.push((*name, *value));
next
})
})
.collect()
})
}
fn assert_exact(rules: &str) {
let engine = load(&main_spec(rules));
let used: Vec<(&str, &[&str])> = DOMAINS
.iter()
.copied()
.filter(|(name, _)| {
rules
.split(|c: char| !c.is_alphanumeric() && c != '_')
.any(|word| word == *name)
})
.collect();
let mut wrong = Vec::new();
for subset in 0..(1usize << used.len()) {
let given: Vec<_> = used
.iter()
.copied()
.enumerate()
.filter(|(index, _)| subset & (1 << index) != 0)
.map(|(_, domain)| domain)
.collect();
let open: Vec<_> = used
.iter()
.copied()
.filter(|(name, _)| !given.iter().any(|(other, _)| other == name))
.collect();
for inputs in choices(&given) {
let response = evaluate(&engine, "main", data(&inputs), None, false);
let mut needed: IndexMap<String, BTreeSet<String>> = IndexMap::new();
for (key, _) in &open {
let others: Vec<_> = open.iter().copied().filter(|(o, _)| o != key).collect();
for rest in choices(&others) {
let all: Vec<_> = inputs.iter().chain(&rest).copied().collect();
let completed = evaluate(&engine, "main", data(&all), None, false);
for (name, result) in &completed.results {
if !result.missing_data().is_empty() {
needed
.entry(name.clone())
.or_default()
.insert(key.to_string());
}
}
}
}
for (name, result) in &response.results {
if result.missing_data().is_empty() {
continue;
}
let listed: BTreeSet<String> = result.missing_data().iter().cloned().collect();
let needed = needed.get(name).cloned().unwrap_or_default();
if listed != needed {
wrong.push(format!(
"{name} given {inputs:?}: lists {listed:?}, needs {needed:?}"
));
}
}
}
}
assert!(
wrong.is_empty(),
"{} of the requests are wrong, the first: {}",
wrong.len(),
wrong[0]
);
}
#[test]
fn exact_for_one_unless() {
assert_exact("rule r: x\n unless b then z");
}
#[test]
fn exact_for_two_unless() {
assert_exact("rule r: x\n unless c then z\n unless b then 7");
}
#[test]
fn exact_for_four_unless() {
assert_exact(
"rule r: x\n unless y > 1 then 1\n unless a then z\n unless c then 3\n unless b then x",
);
}
#[test]
fn exact_for_nested_rules() {
assert_exact(
"rule q: x\n unless c then z\nrule r: q\n unless b then 7\nrule s: z\n unless a then r",
);
}
#[test]
fn exact_for_vetoes_in_branches() {
assert_exact("rule r: x\n unless c then veto \"closed\"\n unless b then z\n unless a then veto \"full\"");
}
#[test]
fn exact_for_connectives() {
assert_exact("rule r: x\n unless a and c then z\n unless b then 7");
}
#[test]
fn exact_for_a_disjunction() {
assert_exact("rule r: x\n unless a or y > 1 then 5\n unless b or c then z");
}
#[test]
fn exact_for_arithmetic_on_branches() {
assert_exact("rule q: x\n unless c then 5\n unless b then z\nrule r: q + x");
}