lemma-engine 0.8.21

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
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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
//! Additional edge-case scenarios targeting potential bugs

use lemma::{DateTimeValue, Engine, SourceType};
use std::collections::HashMap;
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::Arc;

fn src(name: &str) -> SourceType {
    SourceType::Path(Arc::new(PathBuf::from(name)))
}

fn run_spec(engine: &Engine, spec: &str, data: &[(&str, &str)]) -> lemma::Response {
    let now = DateTimeValue::now();
    let data_map: HashMap<String, String> = data
        .iter()
        .map(|(k, v)| (k.to_string(), v.to_string()))
        .collect();
    engine
        .run(None, spec, Some(&now), data_map, false, None)
        .unwrap()
}

fn rule_display(response: &lemma::Response, rule_name: &str) -> String {
    response
        .results
        .values()
        .find(|r| r.rule.name == rule_name)
        .unwrap_or_else(|| panic!("rule '{}' not found", rule_name))
        .display
        .clone()
        .unwrap_or_else(|| panic!("rule '{}' has no display", rule_name))
}

fn rule_vetoed(response: &lemma::Response, rule_name: &str) -> bool {
    response
        .results
        .values()
        .find(|r| r.rule.name == rule_name)
        .unwrap_or_else(|| panic!("rule '{}' not found", rule_name))
        .vetoed
}

// ===========================================================================
// EDGE CASE 1: Very large exponentiation
// ===========================================================================

#[test]
fn edge_large_exponentiation() {
    let mut engine = Engine::new();
    engine
        .load(
            r#"
spec big_math

data base: number
data exponent: number

rule result: base ^ exponent
"#,
            src("big.lemma"),
        )
        .unwrap();

    // 2^10 = 1024
    let resp = run_spec(&engine, "big_math", &[("base", "2"), ("exponent", "10")]);
    let display = rule_display(&resp, "result");
    assert_eq!(display, "1024", "2^10 = 1024");

    // 10^0 = 1
    let resp = run_spec(&engine, "big_math", &[("base", "10"), ("exponent", "0")]);
    let display = rule_display(&resp, "result");
    assert_eq!(display, "1", "10^0 = 1");
}

// ===========================================================================
// EDGE CASE 2: Negative number arithmetic
// ===========================================================================

#[test]
fn edge_negative_arithmetic() {
    let mut engine = Engine::new();
    engine
        .load(
            r#"
spec negatives

data a: number
data b: number

rule sum: a + b
rule diff: a - b
rule product: a * b
rule negated: 0 - a
"#,
            src("neg.lemma"),
        )
        .unwrap();

    let resp = run_spec(&engine, "negatives", &[("a", "-5"), ("b", "3")]);
    let sum = rule_display(&resp, "sum");
    assert_eq!(sum, "-2", "-5 + 3 = -2");

    let diff = rule_display(&resp, "diff");
    assert_eq!(diff, "-8", "-5 - 3 = -8");

    let product = rule_display(&resp, "product");
    assert_eq!(product, "-15", "-5 * 3 = -15");

    let negated = rule_display(&resp, "negated");
    assert_eq!(negated, "5", "0 - (-5) = 5");
}

// ===========================================================================
// EDGE CASE 3: Deeply nested cross-spec references
// ===========================================================================

#[test]
fn edge_three_level_spec_composition() {
    let mut engine = Engine::new();
    engine
        .load(
            r#"
spec base
data factor: 2

spec middle
uses b: base
rule doubled: b.factor * 3

spec top
uses m: middle
rule final: m.doubled + 1
"#,
            src("nested.lemma"),
        )
        .unwrap();

    let resp = run_spec(&engine, "top", &[]);
    let display = rule_display(&resp, "final");
    assert_eq!(display, "7", "2 * 3 + 1 = 7");
}

// ===========================================================================
// EDGE CASE 4: Chained percentage operations (explicit scaling)
// ===========================================================================

#[test]
fn edge_chained_percentage_reduction() {
    let mut engine = Engine::new();
    engine
        .load(
            r#"
spec chain_pct

data amount: 1000

rule half: amount - 50% * amount
rule quarter: half - 50% * half
rule eighth: quarter - 50% * quarter
"#,
            src("chain.lemma"),
        )
        .unwrap();

    let resp = run_spec(&engine, "chain_pct", &[]);
    assert_eq!(rule_display(&resp, "half"), "500");
    assert_eq!(rule_display(&resp, "quarter"), "250");
    assert_eq!(rule_display(&resp, "eighth"), "125");
}

