lemma-engine 0.9.0

A pure, declarative language for business rules.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
use lemma::DateTimeValue;
use lemma::{Engine, TypeSpecification};
use std::collections::HashMap;

#[test]
fn test_missing_uses_for_data_reference_fails() {
    let mut engine = Engine::new();

    let money_spec = r#"
spec money
data salary: number
"#;

    let test_spec = r#"
spec test
with salary: money.salary
rule total: salary
"#;

    engine
        .load([(
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("money.lemma"))),
            money_spec.to_string(),
        )])
        .unwrap();
    let err = engine
        .load([(lemma::SourceType::Volatile, test_spec.to_string())])
        .unwrap_err();

    let err_msg = err.errors[0].to_string();
    assert!(
        err_msg.contains("imported spec") || err_msg.contains("alias.field"),
        "local with without import path must be rejected at parse: {}",
        err_msg
    );
}

#[test]
fn test_type_system_with_imports_and_extensions() {
    let mut engine = Engine::new();

    let age_spec = r#"
spec age
data age: number
  -> minimum 0
  -> maximum 150
"#;

    let test_types_spec = r#"
spec test_types

uses age_spec: age
data age: age_spec.age

data adult_age: age
  -> minimum 21

data twenties: adult_age -> maximum 30

rule total: age + adult_age + twenties
"#;

    engine
        .load([(
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("age.lemma"))),
            age_spec.to_string(),
        )])
        .unwrap();
    engine
        .load([(
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "test_types.lemma",
            ))),
            test_types_spec.to_string(),
        )])
        .unwrap();
    let now = DateTimeValue::now();

    let mut data = HashMap::new();
    data.insert("age".to_string(), "25".to_string());
    data.insert("adult_age".to_string(), "30".to_string());
    data.insert("twenties".to_string(), "25".to_string());
    let response = engine
        .run(None, "test_types", Some(&now), data, None, false)
        .expect("Evaluation failed");

    assert_eq!(response.spec_name, "test_types");

    let total_rule = response
        .results
        .values()
        .find(|r| r.rule.name == "total")
        .expect("total rule not found");

    // 25 + 30 + 25 = 80
    assert_eq!(total_rule.display.clone().expect("display"), "80");
}

#[test]
fn test_import_literal_number_via_from_dependency_spec() {
    let mut engine = Engine::new();

    engine
        .load([(
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "workspace.lemma",
            ))),
            r#"
spec constants
data pi: 3.14

spec finance
uses constants
data pi: constants.pi
rule x: pi
"#
            .to_string(),
        )])
        .expect("loading specs with literal + from-import must succeed");

    let now = DateTimeValue::now();
    let mut data = HashMap::new();
    data.insert("pi".to_string(), "3.14".to_string());
    let response = engine
        .run(None, "finance", Some(&now), data, None, false)
        .expect("run finance");

    let rule_x = response.results.get("x").expect("rule x");
    assert_eq!(rule_x.display.clone().expect("display"), "3.14");
}

/// Regression test: measure type with `-> suggest` before `-> unit` must work.
/// Previously, constraints were applied in declaration order, so `default`
/// would fail to find the unit because it hadn't been registered yet.
#[test]
fn test_measure_type_default_before_unit_declarations() {
    let mut engine = Engine::new();

    engine
        .load([(
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "pricing.lemma",
            ))),
            r#"
        spec pricing
        data money: measure
          -> suggest 4 eur
          -> unit eur 1
          -> unit usd 0.84
        data price: money
        rule doubled: price * 2
    "#
            .to_string(),
        )])
        .expect("default before unit should be valid");
    let now = DateTimeValue::now();

    let show = engine.show(None, "pricing", Some(&now)).unwrap();
    let entry = show.data.get("price").expect("price data in show");
    assert!(
        entry.lemma_type.is_measure(),
        "price must be measure money type"
    );
    assert_eq!(entry.lemma_type.extends.parent_name(), Some("money"));
    match &entry.lemma_type.specifications {
        TypeSpecification::Measure { units, .. } => {
            let names: Vec<&str> = units.iter().map(|u| u.name.as_str()).collect();
            assert!(names.contains(&"eur") && names.contains(&"usd"));
        }
        other => panic!("expected Measure, got {:?}", other),
    }
    assert!(
        entry.suggestion.is_some() && entry.prefilled.is_none(),
        "typedef money default must surface on price as show suggestion"
    );
}

/// Verify that `-> suggest` after `-> unit` (the original order) still works.
#[test]
fn test_measure_type_default_after_unit_declarations() {
    let mut engine = Engine::new();

    engine
        .load([(
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "pricing.lemma",
            ))),
            r#"
        spec pricing
        data money: measure
          -> unit eur 1
          -> unit usd 0.84
          -> suggest 4 eur
        rule doubled: money * 2
    "#
            .to_string(),
        )])
        .expect("default after unit should be valid");
    let now = DateTimeValue::now();

    let show = engine.show(None, "pricing", Some(&now)).unwrap();
    let entry = show.data.get("money").expect("money data in show");
    assert!(
        entry.lemma_type.is_measure(),
        "money must be measure money type"
    );
    assert_eq!(entry.lemma_type.name(), "money");
    match &entry.lemma_type.specifications {
        TypeSpecification::Measure { units, .. } => {
            let names: Vec<&str> = units.iter().map(|u| u.name.as_str()).collect();
            assert!(names.contains(&"eur") && names.contains(&"usd"));
        }
        other => panic!("expected Measure, got {:?}", other),
    }
    assert!(
        entry.suggestion.is_some() && entry.prefilled.is_none(),
        "typedef money default must surface on price as show suggestion"
    );
}

