use indexmap::IndexMap;
use lemma::{DateTimeValue, Engine, EvaluateDataValue};
use std::str::FromStr;
fn load(source: &str) -> Engine {
let mut engine = Engine::new();
engine
.load([(lemma::SourceType::Volatile, source.to_string())])
.expect("load");
engine
}
fn load_err(source: &str) -> String {
let mut engine = Engine::new();
let err = engine
.load([(lemma::SourceType::Volatile, source.to_string())])
.expect_err("expected planning error");
err.iter()
.map(|e| e.to_string())
.collect::<Vec<_>>()
.join("; ")
}
fn evaluate(
engine: &Engine,
spec: &str,
effective: &str,
data: &[(&str, &str)],
) -> lemma::Response {
let at = DateTimeValue::from_str(effective).expect("effective");
let map: IndexMap<String, EvaluateDataValue> = data
.iter()
.map(|(key, value)| ((*key).to_string(), (*value).into()))
.collect();
engine
.evaluate(None, spec, Some(&at), map, None, false)
.expect("evaluate")
}
fn rule_result(response: &lemma::Response, rule: &str) -> String {
let entry = response.results.get(rule).expect(rule);
if entry.vetoed {
return format!("veto:{}", entry.veto_reason.as_deref().unwrap_or_default());
}
entry.result().unwrap_or_default().to_string()
}
#[test]
fn parse_effective_on_uses() {
let source = r#"
spec alpha2 2020-01-01
data code: text
-> option "NL"
rule name: "Netherlands"
spec intake
data birth_date: date
data birth_country: text
uses iso: alpha2
-> effective birth_date
-> with code: birth_country
rule birth_country_name: iso.name
"#;
let engine = load(source);
let response = evaluate(
&engine,
"intake",
"2024-01-01",
&[("birth_date", "2021-06-01"), ("birth_country", "NL")],
);
assert_eq!(rule_result(&response, "birth_country_name"), "Netherlands");
}
#[test]
fn dynamic_effective_selects_version_by_pin_date() {
let source = r#"
spec alpha2 2020-01-01
data code: text
-> option "NL"
-> option "CS"
rule name:
veto "unknown"
unless code is "NL" then "Netherlands"
unless code is "CS" then "Serbia and Montenegro"
spec alpha2 2023-01-01
data code: text
-> option "NL"
-> option "RS"
rule name:
veto "unknown"
unless code is "NL" then "Netherlands"
unless code is "RS" then "Serbia"
spec intake
data birth_date: date
data birth_country: text
uses iso: alpha2
-> effective birth_date
-> with code: birth_country
rule birth_country_name: iso.name
"#;
let engine = load(source);
let early = evaluate(
&engine,
"intake",
"2024-06-01",
&[("birth_date", "2021-06-01"), ("birth_country", "CS")],
);
assert_eq!(
rule_result(&early, "birth_country_name"),
"Serbia and Montenegro"
);
let late = evaluate(
&engine,
"intake",
"2024-06-01",
&[("birth_date", "2023-06-01"), ("birth_country", "RS")],
);
assert_eq!(rule_result(&late, "birth_country_name"), "Serbia");
let wrong_code = evaluate(
&engine,
"intake",
"2024-06-01",
&[("birth_date", "2023-06-01"), ("birth_country", "CS")],
);
assert!(
rule_result(&wrong_code, "birth_country_name").starts_with("veto:"),
"CS must veto against the 2023 options: {}",
rule_result(&wrong_code, "birth_country_name")
);
let before = evaluate(
&engine,
"intake",
"2024-06-01",
&[("birth_date", "2019-01-01"), ("birth_country", "NL")],
);
assert!(
rule_result(&before, "birth_country_name").starts_with("veto:"),
"pin before first version must veto: {}",
rule_result(&before, "birth_country_name")
);
}
#[test]
fn reject_literal_pin_with_effective() {
let err = load_err(
r#"
spec alpha2 2020-01-01
data code: text
spec intake
data birth_date: date
uses iso: alpha2 2020-01-01
-> effective birth_date
"#,
);
assert!(
err.contains("Cannot combine") || err.contains("effective"),
"{err}"
);
}
#[test]
fn reject_two_effective_commands() {
let err = load_err(
r#"
spec alpha2 2020-01-01
data code: text
spec intake
data birth_date: date
data other_date: date
uses iso: alpha2
-> effective birth_date
-> effective other_date
"#,
);
assert!(
err.contains("at most one") || err.contains("effective"),
"{err}"
);
}
#[test]
fn reject_effective_as_data_name() {
let err = load_err(
r#"
spec intake
data effective: date
"#,
);
assert!(
err.contains("reserved") || err.contains("effective"),
"{err}"
);
}
#[test]
fn dynamic_effective_consumer_not_split_by_dependency_versions() {
let source = r#"
spec alpha2 2020-01-01
data code: text
-> option "NL"
-> option "CS"
rule name:
veto "unknown"
unless code is "NL" then "Netherlands"
unless code is "CS" then "Serbia and Montenegro"
spec alpha2 2023-01-01
data code: text
-> option "NL"
-> option "RS"
rule name:
veto "unknown"
unless code is "NL" then "Netherlands"
unless code is "RS" then "Serbia"
spec intake
data birth_date: date
data birth_country: text
uses iso: alpha2
-> effective birth_date
-> with code: birth_country
rule birth_country_name: iso.name
"#;
let engine = load(source);
let data = [("birth_date", "2021-06-01"), ("birth_country", "CS")];
let before_boundary = evaluate(&engine, "intake", "2021-06-01", &data);
let after_boundary = evaluate(&engine, "intake", "2024-06-01", &data);
assert_eq!(
rule_result(&before_boundary, "birth_country_name"),
"Serbia and Montenegro"
);
assert_eq!(
rule_result(&after_boundary, "birth_country_name"),
"Serbia and Montenegro"
);
}
#[test]
fn option_only_drift_allowed_for_dynamic_effective() {
let source = r#"
spec alpha2 2020-01-01
data code: text
-> option "NL"
-> help "country"
rule name: "old"
spec alpha2 2023-01-01
data code: text
-> option "NL"
-> option "RS"
-> help "country"
rule name: "new"
spec intake
data birth_date: date
uses iso: alpha2
-> effective birth_date
rule label: iso.name
"#;
load(source);
}
#[test]
fn cycle_through_effective_pin_is_error() {
let err = load_err(
r#"
spec alpha2 2020-01-01
data code: text
data as_of: date
spec intake
data fallback: date
uses iso: alpha2
-> effective chosen
-> with code: "NL"
-> with as_of: fallback
rule chosen: iso.as_of
"#,
);
assert!(
err.contains("cycle") || err.contains("circular") || err.contains("Circular"),
"{err}"
);
}
#[test]
fn binding_slot_missing_on_one_version_is_error() {
let err = load_err(
r#"
spec alpha2 2020-01-01
data code: text
data label: text
spec alpha2 2023-01-01
data code: text
spec intake
data birth_date: date
uses iso: alpha2
-> effective birth_date
-> with label: "x"
"#,
);
assert!(
err.contains("label") || err.contains("no data field") || err.contains("2023"),
"{err}"
);
}
#[test]
fn adding_dependency_version_rebuilds_dynamic_effective_consumer() {
let mut engine = Engine::new();
let dep = lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
"alpha2.lemma",
)));
let consumer = lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
"intake.lemma",
)));
engine
.load([
(
dep.clone(),
r#"
spec alpha2 2020-01-01
data code: text
-> option "NL"
rule name: "Netherlands"
"#
.to_string(),
),
(
consumer.clone(),
r#"
spec intake
data birth_date: date
data birth_country: text
uses iso: alpha2
-> effective birth_date
-> with code: birth_country
rule birth_country_name: iso.name
"#
.to_string(),
),
])
.expect("load");
engine
.update(
None,
r#"
spec alpha2 2020-01-01
data code: text
-> option "NL"
-> option "CS"
rule name:
veto "unknown"
unless code is "NL" then "Netherlands"
unless code is "CS" then "Serbia and Montenegro"
spec alpha2 2023-01-01
data code: text
-> option "NL"
-> option "RS"
rule name:
veto "unknown"
unless code is "NL" then "Netherlands"
unless code is "RS" then "Serbia"
"#
.to_string(),
dep,
)
.expect("new dependency version must rebuild the dynamic-effective consumer");
let late = evaluate(
&engine,
"intake",
"2024-06-01",
&[("birth_date", "2023-06-01"), ("birth_country", "RS")],
);
assert_eq!(rule_result(&late, "birth_country_name"), "Serbia");
}
#[test]
fn help_drift_rejected_for_dynamic_effective() {
let err = load_err(
r#"
spec alpha2 2020-01-01
data code: text
-> help "a"
rule name: "old"
spec alpha2 2023-01-01
data code: text
-> help "b"
rule name: "new"
spec intake
data birth_date: date
uses iso: alpha2
-> effective birth_date
rule label: iso.code
"#,
);
assert!(
err.contains("without pinning") || err.contains("changed") || err.contains("help"),
"{err}"
);
}
#[test]
fn dynamic_effective_type_path_unions_option_values() {
let source = r#"
spec alpha2 2020-01-01
data code: text
-> option "NL"
-> option "CS"
rule name:
veto "unknown"
unless code is "NL" then "Netherlands"
unless code is "CS" then "Serbia and Montenegro"
spec alpha2 2023-01-01
data code: text
-> option "NL"
-> option "RS"
rule name:
veto "unknown"
unless code is "NL" then "Netherlands"
unless code is "RS" then "Serbia"
spec intake
data birth_date: date
uses iso: alpha2
-> effective birth_date
-> with code: birth_country
data birth_country: iso.code
rule birth_country_name: iso.name
"#;
let engine = load(source);
let missing = evaluate(
&engine,
"intake",
"2024-06-01",
&[("birth_date", "2021-06-01")],
);
let offered = missing
.results
.get("birth_country_name")
.expect("birth_country_name")
.missing_data_options()
.get("birth_country")
.expect("birth_country options");
let rendered: Vec<String> = offered.iter().map(|value| format!("{value:?}")).collect();
assert!(
rendered.iter().any(|value| value.contains("CS"))
&& rendered.iter().any(|value| value.contains("RS"))
&& rendered.iter().any(|value| value.contains("NL")),
"type path must expose the sorted option union, got {rendered:?}"
);
let early = evaluate(
&engine,
"intake",
"2024-06-01",
&[("birth_date", "2021-06-01"), ("birth_country", "CS")],
);
assert_eq!(
rule_result(&early, "birth_country_name"),
"Serbia and Montenegro"
);
let late = evaluate(
&engine,
"intake",
"2024-06-01",
&[("birth_date", "2023-06-01"), ("birth_country", "RS")],
);
assert_eq!(rule_result(&late, "birth_country_name"), "Serbia");
let wrong_for_selected = evaluate(
&engine,
"intake",
"2024-06-01",
&[("birth_date", "2023-06-01"), ("birth_country", "CS")],
);
assert!(
rule_result(&wrong_for_selected, "birth_country_name").starts_with("veto:"),
"binding into the selected body must enforce that body's options: {}",
rule_result(&wrong_for_selected, "birth_country_name")
);
}
#[test]
fn dynamic_effective_type_path_rejects_divergent_options_rule() {
let err = load_err(
r#"
spec alpha2 2020-01-01
data codes: text list
rule offered:
codes
data code: text
-> options offered
spec alpha2 2023-01-01
data codes: text list
rule other_offered:
codes
data code: text
-> options other_offered
spec intake
data birth_date: date
uses iso: alpha2
-> effective birth_date
data birth_country: iso.code
"#,
);
assert!(
err.contains("options") || err.contains("changed") || err.contains("rule"),
"{err}"
);
}
const TARIEF_FIELDS_DIFFER: &str = r#"
spec tarief 2020-01-01
data btw: ratio
rule bedrag:
100 * btw
spec tarief 2023-01-01
data btw_laag: ratio
rule bedrag:
100 * btw_laag
spec bon
data peildatum: date
uses t: tarief
-> effective peildatum
rule bedrag:
t.bedrag
"#;
#[test]
fn show_lists_data_of_every_selectable_body() {
let engine = load(TARIEF_FIELDS_DIFFER);
let at = DateTimeValue::from_str("2024-06-01").expect("effective");
let show = engine.show(None, "bon", Some(&at)).expect("show");
for input in ["peildatum", "t.btw", "t.btw_laag"] {
assert!(
show.data.contains_key(input),
"Show must list {input}: {:?}",
show.data.keys().collect::<Vec<_>>()
);
}
}
#[test]
fn dotted_data_reaches_the_selected_body() {
let engine = load(TARIEF_FIELDS_DIFFER);
let early = evaluate(
&engine,
"bon",
"2024-06-01",
&[
("peildatum", "2021-01-01"),
("t.btw", "21%"),
("t.btw_laag", "9%"),
],
);
assert_eq!(rule_result(&early, "bedrag"), "21");
let late = evaluate(
&engine,
"bon",
"2024-06-01",
&[
("peildatum", "2024-01-01"),
("t.btw", "21%"),
("t.btw_laag", "9%"),
],
);
assert_eq!(rule_result(&late, "bedrag"), "9");
let missing = evaluate(&engine, "bon", "2024-06-01", &[("peildatum", "2024-01-01")]);
let bedrag = missing.results.get("bedrag").expect("bedrag");
assert_eq!(bedrag.missing_data(), ["t.btw_laag".to_string()]);
}
const NESTED_PIN: &str = r#"
spec tarief 2020-01-01
data btw: ratio
rule bedrag:
100 * btw
spec tarief 2023-01-01
data btw: ratio
rule bedrag:
200 * btw
spec regel
data peildatum: date
uses t: tarief
-> effective peildatum
rule bedrag:
t.bedrag
spec bon
uses vroeg: regel
-> with peildatum: 2021-01-01
uses laat: regel
-> with peildatum: 2024-01-01
uses open: regel
rule vroeg_bedrag:
vroeg.bedrag
rule laat_bedrag:
laat.bedrag
rule open_bedrag:
open.bedrag
"#;
#[test]
fn nested_pin_selects_per_instance() {
let engine = load(NESTED_PIN);
let response = evaluate(
&engine,
"bon",
"2024-06-01",
&[
("vroeg.t.btw", "10%"),
("laat.t.btw", "10%"),
("open.t.btw", "10%"),
("open.peildatum", "2024-01-01"),
],
);
assert_eq!(rule_result(&response, "vroeg_bedrag"), "10");
assert_eq!(rule_result(&response, "laat_bedrag"), "20");
assert_eq!(rule_result(&response, "open_bedrag"), "20");
}
#[test]
fn nested_unset_pin_is_missing_data() {
let engine = load(NESTED_PIN);
let response = evaluate(
&engine,
"bon",
"2024-06-01",
&[("vroeg.t.btw", "10%"), ("laat.t.btw", "10%")],
);
let open = response.results.get("open_bedrag").expect("open_bedrag");
assert!(
open.vetoed && open.is_missing_data(),
"got {:?}",
open.veto_reason
);
assert_eq!(open.missing_data(), ["open.peildatum".to_string()]);
}
#[test]
fn show_lists_nested_pin_and_every_body() {
let engine = load(
&TARIEF_FIELDS_DIFFER.replace(
"spec bon\n\ndata peildatum: date\n\nuses t: tarief\n -> effective peildatum\n\nrule bedrag:\n t.bedrag\n",
"spec regel\n\ndata peildatum: date\n\nuses t: tarief\n -> effective peildatum\n\nrule bedrag:\n t.bedrag\n\n\nspec bon\n\nuses r: regel\n\nrule bedrag:\n r.bedrag\n",
),
);
let at = DateTimeValue::from_str("2024-06-01").expect("effective");
let show = engine.show(None, "bon", Some(&at)).expect("show");
for input in ["r.peildatum", "r.t.btw", "r.t.btw_laag"] {
assert!(
show.data.contains_key(input),
"Show must list {input}: {:?}",
show.data.keys().collect::<Vec<_>>()
);
}
}
#[test]
fn list_data_reaches_the_selected_body() {
let engine = load(
r#"
spec regel
data bedrag: number
spec tarief 2020-01-01
uses regel
data regels: regel list
rule totaal:
regels -> sum regels.bedrag
spec tarief 2023-01-01
uses regel
data regels: regel list
rule totaal:
regels -> sum regels.bedrag
rule aantal:
regels -> count
spec bon
data peildatum: date
uses t: tarief
-> effective peildatum
rule totaal:
t.totaal
"#,
);
let at = DateTimeValue::from_str("2024-06-01").expect("effective");
for peildatum in ["2021-01-01", "2024-01-01"] {
let row = |bedrag: &str| {
let mut fields = IndexMap::new();
fields.insert("bedrag".to_string(), EvaluateDataValue::string(bedrag));
EvaluateDataValue::Map(fields)
};
let mut data: IndexMap<String, EvaluateDataValue> = IndexMap::new();
data.insert(
"peildatum".to_string(),
EvaluateDataValue::string(peildatum),
);
data.insert(
"t.regels".to_string(),
EvaluateDataValue::List(vec![row("3"), row("4")]),
);
let response = engine
.evaluate(None, "bon", Some(&at), data, None, false)
.expect("evaluate");
assert_eq!(
rule_result(&response, "totaal"),
"7",
"peildatum {peildatum}"
);
}
}
const NESTED_OPTIONS: &str = r#"
spec tarief 2020-01-01
data code: text
-> option "laag"
-> option "hoog"
rule bedrag:
1
unless code is "hoog" then 2
spec tarief 2023-01-01
data code: text
-> option "laag"
-> option "hoog"
-> option "nul"
rule bedrag:
10
unless code is "hoog" then 20
spec regel
data peildatum: date
uses t: tarief
-> effective peildatum
rule bedrag:
t.bedrag
"#;
#[test]
fn missing_field_under_a_nested_effective_slot_offers_its_options() {
let engine = load(&format!(
"{NESTED_OPTIONS}\n\nspec bon 2026-01-01\n\nuses open: regel\n -> with peildatum: 2024-01-01\n\nrule bedrag:\n open.bedrag\n"
));
let response = evaluate(&engine, "bon", "2026-06-01", &[]);
let offered: Vec<String> = response
.results
.get("bedrag")
.expect("bedrag")
.missing_data_options()
.get("open.t.code")
.expect("open.t.code options")
.iter()
.map(|value| format!("{value:?}"))
.collect();
assert_eq!(
offered.len(),
3,
"the 2023 body's three options, got {offered:?}"
);
assert!(
offered.iter().any(|value| value.contains("nul")),
"{offered:?}"
);
}
#[test]
fn a_global_with_a_dynamic_pin_is_a_planning_error() {
let source = NESTED_OPTIONS.replace("uses t: tarief", "uses global t: tarief");
let message = load_err(&source);
assert!(
message.contains("`uses global` takes no `-> effective`"),
"got: {message}"
);
}
#[test]
fn explain_with_a_rule_pin_missing_its_data_reports_the_data() {
let source = r#"
spec rate 2020-01-01
data base: number
rule amount: base * 2
spec rate 2023-01-01
data base: number
rule amount: base * 3
spec holder
data when: date
rule chosen: when
uses by_rule: rate
-> effective chosen
-> with base: 7
rule from_rule: by_rule.amount
"#;
let engine = load(source);
let at = DateTimeValue::from_str("2024-06-01").expect("effective");
let response = engine
.evaluate(None, "holder", Some(&at), IndexMap::new(), None, true)
.expect("evaluate");
let result = &response.results["from_rule"];
assert!(result.vetoed, "from_rule must veto without `when`");
assert_eq!(result.missing_data(), ["when"]);
}
const PIN_WITH_OPTIONS_RULE: &str = r#"
spec rate 2020-01-01
data base: number
rule amount: base * 2
spec rate 2023-01-01
data base: number
rule amount: base * 3
spec holder
data dates: date list
-> with 2020-01-01
-> with 2023-01-01
rule allowed: dates
data when: date
-> options allowed
uses r: rate
-> effective when
-> with base: 5
rule checked: r.amount
spec outer
uses h: holder
-> with when: 2022-06-01
rule through: h.checked
"#;
#[test]
fn effective_pin_outside_its_options_rule_vetoes() {
let engine = load(PIN_WITH_OPTIONS_RULE);
let outside = evaluate(&engine, "holder", "2024-06-01", &[("when", "2022-06-01")]);
assert_eq!(
rule_result(&outside, "checked"),
"veto:'2022-06-01' is not one of the allowed options: 2020-01-01, 2023-01-01."
);
let listed = evaluate(&engine, "holder", "2024-06-01", &[("when", "2023-01-01")]);
assert_eq!(rule_result(&listed, "checked"), "15");
}
#[test]
fn nested_effective_pin_outside_its_options_rule_vetoes() {
let engine = load(PIN_WITH_OPTIONS_RULE);
let response = evaluate(&engine, "outer", "2024-06-01", &[]);
assert_eq!(
rule_result(&response, "through"),
"veto:'2022-06-01' is not one of the allowed options: 2020-01-01, 2023-01-01."
);
}
#[test]
fn a_unit_named_only_in_a_literal_that_changes_between_versions_is_error() {
let err = load_err(
r#"
spec fx
data money: measure
-> unit eur: 1
-> unit usd: 0.96
spec fx 2026-01-01
data money: measure
-> unit eur: 2
-> unit usd: 0.96
spec invoice
data booking_date: date
uses fx
-> effective booking_date
rule fee_in_usd: 5 eur as usd
"#,
);
assert!(err.contains("money") && err.contains("changed"), "{err}");
}
#[test]
fn a_unit_named_only_in_a_literal_missing_on_one_version_is_error() {
let err = load_err(
r#"
spec fx
data money: measure
-> unit eur: 1
-> unit usd: 0.96
spec fx 2026-01-01
data money: measure
-> unit usd: 0.96
spec invoice
data booking_date: date
uses fx
-> effective booking_date
rule fee: 5 eur
"#,
);
assert!(err.contains("unit 'eur'"), "{err}");
}
#[test]
fn a_unit_named_only_in_a_literal_that_changes_under_an_unpinned_uses_is_error() {
let err = load_err(
r#"
spec fx
data money: measure
-> unit eur: 1
-> unit usd: 0.96
spec fx 2026-01-01
data money: measure
-> unit eur: 2
-> unit usd: 0.96
spec invoice
uses fx
rule fee_in_usd: 5 eur as usd
"#,
);
assert!(err.contains("money") && err.contains("changed"), "{err}");
}
#[test]
fn a_unit_named_only_in_a_literal_that_every_version_declares_alike_loads() {
let engine = load(
r#"
spec fx
data money: measure
-> unit eur: 1
-> unit usd: 0.96
rule rate: 1
spec fx 2026-01-01
data money: measure
-> unit eur: 1
-> unit usd: 0.96
rule rate: 2
spec invoice
data booking_date: date
uses fx
-> effective booking_date
rule fee_in_usd: 5 eur as usd
"#,
);
let response = evaluate(
&engine,
"invoice",
"2026-07-01",
&[("booking_date", "2025-03-01")],
);
assert!(
rule_result(&response, "fee_in_usd").starts_with("5.208333"),
"{}",
rule_result(&response, "fee_in_usd")
);
}
#[test]
fn a_unit_no_version_declares_is_not_read_from_the_versions() {
let engine = load(
r#"
spec fx
data money: measure
-> unit eur: 1
spec fx 2026-01-01
data money: measure
-> unit eur: 2
spec invoice
data booking_date: date
data mass: measure
-> unit kg: 1
uses fx
-> effective booking_date
rule weight: 5 kg
"#,
);
let response = evaluate(
&engine,
"invoice",
"2026-07-01",
&[("booking_date", "2025-03-01")],
);
assert_eq!(rule_result(&response, "weight"), "5 kg");
}