// ===========================================================================
// EDGE CASE 5: Veto in one unless arm, value in another — last wins
// If veto arm matches AND a later non-veto arm matches, the veto is overridden
// ===========================================================================

#[test]
fn edge_veto_overridden_by_later_clause() {
    let mut engine = Engine::new();
    engine
        .load(
            r#"
spec veto_override

data value: number
data override_flag: boolean

rule result: 0
  unless value > 100 then veto "Too large"
  unless override_flag then 999
"#,
            src("veto_override.lemma"),
        )
        .unwrap();

    // value=200 (triggers veto), override_flag=true (later clause wins)
    let resp = run_spec(
        &engine,
        "veto_override",
        &[("value", "200"), ("override_flag", "true")],
    );
    // Last matching clause wins: override_flag is true → 999
    assert!(
        !rule_vetoed(&resp, "result"),
        "later clause should override veto"
    );
    assert_eq!(rule_display(&resp, "result"), "999");

    // value=200 (triggers veto), override_flag=false (veto is last match)
    let resp = run_spec(
        &engine,
        "veto_override",
        &[("value", "200"), ("override_flag", "false")],
    );
    assert!(
        rule_vetoed(&resp, "result"),
        "veto should win when no later clause matches"
    );
}

// ===========================================================================
// EDGE CASE 6: Zero multiplied by anything
// ===========================================================================

#[test]
fn edge_zero_multiplication() {
    let mut engine = Engine::new();
    engine
        .load(
            r#"
spec zero_mult

data quantity: number
data price: number

rule total: quantity * price
rule zero_check: 0 * price
"#,
            src("zero.lemma"),
        )
        .unwrap();

    let resp = run_spec(
        &engine,
        "zero_mult",
        &[("quantity", "0"), ("price", "9999")],
    );
    assert_eq!(rule_display(&resp, "total"), "0", "0 * anything = 0");
    assert_eq!(
        rule_display(&resp, "zero_check"),
        "0",
        "literal 0 * price = 0"
    );
}

// ===========================================================================
// EDGE CASE 7: Text comparison edge cases
// ===========================================================================

#[test]
fn edge_text_comparison() {
    let mut engine = Engine::new();
    engine
        .load(
            r#"
spec text_cmp

data status: text
  -> option "active"
  -> option "inactive"
  -> option "pending"

rule is_active: status is "active"
rule is_not_pending: status is not "pending"
"#,
            src("text.lemma"),
        )
        .unwrap();

    let resp = run_spec(&engine, "text_cmp", &[("status", "active")]);
    assert_eq!(rule_display(&resp, "is_active"), "true");
    assert_eq!(rule_display(&resp, "is_not_pending"), "true");

    let resp = run_spec(&engine, "text_cmp", &[("status", "pending")]);
    assert_eq!(rule_display(&resp, "is_active"), "false");
    assert_eq!(rule_display(&resp, "is_not_pending"), "false");
}

// ===========================================================================
// EDGE CASE 8: Unless with complex boolean AND condition
// ===========================================================================

#[test]
fn edge_unless_complex_and() {
    let mut engine = Engine::new();
    engine
        .load(
            r#"
spec complex_and

data a: boolean
data b: boolean
data c: boolean

rule result: "none"
  unless a and b then "a_and_b"
  unless a and b and c then "all_three"
"#,
            src("complex.lemma"),
        )
        .unwrap();

    // All true → last matching is "all_three"
    let resp = run_spec(
        &engine,
        "complex_and",
        &[("a", "true"), ("b", "true"), ("c", "true")],
    );
    assert_eq!(rule_display(&resp, "result"), "all_three");

    // a=true, b=true, c=false → only "a_and_b" matches
    let resp = run_spec(
        &engine,
        "complex_and",
        &[("a", "true"), ("b", "true"), ("c", "false")],
    );
    assert_eq!(rule_display(&resp, "result"), "a_and_b");

    // a=true, b=false, c=true → no unless matches → "none"
    let resp = run_spec(
        &engine,
        "complex_and",
        &[("a", "true"), ("b", "false"), ("c", "true")],
    );
    assert_eq!(rule_display(&resp, "result"), "none");
}

