lemma 0.8.19

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
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
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
use assert_cmd::cargo::cargo_bin_cmd;

use predicates::prelude::*;
use std::fs;
use tempfile::TempDir;

#[test]
fn test_cli_run_simple_spec() {
    let temp_dir = TempDir::new().unwrap();
    fs::write(
        temp_dir.path().join("test.lemma"),
        r#"
spec simple_test
data x: 10
data y: 5
rule sum: x + y
rule product: x * y
"#,
    )
    .unwrap();

    let mut cmd = cargo_bin_cmd!("lemma");
    cmd.arg("run")
        .arg("--prefix")
        .arg(temp_dir.path())
        .arg("simple_test");

    cmd.assert()
        .success()
        .stdout(predicate::str::contains("sum"))
        .stdout(predicate::str::contains("15"))
        .stdout(predicate::str::contains("product"))
        .stdout(predicate::str::contains("50"));
}

#[test]
fn test_cli_run_data_values() {
    let temp_dir = TempDir::new().unwrap();
    fs::write(
        temp_dir.path().join("test.lemma"),
        r#"
spec override_test
data base: number
rule doubled: base * 2
"#,
    )
    .unwrap();

    let mut cmd = cargo_bin_cmd!("lemma");
    cmd.arg("run")
        .arg("--prefix")
        .arg(temp_dir.path())
        .arg("override_test")
        .arg("base=7");

    cmd.assert()
        .success()
        .stdout(predicate::str::contains("14"));
}

#[test]
fn test_cli_run_nonexistent_spec() {
    let temp_dir = TempDir::new().unwrap();

    let mut cmd = cargo_bin_cmd!("lemma");
    cmd.arg("run")
        .arg("--prefix")
        .arg(temp_dir.path())
        .arg("nonexistent");

    cmd.assert()
        .failure()
        .stderr(predicate::str::contains("not found"));
}

#[test]
fn test_cli_run_rejects_dash_source() {
    let mut cmd = cargo_bin_cmd!("lemma");
    cmd.arg("run").arg("-").arg("any_spec");

    cmd.assert()
        .failure()
        .stderr(predicate::str::contains("--prefix"));
}

#[test]
fn test_cli_run_with_unless_clause() {
    let temp_dir = TempDir::new().unwrap();
    fs::write(
        temp_dir.path().join("test.lemma"),
        r#"
spec discount_test
data quantity: 15
rule discount: 0
  unless quantity >= 10 then 10
  unless quantity >= 20 then 20
"#,
    )
    .unwrap();

    let mut cmd = cargo_bin_cmd!("lemma");
    cmd.arg("run")
        .arg("--prefix")
        .arg(temp_dir.path())
        .arg("discount_test");

    cmd.assert()
        .success()
        .stdout(predicate::str::contains("10"));
}

#[test]
fn test_cli_schema_spec() {
    let temp_dir = TempDir::new().unwrap();
    fs::write(
        temp_dir.path().join("test.lemma"),
        r#"
spec inspect_test
data name: text
  -> option "Test"
data value: number
  -> minimum 0
rule doubled: value * 2
"#,
    )
    .unwrap();

    let mut cmd = cargo_bin_cmd!("lemma");
    cmd.arg("schema")
        .arg("--prefix")
        .arg(temp_dir.path())
        .arg("inspect_test");

    cmd.assert()
        .success()
        .stdout(predicate::str::contains("inspect_test"))
        .stdout(predicate::str::contains("Data"))
        .stdout(predicate::str::contains("Rules"))
        .stdout(predicate::str::contains("name"))
        .stdout(predicate::str::contains("options"))
        .stdout(predicate::str::contains("minimum"))
        .stdout(predicate::str::contains("text"))
        .stdout(predicate::str::contains("number"));
}

#[test]
fn test_cli_list_summary() {
    let temp_dir = TempDir::new().unwrap();

    fs::write(
        temp_dir.path().join("spec1.lemma"),
        r#"
spec spec1
data x: 1
"#,
    )
    .unwrap();

    fs::write(
        temp_dir.path().join("spec2.lemma"),
        r#"
spec spec2
data y: 2
"#,
    )
    .unwrap();

    let mut cmd = cargo_bin_cmd!("lemma");
    cmd.arg("list").arg("--prefix").arg(temp_dir.path());

    cmd.assert()
        .success()
        .stdout(predicate::str::contains("spec1"))
        .stdout(predicate::str::contains("spec2"))
        .stdout(predicate::str::contains("Found").not())
        .stdout(predicate::str::contains("data").not());
}

