lemma-engine 0.8.13

A language that means business.
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
//! Integration test for coffee_order example
//!
//! Tests data imports, inline type declarations with constraints, and complex rule chains

use lemma::parsing::ast::DateTimeValue;
use lemma::Engine;
use rust_decimal::Decimal;
use std::collections::HashMap;
use std::str::FromStr;

fn load_coffee_order() -> Engine {
    let mut engine = Engine::new();

    // Load the examples spec first (contains money and priority types)
    let examples = r#"
spec examples

data money: scale
  -> decimals 2
  -> unit eur 1.00
  -> unit gbp 1.17
  -> minimum 0 eur

data priority: text
  -> option "low"
  -> option "medium"
  -> option "high"
"#;

    let coffee_order = r#"
spec coffee_order

data coffee: text
  -> option "espresso"
  -> option "latte"
  -> option "cappuccino"
  -> option "mocha"

data size: text
  -> option "small"
  -> option "medium"
  -> option "large"
  -> option "extra large"

data price           : money from examples
data priority        : priority from examples
data number_of_cups  : number -> maximum 10
data has_loyalty_card: boolean

rule ordered_priority: veto "Unknown priority"
  unless priority is "low"    then 1
  unless priority is "medium" then 2
  unless priority is "high"   then 3

rule base_price: veto "Unknown type of coffee"
  unless coffee is "espresso"   then 2.50 eur
  unless coffee is "latte"      then 3.50 eur
  unless coffee is "cappuccino" then 3.50 eur
  unless coffee is "mocha"      then 4.00 eur

rule size_multiplier: veto "Unknown size of coffee"
  unless size is "small"  then 0.80
  unless size is "medium" then 1.00
  unless size is "large"  then 1.20

rule price_per_cup: base_price * size_multiplier

rule subtotal: price_per_cup * number_of_cups

rule loyalty_discount: 0.0
  unless has_loyalty_card then 0.10

rule discount_amount: subtotal * loyalty_discount

rule total: subtotal - discount_amount
"#;

    engine
        .load(
            examples,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "examples.lemma",
            ))),
        )
        .expect("Failed to parse examples");
    engine
        .load(
            coffee_order,
            lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
                "coffee_order.lemma",
            ))),
        )
        .expect("Failed to parse coffee_order");

    engine
}