// ===========================================================================
// EDGE CASE 9: Ratio type with custom constraints — multiply only
// ===========================================================================

#[test]
fn edge_ratio_operations() {
    let mut engine = Engine::new();
    engine
        .load(
            r#"
spec ratio_math

data discount: ratio -> minimum 0% -> maximum 100%
data base: number

rule raw_mult: base * discount
"#,
            src("ratio.lemma"),
        )
        .unwrap();

    let resp = run_spec(
        &engine,
        "ratio_math",
        &[("discount", "25%"), ("base", "400")],
    );
    assert_eq!(rule_display(&resp, "raw_mult"), "100", "400 * 25% = 100");
}

#[test]
fn edge_ratio_add_subtract_rejected() {
    let mut engine = Engine::new();
    let result = engine.load(
        r#"
spec ratio_math
data discount: ratio
data base: number
rule bad: base - discount
"#,
        src("ratio.lemma"),
    );
    assert!(result.is_err());
    let msg = result
        .unwrap_err()
        .iter()
        .map(|e| e.to_string())
        .collect::<Vec<_>>()
        .join("; ");
    assert!(msg.contains("scale explicitly"), "got: {}", msg);
}

// ===========================================================================
// EDGE CASE 10: Multiple specs same name different effective dates
// with unpinned import (temporal slicing)
// ===========================================================================

#[test]
fn edge_temporal_before_any_version() {
    let mut engine = Engine::new();
    engine
        .load(
            r#"
spec rates 2024-01-01
data rate: 5%

spec rates 2025-01-01
data rate: 7%

spec calculator 2024-01-01
uses r: rates
data amount: number
rule result: amount * r.rate
"#,
            src("temporal2.lemma"),
        )
        .unwrap();

    // Evaluate at 2024-06-01 → rate = 5%
    let effective = DateTimeValue::from_str("2024-06-01").unwrap();
    let data: HashMap<String, String> = [("amount".to_string(), "1000".to_string())].into();
    let resp = engine
        .run(None, "calculator", Some(&effective), data, false, None)
        .unwrap();
    let display = rule_display(&resp, "result");
    assert_eq!(display, "50", "2024: 1000 * 5% = 50");

    // Evaluate at 2025-06-01 → rate = 7%
    let effective = DateTimeValue::from_str("2025-06-01").unwrap();
    let data: HashMap<String, String> = [("amount".to_string(), "1000".to_string())].into();
    let resp = engine
        .run(None, "calculator", Some(&effective), data, false, None)
        .unwrap();
    let display = rule_display(&resp, "result");
    assert_eq!(display, "70", "2025: 1000 * 7% = 70");
}

// ===========================================================================
// EDGE CASE 11: sqrt of perfect square
// ===========================================================================

#[test]
fn edge_sqrt_operations() {
    let mut engine = Engine::new();
    engine
        .load(
            r#"
spec sqrt_test

data value: number -> minimum 0

rule root: sqrt(value)
rule root_of_zero: sqrt(0)
rule root_of_one: sqrt(1)
"#,
            src("sqrt.lemma"),
        )
        .unwrap();

    let resp = run_spec(&engine, "sqrt_test", &[("value", "144")]);
    assert_eq!(rule_display(&resp, "root"), "12", "sqrt(144) = 12");
    assert_eq!(rule_display(&resp, "root_of_zero"), "0", "sqrt(0) = 0");
    assert_eq!(rule_display(&resp, "root_of_one"), "1", "sqrt(1) = 1");
}

// ===========================================================================
// EDGE CASE 12: Division yielding non-terminating decimal
// 1/3 should display cleanly
// ===========================================================================

#[test]
fn edge_non_terminating_division() {
    let mut engine = Engine::new();
    engine
        .load(
            r#"
spec repeating

data a: number
data b: number

rule third: a / b
"#,
            src("repeating.lemma"),
        )
        .unwrap();

    let resp = run_spec(&engine, "repeating", &[("a", "1"), ("b", "3")]);
    // Should display with reasonable precision, not crash or produce infinite string
    let display = rule_display(&resp, "third");
    assert!(!display.is_empty(), "1/3 should have a display value");
    // The exact format depends on engine precision handling
}

