tessellate 0.3.0

Command-line interface for the Tess rule language
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
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
use anstyle::{AnsiColor, Style};
use std::borrow::Cow;
use std::collections::{BTreeMap, BTreeSet};
use std::fmt::{Arguments, Write as _};
use std::path::Path;
use tess::ast::{Cardinality, Effect};
use tess::compiler::normalize_name;
use tess::engine::{
    Candidate, DecisionStatus, Evaluation, FragmentEvidence, Input, RuleOutcome, RuleTrace,
    SuppressionReason,
};
use tess::value::Value;
use tess::{CompiledProgram, SourceFile, Span};

const CASE_STYLE: Style = AnsiColor::Cyan.on_default().bold();
const NAME_STYLE: Style = AnsiColor::Blue.on_default().bold();
const SUCCESS_STYLE: Style = AnsiColor::Green.on_default().bold();
const INCOMPLETE_STYLE: Style = AnsiColor::Yellow.on_default().bold();
const CONFLICT_STYLE: Style = AnsiColor::Red.on_default().bold();
const SECTION_STYLE: Style = AnsiColor::Cyan.on_default().bold();
const LABEL_STYLE: Style = AnsiColor::BrightBlack.on_default();
const LOCATION_STYLE: Style = AnsiColor::BrightBlack.on_default();
const MARKER_STYLE: Style = AnsiColor::Cyan.on_default().bold();
const METADATA_VALUE_COLUMN: usize = 15;

#[derive(Clone, Copy)]
struct Styles {
    color: bool,
}

impl Styles {
    const fn new(color: bool) -> Self {
        Self { color }
    }

    fn write(self, output: &mut String, style: Style, value: Arguments<'_>) {
        if self.color {
            let _ = write!(output, "{style}{value}{style:#}");
        } else {
            let _ = output.write_fmt(value);
        }
    }
}

/// Render one evaluation as a short human explanation.
///
/// This intentionally names only the decisive rules, overrides, missing facts,
/// and fragment bases. Source locations, source excerpts, conditions, and the
/// complete rule trace belong to the verbose renderer below.
pub(crate) fn render_concise_evaluation(
    evaluation: &Evaluation,
    case_name: Option<&str>,
    color: bool,
) -> String {
    render_concise_evaluations(std::slice::from_ref(evaluation), case_name, color)
}

/// Render all evaluations for one input without repeating input records.
pub(crate) fn render_concise_evaluations(
    evaluations: &[Evaluation],
    case_name: Option<&str>,
    color: bool,
) -> String {
    let styles = Styles::new(color);
    let mut output = String::new();
    if let Some(case_name) = case_name {
        styles.write(&mut output, CASE_STYLE, format_args!("{case_name}"));
        output.push('\n');
    }

    for evaluation in evaluations {
        write_status(&mut output, evaluation, styles);
        write_concise_reasons(&mut output, evaluation, styles);
    }

    if !output.ends_with('\n') {
        output.push('\n');
    }
    output
}