#[test]
fn test_show_returns_data_in_definition_order() {
    let mut engine = Engine::new();

    engine
        .load([(
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "ordering.lemma",
            ))),
            r#"
        spec ordering
        data zebra: number
        data alpha: number
        data middle: number
        rule total: zebra + alpha + middle
    "#
            .to_string(),
        )])
        .unwrap();
    let now = DateTimeValue::now();

    let show = engine.show(None, "ordering", Some(&now)).unwrap();
    let data_names: Vec<&String> = show.data.keys().collect();
    assert_eq!(
        data_names,
        vec!["zebra", "alpha", "middle"],
        "Data should be in definition order, not alphabetical"
    );
}

#[test]
fn test_run_returns_data_in_definition_order() {
    let mut engine = Engine::new();

    engine
        .load([(
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "ordering.lemma",
            ))),
            r#"
        spec ordering
        data zebra: number
        data alpha: number
        data middle: number
        rule total: zebra + alpha + middle
    "#
            .to_string(),
        )])
        .unwrap();
    let now = DateTimeValue::now();

    let response = engine
        .run(
            None,
            "ordering",
            Some(&now),
            std::collections::HashMap::new(),
            Some(&["total".to_string()]),
            false,
        )
        .expect("run must succeed");
    let data_names = response
        .results
        .get("total")
        .expect("total rule")
        .missing_data
        .clone();
    assert_eq!(
        data_names,
        vec!["zebra", "alpha", "middle"],
        "scoped run should preserve definition order for rule missing_data"
    );
}

#[test]
fn test_show_splits_prefilled_literal_and_suggestion() {
    let mut engine = Engine::new();

    engine
        .load([(
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "defaults.lemma",
            ))),
            r#"
        spec defaults
        data quantity: number -> suggest 10
        data name: text
        data price: 99
        rule total: quantity * price
        rule label: name
    "#
            .to_string(),
        )])
        .unwrap();
    let now = DateTimeValue::now();

    let show = engine.show(None, "defaults", Some(&now)).unwrap();

    let quantity = show.data.get("quantity").expect("quantity should exist");
    assert!(
        quantity.suggestion.is_some() && quantity.prefilled.is_none(),
        "type-level default is a suggestion only"
    );

    let name = show.data.get("name").expect("name should exist");
    assert!(
        name.suggestion.is_none() && name.prefilled.is_none(),
        "type-only data without default has no prefilled value or suggestion"
    );

    let price = show.data.get("price").expect("price should exist");
    assert!(
        price.prefilled.is_some() && price.suggestion.is_none(),
        "explicit literal is prefilled, not a default suggestion"
    );
}

#[test]
fn test_show_measure_default_is_value() {
    let mut engine = Engine::new();

    engine
        .load([(
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "salary.lemma",
            ))),
            r#"
        spec salary
        data money: measure
          -> unit eur 1
          -> unit usd 0.84
          -> suggest 3000 eur
        data salary: money
        rule doubled: salary * 2
    "#
            .to_string(),
        )])
        .unwrap();
    let now = DateTimeValue::now();

    let show = engine.show(None, "salary", Some(&now)).unwrap();

    let salary = show.data.get("salary").expect("salary should exist");
    assert!(
        salary.suggestion.is_some() && salary.prefilled.is_none(),
        "measure typedef default must surface as show suggestion on salary"
    );
}

/// Default declared on an inner typedef must propagate through all extending
/// types and land on the data binding's default, without the intermediate
/// types redeclaring it.
#[test]
fn test_typedef_default_inherits_through_extension_chain() {
    let mut engine = Engine::new();
    engine
        .load([(
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("chain.lemma"))),
            r#"
            spec chain
            data money: measure
              -> unit eur 1
              -> suggest 4 eur
            data price: money
            data final_price: price
            rule doubled: final_price * 2
            "#
            .to_string(),
        )])
        .unwrap();
    let now = DateTimeValue::now();

    let show = engine.show(None, "chain", Some(&now)).unwrap();
    let final_price = show
        .data
        .get("final_price")
        .expect("final_price should exist");
    assert!(
        final_price.suggestion.is_some() && final_price.prefilled.is_none(),
        "typedef default declared on ancestor type must inherit as suggestion on leaf binding"
    );
}

#[test]
fn child_measure_cannot_change_inherited_unit_factor() {
    let mut engine = Engine::new();
    let err = engine
        .load([(
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("units.lemma"))),
            r#"
            spec money_type
            data money: measure
              -> unit eur 1.00
              -> unit usd 0.91
            data price: money
              -> unit usd 1.00
            "#
            .to_string(),
        )])
        .expect_err("child must not change inherited usd factor");
    let joined = err
        .iter()
        .map(|e| e.to_string())
        .collect::<Vec<_>>()
        .join("; ");
    assert!(
        joined.contains("usd")
            && (joined.contains("inherited") || joined.contains("cannot change")),
        "expected inherited unit factor rejection, got: {joined}"
    );
}

#[test]
fn child_measure_may_add_new_unit() {
    let mut engine = Engine::new();
    engine
        .load([(
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("units.lemma"))),
            r#"
            spec money_type
            data money: measure
              -> unit eur 1.00
            data price: money
              -> unit usd 0.91
            data amount: 100 usd
            rule r: amount as eur
            "#
            .to_string(),
        )])
        .expect("child may add new unit");
    let now = DateTimeValue::now();
    let response = engine
        .run(None, "money_type", Some(&now), HashMap::new(), None, false)
        .expect("run");
    let display = response
        .results
        .get("r")
        .and_then(|r| r.display.clone())
        .expect("display");
    assert!(
        display.contains("eur"),
        "expected eur conversion display, got {display}"
    );
}