// ===========================================================================
// EDGE CASE 13: Multiple unless clauses where NONE match
// ===========================================================================

#[test]
fn edge_no_unless_matches() {
    let mut engine = Engine::new();
    engine
        .load(
            r#"
spec fallthrough

data x: number

rule category: "default"
  unless x > 100 then "high"
  unless x < 0 then "negative"
"#,
            src("fallthrough.lemma"),
        )
        .unwrap();

    // x=50: neither >100 nor <0, so default applies
    let resp = run_spec(&engine, "fallthrough", &[("x", "50")]);
    assert_eq!(rule_display(&resp, "category"), "default");
}

// ===========================================================================
// EDGE CASE 14: Rule referencing another rule that references another rule
// (Deep dependency chain)
// ===========================================================================

#[test]
fn edge_deep_rule_chain() {
    let mut engine = Engine::new();
    engine
        .load(
            r#"
spec chain

data input: number

rule step1: input + 1
rule step2: step1 * 2
rule step3: step2 - 3
rule step4: step3 / 2
rule step5: step4 + 10
"#,
            src("chain.lemma"),
        )
        .unwrap();

    // input=5: step1=6, step2=12, step3=9, step4=4.5, step5=14.5
    let resp = run_spec(&engine, "chain", &[("input", "5")]);
    assert_eq!(
        rule_display(&resp, "step5"),
        "14.5",
        "(((5+1)*2)-3)/2+10 = 14.5"
    );
}

// ===========================================================================
// EDGE CASE 15: Unit conversion chain: measure -> as unit -> as number
// ===========================================================================

#[test]
fn edge_measure_to_number_conversion() {
    let mut engine = Engine::new();
    engine
        .load(
            r#"
spec unit_strip
uses lemma units

data weight: 5 kilogram

rule kg_value: weight as kilogram as number
rule gram_value: weight as gram as number
"#,
            src("strip.lemma"),
        )
        .unwrap();

    let resp = run_spec(&engine, "unit_strip", &[]);
    assert_eq!(
        rule_display(&resp, "kg_value"),
        "5",
        "5kg as kg as number = 5"
    );
    assert_eq!(
        rule_display(&resp, "gram_value"),
        "5000",
        "5kg as g as number = 5000"
    );
}

// ===========================================================================
// EDGE CASE 16: `not` operator on comparison
// ===========================================================================

#[test]
fn edge_not_operator() {
    let mut engine = Engine::new();
    engine
        .load(
            r#"
spec not_test

data active: boolean
data score: number

rule is_inactive: not active
rule below_threshold: not score >= 70
"#,
            src("not.lemma"),
        )
        .unwrap();

    let resp = run_spec(&engine, "not_test", &[("active", "true"), ("score", "80")]);
    assert_eq!(
        rule_display(&resp, "is_inactive"),
        "false",
        "not true = false"
    );
    assert_eq!(
        rule_display(&resp, "below_threshold"),
        "false",
        "not (80>=70) = false"
    );

    let resp = run_spec(&engine, "not_test", &[("active", "false"), ("score", "50")]);
    assert_eq!(
        rule_display(&resp, "is_inactive"),
        "true",
        "not false = true"
    );
    assert_eq!(
        rule_display(&resp, "below_threshold"),
        "true",
        "not (50>=70) = true"
    );
}

// ===========================================================================
// EDGE CASE 17: With binding + overriding data from parent
// ===========================================================================

#[test]
fn edge_with_binding_override() {
    let mut engine = Engine::new();
    engine
        .load(
            r#"
spec config
data tax_rate: 10%
data base_price: 100
rule tax_amount: base_price * tax_rate
rule total: base_price + tax_amount

spec custom
uses c: config
with c.tax_rate: 25%
rule custom_total: c.total
"#,
            src("with.lemma"),
        )
        .unwrap();

    let resp = run_spec(&engine, "custom", &[]);
    // c.total should use overridden tax_rate of 25%
    // tax_amount = 100 * 0.25 = 25, total = 100 + 25 = 125
    assert_eq!(
        rule_display(&resp, "custom_total"),
        "125",
        "with override: 100 + 100*25% = 125"
    );
}

fn main() {}