fn write_concise_reasons(output: &mut String, evaluation: &Evaluation, styles: Styles) {
    match &evaluation.result.status {
        DecisionStatus::Resolved { values } if values.is_empty() => {
            write_concise_item(
                output,
                "reason",
                "no rule produced a value; an empty result is allowed",
                styles,
            );
        }
        DecisionStatus::Resolved { .. } | DecisionStatus::Conflict { .. } => {
            for candidate in &evaluation.result.candidates {
                write_concise_item(
                    output,
                    "reason",
                    &concise_candidate_reason(candidate, "produced"),
                    styles,
                );
            }
        }
        DecisionStatus::Undefined => {
            let reason = if evaluation.result.suppressed.is_empty() {
                "no rule produced a value"
            } else {
                "no value remained after overrides"
            };
            write_concise_item(output, "reason", reason, styles);
        }
        DecisionStatus::Unknown { missing } => {
            if missing.is_empty() {
                write_concise_item(
                    output,
                    "reason",
                    "the applicable rules could not be decided",
                    styles,
                );
            } else {
                write_concise_item(
                    output,
                    "missing",
                    &format!("{}; these facts can change the result", missing.join(", ")),
                    styles,
                );
            }
            for candidate in &evaluation.result.candidates {
                write_concise_item(
                    output,
                    "possible",
                    &concise_candidate_reason(candidate, "could produce"),
                    styles,
                );
            }
        }
    }

    for suppressed in &evaluation.result.suppressed {
        let SuppressionReason::ExplicitOverride { by } = &suppressed.reason;
        write_concise_item(
            output,
            "override",
            &format!(
                "rule `{by}` removed `{}` -> `{}`",
                suppressed.candidate.rule, suppressed.candidate.value
            ),
            styles,
        );
    }

    let mut bases = BTreeSet::new();
    for candidate in &evaluation.result.candidates {
        collect_concise_bases(&mut bases, &candidate.basis);
    }
    for suppressed in &evaluation.result.suppressed {
        collect_concise_bases(&mut bases, &suppressed.candidate.basis);
        let SuppressionReason::ExplicitOverride { by } = &suppressed.reason;
        if let Some(trace) = trace_for_rule(evaluation, by) {
            collect_concise_bases(&mut bases, &trace.basis);
        }
    }
    if matches!(&evaluation.result.status, DecisionStatus::Unknown { .. }) {
        for trace in &evaluation.rules {
            if matches!(
                trace.outcome,
                RuleOutcome::Blocked | RuleOutcome::Conflicted
            ) {
                collect_concise_bases(&mut bases, &trace.basis);
            }
        }
    }
    for (id, locator) in bases {
        let value = if id == locator {
            format!("`{id}`")
        } else {
            format!("`{id}` @ `{locator}`")
        };
        write_concise_item(output, "basis", &value, styles);
    }
}

fn collect_concise_bases<'a>(
    bases: &mut BTreeSet<(&'a str, &'a str)>,
    evidence: &'a [FragmentEvidence],
) {
    bases.extend(
        evidence
            .iter()
            .map(|basis| (basis.id.as_str(), basis.locator.as_str())),
    );
}

fn concise_candidate_reason(candidate: &Candidate, outcome: &str) -> String {
    let rule = candidate
        .rule
        .rsplit("::")
        .next()
        .unwrap_or(candidate.rule.as_str());
    format!("rule `{rule}` {outcome} `{}`", candidate.value)
}

fn write_concise_item(output: &mut String, label: &str, value: &str, styles: Styles) {
    write_indent(output, 4);
    styles.write(output, LABEL_STYLE, format_args!("{label}"));
    output.push(' ');
    output.push_str(value);
    output.push('\n');
}

/// Render one evaluation as a source-oriented explanation for humans.
///
/// The serialized evaluation deliberately stays location-free. Human-facing
/// tools can recover declaration spans from the compiled program without
/// changing the stable JSON result schema.
pub(crate) fn render_evaluation(
    program: &CompiledProgram,
    input: &Input,
    evaluation: &Evaluation,
    case_name: Option<&str>,
    color: bool,
) -> String {
    render_evaluations(
        program,
        input,
        std::slice::from_ref(evaluation),
        case_name,
        color,
    )
}

/// Render all evaluations for one input in a single test-shaped block.
///
/// Context is intentionally emitted once so a test with several expectations
/// reads as one input followed by a nested list of decision results.
pub(crate) fn render_evaluations(
    program: &CompiledProgram,
    input: &Input,
    evaluations: &[Evaluation],
    case_name: Option<&str>,
    color: bool,
) -> String {
    let styles = Styles::new(color);
    let mut output = String::new();
    write_context(&mut output, input, case_name, styles);

    for evaluation in evaluations {
        output.push('\n');
        write_evaluation(&mut output, program, evaluation, styles);
    }

    while output.ends_with("\n\n") {
        output.pop();
    }
    if !output.ends_with('\n') {
        output.push('\n');
    }
    output
}

