Skip to main content

lemma/formatting/
mod.rs

1//! Lemma source code formatting.
2//!
3//! Formats parsed specs into canonical Lemma source text. Uses `AsLemmaSource`
4//! and `Expression::Display` for syntax; this module handles layout only.
5//! Canonical source includes ASCII-lowercase logical identifier names.
6
7pub(crate) mod expression;
8
9use crate::parsing::ast::{
10    AsLemmaSource, Constraint, ContinuationShape, DataValue, Expression, ExpressionKind, LemmaData,
11    LemmaRule, LemmaSpec, ListCommand, ListWithRows, TypeConstraintCommand,
12};
13use crate::parsing::{parse, ParseResult};
14use crate::{Error, ResourceLimits};
15use expression::{display_wrapped, Syntax};
16
17/// Soft line length limit for prose (`unless`, expression soft-breaks, comma-value lists).
18/// Aligned instance-row tables may exceed this so each `-> with` stays on one padded line.
19/// 56 has been chosen to fit on an average mobile screen with an 11pt font.
20pub const MAX_COLS: usize = 56;
21
22// =============================================================================
23// Public entry points
24// =============================================================================
25
26/// Format a sequence of parsed specs into canonical Lemma source.
27///
28/// specs are separated by two blank lines.
29/// The result ends with a single newline.
30#[must_use]
31pub fn format_specs(specs: &[LemmaSpec]) -> String {
32    let refs: Vec<&LemmaSpec> = specs.iter().collect();
33    format_spec_refs(&refs)
34}
35
36/// Like [`format_specs`] for borrowed specs (e.g. from Context storage).
37#[must_use]
38pub fn format_spec_refs(specs: &[&LemmaSpec]) -> String {
39    let mut out = String::new();
40    for (index, spec) in specs.iter().enumerate() {
41        if index > 0 {
42            out.push_str("\n\n");
43        }
44        out.push_str(&format_spec(spec, MAX_COLS));
45    }
46    if !out.ends_with('\n') {
47        out.push('\n');
48    }
49    out
50}
51
52/// Format a [`ParseResult`] (repository groups + specs) into canonical Lemma source.
53#[must_use]
54pub fn format_parse_result(result: &ParseResult) -> String {
55    let mut blocks: Vec<String> = Vec::new();
56    for (repo, specs) in &result.repositories {
57        let mut prefix = String::new();
58        if let Some(name) = repo.name.as_deref() {
59            prefix.push_str("repo ");
60            prefix.push_str(name);
61            prefix.push_str("\n\n");
62        }
63        if specs.is_empty() {
64            if !prefix.is_empty() {
65                blocks.push(prefix);
66            }
67            continue;
68        }
69        let body = format_specs(specs.as_slice());
70        if prefix.is_empty() {
71            blocks.push(body);
72        } else {
73            prefix.push_str(&body);
74            blocks.push(prefix);
75        }
76    }
77    let mut out = blocks.join("\n\n");
78    if !out.ends_with('\n') {
79        out.push('\n');
80    }
81    out
82}
83
84/// Parse a source string and format it to canonical Lemma source.
85///
86/// Returns an error if the source does not parse.
87pub fn format_source(
88    source: &str,
89    source_type: crate::parsing::source::SourceType,
90) -> Result<String, Error> {
91    let limits = ResourceLimits::default();
92    let result = parse(source, source_type, &limits)?;
93    Ok(format_parse_result(&result))
94}
95
96// =============================================================================
97// Spec
98// =============================================================================
99
100pub(crate) fn format_spec(spec: &LemmaSpec, max_cols: usize) -> String {
101    let mut out = String::new();
102    out.push_str("spec ");
103    out.push_str(&spec.name);
104    if let crate::parsing::ast::EffectiveDate::DateTimeValue(ref af) = spec.effective_from {
105        out.push(' ');
106        out.push_str(&af.to_string());
107    }
108    out.push('\n');
109
110    if let Some(ref commentary) = spec.commentary {
111        out.push_str("\"\"\"\n");
112        out.push_str(commentary);
113        out.push_str("\n\"\"\"\n");
114    }
115
116    for meta in &spec.meta_fields {
117        out.push_str(&format!("{meta}\n"));
118    }
119
120    if !spec.data.is_empty() {
121        format_sorted_data(&spec.data, &mut out, "", max_cols);
122    }
123
124    if !spec.rules.is_empty() {
125        out.push('\n');
126        for (index, rule) in spec.rules.iter().enumerate() {
127            if index > 0 {
128                out.push('\n');
129            }
130            let rule_text = format_rule(rule, max_cols);
131            for line in rule_text.lines() {
132                out.push_str(line);
133                out.push('\n');
134            }
135        }
136    }
137
138    out
139}
140
141// =============================================================================
142// Data
143// =============================================================================
144
145/// Two spaces after `line_prefix` for each `-> ...` constraint line under `data ...: ...`.
146const DATA_CONSTRAINT_INDENT: &str = "  ";
147
148fn data_constraints_nonempty(constraints: &Option<Vec<Constraint>>) -> bool {
149    constraints.as_ref().is_some_and(|v| !v.is_empty())
150}
151
152fn data_value_has_arrow_constraints(value: &DataValue) -> bool {
153    match value {
154        DataValue::Definition {
155            constraints,
156            list: Some(list),
157            ..
158        } => {
159            data_constraints_nonempty(constraints)
160                || list.key.is_some()
161                || !list.rows.is_empty()
162                || !list.option_rows.is_empty()
163        }
164        DataValue::Definition { constraints, .. } => data_constraints_nonempty(constraints),
165        DataValue::Import { .. } | DataValue::ImportList { .. } | DataValue::OwnRows { .. } => {
166            false
167        }
168    }
169}
170
171fn format_with_rhs(rhs: &crate::parsing::ast::WithRhs) -> String {
172    match rhs {
173        crate::parsing::ast::WithRhs::Literal(v) => format!("{}", AsLemmaSource(v)),
174        crate::parsing::ast::WithRhs::Reference { target } => target.to_string(),
175    }
176}
177
178fn format_uses_literal_binding(value: &crate::parsing::ast::Value) -> String {
179    format!("{}", AsLemmaSource(value))
180}
181
182fn data_value_rhs_for_spec_body(
183    value: &DataValue,
184    continuation_prefix: &str,
185    max_cols: usize,
186) -> String {
187    match value {
188        DataValue::Definition {
189            base,
190            constraints,
191            value,
192            list: Some(list),
193        } => {
194            let head: String = match base.as_ref() {
195                Some(b) => format!("{}", b),
196                None => match value {
197                    Some(v) => format!("{}", AsLemmaSource(v)),
198                    None => String::new(),
199                },
200            };
201            let mut out = head;
202            if data_constraints_nonempty(constraints) {
203                let cs = constraints
204                    .as_ref()
205                    .expect("BUG: constraints checked above");
206                for row in cs {
207                    out.push('\n');
208                    out.push_str(&format_constraint_block(
209                        &row.command,
210                        &row.args,
211                        continuation_prefix,
212                        max_cols,
213                    ));
214                }
215            }
216            out.push_str(&format_uses_list_commands(
217                list,
218                continuation_prefix,
219                max_cols,
220            ));
221            out
222        }
223        DataValue::Definition {
224            base,
225            constraints,
226            value,
227            list: None,
228        } if data_constraints_nonempty(constraints) => {
229            let cs = constraints
230                .as_ref()
231                .expect("BUG: constraints checked above");
232            let head: String = if base.is_none() {
233                match value {
234                    Some(v) => format!("{}", AsLemmaSource(v)),
235                    None => String::new(),
236                }
237            } else {
238                match base.as_ref() {
239                    Some(b) => format!("{}", b),
240                    None => String::new(),
241                }
242            };
243            let mut out = head;
244            for row in cs {
245                out.push('\n');
246                out.push_str(&format_constraint_block(
247                    &row.command,
248                    &row.args,
249                    continuation_prefix,
250                    max_cols,
251                ));
252            }
253            out
254        }
255        DataValue::Definition { .. } => format!("{}", AsLemmaSource(value)),
256        DataValue::Import { .. } | DataValue::ImportList { .. } | DataValue::OwnRows { .. } => {
257            unreachable!("BUG: data row right-hand side requested for an import")
258        }
259    }
260}
261
262/// Soft-wrap a comma-separated item list after `first_line_prefix`.
263///
264/// Overflowing lines end with a trailing comma; continuations start at
265/// `continuation_prefix` plus four spaces.
266fn format_comma_items_wrapped(
267    first_line_prefix: &str,
268    items: &[String],
269    continuation_prefix: &str,
270    max_cols: usize,
271) -> String {
272    let first = items
273        .first()
274        .expect("BUG: comma wrap requires at least one item");
275    let wrap_indent = format!("{continuation_prefix}    ");
276    let mut lines: Vec<String> = Vec::new();
277    let mut current = format!("{first_line_prefix}{first}");
278    for item in items.iter().skip(1) {
279        let candidate = format!("{current}, {item}");
280        if candidate.len() <= max_cols {
281            current = candidate;
282        } else {
283            current.push(',');
284            lines.push(current);
285            current = format!("{wrap_indent}{item}");
286        }
287    }
288    lines.push(current);
289    lines.join("\n")
290}
291
292fn format_constraint_block(
293    command: &TypeConstraintCommand,
294    args: &[crate::parsing::ast::CommandArg],
295    continuation_prefix: &str,
296    max_cols: usize,
297) -> String {
298    if command.continuation_shape() != ContinuationShape::CommaSeparated || args.len() < 2 {
299        return format!(
300            "{}-> {}",
301            continuation_prefix,
302            crate::parsing::ast::format_constraint_as_source(command, args)
303        );
304    }
305    let items: Vec<String> = args
306        .iter()
307        .map(|arg| format!("{}", AsLemmaSource(arg)))
308        .collect();
309    format_comma_items_wrapped(
310        &format!("{continuation_prefix}-> {command} "),
311        &items,
312        continuation_prefix,
313        max_cols,
314    )
315}
316
317/// `data reference:` then `gap` spaces, then `rhs`.
318fn push_data_line(out: &mut String, line_prefix: &str, reference: &str, gap: usize, rhs: &str) {
319    out.push_str(line_prefix);
320    out.push_str("data ");
321    out.push_str(reference);
322    out.push(':');
323    out.push_str(&" ".repeat(gap));
324    out.push_str(rhs);
325    out.push('\n');
326}
327
328/// A run of single-line rows aligns its right-hand sides; a multi-line row stands alone.
329fn emit_data_row_group(rows: &[&LemmaData], line_prefix: &str, max_cols: usize, out: &mut String) {
330    let continuation = format!("{line_prefix}{DATA_CONSTRAINT_INDENT}");
331    let formatted: Vec<(String, String)> = rows
332        .iter()
333        .map(|row| {
334            (
335                row.reference.to_string(),
336                data_value_rhs_for_spec_body(&row.value, &continuation, max_cols),
337            )
338        })
339        .collect();
340    let mut i = 0;
341    while i < rows.len() {
342        let mut run_end = i;
343        while run_end < rows.len() && !formatted[run_end].1.contains('\n') {
344            run_end += 1;
345        }
346        if run_end == i {
347            let (reference, rhs) = &formatted[i];
348            push_data_line(out, line_prefix, reference, 1, rhs);
349            if data_value_has_arrow_constraints(&rows[i].value) && i + 1 < rows.len() {
350                out.push('\n');
351            }
352            i += 1;
353            continue;
354        }
355        let width = formatted[i..run_end]
356            .iter()
357            .map(|(reference, _)| reference.len())
358            .max()
359            .expect("BUG: non-empty run");
360        for (reference, rhs) in &formatted[i..run_end] {
361            push_data_line(
362                out,
363                line_prefix,
364                reference,
365                1 + width - reference.len(),
366                rhs,
367            );
368        }
369        i = run_end;
370    }
371}
372
373fn format_import_header(data: &LemmaData) -> String {
374    let alias = &data.reference.name;
375    let (spec_ref, global) = match &data.value {
376        DataValue::Import {
377            spec_ref, global, ..
378        } => (spec_ref, *global),
379        DataValue::OwnRows { spec_ref, .. } => (spec_ref, false),
380        DataValue::ImportList { .. } | DataValue::Definition { .. } => {
381            unreachable!("BUG: format_import_header called on non-Import data")
382        }
383    };
384    let keyword = if global { "uses global" } else { "uses" };
385    let spec_name = &spec_ref.name;
386    if alias == spec_name {
387        format!("{keyword} {spec_ref}")
388    } else {
389        format!("{keyword} {alias}: {spec_ref}")
390    }
391}
392
393/// `name: value` strings of one inline row, before alignment.
394fn uses_row_fields(bindings: &[crate::parsing::ast::RowBinding]) -> Vec<(String, String)> {
395    bindings
396        .iter()
397        .map(|binding| (binding.path.to_string(), format_with_rhs(&binding.rhs)))
398        .collect()
399}
400
401/// Per-column width when every row names the same fields in the same order; otherwise empty.
402fn aligned_column_widths(field_rows: &[Vec<(String, String)>]) -> Vec<usize> {
403    let Some(first) = field_rows.first() else {
404        return Vec::new();
405    };
406    let names: Vec<&str> = first.iter().map(|(name, _)| name.as_str()).collect();
407    let aligned = field_rows.iter().all(|row| {
408        row.len() == names.len()
409            && row
410                .iter()
411                .zip(names.iter())
412                .all(|((name, _), shared)| name == shared)
413    });
414    if !aligned {
415        return Vec::new();
416    }
417    (0..names.len())
418        .map(|column| {
419            field_rows
420                .iter()
421                .map(|row| row[column].0.len() + 2 + row[column].1.len() + 1)
422                .max()
423                .expect("BUG: aligned rows are non-empty")
424        })
425        .collect()
426}
427
428/// One `-> with` / `-> option` Fields line. When `column_widths` is non-empty, pad to those
429/// widths and never verticalize. When empty, keep one line if it fits `max_cols`, else one
430/// field per line.
431fn format_fields_row_line(
432    command: &str,
433    fields: &[(String, String)],
434    command_prefix: &str,
435    vertical_indent: &str,
436    column_widths: &[usize],
437    max_cols: usize,
438) -> String {
439    let mut inline = String::new();
440    for (index, (name, value)) in fields.iter().enumerate() {
441        let last = index + 1 == fields.len();
442        let cell = if last {
443            format!("{name}: {value}")
444        } else {
445            format!("{name}: {value},")
446        };
447        inline.push_str(&cell);
448        if !last {
449            let width = column_widths.get(index).copied().unwrap_or(cell.len());
450            inline.push_str(&" ".repeat(width.saturating_sub(cell.len()) + 1));
451        }
452    }
453    let line = format!("{command_prefix}{command} {inline}");
454    if !column_widths.is_empty() || line.len() <= max_cols {
455        return line;
456    }
457    let mut out = String::new();
458    out.push_str(command_prefix);
459    out.push_str(command);
460    for (index, (name, value)) in fields.iter().enumerate() {
461        out.push('\n');
462        out.push_str(vertical_indent);
463        out.push_str(&format!("{name}: {value}"));
464        if index + 1 < fields.len() {
465            out.push(',');
466        }
467    }
468    out
469}
470
471/// `-> key` first, then rows in source order. Rows with the same field order pad to equal
472/// column widths on one line each; misaligned rows that exceed `max_cols` go vertical.
473fn format_uses_list_commands(
474    list: &crate::parsing::ast::InstanceListBody,
475    continuation_prefix: &str,
476    max_cols: usize,
477) -> String {
478    use crate::parsing::ast::InstanceListRow;
479    let mut out = String::new();
480    let command_prefix = format!("{continuation_prefix}-> ");
481    if let Some(key) = &list.key {
482        let fields: Vec<String> = key.fields.iter().map(ToString::to_string).collect();
483        out.push('\n');
484        out.push_str(&command_prefix);
485        out.push_str("key ");
486        out.push_str(&fields.join(", "));
487    }
488
489    let field_rows: Vec<Vec<(String, String)>> = list
490        .rows
491        .iter()
492        .filter_map(|row| match row {
493            InstanceListRow::Fields { bindings, .. } => Some(uses_row_fields(bindings)),
494            InstanceListRow::Values { .. } => None,
495        })
496        .collect();
497    let column_widths = aligned_column_widths(&field_rows);
498
499    let vertical_indent = format!("{continuation_prefix}     ");
500    for row in &list.option_rows {
501        out.push('\n');
502        out.push_str(&format_instance_row_line(
503            "option",
504            row,
505            &command_prefix,
506            &vertical_indent,
507            &column_widths,
508            max_cols,
509        ));
510    }
511    for row in &list.rows {
512        out.push('\n');
513        out.push_str(&format_instance_row_line(
514            "with",
515            row,
516            &command_prefix,
517            &vertical_indent,
518            &column_widths,
519            max_cols,
520        ));
521    }
522    out
523}
524
525fn format_instance_row_line(
526    command: &str,
527    row: &crate::parsing::ast::InstanceListRow,
528    command_prefix: &str,
529    vertical_indent: &str,
530    column_widths: &[usize],
531    max_cols: usize,
532) -> String {
533    use crate::parsing::ast::InstanceListRow;
534    match row {
535        InstanceListRow::Fields { bindings, .. } => format_fields_row_line(
536            command,
537            &uses_row_fields(bindings),
538            command_prefix,
539            vertical_indent,
540            column_widths,
541            max_cols,
542        ),
543        InstanceListRow::Values { values, .. } => {
544            let items: Vec<String> = values.iter().map(format_with_rhs).collect();
545            let mut out = String::new();
546            out.push_str(command_prefix);
547            out.push_str(command);
548            out.push(' ');
549            out.push_str(&items.join(", "));
550            out
551        }
552    }
553}
554
555fn format_uses_block(data: &LemmaData, line_prefix: &str, max_cols: usize) -> String {
556    let mut out = format_import_header(data);
557    let (bindings, effective_ref) = match &data.value {
558        DataValue::Import {
559            bindings,
560            effective_ref,
561            ..
562        } => (bindings, effective_ref.as_ref()),
563        DataValue::OwnRows { bindings, .. } => (bindings, None),
564        DataValue::ImportList { .. } | DataValue::Definition { .. } => {
565            unreachable!("BUG: format_uses_block called on non-Import data")
566        }
567    };
568    if let Some(reference) = effective_ref {
569        out.push('\n');
570        out.push_str(line_prefix);
571        out.push_str(DATA_CONSTRAINT_INDENT);
572        out.push_str("-> effective ");
573        out.push_str(&reference.to_string());
574    }
575    for binding in bindings {
576        out.push('\n');
577        let continuation_prefix = format!("{line_prefix}{DATA_CONSTRAINT_INDENT}");
578        match &binding.rhs {
579            crate::parsing::ast::UsesBindingRhs::References { targets } => {
580                let items: Vec<String> = targets.iter().map(ToString::to_string).collect();
581                out.push_str(&format_comma_items_wrapped(
582                    &format!("{continuation_prefix}-> with {}: ", binding.path),
583                    &items,
584                    &continuation_prefix,
585                    max_cols,
586                ));
587            }
588            crate::parsing::ast::UsesBindingRhs::Literal(value) => {
589                out.push_str(&continuation_prefix);
590                out.push_str("-> ");
591                out.push_str(&crate::parsing::ast::format_assignment_continuation(
592                    "with",
593                    &format!("{}", binding.path),
594                    &format_uses_literal_binding(value),
595                ));
596            }
597        }
598    }
599    out
600}
601
602/// Group data into sections separated by blank lines:
603///
604/// 1. Imports (`uses`) with `-> with` bindings — declaration order
605/// 2. Regular local `data` — declaration order
606fn format_sorted_data(data: &[LemmaData], out: &mut String, line_prefix: &str, max_cols: usize) {
607    let mut regular: Vec<&LemmaData> = Vec::new();
608    let mut imports: Vec<&LemmaData> = Vec::new();
609
610    for data in data {
611        if data.value.uses_spec_ref().is_some() || matches!(data.value, DataValue::OwnRows { .. }) {
612            imports.push(data);
613        } else {
614            regular.push(data);
615        }
616    }
617
618    let emit_group = |rows: &[&LemmaData], out: &mut String| {
619        emit_data_row_group(rows, line_prefix, max_cols, out)
620    };
621
622    if !imports.is_empty() {
623        out.push('\n');
624
625        for (i, row) in imports.iter().enumerate() {
626            if i > 0 {
627                out.push('\n');
628            }
629            out.push_str(line_prefix);
630            out.push_str(&format_uses_block(row, line_prefix, max_cols));
631            out.push('\n');
632        }
633    }
634
635    if !regular.is_empty() {
636        out.push('\n');
637        emit_group(&regular, out);
638    }
639}
640
641// =============================================================================
642// Rules
643// =============================================================================
644
645const UNLESS_LINE_PREFIX: &str = "  unless ";
646
647/// Rule body always starts on the line after `rule name:`.
648///
649/// When every `unless` clause fits on one line under `max_cols`, `then` columns align across
650/// sisters. If any clause needs split `then` (wrapped condition, wrapped result, or oversize
651/// flat line), every clause on the rule uses split `then` at a fixed 4-space indent.
652fn format_rule(rule: &LemmaRule, max_cols: usize) -> String {
653    let expr_indent = "  ";
654    let body = format_expr_wrapped(&rule.expression, expr_indent.len(), max_cols, expr_indent);
655    let mut out = String::new();
656    out.push_str("rule ");
657    out.push_str(&rule.name);
658    out.push_str(":\n");
659    out.push_str(expr_indent);
660    out.push_str(&body);
661
662    const SPLIT_THEN_INDENT_SPACES: usize = 4;
663    let pl = UNLESS_LINE_PREFIX.len();
664    let naive_single_len = |cond: &str, res: &str| pl + cond.len() + 6 + res.len();
665    let aligned_single_len = |res: &str, max_end: usize| max_end + 6 + res.len();
666
667    let mut clauses: Vec<(String, String)> = Vec::new();
668    for unless_clause in &rule.unless_clauses {
669        let condition = format_expr_wrapped(&unless_clause.condition, pl, max_cols, "    ");
670        let result = format_expr_wrapped(
671            &unless_clause.result,
672            SPLIT_THEN_INDENT_SPACES + "then ".len(),
673            max_cols,
674            "    ",
675        );
676        clauses.push((condition, result));
677    }
678
679    let clause_needs_split_then = |condition: &str, result: &str| {
680        condition.contains('\n')
681            || result.contains('\n')
682            || naive_single_len(condition, result) > max_cols
683    };
684
685    let any_split = clauses.iter().any(|(c, r)| clause_needs_split_then(c, r));
686
687    let mut singles: Vec<usize> = if any_split {
688        Vec::new()
689    } else {
690        (0..clauses.len()).collect()
691    };
692
693    loop {
694        if singles.is_empty() {
695            break;
696        }
697        let max_end = singles
698            .iter()
699            .map(|&i| pl + clauses[i].0.len())
700            .max()
701            .expect("BUG: singles non-empty");
702        let before = singles.len();
703        singles.retain(|&i| aligned_single_len(&clauses[i].1, max_end) <= max_cols);
704        if singles.len() == before {
705            break;
706        }
707    }
708
709    let align_max_end = singles.iter().map(|&i| pl + clauses[i].0.len()).max();
710
711    for (i, (condition, result)) in clauses.iter().enumerate() {
712        out.push('\n');
713        out.push_str(UNLESS_LINE_PREFIX);
714        out.push_str(condition);
715        if singles.contains(&i) {
716            let max_end = align_max_end.expect("BUG: singles.contains but align_max_end empty");
717            out.push_str(&" ".repeat(1 + max_end.saturating_sub(pl + condition.len())));
718        } else {
719            out.push('\n');
720            out.push_str(&" ".repeat(SPLIT_THEN_INDENT_SPACES));
721        }
722        out.push_str("then ");
723        out.push_str(result);
724    }
725    out.push('\n');
726    out
727}
728
729// =============================================================================
730// Expression wrapping (soft line breaking at max_cols)
731// =============================================================================
732
733/// The expression within `max_cols` columns, wrapped at operators ([`display_wrapped`]).
734/// A sealed-catalog spine (`base`, optional `-> key`, then aligned `-> with` field rows)
735/// prints as a multi-line padded table instead.
736fn format_expr_wrapped(expr: &Expression, column: usize, max_cols: usize, indent: &str) -> String {
737    format_list_catalog_table(expr, indent)
738        .unwrap_or_else(|| display_wrapped(expr.root(), column, max_cols, indent.len()))
739}
740
741/// `base -> key? -> with field: … -> with …` when every `-> with` shares field order:
742/// one padded row per line. First line is the base (caller supplies indent for that line);
743/// continuation `->` lines use `indent`.
744fn format_list_catalog_table(expr: &Expression, indent: &str) -> Option<String> {
745    let mut commands = Vec::new();
746    let mut cur = expr.root;
747    while let ExpressionKind::ListCommand { list, command } = expr.table.kind(cur) {
748        commands.push(command.clone());
749        cur = *list;
750    }
751    if commands.is_empty() {
752        return None;
753    }
754    commands.reverse();
755
756    let mut with_start = 0;
757    let key_fields = match commands.first() {
758        Some(ListCommand::Key { fields }) => {
759            with_start = 1;
760            Some(fields)
761        }
762        _ => None,
763    };
764    let with_commands = &commands[with_start..];
765    if with_commands.is_empty() {
766        return None;
767    }
768
769    let mut field_rows: Vec<Vec<(String, String)>> = Vec::with_capacity(with_commands.len());
770    for command in with_commands {
771        let ListCommand::With {
772            rows: ListWithRows::FieldPairs(pairs),
773        } = command
774        else {
775            return None;
776        };
777        field_rows.push(
778            pairs
779                .iter()
780                .map(|(name, value)| (name.to_string(), Syntax(expr.at(*value)).to_string()))
781                .collect(),
782        );
783    }
784
785    let column_widths = aligned_column_widths(&field_rows);
786    if column_widths.is_empty() {
787        return None;
788    }
789
790    let command_prefix = format!("{indent}-> ");
791    let vertical_indent = format!("{indent}     ");
792    let mut out = Syntax(expr.at(cur)).to_string();
793    if let Some(fields) = key_fields {
794        let names: Vec<String> = fields.iter().map(ToString::to_string).collect();
795        out.push('\n');
796        out.push_str(&command_prefix);
797        out.push_str("key ");
798        out.push_str(&names.join(", "));
799    }
800    for fields in &field_rows {
801        out.push('\n');
802        out.push_str(&format_fields_row_line(
803            "with",
804            fields,
805            &command_prefix,
806            &vertical_indent,
807            &column_widths,
808            MAX_COLS,
809        ));
810    }
811    Some(out)
812}
813
814// =============================================================================
815// Tests
816// =============================================================================
817
818#[cfg(test)]
819mod tests {
820    use super::*;
821    use crate::literals::DateGranularity;
822    use crate::parsing::ast::{
823        AsLemmaSource, BooleanValue, DateTimeValue, TimeValue, TimezoneValue, Value,
824    };
825    use rust_decimal::prelude::FromStr;
826    use rust_decimal::Decimal;
827
828    /// Helper: format a Value as canonical Lemma source via AsLemmaSource.
829    fn fmt_value(v: &Value) -> String {
830        format!("{}", AsLemmaSource(v))
831    }
832
833    #[test]
834    fn test_format_value_text_is_quoted() {
835        let v = Value::Text("light".to_string());
836        assert_eq!(fmt_value(&v), "\"light\"");
837    }
838
839    /// A text literal has no escapes, so parsed text never holds a `"`.
840    #[test]
841    #[should_panic(expected = "BUG: parsed Lemma text cannot hold a double quote")]
842    fn test_format_value_text_with_a_quote_is_a_bug() {
843        let v = Value::Text("say \"hello\"".to_string());
844        let text = fmt_value(&v);
845        unreachable!("formatted a text holding a quote: {text}");
846    }
847
848    #[test]
849    fn test_format_value_text_writes_backslashes_as_they_are() {
850        let v = Value::Text("a\\b".to_string());
851        assert_eq!(fmt_value(&v), "\"a\\b\"");
852    }
853
854    #[test]
855    fn test_format_value_number() {
856        let v = Value::Number(Decimal::from_str("42.50").unwrap());
857        assert_eq!(fmt_value(&v), "42.50");
858    }
859
860    #[test]
861    fn test_format_value_number_integer() {
862        let v = Value::Number(Decimal::from_str("100.00").unwrap());
863        assert_eq!(fmt_value(&v), "100");
864    }
865
866    #[test]
867    fn test_format_value_boolean() {
868        assert_eq!(fmt_value(&Value::Boolean(BooleanValue::True)), "true");
869        assert_eq!(fmt_value(&Value::Boolean(BooleanValue::Yes)), "yes");
870        assert_eq!(fmt_value(&Value::Boolean(BooleanValue::No)), "no");
871    }
872
873    #[test]
874    fn test_format_value_measure() {
875        let v = Value::NumberWithUnit(Decimal::from_str("99.50").unwrap(), "eur".to_string());
876        assert_eq!(fmt_value(&v), "99.50 eur");
877    }
878
879    #[test]
880    fn test_format_value_duration_as_measure() {
881        let v = Value::NumberWithUnit(Decimal::from(40), "hour".to_string());
882        assert_eq!(fmt_value(&v), "40 hour");
883    }
884
885    #[test]
886    fn test_format_value_calendar() {
887        let v = Value::NumberWithUnit(Decimal::from(6), "month".to_string());
888        assert_eq!(fmt_value(&v), "6 month");
889    }
890
891    #[test]
892    fn test_format_value_ratio_percent() {
893        let v = Value::NumberWithUnit(Decimal::from_str("10").unwrap(), "percent".to_string());
894        assert_eq!(fmt_value(&v), "10%");
895    }
896
897    #[test]
898    fn test_format_value_ratio_permille() {
899        let v = Value::NumberWithUnit(Decimal::from_str("5").unwrap(), "permille".to_string());
900        assert_eq!(fmt_value(&v), "5%%");
901    }
902
903    #[test]
904    fn test_format_value_number_with_unit_named() {
905        let v = Value::NumberWithUnit(
906            Decimal::from_str("500").unwrap(),
907            "basis_points".to_string(),
908        );
909        assert_eq!(fmt_value(&v), "500 basis_points");
910    }
911
912    #[test]
913    fn test_format_value_date_only() {
914        let v = Value::Date(DateTimeValue {
915            year: 2024,
916            month: 1,
917            day: 15,
918            hour: 0,
919            minute: 0,
920            second: 0,
921            microsecond: 0,
922            timezone: None,
923
924            granularity: DateGranularity::Full,
925        });
926        assert_eq!(fmt_value(&v), "2024-01-15");
927    }
928
929    #[test]
930    fn test_format_value_datetime_with_tz() {
931        let v = Value::Date(DateTimeValue {
932            year: 2024,
933            month: 1,
934            day: 15,
935            hour: 14,
936            minute: 30,
937            second: 0,
938            microsecond: 0,
939            timezone: Some(TimezoneValue { offset_minutes: 0 }),
940
941            granularity: DateGranularity::DateTime,
942        });
943        assert_eq!(fmt_value(&v), "2024-01-15T14:30:00Z");
944    }
945
946    #[test]
947    fn test_format_value_time() {
948        let v = Value::Time(TimeValue {
949            hour: 14,
950            minute: 30,
951            second: 45,
952            microsecond: 0,
953            timezone: None,
954        });
955        assert_eq!(fmt_value(&v), "14:30:45");
956    }
957
958    #[test]
959    fn test_format_source_preserves_date_granularity() {
960        let formatted = format_source(
961            "spec x 2026\n",
962            crate::parsing::source::SourceType::Volatile,
963        )
964        .expect("spec x 2026 should format");
965        assert!(
966            formatted.contains("spec x 2026\n"),
967            "year-only effective date must round-trip, got: {formatted}"
968        );
969        assert!(
970            !formatted.contains("2026-01-01"),
971            "year-only effective date must not expand, got: {formatted}"
972        );
973        let reformatted = format_source(&formatted, crate::parsing::source::SourceType::Volatile)
974            .expect("reformat");
975        assert_eq!(formatted, reformatted, "spec x 2026 must be idempotent");
976
977        let formatted = format_source(
978            "spec x 2026-03\n",
979            crate::parsing::source::SourceType::Volatile,
980        )
981        .expect("spec x 2026-03 should format");
982        assert!(
983            formatted.contains("spec x 2026-03\n"),
984            "year-month effective date must round-trip, got: {formatted}"
985        );
986
987        let formatted = format_source(
988            "spec x 2026-W34\n",
989            crate::parsing::source::SourceType::Volatile,
990        )
991        .expect("spec x 2026-W34 should format");
992        assert!(
993            formatted.contains("spec x 2026-W34\n"),
994            "iso week effective date must round-trip, got: {formatted}"
995        );
996
997        let source = "spec consumer\nuses finance 2026\n";
998        let formatted = format_source(source, crate::parsing::source::SourceType::Volatile)
999            .expect("uses with year should format");
1000        assert!(
1001            formatted.contains("uses finance 2026"),
1002            "uses effective pin must preserve year-only date, got: {formatted}"
1003        );
1004        assert!(
1005            !formatted.contains("2026-01-01"),
1006            "uses effective pin must not expand year-only date, got: {formatted}"
1007        );
1008    }
1009
1010    #[test]
1011    fn format_uses_dynamic_effective_command() {
1012        let source = r#"
1013spec alpha2 2020-01-01
1014data code: text
1015
1016spec intake
1017data birth_date: date
1018uses iso: alpha2
1019  -> effective birth_date
1020  -> with code: "NL"
1021"#;
1022        let formatted = format_source(source, crate::parsing::source::SourceType::Volatile)
1023            .expect("dynamic effective uses should format");
1024        assert!(
1025            formatted.contains("-> effective birth_date"),
1026            "formatter must emit -> effective, got: {formatted}"
1027        );
1028        assert!(
1029            formatted
1030                .find("-> effective birth_date")
1031                .expect("effective")
1032                < formatted.find("-> with code").expect("with"),
1033            "-> effective must precede -> with, got: {formatted}"
1034        );
1035    }
1036
1037    #[test]
1038    fn test_format_source_lowercases_logical_identifiers() {
1039        let source = r#"spec Test
1040data Price: number -> suggest 1
1041rule Total: price
1042"#;
1043        let formatted =
1044            format_source(source, crate::parsing::source::SourceType::Volatile).unwrap();
1045        assert!(formatted.contains("spec test"), "got: {formatted}");
1046        assert!(formatted.contains("data price"), "got: {formatted}");
1047        assert!(formatted.contains("rule total"), "got: {formatted}");
1048    }
1049
1050    #[test]
1051    fn test_format_source_round_trips_text() {
1052        let source = r#"spec test
1053
1054data name: "Alice"
1055
1056rule greeting: "hello"
1057"#;
1058        let formatted =
1059            format_source(source, crate::parsing::source::SourceType::Volatile).unwrap();
1060        assert!(formatted.contains("\"Alice\""), "data text must be quoted");
1061        assert!(formatted.contains("\"hello\""), "rule text must be quoted");
1062    }
1063
1064    #[test]
1065    fn test_format_source_preserves_percent() {
1066        let source = r#"spec test
1067
1068data rate: 10 percent
1069
1070rule tax: rate * 21%
1071"#;
1072        let formatted =
1073            format_source(source, crate::parsing::source::SourceType::Volatile).unwrap();
1074        assert!(
1075            formatted.contains("10%"),
1076            "data percent must use shorthand %, got: {}",
1077            formatted
1078        );
1079    }
1080
1081    #[test]
1082    fn test_format_groups_data_preserving_order() {
1083        // Data are deliberately mixed: the formatter keeps all regular data together
1084        // in original order, aligned
1085        let source = r#"spec test
1086
1087data income: number -> minimum 0
1088data filing_status: filing_status_type -> suggest "single"
1089data country: "NL"
1090data deductions: number -> minimum 0
1091data name: text
1092
1093rule total: income
1094"#;
1095        let formatted =
1096            format_source(source, crate::parsing::source::SourceType::Volatile).unwrap();
1097        let data_section = formatted
1098            .split("rule total")
1099            .next()
1100            .unwrap()
1101            .split("spec test\n")
1102            .nth(1)
1103            .unwrap();
1104        let lines: Vec<&str> = data_section.lines().filter(|l| !l.is_empty()).collect();
1105        // Constrained rows: one blank line after each when more `data` follows.
1106        assert_eq!(lines[0], "data income: number");
1107        assert_eq!(lines[1], "  -> minimum 0");
1108        assert_eq!(lines[2], "data filing_status: filing_status_type");
1109        assert_eq!(lines[3], "  -> suggest \"single\"");
1110        assert_eq!(lines[4], "data country: \"NL\"");
1111        assert_eq!(lines[5], "data deductions: number");
1112        assert_eq!(lines[6], "  -> minimum 0");
1113        assert_eq!(lines[7], "data name: text");
1114    }
1115
1116    #[test]
1117    fn test_format_groups_spec_refs_with_overrides() {
1118        let source = r#"spec test
1119
1120uses order wholesale
1121  -> with quantity: 100
1122uses order retail
1123  -> with quantity: 5
1124data base_price: 50
1125
1126rule total: base_price
1127"#;
1128        let formatted =
1129            format_source(source, crate::parsing::source::SourceType::Volatile).unwrap();
1130        let data_section = formatted
1131            .split("rule total")
1132            .next()
1133            .unwrap()
1134            .split("spec test\n")
1135            .nth(1)
1136            .unwrap();
1137        let lines: Vec<&str> = data_section.lines().filter(|l| !l.is_empty()).collect();
1138        assert_eq!(lines[0], "uses order wholesale");
1139        assert_eq!(lines[1], "  -> with quantity: 100");
1140        assert_eq!(lines[2], "uses order retail");
1141        assert_eq!(lines[3], "  -> with quantity: 5");
1142        assert_eq!(lines[4], "data base_price: 50");
1143    }
1144
1145    #[test]
1146    fn test_format_groups_with_literals_under_each_uses() {
1147        let source = r#"spec test
1148
1149uses x
1150  -> with name: "Ben"
1151uses y
1152  -> with age: 15
1153
1154rule r: 1
1155"#;
1156        let formatted =
1157            format_source(source, crate::parsing::source::SourceType::Volatile).unwrap();
1158        let data_section = formatted
1159            .split("rule r")
1160            .next()
1161            .unwrap()
1162            .split("spec test\n")
1163            .nth(1)
1164            .unwrap();
1165        let lines: Vec<&str> = data_section.lines().filter(|l| !l.is_empty()).collect();
1166        assert_eq!(lines[0], "uses x");
1167        assert_eq!(lines[1], "  -> with name: \"Ben\"");
1168        assert_eq!(lines[2], "uses y");
1169        assert_eq!(lines[3], "  -> with age: 15");
1170    }
1171
1172    #[test]
1173    fn test_format_source_weather_clothing_text_quoted() {
1174        let source = r#"spec weather_clothing
1175
1176data clothing_style: text
1177  -> option "light"
1178  -> option "warm"
1179
1180data temperature: number
1181
1182rule clothing_layer: "light"
1183  unless temperature < 5 then "warm"
1184"#;
1185        let formatted =
1186            format_source(source, crate::parsing::source::SourceType::Volatile).unwrap();
1187        assert!(
1188            formatted.contains("\"light\""),
1189            "text in rule must be quoted, got: {}",
1190            formatted
1191        );
1192        assert!(
1193            formatted.contains("\"warm\""),
1194            "text in unless must be quoted, got: {}",
1195            formatted
1196        );
1197    }
1198
1199    // NOTE: Default value type validation (e.g. rejecting "10 $$" as a number
1200    // default) is tested at the planning level in engine.rs, not here. The
1201    // formatter only parses — it does not validate types. Planning catches
1202    // invalid defaults for both primitives and named types.
1203
1204    #[test]
1205    fn test_format_text_option_round_trips() {
1206        let source = r#"spec test
1207
1208data status: text
1209  -> option "active"
1210  -> option "inactive"
1211
1212data s: status
1213
1214rule out: s
1215"#;
1216        let formatted =
1217            format_source(source, crate::parsing::source::SourceType::Volatile).unwrap();
1218        assert!(
1219            formatted.contains("option \"active\""),
1220            "text option must be quoted, got: {}",
1221            formatted
1222        );
1223        assert!(
1224            formatted.contains("option \"inactive\""),
1225            "text option must be quoted, got: {}",
1226            formatted
1227        );
1228        // Round-trip
1229        let reparsed = format_source(&formatted, crate::parsing::source::SourceType::Volatile);
1230        assert!(reparsed.is_ok(), "formatted output should re-parse");
1231    }
1232
1233    #[test]
1234    fn test_format_help_round_trips() {
1235        let source = r#"spec test
1236data quantity: number -> help "Number of items to order"
1237rule total: quantity
1238"#;
1239        let formatted =
1240            format_source(source, crate::parsing::source::SourceType::Volatile).unwrap();
1241        assert!(
1242            formatted.contains("help \"Number of items to order\""),
1243            "help must be quoted, got: {}",
1244            formatted
1245        );
1246        // Round-trip
1247        let reparsed = format_source(&formatted, crate::parsing::source::SourceType::Volatile);
1248        assert!(reparsed.is_ok(), "formatted output should re-parse");
1249    }
1250
1251    #[test]
1252    fn test_format_measure_type_def_round_trips() {
1253        let source = r#"spec test
1254
1255data money: measure
1256  -> unit eur: 1.00
1257  -> unit usd: 0.91
1258  -> minimum 0
1259
1260data price: money
1261
1262rule total: price
1263"#;
1264        let formatted =
1265            format_source(source, crate::parsing::source::SourceType::Volatile).unwrap();
1266        assert!(
1267            formatted.contains("unit eur: 1.00"),
1268            "measure unit should not be quoted, got: {}",
1269            formatted
1270        );
1271        // Round-trip
1272        let reparsed = format_source(&formatted, crate::parsing::source::SourceType::Volatile);
1273        assert!(
1274            reparsed.is_ok(),
1275            "formatted output should re-parse, got: {:?}",
1276            reparsed
1277        );
1278    }
1279
1280    #[test]
1281    fn format_deprecated_unit_space_emits_assignment_colon() {
1282        let source = r#"spec test
1283uses lemma units
1284
1285data money: measure
1286  -> unit eur: 1.00
1287
1288data rate: measure
1289  -> unit eur_per_hour: eur/hour
1290"#;
1291        let formatted =
1292            format_source(source, crate::parsing::source::SourceType::Volatile).unwrap();
1293        assert!(
1294            formatted.contains("unit eur: 1.00"),
1295            "formatter must emit assignment colon for unit, got: {}",
1296            formatted
1297        );
1298        assert!(
1299            formatted.contains("unit eur_per_hour: eur/hour"),
1300            "formatter must emit assignment colon for compound unit, got: {}",
1301            formatted
1302        );
1303        assert!(
1304            !formatted.contains("unit eur 1.00"),
1305            "formatter must not emit deprecated space unit syntax, got: {}",
1306            formatted
1307        );
1308    }
1309
1310    #[test]
1311    fn format_canonical_unit_colon_round_trips() {
1312        let source = r#"spec test
1313uses lemma units
1314
1315data money: measure
1316  -> unit eur: 1.00
1317
1318data rate: measure
1319  -> unit eur_per_hour: eur/hour
1320"#;
1321        let formatted =
1322            format_source(source, crate::parsing::source::SourceType::Volatile).unwrap();
1323        assert!(
1324            formatted.contains("unit eur: 1.00"),
1325            "canonical unit syntax must survive format, got: {}",
1326            formatted
1327        );
1328        let reparsed = format_source(&formatted, crate::parsing::source::SourceType::Volatile);
1329        assert!(
1330            reparsed.is_ok(),
1331            "formatted canonical unit syntax should re-parse, got: {:?}",
1332            reparsed
1333        );
1334    }
1335
1336    #[test]
1337    fn test_format_expression_display_stable_round_trip() {
1338        let source = r#"spec test
1339data a: 1.00
1340rule r: a + 2.00 * 3
1341"#;
1342        let formatted =
1343            format_source(source, crate::parsing::source::SourceType::Volatile).unwrap();
1344        let again =
1345            format_source(&formatted, crate::parsing::source::SourceType::Volatile).unwrap();
1346        assert_eq!(
1347            formatted, again,
1348            "AST Display-based format must be idempotent under parse/format"
1349        );
1350    }
1351
1352    #[test]
1353    fn test_format_past_future_range_no_duplicate_in() {
1354        let source = r#"spec test
1355data start: date
1356data length: duration
1357rule valid: start in past length
1358rule window: past length
1359"#;
1360        let formatted =
1361            format_source(source, crate::parsing::source::SourceType::Volatile).unwrap();
1362        assert!(
1363            formatted.contains("rule valid:\n  start in past length"),
1364            "RangeContainment+PastFutureRange must not emit duplicate 'in', got:\n{formatted}"
1365        );
1366        assert!(
1367            formatted.contains("rule window:\n  past length"),
1368            "bare PastFutureRange must print 'past' not 'in past', got:\n{formatted}"
1369        );
1370        assert!(
1371            !formatted.contains("in in past"),
1372            "must not contain duplicate 'in', got:\n{formatted}"
1373        );
1374    }
1375
1376    #[test]
1377    fn test_format_rule_body_on_next_line() {
1378        let source = "spec test\nrule r: 1\n";
1379        let formatted =
1380            format_source(source, crate::parsing::source::SourceType::Volatile).unwrap();
1381        assert!(
1382            formatted.contains("rule r:\n  1\n"),
1383            "rule body must start on next line, got:\n{formatted}"
1384        );
1385    }
1386
1387    #[test]
1388    fn test_format_blank_line_between_data_and_rules() {
1389        let source = "spec test\ndata x: 1\nrule r: x\n";
1390        let formatted =
1391            format_source(source, crate::parsing::source::SourceType::Volatile).unwrap();
1392        assert!(
1393            formatted.contains("data x: 1\n\nrule r:\n")
1394                && !formatted.contains("data x: 1\n\n\nrule r:\n"),
1395            "one blank line required between data block and rules block, got:\n{formatted:?}"
1396        );
1397    }
1398
1399    #[test]
1400    fn test_format_rule_unless_single_line_when_short() {
1401        let source = r#"spec test
1402data a: number
1403data b: boolean
1404
1405rule r: no
1406  unless a < 1 then yes
1407  unless b then yes
1408"#;
1409        let formatted =
1410            format_source(source, crate::parsing::source::SourceType::Volatile).unwrap();
1411        assert!(
1412            formatted.contains("unless a < 1 then yes")
1413                && formatted.contains("unless b     then yes"),
1414            "unless stays on one line when under MAX_COLS, got:\n{formatted}"
1415        );
1416    }
1417
1418    #[test]
1419    fn test_format_rule_unless_child_premium_applies_inline_aligned() {
1420        let source = r#"spec child_premium_applies
1421data child_age_years: number
1422data is_male: boolean
1423data child_has_own_children: boolean
1424data child_is_oldest_insured: boolean
1425
1426rule child_premium_applies:
1427  yes
1428  unless child_age_years >= 25 and is_male then no
1429  unless child_has_own_children then no
1430  unless child_is_oldest_insured then no
1431"#;
1432        let formatted =
1433            format_source(source, crate::parsing::source::SourceType::Volatile).unwrap();
1434        assert!(
1435            formatted.contains("unless child_age_years >= 25 and is_male then no")
1436                && formatted.contains("unless child_has_own_children            then no")
1437                && formatted.contains("unless child_is_oldest_insured           then no"),
1438            "all-single unless clauses align then, got:\n{formatted}"
1439        );
1440        let twice =
1441            format_source(&formatted, crate::parsing::source::SourceType::Volatile).unwrap();
1442        assert_eq!(formatted, twice);
1443    }
1444
1445    #[test]
1446    fn test_format_rule_unless_can_request_reinstatement_and_wrap() {
1447        let source = r#"spec can_request_reinstatement
1448data days_since_policy_stopped: number
1449data arrears_paid: boolean
1450data surrender_value_repaid: boolean
1451data all_insured_persons_alive: boolean
1452
1453rule can_request_reinstatement:
1454  no
1455  unless days_since_policy_stopped <= 365 and arrears_paid and surrender_value_repaid and all_insured_persons_alive then yes
1456"#;
1457        let formatted =
1458            format_source(source, crate::parsing::source::SourceType::Volatile).unwrap();
1459        assert!(
1460            formatted.contains(
1461                "unless days_since_policy_stopped <= 365\n    and arrears_paid and surrender_value_repaid\n    and all_insured_persons_alive\n    then yes"
1462            ),
1463            "long and chain fills the condition budget, got:\n{formatted}"
1464        );
1465        let twice =
1466            format_source(&formatted, crate::parsing::source::SourceType::Volatile).unwrap();
1467        assert_eq!(formatted, twice);
1468    }
1469
1470    #[test]
1471    fn test_format_rule_unless_foreign_transport_uniform_split_then() {
1472        let source = r#"spec foreign_transport_covered
1473data death_location: text
1474data trip_duration_months: number
1475data negative_travel_advisory_at_departure: boolean
1476data left_area_asap_after_advisory: boolean
1477
1478rule foreign_transport_covered:
1479  yes
1480  unless death_location is "abroad" then no
1481  unless death_location is "abroad" and trip_duration_months <= 2 then yes
1482  unless death_location is "abroad" and trip_duration_months <= 2 and negative_travel_advisory_at_departure then no
1483  unless death_location is "abroad" and trip_duration_months <= 2 and negative_travel_advisory_at_departure and left_area_asap_after_advisory then yes
1484"#;
1485        let formatted =
1486            format_source(source, crate::parsing::source::SourceType::Volatile).unwrap();
1487        assert!(
1488            formatted.contains("unless death_location is \"abroad\"\n    then no"),
1489            "short sister uses split then when any clause needs it, got:\n{formatted}"
1490        );
1491        assert!(
1492            formatted.contains(
1493                "unless death_location is \"abroad\"\n    and trip_duration_months <= 2\n    then yes"
1494            ),
1495            "wrapped and chain with split then, got:\n{formatted}"
1496        );
1497        let twice =
1498            format_source(&formatted, crate::parsing::source::SourceType::Volatile).unwrap();
1499        assert_eq!(formatted, twice);
1500    }
1501
1502    #[test]
1503    fn test_format_rule_unless_child_auto_covered_service_only() {
1504        let source = r#"spec child_auto_covered_service_only
1505data days_since_birth: number
1506data birth_reported_within_60_days: boolean
1507
1508rule child_auto_covered_service_only:
1509  yes
1510  unless days_since_birth >= 60 and not birth_reported_within_60_days then no
1511"#;
1512        let formatted =
1513            format_source(source, crate::parsing::source::SourceType::Volatile).unwrap();
1514        assert!(
1515            formatted.contains(
1516                "unless days_since_birth >= 60\n    and not birth_reported_within_60_days\n    then no"
1517            ),
1518            "multiline unless condition with split then, got:\n{formatted}"
1519        );
1520        let twice =
1521            format_source(&formatted, crate::parsing::source::SourceType::Volatile).unwrap();
1522        assert_eq!(formatted, twice);
1523    }
1524
1525    #[test]
1526    fn test_format_long_arithmetic_chain_fills_to_max_cols() {
1527        let source = r#"spec test
1528data first_amount: number
1529data second_amount: number
1530data third_amount: number
1531data fourth_amount: number
1532data fifth_amount: number
1533data sixth_amount: number
1534
1535rule total: first_amount + second_amount + third_amount + fourth_amount + fifth_amount + sixth_amount
1536"#;
1537        let formatted =
1538            format_source(source, crate::parsing::source::SourceType::Volatile).unwrap();
1539        assert!(
1540            formatted.contains(
1541                "rule total:\n  first_amount + second_amount + third_amount\n  + fourth_amount + fifth_amount + sixth_amount\n"
1542            ),
1543            "overlong chain fills to 56 columns, got:\n{formatted}"
1544        );
1545        let twice =
1546            format_source(&formatted, crate::parsing::source::SourceType::Volatile).unwrap();
1547        assert_eq!(formatted, twice);
1548    }
1549
1550    #[test]
1551    fn test_format_nested_sum_that_fits_is_one_line() {
1552        let source = "spec test\nrule total: (0 + 0) + (0 + 0)\n";
1553        let formatted =
1554            format_source(source, crate::parsing::source::SourceType::Volatile).unwrap();
1555        assert!(
1556            formatted.contains("rule total:\n  0 + 0 + 0 + 0\n"),
1557            "nested sum that fits is one chain, got:\n{formatted}"
1558        );
1559        let twice =
1560            format_source(&formatted, crate::parsing::source::SourceType::Volatile).unwrap();
1561        assert_eq!(formatted, twice);
1562    }
1563
1564    #[test]
1565    fn test_format_nested_sum_fills_columns() {
1566        let source = "spec test\nrule total: ((((0 + 0) + (0 + 0)) + ((0 + 0) + (0 + 0))) + (((0 + 0) + (0 + 0)) + ((0 + 0) + (0 + 0))))\n";
1567        let formatted =
1568            format_source(source, crate::parsing::source::SourceType::Volatile).unwrap();
1569        assert!(
1570            formatted.contains(
1571                "rule total:\n  0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0\n  + 0 + 0\n"
1572            ),
1573            "sixteen zeros fill 56 columns, got:\n{formatted}"
1574        );
1575        let twice =
1576            format_source(&formatted, crate::parsing::source::SourceType::Volatile).unwrap();
1577        assert_eq!(formatted, twice);
1578    }
1579
1580    #[test]
1581    fn test_format_subtraction_keeps_right_parentheses() {
1582        let source = "spec test\ndata a: 1\ndata b: 2\ndata c: 3\nrule total: a + (b - c)\n";
1583        let formatted =
1584            format_source(source, crate::parsing::source::SourceType::Volatile).unwrap();
1585        assert!(
1586            formatted.contains("rule total:\n  a + (b - c)\n"),
1587            "subtraction stays grouped, got:\n{formatted}"
1588        );
1589    }
1590
1591    #[test]
1592    fn test_format_broken_chain_respects_the_width() {
1593        let source = r#"spec test
1594data base_amount_value: number
1595data first_amount: number
1596data second_amount: number
1597data third_amount: number
1598data other_amount_value: number
1599
1600rule total: base_amount_value * (first_amount + second_amount + third_amount) + other_amount_value
1601"#;
1602        let formatted =
1603            format_source(source, crate::parsing::source::SourceType::Volatile).unwrap();
1604        assert!(
1605            formatted.contains(
1606                "rule total:\n  base_amount_value\n    * (first_amount + second_amount + third_amount)\n  + other_amount_value\n"
1607            ),
1608            "a nested chain breaks when its line is too long, got:\n{formatted}"
1609        );
1610        let twice =
1611            format_source(&formatted, crate::parsing::source::SourceType::Volatile).unwrap();
1612        assert_eq!(formatted, twice);
1613    }
1614
1615    const ORDER: &str = r#"spec order_line
1616data purchase_cost: number
1617data discount_percentage: ratio
1618data handling_percentage: ratio
1619
1620spec order
1621uses order_line
1622data order_lines: order_line list
1623data contract_percentage: ratio
1624"#;
1625
1626    /// Formats `rules` below [`ORDER`]. The result must be stable.
1627    fn format_order(rules: &str) -> String {
1628        let format = |source: &str| {
1629            format_source(source, crate::parsing::source::SourceType::Volatile)
1630                .expect("order must parse")
1631        };
1632        let formatted = format(&format!("{ORDER}\n{rules}"));
1633        assert_eq!(formatted, format(&formatted), "formatting must be stable");
1634        for line in formatted.lines() {
1635            assert!(line.len() <= MAX_COLS, "line is too long: {line}");
1636            assert_eq!(line, line.trim_end(), "trailing space: {line:?}");
1637        }
1638        formatted
1639    }
1640
1641    #[test]
1642    fn test_format_long_list_command_starts_a_line_and_breaks_in_its_argument() {
1643        let formatted = format_order(
1644            "rule total: order_lines -> sum(order_lines.purchase_cost / (100% - order_lines.discount_percentage - contract_percentage - order_lines.handling_percentage))\n",
1645        );
1646        let expected = "rule total:
1647  order_lines
1648    -> sum(order_lines.purchase_cost / (100%
1649      - order_lines.discount_percentage
1650      - contract_percentage
1651      - order_lines.handling_percentage))
1652";
1653        assert!(formatted.ends_with(expected), "got:\n{formatted}");
1654    }
1655
1656    #[test]
1657    fn test_format_list_command_that_fits_is_one_line() {
1658        let formatted =
1659            format_order("rule total: order_lines\n  -> sum\n  order_lines.purchase_cost\n");
1660        let expected = "rule total:
1661  order_lines -> sum order_lines.purchase_cost
1662";
1663        assert!(formatted.ends_with(expected), "got:\n{formatted}");
1664    }
1665
1666    #[test]
1667    fn test_format_list_command_that_fits_on_its_own_line_does_not_break() {
1668        let formatted =
1669            format_order("rule total: order_lines -> sum(purchase_cost * discount_percentage)\n");
1670        let expected = "rule total:
1671  order_lines
1672    -> sum(purchase_cost * discount_percentage)
1673";
1674        assert!(formatted.ends_with(expected), "got:\n{formatted}");
1675    }
1676
1677    #[test]
1678    fn test_format_long_list_commands_wrap_when_needed() {
1679        let formatted = format_order(
1680            "rule cheapest: order_lines -> where(discount_percentage > 10%) -> sort purchase_cost asc -> first\n",
1681        );
1682        let expected = "rule cheapest:
1683  order_lines -> where discount_percentage > 10%
1684    -> sort purchase_cost asc -> first
1685";
1686        assert!(formatted.ends_with(expected), "got:\n{formatted}");
1687    }
1688
1689    #[test]
1690    fn test_format_long_list_command_argument_keeps_terms_that_fit_whole() {
1691        let formatted = format_order(
1692            "rule total: order_lines -> sum(purchase_cost * discount_percentage + purchase_cost * handling_percentage + purchase_cost * contract_percentage)\n",
1693        );
1694        let expected = "rule total:
1695  order_lines
1696    -> sum(purchase_cost * discount_percentage
1697      + purchase_cost * handling_percentage
1698      + purchase_cost * contract_percentage)
1699";
1700        assert!(formatted.ends_with(expected), "got:\n{formatted}");
1701    }
1702
1703    #[test]
1704    fn test_format_long_list_command_breaks_at_and() {
1705        let formatted = format_order(
1706            "rule costly: order_lines -> where(discount_percentage > 10% and handling_percentage > 10% and contract_percentage > 10%)\n",
1707        );
1708        let expected = "rule costly:
1709  order_lines
1710    -> where(discount_percentage > 10%
1711      and handling_percentage > 10%
1712      and contract_percentage > 10%)
1713";
1714        assert!(formatted.ends_with(expected), "got:\n{formatted}");
1715    }
1716
1717    #[test]
1718    fn test_format_long_parenthesized_operand_breaks_inside() {
1719        let formatted = format_order(
1720            "rule total: contract_percentage * (purchase_cost + purchase_cost + purchase_cost + purchase_cost + purchase_cost) + purchase_cost\n",
1721        );
1722        let expected = "rule total:
1723  contract_percentage * (purchase_cost + purchase_cost
1724    + purchase_cost + purchase_cost + purchase_cost)
1725  + purchase_cost
1726";
1727        assert!(formatted.ends_with(expected), "got:\n{formatted}");
1728    }
1729
1730    #[test]
1731    fn test_format_long_list_command_in_parentheses_breaks_inside() {
1732        let formatted = format_order(
1733            "rule total: (order_lines -> sum(order_lines.purchase_cost * order_lines.discount_percentage)) / purchase_cost\n",
1734        );
1735        let expected = "rule total:
1736  (order_lines
1737    -> sum(order_lines.purchase_cost
1738      * order_lines.discount_percentage))
1739  / purchase_cost
1740";
1741        assert!(formatted.ends_with(expected), "got:\n{formatted}");
1742    }
1743
1744    #[test]
1745    fn test_format_long_comparison_breaks_at_its_operator() {
1746        let formatted = format_order(
1747            "rule costly: order_lines.purchase_cost + contract_percentage >= order_lines.handling_percentage\n",
1748        );
1749        let expected = "rule costly:
1750  order_lines.purchase_cost + contract_percentage
1751  >= order_lines.handling_percentage
1752";
1753        assert!(formatted.ends_with(expected), "got:\n{formatted}");
1754    }
1755
1756    #[test]
1757    fn test_format_rule_body_counts_its_indent() {
1758        let formatted =
1759            format_order("rule total: contract_percentage + purchase_cost + purchase_costs + 1\n");
1760        let expected = "rule total:
1761  contract_percentage + purchase_cost + purchase_costs
1762  + 1
1763";
1764        assert!(formatted.ends_with(expected), "got:\n{formatted}");
1765    }
1766
1767    #[test]
1768    fn test_format_long_list_command_in_unless() {
1769        let formatted = format_order(
1770            "rule accepted: yes\n  unless order_lines -> any(discount_percentage > contract_percentage) then no\n",
1771        );
1772        let expected = "rule accepted:
1773  yes
1774  unless order_lines
1775      -> any discount_percentage > contract_percentage
1776    then no
1777";
1778        assert!(formatted.ends_with(expected), "got:\n{formatted}");
1779    }
1780
1781    #[test]
1782    fn test_format_constrained_data_row_stands_alone_between_aligned_runs() {
1783        let source = r#"spec test
1784data a: 1
1785data longer_name: 2
1786data limit: number -> minimum 0
1787data b: 3
1788"#;
1789        let formatted =
1790            format_source(source, crate::parsing::source::SourceType::Volatile).unwrap();
1791        assert!(
1792            formatted.contains(
1793                "data a:           1\ndata longer_name: 2\ndata limit: number\n  -> minimum 0\n\ndata b: 3\n"
1794            ),
1795            "got:\n{formatted}"
1796        );
1797    }
1798}