#[test]
fn test_cli_list_scopes_main_repository() {
    let temp_dir = TempDir::new().unwrap();

    fs::write(
        temp_dir.path().join("named.lemma"),
        r#"repo deps_repo

spec dep_only
data d: 1
"#,
    )
    .unwrap();

    fs::write(
        temp_dir.path().join("workspace.lemma"),
        r#"spec entry
data x: 1"#,
    )
    .unwrap();

    let mut cmd = cargo_bin_cmd!("lemma");
    cmd.arg("list").arg("--prefix").arg(temp_dir.path());

    cmd.assert().success().stdout(
        predicate::str::contains("entry")
            .and(predicate::str::contains("deps_repo"))
            .and(predicate::str::contains("dep_only"))
            .and(predicate::str::contains("Found").not())
            .and(predicate::str::contains("Repositories:").not()),
    );
}

#[test]
fn test_cli_run_with_arithmetic() {
    let temp_dir = TempDir::new().unwrap();
    fs::write(
        temp_dir.path().join("test.lemma"),
        r#"
spec arithmetic_test
data price: 100
rule with_tax: price * 1.21
"#,
    )
    .unwrap();

    let mut cmd = cargo_bin_cmd!("lemma");
    cmd.arg("run")
        .arg("--prefix")
        .arg(temp_dir.path())
        .arg("arithmetic_test");

    cmd.assert()
        .success()
        .stdout(predicate::str::contains("121"));
}

#[test]
fn test_cli_parse_error_handling() {
    let temp_dir = TempDir::new().unwrap();
    fs::write(
        temp_dir.path().join("test.lemma"),
        r#"
spec invalid
this is not valid lemma syntax
"#,
    )
    .unwrap();

    let mut cmd = cargo_bin_cmd!("lemma");
    cmd.arg("run")
        .arg("--prefix")
        .arg(temp_dir.path())
        .arg("invalid");

    cmd.assert()
        .failure()
        .stderr(predicate::str::contains("error").or(predicate::str::contains("Error")));
}

#[test]
fn test_cli_reports_errors_from_all_files() {
    let temp_dir = TempDir::new().unwrap();

    fs::write(
        temp_dir.path().join("valid.lemma"),
        r#"
spec valid_spec
data price: 100
rule doubled: price * 2
"#,
    )
    .unwrap();

    fs::write(
        temp_dir.path().join("broken_a.lemma"),
        r#"
spec broken_a
this is not valid lemma
"#,
    )
    .unwrap();

    fs::write(
        temp_dir.path().join("broken_b.lemma"),
        r#"
spec broken_b
also invalid lemma syntax
"#,
    )
    .unwrap();

    let mut cmd = cargo_bin_cmd!("lemma");
    cmd.arg("run")
        .arg("--prefix")
        .arg(temp_dir.path())
        .arg("valid_spec");

    let output = cmd.output().unwrap();
    let stderr = String::from_utf8_lossy(&output.stderr);

    assert!(
        !output.status.success(),
        "Should fail when workspace has broken files"
    );
    assert!(
        stderr.contains("broken_a") && stderr.contains("broken_b"),
        "Should report errors from both broken files, got:\n{}",
        stderr
    );
}

#[test]
fn test_cli_explain_renders_data_section() {
    let temp_dir = TempDir::new().unwrap();
    fs::write(
        temp_dir.path().join("test.lemma"),
        r#"
spec data_section
data base_value: 100
rule doubled: base_value * 2
"#,
    )
    .unwrap();

    let mut cmd = cargo_bin_cmd!("lemma");
    cmd.arg("run")
        .arg("--prefix")
        .arg(temp_dir.path())
        .arg("data_section")
        .arg("--rules=doubled")
        .arg("--explain");

    let output = cmd.output().unwrap();
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        output.status.success(),
        "run --explain should succeed: {}",
        stdout
    );

    assert!(
        stdout.contains("Data"),
        "explain output should render the Data section, got:\n{}",
        stdout
    );
    assert!(
        stdout.contains("base_value") && stdout.contains("100"),
        "the Data section should list base_value with its effective value, got:\n{}",
        stdout
    );
}

#[test]
fn test_cli_explain_shows_all_operands_in_nested_arithmetic() {
    let temp_dir = TempDir::new().unwrap();
    fs::write(
        temp_dir.path().join("test.lemma"),
        r#"
spec nested_explanation
data x: 10
data y: 20
data z: 30
rule a: x + 1
rule b: y + 2
rule c: z + 3
rule total: a + b + c
"#,
    )
    .unwrap();

    let mut cmd = cargo_bin_cmd!("lemma");
    cmd.arg("run")
        .arg("--prefix")
        .arg(temp_dir.path())
        .arg("nested_explanation")
        .arg("--rules=total")
        .arg("--explain");

    let output = cmd.output().unwrap();
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        output.status.success(),
        "run --explain should succeed: {}",
        stdout
    );

    assert!(
        stdout.contains("a:") && stdout.contains("b:") && stdout.contains("c:"),
        "explain should expand all three rule operands (a, b, c), got:\n{}",
        stdout
    );

    let lines: Vec<&str> = stdout.lines().collect();
    let a_line = lines.iter().find(|l| l.contains("a:")).unwrap();
    let b_line = lines.iter().find(|l| l.contains("b:")).unwrap();
    let c_line = lines.iter().find(|l| l.contains("c:")).unwrap();
    let indent_of = |line: &str| line.len() - line.trim_start().len();
    assert_eq!(
        indent_of(a_line),
        indent_of(b_line),
        "a and b should be at the same depth (flattened), got:\n{}",
        stdout
    );
    assert_eq!(
        indent_of(b_line),
        indent_of(c_line),
        "b and c should be at the same depth (flattened), got:\n{}",
        stdout
    );
}