fn write_context(output: &mut String, input: &Input, case_name: Option<&str>, styles: Styles) {
    let heading = case_name.unwrap_or("input");
    styles.write(output, CASE_STYLE, format_args!("{heading}"));
    output.push('\n');

    if input.bindings.is_empty() {
        output.push_str("  (no record bindings)\n");
        return;
    }

    for (binding_name, binding) in &input.bindings {
        write_indent(output, 2);
        output.push_str("let ");
        styles.write(output, NAME_STYLE, format_args!("{binding_name}"));
        output.push_str(" = ");
        styles.write(output, NAME_STYLE, format_args!("{}", binding.entity));
        if binding.fields.is_empty() {
            output.push_str(" {}\n");
            continue;
        }
        output.push_str(" {\n");
        for (field, value) in &binding.fields {
            let _ = writeln!(output, "    {field}: {value},");
        }
        output.push_str("  }\n");
    }
}

fn write_evaluation(
    output: &mut String,
    program: &CompiledProgram,
    evaluation: &Evaluation,
    styles: Styles,
) {
    write_status(output, evaluation, styles);
    write_contract(output, evaluation, styles);

    let undefined_decision = match evaluation.result.status {
        DecisionStatus::Undefined => program.decision(&evaluation.result.decision),
        _ => None,
    };
    if let Some(decision) = undefined_decision {
        output.push('\n');
        write_snippet(
            output,
            program.source(),
            decision.span,
            "this decision requires exactly one value, but no candidate survived",
            4,
            styles,
        );
    }

    let mut explained_rules = BTreeSet::new();
    write_support(output, program, evaluation, &mut explained_rules, styles);
    write_suppressed(output, program, evaluation, &mut explained_rules, styles);
    write_blocked_rules(output, program, evaluation, &mut explained_rules, styles);
    write_other_applied_rules(output, program, evaluation, &explained_rules, styles);
    write_skipped_rules(output, program, evaluation, styles);
    write_help(output, evaluation, styles);
}

fn write_status(output: &mut String, evaluation: &Evaluation, styles: Styles) {
    let (style, status) = match &evaluation.result.status {
        DecisionStatus::Resolved { values } => (
            SUCCESS_STYLE,
            format!("✓ {} = {}", evaluation.query, resolved_values(values)),
        ),
        DecisionStatus::Undefined => (
            INCOMPLETE_STYLE,
            format!("â—‹ {} = undefined", evaluation.query),
        ),
        DecisionStatus::Unknown { .. } => (
            INCOMPLETE_STYLE,
            format!("? {} = unknown", evaluation.query),
        ),
        DecisionStatus::Conflict { values, .. } => (
            CONFLICT_STYLE,
            format!(
                "✗ {} = conflict [{}]",
                evaluation.query,
                display_values(values)
            ),
        ),
    };
    write_indent(output, 2);
    styles.write(output, style, format_args!("{status}"));
    output.push('\n');
}