#[test]
fn test_coffee_order_espresso_small_no_loyalty() {
    let engine = load_coffee_order();
    let now = DateTimeValue::now();

    let data_values = HashMap::from([
        ("coffee".to_string(), "espresso".to_string()),
        ("size".to_string(), "small".to_string()),
        ("number_of_cups".to_string(), "2".to_string()),
        ("has_loyalty_card".to_string(), "false".to_string()),
    ]);

    let response = engine
        .run(None, "coffee_order", Some(&now), data_values, false)
        .expect("Evaluation failed");

    // Check base_price: espresso = 2.50 usd
    let base_price = response
        .results
        .values()
        .find(|r| r.rule.name == "base_price")
        .expect("base_price rule not found");

    let base_price_value = base_price
        .result
        .value()
        .expect("base_price should have value");
    // base_price should be Scale with unit "eur"
    match &base_price_value.value {
        lemma::ValueKind::Scale(n, unit) => {
            assert_eq!(
                unit.as_str(),
                "eur",
                "base_price should have unit 'eur', got: {:?}",
                unit
            );
            // base_price preserves the numeric value as written for the unit.
            assert_eq!(
                *n,
                Decimal::from_str("2.50").unwrap(),
                "base_price should be exactly 2.50 (2.50 eur), got: {}",
                n
            );
        }
        _ => panic!(
            "base_price should be Scale type, got: {:?}",
            base_price_value.value
        ),
    }

    // Check size_multiplier: small = 0.80
    let size_multiplier = response
        .results
        .values()
        .find(|r| r.rule.name == "size_multiplier")
        .expect("size_multiplier rule not found");

    let multiplier_value = size_multiplier
        .result
        .value()
        .expect("size_multiplier should have value");
    // size_multiplier should be Number (no unit)
    match &multiplier_value.value {
        lemma::ValueKind::Number(n) => {
            assert_eq!(
                *n,
                Decimal::from_str("0.80").unwrap(),
                "size_multiplier should be 0.80, got: {}",
                n
            );
        }
        _ => panic!(
            "size_multiplier should be Number type, got: {:?}",
            multiplier_value.value
        ),
    }

    // Check price_per_cup = base_price * size_multiplier
    let price_per_cup = response
        .results
        .values()
        .find(|r| r.rule.name == "price_per_cup")
        .expect("price_per_cup rule not found");

    let cup_price = price_per_cup
        .result
        .value()
        .expect("price_per_cup should have value");
    // price_per_cup should be Scale with unit "eur" (inherited from base_price)
    match &cup_price.value {
        lemma::ValueKind::Scale(n, unit) => {
            assert_eq!(
                unit.as_str(),
                "eur",
                "price_per_cup should have unit 'eur', got: {:?}",
                unit
            );
            // base_price = 2.50, size_multiplier = 0.80
            // price_per_cup = 2.50 * 0.80 = 2.00
            assert_eq!(
                *n,
                Decimal::from_str("2.00").unwrap(),
                "price_per_cup should be exactly 2.00 (2.50 * 0.80), got: {}",
                n
            );
        }
        _ => panic!(
            "price_per_cup should be Scale type, got: {:?}",
            cup_price.value
        ),
    }

    // Check subtotal = price_per_cup * 2 cups
    let subtotal = response
        .results
        .values()
        .find(|r| r.rule.name == "subtotal")
        .expect("subtotal rule not found");

    let subtotal_value = subtotal.result.value().expect("subtotal should have value");
    // subtotal should be Scale with unit "eur" (inherited from price_per_cup)
    let subtotal_num = match &subtotal_value.value {
        lemma::ValueKind::Scale(n, unit) => {
            assert_eq!(
                unit.as_str(),
                "eur",
                "subtotal should have unit 'eur', got: {:?}",
                unit
            );
            *n
        }
        _ => panic!(
            "subtotal should be Scale type, got: {:?}",
            subtotal_value.value
        ),
    };
    // price_per_cup = 2.00, number_of_cups = 2
    // subtotal = 2.00 * 2 = 4.00
    assert_eq!(
        subtotal_num,
        Decimal::from_str("4.00").unwrap(),
        "subtotal should be exactly 4.00 (2.00 * 2), got: {}",
        subtotal_num
    );

    // Check loyalty_discount: false = 0.0
    let loyalty_discount = response
        .results
        .values()
        .find(|r| r.rule.name == "loyalty_discount")
        .expect("loyalty_discount rule not found");

    let discount = loyalty_discount
        .result
        .value()
        .expect("loyalty_discount should have value");
    // loyalty_discount: false = 0.0 (should be Number, not Ratio when 0.0)
    match &discount.value {
        lemma::ValueKind::Number(n) => {
            assert_eq!(
                *n,
                Decimal::from_str("0.00").unwrap(),
                "loyalty_discount should be 0.00, got: {}",
                n
            );
        }
        _ => panic!(
            "loyalty_discount should be Number type when 0.0, got: {:?}",
            discount.value
        ),
    }

    // Check total = subtotal - discount_amount (should equal subtotal when no discount)
    let total = response
        .results
        .values()
        .find(|r| r.rule.name == "total")
        .expect("total rule not found");

    let total_value = total.result.value().expect("total should have value");
    // total should be Scale with unit "eur" (inherited from subtotal)
    let total_num = match &total_value.value {
        lemma::ValueKind::Scale(n, unit) => {
            assert_eq!(
                unit.as_str(),
                "eur",
                "total should have unit 'eur', got: {:?}",
                unit
            );
            *n
        }
        _ => panic!("total should be Scale type, got: {:?}", total_value.value),
    };
    // Total should equal subtotal when discount is 0
    assert!(
        (total_num - subtotal_num).abs() < Decimal::from_str("0.01").unwrap(),
        "total should equal subtotal when discount is 0, got total: {}, subtotal: {}",
        total_num,
        subtotal_num
    );
}

