Skip to main content

lemma/parsing/
ast.rs

1//! AST types
2//!
3//! Infrastructure (Span, DepthTracker) and spec/data/rule/expression/value types from parsing.
4//!
5//! # Human `Display` vs canonical `AsLemmaSource`
6//!
7//! [`DataValue`] and [`CommandArg`] use human-oriented `Display` (stable for
8//! `to_string()`, logs, APIs). [`Expression`] and [`LemmaRule`]/[`LemmaSpec`]
9//! use canonical Lemma source for literals via [`AsLemmaSource`] around
10//! [`Value`]. Wrap [`DataValue`] in [`AsLemmaSource`] when emitting
11//! round-trippable source (e.g. the formatter).
12//!
13//! Logical identifier names (spec, data, rule, unit, reference path segments) are stored
14//! as ASCII lowercase after parse. String literals and text option values are unchanged.
15
16/// Fold a logical identifier name to canonical ASCII lowercase.
17pub(crate) fn ascii_lowercase_logical_name(name: String) -> String {
18    name.to_ascii_lowercase()
19}
20
21/// Canonical ASCII lowercase form of a logical identifier, borrowed when `name` is already
22/// canonical. Lookups use this so an already-lowercase request allocates nothing.
23pub(crate) fn canonical_logical_name(name: &str) -> std::borrow::Cow<'_, str> {
24    if name.bytes().any(|byte| byte.is_ascii_uppercase()) {
25        std::borrow::Cow::Owned(name.to_ascii_lowercase())
26    } else {
27        std::borrow::Cow::Borrowed(name)
28    }
29}
30
31/// Span representing a location in source code
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize)]
33pub struct Span {
34    pub start: usize,
35    pub end: usize,
36    pub line: usize,
37    pub col: usize,
38}
39
40/// Tracks expression nesting depth during parsing to prevent stack overflow
41pub struct DepthTracker {
42    depth: usize,
43    max_depth: usize,
44}
45
46impl DepthTracker {
47    pub fn with_max_depth(max_depth: usize) -> Self {
48        Self {
49            depth: 0,
50            max_depth,
51        }
52    }
53
54    /// Returns Ok(()) if within limits, Err(current_depth) if exceeded.
55    pub fn push_depth(&mut self) -> Result<(), usize> {
56        self.depth += 1;
57        if self.depth > self.max_depth {
58            return Err(self.depth);
59        }
60        Ok(())
61    }
62
63    pub fn pop_depth(&mut self) {
64        if self.depth > 0 {
65            self.depth -= 1;
66        }
67    }
68
69    pub fn max_depth(&self) -> usize {
70        self.max_depth
71    }
72}
73
74impl Default for DepthTracker {
75    fn default() -> Self {
76        Self {
77            depth: 0,
78            max_depth: 5,
79        }
80    }
81}
82
83// -----------------------------------------------------------------------------
84// Spec, data, rule, expression and value types
85// -----------------------------------------------------------------------------
86
87use crate::formatting::expression::{
88    CommandSyntax, CommandView, PredicateView, Syntax, SyntaxNode, SyntaxView,
89};
90use crate::parsing::arena::{ExprKind, ExprRef};
91use crate::parsing::source::Source;
92use rust_decimal::Decimal;
93use serde::Serialize;
94use std::cmp::Ordering;
95use std::fmt;
96use std::hash::{Hash, Hasher};
97
98pub use crate::literals::{BooleanValue, DateTimeValue, TimeValue, TimezoneValue, Value};
99
100#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize)]
101#[serde(rename_all = "snake_case")]
102pub enum EffectiveDate {
103    Origin,
104    DateTimeValue(crate::DateTimeValue),
105}
106
107impl EffectiveDate {
108    pub fn as_ref(&self) -> Option<&crate::DateTimeValue> {
109        match self {
110            EffectiveDate::Origin => None,
111            EffectiveDate::DateTimeValue(dt) => Some(dt),
112        }
113    }
114
115    pub fn from_option(opt: Option<crate::DateTimeValue>) -> Self {
116        match opt {
117            None => EffectiveDate::Origin,
118            Some(dt) => EffectiveDate::DateTimeValue(dt),
119        }
120    }
121
122    pub fn to_option(&self) -> Option<crate::DateTimeValue> {
123        match self {
124            EffectiveDate::Origin => None,
125            EffectiveDate::DateTimeValue(dt) => Some(dt.clone()),
126        }
127    }
128
129    pub fn is_origin(&self) -> bool {
130        matches!(self, EffectiveDate::Origin)
131    }
132}
133
134impl PartialOrd for EffectiveDate {
135    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
136        Some(self.cmp(other))
137    }
138}
139
140impl Ord for EffectiveDate {
141    // As ref returns None for Origin, so Origin < DateTimeValue(_).
142    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
143        self.as_ref().cmp(&other.as_ref())
144    }
145}
146
147impl fmt::Display for EffectiveDate {
148    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
149        match self {
150            EffectiveDate::Origin => Ok(()),
151            EffectiveDate::DateTimeValue(dt) => write!(f, "{}", dt),
152        }
153    }
154}
155
156/// A Lemma repository header. Identity carrier; never owns specs.
157///
158/// `name` includes the `@` prefix when present (e.g. `Some("@jack/finance")`).
159/// `None` for the default unnamed repository. Identity (used by
160/// `PartialEq`, `Eq`, `Hash`, and `Ord` for `BTreeMap` keying) is just `name`.
161/// `dependency`, `start_line` and `source_type` are metadata excluded from identity.
162///
163/// `dependency` is the provenance guard: `None` for locally loaded repos,
164/// `Some(id)` for repos introduced by a dependency. All specs in a repo must
165/// share the same `dependency` value — the engine rejects mismatches at load time.
166///
167/// The parser fills [`LemmaRepository`] for each `repo` section before grouping specs in
168/// [`ParseResult`]; loaders set `dependency` when inserting dependency bundles.
169#[derive(Debug, Clone)]
170pub struct LemmaRepository {
171    /// Repository name, including `@` when present. `None` for the default unnamed repository.
172    pub name: Option<String>,
173    /// Dependency provenance: `None` for locally loaded repos, `Some(id)` for dependency repos.
174    /// Not part of identity — used as an isolation guard at load time.
175    pub dependency: Option<String>,
176    pub start_line: usize,
177    pub source_type: Option<crate::parsing::source::SourceType>,
178}
179
180impl LemmaRepository {
181    #[must_use]
182    pub fn new(name: Option<String>) -> Self {
183        Self {
184            name: name.map(ascii_lowercase_logical_name),
185            dependency: None,
186            start_line: 1,
187            source_type: None,
188        }
189    }
190
191    #[must_use]
192    pub fn with_start_line(mut self, start_line: usize) -> Self {
193        self.start_line = start_line;
194        self
195    }
196
197    #[must_use]
198    pub fn with_source_type(mut self, source_type: crate::parsing::source::SourceType) -> Self {
199        self.source_type = Some(source_type);
200        self
201    }
202
203    #[must_use]
204    pub fn with_dependency(mut self, dependency_id: impl Into<String>) -> Self {
205        self.dependency = Some(dependency_id.into());
206        self
207    }
208}
209
210impl PartialEq for LemmaRepository {
211    fn eq(&self, other: &Self) -> bool {
212        self.name == other.name
213    }
214}
215
216impl Eq for LemmaRepository {}
217
218impl PartialOrd for LemmaRepository {
219    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
220        Some(self.cmp(other))
221    }
222}
223
224impl Ord for LemmaRepository {
225    fn cmp(&self, other: &Self) -> Ordering {
226        self.name.cmp(&other.name)
227    }
228}
229
230impl Hash for LemmaRepository {
231    fn hash<H: Hasher>(&self, state: &mut H) {
232        self.name.hash(state);
233    }
234}
235
236/// Textual repository qualifier as written in source (for example `@iso/countries`).
237/// `name` stores the qualifier verbatim, including a leading `@` when present. The planner
238/// resolves a [`RepositoryQualifier`] to an `Arc<LemmaRepository>` against the active context.
239#[derive(Debug, Clone, PartialEq, Eq, Hash)]
240pub struct RepositoryQualifier {
241    pub name: String,
242}
243
244impl RepositoryQualifier {
245    #[must_use]
246    pub fn new(name: impl Into<String>) -> Self {
247        Self {
248            name: ascii_lowercase_logical_name(name.into()),
249        }
250    }
251
252    /// Whether this repository qualifier refers to a registry (e.g., starts with `@`).
253    #[must_use]
254    pub fn is_registry(&self) -> bool {
255        self.name.starts_with('@')
256    }
257}
258
259impl fmt::Display for RepositoryQualifier {
260    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
261        write!(f, "{}", self.name)
262    }
263}
264
265/// A Lemma spec containing data and rules.
266///
267/// Owning repository is carried by [`crate::engine::Context`], not fields here.
268/// Context identity is `(repository, name, EffectiveDate)` or `std::ptr::eq` on a
269/// Context-owned row — not [`PartialEq`]. [`PartialEq`] is full AST equality
270/// (including statement [`Source`] spans) for [`crate::Engine::update`] skip only.
271#[derive(Debug, Clone, PartialEq)]
272pub struct LemmaSpec {
273    pub name: String,
274    pub effective_from: EffectiveDate,
275    pub source_type: Option<crate::parsing::source::SourceType>,
276    pub start_line: usize,
277    pub commentary: Option<String>,
278    pub data: Vec<LemmaData>,
279    pub rules: Vec<LemmaRule>,
280    pub meta_fields: Vec<MetaField>,
281}
282
283#[derive(Debug, Clone, PartialEq)]
284pub struct MetaField {
285    pub key: String,
286    pub value: Value,
287    pub source_location: Source,
288}
289
290impl fmt::Display for MetaField {
291    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
292        write!(f, "meta {}: {}", self.key, AsLemmaSource(&self.value))
293    }
294}
295
296#[derive(Debug, Clone, PartialEq)]
297pub struct LemmaData {
298    pub reference: Reference,
299    pub value: DataValue,
300    pub source_location: Source,
301}
302
303/// An unless clause that provides an alternative result
304///
305/// Unless clauses are evaluated in order, and the last matching condition wins.
306/// This matches natural language: "X unless A then Y, unless B then Z" - if both
307/// A and B are true, Z is returned (the last match).
308#[derive(Debug, Clone, PartialEq)]
309pub struct UnlessClause {
310    pub condition: Expression,
311    pub result: Expression,
312    pub source_location: Source,
313}
314
315/// A rule with a single expression and optional unless clauses
316#[derive(Debug, Clone, PartialEq)]
317pub struct LemmaRule {
318    pub name: String,
319    pub expression: Expression,
320    pub unless_clauses: Vec<UnlessClause>,
321    pub source_location: Source,
322}
323
324/// An expression that can be evaluated, with source location
325///
326/// Expressions use semantic equality: two expressions with the same structure are equal
327/// regardless of source location.
328pub type Expression = ExprTree<ExpressionKind>;
329
330pub use crate::parsing::arena::{ExprId, ExprTable, ExprTree};
331
332/// One operator step of a flat left-associative chain. `source_location` spans from the
333/// start of the chain through `operand`.
334#[derive(Debug, Clone)]
335pub struct ChainStep<Op> {
336    pub op: Op,
337    pub operand: ExprId,
338    pub source_location: Source,
339}
340
341#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
342pub enum LogicalConnective {
343    And,
344    Or,
345}
346
347impl LogicalConnective {
348    #[must_use]
349    pub fn absorbing_operand(self) -> bool {
350        match self {
351            Self::And => false,
352            Self::Or => true,
353        }
354    }
355
356    #[must_use]
357    pub fn keyword(self) -> &'static str {
358        match self {
359            Self::And => "and",
360            Self::Or => "or",
361        }
362    }
363}
364
365/// Semantic equality as for [`Expression`]: the step's span is not part of its identity.
366impl<Op: PartialEq> PartialEq for ChainStep<Op> {
367    fn eq(&self, other: &Self) -> bool {
368        self.op == other.op && self.operand == other.operand
369    }
370}
371
372impl<Op: Eq> Eq for ChainStep<Op> {}
373
374/// Whether a date is relative to `now` in the past or future direction.
375#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
376#[serde(rename_all = "snake_case")]
377pub enum DateRelativeKind {
378    InPast,
379    InFuture,
380}
381
382/// Calendar-period membership checks.
383#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
384#[serde(rename_all = "snake_case")]
385pub enum DateCalendarKind {
386    Current,
387    Past,
388    Future,
389    NotIn,
390}
391
392/// Granularity of a calendar-period check.
393#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
394#[serde(rename_all = "snake_case")]
395pub enum CalendarPeriodUnit {
396    Year,
397    Month,
398    Week,
399}
400
401impl CalendarPeriodUnit {
402    #[must_use]
403    pub fn from_keyword(s: &str) -> Option<Self> {
404        match s.trim().to_lowercase().as_str() {
405            "year" => Some(Self::Year),
406            "month" => Some(Self::Month),
407            "week" => Some(Self::Week),
408            _ => None,
409        }
410    }
411}
412
413impl fmt::Display for DateRelativeKind {
414    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
415        match self {
416            DateRelativeKind::InPast => write!(f, "in past"),
417            DateRelativeKind::InFuture => write!(f, "in future"),
418        }
419    }
420}
421
422impl fmt::Display for DateCalendarKind {
423    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
424        match self {
425            DateCalendarKind::Current => write!(f, "in calendar"),
426            DateCalendarKind::Past => write!(f, "in past calendar"),
427            DateCalendarKind::Future => write!(f, "in future calendar"),
428            DateCalendarKind::NotIn => write!(f, "not in calendar"),
429        }
430    }
431}
432
433impl fmt::Display for CalendarPeriodUnit {
434    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
435        match self {
436            CalendarPeriodUnit::Year => write!(f, "year"),
437            CalendarPeriodUnit::Month => write!(f, "month"),
438            CalendarPeriodUnit::Week => write!(f, "week"),
439        }
440    }
441}
442
443/// The kind/type of expression
444#[derive(Debug, Clone, PartialEq)]
445pub enum ExpressionKind {
446    /// Parse-time literal value (type will be resolved during planning)
447    Literal(Value),
448    /// Parser-only current value-list row inside a headless predicate comparison.
449    ImplicitRowValue,
450    /// Unresolved reference (identifier or dot path). Resolved during planning to DataPath or RulePath.
451    Reference(Reference),
452    /// The `now` keyword — resolves to the evaluation datetime (= effective).
453    Now,
454    /// Date-relative sugar: `<date_expr> in past` / `<date_expr> in future`
455    /// Fields: (kind, date_expression)
456    DateRelative(DateRelativeKind, ExprId),
457    /// Calendar-period sugar: `<date_expr> in [past|future] calendar year|month|week`
458    /// Fields: (kind, unit, date_expression)
459    DateCalendar(DateCalendarKind, CalendarPeriodUnit, ExprId),
460    /// Range literal: `{left_expr}...{right_expr}`
461    RangeLiteral(ExprId, ExprId),
462    /// Relative date range: `past 7 day` / `future 30 day`
463    PastFutureRange(DateRelativeKind, ExprId),
464    /// Range containment: `{value_expr} in {range_expr}`
465    RangeContainment(ExprId, ExprId),
466    /// Ordered endpoint of a range: `lower` (included) or `upper` (excluded).
467    RangeBound(RangeBound, ExprId),
468    /// One left fold of one logical connective, operands in source order.
469    Logical {
470        connective: LogicalConnective,
471        first: ExprId,
472        steps: Vec<ChainStep<()>>,
473    },
474    /// `a + b - c * d`: one left fold per precedence level, operands in source order.
475    Arithmetic {
476        first: ExprId,
477        steps: Vec<ChainStep<ArithmeticComputation>>,
478    },
479    Comparison(ExprId, ComparisonComputation, ExprId),
480    UnitConversion(ExprId, ConversionTarget),
481    LogicalNegation(ExprId, NegationType),
482    MathematicalComputation(MathematicalComputation, ExprId),
483    Veto(VetoExpression),
484    /// `expr is veto` / `veto is expr` — boolean: whether evaluating `expr` yields `OperationResult::Veto`.
485    ResultIsVeto(ExprId),
486    /// Type in expression position: `text list`, `money list`, `money range list`.
487    ListType {
488        element: ParentType,
489    },
490    /// Postfix `->` list command: `fares -> sum`, `fares -> where >= 100 eur`.
491    ListCommand {
492        list: ExprId,
493        command: ListCommand,
494    },
495    /// Postfix `->` rounding: `x -> round`, or `price -> round 0.05 eur` with a step.
496    StepRounding {
497        operand: ExprId,
498        mode: RoundingMode,
499        step: Option<ExprId>,
500    },
501    /// Postfix member read on a parenthesised expression: `(staff -> find "ada").salary`.
502    Member {
503        base: ExprId,
504        path: Reference,
505    },
506}
507
508impl ExprKind for ExpressionKind {
509    fn for_each_child(&self, mut f: impl FnMut(ExprId)) {
510        match self {
511            ExpressionKind::Literal(_)
512            | ExpressionKind::ImplicitRowValue
513            | ExpressionKind::Reference(_)
514            | ExpressionKind::Now
515            | ExpressionKind::Veto(_)
516            | ExpressionKind::ListType { .. } => {}
517            ExpressionKind::DateRelative(_, inner)
518            | ExpressionKind::DateCalendar(_, _, inner)
519            | ExpressionKind::PastFutureRange(_, inner)
520            | ExpressionKind::RangeBound(_, inner)
521            | ExpressionKind::UnitConversion(inner, _)
522            | ExpressionKind::LogicalNegation(inner, _)
523            | ExpressionKind::MathematicalComputation(_, inner)
524            | ExpressionKind::ResultIsVeto(inner)
525            | ExpressionKind::Member { base: inner, .. } => f(*inner),
526            ExpressionKind::RangeLiteral(left, right)
527            | ExpressionKind::RangeContainment(left, right)
528            | ExpressionKind::Comparison(left, _, right) => {
529                f(*left);
530                f(*right);
531            }
532            ExpressionKind::StepRounding { operand, step, .. } => {
533                f(*operand);
534                if let Some(step) = step {
535                    f(*step);
536                }
537            }
538            ExpressionKind::Logical { first, steps, .. } => {
539                f(*first);
540                steps.iter().for_each(|step| f(step.operand));
541            }
542            ExpressionKind::Arithmetic { first, steps } => {
543                f(*first);
544                steps.iter().for_each(|step| f(step.operand));
545            }
546            ExpressionKind::ListCommand { list, command } => {
547                f(*list);
548                command.for_each_child(f);
549            }
550        }
551    }
552
553    fn children_mut(&mut self) -> Vec<&mut ExprId> {
554        match self {
555            ExpressionKind::Literal(_)
556            | ExpressionKind::ImplicitRowValue
557            | ExpressionKind::Reference(_)
558            | ExpressionKind::Now
559            | ExpressionKind::Veto(_)
560            | ExpressionKind::ListType { .. } => Vec::new(),
561            ExpressionKind::DateRelative(_, inner)
562            | ExpressionKind::DateCalendar(_, _, inner)
563            | ExpressionKind::PastFutureRange(_, inner)
564            | ExpressionKind::RangeBound(_, inner)
565            | ExpressionKind::UnitConversion(inner, _)
566            | ExpressionKind::LogicalNegation(inner, _)
567            | ExpressionKind::MathematicalComputation(_, inner)
568            | ExpressionKind::ResultIsVeto(inner)
569            | ExpressionKind::Member { base: inner, .. } => vec![inner],
570            ExpressionKind::RangeLiteral(left, right)
571            | ExpressionKind::RangeContainment(left, right)
572            | ExpressionKind::Comparison(left, _, right) => vec![left, right],
573            ExpressionKind::StepRounding { operand, step, .. } => {
574                let mut children = vec![operand];
575                if let Some(step) = step {
576                    children.push(step);
577                }
578                children
579            }
580            ExpressionKind::Logical { first, steps, .. } => std::iter::once(first)
581                .chain(steps.iter_mut().map(|step| &mut step.operand))
582                .collect(),
583            ExpressionKind::Arithmetic { first, steps } => std::iter::once(first)
584                .chain(steps.iter_mut().map(|step| &mut step.operand))
585                .collect(),
586            ExpressionKind::ListCommand { list, command } => std::iter::once(list)
587                .chain(command.children_mut())
588                .collect(),
589        }
590    }
591}
592
593impl ListCommand {
594    fn for_each_child(&self, mut f: impl FnMut(ExprId)) {
595        match self {
596            ListCommand::First
597            | ListCommand::Last
598            | ListCommand::Count
599            | ListCommand::Key { .. } => {}
600            ListCommand::Find { keys } => keys.iter().copied().for_each(f),
601            ListCommand::Sum { argument }
602            | ListCommand::Avg { argument }
603            | ListCommand::Product { argument }
604            | ListCommand::Min { argument }
605            | ListCommand::Max { argument }
606            | ListCommand::Sort { argument, .. } => argument.iter().copied().for_each(f),
607            ListCommand::Any { form } | ListCommand::All { form } | ListCommand::Where { form } => {
608                match form {
609                    ListPredicate::Value { expr } => f(*expr),
610                    ListPredicate::Instance { expr } => f(*expr),
611                }
612            }
613            ListCommand::Top { n } => f(*n),
614            ListCommand::With { rows } => match rows {
615                ListWithRows::Values(values) => values.iter().copied().for_each(f),
616                ListWithRows::FieldPairs(pairs) => pairs.iter().for_each(|(_, value)| f(*value)),
617            },
618        }
619    }
620
621    fn children_mut(&mut self) -> Vec<&mut ExprId> {
622        match self {
623            ListCommand::First
624            | ListCommand::Last
625            | ListCommand::Count
626            | ListCommand::Key { .. } => Vec::new(),
627            ListCommand::Find { keys } => keys.iter_mut().collect(),
628            ListCommand::Sum { argument }
629            | ListCommand::Avg { argument }
630            | ListCommand::Product { argument }
631            | ListCommand::Min { argument }
632            | ListCommand::Max { argument }
633            | ListCommand::Sort { argument, .. } => argument.iter_mut().collect(),
634            ListCommand::Any { form } | ListCommand::All { form } | ListCommand::Where { form } => {
635                match form {
636                    ListPredicate::Value { expr } => vec![expr],
637                    ListPredicate::Instance { expr } => vec![expr],
638                }
639            }
640            ListCommand::Top { n } => vec![n],
641            ListCommand::With { rows } => match rows {
642                ListWithRows::Values(values) => values.iter_mut().collect(),
643                ListWithRows::FieldPairs(pairs) => {
644                    pairs.iter_mut().map(|(_, value)| value).collect()
645                }
646            },
647        }
648    }
649}
650
651/// One postfix `->` command on a list-valued expression.
652#[derive(Debug, Clone, PartialEq)]
653pub enum ListCommand {
654    Find {
655        keys: Vec<ExprId>,
656    },
657    First,
658    Last,
659    Sum {
660        argument: Option<ExprId>,
661    },
662    Avg {
663        argument: Option<ExprId>,
664    },
665    Product {
666        argument: Option<ExprId>,
667    },
668    Count,
669    Min {
670        argument: Option<ExprId>,
671    },
672    Max {
673        argument: Option<ExprId>,
674    },
675    Any {
676        form: ListPredicate,
677    },
678    All {
679        form: ListPredicate,
680    },
681    Where {
682        form: ListPredicate,
683    },
684    Sort {
685        descending: bool,
686        argument: Option<ExprId>,
687    },
688    Top {
689        n: ExprId,
690    },
691    With {
692        rows: ListWithRows,
693    },
694    /// `-> key a, b` on a Spec-element list expression.
695    Key {
696        fields: Vec<Reference>,
697    },
698}
699
700/// Operator of a value-list condition; the row value is the implicit left operand.
701#[derive(Debug, Clone, PartialEq, Eq, Hash)]
702pub enum RowCondition {
703    Compare(ComparisonComputation),
704    In,
705}
706
707impl fmt::Display for RowCondition {
708    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
709        match self {
710            RowCondition::Compare(op) => write!(f, "{op}"),
711            RowCondition::In => write!(f, "in"),
712        }
713    }
714}
715
716/// `where` / `any` / `all` argument: value-list comparison, or instance-list expression.
717#[derive(Debug, Clone, PartialEq)]
718pub enum ListPredicate {
719    Value { expr: ExprId },
720    Instance { expr: ExprId },
721}
722
723#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
724pub enum ListPredicateForm {
725    Value,
726    Instance,
727}
728
729/// `-> with` rows on a list expression.
730#[derive(Debug, Clone, PartialEq)]
731pub enum ListWithRows {
732    Values(Vec<ExprId>),
733    FieldPairs(Vec<(Reference, ExprId)>),
734}
735
736/// Unresolved reference from parser
737///
738/// Reference to a data or rule (identifier or dot path).
739///
740/// Used in expressions and in LemmaData. During planning, references
741/// are resolved to DataPath or RulePath (semantics layer).
742/// Examples:
743/// - Local "age": segments=[], name="age"
744/// - Cross-spec "employee.salary": segments=["employee"], name="salary"
745#[derive(Debug, Clone, PartialEq, Eq, Hash)]
746pub struct Reference {
747    pub segments: Vec<String>,
748    pub name: String,
749}
750
751impl Reference {
752    #[must_use]
753    pub fn local(name: String) -> Self {
754        Self {
755            segments: Vec::new(),
756            name: ascii_lowercase_logical_name(name),
757        }
758    }
759
760    #[must_use]
761    pub fn from_path(path: Vec<String>) -> Self {
762        if path.is_empty() {
763            Self {
764                segments: Vec::new(),
765                name: String::new(),
766            }
767        } else {
768            // Safe: path is non-empty.
769            let name = ascii_lowercase_logical_name(path[path.len() - 1].clone());
770            let segments = path[..path.len() - 1]
771                .iter()
772                .map(|segment| ascii_lowercase_logical_name(segment.clone()))
773                .collect();
774            Self { segments, name }
775        }
776    }
777
778    #[must_use]
779    pub fn is_local(&self) -> bool {
780        self.segments.is_empty()
781    }
782
783    #[must_use]
784    pub fn full_path(&self) -> Vec<String> {
785        let mut path = self.segments.clone();
786        path.push(self.name.clone());
787        path
788    }
789}
790
791impl fmt::Display for Reference {
792    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
793        for segment in &self.segments {
794            write!(f, "{}.", segment)?;
795        }
796        write!(f, "{}", self.name)
797    }
798}
799
800/// Arithmetic computations
801#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, serde::Deserialize)]
802#[serde(rename_all = "snake_case")]
803pub enum ArithmeticComputation {
804    Add,
805    Subtract,
806    Multiply,
807    Divide,
808    Modulo,
809    Power,
810}
811
812/// Comparison computations
813#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, serde::Deserialize)]
814#[serde(rename_all = "snake_case")]
815pub enum ComparisonComputation {
816    GreaterThan,
817    LessThan,
818    GreaterThanOrEqual,
819    LessThanOrEqual,
820    Is,
821    IsNot,
822}
823
824impl ComparisonComputation {
825    /// Check if this is an equality comparison (`is`)
826    #[must_use]
827    pub fn is_equal(&self) -> bool {
828        matches!(self, ComparisonComputation::Is)
829    }
830
831    /// Check if this is an inequality comparison (`is not`)
832    #[must_use]
833    pub fn is_not_equal(&self) -> bool {
834        matches!(self, ComparisonComputation::IsNot)
835    }
836}
837
838/// Primitive kind that can appear as an `as` conversion target. Excludes `Text`
839/// (display formatting is not a conversion) and the range kinds (a range is not
840/// a cast target — use a range literal or `...` operator instead). The parser
841/// rejects `as text` at the `as` target position; `data x: text` declarations
842/// still use [`PrimitiveKind::Text`] via [`crate::parsing::lexer::token_kind_to_primitive`].
843#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
844#[serde(rename_all = "snake_case")]
845pub enum ConversionTypeKind {
846    Boolean,
847    Measure,
848    Number,
849    Ratio,
850    Date,
851    Time,
852}
853
854impl fmt::Display for ConversionTypeKind {
855    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
856        let s = match self {
857            ConversionTypeKind::Boolean => "boolean",
858            ConversionTypeKind::Measure => "measure",
859            ConversionTypeKind::Number => "number",
860            ConversionTypeKind::Ratio => "ratio",
861            ConversionTypeKind::Date => "date",
862            ConversionTypeKind::Time => "time",
863        };
864        write!(f, "{}", s)
865    }
866}
867
868impl ConversionTypeKind {
869    /// The [`PrimitiveKind`] that corresponds to this conversion target kind.
870    #[must_use]
871    pub fn to_primitive_kind(self) -> PrimitiveKind {
872        match self {
873            ConversionTypeKind::Boolean => PrimitiveKind::Boolean,
874            ConversionTypeKind::Measure => PrimitiveKind::Measure,
875            ConversionTypeKind::Number => PrimitiveKind::Number,
876            ConversionTypeKind::Ratio => PrimitiveKind::Ratio,
877            ConversionTypeKind::Date => PrimitiveKind::Date,
878            ConversionTypeKind::Time => PrimitiveKind::Time,
879        }
880    }
881}
882
883/// The target type for `as` cast expressions (e.g. `as number`, `as eur`).
884#[derive(Debug, Clone, PartialEq, Eq, Hash)]
885pub enum ConversionTarget {
886    Type(ConversionTypeKind),
887    Unit { unit_name: String },
888}
889
890/// Types of logical negation
891#[derive(Debug, Clone, PartialEq, Eq, Hash)]
892pub enum NegationType {
893    Not,
894}
895
896/// A veto expression that prohibits any valid verdict from the rule
897///
898/// A veto prevents the rule from producing any valid result. This is used for
899/// validation and constraint enforcement — distinct from boolean `false`.
900///
901/// Example: `veto "Must be over 18"` - blocks the rule entirely with a message
902#[derive(Debug, Clone, PartialEq, Eq, Hash)]
903pub struct VetoExpression {
904    pub message: Option<String>,
905}
906
907/// Mathematical computations
908#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, serde::Deserialize)]
909pub enum MathematicalComputation {
910    Sqrt,
911    Sin,
912    Cos,
913    Tan,
914    Asin,
915    Acos,
916    Atan,
917    Log,
918    Exp,
919    Abs,
920}
921
922/// Direction of a `-> round|floor|ceil <step>` command.
923#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, serde::Deserialize)]
924#[serde(rename_all = "snake_case")]
925pub enum RoundingMode {
926    /// Nearest multiple; an exact half goes away from zero.
927    Round,
928    /// Largest multiple at or below.
929    Floor,
930    /// Smallest multiple at or above.
931    Ceil,
932}
933
934impl RoundingMode {
935    pub fn keyword(self) -> &'static str {
936        match self {
937            RoundingMode::Round => "round",
938            RoundingMode::Floor => "floor",
939            RoundingMode::Ceil => "ceil",
940        }
941    }
942}
943
944impl fmt::Display for RoundingMode {
945    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
946        f.write_str(self.keyword())
947    }
948}
949
950/// Which endpoint of a range `lower` / `upper` reads.
951#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, serde::Deserialize)]
952pub enum RangeBound {
953    Lower,
954    Upper,
955}
956
957impl fmt::Display for RangeBound {
958    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
959        match self {
960            RangeBound::Lower => write!(f, "lower"),
961            RangeBound::Upper => write!(f, "upper"),
962        }
963    }
964}
965
966/// A spec reference written in source.
967///
968/// [`SpecRef::repository`] is `None` for same-repository references, or
969/// `Some(RepositoryQualifier)` when a repository qualifier was written before the spec name.
970/// `effective` carries an optional explicit pin written next to the spec name.
971#[derive(Debug, Clone, PartialEq)]
972pub struct SpecRef {
973    /// Optional explicit repository qualifier. `None` means the reference resolves against
974    /// the consumer spec's own repository.
975    pub repository: Option<RepositoryQualifier>,
976    /// The spec name.
977    pub name: String,
978    /// Optional explicit effective datetime pin written in source.
979    pub effective: Option<DateTimeValue>,
980    /// Source span of the repository qualifier (when `repository` is present).
981    pub repository_span: Option<Span>,
982    /// Source span of `name` and optional `effective`.
983    pub target_span: Option<Span>,
984}
985
986impl std::fmt::Display for SpecRef {
987    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
988        if let Some(qualifier) = &self.repository {
989            write!(f, "{} ", qualifier)?;
990        }
991        write!(f, "{}", self.name)?;
992        if let Some(d) = &self.effective {
993            write!(f, " {}", d)?;
994        }
995        Ok(())
996    }
997}
998
999impl SpecRef {
1000    /// Same-repository reference: resolution uses the consumer's repository.
1001    pub fn same_repository(name: impl Into<String>) -> Self {
1002        Self {
1003            name: ascii_lowercase_logical_name(name.into()),
1004            repository: None,
1005            effective: None,
1006            repository_span: None,
1007            target_span: None,
1008        }
1009    }
1010
1011    /// Cross-repository reference with an explicit repository qualifier.
1012    pub fn cross_repository(name: impl Into<String>, qualifier: RepositoryQualifier) -> Self {
1013        Self {
1014            name: ascii_lowercase_logical_name(name.into()),
1015            repository: Some(qualifier),
1016            effective: None,
1017            repository_span: None,
1018            target_span: None,
1019        }
1020    }
1021
1022    /// Resolve the effective instant for this reference given the planning slice's `effective`.
1023    /// Explicit qualifier on the reference wins; otherwise inherits the slice instant.
1024    pub fn at(&self, effective: &EffectiveDate) -> EffectiveDate {
1025        self.effective
1026            .clone()
1027            .map_or_else(|| effective.clone(), EffectiveDate::DateTimeValue)
1028    }
1029
1030    /// Concrete instant for evaluation or navigation: explicit ref pin wins, else consumer bound.
1031    /// Returns `None` when neither side names a concrete instant (consumer at Origin, no ref pin).
1032    pub fn resolved_instant(
1033        &self,
1034        consumer_effective_from: Option<&DateTimeValue>,
1035    ) -> Option<DateTimeValue> {
1036        self.effective
1037            .clone()
1038            .or_else(|| consumer_effective_from.cloned())
1039    }
1040}
1041
1042/// A single factor in a compound unit expression.
1043///
1044/// `measure_ref` is the name of the referenced unit (e.g. `"meter"`, `"second"`).
1045/// `exp` is the integer exponent, positive for numerator and negative for denominator.
1046/// For example `meter/second^2` produces:
1047/// - `UnitFactor { measure_ref: "meter", exp: 1 }`
1048/// - `UnitFactor { measure_ref: "second", exp: -2 }`
1049#[derive(Debug, Clone, PartialEq, Eq)]
1050pub struct UnitFactor {
1051    pub measure_ref: String,
1052    pub exp: i32,
1053}
1054
1055/// The argument to a `-> unit <name> ...` command, either a plain numeric
1056/// conversion factor, a compound unit expression, or a reference to a
1057/// `number`-typed data field or rule used as a dynamic scale.
1058///
1059/// - `Factor(v)` — simple unit: `-> unit meter: 1`, `-> unit kilometer: 1000`
1060/// - `Expr(prefix, factors)` — compound unit: `-> unit mps: meter/second`,
1061///   `-> unit kmh: 3.6 meter/second`
1062///   The `prefix` is an additional scalar multiplier beyond what the unit
1063///   factor references contribute; it defaults to `1` when omitted.
1064/// - `Reference(r)` — bare or dotted identifier path without `*` `/` `^`.
1065///   Planning classifies it as a dynamic scale (local data/rule or `uses.member`)
1066///   or rewrites a resolvable unit path into a factor-1 compound. A name that is
1067///   both a local data/rule and a unit path is a planning error.
1068#[derive(Debug, Clone, PartialEq, Eq)]
1069pub enum UnitArg {
1070    Factor(Decimal),
1071    Expr(Decimal, Vec<UnitFactor>),
1072    Reference(Reference),
1073}
1074
1075impl fmt::Display for UnitArg {
1076    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1077        match self {
1078            UnitArg::Factor(v) => write!(f, "{}", v),
1079            UnitArg::Expr(prefix, factors) => {
1080                if *prefix != Decimal::ONE {
1081                    write!(f, "{} ", prefix)?;
1082                }
1083                for (index, factor) in factors.iter().enumerate() {
1084                    if factor.exp == 0 {
1085                        unreachable!("BUG: unit factor exponent cannot be zero");
1086                    }
1087                    // `/` divides by the one factor after it and cannot start an
1088                    // expression, so a leading negative factor keeps its exponent.
1089                    let exponent = if index == 0 {
1090                        write!(f, "{}", factor.measure_ref)?;
1091                        factor.exp
1092                    } else {
1093                        let operator = if factor.exp > 0 { " * " } else { "/" };
1094                        write!(f, "{operator}{}", factor.measure_ref)?;
1095                        factor
1096                            .exp
1097                            .checked_abs()
1098                            .expect("BUG: unit factor exponent magnitude")
1099                    };
1100                    if exponent != 1 {
1101                        write!(f, "^{exponent}")?;
1102                    }
1103                }
1104                Ok(())
1105            }
1106            UnitArg::Reference(reference) => write!(f, "{reference}"),
1107        }
1108    }
1109}
1110
1111/// A parsed constraint command argument, preserving the literal kind from the
1112/// grammar rule `command_arg: { number_literal | boolean_literal | text_literal | label }`.
1113///
1114/// Three grammatical kinds appear after a constraint command:
1115/// - **Literal** — a fully-typed value carrying the literal kind the parser
1116///   recognised (`Number`, `Ratio`, `Measure`, `Date`, `Time`,
1117///   `Boolean`, `Text`). Stored as the canonical [`crate::literals::Value`]
1118///   so downstream consumers match on the variant rather than re-parsing strings.
1119/// - **Label** — a bare identifier used as a name (e.g. the unit name `eur`
1120///   in `unit eur 1.00`, or a primitive type keyword used as an option label).
1121/// - **UnitExpr** — compound unit expression produced by the parser for
1122///   `-> unit <name> ...` commands. Only appears as the second argument of a
1123///   `Unit` command; the first argument is always the unit name as `Label`.
1124///
1125/// Planning validates each command's args against the variant kinds it accepts
1126/// and rejects mismatches without coercion (a `Text` literal is never a `Number`,
1127/// a `Ratio` literal is never a bare `Number`, etc.).
1128#[derive(Debug, Clone, PartialEq, Eq)]
1129pub enum CommandArg {
1130    /// A typed literal value parsed by [`crate::parsing::parser::Parser::parse_literal_value`].
1131    Literal(crate::literals::Value),
1132    /// An identifier used as a name (unit name, option keyword, etc.).
1133    Label(String),
1134    /// A unit argument produced by the parser for `-> unit <name> ...` commands.
1135    UnitExpr(UnitArg),
1136}
1137
1138impl fmt::Display for CommandArg {
1139    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1140        match self {
1141            CommandArg::Literal(v) => write!(f, "{}", v),
1142            CommandArg::Label(s) => write!(f, "{}", s),
1143            CommandArg::UnitExpr(unit_arg) => write!(f, "{}", unit_arg),
1144        }
1145    }
1146}
1147
1148/// Constraint command for type definitions. Derived from lexer tokens; no string matching.
1149#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1150pub enum TypeConstraintCommand {
1151    Help,
1152    Suggest,
1153    With,
1154    Unit,
1155    Trait,
1156    Minimum,
1157    Maximum,
1158    Lower,
1159    Upper,
1160    Decimals,
1161    Option,
1162    Options,
1163    Length,
1164}
1165
1166impl fmt::Display for TypeConstraintCommand {
1167    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1168        let s = match self {
1169            TypeConstraintCommand::Help => "help",
1170            TypeConstraintCommand::Suggest => "suggest",
1171            TypeConstraintCommand::With => "with",
1172            TypeConstraintCommand::Unit => "unit",
1173            TypeConstraintCommand::Trait => "trait",
1174            TypeConstraintCommand::Minimum => "minimum",
1175            TypeConstraintCommand::Maximum => "maximum",
1176            TypeConstraintCommand::Lower => "lower",
1177            TypeConstraintCommand::Upper => "upper",
1178            TypeConstraintCommand::Decimals => "decimals",
1179            TypeConstraintCommand::Option => "option",
1180            TypeConstraintCommand::Options => "options",
1181            TypeConstraintCommand::Length => "length",
1182        };
1183        write!(f, "{}", s)
1184    }
1185}
1186
1187/// Parses a constraint command name. Returns None for unknown (parser returns error).
1188#[must_use]
1189pub fn try_parse_type_constraint_command(s: &str) -> Option<TypeConstraintCommand> {
1190    // ASCII fold without allocating a lowercased String on every `->` command.
1191    match s.trim() {
1192        s if s.eq_ignore_ascii_case("help") => Some(TypeConstraintCommand::Help),
1193        s if s.eq_ignore_ascii_case("suggest") => Some(TypeConstraintCommand::Suggest),
1194        s if s.eq_ignore_ascii_case("with") => Some(TypeConstraintCommand::With),
1195        s if s.eq_ignore_ascii_case("unit") => Some(TypeConstraintCommand::Unit),
1196        s if s.eq_ignore_ascii_case("trait") => Some(TypeConstraintCommand::Trait),
1197        s if s.eq_ignore_ascii_case("minimum") => Some(TypeConstraintCommand::Minimum),
1198        s if s.eq_ignore_ascii_case("maximum") => Some(TypeConstraintCommand::Maximum),
1199        s if s.eq_ignore_ascii_case("lower") => Some(TypeConstraintCommand::Lower),
1200        s if s.eq_ignore_ascii_case("upper") => Some(TypeConstraintCommand::Upper),
1201        s if s.eq_ignore_ascii_case("decimals") => Some(TypeConstraintCommand::Decimals),
1202        s if s.eq_ignore_ascii_case("option") => Some(TypeConstraintCommand::Option),
1203        s if s.eq_ignore_ascii_case("options") => Some(TypeConstraintCommand::Options),
1204        s if s.eq_ignore_ascii_case("length") => Some(TypeConstraintCommand::Length),
1205        _ => None,
1206    }
1207}
1208
1209/// Whether a `->` continuation uses assignment (`key: value`), one argument, or a comma list.
1210#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1211pub enum ContinuationShape {
1212    Assignment,
1213    Single,
1214    CommaSeparated,
1215}
1216
1217impl TypeConstraintCommand {
1218    #[must_use]
1219    pub fn continuation_shape(self) -> ContinuationShape {
1220        match self {
1221            TypeConstraintCommand::Unit => ContinuationShape::Assignment,
1222            TypeConstraintCommand::With | TypeConstraintCommand::Options => {
1223                ContinuationShape::CommaSeparated
1224            }
1225            TypeConstraintCommand::Help
1226            | TypeConstraintCommand::Suggest
1227            | TypeConstraintCommand::Trait
1228            | TypeConstraintCommand::Minimum
1229            | TypeConstraintCommand::Maximum
1230            | TypeConstraintCommand::Lower
1231            | TypeConstraintCommand::Upper
1232            | TypeConstraintCommand::Decimals
1233            | TypeConstraintCommand::Option
1234            | TypeConstraintCommand::Length => ContinuationShape::Single,
1235        }
1236    }
1237
1238    pub const ALL: &[Self] = &[
1239        Self::Help,
1240        Self::Suggest,
1241        Self::With,
1242        Self::Unit,
1243        Self::Trait,
1244        Self::Minimum,
1245        Self::Maximum,
1246        Self::Lower,
1247        Self::Upper,
1248        Self::Decimals,
1249        Self::Option,
1250        Self::Options,
1251        Self::Length,
1252    ];
1253
1254    /// Data-declaration `->` commands (not list-expression postfix queries).
1255    #[must_use]
1256    pub fn is_data_constraint(self) -> bool {
1257        true
1258    }
1259}
1260
1261/// One `-> command …` row on a [`DataValue::Definition`].
1262#[derive(Debug, Clone, PartialEq)]
1263pub struct Constraint {
1264    pub command: TypeConstraintCommand,
1265    pub args: Vec<CommandArg>,
1266    pub source_location: crate::parsing::source::Source,
1267    /// Parsed from deprecated `unit name value` without colon (removed in a future release).
1268    pub deprecated_without_colon: bool,
1269}
1270
1271impl Constraint {
1272    #[must_use]
1273    pub fn new(
1274        command: TypeConstraintCommand,
1275        args: Vec<CommandArg>,
1276        source_location: crate::parsing::source::Source,
1277    ) -> Self {
1278        Self {
1279            command,
1280            args,
1281            source_location,
1282            deprecated_without_colon: false,
1283        }
1284    }
1285}
1286
1287#[cfg(test)]
1288pub(crate) fn test_constraint(command: TypeConstraintCommand, args: Vec<CommandArg>) -> Constraint {
1289    Constraint::new(
1290        command,
1291        args,
1292        crate::parsing::source::Source::new(
1293            crate::parsing::source::SourceType::Volatile,
1294            Span {
1295                start: 0,
1296                end: 0,
1297                line: 1,
1298                col: 0,
1299            },
1300        ),
1301    )
1302}
1303
1304/// Single literal/reference right-hand side used by inline instance-list rows.
1305#[derive(Debug, Clone, PartialEq)]
1306pub enum WithRhs {
1307    Literal(Value),
1308    Reference { target: Reference },
1309}
1310
1311/// One `-> with path: value` row under a [`DataValue::Import`] block.
1312#[derive(Debug, Clone, PartialEq)]
1313pub struct UsesBinding {
1314    /// Path relative to the imported spec (no import alias prefix).
1315    pub path: Reference,
1316    pub rhs: UsesBindingRhs,
1317    pub source_location: Source,
1318}
1319
1320/// Right-hand side of one import `-> with path: ...` binding.
1321#[derive(Debug, Clone, PartialEq)]
1322pub enum UsesBindingRhs {
1323    Literal(Value),
1324    References { targets: Vec<Reference> },
1325}
1326
1327/// One field assignment in an inline instance-list or option row.
1328#[derive(Debug, Clone, PartialEq)]
1329pub struct RowBinding {
1330    pub path: Reference,
1331    pub rhs: WithRhs,
1332    pub source_location: Source,
1333}
1334
1335/// Prefix import alias onto a relative binding path (`pricing.tax_rate` under alias `line` → `line.pricing.tax_rate`).
1336#[must_use]
1337pub fn prefix_reference(alias: &str, relative: &Reference) -> Reference {
1338    let mut segments = vec![ascii_lowercase_logical_name(alias.to_string())];
1339    segments.extend(relative.segments.iter().cloned());
1340    Reference {
1341        segments,
1342        name: relative.name.clone(),
1343    }
1344}
1345
1346#[derive(Debug, Clone, PartialEq)]
1347/// Parse-time data value (before type resolution)
1348pub enum DataValue {
1349    /// Declares data: optional explicit parent type, optional constraints (`-> ...`),
1350    /// optional literal value, and optional instance-list body (`-> key` / `-> with` rows).
1351    ///
1352    /// Examples:
1353    /// - `data x: 3.14` → `base: None`, `value: Some(Number)`
1354    /// - `data x: number -> minimum 0` → `base: Some(Number)`, `constraints: Some(...)`
1355    /// - `data x: finance.money` → `base: Some(Qualified { spec_alias: "finance", inner: Custom("money") })`
1356    /// - `data staff: employee list -> with name: "Ada"` → `base: Some(List { … })`, `list: Some(…)`
1357    ///
1358    /// Value-list rows stay in `constraints` (`money list -> with 89 eur`). Instance-list
1359    /// `-> key` and field / named-instance rows live in `list`.
1360    Definition {
1361        base: Option<ParentType>,
1362        constraints: Option<Vec<Constraint>>,
1363        value: Option<Value>,
1364        list: Option<InstanceListBody>,
1365    },
1366    /// Import from another spec (surface syntax is `uses`; alias is [`LemmaData::reference`]).
1367    /// `effective_ref` is `-> effective <ref>` on the uses block; mutually exclusive with
1368    /// a trailing literal pin on [`SpecRef::effective`].
1369    /// `global` is `uses global`: the slot reads the declaring repository's one instance
1370    /// of the target in an evaluation. Its `bindings` write on that instance.
1371    Import {
1372        spec_ref: SpecRef,
1373        bindings: Vec<UsesBinding>,
1374        effective_ref: Option<Reference>,
1375        global: bool,
1376    },
1377    /// `uses` names one spec. A list after that target is a parse error, so planning
1378    /// never sees this variant. It stays so matches stay exhaustive with the published type.
1379    ImportList {
1380        spec_ref: SpecRef,
1381        list: InstanceListBody,
1382    },
1383    /// `uses x -> with f: v` inside `spec x`, which holds a list of its own rows
1384    /// (`data xs: x list`): what the spec writes on those rows. It is no instance; planning rejects it.
1385    OwnRows {
1386        spec_ref: SpecRef,
1387        bindings: Vec<UsesBinding>,
1388    },
1389}
1390
1391/// Instance-list body on `data x: spec list`: `-> key` and `-> with` rows.
1392#[derive(Debug, Clone, PartialEq)]
1393pub struct InstanceListBody {
1394    pub key: Option<InstanceListKey>,
1395    pub rows: Vec<InstanceListRow>,
1396    /// `-> option` field rows. These constrain the list. They are not list rows.
1397    pub option_rows: Vec<InstanceListRow>,
1398}
1399
1400/// `-> key a, b` under a data instance list.
1401#[derive(Debug, Clone, PartialEq)]
1402pub struct InstanceListKey {
1403    pub fields: Vec<Reference>,
1404    pub source_location: Source,
1405}
1406
1407/// One `-> with` line under a data instance list.
1408#[derive(Debug, Clone, PartialEq)]
1409pub enum InstanceListRow {
1410    /// `-> with drink: "latte", price: 3.50 eur`: one row.
1411    Fields {
1412        bindings: Vec<RowBinding>,
1413        source_location: Source,
1414    },
1415    /// `-> with ada, grace`: one row per named `uses` instance.
1416    Values {
1417        values: Vec<WithRhs>,
1418        source_location: Source,
1419    },
1420}
1421
1422impl DataValue {
1423    #[must_use]
1424    pub fn import(spec_ref: SpecRef) -> Self {
1425        Self::Import {
1426            spec_ref,
1427            bindings: Vec::new(),
1428            effective_ref: None,
1429            global: false,
1430        }
1431    }
1432
1433    /// Whether this is only a literal RHS (`data x: 3.14`), valid as a binding value.
1434    #[must_use]
1435    pub fn is_definition_literal_only(&self) -> bool {
1436        matches!(
1437            self,
1438            DataValue::Definition {
1439                base: None,
1440                constraints: None,
1441                value: Some(_),
1442                list: None,
1443            }
1444        )
1445    }
1446
1447    /// Whether planning must resolve this [`LemmaData`] row through the type resolver / named types.
1448    ///
1449    /// Spec-element instance lists (`list: Some` or empty `spec list`) are planned via
1450    /// `add_instance_list`, not the named-type registry.
1451    #[must_use]
1452    pub fn definition_needs_type_resolution(&self) -> bool {
1453        match self {
1454            DataValue::Definition { list: Some(_), .. } => false,
1455            DataValue::Definition { base: Some(_), .. }
1456            | DataValue::Definition {
1457                constraints: Some(_),
1458                ..
1459            } => true,
1460            DataValue::Definition {
1461                base: None,
1462                constraints: None,
1463                value: Some(v),
1464                list: None,
1465            } => !matches!(v, Value::NumberWithUnit(_, _)),
1466            DataValue::Import { .. }
1467            | DataValue::ImportList { .. }
1468            | DataValue::OwnRows { .. }
1469            | DataValue::Definition { .. } => false,
1470        }
1471    }
1472
1473    /// Spec named by a `uses` alias.
1474    /// Types and units read through the alias the same way.
1475    #[must_use]
1476    pub fn uses_spec_ref(&self) -> Option<&SpecRef> {
1477        match self {
1478            DataValue::Import { spec_ref, .. } | DataValue::ImportList { spec_ref, .. } => {
1479                Some(spec_ref)
1480            }
1481            DataValue::Definition { .. } | DataValue::OwnRows { .. } => None,
1482        }
1483    }
1484}
1485
1486impl LemmaData {
1487    #[must_use]
1488    pub fn new(reference: Reference, value: DataValue, source_location: Source) -> Self {
1489        Self {
1490            reference,
1491            value,
1492            source_location,
1493        }
1494    }
1495}
1496
1497impl LemmaSpec {
1498    #[must_use]
1499    pub fn new(name: String) -> Self {
1500        Self {
1501            name: ascii_lowercase_logical_name(name),
1502            effective_from: EffectiveDate::Origin,
1503            source_type: None,
1504            start_line: 1,
1505            commentary: None,
1506            data: Vec::new(),
1507            rules: Vec::new(),
1508            meta_fields: Vec::new(),
1509        }
1510    }
1511
1512    /// Temporal range start. Origin (None) means −∞.
1513    pub fn effective_from(&self) -> Option<&DateTimeValue> {
1514        self.effective_from.as_ref()
1515    }
1516
1517    #[must_use]
1518    pub fn with_source_type(mut self, source_type: crate::parsing::source::SourceType) -> Self {
1519        self.source_type = Some(source_type);
1520        self
1521    }
1522
1523    #[must_use]
1524    pub fn with_start_line(mut self, start_line: usize) -> Self {
1525        self.start_line = start_line;
1526        self
1527    }
1528
1529    #[must_use]
1530    pub fn set_commentary(mut self, commentary: String) -> Self {
1531        self.commentary = Some(commentary);
1532        self
1533    }
1534
1535    #[must_use]
1536    pub fn add_data(mut self, data: LemmaData) -> Self {
1537        self.data.push(data);
1538        self
1539    }
1540
1541    #[must_use]
1542    pub fn add_rule(mut self, rule: LemmaRule) -> Self {
1543        self.rules.push(rule);
1544        self
1545    }
1546
1547    #[must_use]
1548    pub fn add_meta_field(mut self, meta: MetaField) -> Self {
1549        self.meta_fields.push(meta);
1550        self
1551    }
1552}
1553
1554fn value_starts_with_sign(value: &crate::literals::Value) -> bool {
1555    let mut current = value;
1556    loop {
1557        match current {
1558            crate::literals::Value::Number(n) | crate::literals::Value::NumberWithUnit(n, _) => {
1559                return n.is_sign_negative()
1560            }
1561            crate::literals::Value::Range(left, _) => current = left.as_ref(),
1562            _ => return false,
1563        }
1564    }
1565}
1566
1567/// Leaf of a source expression, printed as Lemma source.
1568#[derive(Clone, Copy)]
1569pub(crate) enum AstAtom<'a> {
1570    Literal(&'a crate::literals::Value),
1571    Reference(&'a Reference),
1572    Now,
1573    Veto(&'a VetoExpression),
1574    ListType(&'a ParentType),
1575}
1576
1577impl fmt::Display for AstAtom<'_> {
1578    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1579        match self {
1580            AstAtom::Literal(value) => write!(f, "{}", AsLemmaSource(*value)),
1581            AstAtom::Reference(reference) => write!(f, "{reference}"),
1582            AstAtom::Now => write!(f, "now"),
1583            AstAtom::Veto(veto) => write!(f, "{veto}"),
1584            AstAtom::ListType(element) => write!(f, "{element}"),
1585        }
1586    }
1587}
1588
1589impl fmt::Display for VetoExpression {
1590    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1591        match &self.message {
1592            Some(msg) => write!(f, "veto {}", quote_lemma_text(msg)),
1593            None => write!(f, "veto"),
1594        }
1595    }
1596}
1597
1598impl<'a> SyntaxNode<'a> for ExprRef<'a, ExpressionKind> {
1599    type Atom = AstAtom<'a>;
1600
1601    fn view(self) -> SyntaxView<'a, Self> {
1602        let atom = |atom| SyntaxView::Atom {
1603            atom,
1604            starts_with_sign: false,
1605        };
1606        match self.kind() {
1607            ExpressionKind::Literal(value) => SyntaxView::Atom {
1608                atom: AstAtom::Literal(value),
1609                starts_with_sign: value_starts_with_sign(value),
1610            },
1611            ExpressionKind::ImplicitRowValue => SyntaxView::ImplicitRowValue,
1612            ExpressionKind::Reference(reference) => atom(AstAtom::Reference(reference)),
1613            ExpressionKind::Now => atom(AstAtom::Now),
1614            ExpressionKind::Veto(veto) => atom(AstAtom::Veto(veto)),
1615            ExpressionKind::ListType { element } => atom(AstAtom::ListType(element)),
1616            ExpressionKind::DateRelative(kind, date) => {
1617                SyntaxView::DateRelative(kind, self.child(*date))
1618            }
1619            ExpressionKind::DateCalendar(kind, unit, date) => {
1620                SyntaxView::DateCalendar(kind, unit, self.child(*date))
1621            }
1622            ExpressionKind::RangeLiteral(left, right) => {
1623                SyntaxView::RangeLiteral(self.child(*left), self.child(*right))
1624            }
1625            ExpressionKind::PastFutureRange(kind, offset) => {
1626                SyntaxView::PastFutureRange(kind, self.child(*offset))
1627            }
1628            ExpressionKind::RangeContainment(value, range) => {
1629                SyntaxView::RangeContainment(self.child(*value), self.child(*range))
1630            }
1631            ExpressionKind::RangeBound(bound, operand) => {
1632                SyntaxView::Prefix(bound, self.child(*operand))
1633            }
1634            ExpressionKind::Logical {
1635                connective,
1636                first,
1637                steps,
1638            } => SyntaxView::Logical {
1639                connective: *connective,
1640                operands: std::iter::once(*first)
1641                    .chain(steps.iter().map(|step| step.operand))
1642                    .map(|id| self.child(id))
1643                    .collect(),
1644            },
1645            ExpressionKind::Arithmetic { first, steps } => {
1646                let level = match steps.first() {
1647                    Some(step) => &step.op,
1648                    None => panic!("BUG: arithmetic chain without steps"),
1649                };
1650                SyntaxView::Chain {
1651                    level,
1652                    operands: std::iter::once(*first)
1653                        .chain(steps.iter().map(|step| step.operand))
1654                        .map(|id| self.child(id))
1655                        .collect(),
1656                    ops: steps.iter().map(|step| &step.op).collect(),
1657                }
1658            }
1659            ExpressionKind::Comparison(left, op, right) => {
1660                SyntaxView::Comparison(self.child(*left), op, self.child(*right))
1661            }
1662            ExpressionKind::UnitConversion(value, target) => {
1663                SyntaxView::UnitConversion(self.child(*value), target)
1664            }
1665            ExpressionKind::LogicalNegation(operand, NegationType::Not) => {
1666                match self.child(*operand).kind() {
1667                    ExpressionKind::ResultIsVeto(inner) => {
1668                        SyntaxView::IsNotVeto(self.child(*inner))
1669                    }
1670                    _ => SyntaxView::Not(self.child(*operand)),
1671                }
1672            }
1673            ExpressionKind::MathematicalComputation(op, operand) => {
1674                SyntaxView::Prefix(op, self.child(*operand))
1675            }
1676            ExpressionKind::ResultIsVeto(operand) => SyntaxView::IsVeto(self.child(*operand)),
1677            ExpressionKind::ListCommand { list, command } => SyntaxView::ListCommand {
1678                list: self.child(*list),
1679                command: command_view(self.table, command),
1680            },
1681            ExpressionKind::StepRounding {
1682                operand,
1683                mode,
1684                step,
1685            } => SyntaxView::ListCommand {
1686                list: self.child(*operand),
1687                command: CommandView::Step(mode.keyword(), step.map(|id| self.child(id))),
1688            },
1689            ExpressionKind::Member { base, path } => SyntaxView::Member {
1690                base: self.child(*base),
1691                path: AstAtom::Reference(path),
1692                parenthesize_base: true,
1693            },
1694        }
1695    }
1696}
1697
1698fn predicate_view<'a>(
1699    table: &'a ExprTable<ExpressionKind>,
1700    form: &'a ListPredicate,
1701) -> PredicateView<ExprRef<'a, ExpressionKind>> {
1702    let child = |id: ExprId| ExprRef { table, id };
1703    match form {
1704        ListPredicate::Value { expr } => PredicateView::Value(child(*expr)),
1705        ListPredicate::Instance { expr } => PredicateView::Instance(child(*expr)),
1706    }
1707}
1708
1709/// Renders a list command whose argument nodes live in `table`.
1710pub(crate) fn display_list_command(
1711    table: &ExprTable<ExpressionKind>,
1712    command: &ListCommand,
1713) -> String {
1714    CommandSyntax(&command_view(table, command)).to_string()
1715}
1716
1717/// Renders the `->` command of `id` (a list command or step rounding) in call form.
1718pub(crate) fn display_pipe_command(table: &ExprTable<ExpressionKind>, id: ExprId) -> String {
1719    let command = match table.kind(id) {
1720        ExpressionKind::ListCommand { command, .. } => command_view(table, command),
1721        ExpressionKind::StepRounding { mode, step, .. } => {
1722            CommandView::Step(mode.keyword(), step.map(|id| ExprRef { table, id }))
1723        }
1724        other => panic!("BUG: piped expression must be a `->` command, got {other:?}"),
1725    };
1726    format!("{:#}", CommandSyntax(&command))
1727}
1728
1729/// Renders the expression `id` in `table` as Lemma syntax.
1730pub(crate) fn display_expression(table: &ExprTable<ExpressionKind>, id: ExprId) -> String {
1731    Syntax(ExprRef { table, id }).to_string()
1732}
1733
1734fn command_view<'a>(
1735    table: &'a ExprTable<ExpressionKind>,
1736    command: &'a ListCommand,
1737) -> CommandView<'a, ExprRef<'a, ExpressionKind>> {
1738    let child = |id: &ExprId| ExprRef { table, id: *id };
1739    match command {
1740        ListCommand::Find { keys } => CommandView::Find(keys.iter().map(child).collect()),
1741        ListCommand::First => CommandView::First,
1742        ListCommand::Last => CommandView::Last,
1743        ListCommand::Count => CommandView::Count,
1744        ListCommand::Sum { argument } => CommandView::Reduce("sum", argument.as_ref().map(child)),
1745        ListCommand::Avg { argument } => CommandView::Reduce("avg", argument.as_ref().map(child)),
1746        ListCommand::Product { argument } => {
1747            CommandView::Reduce("product", argument.as_ref().map(child))
1748        }
1749        ListCommand::Min { argument } => CommandView::Reduce("min", argument.as_ref().map(child)),
1750        ListCommand::Max { argument } => CommandView::Reduce("max", argument.as_ref().map(child)),
1751        ListCommand::Any { form } => CommandView::Predicate("any", predicate_view(table, form)),
1752        ListCommand::All { form } => CommandView::Predicate("all", predicate_view(table, form)),
1753        ListCommand::Where { form } => CommandView::Predicate("where", predicate_view(table, form)),
1754        ListCommand::Sort {
1755            descending,
1756            argument,
1757        } => CommandView::Sort {
1758            descending: *descending,
1759            argument: argument.as_ref().map(child),
1760        },
1761        ListCommand::Top { n } => CommandView::Top(child(n)),
1762        ListCommand::With { rows } => CommandView::With(match rows {
1763            ListWithRows::Values(values) => {
1764                values.iter().map(|value| (None, child(value))).collect()
1765            }
1766            ListWithRows::FieldPairs(pairs) => pairs
1767                .iter()
1768                .map(|(name, value)| (Some(AstAtom::Reference(name)), child(value)))
1769                .collect(),
1770        }),
1771        ListCommand::Key { fields } => {
1772            CommandView::Key(fields.iter().map(AstAtom::Reference).collect())
1773        }
1774    }
1775}
1776
1777impl fmt::Display for Expression {
1778    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1779        fmt::Display::fmt(&Syntax(self.root()), f)
1780    }
1781}
1782
1783impl fmt::Display for ConversionTarget {
1784    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1785        match self {
1786            ConversionTarget::Type(kind) => write!(f, "{kind}"),
1787            ConversionTarget::Unit { unit_name } => write!(f, "{unit_name}"),
1788        }
1789    }
1790}
1791
1792impl fmt::Display for ArithmeticComputation {
1793    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1794        match self {
1795            ArithmeticComputation::Add => write!(f, "+"),
1796            ArithmeticComputation::Subtract => write!(f, "-"),
1797            ArithmeticComputation::Multiply => write!(f, "*"),
1798            ArithmeticComputation::Divide => write!(f, "/"),
1799            ArithmeticComputation::Modulo => write!(f, "mod"),
1800            ArithmeticComputation::Power => write!(f, "^"),
1801        }
1802    }
1803}
1804
1805impl fmt::Display for ComparisonComputation {
1806    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1807        match self {
1808            ComparisonComputation::GreaterThan => write!(f, ">"),
1809            ComparisonComputation::LessThan => write!(f, "<"),
1810            ComparisonComputation::GreaterThanOrEqual => write!(f, ">="),
1811            ComparisonComputation::LessThanOrEqual => write!(f, "<="),
1812            ComparisonComputation::Is => write!(f, "is"),
1813            ComparisonComputation::IsNot => write!(f, "is not"),
1814        }
1815    }
1816}
1817
1818impl fmt::Display for MathematicalComputation {
1819    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1820        match self {
1821            MathematicalComputation::Sqrt => write!(f, "sqrt"),
1822            MathematicalComputation::Sin => write!(f, "sin"),
1823            MathematicalComputation::Cos => write!(f, "cos"),
1824            MathematicalComputation::Tan => write!(f, "tan"),
1825            MathematicalComputation::Asin => write!(f, "asin"),
1826            MathematicalComputation::Acos => write!(f, "acos"),
1827            MathematicalComputation::Atan => write!(f, "atan"),
1828            MathematicalComputation::Log => write!(f, "log"),
1829            MathematicalComputation::Exp => write!(f, "exp"),
1830            MathematicalComputation::Abs => write!(f, "abs"),
1831        }
1832    }
1833}
1834
1835// -----------------------------------------------------------------------------
1836// Primitive type kinds and parent type references
1837// -----------------------------------------------------------------------------
1838
1839/// Built-in primitive type kind. Single source of truth for type keywords.
1840#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
1841#[serde(rename_all = "snake_case")]
1842pub enum PrimitiveKind {
1843    Boolean,
1844    Measure,
1845    MeasureRange,
1846    Number,
1847    NumberRange,
1848    Ratio,
1849    RatioRange,
1850    Text,
1851    Date,
1852    DateRange,
1853    Time,
1854    TimeRange,
1855}
1856
1857impl std::fmt::Display for PrimitiveKind {
1858    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1859        let s = match self {
1860            PrimitiveKind::Boolean => "boolean",
1861            PrimitiveKind::Measure => "measure",
1862            PrimitiveKind::MeasureRange => "measure range",
1863            PrimitiveKind::Number => "number",
1864            PrimitiveKind::NumberRange => "number range",
1865            PrimitiveKind::Ratio => "ratio",
1866            PrimitiveKind::RatioRange => "ratio range",
1867            PrimitiveKind::Text => "text",
1868            PrimitiveKind::Date => "date",
1869            PrimitiveKind::DateRange => "date range",
1870            PrimitiveKind::Time => "time",
1871            PrimitiveKind::TimeRange => "time range",
1872        };
1873        write!(f, "{}", s)
1874    }
1875}
1876
1877/// Parent type in a type definition: built-in primitive or custom type name.
1878///
1879/// `name` is the declared type name (the data name that introduces this type).
1880/// For `data temperature: measure`, name = "temperature", primitive = Measure.
1881///
1882/// [`ParentType::Custom`] is a bare type or Spec name. Pin and `@repo` live on
1883/// `uses`, not on a list or type parent (`uses tax_bracket 2024` then
1884/// `data brackets: tax_bracket list`).
1885#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1886pub enum ParentType {
1887    Primitive {
1888        primitive: PrimitiveKind,
1889    },
1890    Custom {
1891        name: String,
1892    },
1893    /// Parent type defined in another spec: `spec_alias.inner` (e.g. `data x: finance.money`).
1894    /// `inner` must be [`ParentType::Primitive`] or [`ParentType::Custom`], not nested [`ParentType::Qualified`].
1895    Qualified {
1896        spec_alias: String,
1897        inner: Box<ParentType>,
1898    },
1899    /// Range over an element type: `<inner> range` (e.g. `money range`, `date range`).
1900    Ranged {
1901        inner: Box<ParentType>,
1902    },
1903    /// List of an element type: `<inner> list` (e.g. `money list`, `money range list`).
1904    List {
1905        inner: Box<ParentType>,
1906    },
1907}
1908
1909impl ParentType {
1910    /// Local custom type name.
1911    #[must_use]
1912    pub fn custom(name: impl Into<String>) -> Self {
1913        Self::Custom { name: name.into() }
1914    }
1915}
1916
1917impl std::fmt::Display for ParentType {
1918    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1919        match self {
1920            ParentType::Primitive { primitive } => write!(f, "{}", primitive),
1921            ParentType::Custom { name } => write!(f, "{name}"),
1922            ParentType::Qualified { spec_alias, inner } => {
1923                write!(f, "{spec_alias}.{inner}")
1924            }
1925            ParentType::Ranged { inner } => write!(f, "{inner} range"),
1926            ParentType::List { inner } => write!(f, "{inner} list"),
1927        }
1928    }
1929}
1930
1931// =============================================================================
1932// AsLemmaSource<Value> — canonical literal formatting
1933// =============================================================================
1934
1935/// Wrap a value to emit canonical Lemma source (round-trippable). See module docs.
1936pub struct AsLemmaSource<'a, T: ?Sized>(pub &'a T);
1937
1938/// Wrap a parsed text in double quotes for Lemma source output. A Lemma text literal
1939/// has no escapes: it runs to the next `"`, so its content is written as it is, and
1940/// parsed text never holds a `"`.
1941pub fn quote_lemma_text(s: &str) -> String {
1942    assert!(
1943        !s.contains('"'),
1944        "BUG: parsed Lemma text cannot hold a double quote: {s:?}"
1945    );
1946    format!("\"{s}\"")
1947}
1948
1949/// Format a Decimal for Lemma source, preserving precision (trailing zeros).
1950/// Strips the fractional part only when it is zero (e.g. `100` stays `"100"`,
1951/// `1.00` stays `"1.00"`). Inserts underscore separators in the integer part
1952/// when it has 4+ digits (e.g. `30000000.50` → `"30_000_000.50"`).
1953fn format_decimal_source(n: &Decimal) -> String {
1954    let raw = if n.fract().is_zero() {
1955        n.trunc().to_string()
1956    } else {
1957        n.to_string()
1958    };
1959    group_digits(&raw)
1960}
1961
1962/// Insert `_` every 3 digits in the integer part of a numeric string.
1963/// Handles optional leading `-`/`+` sign and optional fractional part.
1964/// Only groups when the integer part has 4 or more digits.
1965fn group_digits(s: &str) -> String {
1966    let (sign, rest) = if s.starts_with('-') || s.starts_with('+') {
1967        (&s[..1], &s[1..])
1968    } else {
1969        ("", s)
1970    };
1971
1972    let (int_part, frac_part) = match rest.find('.') {
1973        Some(pos) => (&rest[..pos], &rest[pos..]),
1974        None => (rest, ""),
1975    };
1976
1977    if int_part.len() < 4 {
1978        return s.to_string();
1979    }
1980
1981    let mut grouped = String::with_capacity(int_part.len() + int_part.len() / 3);
1982    for (i, ch) in int_part.chars().enumerate() {
1983        let digits_remaining = int_part.len() - i;
1984        if i > 0 && digits_remaining % 3 == 0 {
1985            grouped.push('_');
1986        }
1987        grouped.push(ch);
1988    }
1989
1990    format!("{}{}{}", sign, grouped, frac_part)
1991}
1992
1993impl<'a> fmt::Display for AsLemmaSource<'a, CommandArg> {
1994    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1995        use crate::literals::Value;
1996        match self.0 {
1997            CommandArg::Literal(Value::Number(d)) => {
1998                write!(f, "{}", group_digits(&d.to_string()))
1999            }
2000            CommandArg::Literal(Value::NumberWithUnit(d, unit)) => {
2001                write!(f, "{} {}", group_digits(&d.to_string()), unit)
2002            }
2003            CommandArg::Literal(value) => write!(f, "{}", AsLemmaSource(value)),
2004            CommandArg::Label(s) => write!(f, "{}", s),
2005            CommandArg::UnitExpr(unit_arg) => write!(f, "{}", unit_arg),
2006        }
2007    }
2008}
2009
2010/// Format `command key: value` for assignment continuations (`unit`, `with`).
2011pub(crate) fn format_assignment_continuation(
2012    command: &str,
2013    key: &str,
2014    value: &impl fmt::Display,
2015) -> String {
2016    format!("{} {}: {}", command, key, value)
2017}
2018
2019/// Format a single constraint command and its args as valid Lemma source.
2020pub(crate) fn format_constraint_as_source(
2021    cmd: &TypeConstraintCommand,
2022    args: &[CommandArg],
2023) -> String {
2024    if *cmd == TypeConstraintCommand::Unit {
2025        let Some(CommandArg::Label(name)) = args.first() else {
2026            return cmd.to_string();
2027        };
2028        let Some(CommandArg::UnitExpr(unit_arg)) = args.get(1) else {
2029            return format!("{} {}", cmd, name);
2030        };
2031        return format_assignment_continuation("unit", name, unit_arg);
2032    }
2033
2034    if args.is_empty() {
2035        cmd.to_string()
2036    } else {
2037        let args_str: Vec<String> = args
2038            .iter()
2039            .map(|a| format!("{}", AsLemmaSource(a)))
2040            .collect();
2041        let sep = match cmd.continuation_shape() {
2042            ContinuationShape::CommaSeparated => ", ",
2043            ContinuationShape::Single | ContinuationShape::Assignment => " ",
2044        };
2045        format!("{} {}", cmd, args_str.join(sep))
2046    }
2047}
2048
2049/// Format a constraint list as valid Lemma source.
2050/// Returns the `cmd arg -> cmd arg` portion joined by `separator`.
2051fn format_constraints_as_source(constraints: &[Constraint], separator: &str) -> String {
2052    constraints
2053        .iter()
2054        .map(|row| format_constraint_as_source(&row.command, &row.args))
2055        .collect::<Vec<_>>()
2056        .join(separator)
2057}
2058
2059// -- Display for AsLemmaSource<Value> ----------------------------------------
2060
2061impl<'a> fmt::Display for AsLemmaSource<'a, Value> {
2062    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2063        match self.0 {
2064            Value::Number(n) => write!(f, "{}", format_decimal_source(n)),
2065            Value::Text(s) => write!(f, "{}", quote_lemma_text(s)),
2066            Value::Date(dt) => write!(f, "{dt}"),
2067            Value::Time(t) => write!(f, "{t}"),
2068            Value::Boolean(b) => write!(f, "{}", b),
2069            Value::NumberWithUnit(n, u) => match u.as_str() {
2070                "percent" => write!(f, "{}%", format_decimal_source(n)),
2071                "permille" => write!(f, "{}%%", format_decimal_source(n)),
2072                unit => write!(f, "{} {}", format_decimal_source(n), unit),
2073            },
2074            Value::Range(left, right) => {
2075                write!(
2076                    f,
2077                    "{}...{}",
2078                    AsLemmaSource(left.as_ref()),
2079                    AsLemmaSource(right.as_ref())
2080                )
2081            }
2082        }
2083    }
2084}
2085
2086// -- AsLemmaSource: DataValue (formatter / round-trip) ---
2087
2088impl<'a> fmt::Display for AsLemmaSource<'a, DataValue> {
2089    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2090        match self.0 {
2091            DataValue::Definition {
2092                base,
2093                constraints,
2094                value,
2095                list: _,
2096            } => {
2097                if base.is_none() && constraints.is_none() {
2098                    if let Some(v) = value {
2099                        return write!(f, "{}", AsLemmaSource(v));
2100                    }
2101                }
2102                let base_str = match base.as_ref() {
2103                    Some(b) => format!("{}", b),
2104                    None => match value {
2105                        Some(v) => {
2106                            if let Some(ref constraints_vec) = constraints {
2107                                let constraint_str =
2108                                    format_constraints_as_source(constraints_vec, " -> ");
2109                                return write!(f, "{} -> {}", AsLemmaSource(v), constraint_str);
2110                            }
2111                            return write!(f, "{}", AsLemmaSource(v));
2112                        }
2113                        None => String::new(),
2114                    },
2115                };
2116                if let Some(ref constraints_vec) = constraints {
2117                    let constraint_str = format_constraints_as_source(constraints_vec, " -> ");
2118                    write!(f, "{} -> {}", base_str, constraint_str)
2119                } else {
2120                    write!(f, "{}", base_str)
2121                }
2122            }
2123            DataValue::Import {
2124                spec_ref,
2125                bindings: _,
2126                effective_ref: _,
2127                global,
2128            } => {
2129                if *global {
2130                    write!(f, "uses global {}", spec_ref)
2131                } else {
2132                    write!(f, "uses {}", spec_ref)
2133                }
2134            }
2135            DataValue::ImportList { spec_ref, list: _ }
2136            | DataValue::OwnRows {
2137                spec_ref,
2138                bindings: _,
2139            } => {
2140                write!(f, "uses {}", spec_ref)
2141            }
2142        }
2143    }
2144}
2145
2146pub(crate) fn canonicalize_value(value: &mut Value) {
2147    if let Value::NumberWithUnit(_, unit) = value {
2148        *unit = ascii_lowercase_logical_name(std::mem::take(unit));
2149    }
2150}
2151
2152pub(crate) fn canonicalize_reference(reference: &mut Reference) {
2153    for segment in &mut reference.segments {
2154        *segment = ascii_lowercase_logical_name(std::mem::take(segment));
2155    }
2156    reference.name = ascii_lowercase_logical_name(std::mem::take(&mut reference.name));
2157}
2158
2159pub(crate) fn canonicalize_spec_ref(spec_ref: &mut SpecRef) {
2160    spec_ref.name = ascii_lowercase_logical_name(std::mem::take(&mut spec_ref.name));
2161    if let Some(qualifier) = spec_ref.repository.as_mut() {
2162        qualifier.name = ascii_lowercase_logical_name(std::mem::take(&mut qualifier.name));
2163    }
2164}
2165
2166pub(crate) fn canonicalize_parent_type(parent: &mut ParentType) {
2167    let mut current = parent;
2168    loop {
2169        current = match current {
2170            ParentType::Custom { name } => {
2171                *name = ascii_lowercase_logical_name(std::mem::take(name));
2172                return;
2173            }
2174            ParentType::Qualified { spec_alias, inner } => {
2175                *spec_alias = ascii_lowercase_logical_name(std::mem::take(spec_alias));
2176                inner.as_mut()
2177            }
2178            ParentType::Ranged { inner } | ParentType::List { inner } => inner.as_mut(),
2179            ParentType::Primitive { .. } => return,
2180        }
2181    }
2182}
2183
2184pub(crate) fn canonicalize_unit_factor(factor: &mut UnitFactor) {
2185    factor.measure_ref = ascii_lowercase_logical_name(std::mem::take(&mut factor.measure_ref));
2186}
2187
2188pub(crate) fn canonicalize_unit_arg(unit_arg: &mut UnitArg) {
2189    match unit_arg {
2190        UnitArg::Expr(_, factors) => {
2191            for factor in factors {
2192                canonicalize_unit_factor(factor);
2193            }
2194        }
2195        UnitArg::Reference(reference) => {
2196            reference.name = ascii_lowercase_logical_name(std::mem::take(&mut reference.name));
2197            for segment in &mut reference.segments {
2198                *segment = ascii_lowercase_logical_name(std::mem::take(segment));
2199            }
2200        }
2201        UnitArg::Factor(_) => {}
2202    }
2203}
2204
2205pub(crate) fn canonicalize_command_arg(command_arg: &mut CommandArg) {
2206    match command_arg {
2207        CommandArg::Literal(value) => canonicalize_value(value),
2208        CommandArg::Label(label) => {
2209            *label = ascii_lowercase_logical_name(std::mem::take(label));
2210        }
2211        CommandArg::UnitExpr(unit_arg) => canonicalize_unit_arg(unit_arg),
2212    }
2213}
2214
2215pub(crate) fn canonicalize_constraints(constraints: &mut [Constraint]) {
2216    for row in constraints {
2217        for arg in &mut row.args {
2218            canonicalize_command_arg(arg);
2219        }
2220    }
2221}
2222
2223pub(crate) fn canonicalize_expression(expression: &mut Expression) {
2224    for kind in expression.table.kinds_mut() {
2225        canonicalize_expression_kind(kind);
2226    }
2227}
2228
2229/// Canonicalizes the payload a node owns. Child nodes are visited by the table sweep.
2230fn canonicalize_expression_kind(kind: &mut ExpressionKind) {
2231    match kind {
2232        ExpressionKind::Literal(value) => canonicalize_value(value),
2233        ExpressionKind::Reference(reference) => canonicalize_reference(reference),
2234        ExpressionKind::ListType { element } => canonicalize_parent_type(element),
2235        ExpressionKind::Member { path, .. } => canonicalize_reference(path),
2236        ExpressionKind::ListCommand { command, .. } => canonicalize_list_command(command),
2237        ExpressionKind::Now
2238        | ExpressionKind::ImplicitRowValue
2239        | ExpressionKind::DateRelative(..)
2240        | ExpressionKind::DateCalendar(..)
2241        | ExpressionKind::RangeLiteral(..)
2242        | ExpressionKind::PastFutureRange(..)
2243        | ExpressionKind::RangeContainment(..)
2244        | ExpressionKind::RangeBound(..)
2245        | ExpressionKind::Logical { .. }
2246        | ExpressionKind::Arithmetic { .. }
2247        | ExpressionKind::Comparison(..)
2248        | ExpressionKind::UnitConversion(..)
2249        | ExpressionKind::LogicalNegation(..)
2250        | ExpressionKind::MathematicalComputation(..)
2251        | ExpressionKind::StepRounding { .. }
2252        | ExpressionKind::Veto(_)
2253        | ExpressionKind::ResultIsVeto(..) => {}
2254    }
2255}
2256
2257fn canonicalize_list_command(command: &mut ListCommand) {
2258    match command {
2259        ListCommand::First
2260        | ListCommand::Last
2261        | ListCommand::Count
2262        | ListCommand::Find { .. }
2263        | ListCommand::Sum { .. }
2264        | ListCommand::Avg { .. }
2265        | ListCommand::Product { .. }
2266        | ListCommand::Min { .. }
2267        | ListCommand::Max { .. }
2268        | ListCommand::Any { .. }
2269        | ListCommand::All { .. }
2270        | ListCommand::Where { .. }
2271        | ListCommand::Sort { .. }
2272        | ListCommand::Top { .. }
2273        | ListCommand::With {
2274            rows: ListWithRows::Values(_),
2275        } => {}
2276        ListCommand::With {
2277            rows: ListWithRows::FieldPairs(pairs),
2278        } => {
2279            for (name, _) in pairs {
2280                canonicalize_reference(name);
2281            }
2282        }
2283        ListCommand::Key { fields } => {
2284            for field in fields {
2285                canonicalize_reference(field);
2286            }
2287        }
2288    }
2289}
2290
2291pub(crate) fn canonicalize_unless_clause(unless_clause: &mut UnlessClause) {
2292    canonicalize_expression(&mut unless_clause.condition);
2293    canonicalize_expression(&mut unless_clause.result);
2294}
2295
2296pub(crate) fn canonicalize_data_value(data_value: &mut DataValue) {
2297    match data_value {
2298        DataValue::Definition {
2299            base,
2300            constraints,
2301            value,
2302            list,
2303        } => {
2304            if let Some(base) = base {
2305                canonicalize_parent_type(base);
2306            }
2307            if let Some(constraints) = constraints {
2308                canonicalize_constraints(constraints);
2309            }
2310            if let Some(value) = value {
2311                canonicalize_value(value);
2312            }
2313            if let Some(list) = list {
2314                canonicalize_instance_list_body(list);
2315            }
2316        }
2317        DataValue::Import {
2318            spec_ref,
2319            bindings,
2320            effective_ref,
2321            global: _,
2322        } => {
2323            canonicalize_spec_ref(spec_ref);
2324            canonicalize_uses_bindings(bindings);
2325            if let Some(reference) = effective_ref {
2326                canonicalize_reference(reference);
2327            }
2328        }
2329        DataValue::ImportList { spec_ref, list } => {
2330            canonicalize_spec_ref(spec_ref);
2331            canonicalize_instance_list_body(list);
2332        }
2333        DataValue::OwnRows { spec_ref, bindings } => {
2334            canonicalize_spec_ref(spec_ref);
2335            canonicalize_uses_bindings(bindings);
2336        }
2337    }
2338}
2339
2340pub(crate) fn canonicalize_instance_list_body(list: &mut InstanceListBody) {
2341    if let Some(key) = &mut list.key {
2342        for field in &mut key.fields {
2343            canonicalize_reference(field);
2344        }
2345    }
2346    for row in list.rows.iter_mut().chain(list.option_rows.iter_mut()) {
2347        match row {
2348            InstanceListRow::Fields { bindings, .. } => {
2349                for binding in bindings {
2350                    canonicalize_reference(&mut binding.path);
2351                    canonicalize_with_rhs(&mut binding.rhs);
2352                }
2353            }
2354            InstanceListRow::Values { values, .. } => {
2355                for value in values {
2356                    canonicalize_with_rhs(value);
2357                }
2358            }
2359        }
2360    }
2361}
2362
2363fn canonicalize_with_rhs(rhs: &mut WithRhs) {
2364    match rhs {
2365        WithRhs::Literal(value) => canonicalize_value(value),
2366        WithRhs::Reference { target } => canonicalize_reference(target),
2367    }
2368}
2369
2370fn canonicalize_uses_bindings(bindings: &mut [UsesBinding]) {
2371    for binding in bindings {
2372        canonicalize_reference(&mut binding.path);
2373        match &mut binding.rhs {
2374            UsesBindingRhs::Literal(value) => canonicalize_value(value),
2375            UsesBindingRhs::References { targets } => {
2376                for target in targets {
2377                    canonicalize_reference(target);
2378                }
2379            }
2380        }
2381    }
2382}
2383
2384pub(crate) fn canonicalize_lemma_data(data: &mut LemmaData) {
2385    canonicalize_reference(&mut data.reference);
2386    canonicalize_data_value(&mut data.value);
2387}
2388
2389pub(crate) fn canonicalize_lemma_rule(rule: &mut LemmaRule) {
2390    rule.name = ascii_lowercase_logical_name(std::mem::take(&mut rule.name));
2391    canonicalize_expression(&mut rule.expression);
2392    for unless_clause in &mut rule.unless_clauses {
2393        canonicalize_unless_clause(unless_clause);
2394    }
2395}
2396
2397pub(crate) fn canonicalize_lemma_spec(spec: &mut LemmaSpec) {
2398    spec.name = ascii_lowercase_logical_name(std::mem::take(&mut spec.name));
2399    for meta in &mut spec.meta_fields {
2400        meta.key = ascii_lowercase_logical_name(std::mem::take(&mut meta.key));
2401    }
2402    for data in &mut spec.data {
2403        canonicalize_lemma_data(data);
2404    }
2405    for rule in &mut spec.rules {
2406        canonicalize_lemma_rule(rule);
2407    }
2408}
2409
2410pub(crate) fn canonicalize_repository(repository: &mut LemmaRepository) {
2411    if let Some(name) = repository.name.take() {
2412        repository.name = Some(ascii_lowercase_logical_name(name));
2413    }
2414}
2415
2416#[cfg(test)]
2417mod tests {
2418    use super::*;
2419    use crate::literals::DateGranularity;
2420
2421    #[test]
2422    fn test_conversion_target_display() {
2423        assert_eq!(
2424            format!("{}", ConversionTarget::Type(ConversionTypeKind::Number)),
2425            "number"
2426        );
2427    }
2428
2429    #[test]
2430    fn test_value_number_with_unit_ratio_display() {
2431        use rust_decimal::Decimal;
2432        use std::str::FromStr;
2433        let percent =
2434            Value::NumberWithUnit(Decimal::from_str("10").unwrap(), "percent".to_string());
2435        assert_eq!(format!("{}", percent), "10%");
2436        let permille =
2437            Value::NumberWithUnit(Decimal::from_str("5").unwrap(), "permille".to_string());
2438        assert_eq!(format!("{}", permille), "5%%");
2439    }
2440
2441    #[test]
2442    fn test_datetime_value_display() {
2443        let dt = DateTimeValue {
2444            year: 2024,
2445            month: 12,
2446            day: 25,
2447            hour: 14,
2448            minute: 30,
2449            second: 45,
2450            microsecond: 0,
2451            timezone: Some(TimezoneValue { offset_minutes: 60 }),
2452
2453            granularity: DateGranularity::DateTime,
2454        };
2455        assert_eq!(format!("{}", dt), "2024-12-25T14:30:45+01:00");
2456    }
2457
2458    #[test]
2459    fn test_datetime_value_display_date_only() {
2460        let dt = DateTimeValue {
2461            year: 2026,
2462            month: 3,
2463            day: 4,
2464            hour: 0,
2465            minute: 0,
2466            second: 0,
2467            microsecond: 0,
2468            timezone: None,
2469
2470            granularity: DateGranularity::Full,
2471        };
2472        assert_eq!(format!("{}", dt), "2026-03-04");
2473    }
2474
2475    #[test]
2476    fn test_datetime_value_display_microseconds() {
2477        let dt = DateTimeValue {
2478            year: 2026,
2479            month: 2,
2480            day: 23,
2481            hour: 14,
2482            minute: 30,
2483            second: 45,
2484            microsecond: 123456,
2485            timezone: Some(TimezoneValue { offset_minutes: 0 }),
2486
2487            granularity: DateGranularity::DateTime,
2488        };
2489        assert_eq!(format!("{}", dt), "2026-02-23T14:30:45.123456Z");
2490    }
2491
2492    #[test]
2493    fn test_datetime_microsecond_in_ordering() {
2494        let a = DateTimeValue {
2495            year: 2026,
2496            month: 1,
2497            day: 1,
2498            hour: 0,
2499            minute: 0,
2500            second: 0,
2501            microsecond: 100,
2502            timezone: None,
2503
2504            granularity: DateGranularity::DateTime,
2505        };
2506        let b = DateTimeValue {
2507            year: 2026,
2508            month: 1,
2509            day: 1,
2510            hour: 0,
2511            minute: 0,
2512            second: 0,
2513            microsecond: 200,
2514            timezone: None,
2515
2516            granularity: DateGranularity::DateTime,
2517        };
2518        assert!(a < b);
2519    }
2520
2521    #[test]
2522    fn test_datetime_parse_iso_week() {
2523        let dt: DateTimeValue = "2026-W01".parse().unwrap();
2524        assert_eq!(dt.year, 2025);
2525        assert_eq!(dt.month, 12);
2526        assert_eq!(dt.day, 29);
2527        assert_eq!(dt.microsecond, 0);
2528        assert_eq!(dt.to_string(), "2026-W01");
2529        assert!(matches!(
2530            dt.granularity,
2531            DateGranularity::IsoWeek {
2532                iso_year: 2026,
2533                week: 1
2534            }
2535        ));
2536    }
2537
2538    // =====================================================================
2539    // DataValue Display — constraint formatting
2540    // =====================================================================
2541
2542    fn text_arg(s: &str) -> CommandArg {
2543        CommandArg::Literal(crate::literals::Value::Text(s.to_string()))
2544    }
2545
2546    fn number_arg(s: &str) -> CommandArg {
2547        let d: rust_decimal::Decimal = s.parse().expect("decimal");
2548        CommandArg::Literal(crate::literals::Value::Number(d))
2549    }
2550
2551    fn boolean_arg(b: BooleanValue) -> CommandArg {
2552        CommandArg::Literal(crate::literals::Value::Boolean(b))
2553    }
2554
2555    fn measure_arg(value: &str, unit: &str) -> CommandArg {
2556        let d: rust_decimal::Decimal = value.parse().expect("decimal");
2557        CommandArg::Literal(crate::literals::Value::NumberWithUnit(d, unit.to_string()))
2558    }
2559
2560    fn duration_arg(value: &str, unit: &str) -> CommandArg {
2561        let d: rust_decimal::Decimal = value.parse().expect("decimal");
2562        CommandArg::Literal(crate::literals::Value::NumberWithUnit(d, unit.to_string()))
2563    }
2564
2565    #[test]
2566    fn as_lemma_source_text_default_is_quoted() {
2567        let fv = DataValue::Definition {
2568            base: Some(ParentType::Primitive {
2569                primitive: PrimitiveKind::Text,
2570            }),
2571            constraints: Some(vec![test_constraint(
2572                TypeConstraintCommand::Suggest,
2573                vec![text_arg("single")],
2574            )]),
2575            value: None,
2576
2577            list: None,
2578        };
2579        assert_eq!(
2580            format!("{}", AsLemmaSource(&fv)),
2581            "text -> suggest \"single\""
2582        );
2583    }
2584
2585    #[test]
2586    fn as_lemma_source_number_default_not_quoted() {
2587        let fv = DataValue::Definition {
2588            base: Some(ParentType::Primitive {
2589                primitive: PrimitiveKind::Number,
2590            }),
2591            constraints: Some(vec![test_constraint(
2592                TypeConstraintCommand::Suggest,
2593                vec![number_arg("10")],
2594            )]),
2595            value: None,
2596
2597            list: None,
2598        };
2599        assert_eq!(format!("{}", AsLemmaSource(&fv)), "number -> suggest 10");
2600    }
2601
2602    #[test]
2603    fn as_lemma_source_help_always_quoted() {
2604        let fv = DataValue::Definition {
2605            base: Some(ParentType::Primitive {
2606                primitive: PrimitiveKind::Number,
2607            }),
2608            constraints: Some(vec![test_constraint(
2609                TypeConstraintCommand::Help,
2610                vec![text_arg("Enter a measure")],
2611            )]),
2612            value: None,
2613
2614            list: None,
2615        };
2616        assert_eq!(
2617            format!("{}", AsLemmaSource(&fv)),
2618            "number -> help \"Enter a measure\""
2619        );
2620    }
2621
2622    #[test]
2623    fn as_lemma_source_text_option_quoted() {
2624        let fv = DataValue::Definition {
2625            base: Some(ParentType::Primitive {
2626                primitive: PrimitiveKind::Text,
2627            }),
2628            constraints: Some(vec![
2629                test_constraint(TypeConstraintCommand::Option, vec![text_arg("active")]),
2630                test_constraint(TypeConstraintCommand::Option, vec![text_arg("inactive")]),
2631            ]),
2632            value: None,
2633
2634            list: None,
2635        };
2636        assert_eq!(
2637            format!("{}", AsLemmaSource(&fv)),
2638            "text -> option \"active\" -> option \"inactive\""
2639        );
2640    }
2641
2642    #[test]
2643    fn as_lemma_source_measure_unit_not_quoted() {
2644        let fv = DataValue::Definition {
2645            base: Some(ParentType::Primitive {
2646                primitive: PrimitiveKind::Measure,
2647            }),
2648            constraints: Some(vec![
2649                test_constraint(
2650                    TypeConstraintCommand::Unit,
2651                    vec![
2652                        CommandArg::Label("eur".to_string()),
2653                        CommandArg::UnitExpr(UnitArg::Factor(decimal("1.00"))),
2654                    ],
2655                ),
2656                test_constraint(
2657                    TypeConstraintCommand::Unit,
2658                    vec![
2659                        CommandArg::Label("usd".to_string()),
2660                        CommandArg::UnitExpr(UnitArg::Factor(decimal("0.91"))),
2661                    ],
2662                ),
2663            ]),
2664            value: None,
2665
2666            list: None,
2667        };
2668        assert_eq!(
2669            format!("{}", AsLemmaSource(&fv)),
2670            "measure -> unit eur: 1.00 -> unit usd: 0.91"
2671        );
2672    }
2673
2674    #[test]
2675    fn as_lemma_source_measure_minimum_with_unit() {
2676        let fv = DataValue::Definition {
2677            base: Some(ParentType::Primitive {
2678                primitive: PrimitiveKind::Measure,
2679            }),
2680            constraints: Some(vec![test_constraint(
2681                TypeConstraintCommand::Minimum,
2682                vec![measure_arg("0", "eur")],
2683            )]),
2684            value: None,
2685
2686            list: None,
2687        };
2688        assert_eq!(
2689            format!("{}", AsLemmaSource(&fv)),
2690            "measure -> minimum 0 eur"
2691        );
2692    }
2693
2694    #[test]
2695    fn as_lemma_source_boolean_default() {
2696        let fv = DataValue::Definition {
2697            base: Some(ParentType::Primitive {
2698                primitive: PrimitiveKind::Boolean,
2699            }),
2700            constraints: Some(vec![test_constraint(
2701                TypeConstraintCommand::Suggest,
2702                vec![boolean_arg(BooleanValue::True)],
2703            )]),
2704            value: None,
2705
2706            list: None,
2707        };
2708        assert_eq!(format!("{}", AsLemmaSource(&fv)), "boolean -> suggest true");
2709    }
2710
2711    #[test]
2712    fn as_lemma_source_duration_default() {
2713        let fv = DataValue::Definition {
2714            base: Some(ParentType::custom("duration")),
2715            constraints: Some(vec![test_constraint(
2716                TypeConstraintCommand::Suggest,
2717                vec![duration_arg("40", "hour")],
2718            )]),
2719            value: None,
2720
2721            list: None,
2722        };
2723        assert_eq!(
2724            format!("{}", AsLemmaSource(&fv)),
2725            "duration -> suggest 40 hour"
2726        );
2727    }
2728
2729    #[test]
2730    fn as_lemma_source_named_type_default_quoted() {
2731        // Named types (user-defined): the parser produces a typed Text literal for
2732        // quoted suggestion values like `suggest "single"`.
2733        let fv = DataValue::Definition {
2734            base: Some(ParentType::custom("filing_status_type")),
2735            constraints: Some(vec![test_constraint(
2736                TypeConstraintCommand::Suggest,
2737                vec![text_arg("single")],
2738            )]),
2739            value: None,
2740
2741            list: None,
2742        };
2743        assert_eq!(
2744            format!("{}", AsLemmaSource(&fv)),
2745            "filing_status_type -> suggest \"single\""
2746        );
2747    }
2748
2749    /// A text literal has no escapes, so parsed text never holds a `"`; one that does
2750    /// is a bug.
2751    #[test]
2752    #[should_panic(expected = "BUG: parsed Lemma text cannot hold a double quote")]
2753    fn as_lemma_source_help_with_a_quote_is_a_bug() {
2754        let fv = DataValue::Definition {
2755            base: Some(ParentType::Primitive {
2756                primitive: PrimitiveKind::Text,
2757            }),
2758            constraints: Some(vec![test_constraint(
2759                TypeConstraintCommand::Help,
2760                vec![text_arg("say \"hello\"")],
2761            )]),
2762            value: None,
2763
2764            list: None,
2765        };
2766        let text = format!("{}", AsLemmaSource(&fv));
2767        unreachable!("formatted a text holding a quote: {text}");
2768    }
2769
2770    #[test]
2771    fn as_lemma_source_help_writes_backslashes_as_they_are() {
2772        let fv = DataValue::Definition {
2773            base: Some(ParentType::Primitive {
2774                primitive: PrimitiveKind::Text,
2775            }),
2776            constraints: Some(vec![test_constraint(
2777                TypeConstraintCommand::Help,
2778                vec![text_arg("a\\b")],
2779            )]),
2780            value: None,
2781
2782            list: None,
2783        };
2784        assert_eq!(format!("{}", AsLemmaSource(&fv)), "text -> help \"a\\b\"");
2785    }
2786
2787    fn unit_arg_expr(prefix: Decimal, factors: &[(&str, i32)]) -> UnitArg {
2788        UnitArg::Expr(
2789            prefix,
2790            factors
2791                .iter()
2792                .map(|(measure_ref, exp)| UnitFactor {
2793                    measure_ref: (*measure_ref).to_string(),
2794                    exp: *exp,
2795                })
2796                .collect(),
2797        )
2798    }
2799
2800    #[test]
2801    fn unit_arg_display_metre_per_second() {
2802        let arg = unit_arg_expr(Decimal::ONE, &[("meter", 1), ("second", -1)]);
2803        assert_eq!(format!("{arg}"), "meter/second");
2804        assert!(
2805            !format!("{arg}").contains("second^-1"),
2806            "must not print denominator as negative exponent"
2807        );
2808    }
2809
2810    #[test]
2811    fn unit_arg_display_meter_per_second_squared() {
2812        let arg = unit_arg_expr(Decimal::ONE, &[("meter", 1), ("second", -2)]);
2813        assert_eq!(format!("{arg}"), "meter/second^2");
2814    }
2815
2816    #[test]
2817    fn unit_arg_display_divides_by_every_denominator() {
2818        let arg = unit_arg_expr(Decimal::ONE, &[("eur", 1), ("pallet", -1), ("week", -2)]);
2819        assert_eq!(format!("{arg}"), "eur/pallet/week^2");
2820    }
2821
2822    #[test]
2823    fn unit_arg_display_returns_to_the_numerator_after_a_denominator() {
2824        let arg = unit_arg_expr(Decimal::ONE, &[("eur", 1), ("pallet", -1), ("week", 1)]);
2825        assert_eq!(format!("{arg}"), "eur/pallet * week");
2826    }
2827
2828    #[test]
2829    fn unit_arg_display_keeps_a_leading_negative_exponent() {
2830        let arg = unit_arg_expr(Decimal::ONE, &[("week", -1), ("pallet", -1)]);
2831        assert_eq!(format!("{arg}"), "week^-1/pallet");
2832    }
2833
2834    #[test]
2835    fn unit_arg_display_kg_times_mps2() {
2836        let arg = unit_arg_expr(Decimal::ONE, &[("kg", 1), ("mps2", 1)]);
2837        assert_eq!(format!("{arg}"), "kg * mps2");
2838    }
2839
2840    #[test]
2841    fn unit_arg_display_numeric_prefix_metre_per_second() {
2842        use std::str::FromStr;
2843        let prefix = Decimal::from_str("3.6").expect("decimal");
2844        let arg = unit_arg_expr(prefix, &[("meter", 1), ("second", -1)]);
2845        assert_eq!(format!("{arg}"), "3.6 meter/second");
2846    }
2847
2848    #[test]
2849    fn unit_arg_display_metre_per_second_times_kg() {
2850        let arg = unit_arg_expr(Decimal::ONE, &[("meter", 1), ("second", -1), ("kg", 1)]);
2851        assert_eq!(format!("{arg}"), "meter/second * kg");
2852    }
2853
2854    #[test]
2855    fn unit_arg_display_kg_meter_per_second_squared() {
2856        let arg = unit_arg_expr(Decimal::ONE, &[("kg", 1), ("meter", 1), ("second", -2)]);
2857        assert_eq!(format!("{arg}"), "kg * meter/second^2");
2858    }
2859
2860    // ─── Assignment continuation formatting (red until formatter lands) ───────
2861
2862    #[test]
2863    fn format_constraint_as_source_unit_factor_uses_assignment_colon() {
2864        let args = vec![
2865            CommandArg::Label("eur".to_string()),
2866            CommandArg::UnitExpr(UnitArg::Factor(decimal("1"))),
2867        ];
2868        assert_eq!(
2869            format_constraint_as_source(&TypeConstraintCommand::Unit, &args),
2870            "unit eur: 1"
2871        );
2872    }
2873
2874    #[test]
2875    fn format_constraint_as_source_unit_compound_uses_assignment_colon() {
2876        let arg = unit_arg_expr(decimal("3.6"), &[("meter", 1), ("second", -1)]);
2877        let args = vec![
2878            CommandArg::Label("kmh".to_string()),
2879            CommandArg::UnitExpr(arg),
2880        ];
2881        assert_eq!(
2882            format_constraint_as_source(&TypeConstraintCommand::Unit, &args),
2883            "unit kmh: 3.6 meter/second"
2884        );
2885    }
2886
2887    #[test]
2888    fn format_constraint_as_source_unit_factor_one_decimal_uses_assignment_colon() {
2889        let args = vec![
2890            CommandArg::Label("eur".to_string()),
2891            CommandArg::UnitExpr(UnitArg::Factor(decimal("1.00"))),
2892        ];
2893        assert_eq!(
2894            format_constraint_as_source(&TypeConstraintCommand::Unit, &args),
2895            "unit eur: 1.00"
2896        );
2897    }
2898
2899    #[test]
2900    fn as_lemma_source_measure_unit_uses_assignment_colon() {
2901        let fv = DataValue::Definition {
2902            base: Some(ParentType::Primitive {
2903                primitive: PrimitiveKind::Measure,
2904            }),
2905            constraints: Some(vec![
2906                test_constraint(
2907                    TypeConstraintCommand::Unit,
2908                    vec![
2909                        CommandArg::Label("eur".to_string()),
2910                        CommandArg::UnitExpr(UnitArg::Factor(decimal("1.00"))),
2911                    ],
2912                ),
2913                test_constraint(
2914                    TypeConstraintCommand::Unit,
2915                    vec![
2916                        CommandArg::Label("usd".to_string()),
2917                        CommandArg::UnitExpr(UnitArg::Factor(decimal("0.91"))),
2918                    ],
2919                ),
2920            ]),
2921            value: None,
2922
2923            list: None,
2924        };
2925        assert_eq!(
2926            format!("{}", AsLemmaSource(&fv)),
2927            "measure -> unit eur: 1.00 -> unit usd: 0.91"
2928        );
2929    }
2930
2931    #[test]
2932    fn as_lemma_source_time_keeps_microseconds() {
2933        let time = Value::Time(crate::literals::TimeValue {
2934            hour: 14,
2935            minute: 30,
2936            second: 45,
2937            microsecond: 250,
2938            timezone: None,
2939        });
2940        assert_eq!(format!("{}", AsLemmaSource(&time)), "14:30:45.000250");
2941    }
2942
2943    #[test]
2944    fn as_lemma_source_datetime_keeps_microseconds() {
2945        let datetime = Value::Date(DateTimeValue {
2946            year: 2024,
2947            month: 1,
2948            day: 15,
2949            hour: 14,
2950            minute: 30,
2951            second: 0,
2952            microsecond: 500000,
2953            timezone: Some(crate::literals::TimezoneValue { offset_minutes: 0 }),
2954            granularity: DateGranularity::DateTime,
2955        });
2956        assert_eq!(
2957            format!("{}", AsLemmaSource(&datetime)),
2958            "2024-01-15T14:30:00.500000Z"
2959        );
2960    }
2961
2962    fn decimal(value: &str) -> rust_decimal::Decimal {
2963        use std::str::FromStr;
2964        rust_decimal::Decimal::from_str(value).expect("decimal literal in test")
2965    }
2966}