fn write_contract(output: &mut String, evaluation: &Evaluation, styles: Styles) {
    let distinct = evaluation
        .result
        .candidates
        .iter()
        .map(|candidate| &candidate.value)
        .collect::<BTreeSet<_>>()
        .len();
    let support = evaluation.result.candidates.len();
    write_metadata(
        output,
        4,
        "cardinality",
        format_args!("{}", cardinality_contract(evaluation.result.cardinality)),
        styles,
    );
    write_metadata(
        output,
        4,
        "candidates",
        format_args!(
            "{} · {} · {} overridden",
            counted(support, "rule candidate", "rule candidates"),
            counted(distinct, "distinct value", "distinct values"),
            evaluation.result.suppressed.len()
        ),
        styles,
    );

    match &evaluation.result.status {
        DecisionStatus::Resolved { values } if values.is_empty() => write_metadata(
            output,
            4,
            "reason",
            format_args!("no value remained, which this cardinality permits"),
            styles,
        ),
        DecisionStatus::Resolved { .. } if support > distinct => write_metadata(
            output,
            4,
            "reason",
            format_args!(
                "{} agreed on {}; equal values were merged",
                counted(support, "rule", "rules"),
                counted(distinct, "distinct value", "distinct values")
            ),
            styles,
        ),
        DecisionStatus::Resolved { .. } => write_metadata(
            output,
            4,
            "reason",
            format_args!(
                "{} remained after explicit overrides",
                counted(distinct, "distinct value", "distinct values")
            ),
            styles,
        ),
        DecisionStatus::Undefined => write_metadata(
            output,
            4,
            "reason",
            format_args!("no candidate survived for a decision that requires one"),
            styles,
        ),
        DecisionStatus::Unknown { missing } => {
            write_metadata(
                output,
                4,
                "missing",
                format_args!("{}", missing.join(", ")),
                styles,
            );
            write_metadata(
                output,
                4,
                "reason",
                format_args!("missing input can still change which rules or overrides apply"),
                styles,
            );
        }
        DecisionStatus::Conflict { reasons, .. } => {
            for reason in reasons {
                write_metadata(output, 4, "reason", format_args!("{reason}"), styles);
            }
            write_metadata(
                output,
                4,
                "note",
                format_args!("source order never chooses between different values"),
                styles,
            );
        }
    }
}

fn write_support(
    output: &mut String,
    program: &CompiledProgram,
    evaluation: &Evaluation,
    explained_rules: &mut BTreeSet<String>,
    styles: Styles,
) {
    if evaluation.result.candidates.is_empty() {
        return;
    }
    let mut groups = BTreeMap::<&Value, Vec<&Candidate>>::new();
    for candidate in &evaluation.result.candidates {
        groups.entry(&candidate.value).or_default().push(candidate);
    }

    for (value, candidates) in groups {
        output.push('\n');
        let merged = candidates.len() > 1;
        let qualifier = match evaluation.result.status {
            DecisionStatus::Unknown { .. } => "provisional candidate",
            DecisionStatus::Conflict { .. } => "conflicting candidate",
            DecisionStatus::Resolved { .. } if merged => "merged candidate",
            DecisionStatus::Resolved { .. } | DecisionStatus::Undefined => "selected candidate",
        };
        write_section(output, 4, format_args!("{qualifier} `{value}`"), styles);
        for candidate in &candidates {
            explained_rules.insert(normalize_name(&candidate.rule));
            let (span, exact_effect) =
                candidate_location(program, &candidate.rule, &evaluation.result.decision);
            let label = if exact_effect {
                format!("proposed `{value}` by rule `{}`", candidate.rule)
            } else {
                format!("rule `{}` supports `{value}`", candidate.rule)
            };
            if let Some(span) = span {
                write_snippet(output, program.source(), span, &label, 6, styles);
            } else {
                write_metadata(
                    output,
                    6,
                    "rule",
                    format_args!("{} proposed `{value}`", candidate.rule),
                    styles,
                );
            }
            write_condition_note(output, evaluation, &candidate.rule, styles);
            write_basis(output, 6, &candidate.basis, styles);
        }
        if merged {
            write_metadata(
                output,
                6,
                "note",
                format_args!("equal values are merged and count once toward cardinality"),
                styles,
            );
        }
    }
}