#[test]
fn test_cli_explain_shows_negated_comparison_not_false() {
    let temp_dir = TempDir::new().unwrap();
    fs::write(
        temp_dir.path().join("test.lemma"),
        r#"
spec explain_test
rule out: true
 unless 5 < 3 then false
"#,
    )
    .unwrap();

    let mut cmd = cargo_bin_cmd!("lemma");
    cmd.arg("run")
        .arg("--prefix")
        .arg(temp_dir.path())
        .arg("explain_test")
        .arg("--explain");

    let output = cmd.output().unwrap();
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        output.status.success(),
        "run --explain should succeed: {}",
        stdout
    );

    // The condition `5 < 3` was false; the explanation states the flipped
    // fact that held instead of appending "is false".
    assert!(
        stdout.contains("5 >= 3"),
        "explain should state the falsified unless condition as a flipped fact, got:\n{}",
        stdout
    );
}

#[test]
fn test_cli_explain_scalar_conversion_format() {
    let temp_dir = TempDir::new().unwrap();
    fs::write(
        temp_dir.path().join("test.lemma"),
        r#"
spec test_cli_conversion_explain
data mass: quantity
    -> unit kilogram 1.0
    -> unit gram 0.001
    -> default 2 kilogram
rule result: mass as gram
"#,
    )
    .unwrap();

    let mut cmd = cargo_bin_cmd!("lemma");
    cmd.arg("run")
        .arg("--prefix")
        .arg(temp_dir.path())
        .arg("test_cli_conversion_explain")
        .arg("--rules=result")
        .arg("--explain");

    let output = cmd.output().unwrap();
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        output.status.success(),
        "run --explain should succeed: {}",
        stdout
    );
    assert!(stdout.contains("2 kilogram"), "stdout:\n{stdout}");
    assert!(
        stdout.contains("1 kilogram is 1000 gram"),
        "stdout:\n{stdout}"
    );
    assert!(
        stdout.contains("The quantity of mass is 2 kilogram"),
        "stdout:\n{stdout}"
    );
    assert!(!stdout.contains('×'), "stdout:\n{stdout}");
    assert!(!stdout.contains("mass as gram is"), "stdout:\n{stdout}");
}

#[test]
fn test_cli_explain_date_range_conversion_format() {
    let temp_dir = TempDir::new().unwrap();
    fs::write(
        temp_dir.path().join("test.lemma"),
        r#"
spec test_cli_date_conversion_explain
uses lemma units
data age: date range -> default 2024-06-01...2024-06-15
rule result: age as days
"#,
    )
    .unwrap();

    let mut cmd = cargo_bin_cmd!("lemma");
    cmd.arg("run")
        .arg("--prefix")
        .arg(temp_dir.path())
        .arg("test_cli_date_conversion_explain")
        .arg("--rules=result")
        .arg("--explain");

    let output = cmd.output().unwrap();
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        output.status.success(),
        "run --explain should succeed: {}",
        stdout
    );
    assert!(
        stdout.contains("2 week") || (stdout.contains("14") && stdout.contains("day")),
        "stdout:\n{stdout}"
    );
    assert!(stdout.contains('−'), "stdout:\n{stdout}");
    assert!(
        stdout.contains("2024-06-01") && stdout.contains("2024-06-15"),
        "stdout:\n{stdout}"
    );
    assert!(
        stdout.contains("The date range of age is"),
        "stdout:\n{stdout}"
    );
    assert!(!stdout.contains("age as days is"), "stdout:\n{stdout}");
}

