Skip to main content

lemma/evaluation/
explanations.rs

1//! Root explanation type and formatting.
2//!
3//! The root `Explanation` (with `result: OperationResult`) is built once per
4//! requested rule from its narrated arena entry. Nested rule uses are
5//! [`ExplanationNode::RuleRef`] into [`Explanation::rules`]. The tree types
6//! live in `planning::explanation`; `evaluation::narration` builds them from
7//! the filled value table.
8
9use crate::computation::rational::RationalInteger;
10use crate::computation::{OperationResult, VetoType};
11use crate::planning::explanation::{ExplainedRule, ExplainedRuleId};
12use crate::planning::semantics::{LemmaType, RulePath, APPENDED_ROW_LABEL};
13use crate::planning::unit_family::FamilyUnitCatalog;
14use crate::result_value::{
15    rule_result_value_failure_message, rule_result_value_from_literal, RuleResultValue,
16    RuleResultValueFailure,
17};
18use serde::Serialize;
19use std::collections::{HashMap, HashSet};
20use std::sync::Arc;
21
22// Re-export tree types for use within the evaluation module
23pub use crate::planning::explanation::{
24    Cause, ConversionTraceRole, ExplanationNode, SerializedConversionTraceStep,
25};
26
27#[derive(Debug, Clone)]
28pub struct Explanation {
29    pub name: RulePath,
30    pub result: OperationResult,
31    /// Type of [`Self::result`] for measure/ratio rendering (binding unit).
32    pub result_type: Arc<LemmaType>,
33    /// Family catalog needed to build the rule-node [`RuleResultValue`] on serialize.
34    pub(crate) family_units: Arc<FamilyUnitCatalog>,
35    /// Settled reference-scale factors for this rule's result family.
36    pub(crate) runtime_scales: HashMap<String, RationalInteger>,
37    pub body: String,
38    pub causes: Vec<Cause>,
39    pub children: Vec<ExplanationNode>,
40    /// Reachable narrated rules, ids in first-reach order from this root.
41    pub rules: Vec<ExplainedRule>,
42}
43
44#[derive(Serialize)]
45struct ExplanationSer<'a> {
46    #[serde(rename = "type")]
47    kind: &'static str,
48    #[serde(serialize_with = "crate::planning::explanation::serialize_rule_path_as_name")]
49    name: &'a RulePath,
50    #[serde(flatten)]
51    result: RuleResultValue,
52    body: &'a str,
53    #[serde(skip_serializing_if = "<[_]>::is_empty")]
54    causes: &'a [Cause],
55    #[serde(skip_serializing_if = "<[_]>::is_empty")]
56    children: &'a [ExplanationNode],
57    #[serde(skip_serializing_if = "<[_]>::is_empty")]
58    rules: &'a [ExplainedRule],
59}
60
61impl Serialize for Explanation {
62    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
63    where
64        S: serde::Serializer,
65    {
66        ExplanationSer {
67            kind: "rule",
68            name: &self.name,
69            result: explanation_result_value(
70                &self.result,
71                self.result_type.as_ref(),
72                &self.family_units,
73                Some(&self.runtime_scales),
74            ),
75            body: &self.body,
76            causes: self.causes.as_slice(),
77            children: self.children.as_slice(),
78            rules: self.rules.as_slice(),
79        }
80        .serialize(serializer)
81    }
82}
83
84pub(crate) fn format_operation_result(result: &OperationResult, result_type: &LemmaType) -> String {
85    match result {
86        OperationResult::Value(bound) => bound.to_literal().display_value_with_type(result_type),
87        OperationResult::Veto(VetoType::UserDefined { message: None }) => String::new(),
88        OperationResult::Veto(veto) => veto.to_string(),
89    }
90}
91
92/// Build a [`RuleResultValue`] for an explanation node from a settled operation result.
93pub(crate) fn explanation_result_value(
94    result: &OperationResult,
95    lemma_type: &LemmaType,
96    family_units: &FamilyUnitCatalog,
97    runtime_scales: Option<&HashMap<String, RationalInteger>>,
98) -> RuleResultValue {
99    match result {
100        OperationResult::Value(bound) => {
101            match rule_result_value_from_literal(
102                &bound.to_literal(),
103                lemma_type,
104                family_units,
105                runtime_scales,
106            ) {
107                Ok(value) => value,
108                // Same veto message RuleResult attaches; result is veto text, not magnitude.
109                Err(RuleResultValueFailure::DecimalLimit) => RuleResultValue {
110                    result: Some(
111                        rule_result_value_failure_message(RuleResultValueFailure::DecimalLimit)
112                            .to_string(),
113                    ),
114                    ..RuleResultValue::default()
115                },
116                Err(failure) => panic!(
117                    "BUG: settled explanation value failed rule_result_value_from_literal: {}",
118                    rule_result_value_failure_message(failure)
119                ),
120            }
121        }
122        OperationResult::Veto(VetoType::UserDefined { message: None }) => RuleResultValue {
123            result: Some(String::new()),
124            ..RuleResultValue::default()
125        },
126        OperationResult::Veto(veto) => RuleResultValue {
127            result: Some(veto.to_string()),
128            ..RuleResultValue::default()
129        },
130    }
131}
132
133pub fn format_explanation(explanation: &Explanation) -> String {
134    let mut lines = Vec::new();
135    let result_line = explanation_result_value(
136        &explanation.result,
137        explanation.result_type.as_ref(),
138        &explanation.family_units,
139        Some(&explanation.runtime_scales),
140    )
141    .result
142    .expect("BUG: root explanation must carry result");
143    lines.push(format!("{}: {}", explanation.name, result_line));
144    let mut state = FormatState {
145        lines: &mut lines,
146        rules: &explanation.rules,
147        expanded: HashSet::new(),
148        stack: Vec::new(),
149    };
150    state.push_rule_contents(
151        &result_line,
152        &explanation.body,
153        &explanation.body,
154        &explanation.causes,
155        &explanation.children,
156        String::new(),
157    );
158    state.run();
159    lines.join("\n")
160}
161
162#[derive(Copy, Clone)]
163enum Connector {
164    Branch,
165    Last,
166}
167
168enum ConversionSteps {
169    Owned(Vec<SerializedConversionTraceStep>),
170}
171
172impl ConversionSteps {
173    fn as_slice(&self) -> &[SerializedConversionTraceStep] {
174        match self {
175            ConversionSteps::Owned(steps) => steps.as_slice(),
176        }
177    }
178}
179
180/// Visible children of one parent, with tree connectors. `Filter` nodes are
181/// flattened away so matched rows sit directly under the list pipeline.
182struct Siblings<'a> {
183    nodes: Vec<&'a ExplanationNode>,
184    /// Pre-aligned comma headlines for [`ExplanationNode::Row`] entries, keyed by index.
185    row_headlines: std::collections::HashMap<usize, String>,
186}
187
188impl<'a> Siblings<'a> {
189    fn new(nodes: impl Iterator<Item = &'a ExplanationNode>) -> Self {
190        let mut flat = Vec::new();
191        for node in nodes {
192            flatten_visible(node, &mut flat);
193        }
194        let row_headlines = aligned_row_headlines(&flat);
195        Self {
196            nodes: flat,
197            row_headlines,
198        }
199    }
200
201    fn len(&self) -> usize {
202        self.nodes.len()
203    }
204}
205
206fn flatten_visible<'a>(node: &'a ExplanationNode, out: &mut Vec<&'a ExplanationNode>) {
207    let mut pending = vec![node];
208    while let Some(node) = pending.pop() {
209        if is_bare_literal_compose(node) || is_visually_empty_compose(node) {
210            continue;
211        }
212        match node {
213            ExplanationNode::Filter { children, .. } => {
214                for child in children.iter().rev() {
215                    pending.push(child);
216                }
217            }
218            _ => out.push(node),
219        }
220    }
221}
222
223enum Work<'a> {
224    Line {
225        indent: String,
226        connector: Connector,
227        text: String,
228    },
229    RuleBody {
230        id: ExplainedRuleId,
231        result_line: String,
232        indent: String,
233    },
234    Nodes {
235        siblings: Siblings<'a>,
236        parent_body: Option<&'a str>,
237        indent: String,
238        next: usize,
239        elide_list_commands: bool,
240    },
241    CauseChildren {
242        children: Vec<&'a ExplanationNode>,
243        /// Cause line already printed. A RuleRef that repeats it is expanded
244        /// without a second header.
245        cause_line: String,
246        indent: String,
247        next: usize,
248    },
249    Conversion {
250        steps: ConversionSteps,
251        siblings: Siblings<'a>,
252        indent: String,
253        next: usize,
254    },
255}
256
257struct FormatState<'a> {
258    lines: &'a mut Vec<String>,
259    rules: &'a [ExplainedRule],
260    expanded: HashSet<ExplainedRuleId>,
261    stack: Vec<Work<'a>>,
262}
263
264impl<'a> FormatState<'a> {
265    fn push_line(&mut self, indent: &str, connector: Connector, text: &str) {
266        self.lines
267            .push(format!("{indent}{} {text}", connector_str(connector)));
268    }
269
270    fn child_indent(indent: &str, connector: Connector) -> String {
271        match connector {
272            Connector::Branch => format!("{indent}│  "),
273            Connector::Last => format!("{indent}   "),
274        }
275    }
276
277    fn rule_by_id(&self, id: ExplainedRuleId) -> &'a ExplainedRule {
278        self.rules
279            .iter()
280            .find(|rule| rule.id == id)
281            .unwrap_or_else(|| panic!("BUG: explanation missing rules entry for id {}", id.0))
282    }
283
284    fn push_rule_contents(
285        &mut self,
286        result_line: &str,
287        body: &'a str,
288        shown_body: &'a str,
289        causes: &'a [Cause],
290        children: &'a [ExplanationNode],
291        indent: String,
292    ) {
293        // Bare data-path rule bodies (`rule guardian: has_ward`) already appear as the
294        // sole Data child (`has_ward: true`); printing the path again nests a duplicate.
295        let body_restated_by_sole_data = matches!(
296            children,
297            [ExplanationNode::Data { name, .. }] if name.input_key() == body
298        );
299        let body_shown = !body.is_empty() && body != result_line && !body_restated_by_sole_data;
300        let total = causes.len() + usize::from(body_shown);
301        // LIFO: push later output first so first cause prints first.
302        if body_shown {
303            let child_indent = Self::child_indent(&indent, Connector::Last);
304            self.stack.push(Work::Nodes {
305                siblings: Siblings::new(children.iter()),
306                parent_body: Some(body),
307                indent: child_indent,
308                next: 0,
309                elide_list_commands: false,
310            });
311            self.stack.push(Work::Line {
312                indent: indent.clone(),
313                connector: Connector::Last,
314                text: shown_body.to_string(),
315            });
316        } else if !children.is_empty() {
317            self.stack.push(Work::Nodes {
318                siblings: Siblings::new(children.iter()),
319                parent_body: None,
320                indent: indent.clone(),
321                next: 0,
322                elide_list_commands: false,
323            });
324        }
325        for (i, cause) in causes.iter().enumerate().rev() {
326            let connector = if i + 1 == total {
327                Connector::Last
328            } else {
329                Connector::Branch
330            };
331            let value = cause.value.as_str();
332            let line = if value == "true" {
333                cause.condition.clone()
334            } else {
335                format!("{} is {}", cause.condition, value)
336            };
337            let visible: Vec<&'a ExplanationNode> = cause
338                .children
339                .iter()
340                .filter(|node| !is_bare_literal_compose(node))
341                .filter(|node| !data_restates_true_cause_line(node, value, &line))
342                .collect();
343            let child_indent = Self::child_indent(&indent, connector);
344            self.stack.push(Work::CauseChildren {
345                children: visible,
346                cause_line: line.clone(),
347                indent: child_indent,
348                next: 0,
349            });
350            self.stack.push(Work::Line {
351                indent: indent.clone(),
352                connector,
353                text: line,
354            });
355        }
356    }
357
358    fn run(&mut self) {
359        while let Some(work) = self.stack.pop() {
360            match work {
361                Work::Line {
362                    indent,
363                    connector,
364                    text,
365                } => self.push_line(&indent, connector, &text),
366                Work::RuleBody {
367                    id,
368                    result_line,
369                    indent,
370                } => {
371                    let rule = self.rule_by_id(id);
372                    self.push_rule_contents(
373                        &result_line,
374                        rule.body.as_str(),
375                        body_for_display(rule),
376                        rule.causes.as_slice(),
377                        rule.children.as_slice(),
378                        indent,
379                    );
380                }
381                Work::Nodes {
382                    siblings,
383                    parent_body,
384                    indent,
385                    next,
386                    elide_list_commands,
387                } => self.step_nodes(siblings, parent_body, indent, next, elide_list_commands),
388                Work::CauseChildren {
389                    children,
390                    cause_line,
391                    indent,
392                    next,
393                } => self.step_cause_children(children, cause_line, indent, next),
394                Work::Conversion {
395                    steps,
396                    siblings,
397                    indent,
398                    next,
399                } => self.step_conversion(steps, siblings, indent, next),
400            }
401        }
402    }
403
404    fn step_nodes(
405        &mut self,
406        siblings: Siblings<'a>,
407        parent_body: Option<&'a str>,
408        indent: String,
409        next: usize,
410        elide_list_commands: bool,
411    ) {
412        if next >= siblings.len() {
413            return;
414        }
415        let connector = if next + 1 == siblings.len() {
416            Connector::Last
417        } else {
418            Connector::Branch
419        };
420        let node = siblings.nodes[next];
421        let row_headline = siblings.row_headlines.get(&next).cloned();
422        self.stack.push(Work::Nodes {
423            siblings,
424            parent_body,
425            indent: indent.clone(),
426            next: next + 1,
427            elide_list_commands,
428        });
429        self.emit_node(
430            node,
431            connector,
432            parent_body,
433            indent,
434            elide_list_commands,
435            row_headline,
436        );
437    }
438
439    fn step_cause_children(
440        &mut self,
441        children: Vec<&'a ExplanationNode>,
442        cause_line: String,
443        indent: String,
444        next: usize,
445    ) {
446        if next >= children.len() {
447            return;
448        }
449        let node = children[next];
450        let last = next + 1 == children.len();
451        self.stack.push(Work::CauseChildren {
452            children,
453            cause_line: cause_line.clone(),
454            indent: indent.clone(),
455            next: next + 1,
456        });
457        if let Some((id, result_line)) = rule_ref_restating_cause(node, &cause_line) {
458            if self.expanded.insert(id) {
459                self.stack.push(Work::RuleBody {
460                    id,
461                    result_line,
462                    indent,
463                });
464            }
465            return;
466        }
467        let connector = if last {
468            Connector::Last
469        } else {
470            Connector::Branch
471        };
472        self.emit_node(node, connector, None, indent, false, None);
473    }
474
475    fn step_conversion(
476        &mut self,
477        steps: ConversionSteps,
478        siblings: Siblings<'a>,
479        indent: String,
480        next: usize,
481    ) {
482        let sibling_len = siblings.len();
483        let step_len = steps.as_slice().len();
484        let total = step_len + sibling_len;
485        if next >= total {
486            return;
487        }
488        let connector = if next + 1 == total {
489            Connector::Last
490        } else {
491            Connector::Branch
492        };
493        if next < sibling_len {
494            let node = siblings.nodes[next];
495            let row_headline = siblings.row_headlines.get(&next).cloned();
496            self.stack.push(Work::Conversion {
497                steps,
498                siblings,
499                indent: indent.clone(),
500                next: next + 1,
501            });
502            self.emit_node(node, connector, None, indent, false, row_headline);
503            return;
504        }
505        let step_index = next - sibling_len;
506        let text = steps.as_slice()[step_index].text.clone();
507        self.stack.push(Work::Conversion {
508            steps,
509            siblings,
510            indent: indent.clone(),
511            next: next + 1,
512        });
513        self.push_line(&indent, connector, &text);
514    }
515
516    fn emit_node(
517        &mut self,
518        node: &'a ExplanationNode,
519        connector: Connector,
520        parent_body: Option<&'a str>,
521        indent: String,
522        elide_list_commands: bool,
523        row_headline: Option<String>,
524    ) {
525        match node {
526            ExplanationNode::RuleRef { id, name, result } => {
527                let result_str = display_result(result);
528                if self.expanded.insert(*id) {
529                    self.push_line(&indent, connector, &format!("{name}: {result_str}"));
530                    self.stack.push(Work::RuleBody {
531                        id: *id,
532                        result_line: result_str.clone(),
533                        indent: Self::child_indent(&indent, connector),
534                    });
535                } else {
536                    self.push_line(
537                        &indent,
538                        connector,
539                        &format!("{name}: {result_str} (see above)"),
540                    );
541                }
542            }
543            ExplanationNode::Compose {
544                expression,
545                operands,
546                result: _,
547                ..
548            } => {
549                let siblings = Siblings::new(operands.iter());
550                if parent_body.is_some_and(|body| body == expression.as_str()) {
551                    self.stack.push(Work::Nodes {
552                        siblings,
553                        parent_body: None,
554                        indent,
555                        next: 0,
556                        elide_list_commands,
557                    });
558                } else {
559                    self.push_line(&indent, connector, expression);
560                    let child_indent = Self::child_indent(&indent, connector);
561                    self.stack.push(Work::Nodes {
562                        siblings,
563                        parent_body: None,
564                        indent: child_indent,
565                        next: 0,
566                        elide_list_commands,
567                    });
568                }
569            }
570            ExplanationNode::ListCommand {
571                expression,
572                operands,
573                result: _,
574                ..
575            } => {
576                let elide = elide_list_commands
577                    || parent_body.is_some_and(|body| body == expression.as_str());
578                if elide {
579                    self.stack.push(Work::Nodes {
580                        siblings: Siblings::new(operands.iter()),
581                        parent_body: None,
582                        indent,
583                        next: 0,
584                        elide_list_commands: true,
585                    });
586                } else {
587                    self.push_line(&indent, connector, expression);
588                    let child_indent = Self::child_indent(&indent, connector);
589                    self.stack.push(Work::Nodes {
590                        siblings: Siblings::new(operands.iter()),
591                        parent_body: None,
592                        indent: child_indent,
593                        next: 0,
594                        elide_list_commands: true,
595                    });
596                }
597            }
598            ExplanationNode::Data { name, result } => {
599                let result_str = result
600                    .result
601                    .as_deref()
602                    .expect("BUG: ExplanationNode::Data.result.result not filled by eval");
603                if name.data.is_empty() {
604                    self.push_line(&indent, connector, result_str);
605                } else {
606                    self.push_line(&indent, connector, &format!("{name}: {result_str}"));
607                }
608            }
609            ExplanationNode::DataUnused { name } => {
610                self.push_line(&indent, connector, &name.to_string());
611            }
612            ExplanationNode::Conversion {
613                expression,
614                steps,
615                operands,
616                result: _,
617            } => {
618                let expression_is_parent_body =
619                    parent_body.is_some_and(|body| body == expression.as_str());
620                let rule_steps: Vec<SerializedConversionTraceStep> = steps
621                    .iter()
622                    .filter(|step| !matches!(step.role, ConversionTraceRole::Outcome))
623                    .cloned()
624                    .collect();
625                // Rule 2: when the single operand is a Compose, skip the compose line
626                // (its expression is already on this conversion line) and promote the
627                // compose's operands to direct children.
628                let siblings = if let [ExplanationNode::Compose {
629                    operands: compose_operands,
630                    ..
631                }] = operands.as_slice()
632                {
633                    Siblings::new(compose_operands.iter())
634                } else {
635                    Siblings::new(operands.iter())
636                };
637                if expression_is_parent_body {
638                    self.stack.push(Work::Conversion {
639                        steps: ConversionSteps::Owned(rule_steps),
640                        siblings,
641                        indent,
642                        next: 0,
643                    });
644                } else {
645                    self.push_line(&indent, connector, expression);
646                    let child_indent = Self::child_indent(&indent, connector);
647                    self.stack.push(Work::Conversion {
648                        steps: ConversionSteps::Owned(rule_steps),
649                        siblings,
650                        indent: child_indent,
651                        next: 0,
652                    });
653                }
654            }
655            ExplanationNode::Veto { message } => {
656                let text = match message.as_deref() {
657                    Some(msg) if !msg.is_empty() => format!("veto \"{msg}\""),
658                    _ => "veto".to_string(),
659                };
660                self.push_line(&indent, connector, &text);
661            }
662            ExplanationNode::Row {
663                number,
664                appended,
665                key,
666                fields,
667            } => {
668                let tree_fields = row_tree_fields(key, fields);
669                // Numbered row whose only field is a RuleRef: `2. bonus: 950 eur`.
670                if key.is_empty()
671                    && row_comma_columns(key, fields).is_empty()
672                    && tree_fields.len() == 1
673                {
674                    if let ExplanationNode::RuleRef { id, name, result } = tree_fields[0] {
675                        let result_str = display_result(result);
676                        let prefix = if *appended {
677                            format!("appended {number}.")
678                        } else {
679                            format!("{number}.")
680                        };
681                        let child_indent = Self::child_indent(&indent, connector);
682                        if self.expanded.insert(*id) {
683                            self.push_line(
684                                &indent,
685                                connector,
686                                &format!("{prefix} {name}: {result_str}"),
687                            );
688                            self.stack.push(Work::RuleBody {
689                                id: *id,
690                                result_line: result_str.clone(),
691                                indent: child_indent,
692                            });
693                        } else {
694                            self.push_line(
695                                &indent,
696                                connector,
697                                &format!("{prefix} {name}: {result_str} (see above)"),
698                            );
699                        }
700                        return;
701                    }
702                }
703                let headline = row_headline
704                    .unwrap_or_else(|| row_headline_for(*number, *appended, key, fields));
705                self.push_line(&indent, connector, &headline);
706                if !tree_fields.is_empty() {
707                    let child_indent = Self::child_indent(&indent, connector);
708                    self.stack.push(Work::Nodes {
709                        siblings: Siblings::new(tree_fields.into_iter()),
710                        parent_body: None,
711                        indent: child_indent,
712                        next: 0,
713                        elide_list_commands,
714                    });
715                }
716            }
717            ExplanationNode::Filter { .. } => {
718                unreachable!("BUG: Filter nodes are flattened in Siblings::new");
719            }
720        }
721    }
722}
723
724/// Number of rows when `value` is a list of inline `-> with` rows. Such a row has no name
725/// beyond its position, so enumerating them says nothing. A row named by its instance
726/// path, and every value-list item (which also carries a typed field), is left alone.
727fn instance_list_len(value: &RuleResultValue) -> Option<usize> {
728    let rows = value.list.as_deref().filter(|rows| !rows.is_empty())?;
729    rows.iter()
730        .all(|row| {
731            row.result
732                .as_deref()
733                .is_some_and(|text| text.starts_with(APPENDED_ROW_LABEL))
734                && row.number.is_none()
735                && row.boolean.is_none()
736                && row.text.is_none()
737                && row.measure.is_none()
738                && row.ratio.is_none()
739                && row.date.is_none()
740                && row.time.is_none()
741                && row.calendar.is_none()
742                && row.range.is_none()
743        })
744        .then_some(rows.len())
745}
746
747/// Result line of a rule reference. A list of instance rows is counted, not enumerated.
748fn display_result(value: &RuleResultValue) -> String {
749    match instance_list_len(value) {
750        Some(1) => "list of 1 row".to_string(),
751        Some(count) => format!("list of {count} rows"),
752        None => value
753            .result
754            .clone()
755            .expect("BUG: ExplanationNode::RuleRef.result.result not filled by eval"),
756    }
757}
758
759/// Body of a rule as the tree prints it. A list definition stops before its `-> with` rows.
760fn body_for_display(rule: &ExplainedRule) -> &str {
761    let body = rule.body.as_str();
762    if instance_list_len(&rule.result).is_none() {
763        return body;
764    }
765    match body.find(" -> with ") {
766        Some(end) => &body[..end],
767        None => body,
768    }
769}
770
771fn connector_str(connector: Connector) -> &'static str {
772    match connector {
773        Connector::Branch => "├─",
774        Connector::Last => "└─",
775    }
776}
777
778fn aligned_row_headlines(nodes: &[&ExplanationNode]) -> std::collections::HashMap<usize, String> {
779    let mut out = std::collections::HashMap::new();
780    let mut index = 0;
781    while index < nodes.len() {
782        if !matches!(nodes[index], ExplanationNode::Row { .. }) {
783            index += 1;
784            continue;
785        }
786        let start = index;
787        while index < nodes.len() && matches!(nodes[index], ExplanationNode::Row { .. }) {
788            index += 1;
789        }
790        let rows = &nodes[start..index];
791        let branched = rows.iter().any(|node| {
792            let ExplanationNode::Row { key, fields, .. } = node else {
793                unreachable!("BUG: row run contains non-Row");
794            };
795            !row_tree_fields(key, fields).is_empty()
796        });
797        let columns: Vec<Vec<RowColumn>> = rows
798            .iter()
799            .map(|node| {
800                let ExplanationNode::Row { key, fields, .. } = node else {
801                    unreachable!("BUG: row run contains non-Row");
802                };
803                row_comma_columns(key, fields)
804            })
805            .collect();
806        let col_widths = if branched {
807            Vec::new()
808        } else {
809            let width = columns.iter().map(|cols| cols.len()).max().unwrap_or(0);
810            let mut widths = vec![0; width];
811            for cols in &columns {
812                for (i, column) in cols.iter().enumerate() {
813                    widths[i] = widths[i].max(column.text.len());
814                }
815            }
816            widths
817        };
818        for (offset, (node, cols)) in rows.iter().zip(columns.iter()).enumerate() {
819            let ExplanationNode::Row {
820                number, appended, ..
821            } = node
822            else {
823                unreachable!("BUG: row run contains non-Row");
824            };
825            let line = if branched {
826                cols.iter()
827                    .map(|column| column.text.as_str())
828                    .collect::<Vec<_>>()
829                    .join(", ")
830            } else {
831                let mut line = String::new();
832                for (i, column) in cols.iter().enumerate() {
833                    let text = &column.text;
834                    if i + 1 == cols.len() {
835                        line.push_str(text);
836                    } else {
837                        line.push_str(text);
838                        line.push(',');
839                        let pad = col_widths[i].saturating_sub(text.len()) + 1;
840                        line.push_str(&" ".repeat(pad));
841                    }
842                }
843                line
844            };
845            let all_appended = rows
846                .iter()
847                .all(|row| matches!(row, ExplanationNode::Row { appended: true, .. }));
848            let headline = if key_is_empty(node) && !all_appended {
849                let prefix = if *appended {
850                    format!("appended {number}.")
851                } else {
852                    format!("{number}.")
853                };
854                if line.is_empty() {
855                    prefix
856                } else {
857                    format!("{prefix} {line}")
858                }
859            } else {
860                line
861            };
862            out.insert(start + offset, headline);
863        }
864    }
865    out
866}
867
868fn key_is_empty(node: &ExplanationNode) -> bool {
869    matches!(node, ExplanationNode::Row { key, .. } if key.is_empty())
870}
871
872fn row_headline_for(
873    number: usize,
874    appended: bool,
875    key: &[ExplanationNode],
876    fields: &[ExplanationNode],
877) -> String {
878    let cols = row_comma_columns(key, fields);
879    let comma = cols
880        .iter()
881        .map(|column| column.text.as_str())
882        .collect::<Vec<_>>()
883        .join(", ");
884    if key.is_empty() {
885        let prefix = if appended {
886            format!("appended {number}.")
887        } else {
888            format!("{number}.")
889        };
890        if comma.is_empty() {
891            prefix
892        } else {
893            format!("{prefix} {comma}")
894        }
895    } else {
896        comma
897    }
898}
899
900/// One comma column of a row line.
901struct RowColumn {
902    name: String,
903    text: String,
904}
905
906fn row_comma_columns(key: &[ExplanationNode], fields: &[ExplanationNode]) -> Vec<RowColumn> {
907    let mut cols = Vec::new();
908    let mut seen = std::collections::HashSet::new();
909    for node in key {
910        let column = row_column(node);
911        seen.insert(column.name.clone());
912        cols.push(column);
913    }
914    for node in fields {
915        if !is_comma_field(node) {
916            continue;
917        }
918        let column = row_column(node);
919        if seen.insert(column.name.clone()) {
920            cols.push(column);
921        }
922    }
923    cols
924}
925
926fn row_tree_fields<'a>(
927    key: &'a [ExplanationNode],
928    fields: &'a [ExplanationNode],
929) -> Vec<&'a ExplanationNode> {
930    let _ = key;
931    fields.iter().filter(|node| !is_comma_field(node)).collect()
932}
933
934fn is_comma_field(node: &ExplanationNode) -> bool {
935    matches!(
936        node,
937        ExplanationNode::Data { .. }
938            | ExplanationNode::DataUnused { .. }
939            | ExplanationNode::Veto { .. }
940    )
941}
942
943fn row_column(node: &ExplanationNode) -> RowColumn {
944    match node {
945        ExplanationNode::Data { name, result } => {
946            let value = result
947                .result
948                .as_deref()
949                .expect("BUG: row Data must carry result");
950            RowColumn {
951                name: name.to_string(),
952                text: format!("{name}: {value}"),
953            }
954        }
955        ExplanationNode::DataUnused { name } => RowColumn {
956            name: name.to_string(),
957            text: name.to_string(),
958        },
959        ExplanationNode::Veto { message } => {
960            let value = match message.as_deref() {
961                Some(msg) if !msg.is_empty() => format!("veto \"{msg}\""),
962                _ => "veto".to_string(),
963            };
964            RowColumn {
965                name: String::new(),
966                text: format!(": {value}"),
967            }
968        }
969        other => panic!("BUG: comma column node is {other:?}"),
970    }
971}
972
973/// Bare literal compose: expression text already names it; ASCII omits the node.
974fn is_bare_literal_compose(node: &ExplanationNode) -> bool {
975    matches!(node, ExplanationNode::Compose { operands, .. } if operands.is_empty())
976}
977
978/// Visually empty compose: a `Compose` whose every operand is itself omitted by
979/// the formatter (bare literal, or recursively visually empty). Its line would
980/// only restate a sub-expression already shown on the parent and Rule 7 strips
981/// its value, so it is dropped from siblings before tree connectors are assigned.
982fn is_visually_empty_compose(node: &ExplanationNode) -> bool {
983    let ExplanationNode::Compose { operands, .. } = node else {
984        return false;
985    };
986    operands.iter().all(operand_omitted_from_tree)
987}
988
989fn operand_omitted_from_tree(node: &ExplanationNode) -> bool {
990    if is_bare_literal_compose(node) {
991        return true;
992    }
993    is_visually_empty_compose(node)
994}
995
996/// RuleRef whose `name: result` line is the cause line already printed.
997fn rule_ref_restating_cause(
998    node: &ExplanationNode,
999    cause_line: &str,
1000) -> Option<(ExplainedRuleId, String)> {
1001    let ExplanationNode::RuleRef { id, name, result } = node else {
1002        return None;
1003    };
1004    let result_str = result
1005        .result
1006        .as_deref()
1007        .expect("BUG: ExplanationNode::RuleRef.result.result not filled by eval");
1008    if format!("{name}: {result_str}") == cause_line {
1009        Some((*id, result_str.to_string()))
1010    } else {
1011        None
1012    }
1013}
1014
1015/// `code is NL` already states the binding; ASCII skips child `code: NL`.
1016/// Flipped / inequality cause lines do not match `{key} is {result}`.
1017fn data_restates_true_cause_line(node: &ExplanationNode, value: &str, line: &str) -> bool {
1018    if value != "true" {
1019        return false;
1020    }
1021    match node {
1022        ExplanationNode::Data {
1023            name,
1024            result: node_result,
1025        } => {
1026            let result_str = node_result
1027                .result
1028                .as_deref()
1029                .expect("BUG: Data node must carry result");
1030            line == format!("{} is {result_str}", name.input_key())
1031        }
1032        _ => false,
1033    }
1034}