fn write_suppressed(
    output: &mut String,
    program: &CompiledProgram,
    evaluation: &Evaluation,
    explained_rules: &mut BTreeSet<String>,
    styles: Styles,
) {
    for suppressed in &evaluation.result.suppressed {
        output.push('\n');
        let candidate = &suppressed.candidate;
        explained_rules.insert(normalize_name(&candidate.rule));
        let SuppressionReason::ExplicitOverride { by } = &suppressed.reason;
        explained_rules.insert(normalize_name(by));
        write_section(
            output,
            4,
            format_args!("overridden candidate `{}`", candidate.value),
            styles,
        );

        let (candidate_span, exact_effect) =
            candidate_location(program, &candidate.rule, &evaluation.result.decision);
        let candidate_label = if exact_effect {
            format!("proposed by rule `{}`", candidate.rule)
        } else {
            format!("candidate came from rule `{}`", candidate.rule)
        };
        if let Some(span) = candidate_span {
            write_snippet(output, program.source(), span, &candidate_label, 6, styles);
        }
        write_condition_note(output, evaluation, &candidate.rule, styles);
        write_basis(output, 6, &candidate.basis, styles);

        if let Some(span) = override_location(program, by, &candidate.rule) {
            write_snippet(
                output,
                program.source(),
                span,
                &format!("rule `{by}` removed this candidate"),
                6,
                styles,
            );
        } else {
            write_metadata(output, 6, "overridden by", format_args!("{by}"), styles);
        }
        write_condition_note(output, evaluation, by, styles);
    }
}

fn write_blocked_rules(
    output: &mut String,
    program: &CompiledProgram,
    evaluation: &Evaluation,
    explained_rules: &mut BTreeSet<String>,
    styles: Styles,
) {
    let blocked = evaluation
        .rules
        .iter()
        .filter(|trace| {
            matches!(
                trace.outcome,
                RuleOutcome::Blocked | RuleOutcome::Conflicted
            )
        })
        .collect::<Vec<_>>();
    if blocked.is_empty() {
        return;
    }

    output.push('\n');
    write_section(output, 4, format_args!("blocked rules"), styles);
    for trace in blocked {
        explained_rules.insert(normalize_name(&trace.rule));
        let effect_blocked = trace.condition == tess::value::TruthValue::True;
        let span = if effect_blocked {
            candidate_location(program, &trace.rule, &evaluation.result.decision).0
        } else {
            program.rule(&trace.rule).map(|rule| rule.condition.span)
        };
        let state = match trace.outcome {
            RuleOutcome::Conflicted => "conflicting evidence prevented this rule",
            RuleOutcome::Blocked if trace.missing.is_empty() => "this rule could not be resolved",
            RuleOutcome::Blocked => "this rule needs additional input",
            _ => unreachable!(),
        };
        if let Some(span) = span {
            write_snippet(
                output,
                program.source(),
                span,
                &format!("{state}: `{}`", trace.rule),
                6,
                styles,
            );
        }
        write_metadata(
            output,
            6,
            "condition",
            format_args!("{} → {}", trace.condition_expression, trace.condition),
            styles,
        );
        if !trace.missing.is_empty() {
            write_metadata(
                output,
                6,
                "missing",
                format_args!("{}", trace.missing.join(", ")),
                styles,
            );
        }
        write_basis(output, 6, &trace.basis, styles);
    }
}

fn write_other_applied_rules(
    output: &mut String,
    program: &CompiledProgram,
    evaluation: &Evaluation,
    explained_rules: &BTreeSet<String>,
    styles: Styles,
) {
    let other = evaluation
        .rules
        .iter()
        .filter(|trace| {
            matches!(
                trace.outcome,
                RuleOutcome::Applied | RuleOutcome::OverrideApplied
            ) && !explained_rules.contains(&normalize_name(&trace.rule))
        })
        .collect::<Vec<_>>();
    if other.is_empty() {
        return;
    }
    output.push('\n');
    write_section(output, 4, format_args!("other applied rules"), styles);
    for trace in other {
        if let Some(rule) = program.rule(&trace.rule) {
            write_snippet(
                output,
                program.source(),
                rule.condition.span,
                &format!("condition evaluated to true for rule `{}`", trace.rule),
                6,
                styles,
            );
        }
        write_basis(output, 6, &trace.basis, styles);
    }
}

