Skip to main content

lemma/planning/
semantics.rs

1//! Resolved semantic types for Lemma
2//!
3//! This module contains all types that represent resolved semantics after planning.
4//! These types are created during the planning phase and used by evaluation, inversion, etc.
5
6// Re-exported parsing types: downstream modules (evaluation, inversion, computation,
7// serialization) import these from `planning::semantics`, never from `parsing` directly.
8use crate::parsing::arena::{ExprId, ExprKind, ExprTree};
9pub use crate::parsing::ast::{
10    ArithmeticComputation, ComparisonComputation, MathematicalComputation, NegationType,
11    RangeBound, RoundingMode, VetoExpression,
12};
13pub use crate::parsing::source::Source;
14
15/// Logical computation operators (defined in semantics, not used by the parser).
16/// Returns the logical negation of a comparison (used by De Morgan / NOT-normal-form rewriting).
17#[must_use]
18pub fn negated_comparison(op: ComparisonComputation) -> ComparisonComputation {
19    match op {
20        ComparisonComputation::LessThan => ComparisonComputation::GreaterThanOrEqual,
21        ComparisonComputation::LessThanOrEqual => ComparisonComputation::GreaterThan,
22        ComparisonComputation::GreaterThan => ComparisonComputation::LessThanOrEqual,
23        ComparisonComputation::GreaterThanOrEqual => ComparisonComputation::LessThan,
24        ComparisonComputation::Is => ComparisonComputation::IsNot,
25        ComparisonComputation::IsNot => ComparisonComputation::Is,
26    }
27}
28
29/// Returns the operator that states the same fact with the operands swapped:
30/// `k < x` and `x > k` hold on exactly the same values.
31#[must_use]
32pub fn mirrored_comparison(op: ComparisonComputation) -> ComparisonComputation {
33    match op {
34        ComparisonComputation::LessThan => ComparisonComputation::GreaterThan,
35        ComparisonComputation::LessThanOrEqual => ComparisonComputation::GreaterThanOrEqual,
36        ComparisonComputation::GreaterThan => ComparisonComputation::LessThan,
37        ComparisonComputation::GreaterThanOrEqual => ComparisonComputation::LessThanOrEqual,
38        ComparisonComputation::Is => ComparisonComputation::Is,
39        ComparisonComputation::IsNot => ComparisonComputation::IsNot,
40    }
41}
42
43// Internal-only parsing imports (used only within this module for value/type resolution).
44use crate::computation::rational::{checked_div, rational_new, RationalInteger};
45use crate::computation::OperationResult;
46use crate::parsing::ast::Constraint;
47use crate::parsing::ast::{
48    BooleanValue, CalendarPeriodUnit, ChainStep, CommandArg, ConversionTypeKind, DateCalendarKind,
49    DateRelativeKind, DateTimeValue, LogicalConnective, PrimitiveKind, TimeValue, TimezoneValue,
50    TypeConstraintCommand,
51};
52use crate::planning::normalize::NormalFormId;
53use crate::planning::unit_index::UnitIndex;
54use crate::Error;
55use indexmap::IndexMap;
56use rust_decimal::Decimal;
57use serde::{Deserialize, Deserializer, Serialize, Serializer};
58use std::collections::{BTreeMap, HashMap};
59use std::fmt;
60use std::hash::Hash;
61use std::str::FromStr;
62use std::sync::{Arc, OnceLock};
63
64// -----------------------------------------------------------------------------
65// Type specification and units (resolved type shape; apply constraints is planning)
66// -----------------------------------------------------------------------------
67
68// Unit tables live in `crate::literals` (no dependency on parsing/ast). Re-exported
69// here so downstream modules importing from `planning::semantics` keep working.
70pub use crate::literals::{
71    BaseMeasureVector, MeasureUnit, MeasureUnits, RatioUnit, RatioUnits, UnitScale,
72};
73
74/// Combine two `BaseMeasureVector`s by adding (for multiply) or subtracting (for divide) exponents.
75/// Entries that reach zero exponent are removed (they cancel out). `None` when a resulting
76/// exponent exceeds [`crate::limits::MAX_UNIT_EXPONENT`] in magnitude.
77pub fn combine_decompositions(
78    left: &BaseMeasureVector,
79    right: &BaseMeasureVector,
80    is_multiply: bool,
81) -> Option<BaseMeasureVector> {
82    let mut result = left.clone();
83    for (dim, &exp) in right {
84        let delta = if is_multiply { exp } else { exp.checked_neg()? };
85        let entry = result.entry(dim.clone()).or_insert(0);
86        *entry = entry.checked_add(delta)?;
87        if entry.unsigned_abs() > crate::limits::MAX_UNIT_EXPONENT.unsigned_abs() {
88            return None;
89        }
90        if *entry == 0 {
91            result.remove(dim);
92        }
93    }
94    Some(result)
95}
96
97/// Scale every exponent in `base` by `exponent`. Zero cancels to an empty vector.
98/// `None` when a product overflows `i32` or exceeds [`crate::limits::MAX_UNIT_EXPONENT`].
99pub fn scale_decomposition(base: &BaseMeasureVector, exponent: i32) -> Option<BaseMeasureVector> {
100    if exponent == 0 {
101        return Some(BaseMeasureVector::new());
102    }
103    let mut result = BaseMeasureVector::new();
104    for (dimension, &power) in base {
105        let scaled = power.checked_mul(exponent)?;
106        if scaled.unsigned_abs() > crate::limits::MAX_UNIT_EXPONENT.unsigned_abs() {
107            return None;
108        }
109        if scaled != 0 {
110            result.insert(dimension.clone(), scaled);
111        }
112    }
113    Some(result)
114}
115
116/// Combine two symbolic unit signatures (sorted-by-unit-name, no-zero-exponent vectors)
117/// under multiplication or division. The result is in canonical form: sorted by unit name
118/// ascending, no zero exponents.
119///
120/// Planning resolves measure products via decompositions; this remains the pinned algebra
121/// for signature-index tests.
122#[cfg(test)]
123pub fn combine_signatures(
124    left: &[(String, i32)],
125    right: &[(String, i32)],
126    is_multiply: bool,
127) -> Vec<(String, i32)> {
128    use std::collections::BTreeMap;
129    let mut accumulator: BTreeMap<String, i32> = BTreeMap::new();
130    for (name, exponent) in left {
131        *accumulator.entry(name.clone()).or_insert(0) += exponent;
132    }
133    for (name, exponent) in right {
134        let delta = if is_multiply { *exponent } else { -*exponent };
135        *accumulator.entry(name.clone()).or_insert(0) += delta;
136    }
137    accumulator
138        .into_iter()
139        .filter(|(_, exponent)| *exponent != 0)
140        .collect()
141}
142
143/// Canonicalize a unit signature: sum duplicate entries by name, drop zero exponents,
144/// sort ascending by unit name. Idempotent.
145/// Format a canonical unit signature into human-readable operator style.
146///
147/// Rules:
148/// - Numerator units (positive exponents) sorted alphabetically, joined by `*`.
149/// - Denominator units (negative exponents) sorted alphabetically, joined by `*`, exponents shown
150///   as positive values.
151/// - Separated by `/`. Empty numerator: `1/<denominator>`. No denominator: numerator only.
152/// - Exponents > 1 suffixed as `^n`.
153///
154/// Examples: `eur/hour`, `kilogram*meter^2/second^2`, `1/meter`.
155pub fn format_signature_operator_style(signature: &[(String, i32)]) -> String {
156    let canonical = canonicalize_signature(signature);
157    let mut numerator: Vec<(String, i32)> = Vec::new();
158    let mut denominator: Vec<(String, i32)> = Vec::new();
159    for (name, exponent) in canonical {
160        if exponent > 0 {
161            numerator.push((name, exponent));
162        } else if exponent < 0 {
163            denominator.push((name, -exponent));
164        }
165    }
166    let render = |terms: &[(String, i32)]| -> String {
167        terms
168            .iter()
169            .map(|(name, exp)| {
170                if *exp == 1 {
171                    name.clone()
172                } else {
173                    format!("{name}^{exp}")
174                }
175            })
176            .collect::<Vec<_>>()
177            .join("*")
178    };
179    match (numerator.is_empty(), denominator.is_empty()) {
180        (true, true) => String::new(),
181        (false, true) => render(&numerator),
182        (true, false) => format!("1/{}", render(&denominator)),
183        (false, false) => format!("{}/{}", render(&numerator), render(&denominator)),
184    }
185}
186
187/// Returns the intra-calendar-dimension factor for `name`, if it is a known calendar unit.
188///
189/// Month is canonical (factor 1). Year = 12.
190/// Keys are **singular** (`"month"`, `"year"`).
191///
192/// Returns `None` for names that are not calendar units.
193pub fn calendar_unit_factor(name: &str) -> Option<crate::computation::rational::RationalInteger> {
194    use crate::computation::rational::rational_one;
195    match name {
196        "month" => Some(rational_one()),
197        "year" => Some(rational_new(12, 1)),
198        _ => None,
199    }
200}
201
202fn reject_negative_width_magnitude(magnitude: &RationalInteger, cmd: &str) -> Result<(), String> {
203    use crate::computation::rational::rational_zero;
204    use std::cmp::Ordering;
205    match magnitude.try_cmp(&rational_zero()) {
206        Ok(Ordering::Less) => Err(format!("{cmd} width must not be negative")),
207        Ok(Ordering::Equal | Ordering::Greater) => Ok(()),
208        Err(failure) => Err(format!("{cmd} width compare failed: {failure}")),
209    }
210}
211
212/// Store a width bound as declared `(magnitude, unit)`. Family and factors are resolved
213/// later against `unit_index` during planning validation.
214fn parse_unresolved_width_bound(
215    args: &[CommandArg],
216    cmd: &str,
217) -> Result<(RationalInteger, String), String> {
218    use crate::computation::rational::decimal_to_rational;
219    let lit = require_literal(args, cmd)?;
220    let (magnitude, unit_name) = match lit {
221        crate::literals::Value::NumberWithUnit(n, unit) => (*n, unit.clone()),
222        other => {
223            return Err(format!(
224                "{cmd} requires a measure literal with a unit, got {}",
225                value_kind_name(other)
226            ));
227        }
228    };
229    let magnitude_rational = decimal_to_rational(magnitude)
230        .map_err(|failure| format!("{cmd} literal failed rational lift: {failure}"))?;
231    reject_negative_width_magnitude(&magnitude_rational, cmd)?;
232    Ok((magnitude_rational, unit_name))
233}
234
235/// Planning consistency for range endpoint and width bound declarations.
236///
237/// `unit_index` resolves date/time width units (duration vs calendar). Pass empty for
238/// callers that only check number/ratio/measure ranges.
239pub(crate) fn check_range_bound_consistency(
240    spec: &TypeSpecification,
241    unit_index: &crate::planning::unit_index::UnitIndex,
242) -> Result<(), String> {
243    use std::cmp::Ordering;
244
245    fn endpoint_order_ok_dates(lo: &DateTimeValue, hi: &DateTimeValue) -> bool {
246        compare_semantic_dates(&date_time_to_semantic(lo), &date_time_to_semantic(hi))
247            != Ordering::Greater
248    }
249    fn endpoint_order_ok_times(lo: &TimeValue, hi: &TimeValue) -> bool {
250        compare_semantic_times(&time_to_semantic(lo), &time_to_semantic(hi)) != Ordering::Greater
251    }
252
253    match spec {
254        TypeSpecification::NumberRange {
255            lower,
256            upper,
257            minimum,
258            maximum,
259            ..
260        }
261        | TypeSpecification::RatioRange {
262            lower,
263            upper,
264            minimum,
265            maximum,
266            ..
267        } => {
268            if let (Some(lo), Some(hi)) = (lower, upper) {
269                if lo
270                    .try_cmp(hi)
271                    .map_err(|failure| format!("range endpoint compare failed: {failure}"))?
272                    == Ordering::Greater
273                {
274                    return Err(format!(
275                        "invalid range: lower {} is greater than upper {}",
276                        lo.display_str(),
277                        hi.display_str()
278                    ));
279                }
280            }
281            if let (Some(min_w), Some(max_w)) = (minimum, maximum) {
282                if min_w
283                    .try_cmp(max_w)
284                    .map_err(|failure| format!("range width compare failed: {failure}"))?
285                    == Ordering::Greater
286                {
287                    return Err(format!(
288                        "invalid range: minimum width {} is greater than maximum width {}",
289                        min_w.display_str(),
290                        max_w.display_str()
291                    ));
292                }
293            }
294            Ok(())
295        }
296        TypeSpecification::MeasureRange {
297            lower,
298            upper,
299            minimum,
300            maximum,
301            units,
302            ..
303        } => {
304            if let (Some(lo), Some(hi)) = (lower, upper) {
305                let lo_c =
306                    measure_declared_bound_to_canonical(&lo.0, &lo.1, units, "range", "lower")?;
307                let hi_c =
308                    measure_declared_bound_to_canonical(&hi.0, &hi.1, units, "range", "upper")?;
309                if lo_c
310                    .try_cmp(&hi_c)
311                    .map_err(|failure| format!("range endpoint compare failed: {failure}"))?
312                    == Ordering::Greater
313                {
314                    return Err(format!(
315                        "invalid range: lower {} {} is greater than upper {} {}",
316                        lo.0.display_str(),
317                        lo.1,
318                        hi.0.display_str(),
319                        hi.1
320                    ));
321                }
322            }
323            if let (Some(min_w), Some(max_w)) = (minimum, maximum) {
324                let min_c = measure_declared_bound_to_canonical(
325                    &min_w.0, &min_w.1, units, "range", "minimum",
326                )?;
327                let max_c = measure_declared_bound_to_canonical(
328                    &max_w.0, &max_w.1, units, "range", "maximum",
329                )?;
330                if min_c
331                    .try_cmp(&max_c)
332                    .map_err(|failure| format!("range width compare failed: {failure}"))?
333                    == Ordering::Greater
334                {
335                    return Err(format!(
336                        "invalid range: minimum width {} {} is greater than maximum width {} {}",
337                        min_w.0.display_str(),
338                        min_w.1,
339                        max_w.0.display_str(),
340                        max_w.1
341                    ));
342                }
343            }
344            Ok(())
345        }
346        TypeSpecification::DateRange {
347            lower,
348            upper,
349            minimum,
350            maximum,
351            ..
352        } => {
353            if let (Some(lo), Some(hi)) = (lower, upper) {
354                if !endpoint_order_ok_dates(lo, hi) {
355                    return Err(format!(
356                        "invalid range: lower {lo} is greater than upper {hi}"
357                    ));
358                }
359            }
360            check_temporal_width_pair_consistency(minimum, maximum, unit_index, true)
361        }
362        TypeSpecification::TimeRange {
363            lower,
364            upper,
365            minimum,
366            maximum,
367            ..
368        } => {
369            if let (Some(lo), Some(hi)) = (lower, upper) {
370                if !endpoint_order_ok_times(lo, hi) {
371                    return Err(format!(
372                        "invalid range: lower {lo} is greater than upper {hi}"
373                    ));
374                }
375            }
376            check_temporal_width_pair_consistency(minimum, maximum, unit_index, false)
377        }
378        _ => Ok(()),
379    }
380}
381
382fn check_temporal_width_pair_consistency(
383    minimum: &Option<(RationalInteger, String)>,
384    maximum: &Option<(RationalInteger, String)>,
385    unit_index: &crate::planning::unit_index::UnitIndex,
386    allow_calendar: bool,
387) -> Result<(), String> {
388    use std::cmp::Ordering;
389    let resolve = |bound: &(RationalInteger, String),
390                   command: &str|
391     -> Result<(RationalInteger, Arc<LemmaType>), String> {
392        let (bare, owner) = unit_index.resolve(bound.1.as_str()).map_err(|err| {
393            format!(
394                "{command} width unit '{}': {err} (add `uses lemma units` or declare the unit)",
395                bound.1
396            )
397        })?;
398        if allow_calendar {
399            if !owner.is_duration_like() && !owner.is_calendar_like() {
400                return Err(format!(
401                    "{command} width unit '{bare}' must be a duration or calendar unit",
402                ));
403            }
404        } else if !owner.is_duration_like() {
405            return Err(format!(
406                "{command} width unit '{bare}' must be a duration unit",
407            ));
408        }
409        let TypeSpecification::Measure { units, .. } = &owner.specifications else {
410            return Err(format!(
411                "{command} width unit '{bare}' must resolve to a measure type",
412            ));
413        };
414        let canonical = measure_declared_bound_to_canonical(
415            &bound.0,
416            &bare,
417            units,
418            owner.name().as_str(),
419            command,
420        )?;
421        Ok((canonical, Arc::clone(&owner)))
422    };
423
424    match (minimum, maximum) {
425        (None, None) => Ok(()),
426        (Some(min_w), None) => {
427            resolve(min_w, "minimum")?;
428            Ok(())
429        }
430        (None, Some(max_w)) => {
431            resolve(max_w, "maximum")?;
432            Ok(())
433        }
434        (Some(min_w), Some(max_w)) => {
435            let (min_c, min_owner) = resolve(min_w, "minimum")?;
436            let (max_c, max_owner) = resolve(max_w, "maximum")?;
437            if min_owner.is_calendar_like() != max_owner.is_calendar_like() {
438                return Err(
439                    "invalid range: minimum and maximum width must not mix calendar and duration units"
440                        .to_string(),
441                );
442            }
443            if min_c
444                .try_cmp(&max_c)
445                .map_err(|failure| format!("range width compare failed: {failure}"))?
446                == Ordering::Greater
447            {
448                return Err(format!(
449                    "invalid range: minimum width {} {} is greater than maximum width {} {}",
450                    min_w.0.display_str(),
451                    min_w.1,
452                    max_w.0.display_str(),
453                    max_w.1
454                ));
455            }
456            Ok(())
457        }
458    }
459}
460
461fn owner_declares_measure_unit(owner: &LemmaType, unit_name: &str) -> bool {
462    owner
463        .measure_unit_names()
464        .is_some_and(|names| names.contains(&unit_name))
465}
466
467/// Compute the numeric factor of a symbolic unit signature relative to canonical bases.
468///
469/// For each `(unit_name, exponent)` in `signature`:
470/// 1. When `owner` declares the unit, use `owner.measure_unit_factor(unit_name)`.
471/// 2. Fall back to `expression_units[unit_name].measure_unit_factor(unit_name)`.
472/// 3. Unknown names panic with `"BUG: signature_factor called with unresolved unit name"`.
473///    Ambiguous multi-owner names panic asking the caller to pass a declaring owner.
474///
475/// Returns the product of `factor^exponent` over all pairs, or `NumericFailure` on overflow.
476pub fn signature_factor(
477    signature: &[(String, i32)],
478    expression_units: &crate::planning::unit_index::UnitIndex,
479    owner: Option<&LemmaType>,
480) -> Result<
481    crate::computation::rational::RationalInteger,
482    crate::computation::rational::NumericFailure,
483> {
484    use crate::computation::rational::{checked_div, checked_mul, rational_one};
485    let mut acc = rational_one();
486    for (name, exponent) in signature {
487        let factor =
488            if let Some(owner) = owner.filter(|owner| owner_declares_measure_unit(owner, name)) {
489                owner.measure_unit_factor(name).clone()
490            } else if let Some(lemma_type) = expression_units.unique_owner(name) {
491                lemma_type.measure_unit_factor(name).clone()
492            } else if !expression_units.owners_for(name).is_empty() {
493                panic!(
494                "BUG: signature_factor called with ambiguous unit name '{}' (pass declaring owner)",
495                name
496            );
497            } else {
498                panic!(
499                    "BUG: signature_factor called with unresolved unit name '{}'",
500                    name
501                );
502            };
503        let mut term = rational_one();
504        let abs_exp = exponent.unsigned_abs();
505        for _ in 0..abs_exp {
506            term = checked_mul(&term, &factor)?;
507        }
508        if *exponent >= 0 {
509            acc = checked_mul(&acc, &term)?;
510        } else {
511            acc = checked_div(&acc, &term)?;
512        }
513    }
514    Ok(acc)
515}
516
517pub fn canonicalize_signature(signature: &[(String, i32)]) -> Vec<(String, i32)> {
518    use std::collections::BTreeMap;
519    let mut accumulator: BTreeMap<String, i32> = BTreeMap::new();
520    for (name, exponent) in signature {
521        let entry = accumulator.entry(name.clone()).or_insert(0);
522        *entry = entry
523            .checked_add(*exponent)
524            .expect("BUG: planning bounds signature unit exponents");
525    }
526    accumulator
527        .into_iter()
528        .filter(|(_, exponent)| *exponent != 0)
529        .collect()
530}
531
532/// Convert a `BaseMeasureVector` decomposition into canonical signature form.
533pub fn base_measure_vector_as_signature(decomposition: &BaseMeasureVector) -> Vec<(String, i32)> {
534    decomposition
535        .iter()
536        .filter(|(_, exponent)| **exponent != 0)
537        .map(|(dimension, exponent)| (dimension.name().to_string(), *exponent))
538        .collect()
539}
540
541/// One base axis of a measure decomposition.
542#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
543pub enum Dimension {
544    Duration,
545    Calendar,
546    Family(TypeFamily),
547}
548
549impl Dimension {
550    /// Bare name: builtin axis or family root type name.
551    #[must_use]
552    pub fn name(&self) -> &str {
553        match self {
554            Dimension::Duration => "duration",
555            Dimension::Calendar => "calendar",
556            Dimension::Family(family) => &family.name,
557        }
558    }
559
560    #[must_use]
561    fn with_families_without_effective(&self) -> Self {
562        match self {
563            Dimension::Duration => Dimension::Duration,
564            Dimension::Calendar => Dimension::Calendar,
565            Dimension::Family(family) => Dimension::Family(family.without_effective()),
566        }
567    }
568}
569
570fn base_measure_vector_without_effective(domain: &BaseMeasureVector) -> BaseMeasureVector {
571    domain
572        .iter()
573        .map(|(dimension, exponent)| (dimension.with_families_without_effective(), *exponent))
574        .collect()
575}
576
577fn measure_units_without_effective(units: &MeasureUnits) -> MeasureUnits {
578    MeasureUnits(
579        units
580            .iter()
581            .map(|unit| MeasureUnit {
582                name: unit.name.clone(),
583                scale: unit.scale.clone(),
584                derived_measure_factors: unit.derived_measure_factors.clone(),
585                decomposition: base_measure_vector_without_effective(&unit.decomposition),
586                minimum: unit.minimum.clone(),
587                maximum: unit.maximum.clone(),
588                suggestion_magnitude: unit.suggestion_magnitude.clone(),
589            })
590            .collect(),
591    )
592}
593
594#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
595pub enum MeasureTrait {
596    Duration,
597    Calendar,
598}
599
600pub fn duration_decomposition() -> BaseMeasureVector {
601    [(Dimension::Duration, 1i32)].into_iter().collect()
602}
603
604pub fn calendar_decomposition() -> BaseMeasureVector {
605    [(Dimension::Calendar, 1i32)].into_iter().collect()
606}
607
608/// Marker `LemmaType` for a Measure value whose signature has not been resolved to
609/// a named measure type. Carries an empty decomposition; runtime signature is
610/// derived via [`LemmaType::measure_runtime_signature`].
611pub fn anonymous_measure_type() -> LemmaType {
612    LemmaType::anonymous_for_decomposition(BaseMeasureVector::new())
613}
614
615/// Return a copy of `signature` with every exponent negated. Used by Number/Measure
616/// reciprocal construction (`1 / Q`).
617pub fn negate_signature(signature: &[(String, i32)]) -> Vec<(String, i32)> {
618    signature.iter().map(|(n, e)| (n.clone(), -*e)).collect()
619}
620
621/// Allowed values of a type, plus at most one rule whose list is added to that set.
622/// Empty values and no rule means the type is not constrained by a set. A spec list
623/// has no values: its set is the rule's list.
624#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
625pub(crate) struct TypeOptions {
626    pub values: Vec<OptionValue>,
627    pub rule: Option<String>,
628}
629
630/// One inline option: canonical value and the written unit, when the literal named one.
631#[derive(Clone, Debug, PartialEq, Eq, Hash)]
632pub(crate) struct OptionValue {
633    pub value: BoundValueKind,
634}
635
636pub(crate) const SPEC_LIST_HAS_NO_OPTIONS: &str =
637    "`-> option` and `-> options` do not apply to a list of spec instances";
638
639/// Dot-separated field key for a spec member read (`path` hops, then `name`).
640pub(crate) fn spec_member_input_key(path: &[String], name: &str) -> String {
641    let mut key = String::new();
642    for segment in path {
643        key.push_str(segment);
644        key.push('.');
645    }
646    key.push_str(name);
647    key
648}
649
650impl TypeOptions {
651    #[must_use]
652    pub fn is_empty(&self) -> bool {
653        self.values.is_empty() && self.rule.is_none()
654    }
655}
656
657#[derive(Clone, Debug, PartialEq, Eq, Hash)]
658pub enum TypeSpecification {
659    Boolean {
660        help: String,
661    },
662    Measure {
663        minimum: Option<(RationalInteger, String)>,
664        maximum: Option<(RationalInteger, String)>,
665        units: MeasureUnits,
666        traits: Vec<MeasureTrait>,
667        /// Common dimensional decomposition vector shared by all units in this measure.
668        /// `None` until the decomposition pass runs. Base measures (no compound unit expression)
669        /// are assigned `Some({measure_name: 1})` by the pass. `Some(empty_map)` means resolved
670        /// to dimensionless (e.g. `kg/kg`).
671        decomposition: Option<BaseMeasureVector>,
672        /// Written unit for this measure value (`100 eur`, `as usd`). Schema types use `None`.
673        unit: Option<String>,
674        help: String,
675    },
676    Number {
677        minimum: Option<RationalInteger>,
678        maximum: Option<RationalInteger>,
679        decimals: Option<u8>,
680        help: String,
681    },
682    NumberRange {
683        lower: Option<RationalInteger>,
684        upper: Option<RationalInteger>,
685        minimum: Option<RationalInteger>,
686        maximum: Option<RationalInteger>,
687        help: String,
688    },
689    Ratio {
690        minimum: Option<RationalInteger>,
691        maximum: Option<RationalInteger>,
692        units: RatioUnits,
693        /// Written unit for this ratio value (`25%`, `as percent`). Schema types use `None`.
694        unit: Option<String>,
695        help: String,
696    },
697    RatioRange {
698        lower: Option<RationalInteger>,
699        upper: Option<RationalInteger>,
700        minimum: Option<RationalInteger>,
701        maximum: Option<RationalInteger>,
702        units: RatioUnits,
703        help: String,
704    },
705    Text {
706        length: Option<usize>,
707        help: String,
708    },
709    Date {
710        minimum: Option<DateTimeValue>,
711        maximum: Option<DateTimeValue>,
712        help: String,
713    },
714    DateRange {
715        lower: Option<DateTimeValue>,
716        upper: Option<DateTimeValue>,
717        minimum: Option<(RationalInteger, String)>,
718        maximum: Option<(RationalInteger, String)>,
719        help: String,
720    },
721    Time {
722        minimum: Option<TimeValue>,
723        maximum: Option<TimeValue>,
724        help: String,
725    },
726    TimeRange {
727        lower: Option<TimeValue>,
728        upper: Option<TimeValue>,
729        minimum: Option<(RationalInteger, String)>,
730        maximum: Option<(RationalInteger, String)>,
731        help: String,
732    },
733    MeasureRange {
734        lower: Option<(RationalInteger, String)>,
735        upper: Option<(RationalInteger, String)>,
736        minimum: Option<(RationalInteger, String)>,
737        maximum: Option<(RationalInteger, String)>,
738        units: MeasureUnits,
739        decomposition: Option<BaseMeasureVector>,
740        help: String,
741    },
742    Veto {
743        message: Option<String>,
744    },
745    /// Sentinel used during type inference when the type could not be determined.
746    /// Propagates through expressions without generating cascading errors.
747    /// Must never appear in a successfully validated graph or execution plan.
748    Undetermined,
749    /// A spec instance. Identity is repository, spec name, and the resolved
750    /// temporal row (`effective`). Appended so discriminants of earlier
751    /// variants stay stable.
752    Spec {
753        spec: SpecIdentity,
754    },
755    /// A list of rows of `element`, keyed by row number or named fields.
756    List {
757        element: Arc<LemmaType>,
758        key: ListKey,
759        help: String,
760    },
761}
762
763/// One field in a list's row key: display name and resolved template data path.
764#[derive(Clone, Debug, PartialEq, Eq, Hash)]
765pub struct KeyField {
766    pub name: String,
767    pub path: DataPath,
768}
769
770/// How a list addresses its rows.
771#[derive(Clone, Debug, PartialEq, Eq, Hash)]
772pub enum ListKey {
773    Numbered,
774    Fields(Vec<KeyField>),
775}
776
777/// One loaded spec version: its repository, name and `effective_from`. Types are declared
778/// per version, whatever slice of it a plan covers.
779#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
780pub(crate) struct SpecVersionKey {
781    pub repository: Option<String>,
782    pub spec: String,
783    pub effective: crate::parsing::ast::EffectiveDate,
784}
785
786impl SpecVersionKey {
787    #[must_use]
788    pub(crate) fn of(
789        repository: &crate::parsing::ast::LemmaRepository,
790        spec: &crate::parsing::ast::LemmaSpec,
791    ) -> Self {
792        Self {
793            repository: repository.name.clone(),
794            spec: spec.name.clone(),
795            effective: spec.effective_from.clone(),
796        }
797    }
798}
799
800/// Resolved spec a value or rule result refers to: one temporal slice of one version.
801///
802/// `effective` is the resolved row's `effective_from`, not the run instant. `slice` is
803/// the start of the slice of that version the plan covers: the greatest of the version's
804/// breakpoints ([`crate::planning::discovery::plan_breakpoints`]) at or before the
805/// instant the spec was resolved at. Inside one slice every unpinned import of the
806/// version resolves to the same version, so one slice is one plan.
807#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
808pub struct SpecIdentity {
809    pub repository: Option<String>,
810    pub spec: String,
811    pub effective: crate::parsing::ast::EffectiveDate,
812    pub slice: crate::parsing::ast::EffectiveDate,
813}
814
815impl SpecIdentity {
816    #[must_use]
817    pub(crate) fn of(
818        repository: &crate::parsing::ast::LemmaRepository,
819        spec: &crate::parsing::ast::LemmaSpec,
820        slice: crate::parsing::ast::EffectiveDate,
821    ) -> Self {
822        assert!(
823            slice >= spec.effective_from,
824            "BUG: slice {slice:?} of spec '{}' starts before its version",
825            spec.name
826        );
827        Self {
828            repository: repository.name.clone(),
829            spec: spec.name.clone(),
830            effective: spec.effective_from.clone(),
831            slice,
832        }
833    }
834}
835
836/// `[<repo> ]<spec>[ <date>][ slice <date>]`: the slice is written when it starts after
837/// the version.
838impl fmt::Display for SpecIdentity {
839    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
840        if let Some(repository) = &self.repository {
841            write!(f, "{repository} ")?;
842        }
843        write!(f, "{}", self.spec)?;
844        if let crate::parsing::ast::EffectiveDate::DateTimeValue(at) = &self.effective {
845            write!(f, " {at}")?;
846        }
847        if self.slice != self.effective {
848            let crate::parsing::ast::EffectiveDate::DateTimeValue(at) = &self.slice else {
849                unreachable!("BUG: a slice after its version's start is a date");
850            };
851            write!(f, " slice {at}")?;
852        }
853        Ok(())
854    }
855}
856
857impl std::fmt::Display for TypeSpecification {
858    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
859        match self {
860            Self::Boolean { .. } => f.write_str("boolean"),
861            Self::Measure { .. } => f.write_str("measure"),
862            Self::MeasureRange { .. } => f.write_str("measure range"),
863            Self::Number { .. } => f.write_str("number"),
864            Self::NumberRange { .. } => f.write_str("number range"),
865            Self::Text { .. } => f.write_str("text"),
866            Self::Date { .. } => f.write_str("date"),
867            Self::DateRange { .. } => f.write_str("date range"),
868            Self::Time { .. } => f.write_str("time"),
869            Self::TimeRange { .. } => f.write_str("time range"),
870            Self::Ratio { .. } => f.write_str("ratio"),
871            Self::RatioRange { .. } => f.write_str("ratio range"),
872            Self::Veto { .. } => f.write_str("veto"),
873            Self::Undetermined => f.write_str("undetermined"),
874            Self::Spec { spec } => write!(f, "{spec}"),
875            Self::List {
876                element,
877                key: ListKey::Numbered,
878                ..
879            } => write!(f, "{} list", element.specifications),
880            Self::List {
881                element,
882                key: ListKey::Fields(fields),
883                ..
884            } => write!(
885                f,
886                "{} list key {}",
887                element.specifications,
888                fields
889                    .iter()
890                    .map(|field| field.name.as_str())
891                    .collect::<Vec<_>>()
892                    .join(", ")
893            ),
894        }
895    }
896}
897
898impl TypeSpecification {
899    /// Returns the help text associated with this type, or an empty string if none.
900    pub fn help(&self) -> &str {
901        match self {
902            Self::Boolean { help, .. }
903            | Self::Measure { help, .. }
904            | Self::Number { help, .. }
905            | Self::NumberRange { help, .. }
906            | Self::Text { help, .. }
907            | Self::Date { help, .. }
908            | Self::DateRange { help, .. }
909            | Self::Time { help, .. }
910            | Self::TimeRange { help, .. }
911            | Self::Ratio { help, .. }
912            | Self::RatioRange { help, .. }
913            | Self::MeasureRange { help, .. } => help.as_str(),
914            Self::Veto { .. } | Self::Undetermined | Self::Spec { .. } => "",
915            Self::List { element, help, .. } => {
916                if help.is_empty() {
917                    element.specifications.help()
918                } else {
919                    help.as_str()
920                }
921            }
922        }
923    }
924
925    /// Primitive `measure range` before units/decomposition are declared on a named type.
926    #[must_use]
927    pub fn is_unresolved_measure_range(&self) -> bool {
928        matches!(
929            self,
930            Self::MeasureRange {
931                units,
932                decomposition: None,
933                ..
934            } if units.0.is_empty()
935        )
936    }
937
938    #[must_use]
939    fn with_families_without_effective(&self) -> Self {
940        match self {
941            Self::Measure {
942                minimum,
943                maximum,
944                units,
945                traits,
946                decomposition,
947                unit,
948                help,
949            } => Self::Measure {
950                minimum: minimum.clone(),
951                maximum: maximum.clone(),
952                units: measure_units_without_effective(units),
953                traits: traits.clone(),
954                decomposition: decomposition
955                    .as_ref()
956                    .map(base_measure_vector_without_effective),
957                unit: unit.clone(),
958                help: help.clone(),
959            },
960            Self::MeasureRange {
961                lower,
962                upper,
963                minimum,
964                maximum,
965                units,
966                decomposition,
967                help,
968            } => Self::MeasureRange {
969                lower: lower.clone(),
970                upper: upper.clone(),
971                minimum: minimum.clone(),
972                maximum: maximum.clone(),
973                units: measure_units_without_effective(units),
974                decomposition: decomposition
975                    .as_ref()
976                    .map(base_measure_vector_without_effective),
977                help: help.clone(),
978            },
979            Self::List { element, key, help } => Self::List {
980                element: Arc::new(element.with_families_without_effective()),
981                key: key.clone(),
982                help: help.clone(),
983            },
984            other => other.clone(),
985        }
986    }
987
988    /// Schema equality that ignores written [`unit`](Self::Measure::unit) /
989    /// [`unit`](Self::Ratio::unit). Used when comparing declared types that may
990    /// carry a value-specific written unit.
991    #[must_use]
992    pub fn equal_ignoring_unit(&self, other: &Self) -> bool {
993        match (self, other) {
994            (
995                Self::Measure {
996                    minimum: a_min,
997                    maximum: a_max,
998                    units: a_units,
999                    traits: a_traits,
1000                    decomposition: a_decomp,
1001                    help: a_help,
1002                    unit: _,
1003                },
1004                Self::Measure {
1005                    minimum: b_min,
1006                    maximum: b_max,
1007                    units: b_units,
1008                    traits: b_traits,
1009                    decomposition: b_decomp,
1010                    help: b_help,
1011                    unit: _,
1012                },
1013            ) => {
1014                a_min == b_min
1015                    && a_max == b_max
1016                    && a_units == b_units
1017                    && a_traits == b_traits
1018                    && a_decomp == b_decomp
1019                    && a_help == b_help
1020            }
1021            (
1022                Self::Ratio {
1023                    minimum: a_min,
1024                    maximum: a_max,
1025                    units: a_units,
1026                    help: a_help,
1027                    unit: _,
1028                },
1029                Self::Ratio {
1030                    minimum: b_min,
1031                    maximum: b_max,
1032                    units: b_units,
1033                    help: b_help,
1034                    unit: _,
1035                },
1036            ) => a_min == b_min && a_max == b_max && a_units == b_units && a_help == b_help,
1037            _ => self == other,
1038        }
1039    }
1040}
1041
1042/// Extract a typed [`Value`] from the first `CommandArg`, requiring `Literal` shape.
1043///
1044/// `Label` args carry identifiers (unit names, option keywords) and never satisfy a
1045/// command position that wants a literal value. Returning a typed `Value` keeps the
1046/// caller's match exhaustive over [`Value`] variants — no string coercion path.
1047fn require_literal<'a>(
1048    args: &'a [CommandArg],
1049    cmd: &str,
1050) -> Result<&'a crate::literals::Value, String> {
1051    if args.len() > 1 {
1052        return Err(format!("{cmd} takes exactly one value"));
1053    }
1054    let arg = args
1055        .first()
1056        .ok_or_else(|| format!("{} requires an argument", cmd))?;
1057    match arg {
1058        CommandArg::Literal(v) => Ok(v),
1059        CommandArg::Label(name) => Err(format!(
1060            "{} requires a literal value, got identifier '{}'",
1061            cmd, name
1062        )),
1063        CommandArg::UnitExpr(_) => Err(format!(
1064            "{} requires a literal value, got a unit expression (only valid for 'unit' command)",
1065            cmd
1066        )),
1067    }
1068}
1069
1070fn apply_type_help_command(help: &mut String, args: &[CommandArg]) -> Result<(), String> {
1071    match require_literal(args, "help")? {
1072        crate::literals::Value::Text(s) => {
1073            *help = s.clone();
1074            Ok(())
1075        }
1076        other => Err(format!(
1077            "help requires a text literal (quoted string), got {}",
1078            value_kind_name(other)
1079        )),
1080    }
1081}
1082
1083fn format_measure_units_list(units: &MeasureUnits) -> String {
1084    units
1085        .iter()
1086        .map(|u| u.name.as_str())
1087        .collect::<Vec<_>>()
1088        .join(", ")
1089}
1090
1091/// What kind of value `-> suggest` expects when rejecting a calendar literal.
1092#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1093pub(crate) enum SuggestionExpectation {
1094    MeasureUnits,
1095    Text,
1096    Number,
1097    Boolean,
1098    Date,
1099    Time,
1100    Ratio,
1101    NumberRange,
1102    DateRange,
1103    TimeRange,
1104    MeasureRange,
1105    RatioRange,
1106}
1107
1108pub(crate) fn suggestion_value_mismatch_error(
1109    calendar_unit: &str,
1110    type_name: &str,
1111    expectation: SuggestionExpectation,
1112    measure_units: Option<&MeasureUnits>,
1113) -> String {
1114    let unit_label = calendar_unit;
1115    let first = format!("Unit '{unit_label}' is for calendar data.");
1116    match expectation {
1117        SuggestionExpectation::MeasureUnits => {
1118            let list = measure_units
1119                .map(format_measure_units_list)
1120                .unwrap_or_default();
1121            format!("{first} Valid '{type_name}' units are: {list}.")
1122        }
1123        SuggestionExpectation::Text => format!(
1124            "{first} Please provide a text value in double quotes, for example `-> suggest \"my default value\"`."
1125        ),
1126        SuggestionExpectation::Number => format!(
1127            "{first} Please provide a number, for example `-> suggest 42`."
1128        ),
1129        SuggestionExpectation::Boolean => format!(
1130            "{first} Please provide true or false, for example `-> suggest true`."
1131        ),
1132        SuggestionExpectation::Date => format!(
1133            "{first} Please provide a date, for example `-> suggest 2024-06-15`."
1134        ),
1135        SuggestionExpectation::Time => format!(
1136            "{first} Please provide a time, for example `-> suggest 09:00:00`."
1137        ),
1138        SuggestionExpectation::Ratio | SuggestionExpectation::RatioRange => format!(
1139            "{first} Please provide a ratio, for example `-> suggest 25%`."
1140        ),
1141        SuggestionExpectation::NumberRange => format!(
1142            "{first} Please provide a number range, for example `-> suggest 10...100`."
1143        ),
1144        SuggestionExpectation::DateRange => format!(
1145            "{first} Please provide a date range, for example `-> suggest 2024-01-01...2024-12-31`."
1146        ),
1147        SuggestionExpectation::TimeRange => format!(
1148            "{first} Please provide a time range, for example `-> suggest 09:00...17:00`."
1149        ),
1150        SuggestionExpectation::MeasureRange => format!(
1151            "{first} Please provide a range with units valid for '{type_name}', for example `-> suggest 30 kilogram...35 kilogram`."
1152        ),
1153    }
1154}
1155
1156fn measure_suggestion_wrong_shape_error(type_name: &str, traits: &[MeasureTrait]) -> String {
1157    let example = if traits.contains(&MeasureTrait::Duration) {
1158        "4 week"
1159    } else if traits.contains(&MeasureTrait::Calendar) {
1160        "3 month"
1161    } else {
1162        "30 kilogram"
1163    };
1164    format!(
1165        "Please provide a value with a unit valid for '{type_name}', for example `-> suggest {example}`."
1166    )
1167}
1168
1169/// Names a data command reports in its errors: the type the command applies to,
1170/// and the data being declared.
1171#[derive(Clone, Copy, Debug)]
1172pub struct ConstraintNames<'a> {
1173    pub type_name: &'a str,
1174    pub data_name: &'a str,
1175}
1176
1177fn decimals_depend_on_the_unit_error(
1178    kind: &str,
1179    names: ConstraintNames<'_>,
1180    args: &[CommandArg],
1181    first_unit: Option<&str>,
1182) -> Result<String, String> {
1183    let ConstraintNames {
1184        type_name,
1185        data_name,
1186    } = names;
1187    let places = decimal_to_u8(require_decimal_literal(args, "decimals")?, "decimals")?;
1188    let step = match places {
1189        0 => "1".to_string(),
1190        _ => format!("0.{}1", "0".repeat(usize::from(places) - 1)),
1191    };
1192    let advice = match first_unit {
1193        Some(unit) => {
1194            format!("Round in a rule instead, for example '{data_name} -> round {step} {unit}'.")
1195        }
1196        None => format!(
1197            "Round in a rule instead, for example '{data_name} -> round' followed by a step of {step} in one of the type's units."
1198        ),
1199    };
1200    Ok(format!("'decimals' is not valid on {kind} type '{type_name}': precision depends on the unit. {advice}"))
1201}
1202
1203fn reject_calendar_for_suggestion(
1204    value: &crate::literals::Value,
1205    type_name: &str,
1206    expectation: SuggestionExpectation,
1207    measure_units: Option<&MeasureUnits>,
1208) -> Result<(), String> {
1209    if let crate::literals::Value::NumberWithUnit(_, unit) = value {
1210        if calendar_unit_factor(unit).is_some() {
1211            return Err(suggestion_value_mismatch_error(
1212                unit,
1213                type_name,
1214                expectation,
1215                measure_units,
1216            ));
1217        }
1218    }
1219    Ok(())
1220}
1221
1222/// Human-readable name for a [`Value`] variant — used in mismatch error messages.
1223fn value_kind_name(v: &crate::literals::Value) -> &'static str {
1224    use crate::literals::Value;
1225    match v {
1226        Value::Number(_) => "number",
1227        Value::NumberWithUnit(_, _) => "number_with_unit",
1228        Value::Text(_) => "text",
1229        Value::Date(_) => "date",
1230        Value::Time(_) => "time",
1231        Value::Boolean(_) => "boolean",
1232        Value::Range(_, _) => "range",
1233    }
1234}
1235
1236fn require_suggestion_range_endpoints<'a>(
1237    args: &'a [CommandArg],
1238    type_name: &str,
1239    expectation: SuggestionExpectation,
1240    measure_units: Option<&MeasureUnits>,
1241) -> Result<(&'a crate::literals::Value, &'a crate::literals::Value), String> {
1242    match require_literal(args, "suggest")? {
1243        crate::literals::Value::NumberWithUnit(_, unit)
1244            if calendar_unit_factor(unit).is_some() =>
1245        {
1246            Err(suggestion_value_mismatch_error(
1247                unit,
1248                type_name,
1249                expectation,
1250                measure_units,
1251            ))
1252        }
1253        crate::literals::Value::Range(left, right) => Ok((left.as_ref(), right.as_ref())),
1254        _ => Err(match expectation {
1255            SuggestionExpectation::NumberRange => {
1256                "Please provide a number range, for example `-> suggest 10...100`.".to_string()
1257            }
1258            SuggestionExpectation::DateRange => {
1259                "Please provide a date range, for example `-> suggest 2024-01-01...2024-12-31`."
1260                    .to_string()
1261            }
1262            SuggestionExpectation::RatioRange => {
1263                "Please provide a ratio range, for example `-> suggest 10%...50%`.".to_string()
1264            }
1265            SuggestionExpectation::MeasureRange => format!(
1266                "Please provide a range with units valid for '{type_name}', for example `-> suggest 30 kilogram...35 kilogram`."
1267            ),
1268            _ => unreachable!("BUG: require_suggestion_range_endpoints called with non-range expectation"),
1269        }),
1270    }
1271}
1272
1273fn lift_parser_decimal(decimal: rust_decimal::Decimal) -> Result<RationalInteger, String> {
1274    crate::computation::rational::decimal_to_rational(decimal)
1275        .map_err(|failure| format!("literal failed rational lift: {failure}"))
1276}
1277
1278/// Element spec for a range type, used for parsing endpoints and lifting literal endpoints.
1279pub fn range_element_type_specification(
1280    range_spec: &TypeSpecification,
1281) -> Option<TypeSpecification> {
1282    range_spec.element_from_range()
1283}
1284
1285fn range_endpoints_compatible(left: &LemmaType, right: &LemmaType) -> bool {
1286    match (&left.specifications, &right.specifications) {
1287        (TypeSpecification::Date { .. }, TypeSpecification::Date { .. }) => true,
1288        (TypeSpecification::Time { .. }, TypeSpecification::Time { .. }) => true,
1289        (TypeSpecification::Number { .. }, TypeSpecification::Number { .. }) => true,
1290        (TypeSpecification::Measure { .. }, TypeSpecification::Measure { .. }) => {
1291            left.same_measure_family(right)
1292        }
1293        (TypeSpecification::Ratio { .. }, TypeSpecification::Ratio { .. }) => true,
1294        _ => false,
1295    }
1296}
1297
1298/// Infer the range type specification from two compatible endpoint types.
1299pub fn range_type_specification_from_endpoints(
1300    left: &LemmaType,
1301    right: &LemmaType,
1302) -> Option<TypeSpecification> {
1303    if !range_endpoints_compatible(left, right) {
1304        return None;
1305    }
1306    left.specifications.range_from_element()
1307}
1308
1309/// Resolves a written unit token to a bare declared unit name against the named types
1310/// visible at one planning site.
1311pub enum UnitTokenResolver<'a> {
1312    /// The spec's types are resolved: tokens resolve through its unit index.
1313    Declared {
1314        unit_index: &'a UnitIndex,
1315        named_types: &'a IndexMap<String, Arc<LemmaType>>,
1316    },
1317    /// The spec has no resolved types: every token is unknown.
1318    Undeclared,
1319    /// Tokens resolve through the planning unit index of the spec being planned.
1320    Planning {
1321        unit_index: &'a crate::planning::unit_index::PlanningUnitIndex,
1322        named_types: &'a IndexMap<String, Arc<LemmaType>>,
1323    },
1324    /// Tokens resolve through the first scope that knows them.
1325    Search(Vec<(&'a UnitIndex, &'a IndexMap<String, Arc<LemmaType>>)>),
1326    /// Tokens resolve through the unit index and must be declared on `lemma_type`
1327    /// or on its range element.
1328    Typed {
1329        unit_index: &'a UnitIndex,
1330        named_types: &'a IndexMap<String, Arc<LemmaType>>,
1331        lemma_type: &'a LemmaType,
1332    },
1333}
1334
1335impl UnitTokenResolver<'_> {
1336    pub fn resolve(&self, unit: &str) -> Result<String, String> {
1337        match self {
1338            UnitTokenResolver::Declared {
1339                unit_index,
1340                named_types,
1341            } => unit_index
1342                .resolve_with_named_types(unit, named_types)
1343                .map(|(bare, _)| bare),
1344            UnitTokenResolver::Undeclared => Err(unknown_unit_message(unit)),
1345            UnitTokenResolver::Planning {
1346                unit_index,
1347                named_types,
1348            } => unit_index
1349                .resolve_with_named_types(unit, named_types)
1350                .map(|(bare, _)| bare),
1351            UnitTokenResolver::Search(scopes) => scopes
1352                .iter()
1353                .find_map(|(unit_index, named_types)| {
1354                    unit_index
1355                        .resolve_with_named_types(unit, named_types)
1356                        .ok()
1357                        .map(|(bare, _)| bare)
1358                })
1359                .ok_or_else(|| unknown_unit_message(unit)),
1360            UnitTokenResolver::Typed {
1361                unit_index,
1362                named_types,
1363                lemma_type,
1364            } => resolve_declared_on_type(unit, lemma_type, unit_index, named_types),
1365        }
1366    }
1367}
1368
1369fn unknown_unit_message(unit: &str) -> String {
1370    format!("Unknown unit '{unit}'. Declare it on a measure or ratio type, or import it with uses.")
1371}
1372
1373fn resolve_declared_on_type(
1374    written: &str,
1375    lemma_type: &LemmaType,
1376    unit_index: &UnitIndex,
1377    named_types: &IndexMap<String, Arc<LemmaType>>,
1378) -> Result<String, String> {
1379    match unit_index.resolve_with_named_types(written, named_types) {
1380        Ok((bare, _)) => {
1381            if unit_name_declared_on_type(lemma_type, &bare)
1382                || range_element_declares_unit(lemma_type, &bare)
1383            {
1384                Ok(bare)
1385            } else {
1386                Err(format!(
1387                    "Unit '{written}' resolves to '{bare}', which is not declared on type {}",
1388                    lemma_type.name()
1389                ))
1390            }
1391        }
1392        Err(index_err) => {
1393            if unit_name_declared_on_type(lemma_type, written)
1394                || range_element_declares_unit(lemma_type, written)
1395            {
1396                Ok(written.to_string())
1397            } else {
1398                Err(index_err)
1399            }
1400        }
1401    }
1402}
1403
1404fn range_element_declares_unit(lemma_type: &LemmaType, unit_name: &str) -> bool {
1405    let Some(element) = lemma_type.specifications.element_from_range() else {
1406        return false;
1407    };
1408    unit_name_declared_on_type(&LemmaType::primitive(element), unit_name)
1409}
1410
1411pub(crate) fn unit_name_declared_on_type(lemma_type: &LemmaType, unit_name: &str) -> bool {
1412    match &lemma_type.specifications {
1413        TypeSpecification::Measure { units, .. } => units.get(unit_name).is_ok(),
1414        TypeSpecification::Ratio { units, .. } => units.get(unit_name).is_ok(),
1415        _ => false,
1416    }
1417}
1418
1419/// Declared bare unit name on a measure or ratio element type for `token`.
1420fn bare_declared_unit_on_element(
1421    element_spec: &TypeSpecification,
1422    token: &str,
1423) -> Result<String, String> {
1424    match element_spec {
1425        TypeSpecification::Measure { units, .. } => Ok(units.get(token)?.name.clone()),
1426        TypeSpecification::Ratio { units, .. } => Ok(units.get(token)?.name.clone()),
1427        other => panic!("BUG: bare_declared_unit_on_element on non-measure/ratio element {other}"),
1428    }
1429}
1430
1431/// Resolve a written unit token to a bare declared name on `element_spec`.
1432///
1433/// Tries an exact declared name first. When that fails and `resolve_unit` is
1434/// provided, resolves through the unit index and checks the bare name is declared
1435/// on the element.
1436pub fn resolve_endpoint_unit_token(
1437    token: &str,
1438    element_spec: &TypeSpecification,
1439    resolve_unit: Option<&UnitTokenResolver<'_>>,
1440) -> Result<String, String> {
1441    match bare_declared_unit_on_element(element_spec, token) {
1442        Ok(bare) => Ok(bare),
1443        Err(declared_err) => {
1444            let Some(resolve) = resolve_unit else {
1445                return Err(declared_err);
1446            };
1447            let bare = resolve.resolve(token)?;
1448            bare_declared_unit_on_element(element_spec, &bare).map_err(|_| {
1449                format!("Unit '{token}' resolves to '{bare}', which is not declared on this type")
1450            })
1451        }
1452    }
1453}
1454
1455/// Lift a parser literal range endpoint to a [`TypedLiteral`] typed as `element_type`.
1456/// Routes [`Value::NumberWithUnit`] through [`number_with_unit_value_kind`] so ratio endpoints
1457/// (e.g. `10%` in a `ratio range`) canonicalize to ratios, not anonymous quantities.
1458///
1459/// `element_type` must already carry the slot's measure/ratio family when the range
1460/// is a named type (`money range` → money). Callers use [`LemmaType::range_element_type`].
1461///
1462/// When `resolve_unit` is set, qualified tokens are resolved to bare declared names before bind.
1463pub(crate) fn lift_range_endpoint(
1464    value: &crate::parsing::ast::Value,
1465    element_type: &LemmaType,
1466    resolve_unit: Option<&UnitTokenResolver<'_>>,
1467) -> Result<TypedLiteral, String> {
1468    use crate::parsing::ast::Value;
1469    let element_spec = &element_type.specifications;
1470    match value {
1471        Value::NumberWithUnit(magnitude, unit_token) => {
1472            let bare = resolve_endpoint_unit_token(unit_token, element_spec, resolve_unit)?;
1473            let kind = number_with_unit_value_kind(*magnitude, &bare, element_spec)?;
1474            let lemma_type = match &kind {
1475                ValueKind::Measure(_) | ValueKind::Ratio(_) | ValueKind::UnscaledMeasure { .. } => {
1476                    Arc::new(element_type.clone().with_unit(bare))
1477                }
1478                _ => Arc::new(element_type.clone()),
1479            };
1480            Ok(TypedLiteral {
1481                value: kind,
1482                lemma_type,
1483            })
1484        }
1485        _ => {
1486            let kind = parser_scalar_to_value_kind(value, element_spec)?;
1487            Ok(TypedLiteral {
1488                value: kind,
1489                lemma_type: Arc::new(element_type.clone()),
1490            })
1491        }
1492    }
1493}
1494
1495fn literal_value_from_parser_value(
1496    value: &crate::parsing::ast::Value,
1497) -> Result<TypedLiteral, String> {
1498    use crate::parsing::ast::Value;
1499
1500    enum Step<'a> {
1501        Visit(&'a Value),
1502        CombineRange,
1503    }
1504
1505    let mut steps = vec![Step::Visit(value)];
1506    let mut literals: Vec<TypedLiteral> = Vec::new();
1507    while let Some(step) = steps.pop() {
1508        match step {
1509            Step::Visit(Value::Range(left, right)) => {
1510                steps.push(Step::CombineRange);
1511                steps.push(Step::Visit(right));
1512                steps.push(Step::Visit(left));
1513            }
1514            Step::Visit(scalar) => literals.push(scalar_literal_from_parser_value(scalar)?),
1515            Step::CombineRange => {
1516                let right = literals
1517                    .pop()
1518                    .expect("BUG: range right endpoint missing from literal stack");
1519                let left = literals
1520                    .pop()
1521                    .expect("BUG: range left endpoint missing from literal stack");
1522                let compatible = match (
1523                    &left.lemma_type.specifications,
1524                    &right.lemma_type.specifications,
1525                ) {
1526                    (TypeSpecification::Date { .. }, TypeSpecification::Date { .. }) => true,
1527                    (TypeSpecification::Time { .. }, TypeSpecification::Time { .. }) => true,
1528                    (TypeSpecification::Number { .. }, TypeSpecification::Number { .. }) => true,
1529                    (TypeSpecification::Measure { .. }, TypeSpecification::Measure { .. }) => {
1530                        left.lemma_type.same_measure_family(&right.lemma_type)
1531                            || left
1532                                .lemma_type
1533                                .compatible_with_anonymous_measure(&right.lemma_type)
1534                            || right
1535                                .lemma_type
1536                                .compatible_with_anonymous_measure(&left.lemma_type)
1537                    }
1538                    (TypeSpecification::Ratio { .. }, TypeSpecification::Ratio { .. }) => true,
1539                    _ => false,
1540                };
1541                if !compatible {
1542                    return Err(format!(
1543                        "range endpoints must have the same supported base type, got {} and {}",
1544                        left.lemma_type.name(),
1545                        right.lemma_type.name()
1546                    ));
1547                }
1548                literals.push(TypedLiteral::range(left, right));
1549            }
1550        }
1551    }
1552    Ok(literals.pop().expect("BUG: literal walk left no result"))
1553}
1554
1555fn scalar_literal_from_parser_value(
1556    value: &crate::parsing::ast::Value,
1557) -> Result<TypedLiteral, String> {
1558    use crate::parsing::ast::Value;
1559
1560    match value {
1561        Value::Number(n) => Ok(TypedLiteral::number(lift_parser_decimal(*n)?)),
1562        Value::Text(s) => Ok(TypedLiteral::text(s.clone())),
1563        Value::Date(dt) => Ok(TypedLiteral::date(date_time_to_semantic(dt))),
1564        Value::Time(t) => Ok(TypedLiteral::time(time_to_semantic(t))),
1565        Value::Boolean(b) => Ok(TypedLiteral::from_bool(bool::from(*b))),
1566        Value::NumberWithUnit(n, _) => Ok(TypedLiteral::number_interpreted_as_measure(
1567            lift_parser_decimal(*n)?,
1568        )),
1569        Value::Range(_, _) => {
1570            unreachable!("BUG: range values are walked by literal_value_from_parser_value")
1571        }
1572    }
1573}
1574
1575/// Cast a [`RationalInteger`] to `u8`, requiring it to be a non-negative whole number that fits.
1576fn decimal_to_u8(d: RationalInteger, ctx: &str) -> Result<u8, String> {
1577    if !d.is_integer() {
1578        return Err(format!(
1579            "{} requires a whole number, got fractional value",
1580            ctx
1581        ));
1582    }
1583    d.numer_to_u8()
1584        .ok_or_else(|| format!("{} value out of range for u8", ctx))
1585}
1586
1587/// Cast a [`RationalInteger`] to `usize`, requiring it to be a non-negative whole number that fits.
1588fn decimal_to_usize(d: RationalInteger, ctx: &str) -> Result<usize, String> {
1589    if !d.is_integer() {
1590        return Err(format!(
1591            "{} requires a whole number, got fractional value",
1592            ctx
1593        ));
1594    }
1595    d.numer_to_usize()
1596        .ok_or_else(|| format!("{} value out of range for usize", ctx))
1597}
1598
1599/// Extract a number literal from a [`Value::Number`] arg and lift it to [`RationalInteger`].
1600///
1601/// Numeric meta-constraints (`decimals`, `length`, `minimum`/`maximum`
1602/// on `Number` and `Measure`) take a bare number literal — not a ratio, not a measure. Reject
1603/// any other variant to honour the no-coercion contract.
1604fn ratio_bound_to_canonical_rational(
1605    args: &[CommandArg],
1606    cmd: &str,
1607    units: &RatioUnits,
1608) -> Result<RationalInteger, String> {
1609    use crate::computation::rational::{checked_div, decimal_to_rational};
1610    let lit = require_literal(args, cmd)?;
1611    match lit {
1612        crate::literals::Value::NumberWithUnit(magnitude, unit_name) => {
1613            let unit = units.get(unit_name.as_str())?;
1614            let magnitude_rational = decimal_to_rational(*magnitude)
1615                .map_err(|failure| format!("{cmd} literal failed rational lift: {failure}"))?;
1616            checked_div(&magnitude_rational, &unit.value)
1617                .map_err(|failure| format!("{cmd}: unit conversion failed: {failure}"))
1618        }
1619        other => Err(format!(
1620            "{cmd} requires a ratio literal with a unit, got {}",
1621            value_kind_name(other)
1622        )),
1623    }
1624}
1625
1626fn require_decimal_literal(args: &[CommandArg], cmd: &str) -> Result<RationalInteger, String> {
1627    use crate::computation::rational::decimal_to_rational;
1628    match require_literal(args, cmd)? {
1629        crate::literals::Value::Number(d) => decimal_to_rational(*d)
1630            .map_err(|failure| format!("{} literal failed rational lift: {}", cmd, failure)),
1631        other => Err(format!(
1632            "{} requires a number literal, got {}",
1633            cmd,
1634            value_kind_name(other)
1635        )),
1636    }
1637}
1638
1639enum UnitConstraintField {
1640    Minimum,
1641    Maximum,
1642    SuggestionMagnitude,
1643}
1644
1645fn apply_measure_unit_factor(
1646    units: &mut MeasureUnits,
1647    unit_name: String,
1648    value: rust_decimal::Decimal,
1649    derived_measure_factors: Vec<(String, i32)>,
1650) -> Result<(), String> {
1651    if let Some(existing) = units.0.iter().find(|u| u.name == unit_name) {
1652        let new_factor = crate::computation::rational::decimal_to_rational(value)
1653            .map_err(|failure| failure.to_string())?;
1654        if existing.declared_factor() != Some(&new_factor)
1655            || existing.derived_measure_factors != derived_measure_factors
1656        {
1657            return Err(format!(
1658                "Unit '{unit_name}' is already defined in this type's inherited units; \
1659                 cannot change factor or decomposition. Add a new unit name instead."
1660            ));
1661        }
1662        return Ok(());
1663    }
1664    units.0.push(MeasureUnit::from_decimal_factor(
1665        unit_name,
1666        value,
1667        derived_measure_factors,
1668    )?);
1669    Ok(())
1670}
1671
1672pub(crate) fn measure_declared_bound_to_canonical(
1673    magnitude: &RationalInteger,
1674    unit_name: &str,
1675    units: &MeasureUnits,
1676    type_name: &str,
1677    command: &str,
1678) -> Result<RationalInteger, String> {
1679    use crate::computation::rational::checked_mul;
1680    let unit = units.get(unit_name).map_err(|_| {
1681        format!(
1682            "Unit '{unit_name}' is not defined on '{type_name}'. Valid units are: {}.",
1683            format_measure_units_list(units)
1684        )
1685    })?;
1686    let factor = unit.literal_factor().ok_or_else(|| {
1687        format!(
1688            "{command} cannot use unit '{unit_name}' on '{type_name}': its conversion factor is a reference and is not known at planning."
1689        )
1690    })?;
1691    checked_mul(magnitude, factor)
1692        .map_err(|failure| format!("{command}: unit conversion overflow: {failure}"))
1693}
1694
1695fn parse_measure_declared_bound(
1696    args: &[CommandArg],
1697    cmd: &str,
1698    units: &MeasureUnits,
1699    type_name: &str,
1700) -> Result<(RationalInteger, String), String> {
1701    use crate::computation::rational::decimal_to_rational;
1702    let lit = require_literal(args, cmd)?;
1703    let (magnitude, unit_name) = match lit {
1704        crate::literals::Value::NumberWithUnit(n, unit) => (*n, unit.clone()),
1705        other => {
1706            return Err(format!(
1707                "{cmd} requires a measure literal with a unit, got {}",
1708                value_kind_name(other)
1709            ));
1710        }
1711    };
1712    units.get(unit_name.as_str()).map_err(|_| {
1713        format!(
1714            "Unit '{unit_name}' is not defined on '{type_name}'. Valid units are: {}.",
1715            format_measure_units_list(units)
1716        )
1717    })?;
1718    let magnitude_rational = decimal_to_rational(magnitude)
1719        .map_err(|failure| format!("{cmd} literal failed rational lift: {failure}"))?;
1720    Ok((magnitude_rational, unit_name))
1721}
1722
1723fn sync_measure_units_from_canonical(
1724    units: &mut MeasureUnits,
1725    canonical: &RationalInteger,
1726    field: UnitConstraintField,
1727) -> Result<(), String> {
1728    use crate::computation::rational::checked_div;
1729    for unit in &mut units.0 {
1730        let Some(factor) = unit.literal_factor() else {
1731            continue;
1732        };
1733        let magnitude = checked_div(canonical, factor).map_err(|failure| {
1734            format!(
1735                "cannot derive per-unit constraint for unit '{}': {failure}",
1736                unit.name
1737            )
1738        })?;
1739        match field {
1740            UnitConstraintField::Minimum => unit.minimum = Some(magnitude),
1741            UnitConstraintField::Maximum => unit.maximum = Some(magnitude),
1742            UnitConstraintField::SuggestionMagnitude => unit.suggestion_magnitude = Some(magnitude),
1743        }
1744    }
1745    Ok(())
1746}
1747
1748fn sync_ratio_units_from_canonical(
1749    units: &mut RatioUnits,
1750    canonical: &RationalInteger,
1751    field: UnitConstraintField,
1752) -> Result<(), String> {
1753    use crate::computation::rational::checked_mul;
1754    for unit in &mut units.0 {
1755        let magnitude = checked_mul(canonical, &unit.value).map_err(|failure| {
1756            format!(
1757                "cannot derive per-unit constraint for ratio unit '{}': {failure}",
1758                unit.name
1759            )
1760        })?;
1761        match field {
1762            UnitConstraintField::Minimum => unit.minimum = Some(magnitude),
1763            UnitConstraintField::Maximum => unit.maximum = Some(magnitude),
1764            UnitConstraintField::SuggestionMagnitude => unit.suggestion_magnitude = Some(magnitude),
1765        }
1766    }
1767    Ok(())
1768}
1769
1770fn sync_measure_suggestion_units(
1771    units: &mut MeasureUnits,
1772    default: &ValueKind,
1773    type_name: &str,
1774) -> Result<(), String> {
1775    let ValueKind::Measure(magnitude) = default else {
1776        return Ok(());
1777    };
1778    let unit_name = units
1779        .iter()
1780        .find(|unit| unit.is_canonical_factor())
1781        .or_else(|| units.iter().next())
1782        .map(|unit| unit.name.as_str())
1783        .expect(
1784            "BUG: Measure suggestion value requires at least one declared unit on the measure type",
1785        );
1786    units.get(unit_name).map_err(|_| {
1787        format!("Suggestion unit '{unit_name}' is not defined on measure type '{type_name}'.")
1788    })?;
1789    sync_measure_units_from_canonical(units, magnitude, UnitConstraintField::SuggestionMagnitude)
1790}
1791
1792pub(crate) fn finalize_measure_unit_constraint_magnitudes(
1793    specification: &mut TypeSpecification,
1794    declared_suggestion: Option<&ValueKind>,
1795    type_name: &str,
1796) -> Result<(), String> {
1797    let TypeSpecification::Measure {
1798        minimum,
1799        maximum,
1800        units,
1801        ..
1802    } = specification
1803    else {
1804        return Ok(());
1805    };
1806
1807    let mut synced_minimum = false;
1808    if let Some(bound) = minimum.as_ref() {
1809        let bound_unit = units.get(bound.1.as_str()).map_err(|err| err.to_string())?;
1810        if bound_unit.literal_factor().is_some() {
1811            let canonical = measure_declared_bound_to_canonical(
1812                &bound.0, &bound.1, units, type_name, "minimum",
1813            )?;
1814            sync_measure_units_from_canonical(units, &canonical, UnitConstraintField::Minimum)?;
1815            synced_minimum = true;
1816        }
1817    }
1818    let mut synced_maximum = false;
1819    if let Some(bound) = maximum.as_ref() {
1820        let bound_unit = units.get(bound.1.as_str()).map_err(|err| err.to_string())?;
1821        if bound_unit.literal_factor().is_some() {
1822            let canonical = measure_declared_bound_to_canonical(
1823                &bound.0, &bound.1, units, type_name, "maximum",
1824            )?;
1825            sync_measure_units_from_canonical(units, &canonical, UnitConstraintField::Maximum)?;
1826            synced_maximum = true;
1827        }
1828    }
1829    let mut synced_suggestion = false;
1830    if let Some(default) = declared_suggestion {
1831        if matches!(default, ValueKind::Measure(_)) {
1832            sync_measure_suggestion_units(units, default, type_name)?;
1833            synced_suggestion = true;
1834        }
1835    }
1836
1837    if synced_minimum {
1838        for unit in units.iter() {
1839            if unit.literal_factor().is_none() {
1840                continue;
1841            }
1842            assert!(
1843                unit.minimum.is_some(),
1844                "BUG: type '{type_name}' has minimum but unit '{}' missing per-unit minimum after finalize",
1845                unit.name
1846            );
1847        }
1848    }
1849    if synced_maximum {
1850        for unit in units.iter() {
1851            if unit.literal_factor().is_none() {
1852                continue;
1853            }
1854            assert!(
1855                unit.maximum.is_some(),
1856                "BUG: type '{type_name}' has maximum but unit '{}' missing per-unit maximum after finalize",
1857                unit.name
1858            );
1859        }
1860    }
1861    if synced_suggestion {
1862        for unit in units.iter() {
1863            if unit.literal_factor().is_none() {
1864                continue;
1865            }
1866            assert!(
1867                unit.suggestion_magnitude.is_some(),
1868                "BUG: type '{type_name}' has default but unit '{}' missing per-unit default after finalize",
1869                unit.name
1870            );
1871        }
1872    }
1873
1874    Ok(())
1875}
1876
1877fn sync_ratio_suggestion_units(units: &mut RatioUnits, default: &ValueKind) -> Result<(), String> {
1878    let ValueKind::Ratio(canonical) = default else {
1879        return Ok(());
1880    };
1881    sync_ratio_units_from_canonical(units, canonical, UnitConstraintField::SuggestionMagnitude)
1882}
1883
1884/// Extract an option name from a single arg.
1885///
1886/// Both `option red` (bare identifier, parsed as `Label`) and `option "red"`
1887/// (quoted text literal) are valid lemma syntax for option enumeration; the
1888/// grammar accepts either form. All other variants are rejected.
1889pub(crate) fn apply_option_constraint(
1890    lemma_type: &mut LemmaType,
1891    command: TypeConstraintCommand,
1892    args: &[CommandArg],
1893    resolve_unit: Option<&UnitTokenResolver<'_>>,
1894    spec: &crate::parsing::ast::LemmaSpec,
1895) -> Result<(), String> {
1896    let mut hops = 0;
1897    {
1898        let mut probe = &*lemma_type;
1899        while let TypeSpecification::List { element, .. } = &probe.specifications {
1900            hops += 1;
1901            probe = element.as_ref();
1902        }
1903    }
1904    let mut current = lemma_type;
1905    for _ in 0..hops {
1906        let TypeSpecification::List { element, .. } = &mut current.specifications else {
1907            unreachable!("BUG: option forwarding counted a list");
1908        };
1909        current = Arc::make_mut(element);
1910    }
1911    apply_options_command(current, command, args, resolve_unit, spec)
1912}
1913
1914/// `-> with` / `-> suggest` naming one `uses` instance of a spec type.
1915pub(crate) fn apply_spec_member_command(
1916    lemma_type: &LemmaType,
1917    command: TypeConstraintCommand,
1918    args: &[CommandArg],
1919    spec: &crate::parsing::ast::LemmaSpec,
1920    target: &mut Option<RawSuggestion>,
1921) -> Result<(), String> {
1922    let label = match args {
1923        [CommandArg::Label(name)] => name,
1924        _ => return Err(format!("{command} on a spec takes one instance name")),
1925    };
1926    let option = spec_alias_option(
1927        lemma_type,
1928        uses_alias(spec, label)
1929            .ok_or_else(|| format!("'{label}' is not an instance of this spec"))?,
1930        label,
1931    )?;
1932    *target = Some(RawSuggestion::Value(option.value.value));
1933    Ok(())
1934}
1935
1936/// One `-> with` line appends rows on a list. A spec element names a `uses` instance.
1937pub(crate) fn apply_list_with_rows(
1938    lemma_type: &mut LemmaType,
1939    names: ConstraintNames<'_>,
1940    args: &[CommandArg],
1941    declared_value: &mut Option<RawSuggestion>,
1942    resolve_unit: Option<&UnitTokenResolver<'_>>,
1943    spec: &crate::parsing::ast::LemmaSpec,
1944) -> Result<(), String> {
1945    let mut rows = match declared_value.take() {
1946        Some(RawSuggestion::List(existing)) => existing,
1947        None => Vec::new(),
1948        Some(other) => {
1949            unreachable!("BUG: list declared value must be RawSuggestion::List, got {other:?}")
1950        }
1951    };
1952    let TypeSpecification::List { element, .. } = &mut lemma_type.specifications else {
1953        unreachable!("BUG: apply_list_with_rows on a non-list type");
1954    };
1955    for arg in args {
1956        rows.push(list_with_row(
1957            Arc::make_mut(element),
1958            names,
1959            arg,
1960            resolve_unit,
1961            spec,
1962        )?);
1963    }
1964    *declared_value = Some(RawSuggestion::List(rows));
1965    Ok(())
1966}
1967
1968fn list_with_row(
1969    element: &mut LemmaType,
1970    names: ConstraintNames<'_>,
1971    arg: &CommandArg,
1972    resolve_unit: Option<&UnitTokenResolver<'_>>,
1973    spec: &crate::parsing::ast::LemmaSpec,
1974) -> Result<RawSuggestion, String> {
1975    let mut hops = 0;
1976    {
1977        let mut probe = &*element;
1978        while let TypeSpecification::List { element, .. } = &probe.specifications {
1979            hops += 1;
1980            probe = element.as_ref();
1981        }
1982    }
1983    let mut current = element;
1984    for _ in 0..hops {
1985        let TypeSpecification::List { element, .. } = &mut current.specifications else {
1986            unreachable!("BUG: list -> with counted a list");
1987        };
1988        current = Arc::make_mut(element);
1989    }
1990    let mut row_value = None;
1991    if matches!(current.specifications, TypeSpecification::Spec { .. }) {
1992        apply_spec_member_command(
1993            current,
1994            TypeConstraintCommand::With,
1995            std::slice::from_ref(arg),
1996            spec,
1997            &mut row_value,
1998        )?;
1999    } else {
2000        let mut unused_suggestion = None;
2001        current.apply_constraint(
2002            names,
2003            TypeConstraintCommand::With,
2004            std::slice::from_ref(arg),
2005            &mut unused_suggestion,
2006            &mut row_value,
2007            resolve_unit,
2008        )?;
2009    }
2010    let mut value = row_value.expect("BUG: -> with on a list row must produce a value");
2011    for _ in 0..hops {
2012        value = RawSuggestion::List(vec![value]);
2013    }
2014    Ok(value)
2015}
2016
2017fn apply_options_command(
2018    lemma_type: &mut LemmaType,
2019    command: TypeConstraintCommand,
2020    args: &[CommandArg],
2021    resolve_unit: Option<&UnitTokenResolver<'_>>,
2022    spec: &crate::parsing::ast::LemmaSpec,
2023) -> Result<(), String> {
2024    if command == TypeConstraintCommand::Option && args.len() != 1 {
2025        return Err("option takes exactly one argument".to_string());
2026    }
2027    if args.is_empty() {
2028        return Err("options takes at least one value".to_string());
2029    }
2030    let mut literals: Vec<OptionValue> = Vec::new();
2031    let mut names: Vec<String> = Vec::new();
2032    for arg in args {
2033        match arg {
2034            CommandArg::Literal(value) => {
2035                literals.push(OptionValue {
2036                    value: option_bound_from_literal(value, lemma_type, resolve_unit)?,
2037                });
2038            }
2039            CommandArg::Label(name) => names.push(name.clone()),
2040            CommandArg::UnitExpr(_) => {
2041                return Err(format!(
2042                    "{command} requires a value of this type, got a unit expression"
2043                ));
2044            }
2045        }
2046    }
2047    if !literals.is_empty() && !names.is_empty() {
2048        return Err(format!(
2049            "{command} mixes values and a rule. Write the values, or name one rule."
2050        ));
2051    }
2052    if matches!(lemma_type.specifications, TypeSpecification::Spec { .. }) {
2053        return apply_spec_list_options(lemma_type, command, args, spec);
2054    }
2055    if !names.is_empty() {
2056        return apply_option_names(lemma_type, &names, spec);
2057    }
2058    append_option_literals(lemma_type, literals)?;
2059    Ok(())
2060}
2061
2062fn option_bound_from_literal(
2063    value: &crate::literals::Value,
2064    lemma_type: &LemmaType,
2065    resolve_unit: Option<&UnitTokenResolver<'_>>,
2066) -> Result<BoundValueKind, String> {
2067    let kind = parser_value_to_value_kind(value, lemma_type, resolve_unit)?;
2068    let token = match value {
2069        crate::literals::Value::NumberWithUnit(_, unit) => Some(unit.as_str()),
2070        crate::literals::Value::Range(left, right) => match (left.as_ref(), right.as_ref()) {
2071            (
2072                crate::literals::Value::NumberWithUnit(_, left_unit),
2073                crate::literals::Value::NumberWithUnit(_, right_unit),
2074            ) if left_unit == right_unit => Some(left_unit.as_str()),
2075            _ => None,
2076        },
2077        _ => None,
2078    };
2079    let unit = match token {
2080        Some(token) => Some(Arc::<str>::from(resolve_endpoint_unit_token(
2081            token,
2082            &lemma_type.specifications,
2083            resolve_unit,
2084        )?)),
2085        None => None,
2086    };
2087    Ok(BoundValueKind {
2088        value: kind,
2089        unit,
2090        instance_factors: None,
2091    })
2092}
2093
2094fn apply_spec_list_options(
2095    _lemma_type: &mut LemmaType,
2096    _command: TypeConstraintCommand,
2097    _args: &[CommandArg],
2098    _spec: &crate::parsing::ast::LemmaSpec,
2099) -> Result<(), String> {
2100    Err(SPEC_LIST_HAS_NO_OPTIONS.to_string())
2101}
2102
2103enum OptionName {
2104    Text(OptionValue),
2105    Instance(OptionValue),
2106    Rule,
2107}
2108
2109fn apply_option_names(
2110    lemma_type: &mut LemmaType,
2111    names: &[String],
2112    spec: &crate::parsing::ast::LemmaSpec,
2113) -> Result<(), String> {
2114    let mut meanings = Vec::with_capacity(names.len());
2115    for name in names {
2116        meanings.push(option_name_meaning(lemma_type, spec, name)?);
2117    }
2118    let rule_count = meanings
2119        .iter()
2120        .filter(|meaning| matches!(meaning, OptionName::Rule))
2121        .count();
2122    if rule_count > 0 {
2123        if names.len() != 1 || rule_count != 1 {
2124            return Err(
2125                "options names one rule, or lists values. A rule is not mixed with values."
2126                    .to_string(),
2127            );
2128        }
2129        if let Some(existing) = &lemma_type.options.rule {
2130            return Err(format!(
2131                "`-> options` already names rule '{existing}', not '{}'",
2132                names[0]
2133            ));
2134        }
2135        lemma_type.options.rule = Some(names[0].clone());
2136        return Ok(());
2137    }
2138    let mut literals = Vec::with_capacity(meanings.len());
2139    for meaning in meanings {
2140        match meaning {
2141            OptionName::Text(value) | OptionName::Instance(value) => literals.push(value),
2142            OptionName::Rule => unreachable!("BUG: rule meanings are returned above"),
2143        }
2144    }
2145    reject_duplicate_options(lemma_type, &literals)?;
2146    append_option_literals(lemma_type, literals)?;
2147    Ok(())
2148}
2149
2150/// One grammatical name has one meaning. Two meanings is an error; zero is an error.
2151fn option_name_meaning(
2152    lemma_type: &LemmaType,
2153    spec: &crate::parsing::ast::LemmaSpec,
2154    name: &str,
2155) -> Result<OptionName, String> {
2156    let mut found: Vec<OptionName> = Vec::new();
2157    if matches!(lemma_type.specifications, TypeSpecification::Text { .. }) {
2158        found.push(OptionName::Text(OptionValue {
2159            value: BoundValueKind::unbound(ValueKind::Text(Arc::from(name))),
2160        }));
2161    }
2162    if let Some(data) = uses_alias(spec, name) {
2163        if let Ok(instance) = spec_alias_option(lemma_type, data, name) {
2164            found.push(OptionName::Instance(instance));
2165        }
2166    }
2167    if spec.rules.iter().any(|rule| rule.name == name) {
2168        found.push(OptionName::Rule);
2169    }
2170    match found.len() {
2171        1 => Ok(found.pop().expect("BUG: one option meaning")),
2172        0 => Err(format!("'{name}' is not a value of this type or a rule")),
2173        _ => Err(format!(
2174            "'{name}' is more than one of a text option, an instance, and a rule"
2175        )),
2176    }
2177}
2178
2179fn uses_alias<'a>(
2180    spec: &'a crate::parsing::ast::LemmaSpec,
2181    name: &str,
2182) -> Option<&'a crate::parsing::ast::LemmaData> {
2183    spec.data.iter().find(|data| {
2184        data.reference.name == name
2185            && matches!(data.value, crate::parsing::ast::DataValue::Import { .. })
2186    })
2187}
2188
2189fn spec_alias_option(
2190    lemma_type: &LemmaType,
2191    data: &crate::parsing::ast::LemmaData,
2192    name: &str,
2193) -> Result<OptionValue, String> {
2194    let TypeSpecification::Spec { spec } = &lemma_type.specifications else {
2195        return Err(format!("'{name}' is not a value of this type or a rule"));
2196    };
2197    let crate::parsing::ast::DataValue::Import { spec_ref, .. } = &data.value else {
2198        unreachable!("BUG: uses_alias returns an import");
2199    };
2200    if spec_ref.name != spec.spec {
2201        return Err(format!(
2202            "'{name}' is an instance of '{}', not '{}'",
2203            spec_ref.name, spec.spec
2204        ));
2205    }
2206    unreachable!(
2207        "BUG: `uses` alias `{name}` named on a spec type: a spec type is only a list element, `-> options` on it names a rule, and the parser reads `-> with {name}` on a list as an instance-list row"
2208    )
2209}
2210
2211fn append_option_literals(
2212    lemma_type: &mut LemmaType,
2213    incoming: Vec<OptionValue>,
2214) -> Result<(), String> {
2215    for option in incoming {
2216        if lemma_type
2217            .options
2218            .values
2219            .iter()
2220            .any(|existing| existing.value == option.value)
2221        {
2222            return Err(format!(
2223                "duplicate option '{}'",
2224                lemma_type.display_bound(&option.value)
2225            ));
2226        }
2227        lemma_type.options.values.push(option);
2228    }
2229    Ok(())
2230}
2231
2232fn static_option_match(options: &TypeOptions, value: &ValueKind) -> bool {
2233    options
2234        .values
2235        .iter()
2236        .any(|option| option_values_match(&option.value.value, value))
2237}
2238
2239fn options_have_unscaled_measure(options: &TypeOptions) -> bool {
2240    options
2241        .values
2242        .iter()
2243        .any(|option| option.value.value.has_unscaled_measure())
2244}
2245
2246/// Rewrite every [`ValueKind::UnscaledMeasure`] using composed runtime unit factors.
2247/// Walks ranges and lists iteratively. Missing scale for a needed unit is an error.
2248pub(crate) fn settle_value_kind_with_scales(
2249    value: &ValueKind,
2250    scales: &std::collections::HashMap<String, crate::computation::rational::RationalInteger>,
2251) -> Result<ValueKind, String> {
2252    use crate::computation::rational::checked_mul;
2253
2254    enum Task {
2255        Visit(ValueKind),
2256        AssembleRange {
2257            left_type: Arc<LemmaType>,
2258            right_type: Arc<LemmaType>,
2259        },
2260        AssembleList {
2261            row_types: Vec<Arc<LemmaType>>,
2262        },
2263    }
2264
2265    let mut tasks = vec![Task::Visit(value.clone())];
2266    let mut done: Vec<ValueKind> = Vec::new();
2267    while let Some(task) = tasks.pop() {
2268        match task {
2269            Task::Visit(ValueKind::UnscaledMeasure { magnitude, unit }) => {
2270                let factor = scales.get(unit.as_ref()).ok_or_else(|| {
2271                    format!("unit '{unit}' scale is not settled for option membership")
2272                })?;
2273                let canonical =
2274                    checked_mul(&magnitude, factor).map_err(|failure| failure.to_string())?;
2275                done.push(ValueKind::Measure(canonical));
2276            }
2277            Task::Visit(ValueKind::Range(left, right)) => {
2278                tasks.push(Task::AssembleRange {
2279                    left_type: Arc::clone(&left.lemma_type),
2280                    right_type: Arc::clone(&right.lemma_type),
2281                });
2282                let right = *right;
2283                let left = *left;
2284                tasks.push(Task::Visit(right.value));
2285                tasks.push(Task::Visit(left.value));
2286            }
2287            Task::Visit(ValueKind::List(rows)) => {
2288                let owned = rows.to_vec();
2289                let row_types: Vec<Arc<LemmaType>> = owned
2290                    .iter()
2291                    .map(|row| Arc::clone(&row.lemma_type))
2292                    .collect();
2293                tasks.push(Task::AssembleList { row_types });
2294                for row in owned.into_iter().rev() {
2295                    tasks.push(Task::Visit(row.value));
2296                }
2297            }
2298            Task::Visit(other) => done.push(other),
2299            Task::AssembleRange {
2300                left_type,
2301                right_type,
2302            } => {
2303                let right_value = done
2304                    .pop()
2305                    .expect("BUG: settled range missing right endpoint");
2306                let left_value = done
2307                    .pop()
2308                    .expect("BUG: settled range missing left endpoint");
2309                done.push(ValueKind::Range(
2310                    Box::new(TypedLiteral {
2311                        value: left_value,
2312                        lemma_type: left_type,
2313                    }),
2314                    Box::new(TypedLiteral {
2315                        value: right_value,
2316                        lemma_type: right_type,
2317                    }),
2318                ));
2319            }
2320            Task::AssembleList { row_types } => {
2321                let mut settled = Vec::with_capacity(row_types.len());
2322                for lemma_type in row_types.into_iter().rev() {
2323                    let value = done.pop().expect("BUG: settled list missing a row");
2324                    settled.push(TypedLiteral { value, lemma_type });
2325                }
2326                settled.reverse();
2327                done.push(ValueKind::List(settled.into()));
2328            }
2329        }
2330    }
2331    Ok(done
2332        .pop()
2333        .expect("BUG: settle_value_kind_with_scales leaves one result"))
2334}
2335
2336fn static_option_match_with_scales(
2337    options: &TypeOptions,
2338    value: &ValueKind,
2339    scales: &std::collections::HashMap<String, crate::computation::rational::RationalInteger>,
2340) -> Result<bool, String> {
2341    let settled_value = settle_value_kind_with_scales(value, scales)?;
2342    for option in &options.values {
2343        let settled_option = settle_value_kind_with_scales(&option.value.value, scales)?;
2344        if option_values_match(&settled_option, &settled_value) {
2345            return Ok(true);
2346        }
2347    }
2348    Ok(false)
2349}
2350
2351pub(crate) fn disallowed_message(
2352    lemma_type: &LemmaType,
2353    options: &TypeOptions,
2354    value: &ValueKind,
2355    rule_rows: Option<&ListValue>,
2356) -> String {
2357    let mut shown = options
2358        .values
2359        .iter()
2360        .map(|option| lemma_type.display_bound(&option.value))
2361        .collect::<Vec<_>>()
2362        .join(", ");
2363    if let Some(rows) = rule_rows {
2364        let rule_shown = rows
2365            .iter()
2366            .map(|row| row.value.to_string())
2367            .collect::<Vec<_>>()
2368            .join(", ");
2369        if !shown.is_empty() && !rule_shown.is_empty() {
2370            shown.push_str(", ");
2371        }
2372        shown.push_str(&rule_shown);
2373    }
2374    format!("'{value}' is not one of the allowed options: {shown}.")
2375}
2376
2377/// Equality for option matching of scalar and list-of-scalar values. Spec values never
2378/// appear: a list of spec instances takes no options ([`SPEC_LIST_HAS_NO_OPTIONS`]).
2379fn option_values_match(option: &ValueKind, value: &ValueKind) -> bool {
2380    let mut values: Vec<(ValueKind, ValueKind)> = vec![(option.clone(), value.clone())];
2381    while let Some((left, right)) = values.pop() {
2382        match (left, right) {
2383            (ValueKind::Spec(_), _) | (_, ValueKind::Spec(_)) => {
2384                unreachable!(
2385                    "BUG: option matching saw a spec value; {}",
2386                    SPEC_LIST_HAS_NO_OPTIONS
2387                );
2388            }
2389            (ValueKind::List(left), ValueKind::List(right)) => {
2390                if left.len() != right.len() {
2391                    return false;
2392                }
2393                for (a, b) in left.iter().zip(right.iter()) {
2394                    if a.lemma_type != b.lemma_type {
2395                        return false;
2396                    }
2397                    values.push((a.into_owned().value, b.into_owned().value));
2398                }
2399            }
2400            (left, right) => {
2401                if left != right {
2402                    return false;
2403                }
2404            }
2405        }
2406    }
2407    true
2408}
2409
2410pub(crate) fn option_detail_line(lemma_type: &LemmaType) -> Option<String> {
2411    let options = &lemma_type.options;
2412    let mut parts = Vec::new();
2413    if !options.values.is_empty() {
2414        parts.push(
2415            options
2416                .values
2417                .iter()
2418                .map(|option| lemma_type.display_bound(&option.value))
2419                .collect::<Vec<_>>()
2420                .join(", "),
2421        );
2422    }
2423    if let Some(name) = &options.rule {
2424        parts.push(name.clone());
2425    }
2426    if parts.is_empty() {
2427        None
2428    } else {
2429        Some(format!("options: {}", parts.join(", ")))
2430    }
2431}
2432
2433fn reject_duplicate_options(lemma_type: &LemmaType, values: &[OptionValue]) -> Result<(), String> {
2434    for (index, option) in values.iter().enumerate() {
2435        if values[..index]
2436            .iter()
2437            .any(|earlier| earlier.value == option.value)
2438        {
2439            return Err(format!(
2440                "duplicate option '{}'",
2441                lemma_type.display_bound(&option.value)
2442            ));
2443        }
2444    }
2445    Ok(())
2446}
2447
2448fn label_name(arg: &CommandArg, cmd: &str) -> Result<String, String> {
2449    match arg {
2450        CommandArg::Label(name) => Ok(name.clone()),
2451        CommandArg::Literal(other) => Err(format!(
2452            "{} requires an identifier, got {}",
2453            cmd,
2454            value_kind_name(other)
2455        )),
2456        CommandArg::UnitExpr(_) => Err(format!(
2457            "{} requires an identifier, got a unit expression",
2458            cmd
2459        )),
2460    }
2461}
2462
2463fn measure_trait_name(measure_trait: MeasureTrait) -> &'static str {
2464    match measure_trait {
2465        MeasureTrait::Duration => "duration",
2466        MeasureTrait::Calendar => "calendar",
2467    }
2468}
2469
2470fn parse_measure_trait(args: &[CommandArg]) -> Result<MeasureTrait, String> {
2471    if args.len() != 1 {
2472        return Err("trait requires exactly one identifier argument".to_string());
2473    }
2474    match label_name(&args[0], "trait")?
2475        .trim()
2476        .to_lowercase()
2477        .as_str()
2478    {
2479        "duration" => Ok(MeasureTrait::Duration),
2480        "calendar" => Ok(MeasureTrait::Calendar),
2481        other => Err(format!("Unknown measure trait '{}'", other)),
2482    }
2483}
2484
2485fn validate_calendar_trait_requirements(units: &MeasureUnits) -> Result<(), String> {
2486    let month_unit = units
2487        .iter()
2488        .find(|unit| unit.name == "month")
2489        .ok_or_else(|| {
2490            "trait calendar requires a canonical 'month' unit declared before 'trait calendar'"
2491                .to_string()
2492        })?;
2493    if !month_unit.is_canonical_factor() {
2494        return Err("trait calendar requires unit month 1".to_string());
2495    }
2496    Ok(())
2497}
2498
2499fn validate_duration_trait_requirements(units: &MeasureUnits) -> Result<(), String> {
2500    let second_unit = units
2501        .iter()
2502        .find(|unit| unit.name == "second")
2503        .ok_or_else(|| {
2504            "trait duration requires a canonical 'second' unit declared before 'trait duration'"
2505                .to_string()
2506        })?;
2507    if !second_unit.is_canonical_factor() {
2508        return Err("trait duration requires unit second 1".to_string());
2509    }
2510    Ok(())
2511}
2512
2513/// Extract a [`DateTimeValue`] from a [`Value::Date`] literal arg.
2514fn require_date_literal(args: &[CommandArg], cmd: &str) -> Result<DateTimeValue, String> {
2515    match require_literal(args, cmd)? {
2516        crate::literals::Value::Date(dt) => Ok(dt.clone()),
2517        other => Err(format!(
2518            "{} requires a date literal (e.g. 2024-01-01), got {}",
2519            cmd,
2520            value_kind_name(other)
2521        )),
2522    }
2523}
2524
2525/// Extract a [`TimeValue`] from a [`Value::Time`] literal arg.
2526fn require_time_literal(args: &[CommandArg], cmd: &str) -> Result<TimeValue, String> {
2527    match require_literal(args, cmd)? {
2528        crate::literals::Value::Time(t) => Ok(t.clone()),
2529        other => Err(format!(
2530            "{} requires a time literal (e.g. 12:30:00), got {}",
2531            cmd,
2532            value_kind_name(other)
2533        )),
2534    }
2535}
2536
2537/// Default `help` for a built-in primitive (goal-oriented; syntax lives in [`LemmaType::example_value`]).
2538#[must_use]
2539pub fn default_help_for_primitive(kind: PrimitiveKind) -> &'static str {
2540    use PrimitiveKind::*;
2541    match kind {
2542        Boolean => "Whether this holds (true or false).",
2543        Number => "A dimensionless number.",
2544        NumberRange => "The lower and upper bound of the number range.",
2545        Text => "A text value.",
2546        Measure => "A numeric amount in one of this type's units.",
2547        MeasureRange => "The lower and upper bound of the measure range.",
2548        Ratio => "A ratio in one of this type's units (e.g. percent).",
2549        RatioRange => "The lower and upper bound of the ratio range.",
2550        Date => "A date, or a date and time with optional timezone.",
2551        DateRange => "The start date and end date of the date range.",
2552        Time => "A time of day, with optional timezone.",
2553        TimeRange => "The start time and end time of the time range.",
2554    }
2555}
2556
2557impl TypeSpecification {
2558    pub fn boolean() -> Self {
2559        TypeSpecification::Boolean {
2560            help: default_help_for_primitive(PrimitiveKind::Boolean).to_string(),
2561        }
2562    }
2563    pub fn measure() -> Self {
2564        TypeSpecification::Measure {
2565            minimum: None,
2566            maximum: None,
2567            units: MeasureUnits::new(),
2568            traits: Vec::new(),
2569            decomposition: None,
2570            unit: None,
2571            help: default_help_for_primitive(PrimitiveKind::Measure).to_string(),
2572        }
2573    }
2574    pub fn number() -> Self {
2575        TypeSpecification::Number {
2576            minimum: None,
2577            maximum: None,
2578            decimals: None,
2579            help: default_help_for_primitive(PrimitiveKind::Number).to_string(),
2580        }
2581    }
2582    pub fn number_range() -> Self {
2583        TypeSpecification::NumberRange {
2584            lower: None,
2585            upper: None,
2586            minimum: None,
2587            maximum: None,
2588            help: default_help_for_primitive(PrimitiveKind::NumberRange).to_string(),
2589        }
2590    }
2591    pub fn ratio() -> Self {
2592        TypeSpecification::Ratio {
2593            minimum: None,
2594            maximum: None,
2595            units: RatioUnits(vec![
2596                RatioUnit {
2597                    name: "percent".to_string(),
2598                    value: crate::computation::rational::rational_new(100, 1),
2599                    minimum: None,
2600                    maximum: None,
2601                    suggestion_magnitude: None,
2602                },
2603                RatioUnit {
2604                    name: "permille".to_string(),
2605                    value: crate::computation::rational::rational_new(1000, 1),
2606                    minimum: None,
2607                    maximum: None,
2608                    suggestion_magnitude: None,
2609                },
2610            ]),
2611            unit: None,
2612            help: default_help_for_primitive(PrimitiveKind::Ratio).to_string(),
2613        }
2614    }
2615    pub fn ratio_range() -> Self {
2616        TypeSpecification::RatioRange {
2617            lower: None,
2618            upper: None,
2619            minimum: None,
2620            maximum: None,
2621            units: match TypeSpecification::ratio() {
2622                TypeSpecification::Ratio { units, .. } => units,
2623                _ => unreachable!("BUG: ratio constructor must return a ratio type"),
2624            },
2625            help: default_help_for_primitive(PrimitiveKind::RatioRange).to_string(),
2626        }
2627    }
2628    pub fn text() -> Self {
2629        TypeSpecification::Text {
2630            length: None,
2631            help: default_help_for_primitive(PrimitiveKind::Text).to_string(),
2632        }
2633    }
2634    pub fn date() -> Self {
2635        TypeSpecification::Date {
2636            minimum: None,
2637            maximum: None,
2638            help: default_help_for_primitive(PrimitiveKind::Date).to_string(),
2639        }
2640    }
2641    pub fn date_range() -> Self {
2642        TypeSpecification::DateRange {
2643            lower: None,
2644            upper: None,
2645            minimum: None,
2646            maximum: None,
2647            help: default_help_for_primitive(PrimitiveKind::DateRange).to_string(),
2648        }
2649    }
2650    pub fn time() -> Self {
2651        TypeSpecification::Time {
2652            minimum: None,
2653            maximum: None,
2654            help: default_help_for_primitive(PrimitiveKind::Time).to_string(),
2655        }
2656    }
2657    pub fn time_range() -> Self {
2658        TypeSpecification::TimeRange {
2659            lower: None,
2660            upper: None,
2661            minimum: None,
2662            maximum: None,
2663            help: default_help_for_primitive(PrimitiveKind::TimeRange).to_string(),
2664        }
2665    }
2666    pub fn measure_range() -> Self {
2667        TypeSpecification::MeasureRange {
2668            lower: None,
2669            upper: None,
2670            minimum: None,
2671            maximum: None,
2672            units: MeasureUnits::new(),
2673            decomposition: None,
2674            help: default_help_for_primitive(PrimitiveKind::MeasureRange).to_string(),
2675        }
2676    }
2677
2678    /// Element spec for a range type (e.g. `MeasureRange` → `Measure`).
2679    #[must_use]
2680    pub fn element_from_range(&self) -> Option<Self> {
2681        match self {
2682            TypeSpecification::NumberRange { lower, upper, .. } => {
2683                Some(TypeSpecification::Number {
2684                    minimum: lower.clone(),
2685                    maximum: upper.clone(),
2686                    decimals: None,
2687                    help: String::new(),
2688                })
2689            }
2690            TypeSpecification::MeasureRange {
2691                lower,
2692                upper,
2693                units,
2694                decomposition,
2695                ..
2696            } => Some(TypeSpecification::Measure {
2697                minimum: lower.clone(),
2698                maximum: upper.clone(),
2699                units: units.clone(),
2700                traits: Vec::new(),
2701                decomposition: decomposition.clone(),
2702                unit: None,
2703                help: String::new(),
2704            }),
2705            TypeSpecification::DateRange { lower, upper, .. } => Some(TypeSpecification::Date {
2706                minimum: lower.clone(),
2707                maximum: upper.clone(),
2708                help: String::new(),
2709            }),
2710            TypeSpecification::TimeRange { lower, upper, .. } => Some(TypeSpecification::Time {
2711                minimum: lower.clone(),
2712                maximum: upper.clone(),
2713                help: String::new(),
2714            }),
2715            TypeSpecification::RatioRange {
2716                lower,
2717                upper,
2718                units,
2719                ..
2720            } => Some(TypeSpecification::Ratio {
2721                minimum: lower.clone(),
2722                maximum: upper.clone(),
2723                units: units.clone(),
2724                unit: None,
2725                help: String::new(),
2726            }),
2727            _ => None,
2728        }
2729    }
2730
2731    /// Range spec for an element type (e.g. `Measure` → `MeasureRange`).
2732    #[must_use]
2733    pub fn range_from_element(&self) -> Option<Self> {
2734        match self {
2735            TypeSpecification::Number {
2736                minimum, maximum, ..
2737            } => Some(TypeSpecification::NumberRange {
2738                lower: minimum.clone(),
2739                upper: maximum.clone(),
2740                minimum: None,
2741                maximum: None,
2742                help: default_help_for_primitive(PrimitiveKind::NumberRange).to_string(),
2743            }),
2744            TypeSpecification::Measure {
2745                minimum,
2746                maximum,
2747                units,
2748                decomposition,
2749                ..
2750            } => Some(TypeSpecification::MeasureRange {
2751                lower: minimum.clone(),
2752                upper: maximum.clone(),
2753                minimum: None,
2754                maximum: None,
2755                units: units.clone(),
2756                decomposition: decomposition.clone(),
2757                help: default_help_for_primitive(PrimitiveKind::MeasureRange).to_string(),
2758            }),
2759            TypeSpecification::Date {
2760                minimum, maximum, ..
2761            } => Some(TypeSpecification::DateRange {
2762                lower: minimum.clone(),
2763                upper: maximum.clone(),
2764                minimum: None,
2765                maximum: None,
2766                help: default_help_for_primitive(PrimitiveKind::DateRange).to_string(),
2767            }),
2768            TypeSpecification::Time {
2769                minimum, maximum, ..
2770            } => Some(TypeSpecification::TimeRange {
2771                lower: minimum.clone(),
2772                upper: maximum.clone(),
2773                minimum: None,
2774                maximum: None,
2775                help: default_help_for_primitive(PrimitiveKind::TimeRange).to_string(),
2776            }),
2777            TypeSpecification::Ratio {
2778                minimum,
2779                maximum,
2780                units,
2781                ..
2782            } => Some(TypeSpecification::RatioRange {
2783                lower: minimum.clone(),
2784                upper: maximum.clone(),
2785                minimum: None,
2786                maximum: None,
2787                units: units.clone(),
2788                help: default_help_for_primitive(PrimitiveKind::RatioRange).to_string(),
2789            }),
2790            _ => None,
2791        }
2792    }
2793
2794    /// Type-level minimum as decimal: bare number bound, ratio canonical fraction, or
2795    /// measure magnitude in the declaring unit (unit tag ignored). Interactive prompts that
2796    /// ask for a selected-unit magnitude must use [`crate::RatioUnit`] /
2797    /// [`crate::MeasureUnit`] decimals after unit selection instead.
2798    #[must_use]
2799    pub fn minimum_decimal(&self) -> Option<Decimal> {
2800        match self {
2801            TypeSpecification::Number { minimum, .. }
2802            | TypeSpecification::Ratio { minimum, .. } => minimum.as_ref().map(|bound| {
2803                bound
2804                    .try_to_decimal()
2805                    .expect("BUG: planned minimum must convert to decimal")
2806            }),
2807            TypeSpecification::Measure { minimum, .. } => minimum.as_ref().map(|(bound, _)| {
2808                bound
2809                    .try_to_decimal()
2810                    .expect("BUG: planned minimum must convert to decimal")
2811            }),
2812            _ => None,
2813        }
2814    }
2815
2816    /// Type-level maximum as decimal: bare number bound, ratio canonical fraction, or
2817    /// measure magnitude in the declaring unit (unit tag ignored). Interactive prompts that
2818    /// ask for a selected-unit magnitude must use [`crate::RatioUnit`] /
2819    /// [`crate::MeasureUnit`] decimals after unit selection instead.
2820    #[must_use]
2821    pub fn maximum_decimal(&self) -> Option<Decimal> {
2822        match self {
2823            TypeSpecification::Number { maximum, .. }
2824            | TypeSpecification::Ratio { maximum, .. } => maximum.as_ref().map(|bound| {
2825                bound
2826                    .try_to_decimal()
2827                    .expect("BUG: planned maximum must convert to decimal")
2828            }),
2829            TypeSpecification::Measure { maximum, .. } => maximum.as_ref().map(|(bound, _)| {
2830                bound
2831                    .try_to_decimal()
2832                    .expect("BUG: planned maximum must convert to decimal")
2833            }),
2834            _ => None,
2835        }
2836    }
2837
2838    pub fn veto() -> Self {
2839        TypeSpecification::Veto { message: None }
2840    }
2841
2842    /// Apply a single constraint command to this spec.
2843    ///
2844    /// The `declared_suggestion` and `declared_value` out-parameters receive default values
2845    /// (if the command is `Suggest` or `With`), encoded as [`RawSuggestion`]. Defaults are
2846    /// owned by the data binding or typedef entry, not by the type specification itself;
2847    /// callers thread `&mut Option<RawSuggestion>` for each across constraint applications
2848    /// for one declaration. Duplicate `-> suggest` / `-> with` / `minimum` / `maximum` /
2849    /// `decimals` on the same declaration are rejected by the caller seen-set before this
2850    /// runs. A child typedef may override an inherited suggest, with, or bound with one
2851    /// command of that kind. Measure scalars stay raw until unit factors are resolved;
2852    /// callers convert via [`bound_value_kind_from_raw_suggestion`].
2853    pub fn apply_constraint(
2854        &mut self,
2855        names: ConstraintNames<'_>,
2856        command: TypeConstraintCommand,
2857        args: &[CommandArg],
2858        declared_suggestion: &mut Option<RawSuggestion>,
2859        declared_value: &mut Option<RawSuggestion>,
2860        resolve_unit: Option<&UnitTokenResolver<'_>>,
2861    ) -> Result<(), String> {
2862        let type_name = names.type_name;
2863        if command == TypeConstraintCommand::With
2864            && args.len() > 1
2865            && !matches!(self, TypeSpecification::List { .. })
2866        {
2867            return Err(format!("`-> with` on {self} takes exactly one value"));
2868        }
2869        if command == TypeConstraintCommand::Trait
2870            && !matches!(&self, TypeSpecification::Measure { .. })
2871        {
2872            return Err("trait command is only valid on measure types".to_string());
2873        }
2874        match self {
2875            TypeSpecification::Boolean { help } => match command {
2876                TypeConstraintCommand::Help => {
2877                    apply_type_help_command(help, args)?;
2878                }
2879                TypeConstraintCommand::Suggest | TypeConstraintCommand::With => {
2880                    let (target, cmd) = match command {
2881                        TypeConstraintCommand::Suggest => (&mut *declared_suggestion, "suggest"),
2882                        TypeConstraintCommand::With => (&mut *declared_value, "with"),
2883                        _ => unreachable!("BUG: only Suggest or With in this arm"),
2884                    };
2885                    let lit = require_literal(args, cmd)?;
2886                    reject_calendar_for_suggestion(
2887                        lit,
2888                        type_name,
2889                        SuggestionExpectation::Boolean,
2890                        None,
2891                    )?;
2892                    match lit {
2893                        crate::literals::Value::Boolean(bv) => {
2894                            *target =
2895                                Some(RawSuggestion::Value(ValueKind::Boolean(bool::from(bv))));
2896                        }
2897                        _ => {
2898                            return Err(
2899                                "Please provide true or false, for example `-> suggest true`."
2900                                    .to_string(),
2901                            );
2902                        }
2903                    }
2904                }
2905                other => {
2906                    return Err(format!(
2907                        "Invalid command '{}' for boolean type. Valid commands: help, suggest, with",
2908                        other
2909                    ));
2910                }
2911            },
2912            TypeSpecification::Measure {
2913                minimum,
2914                maximum,
2915                units,
2916                traits,
2917                help,
2918                ..
2919            } => match command {
2920                TypeConstraintCommand::Decimals => {
2921                    return Err(decimals_depend_on_the_unit_error(
2922                        "measure",
2923                        names,
2924                        args,
2925                        units.0.first().map(|unit| unit.name.as_str()),
2926                    )?);
2927                }
2928                TypeConstraintCommand::Unit => match args {
2929                    [CommandArg::Label(name), CommandArg::UnitExpr(crate::parsing::ast::UnitArg::Reference(reference))] =>
2930                    {
2931                        let unit_name = name.clone();
2932                        let written = reference.to_string();
2933                        if let Some(existing) = units.0.iter().find(|u| u.name == unit_name) {
2934                            let same = match &existing.scale {
2935                                UnitScale::Unresolved {
2936                                    segments,
2937                                    name: target_name,
2938                                    ..
2939                                } => {
2940                                    segments == &reference.segments
2941                                        && target_name == &reference.name
2942                                }
2943                                UnitScale::Literal(_)
2944                                | UnitScale::Compound { .. }
2945                                | UnitScale::Reference { .. } => false,
2946                            };
2947                            if !same {
2948                                return Err(format!(
2949                                        "Unit '{unit_name}' is already defined in this type's inherited units; \
2950                                         cannot change factor or decomposition. Add a new unit name instead."
2951                                    ));
2952                            }
2953                        } else {
2954                            units.0.push(MeasureUnit::from_reference(
2955                                unit_name,
2956                                written,
2957                                reference.segments.clone(),
2958                                reference.name.clone(),
2959                            ));
2960                        }
2961                    }
2962                    [CommandArg::Label(name), CommandArg::UnitExpr(crate::parsing::ast::UnitArg::Factor(value))] =>
2963                    {
2964                        apply_measure_unit_factor(units, name.clone(), *value, Vec::new())?;
2965                    }
2966                    [CommandArg::Label(name), CommandArg::UnitExpr(crate::parsing::ast::UnitArg::Expr(prefix, factors))] =>
2967                    {
2968                        let derived_measure_factors: Vec<(String, i32)> = factors
2969                            .iter()
2970                            .map(|f| (f.measure_ref.clone(), f.exp))
2971                            .collect();
2972                        apply_measure_unit_factor(
2973                            units,
2974                            name.clone(),
2975                            *prefix,
2976                            derived_measure_factors,
2977                        )?;
2978                    }
2979                    _ => {
2980                        return Err(
2981                                "unit requires a unit name followed by a conversion factor, compound unit expression, or number reference (e.g., 'unit eur 1.00', 'unit mps meter/second', 'unit gbp rate')"
2982                                    .to_string(),
2983                            );
2984                    }
2985                },
2986                TypeConstraintCommand::Trait => {
2987                    let measure_trait = parse_measure_trait(args)?;
2988                    if traits.contains(&measure_trait) {
2989                        return Err(format!(
2990                            "Duplicate trait '{}' for measure type.",
2991                            measure_trait_name(measure_trait)
2992                        ));
2993                    }
2994                    if measure_trait == MeasureTrait::Duration {
2995                        validate_duration_trait_requirements(units)?;
2996                    }
2997                    if measure_trait == MeasureTrait::Calendar {
2998                        validate_calendar_trait_requirements(units)?;
2999                    }
3000                    traits.push(measure_trait);
3001                }
3002                TypeConstraintCommand::Minimum => {
3003                    *minimum = Some(parse_measure_declared_bound(
3004                        args, "minimum", units, type_name,
3005                    )?);
3006                }
3007                TypeConstraintCommand::Maximum => {
3008                    *maximum = Some(parse_measure_declared_bound(
3009                        args, "maximum", units, type_name,
3010                    )?);
3011                }
3012                TypeConstraintCommand::Help => {
3013                    apply_type_help_command(help, args)?;
3014                }
3015                TypeConstraintCommand::Suggest | TypeConstraintCommand::With => {
3016                    let (target, cmd) = match command {
3017                        TypeConstraintCommand::Suggest => (&mut *declared_suggestion, "suggest"),
3018                        TypeConstraintCommand::With => (&mut *declared_value, "with"),
3019                        _ => unreachable!("BUG: only Suggest or With in this arm"),
3020                    };
3021                    let lit = require_literal(args, cmd)?;
3022                    if !traits.contains(&MeasureTrait::Calendar) {
3023                        reject_calendar_for_suggestion(
3024                            lit,
3025                            type_name,
3026                            SuggestionExpectation::MeasureUnits,
3027                            Some(units),
3028                        )?;
3029                    }
3030                    match lit {
3031                        crate::literals::Value::NumberWithUnit(n, unit_name) => {
3032                            if units
3033                                .get(unit_name)
3034                                .is_ok_and(crate::literals::MeasureUnit::is_dynamic)
3035                            {
3036                                *target = Some(RawSuggestion::Measure {
3037                                    magnitude: lift_parser_decimal(*n)?,
3038                                    unit_name: unit_name.clone(),
3039                                });
3040                            } else {
3041                                let (magnitude, unit_name) =
3042                                    parse_measure_declared_bound(args, cmd, units, type_name)?;
3043                                *target = Some(RawSuggestion::Measure {
3044                                    magnitude,
3045                                    unit_name,
3046                                });
3047                            }
3048                        }
3049                        _ => {
3050                            return Err(measure_suggestion_wrong_shape_error(type_name, traits));
3051                        }
3052                    }
3053                }
3054                _ => {
3055                    return Err(format!(
3056                        "Invalid command '{}' for measure type. Valid commands: unit, trait, minimum, maximum, help, suggest, with",
3057                        command
3058                    ));
3059                }
3060            },
3061            TypeSpecification::Number {
3062                decimals,
3063                minimum,
3064                maximum,
3065                help,
3066            } => match command {
3067                TypeConstraintCommand::Decimals => {
3068                    let d = require_decimal_literal(args, "decimals")?;
3069                    *decimals = Some(decimal_to_u8(d, "decimals")?);
3070                }
3071                TypeConstraintCommand::Unit => {
3072                    return Err(
3073                        "Invalid command 'unit' for number type. Number types are dimensionless and cannot have units. Use 'measure' type instead.".to_string()
3074                    );
3075                }
3076                TypeConstraintCommand::Minimum => {
3077                    *minimum = Some(require_decimal_literal(args, "minimum")?);
3078                }
3079                TypeConstraintCommand::Maximum => {
3080                    *maximum = Some(require_decimal_literal(args, "maximum")?);
3081                }
3082                TypeConstraintCommand::Help => {
3083                    apply_type_help_command(help, args)?;
3084                }
3085                TypeConstraintCommand::Suggest | TypeConstraintCommand::With => {
3086                    let (target, cmd) = match command {
3087                        TypeConstraintCommand::Suggest => (&mut *declared_suggestion, "suggest"),
3088                        TypeConstraintCommand::With => (&mut *declared_value, "with"),
3089                        _ => unreachable!("BUG: only Suggest or With in this arm"),
3090                    };
3091                    let lit = require_literal(args, cmd)?;
3092                    reject_calendar_for_suggestion(
3093                        lit,
3094                        type_name,
3095                        SuggestionExpectation::Number,
3096                        None,
3097                    )?;
3098                    match lit {
3099                        crate::literals::Value::Number(d) => {
3100                            *target = Some(RawSuggestion::Value(ValueKind::Number(
3101                                lift_parser_decimal(*d)?,
3102                            )));
3103                        }
3104                        _ => {
3105                            return Err(
3106                                "Please provide a number, for example `-> suggest 42`.".to_string()
3107                            );
3108                        }
3109                    }
3110                }
3111                _ => {
3112                    return Err(format!(
3113                        "Invalid command '{}' for number type. Valid commands: minimum, maximum, decimals, help, suggest, with",
3114                        command
3115                    ));
3116                }
3117            },
3118            TypeSpecification::NumberRange {
3119                lower,
3120                upper,
3121                minimum,
3122                maximum,
3123                help,
3124            } => match command {
3125                TypeConstraintCommand::Lower => {
3126                    *lower = Some(require_decimal_literal(args, "lower")?);
3127                }
3128                TypeConstraintCommand::Upper => {
3129                    *upper = Some(require_decimal_literal(args, "upper")?);
3130                }
3131                TypeConstraintCommand::Minimum => {
3132                    let width = require_decimal_literal(args, "minimum")?;
3133                    reject_negative_width_magnitude(&width, "minimum")?;
3134                    *minimum = Some(width);
3135                }
3136                TypeConstraintCommand::Maximum => {
3137                    let width = require_decimal_literal(args, "maximum")?;
3138                    reject_negative_width_magnitude(&width, "maximum")?;
3139                    *maximum = Some(width);
3140                }
3141                TypeConstraintCommand::Help => {
3142                    apply_type_help_command(help, args)?;
3143                }
3144                TypeConstraintCommand::Suggest | TypeConstraintCommand::With => {
3145                    let target = match command {
3146                        TypeConstraintCommand::Suggest => &mut *declared_suggestion,
3147                        TypeConstraintCommand::With => &mut *declared_value,
3148                        _ => unreachable!("BUG: only Suggest or With in this arm"),
3149                    };
3150                    let (left, right) = require_suggestion_range_endpoints(
3151                        args,
3152                        type_name,
3153                        SuggestionExpectation::NumberRange,
3154                        None,
3155                    )?;
3156                    let left = literal_value_from_parser_value(left)?;
3157                    let right = literal_value_from_parser_value(right)?;
3158                    if !left.lemma_type.is_number() || !right.lemma_type.is_number() {
3159                        return Err(
3160                            "Please provide a number range, for example `-> suggest 10...100`."
3161                                .to_string(),
3162                        );
3163                    }
3164                    *target = Some(RawSuggestion::Value(ValueKind::Range(
3165                        Box::new(left),
3166                        Box::new(right),
3167                    )));
3168                }
3169                _ => {
3170                    return Err(format!(
3171                        "Invalid command '{}' for number range type. Valid commands: lower, upper, minimum, maximum, help, suggest, with",
3172                        command
3173                    ));
3174                }
3175            },
3176            TypeSpecification::Ratio {
3177                minimum,
3178                maximum,
3179                units,
3180                unit: _,
3181                help,
3182            } => match command {
3183                TypeConstraintCommand::Decimals => {
3184                    return Err(decimals_depend_on_the_unit_error(
3185                        "ratio",
3186                        names,
3187                        args,
3188                        units.0.first().map(|unit| unit.name.as_str()),
3189                    )?);
3190                }
3191                TypeConstraintCommand::Unit => {
3192                    let (unit_name, value_dec) = match args {
3193                        [CommandArg::Label(name), CommandArg::UnitExpr(crate::parsing::ast::UnitArg::Factor(v))] => {
3194                            (name.clone(), *v)
3195                        }
3196                        _ => {
3197                            return Err(
3198                                "unit requires a unit name followed by a numeric conversion factor (e.g., '-> unit percent: 100'). Compound unit expressions are not supported for ratio types."
3199                                    .to_string(),
3200                            );
3201                        }
3202                    };
3203                    let value = crate::computation::rational::decimal_to_rational(value_dec)
3204                        .map_err(|failure| {
3205                            format!(
3206                                "ratio unit value is not exactly representable as a rational: {}",
3207                                failure
3208                            )
3209                        })?;
3210                    if let Some(existing) = units.0.iter().find(|u| u.name == unit_name) {
3211                        if existing.value != value {
3212                            return Err(format!(
3213                                "Unit '{unit_name}' is already defined in this type's inherited units; \
3214                                 cannot change factor. Add a new unit name instead."
3215                            ));
3216                        }
3217                    } else {
3218                        units.0.push(RatioUnit {
3219                            name: unit_name,
3220                            value,
3221                            minimum: None,
3222                            maximum: None,
3223                            suggestion_magnitude: None,
3224                        });
3225                    }
3226                }
3227                TypeConstraintCommand::Minimum => {
3228                    let canonical = ratio_bound_to_canonical_rational(args, "minimum", units)?;
3229                    sync_ratio_units_from_canonical(
3230                        units,
3231                        &canonical,
3232                        UnitConstraintField::Minimum,
3233                    )?;
3234                    *minimum = Some(canonical);
3235                }
3236                TypeConstraintCommand::Maximum => {
3237                    let canonical = ratio_bound_to_canonical_rational(args, "maximum", units)?;
3238                    sync_ratio_units_from_canonical(
3239                        units,
3240                        &canonical,
3241                        UnitConstraintField::Maximum,
3242                    )?;
3243                    *maximum = Some(canonical);
3244                }
3245                TypeConstraintCommand::Help => {
3246                    apply_type_help_command(help, args)?;
3247                }
3248                TypeConstraintCommand::Suggest | TypeConstraintCommand::With => {
3249                    let (target, cmd) = match command {
3250                        TypeConstraintCommand::Suggest => (&mut *declared_suggestion, "suggest"),
3251                        TypeConstraintCommand::With => (&mut *declared_value, "with"),
3252                        _ => unreachable!("BUG: only Suggest or With in this arm"),
3253                    };
3254                    let lit = require_literal(args, cmd)?;
3255                    reject_calendar_for_suggestion(
3256                        lit,
3257                        type_name,
3258                        SuggestionExpectation::Ratio,
3259                        None,
3260                    )?;
3261                    match lit {
3262                        crate::literals::Value::NumberWithUnit(_, unit_name) => {
3263                            let element_type = LemmaType::primitive(TypeSpecification::Ratio {
3264                                minimum: minimum.clone(),
3265                                maximum: maximum.clone(),
3266                                units: units.clone(),
3267                                unit: None,
3268                                help: help.clone(),
3269                            });
3270                            let value = parser_value_to_value_kind(lit, &element_type, None)?;
3271                            sync_ratio_suggestion_units(units, &value)?;
3272                            *target = Some(RawSuggestion::UnitBound {
3273                                value,
3274                                unit_name: unit_name.clone(),
3275                            });
3276                        }
3277                        other => {
3278                            return Err(format!(
3279                                "suggest requires a ratio literal with a unit, got {}. Please provide a ratio value with a unit, for example `-> suggest 25%`.",
3280                                value_kind_name(other)
3281                            ));
3282                        }
3283                    }
3284                }
3285                _ => {
3286                    return Err(format!(
3287                        "Invalid command '{}' for ratio type. Valid commands: unit, minimum, maximum, help, suggest, with",
3288                        command
3289                    ));
3290                }
3291            },
3292            TypeSpecification::RatioRange {
3293                lower,
3294                upper,
3295                minimum,
3296                maximum,
3297                units,
3298                help,
3299            } => match command {
3300                TypeConstraintCommand::Unit => {
3301                    return Err(format!(
3302                        "'unit' is not allowed on 'ratio range' type '{type_name}'. Declare units on a ratio type and write 'data x: <that type> range'."
3303                    ));
3304                }
3305                TypeConstraintCommand::Lower => {
3306                    *lower = Some(ratio_bound_to_canonical_rational(args, "lower", units)?);
3307                }
3308                TypeConstraintCommand::Upper => {
3309                    *upper = Some(ratio_bound_to_canonical_rational(args, "upper", units)?);
3310                }
3311                TypeConstraintCommand::Minimum => {
3312                    let width = ratio_bound_to_canonical_rational(args, "minimum", units)?;
3313                    reject_negative_width_magnitude(&width, "minimum")?;
3314                    *minimum = Some(width);
3315                }
3316                TypeConstraintCommand::Maximum => {
3317                    let width = ratio_bound_to_canonical_rational(args, "maximum", units)?;
3318                    reject_negative_width_magnitude(&width, "maximum")?;
3319                    *maximum = Some(width);
3320                }
3321                TypeConstraintCommand::Help => {
3322                    apply_type_help_command(help, args)?;
3323                }
3324                TypeConstraintCommand::Suggest | TypeConstraintCommand::With => {
3325                    let target = match command {
3326                        TypeConstraintCommand::Suggest => &mut *declared_suggestion,
3327                        TypeConstraintCommand::With => &mut *declared_value,
3328                        _ => unreachable!("BUG: only Suggest or With in this arm"),
3329                    };
3330                    let (left, right) = require_suggestion_range_endpoints(
3331                        args,
3332                        type_name,
3333                        SuggestionExpectation::RatioRange,
3334                        None,
3335                    )?;
3336                    let element_type = LemmaType::primitive(
3337                        TypeSpecification::RatioRange {
3338                            lower: lower.clone(),
3339                            upper: upper.clone(),
3340                            minimum: minimum.clone(),
3341                            maximum: maximum.clone(),
3342                            units: units.clone(),
3343                            help: help.clone(),
3344                        }
3345                        .element_from_range()
3346                        .expect("BUG: RatioRange must define element_from_range"),
3347                    );
3348                    let left = lift_range_endpoint(left, &element_type, resolve_unit)?;
3349                    let right = lift_range_endpoint(right, &element_type, resolve_unit)?;
3350                    if !value_kind_matches_spec(&left.value, &element_type.specifications)
3351                        || !value_kind_matches_spec(&right.value, &element_type.specifications)
3352                        || !matches!(&left.value, ValueKind::Ratio(_))
3353                        || !matches!(&right.value, ValueKind::Ratio(_))
3354                    {
3355                        return Err(
3356                            "Please provide a ratio range, for example `-> suggest 10%...50%`."
3357                                .to_string(),
3358                        );
3359                    }
3360                    *target = Some(RawSuggestion::Value(ValueKind::Range(
3361                        Box::new(left),
3362                        Box::new(right),
3363                    )));
3364                }
3365                _ => {
3366                    return Err(format!(
3367                        "Invalid command '{}' for ratio range type. Valid commands: lower, upper, minimum, maximum, help, suggest, with",
3368                        command
3369                    ));
3370                }
3371            },
3372            TypeSpecification::Text { length, help } => match command {
3373                TypeConstraintCommand::Length => {
3374                    let d = require_decimal_literal(args, "length")?;
3375                    *length = Some(decimal_to_usize(d, "length")?);
3376                }
3377                TypeConstraintCommand::Help => {
3378                    apply_type_help_command(help, args)?;
3379                }
3380                TypeConstraintCommand::Suggest | TypeConstraintCommand::With => {
3381                    let (target, cmd) = match command {
3382                        TypeConstraintCommand::Suggest => (&mut *declared_suggestion, "suggest"),
3383                        TypeConstraintCommand::With => (&mut *declared_value, "with"),
3384                        _ => unreachable!("BUG: only Suggest or With in this arm"),
3385                    };
3386                    let lit = require_literal(args, cmd)?;
3387                    reject_calendar_for_suggestion(
3388                        lit,
3389                        type_name,
3390                        SuggestionExpectation::Text,
3391                        None,
3392                    )?;
3393                    match lit {
3394                        crate::literals::Value::Text(s) => {
3395                            *target =
3396                                Some(RawSuggestion::Value(ValueKind::Text(Arc::from(s.as_str()))));
3397                        }
3398                        _ => {
3399                            return Err(
3400                                "Please provide a text value in double quotes, for example `-> suggest \"my default value\"`."
3401                                    .to_string(),
3402                            );
3403                        }
3404                    }
3405                }
3406                _ => {
3407                    return Err(format!(
3408                        "Invalid command '{}' for text type. Valid commands: length, help, suggest, with",
3409                        command
3410                    ));
3411                }
3412            },
3413            TypeSpecification::Date {
3414                minimum,
3415                maximum,
3416                help,
3417            } => match command {
3418                TypeConstraintCommand::Minimum => {
3419                    let dt = require_date_literal(args, "minimum")?;
3420                    *minimum = Some(dt);
3421                }
3422                TypeConstraintCommand::Maximum => {
3423                    let dt = require_date_literal(args, "maximum")?;
3424                    *maximum = Some(dt);
3425                }
3426                TypeConstraintCommand::Help => {
3427                    apply_type_help_command(help, args)?;
3428                }
3429                TypeConstraintCommand::Suggest | TypeConstraintCommand::With => {
3430                    let (target, cmd) = match command {
3431                        TypeConstraintCommand::Suggest => (&mut *declared_suggestion, "suggest"),
3432                        TypeConstraintCommand::With => (&mut *declared_value, "with"),
3433                        _ => unreachable!("BUG: only Suggest or With in this arm"),
3434                    };
3435                    let lit = require_literal(args, cmd)?;
3436                    reject_calendar_for_suggestion(
3437                        lit,
3438                        type_name,
3439                        SuggestionExpectation::Date,
3440                        None,
3441                    )?;
3442                    match lit {
3443                        crate::literals::Value::Date(dt) => {
3444                            *target = Some(RawSuggestion::Value(ValueKind::Date(
3445                                date_time_to_semantic(dt),
3446                            )));
3447                        }
3448                        _ => {
3449                            return Err(
3450                                "Please provide a date, for example `-> suggest 2024-06-15`."
3451                                    .to_string(),
3452                            );
3453                        }
3454                    }
3455                }
3456                _ => {
3457                    return Err(format!(
3458                        "Invalid command '{}' for date type. Valid commands: minimum, maximum, help, suggest, with",
3459                        command
3460                    ));
3461                }
3462            },
3463            TypeSpecification::DateRange {
3464                lower,
3465                upper,
3466                minimum,
3467                maximum,
3468                help,
3469            } => match command {
3470                TypeConstraintCommand::Lower => {
3471                    *lower = Some(require_date_literal(args, "lower")?);
3472                }
3473                TypeConstraintCommand::Upper => {
3474                    *upper = Some(require_date_literal(args, "upper")?);
3475                }
3476                TypeConstraintCommand::Minimum => {
3477                    *minimum = Some(parse_unresolved_width_bound(args, "minimum")?);
3478                }
3479                TypeConstraintCommand::Maximum => {
3480                    *maximum = Some(parse_unresolved_width_bound(args, "maximum")?);
3481                }
3482                TypeConstraintCommand::Help => {
3483                    apply_type_help_command(help, args)?;
3484                }
3485                TypeConstraintCommand::Suggest | TypeConstraintCommand::With => {
3486                    let target = match command {
3487                        TypeConstraintCommand::Suggest => &mut *declared_suggestion,
3488                        TypeConstraintCommand::With => &mut *declared_value,
3489                        _ => unreachable!("BUG: only Suggest or With in this arm"),
3490                    };
3491                    let (left, right) = require_suggestion_range_endpoints(
3492                        args,
3493                        type_name,
3494                        SuggestionExpectation::DateRange,
3495                        None,
3496                    )?;
3497                    let left = literal_value_from_parser_value(left)?;
3498                    let right = literal_value_from_parser_value(right)?;
3499                    if !left.lemma_type.is_date() || !right.lemma_type.is_date() {
3500                        return Err(
3501                            "Please provide a date range, for example `-> suggest 2024-01-01...2024-12-31`."
3502                                .to_string(),
3503                        );
3504                    }
3505                    *target = Some(RawSuggestion::Value(ValueKind::Range(
3506                        Box::new(left),
3507                        Box::new(right),
3508                    )));
3509                }
3510                _ => {
3511                    return Err(format!(
3512                        "Invalid command '{}' for date range type. Valid commands: lower, upper, minimum, maximum, help, suggest, with",
3513                        command
3514                    ));
3515                }
3516            },
3517            TypeSpecification::Time {
3518                minimum,
3519                maximum,
3520                help,
3521            } => match command {
3522                TypeConstraintCommand::Minimum => {
3523                    let t = require_time_literal(args, "minimum")?;
3524                    *minimum = Some(t);
3525                }
3526                TypeConstraintCommand::Maximum => {
3527                    let t = require_time_literal(args, "maximum")?;
3528                    *maximum = Some(t);
3529                }
3530                TypeConstraintCommand::Help => {
3531                    apply_type_help_command(help, args)?;
3532                }
3533                TypeConstraintCommand::Suggest | TypeConstraintCommand::With => {
3534                    let (target, cmd) = match command {
3535                        TypeConstraintCommand::Suggest => (&mut *declared_suggestion, "suggest"),
3536                        TypeConstraintCommand::With => (&mut *declared_value, "with"),
3537                        _ => unreachable!("BUG: only Suggest or With in this arm"),
3538                    };
3539                    let lit = require_literal(args, cmd)?;
3540                    reject_calendar_for_suggestion(
3541                        lit,
3542                        type_name,
3543                        SuggestionExpectation::Time,
3544                        None,
3545                    )?;
3546                    match lit {
3547                        crate::literals::Value::Time(t) => {
3548                            *target =
3549                                Some(RawSuggestion::Value(ValueKind::Time(time_to_semantic(t))));
3550                        }
3551                        _ => {
3552                            return Err(
3553                                "Please provide a time, for example `-> suggest 09:00:00`."
3554                                    .to_string(),
3555                            );
3556                        }
3557                    }
3558                }
3559                _ => {
3560                    return Err(format!(
3561                        "Invalid command '{}' for time type. Valid commands: minimum, maximum, help, suggest, with",
3562                        command
3563                    ));
3564                }
3565            },
3566            TypeSpecification::TimeRange {
3567                lower,
3568                upper,
3569                minimum,
3570                maximum,
3571                help,
3572            } => match command {
3573                TypeConstraintCommand::Lower => {
3574                    *lower = Some(require_time_literal(args, "lower")?);
3575                }
3576                TypeConstraintCommand::Upper => {
3577                    *upper = Some(require_time_literal(args, "upper")?);
3578                }
3579                TypeConstraintCommand::Minimum => {
3580                    *minimum = Some(parse_unresolved_width_bound(args, "minimum")?);
3581                }
3582                TypeConstraintCommand::Maximum => {
3583                    *maximum = Some(parse_unresolved_width_bound(args, "maximum")?);
3584                }
3585                TypeConstraintCommand::Help => {
3586                    apply_type_help_command(help, args)?;
3587                }
3588                TypeConstraintCommand::Suggest | TypeConstraintCommand::With => {
3589                    let target = match command {
3590                        TypeConstraintCommand::Suggest => &mut *declared_suggestion,
3591                        TypeConstraintCommand::With => &mut *declared_value,
3592                        _ => unreachable!("BUG: only Suggest or With in this arm"),
3593                    };
3594                    let (left, right) = require_suggestion_range_endpoints(
3595                        args,
3596                        type_name,
3597                        SuggestionExpectation::TimeRange,
3598                        None,
3599                    )?;
3600                    let left = literal_value_from_parser_value(left)?;
3601                    let right = literal_value_from_parser_value(right)?;
3602                    if !left.lemma_type.is_time() || !right.lemma_type.is_time() {
3603                        return Err(
3604                            "Please provide a time range, for example `-> suggest 09:00...17:00`."
3605                                .to_string(),
3606                        );
3607                    }
3608                    *target = Some(RawSuggestion::Value(ValueKind::Range(
3609                        Box::new(left),
3610                        Box::new(right),
3611                    )));
3612                }
3613                _ => {
3614                    return Err(format!(
3615                        "Invalid command '{}' for time range type. Valid commands: lower, upper, minimum, maximum, help, suggest, with",
3616                        command
3617                    ));
3618                }
3619            },
3620            TypeSpecification::MeasureRange {
3621                lower,
3622                upper,
3623                minimum,
3624                maximum,
3625                units,
3626                decomposition,
3627                help,
3628            } => match command {
3629                TypeConstraintCommand::Unit => {
3630                    return Err(format!(
3631                        "'unit' is not allowed on 'measure range' type '{type_name}'. Declare units on a measure type and write 'data x: <that type> range'."
3632                    ));
3633                }
3634                TypeConstraintCommand::Lower => {
3635                    *lower = Some(parse_measure_declared_bound(
3636                        args, "lower", units, type_name,
3637                    )?);
3638                }
3639                TypeConstraintCommand::Upper => {
3640                    *upper = Some(parse_measure_declared_bound(
3641                        args, "upper", units, type_name,
3642                    )?);
3643                }
3644                TypeConstraintCommand::Minimum => {
3645                    let width = parse_measure_declared_bound(args, "minimum", units, type_name)?;
3646                    reject_negative_width_magnitude(&width.0, "minimum")?;
3647                    *minimum = Some(width);
3648                }
3649                TypeConstraintCommand::Maximum => {
3650                    let width = parse_measure_declared_bound(args, "maximum", units, type_name)?;
3651                    reject_negative_width_magnitude(&width.0, "maximum")?;
3652                    *maximum = Some(width);
3653                }
3654                TypeConstraintCommand::Help => {
3655                    apply_type_help_command(help, args)?;
3656                }
3657                TypeConstraintCommand::Suggest | TypeConstraintCommand::With => {
3658                    let target = match command {
3659                        TypeConstraintCommand::Suggest => &mut *declared_suggestion,
3660                        TypeConstraintCommand::With => &mut *declared_value,
3661                        _ => unreachable!("BUG: only Suggest or With in this arm"),
3662                    };
3663                    let (left, right) = require_suggestion_range_endpoints(
3664                        args,
3665                        type_name,
3666                        SuggestionExpectation::MeasureRange,
3667                        Some(units),
3668                    )?;
3669                    let element_type = LemmaType::primitive(
3670                        TypeSpecification::MeasureRange {
3671                            lower: lower.clone(),
3672                            upper: upper.clone(),
3673                            minimum: minimum.clone(),
3674                            maximum: maximum.clone(),
3675                            units: units.clone(),
3676                            decomposition: decomposition.clone(),
3677                            help: help.clone(),
3678                        }
3679                        .element_from_range()
3680                        .expect("BUG: MeasureRange must define element_from_range"),
3681                    );
3682                    let left = lift_range_endpoint(left, &element_type, resolve_unit)?;
3683                    let right = lift_range_endpoint(right, &element_type, resolve_unit)?;
3684                    if !value_kind_matches_spec(&left.value, &element_type.specifications)
3685                        || !value_kind_matches_spec(&right.value, &element_type.specifications)
3686                        || !matches!(&left.value, ValueKind::Measure(_))
3687                        || !matches!(&right.value, ValueKind::Measure(_))
3688                    {
3689                        return Err(format!(
3690                            "Please provide a range with units valid for '{type_name}', for example `-> suggest 30 kilogram...35 kilogram`."
3691                        ));
3692                    }
3693                    *target = Some(RawSuggestion::Value(ValueKind::Range(
3694                        Box::new(left),
3695                        Box::new(right),
3696                    )));
3697                }
3698                _ => {
3699                    return Err(format!(
3700                        "Invalid command '{}' for measure range type. Valid commands: lower, upper, minimum, maximum, help, suggest, with",
3701                        command
3702                    ));
3703                }
3704            },
3705            TypeSpecification::Veto { .. } => {
3706                return Err(format!(
3707                    "Invalid command '{}' for veto type. Veto is not a user-declarable type and cannot have constraints",
3708                    command
3709                ));
3710            }
3711            TypeSpecification::Undetermined => {
3712                return Err(format!(
3713                    "Invalid command '{}' for undetermined sentinel type. Undetermined is an internal type used during type inference and cannot have constraints",
3714                    command
3715                ));
3716            }
3717            TypeSpecification::Spec { .. } => {
3718                return Err(format!(
3719                    "Invalid command '{command}' for spec type. A spec instance has no data constraints"
3720                ));
3721            }
3722            TypeSpecification::List { element, help, .. } => match command {
3723                TypeConstraintCommand::Help => {
3724                    if matches!(element.specifications, TypeSpecification::Spec { .. }) {
3725                        apply_type_help_command(help, args)?;
3726                    } else {
3727                        let mut unused_suggestion = None;
3728                        let mut unused_value = None;
3729                        Arc::make_mut(element).specifications.apply_constraint(
3730                            names,
3731                            command,
3732                            args,
3733                            &mut unused_suggestion,
3734                            &mut unused_value,
3735                            resolve_unit,
3736                        )?;
3737                    }
3738                }
3739                TypeConstraintCommand::With => {
3740                    return Err(
3741                        "BUG: list -> with is applied before TypeSpecification::apply_constraint"
3742                            .to_string(),
3743                    );
3744                }
3745                other => {
3746                    return Err(format!(
3747                        "Invalid command '{other}' for list type. Valid commands: with, help"
3748                    ));
3749                }
3750            },
3751        }
3752        Ok(())
3753    }
3754}
3755
3756/// Parse a "number unit" string into a Measure or Ratio value according to the type.
3757/// Caller must have obtained the TypeSpecification via unit_index from the unit in the string.
3758pub fn parse_number_unit(
3759    value_str: &str,
3760    type_spec: &TypeSpecification,
3761) -> Result<crate::parsing::ast::Value, String> {
3762    use crate::literals::{NumberWithUnit, RatioLiteral};
3763    use crate::parsing::ast::Value;
3764
3765    let trimmed = value_str.trim();
3766    match type_spec {
3767        TypeSpecification::Measure { units, .. } => {
3768            if units.is_empty() {
3769                unreachable!(
3770                    "BUG: Measure type has no units; should have been validated during planning"
3771                );
3772            }
3773            match trimmed.parse::<NumberWithUnit>() {
3774                Ok(n) => {
3775                    let unit = units.get(&n.1).map_err(|e| e.to_string())?;
3776                    Ok(Value::NumberWithUnit(n.0, unit.name.clone()))
3777                }
3778                Err(e) => {
3779                    if trimmed.split_whitespace().count() == 1 && !trimmed.is_empty() {
3780                        let valid: Vec<&str> = units.iter().map(|u| u.name.as_str()).collect();
3781                        let example_unit = units
3782                            .iter()
3783                            .next()
3784                            .expect("BUG: units non-empty after guard")
3785                            .name
3786                            .as_str();
3787                        Err(format!(
3788                            "Measure value must include a unit, for example: '{} {}'. Valid units: {}.",
3789                            trimmed,
3790                            example_unit,
3791                            valid.join(", ")
3792                        ))
3793                    } else {
3794                        Err(e)
3795                    }
3796                }
3797            }
3798        }
3799        TypeSpecification::Ratio { units, .. } => {
3800            if units.is_empty() {
3801                unreachable!(
3802                    "BUG: Ratio type has no units; should have been validated during planning"
3803                );
3804            }
3805            match trimmed.parse::<RatioLiteral>()? {
3806                RatioLiteral::Bare(_) => {
3807                    Err("Ratio value requires a unit (e.g. '50%', '500 basis_points').".to_string())
3808                }
3809                RatioLiteral::Percent(n) => {
3810                    let unit = units.get("percent").map_err(|e| e.to_string())?;
3811                    Ok(Value::NumberWithUnit(n, unit.name.clone()))
3812                }
3813                RatioLiteral::Permille(n) => {
3814                    let unit = units.get("permille").map_err(|e| e.to_string())?;
3815                    Ok(Value::NumberWithUnit(n, unit.name.clone()))
3816                }
3817                RatioLiteral::Named { value, unit } => {
3818                    let resolved = units.get(&unit).map_err(|e| e.to_string())?;
3819                    Ok(Value::NumberWithUnit(value, resolved.name.clone()))
3820                }
3821            }
3822        }
3823        _ => Err("parse_number_unit only accepts Measure or Ratio type".to_string()),
3824    }
3825}
3826
3827/// Parse a string value according to a TypeSpecification.
3828/// Used to parse runtime user input into typed values.
3829pub fn parse_value_from_string(
3830    value_str: &str,
3831    type_spec: &TypeSpecification,
3832    source: &Source,
3833) -> Result<crate::parsing::ast::Value, Error> {
3834    match type_spec {
3835        TypeSpecification::NumberRange { .. }
3836        | TypeSpecification::MeasureRange { .. }
3837        | TypeSpecification::DateRange { .. }
3838        | TypeSpecification::TimeRange { .. }
3839        | TypeSpecification::RatioRange { .. } => {
3840            let element_spec = range_element_type_specification(type_spec).unwrap_or_else(|| {
3841                unreachable!(
3842                    "BUG: range_element_type_specification missing arm for known range type"
3843                )
3844            });
3845            parse_range_value_from_string(value_str, &element_spec, source)
3846        }
3847        _ => parse_scalar_value_from_string(value_str, type_spec, source),
3848    }
3849}
3850
3851fn parse_range_value_from_string(
3852    value_str: &str,
3853    element_spec: &TypeSpecification,
3854    source: &Source,
3855) -> Result<crate::parsing::ast::Value, Error> {
3856    use crate::parsing::ast::Value;
3857
3858    let to_err = |msg: String| Error::validation(msg, Some(source.clone()), None::<String>);
3859
3860    let (left_str, right_str) = value_str.split_once("...").ok_or_else(|| {
3861        to_err("Range value must use '...' between the two endpoints".to_string())
3862    })?;
3863    if left_str.trim().is_empty() || right_str.trim().is_empty() {
3864        return Err(to_err(
3865            "Range value must contain a non-empty left and right endpoint".to_string(),
3866        ));
3867    }
3868    let left = parse_scalar_value_from_string(left_str.trim(), element_spec, source)?;
3869    let right = parse_scalar_value_from_string(right_str.trim(), element_spec, source)?;
3870    Ok(Value::Range(Box::new(left), Box::new(right)))
3871}
3872
3873fn parse_scalar_value_from_string(
3874    value_str: &str,
3875    type_spec: &TypeSpecification,
3876    source: &Source,
3877) -> Result<crate::parsing::ast::Value, Error> {
3878    use crate::parsing::ast::Value;
3879
3880    let to_err = |msg: String| Error::validation(msg, Some(source.clone()), None::<String>);
3881
3882    match type_spec {
3883        TypeSpecification::Text { .. } => value_str
3884            .parse::<crate::literals::TextLiteral>()
3885            .map(|t| Value::Text(t.0))
3886            .map_err(to_err),
3887        TypeSpecification::Number { .. } => value_str
3888            .parse::<crate::literals::NumberLiteral>()
3889            .map(|n| Value::Number(n.0))
3890            .map_err(to_err),
3891        TypeSpecification::Measure { .. } => {
3892            parse_number_unit(value_str, type_spec).map_err(to_err)
3893        }
3894        TypeSpecification::Boolean { .. } => value_str
3895            .parse::<BooleanValue>()
3896            .map(Value::Boolean)
3897            .map_err(to_err),
3898        TypeSpecification::Date { .. } => {
3899            let date = value_str.parse::<DateTimeValue>().map_err(to_err)?;
3900            Ok(Value::Date(date))
3901        }
3902        TypeSpecification::Time { .. } => {
3903            let time = value_str.parse::<TimeValue>().map_err(to_err)?;
3904            Ok(Value::Time(time))
3905        }
3906        TypeSpecification::Ratio { .. } => {
3907            parse_number_unit(value_str, type_spec).map_err(to_err)
3908        }
3909        TypeSpecification::NumberRange { .. }
3910        | TypeSpecification::MeasureRange { .. }
3911        | TypeSpecification::DateRange { .. }
3912        | TypeSpecification::TimeRange { .. }
3913        | TypeSpecification::RatioRange { .. } => {
3914            unreachable!("BUG: range types are parsed by parse_range_value_from_string")
3915        }
3916        TypeSpecification::Veto { .. } => Err(to_err(
3917            "Veto type cannot be parsed from string".to_string(),
3918        )),
3919        TypeSpecification::Undetermined => unreachable!(
3920            "BUG: parse_value_from_string called with Undetermined sentinel type; this type exists only during type inference"
3921        ),
3922        TypeSpecification::Spec { .. } => Err(to_err(
3923            "spec values are not evaluation-data scalars".to_string(),
3924        )),
3925        TypeSpecification::List { .. } => Err(to_err(
3926            "list values are not evaluation-data scalars".to_string(),
3927        )),
3928    }
3929}
3930
3931// -----------------------------------------------------------------------------
3932// Semantic value types (no parser dependency - used by evaluation, inversion, etc.)
3933// -----------------------------------------------------------------------------
3934
3935#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3936pub enum SemanticCalendarUnit {
3937    Month,
3938    Year,
3939}
3940
3941impl fmt::Display for SemanticCalendarUnit {
3942    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3943        let s = match self {
3944            SemanticCalendarUnit::Month => "month",
3945            SemanticCalendarUnit::Year => "year",
3946        };
3947        write!(f, "{}", s)
3948    }
3949}
3950
3951pub fn semantic_calendar_unit_from_unit_name(unit_name: &str) -> SemanticCalendarUnit {
3952    match unit_name {
3953        "month" => SemanticCalendarUnit::Month,
3954        "year" => SemanticCalendarUnit::Year,
3955        other => unreachable!(
3956            "BUG: calendar measure signature unit must be month or year, got '{other}'"
3957        ),
3958    }
3959}
3960
3961pub fn semantic_calendar_unit_from_measure_signature(
3962    signature: &[(String, i32)],
3963) -> SemanticCalendarUnit {
3964    let unit_name = signature
3965        .first()
3966        .map(|(name, _)| name.as_str())
3967        .expect("BUG: calendar measure must carry a unit signature");
3968    semantic_calendar_unit_from_unit_name(unit_name)
3969}
3970
3971pub fn semantic_calendar_unit_from_measure_type(lemma_type: &LemmaType) -> SemanticCalendarUnit {
3972    if !lemma_type.is_calendar_like() {
3973        unreachable!(
3974            "BUG: semantic_calendar_unit_from_measure_type called on non-calendar type {}",
3975            lemma_type.name()
3976        );
3977    }
3978    let signature = lemma_type.measure_runtime_signature();
3979    if signature.is_empty() {
3980        return SemanticCalendarUnit::Month;
3981    }
3982    semantic_calendar_unit_from_measure_signature(&signature)
3983}
3984
3985/// Target type for `as` casts (semantic; used by evaluation/computation).
3986#[derive(Debug, Clone, PartialEq, Eq)]
3987pub enum SemanticConversionTarget {
3988    Type(ConversionTypeKind),
3989    /// `number as eur` — construct, convert, relabel, or range-span into `unit_name`.
3990    Unit {
3991        unit_name: String,
3992        /// Measure/ratio type resolved in the spec where the conversion was written.
3993        owning_type: Arc<LemmaType>,
3994    },
3995}
3996
3997impl std::hash::Hash for SemanticConversionTarget {
3998    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
3999        match self {
4000            Self::Type(kind) => {
4001                0u8.hash(state);
4002                kind.hash(state);
4003            }
4004            Self::Unit {
4005                unit_name,
4006                owning_type,
4007            } => {
4008                1u8.hash(state);
4009                unit_name.hash(state);
4010                owning_type.hash(state);
4011            }
4012        }
4013    }
4014}
4015
4016impl SemanticConversionTarget {}
4017
4018impl fmt::Display for SemanticConversionTarget {
4019    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4020        match self {
4021            SemanticConversionTarget::Type(kind) => write!(f, "{kind}"),
4022            SemanticConversionTarget::Unit { unit_name, .. } => write!(f, "{unit_name}"),
4023        }
4024    }
4025}
4026
4027/// Timezone for semantic date/time values: UTC offset in signed whole minutes, same
4028/// representation and bounds as [`TimezoneValue`].
4029#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
4030pub struct SemanticTimezone {
4031    pub offset_minutes: i16,
4032}
4033
4034impl SemanticTimezone {
4035    /// `None` when `seconds` is not a whole number of minutes within ±23:59.
4036    pub fn from_offset_seconds(seconds: i32) -> Option<Self> {
4037        TimezoneValue::from_offset_seconds(seconds).map(|tz| Self::from(&tz))
4038    }
4039
4040    pub fn offset_seconds(&self) -> i32 {
4041        i32::from(self.offset_minutes) * 60
4042    }
4043}
4044
4045impl From<&TimezoneValue> for SemanticTimezone {
4046    fn from(tz: &TimezoneValue) -> Self {
4047        Self {
4048            offset_minutes: tz.offset_minutes,
4049        }
4050    }
4051}
4052
4053impl From<&SemanticTimezone> for TimezoneValue {
4054    fn from(tz: &SemanticTimezone) -> Self {
4055        Self {
4056            offset_minutes: tz.offset_minutes,
4057        }
4058    }
4059}
4060
4061impl fmt::Display for SemanticTimezone {
4062    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4063        TimezoneValue::from(self).fmt(f)
4064    }
4065}
4066
4067impl Serialize for SemanticTimezone {
4068    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
4069        serializer.serialize_str(&self.to_string())
4070    }
4071}
4072
4073impl<'de> Deserialize<'de> for SemanticTimezone {
4074    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
4075        let s = String::deserialize(deserializer)?;
4076        Self::from_str(&s).map_err(serde::de::Error::custom)
4077    }
4078}
4079
4080impl FromStr for SemanticTimezone {
4081    type Err = String;
4082
4083    fn from_str(s: &str) -> Result<Self, Self::Err> {
4084        Ok(Self::from(&TimezoneValue::from_str(s)?))
4085    }
4086}
4087
4088/// Time-of-day for semantic values
4089#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
4090pub struct SemanticTime {
4091    pub hour: u32,
4092    pub minute: u32,
4093    pub second: u32,
4094    pub microsecond: u32,
4095    pub timezone: Option<SemanticTimezone>,
4096}
4097
4098impl fmt::Display for SemanticTime {
4099    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4100        write!(f, "{:02}:{:02}:{:02}", self.hour, self.minute, self.second)?;
4101        if self.microsecond != 0 {
4102            write!(f, ".{:06}", self.microsecond)?;
4103        }
4104        if let Some(timezone) = &self.timezone {
4105            write!(f, "{}", timezone)?;
4106        }
4107        Ok(())
4108    }
4109}
4110
4111impl Serialize for SemanticTime {
4112    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
4113        serializer.serialize_str(&self.to_string())
4114    }
4115}
4116
4117impl<'de> Deserialize<'de> for SemanticTime {
4118    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
4119        let s = String::deserialize(deserializer)?;
4120        Self::from_str(&s).map_err(serde::de::Error::custom)
4121    }
4122}
4123
4124impl FromStr for SemanticTime {
4125    type Err = String;
4126
4127    fn from_str(s: &str) -> Result<Self, Self::Err> {
4128        Ok(time_to_semantic(&TimeValue::from_str(s)?))
4129    }
4130}
4131
4132/// Date-time for semantic values
4133#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
4134pub struct SemanticDateTime {
4135    pub year: i32,
4136    pub month: u32,
4137    pub day: u32,
4138    pub hour: u32,
4139    pub minute: u32,
4140    pub second: u32,
4141    pub microsecond: u32,
4142    pub timezone: Option<SemanticTimezone>,
4143}
4144
4145impl fmt::Display for SemanticDateTime {
4146    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4147        let has_time = self.hour != 0
4148            || self.minute != 0
4149            || self.second != 0
4150            || self.microsecond != 0
4151            || self.timezone.is_some();
4152        if !has_time {
4153            write!(f, "{:04}-{:02}-{:02}", self.year, self.month, self.day)
4154        } else {
4155            write!(
4156                f,
4157                "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}",
4158                self.year, self.month, self.day, self.hour, self.minute, self.second
4159            )?;
4160            if self.microsecond != 0 {
4161                write!(f, ".{:06}", self.microsecond)?;
4162            }
4163            if let Some(tz) = &self.timezone {
4164                write!(f, "{}", tz)?;
4165            }
4166            Ok(())
4167        }
4168    }
4169}
4170
4171impl Serialize for SemanticDateTime {
4172    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
4173        serializer.serialize_str(&self.to_string())
4174    }
4175}
4176
4177impl<'de> Deserialize<'de> for SemanticDateTime {
4178    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
4179        let s = String::deserialize(deserializer)?;
4180        Self::from_str(&s).map_err(serde::de::Error::custom)
4181    }
4182}
4183
4184impl FromStr for SemanticDateTime {
4185    type Err = String;
4186
4187    fn from_str(s: &str) -> Result<Self, Self::Err> {
4188        Ok(date_time_to_semantic(&DateTimeValue::from_str(s)?))
4189    }
4190}
4191
4192/// Default captured during type constraint application, before measure unit factors are final.
4193/// Converted into [`ValueKind`] after `resolve_measure_decompositions` (or immediately for
4194/// reference-local defaults, which run after that pass).
4195#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4196pub enum RawSuggestion {
4197    Value(ValueKind),
4198    /// Measure suggest/fill: magnitude in the written unit (canonicalized later).
4199    Measure {
4200        magnitude: RationalInteger,
4201        unit_name: String,
4202    },
4203    /// Ratio (or other) suggest/fill that already holds a canonical [`ValueKind`]
4204    /// plus the written unit name for display binding.
4205    UnitBound {
4206        value: ValueKind,
4207        unit_name: String,
4208    },
4209    List(Vec<RawSuggestion>),
4210}
4211
4212/// Canonical suggestion/fill value plus the written measure unit when one was declared.
4213///
4214/// `unit` is the unit from `-> suggest 100 inr` / `-> with 5 eur`; Show
4215/// display stamps it so the one-liner matches the written unit, not the type's first unit.
4216/// Shared via [`Arc`] so value-table clones bump a refcount instead of allocating.
4217/// For ranges this stays `None`; each endpoint carries its own unit on its type.
4218///
4219/// `instance_factors` are the settled dynamic unit factors of the instance this value
4220/// was read from (`uses` alias or list row). Same-family arithmetic keeps only factors
4221/// both sides agree on; a family change drops them.
4222#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4223pub struct BoundValueKind {
4224    pub value: ValueKind,
4225    pub unit: Option<Arc<str>>,
4226    pub instance_factors: Option<Arc<InstanceFactors>>,
4227}
4228
4229/// The dynamic unit factors an instance settled, read as a map of unit to factor, and
4230/// the units it could not settle, with why (missing data, or a veto such as a factor
4231/// that is not greater than zero): a conversion into such a unit has that outcome.
4232#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
4233pub struct InstanceFactors {
4234    factors: BTreeMap<String, RationalInteger>,
4235    unsettled: BTreeMap<String, crate::computation::VetoType>,
4236}
4237
4238impl InstanceFactors {
4239    pub(crate) fn new(
4240        factors: BTreeMap<String, RationalInteger>,
4241        unsettled: BTreeMap<String, crate::computation::VetoType>,
4242    ) -> Self {
4243        Self { factors, unsettled }
4244    }
4245
4246    /// Why the instance has no factor for `unit`, when it tried and failed.
4247    pub(crate) fn unsettled(&self, unit: &str) -> Option<&crate::computation::VetoType> {
4248        self.unsettled.get(unit)
4249    }
4250
4251    fn is_empty(&self) -> bool {
4252        self.factors.is_empty() && self.unsettled.is_empty()
4253    }
4254
4255    /// These factors read on top of `carried`: a unit this instance settles, or fails
4256    /// to settle, takes its outcome; every other unit keeps what the value carried.
4257    pub(crate) fn over(&self, carried: &Self) -> Self {
4258        let mut factors = carried.factors.clone();
4259        let mut unsettled = carried.unsettled.clone();
4260        for (unit, factor) in &self.factors {
4261            unsettled.remove(unit);
4262            factors.insert(unit.clone(), factor.clone());
4263        }
4264        for (unit, veto) in &self.unsettled {
4265            factors.remove(unit);
4266            unsettled.insert(unit.clone(), veto.clone());
4267        }
4268        Self { factors, unsettled }
4269    }
4270
4271    /// These factors with `unit` at `factor`: what a value converted into `unit` at
4272    /// that factor carries.
4273    pub(crate) fn with_factor(&self, unit: &str, factor: &RationalInteger) -> Self {
4274        let mut factors = self.factors.clone();
4275        factors.insert(unit.to_string(), factor.clone());
4276        let mut unsettled = self.unsettled.clone();
4277        unsettled.remove(unit);
4278        Self { factors, unsettled }
4279    }
4280}
4281
4282impl std::ops::Deref for InstanceFactors {
4283    type Target = BTreeMap<String, RationalInteger>;
4284
4285    fn deref(&self) -> &Self::Target {
4286        &self.factors
4287    }
4288}
4289
4290impl BoundValueKind {
4291    pub fn unbound(value: ValueKind) -> Self {
4292        Self {
4293            value,
4294            unit: None,
4295            instance_factors: None,
4296        }
4297    }
4298
4299    pub fn with_binding(value: ValueKind, unit: Option<Arc<str>>) -> Self {
4300        Self {
4301            value,
4302            unit,
4303            instance_factors: None,
4304        }
4305    }
4306
4307    pub fn with_instance_factors(
4308        value: ValueKind,
4309        unit: Option<Arc<str>>,
4310        instance_factors: Option<Arc<InstanceFactors>>,
4311    ) -> Self {
4312        Self {
4313            value,
4314            unit,
4315            instance_factors,
4316        }
4317    }
4318
4319    /// This value as a value of `holder`, the type of what holds it: a rule, a cell or a
4320    /// slot of another instance. A unit `holder` does not declare is not carried on; the
4321    /// magnitude is the same in every unit of the family.
4322    pub(crate) fn held_as(mut self, holder: &LemmaType) -> Self {
4323        if let (Some(units), Some(unit)) = (holder.measure_units_table(), &self.unit) {
4324            if units.get(unit).is_err() {
4325                self.unit = None;
4326            }
4327        }
4328        self
4329    }
4330
4331    pub fn to_literal(&self) -> LiteralValue {
4332        LiteralValue {
4333            value: self.value.clone(),
4334        }
4335    }
4336
4337    /// Written-unit agreement for ± on same-family measure/ratio: equal keep; one Some keep that;
4338    /// conflict → left wins.
4339    #[must_use]
4340    pub fn agree_or_left_binding(
4341        left: Option<&Arc<str>>,
4342        right: Option<&Arc<str>>,
4343    ) -> Option<Arc<str>> {
4344        match (left, right) {
4345            (Some(a), Some(b)) if a.as_ref() == b.as_ref() => Some(Arc::clone(a)),
4346            (Some(a), Some(_)) => Some(Arc::clone(a)),
4347            (Some(a), None) => Some(Arc::clone(a)),
4348            (None, Some(b)) => Some(Arc::clone(b)),
4349            (None, None) => None,
4350        }
4351    }
4352
4353    /// Agreed instance factors for same-family arithmetic: units both sides carry with
4354    /// equal factors stay; either side missing a map means no carried instance agreement
4355    /// (local / plan-scoped values rely on runtime scales, not a one-sided carry).
4356    #[must_use]
4357    pub fn agree_instance_factors(
4358        left: Option<&Arc<InstanceFactors>>,
4359        right: Option<&Arc<InstanceFactors>>,
4360    ) -> Option<Arc<InstanceFactors>> {
4361        match (left, right) {
4362            (None, None) | (Some(_), None) | (None, Some(_)) => None,
4363            (Some(left), Some(right)) => {
4364                let mut agreed = BTreeMap::new();
4365                for (unit, factor) in left.iter() {
4366                    if right.get(unit) == Some(factor) {
4367                        agreed.insert(unit.clone(), factor.clone());
4368                    }
4369                }
4370                // A unit either side could not settle stays unsettled: the sum has no
4371                // factor for it either.
4372                let mut unsettled = left.unsettled.clone();
4373                for (unit, veto) in &right.unsettled {
4374                    unsettled
4375                        .entry(unit.clone())
4376                        .or_insert_with(|| veto.clone());
4377                }
4378                let agreed = InstanceFactors::new(agreed, unsettled);
4379                (!agreed.is_empty()).then(|| Arc::new(agreed))
4380            }
4381        }
4382    }
4383
4384    /// Keep a written unit only when agreed instance factors still know its factor.
4385    /// When there is no instance map, leave the binding for plan-scoped runtime scales.
4386    #[must_use]
4387    pub fn binding_with_agreed_factors(
4388        unit: Option<Arc<str>>,
4389        factors: &Option<Arc<InstanceFactors>>,
4390    ) -> Option<Arc<str>> {
4391        match (unit, factors) {
4392            (Some(unit), Some(factors))
4393                if factors.contains_key(unit.as_ref())
4394                    || factors.unsettled(unit.as_ref()).is_some() =>
4395            {
4396                Some(unit)
4397            }
4398            (Some(_), Some(_)) => None,
4399            (unit, None) => unit,
4400            (None, _) => None,
4401        }
4402    }
4403}
4404
4405pub fn bound_value_kind_from_raw_suggestion(
4406    raw: RawSuggestion,
4407    specifications: &TypeSpecification,
4408    type_name: &str,
4409) -> Result<BoundValueKind, String> {
4410    enum Step<'a> {
4411        Visit(RawSuggestion, &'a TypeSpecification),
4412        CollectList {
4413            element: &'a Arc<LemmaType>,
4414            rows: usize,
4415        },
4416    }
4417
4418    let mut steps = vec![Step::Visit(raw, specifications)];
4419    let mut bounds: Vec<BoundValueKind> = Vec::new();
4420    while let Some(step) = steps.pop() {
4421        match step {
4422            Step::Visit(raw, specifications) => match raw {
4423                RawSuggestion::Value(vk) => bounds.push(BoundValueKind::unbound(vk)),
4424                RawSuggestion::UnitBound { value, unit_name } => bounds.push(BoundValueKind {
4425                    value,
4426                    unit: Some(Arc::from(unit_name)),
4427                    instance_factors: None,
4428                }),
4429                RawSuggestion::Measure {
4430                    magnitude,
4431                    unit_name,
4432                } => {
4433                    let TypeSpecification::Measure { units, .. } = specifications else {
4434                        unreachable!(
4435                            "BUG: RawSuggestion::Measure for non-measure type '{type_name}'"
4436                        );
4437                    };
4438                    if units
4439                        .get(&unit_name)
4440                        .is_ok_and(crate::literals::MeasureUnit::is_dynamic)
4441                    {
4442                        bounds.push(BoundValueKind {
4443                            value: ValueKind::UnscaledMeasure {
4444                                magnitude,
4445                                unit: Arc::from(unit_name.as_str()),
4446                            },
4447                            unit: Some(Arc::from(unit_name)),
4448                            instance_factors: None,
4449                        });
4450                    } else {
4451                        let canonical = measure_declared_bound_to_canonical(
4452                            &magnitude, &unit_name, units, type_name, "suggest",
4453                        )?;
4454                        bounds.push(BoundValueKind {
4455                            value: ValueKind::Measure(canonical),
4456                            unit: Some(Arc::from(unit_name)),
4457                            instance_factors: None,
4458                        });
4459                    }
4460                }
4461                RawSuggestion::List(rows) => {
4462                    let TypeSpecification::List { element, .. } = specifications else {
4463                        unreachable!("BUG: RawSuggestion::List for non-list type '{type_name}'");
4464                    };
4465                    steps.push(Step::CollectList {
4466                        element,
4467                        rows: rows.len(),
4468                    });
4469                    for row in rows.into_iter().rev() {
4470                        steps.push(Step::Visit(row, &element.specifications));
4471                    }
4472                }
4473            },
4474            Step::CollectList { element, rows } => {
4475                let start = bounds
4476                    .len()
4477                    .checked_sub(rows)
4478                    .expect("BUG: list rows missing from bound stack");
4479                let converted: Arc<[TypedLiteral]> = bounds
4480                    .split_off(start)
4481                    .iter()
4482                    .map(|bound| typed_literal_from_bound(bound, element))
4483                    .collect();
4484                bounds.push(BoundValueKind::unbound(ValueKind::List(converted.into())));
4485            }
4486        }
4487    }
4488    Ok(bounds.pop().expect("BUG: bound walk left no result"))
4489}
4490
4491/// Display one-liner unit: `as` / schema > settled > fill > suggest > none (first declared).
4492///
4493/// Range schemas are skipped: endpoint units live on each endpoint type.
4494#[must_use]
4495pub fn display_binding_unit(
4496    schema: &LemmaType,
4497    settled: Option<&BoundValueKind>,
4498    fill: Option<&BoundValueKind>,
4499    suggestion: Option<&BoundValueKind>,
4500) -> Option<String> {
4501    if schema.is_measure_range() || schema.is_ratio_range() {
4502        return None;
4503    }
4504    if let Some(unit) = schema.unit() {
4505        return Some(unit.to_string());
4506    }
4507    if let Some(unit) = settled.and_then(|bound| bound.unit.as_ref()) {
4508        return Some(unit.to_string());
4509    }
4510    if let Some(unit) = fill.and_then(|bound| bound.unit.as_ref()) {
4511        return Some(unit.to_string());
4512    }
4513    suggestion
4514        .and_then(|bound| bound.unit.as_ref())
4515        .map(|unit| unit.to_string())
4516}
4517
4518/// Schema type stamped with [`display_binding_unit`] when a binding wins.
4519///
4520/// Clones only when the winning unit differs from what `schema` already carries.
4521/// Range types are returned unchanged.
4522#[must_use]
4523pub fn lemma_type_with_display_binding(
4524    schema: &LemmaType,
4525    settled: Option<&BoundValueKind>,
4526    fill: Option<&BoundValueKind>,
4527    suggestion: Option<&BoundValueKind>,
4528) -> LemmaType {
4529    if schema.is_measure_range() || schema.is_ratio_range() {
4530        return schema.clone();
4531    }
4532    match display_binding_unit(schema, settled, fill, suggestion) {
4533        Some(unit) if schema.unit() != Some(unit.as_str()) => schema.clone().with_unit(unit),
4534        Some(_) | None => schema.clone(),
4535    }
4536}
4537
4538/// Like [`lemma_type_with_display_binding`] but reuses `schema` when no override.
4539#[must_use]
4540pub fn lemma_type_arc_with_display_binding(
4541    schema: &Arc<LemmaType>,
4542    settled: Option<&BoundValueKind>,
4543    fill: Option<&BoundValueKind>,
4544    suggestion: Option<&BoundValueKind>,
4545) -> Arc<LemmaType> {
4546    if schema.is_measure_range() || schema.is_ratio_range() {
4547        return Arc::clone(schema);
4548    }
4549    match display_binding_unit(schema.as_ref(), settled, fill, suggestion) {
4550        Some(unit) if schema.unit() != Some(unit.as_str()) => {
4551            Arc::new(schema.as_ref().clone().with_unit(unit))
4552        }
4553        Some(_) | None => Arc::clone(schema),
4554    }
4555}
4556
4557/// Build a [`TypedLiteral`] from an eval bound and the plan type for that cell.
4558///
4559/// Stamps `bound.unit` onto measure/ratio types. Range values already carry
4560/// typed endpoints inside [`ValueKind::Range`].
4561#[must_use]
4562pub fn typed_literal_from_bound(
4563    bound: &BoundValueKind,
4564    lemma_type: &Arc<LemmaType>,
4565) -> TypedLiteral {
4566    let lemma_type = match (&bound.unit, &lemma_type.specifications) {
4567        (Some(unit), TypeSpecification::Measure { .. } | TypeSpecification::Ratio { .. })
4568            if lemma_type.unit() != Some(unit.as_ref()) =>
4569        {
4570            Arc::new(lemma_type.as_ref().clone().with_unit(unit.as_ref()))
4571        }
4572        _ => Arc::clone(lemma_type),
4573    };
4574    TypedLiteral {
4575        value: bound.value.clone(),
4576        lemma_type,
4577    }
4578}
4579
4580/// Value payload (shape of a literal).
4581///
4582/// Scalar variants are type-free: type lives on `NormalForm.result_type` /
4583/// `DataDefinition`. The [`ValueKind::Range`] arm is the exception — each
4584/// endpoint keeps a [`TypedLiteral`] so a mixed-unit range (`10 eur...20 usd`)
4585/// retains both written units.
4586#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4587pub enum ValueKind {
4588    Number(RationalInteger),
4589    /// Measure: magnitude in canonical (base-unit) space.
4590    ///
4591    /// At bind time the user-facing value is multiplied by the unit's scale to produce
4592    /// the stored magnitude; API unit maps divide back. Unit/signature identity
4593    /// comes from the node/`DataDefinition` type via [`LemmaType::measure_runtime_signature`].
4594    Measure(RationalInteger),
4595    /// Measure written in a reference-scaled unit. Lives only in stored values
4596    /// (literal leaves, data slots, definitions, bindings). A cell result never
4597    /// holds one: the owning leaf settles it to [`ValueKind::Measure`] first.
4598    UnscaledMeasure {
4599        magnitude: RationalInteger,
4600        unit: Arc<str>,
4601    },
4602    Text(Arc<str>),
4603    Date(SemanticDateTime),
4604    Time(SemanticTime),
4605    Boolean(bool),
4606    /// Ratio: canonical magnitude. Display unit comes from the node/`DataDefinition` type.
4607    Ratio(RationalInteger),
4608    /// Range endpoints carry their own type (and written unit for measure/ratio).
4609    Range(Box<TypedLiteral>, Box<TypedLiteral>),
4610    /// A spec instance: a `uses` path in the consumer plan, or one row of an instance list.
4611    Spec(SpecValue),
4612    /// Ordered rows of one type. Each row keeps its own type (written unit for measures).
4613    List(ListValue),
4614}
4615
4616/// Items of a list value, with the key index of a keyed list that carries one.
4617/// Equality, hashing and serialization are over the items only.
4618#[derive(Debug, Clone)]
4619pub struct ListValue {
4620    items: ListItems,
4621    index: Option<Arc<crate::planning::instance_list::KeyIndex>>,
4622}
4623
4624/// The rows of a store as one list reads them.
4625pub(crate) struct StoredRows<'l> {
4626    pub rows: &'l [Arc<RowInstance>],
4627    pub owner: Option<&'l InstanceKey>,
4628}
4629
4630#[derive(Debug, Clone)]
4631enum ListItems {
4632    Values(Arc<[TypedLiteral]>),
4633    /// The rows of a store as one list reads them: each item is the row owned by
4634    /// `owner`, of type `row_type`.
4635    Rows {
4636        store: Arc<crate::planning::instance_list::RowStore>,
4637        owner: Option<InstanceKey>,
4638        row_type: Arc<LemmaType>,
4639    },
4640}
4641
4642impl ListValue {
4643    /// A list holding `items`, without an index.
4644    fn held(items: Arc<[TypedLiteral]>) -> Self {
4645        Self {
4646            items: ListItems::Values(items),
4647            index: None,
4648        }
4649    }
4650
4651    pub(crate) fn indexed(
4652        items: Arc<[TypedLiteral]>,
4653        index: Arc<crate::planning::instance_list::KeyIndex>,
4654    ) -> Self {
4655        Self {
4656            items: ListItems::Values(items),
4657            index: Some(index),
4658        }
4659    }
4660
4661    /// The rows of `store` read by `owner`, indexed by the store's index.
4662    pub(crate) fn stored_rows(
4663        store: &Arc<crate::planning::instance_list::RowStore>,
4664        owner: Option<InstanceKey>,
4665        row_type: Arc<LemmaType>,
4666    ) -> Self {
4667        Self {
4668            index: store.index.clone(),
4669            items: ListItems::Rows {
4670                store: Arc::clone(store),
4671                owner,
4672                row_type,
4673            },
4674        }
4675    }
4676
4677    pub fn len(&self) -> usize {
4678        match &self.items {
4679            ListItems::Values(items) => items.len(),
4680            ListItems::Rows { store, .. } => store.rows.len(),
4681        }
4682    }
4683
4684    pub fn is_empty(&self) -> bool {
4685        self.len() == 0
4686    }
4687
4688    pub fn get(&self, position: usize) -> Option<std::borrow::Cow<'_, TypedLiteral>> {
4689        match &self.items {
4690            ListItems::Values(items) => items.get(position).map(std::borrow::Cow::Borrowed),
4691            ListItems::Rows {
4692                store,
4693                owner,
4694                row_type,
4695            } => store.rows.get(position).map(|row| {
4696                std::borrow::Cow::Owned(TypedLiteral {
4697                    value: ValueKind::Spec(SpecValue::Row(InstanceKey::new(
4698                        Arc::clone(row),
4699                        owner.clone(),
4700                    ))),
4701                    lemma_type: Arc::clone(row_type),
4702                })
4703            }),
4704        }
4705    }
4706
4707    pub fn first(&self) -> Option<std::borrow::Cow<'_, TypedLiteral>> {
4708        self.get(0)
4709    }
4710
4711    pub fn last(&self) -> Option<std::borrow::Cow<'_, TypedLiteral>> {
4712        self.len().checked_sub(1).and_then(|last| self.get(last))
4713    }
4714
4715    pub fn iter(
4716        &self,
4717    ) -> impl DoubleEndedIterator<Item = std::borrow::Cow<'_, TypedLiteral>> + ExactSizeIterator
4718    {
4719        (0..self.len()).map(|position| {
4720            self.get(position)
4721                .expect("BUG: list position below the list length")
4722        })
4723    }
4724
4725    /// The items of a list that holds them: every list but one reading a row store.
4726    pub(crate) fn values(&self) -> &[TypedLiteral] {
4727        match &self.items {
4728            ListItems::Values(items) => items,
4729            ListItems::Rows { .. } => panic!("BUG: held items read from a list of stored rows"),
4730        }
4731    }
4732
4733    /// The rows of the store this list reads, when it reads one.
4734    pub(crate) fn stored(&self) -> Option<StoredRows<'_>> {
4735        match &self.items {
4736            ListItems::Values(_) => None,
4737            ListItems::Rows { store, owner, .. } => Some(StoredRows {
4738                rows: &store.rows,
4739                owner: owner.as_ref(),
4740            }),
4741        }
4742    }
4743
4744    /// The items as owned values.
4745    pub fn to_vec(&self) -> Vec<TypedLiteral> {
4746        self.iter().map(std::borrow::Cow::into_owned).collect()
4747    }
4748
4749    pub(crate) fn index(&self) -> Option<&Arc<crate::planning::instance_list::KeyIndex>> {
4750        self.index.as_ref()
4751    }
4752
4753    /// The same items, rows evaluation data supplies owned by `owner` (their list is a
4754    /// list of `owner`).
4755    pub(crate) fn owned_by(&self, owner: &InstanceKey) -> Self {
4756        let ListItems::Values(items) = &self.items else {
4757            return self.clone();
4758        };
4759        Self {
4760            items: ListItems::Values(
4761                items
4762                    .iter()
4763                    .map(|item| match &item.value {
4764                        ValueKind::Spec(SpecValue::Row(key))
4765                            if key.owner.is_none()
4766                                && matches!(key.row.origin, RowOrigin::Numbered { .. }) =>
4767                        {
4768                            TypedLiteral {
4769                                value: ValueKind::Spec(SpecValue::Row(InstanceKey::new(
4770                                    Arc::clone(&key.row),
4771                                    Some(owner.clone()),
4772                                ))),
4773                                lemma_type: Arc::clone(&item.lemma_type),
4774                            }
4775                        }
4776                        _ => item.clone(),
4777                    })
4778                    .collect(),
4779            ),
4780            index: self.index.clone(),
4781        }
4782    }
4783
4784    /// The same items without an index.
4785    pub(crate) fn unindexed(&self) -> Self {
4786        Self {
4787            items: self.items.clone(),
4788            index: None,
4789        }
4790    }
4791
4792    /// The same items with `index`.
4793    pub(crate) fn with_index(&self, index: Arc<crate::planning::instance_list::KeyIndex>) -> Self {
4794        Self {
4795            items: self.items.clone(),
4796            index: Some(index),
4797        }
4798    }
4799}
4800
4801impl From<Arc<[TypedLiteral]>> for ListValue {
4802    fn from(items: Arc<[TypedLiteral]>) -> Self {
4803        Self::held(items)
4804    }
4805}
4806
4807impl From<Vec<TypedLiteral>> for ListValue {
4808    fn from(items: Vec<TypedLiteral>) -> Self {
4809        Self::held(Arc::from(items))
4810    }
4811}
4812
4813impl FromIterator<TypedLiteral> for ListValue {
4814    fn from_iter<I: IntoIterator<Item = TypedLiteral>>(iter: I) -> Self {
4815        Self::held(iter.into_iter().collect())
4816    }
4817}
4818
4819impl PartialEq for ListValue {
4820    fn eq(&self, other: &Self) -> bool {
4821        self.len() == other.len() && self.iter().eq(other.iter())
4822    }
4823}
4824
4825impl Eq for ListValue {}
4826
4827impl Hash for ListValue {
4828    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
4829        self.len().hash(state);
4830        for item in self.iter() {
4831            item.hash(state);
4832        }
4833    }
4834}
4835
4836impl ValueKind {
4837    /// Decimal magnitude for numeric variants (number, measure, ratio).
4838    pub fn as_decimal_magnitude(&self) -> Result<Decimal, String> {
4839        match self {
4840            ValueKind::Number(n) | ValueKind::Measure(n) | ValueKind::Ratio(n) => {
4841                n.try_to_decimal().map_err(|failure| failure.to_string())
4842            }
4843            other => Err(format!("expected numeric value kind, got {other}")),
4844        }
4845    }
4846
4847    /// Cheap structural byte-size estimate (no formatting, no rational→decimal).
4848    ///
4849    /// Used by resource-limit checks where the exact string length is not
4850    /// required — only an upper-bound within a constant factor.
4851    pub fn structural_byte_size(&self) -> usize {
4852        fn rational_byte_estimate(r: &RationalInteger) -> usize {
4853            let numer_bytes = (r.numer_magnitude_bits() as usize).div_ceil(8);
4854            let denom_bytes = (r.denom_magnitude_bits() as usize).div_ceil(8);
4855            numer_bytes.max(1) + denom_bytes.max(1)
4856        }
4857        match self {
4858            ValueKind::Number(r) => rational_byte_estimate(r),
4859            ValueKind::Measure(r) => rational_byte_estimate(r),
4860            ValueKind::UnscaledMeasure { magnitude, unit } => {
4861                rational_byte_estimate(magnitude) + unit.len()
4862            }
4863            ValueKind::Ratio(r) => rational_byte_estimate(r),
4864            ValueKind::Text(s) => s.len(),
4865            ValueKind::Date(_) => 30, // "2026-01-01T00:00:00+02:00" upper bound
4866            ValueKind::Time(_) => 12, // "23:59:59" upper bound
4867            ValueKind::Boolean(_) => 5, // "false"
4868            ValueKind::Range(left, right) => {
4869                left.value.structural_byte_size() + 3 + right.value.structural_byte_size()
4870            }
4871            ValueKind::Spec(SpecValue::Fixed(instance)) => instance.structural_byte_size(),
4872            ValueKind::Spec(SpecValue::Row(InstanceKey { row, .. })) => row.structural_byte_size(),
4873            ValueKind::List(rows) => rows
4874                .iter()
4875                .map(|row| row.value.structural_byte_size())
4876                .sum(),
4877        }
4878    }
4879
4880    /// Whether this stored value still contains a reference-scaled measure.
4881    #[must_use]
4882    pub fn has_unscaled_measure(&self) -> bool {
4883        match self {
4884            ValueKind::UnscaledMeasure { .. } => true,
4885            ValueKind::Range(left, right) => match (&left.value, &right.value) {
4886                (ValueKind::UnscaledMeasure { .. }, _) | (_, ValueKind::UnscaledMeasure { .. }) => {
4887                    true
4888                }
4889                (ValueKind::Range(_, _) | ValueKind::List(_), _)
4890                | (_, ValueKind::Range(_, _) | ValueKind::List(_)) => unscaled_in_value_tree(self),
4891                _ => false,
4892            },
4893            ValueKind::List(_) => unscaled_in_value_tree(self),
4894            _ => false,
4895        }
4896    }
4897}
4898
4899fn unscaled_in_value_tree(root: &ValueKind) -> bool {
4900    let mut pending = vec![root];
4901    while let Some(value) = pending.pop() {
4902        match value {
4903            ValueKind::UnscaledMeasure { .. } => return true,
4904            ValueKind::Range(left, right) => {
4905                pending.push(&right.value);
4906                pending.push(&left.value);
4907            }
4908            ValueKind::List(rows) => {
4909                if rows.stored().is_none() {
4910                    for item in rows.values().iter() {
4911                        pending.push(&item.value);
4912                    }
4913                }
4914            }
4915            _ => {}
4916        }
4917    }
4918    false
4919}
4920
4921fn format_rational_magnitude_for_display(rational: &RationalInteger) -> String {
4922    rational.display_str()
4923}
4924
4925fn format_number_with_unit_for_display(rational: &RationalInteger, unit: &str) -> String {
4926    use crate::parsing::ast::Value;
4927    match rational.try_to_decimal() {
4928        Ok(decimal) => format!("{}", Value::NumberWithUnit(decimal, unit.to_string())),
4929        Err(_) => format!("{} {}", rational.display_str(), unit),
4930    }
4931}
4932
4933impl fmt::Display for ValueKind {
4934    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4935        match self {
4936            ValueKind::Number(rational) => {
4937                write!(f, "{}", format_rational_magnitude_for_display(rational))
4938            }
4939            ValueKind::Measure(rational) => {
4940                write!(f, "{}", format_rational_magnitude_for_display(rational))
4941            }
4942            ValueKind::UnscaledMeasure { magnitude, unit } => {
4943                write!(
4944                    f,
4945                    "{} {unit}",
4946                    format_rational_magnitude_for_display(magnitude)
4947                )
4948            }
4949            ValueKind::Text(s) => {
4950                write!(f, "{}", crate::parsing::ast::Value::Text(s.to_string()))
4951            }
4952            ValueKind::Ratio(rational) => {
4953                write!(f, "{}", format_rational_magnitude_for_display(rational))
4954            }
4955            ValueKind::Date(dt) => write!(f, "{}", dt),
4956            ValueKind::Time(t) => write!(
4957                f,
4958                "{}",
4959                crate::parsing::ast::Value::Time(crate::parsing::ast::TimeValue {
4960                    hour: t.hour as u8,
4961                    minute: t.minute as u8,
4962                    second: t.second as u8,
4963                    microsecond: t.microsecond,
4964                    timezone: t
4965                        .timezone
4966                        .as_ref()
4967                        .map(crate::parsing::ast::TimezoneValue::from),
4968                })
4969            ),
4970            ValueKind::Boolean(b) => write!(f, "{}", b),
4971            ValueKind::Range(left, right) => write!(f, "{}...{}", left, right),
4972            ValueKind::Spec(value) => write!(f, "{value}"),
4973            ValueKind::List(rows) => {
4974                write!(f, "list[")?;
4975                for (i, row) in rows.iter().enumerate() {
4976                    if i > 0 {
4977                        write!(f, ", ")?;
4978                    }
4979                    write!(f, "{row}")?;
4980                }
4981                write!(f, "]")
4982            }
4983        }
4984    }
4985}
4986
4987// -----------------------------------------------------------------------------
4988// Resolved path types (moved from parsing::ast)
4989// -----------------------------------------------------------------------------
4990
4991/// A single segment in a resolved path traversal
4992///
4993/// Used in both DataPath and RulePath for cross-spec traversal. Each segment is
4994/// one spec instance of the consumer plan: a `uses` import (`uses`, `row: None`)
4995/// or row `row` of the instance list `uses` written in the spec (`row: Some(n)`,
4996/// 1-based). `repository` is the resolved target repository name (`None` = unnamed
4997/// workspace) and `spec` the resolved target spec name.
4998#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
4999pub struct PathSegment {
5000    /// The `uses` alias, or the instance list name when `row` is set.
5001    pub uses: Arc<str>,
5002    /// Row number (1-based) of list `uses` when this hop is a row written in the spec.
5003    pub row: Option<usize>,
5004    /// Target repository name from `Arc<LemmaRepository>.name` at resolve.
5005    /// `None` is the unnamed workspace.
5006    pub repository: Option<Arc<str>>,
5007    /// The spec this hop resolves to (resolved during planning)
5008    pub spec: Arc<str>,
5009}
5010
5011impl PathSegment {
5012    /// `uses` import hop of `identity` named `alias`.
5013    pub(crate) fn import(alias: &str, identity: &SpecIdentity) -> Self {
5014        Self {
5015            uses: Arc::from(alias),
5016            row: None,
5017            repository: identity.repository.as_deref().map(Arc::from),
5018            spec: Arc::from(identity.spec.as_str()),
5019        }
5020    }
5021
5022    /// Hop of row `number` (1-based) of instance list whose name and identity strings
5023    /// are already shared as `Arc<str>`: every row of one list reuses the same three
5024    /// allocations, so building a row's hop is refcount bumps, not fresh allocations.
5025    pub(crate) fn list_row_shared(
5026        list: &Arc<str>,
5027        number: usize,
5028        spec: &Arc<str>,
5029        repository: Option<&Arc<str>>,
5030    ) -> Self {
5031        Self {
5032            uses: Arc::clone(list),
5033            row: Some(number),
5034            repository: repository.map(Arc::clone),
5035            spec: Arc::clone(spec),
5036        }
5037    }
5038
5039    /// Dotted input-key form of this hop: `ada`, or `staff.2` for a row.
5040    pub fn input_key(&self) -> String {
5041        match self.row {
5042            Some(number) => format!("{}.{number}", self.uses),
5043            None => self.uses.to_string(),
5044        }
5045    }
5046}
5047
5048/// A global instance of an evaluation: the spec `spec` as `uses global` in repository
5049/// `repository` (the declaring repository, `None` for the unnamed workspace) reads it.
5050/// Every plan that reaches a global holds it as a `uses` slot named
5051/// [`Self::alias_in`] (`global.x`, or `accounting global.x` for another repository).
5052#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
5053pub struct GlobalKey {
5054    pub repository: Option<Arc<str>>,
5055    pub spec: Arc<str>,
5056}
5057
5058/// Keyword prefix of a global instance's slot name.
5059pub(crate) const GLOBAL_PREFIX: &str = "global.";
5060
5061impl GlobalKey {
5062    /// Slot name of this global in a plan of repository `plan_repository`: `global.x` for
5063    /// a global of that repository, `<repo> global.x` for one of another repository.
5064    #[must_use]
5065    pub fn alias_in(&self, plan_repository: Option<&str>) -> String {
5066        if self.repository.as_deref() == plan_repository {
5067            return format!("{GLOBAL_PREFIX}{}", self.spec);
5068        }
5069        let repository = self.repository.as_deref().expect(
5070            "BUG: a named repository reaches no global of the unnamed workspace; it cannot name it",
5071        );
5072        format!("{repository} {GLOBAL_PREFIX}{}", self.spec)
5073    }
5074
5075    /// The global a slot name of [`Self::alias_in`] names in a plan of `plan_repository`;
5076    /// `None` for any other name.
5077    #[must_use]
5078    pub fn from_alias(alias: &str, plan_repository: Option<&str>) -> Option<Self> {
5079        let (repository, rest) = match alias.split_once(' ') {
5080            Some((repository, rest)) => (Some(repository), rest),
5081            None => (plan_repository, alias),
5082        };
5083        let spec = rest.strip_prefix(GLOBAL_PREFIX)?;
5084        if spec.is_empty() || spec.contains('.') || spec.contains(' ') {
5085            return None;
5086        }
5087        Some(Self {
5088            repository: repository.map(Arc::from),
5089            spec: Arc::from(spec),
5090        })
5091    }
5092}
5093
5094/// Whether a path through `segments` starts in a global.
5095#[must_use]
5096pub(crate) fn reads_global(segments: &[PathSegment]) -> bool {
5097    segments
5098        .first()
5099        .is_some_and(|segment| is_global_slot_name(&segment.uses))
5100}
5101
5102/// Whether `name` is the slot name of a global ([`GlobalKey::alias_in`]): no written
5103/// name has one, since `global` is a keyword and names have no `.`.
5104#[must_use]
5105pub(crate) fn is_global_slot_name(name: &str) -> bool {
5106    name.starts_with(GLOBAL_PREFIX) || name.contains(" global.")
5107}
5108
5109/// Whether `row` is a global's one instance: the row of a `global.x` slot. Only the
5110/// root plan's `global.x` rows are read as instances; every other plan's are redirected.
5111#[must_use]
5112pub(crate) fn is_global_instance_row(row: &RowInstance) -> bool {
5113    matches!(&row.origin, RowOrigin::Import { alias } if is_global_slot_name(alias))
5114}
5115
5116impl fmt::Display for GlobalKey {
5117    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5118        match &self.repository {
5119            Some(repository) => write!(f, "{repository} {GLOBAL_PREFIX}{}", self.spec),
5120            None => write!(f, "{GLOBAL_PREFIX}{}", self.spec),
5121        }
5122    }
5123}
5124
5125/// The hops that name a spec instance, relative to the plan holding it: `uses` hops
5126/// (`rack.low`), or a list hop with its row number (`staff.2`).
5127#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
5128pub struct SpecInstance {
5129    pub prefix: Vec<PathSegment>,
5130}
5131
5132impl SpecInstance {
5133    pub fn structural_byte_size(&self) -> usize {
5134        self.prefix
5135            .iter()
5136            .map(|segment| {
5137                segment.uses.len()
5138                    + segment.spec.len()
5139                    + segment.repository.as_deref().map_or(0, str::len)
5140                    + segment.row.map_or(0, |_| std::mem::size_of::<usize>())
5141            })
5142            .sum()
5143    }
5144}
5145
5146impl fmt::Display for SpecInstance {
5147    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5148        for (index, segment) in self.prefix.iter().enumerate() {
5149            if index > 0 {
5150                write!(f, ".")?;
5151            }
5152            write!(f, "{}", segment.input_key())?;
5153        }
5154        Ok(())
5155    }
5156}
5157
5158/// Value of a spec-typed expression.
5159///
5160/// `Row` is a row instance as read (see [`InstanceKey`]); a `uses` import is the row of
5161/// its alias, read by the instance that declares it. Evaluation produces only `Row`.
5162/// `Fixed` is a spec instance named by its hops, rebuilt from a [`SpecResult`] by
5163/// [`RuleResultValue::to_literal`].
5164///
5165/// [`SpecResult`]: crate::result_value::SpecResult
5166/// [`RuleResultValue::to_literal`]: crate::result_value::RuleResultValue::to_literal
5167#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5168pub enum SpecValue {
5169    Fixed(SpecInstance),
5170    Row(InstanceKey),
5171}
5172
5173impl fmt::Display for SpecValue {
5174    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5175        match self {
5176            SpecValue::Fixed(instance) => write!(f, "{instance}"),
5177            SpecValue::Row(key) => write!(f, "{key}"),
5178        }
5179    }
5180}
5181
5182/// One row as read in an evaluation request, and the identity of its context: the row
5183/// `Arc` and the owning instance whose context read it (`None` for the root scope).
5184/// The bindings of the row resolve in the owner's context.
5185#[derive(Debug, Clone)]
5186pub struct InstanceKey {
5187    pub row: Arc<RowInstance>,
5188    pub owner: Option<Box<InstanceKey>>,
5189}
5190
5191impl InstanceKey {
5192    pub fn new(row: Arc<RowInstance>, owner: Option<InstanceKey>) -> Self {
5193        Self {
5194            row,
5195            owner: owner.map(Box::new),
5196        }
5197    }
5198
5199    pub fn owner(&self) -> Option<&InstanceKey> {
5200        self.owner.as_deref()
5201    }
5202
5203    /// Origins naming this instance, innermost first, up to the first that is absolute.
5204    fn naming_origins(&self) -> Vec<&RowOrigin> {
5205        let mut origins = Vec::new();
5206        let mut key = Some(self);
5207        while let Some(current) = key {
5208            origins.push(&current.row.origin);
5209            if matches!(current.row.origin, RowOrigin::Numbered { .. }) {
5210                break;
5211            }
5212            key = current.owner();
5213        }
5214        origins
5215    }
5216
5217    /// Data path of this instance in the run data that wrote its nearest run-data row
5218    /// (`i`, `i.staff.2`, `items.2.j`; `lines.1.i` for a row of a run-data row's list);
5219    /// `None` when it is or sits under an inline row, which has no path.
5220    pub fn path(&self) -> Option<String> {
5221        let origins = self.naming_origins();
5222        if origins.iter().any(|origin| origin.is_inline()) {
5223            return None;
5224        }
5225        Some(
5226            origins
5227                .iter()
5228                .rev()
5229                .map(ToString::to_string)
5230                .collect::<Vec<_>>()
5231                .join("."),
5232        )
5233    }
5234
5235    /// This instance named from `row`, one of its owners (`holder.items.1`); `None` when
5236    /// `row` does not hold it.
5237    pub(crate) fn label_under(&self, row: &InstanceKey) -> Option<String> {
5238        let mut below: Vec<&RowOrigin> = Vec::new();
5239        let mut key = self;
5240        while key != row {
5241            below.push(&key.row.origin);
5242            key = key.owner()?;
5243        }
5244        Some(
5245            below
5246                .iter()
5247                .rev()
5248                .map(ToString::to_string)
5249                .collect::<Vec<_>>()
5250                .join("."),
5251        )
5252    }
5253
5254    /// The rows-table row this instance publishes under: itself or the nearest owner that
5255    /// is a run-data or appended row. With the label of this instance: its path, or under
5256    /// an appended row its path from that row (`item`).
5257    pub(crate) fn table_row(&self) -> (&InstanceKey, Option<String>) {
5258        let mut key = self;
5259        loop {
5260            match &key.row.origin {
5261                RowOrigin::Numbered { .. } => return (key, self.path()),
5262                RowOrigin::Inline { .. } if key == self => return (key, None),
5263                RowOrigin::Inline { .. } => return (key, self.label_under(key)),
5264                RowOrigin::Import { .. } | RowOrigin::Written { .. } => {
5265                    key = key
5266                        .owner()
5267                        .expect("BUG: an instance off the rows table published as a table row");
5268                }
5269            }
5270        }
5271    }
5272
5273    /// Evaluation-data key of field `key` of this instance from the request's plan;
5274    /// `None` when it has no path.
5275    pub(crate) fn field_key(&self, key: &str) -> Option<String> {
5276        self.request_path().map(|path| format!("{path}.{key}"))
5277    }
5278
5279    /// [`Self::path`] from the request's plan: a run-data row of a run-data row's list
5280    /// is named under that row (`shipments.1.lines.1.i`).
5281    fn request_path(&self) -> Option<String> {
5282        let origins = self.naming_origins();
5283        if origins.iter().any(|origin| origin.is_inline()) {
5284            return None;
5285        }
5286        Some(
5287            origins
5288                .iter()
5289                .rev()
5290                .map(|origin| match origin {
5291                    RowOrigin::Numbered {
5292                        under: Some(under), ..
5293                    } => format!("{under}.{origin}"),
5294                    origin => origin.to_string(),
5295                })
5296                .collect::<Vec<_>>()
5297                .join("."),
5298        )
5299    }
5300
5301    /// Hops naming this instance from the root plan, when every hop is a `uses` import or a
5302    /// row written in a spec.
5303    pub(crate) fn segments(&self) -> Option<Vec<PathSegment>> {
5304        let mut parts: Vec<Vec<PathSegment>> = Vec::new();
5305        let mut key = Some(self);
5306        while let Some(current) = key {
5307            match &current.row.origin {
5308                RowOrigin::Import { alias } => {
5309                    parts.push(vec![PathSegment::import(alias, &current.row.identity)])
5310                }
5311                RowOrigin::Written { instance, .. } => parts.push(instance.prefix.clone()),
5312                RowOrigin::Numbered { .. } | RowOrigin::Inline { .. } => return None,
5313            }
5314            key = current.owner();
5315        }
5316        Some(parts.into_iter().rev().flatten().collect())
5317    }
5318
5319    /// Hops of the `uses` imports this instance is reached through from the nearest row
5320    /// (or the root) above it, outermost first: empty for a row itself.
5321    pub(crate) fn import_hops(&self) -> Vec<PathSegment> {
5322        let mut hops = Vec::new();
5323        let mut key = Some(self);
5324        while let Some(current) = key {
5325            let RowOrigin::Import { alias } = &current.row.origin else {
5326                break;
5327            };
5328            hops.push(PathSegment::import(alias, &current.row.identity));
5329            key = current.owner();
5330        }
5331        hops.reverse();
5332        hops
5333    }
5334
5335    /// Whether this instance and every owner above it is a `uses` import or a row written
5336    /// in a spec.
5337    pub(crate) fn is_planned(&self) -> bool {
5338        let mut key = Some(self);
5339        while let Some(current) = key {
5340            if !matches!(
5341                current.row.origin,
5342                RowOrigin::Import { .. } | RowOrigin::Written { .. }
5343            ) {
5344                return false;
5345            }
5346            key = current.owner();
5347        }
5348        true
5349    }
5350}
5351
5352impl fmt::Display for InstanceKey {
5353    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5354        for (index, origin) in self.naming_origins().iter().rev().enumerate() {
5355            if index > 0 {
5356                write!(f, ".")?;
5357            }
5358            write!(f, "{origin}")?;
5359        }
5360        Ok(())
5361    }
5362}
5363
5364impl PartialEq for InstanceKey {
5365    fn eq(&self, other: &Self) -> bool {
5366        Arc::ptr_eq(&self.row, &other.row) && self.owner == other.owner
5367    }
5368}
5369
5370impl Eq for InstanceKey {}
5371
5372impl std::hash::Hash for InstanceKey {
5373    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
5374        (Arc::as_ptr(&self.row) as usize).hash(state);
5375        self.owner.hash(state);
5376    }
5377}
5378
5379/// A field of a [`RowInstance`]: a value, or a reference read in the context that holds
5380/// the row.
5381#[derive(Debug, Clone)]
5382pub enum RowBinding {
5383    Bound(OperationResult),
5384    /// Sealed spec-written reference. Not yet forced: resolution happens when a read of
5385    /// the row touches the field, so lists holding rule-bound rows can be read
5386    /// (`-> count`) without evaluating rules the read never reaches.
5387    Deferred {
5388        target: ReferenceTarget,
5389    },
5390}
5391
5392/// A row instance: its spec, where it came from, and its bound fields.
5393///
5394/// `bindings` are positional over the row spec's template plan `data` slots (`index = template.data.get_index_of`).
5395/// A slot that is `None` reads the template's own default or is missing.
5396#[derive(Debug, Clone)]
5397pub struct RowInstance {
5398    pub identity: Arc<SpecIdentity>,
5399    pub origin: RowOrigin,
5400    pub bindings: Box<[Option<RowBinding>]>,
5401}
5402
5403impl RowInstance {
5404    pub fn get_binding(
5405        &self,
5406        template: &crate::planning::execution_plan::ExecutionPlan,
5407        path: &DataPath,
5408    ) -> Option<&RowBinding> {
5409        let index = template.data.get_index_of(path)?;
5410        self.bindings.get(index)?.as_ref()
5411    }
5412
5413    /// Upper-bound byte size of the row's bound fields; see [`ValueKind::structural_byte_size`].
5414    pub fn structural_byte_size(&self) -> usize {
5415        self.bindings
5416            .iter()
5417            .flatten()
5418            .map(|binding| match binding {
5419                RowBinding::Bound(OperationResult::Value(bound)) => {
5420                    bound.value.structural_byte_size()
5421                }
5422                RowBinding::Bound(OperationResult::Veto(_)) | RowBinding::Deferred { .. } => 0,
5423            })
5424            .sum()
5425    }
5426}
5427
5428/// Where a row instance came from. Names missing fields and explanations.
5429#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5430pub enum RowOrigin {
5431    /// Row `number` (1-based) of list `list`: a run-data row. `under` is the
5432    /// evaluation-data key of the run-data row whose list it is (`items.1`); `None` for
5433    /// a list of the request's plan.
5434    Numbered {
5435        list: String,
5436        number: usize,
5437        under: Option<Arc<str>>,
5438    },
5439    /// A row written in the spec at `source`, read through the row spec's template
5440    /// plan. The instance names it relative to the plan holding its list (`staff.2`).
5441    Written {
5442        instance: SpecInstance,
5443        source: Source,
5444        /// The row is a copy of this instance, made when a list reference gives the list
5445        /// its rows (rule 4): what it does not hold is looked up there.
5446        copy_of: Option<Box<InstanceKey>>,
5447    },
5448    /// The row of `uses alias`, named relative to the plan declaring it.
5449    Import { alias: Arc<str> },
5450    /// Row written inline by the `-> with field: value` command at cell `node`, as row
5451    /// `position` (1-based) of its result. Its written fields are values of the plan
5452    /// that holds the command and are read as that plan planned them; the row spec's
5453    /// rules run over them in the row's context. Every field a read names is set:
5454    /// planning rejects reads of unset fields.
5455    Inline { node: NormalFormId, position: usize },
5456}
5457
5458/// 1-based numbered origin of a list row (`items.2`).
5459#[must_use]
5460pub fn numbered_row_origin(list_key: &str, number: usize) -> String {
5461    format!("{list_key}.{number}")
5462}
5463
5464/// Input key of a field of a numbered list row (`items.2.weight`).
5465#[must_use]
5466pub fn row_field_input_key(list_key: &str, number: usize, field_key: &str) -> String {
5467    format!("{}.{field_key}", numbered_row_origin(list_key, number))
5468}
5469
5470impl RowOrigin {
5471    /// Row number (1-based) of a list row, and whether it was appended inline.
5472    pub(crate) fn list_position(&self) -> (usize, bool) {
5473        match self {
5474            RowOrigin::Numbered { number, .. } => (*number, false),
5475            RowOrigin::Written { instance, .. } => (
5476                instance
5477                    .prefix
5478                    .last()
5479                    .and_then(|last| last.row)
5480                    .expect("BUG: written row origin without a row hop"),
5481                false,
5482            ),
5483            RowOrigin::Inline { position, .. } => (*position, true),
5484            RowOrigin::Import { alias } => {
5485                unreachable!("BUG: the row of `uses {alias}` is not a list row")
5486            }
5487        }
5488    }
5489
5490    pub(crate) fn is_inline(&self) -> bool {
5491        matches!(self, RowOrigin::Inline { .. })
5492    }
5493
5494    /// Whether a request made the row: planning knows its template, not the row.
5495    #[cfg(feature = "call-graph-check")]
5496    pub(crate) fn is_request(&self) -> bool {
5497        matches!(
5498            self,
5499            RowOrigin::Numbered { .. }
5500                | RowOrigin::Inline { .. }
5501                | RowOrigin::Written {
5502                    copy_of: Some(_),
5503                    ..
5504                }
5505        )
5506    }
5507}
5508
5509/// How an inline `-> with` row is named in results and explanations.
5510pub(crate) const APPENDED_ROW_LABEL: &str = "appended row";
5511
5512impl fmt::Display for RowOrigin {
5513    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5514        match self {
5515            RowOrigin::Numbered { list, number, .. } => {
5516                write!(f, "{}", numbered_row_origin(list, *number))
5517            }
5518            RowOrigin::Written { instance, .. } => write!(f, "{instance}"),
5519            RowOrigin::Import { alias } => write!(f, "{alias}"),
5520            RowOrigin::Inline { position, .. } => {
5521                write!(f, "{APPENDED_ROW_LABEL} {position}")
5522            }
5523        }
5524    }
5525}
5526
5527/// One evaluated instance-list row as a typed literal.
5528#[must_use]
5529pub fn row_literal(
5530    identity: Arc<SpecIdentity>,
5531    origin: RowOrigin,
5532    bindings: Vec<Option<RowBinding>>,
5533    lemma_type: Arc<LemmaType>,
5534) -> TypedLiteral {
5535    TypedLiteral {
5536        value: ValueKind::Spec(SpecValue::Row(InstanceKey::new(
5537            Arc::new(RowInstance {
5538                identity,
5539                origin,
5540                bindings: bindings.into(),
5541            }),
5542            None,
5543        ))),
5544        lemma_type,
5545    }
5546}
5547
5548/// Field of a row read through the row spec's template plan.
5549#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5550pub enum RowEnd {
5551    Data(DataPath),
5552    Rule(RulePath),
5553}
5554
5555impl fmt::Display for RowEnd {
5556    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5557        match self {
5558            RowEnd::Data(path) => write!(f, "{}", path.input_key()),
5559            RowEnd::Rule(path) => write!(f, "{}", path.input_key()),
5560        }
5561    }
5562}
5563
5564/// Resolved path to a data (created during planning from AST DataReference)
5565///
5566/// Represents a fully resolved path through specs to reach a datum.
5567#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
5568pub struct DataPath {
5569    /// Path segments (each is a cross-spec step)
5570    pub segments: Vec<PathSegment>,
5571    /// Final data name
5572    pub data: String,
5573}
5574
5575impl DataPath {
5576    /// Whether this is data of a global: evaluation data gives it once, at the top, and no
5577    /// row holds it.
5578    #[must_use]
5579    pub fn reads_global(&self) -> bool {
5580        reads_global(&self.segments)
5581    }
5582
5583    /// Create a data path from segments and data name (matches AST DataReference shape)
5584    pub fn new(segments: Vec<PathSegment>, data: String) -> Self {
5585        Self { segments, data }
5586    }
5587
5588    /// Create a local data path (no cross-spec steps)
5589    pub fn local(data: String) -> Self {
5590        Self {
5591            segments: vec![],
5592            data,
5593        }
5594    }
5595
5596    /// Dot-separated key used for matching user-provided data values (e.g. `"order.payment_method"`,
5597    /// `"staff.2.salary"`). Same string as [`Display`]: hops only, no repository or spec names.
5598    pub fn input_key(&self) -> String {
5599        let mut s = String::new();
5600        for segment in &self.segments {
5601            s.push_str(&segment.input_key());
5602            s.push('.');
5603        }
5604        s.push_str(&self.data);
5605        s
5606    }
5607}
5608
5609/// Resolved path to a rule (created during planning from a rule reference).
5610///
5611/// Represents a fully resolved path through specs to reach a rule.
5612#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
5613pub struct RulePath {
5614    /// Path segments (each is a cross-spec step)
5615    pub segments: Vec<PathSegment>,
5616    /// Final rule name
5617    pub rule: String,
5618}
5619
5620impl RulePath {
5621    /// Create a rule path from segments and rule name.
5622    pub fn new(segments: Vec<PathSegment>, rule: String) -> Self {
5623        Self { segments, rule }
5624    }
5625
5626    /// Dot-separated key for Show/run (`alias.rule`), twin of [`DataPath::input_key`].
5627    /// Same string as [`Display`]: alias hops only, no repository or spec names.
5628    pub fn input_key(&self) -> String {
5629        if self.segments.is_empty() {
5630            return self.rule.clone();
5631        }
5632        let mut s = String::new();
5633        for segment in &self.segments {
5634            s.push_str(&segment.input_key());
5635            s.push('.');
5636        }
5637        s.push_str(&self.rule);
5638        s
5639    }
5640}
5641
5642// -----------------------------------------------------------------------------
5643// Resolved expression types (created during planning)
5644// -----------------------------------------------------------------------------
5645
5646/// Resolved expression (all references resolved to paths, all literals typed)
5647///
5648/// Created during planning from AST Expression. All unresolved references
5649/// are converted to DataPath/RulePath, and all literals are typed.
5650/// Resolved expression tree (all references resolved to paths, all literals typed).
5651///
5652/// Nodes live in a flat table and reference children by [`ExprId`]. Created during
5653/// planning from the AST; all unresolved references are converted to DataPath/RulePath.
5654pub type Expression = ExprTree<ExpressionKind>;
5655
5656/// Resolved expression kind (only resolved variants, no unresolved references)
5657#[derive(Debug, Clone, PartialEq)]
5658pub enum ExpressionKind {
5659    /// Resolved literal with type (boxed to keep enum small)
5660    Literal(Box<TypedLiteral>),
5661    /// Resolved data path
5662    DataPath(DataPath),
5663    /// Resolved rule path
5664    RulePath(RulePath),
5665    Logical {
5666        connective: LogicalConnective,
5667        first: ExprId,
5668        steps: Vec<ChainStep<()>>,
5669    },
5670    /// Left fold of `first` over `steps`; every step's operator has one precedence level.
5671    Arithmetic {
5672        first: ExprId,
5673        steps: Vec<ChainStep<ArithmeticComputation>>,
5674    },
5675    Comparison(ExprId, ComparisonComputation, ExprId),
5676    UnitConversion(ExprId, SemanticConversionTarget),
5677    LogicalNegation(ExprId, NegationType),
5678    MathematicalComputation(MathematicalComputation, ExprId),
5679    /// `operand -> round` or `operand -> round step`.
5680    StepRounding {
5681        operand: ExprId,
5682        mode: RoundingMode,
5683        step: Option<ExprId>,
5684    },
5685    Veto(VetoExpression),
5686    /// The `now` keyword — resolved at evaluation to the effective datetime.
5687    Now,
5688    /// Date-relative sugar: `<date_expr> in past` / `in future`
5689    DateRelative(DateRelativeKind, ExprId),
5690    /// Calendar-period sugar: `<date_expr> in [past|future] calendar year|month|week`
5691    DateCalendar(DateCalendarKind, CalendarPeriodUnit, ExprId),
5692    RangeLiteral(ExprId, ExprId),
5693    PastFutureRange(DateRelativeKind, ExprId),
5694    RangeContainment(ExprId, ExprId),
5695    /// Ordered endpoint of a range (`lower` included, `upper` excluded).
5696    RangeBound(RangeBound, ExprId),
5697    /// Whether evaluating the operand produced a veto (no value). Parses as `is veto` syntax.
5698    ResultIsVeto(ExprId),
5699    /// Field of a spec value: `top_bracket.tax`, `top_bracket.finance.fee`, or
5700    /// `(staff -> first).bonus`.
5701    ///
5702    /// Every instance the base yields is a row of its spec, so the field is read through
5703    /// that spec's template plan. A `uses` alias base is its import slot.
5704    SpecMember {
5705        base: ExprId,
5706        path: Vec<String>,
5707        name: String,
5708    },
5709    /// Field of the current row of the list command at `level` (0 = outermost).
5710    ///
5711    /// `end` is the field on the row spec's own plan: every row reads it through its
5712    /// row template.
5713    RowField {
5714        level: u32,
5715        identity: SpecIdentity,
5716        end: RowEnd,
5717        /// Written list qualifier (`children` in `children.is_leaf`), when the
5718        /// source used a qualified row-field reference. `None` for bare unambiguous refs.
5719        qualifier: Option<Vec<String>>,
5720    },
5721    /// Current value row. `list` is a type-only reference to the earlier list expression.
5722    RowValue {
5723        level: u32,
5724        list: ExprId,
5725    },
5726    /// Unless structure: (condition, result) pairs in source order; last true condition wins.
5727    /// First arm is the default (condition is always-true literal).
5728    Piecewise(Vec<(ExprId, ExprId)>),
5729    /// `row_level` is set when arguments read the current list row at that
5730    /// level, through [`Self::RowValue`] or [`Self::RowField`].
5731    ListCommand {
5732        list: ExprId,
5733        op: ListOp,
5734        row_level: Option<u32>,
5735    },
5736}
5737
5738/// Planned postfix list command.
5739#[derive(Debug, Clone, PartialEq)]
5740pub enum ListOp {
5741    Find {
5742        keys: Vec<ExprId>,
5743    },
5744    First,
5745    Last,
5746    Count,
5747    Reduce {
5748        kind: ListReduce,
5749        argument: Option<ExprId>,
5750    },
5751    Predicate {
5752        kind: ListPredKind,
5753        form: crate::parsing::ast::ListPredicateForm,
5754        expr: ExprId,
5755    },
5756    Sort {
5757        descending: bool,
5758        argument: Option<ExprId>,
5759    },
5760    Top {
5761        n: ExprId,
5762    },
5763    With {
5764        rows: Vec<ExprId>,
5765    },
5766    /// Append one row of spec `identity`; each field is a row-spec data path and its value.
5767    WithRow {
5768        identity: SpecIdentity,
5769        fields: Vec<(DataPath, ExprId)>,
5770    },
5771    /// Declare field key(s) on a Spec-element list; lives on the list type, eval no-op.
5772    Key {
5773        fields: Vec<DataPath>,
5774    },
5775}
5776
5777#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
5778pub enum ListReduce {
5779    Sum,
5780    Avg,
5781    Product,
5782    Min,
5783    Max,
5784}
5785
5786impl ListReduce {
5787    pub fn keyword(self) -> &'static str {
5788        match self {
5789            ListReduce::Sum => "sum",
5790            ListReduce::Avg => "avg",
5791            ListReduce::Product => "product",
5792            ListReduce::Min => "min",
5793            ListReduce::Max => "max",
5794        }
5795    }
5796}
5797
5798#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
5799pub enum ListPredKind {
5800    Any,
5801    All,
5802    Where,
5803}
5804
5805impl ListPredKind {
5806    pub fn keyword(self) -> &'static str {
5807        match self {
5808            ListPredKind::Any => "any",
5809            ListPredKind::All => "all",
5810            ListPredKind::Where => "where",
5811        }
5812    }
5813}
5814
5815impl ExprKind for ExpressionKind {
5816    fn for_each_child(&self, mut f: impl FnMut(ExprId)) {
5817        match self {
5818            ExpressionKind::Literal(_)
5819            | ExpressionKind::DataPath(_)
5820            | ExpressionKind::RulePath(_)
5821            | ExpressionKind::Veto(_)
5822            | ExpressionKind::Now
5823            | ExpressionKind::RowField { .. }
5824            | ExpressionKind::RowValue { .. } => {}
5825            ExpressionKind::Logical { first, steps, .. } => {
5826                f(*first);
5827                steps.iter().for_each(|step| f(step.operand));
5828            }
5829            ExpressionKind::Arithmetic { first, steps } => {
5830                f(*first);
5831                steps.iter().for_each(|step| f(step.operand));
5832            }
5833            ExpressionKind::Comparison(left, _, right)
5834            | ExpressionKind::RangeLiteral(left, right)
5835            | ExpressionKind::RangeContainment(left, right) => {
5836                f(*left);
5837                f(*right);
5838            }
5839            ExpressionKind::StepRounding { operand, step, .. } => {
5840                f(*operand);
5841                if let Some(step) = step {
5842                    f(*step);
5843                }
5844            }
5845            ExpressionKind::UnitConversion(inner, _)
5846            | ExpressionKind::LogicalNegation(inner, _)
5847            | ExpressionKind::MathematicalComputation(_, inner)
5848            | ExpressionKind::DateRelative(_, inner)
5849            | ExpressionKind::DateCalendar(_, _, inner)
5850            | ExpressionKind::PastFutureRange(_, inner)
5851            | ExpressionKind::RangeBound(_, inner)
5852            | ExpressionKind::ResultIsVeto(inner)
5853            | ExpressionKind::SpecMember { base: inner, .. } => f(*inner),
5854            ExpressionKind::Piecewise(arms) => arms.iter().for_each(|(condition, result)| {
5855                f(*condition);
5856                f(*result);
5857            }),
5858            ExpressionKind::ListCommand { list, op, .. } => {
5859                f(*list);
5860                op.for_each_child(f);
5861            }
5862        }
5863    }
5864
5865    fn children_mut(&mut self) -> Vec<&mut ExprId> {
5866        match self {
5867            ExpressionKind::Literal(_)
5868            | ExpressionKind::DataPath(_)
5869            | ExpressionKind::RulePath(_)
5870            | ExpressionKind::Veto(_)
5871            | ExpressionKind::Now
5872            | ExpressionKind::RowField { .. }
5873            | ExpressionKind::RowValue { .. } => Vec::new(),
5874            ExpressionKind::Logical { first, steps, .. } => std::iter::once(first)
5875                .chain(steps.iter_mut().map(|step| &mut step.operand))
5876                .collect(),
5877            ExpressionKind::Arithmetic { first, steps } => std::iter::once(first)
5878                .chain(steps.iter_mut().map(|step| &mut step.operand))
5879                .collect(),
5880            ExpressionKind::Comparison(left, _, right)
5881            | ExpressionKind::RangeLiteral(left, right)
5882            | ExpressionKind::RangeContainment(left, right) => vec![left, right],
5883            ExpressionKind::StepRounding { operand, step, .. } => {
5884                let mut children = vec![operand];
5885                if let Some(step) = step {
5886                    children.push(step);
5887                }
5888                children
5889            }
5890            ExpressionKind::UnitConversion(inner, _)
5891            | ExpressionKind::LogicalNegation(inner, _)
5892            | ExpressionKind::MathematicalComputation(_, inner)
5893            | ExpressionKind::DateRelative(_, inner)
5894            | ExpressionKind::DateCalendar(_, _, inner)
5895            | ExpressionKind::PastFutureRange(_, inner)
5896            | ExpressionKind::RangeBound(_, inner)
5897            | ExpressionKind::ResultIsVeto(inner) => vec![inner],
5898            ExpressionKind::SpecMember { base, .. } => vec![base],
5899            ExpressionKind::Piecewise(arms) => arms
5900                .iter_mut()
5901                .flat_map(|(condition, result)| [condition, result])
5902                .collect(),
5903            ExpressionKind::ListCommand { list, op, .. } => {
5904                let mut children = vec![list];
5905                children.extend(op.children_mut());
5906                children
5907            }
5908        }
5909    }
5910}
5911
5912impl ListOp {
5913    fn for_each_child(&self, mut f: impl FnMut(ExprId)) {
5914        match self {
5915            ListOp::First | ListOp::Last | ListOp::Count | ListOp::Key { .. } => {}
5916            ListOp::Find { keys } => keys.iter().copied().for_each(f),
5917            ListOp::Reduce { argument, .. } | ListOp::Sort { argument, .. } => {
5918                argument.iter().copied().for_each(f)
5919            }
5920            ListOp::Predicate { expr, .. } => f(*expr),
5921            ListOp::Top { n } => f(*n),
5922            ListOp::With { rows } => rows.iter().copied().for_each(f),
5923            ListOp::WithRow { fields, .. } => fields.iter().for_each(|(_, value)| f(*value)),
5924        }
5925    }
5926
5927    fn children_mut(&mut self) -> Vec<&mut ExprId> {
5928        match self {
5929            ListOp::First | ListOp::Last | ListOp::Count | ListOp::Key { .. } => Vec::new(),
5930            ListOp::Find { keys } => keys.iter_mut().collect(),
5931            ListOp::Reduce { argument, .. } | ListOp::Sort { argument, .. } => {
5932                argument.iter_mut().collect()
5933            }
5934            ListOp::Predicate { expr, .. } => vec![expr],
5935            ListOp::Top { n } => vec![n],
5936            ListOp::With { rows } => rows.iter_mut().collect(),
5937            ListOp::WithRow { fields, .. } => fields.iter_mut().map(|(_, value)| value).collect(),
5938        }
5939    }
5940}
5941
5942// -----------------------------------------------------------------------------
5943// Resolved types and values
5944// -----------------------------------------------------------------------------
5945
5946/// Where the custom extension chain is rooted: same spec as this type, or imported from another resolved spec.
5947#[derive(Clone, Debug, PartialEq, Eq, Hash)]
5948pub enum TypeDefiningSpec {
5949    /// Parent type is defined in the same spec as this type.
5950    Local,
5951    /// Parent type was resolved from types loaded from another spec.
5952    Import,
5953}
5954
5955/// Root of a custom type's extension chain: the spec version that declares the root type,
5956/// and its name. Types share a unit family only when they share this root declaration;
5957/// a local `money` and an imported `pricing.money` are different families. Two versions
5958/// of `pricing` declare different `pricing <date>.money` families; values from different
5959/// versions do not mix. Interface drift across unpinned versions compares structure with
5960/// [`LemmaType::same_interface`], which ignores the family's effective date.
5961#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
5962pub struct TypeFamily {
5963    pub repository: Option<String>,
5964    pub spec: String,
5965    pub effective: crate::parsing::ast::EffectiveDate,
5966    pub name: String,
5967}
5968
5969impl TypeFamily {
5970    #[must_use]
5971    pub(crate) fn declared_in(spec: &SpecVersionKey, name: &str) -> Self {
5972        Self {
5973            repository: spec.repository.clone(),
5974            spec: spec.spec.clone(),
5975            effective: spec.effective.clone(),
5976            name: name.to_string(),
5977        }
5978    }
5979
5980    /// Whether `spec` (this exact version) declares this family's root.
5981    #[must_use]
5982    pub(crate) fn is_declared_in(&self, spec: &SpecVersionKey) -> bool {
5983        self.repository == spec.repository
5984            && self.spec == spec.spec
5985            && self.effective == spec.effective
5986    }
5987
5988    /// Family identity with the version erased (interface comparisons only).
5989    #[must_use]
5990    pub fn without_effective(&self) -> Self {
5991        Self {
5992            repository: self.repository.clone(),
5993            spec: self.spec.clone(),
5994            effective: crate::parsing::ast::EffectiveDate::Origin,
5995            name: self.name.clone(),
5996        }
5997    }
5998}
5999
6000/// `[<repo> ]<spec>[ <date>].<type>`: the root type named with its declaring spec version.
6001impl fmt::Display for TypeFamily {
6002    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6003        if let Some(repository) = &self.repository {
6004            write!(f, "{repository} ")?;
6005        }
6006        write!(f, "{}", self.spec)?;
6007        if let crate::parsing::ast::EffectiveDate::DateTimeValue(at) = &self.effective {
6008            write!(f, " {at}")?;
6009        }
6010        write!(f, ".{}", self.name)
6011    }
6012}
6013
6014/// What this type extends (primitive built-in or custom type by name).
6015#[derive(Clone, Debug)]
6016pub enum TypeExtends {
6017    /// Extends a primitive built-in type (number, boolean, text, etc.)
6018    Primitive,
6019    /// Extends a custom type: parent is the immediate parent type name; family is the root of the extension chain.
6020    /// `defining_spec` records whether the parent chain is local or imported from another spec.
6021    Custom {
6022        parent: String,
6023        family: TypeFamily,
6024        defining_spec: TypeDefiningSpec,
6025    },
6026}
6027
6028impl PartialEq for TypeExtends {
6029    fn eq(&self, other: &Self) -> bool {
6030        match (self, other) {
6031            (TypeExtends::Primitive, TypeExtends::Primitive) => true,
6032            (
6033                TypeExtends::Custom {
6034                    parent: lp,
6035                    family: lf,
6036                    defining_spec: ld,
6037                },
6038                TypeExtends::Custom {
6039                    parent: rp,
6040                    family: rf,
6041                    defining_spec: rd,
6042                },
6043            ) => lp == rp && lf == rf && ld == rd,
6044            _ => false,
6045        }
6046    }
6047}
6048
6049impl Eq for TypeExtends {}
6050
6051impl std::hash::Hash for TypeExtends {
6052    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
6053        match self {
6054            TypeExtends::Primitive => {
6055                0u8.hash(state);
6056            }
6057            TypeExtends::Custom {
6058                parent,
6059                family,
6060                defining_spec,
6061            } => {
6062                1u8.hash(state);
6063                parent.hash(state);
6064                family.hash(state);
6065                defining_spec.hash(state);
6066            }
6067        }
6068    }
6069}
6070
6071impl TypeExtends {
6072    /// Custom extension in the same spec as the defining type (no cross-spec import for the parent chain).
6073    #[must_use]
6074    pub fn custom_local(parent: String, family: TypeFamily) -> Self {
6075        TypeExtends::Custom {
6076            parent,
6077            family,
6078            defining_spec: TypeDefiningSpec::Local,
6079        }
6080    }
6081
6082    /// Returns the parent type name if this type extends a custom type.
6083    #[must_use]
6084    pub fn parent_name(&self) -> Option<&str> {
6085        match self {
6086            TypeExtends::Primitive => None,
6087            TypeExtends::Custom { parent, .. } => Some(parent.as_str()),
6088        }
6089    }
6090
6091    #[must_use]
6092    fn with_families_without_effective(&self) -> Self {
6093        match self {
6094            TypeExtends::Primitive => TypeExtends::Primitive,
6095            TypeExtends::Custom {
6096                parent,
6097                family,
6098                defining_spec,
6099            } => TypeExtends::Custom {
6100                parent: parent.clone(),
6101                family: family.without_effective(),
6102                defining_spec: defining_spec.clone(),
6103            },
6104        }
6105    }
6106}
6107
6108/// Resolved type after planning
6109///
6110/// Contains a type specification and optional name. Created during planning
6111/// from TypeSpecification in the AST.
6112#[derive(Clone, Debug, PartialEq, Eq, Hash)]
6113pub struct LemmaType {
6114    /// Optional type name (e.g., "age", "temperature")
6115    pub name: Option<String>,
6116    /// The type specification (Boolean, Number, Measure, etc.).
6117    pub specifications: TypeSpecification,
6118    /// What this type extends (primitive or custom from a spec)
6119    pub extends: TypeExtends,
6120    pub(crate) options: TypeOptions,
6121}
6122
6123impl LemmaType {
6124    /// Functional update of the `Measure` payload (units + decomposition).
6125    /// Non-Measure variants pass through unchanged. The transform receives the owned
6126    /// units and decomposition and returns the replacements.
6127    pub fn map_measure<F>(self, f: F) -> Self
6128    where
6129        F: FnOnce(
6130            MeasureUnits,
6131            Option<BaseMeasureVector>,
6132        ) -> (MeasureUnits, Option<BaseMeasureVector>),
6133    {
6134        let LemmaType {
6135            name,
6136            specifications,
6137            extends,
6138            options,
6139        } = self;
6140        let specifications = match specifications {
6141            TypeSpecification::Measure {
6142                minimum,
6143                maximum,
6144                units,
6145                traits,
6146                decomposition,
6147                unit,
6148                help,
6149            } => {
6150                let (units, decomposition) = f(units, decomposition);
6151                TypeSpecification::Measure {
6152                    minimum,
6153                    maximum,
6154                    units,
6155                    traits,
6156                    decomposition,
6157                    unit,
6158                    help,
6159                }
6160            }
6161            other => other,
6162        };
6163        LemmaType {
6164            name,
6165            specifications,
6166            extends,
6167            options,
6168        }
6169    }
6170
6171    /// Create a new type with a name
6172    pub fn new(name: String, specifications: TypeSpecification, extends: TypeExtends) -> Self {
6173        Self {
6174            name: Some(name),
6175            specifications,
6176            extends,
6177            options: TypeOptions::default(),
6178        }
6179    }
6180
6181    /// Create a type without a name (anonymous/inline type)
6182    pub fn without_name(specifications: TypeSpecification, extends: TypeExtends) -> Self {
6183        Self {
6184            name: None,
6185            specifications,
6186            extends,
6187            options: TypeOptions::default(),
6188        }
6189    }
6190
6191    /// Create a primitive type (no name, extends Primitive)
6192    pub fn primitive(specifications: TypeSpecification) -> Self {
6193        Self {
6194            name: None,
6195            specifications,
6196            extends: TypeExtends::Primitive,
6197            options: TypeOptions::default(),
6198        }
6199    }
6200
6201    /// Apply one data command that does not need the surrounding spec.
6202    /// `-> option`, `-> options`, and a spec `-> with` / `-> suggest` are applied
6203    /// by the caller, which already holds the spec.
6204    pub fn apply_constraint(
6205        &mut self,
6206        names: ConstraintNames<'_>,
6207        command: TypeConstraintCommand,
6208        args: &[CommandArg],
6209        declared_suggestion: &mut Option<RawSuggestion>,
6210        declared_value: &mut Option<RawSuggestion>,
6211        resolve_unit: Option<&UnitTokenResolver<'_>>,
6212    ) -> Result<(), String> {
6213        self.specifications.apply_constraint(
6214            names,
6215            command,
6216            args,
6217            declared_suggestion,
6218            declared_value,
6219            resolve_unit,
6220        )
6221    }
6222
6223    /// Value is outside an inline option set. A rule is checked at evaluation, with the static rows.
6224    ///
6225    /// When the option set contains unscaled (dynamic-unit) values and `runtime_scales` is
6226    /// absent, membership is deferred to the evaluation walk (`Ok`).
6227    pub(crate) fn reject_disallowed(
6228        &self,
6229        value: &ValueKind,
6230        runtime_scales: Option<
6231            &std::collections::HashMap<String, crate::computation::rational::RationalInteger>,
6232        >,
6233    ) -> Result<(), String> {
6234        let options = self.options_for_check();
6235        if options.rule.is_some() || options.values.is_empty() {
6236            return Ok(());
6237        }
6238        if options_have_unscaled_measure(&options) {
6239            let Some(scales) = runtime_scales else {
6240                return Ok(());
6241            };
6242            return if static_option_match_with_scales(&options, value, scales)? {
6243                Ok(())
6244            } else {
6245                Err(disallowed_message(self, &options, value, None))
6246            };
6247        }
6248        if static_option_match(&options, value) {
6249            return Ok(());
6250        }
6251        Err(disallowed_message(self, &options, value, None))
6252    }
6253
6254    /// Rule whose list is added to the allowed set, on this type or on a list's element.
6255    #[must_use]
6256    pub fn options_rule(&self) -> Option<&str> {
6257        if let Some(name) = &self.options.rule {
6258            return Some(name.as_str());
6259        }
6260        if let TypeSpecification::List { element, .. } = &self.specifications {
6261            if let Some(name) = &element.options.rule {
6262                return Some(name.as_str());
6263            }
6264        }
6265        None
6266    }
6267
6268    /// Inline option literals that still need a runtime scale before membership.
6269    #[must_use]
6270    pub(crate) fn has_unscaled_options(&self) -> bool {
6271        options_have_unscaled_measure(&self.options_for_check())
6272    }
6273
6274    /// Evaluation re-checks a named options rule, or a static set that includes
6275    /// dynamic-unit (unscaled) option literals.
6276    #[must_use]
6277    pub(crate) fn needs_runtime_option_check(&self) -> bool {
6278        self.options_rule().is_some() || self.has_unscaled_options()
6279    }
6280
6281    /// Static option displays. A rule that adds rows on a run is not included.
6282    #[must_use]
6283    pub fn static_options(&self) -> Vec<String> {
6284        let options = self.options_for_check();
6285        options
6286            .values
6287            .iter()
6288            .map(|option| self.display_bound(&option.value))
6289            .collect()
6290    }
6291
6292    /// Inline `-> option` values on this type (and a list's element, when both carry options).
6293    /// A named `-> options` rule is not enumerated.
6294    #[must_use]
6295    pub fn inline_option_values(&self) -> Vec<BoundValueKind> {
6296        self.options_for_check()
6297            .values
6298            .iter()
6299            .map(|option| option.value.clone())
6300            .collect()
6301    }
6302
6303    pub(crate) fn display_bound(&self, bound: &BoundValueKind) -> String {
6304        typed_literal_from_bound(bound, &Arc::new(self.clone())).display_value()
6305    }
6306
6307    /// Borrow the set that applies. Clone only when a list and its element both carry options.
6308    pub(crate) fn options_for_check(&self) -> std::borrow::Cow<'_, TypeOptions> {
6309        match &self.specifications {
6310            TypeSpecification::List { element, .. }
6311                if !self.options.is_empty() && !element.options.is_empty() =>
6312            {
6313                let mut options = self.options.clone();
6314                options
6315                    .values
6316                    .extend(element.options.values.iter().cloned());
6317                if options.rule.is_none() {
6318                    options.rule.clone_from(&element.options.rule);
6319                }
6320                std::borrow::Cow::Owned(options)
6321            }
6322            TypeSpecification::List { element, .. } if !element.options.is_empty() => {
6323                std::borrow::Cow::Borrowed(&element.options)
6324            }
6325            _ => std::borrow::Cow::Borrowed(&self.options),
6326        }
6327    }
6328
6329    /// `None` when `value` is in the static set or in `rule_rows`.
6330    ///
6331    /// When the static set has unscaled options and `runtime_scales` is absent, returns
6332    /// `None` so the caller can defer. When scales are present, settles before matching.
6333    /// Settle failure returns `Some(message)`.
6334    pub(crate) fn explain_disallowed(
6335        &self,
6336        value: &ValueKind,
6337        rule_rows: Option<&ListValue>,
6338        runtime_scales: Option<
6339            &std::collections::HashMap<String, crate::computation::rational::RationalInteger>,
6340        >,
6341    ) -> Option<String> {
6342        let options = self.options_for_check();
6343        let needs_scales = options_have_unscaled_measure(&options)
6344            || rule_rows
6345                .is_some_and(|rows| rows.iter().any(|row| row.value.has_unscaled_measure()))
6346            || value.has_unscaled_measure();
6347        if needs_scales && runtime_scales.is_none() {
6348            return None;
6349        }
6350        let allowed = |candidate: &ValueKind| -> Result<bool, String> {
6351            if let Some(scales) = runtime_scales {
6352                if options_have_unscaled_measure(&options) {
6353                    if static_option_match_with_scales(&options, candidate, scales)? {
6354                        return Ok(true);
6355                    }
6356                } else if static_option_match(&options, candidate) {
6357                    return Ok(true);
6358                }
6359                if let Some(rows) = rule_rows {
6360                    let settled_candidate = settle_value_kind_with_scales(candidate, scales)?;
6361                    for option in rows.iter() {
6362                        let settled_option = settle_value_kind_with_scales(&option.value, scales)?;
6363                        if option_values_match(&settled_option, &settled_candidate) {
6364                            return Ok(true);
6365                        }
6366                    }
6367                    return Ok(false);
6368                }
6369                return Ok(options.is_empty());
6370            }
6371            if static_option_match(&options, candidate) {
6372                return Ok(true);
6373            }
6374            if let Some(rows) = rule_rows {
6375                return Ok(rows
6376                    .iter()
6377                    .any(|option| option_values_match(&option.value, candidate)));
6378            }
6379            Ok(options.is_empty())
6380        };
6381        match (&self.specifications, value) {
6382            (TypeSpecification::List { .. }, ValueKind::List(rows)) => {
6383                for row in rows.iter() {
6384                    match allowed(&row.value) {
6385                        Ok(true) => {}
6386                        Ok(false) => {
6387                            return Some(disallowed_message(self, &options, &row.value, rule_rows));
6388                        }
6389                        Err(message) => return Some(message),
6390                    }
6391                }
6392                None
6393            }
6394            _ => match allowed(value) {
6395                Ok(true) => None,
6396                Ok(false) => Some(disallowed_message(self, &options, value, rule_rows)),
6397                Err(message) => Some(message),
6398            },
6399        }
6400    }
6401
6402    /// Prefer `unit_name` for [`measure_runtime_signature`] (bind / signature-index hit).
6403    ///
6404    /// Writes `unit` onto `Measure` or `Ratio` specifications. Any other variant panics.
6405    #[must_use]
6406    pub fn with_unit(mut self, unit_name: impl Into<String>) -> Self {
6407        let unit_name = unit_name.into();
6408        match &mut self.specifications {
6409            TypeSpecification::Measure { unit, .. } | TypeSpecification::Ratio { unit, .. } => {
6410                *unit = Some(unit_name);
6411            }
6412            other => panic!(
6413                "BUG: with_unit called on non-measure/non-ratio type {}",
6414                other
6415            ),
6416        }
6417        self
6418    }
6419
6420    /// Prefix dynamic scale references on `lemma_type` with the `uses` hops from
6421    /// import `base_alias` of spec `importer`, through nested import names along
6422    /// `member_path`. `nested_import` returns the identity of the import slot named
6423    /// `segment` on the template of the current identity, or `None` when that hop is
6424    /// not an import.
6425    #[must_use]
6426    pub(crate) fn reanchor_through_import_path(
6427        lemma_type: Arc<LemmaType>,
6428        importer: &SpecIdentity,
6429        base_alias: &str,
6430        base_identity: &SpecIdentity,
6431        member_path: &[String],
6432        mut nested_import: impl FnMut(&SpecIdentity, &str) -> Option<SpecIdentity>,
6433    ) -> Arc<LemmaType> {
6434        let mut hops = vec![PathSegment::import(base_alias, base_identity)];
6435        let mut identity = base_identity.clone();
6436        for segment in member_path {
6437            let Some(next) = nested_import(&identity, segment) else {
6438                break;
6439            };
6440            hops.push(PathSegment::import(segment, &next));
6441            identity = next;
6442        }
6443        let mut out = lemma_type.as_ref().clone();
6444        for index in (0..hops.len()).rev() {
6445            let into = match index.checked_sub(1) {
6446                Some(outer) => ScaleOwner::of_segment(&hops[outer]),
6447                None => ScaleOwner::new(importer.repository.as_deref(), &importer.spec),
6448            };
6449            out = out.with_scale_import_hop(&hops[index], &into);
6450        }
6451        Arc::new(out)
6452    }
6453
6454    /// Clone as spec `into` reads it through the `uses` alias hop `segment`: every
6455    /// dynamic unit scale reference written in the used spec gains the hop. The
6456    /// declaring spec's coordinates stay on the type of the declaring spec itself;
6457    /// this clone is the importing spec's instance view of the same type. A reference
6458    /// of another spec, such as a unit of the used spec's rows, is left as it is.
6459    #[must_use]
6460    pub(crate) fn with_scale_import_hop(&self, segment: &PathSegment, into: &ScaleOwner) -> Self {
6461        self.with_scale_targets_mapped(&ScaleOwner::of_segment(segment), into, &|segments| {
6462            segments.insert(0, segment.clone())
6463        })
6464    }
6465
6466    /// Clone with `map` applied to the hops of every dynamic unit scale reference
6467    /// written in spec `from`, which becomes a reference written in spec `into`.
6468    #[must_use]
6469    pub(crate) fn with_scale_targets_mapped<F: Fn(&mut Vec<PathSegment>)>(
6470        &self,
6471        from: &ScaleOwner,
6472        into: &ScaleOwner,
6473        map: &F,
6474    ) -> Self {
6475        fn map_units<F: Fn(&mut Vec<PathSegment>)>(
6476            units: &mut MeasureUnits,
6477            from: &ScaleOwner,
6478            into: &ScaleOwner,
6479            map: &F,
6480        ) {
6481            for unit in units.0.iter_mut() {
6482                if let crate::literals::UnitScale::Reference { factors, .. } = &mut unit.scale {
6483                    for (scale, _) in factors.iter_mut() {
6484                        if scale.owner != *from {
6485                            continue;
6486                        }
6487                        match &mut scale.target {
6488                            ReferenceTarget::Data(path) => map(&mut path.segments),
6489                            ReferenceTarget::Rule(rule) => map(&mut rule.segments),
6490                        }
6491                        scale.owner = into.clone();
6492                    }
6493                }
6494            }
6495        }
6496        fn map_specifications<F: Fn(&mut Vec<PathSegment>)>(
6497            specifications: &mut TypeSpecification,
6498            from: &ScaleOwner,
6499            into: &ScaleOwner,
6500            map: &F,
6501        ) {
6502            match specifications {
6503                TypeSpecification::Measure { units, .. }
6504                | TypeSpecification::MeasureRange { units, .. } => {
6505                    map_units(units, from, into, map);
6506                }
6507                TypeSpecification::List { element, .. } => {
6508                    let mapped = element.with_scale_targets_mapped(from, into, map);
6509                    *element = Arc::new(mapped);
6510                }
6511                _ => {}
6512            }
6513        }
6514        let mut out = self.clone();
6515        map_specifications(&mut out.specifications, from, into, map);
6516        out
6517    }
6518
6519    /// Scale factors of `unit_name` when that unit is reference-scaled on this type.
6520    /// Targets are in the coordinates of the spec that holds this type Arc
6521    /// (`uses` hops are already prefixed). Empty when the unit is not dynamic.
6522    #[must_use]
6523    pub(crate) fn unit_scale_factors(&self, unit_name: &str) -> &[(ScaleTarget, i32)] {
6524        self.measure_units_table()
6525            .and_then(|units| units.get(unit_name).ok())
6526            .map(MeasureUnit::resolved_scale_factors)
6527            .unwrap_or(&[])
6528    }
6529
6530    /// Every scale target of every reference-scaled unit on this measure type,
6531    /// in declaration order (factors flattened per unit).
6532    #[must_use]
6533    pub(crate) fn dynamic_scale_targets(&self) -> Vec<ScaleTarget> {
6534        let Some(units) = self.measure_units_table() else {
6535            return Vec::new();
6536        };
6537        units
6538            .iter()
6539            .flat_map(|unit| {
6540                unit.resolved_scale_factors()
6541                    .iter()
6542                    .map(|(target, _)| target.clone())
6543            })
6544            .collect()
6545    }
6546
6547    /// Written unit on a measure or ratio specification, if any.
6548    #[must_use]
6549    pub fn unit(&self) -> Option<&str> {
6550        match &self.specifications {
6551            TypeSpecification::Measure { unit, .. } | TypeSpecification::Ratio { unit, .. } => {
6552                unit.as_deref()
6553            }
6554            _ => None,
6555        }
6556    }
6557
6558    /// Get the type name, or a default based on the type specification
6559    pub fn name(&self) -> String {
6560        self.name
6561            .clone()
6562            .unwrap_or_else(|| self.specifications.to_string())
6563    }
6564
6565    /// Check if this type is boolean
6566    pub fn is_boolean(&self) -> bool {
6567        matches!(&self.specifications, TypeSpecification::Boolean { .. })
6568    }
6569
6570    pub fn matches_primitive_kind(&self, kind: PrimitiveKind) -> bool {
6571        matches!(
6572            (kind, &self.specifications),
6573            (PrimitiveKind::Number, TypeSpecification::Number { .. })
6574                | (PrimitiveKind::Text, TypeSpecification::Text { .. })
6575                | (PrimitiveKind::Boolean, TypeSpecification::Boolean { .. })
6576                | (PrimitiveKind::Date, TypeSpecification::Date { .. })
6577                | (PrimitiveKind::Time, TypeSpecification::Time { .. })
6578                | (PrimitiveKind::Ratio, TypeSpecification::Ratio { .. })
6579                | (PrimitiveKind::Measure, TypeSpecification::Measure { .. })
6580        )
6581    }
6582
6583    /// Check if this type is measure
6584    pub fn is_measure(&self) -> bool {
6585        matches!(&self.specifications, TypeSpecification::Measure { .. })
6586    }
6587
6588    pub fn is_measure_range(&self) -> bool {
6589        matches!(&self.specifications, TypeSpecification::MeasureRange { .. })
6590    }
6591
6592    /// Check if this type is number (dimensionless)
6593    pub fn is_number(&self) -> bool {
6594        matches!(&self.specifications, TypeSpecification::Number { .. })
6595    }
6596
6597    pub fn is_number_range(&self) -> bool {
6598        matches!(&self.specifications, TypeSpecification::NumberRange { .. })
6599    }
6600
6601    /// Check if this type is numeric (either measure or number)
6602    pub fn is_numeric(&self) -> bool {
6603        matches!(
6604            &self.specifications,
6605            TypeSpecification::Measure { .. } | TypeSpecification::Number { .. }
6606        )
6607    }
6608
6609    /// Check if this type is text
6610    pub fn is_text(&self) -> bool {
6611        matches!(&self.specifications, TypeSpecification::Text { .. })
6612    }
6613
6614    /// Check if this type is date
6615    pub fn is_date(&self) -> bool {
6616        matches!(&self.specifications, TypeSpecification::Date { .. })
6617    }
6618
6619    pub fn is_date_range(&self) -> bool {
6620        matches!(&self.specifications, TypeSpecification::DateRange { .. })
6621    }
6622
6623    pub fn is_time_range(&self) -> bool {
6624        matches!(&self.specifications, TypeSpecification::TimeRange { .. })
6625    }
6626
6627    /// Check if this type is time
6628    pub fn is_time(&self) -> bool {
6629        matches!(&self.specifications, TypeSpecification::Time { .. })
6630    }
6631
6632    pub fn has_trait_duration(&self) -> bool {
6633        match &self.specifications {
6634            TypeSpecification::Measure { traits, .. } => traits.contains(&MeasureTrait::Duration),
6635            _ => false,
6636        }
6637    }
6638
6639    pub fn is_duration_like_measure(&self) -> bool {
6640        if !self.is_measure() {
6641            return false;
6642        }
6643        if self.has_trait_duration() {
6644            return true;
6645        }
6646        self.is_anonymous_measure()
6647            && self
6648                .measure_type_decomposition()
6649                .is_some_and(|d| *d == duration_decomposition())
6650    }
6651
6652    pub fn is_duration_like(&self) -> bool {
6653        self.is_duration_like_measure()
6654    }
6655
6656    pub fn has_trait_calendar(&self) -> bool {
6657        match &self.specifications {
6658            TypeSpecification::Measure { traits, .. } => traits.contains(&MeasureTrait::Calendar),
6659            _ => false,
6660        }
6661    }
6662
6663    pub fn is_calendar_like_measure(&self) -> bool {
6664        if !self.is_measure() {
6665            return false;
6666        }
6667        if self.has_trait_calendar() {
6668            return true;
6669        }
6670        self.is_anonymous_measure()
6671            && self
6672                .measure_type_decomposition()
6673                .is_some_and(|d| *d == calendar_decomposition())
6674    }
6675
6676    pub fn is_calendar_like(&self) -> bool {
6677        self.is_calendar_like_measure()
6678    }
6679
6680    /// Check if this type is ratio
6681    pub fn is_ratio(&self) -> bool {
6682        matches!(&self.specifications, TypeSpecification::Ratio { .. })
6683    }
6684
6685    pub fn is_ratio_range(&self) -> bool {
6686        matches!(&self.specifications, TypeSpecification::RatioRange { .. })
6687    }
6688
6689    pub fn is_calendar_measure_range(&self) -> bool {
6690        matches!(
6691            &self.specifications,
6692            TypeSpecification::MeasureRange { decomposition: Some(decomposition), .. }
6693                if *decomposition == calendar_decomposition()
6694        )
6695    }
6696
6697    pub fn is_calendar_like_range(&self) -> bool {
6698        self.is_calendar_measure_range()
6699    }
6700
6701    pub fn is_range(&self) -> bool {
6702        matches!(
6703            &self.specifications,
6704            TypeSpecification::DateRange { .. }
6705                | TypeSpecification::TimeRange { .. }
6706                | TypeSpecification::NumberRange { .. }
6707                | TypeSpecification::MeasureRange { .. }
6708                | TypeSpecification::RatioRange { .. }
6709        )
6710    }
6711
6712    /// Check if this type is a spec instance.
6713    pub fn is_spec(&self) -> bool {
6714        matches!(&self.specifications, TypeSpecification::Spec { .. })
6715    }
6716
6717    pub fn is_list(&self) -> bool {
6718        matches!(&self.specifications, TypeSpecification::List { .. })
6719    }
6720
6721    pub fn list_element_spec(&self) -> Option<&TypeSpecification> {
6722        match &self.specifications {
6723            TypeSpecification::List { element, .. } => Some(&element.specifications),
6724            _ => None,
6725        }
6726    }
6727
6728    pub fn list_of(element: Arc<LemmaType>) -> Self {
6729        Self {
6730            name: Some(format!("{} list", element.name())),
6731            specifications: TypeSpecification::List {
6732                element,
6733                key: ListKey::Numbered,
6734                help: String::new(),
6735            },
6736            extends: TypeExtends::Primitive,
6737            options: TypeOptions::default(),
6738        }
6739    }
6740
6741    /// Element type of a list type (`money` for `money list`).
6742    pub fn list_element_lemma_type(&self) -> &Arc<LemmaType> {
6743        let TypeSpecification::List { element, .. } = &self.specifications else {
6744            panic!(
6745                "BUG: list_element_lemma_type on non-list type {}",
6746                self.name()
6747            );
6748        };
6749        element
6750    }
6751
6752    /// Spec identity when this type is a spec instance.
6753    #[must_use]
6754    pub fn spec_identity(&self) -> Option<&SpecIdentity> {
6755        match &self.specifications {
6756            TypeSpecification::Spec { spec } => Some(spec),
6757            _ => None,
6758        }
6759    }
6760
6761    /// Check if this type is veto
6762    pub fn vetoed(&self) -> bool {
6763        matches!(&self.specifications, TypeSpecification::Veto { .. })
6764    }
6765
6766    /// True if this type is the undetermined sentinel (type could not be inferred).
6767    pub fn is_undetermined(&self) -> bool {
6768        matches!(&self.specifications, TypeSpecification::Undetermined)
6769    }
6770
6771    /// Check if two types have the same base type specification (ignoring constraints)
6772    pub fn has_same_base_type(&self, other: &LemmaType) -> bool {
6773        use TypeSpecification::*;
6774        matches!(
6775            (&self.specifications, &other.specifications),
6776            (Boolean { .. }, Boolean { .. })
6777                | (Number { .. }, Number { .. })
6778                | (NumberRange { .. }, NumberRange { .. })
6779                | (Measure { .. }, Measure { .. })
6780                | (MeasureRange { .. }, MeasureRange { .. })
6781                | (Text { .. }, Text { .. })
6782                | (Date { .. }, Date { .. })
6783                | (DateRange { .. }, DateRange { .. })
6784                | (Time { .. }, Time { .. })
6785                | (TimeRange { .. }, TimeRange { .. })
6786                | (Ratio { .. }, Ratio { .. })
6787                | (RatioRange { .. }, RatioRange { .. })
6788                | (Veto { .. }, Veto { .. })
6789                | (Undetermined, Undetermined)
6790                | (Spec { .. }, Spec { .. })
6791                | (List { .. }, List { .. })
6792        )
6793    }
6794
6795    /// Root of the custom extension chain; `None` for primitive and anonymous types.
6796    #[must_use]
6797    pub fn family(&self) -> Option<&TypeFamily> {
6798        match &self.extends {
6799            TypeExtends::Custom { family, .. } => Some(family),
6800            TypeExtends::Primitive => None,
6801        }
6802    }
6803
6804    /// Element type of a measure or ratio range. Keeps the range's [`TypeExtends`]
6805    /// (and thus its [`TypeFamily`]). Name is the family's root name when the
6806    /// range extends a named type; otherwise the range's own name.
6807    #[must_use]
6808    pub fn range_element_type(&self) -> Arc<LemmaType> {
6809        let element_spec = self
6810            .specifications
6811            .element_from_range()
6812            .expect("BUG: range_element_type requires a range specification");
6813        let name = match &self.extends {
6814            TypeExtends::Custom { family, .. } => Some(family.name.clone()),
6815            TypeExtends::Primitive => self.name.clone(),
6816        };
6817        Arc::new(LemmaType {
6818            name,
6819            specifications: element_spec,
6820            extends: self.extends.clone(),
6821            options: TypeOptions::default(),
6822        })
6823    }
6824
6825    /// Unit family of a measure or measure-range type.
6826    #[must_use]
6827    pub fn measure_family(&self) -> Option<&TypeFamily> {
6828        (self.is_measure() || self.is_measure_range())
6829            .then(|| self.family())
6830            .flatten()
6831    }
6832
6833    /// Type of the values this type holds: itself, or its (nested) list element.
6834    #[must_use]
6835    pub(crate) fn held_value_type(&self) -> &LemmaType {
6836        let mut current = self;
6837        while current.is_list() {
6838            current = current.list_element_lemma_type().as_ref();
6839        }
6840        current
6841    }
6842
6843    /// Measure family of the values this type holds: its own, or its list element's.
6844    #[must_use]
6845    pub(crate) fn held_measure_family(&self) -> Option<&TypeFamily> {
6846        self.held_value_type().measure_family()
6847    }
6848
6849    /// Unit family of a ratio or ratio-range type.
6850    #[must_use]
6851    pub fn ratio_family(&self) -> Option<&TypeFamily> {
6852        (self.is_ratio() || self.is_ratio_range())
6853            .then(|| self.family())
6854            .flatten()
6855    }
6856
6857    /// Unit family of a measure or ratio type.
6858    #[must_use]
6859    pub(crate) fn unit_family(&self) -> Option<&TypeFamily> {
6860        self.measure_family().or_else(|| self.ratio_family())
6861    }
6862
6863    /// Root type name of [`Self::measure_family`], for display.
6864    #[must_use]
6865    pub fn measure_family_name(&self) -> Option<&str> {
6866        self.measure_family().map(|family| family.name.as_str())
6867    }
6868
6869    /// Root type name of [`Self::ratio_family`], for display.
6870    #[must_use]
6871    pub fn ratio_family_name(&self) -> Option<&str> {
6872        self.ratio_family().map(|family| family.name.as_str())
6873    }
6874
6875    /// Same base kind and, for measures / measure ranges, the same named family:
6876    /// the relation under which two types describe the same values. Names and
6877    /// constraints may differ. Ratio and RatioRange stay base-kind only.
6878    #[must_use]
6879    pub(crate) fn same_value_type(&self, other: &LemmaType) -> bool {
6880        if !self.has_same_base_type(other) {
6881            return false;
6882        }
6883        if self.is_measure() {
6884            return match (self.measure_family(), other.measure_family()) {
6885                (Some(_), Some(_)) => self.same_measure_family(other),
6886                (None, None) => {
6887                    self.measure_type_decomposition() == other.measure_type_decomposition()
6888                }
6889                _ => false,
6890            };
6891        }
6892        if let (
6893            TypeSpecification::Spec { spec: self_spec },
6894            TypeSpecification::Spec { spec: other_spec },
6895        ) = (&self.specifications, &other.specifications)
6896        {
6897            return self_spec == other_spec;
6898        }
6899        if let (
6900            TypeSpecification::List {
6901                element: self_element,
6902                key: self_key,
6903                ..
6904            },
6905            TypeSpecification::List {
6906                element: other_element,
6907                key: other_key,
6908                ..
6909            },
6910        ) = (&self.specifications, &other.specifications)
6911        {
6912            return self_key == other_key && self_element.same_value_type(other_element);
6913        }
6914        if self.is_measure_range() {
6915            match (self.family(), other.family()) {
6916                (Some(self_family), Some(other_family)) => self_family == other_family,
6917                (None, None) => {
6918                    let self_element = self
6919                        .specifications
6920                        .element_from_range()
6921                        .expect("BUG: MeasureRange always defines element_from_range");
6922                    let other_element = other
6923                        .specifications
6924                        .element_from_range()
6925                        .expect("BUG: MeasureRange always defines element_from_range");
6926                    match (&self_element, &other_element) {
6927                        (
6928                            TypeSpecification::Measure {
6929                                decomposition: self_decomp,
6930                                ..
6931                            },
6932                            TypeSpecification::Measure {
6933                                decomposition: other_decomp,
6934                                ..
6935                            },
6936                        ) => self_decomp == other_decomp,
6937                        _ => unreachable!("BUG: element_from_range of MeasureRange yields Measure"),
6938                    }
6939                }
6940                _ => false,
6941            }
6942        } else {
6943            true
6944        }
6945    }
6946
6947    /// Drop a written unit so a path/reference expression type does not claim
6948    /// the stored value named that unit. Literals and `as <unit>` results keep
6949    /// units via [`Self::with_unit`].
6950    #[must_use]
6951    pub(crate) fn without_written_unit(&self) -> Self {
6952        let mut cleared = self.clone();
6953        match &mut cleared.specifications {
6954            TypeSpecification::Measure { unit, .. } | TypeSpecification::Ratio { unit, .. } => {
6955                *unit = None;
6956            }
6957            _ => {}
6958        }
6959        cleared
6960    }
6961
6962    /// Clear slot bounds, help, and written unit so a computed/generalized type
6963    /// does not carry either operand's constraints.
6964    #[must_use]
6965    pub(crate) fn without_slot_bounds(&self) -> Self {
6966        let mut cleared = self.without_written_unit();
6967        match &mut cleared.specifications {
6968            TypeSpecification::Measure {
6969                minimum,
6970                maximum,
6971                help,
6972                ..
6973            } => {
6974                *minimum = None;
6975                *maximum = None;
6976                *help = String::new();
6977            }
6978            TypeSpecification::Ratio {
6979                minimum,
6980                maximum,
6981                help,
6982                ..
6983            } => {
6984                *minimum = None;
6985                *maximum = None;
6986                *help = String::new();
6987            }
6988            TypeSpecification::Number {
6989                minimum,
6990                maximum,
6991                help,
6992                ..
6993            } => {
6994                *minimum = None;
6995                *maximum = None;
6996                *help = String::new();
6997            }
6998            TypeSpecification::Date {
6999                minimum,
7000                maximum,
7001                help,
7002                ..
7003            } => {
7004                *minimum = None;
7005                *maximum = None;
7006                *help = String::new();
7007            }
7008            TypeSpecification::Time {
7009                minimum,
7010                maximum,
7011                help,
7012                ..
7013            } => {
7014                *minimum = None;
7015                *maximum = None;
7016                *help = String::new();
7017            }
7018            TypeSpecification::MeasureRange {
7019                minimum,
7020                maximum,
7021                help,
7022                ..
7023            } => {
7024                *minimum = None;
7025                *maximum = None;
7026                *help = String::new();
7027            }
7028            TypeSpecification::DateRange {
7029                minimum,
7030                maximum,
7031                help,
7032                ..
7033            } => {
7034                *minimum = None;
7035                *maximum = None;
7036                *help = String::new();
7037            }
7038            TypeSpecification::TimeRange {
7039                minimum,
7040                maximum,
7041                help,
7042                ..
7043            } => {
7044                *minimum = None;
7045                *maximum = None;
7046                *help = String::new();
7047            }
7048            TypeSpecification::NumberRange {
7049                minimum,
7050                maximum,
7051                help,
7052                ..
7053            } => {
7054                *minimum = None;
7055                *maximum = None;
7056                *help = String::new();
7057            }
7058            TypeSpecification::RatioRange {
7059                minimum,
7060                maximum,
7061                help,
7062                ..
7063            } => {
7064                *minimum = None;
7065                *maximum = None;
7066                *help = String::new();
7067            }
7068            TypeSpecification::Boolean { help, .. } | TypeSpecification::Text { help, .. } => {
7069                *help = String::new();
7070            }
7071            TypeSpecification::Veto { .. }
7072            | TypeSpecification::Undetermined
7073            | TypeSpecification::Spec { .. }
7074            | TypeSpecification::List { .. } => {}
7075        }
7076        cleared
7077    }
7078
7079    /// Returns true if both types are measure and belong to the same named measure family.
7080    #[must_use]
7081    pub fn same_measure_family(&self, other: &LemmaType) -> bool {
7082        if !self.is_measure() || !other.is_measure() {
7083            return false;
7084        }
7085        match (self.measure_family(), other.measure_family()) {
7086            (Some(self_family), Some(other_family)) => self_family == other_family,
7087            _ => false,
7088        }
7089    }
7090
7091    /// Structural equality for interface drift: same as [`PartialEq`] but family
7092    /// versions (`TypeFamily::effective`) are ignored. Unpinned imports spanning
7093    /// unchanged versions of a dependency compare equal; real changes still differ.
7094    #[must_use]
7095    pub fn same_interface(&self, other: &Self) -> bool {
7096        self.with_families_without_effective() == other.with_families_without_effective()
7097    }
7098
7099    /// Like [`Self::same_interface`], but [`TypeOptions`] may differ. Used for
7100    /// `uses … -> effective` where option sets change across temporal versions.
7101    #[must_use]
7102    pub fn same_interface_ignoring_options(&self, other: &Self) -> bool {
7103        let mut left = self.with_families_without_effective();
7104        let mut right = other.with_families_without_effective();
7105        left.options = TypeOptions::default();
7106        right.options = TypeOptions::default();
7107        left == right
7108    }
7109
7110    /// Clone with every [`TypeFamily::effective`] set to [`EffectiveDate::Origin`].
7111    #[must_use]
7112    pub fn with_families_without_effective(&self) -> Self {
7113        Self {
7114            name: self.name.clone(),
7115            specifications: self.specifications.with_families_without_effective(),
7116            extends: self.extends.with_families_without_effective(),
7117            options: self.options.clone(),
7118        }
7119    }
7120
7121    #[must_use]
7122    pub fn compatible_with_anonymous_measure(&self, other: &LemmaType) -> bool {
7123        if !self.is_measure() || !other.is_measure() {
7124            return false;
7125        }
7126        if !self.is_anonymous_measure() && !other.is_anonymous_measure() {
7127            return false;
7128        }
7129        match (
7130            self.measure_type_decomposition(),
7131            other.measure_type_decomposition(),
7132        ) {
7133            (Some(a), Some(b)) => a == b,
7134            _ => false,
7135        }
7136    }
7137
7138    /// Create a Veto LemmaType
7139    pub fn veto_type() -> Self {
7140        Self::primitive(TypeSpecification::veto())
7141    }
7142
7143    /// LemmaType sentinel for undetermined type (used during inference when a type cannot be determined).
7144    /// Propagates through expressions and is never present in a validated graph.
7145    pub fn undetermined_type() -> Self {
7146        Self::primitive(TypeSpecification::Undetermined)
7147    }
7148
7149    /// Input scale on a number declaration. Rejects a supplied value with more
7150    /// fractional digits. Not applied when a result is published.
7151    pub fn decimal_places(&self) -> Option<u8> {
7152        match &self.specifications {
7153            TypeSpecification::Number { decimals, .. } => *decimals,
7154            _ => None,
7155        }
7156    }
7157
7158    /// Convert a rational magnitude to an API [`Decimal`] (28-scale boundary).
7159    ///
7160    /// Returns [`NumericFailure::Overflow`] when |magnitude| > Decimal::MAX
7161    /// (callers map this to a decimal-limit Veto). Does not apply `decimals`.
7162    pub fn try_rational_as_decimal(
7163        &self,
7164        magnitude: &crate::computation::rational::RationalInteger,
7165    ) -> Result<rust_decimal::Decimal, crate::computation::rational::NumericFailure> {
7166        let decimal = magnitude.try_to_decimal()?;
7167        Ok(format_decimal_for_api(decimal))
7168    }
7169
7170    /// Convert a canonical measure magnitude in the named declared unit to an API [`Decimal`].
7171    pub fn try_measure_canonical_as_decimal_in_unit(
7172        &self,
7173        canonical_magnitude: &crate::computation::rational::RationalInteger,
7174        unit_name: &str,
7175    ) -> Result<rust_decimal::Decimal, crate::computation::rational::NumericFailure> {
7176        use crate::computation::rational::checked_div;
7177        let unit_factor = self.measure_unit_factor(unit_name);
7178        let magnitude_in_unit = checked_div(canonical_magnitude, unit_factor)?;
7179        self.try_rational_as_decimal(&magnitude_in_unit)
7180    }
7181
7182    /// Convert a canonical ratio magnitude in the named declared unit to an API [`Decimal`].
7183    pub fn try_ratio_canonical_as_decimal_in_unit(
7184        &self,
7185        canonical_magnitude: &crate::computation::rational::RationalInteger,
7186        unit_name: &str,
7187    ) -> Result<rust_decimal::Decimal, crate::computation::rational::NumericFailure> {
7188        use crate::computation::rational::checked_mul;
7189        let units = match &self.specifications {
7190            TypeSpecification::Ratio { units, .. } => units,
7191            _ => unreachable!(
7192                "BUG: try_ratio_canonical_as_decimal_in_unit called on non-ratio type {}",
7193                self.name()
7194            ),
7195        };
7196        let ratio_unit = units
7197            .iter()
7198            .find(|unit| unit.name == unit_name)
7199            .unwrap_or_else(|| {
7200                let valid: Vec<&str> = units.iter().map(|unit| unit.name.as_str()).collect();
7201                unreachable!(
7202                    "BUG: unknown ratio unit '{}' for type {} (valid: {}); planning must reject invalid units",
7203                    unit_name,
7204                    self.name(),
7205                    valid.join(", ")
7206                )
7207            });
7208        let magnitude_in_unit = checked_mul(canonical_magnitude, &ratio_unit.value)?;
7209        self.try_rational_as_decimal(&magnitude_in_unit)
7210    }
7211
7212    /// Get an example value string for this type, suitable for UI help text
7213    pub fn example_value(&self) -> &'static str {
7214        match &self.specifications {
7215            TypeSpecification::Text { .. } => "\"hello world\"",
7216            TypeSpecification::Measure { .. } => "12.50 eur",
7217            TypeSpecification::MeasureRange { .. } => "30 kilogram...35 kilogram",
7218            TypeSpecification::Number { .. } => "3.14",
7219            TypeSpecification::NumberRange { .. } => "0...100",
7220            TypeSpecification::Boolean { .. } => "true",
7221            TypeSpecification::Date { .. } => "2023-12-25T14:30:00Z",
7222            TypeSpecification::DateRange { .. } => "2024-01-01...2024-12-31",
7223            TypeSpecification::TimeRange { .. } => "09:00...17:00",
7224            TypeSpecification::Veto { .. } => "veto",
7225            TypeSpecification::Time { .. } => "14:30:00",
7226            TypeSpecification::Ratio { .. } => "50%",
7227            TypeSpecification::RatioRange { .. } => "10%...50%",
7228            TypeSpecification::Undetermined => unreachable!(
7229                "BUG: example_value called on Undetermined sentinel type; this type must never reach user-facing code"
7230            ),
7231            TypeSpecification::Spec { .. } => unreachable!(
7232                "BUG: example_value called on a spec type; spec instances are not prompted data"
7233            ),
7234            TypeSpecification::List { element, .. } => element.example_value(),
7235        }
7236    }
7237
7238    /// Factor for a unit of this measure type (for unit conversion during evaluation only).
7239    /// Planning must validate conversions first and return Error for invalid units.
7240    /// If called with a non-measure type or unknown unit name, panics (invariant violation).
7241    #[must_use]
7242    /// Returns the resolved `BaseMeasureVector` for Measure types, or `None` if
7243    /// the decomposition pass has not yet resolved this type.
7244    /// Panics if called on non-Measure types.
7245    pub fn measure_type_decomposition(&self) -> Option<&BaseMeasureVector> {
7246        match &self.specifications {
7247            TypeSpecification::Measure { decomposition, .. } => decomposition.as_ref(),
7248            _ => unreachable!(
7249                "BUG: measure_type_decomposition called on non-measure type {}",
7250                self.name()
7251            ),
7252        }
7253    }
7254
7255    /// One family dimension with exponent 1 — the shape that may cross-family
7256    /// relabel when the expression also names a unit (`5 eur as kg`).
7257    #[must_use]
7258    pub(crate) fn is_simple_base_measure(&self) -> bool {
7259        if !self.is_measure() {
7260            return false;
7261        }
7262        match self.measure_type_decomposition() {
7263            Some(decomposition) if decomposition.len() == 1 => {
7264                decomposition.values().next() == Some(&1)
7265            }
7266            _ => false,
7267        }
7268    }
7269
7270    /// Declared measure unit table, when this type is a measure or measure range.
7271    #[must_use]
7272    pub fn measure_units_table(&self) -> Option<&MeasureUnits> {
7273        match &self.specifications {
7274            TypeSpecification::Measure { units, .. }
7275            | TypeSpecification::MeasureRange { units, .. } => Some(units),
7276            _ => None,
7277        }
7278    }
7279
7280    /// Whether any declared unit of this measure family has a reference scale.
7281    /// List types follow their element.
7282    #[must_use]
7283    pub fn has_dynamic_units(&self) -> bool {
7284        if self
7285            .measure_units_table()
7286            .is_some_and(|units| units.iter().any(MeasureUnit::is_dynamic))
7287        {
7288            return true;
7289        }
7290        match &self.specifications {
7291            TypeSpecification::List { element, .. } => element.has_dynamic_units(),
7292            _ => false,
7293        }
7294    }
7295
7296    /// Whether `unit_name` is a reference-scaled unit of this measure type.
7297    #[must_use]
7298    pub fn unit_is_dynamic(&self, unit_name: &str) -> bool {
7299        self.measure_units_table()
7300            .and_then(|units| units.get(unit_name).ok())
7301            .is_some_and(MeasureUnit::is_dynamic)
7302    }
7303
7304    /// Unit name chosen for measure display / wire `unit` under `runtime_scales`.
7305    #[must_use]
7306    pub(crate) fn measure_display_unit_name(
7307        &self,
7308        runtime_scales: Option<&HashMap<String, crate::computation::rational::RationalInteger>>,
7309    ) -> Option<&str> {
7310        match &self.specifications {
7311            TypeSpecification::Measure { units, .. } if !units.is_empty() => Some(
7312                measure_display_unit(units, self, runtime_scales)
7313                    .name
7314                    .as_str(),
7315            ),
7316            _ => None,
7317        }
7318    }
7319
7320    /// Fallback unit for a measure with no binding: factor-1, then the first
7321    /// literal-factor unit, then the first declared unit.
7322    #[must_use]
7323    pub fn measure_fallback_unit(&self) -> Option<&MeasureUnit> {
7324        let units = self.measure_units_table()?;
7325        units
7326            .iter()
7327            .find(|unit| unit.is_canonical_factor())
7328            .or_else(|| units.iter().find(|unit| unit.literal_factor().is_some()))
7329            .or_else(|| units.iter().next())
7330    }
7331
7332    /// Runtime unit signature for measure arithmetic and display.
7333    ///
7334    /// - Named measure with units: `[(binding_or_fallback_unit_name, 1)]`. Arithmetic
7335    ///   expands this via `expand_signature_to_base_units` using the unit table.
7336    /// - Anonymous / no units: decomposition converted to signature form.
7337    ///
7338    /// Fallback order when there is no binding: the factor-1 unit, the first unit
7339    /// with a literal factor, the first declared unit.
7340    #[must_use]
7341    pub fn measure_runtime_signature(&self) -> Vec<(String, i32)> {
7342        if let Some(binding) = self.unit() {
7343            return vec![(binding.to_string(), 1)];
7344        }
7345        match &self.specifications {
7346            TypeSpecification::Measure {
7347                units,
7348                decomposition,
7349                ..
7350            } => {
7351                if let Some(unit) = self.measure_fallback_unit() {
7352                    return vec![(unit.name.clone(), 1)];
7353                }
7354                if units.is_empty() {
7355                    return base_measure_vector_as_signature(
7356                        decomposition
7357                            .as_ref()
7358                            .expect("BUG: measure type without units must carry a decomposition"),
7359                    );
7360                }
7361                unreachable!("BUG: non-empty measure unit table has no fallback unit");
7362            }
7363            TypeSpecification::MeasureRange {
7364                units,
7365                decomposition,
7366                ..
7367            } => {
7368                if let Some(unit) = self.measure_fallback_unit() {
7369                    return vec![(unit.name.clone(), 1)];
7370                }
7371                if units.is_empty() {
7372                    return base_measure_vector_as_signature(
7373                        decomposition
7374                            .as_ref()
7375                            .expect("BUG: measure type without units must carry a decomposition"),
7376                    );
7377                }
7378                unreachable!("BUG: non-empty measure-range unit table has no fallback unit");
7379            }
7380            _ => unreachable!(
7381                "BUG: measure_runtime_signature called on non-measure type {}",
7382                self.name()
7383            ),
7384        }
7385    }
7386
7387    /// Primary declared ratio unit name when the type carries a non-empty unit table.
7388    #[must_use]
7389    pub fn ratio_primary_unit(&self) -> Option<&str> {
7390        match &self.specifications {
7391            TypeSpecification::Ratio { units, .. } if !units.is_empty() => {
7392                units.iter().next().map(|unit| unit.name.as_str())
7393            }
7394            TypeSpecification::RatioRange { units, .. } if !units.is_empty() => {
7395                units.iter().next().map(|unit| unit.name.as_str())
7396            }
7397            _ => None,
7398        }
7399    }
7400
7401    /// Returns true if this is an anonymous (no-name) Measure — i.e. an anonymous
7402    /// intermediate produced by cross-axis arithmetic.
7403    pub fn is_anonymous_measure(&self) -> bool {
7404        self.name.is_none() && matches!(&self.specifications, TypeSpecification::Measure { .. })
7405    }
7406
7407    /// Build an anonymous `LemmaType` for a given dimensional decomposition.
7408    /// Used at plan time to represent the inferred type of cross-axis intermediates.
7409    /// Runtime unit signature is derived from this decomposition via
7410    /// [`LemmaType::measure_runtime_signature`].
7411    pub fn anonymous_for_decomposition(decomposition: BaseMeasureVector) -> Self {
7412        Self {
7413            name: None,
7414            specifications: TypeSpecification::Measure {
7415                minimum: None,
7416                maximum: None,
7417                units: crate::literals::MeasureUnits::new(),
7418                traits: Vec::new(),
7419                decomposition: Some(decomposition),
7420                unit: None,
7421                help: String::new(),
7422            },
7423            extends: TypeExtends::Primitive,
7424            options: TypeOptions::default(),
7425        }
7426    }
7427
7428    /// Declared ratio unit names when the type carries a non-empty unit table (`None` otherwise).
7429    #[must_use]
7430    pub fn ratio_unit_names(&self) -> Option<Vec<&str>> {
7431        match &self.specifications {
7432            TypeSpecification::Ratio { units, .. } if !units.is_empty() => {
7433                Some(units.iter().map(|unit| unit.name.as_str()).collect())
7434            }
7435            TypeSpecification::RatioRange { units, .. } if !units.is_empty() => {
7436                Some(units.iter().map(|unit| unit.name.as_str()).collect())
7437            }
7438            _ => None,
7439        }
7440    }
7441
7442    /// Declared unit names when the type carries a non-empty unit table (`None` otherwise).
7443    #[must_use]
7444    pub fn measure_unit_names(&self) -> Option<Vec<&str>> {
7445        match &self.specifications {
7446            TypeSpecification::Measure { units, .. } if !units.is_empty() => {
7447                Some(units.iter().map(|unit| unit.name.as_str()).collect())
7448            }
7449            TypeSpecification::MeasureRange { units, .. } if !units.is_empty() => {
7450                Some(units.iter().map(|unit| unit.name.as_str()).collect())
7451            }
7452            _ => None,
7453        }
7454    }
7455
7456    /// `age [number]` or `gender [gender_code]` — brackets omitted when type adds nothing.
7457    #[must_use]
7458    pub fn label_for_data_input(&self, input_key: &str) -> String {
7459        let type_label = if let Some(parent) = self.extends.parent_name() {
7460            parent.to_string()
7461        } else {
7462            let type_name = self.name();
7463            if type_name == input_key {
7464                self.specifications.to_string()
7465            } else {
7466                type_name
7467            }
7468        };
7469        if type_label == input_key {
7470            input_key.to_string()
7471        } else {
7472            format!("{input_key} [{type_label}]")
7473        }
7474    }
7475
7476    /// `Data age [number]: {detail}` for runtime data override vetoes (parse/validation).
7477    #[must_use]
7478    pub fn data_veto_message(&self, input_key: &str, detail: &str) -> String {
7479        format!("Data {}: {}", self.label_for_data_input(input_key), detail)
7480    }
7481
7482    /// Whether an empty [`EvaluateDataValue`] should veto before parse (text may accept `""`).
7483    #[must_use]
7484    pub fn empty_runtime_input_vetoes(&self) -> bool {
7485        !matches!(self.specifications, TypeSpecification::Text { .. })
7486    }
7487
7488    /// Return the conversion factor for a declared unit name on this measure type.
7489    pub fn measure_unit_factor(
7490        &self,
7491        unit_name: &str,
7492    ) -> &crate::computation::rational::RationalInteger {
7493        let units = match &self.specifications {
7494            TypeSpecification::Measure { units, .. } => units,
7495            TypeSpecification::MeasureRange { units, .. } => units,
7496            _ => unreachable!(
7497                "BUG: measure_unit_factor called with non-measure type {}; only call during evaluation after planning validated measure conversion",
7498                self.name()
7499            ),
7500        };
7501        match units.get(unit_name) {
7502            Ok(unit) => unit.require_literal_factor(),
7503            Err(_) => {
7504                let valid: Vec<&str> = units.iter().map(|u| u.name.as_str()).collect();
7505                unreachable!(
7506                    "BUG: unknown unit '{}' for measure type {} (valid: {}); planning must reject invalid conversions with Error",
7507                    unit_name,
7508                    self.name(),
7509                    valid.join(", ")
7510                );
7511            }
7512        }
7513    }
7514
7515    pub fn ratio_unit_factor(
7516        &self,
7517        unit_name: &str,
7518    ) -> &crate::computation::rational::RationalInteger {
7519        let units = match &self.specifications {
7520            TypeSpecification::Ratio { units, .. } => units,
7521            _ => unreachable!(
7522                "BUG: ratio_unit_factor called with non-ratio type {}; only call during evaluation after planning validated ratio conversion",
7523                self.name()
7524            ),
7525        };
7526        match units.get(unit_name) {
7527            Ok(RatioUnit { value, .. }) => value,
7528            Err(_) => {
7529                let valid: Vec<&str> = units.0.iter().map(|u| u.name.as_str()).collect();
7530                unreachable!(
7531                    "BUG: unknown unit '{}' for ratio type {} (valid: {}); planning must reject invalid conversions with Error",
7532                    unit_name,
7533                    self.name(),
7534                    valid.join(", ")
7535                );
7536            }
7537        }
7538    }
7539
7540    /// Convert a measure literal to API [`Decimal`]s in the given unit names.
7541    pub(crate) fn measure_literal_unit_map(
7542        &self,
7543        literal: &LiteralValue,
7544        unit_names: &[&str],
7545        factor_source: UnitFactorSource<'_>,
7546    ) -> Result<BTreeMap<String, rust_decimal::Decimal>, LiteralUnitMapFailure> {
7547        use crate::computation::rational::checked_div;
7548
7549        let ValueKind::Measure(magnitude) = &literal.value else {
7550            panic!("BUG: measure_literal_unit_map called with non-measure value");
7551        };
7552        let mut map = BTreeMap::new();
7553        for &unit_name in unit_names {
7554            let Some(unit_factor) = factor_source.try_measure_unit_factor(unit_name) else {
7555                continue;
7556            };
7557            let magnitude_in_unit = checked_div(magnitude, &unit_factor)
7558                .map_err(LiteralUnitMapFailure::UnitConversion)?;
7559            let decimal = self
7560                .try_rational_as_decimal(&magnitude_in_unit)
7561                .map_err(LiteralUnitMapFailure::Commit)?;
7562            map.insert(unit_name.to_string(), decimal);
7563        }
7564        Ok(map)
7565    }
7566
7567    /// Convert a ratio literal to API [`Decimal`]s in the given unit names.
7568    pub(crate) fn ratio_literal_unit_map(
7569        &self,
7570        literal: &LiteralValue,
7571        unit_names: &[&str],
7572        factor_source: UnitFactorSource<'_>,
7573    ) -> Result<BTreeMap<String, rust_decimal::Decimal>, LiteralUnitMapFailure> {
7574        use crate::computation::rational::checked_mul;
7575
7576        let ratio_api_type = match &self.specifications {
7577            TypeSpecification::Ratio { .. } => self,
7578            TypeSpecification::RatioRange { .. } => {
7579                return ratio_element_type_for_api(self).ratio_literal_unit_map(
7580                    literal,
7581                    unit_names,
7582                    factor_source,
7583                );
7584            }
7585            _ => {
7586                panic!(
7587                    "BUG: ratio_literal_unit_map called with non-ratio type {}",
7588                    self.name()
7589                );
7590            }
7591        };
7592        let ValueKind::Ratio(canonical) = &literal.value else {
7593            panic!("BUG: ratio_literal_unit_map called with non-ratio value");
7594        };
7595        if unit_names.is_empty() {
7596            panic!(
7597                "BUG: ratio literal type '{}' must have at least one unit name",
7598                self.name()
7599            );
7600        }
7601        let mut map = BTreeMap::new();
7602        for &unit_name in unit_names {
7603            let unit_factor = factor_source.ratio_unit_factor(unit_name);
7604            let magnitude_in_unit = checked_mul(canonical, unit_factor)
7605                .map_err(LiteralUnitMapFailure::UnitConversion)?;
7606            let decimal = ratio_api_type
7607                .try_rational_as_decimal(&magnitude_in_unit)
7608                .map_err(LiteralUnitMapFailure::Commit)?;
7609            map.insert(unit_name.to_string(), decimal);
7610        }
7611        Ok(map)
7612    }
7613}
7614
7615/// Where to read measure/ratio unit factors when building a per-unit decimal map.
7616pub(crate) enum UnitFactorSource<'a> {
7617    DeclaredOn(&'a LemmaType),
7618    Merged {
7619        measure: Option<&'a MeasureUnits>,
7620        ratio: Option<&'a RatioUnits>,
7621    },
7622    /// Evaluated reference scales over a declared or merged table. A dynamic
7623    /// column whose scale is missing from `scales` is omitted.
7624    Runtime {
7625        scales:
7626            &'a std::collections::HashMap<String, crate::computation::rational::RationalInteger>,
7627        fallback: &'a UnitFactorSource<'a>,
7628    },
7629}
7630
7631impl UnitFactorSource<'_> {
7632    /// Literal factor of `unit_name`, or `None` when that unit is reference-scaled
7633    /// and this source has no runtime factor for it (the column is omitted).
7634    fn try_measure_unit_factor(
7635        &self,
7636        unit_name: &str,
7637    ) -> Option<crate::computation::rational::RationalInteger> {
7638        match self {
7639            UnitFactorSource::DeclaredOn(lemma_type) => {
7640                let units = lemma_type.measure_units_table().unwrap_or_else(|| {
7641                    panic!(
7642                        "BUG: measure_unit_factor on non-measure type {}",
7643                        lemma_type.name()
7644                    )
7645                });
7646                let unit = units.get(unit_name).unwrap_or_else(|_| {
7647                    panic!(
7648                        "BUG: unknown unit '{unit_name}' for measure type {}",
7649                        lemma_type.name()
7650                    )
7651                });
7652                unit.literal_factor().cloned()
7653            }
7654            UnitFactorSource::Merged { measure, .. } => {
7655                // A unit omitted from the merged table (owners disagree on its scale)
7656                // has no single factor here; the column is skipped.
7657                let units = (*measure)?;
7658                let unit = units.get(unit_name).ok()?;
7659                unit.literal_factor().cloned()
7660            }
7661            UnitFactorSource::Runtime { scales, fallback } => scales
7662                .get(unit_name)
7663                .cloned()
7664                .or_else(|| fallback.try_measure_unit_factor(unit_name)),
7665        }
7666    }
7667
7668    fn ratio_unit_factor(&self, unit_name: &str) -> &crate::computation::rational::RationalInteger {
7669        match self {
7670            UnitFactorSource::DeclaredOn(lemma_type) => lemma_type.ratio_unit_factor(unit_name),
7671            UnitFactorSource::Merged { ratio, .. } => {
7672                let units = ratio.unwrap_or_else(|| {
7673                    panic!(
7674                        "BUG: family ratio expansion missing merged table for unit '{unit_name}'"
7675                    )
7676                });
7677                &units
7678                    .get(unit_name)
7679                    .unwrap_or_else(|_| {
7680                        panic!("BUG: family unit '{unit_name}' missing from merged ratio table")
7681                    })
7682                    .value
7683            }
7684            UnitFactorSource::Runtime { fallback, .. } => fallback.ratio_unit_factor(unit_name),
7685        }
7686    }
7687}
7688
7689/// Primitive ratio type for API unit-map conversion on ratio range wrappers.
7690pub(crate) fn ratio_element_type_for_api(lemma_type: &LemmaType) -> LemmaType {
7691    match &lemma_type.specifications {
7692        TypeSpecification::Ratio { .. } => lemma_type.clone(),
7693        TypeSpecification::RatioRange { .. } => {
7694            let element = range_element_type_specification(&lemma_type.specifications)
7695                .expect("BUG: ratio range type must have ratio element specification");
7696            let TypeSpecification::Ratio { units, .. } = element else {
7697                panic!("BUG: ratio range element spec must be Ratio");
7698            };
7699            LemmaType::primitive(TypeSpecification::Ratio {
7700                minimum: None,
7701                maximum: None,
7702                units,
7703                unit: None,
7704                help: String::new(),
7705            })
7706        }
7707        _ => panic!(
7708            "BUG: ratio_element_type_for_api called with non-ratio type {}",
7709            lemma_type.name()
7710        ),
7711    }
7712}
7713
7714/// Failure while converting a literal to decimal strings across declared units.
7715#[derive(Debug, Clone, PartialEq, Eq)]
7716pub(crate) enum LiteralUnitMapFailure {
7717    Commit(crate::computation::rational::NumericFailure),
7718    UnitConversion(crate::computation::rational::NumericFailure),
7719}
7720
7721/// Runtime literal payload. Type lives on `NormalForm.result_type` / `DataDefinition` /
7722/// explicit computation parameters — not on the value.
7723#[derive(Clone, Debug, PartialEq, Eq, Hash)]
7724pub struct LiteralValue {
7725    pub value: ValueKind,
7726}
7727
7728impl LiteralValue {
7729    #[inline]
7730    pub fn new(value: ValueKind) -> Self {
7731        Self { value }
7732    }
7733
7734    fn single_measure_signature_unit_name(signature: &[(String, i32)]) -> Option<&str> {
7735        match signature {
7736            [(unit_name, 1)] => Some(unit_name.as_str()),
7737            _ => None,
7738        }
7739    }
7740}
7741
7742/// Planning-time literal: value plus resolved type.
7743///
7744/// Used by `ExpressionKind::Literal` and coerce/typing paths. Runtime
7745/// `OperationResult` / value-table slots store bare [`LiteralValue`]; the type
7746/// is on the node (`NormalForm.result_type`) or data definition.
7747#[derive(Clone, Debug, PartialEq, Eq, Hash)]
7748pub struct TypedLiteral {
7749    pub value: ValueKind,
7750    pub lemma_type: Arc<LemmaType>,
7751}
7752
7753impl TypedLiteral {
7754    #[inline]
7755    pub fn to_literal(&self) -> LiteralValue {
7756        LiteralValue {
7757            value: self.value.clone(),
7758        }
7759    }
7760
7761    #[inline]
7762    pub fn into_literal(self) -> LiteralValue {
7763        LiteralValue { value: self.value }
7764    }
7765}
7766
7767impl From<TypedLiteral> for LiteralValue {
7768    fn from(typed: TypedLiteral) -> Self {
7769        typed.into_literal()
7770    }
7771}
7772
7773impl From<&TypedLiteral> for LiteralValue {
7774    fn from(typed: &TypedLiteral) -> Self {
7775        typed.to_literal()
7776    }
7777}
7778
7779impl LiteralValue {
7780    pub fn text(s: impl Into<Arc<str>>) -> Self {
7781        Self {
7782            value: ValueKind::Text(s.into()),
7783        }
7784    }
7785
7786    pub fn number(n: RationalInteger) -> Self {
7787        Self {
7788            value: ValueKind::Number(n),
7789        }
7790    }
7791
7792    pub fn number_from_decimal(decimal: Decimal) -> Self {
7793        Self::number(
7794            crate::literals::rational_from_parsed_decimal(decimal)
7795                .expect("BUG: literal number from decimal must lift at boundary"),
7796        )
7797    }
7798
7799    pub fn measure(n: RationalInteger) -> Self {
7800        Self {
7801            value: ValueKind::Measure(n),
7802        }
7803    }
7804
7805    pub fn from_bool(b: bool) -> Self {
7806        Self {
7807            value: ValueKind::Boolean(b),
7808        }
7809    }
7810
7811    pub fn from_datetime(dt: &crate::parsing::ast::DateTimeValue) -> Self {
7812        Self::date(date_time_to_semantic(dt))
7813    }
7814
7815    pub fn date(dt: SemanticDateTime) -> Self {
7816        Self {
7817            value: ValueKind::Date(dt),
7818        }
7819    }
7820
7821    pub fn time(t: SemanticTime) -> Self {
7822        Self {
7823            value: ValueKind::Time(t),
7824        }
7825    }
7826
7827    pub fn ratio(r: RationalInteger) -> Self {
7828        Self {
7829            value: ValueKind::Ratio(r),
7830        }
7831    }
7832
7833    pub fn ratio_from_decimal(r: Decimal) -> Self {
7834        Self::ratio(
7835            crate::literals::rational_from_parsed_decimal(r)
7836                .expect("BUG: ratio literal from decimal must lift at boundary"),
7837        )
7838    }
7839
7840    pub fn range(left: TypedLiteral, right: TypedLiteral) -> Self {
7841        Self {
7842            value: ValueKind::Range(Box::new(left), Box::new(right)),
7843        }
7844    }
7845
7846    /// Display without an explicit type. Measure/ratio fall back to magnitude-only.
7847    pub fn display_value(&self) -> String {
7848        match &self.value {
7849            ValueKind::Measure(_) | ValueKind::Ratio(_) | ValueKind::UnscaledMeasure { .. } => {
7850                format!("{}", self.value)
7851            }
7852            ValueKind::Range(left, right) => {
7853                format!("{}...{}", left.display_value(), right.display_value())
7854            }
7855            ValueKind::List(rows) if rows.is_empty() => String::new(),
7856            ValueKind::List(rows) => rows
7857                .iter()
7858                .map(|row| row.display_value())
7859                .collect::<Vec<_>>()
7860                .join(", "),
7861            _ => format!("{}", self.value),
7862        }
7863    }
7864
7865    /// Display string given an explicit type (measure/ratio need unit identity).
7866    pub fn display_value_with_type(&self, lemma_type: &LemmaType) -> String {
7867        self.display_value_with_scales(lemma_type, None)
7868    }
7869
7870    /// Display string given an explicit type and settled reference-scale factors.
7871    pub fn display_value_with_scales(
7872        &self,
7873        lemma_type: &LemmaType,
7874        runtime_scales: Option<&HashMap<String, crate::computation::rational::RationalInteger>>,
7875    ) -> String {
7876        match &self.value {
7877            ValueKind::Measure(n) => {
7878                let signature = lemma_type.measure_runtime_signature();
7879                format_measure_canonical_for_display(n, lemma_type, &signature, runtime_scales)
7880            }
7881            ValueKind::UnscaledMeasure { magnitude, unit } => {
7882                format!(
7883                    "{} {unit}",
7884                    format_rational_magnitude_for_display(magnitude)
7885                )
7886            }
7887            ValueKind::Ratio(n) => format_ratio_canonical_for_display(n, lemma_type),
7888            ValueKind::Range(left, right) => {
7889                format!(
7890                    "{}...{}",
7891                    left.to_literal()
7892                        .display_value_with_scales(&left.lemma_type, runtime_scales),
7893                    right
7894                        .to_literal()
7895                        .display_value_with_scales(&right.lemma_type, runtime_scales)
7896                )
7897            }
7898            ValueKind::List(rows) if rows.is_empty() => lemma_type.specifications.to_string(),
7899            ValueKind::List(rows) => rows
7900                .iter()
7901                .map(|row| {
7902                    row.to_literal()
7903                        .display_value_with_scales(&row.lemma_type, runtime_scales)
7904                })
7905                .collect::<Vec<_>>()
7906                .join(", "),
7907            _ => format!("{}", self.value),
7908        }
7909    }
7910
7911    /// Structural byte-size estimate for resource limit checks.
7912    pub fn byte_size(&self) -> usize {
7913        self.value.structural_byte_size()
7914    }
7915
7916    /// Magnitude for decimal input prompts (API [`Decimal`]; format at call site).
7917    #[must_use]
7918    pub fn magnitude_suggestion_for_decimal_prompt(
7919        &self,
7920        lemma_type: &LemmaType,
7921    ) -> Option<rust_decimal::Decimal> {
7922        match &self.value {
7923            ValueKind::Number(n) => Some(
7924                lemma_type
7925                    .try_rational_as_decimal(n)
7926                    .expect("BUG: stored number literal must convert to decimal for prompt"),
7927            ),
7928            ValueKind::Measure(n) => {
7929                let signature = lemma_type.measure_runtime_signature();
7930                let unit_name = Self::single_measure_signature_unit_name(&signature).expect(
7931                    "BUG: measure prompt requires exactly one signature unit with exponent 1",
7932                );
7933                Some(
7934                    lemma_type
7935                        .try_measure_canonical_as_decimal_in_unit(n, unit_name)
7936                        .expect("BUG: stored measure literal must convert to decimal for prompt"),
7937                )
7938            }
7939            ValueKind::Ratio(n) => {
7940                if let Some(unit_name) = lemma_type.unit() {
7941                    Some(
7942                        lemma_type
7943                            .try_ratio_canonical_as_decimal_in_unit(n, unit_name)
7944                            .expect("BUG: stored ratio literal must convert to decimal for prompt"),
7945                    )
7946                } else {
7947                    Some(lemma_type.try_rational_as_decimal(n).expect(
7948                        "BUG: stored bare ratio literal must convert to decimal for prompt",
7949                    ))
7950                }
7951            }
7952            _ => None,
7953        }
7954    }
7955
7956    /// Per-unit magnitudes when this literal is a measure with declared units.
7957    #[must_use]
7958    pub fn measure_units(
7959        &self,
7960        lemma_type: &LemmaType,
7961    ) -> Option<BTreeMap<String, rust_decimal::Decimal>> {
7962        if !matches!(self.value, ValueKind::Measure(_)) {
7963            return None;
7964        }
7965        lemma_type.measure_unit_names()?;
7966        let declared: Vec<&str> = lemma_type
7967            .measure_unit_names()
7968            .expect("BUG: measure_unit_names checked above");
7969        lemma_type
7970            .measure_literal_unit_map(self, &declared, UnitFactorSource::DeclaredOn(lemma_type))
7971            .ok()
7972    }
7973
7974    /// Per-unit magnitudes when this literal is a ratio with declared units.
7975    #[must_use]
7976    pub fn ratio_units(
7977        &self,
7978        lemma_type: &LemmaType,
7979    ) -> Option<BTreeMap<String, rust_decimal::Decimal>> {
7980        if !matches!(self.value, ValueKind::Ratio(_)) {
7981            return None;
7982        }
7983        let has_declared_units = match &lemma_type.specifications {
7984            TypeSpecification::Ratio { units, .. } => !units.is_empty(),
7985            TypeSpecification::RatioRange { .. } => true,
7986            _ => return None,
7987        };
7988        if !has_declared_units {
7989            return None;
7990        }
7991        let declared: Vec<&str> = lemma_type
7992            .ratio_unit_names()
7993            .expect("BUG: ratio units checked above");
7994        lemma_type
7995            .ratio_literal_unit_map(self, &declared, UnitFactorSource::DeclaredOn(lemma_type))
7996            .ok()
7997    }
7998
7999    /// Magnitude in a declared unit when this literal is measure or ratio.
8000    #[must_use]
8001    pub fn magnitude_in_unit(
8002        &self,
8003        lemma_type: &LemmaType,
8004        unit: &str,
8005    ) -> Option<rust_decimal::Decimal> {
8006        self.measure_units(lemma_type)
8007            .and_then(|map| map.get(unit).copied())
8008            .or_else(|| {
8009                self.ratio_units(lemma_type)
8010                    .and_then(|map| map.get(unit).copied())
8011            })
8012    }
8013
8014    /// Derive second from a duration measure's canonical magnitude.
8015    pub fn duration_canonical_seconds(&self, lemma_type: &LemmaType) -> RationalInteger {
8016        let ValueKind::Measure(magnitude) = &self.value else {
8017            unreachable!(
8018                "BUG: duration_canonical_seconds called with {:?}",
8019                self.value
8020            );
8021        };
8022        if !lemma_type.is_duration_like_measure() {
8023            unreachable!(
8024                "BUG: duration_canonical_seconds called with type {}",
8025                lemma_type.name()
8026            );
8027        }
8028        let factor = lemma_type.measure_unit_factor("second");
8029        checked_div(magnitude, factor).expect("BUG: duration unit factor cannot be zero")
8030    }
8031
8032    /// Derive month from a calendar measure's canonical magnitude.
8033    pub fn calendar_canonical_months(&self, lemma_type: &LemmaType) -> RationalInteger {
8034        let ValueKind::Measure(magnitude) = &self.value else {
8035            unreachable!(
8036                "BUG: calendar_canonical_months called with {:?}",
8037                self.value
8038            );
8039        };
8040        if !lemma_type.is_calendar_like() {
8041            unreachable!(
8042                "BUG: calendar_canonical_months called with type {}",
8043                lemma_type.name()
8044            );
8045        }
8046        let factor = lemma_type.measure_unit_factor("month");
8047        checked_div(magnitude, factor).expect("BUG: calendar unit factor cannot be zero")
8048    }
8049}
8050
8051impl TypedLiteral {
8052    pub fn text(s: impl Into<Arc<str>>) -> Self {
8053        Self {
8054            value: ValueKind::Text(s.into()),
8055            lemma_type: primitive_text_arc().clone(),
8056        }
8057    }
8058
8059    pub fn text_with_type(s: impl Into<Arc<str>>, lemma_type: Arc<LemmaType>) -> Self {
8060        Self {
8061            value: ValueKind::Text(s.into()),
8062            lemma_type,
8063        }
8064    }
8065
8066    pub fn number(n: RationalInteger) -> Self {
8067        Self {
8068            value: ValueKind::Number(n),
8069            lemma_type: primitive_number_arc().clone(),
8070        }
8071    }
8072
8073    pub fn number_from_decimal(decimal: Decimal) -> Self {
8074        Self::number(
8075            crate::literals::rational_from_parsed_decimal(decimal)
8076                .expect("BUG: literal number from decimal must lift at boundary"),
8077        )
8078    }
8079
8080    pub fn number_with_type(n: RationalInteger, lemma_type: Arc<LemmaType>) -> Self {
8081        Self {
8082            value: ValueKind::Number(n),
8083            lemma_type,
8084        }
8085    }
8086
8087    pub fn number_with_type_from_decimal(decimal: Decimal, lemma_type: Arc<LemmaType>) -> Self {
8088        Self::number_with_type(
8089            crate::literals::rational_from_parsed_decimal(decimal)
8090                .expect("BUG: literal number from decimal must lift at boundary"),
8091            lemma_type,
8092        )
8093    }
8094
8095    /// Build a Measure literal bound to a specific declared unit.
8096    pub fn measure_with_bound_unit(
8097        n: RationalInteger,
8098        unit_name: impl Into<String>,
8099        lemma_type: Arc<LemmaType>,
8100    ) -> Self {
8101        Self::measure_with_type(
8102            n,
8103            Arc::new(lemma_type.as_ref().clone().with_unit(unit_name)),
8104        )
8105    }
8106
8107    pub fn measure_with_type(n: RationalInteger, lemma_type: Arc<LemmaType>) -> Self {
8108        Self {
8109            value: ValueKind::Measure(n),
8110            lemma_type,
8111        }
8112    }
8113
8114    pub fn measure_with_signature(n: RationalInteger, lemma_type: Arc<LemmaType>) -> Self {
8115        Self {
8116            value: ValueKind::Measure(n),
8117            lemma_type,
8118        }
8119    }
8120
8121    /// Unit literal outside a measure type context: no family, so no dimensions.
8122    pub fn number_interpreted_as_measure(value: RationalInteger) -> Self {
8123        Self {
8124            value: ValueKind::Measure(value),
8125            lemma_type: Arc::new(anonymous_measure_type()),
8126        }
8127    }
8128
8129    pub fn from_bool(b: bool) -> Self {
8130        Self {
8131            value: ValueKind::Boolean(b),
8132            lemma_type: primitive_boolean_arc().clone(),
8133        }
8134    }
8135
8136    pub fn from_datetime(dt: &crate::parsing::ast::DateTimeValue) -> Self {
8137        Self::date(date_time_to_semantic(dt))
8138    }
8139
8140    pub fn date(dt: SemanticDateTime) -> Self {
8141        Self {
8142            value: ValueKind::Date(dt),
8143            lemma_type: primitive_date_arc().clone(),
8144        }
8145    }
8146
8147    pub fn date_with_type(dt: SemanticDateTime, lemma_type: Arc<LemmaType>) -> Self {
8148        Self {
8149            value: ValueKind::Date(dt),
8150            lemma_type,
8151        }
8152    }
8153
8154    pub fn time(t: SemanticTime) -> Self {
8155        Self {
8156            value: ValueKind::Time(t),
8157            lemma_type: primitive_time_arc().clone(),
8158        }
8159    }
8160
8161    pub fn time_with_type(t: SemanticTime, lemma_type: Arc<LemmaType>) -> Self {
8162        Self {
8163            value: ValueKind::Time(t),
8164            lemma_type,
8165        }
8166    }
8167
8168    pub fn calendar(
8169        value: RationalInteger,
8170        unit: SemanticCalendarUnit,
8171        lemma_type: Arc<LemmaType>,
8172    ) -> Self {
8173        let unit_name = unit.to_string();
8174        debug_assert_eq!(
8175            semantic_calendar_unit_from_unit_name(&unit_name),
8176            unit,
8177            "BUG: calendar unit name must round-trip"
8178        );
8179        Self::measure_with_bound_unit(value, unit_name, lemma_type)
8180    }
8181
8182    pub fn calendar_from_decimal(
8183        value: Decimal,
8184        unit: SemanticCalendarUnit,
8185        lemma_type: Arc<LemmaType>,
8186    ) -> Self {
8187        Self::calendar(
8188            crate::literals::rational_from_parsed_decimal(value)
8189                .expect("BUG: calendar literal from decimal must lift at boundary"),
8190            unit,
8191            lemma_type,
8192        )
8193    }
8194
8195    pub fn calendar_with_type(
8196        value: RationalInteger,
8197        unit: SemanticCalendarUnit,
8198        lemma_type: Arc<LemmaType>,
8199    ) -> Self {
8200        Self::calendar(value, unit, lemma_type)
8201    }
8202
8203    pub fn ratio(r: RationalInteger) -> Self {
8204        Self {
8205            value: ValueKind::Ratio(r),
8206            lemma_type: primitive_ratio_arc().clone(),
8207        }
8208    }
8209
8210    pub fn ratio_from_decimal(r: Decimal) -> Self {
8211        Self::ratio(
8212            crate::literals::rational_from_parsed_decimal(r)
8213                .expect("BUG: ratio literal from decimal must lift at boundary"),
8214        )
8215    }
8216
8217    pub fn ratio_with_type(r: RationalInteger, lemma_type: Arc<LemmaType>) -> Self {
8218        Self {
8219            value: ValueKind::Ratio(r),
8220            lemma_type,
8221        }
8222    }
8223
8224    pub fn ratio_with_bound_unit(
8225        r: RationalInteger,
8226        unit_name: impl Into<String>,
8227        lemma_type: Arc<LemmaType>,
8228    ) -> Self {
8229        Self::ratio_with_type(
8230            r,
8231            Arc::new(lemma_type.as_ref().clone().with_unit(unit_name)),
8232        )
8233    }
8234
8235    pub fn range(left: TypedLiteral, right: TypedLiteral) -> Self {
8236        let specifications =
8237            range_type_specification_from_endpoints(&left.lemma_type, &right.lemma_type)
8238                .unwrap_or_else(|| {
8239                    unreachable!(
8240                "BUG: attempted to construct a range literal from incompatible endpoint types"
8241            )
8242                });
8243
8244        Self {
8245            value: ValueKind::Range(Box::new(left), Box::new(right)),
8246            lemma_type: Arc::new(LemmaType::primitive(specifications)),
8247        }
8248    }
8249
8250    pub fn display_value(&self) -> String {
8251        self.to_literal().display_value_with_type(&self.lemma_type)
8252    }
8253
8254    pub fn get_type(&self) -> &LemmaType {
8255        &self.lemma_type
8256    }
8257
8258    pub fn byte_size(&self) -> usize {
8259        self.value.structural_byte_size()
8260    }
8261}
8262
8263impl fmt::Display for TypedLiteral {
8264    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8265        write!(f, "{}", self.display_value())
8266    }
8267}
8268
8269/// What a [`DataDefinition::Reference`] copies its value from: either another data path
8270/// or a rule whose result becomes this data's value.
8271#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
8272pub enum ReferenceTarget {
8273    Data(DataPath),
8274    Rule(RulePath),
8275}
8276
8277impl fmt::Display for ReferenceTarget {
8278    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8279        match self {
8280            ReferenceTarget::Data(path) => write!(f, "{path}"),
8281            ReferenceTarget::Rule(path) => write!(f, "{path}"),
8282        }
8283    }
8284}
8285
8286/// A `number` data field or rule that sizes a dynamic unit.
8287#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
8288pub struct ScaleTarget {
8289    /// The data or rule, written in the coordinates of `owner`.
8290    pub target: ReferenceTarget,
8291    /// The spec whose names `target` is written in. Only a plan of that spec resolves
8292    /// it: the same name elsewhere is another field. A unit of a list's rows keeps the
8293    /// row spec as its owner wherever its type travels.
8294    pub(crate) owner: ScaleOwner,
8295}
8296
8297impl fmt::Display for ScaleTarget {
8298    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8299        write!(f, "{}", self.target)
8300    }
8301}
8302
8303/// A spec by repository and name, across its versions.
8304#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
8305pub(crate) struct ScaleOwner {
8306    repository: Option<Arc<str>>,
8307    spec: Arc<str>,
8308}
8309
8310impl ScaleOwner {
8311    pub(crate) fn new(repository: Option<&str>, spec: &str) -> Self {
8312        Self {
8313            repository: repository.map(Arc::from),
8314            spec: Arc::from(spec),
8315        }
8316    }
8317
8318    /// The spec the `uses` hop or row `segment` resolves to.
8319    fn of_segment(segment: &PathSegment) -> Self {
8320        Self {
8321            repository: segment.repository.clone(),
8322            spec: Arc::clone(&segment.spec),
8323        }
8324    }
8325
8326    pub(crate) fn is(&self, identity: &SpecIdentity) -> bool {
8327        self.repository.as_deref() == identity.repository.as_deref()
8328            && self.spec.as_ref() == identity.spec.as_str()
8329    }
8330}
8331
8332/// Where a [`DataDefinition::Reference`] chain ends. Computed once per slice in
8333/// [`crate::planning::graph::Graph::validate`] after `compute_data_reference_order`
8334/// rejected cycles.
8335#[derive(Clone, Debug, PartialEq, Eq)]
8336pub(crate) enum ReferenceEnd {
8337    Promptable(DataPath),
8338    Rule(RulePath),
8339}
8340
8341/// Who wrote a data slot's definition.
8342///
8343/// A slot declared by its own spec is a default: evaluation data may replace it. A
8344/// slot bound by a consumer (`uses x -> with field: value`, a path fill, or a row
8345/// field written in a data list) is final: supplying it at evaluate is a request
8346/// [`crate::Error`], and it is not a promptable input.
8347#[derive(Clone, Copy, Debug, PartialEq, Eq)]
8348pub enum DataOrigin {
8349    Declared,
8350    Bound,
8351}
8352
8353/// Date-typed local that a dynamic `uses … -> effective` import reads at evaluation.
8354#[derive(Clone, Debug, PartialEq, Eq, Hash)]
8355pub enum ImportEffectivePin {
8356    Data(DataPath),
8357    Rule(RulePath),
8358}
8359
8360/// Resolved data value for the execution plan: aligned with [`DataValue`] but with source per variant.
8361#[derive(Clone, Debug)]
8362pub enum DataDefinition {
8363    /// Value-holding data: current literal (spec default or `with` binding).
8364    Value {
8365        value: LiteralValue,
8366        resolved_type: Arc<LemmaType>,
8367        origin: DataOrigin,
8368        source: Source,
8369    },
8370    /// Type-only data: type known, value to be supplied (e.g. via run data).
8371    /// `declared_suggestion` carries the `-> suggest ...` payload for this binding or
8372    /// the suggestion inherited from the parent type chain, if any; value-promoting code
8373    /// uses it instead of re-deriving suggestions from [`TypeSpecification`].
8374    /// The evaluator never commits a suggestion — unbound stays MissingData.
8375    TypeDeclaration {
8376        resolved_type: Arc<LemmaType>,
8377        declared_suggestion: Option<BoundValueKind>,
8378        declared_value: Option<BoundValueKind>,
8379        source: Source,
8380    },
8381    /// Import (`uses`): a spec instance named `alias` in this plan, a row over the
8382    /// imported spec's template plan. Its bindings are the `-> with` / path-fill fields
8383    /// the declaring spec wrote; the imported data and rules are read through the
8384    /// template in the instance's context.
8385    ///
8386    /// When `pin` is `None`, `row` is the sole body. When `pin` is `Some` (`-> effective`),
8387    /// `candidates` holds every possible body and evaluation selects among them; `row`
8388    /// then equals an arbitrary candidate and must not be read without selection.
8389    Import {
8390        row: Arc<RowInstance>,
8391        /// Planned path of the `-> effective` date when present.
8392        pin: Option<ImportEffectivePin>,
8393        /// Bound rows keyed by identity when `pin` is set; empty for static imports.
8394        candidates: std::collections::BTreeMap<SpecIdentity, Arc<RowInstance>>,
8395        /// `uses global`: the slot reads the evaluation's one instance of this global
8396        /// ([`GlobalKey`]), held by the root plan's `global.x` slot. `row` names the body;
8397        /// it is never read as the instance. A global slot has no `pin`. The `global.x`
8398        /// slot's `row` holds every write on the global in the plan's instance tree.
8399        global: Option<GlobalKey>,
8400        source: Source,
8401    },
8402    /// Instance list (`data x: spec list`). `resolved_type` is the list type.
8403    /// Rows written in the spec are instances of this plan under the list path
8404    /// ([`crate::planning::execution_plan::ExecutionPlan::instance_lists`]);
8405    /// evaluation lists them unless run data replaces the list.
8406    InstanceList {
8407        resolved_type: Arc<LemmaType>,
8408        origin: DataOrigin,
8409        source: Source,
8410    },
8411    /// Value-copy reference to another data or a rule result.
8412    ///
8413    /// `resolved_type` is the merged type that the copied value must satisfy at
8414    /// evaluation time. Merging folds together: (1) the LHS's own declared type,
8415    /// if any; (2) the target's type (data declared type or rule return type);
8416    /// (3) any `local_constraints` written after the `->` on the reference itself.
8417    /// Merging happens in a dedicated pass once all data and rule types are
8418    /// known; before that pass, `resolved_type` holds a provisional value and
8419    /// must not be consumed for type checking.
8420    ///
8421    /// `local_constraints` preserves the raw constraint list from the reference's
8422    /// `-> ...` tail (e.g. `minimum 5` in `data license2: law.other -> minimum 5`)
8423    /// for that merging pass. It is `None` when the reference has no trailing
8424    /// constraints.
8425    ///
8426    /// `local_suggestion` carries any `suggest <value>` constraint from the
8427    /// reference's `-> ...` tail. The reference-merge pass extracts it from the
8428    /// constraint list during type resolution. It is a UI hint only
8429    /// ([`Self::suggestion`] / show); the evaluator never commits it — unbound
8430    /// stays MissingData.
8431    ///
8432    /// The reference itself is evaluated by copying the target's value (data path)
8433    /// or the target rule's result in topological order. Evaluate data for this
8434    /// path binds via `resolved_type` like a type declaration.
8435    Reference {
8436        target: ReferenceTarget,
8437        resolved_type: Arc<LemmaType>,
8438        local_constraints: Option<Vec<Constraint>>,
8439        local_suggestion: Option<BoundValueKind>,
8440        local_value: Option<BoundValueKind>,
8441        origin: DataOrigin,
8442        source: Source,
8443    },
8444}
8445
8446impl DataDefinition {
8447    /// Whether a consumer bound this slot (`uses -> with`, path fill, or a row field
8448    /// written in a data list). Bound slots take no evaluation data.
8449    pub fn is_bound(&self) -> bool {
8450        match self {
8451            DataDefinition::Value { origin, .. }
8452            | DataDefinition::InstanceList { origin, .. }
8453            | DataDefinition::Reference { origin, .. } => *origin == DataOrigin::Bound,
8454            DataDefinition::TypeDeclaration { .. } | DataDefinition::Import { .. } => false,
8455        }
8456    }
8457
8458    /// Declared lemma type for value, type-declaration, and reference data; `None` for imports.
8459    pub fn lemma_type(&self) -> Option<&LemmaType> {
8460        self.resolved_type_arc().map(|arc| arc.as_ref())
8461    }
8462
8463    /// Shared [`Arc`] for the declared type; `None` for imports.
8464    pub fn resolved_type_arc(&self) -> Option<&Arc<LemmaType>> {
8465        match self {
8466            DataDefinition::Value { resolved_type, .. } => Some(resolved_type),
8467            DataDefinition::TypeDeclaration { resolved_type, .. } => Some(resolved_type),
8468            DataDefinition::Reference { resolved_type, .. } => Some(resolved_type),
8469            DataDefinition::InstanceList { resolved_type, .. } => Some(resolved_type),
8470            DataDefinition::Import { .. } => None,
8471        }
8472    }
8473
8474    /// Alias for [`Self::lemma_type`] (historical name).
8475    #[inline]
8476    pub fn schema_type(&self) -> Option<&LemmaType> {
8477        self.lemma_type()
8478    }
8479
8480    /// Returns the literal value when the data already holds one, including `-> with`
8481    /// on a type declaration or reference. A data-target `Reference`'s copied value
8482    /// is produced by the evaluator at runtime, so at plan-time it has no value yet.
8483    pub fn value(&self) -> Option<LiteralValue> {
8484        match self {
8485            DataDefinition::Value { value, .. } => Some(value.clone()),
8486            DataDefinition::TypeDeclaration {
8487                declared_value: Some(dv),
8488                ..
8489            } => Some(dv.to_literal()),
8490            DataDefinition::Reference {
8491                local_value: Some(dv),
8492                resolved_type: _,
8493                ..
8494            } => Some(dv.to_literal()),
8495            DataDefinition::TypeDeclaration { .. }
8496            | DataDefinition::Import { .. }
8497            | DataDefinition::InstanceList { .. }
8498            | DataDefinition::Reference { .. } => None,
8499        }
8500    }
8501
8502    /// Fill value with optional written measure unit binding (Show display).
8503    pub(crate) fn bound_value(&self) -> Option<&BoundValueKind> {
8504        match self {
8505            DataDefinition::TypeDeclaration {
8506                declared_value: Some(dv),
8507                ..
8508            }
8509            | DataDefinition::Reference {
8510                local_value: Some(dv),
8511                ..
8512            } => Some(dv),
8513            DataDefinition::Value { .. }
8514            | DataDefinition::TypeDeclaration { .. }
8515            | DataDefinition::Reference { .. }
8516            | DataDefinition::InstanceList { .. }
8517            | DataDefinition::Import { .. } => None,
8518        }
8519    }
8520
8521    /// Suggestion with optional written measure unit binding (Show display).
8522    /// Surfaces in [`crate::planning::execution_plan::ShowData::suggestion`] for
8523    /// show/response/UI; the evaluator never commits it — unbound stays MissingData.
8524    pub(crate) fn bound_suggestion(&self) -> Option<&BoundValueKind> {
8525        match self {
8526            DataDefinition::TypeDeclaration {
8527                declared_suggestion: Some(dv),
8528                ..
8529            }
8530            | DataDefinition::Reference {
8531                local_suggestion: Some(dv),
8532                ..
8533            } => Some(dv),
8534            DataDefinition::Value { .. }
8535            | DataDefinition::TypeDeclaration { .. }
8536            | DataDefinition::Reference { .. }
8537            | DataDefinition::InstanceList { .. }
8538            | DataDefinition::Import { .. } => None,
8539        }
8540    }
8541
8542    /// Returns the source location for this data.
8543    pub fn source(&self) -> &Source {
8544        match self {
8545            DataDefinition::Value { source, .. } => source,
8546            DataDefinition::TypeDeclaration { source, .. } => source,
8547            DataDefinition::Import { source, .. } => source,
8548            DataDefinition::InstanceList { source, .. } => source,
8549            DataDefinition::Reference { source, .. } => source,
8550        }
8551    }
8552
8553    /// The sole row of a static (`pin` is `None`) import.
8554    pub fn import_sole_row(&self) -> &Arc<RowInstance> {
8555        let DataDefinition::Import { pin, row, .. } = self else {
8556            panic!("BUG: import_sole_row on non-import data");
8557        };
8558        assert!(
8559            pin.is_none(),
8560            "BUG: dynamic import needs pin selection before reading a row"
8561        );
8562        row
8563    }
8564
8565    /// Candidate rows of a dynamic import (`pin` is set).
8566    pub fn import_candidates(&self) -> &std::collections::BTreeMap<SpecIdentity, Arc<RowInstance>> {
8567        let DataDefinition::Import {
8568            pin, candidates, ..
8569        } = self
8570        else {
8571            panic!("BUG: import_candidates on non-import data");
8572        };
8573        assert!(pin.is_some(), "BUG: static import has no candidate map");
8574        candidates
8575    }
8576
8577    /// Whether this import selects its body from a `-> effective` pin at evaluation.
8578    pub fn import_pin(&self) -> Option<&ImportEffectivePin> {
8579        match self {
8580            DataDefinition::Import { pin, .. } => pin.as_ref(),
8581            _ => None,
8582        }
8583    }
8584
8585    /// Row of a dynamic import for `identity`, or the sole static row when `pin` is `None`.
8586    pub fn import_row_for(&self, identity: &SpecIdentity) -> &Arc<RowInstance> {
8587        let DataDefinition::Import {
8588            pin,
8589            row,
8590            candidates,
8591            ..
8592        } = self
8593        else {
8594            panic!("BUG: import_row_for on non-import data");
8595        };
8596        if pin.is_none() {
8597            return row;
8598        }
8599        candidates
8600            .get(identity)
8601            .unwrap_or_else(|| panic!("BUG: dynamic import has no row for identity '{identity}'"))
8602    }
8603}
8604
8605/// Bind a type-agnostic [`Value::NumberWithUnit`] using the unit index entry for `unit_name`.
8606pub fn number_with_unit_to_value_kind(
8607    magnitude: rust_decimal::Decimal,
8608    unit_name: &str,
8609    lemma_type: &LemmaType,
8610) -> Result<ValueKind, String> {
8611    match &lemma_type.specifications {
8612        TypeSpecification::Ratio { units, .. } => {
8613            use crate::computation::rational::{checked_div, decimal_to_rational};
8614            let unit = units.get(unit_name)?;
8615            let magnitude_rational = decimal_to_rational(magnitude)
8616                .map_err(|failure| format!("ratio literal failed rational lift: {failure}"))?;
8617            let canonical_rational = checked_div(&magnitude_rational, &unit.value)
8618                .map_err(|failure| format!("ratio literal: unit conversion failed: {failure}"))?;
8619            Ok(ValueKind::Ratio(canonical_rational))
8620        }
8621        TypeSpecification::Measure { units, .. } => {
8622            use crate::computation::rational::checked_mul;
8623            let rational = lift_parser_decimal(magnitude)?;
8624            let unit = units.get(unit_name)?;
8625            match unit.literal_factor() {
8626                Some(factor) => {
8627                    let canonical = checked_mul(&rational, factor).map_err(|failure| {
8628                        format!("measure canonicalization overflow: {failure}")
8629                    })?;
8630                    Ok(ValueKind::Measure(canonical))
8631                }
8632                None => Ok(ValueKind::UnscaledMeasure {
8633                    magnitude: rational,
8634                    unit: std::sync::Arc::from(unit_name),
8635                }),
8636            }
8637        }
8638        _ => Err(format!(
8639            "Unit '{}' is defined on type '{}' which is not measure or ratio",
8640            unit_name,
8641            lemma_type.name()
8642        )),
8643    }
8644}
8645
8646/// Whether a [`ValueKind`] is structurally compatible with a [`TypeSpecification`].
8647/// Bound validation (min/max/decimals) is separate; this only checks shape.
8648pub(crate) fn value_kind_matches_spec(value: &ValueKind, type_spec: &TypeSpecification) -> bool {
8649    matches!(
8650        (type_spec, value),
8651        (TypeSpecification::Number { .. }, ValueKind::Number(_))
8652            | (TypeSpecification::Text { .. }, ValueKind::Text(_))
8653            | (TypeSpecification::Boolean { .. }, ValueKind::Boolean(_))
8654            | (TypeSpecification::Date { .. }, ValueKind::Date(_))
8655            | (TypeSpecification::Time { .. }, ValueKind::Time(_))
8656            | (TypeSpecification::Measure { .. }, ValueKind::Measure(_))
8657            | (
8658                TypeSpecification::Measure { .. },
8659                ValueKind::UnscaledMeasure { .. }
8660            )
8661            | (TypeSpecification::Ratio { .. }, ValueKind::Ratio(_))
8662            | (
8663                TypeSpecification::NumberRange { .. },
8664                ValueKind::Range(_, _)
8665            )
8666            | (TypeSpecification::DateRange { .. }, ValueKind::Range(_, _))
8667            | (TypeSpecification::TimeRange { .. }, ValueKind::Range(_, _))
8668            | (TypeSpecification::RatioRange { .. }, ValueKind::Range(_, _))
8669            | (
8670                TypeSpecification::MeasureRange { .. },
8671                ValueKind::Range(_, _)
8672            )
8673            | (TypeSpecification::Veto { .. }, _)
8674            | (TypeSpecification::Undetermined, _)
8675            | (TypeSpecification::Spec { .. }, ValueKind::Spec(_))
8676            | (TypeSpecification::List { .. }, ValueKind::List(_))
8677    )
8678}
8679
8680fn parser_value_type_mismatch(
8681    value: &crate::literals::Value,
8682    type_spec: &TypeSpecification,
8683) -> String {
8684    use crate::parsing::ast::AsLemmaSource;
8685    let value_str = format!("{}", AsLemmaSource(value));
8686    match type_spec {
8687        TypeSpecification::Measure { units, .. } => {
8688            let unit_hint = units
8689                .iter()
8690                .find(|u| u.is_canonical_factor())
8691                .map(|u| u.name.as_str())
8692                .or_else(|| units.iter().next().map(|u| u.name.as_str()))
8693                .unwrap_or("unit");
8694            format!("cannot use {value_str} as {type_spec}: expected `<n> {unit_hint}`")
8695        }
8696        TypeSpecification::Ratio { units, .. } if !units.is_empty() => {
8697            let unit_hint = units
8698                .iter()
8699                .next()
8700                .map(|u| u.name.as_str())
8701                .unwrap_or("unit");
8702            format!("cannot use {value_str} as {type_spec}: expected `<n> {unit_hint}`")
8703        }
8704        _ => format!("cannot use {value_str} as {type_spec}"),
8705    }
8706}
8707
8708/// Re-canonicalize a measure literal after compound unit factors were resolved.
8709///
8710/// Literals parsed before derived unit resolution were canonicalized with prefix-only
8711/// factors; multiply by `resolved_factor / stored_factor` to align with final factors.
8712pub fn refresh_measure_literal_canonical_magnitude(
8713    lit: &mut LiteralValue,
8714    previous_type: &LemmaType,
8715    resolved_type: &LemmaType,
8716) -> Result<(), crate::computation::rational::NumericFailure> {
8717    use crate::computation::rational::{checked_div, checked_mul};
8718    let ValueKind::Measure(magnitude) = &mut lit.value else {
8719        if matches!(lit.value, ValueKind::UnscaledMeasure { .. }) {
8720            return Ok(());
8721        }
8722        return Ok(());
8723    };
8724    // Binding unit is no longer on ValueKind; magnitude was canonicalized at bind time
8725    // against the then-current unit table. When a single-term runtime signature unit
8726    // exists on both tables, rescale if that unit's factor changed.
8727    let signature = previous_type.measure_runtime_signature();
8728    let Some((unit_name, 1)) = signature.first().map(|(n, e)| (n.as_str(), *e)) else {
8729        return Ok(());
8730    };
8731    if signature.len() != 1 {
8732        return Ok(());
8733    }
8734    let stored_factor = previous_type.measure_unit_factor(unit_name);
8735    let resolved_factor = resolved_type.measure_unit_factor(unit_name);
8736    if stored_factor == resolved_factor {
8737        return Ok(());
8738    }
8739    let scaled = checked_mul(magnitude, resolved_factor)?;
8740    *magnitude = checked_div(&scaled, stored_factor)?;
8741    Ok(())
8742}
8743
8744fn number_with_unit_value_kind(
8745    magnitude: rust_decimal::Decimal,
8746    unit_name: &str,
8747    type_spec: &TypeSpecification,
8748) -> Result<ValueKind, String> {
8749    use crate::computation::rational::{checked_div, checked_mul, decimal_to_rational};
8750    match type_spec {
8751        TypeSpecification::Ratio { units, .. } => {
8752            let unit = units.get(unit_name)?;
8753            let magnitude_rational = decimal_to_rational(magnitude)
8754                .map_err(|failure| format!("ratio literal failed rational lift: {failure}"))?;
8755            let canonical_rational = checked_div(&magnitude_rational, &unit.value)
8756                .map_err(|failure| format!("ratio literal: unit conversion failed: {failure}"))?;
8757            Ok(ValueKind::Ratio(canonical_rational))
8758        }
8759        TypeSpecification::Measure { units, .. } => {
8760            let rational = lift_parser_decimal(magnitude)?;
8761            let unit = units.get(unit_name)?;
8762            match unit.literal_factor() {
8763                Some(factor) => {
8764                    let canonical = checked_mul(&rational, factor).map_err(|failure| {
8765                        format!("measure canonicalization overflow: {failure}")
8766                    })?;
8767                    Ok(ValueKind::Measure(canonical))
8768                }
8769                None => Ok(ValueKind::UnscaledMeasure {
8770                    magnitude: rational,
8771                    unit: Arc::from(unit_name),
8772                }),
8773            }
8774        }
8775        _ => Err("number_with_unit literal requires a measure or ratio type".to_string()),
8776    }
8777}
8778
8779/// Convert a non-range parser [`Value`] to [`ValueKind`] using the target type.
8780///
8781/// Range values must go through [`parser_value_to_value_kind`] so endpoints use
8782/// [`lift_range_endpoint`]. Kept separate so that helper cannot re-enter the Range arm.
8783fn parser_scalar_to_value_kind(
8784    value: &crate::literals::Value,
8785    type_spec: &TypeSpecification,
8786) -> Result<ValueKind, String> {
8787    use crate::literals::Value;
8788    match (value, type_spec) {
8789        (Value::NumberWithUnit(magnitude, unit_name), _) => {
8790            number_with_unit_value_kind(*magnitude, unit_name, type_spec)
8791        }
8792        (Value::Number(n), TypeSpecification::Number { .. }) => {
8793            Ok(ValueKind::Number(lift_parser_decimal(*n)?))
8794        }
8795        (Value::Text(s), TypeSpecification::Text { .. }) => {
8796            Ok(ValueKind::Text(Arc::from(s.as_str())))
8797        }
8798        (Value::Boolean(b), TypeSpecification::Boolean { .. }) => Ok(ValueKind::Boolean(b.into())),
8799        (Value::Date(dt), TypeSpecification::Date { .. }) => {
8800            Ok(ValueKind::Date(date_time_to_semantic(dt)))
8801        }
8802        (Value::Time(t), TypeSpecification::Time { .. }) => {
8803            Ok(ValueKind::Time(time_to_semantic(t)))
8804        }
8805        (value, type_spec) => Err(parser_value_type_mismatch(value, type_spec)),
8806    }
8807}
8808
8809/// Convert parser [`Value`] to [`ValueKind`] using the target type (canonicalizes ratio at bind).
8810///
8811/// When `resolve_unit` is set, qualified range-endpoint unit tokens are resolved to bare
8812/// declared names before bind. Measure and ratio range endpoints keep `lemma_type`'s family
8813/// via [`LemmaType::range_element_type`].
8814pub fn parser_value_to_value_kind(
8815    value: &crate::literals::Value,
8816    lemma_type: &LemmaType,
8817    resolve_unit: Option<&UnitTokenResolver<'_>>,
8818) -> Result<ValueKind, String> {
8819    use crate::literals::Value;
8820    match (value, &lemma_type.specifications) {
8821        (
8822            Value::Range(left, right),
8823            TypeSpecification::NumberRange { .. }
8824            | TypeSpecification::DateRange { .. }
8825            | TypeSpecification::TimeRange { .. }
8826            | TypeSpecification::RatioRange { .. }
8827            | TypeSpecification::MeasureRange { .. },
8828        ) => {
8829            let endpoint = match &lemma_type.specifications {
8830                TypeSpecification::MeasureRange { .. } | TypeSpecification::RatioRange { .. } => {
8831                    lemma_type.range_element_type()
8832                }
8833                other => Arc::new(LemmaType::primitive(
8834                    range_element_type_specification(other).expect(
8835                        "BUG: range_element_type_specification missing arm for known range type",
8836                    ),
8837                )),
8838            };
8839            let left_lit = lift_range_endpoint(left, endpoint.as_ref(), resolve_unit)?;
8840            let right_lit = lift_range_endpoint(right, endpoint.as_ref(), resolve_unit)?;
8841            Ok(ValueKind::Range(Box::new(left_lit), Box::new(right_lit)))
8842        }
8843        (value, type_spec) => parser_scalar_to_value_kind(value, type_spec),
8844    }
8845}
8846
8847/// Read a parsed Lemma literal as a value of `lemma_type`, keeping the written unit.
8848pub(crate) fn typed_literal_from_parsed(
8849    parsed: &crate::literals::Value,
8850    lemma_type: &Arc<LemmaType>,
8851    unit_index: &UnitIndex,
8852    named_types: &IndexMap<String, Arc<LemmaType>>,
8853) -> Result<TypedLiteral, String> {
8854    let resolve = UnitTokenResolver::Typed {
8855        unit_index,
8856        named_types,
8857        lemma_type: lemma_type.as_ref(),
8858    };
8859    let kind = parser_value_to_value_kind(parsed, lemma_type.as_ref(), Some(&resolve))?;
8860    let binding = match binding_unit_from_parser_value(parsed) {
8861        Some(written) => Some(resolve.resolve(&written)?),
8862        None => None,
8863    };
8864    Ok(typed_literal_with_binding_unit(kind, binding, lemma_type))
8865}
8866
8867pub(crate) fn typed_literal_with_binding_unit(
8868    kind: ValueKind,
8869    binding_unit: Option<String>,
8870    lemma_type: &Arc<LemmaType>,
8871) -> TypedLiteral {
8872    let typed_type = match binding_unit {
8873        Some(unit)
8874            if matches!(
8875                &lemma_type.specifications,
8876                TypeSpecification::Measure { .. } | TypeSpecification::Ratio { .. }
8877            ) =>
8878        {
8879            Arc::new(lemma_type.as_ref().clone().with_unit(unit))
8880        }
8881        Some(_) | None => Arc::clone(lemma_type),
8882    };
8883    TypedLiteral {
8884        value: kind,
8885        lemma_type: typed_type,
8886    }
8887}
8888
8889fn binding_unit_from_parser_value(value: &crate::literals::Value) -> Option<String> {
8890    use crate::literals::Value;
8891    match value {
8892        Value::NumberWithUnit(_, unit) => Some(unit.clone()),
8893        Value::Range(left, right) => match (left.as_ref(), right.as_ref()) {
8894            (Value::NumberWithUnit(_, left_unit), Value::NumberWithUnit(_, right_unit))
8895                if left_unit == right_unit =>
8896            {
8897                Some(left_unit.clone())
8898            }
8899            _ => None,
8900        },
8901        _ => None,
8902    }
8903}
8904
8905/// Convert parser Value to ValueKind for primitives and ranges only.
8906///
8907/// [`Value::NumberWithUnit`] requires [`parser_value_to_value_kind`] with a measure or ratio type.
8908pub fn value_to_semantic(value: &crate::parsing::ast::Value) -> Result<ValueKind, String> {
8909    use crate::parsing::ast::Value;
8910    Ok(match value {
8911        Value::Number(n) => ValueKind::Number(lift_parser_decimal(*n)?),
8912        Value::Text(s) => ValueKind::Text(Arc::from(s.as_str())),
8913        Value::Boolean(b) => ValueKind::Boolean(bool::from(*b)),
8914        Value::Date(dt) => ValueKind::Date(date_time_to_semantic(dt)),
8915        Value::Time(t) => ValueKind::Time(time_to_semantic(t)),
8916        Value::NumberWithUnit(_, _) => {
8917            return Err(
8918                "number_with_unit literal requires type context (measure or ratio)".to_string(),
8919            );
8920        }
8921        Value::Range(_, _) => literal_value_from_parser_value(value)?.value,
8922    })
8923}
8924
8925/// Convert AST date-time to semantic (for tests and planning).
8926pub(crate) fn date_time_to_semantic(dt: &crate::parsing::ast::DateTimeValue) -> SemanticDateTime {
8927    SemanticDateTime {
8928        year: dt.year,
8929        month: dt.month,
8930        day: dt.day,
8931        hour: dt.hour,
8932        minute: dt.minute,
8933        second: dt.second,
8934        microsecond: dt.microsecond,
8935        timezone: dt.timezone.as_ref().map(SemanticTimezone::from),
8936    }
8937}
8938
8939/// Project a date's clock fields to a time-of-day (date-only values yield midnight).
8940pub(crate) fn semantic_date_as_time(date: &SemanticDateTime) -> SemanticTime {
8941    SemanticTime {
8942        hour: date.hour,
8943        minute: date.minute,
8944        second: date.second,
8945        microsecond: date.microsecond,
8946        timezone: date.timezone.clone(),
8947    }
8948}
8949
8950/// Convert AST time to semantic (for tests and planning).
8951pub(crate) fn time_to_semantic(t: &crate::parsing::ast::TimeValue) -> SemanticTime {
8952    SemanticTime {
8953        hour: t.hour.into(),
8954        minute: t.minute.into(),
8955        second: t.second.into(),
8956        microsecond: t.microsecond,
8957        timezone: t.timezone.as_ref().map(SemanticTimezone::from),
8958    }
8959}
8960
8961/// Compare two semantic date-time values by year, month, day, hour, minute,
8962/// second, then microsecond. Timezone normalisation is a separate concern
8963/// handled at evaluation time.
8964pub(crate) fn compare_semantic_dates(
8965    left: &SemanticDateTime,
8966    right: &SemanticDateTime,
8967) -> std::cmp::Ordering {
8968    left.year
8969        .cmp(&right.year)
8970        .then_with(|| left.month.cmp(&right.month))
8971        .then_with(|| left.day.cmp(&right.day))
8972        .then_with(|| left.hour.cmp(&right.hour))
8973        .then_with(|| left.minute.cmp(&right.minute))
8974        .then_with(|| left.second.cmp(&right.second))
8975        .then_with(|| left.microsecond.cmp(&right.microsecond))
8976}
8977
8978/// Compare two semantic time values by hour, minute, second, then microsecond.
8979/// Timezone is excluded for the same reason as [`compare_semantic_dates`].
8980pub(crate) fn compare_semantic_times(
8981    left: &SemanticTime,
8982    right: &SemanticTime,
8983) -> std::cmp::Ordering {
8984    left.hour
8985        .cmp(&right.hour)
8986        .then_with(|| left.minute.cmp(&right.minute))
8987        .then_with(|| left.second.cmp(&right.second))
8988        .then_with(|| left.microsecond.cmp(&right.microsecond))
8989}
8990
8991// -----------------------------------------------------------------------------
8992// Primitive type constructors (moved from parsing::ast)
8993// -----------------------------------------------------------------------------
8994
8995// Statics for lazy initialization of production-used primitive types.
8996static PRIMITIVE_BOOLEAN: OnceLock<Arc<LemmaType>> = OnceLock::new();
8997static PRIMITIVE_NUMBER: OnceLock<Arc<LemmaType>> = OnceLock::new();
8998static PRIMITIVE_TEXT: OnceLock<Arc<LemmaType>> = OnceLock::new();
8999static PRIMITIVE_DATE: OnceLock<Arc<LemmaType>> = OnceLock::new();
9000static PRIMITIVE_DATE_RANGE: OnceLock<Arc<LemmaType>> = OnceLock::new();
9001static PRIMITIVE_TIME: OnceLock<Arc<LemmaType>> = OnceLock::new();
9002static PRIMITIVE_RATIO: OnceLock<Arc<LemmaType>> = OnceLock::new();
9003static PRIMITIVE_MEASURE: OnceLock<Arc<LemmaType>> = OnceLock::new();
9004static PRIMITIVE_MEASURE_RANGE: OnceLock<Arc<LemmaType>> = OnceLock::new();
9005static PRIMITIVE_NUMBER_RANGE: OnceLock<Arc<LemmaType>> = OnceLock::new();
9006static PRIMITIVE_RATIO_RANGE: OnceLock<Arc<LemmaType>> = OnceLock::new();
9007static PRIMITIVE_TIME_RANGE: OnceLock<Arc<LemmaType>> = OnceLock::new();
9008
9009#[must_use]
9010pub fn primitive_boolean_arc() -> &'static Arc<LemmaType> {
9011    lemma_type_for_primitive(PrimitiveKind::Boolean)
9012}
9013
9014#[must_use]
9015pub fn primitive_number_arc() -> &'static Arc<LemmaType> {
9016    lemma_type_for_primitive(PrimitiveKind::Number)
9017}
9018
9019#[must_use]
9020pub fn primitive_text_arc() -> &'static Arc<LemmaType> {
9021    lemma_type_for_primitive(PrimitiveKind::Text)
9022}
9023
9024#[must_use]
9025pub fn primitive_date_arc() -> &'static Arc<LemmaType> {
9026    lemma_type_for_primitive(PrimitiveKind::Date)
9027}
9028
9029#[must_use]
9030pub fn primitive_date_range_arc() -> &'static Arc<LemmaType> {
9031    lemma_type_for_primitive(PrimitiveKind::DateRange)
9032}
9033
9034#[must_use]
9035pub fn primitive_time_arc() -> &'static Arc<LemmaType> {
9036    lemma_type_for_primitive(PrimitiveKind::Time)
9037}
9038
9039#[must_use]
9040pub fn primitive_ratio_arc() -> &'static Arc<LemmaType> {
9041    lemma_type_for_primitive(PrimitiveKind::Ratio)
9042}
9043
9044/// Singleton primitive `LemmaType` for `kind`. Same `Arc` for the same primitive for the process.
9045#[must_use]
9046pub fn lemma_type_for_primitive(kind: PrimitiveKind) -> &'static Arc<LemmaType> {
9047    let cell = match kind {
9048        PrimitiveKind::Boolean => &PRIMITIVE_BOOLEAN,
9049        PrimitiveKind::Number => &PRIMITIVE_NUMBER,
9050        PrimitiveKind::Text => &PRIMITIVE_TEXT,
9051        PrimitiveKind::Date => &PRIMITIVE_DATE,
9052        PrimitiveKind::DateRange => &PRIMITIVE_DATE_RANGE,
9053        PrimitiveKind::Time => &PRIMITIVE_TIME,
9054        PrimitiveKind::Ratio => &PRIMITIVE_RATIO,
9055        PrimitiveKind::Measure => &PRIMITIVE_MEASURE,
9056        PrimitiveKind::MeasureRange => &PRIMITIVE_MEASURE_RANGE,
9057        PrimitiveKind::NumberRange => &PRIMITIVE_NUMBER_RANGE,
9058        PrimitiveKind::RatioRange => &PRIMITIVE_RATIO_RANGE,
9059        PrimitiveKind::TimeRange => &PRIMITIVE_TIME_RANGE,
9060    };
9061    cell.get_or_init(|| Arc::new(LemmaType::primitive(type_spec_for_primitive(kind))))
9062}
9063
9064/// Map PrimitiveKind to TypeSpecification. Single source of truth for primitive type resolution.
9065#[must_use]
9066pub fn type_spec_for_primitive(kind: PrimitiveKind) -> TypeSpecification {
9067    match kind {
9068        PrimitiveKind::Boolean => TypeSpecification::boolean(),
9069        PrimitiveKind::Measure => TypeSpecification::measure(),
9070        PrimitiveKind::MeasureRange => TypeSpecification::measure_range(),
9071        PrimitiveKind::Number => TypeSpecification::number(),
9072        PrimitiveKind::NumberRange => TypeSpecification::number_range(),
9073        PrimitiveKind::Ratio => TypeSpecification::ratio(),
9074        PrimitiveKind::RatioRange => TypeSpecification::ratio_range(),
9075        PrimitiveKind::Text => TypeSpecification::text(),
9076        PrimitiveKind::Date => TypeSpecification::date(),
9077        PrimitiveKind::DateRange => TypeSpecification::date_range(),
9078        PrimitiveKind::Time => TypeSpecification::time(),
9079        PrimitiveKind::TimeRange => TypeSpecification::time_range(),
9080    }
9081}
9082
9083// -----------------------------------------------------------------------------
9084// Display implementations
9085// -----------------------------------------------------------------------------
9086
9087impl fmt::Display for PathSegment {
9088    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
9089        let hop = self.input_key();
9090        match &self.repository {
9091            Some(repository) => write!(f, "{hop} → {} {}", repository, self.spec),
9092            None => write!(f, "{hop} → {}", self.spec),
9093        }
9094    }
9095}
9096
9097impl fmt::Display for DataPath {
9098    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
9099        write!(f, "{}", self.input_key())
9100    }
9101}
9102
9103impl fmt::Display for RulePath {
9104    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
9105        write!(f, "{}", self.input_key())
9106    }
9107}
9108
9109impl fmt::Display for LemmaType {
9110    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
9111        write!(f, "{}", self.name())
9112    }
9113}
9114
9115pub(crate) fn format_decimal_for_api(decimal: rust_decimal::Decimal) -> rust_decimal::Decimal {
9116    let normalized = decimal.normalize();
9117    if normalized.fract().is_zero() {
9118        normalized.trunc()
9119    } else {
9120        normalized
9121    }
9122}
9123
9124fn format_decimal_for_human_display(decimal: rust_decimal::Decimal) -> String {
9125    decimal.normalize().to_string()
9126}
9127
9128fn format_rational_for_human_display(
9129    magnitude: &crate::computation::rational::RationalInteger,
9130) -> String {
9131    match magnitude.try_to_decimal() {
9132        Ok(decimal) => format_decimal_for_human_display(decimal),
9133        Err(crate::computation::rational::NumericFailure::Overflow) => magnitude.display_str(),
9134        Err(_) => magnitude.display_str(),
9135    }
9136}
9137
9138/// Whether any declared unit of this measure family has a known factor (literal or
9139/// settled / carried in `runtime_scales`).
9140pub(crate) fn measure_family_has_expressible_unit(
9141    lemma_type: &LemmaType,
9142    runtime_scales: Option<&HashMap<String, crate::computation::rational::RationalInteger>>,
9143) -> bool {
9144    let Some(units) = lemma_type.measure_units_table() else {
9145        return true;
9146    };
9147    if units.is_empty() {
9148        return true;
9149    }
9150    units.iter().any(|unit| {
9151        unit.literal_factor().is_some()
9152            || runtime_scales.is_some_and(|scales| scales.contains_key(&unit.name))
9153    })
9154}
9155
9156fn measure_display_unit<'a>(
9157    units: &'a crate::literals::MeasureUnits,
9158    lemma_type: &LemmaType,
9159    runtime_scales: Option<&HashMap<String, crate::computation::rational::RationalInteger>>,
9160) -> &'a crate::literals::MeasureUnit {
9161    let factor_known = |unit: &crate::literals::MeasureUnit| {
9162        unit.literal_factor().is_some()
9163            || runtime_scales.is_some_and(|scales| scales.contains_key(&unit.name))
9164    };
9165    if let Some(binding) = lemma_type.unit() {
9166        let unit = units
9167            .iter()
9168            .find(|unit| unit.name == binding)
9169            .unwrap_or_else(|| {
9170                panic!(
9171                    "BUG: measure display binding '{binding}' is not a declared unit on type {}",
9172                    lemma_type.name()
9173                )
9174            });
9175        if factor_known(unit) {
9176            return unit;
9177        }
9178    }
9179    units
9180        .iter()
9181        .find(|unit| unit.is_canonical_factor() && factor_known(unit))
9182        .or_else(|| {
9183            units
9184                .iter()
9185                .find(|unit| unit.literal_factor().is_some() && factor_known(unit))
9186        })
9187        .or_else(|| units.iter().find(|unit| factor_known(unit)))
9188        .unwrap_or_else(|| {
9189            panic!(
9190                "BUG: measure display of '{}' reached with no factor-known unit; callers must veto first",
9191                lemma_type.name()
9192            )
9193        })
9194}
9195
9196fn format_measure_canonical_for_display(
9197    canonical: &crate::computation::rational::RationalInteger,
9198    lemma_type: &LemmaType,
9199    signature: &[(String, i32)],
9200    runtime_scales: Option<&HashMap<String, crate::computation::rational::RationalInteger>>,
9201) -> String {
9202    use crate::computation::rational::checked_div;
9203
9204    if let TypeSpecification::Measure { units, .. } = &lemma_type.specifications {
9205        if !units.is_empty() {
9206            let unit = measure_display_unit(units, lemma_type, runtime_scales);
9207            let factor = unit
9208                .literal_factor()
9209                .cloned()
9210                .or_else(|| {
9211                    runtime_scales.and_then(|scales| scales.get(&unit.name).cloned())
9212                })
9213                .unwrap_or_else(|| {
9214                    panic!(
9215                        "BUG: display of unit '{}' on {} requires a literal factor or a settled runtime scale",
9216                        unit.name,
9217                        lemma_type.name()
9218                    )
9219                });
9220            let in_unit = checked_div(canonical, &factor)
9221                .expect("BUG: de-canonicalization for measure display must not fail");
9222            return format_number_with_unit_for_display(&in_unit, &unit.name);
9223        }
9224    }
9225
9226    let unit_label = match signature {
9227        [] => String::new(),
9228        [(name, 1)] => name.clone(),
9229        _ => format_signature_operator_style(signature),
9230    };
9231    let formatted = format_rational_for_human_display(canonical);
9232    if unit_label.is_empty() {
9233        formatted
9234    } else {
9235        format!("{formatted} {unit_label}")
9236    }
9237}
9238
9239fn format_ratio_canonical_for_display(
9240    canonical: &crate::computation::rational::RationalInteger,
9241    lemma_type: &LemmaType,
9242) -> String {
9243    use crate::computation::rational::checked_mul;
9244
9245    let units = match &lemma_type.specifications {
9246        TypeSpecification::Ratio { units, .. } | TypeSpecification::RatioRange { units, .. } => {
9247            units
9248        }
9249        _ => unreachable!(
9250            "BUG: ratio display with non-ratio type {}",
9251            lemma_type.name()
9252        ),
9253    };
9254    let display_unit = lemma_type
9255        .unit()
9256        .or_else(|| lemma_type.ratio_primary_unit());
9257    let Some(unit_name) = display_unit else {
9258        return format_rational_magnitude_for_display(canonical);
9259    };
9260    let unit = units.get(unit_name).unwrap_or_else(|_| {
9261        panic!(
9262            "BUG: ratio display unit '{unit_name}' is not declared on type {}",
9263            lemma_type.name()
9264        )
9265    });
9266    let in_unit = checked_mul(canonical, &unit.value)
9267        .expect("BUG: de-canonicalization for ratio display must not fail");
9268    format_number_with_unit_for_display(&in_unit, unit_name)
9269}
9270
9271impl fmt::Display for LiteralValue {
9272    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
9273        // Measure/ratio display needs an explicit type; callers must use
9274        // `display_value_with_type`. Bare Display only covers type-free kinds and
9275        // ranges of those kinds.
9276        match &self.value {
9277            ValueKind::Measure(_) | ValueKind::Ratio(_) => {
9278                write!(f, "{}", self.value)
9279            }
9280            ValueKind::Range(left, right) => write!(f, "{}...{}", left, right),
9281            _ => write!(f, "{}", self.value),
9282        }
9283    }
9284}
9285
9286// -----------------------------------------------------------------------------
9287// Tests
9288// -----------------------------------------------------------------------------
9289
9290#[cfg(test)]
9291pub(crate) mod tests {
9292    use super::*;
9293    use crate::computation::rational::decimal_to_rational;
9294    use crate::literals::DateGranularity;
9295    use crate::literals::Value;
9296    use crate::parsing::ast::{BooleanValue, DateTimeValue, PrimitiveKind, TimeValue};
9297    use rust_decimal::Decimal;
9298    use std::str::FromStr;
9299
9300    fn meter_axis(exponent: i32) -> BaseMeasureVector {
9301        [(Dimension::Family(test_type_family("meter")), exponent)]
9302            .into_iter()
9303            .collect()
9304    }
9305
9306    #[test]
9307    fn scale_decomposition_exponent_one_is_identity() {
9308        let base = meter_axis(1);
9309        assert_eq!(scale_decomposition(&base, 1), Some(base));
9310    }
9311
9312    #[test]
9313    fn scale_decomposition_squares_meter() {
9314        assert_eq!(scale_decomposition(&meter_axis(1), 2), Some(meter_axis(2)));
9315    }
9316
9317    #[test]
9318    fn scale_decomposition_zero_is_empty() {
9319        assert_eq!(
9320            scale_decomposition(&meter_axis(1), 0),
9321            Some(BaseMeasureVector::new())
9322        );
9323    }
9324
9325    #[test]
9326    fn scale_decomposition_negative_inverts_meter() {
9327        assert_eq!(
9328            scale_decomposition(&meter_axis(1), -1),
9329            Some(meter_axis(-1))
9330        );
9331    }
9332
9333    #[test]
9334    fn scale_decomposition_at_exponent_cap() {
9335        assert_eq!(
9336            scale_decomposition(&meter_axis(32), 2),
9337            Some(meter_axis(64))
9338        );
9339    }
9340
9341    #[test]
9342    fn scale_decomposition_past_exponent_cap_is_none() {
9343        assert_eq!(scale_decomposition(&meter_axis(1), 65), None);
9344        assert_eq!(scale_decomposition(&meter_axis(32), 3), None);
9345    }
9346
9347    #[must_use]
9348    pub(crate) fn test_type_family(name: &str) -> TypeFamily {
9349        TypeFamily {
9350            repository: None,
9351            spec: "test".to_string(),
9352            effective: crate::parsing::ast::EffectiveDate::Origin,
9353            name: name.to_string(),
9354        }
9355    }
9356
9357    #[must_use]
9358    pub(crate) fn primitive_measure_arc() -> &'static Arc<LemmaType> {
9359        crate::planning::semantics::lemma_type_for_primitive(PrimitiveKind::Measure)
9360    }
9361
9362    #[must_use]
9363    pub(crate) fn primitive_measure() -> &'static LemmaType {
9364        primitive_measure_arc().as_ref()
9365    }
9366
9367    #[test]
9368    fn default_primitive_help_is_goal_oriented() {
9369        let kinds = [
9370            PrimitiveKind::Boolean,
9371            PrimitiveKind::Measure,
9372            PrimitiveKind::MeasureRange,
9373            PrimitiveKind::Number,
9374            PrimitiveKind::NumberRange,
9375            PrimitiveKind::Ratio,
9376            PrimitiveKind::RatioRange,
9377            PrimitiveKind::Text,
9378            PrimitiveKind::Date,
9379            PrimitiveKind::DateRange,
9380            PrimitiveKind::Time,
9381            PrimitiveKind::TimeRange,
9382        ];
9383        for kind in kinds {
9384            let spec = type_spec_for_primitive(kind);
9385            let help = match &spec {
9386                TypeSpecification::Boolean { help, .. }
9387                | TypeSpecification::Number { help, .. }
9388                | TypeSpecification::NumberRange { help, .. }
9389                | TypeSpecification::Text { help, .. }
9390                | TypeSpecification::Measure { help, .. }
9391                | TypeSpecification::MeasureRange { help, .. }
9392                | TypeSpecification::Ratio { help, .. }
9393                | TypeSpecification::RatioRange { help, .. }
9394                | TypeSpecification::Date { help, .. }
9395                | TypeSpecification::DateRange { help, .. }
9396                | TypeSpecification::TimeRange { help, .. }
9397                | TypeSpecification::Time { help, .. } => help,
9398                TypeSpecification::Veto { .. }
9399                | TypeSpecification::Undetermined
9400                | TypeSpecification::Spec { .. }
9401                | TypeSpecification::List { .. } => {
9402                    unreachable!(
9403                        "BUG: primitive kind {:?} mapped to non-primitive spec",
9404                        kind
9405                    )
9406                }
9407            };
9408            assert!(!help.is_empty(), "help for {:?}", kind);
9409            assert!(
9410                !help.to_ascii_lowercase().contains("format:"),
9411                "help for {:?} must not describe syntax: {:?}",
9412                kind,
9413                help
9414            );
9415            assert_eq!(help, default_help_for_primitive(kind));
9416        }
9417    }
9418
9419    #[test]
9420    fn data_path_and_rule_path_display_are_input_key() {
9421        let implicit = PathSegment {
9422            uses: Arc::from("bag"),
9423            row: None,
9424            repository: None,
9425            spec: Arc::from("bag"),
9426        };
9427        let explicit = PathSegment {
9428            uses: Arc::from("bag"),
9429            row: None,
9430            repository: None,
9431            spec: Arc::from("item_bag"),
9432        };
9433        let named_repo = PathSegment {
9434            uses: Arc::from("calc"),
9435            row: None,
9436            repository: Some(Arc::from("alpha")),
9437            spec: Arc::from("pricing"),
9438        };
9439        let row = PathSegment {
9440            uses: Arc::from("staff"),
9441            row: Some(2),
9442            repository: None,
9443            spec: Arc::from("employee"),
9444        };
9445
9446        assert_eq!(
9447            DataPath::new(vec![row.clone()], "salary".to_string()).to_string(),
9448            "staff.2.salary"
9449        );
9450        assert_eq!(
9451            RulePath::new(vec![row.clone()], "double".to_string()).to_string(),
9452            "staff.2.double"
9453        );
9454        assert_eq!(row.to_string(), "staff.2 → employee");
9455        assert_eq!(
9456            SpecInstance {
9457                prefix: vec![implicit.clone(), row]
9458            }
9459            .to_string(),
9460            "bag.staff.2"
9461        );
9462        assert_eq!(
9463            DataPath::new(vec![implicit.clone()], "weight".to_string()).to_string(),
9464            "bag.weight"
9465        );
9466        assert_eq!(
9467            DataPath::new(vec![explicit.clone()], "weight".to_string()).to_string(),
9468            "bag.weight"
9469        );
9470        assert_eq!(
9471            DataPath::new(vec![named_repo.clone()], "price".to_string()).to_string(),
9472            "calc.price"
9473        );
9474        assert_eq!(
9475            RulePath::new(vec![implicit], "cost".to_string()).to_string(),
9476            "bag.cost"
9477        );
9478        assert_eq!(
9479            RulePath::new(vec![explicit], "cost".to_string()).to_string(),
9480            "bag.cost"
9481        );
9482        assert_eq!(
9483            RulePath::new(vec![named_repo], "price".to_string()).to_string(),
9484            "calc.price"
9485        );
9486
9487        assert_eq!(
9488            PathSegment {
9489                uses: Arc::from("bag"),
9490                row: None,
9491                repository: None,
9492                spec: Arc::from("item_bag"),
9493            }
9494            .to_string(),
9495            "bag → item_bag"
9496        );
9497        assert_eq!(
9498            PathSegment {
9499                uses: Arc::from("calc"),
9500                row: None,
9501                repository: Some(Arc::from("alpha")),
9502                spec: Arc::from("pricing"),
9503            }
9504            .to_string(),
9505            "calc → alpha pricing"
9506        );
9507    }
9508
9509    #[test]
9510    fn test_negated_comparison() {
9511        assert_eq!(
9512            negated_comparison(ComparisonComputation::LessThan),
9513            ComparisonComputation::GreaterThanOrEqual
9514        );
9515        assert_eq!(
9516            negated_comparison(ComparisonComputation::GreaterThanOrEqual),
9517            ComparisonComputation::LessThan
9518        );
9519        assert_eq!(
9520            negated_comparison(ComparisonComputation::Is),
9521            ComparisonComputation::IsNot
9522        );
9523        assert_eq!(
9524            negated_comparison(ComparisonComputation::IsNot),
9525            ComparisonComputation::Is
9526        );
9527    }
9528
9529    #[test]
9530    fn value_to_semantic_number_is_decimal() {
9531        let kind = value_to_semantic(&Value::Number(Decimal::from(42))).unwrap();
9532        assert!(matches!(kind, ValueKind::Number(d) if d == rational_new(42, 1)));
9533    }
9534
9535    #[test]
9536    fn value_kind_measure_serializes_magnitude_only() {
9537        let kind =
9538            ValueKind::Measure(decimal_to_rational(Decimal::from_str("99.50").unwrap()).unwrap());
9539        let json = serde_json::to_value(crate::api::ValueKind::from(&kind)).unwrap();
9540        assert_eq!(json["measure"]["value"], "99.5");
9541        assert!(json["measure"].get("signature").is_none());
9542    }
9543
9544    #[test]
9545    fn value_kind_measure_roundtrips() {
9546        let original =
9547            ValueKind::Measure(decimal_to_rational(Decimal::from_str("4800").unwrap()).unwrap());
9548        let api = crate::api::ValueKind::from(&original);
9549        let json = serde_json::to_string(&api).unwrap();
9550        let parsed: crate::api::ValueKind = serde_json::from_str(&json).unwrap();
9551        assert_eq!(api, parsed);
9552    }
9553
9554    #[test]
9555    fn value_kind_measure_empty_roundtrips() {
9556        let original =
9557            ValueKind::Measure(decimal_to_rational(Decimal::from_str("12.5").unwrap()).unwrap());
9558        let api = crate::api::ValueKind::from(&original);
9559        let json = serde_json::to_string(&api).unwrap();
9560        let parsed: crate::api::ValueKind = serde_json::from_str(&json).unwrap();
9561        assert_eq!(api, parsed);
9562    }
9563
9564    #[test]
9565    fn literal_value_number_serde_not_rational_array() {
9566        let lit = LiteralValue::number_from_decimal(Decimal::from(20));
9567        let json = serde_json::to_value(crate::api::LiteralValue::from(&lit)).unwrap();
9568        let number = json
9569            .get("value")
9570            .and_then(|v| v.get("number"))
9571            .expect("number field");
9572        assert!(number.is_string());
9573        assert_eq!(number.as_str(), Some("20"));
9574        assert!(
9575            !number.is_array(),
9576            "stored number must not serialize as [n,d]"
9577        );
9578    }
9579
9580    #[test]
9581    fn test_literal_value_to_primitive_type() {
9582        let one = rational_new(1, 1);
9583
9584        assert_eq!(TypedLiteral::text("".to_string()).lemma_type.name(), "text");
9585        assert_eq!(
9586            TypedLiteral::number(one.clone()).lemma_type.name(),
9587            "number"
9588        );
9589        assert_eq!(
9590            TypedLiteral::from_bool(bool::from(BooleanValue::True))
9591                .lemma_type
9592                .name(),
9593            "boolean"
9594        );
9595
9596        let dt = DateTimeValue {
9597            year: 2024,
9598            month: 1,
9599            day: 1,
9600            hour: 0,
9601            minute: 0,
9602            second: 0,
9603            microsecond: 0,
9604            timezone: None,
9605
9606            granularity: DateGranularity::Full,
9607        };
9608        assert_eq!(
9609            TypedLiteral::date(date_time_to_semantic(&dt))
9610                .lemma_type
9611                .name(),
9612            "date"
9613        );
9614        assert_eq!(
9615            TypedLiteral::ratio_from_decimal(Decimal::new(1, 2))
9616                .lemma_type
9617                .name(),
9618            "ratio"
9619        );
9620        let dur_type = LemmaType::new(
9621            "duration".to_string(),
9622            TypeSpecification::Measure {
9623                minimum: None,
9624                maximum: None,
9625                units: MeasureUnits::from(vec![MeasureUnit {
9626                    name: "second".to_string(),
9627                    scale: UnitScale::Literal(crate::computation::rational::rational_one()),
9628                    derived_measure_factors: Vec::new(),
9629                    decomposition: BaseMeasureVector::new(),
9630                    minimum: None,
9631                    maximum: None,
9632                    suggestion_magnitude: None,
9633                }]),
9634                traits: vec![MeasureTrait::Duration],
9635                decomposition: None,
9636                unit: None,
9637                help: String::new(),
9638            },
9639            TypeExtends::Primitive,
9640        );
9641        assert_eq!(
9642            TypedLiteral::measure_with_type(one.clone(), Arc::new(dur_type))
9643                .lemma_type
9644                .name(),
9645            "duration"
9646        );
9647    }
9648
9649    #[test]
9650    fn test_type_display() {
9651        let specs = TypeSpecification::text();
9652        let lemma_type = LemmaType::new("name".to_string(), specs, TypeExtends::Primitive);
9653        assert_eq!(format!("{}", lemma_type), "name");
9654    }
9655
9656    #[test]
9657    fn test_type_serialization() {
9658        let specs = TypeSpecification::number();
9659        let lemma_type = LemmaType::new("dice".to_string(), specs, TypeExtends::Primitive);
9660        let api = crate::api::LemmaType::from(&lemma_type);
9661        let serialized = serde_json::to_string(&api).unwrap();
9662        let deserialized: crate::api::LemmaType = serde_json::from_str(&serialized).unwrap();
9663        assert_eq!(api, deserialized);
9664    }
9665
9666    #[test]
9667    fn empty_list_display_value_with_type_is_type_spec() {
9668        let element = Arc::new(LemmaType::new(
9669            "item".to_string(),
9670            TypeSpecification::Spec {
9671                spec: SpecIdentity {
9672                    repository: None,
9673                    spec: "item".to_string(),
9674                    effective: crate::parsing::ast::EffectiveDate::Origin,
9675                    slice: crate::parsing::ast::EffectiveDate::Origin,
9676                },
9677            },
9678            TypeExtends::Primitive,
9679        ));
9680        let list_ty = LemmaType::list_of(element);
9681        let empty = LiteralValue::new(ValueKind::List(Vec::new().into()));
9682        assert_eq!(empty.display_value_with_type(&list_ty), "item list");
9683        assert_eq!(empty.display_value(), "");
9684    }
9685
9686    #[test]
9687    fn test_literal_value_display_value() {
9688        let ten = rational_new(10, 1);
9689
9690        assert_eq!(
9691            LiteralValue::text("hello".to_string()).display_value(),
9692            "hello"
9693        );
9694        assert_eq!(LiteralValue::number(ten).display_value(), "10");
9695        assert_eq!(LiteralValue::from_bool(true).display_value(), "true");
9696        assert_eq!(LiteralValue::from_bool(false).display_value(), "false");
9697
9698        // 0.10 ratio with "percent" binding displays as 10% (unit conversion applied)
9699        let ratio_ty = Arc::new(primitive_ratio_arc().as_ref().clone().with_unit("percent"));
9700        let ten_percent_ratio = LiteralValue::ratio(
9701            crate::literals::rational_from_parsed_decimal(Decimal::new(1, 1))
9702                .expect("ratio decimal"),
9703        );
9704        assert_eq!(
9705            ten_percent_ratio.display_value_with_type(ratio_ty.as_ref()),
9706            "10%"
9707        );
9708
9709        let time = TimeValue {
9710            hour: 14,
9711            minute: 30,
9712            second: 0,
9713            microsecond: 0,
9714            timezone: None,
9715        };
9716        let time_display = LiteralValue::time(time_to_semantic(&time)).display_value();
9717        assert!(time_display.contains("14"));
9718        assert!(time_display.contains("30"));
9719    }
9720
9721    #[test]
9722    fn test_measure_display_trims_trailing_zeros() {
9723        let money_type = LemmaType {
9724            name: Some("money".to_string()),
9725            specifications: TypeSpecification::Measure {
9726                minimum: None,
9727                maximum: None,
9728                units: MeasureUnits::from(vec![MeasureUnit {
9729                    name: "eur".to_string(),
9730                    scale: UnitScale::Literal(crate::computation::rational::rational_one()),
9731                    derived_measure_factors: Vec::new(),
9732                    decomposition: BaseMeasureVector::new(),
9733                    minimum: None,
9734                    maximum: None,
9735                    suggestion_magnitude: None,
9736                }]),
9737                traits: Vec::new(),
9738                decomposition: None,
9739                unit: None,
9740                help: String::new(),
9741            },
9742            extends: TypeExtends::Primitive,
9743            options: TypeOptions::default(),
9744        };
9745        let money_type = Arc::new(money_type);
9746        let val =
9747            LiteralValue::measure(decimal_to_rational(Decimal::from_str("1.8").unwrap()).unwrap());
9748        assert_eq!(val.display_value_with_type(money_type.as_ref()), "1.8 eur");
9749        let more_precision = LiteralValue::measure(
9750            decimal_to_rational(Decimal::from_str("1.80000").unwrap()).unwrap(),
9751        );
9752        assert_eq!(
9753            more_precision.display_value_with_type(money_type.as_ref()),
9754            "1.8 eur"
9755        );
9756        let count_type = Arc::new(LemmaType {
9757            name: Some("count".to_string()),
9758            specifications: TypeSpecification::Measure {
9759                minimum: None,
9760                maximum: None,
9761                units: MeasureUnits::from(vec![MeasureUnit {
9762                    name: "items".to_string(),
9763                    scale: UnitScale::Literal(crate::computation::rational::rational_one()),
9764                    derived_measure_factors: Vec::new(),
9765                    decomposition: BaseMeasureVector::new(),
9766                    minimum: None,
9767                    maximum: None,
9768                    suggestion_magnitude: None,
9769                }]),
9770                traits: Vec::new(),
9771                decomposition: None,
9772                unit: None,
9773                help: String::new(),
9774            },
9775            extends: TypeExtends::Primitive,
9776            options: TypeOptions::default(),
9777        });
9778        let val_any = LiteralValue::measure(
9779            decimal_to_rational(Decimal::from_str("42.50").unwrap()).unwrap(),
9780        );
9781        assert_eq!(
9782            val_any.display_value_with_type(count_type.as_ref()),
9783            "42.5 items"
9784        );
9785    }
9786
9787    #[test]
9788    fn test_literal_value_time_type() {
9789        let time = TimeValue {
9790            hour: 14,
9791            minute: 30,
9792            second: 0,
9793            microsecond: 0,
9794            timezone: None,
9795        };
9796        let lit = TypedLiteral::time(time_to_semantic(&time));
9797        assert_eq!(lit.lemma_type.name(), "time");
9798    }
9799
9800    #[test]
9801    fn test_measure_family_name_none_without_declaring_spec() {
9802        let money_primitive = LemmaType::new(
9803            "money".to_string(),
9804            TypeSpecification::measure(),
9805            TypeExtends::Primitive,
9806        );
9807        assert_eq!(money_primitive.measure_family_name(), None);
9808    }
9809
9810    #[test]
9811    fn test_measure_family_name_custom() {
9812        let measure_spec = TypeSpecification::measure();
9813        let money_custom = LemmaType::new(
9814            "money".to_string(),
9815            measure_spec,
9816            TypeExtends::custom_local("money".to_string(), test_type_family("money")),
9817        );
9818        assert_eq!(money_custom.measure_family_name(), Some("money"));
9819    }
9820
9821    #[test]
9822    fn test_same_named_roots_in_different_specs_are_different_families() {
9823        let declared_in = |spec: &str| TypeFamily {
9824            repository: None,
9825            spec: spec.to_string(),
9826            effective: crate::parsing::ast::EffectiveDate::Origin,
9827            name: "money".to_string(),
9828        };
9829        let pricing_money = LemmaType::new(
9830            "money".to_string(),
9831            TypeSpecification::measure(),
9832            TypeExtends::custom_local("measure".to_string(), declared_in("pricing")),
9833        );
9834        let shop_money = LemmaType::new(
9835            "money".to_string(),
9836            TypeSpecification::measure(),
9837            TypeExtends::custom_local("measure".to_string(), declared_in("shop")),
9838        );
9839        assert!(!pricing_money.same_measure_family(&shop_money));
9840        assert!(!shop_money.same_measure_family(&pricing_money));
9841    }
9842
9843    #[test]
9844    fn test_same_measure_family_parent_and_child() {
9845        let measure_spec = TypeSpecification::measure();
9846        let type_x = LemmaType::new(
9847            "x".to_string(),
9848            measure_spec.clone(),
9849            TypeExtends::custom_local("measure".to_string(), test_type_family("x")),
9850        );
9851        let type_x2 = LemmaType::new(
9852            "x2".to_string(),
9853            measure_spec,
9854            TypeExtends::custom_local("x".to_string(), test_type_family("x")),
9855        );
9856        assert_eq!(type_x.measure_family_name(), Some("x"));
9857        assert_eq!(type_x2.measure_family_name(), Some("x"));
9858        assert!(type_x.same_measure_family(&type_x2));
9859        assert!(type_x2.same_measure_family(&type_x));
9860    }
9861
9862    #[test]
9863    fn test_same_measure_family_siblings() {
9864        let measure_spec = TypeSpecification::measure();
9865        let type_x2_a = LemmaType::new(
9866            "x2a".to_string(),
9867            measure_spec.clone(),
9868            TypeExtends::custom_local("x".to_string(), test_type_family("x")),
9869        );
9870        let type_x2_b = LemmaType::new(
9871            "x2b".to_string(),
9872            measure_spec,
9873            TypeExtends::custom_local("x".to_string(), test_type_family("x")),
9874        );
9875        assert!(type_x2_a.same_measure_family(&type_x2_b));
9876    }
9877
9878    #[test]
9879    fn test_same_measure_family_different_families() {
9880        let measure_spec = TypeSpecification::measure();
9881        let money = LemmaType::new(
9882            "money".to_string(),
9883            measure_spec.clone(),
9884            TypeExtends::Primitive,
9885        );
9886        let temperature = LemmaType::new(
9887            "temperature".to_string(),
9888            measure_spec,
9889            TypeExtends::Primitive,
9890        );
9891        assert!(!money.same_measure_family(&temperature));
9892        assert!(!temperature.same_measure_family(&money));
9893    }
9894
9895    #[test]
9896    fn test_same_measure_family_measure_vs_non_measure() {
9897        let measure_spec = TypeSpecification::measure();
9898        let number_spec = TypeSpecification::number();
9899        let measure_type =
9900            LemmaType::new("money".to_string(), measure_spec, TypeExtends::Primitive);
9901        let number_type = LemmaType::new("amount".to_string(), number_spec, TypeExtends::Primitive);
9902        assert!(!measure_type.same_measure_family(&number_type));
9903        assert!(!number_type.same_measure_family(&measure_type));
9904    }
9905
9906    #[test]
9907    fn test_same_measure_family_anonymous_measures_are_not_family_compatible() {
9908        let left = LemmaType::anonymous_for_decomposition(duration_decomposition());
9909        let right = LemmaType::anonymous_for_decomposition(duration_decomposition());
9910
9911        assert!(!left.same_measure_family(&right));
9912        assert!(left.compatible_with_anonymous_measure(&right));
9913    }
9914
9915    #[test]
9916    fn same_value_type_distinct_families_same_decomposition_are_not_same() {
9917        let decomp: BaseMeasureVector = [
9918            (Dimension::Family(test_type_family("length")), 1i32),
9919            (Dimension::Family(test_type_family("elapsed")), -1i32),
9920        ]
9921        .into_iter()
9922        .collect();
9923        let speed_spec = |name: &str, family: &str| {
9924            let mut spec = TypeSpecification::measure();
9925            if let TypeSpecification::Measure {
9926                decomposition,
9927                help,
9928                ..
9929            } = &mut spec
9930            {
9931                *decomposition = Some(decomp.clone());
9932                *help = String::new();
9933            }
9934            LemmaType::new(
9935                name.to_string(),
9936                spec,
9937                TypeExtends::custom_local("measure".to_string(), test_type_family(family)),
9938            )
9939        };
9940        let speed_a = speed_spec("speed_a", "speed_a");
9941        let speed_b = speed_spec("speed_b", "speed_b");
9942        assert_eq!(
9943            speed_a.measure_type_decomposition(),
9944            speed_b.measure_type_decomposition()
9945        );
9946        assert!(!speed_a.same_measure_family(&speed_b));
9947        assert!(
9948            !speed_a.same_value_type(&speed_b),
9949            "same decomposition alone must not make distinct measure families same_value_type"
9950        );
9951    }
9952
9953    #[test]
9954    fn test_measure_family_name_non_measure_returns_none() {
9955        let number_spec = TypeSpecification::number();
9956        let number_type = LemmaType::new("amount".to_string(), number_spec, TypeExtends::Primitive);
9957        assert_eq!(number_type.measure_family_name(), None);
9958    }
9959
9960    #[test]
9961    fn test_lemma_type_inequality_local_vs_import_same_shape() {
9962        let measure_spec = TypeSpecification::measure();
9963        let local = LemmaType::new(
9964            "t".to_string(),
9965            measure_spec.clone(),
9966            TypeExtends::custom_local("money".to_string(), test_type_family("money")),
9967        );
9968        let imported = LemmaType::new(
9969            "t".to_string(),
9970            measure_spec,
9971            TypeExtends::Custom {
9972                parent: "money".to_string(),
9973                family: test_type_family("money"),
9974                defining_spec: TypeDefiningSpec::Import,
9975            },
9976        );
9977        assert_ne!(local, imported);
9978    }
9979
9980    #[test]
9981    fn test_lemma_type_equality_import_unit_variant() {
9982        let measure_spec = TypeSpecification::measure();
9983        let left = LemmaType::new(
9984            "t".to_string(),
9985            measure_spec.clone(),
9986            TypeExtends::Custom {
9987                parent: "money".to_string(),
9988                family: test_type_family("money"),
9989                defining_spec: TypeDefiningSpec::Import,
9990            },
9991        );
9992        let right = LemmaType::new(
9993            "t".to_string(),
9994            measure_spec,
9995            TypeExtends::Custom {
9996                parent: "money".to_string(),
9997                family: test_type_family("money"),
9998                defining_spec: TypeDefiningSpec::Import,
9999            },
10000        );
10001        assert_eq!(left, right);
10002    }
10003
10004    fn month_suggestion_arg() -> CommandArg {
10005        CommandArg::Literal(crate::literals::Value::NumberWithUnit(
10006            Decimal::ONE,
10007            "month".to_string(),
10008        ))
10009    }
10010
10011    fn unit_factor_arg(name: &str, factor: i64) -> [CommandArg; 2] {
10012        [
10013            CommandArg::Label(name.to_string()),
10014            CommandArg::UnitExpr(crate::parsing::ast::UnitArg::Factor(Decimal::from(factor))),
10015        ]
10016    }
10017
10018    #[test]
10019    fn default_calendar_on_text_reports_hint() {
10020        let mut specs = TypeSpecification::text();
10021        let mut default = None;
10022        let err = specs
10023            .apply_constraint(
10024                ConstraintNames {
10025                    type_name: "notes",
10026                    data_name: "notes",
10027                },
10028                TypeConstraintCommand::Suggest,
10029                &[month_suggestion_arg()],
10030                &mut default,
10031                &mut None,
10032                None,
10033            )
10034            .unwrap_err();
10035        assert!(err.contains("Unit 'month' is for calendar data"));
10036        assert!(err.contains("double quotes"));
10037    }
10038
10039    #[test]
10040    fn default_calendar_on_duration_reports_valid_units() {
10041        let mut specs = TypeSpecification::measure();
10042        specs
10043            .apply_constraint(
10044                ConstraintNames {
10045                    type_name: "duration",
10046                    data_name: "duration",
10047                },
10048                TypeConstraintCommand::Unit,
10049                &unit_factor_arg("second", 1),
10050                &mut None,
10051                &mut None,
10052                None,
10053            )
10054            .unwrap();
10055        specs
10056            .apply_constraint(
10057                ConstraintNames {
10058                    type_name: "duration",
10059                    data_name: "duration",
10060                },
10061                TypeConstraintCommand::Unit,
10062                &unit_factor_arg("week", 604_800),
10063                &mut None,
10064                &mut None,
10065                None,
10066            )
10067            .unwrap();
10068        specs
10069            .apply_constraint(
10070                ConstraintNames {
10071                    type_name: "duration",
10072                    data_name: "duration",
10073                },
10074                TypeConstraintCommand::Trait,
10075                &[CommandArg::Label("duration".to_string())],
10076                &mut None,
10077                &mut None,
10078                None,
10079            )
10080            .unwrap();
10081        let mut default = None;
10082        let err = specs
10083            .apply_constraint(
10084                ConstraintNames {
10085                    type_name: "duration",
10086                    data_name: "duration",
10087                },
10088                TypeConstraintCommand::Suggest,
10089                &[month_suggestion_arg()],
10090                &mut default,
10091                &mut None,
10092                None,
10093            )
10094            .unwrap_err();
10095        assert!(err.contains("Unit 'month' is for calendar data"));
10096        assert!(err.contains("Valid 'duration' units are"));
10097        assert!(err.contains("week"));
10098    }
10099
10100    #[test]
10101    fn default_valid_duration_weeks_accepted() {
10102        let mut specs = TypeSpecification::measure();
10103        specs
10104            .apply_constraint(
10105                ConstraintNames {
10106                    type_name: "duration",
10107                    data_name: "duration",
10108                },
10109                TypeConstraintCommand::Unit,
10110                &unit_factor_arg("second", 1),
10111                &mut None,
10112                &mut None,
10113                None,
10114            )
10115            .unwrap();
10116        specs
10117            .apply_constraint(
10118                ConstraintNames {
10119                    type_name: "duration",
10120                    data_name: "duration",
10121                },
10122                TypeConstraintCommand::Unit,
10123                &unit_factor_arg("week", 604_800),
10124                &mut None,
10125                &mut None,
10126                None,
10127            )
10128            .unwrap();
10129        specs
10130            .apply_constraint(
10131                ConstraintNames {
10132                    type_name: "duration",
10133                    data_name: "duration",
10134                },
10135                TypeConstraintCommand::Trait,
10136                &[CommandArg::Label("duration".to_string())],
10137                &mut None,
10138                &mut None,
10139                None,
10140            )
10141            .unwrap();
10142        let mut default = None;
10143        specs
10144            .apply_constraint(
10145                ConstraintNames {
10146                    type_name: "duration",
10147                    data_name: "duration",
10148                },
10149                TypeConstraintCommand::Suggest,
10150                &[CommandArg::Literal(crate::literals::Value::NumberWithUnit(
10151                    Decimal::from(4),
10152                    "week".to_string(),
10153                ))],
10154                &mut default,
10155                &mut None,
10156                None,
10157            )
10158            .unwrap();
10159        assert!(matches!(
10160            default,
10161            Some(RawSuggestion::Measure {
10162                unit_name,
10163                ..
10164            }) if unit_name == "week"
10165        ));
10166    }
10167
10168    #[test]
10169    fn default_unknown_unit_on_duration_lists_valid_units() {
10170        let mut specs = TypeSpecification::measure();
10171        specs
10172            .apply_constraint(
10173                ConstraintNames {
10174                    type_name: "duration",
10175                    data_name: "duration",
10176                },
10177                TypeConstraintCommand::Unit,
10178                &unit_factor_arg("second", 1),
10179                &mut None,
10180                &mut None,
10181                None,
10182            )
10183            .unwrap();
10184        specs
10185            .apply_constraint(
10186                ConstraintNames {
10187                    type_name: "duration",
10188                    data_name: "duration",
10189                },
10190                TypeConstraintCommand::Trait,
10191                &[CommandArg::Label("duration".to_string())],
10192                &mut None,
10193                &mut None,
10194                None,
10195            )
10196            .unwrap();
10197        let mut default = None;
10198        let err = specs
10199            .apply_constraint(
10200                ConstraintNames {
10201                    type_name: "duration",
10202                    data_name: "duration",
10203                },
10204                TypeConstraintCommand::Suggest,
10205                &[CommandArg::Literal(crate::literals::Value::NumberWithUnit(
10206                    Decimal::ONE,
10207                    "fortnight".to_string(),
10208                ))],
10209                &mut default,
10210                &mut None,
10211                None,
10212            )
10213            .unwrap_err();
10214        assert!(err.contains("fortnight"));
10215        assert!(err.contains("not defined on 'duration'"));
10216        assert!(err.contains("Valid units are"));
10217    }
10218
10219    fn money_measure_type() -> LemmaType {
10220        LemmaType::new(
10221            "Money".to_string(),
10222            TypeSpecification::Measure {
10223                minimum: None,
10224                maximum: None,
10225                units: MeasureUnits::from(vec![
10226                    MeasureUnit {
10227                        name: "eur".to_string(),
10228                        scale: UnitScale::Literal(crate::computation::rational::rational_one()),
10229                        derived_measure_factors: Vec::new(),
10230                        decomposition: BaseMeasureVector::new(),
10231                        minimum: None,
10232                        maximum: None,
10233                        suggestion_magnitude: None,
10234                    },
10235                    MeasureUnit {
10236                        name: "usd".to_string(),
10237                        scale: UnitScale::Literal(
10238                            crate::computation::rational::decimal_to_rational(Decimal::new(91, 2))
10239                                .expect("factor"),
10240                        ),
10241                        derived_measure_factors: Vec::new(),
10242                        decomposition: BaseMeasureVector::new(),
10243                        minimum: None,
10244                        maximum: None,
10245                        suggestion_magnitude: None,
10246                    },
10247                ]),
10248                traits: Vec::new(),
10249                decomposition: None,
10250                unit: None,
10251                help: String::new(),
10252            },
10253            TypeExtends::Primitive,
10254        )
10255    }
10256
10257    #[test]
10258    fn measure_unit_names_for_named_measure() {
10259        let money = money_measure_type();
10260        assert_eq!(money.measure_unit_names(), Some(vec!["eur", "usd"]));
10261    }
10262
10263    // ---------------------------------------------------------------------------
10264    // Phase 0 — pin combine_signatures and canonicalize_signature behavior
10265    // ---------------------------------------------------------------------------
10266
10267    fn sig(pairs: &[(&str, i32)]) -> Vec<(String, i32)> {
10268        pairs.iter().map(|(s, e)| (s.to_string(), *e)).collect()
10269    }
10270
10271    #[test]
10272    fn combine_signatures_multiply_adds_exponents() {
10273        let left = sig(&[("eur", 1)]);
10274        let right = sig(&[("hour", -1)]);
10275        let result = combine_signatures(&left, &right, true);
10276        assert_eq!(result, sig(&[("eur", 1), ("hour", -1)]));
10277    }
10278
10279    #[test]
10280    fn combine_signatures_divide_subtracts_exponents() {
10281        let left = sig(&[("eur", 1)]);
10282        let right = sig(&[("hour", 1)]);
10283        let result = combine_signatures(&left, &right, false);
10284        assert_eq!(result, sig(&[("eur", 1), ("hour", -1)]));
10285    }
10286
10287    #[test]
10288    fn combine_signatures_cancels_to_empty() {
10289        let left = sig(&[("ce", 1), ("minute", -1)]);
10290        let right = sig(&[("minute", 1)]);
10291        let result = combine_signatures(&left, &right, true);
10292        // ce * (ce/min * min) = ce; minute cancels
10293        assert_eq!(result, sig(&[("ce", 1)]));
10294    }
10295
10296    #[test]
10297    fn combine_signatures_output_is_canonical_form() {
10298        let left = sig(&[("eur", 1), ("hour", 1)]);
10299        let right = sig(&[("minute", 1)]);
10300        let result = combine_signatures(&left, &right, false); // divide
10301                                                               // [("eur",1),("hour",1)] / [("minute",1)] = [("eur",1),("hour",1),("minute",-1)]
10302        let expected = sig(&[("eur", 1), ("hour", 1), ("minute", -1)]);
10303        assert_eq!(result, expected);
10304    }
10305
10306    #[test]
10307    fn canonicalize_signature_drops_zero_exponents() {
10308        let sig_with_zero = sig(&[("eur", 1), ("hour", 0), ("minute", -1)]);
10309        let result = canonicalize_signature(&sig_with_zero);
10310        assert_eq!(result, sig(&[("eur", 1), ("minute", -1)]));
10311    }
10312
10313    #[test]
10314    fn canonicalize_signature_sorts_by_name() {
10315        let unsorted = sig(&[("minute", -1), ("eur", 1)]);
10316        let result = canonicalize_signature(&unsorted);
10317        assert_eq!(result, sig(&[("eur", 1), ("minute", -1)]));
10318    }
10319
10320    // ---------------------------------------------------------------------------
10321    // Phase 0 — format_signature_operator_style (to be implemented in
10322    // signature_factor_and_display todo)
10323    // ---------------------------------------------------------------------------
10324
10325    #[test]
10326    fn format_signature_operator_style_numerator_only() {
10327        let signature = sig(&[("eur", 1)]);
10328        let result = format_signature_operator_style(&signature);
10329        assert_eq!(result, "eur");
10330    }
10331
10332    #[test]
10333    fn format_signature_operator_style_with_denominator() {
10334        let signature = sig(&[("eur", 1), ("hour", -1)]);
10335        let result = format_signature_operator_style(&signature);
10336        assert_eq!(result, "eur/hour");
10337    }
10338
10339    #[test]
10340    fn format_signature_operator_style_denominator_only() {
10341        let signature = sig(&[("meter", -1)]);
10342        let result = format_signature_operator_style(&signature);
10343        assert_eq!(result, "1/meter");
10344    }
10345
10346    #[test]
10347    fn format_signature_operator_style_with_exponents() {
10348        let signature = sig(&[("meter", 2), ("second", -2)]);
10349        let result = format_signature_operator_style(&signature);
10350        assert_eq!(result, "meter^2/second^2");
10351    }
10352
10353    // ---------------------------------------------------------------------------
10354    // Phase 0 — calendar_unit_factor (to be implemented in builtin_calendar_factor_table)
10355    // ---------------------------------------------------------------------------
10356
10357    #[test]
10358    fn calendar_unit_factor_table_completeness() {
10359        // Every SemanticCalendarUnit Display string must resolve to a factor.
10360        // Today SemanticCalendarUnit only has Month and Year; more may be added.
10361        for unit in &[SemanticCalendarUnit::Month, SemanticCalendarUnit::Year] {
10362            let name = unit.to_string();
10363            assert!(
10364                calendar_unit_factor(&name).is_some(),
10365                "calendar_unit_factor('{}') must return Some",
10366                name
10367            );
10368        }
10369    }
10370
10371    #[test]
10372    fn semantic_calendar_unit_display_returns_singular() {
10373        // Today Month => "month", Year => "year" (plural).
10374        // After singular_calendar_names_everywhere, must be "month" and "year".
10375        assert_eq!(SemanticCalendarUnit::Month.to_string(), "month");
10376        assert_eq!(SemanticCalendarUnit::Year.to_string(), "year");
10377    }
10378
10379    // ---------------------------------------------------------------------------
10380    // Phase 0 — signature_factor (to be implemented in signature_factor_and_display)
10381    // ---------------------------------------------------------------------------
10382
10383    #[test]
10384    fn signature_factor_with_calendar_units() {
10385        let calendar = test_calendar_type_for_signature_factor();
10386        let unit_index = crate::planning::unit_index::UnitIndex::new();
10387        // month factor = 1, year factor = 12.
10388        // [(month,1),(year,-1)] = 1/12
10389        let sig_month_per_year = sig(&[("month", 1), ("year", -1)]);
10390        let factor = signature_factor(&sig_month_per_year, &unit_index, Some(&calendar))
10391            .expect("must not overflow");
10392        let expected = rational_new(1, 12);
10393        assert_eq!(factor, expected, "month/year factor must be 1/12");
10394    }
10395
10396    fn test_calendar_type_for_signature_factor() -> LemmaType {
10397        use crate::computation::rational::{decimal_to_rational, rational_one};
10398        use crate::literals::{MeasureUnit, MeasureUnits};
10399        use rust_decimal::Decimal;
10400        LemmaType::new(
10401            "calendar".to_string(),
10402            TypeSpecification::Measure {
10403                minimum: None,
10404                maximum: None,
10405                units: MeasureUnits::from(vec![
10406                    MeasureUnit {
10407                        name: "month".to_string(),
10408                        scale: UnitScale::Literal(rational_one()),
10409                        minimum: None,
10410                        maximum: None,
10411                        suggestion_magnitude: None,
10412                        decomposition: calendar_decomposition(),
10413                        derived_measure_factors: Vec::new(),
10414                    },
10415                    MeasureUnit {
10416                        name: "year".to_string(),
10417                        scale: UnitScale::Literal(
10418                            decimal_to_rational(Decimal::from(12)).expect("year factor"),
10419                        ),
10420                        minimum: None,
10421                        maximum: None,
10422                        suggestion_magnitude: None,
10423                        decomposition: calendar_decomposition(),
10424                        derived_measure_factors: Vec::new(),
10425                    },
10426                ]),
10427                traits: vec![MeasureTrait::Calendar],
10428                decomposition: Some(calendar_decomposition()),
10429                unit: None,
10430                help: String::new(),
10431            },
10432            TypeExtends::Primitive,
10433        )
10434    }
10435
10436    #[test]
10437    #[should_panic(expected = "BUG: signature_factor called with unresolved unit name")]
10438    fn signature_factor_panics_on_unresolved_name() {
10439        let unit_index = crate::planning::unit_index::UnitIndex::new();
10440        let bad_sig = sig(&[("nonexistent_unit_xyz", 1)]);
10441        signature_factor(&bad_sig, &unit_index, None)
10442            .expect("BUG: signature_factor must panic before returning a failure");
10443    }
10444
10445    #[test]
10446    fn signature_factor_uses_owner_when_expression_index_empty() {
10447        let money = test_money_type_for_signature_factor();
10448        let expression_units = crate::planning::unit_index::UnitIndex::new();
10449        let sig_usd = sig(&[("usd", 1)]);
10450        let factor =
10451            signature_factor(&sig_usd, &expression_units, Some(&money)).expect("must not overflow");
10452        assert_eq!(factor, rational_new(91, 100));
10453    }
10454
10455    fn test_money_type_for_signature_factor() -> LemmaType {
10456        use crate::computation::rational::decimal_to_rational;
10457        use crate::literals::{MeasureUnit, MeasureUnits};
10458        use rust_decimal::Decimal;
10459        LemmaType::new(
10460            "money".to_string(),
10461            TypeSpecification::Measure {
10462                minimum: None,
10463                maximum: None,
10464                units: MeasureUnits::from(vec![
10465                    MeasureUnit {
10466                        name: "eur".to_string(),
10467                        scale: UnitScale::Literal(crate::computation::rational::rational_one()),
10468                        minimum: None,
10469                        maximum: None,
10470                        suggestion_magnitude: None,
10471                        decomposition: BaseMeasureVector::new(),
10472                        derived_measure_factors: Vec::new(),
10473                    },
10474                    MeasureUnit {
10475                        name: "usd".to_string(),
10476                        scale: UnitScale::Literal(
10477                            decimal_to_rational(Decimal::new(91, 2)).expect("usd factor"),
10478                        ),
10479                        minimum: None,
10480                        maximum: None,
10481                        suggestion_magnitude: None,
10482                        decomposition: BaseMeasureVector::new(),
10483                        derived_measure_factors: Vec::new(),
10484                    },
10485                ]),
10486                traits: Vec::new(),
10487                decomposition: None,
10488                unit: None,
10489                help: String::new(),
10490            },
10491            TypeExtends::Primitive,
10492        )
10493    }
10494
10495    fn measure_type_with_kilogram() -> TypeSpecification {
10496        use crate::computation::rational::rational_one;
10497        use crate::literals::{MeasureUnit, MeasureUnits};
10498        let mut units = MeasureUnits::new();
10499        units.push(MeasureUnit {
10500            name: "kilogram".to_string(),
10501            scale: UnitScale::Literal(rational_one()),
10502            minimum: None,
10503            maximum: None,
10504            suggestion_magnitude: None,
10505            decomposition: BaseMeasureVector::new(),
10506            derived_measure_factors: Vec::new(),
10507        });
10508        TypeSpecification::Measure {
10509            minimum: None,
10510            maximum: None,
10511            units,
10512            traits: Vec::new(),
10513            decomposition: None,
10514            unit: None,
10515            help: String::new(),
10516        }
10517    }
10518
10519    #[test]
10520    fn parser_value_to_value_kind_rejects_bare_number_for_measure() {
10521        let ten = Value::Number(Decimal::from(10));
10522        let measure = LemmaType::primitive(measure_type_with_kilogram());
10523        let err = parser_value_to_value_kind(&ten, &measure, None)
10524            .expect_err("bare number must not bind to measure");
10525        assert!(
10526            err.contains("kilogram"),
10527            "error must hint expected unit, got: {err}"
10528        );
10529    }
10530
10531    #[test]
10532    fn parser_value_to_value_kind_accepts_number_with_unit_for_measure() {
10533        let ten_kg = Value::NumberWithUnit(Decimal::from(10), "kilogram".to_string());
10534        let measure = LemmaType::primitive(measure_type_with_kilogram());
10535        let kind = parser_value_to_value_kind(&ten_kg, &measure, None)
10536            .expect("10 kilogram must bind to measure");
10537        assert!(matches!(kind, ValueKind::Measure(_)));
10538    }
10539
10540    #[test]
10541    fn parser_value_to_value_kind_rejects_bare_number_for_ratio() {
10542        let ten = Value::Number(Decimal::from(10));
10543        let ratio = LemmaType::primitive(TypeSpecification::ratio());
10544        let err = parser_value_to_value_kind(&ten, &ratio, None)
10545            .expect_err("bare number must not bind to ratio");
10546        assert!(
10547            err.contains("percent"),
10548            "error must hint expected unit, got: {err}"
10549        );
10550    }
10551
10552    #[test]
10553    fn value_kind_matches_spec_rejects_number_for_measure() {
10554        let n = ValueKind::Number(rational_new(10, 1));
10555        assert!(!value_kind_matches_spec(&n, &measure_type_with_kilogram()));
10556    }
10557
10558    #[test]
10559    fn value_kind_matches_spec_rejects_number_for_ratio() {
10560        let n = ValueKind::Number(rational_new(1, 2));
10561        assert!(!value_kind_matches_spec(&n, &TypeSpecification::ratio()));
10562    }
10563
10564    #[test]
10565    fn apply_constraint_rejects_inherited_unit_factor_change() {
10566        let mut specs = TypeSpecification::measure();
10567        specs
10568            .apply_constraint(
10569                ConstraintNames {
10570                    type_name: "money",
10571                    data_name: "money",
10572                },
10573                TypeConstraintCommand::Unit,
10574                &unit_factor_arg("eur", 1),
10575                &mut None,
10576                &mut None,
10577                None,
10578            )
10579            .expect("seed eur");
10580        let err = specs
10581            .apply_constraint(
10582                ConstraintNames {
10583                    type_name: "money",
10584                    data_name: "money",
10585                },
10586                TypeConstraintCommand::Unit,
10587                &[
10588                    CommandArg::Label("eur".to_string()),
10589                    CommandArg::UnitExpr(crate::parsing::ast::UnitArg::Factor(Decimal::new(11, 1))),
10590                ],
10591                &mut None,
10592                &mut None,
10593                None,
10594            )
10595            .expect_err("must not change inherited unit factor");
10596        assert!(err.contains("eur"), "error must name unit, got: {err}");
10597        assert!(
10598            err.contains("inherited") || err.contains("cannot change"),
10599            "error must reject factor change, got: {err}"
10600        );
10601    }
10602
10603    #[test]
10604    fn apply_constraint_allows_additive_unit_on_inherited_spec() {
10605        let mut specs = TypeSpecification::measure();
10606        specs
10607            .apply_constraint(
10608                ConstraintNames {
10609                    type_name: "money",
10610                    data_name: "money",
10611                },
10612                TypeConstraintCommand::Unit,
10613                &unit_factor_arg("eur", 1),
10614                &mut None,
10615                &mut None,
10616                None,
10617            )
10618            .expect("seed eur");
10619        specs
10620            .apply_constraint(
10621                ConstraintNames {
10622                    type_name: "money",
10623                    data_name: "money",
10624                },
10625                TypeConstraintCommand::Unit,
10626                &unit_factor_arg("usd", 1),
10627                &mut None,
10628                &mut None,
10629                None,
10630            )
10631            .expect("add usd");
10632        match &specs {
10633            TypeSpecification::Measure { units, .. } => assert_eq!(units.len(), 2),
10634            other => panic!("expected Measure, got {other:?}"),
10635        }
10636    }
10637
10638    #[test]
10639    fn apply_constraint_idempotent_inherited_unit_redeclare() {
10640        let mut specs = TypeSpecification::measure();
10641        specs
10642            .apply_constraint(
10643                ConstraintNames {
10644                    type_name: "money",
10645                    data_name: "money",
10646                },
10647                TypeConstraintCommand::Unit,
10648                &unit_factor_arg("eur", 1),
10649                &mut None,
10650                &mut None,
10651                None,
10652            )
10653            .expect("seed eur");
10654        specs
10655            .apply_constraint(
10656                ConstraintNames {
10657                    type_name: "money",
10658                    data_name: "money",
10659                },
10660                TypeConstraintCommand::Unit,
10661                &unit_factor_arg("eur", 1),
10662                &mut None,
10663                &mut None,
10664                None,
10665            )
10666            .expect("idempotent eur");
10667        match &specs {
10668            TypeSpecification::Measure { units, .. } => {
10669                assert_eq!(units.len(), 1);
10670                assert_eq!(
10671                    *units
10672                        .iter()
10673                        .find(|u| u.name == "eur")
10674                        .expect("eur")
10675                        .require_literal_factor(),
10676                    crate::computation::rational::rational_one()
10677                );
10678            }
10679            other => panic!("expected Measure, got {other:?}"),
10680        }
10681    }
10682
10683    #[test]
10684    fn element_from_range_returns_element_for_every_range_primitive() {
10685        type RangeElementMatcher = fn(&TypeSpecification) -> bool;
10686        let cases: [(PrimitiveKind, RangeElementMatcher); 5] = [
10687            (PrimitiveKind::NumberRange, |element| {
10688                matches!(element, TypeSpecification::Number { .. })
10689            }),
10690            (PrimitiveKind::MeasureRange, |element| {
10691                matches!(element, TypeSpecification::Measure { .. })
10692            }),
10693            (PrimitiveKind::RatioRange, |element| {
10694                matches!(element, TypeSpecification::Ratio { .. })
10695            }),
10696            (PrimitiveKind::DateRange, |element| {
10697                matches!(element, TypeSpecification::Date { .. })
10698            }),
10699            (PrimitiveKind::TimeRange, |element| {
10700                matches!(element, TypeSpecification::Time { .. })
10701            }),
10702        ];
10703        for (kind, matches_element) in cases {
10704            let range_spec = type_spec_for_primitive(kind);
10705            let element = range_spec
10706                .element_from_range()
10707                .unwrap_or_else(|| panic!("{kind:?} must define element_from_range"));
10708            assert!(
10709                matches_element(&element),
10710                "{kind:?} element must match documented mapping, got {element:?}"
10711            );
10712        }
10713    }
10714
10715    #[test]
10716    fn element_from_range_returns_none_for_non_range_primitives() {
10717        let non_range = [
10718            type_spec_for_primitive(PrimitiveKind::Boolean),
10719            type_spec_for_primitive(PrimitiveKind::Measure),
10720            TypeSpecification::Undetermined,
10721            TypeSpecification::veto(),
10722        ];
10723        for spec in non_range {
10724            assert!(
10725                spec.element_from_range().is_none(),
10726                "{spec:?} must not define element_from_range"
10727            );
10728        }
10729    }
10730
10731    fn spec_type(name: &str, effective: crate::parsing::ast::EffectiveDate) -> LemmaType {
10732        LemmaType::primitive(TypeSpecification::Spec {
10733            spec: SpecIdentity {
10734                repository: None,
10735                spec: name.to_string(),
10736                effective: effective.clone(),
10737                slice: effective,
10738            },
10739        })
10740    }
10741
10742    #[test]
10743    fn same_value_type_spec_identity() {
10744        use crate::parsing::ast::EffectiveDate;
10745        let origin = EffectiveDate::Origin;
10746        let dated = EffectiveDate::DateTimeValue(crate::DateTimeValue {
10747            year: 2026,
10748            month: 1,
10749            day: 1,
10750            hour: 0,
10751            minute: 0,
10752            second: 0,
10753            microsecond: 0,
10754            timezone: None,
10755            granularity: crate::literals::DateGranularity::Full,
10756        });
10757        let tax = spec_type("tax_bracket", origin.clone());
10758        let tax_again = spec_type("tax_bracket", origin.clone());
10759        let other = spec_type("menu_item", origin);
10760        let tax_dated = spec_type("tax_bracket", dated.clone());
10761        assert!(tax.same_value_type(&tax_again));
10762        assert!(!tax.same_value_type(&other));
10763        assert!(!tax.same_value_type(&tax_dated));
10764        let mut tax_later_slice = tax.clone();
10765        match &mut tax_later_slice.specifications {
10766            TypeSpecification::Spec { spec } => spec.slice = dated,
10767            other => panic!("expected Spec, got {other:?}"),
10768        }
10769        assert!(!tax.same_value_type(&tax_later_slice));
10770        let mut other_repo = tax.clone();
10771        match &mut other_repo.specifications {
10772            TypeSpecification::Spec { spec } => spec.repository = Some("@jack/finance".to_string()),
10773            other => panic!("expected Spec, got {other:?}"),
10774        }
10775        assert!(!tax.same_value_type(&other_repo));
10776    }
10777
10778    #[test]
10779    fn spec_identity_displays_repository_space_spec_space_effective() {
10780        use crate::parsing::ast::EffectiveDate;
10781        let workspace = SpecIdentity {
10782            repository: None,
10783            spec: "tax_bracket".to_string(),
10784            effective: EffectiveDate::Origin,
10785            slice: EffectiveDate::Origin,
10786        };
10787        assert_eq!(workspace.to_string(), "tax_bracket");
10788        let start =
10789            EffectiveDate::DateTimeValue(DateTimeValue::from_str("2026-01-01").expect("date"));
10790        let dated = SpecIdentity {
10791            repository: Some("@jack/finance".to_string()),
10792            spec: "tax_bracket".to_string(),
10793            effective: start.clone(),
10794            slice: start,
10795        };
10796        assert_eq!(
10797            dated.to_string(),
10798            format!(
10799                "@jack/finance tax_bracket {}",
10800                DateTimeValue::from_str("2026-01-01").expect("date")
10801            )
10802        );
10803        let later_slice = SpecIdentity {
10804            slice: EffectiveDate::DateTimeValue(
10805                DateTimeValue::from_str("2026-07-01").expect("date"),
10806            ),
10807            ..workspace
10808        };
10809        assert_eq!(
10810            later_slice.to_string(),
10811            format!(
10812                "tax_bracket slice {}",
10813                DateTimeValue::from_str("2026-07-01").expect("date")
10814            )
10815        );
10816    }
10817
10818    #[test]
10819    fn type_family_displays_declaring_spec_then_type() {
10820        let workspace = TypeFamily {
10821            repository: None,
10822            spec: "pricing".to_string(),
10823            effective: crate::parsing::ast::EffectiveDate::Origin,
10824            name: "money".to_string(),
10825        };
10826        assert_eq!(workspace.to_string(), "pricing.money");
10827        let stdlib = TypeFamily {
10828            repository: Some("lemma".to_string()),
10829            spec: "units".to_string(),
10830            effective: crate::parsing::ast::EffectiveDate::Origin,
10831            name: "mass".to_string(),
10832        };
10833        assert_eq!(stdlib.to_string(), "lemma units.mass");
10834        let dated = TypeFamily {
10835            repository: None,
10836            spec: "pricing".to_string(),
10837            effective: crate::parsing::ast::EffectiveDate::DateTimeValue(
10838                DateTimeValue::from_str("2024-01-01").expect("date"),
10839            ),
10840            name: "money".to_string(),
10841        };
10842        assert_eq!(dated.to_string(), "pricing 2024-01-01.money");
10843    }
10844
10845    #[test]
10846    fn piecewise_type_keeps_spec_identity() {
10847        use crate::parsing::ast::EffectiveDate;
10848        use crate::planning::typing::{piecewise_type, MeasureScope};
10849        use crate::planning::unit_index::UnitIndex;
10850        let tax = Arc::new(spec_type("tax_bracket", EffectiveDate::Origin));
10851        let unit_index = UnitIndex::new();
10852        let signature_index = crate::computation::arithmetic::SignatureIndex::new();
10853        let named_types = IndexMap::new();
10854        let scope = MeasureScope {
10855            unit_index: &unit_index,
10856            signature_index: &signature_index,
10857            named_types: &named_types,
10858        };
10859        let picked = piecewise_type([Arc::new(LemmaType::veto_type()), Arc::clone(&tax)], &scope);
10860        assert!(picked.same_value_type(&tax));
10861    }
10862
10863    #[test]
10864    #[should_panic(expected = "BUG: literal factor required")]
10865    fn measure_unit_factor_panics_on_reference_scale() {
10866        let units = crate::literals::MeasureUnits::from(vec![
10867            crate::literals::MeasureUnit::from_reference(
10868                "gbp".to_string(),
10869                "rate".to_string(),
10870                Vec::new(),
10871                "rate".to_string(),
10872            ),
10873        ]);
10874        let lemma_type = LemmaType::new(
10875            "money".to_string(),
10876            TypeSpecification::Measure {
10877                units,
10878                traits: vec![],
10879                decomposition: None,
10880                minimum: None,
10881                maximum: None,
10882                unit: None,
10883                help: String::new(),
10884            },
10885            TypeExtends::Primitive,
10886        );
10887        let _ = lemma_type.measure_unit_factor("gbp");
10888    }
10889}