Skip to main content

lemma/planning/
normalize.rs

1//! Expression normalization: algebraic simplification for drift-free evaluation.
2//!
3//! Internal [`NormalForm`] IR used by planning; sealed into [`ExecutionPlan`] tables.
4
5use crate::computation::rational::{NumericFailure, RationalInteger};
6use crate::formatting::expression::{CommandView, PredicateView, Syntax, SyntaxNode, SyntaxView};
7use crate::parsing::arena::{ExprKind, ExprRef};
8use crate::parsing::ast::{
9    CalendarPeriodUnit, DateCalendarKind, DateRelativeKind, ListPredicateForm, LogicalConnective,
10};
11use crate::planning::execution_plan::ExecutionPlan;
12use crate::planning::instance_list::RowHop;
13use crate::planning::ordered_dispatch::DispatchKey;
14use crate::planning::semantics::{
15    primitive_boolean_arc, primitive_date_arc, primitive_number_arc, primitive_ratio_arc,
16    primitive_text_arc, primitive_time_arc, ArithmeticComputation, ComparisonComputation,
17    DataDefinition, DataPath, Expression, ExpressionKind, LemmaType, ListPredKind, LiteralValue,
18    MathematicalComputation, PathSegment, RangeBound, RoundingMode, RowEnd, RulePath,
19    SemanticConversionTarget, Source, SpecIdentity, ValueKind, VetoExpression,
20};
21use crate::planning::typing::{
22    comparison_type, compute_arithmetic_result_type, date_predicate_type,
23    infer_range_type_from_endpoint_types, logical_connective_type, logical_not_type, math_op_type,
24    past_future_range_type, piecewise_type, quantity_integer_power_type, range_bound_result_type,
25    range_containment_type, result_is_veto_type, step_rounding_type, unit_conversion_type,
26    MeasureScope,
27};
28use crate::Error;
29use indexmap::IndexMap;
30use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
31use std::sync::Arc;
32
33mod rewrite;
34
35fn normalization_error(source: Option<Source>, failure: NumericFailure, context: &str) -> Error {
36    Error::validation(format!("{context}: {failure}"), source, None::<String>)
37}
38
39/// Literal for an exactly folded plain-number rational.
40///
41/// Contract: callers fold plain numbers only. Unit-bearing operands never reach
42/// this function; measure folds carry their unit signature on the result type.
43fn literal_from_folded_rational(rational: RationalInteger) -> LiteralValue {
44    LiteralValue::number(rational)
45}
46
47/// One rule lowered into the shared NormalForm graph and normalized.
48pub(crate) struct NormalizedRule {
49    pub(crate) body: NormalFormId,
50    /// Type of the lowered root before any rewrite: the source expression typed
51    /// by [`Cells::type_of`]. Equals the graph's inferred rule type.
52    pub(crate) source_type: Arc<LemmaType>,
53}
54
55/// Plan-level inputs to per-rule normalization that do not change across the
56/// execution order. Per-rule inputs (branches, source) stay explicit.
57pub(crate) struct NormalizeContext<'a> {
58    pub(crate) data: &'a IndexMap<DataPath, DataDefinition>,
59    /// Template plans of instance-list row specs, by row spec.
60    pub(crate) row_templates: &'a BTreeMap<SpecIdentity, Arc<ExecutionPlan>>,
61    /// The spec being planned: rows of its self-lists read this plan.
62    pub(crate) self_identity: &'a SpecIdentity,
63    /// Present rules in topo order (same set as the plan).
64    pub(crate) rule_order: &'a [RulePath],
65    /// Measure scope cells are typed in: the plan's unit + signature indexes.
66    pub(crate) measure_scope: MeasureScope<'a>,
67    pub(crate) max_normalized_expression_nodes: usize,
68}
69
70/// Completed rule roots, graph rule types, and data for lower.
71struct LowerCtx<'a> {
72    completed_rules: &'a HashMap<RulePath, NormalFormId>,
73    /// [`crate::planning::graph::RuleNode::rule_type`] for every rule (pre-topo).
74    rule_types: &'a HashMap<RulePath, Arc<LemmaType>>,
75    data: &'a IndexMap<DataPath, DataDefinition>,
76    row_templates: &'a BTreeMap<SpecIdentity, Arc<ExecutionPlan>>,
77    self_identity: &'a SpecIdentity,
78    rule_order: &'a [RulePath],
79}
80
81impl LowerCtx<'_> {
82    /// Member `path.name` on rows of `identity`, hop by hop.
83    fn row_member_chain(
84        &self,
85        identity: &SpecIdentity,
86        path: &[String],
87        name: &str,
88    ) -> Option<Vec<RowHop>> {
89        let parts: Vec<&str> = path
90            .iter()
91            .map(String::as_str)
92            .chain(std::iter::once(name))
93            .collect();
94        let rules: BTreeSet<RulePath>;
95        let view = if identity == self.self_identity {
96            rules = self.rule_order.iter().cloned().collect();
97            crate::planning::instance_list::RowEndView::Root {
98                data: self.data,
99                rules: &rules,
100            }
101        } else {
102            crate::planning::instance_list::RowEndView::Plan(self.template(identity))
103        };
104        crate::planning::instance_list::row_end_chain(identity, view, self.row_templates, &parts)
105    }
106
107    fn row_end_type(&self, identity: &SpecIdentity, end: &RowEnd) -> Arc<LemmaType> {
108        if identity != self.self_identity {
109            return crate::planning::instance_list::row_end_type(self.template(identity), end);
110        }
111        match end {
112            RowEnd::Data(path) => crate::planning::instance_list::row_data_type(self.data, path),
113            RowEnd::Rule(rule) => Arc::clone(self.rule_types.get(rule).unwrap_or_else(|| {
114                panic!("BUG: row rule '{}' has no rule type", rule.input_key())
115            })),
116        }
117    }
118
119    fn template(&self, identity: &SpecIdentity) -> &ExecutionPlan {
120        self.row_templates
121            .get(identity)
122            .unwrap_or_else(|| panic!("BUG: row field of '{identity}' without a template plan"))
123    }
124}
125
126pub(crate) fn build_normalized_rule(
127    ctx: &NormalizeContext<'_>,
128    completed_rules: &HashMap<RulePath, NormalFormId>,
129    rule_types: &HashMap<RulePath, Arc<LemmaType>>,
130    expression: &Expression,
131    source: Option<Source>,
132    interner: &mut NormalFormInterner,
133) -> Result<NormalizedRule, Error> {
134    let max_normalized_expression_nodes = ctx.max_normalized_expression_nodes;
135    let lower = LowerCtx {
136        completed_rules,
137        rule_types,
138        data: ctx.data,
139        row_templates: ctx.row_templates,
140        self_identity: ctx.self_identity,
141        rule_order: ctx.rule_order,
142    };
143
144    let mut cells = Cells::new(interner, ctx.measure_scope);
145    let root = to_normal_form(expression, &mut cells, &lower);
146    let source_type = Arc::clone(cells.result_type(root));
147    let nf = rewrite::normalize(root, cells, source.clone())?;
148
149    if normal_form_exceeds_node_budget(&interner.forms, nf, max_normalized_expression_nodes) {
150        return Err(expression_node_limit_error(
151            max_normalized_expression_nodes,
152            source,
153        ));
154    }
155
156    Ok(NormalizedRule {
157        body: nf,
158        source_type,
159    })
160}
161
162fn expression_node_limit_error(limit: usize, source: Option<Source>) -> Error {
163    Error::resource_limit_exceeded(
164        "max_normalized_expression_nodes",
165        format!("{limit} expression nodes"),
166        format!(
167            "more than {limit} unique normal-form cells reachable from the rule root (rule references count as one cell)"
168        ),
169        "Restructure the rule or reduce repeated references to other rules",
170        source,
171        None,
172        None,
173    )
174}
175
176/// Whether the normal form, counted as unique DAG cells reachable from `root`,
177/// exceeds the node budget (IR size = distinct cells, not tree expansion).
178/// Rule references count as one cell: the target body was already budgeted when its
179/// rule completed. Rule references are evaluation boundaries, so this measures only
180/// intra-rule IR size.
181pub(crate) fn normal_form_exceeds_node_budget(
182    forms: &[NormalForm],
183    root: NormalFormId,
184    budget: usize,
185) -> bool {
186    let mut visited = HashSet::new();
187    let mut worklist = vec![root];
188    while let Some(current) = worklist.pop() {
189        if !visited.insert(current) {
190            continue;
191        }
192        if visited.len() > budget {
193            return true;
194        }
195        let cell = forms.get(current.index()).unwrap_or_else(|| {
196            panic!(
197                "BUG: NormalFormId {} out of range during node budget walk (table len {})",
198                current.0,
199                forms.len()
200            )
201        });
202        if cell.rule_ref.is_some() {
203            continue;
204        }
205        cell.kind.for_each_child(|child| worklist.push(child));
206        if let Some(origin) = cell.origin {
207            worklist.push(origin);
208        }
209    }
210    false
211}
212
213/// Maximum nesting depth of a NormalForm DAG (leaves and rule references have
214/// depth 1). Rule references are evaluation boundaries, so planning measures only
215/// intra-rule Kind nesting. Used by tests to check that bound.
216#[cfg(test)]
217pub(crate) fn normal_form_depth(forms: &[NormalForm], root: NormalFormId) -> usize {
218    let mut memo: HashMap<NormalFormId, usize> = HashMap::new();
219    // Explicit post-order: (id, children_pushed). Embeds are leaves (depth 1).
220    let mut stack: Vec<(NormalFormId, bool)> = vec![(root, false)];
221    while let Some((id, children_pushed)) = stack.pop() {
222        if memo.contains_key(&id) {
223            continue;
224        }
225        let cell = forms.get(id.index()).unwrap_or_else(|| {
226            panic!(
227                "BUG: NormalFormId {} out of range during depth walk (table len {})",
228                id.0,
229                forms.len()
230            )
231        });
232        if cell.rule_ref.is_some() {
233            memo.insert(id, 1);
234            continue;
235        }
236        if !children_pushed {
237            stack.push((id, true));
238            cell.kind.for_each_child(|child| {
239                if !memo.contains_key(&child) {
240                    stack.push((child, false));
241                }
242            });
243            if let Some(origin) = cell.origin {
244                if !memo.contains_key(&origin) {
245                    stack.push((origin, false));
246                }
247            }
248            continue;
249        }
250        let mut depth = 1usize;
251        cell.kind.for_each_child(|child| {
252            let child_depth = *memo.get(&child).unwrap_or_else(|| {
253                panic!(
254                    "BUG: child NormalFormId {} missing from depth memo after post-order push",
255                    child.0
256                )
257            });
258            depth = depth.max(1 + child_depth);
259        });
260        if let Some(origin) = cell.origin {
261            let origin_depth = *memo.get(&origin).unwrap_or_else(|| {
262                panic!(
263                    "BUG: origin NormalFormId {} missing from depth memo after post-order push",
264                    origin.0
265                )
266            });
267            depth = depth.max(1 + origin_depth);
268        }
269        memo.insert(id, depth);
270    }
271    *memo
272        .get(&root)
273        .unwrap_or_else(|| panic!("BUG: root NormalFormId {} missing from depth memo", root.0))
274}
275
276/// Leaves in the shipped equation DAG: literals and data only.
277#[derive(Clone, Debug, PartialEq, Eq, Hash)]
278pub enum LeafKind {
279    Literal(LiteralValue),
280    DataPath(crate::planning::semantics::DataPath),
281    /// Value of the current value-list row at `level`.
282    RowValue {
283        level: u32,
284    },
285}
286
287/// A member chain read on a row, through the row spec's template plans: every end
288/// but the last reads a `uses` slot, as that instance; the last is the member read.
289#[derive(Clone, Debug, PartialEq, Eq, Hash)]
290pub struct RowRead {
291    pub ends: Vec<RowEnd>,
292    pub result_type: Arc<LemmaType>,
293}
294
295/// Index into a [`NormalFormInterner`] / shipped [`crate::planning::execution_plan::ExecutionPlan::normal_forms`].
296#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
297pub struct NormalFormId(u32);
298
299impl NormalFormId {
300    pub fn index(self) -> usize {
301        self.0 as usize
302    }
303
304    pub fn from_index(index: usize) -> Self {
305        Self(u32::try_from(index).expect("BUG: normal_forms table exceeds u32::MAX"))
306    }
307}
308
309/// One operand of a [`NormalFormKind::Sum`] or [`NormalFormKind::Product`]. `inverse`
310/// marks a subtracted (Sum) or divided (Product) operand. The first term of a
311/// Sum/Product is never inverse.
312#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
313pub struct ArithmeticTerm {
314    pub operand: NormalFormId,
315    pub inverse: bool,
316}
317
318impl ArithmeticTerm {
319    pub(crate) fn direct(operand: NormalFormId) -> Self {
320        Self {
321            operand,
322            inverse: false,
323        }
324    }
325
326    pub(crate) fn inverted(operand: NormalFormId) -> Self {
327        Self {
328            operand,
329            inverse: true,
330        }
331    }
332}
333
334/// One region body of a [`NormalFormKind::OrderedDispatch`] table.
335#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
336pub enum DispatchRegion {
337    /// The region's value is this origin arm body.
338    Body(NormalFormId),
339    /// A conjunctive nest: a Piecewise over the residual arms of one key. Its arm
340    /// bodies are origin arm bodies, and its winner is decided by the same scan as the
341    /// origin Piecewise.
342    Conjunctive(NormalFormId),
343}
344
345impl DispatchRegion {
346    pub fn is_conjunctive(&self) -> bool {
347        matches!(self, DispatchRegion::Conjunctive(_))
348    }
349
350    pub fn cell(self) -> NormalFormId {
351        match self {
352            DispatchRegion::Body(id) | DispatchRegion::Conjunctive(id) => id,
353        }
354    }
355
356    fn map_cell(self, map: &mut impl FnMut(NormalFormId) -> NormalFormId) -> Self {
357        match self {
358            DispatchRegion::Body(id) => DispatchRegion::Body(map(id)),
359            DispatchRegion::Conjunctive(id) => DispatchRegion::Conjunctive(map(id)),
360        }
361    }
362}
363
364/// Algebraic structure only. Children are [`NormalFormId`]. Hash/Eq drive cons —
365/// no source spans or rule-ref identity here (those live on [`NormalForm`]).
366#[derive(Clone, Debug, PartialEq, Eq, Hash)]
367pub enum NormalFormKind {
368    Leaf(LeafKind),
369    Sum(Vec<ArithmeticTerm>),
370    Product(Vec<ArithmeticTerm>),
371    Subtract(NormalFormId, NormalFormId),
372    Divide(NormalFormId, NormalFormId),
373    Power(NormalFormId, NormalFormId),
374    Modulo(NormalFormId, NormalFormId),
375    Negate(NormalFormId),
376    Reciprocal(NormalFormId),
377    Comparison(NormalFormId, ComparisonComputation, NormalFormId),
378    /// Logical operands in source order.
379    Logical(LogicalConnective, Vec<NormalFormId>),
380    Not(NormalFormId),
381    MathOp(MathematicalComputation, NormalFormId),
382    /// `operand -> round` or `operand -> round step`.
383    StepRounding(RoundingMode, NormalFormId, Option<NormalFormId>),
384    UnitConversion(NormalFormId, SemanticConversionTarget),
385    Veto(VetoExpression),
386    DateRelative(DateRelativeKind, NormalFormId),
387    DateCalendar(DateCalendarKind, CalendarPeriodUnit, NormalFormId),
388    RangeLiteral(NormalFormId, NormalFormId),
389    PastFutureRange(DateRelativeKind, NormalFormId),
390    RangeContainment(NormalFormId, NormalFormId),
391    RangeBound(RangeBound, NormalFormId),
392    ResultIsVeto(NormalFormId),
393    Now,
394    Piecewise(Vec<(NormalFormId, NormalFormId)>),
395    /// A [`Self::Piecewise`] over one scrutinee, decided by binary search instead
396    /// of a linear arm scan. Built by [`ordered_dispatch`], which always records
397    /// the pre-image as `origin`, so explanation keeps reading the Piecewise.
398    OrderedDispatch {
399        scrutinee: NormalFormId,
400        /// Sorted, deduplicated, all of one [`DispatchKey`] class.
401        /// Shared so plan extract / rebuild clones are a refcount bump.
402        boundaries: Arc<[DispatchKey]>,
403        /// Exactly [`region_count`] entries; see [`crate::planning::ordered_dispatch`].
404        regions: Vec<DispatchRegion>,
405    },
406    /// Read member `path.name` of the row `base` yields, in that row's context.
407    SpecMember {
408        base: NormalFormId,
409        path: Vec<String>,
410        name: String,
411        row: RowRead,
412    },
413    /// Field `end` of the current row of the instance-list command at `level`
414    /// (0 = outermost), read through the template plan of `identity`.
415    RowField {
416        level: u32,
417        identity: SpecIdentity,
418        end: RowEnd,
419        /// Written list qualifier, preserved for explanation display. `None` for bare refs.
420        qualifier: Option<Vec<String>>,
421    },
422    /// `row_level` is set when argument cells read the current list row at that
423    /// level, through [`LeafKind::RowValue`] or [`Self::RowField`].
424    ListCommand {
425        list: NormalFormId,
426        op: NormalFormListOp,
427        args: Vec<NormalFormId>,
428        row_level: Option<u32>,
429    },
430}
431
432#[derive(Clone, Debug, PartialEq, Eq, Hash)]
433pub enum NormalFormListOp {
434    Find,
435    First,
436    Last,
437    Count,
438    Sum,
439    Avg,
440    Product,
441    Min,
442    Max,
443    /// `args[0]` is the boolean expression evaluated once per row.
444    Predicate {
445        kind: crate::planning::semantics::ListPredKind,
446        form: ListPredicateForm,
447    },
448    Sort {
449        descending: bool,
450    },
451    Top,
452    With,
453    /// Append one row of spec `identity`; `args` are the values of `fields`, in order.
454    WithRow {
455        identity: Arc<SpecIdentity>,
456        fields: Vec<DataPath>,
457    },
458    /// Set field key(s) on a Spec-element list; evaluation returns the list unchanged.
459    Key {
460        fields: Vec<DataPath>,
461    },
462}
463
464impl NormalFormKind {
465    /// Calls `f` on each child cell id in evaluation order. Piecewise yields `cond, body`
466    /// per arm from index 0; OrderedDispatch yields the scrutinee then every region body.
467    pub fn for_each_child(&self, mut f: impl FnMut(NormalFormId)) {
468        match self {
469            NormalFormKind::Leaf(_) | NormalFormKind::Veto(_) | NormalFormKind::Now => {}
470            NormalFormKind::Sum(terms) | NormalFormKind::Product(terms) => {
471                terms.iter().for_each(|term| f(term.operand));
472            }
473            NormalFormKind::Logical(_, children) => children.iter().copied().for_each(f),
474            NormalFormKind::Subtract(a, b)
475            | NormalFormKind::Divide(a, b)
476            | NormalFormKind::Power(a, b)
477            | NormalFormKind::Modulo(a, b)
478            | NormalFormKind::Comparison(a, _, b)
479            | NormalFormKind::RangeLiteral(a, b)
480            | NormalFormKind::RangeContainment(a, b) => {
481                f(*a);
482                f(*b);
483            }
484            NormalFormKind::StepRounding(_, a, step) => {
485                f(*a);
486                if let Some(step) = step {
487                    f(*step);
488                }
489            }
490            NormalFormKind::Negate(x)
491            | NormalFormKind::Reciprocal(x)
492            | NormalFormKind::Not(x)
493            | NormalFormKind::MathOp(_, x)
494            | NormalFormKind::UnitConversion(x, _)
495            | NormalFormKind::DateRelative(_, x)
496            | NormalFormKind::DateCalendar(_, _, x)
497            | NormalFormKind::PastFutureRange(_, x)
498            | NormalFormKind::RangeBound(_, x)
499            | NormalFormKind::ResultIsVeto(x) => f(*x),
500            NormalFormKind::Piecewise(arms) => arms.iter().for_each(|(condition, body)| {
501                f(*condition);
502                f(*body);
503            }),
504            NormalFormKind::OrderedDispatch {
505                scrutinee, regions, ..
506            } => {
507                f(*scrutinee);
508                regions.iter().for_each(|region| f(region.cell()));
509            }
510            NormalFormKind::SpecMember { base, .. } => f(*base),
511            NormalFormKind::RowField { .. } => {}
512            NormalFormKind::ListCommand { list, args, .. } => {
513                f(*list);
514                args.iter().copied().for_each(f);
515            }
516        }
517    }
518
519    /// Child cell ids in [`Self::for_each_child`] order.
520    pub fn children(&self) -> Vec<NormalFormId> {
521        let mut children = Vec::new();
522        self.for_each_child(|child| children.push(child));
523        children
524    }
525
526    /// Same Kind with every child id passed through `map`. Payloads that are not
527    /// child ids (operators, literals, targets, boundaries) are cloned.
528    pub(crate) fn map_children(&self, mut map: impl FnMut(NormalFormId) -> NormalFormId) -> Self {
529        match self {
530            NormalFormKind::Leaf(leaf) => NormalFormKind::Leaf(leaf.clone()),
531            NormalFormKind::Sum(terms) => NormalFormKind::Sum(
532                terms
533                    .iter()
534                    .map(|term| ArithmeticTerm {
535                        operand: map(term.operand),
536                        inverse: term.inverse,
537                    })
538                    .collect(),
539            ),
540            NormalFormKind::Product(terms) => NormalFormKind::Product(
541                terms
542                    .iter()
543                    .map(|term| ArithmeticTerm {
544                        operand: map(term.operand),
545                        inverse: term.inverse,
546                    })
547                    .collect(),
548            ),
549            NormalFormKind::Logical(connective, children) => {
550                NormalFormKind::Logical(*connective, children.iter().copied().map(map).collect())
551            }
552            NormalFormKind::Subtract(a, b) => NormalFormKind::Subtract(map(*a), map(*b)),
553            NormalFormKind::Divide(a, b) => NormalFormKind::Divide(map(*a), map(*b)),
554            NormalFormKind::Power(a, b) => NormalFormKind::Power(map(*a), map(*b)),
555            NormalFormKind::Modulo(a, b) => NormalFormKind::Modulo(map(*a), map(*b)),
556            NormalFormKind::Comparison(a, op, b) => {
557                NormalFormKind::Comparison(map(*a), op.clone(), map(*b))
558            }
559            NormalFormKind::RangeLiteral(a, b) => NormalFormKind::RangeLiteral(map(*a), map(*b)),
560            NormalFormKind::RangeContainment(a, b) => {
561                NormalFormKind::RangeContainment(map(*a), map(*b))
562            }
563            NormalFormKind::Negate(x) => NormalFormKind::Negate(map(*x)),
564            NormalFormKind::Reciprocal(x) => NormalFormKind::Reciprocal(map(*x)),
565            NormalFormKind::Not(x) => NormalFormKind::Not(map(*x)),
566            NormalFormKind::MathOp(op, x) => NormalFormKind::MathOp(op.clone(), map(*x)),
567            NormalFormKind::StepRounding(mode, x, step) => {
568                NormalFormKind::StepRounding(*mode, map(*x), step.map(map))
569            }
570            NormalFormKind::UnitConversion(x, target) => {
571                NormalFormKind::UnitConversion(map(*x), target.clone())
572            }
573            NormalFormKind::Veto(v) => NormalFormKind::Veto(v.clone()),
574            NormalFormKind::DateRelative(kind, x) => NormalFormKind::DateRelative(*kind, map(*x)),
575            NormalFormKind::DateCalendar(kind, unit, x) => {
576                NormalFormKind::DateCalendar(*kind, *unit, map(*x))
577            }
578            NormalFormKind::PastFutureRange(kind, x) => {
579                NormalFormKind::PastFutureRange(*kind, map(*x))
580            }
581            NormalFormKind::RangeBound(bound, x) => NormalFormKind::RangeBound(*bound, map(*x)),
582            NormalFormKind::ResultIsVeto(x) => NormalFormKind::ResultIsVeto(map(*x)),
583            NormalFormKind::Now => NormalFormKind::Now,
584            NormalFormKind::Piecewise(arms) => NormalFormKind::Piecewise(
585                arms.iter()
586                    .map(|(condition, body)| (map(*condition), map(*body)))
587                    .collect(),
588            ),
589            NormalFormKind::OrderedDispatch {
590                scrutinee,
591                boundaries,
592                regions,
593            } => NormalFormKind::OrderedDispatch {
594                scrutinee: map(*scrutinee),
595                boundaries: boundaries.clone(),
596                regions: regions
597                    .iter()
598                    .map(|region| region.map_cell(&mut map))
599                    .collect(),
600            },
601            NormalFormKind::SpecMember {
602                base,
603                path,
604                name,
605                row,
606            } => NormalFormKind::SpecMember {
607                base: map(*base),
608                path: path.clone(),
609                name: name.clone(),
610                row: row.clone(),
611            },
612            NormalFormKind::RowField { .. } => self.clone(),
613            NormalFormKind::ListCommand {
614                list,
615                op,
616                args,
617                row_level,
618            } => NormalFormKind::ListCommand {
619                list: map(*list),
620                op: op.clone(),
621                args: args.iter().copied().map(map).collect(),
622                row_level: *row_level,
623            },
624        }
625    }
626}
627
628/// One node in THE DAG: algebraic Kind, stamped result type, optional conversion
629/// span, optional fold origin, optional rule use-site identity.
630///
631/// A rule use-site shares the completed body's Kind (same child ids) and sets
632/// `rule_ref`. Type is the graph rule type (`RulePath`) or data resolved type
633/// (rule-target DataPath) — not the post-rewrite body cell type. Cons keys on
634/// `(kind, rule_ref, result_type)` so a rule reference never collapses into the
635/// bare body cell, and DataPath leaves that differ only in resolved type stay
636/// distinct.
637#[derive(Clone, Debug)]
638pub struct NormalForm {
639    pub kind: NormalFormKind,
640    /// Type of the value this cell evaluates to. Stamped at planning.
641    pub result_type: Arc<LemmaType>,
642    /// For Sum/Product: type after folding `children[..=k]`. Empty for other kinds.
643    /// `fold_types.last()` equals `result_type` for n-ary arithmetic.
644    pub fold_types: Vec<Arc<LemmaType>>,
645    /// Span for unit-conversion nodes; does not affect sharing.
646    pub source: Option<Source>,
647    /// Pre-image destroyed by a fold; blocks sharing when present.
648    pub origin: Option<NormalFormId>,
649    /// Use-site of a named rule (`None` on ordinary cells).
650    pub rule_ref: Option<RulePath>,
651}
652
653impl NormalForm {
654    /// The Piecewise an [`NormalFormKind::OrderedDispatch`] table looks up.
655    pub(crate) fn dispatched_rule(&self) -> NormalFormId {
656        self.origin
657            .expect("BUG: OrderedDispatch always carries its Piecewise pre-image as origin")
658    }
659}
660
661/// Result of [`Cells::type_of`]: stamped result type plus progressive fold types
662/// for n-ary Sum/Product (empty for every other kind).
663pub(crate) struct Typed {
664    pub(crate) result_type: Arc<LemmaType>,
665    pub(crate) fold_types: Vec<Arc<LemmaType>>,
666}
667
668/// Cons key: algebraic Kind, optional rule-ref identity, and stamped result
669/// type. Type is part of the key so a shared interner across temporal slices
670/// never collapses DataPath leaves that differ only in resolved type (Literal
671/// leaves already distinguish via payload identity inside Kind; range endpoints
672/// carry [`crate::planning::semantics::TypedLiteral`] types on [`crate::planning::semantics::ValueKind::Range`]).
673type ConsKey = (NormalFormKind, Option<RulePath>, Arc<LemmaType>);
674
675/// Build-local table + origin-free cons. Ship via [`Self::extract_reachable`].
676pub(crate) struct NormalFormInterner {
677    forms: Vec<NormalForm>,
678    cons: HashMap<ConsKey, NormalFormId>,
679}
680
681impl NormalFormInterner {
682    pub(crate) fn new() -> Self {
683        Self {
684            forms: Vec::new(),
685            cons: HashMap::new(),
686        }
687    }
688
689    pub(crate) fn intern(
690        &mut self,
691        kind: NormalFormKind,
692        source: Option<Source>,
693        origin: Option<NormalFormId>,
694        rule_ref: Option<RulePath>,
695        typed: Typed,
696    ) -> NormalFormId {
697        let Typed {
698            result_type,
699            fold_types,
700        } = typed;
701        let key = (kind, rule_ref, result_type);
702        if origin.is_none() {
703            if let Some(id) = self.cons.get(&key) {
704                return *id;
705            }
706        }
707        let id = NormalFormId(
708            u32::try_from(self.forms.len()).expect("BUG: normal_forms table exceeds u32::MAX"),
709        );
710        if origin.is_none() {
711            self.cons.insert(key.clone(), id);
712        }
713        self.forms.push(NormalForm {
714            kind: key.0,
715            result_type: key.2,
716            fold_types,
717            source,
718            origin,
719            rule_ref: key.1,
720        });
721        id
722    }
723
724    pub(crate) fn get(&self, id: NormalFormId) -> &NormalForm {
725        self.forms.get(id.index()).unwrap_or_else(|| {
726            panic!(
727                "BUG: NormalFormId {} out of range (table len {})",
728                id.0,
729                self.forms.len()
730            )
731        })
732    }
733
734    pub(crate) fn result_type(&self, id: NormalFormId) -> &Arc<LemmaType> {
735        &self.get(id).result_type
736    }
737
738    /// Number of cells interned so far; ids at or past it do not exist yet.
739    pub(crate) fn len(&self) -> usize {
740        self.forms.len()
741    }
742
743    /// Ship only cells reachable from `roots`. Dense-remap ids in ascending
744    /// old-index order. Walks shape children and origin. Remaps both.
745    ///
746    /// Keeps the interner so one planning pass can share it across every
747    /// temporal slice of a spec set.
748    pub(crate) fn extract_reachable(
749        &self,
750        roots: &[NormalFormId],
751    ) -> (Vec<NormalForm>, Vec<NormalFormId>) {
752        let mut reachable: HashSet<u32> = HashSet::new();
753        let mut worklist: Vec<NormalFormId> = roots.to_vec();
754        while let Some(id) = worklist.pop() {
755            if id.index() >= self.forms.len() {
756                panic!(
757                    "BUG: NormalFormId {} out of range during reachable extract (table len {})",
758                    id.0,
759                    self.forms.len()
760                );
761            }
762            if !reachable.insert(id.0) {
763                continue;
764            }
765            let cell = &self.forms[id.index()];
766            cell.kind.for_each_child(|child| worklist.push(child));
767            if let Some(origin) = cell.origin {
768                worklist.push(origin);
769            }
770        }
771        let mut old_ids: Vec<u32> = reachable.into_iter().collect();
772        old_ids.sort_unstable();
773        let mut remap: HashMap<u32, NormalFormId> = HashMap::with_capacity(old_ids.len());
774        for (new_index, old) in old_ids.iter().copied().enumerate() {
775            remap.insert(
776                old,
777                NormalFormId(
778                    u32::try_from(new_index).expect("BUG: normal_forms table exceeds u32::MAX"),
779                ),
780            );
781        }
782        let mut table = Vec::with_capacity(old_ids.len());
783        for old in &old_ids {
784            let cell = &self.forms[*old as usize];
785            table.push(NormalForm {
786                kind: cell.kind.map_children(|child| {
787                    *remap.get(&child.0).unwrap_or_else(|| {
788                        panic!("BUG: child NormalFormId {} missing from remap", child.0)
789                    })
790                }),
791                result_type: Arc::clone(&cell.result_type),
792                fold_types: cell.fold_types.clone(),
793                source: cell.source.clone(),
794                origin: cell.origin.map(|o| {
795                    *remap.get(&o.0).unwrap_or_else(|| {
796                        panic!("BUG: origin NormalFormId {} missing from remap", o.0)
797                    })
798                }),
799                rule_ref: cell.rule_ref.clone(),
800            });
801        }
802        let remapped_roots = roots
803            .iter()
804            .map(|r| {
805                *remap.get(&r.0).unwrap_or_else(|| {
806                    panic!("BUG: root NormalFormId {} not in reachable set", r.0)
807                })
808            })
809            .collect();
810        (table, remapped_roots)
811    }
812}
813
814/// Result type of a data leaf, from its definition in the flattened data map.
815/// Written units from the stored value are cleared: a path expression does not
816/// name a unit (same invariant as graph expression inference).
817pub(crate) fn data_path_result_type(
818    data: &IndexMap<DataPath, DataDefinition>,
819    path: &DataPath,
820) -> Arc<LemmaType> {
821    match data.get(path) {
822        Some(DataDefinition::Value { resolved_type, .. })
823        | Some(DataDefinition::TypeDeclaration { resolved_type, .. })
824        | Some(DataDefinition::Reference { resolved_type, .. })
825        | Some(DataDefinition::InstanceList { resolved_type, .. }) => {
826            Arc::new(resolved_type.as_ref().without_written_unit())
827        }
828        Some(DataDefinition::Import { row, .. }) => Arc::new(LemmaType::primitive(
829            crate::planning::semantics::TypeSpecification::Spec {
830                spec: row.identity.as_ref().clone(),
831            },
832        )),
833        // Absent: normalize unit tests with an empty data scope, as graph
834        // `infer_data_type`.
835        None => Arc::new(LemmaType::undetermined_type()),
836    }
837}
838
839/// The interner together with the measure scope every new cell is typed in.
840/// Lowering and every rewrite pass build cells through this, so a cell's type
841/// is fixed once, at creation, by [`Cells::type_of`].
842pub(crate) struct Cells<'a> {
843    interner: &'a mut NormalFormInterner,
844    measure_scope: MeasureScope<'a>,
845}
846
847/// Owned row-field end plus its optional written list qualifier
848/// (`children` in `children.is_leaf`). Bundled so [`Cells::intern_row_field`]
849/// stays under the argument-count lint.
850pub(crate) struct RowFieldEnd {
851    pub(crate) end: RowEnd,
852    pub(crate) qualifier: Option<Vec<String>>,
853}
854
855impl<'a> Cells<'a> {
856    pub(crate) fn new(
857        interner: &'a mut NormalFormInterner,
858        measure_scope: MeasureScope<'a>,
859    ) -> Self {
860        Self {
861            interner,
862            measure_scope,
863        }
864    }
865
866    pub(crate) fn get(&self, id: NormalFormId) -> &NormalForm {
867        self.interner.get(id)
868    }
869
870    pub(crate) fn result_type(&self, id: NormalFormId) -> &Arc<LemmaType> {
871        self.interner.result_type(id)
872    }
873
874    /// Number of cells interned so far; ids at or past it do not exist yet.
875    pub(crate) fn len(&self) -> usize {
876        self.interner.len()
877    }
878
879    pub(crate) fn intern_empty(&mut self, kind: NormalFormKind) -> NormalFormId {
880        let typed = self.type_of(&kind, None);
881        self.interner.intern(kind, None, None, None, typed)
882    }
883
884    pub(crate) fn intern_literal_leaf(
885        &mut self,
886        literal: LiteralValue,
887        result_type: Arc<LemmaType>,
888    ) -> NormalFormId {
889        self.interner.intern(
890            NormalFormKind::Leaf(LeafKind::Literal(literal)),
891            None,
892            None,
893            None,
894            Typed {
895                result_type,
896                fold_types: Vec::new(),
897            },
898        )
899    }
900
901    /// Row field cell, typed from the row spec (the type is the same on every row).
902    fn intern_row_field(
903        &mut self,
904        level: u32,
905        identity: SpecIdentity,
906        row_end: RowFieldEnd,
907        result_type: Arc<LemmaType>,
908    ) -> NormalFormId {
909        let RowFieldEnd { end, qualifier } = row_end;
910        self.interner.intern(
911            NormalFormKind::RowField {
912                level,
913                identity,
914                end,
915                qualifier,
916            },
917            None,
918            None,
919            None,
920            Typed {
921                result_type,
922                fold_types: Vec::new(),
923            },
924        )
925    }
926
927    fn intern_row_value_leaf(&mut self, level: u32, result_type: Arc<LemmaType>) -> NormalFormId {
928        self.interner.intern(
929            NormalFormKind::Leaf(LeafKind::RowValue { level }),
930            None,
931            None,
932            None,
933            Typed {
934                result_type,
935                fold_types: Vec::new(),
936            },
937        )
938    }
939
940    fn intern_data_leaf(&mut self, path: DataPath, result_type: Arc<LemmaType>) -> NormalFormId {
941        self.interner.intern(
942            NormalFormKind::Leaf(LeafKind::DataPath(path)),
943            None,
944            None,
945            None,
946            Typed {
947                result_type,
948                fold_types: Vec::new(),
949            },
950        )
951    }
952
953    /// Use-site of a named rule: share the completed body's Kind, set rule_ref,
954    /// stamp the caller-supplied type (graph rule type or data resolved type).
955    /// Empty fold_types: eval never folds through a rule_ref cut.
956    fn intern_rule_ref(
957        &mut self,
958        body: NormalFormId,
959        rule_path: RulePath,
960        result_type: Arc<LemmaType>,
961    ) -> NormalFormId {
962        let kind = self.interner.get(body).kind.clone();
963        self.interner.intern(
964            kind,
965            None,
966            None,
967            Some(rule_path),
968            Typed {
969                result_type,
970                fold_types: Vec::new(),
971            },
972        )
973    }
974
975    pub(crate) fn rebuild(
976        &mut self,
977        kind: NormalFormKind,
978        source: Option<Source>,
979        origin: Option<NormalFormId>,
980    ) -> NormalFormId {
981        let typed = self.type_of(&kind, origin);
982        self.interner.intern(kind, source, origin, None, typed)
983    }
984
985    pub(crate) fn fold_into(
986        &mut self,
987        kind: NormalFormKind,
988        destroyed_id: NormalFormId,
989    ) -> NormalFormId {
990        let typed = self.type_of(&kind, Some(destroyed_id));
991        self.interner
992            .intern(kind, None, Some(destroyed_id), None, typed)
993    }
994
995    pub(crate) fn fold_into_survivor(
996        &mut self,
997        survivor_id: NormalFormId,
998        destroyed_id: NormalFormId,
999    ) -> NormalFormId {
1000        let survivor = self.interner.get(survivor_id);
1001        // Identity-elim unwrap onto a node that already records a fold must not
1002        // erase that fold (e.g. `(exp(log(5))) + 0` → keep exp/log origin).
1003        if survivor.origin.is_some() {
1004            return survivor_id;
1005        }
1006        self.interner.intern(
1007            survivor.kind.clone(),
1008            survivor.source.clone(),
1009            Some(destroyed_id),
1010            survivor.rule_ref.clone(),
1011            Typed {
1012                result_type: Arc::clone(&survivor.result_type),
1013                fold_types: survivor.fold_types.clone(),
1014            },
1015        )
1016    }
1017
1018    /// Always re-intern survivor Kind with `origin = destroyed`, even when the
1019    /// survivor already records an origin (Piecewise collapse must keep the
1020    /// recorded arms as the explanation pre-image).
1021    pub(crate) fn replace_with_survivor(
1022        &mut self,
1023        survivor_id: NormalFormId,
1024        destroyed_id: NormalFormId,
1025    ) -> NormalFormId {
1026        let survivor = self.interner.get(survivor_id);
1027        let result_type =
1028            self.type_or_replaced(Arc::clone(&survivor.result_type), Some(destroyed_id));
1029        assert!(
1030            self.result_type(destroyed_id).same_value_type(&result_type),
1031            "BUG: Piecewise collapse survivor value type differs from destroyed Piecewise"
1032        );
1033        self.interner.intern(
1034            survivor.kind.clone(),
1035            survivor.source.clone(),
1036            Some(destroyed_id),
1037            survivor.rule_ref.clone(),
1038            Typed {
1039                result_type,
1040                fold_types: survivor.fold_types.clone(),
1041            },
1042        )
1043    }
1044
1045    /// `own`, or for a veto, which has no value type of its own, the type of the cell it
1046    /// replaces.
1047    fn type_or_replaced(
1048        &self,
1049        own: Arc<LemmaType>,
1050        pre_image: Option<NormalFormId>,
1051    ) -> Arc<LemmaType> {
1052        match pre_image {
1053            Some(replaced) if own.vetoed() => Arc::clone(self.result_type(replaced)),
1054            _ => own,
1055        }
1056    }
1057
1058    fn fold_arithmetic_child_types(
1059        &self,
1060        terms: &[ArithmeticTerm],
1061        direct: ArithmeticComputation,
1062        inverted: ArithmeticComputation,
1063    ) -> Vec<Arc<LemmaType>> {
1064        let (first, rest) = terms
1065            .split_first()
1066            .expect("BUG: arithmetic NormalForm with zero children");
1067        assert!(
1068            !first.inverse,
1069            "BUG: arithmetic NormalForm starts with an inverse term"
1070        );
1071        let mut fold_types = Vec::with_capacity(terms.len());
1072        let mut acc = Arc::clone(self.result_type(first.operand));
1073        fold_types.push(Arc::clone(&acc));
1074        for term in rest {
1075            let op = if term.inverse { &inverted } else { &direct };
1076            acc = compute_arithmetic_result_type(
1077                acc,
1078                op,
1079                Arc::clone(self.result_type(term.operand)),
1080                &self.measure_scope,
1081            );
1082            fold_types.push(Arc::clone(&acc));
1083        }
1084        fold_types
1085    }
1086
1087    fn binary_arithmetic_type(
1088        &self,
1089        left: NormalFormId,
1090        op: ArithmeticComputation,
1091        right: NormalFormId,
1092    ) -> Arc<LemmaType> {
1093        let left_type = self.result_type(left);
1094        if op == ArithmeticComputation::Power && left_type.is_measure() {
1095            if let Some(exponent) = self.integer_exponent_leaf(right) {
1096                return quantity_integer_power_type(left_type, exponent, &self.measure_scope);
1097            }
1098        }
1099        compute_arithmetic_result_type(
1100            Arc::clone(left_type),
1101            &op,
1102            Arc::clone(self.result_type(right)),
1103            &self.measure_scope,
1104        )
1105    }
1106
1107    fn integer_exponent_leaf(&self, id: NormalFormId) -> Option<i32> {
1108        let NormalFormKind::Leaf(LeafKind::Literal(literal)) = &self.get(id).kind else {
1109            return None;
1110        };
1111        let ValueKind::Number(number) = &literal.value else {
1112            return None;
1113        };
1114        if !number.is_integer() {
1115            return None;
1116        }
1117        number.numer_to_i32()
1118    }
1119}
1120
1121/// Default primitive type for a folded/constructed literal when no richer type is available.
1122/// Named measure types must be stamped explicitly via [`Cells::fold_into`] /
1123/// [`Cells::intern_literal_leaf`].
1124fn literal_value_default_result_type(value: &ValueKind) -> Arc<LemmaType> {
1125    match value {
1126        ValueKind::Number(_) => primitive_number_arc().clone(),
1127        ValueKind::Boolean(_) => primitive_boolean_arc().clone(),
1128        ValueKind::Text(_) => primitive_text_arc().clone(),
1129        ValueKind::Date(_) => primitive_date_arc().clone(),
1130        ValueKind::Time(_) => primitive_time_arc().clone(),
1131        ValueKind::Ratio(_) => primitive_ratio_arc().clone(),
1132        ValueKind::Measure(_) | ValueKind::UnscaledMeasure { .. } => {
1133            panic!(
1134                "BUG: Measure literal result_type must be stamped from expression/fold survivor type"
1135            )
1136        }
1137        ValueKind::Range(_, _) => {
1138            panic!("BUG: Range literal result_type must be stamped from expression/endpoint types")
1139        }
1140        ValueKind::Spec(_) => {
1141            panic!("BUG: Spec literal result_type must be stamped from the spec identity")
1142        }
1143        ValueKind::List(_) => {
1144            panic!("BUG: List literal result_type must be stamped from the list type")
1145        }
1146    }
1147}
1148
1149impl Cells<'_> {
1150    /// Type of a cell from its children's stamped types. Same rules as
1151    /// `infer_expression_type`, so the lowered root of a rule has the rule's
1152    /// inferred type (asserted when the plan is built). Rewrites preserve the
1153    /// value type when arms were `same_value_type` (validation invariant): base
1154    /// kind and measure dimensions stay; a named type may swap for its
1155    /// primitive or back (`x + 0` → `x`, a collapsed `unless`).
1156    ///
1157    /// `pre_image` is the cell this one replaces (a fold's destroyed cell, a
1158    /// rebuild's origin). Three kinds carry no typing information of their own
1159    /// and keep the pre-image's type: a folded literal (the fold survivor's
1160    /// measure family lives only on `result_type`), an OrderedDispatch (its
1161    /// regions are in key order, not the source order the rule type follows) and
1162    /// a Piecewise of which only vetoes are left.
1163    fn type_of(&self, kind: &NormalFormKind, pre_image: Option<NormalFormId>) -> Typed {
1164        let (result_type, fold_types) = match kind {
1165            NormalFormKind::Leaf(LeafKind::Literal(literal)) => (
1166                match pre_image {
1167                    Some(destroyed) => Arc::clone(self.result_type(destroyed)),
1168                    None => literal_value_default_result_type(&literal.value),
1169                },
1170                Vec::new(),
1171            ),
1172            NormalFormKind::Leaf(LeafKind::DataPath(_)) => {
1173                panic!("BUG: DataPath leaf result_type must be stamped from plan.data")
1174            }
1175            NormalFormKind::RowField { .. } => {
1176                panic!("BUG: row field result_type must be stamped from the row spec")
1177            }
1178            NormalFormKind::Leaf(LeafKind::RowValue { .. }) => {
1179                panic!("BUG: row value leaf result_type must be stamped from its list")
1180            }
1181            NormalFormKind::Now => (primitive_date_arc().clone(), Vec::new()),
1182            NormalFormKind::SpecMember { row, .. } => (Arc::clone(&row.result_type), Vec::new()),
1183            NormalFormKind::ListCommand { list, op, args, .. } => (
1184                list_command_result_type(
1185                    self.result_type(*list),
1186                    op,
1187                    args.first().map(|argument| self.result_type(*argument)),
1188                    &self.measure_scope,
1189                ),
1190                Vec::new(),
1191            ),
1192            NormalFormKind::Veto(_) => (Arc::new(LemmaType::veto_type()), Vec::new()),
1193            NormalFormKind::Sum(terms) => {
1194                let fold_types = self.fold_arithmetic_child_types(
1195                    terms,
1196                    ArithmeticComputation::Add,
1197                    ArithmeticComputation::Subtract,
1198                );
1199                let result_type = Arc::clone(
1200                    fold_types
1201                        .last()
1202                        .expect("BUG: Sum fold_types empty after fold_arithmetic_child_types"),
1203                );
1204                (result_type, fold_types)
1205            }
1206            NormalFormKind::Product(terms) => {
1207                let fold_types = self.fold_arithmetic_child_types(
1208                    terms,
1209                    ArithmeticComputation::Multiply,
1210                    ArithmeticComputation::Divide,
1211                );
1212                let result_type = Arc::clone(
1213                    fold_types
1214                        .last()
1215                        .expect("BUG: Product fold_types empty after fold_arithmetic_child_types"),
1216                );
1217                (result_type, fold_types)
1218            }
1219            NormalFormKind::Subtract(a, b) => (
1220                self.binary_arithmetic_type(*a, ArithmeticComputation::Subtract, *b),
1221                Vec::new(),
1222            ),
1223            NormalFormKind::Divide(a, b) => (
1224                self.binary_arithmetic_type(*a, ArithmeticComputation::Divide, *b),
1225                Vec::new(),
1226            ),
1227            NormalFormKind::Power(a, b) => (
1228                self.binary_arithmetic_type(*a, ArithmeticComputation::Power, *b),
1229                Vec::new(),
1230            ),
1231            NormalFormKind::Modulo(a, b) => (
1232                self.binary_arithmetic_type(*a, ArithmeticComputation::Modulo, *b),
1233                Vec::new(),
1234            ),
1235            // `-x` is `-1 * x`; `1/x` is `1 / x`. Typed by the kernel like the
1236            // source arithmetic they were rewritten from.
1237            NormalFormKind::Negate(x) => (
1238                compute_arithmetic_result_type(
1239                    primitive_number_arc().clone(),
1240                    &ArithmeticComputation::Multiply,
1241                    Arc::clone(self.result_type(*x)),
1242                    &self.measure_scope,
1243                ),
1244                Vec::new(),
1245            ),
1246            NormalFormKind::Reciprocal(x) => (
1247                compute_arithmetic_result_type(
1248                    primitive_number_arc().clone(),
1249                    &ArithmeticComputation::Divide,
1250                    Arc::clone(self.result_type(*x)),
1251                    &self.measure_scope,
1252                ),
1253                Vec::new(),
1254            ),
1255            NormalFormKind::Logical(_, children) => {
1256                let mut types = children.iter().map(|id| self.result_type(*id));
1257                let first = types.next().expect("BUG: And has at least two operands");
1258                let ty = types.fold(Arc::clone(first), |acc, next| {
1259                    logical_connective_type(&acc, next)
1260                });
1261                (ty, Vec::new())
1262            }
1263            NormalFormKind::Comparison(a, op, b) => (
1264                comparison_type(self.result_type(*a), op, self.result_type(*b)),
1265                Vec::new(),
1266            ),
1267            NormalFormKind::RangeContainment(a, b) => (
1268                range_containment_type(self.result_type(*a), self.result_type(*b)),
1269                Vec::new(),
1270            ),
1271            NormalFormKind::Not(x) => (logical_not_type(self.result_type(*x)), Vec::new()),
1272            NormalFormKind::DateRelative(_, x) | NormalFormKind::DateCalendar(_, _, x) => {
1273                (date_predicate_type(self.result_type(*x)), Vec::new())
1274            }
1275            NormalFormKind::ResultIsVeto(_) => (result_is_veto_type(), Vec::new()),
1276            NormalFormKind::MathOp(op, x) => (
1277                math_op_type(op, self.result_type(*x), &self.measure_scope),
1278                Vec::new(),
1279            ),
1280            NormalFormKind::StepRounding(_, x, step) => (
1281                step_rounding_type(
1282                    self.result_type(*x),
1283                    step.map(|step| self.result_type(step)),
1284                ),
1285                Vec::new(),
1286            ),
1287            NormalFormKind::UnitConversion(x, target) => (
1288                unit_conversion_type(self.result_type(*x), target),
1289                Vec::new(),
1290            ),
1291            NormalFormKind::RangeLiteral(a, b) => {
1292                let (a, b) = (self.result_type(*a), self.result_type(*b));
1293                let ty = if a.vetoed() || b.vetoed() {
1294                    Arc::new(LemmaType::veto_type())
1295                } else {
1296                    infer_range_type_from_endpoint_types(a.as_ref(), b.as_ref())
1297                };
1298                (ty, Vec::new())
1299            }
1300            NormalFormKind::PastFutureRange(_, offset) => (
1301                past_future_range_type(self.result_type(*offset)),
1302                Vec::new(),
1303            ),
1304            NormalFormKind::RangeBound(_, operand) => (
1305                range_bound_result_type(self.result_type(*operand), &self.measure_scope),
1306                Vec::new(),
1307            ),
1308            NormalFormKind::Piecewise(arms) => (
1309                self.type_or_replaced(
1310                    piecewise_type(
1311                        arms.iter()
1312                            .map(|(_, body)| Arc::clone(self.result_type(*body))),
1313                        &self.measure_scope,
1314                    ),
1315                    pre_image,
1316                ),
1317                Vec::new(),
1318            ),
1319            NormalFormKind::OrderedDispatch { .. } => (
1320                Arc::clone(self.result_type(pre_image.expect(
1321                    "BUG: OrderedDispatch is only built over the Piecewise it re-indexes",
1322                ))),
1323                Vec::new(),
1324            ),
1325        };
1326        // After planning validation every operand is determined, so an undetermined
1327        // stamp here is a validation gap. Unit tests may still lower untyped paths;
1328        // undetermined is then only legal when an operand already was.
1329        if result_type.is_undetermined() {
1330            let input_undetermined = match kind {
1331                NormalFormKind::Leaf(_) | NormalFormKind::Now | NormalFormKind::Veto(_) => false,
1332                NormalFormKind::OrderedDispatch { .. } => {
1333                    pre_image.is_some_and(|id| self.result_type(id).is_undetermined())
1334                }
1335                NormalFormKind::Sum(terms) | NormalFormKind::Product(terms) => terms
1336                    .iter()
1337                    .any(|term| self.result_type(term.operand).is_undetermined()),
1338                NormalFormKind::Logical(_, children) => children
1339                    .iter()
1340                    .any(|id| self.result_type(*id).is_undetermined()),
1341                NormalFormKind::Subtract(a, b)
1342                | NormalFormKind::Divide(a, b)
1343                | NormalFormKind::Power(a, b)
1344                | NormalFormKind::Modulo(a, b)
1345                | NormalFormKind::RangeLiteral(a, b) => {
1346                    self.result_type(*a).is_undetermined() || self.result_type(*b).is_undetermined()
1347                }
1348                NormalFormKind::StepRounding(_, a, step) => {
1349                    self.result_type(*a).is_undetermined()
1350                        || step.is_some_and(|step| self.result_type(step).is_undetermined())
1351                }
1352                // Infer returns Undetermined for invalid operand pairs; validation
1353                // rejects those before a plan is built. Normalize unit tests may
1354                // lower without validation, so determined operands → Undetermined
1355                // is allowed here.
1356                NormalFormKind::Comparison(_, _, _) | NormalFormKind::RangeContainment(_, _) => {
1357                    true
1358                }
1359                NormalFormKind::Negate(x)
1360                | NormalFormKind::Reciprocal(x)
1361                | NormalFormKind::UnitConversion(x, _)
1362                | NormalFormKind::RangeBound(_, x)
1363                | NormalFormKind::ResultIsVeto(x) => self.result_type(*x).is_undetermined(),
1364                NormalFormKind::Not(_)
1365                | NormalFormKind::DateRelative(_, _)
1366                | NormalFormKind::DateCalendar(_, _, _)
1367                | NormalFormKind::MathOp(_, _)
1368                | NormalFormKind::PastFutureRange(_, _) => true,
1369                NormalFormKind::Piecewise(arms) => arms.iter().any(|(condition, body)| {
1370                    self.result_type(*condition).is_undetermined()
1371                        || self.result_type(*body).is_undetermined()
1372                }),
1373                NormalFormKind::SpecMember { base, .. } => {
1374                    self.result_type(*base).is_undetermined()
1375                }
1376                NormalFormKind::RowField { .. } => false,
1377                NormalFormKind::ListCommand { list, args, .. } => {
1378                    self.result_type(*list).is_undetermined()
1379                        || args
1380                            .iter()
1381                            .any(|id| self.result_type(*id).is_undetermined())
1382                }
1383            };
1384            assert!(
1385                input_undetermined,
1386                "BUG: NormalForm cell stamped undetermined type after validation"
1387            );
1388        }
1389        Typed {
1390            result_type,
1391            fold_types,
1392        }
1393    }
1394}
1395
1396impl LowerCtx<'_> {
1397    /// Root of an already planned rule. Every rule a cell reads precedes it in topo order.
1398    fn completed_rule(&self, path: &RulePath) -> NormalFormId {
1399        *self.completed_rules.get(path).unwrap_or_else(|| {
1400            panic!(
1401                "BUG: rule '{}' read before it was planned (missing dependency edge)",
1402                path.input_key()
1403            )
1404        })
1405    }
1406
1407    fn rule_type(&self, path: &RulePath) -> Arc<LemmaType> {
1408        Arc::clone(self.rule_types.get(path).unwrap_or_else(|| {
1409            panic!("BUG: rule '{}' has no RuleNode.rule_type", path.input_key())
1410        }))
1411    }
1412}
1413
1414/// Lower the tree into `cells`, children before parents.
1415fn to_normal_form(tree: &Expression, cells: &mut Cells<'_>, lower: &LowerCtx<'_>) -> NormalFormId {
1416    let mut lowered: Vec<NormalFormId> = Vec::with_capacity(tree.table.len());
1417    let mut children: Vec<NormalFormId> = Vec::new();
1418    for id in tree.table.ids() {
1419        let node = tree.at(id);
1420        children.clear();
1421        node.kind()
1422            .for_each_child(|child| children.push(lowered[child.index()]));
1423        lowered.push(lower_node(node, &children, &lowered, cells, lower));
1424    }
1425    *lowered.last().expect("BUG: expression tree has a root")
1426}
1427
1428/// Operator group whose consecutive chain steps lower to one n-ary cell.
1429#[derive(Clone, Copy, PartialEq, Eq)]
1430enum ArithmeticGroup {
1431    Sum,
1432    Product,
1433}
1434
1435fn arithmetic_group(op: &ArithmeticComputation) -> Option<ArithmeticGroup> {
1436    match op {
1437        ArithmeticComputation::Add | ArithmeticComputation::Subtract => Some(ArithmeticGroup::Sum),
1438        ArithmeticComputation::Multiply | ArithmeticComputation::Divide => {
1439            Some(ArithmeticGroup::Product)
1440        }
1441        ArithmeticComputation::Power | ArithmeticComputation::Modulo => None,
1442    }
1443}
1444
1445/// Lower the left fold of `first` over `steps` whose operands are lowered.
1446///
1447/// Each run of consecutive steps in one group (`a + b - c`, `a * b / c`) interns one
1448/// n-ary cell. Subtract and divide steps become negated and reciprocal operands only
1449/// when every operand of the run is numeric, as normalization expands them; otherwise
1450/// the run is lowered one binary step at a time.
1451fn lower_arithmetic_chain(
1452    first: NormalFormId,
1453    steps: &[(ArithmeticComputation, NormalFormId)],
1454    cells: &mut Cells<'_>,
1455) -> NormalFormId {
1456    let mut current = first;
1457    let mut rest = steps;
1458    while let Some((op, operand)) = rest.first() {
1459        let Some(group) = arithmetic_group(op) else {
1460            current = lower_binary_arithmetic(op, current, *operand, cells);
1461            rest = &rest[1..];
1462            continue;
1463        };
1464        let run_len = rest
1465            .iter()
1466            .take_while(|(op, _)| arithmetic_group(op) == Some(group))
1467            .count();
1468        current = lower_arithmetic_run(current, &rest[..run_len], group, cells);
1469        rest = &rest[run_len..];
1470    }
1471    current
1472}
1473
1474fn lower_arithmetic_run(
1475    first: NormalFormId,
1476    operands: &[(ArithmeticComputation, NormalFormId)],
1477    group: ArithmeticGroup,
1478    cells: &mut Cells<'_>,
1479) -> NormalFormId {
1480    let has_subtract_or_divide = operands.iter().any(|(op, _)| {
1481        matches!(
1482            op,
1483            ArithmeticComputation::Subtract | ArithmeticComputation::Divide
1484        )
1485    });
1486    let all_numeric = {
1487        let mut memo = HashMap::new();
1488        std::iter::once(first)
1489            .chain(operands.iter().map(|(_, id)| *id))
1490            .all(|id| rewrite::numeric_only(cells, &mut memo, id))
1491    };
1492    if !has_subtract_or_divide || (all_numeric && operands.len() > 1) {
1493        let terms: Vec<ArithmeticTerm> = std::iter::once(ArithmeticTerm::direct(first))
1494            .chain(operands.iter().map(|(op, id)| ArithmeticTerm {
1495                operand: *id,
1496                inverse: matches!(
1497                    op,
1498                    ArithmeticComputation::Subtract | ArithmeticComputation::Divide
1499                ),
1500            }))
1501            .collect();
1502        let kind = match group {
1503            ArithmeticGroup::Sum => NormalFormKind::Sum(terms),
1504            ArithmeticGroup::Product => NormalFormKind::Product(terms),
1505        };
1506        return cells.intern_empty(kind);
1507    }
1508    operands.iter().fold(first, |current, (op, operand)| {
1509        lower_binary_arithmetic(op, current, *operand, cells)
1510    })
1511}
1512
1513fn lower_binary_arithmetic(
1514    op: &ArithmeticComputation,
1515    left: NormalFormId,
1516    right: NormalFormId,
1517    cells: &mut Cells<'_>,
1518) -> NormalFormId {
1519    let kind = match op {
1520        ArithmeticComputation::Subtract => NormalFormKind::Subtract(left, right),
1521        ArithmeticComputation::Divide => NormalFormKind::Divide(left, right),
1522        ArithmeticComputation::Add => NormalFormKind::Sum(vec![
1523            ArithmeticTerm::direct(left),
1524            ArithmeticTerm::direct(right),
1525        ]),
1526        ArithmeticComputation::Multiply => NormalFormKind::Product(vec![
1527            ArithmeticTerm::direct(left),
1528            ArithmeticTerm::direct(right),
1529        ]),
1530        ArithmeticComputation::Power => NormalFormKind::Power(left, right),
1531        ArithmeticComputation::Modulo => NormalFormKind::Modulo(left, right),
1532    };
1533    cells.intern_empty(kind)
1534}
1535
1536/// Member `path.name` read on the row `base` yields, through the template plans of
1537/// its spec and of every `uses` hop.
1538fn lower_spec_member(
1539    base: NormalFormId,
1540    path: &[String],
1541    name: &str,
1542    cells: &mut Cells<'_>,
1543    lower: &LowerCtx<'_>,
1544) -> NormalFormId {
1545    let crate::planning::semantics::TypeSpecification::Spec { spec } =
1546        &cells.result_type(base).specifications
1547    else {
1548        panic!(
1549            "BUG: member '{}' read on a base that is not spec-typed after typing",
1550            crate::planning::semantics::spec_member_input_key(path, name)
1551        );
1552    };
1553    let chain = lower.row_member_chain(spec, path, name).unwrap_or_else(|| {
1554        panic!(
1555            "BUG: row member '{}' of '{spec}' passed typing",
1556            crate::planning::semantics::spec_member_input_key(path, name)
1557        )
1558    });
1559    let last = chain.last().expect("BUG: a row end chain has a last hop");
1560    let mut result_type = lower.row_end_type(&last.identity, &last.end);
1561    if let NormalFormKind::Leaf(LeafKind::DataPath(data_path)) = &cells.get(base).kind {
1562        result_type = reanchor_lowered_member_type(lower, data_path, path, result_type);
1563    }
1564    result_type = Arc::new(result_type.as_ref().without_written_unit());
1565    cells.intern_empty(NormalFormKind::SpecMember {
1566        base,
1567        path: path.to_vec(),
1568        name: name.to_string(),
1569        row: RowRead {
1570            ends: chain.into_iter().map(|hop| hop.end).collect(),
1571            result_type,
1572        },
1573    })
1574}
1575
1576/// Prefix `uses` hops from a SpecMember's import base onto the field type's
1577/// dynamic scale references (normalize twin of graph typing's reanchor).
1578fn reanchor_lowered_member_type(
1579    lower: &LowerCtx<'_>,
1580    base_path: &DataPath,
1581    member_path: &[String],
1582    lemma_type: Arc<LemmaType>,
1583) -> Arc<LemmaType> {
1584    use crate::planning::semantics::{DataDefinition, LemmaType, SpecIdentity};
1585    let Some(DataDefinition::Import { row, .. }) = lower.data.get(base_path) else {
1586        return lemma_type;
1587    };
1588    LemmaType::reanchor_through_import_path(
1589        lemma_type,
1590        lower.self_identity,
1591        &base_path.data,
1592        row.identity.as_ref(),
1593        member_path,
1594        |identity: &SpecIdentity, segment: &str| {
1595            let template = lower.template(identity);
1596            let slot = DataPath::local(segment.to_string());
1597            match template.data.get(&slot) {
1598                Some(DataDefinition::Import { row, .. }) => Some(row.identity.as_ref().clone()),
1599                _ => None,
1600            }
1601        },
1602    )
1603}
1604
1605/// Lower one node whose children are already lowered to `children`, in `children()` order.
1606fn lower_node(
1607    node: ExprRef<'_, ExpressionKind>,
1608    children: &[NormalFormId],
1609    lowered: &[NormalFormId],
1610    cells: &mut Cells<'_>,
1611    lower: &LowerCtx<'_>,
1612) -> NormalFormId {
1613    match node.kind() {
1614        ExpressionKind::Literal(lit) => {
1615            cells.intern_literal_leaf(lit.to_literal(), Arc::clone(&lit.lemma_type))
1616        }
1617        // A data slot bound to a rule (`-> with slot: big`) stays a data leaf: the read
1618        // takes the rule's value and checks it against the slot's declared type.
1619        ExpressionKind::DataPath(p) => {
1620            cells.intern_data_leaf(p.clone(), data_path_result_type(lower.data, p))
1621        }
1622        ExpressionKind::SpecMember { path, name, .. } => {
1623            lower_spec_member(children[0], path, name, cells, lower)
1624        }
1625        ExpressionKind::RulePath(path) => {
1626            let body = lower.completed_rule(path);
1627            cells.intern_rule_ref(
1628                body,
1629                path.clone(),
1630                Arc::new(lower.rule_type(path).as_ref().without_written_unit()),
1631            )
1632        }
1633        ExpressionKind::Logical { connective, .. } => {
1634            cells.intern_empty(NormalFormKind::Logical(*connective, children.to_vec()))
1635        }
1636        ExpressionKind::Arithmetic { steps, .. } => {
1637            let (first, operands) = children
1638                .split_first()
1639                .expect("BUG: arithmetic chain has a first operand");
1640            assert_eq!(
1641                operands.len(),
1642                steps.len(),
1643                "BUG: arithmetic chain lowered to one operand per step"
1644            );
1645            let steps: Vec<(ArithmeticComputation, NormalFormId)> = steps
1646                .iter()
1647                .zip(operands)
1648                .map(|(step, operand)| (step.op.clone(), *operand))
1649                .collect();
1650            lower_arithmetic_chain(*first, &steps, cells)
1651        }
1652        ExpressionKind::Comparison(_, op, _) => {
1653            let &[left_id, right_id] = children else {
1654                unreachable!("BUG: comparison has two operands")
1655            };
1656            cells.intern_empty(NormalFormKind::Comparison(left_id, op.clone(), right_id))
1657        }
1658        ExpressionKind::UnitConversion(_, target) => {
1659            let &[inner_id] = children else {
1660                unreachable!("BUG: unit conversion has one operand")
1661            };
1662            cells.rebuild(
1663                NormalFormKind::UnitConversion(inner_id, target.clone()),
1664                node.source().cloned(),
1665                None,
1666            )
1667        }
1668        ExpressionKind::LogicalNegation(_, _) => {
1669            let &[inner_id] = children else {
1670                unreachable!("BUG: negation has one operand")
1671            };
1672            cells.intern_empty(NormalFormKind::Not(inner_id))
1673        }
1674        ExpressionKind::MathematicalComputation(op, _) => {
1675            let &[inner_id] = children else {
1676                unreachable!("BUG: math operator has one operand")
1677            };
1678            cells.intern_empty(NormalFormKind::MathOp(op.clone(), inner_id))
1679        }
1680        ExpressionKind::StepRounding { mode, .. } => match *children {
1681            [operand_id] => {
1682                cells.intern_empty(NormalFormKind::StepRounding(*mode, operand_id, None))
1683            }
1684            [operand_id, step_id] => cells.intern_empty(NormalFormKind::StepRounding(
1685                *mode,
1686                operand_id,
1687                Some(step_id),
1688            )),
1689            _ => unreachable!("BUG: step rounding has an operand and an optional step"),
1690        },
1691        ExpressionKind::Veto(v) => cells.intern_empty(NormalFormKind::Veto(v.clone())),
1692        ExpressionKind::Now => cells.intern_empty(NormalFormKind::Now),
1693        ExpressionKind::DateRelative(kind, _) => {
1694            let &[inner_id] = children else {
1695                unreachable!("BUG: date relative has one operand")
1696            };
1697            cells.intern_empty(NormalFormKind::DateRelative(*kind, inner_id))
1698        }
1699        ExpressionKind::DateCalendar(kind, unit, _) => {
1700            let &[inner_id] = children else {
1701                unreachable!("BUG: date calendar has one operand")
1702            };
1703            cells.intern_empty(NormalFormKind::DateCalendar(*kind, *unit, inner_id))
1704        }
1705        ExpressionKind::RangeLiteral(_, _) => {
1706            let &[left_id, right_id] = children else {
1707                unreachable!("BUG: range literal has two operands")
1708            };
1709            cells.intern_empty(NormalFormKind::RangeLiteral(left_id, right_id))
1710        }
1711        ExpressionKind::PastFutureRange(kind, _) => {
1712            let &[inner_id] = children else {
1713                unreachable!("BUG: past/future range has one operand")
1714            };
1715            cells.intern_empty(NormalFormKind::PastFutureRange(*kind, inner_id))
1716        }
1717        ExpressionKind::RangeBound(bound, _) => {
1718            let &[inner_id] = children else {
1719                unreachable!("BUG: range bound has one operand")
1720            };
1721            cells.intern_empty(NormalFormKind::RangeBound(*bound, inner_id))
1722        }
1723        ExpressionKind::RangeContainment(_, _) => {
1724            let &[left_id, right_id] = children else {
1725                unreachable!("BUG: range containment has two operands")
1726            };
1727            cells.intern_empty(NormalFormKind::RangeContainment(left_id, right_id))
1728        }
1729        ExpressionKind::ResultIsVeto(_) => {
1730            let &[operand_id] = children else {
1731                unreachable!("BUG: result-is-veto has one operand")
1732            };
1733            cells.intern_empty(NormalFormKind::ResultIsVeto(operand_id))
1734        }
1735        ExpressionKind::Piecewise(_) => {
1736            let mapped = children
1737                .chunks_exact(2)
1738                .map(|pair| (pair[0], pair[1]))
1739                .collect();
1740            cells.intern_empty(NormalFormKind::Piecewise(mapped))
1741        }
1742        ExpressionKind::ListCommand { op, row_level, .. } => {
1743            let (list_id, args) = children
1744                .split_first()
1745                .expect("BUG: list command has a list operand");
1746            cells.intern_empty(NormalFormKind::ListCommand {
1747                list: *list_id,
1748                op: list_op_kind(op),
1749                args: args.to_vec(),
1750                row_level: *row_level,
1751            })
1752        }
1753        ExpressionKind::RowField {
1754            level,
1755            identity,
1756            end,
1757            qualifier,
1758        } => cells.intern_row_field(
1759            *level,
1760            identity.clone(),
1761            RowFieldEnd {
1762                end: end.clone(),
1763                qualifier: qualifier.clone(),
1764            },
1765            Arc::new(
1766                lower
1767                    .row_end_type(identity, end)
1768                    .as_ref()
1769                    .without_written_unit(),
1770            ),
1771        ),
1772        ExpressionKind::RowValue { level, list } => {
1773            let list_cell = *lowered.get(list.index()).expect(
1774                "BUG: row value type-only list reference must point to an earlier expression",
1775            );
1776            let element_type = cells.result_type(list_cell).list_element_lemma_type();
1777            cells.intern_row_value_leaf(
1778                *level,
1779                Arc::new(element_type.as_ref().without_written_unit()),
1780            )
1781        }
1782    }
1783}
1784
1785/// The normal-form operation of a list op. Its operands are the list command's children
1786/// in `children()` order.
1787fn list_op_kind(op: &crate::planning::semantics::ListOp) -> NormalFormListOp {
1788    use crate::planning::semantics::{ListOp, ListReduce};
1789    match op {
1790        ListOp::Find { .. } => NormalFormListOp::Find,
1791        ListOp::First => NormalFormListOp::First,
1792        ListOp::Last => NormalFormListOp::Last,
1793        ListOp::Count => NormalFormListOp::Count,
1794        ListOp::Reduce { kind, .. } => match kind {
1795            ListReduce::Sum => NormalFormListOp::Sum,
1796            ListReduce::Avg => NormalFormListOp::Avg,
1797            ListReduce::Product => NormalFormListOp::Product,
1798            ListReduce::Min => NormalFormListOp::Min,
1799            ListReduce::Max => NormalFormListOp::Max,
1800        },
1801        ListOp::Predicate { kind, form, .. } => NormalFormListOp::Predicate {
1802            kind: *kind,
1803            form: *form,
1804        },
1805        ListOp::Sort { descending, .. } => NormalFormListOp::Sort {
1806            descending: *descending,
1807        },
1808        ListOp::Top { .. } => NormalFormListOp::Top,
1809        ListOp::With { .. } => NormalFormListOp::With,
1810        ListOp::WithRow { identity, fields } => NormalFormListOp::WithRow {
1811            identity: Arc::new(identity.clone()),
1812            fields: fields.iter().map(|(path, _)| path.clone()).collect(),
1813        },
1814        ListOp::Key { fields } => NormalFormListOp::Key {
1815            fields: fields.clone(),
1816        },
1817    }
1818}
1819
1820/// `first_argument` is the type of the first argument cell; a reduce over instance
1821/// rows takes the type of its row expression.
1822fn list_command_result_type(
1823    list_type: &Arc<LemmaType>,
1824    op: &NormalFormListOp,
1825    first_argument: Option<&Arc<LemmaType>>,
1826    measure_scope: &crate::planning::typing::MeasureScope<'_>,
1827) -> Arc<LemmaType> {
1828    use crate::planning::typing::{
1829        list_command_result_type as stamp, list_has_instance_rows, ListCommandResultKind,
1830    };
1831    let instance_rows = list_has_instance_rows(list_type);
1832    let kind = match op {
1833        NormalFormListOp::Count => ListCommandResultKind::Count,
1834        NormalFormListOp::Predicate {
1835            kind: ListPredKind::Any | ListPredKind::All,
1836            ..
1837        } => ListCommandResultKind::BooleanPredicate,
1838        NormalFormListOp::Predicate {
1839            kind: ListPredKind::Where,
1840            ..
1841        }
1842        | NormalFormListOp::Sort { .. }
1843        | NormalFormListOp::Top
1844        | NormalFormListOp::With
1845        | NormalFormListOp::WithRow { .. }
1846        | NormalFormListOp::Key { .. } => ListCommandResultKind::KeepList,
1847        NormalFormListOp::Sum
1848        | NormalFormListOp::Avg
1849        | NormalFormListOp::Product
1850        | NormalFormListOp::Min
1851        | NormalFormListOp::Max
1852            if instance_rows =>
1853        {
1854            ListCommandResultKind::InstanceReduce
1855        }
1856        NormalFormListOp::Find
1857        | NormalFormListOp::First
1858        | NormalFormListOp::Last
1859        | NormalFormListOp::Sum
1860        | NormalFormListOp::Avg
1861        | NormalFormListOp::Product
1862        | NormalFormListOp::Min
1863        | NormalFormListOp::Max => ListCommandResultKind::Element,
1864    };
1865    let result = stamp(list_type, kind, first_argument, measure_scope);
1866    match op {
1867        NormalFormListOp::Key { fields } => {
1868            crate::planning::typing::refine_list_key_type(&result, fields)
1869        }
1870        _ => result,
1871    }
1872}
1873
1874fn cell(forms: &[NormalForm], id: NormalFormId) -> &NormalForm {
1875    forms.get(id.index()).unwrap_or_else(|| {
1876        panic!(
1877            "BUG: NormalFormId {} out of range (table len {})",
1878            id.0,
1879            forms.len()
1880        )
1881    })
1882}
1883
1884/// Expression text for a DAG node. Follows origin when present so folded
1885/// nodes display their pre-image.
1886/// Display a cell as Lemma syntax. Data paths are qualified by the written row
1887/// whose context the cell narrates in (`people.1.age`), bare at the root.
1888pub(crate) fn explanation_display(
1889    forms: &[NormalForm],
1890    id: NormalFormId,
1891    qualifier: Option<&NameScope>,
1892) -> String {
1893    Syntax(NfNode {
1894        forms,
1895        id,
1896        qualifier,
1897    })
1898    .to_string()
1899}
1900
1901/// Cell whose spelling a node displays: the pre-image of folded cells.
1902fn displayed_cell(forms: &[NormalForm], mut id: NormalFormId) -> &NormalForm {
1903    loop {
1904        let nf = cell(forms, id);
1905        match nf.origin {
1906            Some(origin) => id = origin,
1907            None => return nf,
1908        }
1909    }
1910}
1911
1912#[derive(Clone, Copy, PartialEq, Eq)]
1913enum SpineLevel {
1914    Additive,
1915    Multiplicative,
1916}
1917
1918/// One same-level, left-associative arithmetic chain as its first operand and the steps
1919/// after it, in source order. Walks the left spine iteratively, through origins, so a
1920/// long chain never recurses. A child at another level or a named rule ends the spine.
1921fn arithmetic_chain(
1922    forms: &[NormalForm],
1923    top: NormalFormId,
1924) -> (
1925    NormalFormId,
1926    Vec<(&'static ArithmeticComputation, NormalFormId)>,
1927) {
1928    let level = match &displayed_cell(forms, top).kind {
1929        NormalFormKind::Sum(_) | NormalFormKind::Subtract(..) => SpineLevel::Additive,
1930        NormalFormKind::Product(_) | NormalFormKind::Divide(..) | NormalFormKind::Modulo(..) => {
1931            SpineLevel::Multiplicative
1932        }
1933        _ => unreachable!("BUG: arithmetic_chain on a non-arithmetic cell"),
1934    };
1935    let mut steps = Vec::new();
1936    let mut current = top;
1937    loop {
1938        let shown = displayed_cell(forms, current);
1939        if shown.rule_ref.is_some() {
1940            break;
1941        }
1942        match (&shown.kind, level) {
1943            (NormalFormKind::Sum(terms), SpineLevel::Additive) => {
1944                let (first, rest) = terms
1945                    .split_first()
1946                    .expect("BUG: Sum cell has at least one operand");
1947                assert!(!first.inverse, "BUG: Sum starts with an inverse term");
1948                steps.extend(rest.iter().rev().map(|term| {
1949                    let op = if term.inverse {
1950                        &ArithmeticComputation::Subtract
1951                    } else {
1952                        &ArithmeticComputation::Add
1953                    };
1954                    (op, term.operand)
1955                }));
1956                current = first.operand;
1957            }
1958            (NormalFormKind::Subtract(left, right), SpineLevel::Additive) => {
1959                steps.push((&ArithmeticComputation::Subtract, *right));
1960                current = *left;
1961            }
1962            (NormalFormKind::Product(terms), SpineLevel::Multiplicative) => {
1963                let (first, rest) = terms
1964                    .split_first()
1965                    .expect("BUG: Product cell has at least one operand");
1966                assert!(!first.inverse, "BUG: Product starts with an inverse term");
1967                steps.extend(rest.iter().rev().map(|term| {
1968                    let op = if term.inverse {
1969                        &ArithmeticComputation::Divide
1970                    } else {
1971                        &ArithmeticComputation::Multiply
1972                    };
1973                    (op, term.operand)
1974                }));
1975                current = first.operand;
1976            }
1977            (NormalFormKind::Divide(left, right), SpineLevel::Multiplicative) => {
1978                steps.push((&ArithmeticComputation::Divide, *right));
1979                current = *left;
1980            }
1981            (NormalFormKind::Modulo(left, right), SpineLevel::Multiplicative) => {
1982                steps.push((&ArithmeticComputation::Modulo, *right));
1983                current = *left;
1984            }
1985            _ => break,
1986        }
1987    }
1988    steps.reverse();
1989    (current, steps)
1990}
1991
1992/// How an explanation names the data and rules of the instance context a cell narrates
1993/// in: as the plan holding the instance names them. Data display under the instance's
1994/// hops (`people.1.age`, `i.x`); rules under the `uses` hops above the nearest row or
1995/// the root (`i.total`), so a row's own rules stay bare.
1996pub(crate) struct NameScope {
1997    pub(crate) data: Vec<PathSegment>,
1998    pub(crate) rules: Vec<PathSegment>,
1999}
2000
2001/// A normal-form cell printed as Lemma syntax.
2002#[derive(Clone, Copy)]
2003pub(crate) struct NfNode<'a> {
2004    pub(crate) forms: &'a [NormalForm],
2005    pub(crate) id: NormalFormId,
2006    /// Instance whose context the cell narrates in; `None` for the root plan.
2007    pub(crate) qualifier: Option<&'a NameScope>,
2008}
2009
2010impl<'a> NfNode<'a> {
2011    fn at(self, id: NormalFormId) -> Self {
2012        Self {
2013            forms: self.forms,
2014            id,
2015            qualifier: self.qualifier,
2016        }
2017    }
2018}
2019
2020/// Leaf of a normal-form cell.
2021#[derive(Clone, Copy)]
2022pub(crate) enum NfAtom<'a> {
2023    Literal(&'a LiteralValue, &'a LemmaType),
2024    DataPath(&'a DataPath),
2025    /// Data path qualified by the instance whose context it narrates in.
2026    QualifiedDataPath {
2027        prefix: &'a [PathSegment],
2028        path: &'a DataPath,
2029    },
2030    Rule(&'a RulePath),
2031    /// Rule qualified by the `uses` hops of the instance whose context it narrates in.
2032    QualifiedRule {
2033        prefix: &'a [PathSegment],
2034        path: &'a RulePath,
2035    },
2036    Row(&'a RowEnd),
2037    /// Row field with its written list qualifier: `children.is_leaf`.
2038    QualifiedRow {
2039        qualifier: &'a [String],
2040        end: &'a RowEnd,
2041    },
2042    SpecMemberField {
2043        path: &'a [String],
2044        name: &'a str,
2045    },
2046    Now,
2047    Veto(&'a VetoExpression),
2048}
2049
2050impl std::fmt::Display for NfAtom<'_> {
2051    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2052        match self {
2053            NfAtom::Literal(literal, lemma_type) => {
2054                write!(f, "{}", literal.display_value_with_type(lemma_type))
2055            }
2056            NfAtom::DataPath(path) => write!(f, "{}", path.input_key()),
2057            NfAtom::QualifiedDataPath { prefix, path } => {
2058                for segment in prefix.iter() {
2059                    write!(f, "{}.", segment.input_key())?;
2060                }
2061                write!(f, "{}", path.input_key())
2062            }
2063            NfAtom::Rule(path) => write!(f, "{}", path.input_key()),
2064            NfAtom::QualifiedRule { prefix, path } => {
2065                for segment in prefix.iter() {
2066                    write!(f, "{}.", segment.input_key())?;
2067                }
2068                write!(f, "{}", path.input_key())
2069            }
2070            NfAtom::Row(end) => write!(f, "{end}"),
2071            NfAtom::QualifiedRow { qualifier, end } => {
2072                for (i, segment) in qualifier.iter().enumerate() {
2073                    if i > 0 {
2074                        f.write_str(".")?;
2075                    }
2076                    f.write_str(segment)?;
2077                }
2078                f.write_str(".")?;
2079                write!(f, "{end}")
2080            }
2081            NfAtom::SpecMemberField { path, name } => {
2082                write!(
2083                    f,
2084                    "{}",
2085                    crate::planning::semantics::spec_member_input_key(path, name)
2086                )
2087            }
2088            NfAtom::Now => write!(f, "now"),
2089            NfAtom::Veto(veto) => write!(f, "{veto}"),
2090        }
2091    }
2092}
2093
2094fn value_starts_with_sign(value: &ValueKind) -> bool {
2095    let mut current = value;
2096    loop {
2097        match current {
2098            ValueKind::Number(n) | ValueKind::Measure(n) | ValueKind::Ratio(n) => {
2099                return n.numer_is_negative()
2100            }
2101            ValueKind::Range(left, _) => current = &left.value,
2102            _ => return false,
2103        }
2104    }
2105}
2106
2107fn single_argument(args: &[NormalFormId], command: &str) -> NormalFormId {
2108    match args {
2109        [argument] => *argument,
2110        other => panic!(
2111            "BUG: `{command}` cell must carry one argument, got {}",
2112            other.len()
2113        ),
2114    }
2115}
2116
2117fn optional_argument(args: &[NormalFormId], command: &str) -> Option<NormalFormId> {
2118    match args {
2119        [] => None,
2120        [argument] => Some(*argument),
2121        other => panic!(
2122            "BUG: `{command}` cell carries at most one argument, got {}",
2123            other.len()
2124        ),
2125    }
2126}
2127
2128impl<'a> SyntaxNode<'a> for NfNode<'a> {
2129    type Atom = NfAtom<'a>;
2130
2131    fn view(self) -> SyntaxView<'a, Self> {
2132        let nf = displayed_cell(self.forms, self.id);
2133        let atom = |atom| SyntaxView::Atom {
2134            atom,
2135            starts_with_sign: false,
2136        };
2137        if let Some(path) = &nf.rule_ref {
2138            return match self.qualifier {
2139                Some(scope) if !scope.rules.is_empty() => atom(NfAtom::QualifiedRule {
2140                    prefix: &scope.rules,
2141                    path,
2142                }),
2143                Some(_) | None => atom(NfAtom::Rule(path)),
2144            };
2145        }
2146        let node = |id: &NormalFormId| self.at(*id);
2147        let nodes = |ids: &[NormalFormId]| ids.iter().map(node).collect::<Vec<_>>();
2148        match &nf.kind {
2149            NormalFormKind::Leaf(LeafKind::Literal(literal)) => SyntaxView::Atom {
2150                atom: NfAtom::Literal(literal, nf.result_type.as_ref()),
2151                starts_with_sign: value_starts_with_sign(&literal.value),
2152            },
2153            NormalFormKind::Leaf(LeafKind::DataPath(path)) => match self.qualifier {
2154                Some(scope) if !scope.data.is_empty() => atom(NfAtom::QualifiedDataPath {
2155                    prefix: &scope.data,
2156                    path,
2157                }),
2158                Some(_) | None => atom(NfAtom::DataPath(path)),
2159            },
2160            NormalFormKind::RowField {
2161                end,
2162                qualifier: Some(segments),
2163                ..
2164            } => atom(NfAtom::QualifiedRow {
2165                qualifier: segments,
2166                end,
2167            }),
2168            NormalFormKind::RowField {
2169                end,
2170                qualifier: None,
2171                ..
2172            } => atom(NfAtom::Row(end)),
2173            NormalFormKind::Leaf(LeafKind::RowValue { .. }) => SyntaxView::ImplicitRowValue,
2174            NormalFormKind::Now => atom(NfAtom::Now),
2175            NormalFormKind::Veto(veto) => atom(NfAtom::Veto(veto)),
2176            NormalFormKind::Comparison(left, op, right) => {
2177                SyntaxView::Comparison(node(left), op, node(right))
2178            }
2179            NormalFormKind::Logical(connective, children) => SyntaxView::Logical {
2180                connective: *connective,
2181                operands: nodes(children),
2182            },
2183            NormalFormKind::Not(operand) => {
2184                let shown = displayed_cell(self.forms, *operand);
2185                match &shown.kind {
2186                    NormalFormKind::ResultIsVeto(inner) if shown.rule_ref.is_none() => {
2187                        SyntaxView::IsNotVeto(node(inner))
2188                    }
2189                    _ => SyntaxView::Not(node(operand)),
2190                }
2191            }
2192            NormalFormKind::ResultIsVeto(operand) => SyntaxView::IsVeto(node(operand)),
2193            NormalFormKind::Sum(_)
2194            | NormalFormKind::Product(_)
2195            | NormalFormKind::Subtract(..)
2196            | NormalFormKind::Divide(..)
2197            | NormalFormKind::Modulo(..) => {
2198                let (first, steps) = arithmetic_chain(self.forms, self.id);
2199                let level = match &nf.kind {
2200                    NormalFormKind::Sum(_) | NormalFormKind::Subtract(..) => {
2201                        &ArithmeticComputation::Add
2202                    }
2203                    _ => &ArithmeticComputation::Multiply,
2204                };
2205                SyntaxView::Chain {
2206                    level,
2207                    operands: std::iter::once(node(&first))
2208                        .chain(steps.iter().map(|(_, operand)| node(operand)))
2209                        .collect(),
2210                    ops: steps.iter().map(|(op, _)| *op).collect(),
2211                }
2212            }
2213            NormalFormKind::Power(left, right) => SyntaxView::Chain {
2214                level: &ArithmeticComputation::Power,
2215                operands: vec![node(left), node(right)],
2216                ops: vec![&ArithmeticComputation::Power],
2217            },
2218            NormalFormKind::Negate(operand) => SyntaxView::Negate(node(operand)),
2219            NormalFormKind::Reciprocal(operand) => SyntaxView::Reciprocal(node(operand)),
2220            NormalFormKind::MathOp(op, operand) => SyntaxView::Prefix(op, node(operand)),
2221            NormalFormKind::StepRounding(mode, operand, step) => SyntaxView::ListCommand {
2222                list: node(operand),
2223                command: CommandView::Step(mode.keyword(), step.as_ref().map(node)),
2224            },
2225            NormalFormKind::RangeBound(bound, operand) => SyntaxView::Prefix(bound, node(operand)),
2226            NormalFormKind::UnitConversion(value, target) => {
2227                SyntaxView::UnitConversion(node(value), target)
2228            }
2229            NormalFormKind::DateRelative(kind, date) => SyntaxView::DateRelative(kind, node(date)),
2230            NormalFormKind::DateCalendar(kind, unit, date) => {
2231                SyntaxView::DateCalendar(kind, unit, node(date))
2232            }
2233            NormalFormKind::RangeLiteral(left, right) => {
2234                SyntaxView::RangeLiteral(node(left), node(right))
2235            }
2236            NormalFormKind::PastFutureRange(kind, offset) => {
2237                SyntaxView::PastFutureRange(kind, node(offset))
2238            }
2239            NormalFormKind::RangeContainment(value, range) => {
2240                SyntaxView::RangeContainment(node(value), node(range))
2241            }
2242            NormalFormKind::Piecewise(arms) => SyntaxView::Piecewise(
2243                arms.iter()
2244                    .map(|(condition, result)| (node(condition), node(result)))
2245                    .collect(),
2246            ),
2247            NormalFormKind::SpecMember {
2248                base, path, name, ..
2249            } => {
2250                let base_cell = cell(self.forms, *base);
2251                let named = base_cell.rule_ref.is_some()
2252                    || matches!(
2253                        base_cell.kind,
2254                        NormalFormKind::Leaf(_) | NormalFormKind::SpecMember { .. }
2255                    );
2256                SyntaxView::Member {
2257                    base: node(base),
2258                    path: NfAtom::SpecMemberField {
2259                        path,
2260                        name: name.as_str(),
2261                    },
2262                    parenthesize_base: !named,
2263                }
2264            }
2265            NormalFormKind::OrderedDispatch { .. } => unreachable!(
2266                "BUG: OrderedDispatch always carries its Piecewise pre-image as origin, \
2267                 so displayed_cell never stops at it"
2268            ),
2269            NormalFormKind::ListCommand { list, op, args, .. } => {
2270                let reduce = |name: &'static str| {
2271                    CommandView::Reduce(name, optional_argument(args, name).map(|id| node(&id)))
2272                };
2273                let command = match op {
2274                    NormalFormListOp::Find => CommandView::Find(nodes(args)),
2275                    NormalFormListOp::First => CommandView::First,
2276                    NormalFormListOp::Last => CommandView::Last,
2277                    NormalFormListOp::Count => CommandView::Count,
2278                    NormalFormListOp::Sum => reduce("sum"),
2279                    NormalFormListOp::Avg => reduce("avg"),
2280                    NormalFormListOp::Product => reduce("product"),
2281                    NormalFormListOp::Min => reduce("min"),
2282                    NormalFormListOp::Max => reduce("max"),
2283                    NormalFormListOp::Predicate { kind, form } => {
2284                        let name = kind.keyword();
2285                        let expr = node(&single_argument(args, name));
2286                        let view = match form {
2287                            ListPredicateForm::Value => PredicateView::Value(expr),
2288                            ListPredicateForm::Instance => PredicateView::Instance(expr),
2289                        };
2290                        CommandView::Predicate(name, view)
2291                    }
2292                    NormalFormListOp::Sort { descending } => CommandView::Sort {
2293                        descending: *descending,
2294                        argument: optional_argument(args, "sort").map(|id| node(&id)),
2295                    },
2296                    NormalFormListOp::Top => CommandView::Top(node(&single_argument(args, "top"))),
2297                    NormalFormListOp::With => {
2298                        CommandView::With(args.iter().map(|id| (None, node(id))).collect())
2299                    }
2300                    NormalFormListOp::WithRow { fields, .. } => {
2301                        assert_eq!(
2302                            fields.len(),
2303                            args.len(),
2304                            "BUG: `with` row cell must carry one value per field"
2305                        );
2306                        CommandView::With(
2307                            fields
2308                                .iter()
2309                                .zip(args)
2310                                .map(|(field, value)| (Some(NfAtom::DataPath(field)), node(value)))
2311                                .collect(),
2312                        )
2313                    }
2314                    NormalFormListOp::Key { fields } => {
2315                        CommandView::Key(fields.iter().map(NfAtom::DataPath).collect())
2316                    }
2317                };
2318                SyntaxView::ListCommand {
2319                    list: node(list),
2320                    command,
2321                }
2322            }
2323        }
2324    }
2325}
2326
2327#[cfg(test)]
2328mod tests {
2329    use super::*;
2330
2331    static EMPTY_ROW_TEMPLATES: BTreeMap<SpecIdentity, Arc<ExecutionPlan>> = BTreeMap::new();
2332    static TEST_SELF_IDENTITY: std::sync::LazyLock<SpecIdentity> =
2333        std::sync::LazyLock::new(|| SpecIdentity {
2334            repository: None,
2335            spec: "test".to_string(),
2336            effective: crate::parsing::ast::EffectiveDate::Origin,
2337            slice: crate::parsing::ast::EffectiveDate::Origin,
2338        });
2339    use crate::computation::arithmetic::SignatureIndex;
2340    use crate::computation::rational::{rational_new, rational_one, rational_zero};
2341    use crate::parsing::arena::{ExprId, ExprTable, ExprTree};
2342    use crate::parsing::ast::{ChainStep, ConversionTypeKind};
2343    use crate::planning::semantics::TypedLiteral;
2344    use crate::planning::semantics::{
2345        ComparisonComputation, DataPath, ExpressionKind, NegationType, SemanticConversionTarget,
2346        ValueKind,
2347    };
2348    use crate::planning::unit_index::UnitIndex;
2349    use std::rc::Rc;
2350
2351    fn interner_forms(interner: &NormalFormInterner) -> &[NormalForm] {
2352        &interner.forms
2353    }
2354
2355    fn empty_named_types() -> &'static IndexMap<String, Arc<LemmaType>> {
2356        use std::sync::OnceLock;
2357        static EMPTY: OnceLock<IndexMap<String, Arc<LemmaType>>> = OnceLock::new();
2358        EMPTY.get_or_init(IndexMap::new)
2359    }
2360
2361    fn empty_measure_scope<'a>(
2362        unit_index: &'a UnitIndex,
2363        signature_index: &'a SignatureIndex,
2364    ) -> MeasureScope<'a> {
2365        MeasureScope {
2366            unit_index,
2367            signature_index,
2368            named_types: empty_named_types(),
2369        }
2370    }
2371
2372    /// Typed data map for algebraic normalize unit tests: mirrors a post-validation
2373    /// plan so [`Cells::type_of`] never stamps undetermined.
2374    fn algebraic_scope() -> IndexMap<DataPath, DataDefinition> {
2375        use crate::parsing::source::{Source as ParseSource, SourceType};
2376        use crate::Span;
2377        let source = ParseSource::new(
2378            SourceType::Volatile,
2379            Span {
2380                start: 0,
2381                end: 0,
2382                line: 1,
2383                col: 1,
2384            },
2385        );
2386        let mut data = IndexMap::new();
2387        for (name, resolved_type) in [
2388            ("x", primitive_number_arc().clone()),
2389            ("y", primitive_number_arc().clone()),
2390            ("flag", primitive_boolean_arc().clone()),
2391            ("flag2", primitive_boolean_arc().clone()),
2392        ] {
2393            data.insert(
2394                DataPath::new(vec![], name.into()),
2395                DataDefinition::TypeDeclaration {
2396                    resolved_type,
2397                    declared_suggestion: None,
2398                    declared_value: None,
2399                    source: source.clone(),
2400                },
2401            );
2402        }
2403        data
2404    }
2405
2406    /// Normalize through the production pipeline with typed algebraic data in scope.
2407    fn normalize_expression(expr: &Ex) -> Result<Expression, Error> {
2408        let data = algebraic_scope();
2409        normalize_expression_with_data(expr, &data).map(|(expr, _)| expr)
2410    }
2411
2412    /// Normalize with a resolved data map in scope, returning the normalized
2413    /// expression alongside the interner so tests can inspect the shipped shape.
2414    fn normalize_expression_with_data(
2415        expr: &Ex,
2416        data: &IndexMap<DataPath, DataDefinition>,
2417    ) -> Result<(Expression, NormalFormInterner), Error> {
2418        let tree = expr.tree();
2419        let source = tree.root_source().cloned();
2420        let mut interner = NormalFormInterner::new();
2421        let root = lower_with_data(&tree, &mut interner, data);
2422        let unit_index = UnitIndex::new();
2423        let signature_index = SignatureIndex::new();
2424        let measure_scope = empty_measure_scope(&unit_index, &signature_index);
2425        let nf = rewrite::normalize(
2426            root,
2427            Cells::new(&mut interner, measure_scope),
2428            source.clone(),
2429        )?;
2430        let expression = to_expression(interner_forms(&interner), nf, source);
2431        Ok((expression, interner))
2432    }
2433
2434    fn to_normal_form_empty(expr: &Ex, interner: &mut NormalFormInterner) -> NormalFormId {
2435        let data = algebraic_scope();
2436        to_normal_form_with_data(expr, interner, &data)
2437    }
2438
2439    fn to_normal_form_with_data(
2440        expr: &Ex,
2441        interner: &mut NormalFormInterner,
2442        data: &IndexMap<DataPath, DataDefinition>,
2443    ) -> NormalFormId {
2444        lower_with_data(&expr.tree(), interner, data)
2445    }
2446
2447    fn lower_with_data(
2448        expr: &Expression,
2449        interner: &mut NormalFormInterner,
2450        data: &IndexMap<DataPath, DataDefinition>,
2451    ) -> NormalFormId {
2452        let completed_rules = HashMap::new();
2453        let rule_types = HashMap::new();
2454        let lower = LowerCtx {
2455            completed_rules: &completed_rules,
2456            rule_types: &rule_types,
2457            data,
2458            row_templates: &EMPTY_ROW_TEMPLATES,
2459            self_identity: &TEST_SELF_IDENTITY,
2460            rule_order: &[],
2461        };
2462        let unit_index = UnitIndex::new();
2463        let signature_index = SignatureIndex::new();
2464        let mut cells = Cells::new(interner, empty_measure_scope(&unit_index, &signature_index));
2465        to_normal_form(expr, &mut cells, &lower)
2466    }
2467
2468    /// Lowers normal forms into one expression table; every node carries `source`.
2469    struct Lowering<'f> {
2470        forms: &'f [NormalForm],
2471        source: Option<Source>,
2472        table: ExprTable<ExpressionKind>,
2473    }
2474
2475    fn to_expression(forms: &[NormalForm], id: NormalFormId, source: Option<Source>) -> Expression {
2476        let mut lowering = Lowering {
2477            forms,
2478            source,
2479            table: ExprTable::default(),
2480        };
2481        let root = lowering.child(id);
2482        ExprTree::new(lowering.table, root)
2483    }
2484
2485    impl Lowering<'_> {
2486        fn child(&mut self, id: NormalFormId) -> ExprId {
2487            let kind = self.kind(id);
2488            self.table.push(kind, self.source.clone())
2489        }
2490
2491        fn kind(&mut self, id: NormalFormId) -> ExpressionKind {
2492            let forms = self.forms;
2493            let source = self.source.clone();
2494            let nf = cell(forms, id);
2495            if let Some(path) = &nf.rule_ref {
2496                return ExpressionKind::RulePath(path.clone());
2497            }
2498            match &nf.kind {
2499                NormalFormKind::Leaf(LeafKind::Literal(lit)) => {
2500                    ExpressionKind::Literal(Box::new(TypedLiteral {
2501                        value: lit.value.clone(),
2502                        lemma_type: Arc::clone(&nf.result_type),
2503                    }))
2504                }
2505                NormalFormKind::Leaf(LeafKind::DataPath(p)) => ExpressionKind::DataPath(p.clone()),
2506                NormalFormKind::Sum(terms) => self.sum_kind(terms),
2507                NormalFormKind::Product(terms) => self.product_kind(terms),
2508                NormalFormKind::Subtract(a, b) => {
2509                    self.binary_kind(*a, ArithmeticComputation::Subtract, *b)
2510                }
2511                NormalFormKind::Divide(a, b) => {
2512                    self.binary_kind(*a, ArithmeticComputation::Divide, *b)
2513                }
2514                NormalFormKind::Power(base, exp) => {
2515                    self.binary_kind(*base, ArithmeticComputation::Power, *exp)
2516                }
2517                NormalFormKind::Modulo(a, b) => {
2518                    self.binary_kind(*a, ArithmeticComputation::Modulo, *b)
2519                }
2520                NormalFormKind::Negate(x) => {
2521                    let zero = self.table.push(
2522                        ExpressionKind::Literal(Box::new(TypedLiteral::number(rational_zero()))),
2523                        source.clone(),
2524                    );
2525                    let operand = self.child(*x);
2526                    arithmetic_kind(zero, vec![(ArithmeticComputation::Subtract, operand)])
2527                }
2528                NormalFormKind::Reciprocal(x) => {
2529                    let one = self.table.push(
2530                        ExpressionKind::Literal(Box::new(TypedLiteral::number(rational_one()))),
2531                        source.clone(),
2532                    );
2533                    let operand = self.child(*x);
2534                    arithmetic_kind(one, vec![(ArithmeticComputation::Divide, operand)])
2535                }
2536                NormalFormKind::Comparison(a, op, b) => {
2537                    ExpressionKind::Comparison(self.child(*a), op.clone(), self.child(*b))
2538                }
2539                NormalFormKind::Logical(connective, children) => {
2540                    self.logical_kind(*connective, children)
2541                }
2542                NormalFormKind::Not(x) => {
2543                    ExpressionKind::LogicalNegation(self.child(*x), NegationType::Not)
2544                }
2545                NormalFormKind::MathOp(op, x) => {
2546                    ExpressionKind::MathematicalComputation(op.clone(), self.child(*x))
2547                }
2548                NormalFormKind::StepRounding(mode, x, step) => ExpressionKind::StepRounding {
2549                    operand: self.child(*x),
2550                    mode: *mode,
2551                    step: step.map(|step| self.child(step)),
2552                },
2553                NormalFormKind::UnitConversion(x, target) => {
2554                    ExpressionKind::UnitConversion(self.child(*x), target.clone())
2555                }
2556                NormalFormKind::Veto(v) => ExpressionKind::Veto(v.clone()),
2557                NormalFormKind::Now => ExpressionKind::Now,
2558                NormalFormKind::DateRelative(kind, x) => {
2559                    ExpressionKind::DateRelative(*kind, self.child(*x))
2560                }
2561                NormalFormKind::DateCalendar(kind, unit, x) => {
2562                    ExpressionKind::DateCalendar(*kind, *unit, self.child(*x))
2563                }
2564                NormalFormKind::RangeLiteral(a, b) => {
2565                    ExpressionKind::RangeLiteral(self.child(*a), self.child(*b))
2566                }
2567                NormalFormKind::PastFutureRange(kind, x) => {
2568                    ExpressionKind::PastFutureRange(*kind, self.child(*x))
2569                }
2570                NormalFormKind::RangeBound(bound, x) => {
2571                    ExpressionKind::RangeBound(*bound, self.child(*x))
2572                }
2573                NormalFormKind::RangeContainment(a, b) => {
2574                    ExpressionKind::RangeContainment(self.child(*a), self.child(*b))
2575                }
2576                NormalFormKind::ResultIsVeto(operand) => {
2577                    ExpressionKind::ResultIsVeto(self.child(*operand))
2578                }
2579                NormalFormKind::Piecewise(arms) => ExpressionKind::Piecewise(
2580                    arms.iter()
2581                        .map(|(condition, result)| (self.child(*condition), self.child(*result)))
2582                        .collect(),
2583                ),
2584                NormalFormKind::SpecMember {
2585                    base, path, name, ..
2586                } => ExpressionKind::SpecMember {
2587                    base: self.child(*base),
2588                    path: path.clone(),
2589                    name: name.clone(),
2590                },
2591                NormalFormKind::RowField {
2592                    level,
2593                    identity,
2594                    end,
2595                    qualifier,
2596                    ..
2597                } => ExpressionKind::RowField {
2598                    level: *level,
2599                    identity: identity.clone(),
2600                    end: end.clone(),
2601                    qualifier: qualifier.clone(),
2602                },
2603                NormalFormKind::Leaf(LeafKind::RowValue { .. }) => {
2604                    panic!("BUG: normal-form RowValue cannot be rebuilt without its list context")
2605                }
2606                // A dispatch table has no Expression spelling; its pre-image does.
2607                NormalFormKind::OrderedDispatch { .. } => self.kind(
2608                    nf.origin
2609                        .expect("BUG: OrderedDispatch without its Piecewise pre-image"),
2610                ),
2611                NormalFormKind::ListCommand {
2612                    list,
2613                    op,
2614                    args,
2615                    row_level,
2616                } => {
2617                    let list_expr = self.child(*list);
2618                    let arg_exprs: Vec<ExprId> = args.iter().map(|id| self.child(*id)).collect();
2619                    use crate::planning::semantics::{ListOp, ListReduce};
2620                    let planned = match op {
2621                        NormalFormListOp::Find => ListOp::Find { keys: arg_exprs },
2622                        NormalFormListOp::First => ListOp::First,
2623                        NormalFormListOp::Last => ListOp::Last,
2624                        NormalFormListOp::Count => ListOp::Count,
2625                        NormalFormListOp::Sum => ListOp::Reduce {
2626                            kind: ListReduce::Sum,
2627                            argument: arg_exprs.into_iter().next(),
2628                        },
2629                        NormalFormListOp::Avg => ListOp::Reduce {
2630                            kind: ListReduce::Avg,
2631                            argument: arg_exprs.into_iter().next(),
2632                        },
2633                        NormalFormListOp::Product => ListOp::Reduce {
2634                            kind: ListReduce::Product,
2635                            argument: arg_exprs.into_iter().next(),
2636                        },
2637                        NormalFormListOp::Min => ListOp::Reduce {
2638                            kind: ListReduce::Min,
2639                            argument: arg_exprs.into_iter().next(),
2640                        },
2641                        NormalFormListOp::Max => ListOp::Reduce {
2642                            kind: ListReduce::Max,
2643                            argument: arg_exprs.into_iter().next(),
2644                        },
2645                        NormalFormListOp::Predicate { kind, form } => ListOp::Predicate {
2646                            kind: *kind,
2647                            form: *form,
2648                            expr: arg_exprs
2649                                .into_iter()
2650                                .next()
2651                                .expect("BUG: predicate needs a row expression"),
2652                        },
2653                        NormalFormListOp::Sort { descending } => ListOp::Sort {
2654                            descending: *descending,
2655                            argument: arg_exprs.into_iter().next(),
2656                        },
2657                        NormalFormListOp::Top => ListOp::Top {
2658                            n: arg_exprs.into_iter().next().expect("BUG: top needs n"),
2659                        },
2660                        NormalFormListOp::With => ListOp::With { rows: arg_exprs },
2661                        NormalFormListOp::WithRow { identity, fields } => ListOp::WithRow {
2662                            identity: SpecIdentity::clone(identity),
2663                            fields: fields.iter().cloned().zip(arg_exprs).collect(),
2664                        },
2665                        NormalFormListOp::Key { fields } => ListOp::Key {
2666                            fields: fields.clone(),
2667                        },
2668                    };
2669                    ExpressionKind::ListCommand {
2670                        list: list_expr,
2671                        op: planned,
2672                        row_level: *row_level,
2673                    }
2674                }
2675            }
2676        }
2677
2678        fn binary_kind(
2679            &mut self,
2680            left: NormalFormId,
2681            op: ArithmeticComputation,
2682            right: NormalFormId,
2683        ) -> ExpressionKind {
2684            let left = self.child(left);
2685            let right = self.child(right);
2686            arithmetic_kind(left, vec![(op, right)])
2687        }
2688
2689        fn sum_kind(&mut self, terms: &[ArithmeticTerm]) -> ExpressionKind {
2690            match terms {
2691                [] => ExpressionKind::Literal(Box::new(TypedLiteral::number(rational_zero()))),
2692                [one] => self.kind(one.operand),
2693                [first, rest @ ..] => self.terms_kind(
2694                    first.operand,
2695                    rest,
2696                    ArithmeticComputation::Add,
2697                    ArithmeticComputation::Subtract,
2698                ),
2699            }
2700        }
2701
2702        fn product_kind(&mut self, terms: &[ArithmeticTerm]) -> ExpressionKind {
2703            match terms {
2704                [] => ExpressionKind::Literal(Box::new(TypedLiteral::number(rational_one()))),
2705                [one] => self.kind(one.operand),
2706                [first, rest @ ..] => self.terms_kind(
2707                    first.operand,
2708                    rest,
2709                    ArithmeticComputation::Multiply,
2710                    ArithmeticComputation::Divide,
2711                ),
2712            }
2713        }
2714
2715        fn terms_kind(
2716            &mut self,
2717            first: NormalFormId,
2718            rest: &[ArithmeticTerm],
2719            direct: ArithmeticComputation,
2720            inverse: ArithmeticComputation,
2721        ) -> ExpressionKind {
2722            let first = self.child(first);
2723            let steps = rest
2724                .iter()
2725                .map(|term| {
2726                    let op = if term.inverse {
2727                        inverse.clone()
2728                    } else {
2729                        direct.clone()
2730                    };
2731                    (op, self.child(term.operand))
2732                })
2733                .collect();
2734            arithmetic_kind(first, steps)
2735        }
2736
2737        fn logical_kind(
2738            &mut self,
2739            connective: LogicalConnective,
2740            children: &[NormalFormId],
2741        ) -> ExpressionKind {
2742            match children {
2743                [] => unreachable!("BUG: Logical has at least one operand"),
2744                [one] => self.kind(*one),
2745                [first, rest @ ..] => {
2746                    let first = self.child(*first);
2747                    let operands = rest.iter().map(|id| self.child(*id)).collect();
2748                    logical_kind(connective, first, operands)
2749                }
2750            }
2751        }
2752    }
2753
2754    /// Test expressions carry no spans; chain steps require one.
2755    fn step_source() -> Source {
2756        Source::new(
2757            crate::parsing::source::SourceType::Volatile,
2758            crate::Span {
2759                start: 0,
2760                end: 0,
2761                line: 1,
2762                col: 1,
2763            },
2764        )
2765    }
2766
2767    fn arithmetic_kind(
2768        first: ExprId,
2769        steps: Vec<(ArithmeticComputation, ExprId)>,
2770    ) -> ExpressionKind {
2771        ExpressionKind::Arithmetic {
2772            first,
2773            steps: steps
2774                .into_iter()
2775                .map(|(op, operand)| ChainStep {
2776                    op,
2777                    operand,
2778                    source_location: step_source(),
2779                })
2780                .collect(),
2781        }
2782    }
2783
2784    /// `left op right` of a one-step arithmetic chain.
2785    fn binary_arithmetic(
2786        kind: &ExpressionKind,
2787    ) -> Option<(&ExprId, &ArithmeticComputation, &ExprId)> {
2788        match kind {
2789            ExpressionKind::Arithmetic { first, steps } => match steps.as_slice() {
2790                [step] => Some((first, &step.op, &step.operand)),
2791                _ => None,
2792            },
2793            _ => None,
2794        }
2795    }
2796
2797    fn logical_kind(
2798        connective: LogicalConnective,
2799        first: ExprId,
2800        operands: Vec<ExprId>,
2801    ) -> ExpressionKind {
2802        ExpressionKind::Logical {
2803            connective,
2804            first,
2805            steps: operands
2806                .into_iter()
2807                .map(|operand| ChainStep {
2808                    op: (),
2809                    operand,
2810                    source_location: step_source(),
2811                })
2812                .collect(),
2813        }
2814    }
2815
2816    fn num_expr(n: i64) -> Ex {
2817        Ex::leaf(
2818            ExpressionKind::Literal(Box::new(TypedLiteral::number(rational_new(n, 1)))),
2819            None,
2820        )
2821    }
2822
2823    fn bool_expr(b: bool) -> Ex {
2824        Ex::leaf(
2825            ExpressionKind::Literal(Box::new(TypedLiteral::from_bool(b))),
2826            None,
2827        )
2828    }
2829
2830    fn dx() -> Ex {
2831        Ex::leaf(
2832            ExpressionKind::DataPath(DataPath::new(vec![], "x".into())),
2833            None,
2834        )
2835    }
2836
2837    fn dflag() -> Ex {
2838        Ex::leaf(
2839            ExpressionKind::DataPath(DataPath::new(vec![], "flag".into())),
2840            None,
2841        )
2842    }
2843
2844    fn dflag2() -> Ex {
2845        Ex::leaf(
2846            ExpressionKind::DataPath(DataPath::new(vec![], "flag2".into())),
2847            None,
2848        )
2849    }
2850
2851    /// Pushes a test expression's nodes into a table and returns its root.
2852    type PushNodes = dyn Fn(&mut ExprTable<ExpressionKind>) -> ExprId;
2853
2854    /// Test expression; [`Ex::tree`] pushes every node straight into one table.
2855    #[derive(Clone)]
2856    struct Ex(Rc<PushNodes>);
2857
2858    impl Ex {
2859        fn leaf(kind: ExpressionKind, source: Option<Source>) -> Self {
2860            Self(Rc::new(move |table| {
2861                table.push(kind.clone(), source.clone())
2862            }))
2863        }
2864
2865        fn push(&self, table: &mut ExprTable<ExpressionKind>) -> ExprId {
2866            (self.0)(table)
2867        }
2868
2869        fn tree(&self) -> Expression {
2870            let mut table = ExprTable::default();
2871            let root = self.push(&mut table);
2872            ExprTree::new(table, root)
2873        }
2874    }
2875
2876    fn compose_expr(children: &[&Ex], make: impl Fn(&[ExprId]) -> ExpressionKind + 'static) -> Ex {
2877        let children: Vec<Ex> = children.iter().map(|child| (*child).clone()).collect();
2878        Ex(Rc::new(move |table| {
2879            let ids: Vec<ExprId> = children.iter().map(|child| child.push(table)).collect();
2880            table.push(make(&ids), None)
2881        }))
2882    }
2883
2884    /// A rule as planning converts it: `default`, or a `Piecewise` over `default` (condition
2885    /// literal `true`) and each `unless <condition> then <result>` arm.
2886    fn unless_chain(default: Ex, arms: Vec<(Ex, Ex)>) -> Ex {
2887        if arms.is_empty() {
2888            return default;
2889        }
2890        Ex(Rc::new(move |table| {
2891            let default_result = default.push(table);
2892            let default_condition = table.push(
2893                ExpressionKind::Literal(Box::new(TypedLiteral::from_bool(true))),
2894                None,
2895            );
2896            let mut pieces = vec![(default_condition, default_result)];
2897            for (condition, result) in &arms {
2898                let condition = condition.push(table);
2899                let result = result.push(table);
2900                pieces.push((condition, result));
2901            }
2902            table.push(ExpressionKind::Piecewise(pieces), None)
2903        }))
2904    }
2905
2906    fn add_expr(a: Ex, b: Ex) -> Ex {
2907        compose_expr(&[&a, &b], |ids| {
2908            arithmetic_kind(ids[0], vec![(ArithmeticComputation::Add, ids[1])])
2909        })
2910    }
2911
2912    fn mul_expr(a: Ex, b: Ex) -> Ex {
2913        compose_expr(&[&a, &b], |ids| {
2914            arithmetic_kind(ids[0], vec![(ArithmeticComputation::Multiply, ids[1])])
2915        })
2916    }
2917
2918    fn div_expr(a: Ex, b: Ex) -> Ex {
2919        compose_expr(&[&a, &b], |ids| {
2920            arithmetic_kind(ids[0], vec![(ArithmeticComputation::Divide, ids[1])])
2921        })
2922    }
2923
2924    fn pow_expr(a: Ex, b: Ex) -> Ex {
2925        compose_expr(&[&a, &b], |ids| {
2926            arithmetic_kind(ids[0], vec![(ArithmeticComputation::Power, ids[1])])
2927        })
2928    }
2929
2930    fn and_expr(a: Ex, b: Ex) -> Ex {
2931        compose_expr(&[&a, &b], |ids| {
2932            logical_kind(LogicalConnective::And, ids[0], vec![ids[1]])
2933        })
2934    }
2935
2936    fn or_expr(a: Ex, b: Ex) -> Ex {
2937        compose_expr(&[&a, &b], |ids| {
2938            logical_kind(LogicalConnective::Or, ids[0], vec![ids[1]])
2939        })
2940    }
2941
2942    fn not_expr(inner: Ex) -> Ex {
2943        compose_expr(&[&inner], |ids| {
2944            ExpressionKind::LogicalNegation(ids[0], NegationType::Not)
2945        })
2946    }
2947
2948    fn lt_expr(a: Ex, b: Ex) -> Ex {
2949        compose_expr(&[&a, &b], |ids| {
2950            ExpressionKind::Comparison(ids[0], ComparisonComputation::LessThan, ids[1])
2951        })
2952    }
2953
2954    fn sub_expr(a: Ex, b: Ex) -> Ex {
2955        compose_expr(&[&a, &b], |ids| {
2956            arithmetic_kind(ids[0], vec![(ArithmeticComputation::Subtract, ids[1])])
2957        })
2958    }
2959
2960    fn math_expr(op: MathematicalComputation, operand: Ex) -> Ex {
2961        compose_expr(&[&operand], move |ids| {
2962            ExpressionKind::MathematicalComputation(op.clone(), ids[0])
2963        })
2964    }
2965
2966    mod ordered_dispatch_fold {
2967        use super::*;
2968        use crate::parsing::source::{Source as ParseSource, SourceType};
2969        use crate::planning::ordered_dispatch::{region_count, DispatchKey};
2970        use crate::planning::semantics::{
2971            primitive_boolean_arc, primitive_date_arc, primitive_number_arc, primitive_text_arc,
2972            LemmaType, TypeSpecification,
2973        };
2974        use crate::Span;
2975
2976        fn test_source() -> ParseSource {
2977            ParseSource::new(
2978                SourceType::Volatile,
2979                Span {
2980                    start: 0,
2981                    end: 0,
2982                    line: 1,
2983                    col: 1,
2984                },
2985            )
2986        }
2987
2988        fn data_path(name: &str) -> DataPath {
2989            DataPath::new(vec![], name.into())
2990        }
2991
2992        fn declared(name: &str, resolved_type: Arc<LemmaType>) -> (DataPath, DataDefinition) {
2993            (
2994                data_path(name),
2995                DataDefinition::TypeDeclaration {
2996                    resolved_type,
2997                    declared_suggestion: None,
2998                    declared_value: None,
2999                    source: test_source(),
3000                },
3001            )
3002        }
3003
3004        /// `x: number`, `code: text`, `flag: boolean`, `day: date`, `rate: ratio`.
3005        fn scope() -> IndexMap<DataPath, DataDefinition> {
3006            let mut data = IndexMap::new();
3007            for entry in [
3008                declared("x", primitive_number_arc().clone()),
3009                declared("y", primitive_number_arc().clone()),
3010                declared("code", primitive_text_arc().clone()),
3011                declared("flag", primitive_boolean_arc().clone()),
3012                declared("day", primitive_date_arc().clone()),
3013                declared(
3014                    "rate",
3015                    Arc::new(LemmaType::primitive(TypeSpecification::ratio())),
3016                ),
3017            ] {
3018                data.insert(entry.0, entry.1);
3019            }
3020            data
3021        }
3022
3023        fn path_expr(name: &str) -> Ex {
3024            Ex::leaf(ExpressionKind::DataPath(data_path(name)), None)
3025        }
3026
3027        fn text_expr(text: &str) -> Ex {
3028            Ex::leaf(
3029                ExpressionKind::Literal(Box::new(TypedLiteral::text(text.to_string()))),
3030                None,
3031            )
3032        }
3033
3034        fn compare(left: Ex, op: ComparisonComputation, right: Ex) -> Ex {
3035            compose_expr(&[&left, &right], move |ids| {
3036                ExpressionKind::Comparison(ids[0], op.clone(), ids[1])
3037            })
3038        }
3039
3040        /// `default` followed by `unless <condition> then <result>` arms.
3041        fn chain(default: Ex, arms: Vec<(Ex, Ex)>) -> Ex {
3042            unless_chain(default, arms)
3043        }
3044
3045        /// Normalize `expr` against `scope()` and return the root cell.
3046        fn fold(expr: &Ex) -> (NormalFormId, NormalFormInterner) {
3047            let data = scope();
3048            let mut interner = NormalFormInterner::new();
3049            let root = to_normal_form_with_data(expr, &mut interner, &data);
3050            let unit_index = UnitIndex::new();
3051            let signature_index = SignatureIndex::new();
3052            let measure_scope = empty_measure_scope(&unit_index, &signature_index);
3053            let nf = rewrite::normalize(root, Cells::new(&mut interner, measure_scope), None)
3054                .expect("normalize");
3055            (nf, interner)
3056        }
3057
3058        /// Boundaries and the result-per-region table, as literal display strings.
3059        fn table(expr: &Ex) -> (Vec<DispatchKey>, Vec<String>) {
3060            let (nf, interner) = fold(expr);
3061            let NormalFormKind::OrderedDispatch {
3062                boundaries,
3063                regions,
3064                ..
3065            } = &interner.get(nf).kind
3066            else {
3067                panic!("expected OrderedDispatch, got {:?}", interner.get(nf).kind);
3068            };
3069            let rendered = regions
3070                .iter()
3071                .map(|region| explanation_display(interner_forms(&interner), region.cell(), None))
3072                .collect();
3073            (boundaries.to_vec(), rendered)
3074        }
3075
3076        fn assert_declines(expr: &Ex, reason: &str) {
3077            let (nf, interner) = fold(expr);
3078            assert!(
3079                !matches!(
3080                    interner.get(nf).kind,
3081                    NormalFormKind::OrderedDispatch { .. }
3082                ),
3083                "must not fold ({reason}), got {:?}",
3084                interner.get(nf).kind
3085            );
3086        }
3087
3088        #[test]
3089        fn equality_chain_on_text_folds_to_point_regions() {
3090            let expr = chain(
3091                num_expr(0),
3092                vec![
3093                    (
3094                        compare(
3095                            path_expr("code"),
3096                            ComparisonComputation::Is,
3097                            text_expr("NL"),
3098                        ),
3099                        num_expr(1),
3100                    ),
3101                    (
3102                        compare(
3103                            path_expr("code"),
3104                            ComparisonComputation::Is,
3105                            text_expr("BE"),
3106                        ),
3107                        num_expr(2),
3108                    ),
3109                ],
3110            );
3111            let (boundaries, regions) = table(&expr);
3112            assert_eq!(
3113                boundaries,
3114                vec![
3115                    DispatchKey::Text(std::sync::Arc::from("BE")),
3116                    DispatchKey::Text(std::sync::Arc::from("NL"))
3117                ]
3118            );
3119            // Every interval holds the default; only the two points carry results.
3120            assert_eq!(regions, vec!["0", "2", "0", "1", "0"]);
3121        }
3122
3123        #[test]
3124        fn later_arm_wins_when_two_arms_share_a_constant() {
3125            let expr = chain(
3126                num_expr(0),
3127                vec![
3128                    (
3129                        compare(path_expr("x"), ComparisonComputation::Is, num_expr(5)),
3130                        num_expr(1),
3131                    ),
3132                    (
3133                        compare(path_expr("x"), ComparisonComputation::Is, num_expr(5)),
3134                        num_expr(2),
3135                    ),
3136                ],
3137            );
3138            let (boundaries, regions) = table(&expr);
3139            assert_eq!(boundaries.len(), 1, "duplicates collapse to one breakpoint");
3140            assert_eq!(regions, vec!["0", "2", "0"]);
3141        }
3142
3143        #[test]
3144        fn greater_than_and_greater_or_equal_differ_at_the_boundary() {
3145            let strict = chain(
3146                num_expr(0),
3147                vec![(
3148                    compare(
3149                        path_expr("x"),
3150                        ComparisonComputation::GreaterThan,
3151                        num_expr(5),
3152                    ),
3153                    num_expr(1),
3154                )],
3155            );
3156            assert_eq!(table(&strict).1, vec!["0", "0", "1"]);
3157
3158            let inclusive = chain(
3159                num_expr(0),
3160                vec![(
3161                    compare(
3162                        path_expr("x"),
3163                        ComparisonComputation::GreaterThanOrEqual,
3164                        num_expr(5),
3165                    ),
3166                    num_expr(1),
3167                )],
3168            );
3169            assert_eq!(table(&inclusive).1, vec!["0", "1", "1"]);
3170        }
3171
3172        #[test]
3173        fn is_not_claims_every_region_but_its_own_point() {
3174            let expr = chain(
3175                num_expr(0),
3176                vec![(
3177                    compare(path_expr("x"), ComparisonComputation::IsNot, num_expr(5)),
3178                    num_expr(1),
3179                )],
3180            );
3181            assert_eq!(table(&expr).1, vec!["1", "0", "1"]);
3182        }
3183
3184        #[test]
3185        fn overlapping_ordering_arms_resolve_by_arm_order() {
3186            // `x > 5 then 1` is shadowed above 10 by the later `x > 10 then 2`.
3187            let expr = chain(
3188                num_expr(0),
3189                vec![
3190                    (
3191                        compare(
3192                            path_expr("x"),
3193                            ComparisonComputation::GreaterThan,
3194                            num_expr(5),
3195                        ),
3196                        num_expr(1),
3197                    ),
3198                    (
3199                        compare(
3200                            path_expr("x"),
3201                            ComparisonComputation::GreaterThan,
3202                            num_expr(10),
3203                        ),
3204                        num_expr(2),
3205                    ),
3206                ],
3207            );
3208            let (boundaries, regions) = table(&expr);
3209            assert_eq!(boundaries.len(), 2);
3210            assert_eq!(regions.len(), region_count(2));
3211            // below 5 | at 5 | between | at 10 | above 10
3212            assert_eq!(regions, vec!["0", "0", "1", "1", "2"]);
3213        }
3214
3215        #[test]
3216        fn literal_on_the_left_mirrors_the_operator() {
3217            let expr = chain(
3218                num_expr(0),
3219                vec![(
3220                    compare(num_expr(5), ComparisonComputation::LessThan, path_expr("x")),
3221                    num_expr(1),
3222                )],
3223            );
3224            // `5 < x` is `x > 5`: only the region above the boundary.
3225            assert_eq!(table(&expr).1, vec!["0", "0", "1"]);
3226        }
3227
3228        #[test]
3229        fn dates_fold_with_ordering_operators() {
3230            let day = |year: i32| {
3231                Ex::leaf(
3232                    ExpressionKind::Literal(Box::new(TypedLiteral::date(
3233                        crate::planning::semantics::SemanticDateTime {
3234                            year,
3235                            month: 1,
3236                            day: 1,
3237                            hour: 0,
3238                            minute: 0,
3239                            second: 0,
3240                            microsecond: 0,
3241                            timezone: None,
3242                        },
3243                    ))),
3244                    None,
3245                )
3246            };
3247            let expr = chain(
3248                num_expr(0),
3249                vec![(
3250                    compare(
3251                        path_expr("day"),
3252                        ComparisonComputation::GreaterThanOrEqual,
3253                        day(2020),
3254                    ),
3255                    num_expr(1),
3256                )],
3257            );
3258            let (boundaries, regions) = table(&expr);
3259            assert!(matches!(boundaries.as_slice(), [DispatchKey::Date(_)]));
3260            assert_eq!(regions, vec!["0", "1", "1"]);
3261        }
3262
3263        #[test]
3264        fn calendar_failure_literal_is_a_planning_error() {
3265            let invalid_day = Ex::leaf(
3266                ExpressionKind::Literal(Box::new(TypedLiteral::date(
3267                    crate::planning::semantics::SemanticDateTime {
3268                        year: 2020,
3269                        month: 13,
3270                        day: 1,
3271                        hour: 0,
3272                        minute: 0,
3273                        second: 0,
3274                        microsecond: 0,
3275                        timezone: None,
3276                    },
3277                ))),
3278                None,
3279            );
3280            let expr = chain(
3281                num_expr(0),
3282                vec![(
3283                    compare(path_expr("day"), ComparisonComputation::Is, invalid_day),
3284                    num_expr(1),
3285                )],
3286            );
3287            let data = scope();
3288            let mut interner = NormalFormInterner::new();
3289            let root = to_normal_form_with_data(&expr, &mut interner, &data);
3290            let unit_index = UnitIndex::new();
3291            let signature_index = SignatureIndex::new();
3292            let measure_scope = empty_measure_scope(&unit_index, &signature_index);
3293            let err = rewrite::normalize(root, Cells::new(&mut interner, measure_scope), None)
3294                .expect_err(
3295                    "invalid calendar literal must fail planning, not silently stay Piecewise",
3296                );
3297            let message = err.to_string();
3298            assert!(
3299                message.contains("ordered dispatch") && message.contains("Invalid date"),
3300                "unexpected error: {message}"
3301            );
3302        }
3303
3304        #[test]
3305        fn the_pre_image_is_kept_as_the_fold_origin() {
3306            let expr = chain(
3307                num_expr(0),
3308                vec![(
3309                    compare(path_expr("x"), ComparisonComputation::Is, num_expr(5)),
3310                    num_expr(1),
3311                )],
3312            );
3313            let (nf, interner) = fold(&expr);
3314            let origin = interner
3315                .get(nf)
3316                .origin
3317                .expect("dispatch must record its pre-image");
3318            assert!(
3319                matches!(interner.get(origin).kind, NormalFormKind::Piecewise(_)),
3320                "origin must be the Piecewise, got {:?}",
3321                interner.get(origin).kind
3322            );
3323        }
3324
3325        #[test]
3326        fn a_collapsed_arm_keeps_the_whole_origin_chain() {
3327            // The `1 < 0` arm is statically false, so `collapse_piecewise` folds first
3328            // and hands this pass a cell that already carries an origin.
3329            let expr = chain(
3330                num_expr(0),
3331                vec![
3332                    (lt_expr(num_expr(1), num_expr(0)), num_expr(9)),
3333                    (
3334                        compare(path_expr("x"), ComparisonComputation::Is, num_expr(5)),
3335                        num_expr(1),
3336                    ),
3337                ],
3338            );
3339            let (nf, interner) = fold(&expr);
3340            let origin = interner
3341                .get(nf)
3342                .origin
3343                .expect("dispatch must record its pre-image");
3344            assert!(
3345                matches!(interner.get(origin).kind, NormalFormKind::Piecewise(_)),
3346                "origin must be the Piecewise, got {:?}",
3347                interner.get(origin).kind
3348            );
3349            let recorded = interner
3350                .get(origin)
3351                .origin
3352                .expect("collapse origin must survive the second fold");
3353            let NormalFormKind::Piecewise(arms) = &interner.get(recorded).kind else {
3354                panic!("recorded pre-image must be a Piecewise");
3355            };
3356            assert_eq!(arms.len(), 3, "the dropped arm must still be recorded");
3357        }
3358
3359        #[test]
3360        fn text_declines_ordering_operators() {
3361            assert_declines(
3362                &chain(
3363                    num_expr(0),
3364                    vec![(
3365                        compare(
3366                            path_expr("code"),
3367                            ComparisonComputation::GreaterThan,
3368                            text_expr("NL"),
3369                        ),
3370                        num_expr(1),
3371                    )],
3372                ),
3373                "text has no ordering comparison",
3374            );
3375        }
3376
3377        #[test]
3378        fn arms_on_different_scrutinees_decline() {
3379            assert_declines(
3380                &chain(
3381                    num_expr(0),
3382                    vec![
3383                        (
3384                            compare(path_expr("x"), ComparisonComputation::Is, num_expr(1)),
3385                            num_expr(1),
3386                        ),
3387                        (
3388                            compare(path_expr("y"), ComparisonComputation::Is, num_expr(2)),
3389                            num_expr(2),
3390                        ),
3391                    ],
3392                ),
3393                "two scrutinees",
3394            );
3395        }
3396
3397        #[test]
3398        fn equality_or_of_is_comparisons_declines() {
3399            assert_declines(
3400                &chain(
3401                    num_expr(0),
3402                    vec![(
3403                        or_expr(
3404                            compare(path_expr("x"), ComparisonComputation::Is, num_expr(1)),
3405                            compare(path_expr("y"), ComparisonComputation::Is, num_expr(2)),
3406                        ),
3407                        num_expr(1),
3408                    )],
3409                ),
3410                "or of equality comparisons is not an And peel",
3411            );
3412        }
3413
3414        #[test]
3415        fn boolean_scrutinee_declines() {
3416            assert_declines(
3417                &chain(
3418                    num_expr(0),
3419                    vec![(
3420                        compare(
3421                            path_expr("flag"),
3422                            ComparisonComputation::Is,
3423                            bool_expr(true),
3424                        ),
3425                        num_expr(1),
3426                    )],
3427                ),
3428                "boolean has at most two keys",
3429            );
3430        }
3431
3432        #[test]
3433        fn mismatched_key_and_scrutinee_types_decline() {
3434            assert_declines(
3435                &chain(
3436                    num_expr(0),
3437                    vec![(
3438                        compare(path_expr("code"), ComparisonComputation::Is, num_expr(1)),
3439                        num_expr(1),
3440                    )],
3441                ),
3442                "text scrutinee against a number key",
3443            );
3444            assert_declines(
3445                &chain(
3446                    num_expr(0),
3447                    vec![(
3448                        compare(path_expr("rate"), ComparisonComputation::Is, num_expr(1)),
3449                        num_expr(1),
3450                    )],
3451                ),
3452                "ratio scrutinee against a plain number key",
3453            );
3454        }
3455
3456        #[test]
3457        fn a_determined_expression_scrutinee_folds() {
3458            // Stamped result_type on the Sum is Number; that is enough to classify.
3459            let expr = chain(
3460                num_expr(0),
3461                vec![(
3462                    compare(
3463                        add_expr(path_expr("x"), num_expr(1)),
3464                        ComparisonComputation::Is,
3465                        num_expr(5),
3466                    ),
3467                    num_expr(1),
3468                )],
3469            );
3470            let (boundaries, regions) = table(&expr);
3471            assert_eq!(boundaries.len(), 1);
3472            assert_eq!(regions, vec!["0", "1", "0"]);
3473        }
3474
3475        #[test]
3476        fn conjunctive_key_lut_folds_to_nested_dispatch() {
3477            let expr = chain(
3478                num_expr(0),
3479                vec![
3480                    (
3481                        and_expr(
3482                            compare(path_expr("x"), ComparisonComputation::Is, num_expr(2)),
3483                            compare(
3484                                path_expr("y"),
3485                                ComparisonComputation::GreaterThanOrEqual,
3486                                num_expr(1),
3487                            ),
3488                        ),
3489                        num_expr(10),
3490                    ),
3491                    (
3492                        and_expr(
3493                            compare(path_expr("x"), ComparisonComputation::Is, num_expr(2)),
3494                            compare(
3495                                path_expr("y"),
3496                                ComparisonComputation::GreaterThanOrEqual,
3497                                num_expr(5),
3498                            ),
3499                        ),
3500                        num_expr(20),
3501                    ),
3502                    (
3503                        and_expr(
3504                            compare(path_expr("x"), ComparisonComputation::Is, num_expr(3)),
3505                            compare(
3506                                path_expr("y"),
3507                                ComparisonComputation::GreaterThanOrEqual,
3508                                num_expr(1),
3509                            ),
3510                        ),
3511                        num_expr(30),
3512                    ),
3513                ],
3514            );
3515            let (nf, interner) = fold(&expr);
3516            let NormalFormKind::OrderedDispatch {
3517                boundaries,
3518                regions,
3519                ..
3520            } = &interner.get(nf).kind
3521            else {
3522                panic!(
3523                    "expected outer OrderedDispatch, got {:?}",
3524                    interner.get(nf).kind
3525                );
3526            };
3527            assert_eq!(boundaries.len(), 2, "outer keys are the two zone values");
3528            // Point regions are nested dispatches; interval regions keep the default.
3529            let point_bodies: Vec<_> = regions
3530                .iter()
3531                .enumerate()
3532                .filter(|(index, _)| index % 2 == 1)
3533                .map(|(_, region)| &interner.get(region.cell()).kind)
3534                .collect();
3535            assert_eq!(point_bodies.len(), 2);
3536            for kind in &point_bodies {
3537                assert!(
3538                    matches!(kind, NormalFormKind::OrderedDispatch { .. }),
3539                    "point region must be an inner OrderedDispatch, got {kind:?}"
3540                );
3541            }
3542            for (index, region) in regions.iter().enumerate() {
3543                if index % 2 == 0 {
3544                    assert_eq!(
3545                        explanation_display(interner_forms(&interner), region.cell(), None),
3546                        "0",
3547                        "interval region must stay the default"
3548                    );
3549                }
3550            }
3551        }
3552
3553        #[test]
3554        fn conjunctive_key_without_shared_is_scrutinee_declines() {
3555            // Residuals only; no shared Is key across arms.
3556            assert_declines(
3557                &chain(
3558                    num_expr(0),
3559                    vec![
3560                        (
3561                            and_expr(
3562                                compare(
3563                                    path_expr("x"),
3564                                    ComparisonComputation::GreaterThan,
3565                                    num_expr(1),
3566                                ),
3567                                compare(
3568                                    path_expr("y"),
3569                                    ComparisonComputation::GreaterThan,
3570                                    num_expr(1),
3571                                ),
3572                            ),
3573                            num_expr(1),
3574                        ),
3575                        (
3576                            and_expr(
3577                                compare(
3578                                    path_expr("x"),
3579                                    ComparisonComputation::GreaterThan,
3580                                    num_expr(2),
3581                                ),
3582                                compare(
3583                                    path_expr("y"),
3584                                    ComparisonComputation::GreaterThan,
3585                                    num_expr(2),
3586                                ),
3587                            ),
3588                            num_expr(2),
3589                        ),
3590                    ],
3591                ),
3592                "no Is key conjunct shared across arms",
3593            );
3594        }
3595
3596        #[test]
3597        fn an_unknown_data_path_declines() {
3598            assert_declines(
3599                &chain(
3600                    num_expr(0),
3601                    vec![(
3602                        compare(path_expr("absent"), ComparisonComputation::Is, num_expr(5)),
3603                        num_expr(1),
3604                    )],
3605                ),
3606                "the scrutinee has no resolved type in scope",
3607            );
3608        }
3609
3610        #[test]
3611        fn a_non_comparison_condition_declines() {
3612            assert_declines(
3613                &chain(num_expr(0), vec![(path_expr("flag"), num_expr(1))]),
3614                "a bare boolean condition is not a comparison",
3615            );
3616        }
3617
3618        #[test]
3619        fn a_comparison_between_two_data_paths_declines() {
3620            assert_declines(
3621                &chain(
3622                    num_expr(0),
3623                    vec![(
3624                        compare(path_expr("x"), ComparisonComputation::Is, path_expr("y")),
3625                        num_expr(1),
3626                    )],
3627                ),
3628                "neither side is a constant",
3629            );
3630        }
3631
3632        /// Every folded cell must agree with its pre-image for every input, which is
3633        /// the property the whole region model exists to preserve.
3634        #[test]
3635        fn folded_table_agrees_with_the_piecewise_it_replaced() {
3636            let operators = [
3637                ComparisonComputation::Is,
3638                ComparisonComputation::IsNot,
3639                ComparisonComputation::GreaterThan,
3640                ComparisonComputation::GreaterThanOrEqual,
3641                ComparisonComputation::LessThan,
3642                ComparisonComputation::LessThanOrEqual,
3643            ];
3644            // Duplicated constants and out-of-order constants are both covered.
3645            let constants = [5i64, 2, 5, 8];
3646            let mut checked = 0usize;
3647
3648            for first in &operators {
3649                for second in &operators {
3650                    for third in &operators {
3651                        let arm_operators = [first, second, third];
3652                        let arms: Vec<(Ex, Ex)> = arm_operators
3653                            .iter()
3654                            .enumerate()
3655                            .map(|(index, operator)| {
3656                                (
3657                                    compare(
3658                                        path_expr("x"),
3659                                        (*operator).clone(),
3660                                        num_expr(constants[index]),
3661                                    ),
3662                                    num_expr(index as i64 + 1),
3663                                )
3664                            })
3665                            .collect();
3666                        let expr = chain(num_expr(0), arms);
3667                        let (boundaries, regions) = table(&expr);
3668
3669                        // Sample below, at and above every constant, plus far outside.
3670                        for probe in [-100i64, 1, 2, 3, 5, 6, 8, 9, 100] {
3671                            let expected = arm_operators
3672                                .iter()
3673                                .enumerate()
3674                                .rev()
3675                                .find_map(|(index, operator)| {
3676                                    predicate_holds(probe, operator, constants[index])
3677                                        .then_some(index as i64 + 1)
3678                                })
3679                                .unwrap_or(0);
3680                            let region = crate::planning::ordered_dispatch::region_for_value(
3681                                &boundaries,
3682                                &DispatchKey::Rational(rational_new(probe, 1)).as_probe(),
3683                            )
3684                            .expect("integers compare");
3685                            assert_eq!(
3686                                regions[region],
3687                                expected.to_string(),
3688                                "operators {first} / {second} / {third} disagree at x = {probe}"
3689                            );
3690                            checked += 1;
3691                        }
3692                    }
3693                }
3694            }
3695            assert_eq!(checked, 6 * 6 * 6 * 9);
3696        }
3697
3698        fn predicate_holds(value: i64, operator: &ComparisonComputation, constant: i64) -> bool {
3699            match operator {
3700                ComparisonComputation::Is => value == constant,
3701                ComparisonComputation::IsNot => value != constant,
3702                ComparisonComputation::GreaterThan => value > constant,
3703                ComparisonComputation::GreaterThanOrEqual => value >= constant,
3704                ComparisonComputation::LessThan => value < constant,
3705                ComparisonComputation::LessThanOrEqual => value <= constant,
3706            }
3707        }
3708    }
3709
3710    #[test]
3711    fn flatten_associative_sum_nested() {
3712        let inner = add_expr(num_expr(1), num_expr(2));
3713        let expr = add_expr(inner, num_expr(3));
3714        let norm = normalize_expression(&expr).expect("normalize");
3715        assert!(matches!(
3716            norm.root_kind(),
3717            ExpressionKind::Literal(ref l)
3718                if matches!(l.value, crate::planning::semantics::ValueKind::Number(ref n) if n == &rational_new(6, 1))
3719        ));
3720    }
3721
3722    #[test]
3723    fn flatten_associative_product_nested() {
3724        let inner = mul_expr(num_expr(2), num_expr(3));
3725        let expr = mul_expr(inner, num_expr(4));
3726        let norm = normalize_expression(&expr).expect("normalize");
3727        assert!(matches!(
3728            norm.root_kind(),
3729            ExpressionKind::Literal(ref l)
3730                if matches!(l.value, crate::planning::semantics::ValueKind::Number(ref n) if n == &rational_new(24, 1))
3731        ));
3732    }
3733
3734    #[test]
3735    fn and_chain_lowers_to_one_flat_cell() {
3736        let chain = compose_expr(
3737            &[&bool_expr(true), &bool_expr(true), &bool_expr(false)],
3738            |ids| logical_kind(LogicalConnective::And, ids[0], vec![ids[1], ids[2]]),
3739        );
3740        let mut interner = NormalFormInterner::new();
3741        let id = to_normal_form_empty(&chain, &mut interner);
3742        let NormalFormKind::Logical(LogicalConnective::And, children) = &interner.get(id).kind
3743        else {
3744            panic!("expected And(..), got {:?}", interner.get(id).kind);
3745        };
3746        let [first, second, third] = children.as_slice() else {
3747            panic!("expected three flat operands, got {children:?}");
3748        };
3749        for operand in [first, second, third] {
3750            assert!(matches!(
3751                &interner.get(*operand).kind,
3752                NormalFormKind::Leaf(LeafKind::Literal(_))
3753            ));
3754        }
3755    }
3756
3757    #[test]
3758    fn parenthesized_sum_flattens_into_parent() {
3759        let y = Ex::leaf(
3760            ExpressionKind::DataPath(DataPath::new(vec![], "y".into())),
3761            None,
3762        );
3763        for expr in [
3764            add_expr(dx(), add_expr(y.clone(), num_expr(2))),
3765            add_expr(add_expr(dx(), y.clone()), num_expr(2)),
3766        ] {
3767            let norm = normalize_expression(&expr).expect("normalize");
3768            let ExpressionKind::Arithmetic { steps, .. } = norm.root_kind() else {
3769                panic!("expected one sum, got {:?}", norm.root_kind());
3770            };
3771            assert_eq!(steps.len(), 2, "expected three flat terms, got {norm:?}");
3772        }
3773    }
3774
3775    #[test]
3776    fn parenthesized_conjunction_flattens_into_parent() {
3777        let x_below_one = lt_expr(dx(), num_expr(1));
3778        for expr in [
3779            and_expr(dflag(), and_expr(dflag2(), x_below_one.clone())),
3780            and_expr(and_expr(dflag(), dflag2()), x_below_one.clone()),
3781        ] {
3782            let norm = normalize_expression(&expr).expect("normalize");
3783            let ExpressionKind::Logical {
3784                connective: LogicalConnective::And,
3785                steps,
3786                ..
3787            } = norm.root_kind()
3788            else {
3789                panic!("expected one conjunction, got {:?}", norm.root_kind());
3790            };
3791            assert_eq!(steps.len(), 2, "expected three flat operands, got {norm:?}");
3792        }
3793    }
3794
3795    #[test]
3796    fn or_chain_lowers_to_one_flat_cell() {
3797        let chain = compose_expr(
3798            &[&bool_expr(false), &bool_expr(false), &bool_expr(true)],
3799            |ids| logical_kind(LogicalConnective::Or, ids[0], vec![ids[1], ids[2]]),
3800        );
3801        let mut interner = NormalFormInterner::new();
3802        let id = to_normal_form_empty(&chain, &mut interner);
3803        let NormalFormKind::Logical(LogicalConnective::Or, children) = &interner.get(id).kind
3804        else {
3805            panic!("expected Or(..), got {:?}", interner.get(id).kind);
3806        };
3807        let [first, second, third] = children.as_slice() else {
3808            panic!("expected three flat operands, got {children:?}");
3809        };
3810        for operand in [first, second, third] {
3811            assert!(matches!(
3812                &interner.get(*operand).kind,
3813                NormalFormKind::Leaf(LeafKind::Literal(_))
3814            ));
3815        }
3816    }
3817
3818    #[test]
3819    fn parenthesized_disjunction_flattens_into_parent() {
3820        let x_below_one = lt_expr(dx(), num_expr(1));
3821        for expr in [
3822            or_expr(dflag(), or_expr(dflag2(), x_below_one.clone())),
3823            or_expr(or_expr(dflag(), dflag2()), x_below_one.clone()),
3824        ] {
3825            let norm = normalize_expression(&expr).expect("normalize");
3826            let ExpressionKind::Logical {
3827                connective: LogicalConnective::Or,
3828                steps,
3829                ..
3830            } = norm.root_kind()
3831            else {
3832                panic!("expected one disjunction, got {:?}", norm.root_kind());
3833            };
3834            assert_eq!(steps.len(), 2, "expected three flat operands, got {norm:?}");
3835        }
3836    }
3837
3838    #[test]
3839    fn mixed_or_and_does_not_flatten() {
3840        let expr = or_expr(dflag(), and_expr(dflag2(), lt_expr(dx(), num_expr(1))));
3841        let norm = normalize_expression(&expr).expect("normalize");
3842        let ExpressionKind::Logical {
3843            connective: LogicalConnective::Or,
3844            first,
3845            steps,
3846        } = norm.root_kind()
3847        else {
3848            panic!("expected or root, got {:?}", norm.root_kind());
3849        };
3850        assert_eq!(steps.len(), 1);
3851        assert!(matches!(
3852            norm.at(*first).kind(),
3853            ExpressionKind::DataPath(ref p) if p.data == "flag"
3854        ));
3855        assert!(matches!(
3856            norm.at(steps[0].operand).kind(),
3857            ExpressionKind::Logical {
3858                connective: LogicalConnective::And,
3859                ..
3860            }
3861        ));
3862    }
3863
3864    #[test]
3865    fn true_or_data_absorbs_to_true() {
3866        let norm = normalize_expression(&or_expr(bool_expr(true), dflag())).expect("normalize");
3867        assert!(matches!(
3868            norm.root_kind(),
3869            ExpressionKind::Literal(ref literal)
3870                if matches!(literal.value, crate::planning::semantics::ValueKind::Boolean(true))
3871        ));
3872    }
3873
3874    #[test]
3875    fn false_or_data_folds_to_data() {
3876        let norm = normalize_expression(&or_expr(bool_expr(false), dflag())).expect("normalize");
3877        assert!(matches!(
3878            norm.root_kind(),
3879            ExpressionKind::DataPath(ref path) if path.data == "flag"
3880        ));
3881    }
3882
3883    #[test]
3884    fn identity_add_zero() {
3885        let expr = add_expr(dx(), num_expr(0));
3886        let norm = normalize_expression(&expr).expect("normalize");
3887        assert!(matches!(norm.root_kind(), ExpressionKind::DataPath(ref p) if p.data == "x"));
3888    }
3889
3890    #[test]
3891    fn identity_mul_one() {
3892        let expr = mul_expr(dx(), num_expr(1));
3893        let norm = normalize_expression(&expr).expect("normalize");
3894        assert!(matches!(norm.root_kind(), ExpressionKind::DataPath(ref p) if p.data == "x"));
3895    }
3896
3897    #[test]
3898    fn identity_mul_zero_with_data_path_is_not_folded() {
3899        // `x * 0` must stay a runtime multiply: folding it to `0` would erase
3900        // a missing-data veto for `x` and drop `x` from the data manifest.
3901        let expr = mul_expr(dx(), num_expr(0));
3902        let norm = normalize_expression(&expr).expect("normalize");
3903        let Some((left, ArithmeticComputation::Multiply, right)) =
3904            binary_arithmetic(norm.root_kind())
3905        else {
3906            panic!("expected preserved multiply, got {:?}", norm.root_kind());
3907        };
3908        assert!(matches!(norm.at(*left).kind(), ExpressionKind::DataPath(ref p) if p.data == "x"));
3909        assert!(matches!(
3910            norm.at(*right).kind(),
3911            ExpressionKind::Literal(ref l)
3912                if matches!(l.value, crate::planning::semantics::ValueKind::Number(ref n) if n == &rational_new(0, 1))
3913        ));
3914    }
3915
3916    #[test]
3917    fn identity_mul_zero_with_literal_folds() {
3918        // All-literal products still fold: `7 * 0 → 0`.
3919        let expr = mul_expr(num_expr(7), num_expr(0));
3920        let norm = normalize_expression(&expr).expect("normalize");
3921        assert!(matches!(
3922            norm.root_kind(),
3923            ExpressionKind::Literal(ref l)
3924                if matches!(l.value, crate::planning::semantics::ValueKind::Number(ref n) if n == &rational_new(0, 1))
3925        ));
3926    }
3927
3928    #[test]
3929    fn identity_pow_one_and_zero() {
3930        let p1 = normalize_expression(&pow_expr(dx(), num_expr(1))).expect("normalize");
3931        assert!(matches!(p1.root_kind(), ExpressionKind::DataPath(ref p) if p.data == "x"));
3932        // `x ^ 0` must stay a runtime power: folding it to `1` would erase a
3933        // missing-data veto for `x`.
3934        let p0 = normalize_expression(&pow_expr(dx(), num_expr(0))).expect("normalize");
3935        let Some((base, ArithmeticComputation::Power, exp)) = binary_arithmetic(p0.root_kind())
3936        else {
3937            panic!("expected preserved power, got {:?}", p0.root_kind());
3938        };
3939        assert!(matches!(p0.at(*base).kind(), ExpressionKind::DataPath(ref p) if p.data == "x"));
3940        assert!(matches!(
3941            p0.at(*exp).kind(),
3942            ExpressionKind::Literal(ref l)
3943                if matches!(l.value, crate::planning::semantics::ValueKind::Number(ref n) if n == &rational_new(0, 1))
3944        ));
3945        // A total, nonzero literal base still folds: `7 ^ 0 → 1`.
3946        let literal_pow_zero =
3947            normalize_expression(&pow_expr(num_expr(7), num_expr(0))).expect("normalize");
3948        assert!(matches!(
3949            literal_pow_zero.root_kind(),
3950            ExpressionKind::Literal(ref l)
3951                if matches!(l.value, crate::planning::semantics::ValueKind::Number(ref n) if n == &rational_new(1, 1))
3952        ));
3953    }
3954
3955    #[test]
3956    fn double_logical_negation() {
3957        let norm = normalize_expression(&not_expr(not_expr(bool_expr(true)))).expect("normalize");
3958        assert!(matches!(
3959            norm.root_kind(),
3960            ExpressionKind::Literal(ref l) if matches!(l.value, crate::planning::semantics::ValueKind::Boolean(true))
3961        ));
3962    }
3963
3964    #[test]
3965    fn double_numeric_negation() {
3966        let zero = num_expr(0);
3967        let inner = sub_expr(zero.clone(), dx());
3968        let expr = sub_expr(zero, inner);
3969        let norm = normalize_expression(&expr).expect("normalize");
3970        assert!(matches!(norm.root_kind(), ExpressionKind::DataPath(ref p) if p.data == "x"));
3971    }
3972
3973    #[test]
3974    fn double_reciprocal_with_data_path_is_not_collapsed() {
3975        // `1 / (1 / x)` must stay nested: collapsing it to `x` would erase
3976        // the inner division-by-zero veto for `x = 0`.
3977        let one = num_expr(1);
3978        let inner = div_expr(one.clone(), dx());
3979        let expr = div_expr(one, inner);
3980        let norm = normalize_expression(&expr).expect("normalize");
3981        let Some((_, ArithmeticComputation::Divide, outer_denominator)) =
3982            binary_arithmetic(norm.root_kind())
3983        else {
3984            panic!(
3985                "expected preserved outer division, got {:?}",
3986                norm.root_kind()
3987            );
3988        };
3989        let Some((_, ArithmeticComputation::Divide, inner_denominator)) =
3990            binary_arithmetic(norm.at(*outer_denominator).kind())
3991        else {
3992            panic!(
3993                "expected preserved inner division, got {:?}",
3994                norm.at(*outer_denominator).kind()
3995            );
3996        };
3997        assert!(
3998            matches!(norm.at(*outer_denominator).child(*inner_denominator).kind(), ExpressionKind::DataPath(ref p) if p.data == "x")
3999        );
4000    }
4001
4002    #[test]
4003    fn sqrt_squared_numeric_folds_to_exact_rational() {
4004        let sqrt2 = math_expr(MathematicalComputation::Sqrt, num_expr(2));
4005        let expr = pow_expr(sqrt2, num_expr(2));
4006        let norm = normalize_expression(&expr).expect("normalize");
4007        assert!(matches!(
4008            norm.root_kind(),
4009            ExpressionKind::Literal(ref l)
4010                if matches!(l.value, crate::planning::semantics::ValueKind::Number(ref n) if n == &rational_new(2, 1))
4011        ));
4012    }
4013
4014    /// `2^(1/2)` has no exact rational result: constant_fold must not substitute a decimal.
4015    #[test]
4016    fn literal_power_with_irrational_result_stays_power() {
4017        let half_lit = literal_from_folded_rational(rational_new(1, 2));
4018        let half = Ex::leaf(
4019            ExpressionKind::Literal(Box::new(TypedLiteral {
4020                value: half_lit.value,
4021                lemma_type: primitive_number_arc().clone(),
4022            })),
4023            None,
4024        );
4025        let expr = pow_expr(num_expr(2), half);
4026        let norm = normalize_expression(&expr).expect("normalize");
4027        assert!(
4028            matches!(
4029                binary_arithmetic(norm.root_kind()),
4030                Some((_, ArithmeticComputation::Power, _))
4031            ),
4032            "expected symbolic Power, got {:?}",
4033            norm.root_kind()
4034        );
4035    }
4036
4037    #[test]
4038    fn negated_conjunction_preserved_for_data_paths() {
4039        // Non-total conjunctions under negation must not be rewritten:
4040        // AND propagates every conjunct's veto, so algebraic rewrites change
4041        // veto observability.
4042        let expr = not_expr(and_expr(dflag(), dflag2()));
4043        let norm = normalize_expression(&expr).expect("normalize");
4044        let ExpressionKind::LogicalNegation(inner, _) = norm.root_kind() else {
4045            panic!("expected preserved negation, got {:?}", norm.root_kind());
4046        };
4047        assert!(
4048            matches!(
4049                norm.at(*inner).kind(),
4050                ExpressionKind::Logical {
4051                    connective: LogicalConnective::And,
4052                    ..
4053                }
4054            ),
4055            "expected preserved conjunction under the negation, got {:?}",
4056            norm.at(*inner).kind()
4057        );
4058    }
4059
4060    #[test]
4061    fn power_law_nested_power() {
4062        let expr = pow_expr(pow_expr(dx(), num_expr(2)), num_expr(3));
4063        let norm = normalize_expression(&expr).expect("normalize");
4064        assert!(matches!(
4065            binary_arithmetic(norm.root_kind()),
4066            Some((_, ArithmeticComputation::Power, _))
4067        ));
4068        let Some((base, ArithmeticComputation::Power, exp)) = binary_arithmetic(norm.root_kind())
4069        else {
4070            unreachable!();
4071        };
4072        assert!(matches!(
4073            norm.at(*base).kind(),
4074            ExpressionKind::DataPath(ref p) if p.data == "x"
4075        ));
4076        assert!(matches!(
4077            norm.at(*exp).kind(),
4078            ExpressionKind::Literal(ref l)
4079                if matches!(l.value, crate::planning::semantics::ValueKind::Number(ref n) if n == &rational_new(6, 1))
4080        ));
4081    }
4082
4083    #[test]
4084    fn power_law_like_base_product() {
4085        let expr = mul_expr(pow_expr(dx(), num_expr(2)), pow_expr(dx(), num_expr(3)));
4086        let norm = normalize_expression(&expr).expect("normalize");
4087        let Some((base, ArithmeticComputation::Power, exp)) = binary_arithmetic(norm.root_kind())
4088        else {
4089            panic!("expected single power, got {:?}", norm.root_kind());
4090        };
4091        assert!(matches!(norm.at(*base).kind(), ExpressionKind::DataPath(ref p) if p.data == "x"));
4092        assert!(matches!(
4093            norm.at(*exp).kind(),
4094            ExpressionKind::Literal(ref l)
4095                if matches!(l.value, crate::planning::semantics::ValueKind::Number(ref n) if n == &rational_new(5, 1))
4096        ));
4097    }
4098
4099    #[test]
4100    fn negated_comparison_not_less_than() {
4101        let cmp = lt_expr(dx(), num_expr(0));
4102        let norm = normalize_expression(&not_expr(cmp)).expect("normalize");
4103        let ExpressionKind::Comparison(_, op, _) = norm.root_kind() else {
4104            panic!("expected Comparison, got {:?}", norm.root_kind());
4105        };
4106        assert_eq!(*op, ComparisonComputation::GreaterThanOrEqual);
4107    }
4108
4109    #[test]
4110    fn logical_short_circuit_and_false_with_data_path_folds() {
4111        // A `false` operand decides `and` whatever the other operands are, so
4112        // `false and flag` folds to `false`.
4113        let expr = and_expr(bool_expr(false), dflag());
4114        let norm = normalize_expression(&expr).expect("normalize");
4115        assert!(matches!(
4116            norm.root_kind(),
4117            ExpressionKind::Literal(ref l) if matches!(l.value, crate::planning::semantics::ValueKind::Boolean(false))
4118        ));
4119    }
4120
4121    #[test]
4122    fn logical_short_circuit_and_false_all_literal_folds() {
4123        let expr = and_expr(bool_expr(false), bool_expr(true));
4124        let norm = normalize_expression(&expr).expect("normalize");
4125        assert!(matches!(
4126            norm.root_kind(),
4127            ExpressionKind::Literal(ref l) if matches!(l.value, crate::planning::semantics::ValueKind::Boolean(false))
4128        ));
4129    }
4130
4131    #[test]
4132    fn logical_and_false_on_right_with_data_path_folds() {
4133        let expr = and_expr(dflag(), bool_expr(false));
4134        let norm = normalize_expression(&expr).expect("normalize");
4135        assert!(matches!(
4136            norm.root_kind(),
4137            ExpressionKind::Literal(ref l) if matches!(l.value, crate::planning::semantics::ValueKind::Boolean(false))
4138        ));
4139    }
4140
4141    #[test]
4142    fn logical_idempotency_and_duplicate_paths() {
4143        let a = dflag();
4144        let expr = and_expr(a.clone(), a);
4145        let norm = normalize_expression(&expr).expect("normalize");
4146        assert!(matches!(norm.root_kind(), ExpressionKind::DataPath(ref p) if p.data == "flag"));
4147    }
4148
4149    #[test]
4150    fn unit_conversion_fold_number_to_number() {
4151        let inner = num_expr(42);
4152        let expr = compose_expr(&[&inner], |ids| {
4153            ExpressionKind::UnitConversion(
4154                ids[0],
4155                SemanticConversionTarget::Type(ConversionTypeKind::Number),
4156            )
4157        });
4158        let norm = normalize_expression(&expr).expect("normalize");
4159        assert!(matches!(
4160            norm.root_kind(),
4161            ExpressionKind::Literal(ref l)
4162                if matches!(l.value, crate::planning::semantics::ValueKind::Number(ref n) if n == &rational_new(42, 1))
4163        ));
4164    }
4165
4166    #[test]
4167    fn piecewise_collapse_last_true_unless_keeps_only_that_result() {
4168        let piecewise = unless_chain(num_expr(0), vec![(bool_expr(true), num_expr(42))]);
4169        let norm = normalize_expression(&piecewise).expect("normalize");
4170        assert!(matches!(
4171            norm.root_kind(),
4172            ExpressionKind::Literal(ref l)
4173                if matches!(l.value, ValueKind::Number(ref n) if n == &rational_new(42, 1))
4174        ));
4175    }
4176
4177    #[test]
4178    fn collapsed_unless_false_retains_piecewise_origin() {
4179        let piecewise = unless_chain(num_expr(1), vec![(bool_expr(false), num_expr(2))]).tree();
4180        let mut interner = NormalFormInterner::new();
4181        let completed_rules = HashMap::new();
4182        let rule_types = HashMap::new();
4183        let data = IndexMap::new();
4184        let unit_index = UnitIndex::new();
4185        let signature_index = SignatureIndex::new();
4186        let measure_scope = empty_measure_scope(&unit_index, &signature_index);
4187        let lower = LowerCtx {
4188            completed_rules: &completed_rules,
4189            rule_types: &rule_types,
4190            data: &data,
4191            row_templates: &EMPTY_ROW_TEMPLATES,
4192            self_identity: &TEST_SELF_IDENTITY,
4193            rule_order: &[],
4194        };
4195        let root = to_normal_form(
4196            &piecewise,
4197            &mut Cells::new(&mut interner, measure_scope),
4198            &lower,
4199        );
4200        let nf = rewrite::normalize(root, Cells::new(&mut interner, measure_scope), None)
4201            .expect("normalize");
4202        let cell = interner.get(nf);
4203        assert!(
4204            cell.origin.is_some(),
4205            "collapsed unless must keep piecewise origin, kind={:?}",
4206            cell.kind
4207        );
4208        let origin = cell.origin.expect("origin");
4209        assert!(
4210            matches!(interner.get(origin).kind, NormalFormKind::Piecewise(_)),
4211            "origin must be piecewise, got {:?}",
4212            interner.get(origin).kind
4213        );
4214    }
4215
4216    #[test]
4217    fn piecewise_collapse_drops_arm_with_statically_false_condition() {
4218        let piecewise = unless_chain(
4219            num_expr(7),
4220            vec![(lt_expr(num_expr(1), num_expr(0)), num_expr(99))],
4221        );
4222        let norm = normalize_expression(&piecewise).expect("normalize");
4223        assert!(matches!(
4224            norm.root_kind(),
4225            ExpressionKind::Literal(ref l)
4226                if matches!(l.value, ValueKind::Number(ref n) if n == &rational_new(7, 1))
4227        ));
4228    }
4229
4230    #[test]
4231    fn constant_fold_divide_of_literals_to_number() {
4232        let expr = div_expr(num_expr(5), num_expr(2));
4233        let norm = normalize_expression(&expr).expect("normalize");
4234        assert!(matches!(
4235            norm.root_kind(),
4236            ExpressionKind::Literal(ref l)
4237                if matches!(l.value, ValueKind::Number(ref n) if n == &rational_new(5, 2))
4238        ));
4239    }
4240
4241    #[test]
4242    fn constant_fold_divide_comparison_to_true() {
4243        let expr = lt_expr(div_expr(num_expr(5), num_expr(2)), num_expr(4));
4244        let norm = normalize_expression(&expr).expect("normalize");
4245        assert!(matches!(
4246            norm.root_kind(),
4247            ExpressionKind::Literal(ref l) if matches!(l.value, ValueKind::Boolean(true))
4248        ));
4249    }
4250
4251    #[test]
4252    fn constant_fold_nested_arithmetic_comparison_to_true() {
4253        // (1 + 2) * 3 / 4 < 10
4254        let expr = lt_expr(
4255            div_expr(
4256                mul_expr(add_expr(num_expr(1), num_expr(2)), num_expr(3)),
4257                num_expr(4),
4258            ),
4259            num_expr(10),
4260        );
4261        let norm = normalize_expression(&expr).expect("normalize");
4262        assert!(matches!(
4263            norm.root_kind(),
4264            ExpressionKind::Literal(ref l) if matches!(l.value, ValueKind::Boolean(true))
4265        ));
4266    }
4267
4268    #[test]
4269    fn power_laws_sqrt_squared_is_not_merged_for_data_paths() {
4270        let x = Ex::leaf(
4271            ExpressionKind::DataPath(DataPath::new(vec![], "x".into())),
4272            None,
4273        );
4274        let expr = mul_expr(
4275            math_expr(MathematicalComputation::Sqrt, x.clone()),
4276            math_expr(MathematicalComputation::Sqrt, x),
4277        );
4278        let norm = normalize_expression(&expr).expect("normalize");
4279        let mut interner = NormalFormInterner::new();
4280        let id = lower_with_data(&norm, &mut interner, &algebraic_scope());
4281        assert!(
4282            matches!(&interner.get(id).kind, NormalFormKind::Product(ref children) if children.len() == 2),
4283            "sqrt(x)*sqrt(x) must stay a product of two powers, got {:?}",
4284            interner.get(id).kind
4285        );
4286    }
4287
4288    /// `sqrt_two * sqrt_two` (each factor inlined with `rule_origin = sqrt_two`)
4289    /// folds to `Leaf(2)` and records the full fold chain as provenance:
4290    #[test]
4291    fn exp_log_not_folded_for_data_path() {
4292        // `exp (log x)` must stay nested: folding it to `x` would erase the
4293        // `log` domain veto for `x <= 0`.
4294        let inner = math_expr(MathematicalComputation::Log, dx());
4295        let expr = math_expr(MathematicalComputation::Exp, inner);
4296        let norm = normalize_expression(&expr).expect("normalize");
4297        let ExpressionKind::MathematicalComputation(MathematicalComputation::Exp, inner) =
4298            norm.root_kind()
4299        else {
4300            panic!("expected preserved exp, got {:?}", norm.root_kind());
4301        };
4302        assert!(
4303            matches!(
4304                norm.at(*inner).kind(),
4305                ExpressionKind::MathematicalComputation(MathematicalComputation::Log, _)
4306            ),
4307            "expected preserved log under exp, got {:?}",
4308            norm.at(*inner).kind()
4309        );
4310    }
4311
4312    #[test]
4313
4314    fn constant_fold_add() {
4315        let expr = add_expr(num_expr(2), num_expr(3));
4316        let norm = normalize_expression(&expr).expect("normalize");
4317        assert!(matches!(
4318            norm.root_kind(),
4319            ExpressionKind::Literal(ref l) if matches!(l.value, crate::planning::semantics::ValueKind::Number(ref n) if n == &rational_new(5, 1))
4320        ));
4321    }
4322
4323    /// `i.sub.x` on a `uses` instance is one member read: the `uses` slot leaf, then a
4324    /// row end per hop through the templates, no cell of the dependency in this plan.
4325    #[test]
4326    fn member_read_on_import_lowers_to_row_ends() {
4327        let mut engine = crate::Engine::new();
4328        engine
4329            .load([(
4330                crate::SourceType::Path(Arc::new(std::path::PathBuf::from("member.lemma"))),
4331                r#"
4332spec leaf
4333data x: 3
4334
4335spec mid
4336uses sub: leaf
4337
4338spec outer
4339uses i: mid
4340rule r: i.sub.x
4341"#
4342                .to_string(),
4343            )])
4344            .expect("load member fixture");
4345        let plan = engine
4346            .plans
4347            .get_plans(None, "outer")
4348            .and_then(|plans| plans.values().next())
4349            .expect("outer plan");
4350        let rule = plan
4351            .rules
4352            .get(&RulePath::new(Vec::new(), "r".to_string()))
4353            .expect("rule r");
4354        let NormalFormKind::SpecMember { base, row, .. } = &plan.normal_form(rule.normal_form).kind
4355        else {
4356            panic!(
4357                "`i.sub.x` lowers to a member read, got {:?}",
4358                plan.normal_form(rule.normal_form).kind
4359            );
4360        };
4361        assert!(matches!(
4362            &plan.normal_form(*base).kind,
4363            NormalFormKind::Leaf(LeafKind::DataPath(path)) if path.input_key() == "i"
4364        ));
4365        assert_eq!(
4366            row.ends,
4367            vec![
4368                RowEnd::Data(DataPath::local("sub".to_string())),
4369                RowEnd::Data(DataPath::local("x".to_string())),
4370            ]
4371        );
4372        assert!(plan.data.keys().all(|path| path.segments.is_empty()));
4373    }
4374}