fn write_skipped_rules(
    output: &mut String,
    program: &CompiledProgram,
    evaluation: &Evaluation,
    styles: Styles,
) {
    let skipped = evaluation
        .rules
        .iter()
        .filter(|trace| trace.outcome == RuleOutcome::Skipped)
        .collect::<Vec<_>>();
    if skipped.is_empty() {
        return;
    }
    output.push('\n');
    write_section(
        output,
        4,
        format_args!(
            "not applicable: {}",
            counted(skipped.len(), "rule", "rules")
        ),
        styles,
    );
    for trace in skipped {
        if let Some(rule) = program.rule(&trace.rule) {
            write_snippet(
                output,
                program.source(),
                rule.condition.span,
                &format!(
                    "condition evaluated to false; rule `{}` was skipped",
                    trace.rule
                ),
                6,
                styles,
            );
        } else {
            write_metadata(
                output,
                6,
                "skipped",
                format_args!("`{}`: {} → false", trace.rule, trace.condition_expression),
                styles,
            );
        }
        write_basis(output, 6, &trace.basis, styles);
    }
}

fn write_help(output: &mut String, evaluation: &Evaluation, styles: Styles) {
    let help = match &evaluation.result.status {
        DecisionStatus::Undefined => Some(
            "add a rule covering this input, or add `?` to the decision result type if no answer is valid".into(),
        ),
        DecisionStatus::Unknown { missing } => {
            Some(format!("provide the missing input: {}", missing.join(", ")))
        }
        DecisionStatus::Conflict { .. } => {
            Some("make the conditions mutually exclusive or add an explicit named override".into())
        }
        DecisionStatus::Resolved { .. } => None,
    };
    if let Some(help) = help {
        output.push('\n');
        write_metadata(output, 4, "help", format_args!("{help}"), styles);
    }
}

fn write_condition_note(
    output: &mut String,
    evaluation: &Evaluation,
    rule_name: &str,
    styles: Styles,
) {
    if let Some(trace) = trace_for_rule(evaluation, rule_name) {
        write_metadata(
            output,
            6,
            "condition",
            format_args!("{} → {}", trace.condition_expression, trace.condition),
            styles,
        );
    }
}

fn trace_for_rule<'a>(evaluation: &'a Evaluation, rule_name: &str) -> Option<&'a RuleTrace> {
    let rule_name = normalize_name(rule_name);
    evaluation
        .rules
        .iter()
        .find(|trace| normalize_name(&trace.rule) == rule_name)
}

fn candidate_location(
    program: &CompiledProgram,
    rule_name: &str,
    decision_name: &str,
) -> (Option<Span>, bool) {
    let Some(rule) = program.rule(rule_name) else {
        return (None, false);
    };
    let decision_name = normalize_name(decision_name);
    match &rule.effect {
        Effect::Decide { decision, span, .. }
            if normalize_name(&decision.value) == decision_name =>
        {
            (Some(*span), true)
        }
        Effect::Decide { .. } | Effect::Override { .. } | Effect::Invalid { .. } => {
            (Some(rule.condition.span), false)
        }
    }
}

fn override_location(program: &CompiledProgram, by: &str, target: &str) -> Option<Span> {
    let rule = program.rule(by)?;
    let target = normalize_name(target);
    match &rule.effect {
        Effect::Override { rule, span } if normalize_name(&rule.value) == target => Some(*span),
        Effect::Override { .. } | Effect::Decide { .. } | Effect::Invalid { .. } => None,
    }
}