#[test]
fn test_cli_explain_conversion_nested_operand() {
    let temp_dir = TempDir::new().unwrap();
    fs::write(
        temp_dir.path().join("test.lemma"),
        r#"
spec test_cli_nested_conversion_explain
data mass: quantity
    -> unit kilogram 1.0
    -> unit gram 0.001
    -> default 2 kilogram
rule result: (mass * 2) as gram
"#,
    )
    .unwrap();

    let mut cmd = cargo_bin_cmd!("lemma");
    cmd.arg("run")
        .arg("--prefix")
        .arg(temp_dir.path())
        .arg("test_cli_nested_conversion_explain")
        .arg("--rules=result")
        .arg("--explain");

    let output = cmd.output().unwrap();
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        output.status.success(),
        "run --explain should succeed: {}",
        stdout
    );
    assert!(stdout.contains("4 kilogram"), "stdout:\n{stdout}");
    assert!(
        stdout.contains("1 kilogram is 1000 gram"),
        "stdout:\n{stdout}"
    );
    assert!(
        stdout.contains("The quantity is 4 kilogram"),
        "stdout:\n{stdout}"
    );
    assert!(stdout.contains("mass"), "stdout:\n{stdout}");
}

#[test]
fn test_cli_run_quantity_rule_result_includes_all_units_json() {
    let temp_dir = TempDir::new().unwrap();
    fs::write(
        temp_dir.path().join("money.lemma"),
        r#"
spec money
data price: quantity
    -> unit eur 1
    -> unit usd 0.91
    -> default 100 eur
rule total: price
"#,
    )
    .unwrap();

    let mut cmd = cargo_bin_cmd!("lemma");
    cmd.arg("run")
        .arg("--prefix")
        .arg(temp_dir.path())
        .arg("money")
        .arg("--rules=total")
        .arg("--json");

    cmd.assert()
        .success()
        .stdout(predicate::str::contains("\"quantity\""))
        .stdout(predicate::str::contains("\"eur\""))
        .stdout(predicate::str::contains("\"usd\""));
}

#[test]
fn test_cli_explain_shows_multiply_trace_for_quantity_product() {
    let temp_dir = TempDir::new().unwrap();
    fs::write(
        temp_dir.path().join("test.lemma"),
        r#"
spec product_explanation
data price: quantity
    -> unit eur 1
    -> default 10 eur
data quantity: number -> default 3
rule product: price * quantity
"#,
    )
    .unwrap();

    let mut cmd = cargo_bin_cmd!("lemma");
    cmd.arg("run")
        .arg("--prefix")
        .arg(temp_dir.path())
        .arg("product_explanation")
        .arg("--rules=product")
        .arg("--explain");

    let output = cmd.output().unwrap();
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        output.status.success(),
        "run --explain should succeed: {}",
        stdout
    );
    assert!(
        stdout.contains("price:") && stdout.contains("quantity:"),
        "explain should show both data operands, got:\n{}",
        stdout
    );
}

#[test]
fn test_cli_explain_with_quantity_product_preserves_multiply_trace() {
    let temp_dir = TempDir::new().unwrap();
    fs::write(
        temp_dir.path().join("test.lemma"),
        r#"
spec product_as_explanation
data price: quantity
    -> unit eur 1
    -> unit usd 0.91
    -> default 10 eur
data quantity: number -> default 3
rule product: price * quantity
"#,
    )
    .unwrap();

    let mut cmd = cargo_bin_cmd!("lemma");
    cmd.arg("run")
        .arg("--prefix")
        .arg(temp_dir.path())
        .arg("product_as_explanation")
        .arg("--rules=product")
        .arg("--explain");

    let output = cmd.output().unwrap();
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        output.status.success(),
        "run --explain should succeed: {}",
        stdout
    );
    assert!(
        stdout.contains("price:") && stdout.contains("quantity:"),
        "explain with --as should still show multiply data operands, got:\n{}",
        stdout
    );
}

#[test]
fn test_cli_run_calc_explain_json_includes_total_explanation() {
    let temp_dir = TempDir::new().unwrap();
    fs::write(
        temp_dir.path().join("calc.lemma"),
        r#"
spec calc

data money: quantity
  -> decimals 2
  -> unit eur 1

data hourly_rate: 85.00 eur
data hours_worked: 37.5
data is_rush: boolean
data is_super_rush: boolean

rule labor: hourly_rate * hours_worked
rule rush_surcharge: 0 eur
  unless is_rush then labor * 25%
  unless is_super_rush then labor * 50%
rule subtotal: labor + rush_surcharge
rule vat: subtotal * 21%
rule total: subtotal + vat
"#,
    )
    .unwrap();

    let mut cmd = cargo_bin_cmd!("lemma");
    cmd.arg("run")
        .arg("--prefix")
        .arg(temp_dir.path())
        .arg("calc")
        .arg("is_rush=true")
        .arg("is_super_rush=false")
        .arg("--rules=total")
        .arg("--explain")
        .arg("--json");

    let output = cmd.output().unwrap();
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        output.status.success(),
        "run calc --explain --json should succeed: {}",
        stdout
    );

    let json: serde_json::Value = serde_json::from_str(&stdout).expect("stdout is valid JSON");
    assert_eq!(json["results"]["total"]["explanation"]["rule"], "total");
    assert_eq!(
        json["results"]["total"]["explanation"]["result"],
        "4821.09 eur"
    );
}