#[test]
fn test_coffee_order_latte_large_with_loyalty() {
    let engine = load_coffee_order();
    let now = DateTimeValue::now();

    let data_values = HashMap::from([
        ("coffee".to_string(), "latte".to_string()),
        ("size".to_string(), "large".to_string()),
        ("number_of_cups".to_string(), "3".to_string()),
        ("has_loyalty_card".to_string(), "true".to_string()),
    ]);

    let response = engine
        .run(None, "coffee_order", Some(&now), data_values, false)
        .expect("Evaluation failed");

    // Check base_price: latte = 3.50 usd
    let base_price = response
        .results
        .values()
        .find(|r| r.rule.name == "base_price")
        .expect("base_price rule not found");

    let base_price_value = base_price
        .result
        .value()
        .expect("base_price should have value");
    // base_price should be Scale with unit "eur"
    match &base_price_value.value {
        lemma::ValueKind::Scale(n, unit) => {
            assert_eq!(
                unit.as_str(),
                "eur",
                "base_price should have unit 'eur', got: {:?}",
                unit
            );
            // base_price preserves the numeric value as written for the unit.
            assert_eq!(
                *n,
                Decimal::from_str("3.50").unwrap(),
                "base_price should be exactly 3.50 (3.50 eur), got: {}",
                n
            );
        }
        _ => panic!(
            "base_price should be Scale type, got: {:?}",
            base_price_value.value
        ),
    }

    // Check size_multiplier: large = 1.20
    let size_multiplier = response
        .results
        .values()
        .find(|r| r.rule.name == "size_multiplier")
        .expect("size_multiplier rule not found");

    let multiplier_value = size_multiplier
        .result
        .value()
        .expect("size_multiplier should have value");
    // size_multiplier should be Number (no unit)
    match &multiplier_value.value {
        lemma::ValueKind::Number(n) => {
            assert_eq!(
                *n,
                Decimal::from_str("1.20").unwrap(),
                "size_multiplier should be 1.20, got: {}",
                n
            );
        }
        _ => panic!(
            "size_multiplier should be Number type, got: {:?}",
            multiplier_value.value
        ),
    }

    // Check loyalty_discount: true = 0.10
    // Note: 0.10 is written as a number literal, not "10%", so it's a Number, not a Ratio
    let loyalty_discount = response
        .results
        .values()
        .find(|r| r.rule.name == "loyalty_discount")
        .expect("loyalty_discount rule not found");

    let discount = loyalty_discount
        .result
        .value()
        .expect("loyalty_discount should have value");
    // loyalty_discount should be Number (since 0.10 is written as number, not percentage)
    match &discount.value {
        lemma::ValueKind::Number(n) => {
            assert_eq!(
                *n,
                Decimal::from_str("0.10").unwrap(),
                "loyalty_discount should be exactly 0.10, got: {}",
                n
            );
        }
        _ => panic!(
            "loyalty_discount should be Number type, got: {:?}",
            discount.value
        ),
    }

    // Check total should be less than subtotal (due to discount)
    let subtotal = response
        .results
        .values()
        .find(|r| r.rule.name == "subtotal")
        .expect("subtotal rule not found");

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

    let subtotal_value = subtotal.result.value().expect("subtotal should have value");
    let total_value = total.result.value().expect("total should have value");

    // subtotal should be Scale with unit "eur" (inherited from price_per_cup)
    let subtotal_num = match &subtotal_value.value {
        lemma::ValueKind::Scale(n, unit) => {
            assert_eq!(
                unit.as_str(),
                "eur",
                "subtotal should have unit 'eur', got: {:?}",
                unit
            );
            *n
        }
        _ => panic!(
            "subtotal should be Scale type, got: {:?}",
            subtotal_value.value
        ),
    };
    // price_per_cup = 3.50 * 1.20 = 4.20, number_of_cups = 3
    // subtotal = 4.20 * 3 = 12.60
    assert_eq!(
        subtotal_num,
        Decimal::from_str("12.60").unwrap(),
        "subtotal should be exactly 12.60 (4.20 * 3), got: {}",
        subtotal_num
    );

    // total should be Scale with unit "eur" (inherited from subtotal)
    let total_num = match &total_value.value {
        lemma::ValueKind::Scale(n, unit) => {
            assert_eq!(
                unit.as_str(),
                "eur",
                "total should have unit 'eur', got: {:?}",
                unit
            );
            *n
        }
        _ => panic!("total should be Scale type, got: {:?}", total_value.value),
    };
    // discount_amount = 12.60 * 0.10 = 1.26
    // total = 12.60 - 1.26 = 11.34
    assert_eq!(
        total_num,
        Decimal::from_str("11.34").unwrap(),
        "total should be exactly 11.34 (12.60 - 1.26), got: {}",
        total_num
    );
}

#[test]
fn test_coffee_order_ordered_priority() {
    let engine = load_coffee_order();
    let now = DateTimeValue::now();

    // Test priority mapping
    let priorities = ["low", "medium", "high"];
    let expected_values = ["1", "2", "3"];

    for (priority, expected) in priorities.iter().zip(expected_values.iter()) {
        let data_values = HashMap::from([("priority".to_string(), priority.to_string())]);

        let response = engine
            .run(None, "coffee_order", Some(&now), data_values, false)
            .expect("Evaluation failed");

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

        let priority_value = ordered_priority
            .result
            .value()
            .expect("ordered_priority should have value");
        assert_eq!(
            priority_value.to_string(),
            *expected,
            "priority '{}' should map to {}, got: {}",
            priority,
            expected,
            priority_value
        );
    }
}

#[test]
fn test_coffee_order_invalid_size_veto() {
    let engine = load_coffee_order();
    let now = DateTimeValue::now();

    // Size "extra large" is defined in the inline type constraint, but size_multiplier
    // only handles small/medium/large, so it should veto
    let data_values = HashMap::from([
        ("coffee".to_string(), "espresso".to_string()),
        ("size".to_string(), "extra large".to_string()),
        ("number_of_cups".to_string(), "1".to_string()),
    ]);

    let response = engine
        .run(None, "coffee_order", Some(&now), data_values, false)
        .expect("Evaluation should complete (even with veto)");

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

    // size_multiplier should veto because "extra large" is not handled
    assert!(
        size_multiplier.result.vetoed(),
        "size_multiplier should veto for 'extra large' size"
    );

    // price_per_cup and subsequent rules should also fail due to dependency
    let price_per_cup = response
        .results
        .values()
        .find(|r| r.rule.name == "price_per_cup");

    if let Some(price_per_cup) = price_per_cup {
        assert!(
            price_per_cup.result.vetoed() || price_per_cup.result.value().is_none(),
            "price_per_cup should fail when size_multiplier vetoes"
        );
    }
}