fn write_snippet(
    output: &mut String,
    source: &SourceFile,
    span: Span,
    label: &str,
    indent: usize,
    styles: Styles,
) {
    let (line, column) = source.line_col(span.start);
    let text = source.line_text_at(span.start);
    let gutter = line.to_string().len().max(3);
    let source_name = display_source_name(source.name_at(span.start));

    write_indent(output, indent);
    styles.write(
        output,
        LOCATION_STYLE,
        format_args!("--> {source_name}:{line}:{column}"),
    );
    output.push('\n');

    write_indent(output, indent);
    styles.write(output, LOCATION_STYLE, format_args!("{:>gutter$} |", ""));
    output.push('\n');

    write_indent(output, indent);
    styles.write(output, LOCATION_STYLE, format_args!("{line:>gutter$} | "));
    output.push_str(text);
    output.push('\n');

    let selected_width = source
        .text
        .get(span.start..span.end)
        .and_then(|selected| selected.lines().next())
        .map_or(1, |selected| selected.chars().count().max(1));
    let remaining_width = text
        .chars()
        .count()
        .saturating_sub(column.saturating_sub(1))
        .max(1);
    let marker_width = selected_width.min(remaining_width);

    write_indent(output, indent);
    styles.write(
        output,
        LOCATION_STYLE,
        format_args!("{:>gutter$} | {}", "", " ".repeat(column.saturating_sub(1))),
    );
    styles.write(
        output,
        MARKER_STYLE,
        format_args!("{}", "^".repeat(marker_width)),
    );
    let _ = writeln!(output, " {label}");
}

fn write_section(output: &mut String, indent: usize, value: Arguments<'_>, styles: Styles) {
    write_indent(output, indent);
    styles.write(output, SECTION_STYLE, value);
    output.push('\n');
}

fn display_source_name(name: &str) -> Cow<'_, str> {
    let path = Path::new(name);
    if !path.is_absolute() {
        return Cow::Borrowed(name);
    }
    let Ok(current_directory) = std::env::current_dir() else {
        return Cow::Borrowed(name);
    };
    path.strip_prefix(current_directory)
        .ok()
        .and_then(Path::to_str)
        .map_or_else(|| Cow::Borrowed(name), Cow::Borrowed)
}

fn write_basis(output: &mut String, indent: usize, basis: &[FragmentEvidence], styles: Styles) {
    for evidence in basis {
        if evidence.id == evidence.locator {
            write_metadata(
                output,
                indent,
                "basis",
                format_args!("`{}`", evidence.id),
                styles,
            );
        } else {
            write_metadata(
                output,
                indent,
                "basis",
                format_args!("`{}` @ `{}`", evidence.id, evidence.locator),
                styles,
            );
        }
        for (index, line) in evidence.text.trim_end_matches('\n').lines().enumerate() {
            write_metadata(
                output,
                indent,
                if index == 0 { "text" } else { "" },
                format_args!("{line}"),
                styles,
            );
        }
    }
}

fn write_metadata(
    output: &mut String,
    indent: usize,
    label: &str,
    value: Arguments<'_>,
    styles: Styles,
) {
    write_indent(output, indent);
    styles.write(output, LABEL_STYLE, format_args!("{label}"));
    output.push_str(&" ".repeat(METADATA_VALUE_COLUMN.saturating_sub(label.len()).max(2)));
    let _ = output.write_fmt(value);
    output.push('\n');
}

fn write_indent(output: &mut String, indent: usize) {
    output.push_str(&" ".repeat(indent));
}

fn resolved_values(values: &[Value]) -> String {
    match values {
        [] => "[]".to_owned(),
        [value] => value.to_string(),
        values => format!("[{}]", display_values(values)),
    }
}

fn display_values(values: &[Value]) -> String {
    values
        .iter()
        .map(ToString::to_string)
        .collect::<Vec<_>>()
        .join(", ")
}

const fn cardinality_contract(cardinality: Cardinality) -> &'static str {
    match cardinality {
        Cardinality::ExactlyOne => "exactly one distinct value is required",
        Cardinality::ZeroOrOne => "zero or one distinct value is allowed",
        Cardinality::Many => "any number of distinct values is allowed",
    }
}

fn counted(count: usize, singular: &str, plural: &str) -> String {
    if count == 1 {
        format!("1 {singular}")
    } else {
        format!("{count} {plural}")
    }
}