Skip to main content

lemma/
result_value.rs

1//! API value for a rule result, `ShowData.value`, or `ShowData.suggestion`.
2//!
3//! This is the single API-facing value representation shared by all three sites, expanded
4//! into every declared unit for measure/ratio on data inputs, and into every unit in the
5//! result type's family for rule results. It sits at the crate root (not under
6//! `evaluation/`) because `planning::execution_plan::ShowData` needs it too, and planning
7//! must not import evaluation. The plan/eval-internal representation is the canonical
8//! `planning::semantics::LiteralValue`; this module is the boundary between the two.
9//!
10//! Magnitudes are [`Decimal`] (28-scale API boundary). JSON still emits decimal strings via
11//! `Decimal`'s default serde.
12
13use crate::computation::rational::{
14    checked_div, checked_mul, decimal_to_display_str, NumericFailure, RationalInteger,
15};
16use crate::literals::rational_from_parsed_decimal;
17use crate::planning::semantics::{
18    format_decimal_for_api, range_element_type_specification, ratio_element_type_for_api,
19    semantic_calendar_unit_from_measure_type, LemmaType, LiteralUnitMapFailure, LiteralValue,
20    SemanticDateTime, SemanticTime, SpecInstance, SpecValue, TypeSpecification, TypedLiteral,
21    UnitFactorSource, ValueKind,
22};
23use crate::planning::unit_family::{declared_bare_names_only, FamilyUnitCatalog, FamilyUnitEntry};
24use indexmap::IndexMap;
25use rust_decimal::Decimal;
26use serde::{Deserialize, Serialize};
27use std::borrow::Cow;
28use std::collections::{BTreeMap, HashMap};
29use std::fmt;
30use std::sync::Arc;
31
32/// Calendar value (a measure whose unit is a calendar unit, e.g. `3 months`) on a result.
33#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
34pub struct CalendarResult {
35    pub value: Decimal,
36    pub unit: String,
37}
38
39/// Both endpoints of a range result.
40///
41/// Each endpoint is itself a [`RuleResultValue`], but an endpoint's own `range` field is
42/// always `None` — a range endpoint must never itself be a range. Building a
43/// [`RuleResultValue`] and reconstructing a literal both panic if this invariant is
44/// violated.
45#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
46pub struct RangeResult {
47    pub from: RuleResultValue,
48    pub to: RuleResultValue,
49}
50
51/// API value shared by flattened [`crate::evaluation::response::RuleResult`],
52/// `ShowData.value` / `suggestion`, and explanation `Data` / `Rule` nodes.
53///
54/// When present: `result` (from [`LiteralValue::display_value`]), plus exactly
55/// one typed field for a non-range value; `range` is set instead for a range value, and
56/// every other typed field stays `None`. A list row carries `row` in rule results and
57/// in [`RowResult`] members; in explanation nodes it carries `result` only. The one
58/// value without `result` is an instance list in Show: the list carries `list` only and
59/// each source row `fields` only, in row order.
60#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
61pub struct RuleResultValue {
62    /// Engine-rendered string for UI (`LiteralValue::display_value`). Present whenever
63    /// this value is present, including range endpoints.
64    #[serde(default, skip_serializing_if = "Option::is_none")]
65    pub result: Option<String>,
66    #[serde(default, skip_serializing_if = "Option::is_none")]
67    pub measure: Option<BTreeMap<String, Decimal>>,
68    #[serde(default, skip_serializing_if = "Option::is_none")]
69    pub ratio: Option<BTreeMap<String, Decimal>>,
70    #[serde(default, skip_serializing_if = "Option::is_none")]
71    pub number: Option<Decimal>,
72    #[serde(default, skip_serializing_if = "Option::is_none")]
73    pub boolean: Option<bool>,
74    #[serde(default, skip_serializing_if = "Option::is_none")]
75    pub text: Option<String>,
76    #[serde(default, skip_serializing_if = "Option::is_none")]
77    pub date: Option<SemanticDateTime>,
78    #[serde(default, skip_serializing_if = "Option::is_none")]
79    pub time: Option<SemanticTime>,
80    #[serde(default, skip_serializing_if = "Option::is_none")]
81    pub calendar: Option<CalendarResult>,
82    /// Unit `result` is expressed in, for a measure or ratio value written in a unit
83    /// (including range endpoints). A written dynamic unit without a factor in the
84    /// presenting spec is reported as the unit used instead.
85    #[serde(default, skip_serializing_if = "Option::is_none")]
86    pub unit: Option<String>,
87    #[serde(default, skip_serializing_if = "Option::is_none")]
88    pub range: Option<Box<RangeResult>>,
89    /// Set when the value is a spec instance. `data` holds one evaluated entry per
90    /// data slot of that instance, keyed relative to that spec.
91    #[serde(default, skip_serializing_if = "Option::is_none")]
92    pub spec: Option<Box<SpecResult>>,
93    /// Set when the value is an instance-list row or a `uses` instance projected from one.
94    #[serde(default, skip_serializing_if = "Option::is_none")]
95    pub row: Option<RowReference>,
96    #[serde(default, skip_serializing_if = "Option::is_none")]
97    pub list: Option<Vec<RuleResultValue>>,
98    /// Set on a source row of an instance list in Show: the fields the row sets,
99    /// keyed relative to the row spec, in the order the row writes them.
100    #[serde(default, skip_serializing_if = "Option::is_none")]
101    pub fields: Option<IndexMap<String, RuleResultValue>>,
102    /// Show only: on a source-row field whose value is a reference; the input key
103    /// of the referenced data in the spec declaring the list.
104    #[serde(default, skip_serializing_if = "Option::is_none")]
105    pub reference: Option<String>,
106}
107
108/// A spec instance returned by a rule, including the values needed to run it again.
109#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
110pub struct SpecResult {
111    #[serde(default, skip_serializing_if = "Option::is_none")]
112    pub repository: Option<String>,
113    pub spec: String,
114    /// Resolved row's effective date. Empty when the row is the origin row.
115    pub effective: String,
116    /// `uses` path of this instance in the consumer (`basic`, `basic.finance`).
117    pub instance: String,
118    /// One segment per `uses` hop of `instance`.
119    pub path: Vec<crate::api::PathSegment>,
120    /// Evaluated data slots, keyed relative to `spec`, declaration order. A slot
121    /// with a value carries that value; a vetoed slot carries `vetoed` and
122    /// `veto_reason`. Unbound slots are omitted.
123    pub data: IndexMap<String, SpecRuleResult>,
124    /// Rule results relative to `spec` (`tax`, `finance.fee`), plan rule order.
125    pub rules: IndexMap<String, SpecRuleResult>,
126}
127
128/// An instance-list row or a `uses` instance projected from one.
129/// Its data and rules are `Response.rows[index]`.
130#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
131pub struct RowReference {
132    #[serde(default, skip_serializing_if = "Option::is_none")]
133    pub repository: Option<String>,
134    pub spec: String,
135    /// Resolved row's effective date. Empty when the row is the origin row.
136    pub effective: String,
137    /// Row path relative to the spec holding this value (`lines.2`, `lines.2.item`).
138    /// Present for a row with a data path (evaluation-data rows). An appended row
139    /// (`-> with`) has no path; its identity is its place in the list, and a value
140    /// bound inside it carries only its row-relative path (`item`).
141    #[serde(default, skip_serializing_if = "Option::is_none")]
142    pub instance: Option<String>,
143    pub index: usize,
144}
145
146/// Data and rules of one distinct row reached by a response, filled once.
147#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
148pub struct RowResult {
149    #[serde(default, skip_serializing_if = "Option::is_none")]
150    pub repository: Option<String>,
151    pub spec: String,
152    /// Resolved row's effective date. Empty when the row is the origin row.
153    pub effective: String,
154    /// Evaluated data slots, keyed relative to `spec`, declaration order.
155    /// Unbound slots are omitted.
156    pub data: IndexMap<String, SpecRuleResult>,
157    /// Rule results relative to `spec`, plan rule order.
158    pub rules: IndexMap<String, SpecRuleResult>,
159}
160
161/// One rule of a [`SpecResult`], or one evaluated data slot of a [`SpecResult`].
162/// A spec-valued rule nests another [`SpecResult`]
163/// in [`RuleResultValue::spec`].
164#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
165pub struct SpecRuleResult {
166    pub vetoed: bool,
167    #[serde(default, skip_serializing_if = "Option::is_none")]
168    pub veto_reason: Option<String>,
169    pub rule_type: String,
170    #[serde(default, skip_serializing_if = "Option::is_none")]
171    pub result: Option<RuleResultValue>,
172}
173
174/// Why building a [`RuleResultValue`] from a canonical [`LiteralValue`] failed.
175#[derive(Debug, Clone, Copy, PartialEq, Eq)]
176pub enum RuleResultValueFailure {
177    DecimalLimit,
178    NumericOverflow,
179    OutOfMemory,
180}
181
182/// Which units to expand when building a [`RuleResultValue`] from a measure or ratio literal.
183pub(crate) enum UnitExpansion<'a> {
184    /// Show data fill/suggestion: units declared on `lemma_type` only.
185    Declared,
186    /// Rule results: precomputed family entry from the plan catalog.
187    Family(&'a FamilyUnitEntry),
188}
189
190/// Human-readable veto message for a [`RuleResultValueFailure`].
191pub fn rule_result_value_failure_message(failure: RuleResultValueFailure) -> &'static str {
192    match failure {
193        RuleResultValueFailure::DecimalLimit => {
194            "The calculated result exceeds the decimal value limit."
195        }
196        RuleResultValueFailure::NumericOverflow => "The numeric result overflowed.",
197        RuleResultValueFailure::OutOfMemory => "The calculation ran out of memory.",
198    }
199}
200
201fn map_numeric_to_rule_result_value_failure(failure: NumericFailure) -> RuleResultValueFailure {
202    match failure {
203        NumericFailure::Overflow => RuleResultValueFailure::DecimalLimit,
204        NumericFailure::OutOfMemory => RuleResultValueFailure::OutOfMemory,
205        NumericFailure::DivisionByZero => {
206            panic!(
207                "BUG: decimal commit encountered division by zero while building RuleResultValue"
208            )
209        }
210        NumericFailure::Irrational => {
211            panic!(
212                "BUG: decimal commit encountered irrational result while building RuleResultValue"
213            )
214        }
215        NumericFailure::MagnitudeLimit => {
216            panic!("BUG: decimal commit does not apply the arithmetic magnitude limit")
217        }
218    }
219}
220
221fn map_unit_conversion_failure(failure: NumericFailure) -> RuleResultValueFailure {
222    match failure {
223        NumericFailure::Overflow => RuleResultValueFailure::NumericOverflow,
224        NumericFailure::OutOfMemory => RuleResultValueFailure::OutOfMemory,
225        NumericFailure::DivisionByZero => {
226            panic!("BUG: unit conversion division by zero while building RuleResultValue")
227        }
228        NumericFailure::Irrational => {
229            panic!("BUG: unit conversion irrational while building RuleResultValue")
230        }
231        NumericFailure::MagnitudeLimit => {
232            panic!("BUG: unit conversion does not apply the arithmetic magnitude limit")
233        }
234    }
235}
236
237fn map_literal_unit_map_failure(failure: LiteralUnitMapFailure) -> RuleResultValueFailure {
238    match failure {
239        LiteralUnitMapFailure::Commit(failure) => map_numeric_to_rule_result_value_failure(failure),
240        LiteralUnitMapFailure::UnitConversion(failure) => map_unit_conversion_failure(failure),
241    }
242}
243
244fn expansion_for_type<'a>(
245    rule_type: &LemmaType,
246    catalog: Option<&'a FamilyUnitCatalog>,
247) -> UnitExpansion<'a> {
248    let Some(catalog) = catalog else {
249        return UnitExpansion::Declared;
250    };
251    match catalog.entry_for_type(rule_type) {
252        Some(entry) => UnitExpansion::Family(entry),
253        None => UnitExpansion::Declared,
254    }
255}
256
257fn unit_names_for_expansion(
258    result_type: &LemmaType,
259    expansion: &UnitExpansion<'_>,
260    catalog: Option<&FamilyUnitCatalog>,
261) -> Arc<[String]> {
262    match expansion {
263        UnitExpansion::Declared => Arc::from(declared_bare_names_only(result_type)),
264        UnitExpansion::Family(_) => catalog
265            .expect("BUG: family expansion requires FamilyUnitCatalog")
266            .ordered_bare_names_for_type(result_type),
267    }
268}
269
270fn measure_factor_source<'a>(
271    result_type: &'a LemmaType,
272    expansion: &'a UnitExpansion<'a>,
273) -> UnitFactorSource<'a> {
274    match expansion {
275        UnitExpansion::Declared => UnitFactorSource::DeclaredOn(result_type),
276        UnitExpansion::Family(entry) => UnitFactorSource::Merged {
277            measure: entry.merged_measure_units.as_ref(),
278            ratio: entry.merged_ratio_units.as_ref(),
279        },
280    }
281}
282
283fn ratio_factor_source<'a>(
284    result_type: &'a LemmaType,
285    expansion: &'a UnitExpansion<'a>,
286) -> UnitFactorSource<'a> {
287    measure_factor_source(result_type, expansion)
288}
289
290/// Type of a node in a value tree walked with an explicit stack: the root type is borrowed,
291/// a list row's type is shared with the row's [`TypedLiteral`].
292enum NodeType<'a> {
293    Borrowed(&'a LemmaType),
294    Shared(Arc<LemmaType>),
295}
296
297impl NodeType<'_> {
298    fn get(&self) -> &LemmaType {
299        match self {
300            Self::Borrowed(lemma_type) => lemma_type,
301            Self::Shared(lemma_type) => lemma_type.as_ref(),
302        }
303    }
304}
305
306enum ResultValueTask<'a> {
307    Visit {
308        literal: Cow<'a, LiteralValue>,
309        lemma_type: NodeType<'a>,
310    },
311    AssembleList {
312        display: String,
313        rows: usize,
314    },
315}
316
317fn result_value_from_literal(
318    literal: &LiteralValue,
319    lemma_type: &LemmaType,
320    expansion: &UnitExpansion<'_>,
321    catalog: Option<&FamilyUnitCatalog>,
322    runtime_scales: Option<&HashMap<String, RationalInteger>>,
323) -> Result<RuleResultValue, RuleResultValueFailure> {
324    let mut tasks = vec![ResultValueTask::Visit {
325        literal: Cow::Borrowed(literal),
326        lemma_type: NodeType::Borrowed(lemma_type),
327    }];
328    let mut converted: Vec<RuleResultValue> = Vec::new();
329    while let Some(task) = tasks.pop() {
330        match task {
331            ResultValueTask::Visit {
332                literal,
333                lemma_type,
334            } => {
335                let lemma_type = lemma_type.get();
336                match &literal.value {
337                    ValueKind::Range(from, to) => {
338                        let from_value = result_value_from_range_endpoint(
339                            &from.to_literal(),
340                            from.lemma_type.as_ref(),
341                            expansion,
342                            catalog,
343                            runtime_scales,
344                        )?;
345                        let to_value = result_value_from_range_endpoint(
346                            &to.to_literal(),
347                            to.lemma_type.as_ref(),
348                            expansion,
349                            catalog,
350                            runtime_scales,
351                        )?;
352                        converted.push(RuleResultValue {
353                            result: Some(literal.display_value_with_type(lemma_type)),
354                            range: Some(Box::new(RangeResult {
355                                from: from_value,
356                                to: to_value,
357                            })),
358                            ..RuleResultValue::default()
359                        });
360                    }
361                    ValueKind::List(rows) => {
362                        tasks.push(ResultValueTask::AssembleList {
363                            display: literal.display_value_with_type(lemma_type),
364                            rows: rows.len(),
365                        });
366                        for row in rows.iter().rev() {
367                            tasks.push(ResultValueTask::Visit {
368                                literal: Cow::Owned(row.to_literal()),
369                                lemma_type: NodeType::Shared(Arc::clone(&row.lemma_type)),
370                            });
371                        }
372                    }
373                    _ => converted.push(result_value_from_non_range_literal(
374                        &literal,
375                        lemma_type,
376                        expansion,
377                        catalog,
378                        runtime_scales,
379                    )?),
380                }
381            }
382            ResultValueTask::AssembleList { display, rows } => {
383                let list = converted.split_off(converted.len() - rows);
384                converted.push(RuleResultValue {
385                    result: Some(display),
386                    list: Some(list),
387                    ..RuleResultValue::default()
388                });
389            }
390        }
391    }
392    Ok(converted
393        .pop()
394        .expect("BUG: literal conversion yields exactly one RuleResultValue"))
395}
396
397/// Build a [`RuleResultValue`] from a canonical [`LiteralValue`] for a rule result.
398///
399/// Measure and ratio expand into every unit in the result type's family.
400pub(crate) fn rule_result_value_from_literal(
401    literal: &LiteralValue,
402    rule_type: &LemmaType,
403    catalog: &FamilyUnitCatalog,
404    runtime_scales: Option<&HashMap<String, RationalInteger>>,
405) -> Result<RuleResultValue, RuleResultValueFailure> {
406    let expansion = expansion_for_type(rule_type, Some(catalog));
407    result_value_from_literal(
408        literal,
409        rule_type,
410        &expansion,
411        Some(catalog),
412        runtime_scales,
413    )
414}
415
416/// Build a [`RuleResultValue`] using only units declared on `lemma_type` (Show data fill/suggestion).
417pub fn type_scoped_result_value_from_literal(
418    literal: &LiteralValue,
419    lemma_type: &LemmaType,
420) -> Result<RuleResultValue, RuleResultValueFailure> {
421    let expansion = UnitExpansion::Declared;
422    result_value_from_literal(literal, lemma_type, &expansion, None, None)
423}
424
425fn result_value_from_range_endpoint(
426    endpoint: &LiteralValue,
427    endpoint_type: &LemmaType,
428    expansion: &UnitExpansion<'_>,
429    catalog: Option<&FamilyUnitCatalog>,
430    runtime_scales: Option<&HashMap<String, RationalInteger>>,
431) -> Result<RuleResultValue, RuleResultValueFailure> {
432    if matches!(&endpoint.value, ValueKind::Range(_, _)) {
433        panic!("BUG: range endpoint must not itself be a range");
434    }
435    result_value_from_non_range_literal(endpoint, endpoint_type, expansion, catalog, runtime_scales)
436}
437
438fn result_value_from_non_range_literal(
439    literal: &LiteralValue,
440    result_type: &LemmaType,
441    expansion: &UnitExpansion<'_>,
442    catalog: Option<&FamilyUnitCatalog>,
443    runtime_scales: Option<&HashMap<String, RationalInteger>>,
444) -> Result<RuleResultValue, RuleResultValueFailure> {
445    match &literal.value {
446        ValueKind::Measure(rational) if result_type.is_calendar_like() => {
447            let unit = semantic_calendar_unit_from_measure_type(result_type);
448            let value = result_type
449                .try_rational_as_decimal(rational)
450                .map_err(map_numeric_to_rule_result_value_failure)?;
451            let result = Some(literal.display_value_with_type(result_type));
452            Ok(RuleResultValue {
453                result,
454                calendar: Some(CalendarResult {
455                    value,
456                    unit: unit.to_string(),
457                }),
458                ..RuleResultValue::default()
459            })
460        }
461        ValueKind::UnscaledMeasure { magnitude, unit } => {
462            let decimal = magnitude
463                .try_to_decimal()
464                .map_err(map_numeric_to_rule_result_value_failure)?;
465            let api_decimal = format_decimal_for_api(decimal);
466            let display = format!("{} {unit}", decimal_to_display_str(&decimal));
467            let mut measure = BTreeMap::new();
468            measure.insert(unit.to_string(), api_decimal);
469            Ok(RuleResultValue {
470                result: Some(display),
471                measure: Some(measure),
472                unit: Some(unit.to_string()),
473                ..RuleResultValue::default()
474            })
475        }
476        ValueKind::Measure(_) => {
477            let unit_names = unit_names_for_expansion(result_type, expansion, catalog);
478            let unit_name_refs: Vec<&str> = unit_names.iter().map(String::as_str).collect();
479            let fallback = measure_factor_source(result_type, expansion);
480            let source = match runtime_scales {
481                Some(scales) => UnitFactorSource::Runtime {
482                    scales,
483                    fallback: &fallback,
484                },
485                None => fallback,
486            };
487            let measure = result_type
488                .measure_literal_unit_map(literal, &unit_name_refs, source)
489                .map_err(map_literal_unit_map_failure)?;
490            let result = Some(literal.display_value_with_scales(result_type, runtime_scales));
491            // Wire `unit` is the unit the result string actually used, not a binding
492            // whose factor was dropped from runtime_scales.
493            let unit = result_type.unit().and_then(|_| {
494                result_type
495                    .measure_display_unit_name(runtime_scales)
496                    .map(str::to_string)
497            });
498            Ok(RuleResultValue {
499                result,
500                measure: Some(measure),
501                unit,
502                ..RuleResultValue::default()
503            })
504        }
505        ValueKind::Ratio(_) => {
506            // The value's unit may be any ratio unit in scope (`basis_point` after
507            // `50 basis_point / 2`), not one declared on the primitive result type.
508            // A unit name types in scope give different factors has no single
509            // meaning there (it reads under qualified names); the value then
510            // displays in percent.
511            let display_type = match catalog {
512                Some(catalog) => {
513                    let scoped = catalog.rule_type_for_show(result_type);
514                    match scoped.unit() {
515                        Some(unit)
516                            if !crate::planning::semantics::unit_name_declared_on_type(
517                                &scoped, unit,
518                            ) =>
519                        {
520                            scoped.with_unit("percent")
521                        }
522                        _ => scoped,
523                    }
524                }
525                None => result_type.clone(),
526            };
527            let result = Some(literal.display_value_with_type(&display_type));
528            let unit_names = unit_names_for_expansion(result_type, expansion, catalog);
529            let unit_name_refs: Vec<&str> = unit_names.iter().map(String::as_str).collect();
530            Ok(RuleResultValue {
531                result,
532                ratio: Some(
533                    result_type
534                        .ratio_literal_unit_map(
535                            literal,
536                            &unit_name_refs,
537                            ratio_factor_source(result_type, expansion),
538                        )
539                        .map_err(map_literal_unit_map_failure)?,
540                ),
541                unit: display_type.unit().map(str::to_string),
542                ..RuleResultValue::default()
543            })
544        }
545        other => scalar_result_value(result_type, other),
546    }
547}
548
549fn scalar_result_value(
550    result_type: &LemmaType,
551    value: &ValueKind,
552) -> Result<RuleResultValue, RuleResultValueFailure> {
553    match value {
554        ValueKind::Number(rational) => {
555            let decimal = rational
556                .try_to_decimal()
557                .map_err(map_numeric_to_rule_result_value_failure)?;
558            let api_decimal = format_decimal_for_api(decimal);
559            let display_string = decimal_to_display_str(&decimal);
560            Ok(RuleResultValue {
561                result: Some(display_string),
562                number: Some(api_decimal),
563                ..RuleResultValue::default()
564            })
565        }
566        ValueKind::Boolean(b) => {
567            let result = Some(value.to_string());
568            Ok(RuleResultValue {
569                result,
570                boolean: Some(*b),
571                ..RuleResultValue::default()
572            })
573        }
574        ValueKind::Text(_) | ValueKind::Date(_) | ValueKind::Time(_) => {
575            let result = Some(value.to_string());
576            Ok(scalar_result_value_non_numeric(result, value))
577        }
578        ValueKind::Measure(_) | ValueKind::Ratio(_) | ValueKind::UnscaledMeasure { .. } => {
579            unreachable!("BUG: measure, ratio and unscaled measure must be handled by caller")
580        }
581        ValueKind::Range(_, _) => {
582            unreachable!("BUG: range must be handled by result_value_from_literal")
583        }
584        ValueKind::List(_) => {
585            unreachable!("BUG: list must be handled by result_value_from_literal")
586        }
587        ValueKind::Spec(SpecValue::Row(key)) => match key.segments() {
588            Some(path) => Ok(RuleResultValue {
589                result: Some(key.to_string()),
590                spec: Some(Box::new(SpecResult {
591                    repository: key.row.identity.repository.clone(),
592                    spec: key.row.identity.spec.clone(),
593                    effective: key.row.identity.effective.to_string(),
594                    instance: key.to_string(),
595                    path: path.iter().map(crate::api::PathSegment::from).collect(),
596                    data: IndexMap::new(),
597                    rules: IndexMap::new(),
598                })),
599                ..RuleResultValue::default()
600            }),
601            None => Ok(RuleResultValue {
602                result: Some(value.to_string()),
603                ..RuleResultValue::default()
604            }),
605        },
606        ValueKind::Spec(SpecValue::Fixed(instance)) => {
607            let identity = result_type
608                .spec_identity()
609                .expect("BUG: spec value whose type is not a spec");
610            Ok(RuleResultValue {
611                result: Some(instance.to_string()),
612                spec: Some(Box::new(SpecResult {
613                    repository: identity.repository.clone(),
614                    spec: identity.spec.clone(),
615                    effective: identity.effective.to_string(),
616                    instance: instance.to_string(),
617                    path: instance
618                        .prefix
619                        .iter()
620                        .map(crate::api::PathSegment::from)
621                        .collect(),
622                    data: IndexMap::new(),
623                    rules: IndexMap::new(),
624                })),
625                ..RuleResultValue::default()
626            })
627        }
628    }
629}
630
631fn scalar_result_value_non_numeric(result: Option<String>, value: &ValueKind) -> RuleResultValue {
632    match value {
633        ValueKind::Text(s) => RuleResultValue {
634            result,
635            text: Some(s.to_string()),
636            ..RuleResultValue::default()
637        },
638        ValueKind::Date(d) => RuleResultValue {
639            result,
640            date: Some(d.clone()),
641            ..RuleResultValue::default()
642        },
643        ValueKind::Time(t) => RuleResultValue {
644            result,
645            time: Some(t.clone()),
646            ..RuleResultValue::default()
647        },
648        _ => unreachable!("BUG: scalar_result_value_non_numeric called with non-scalar type"),
649    }
650}
651
652fn literal_from_measure_map(
653    measure: &BTreeMap<String, Decimal>,
654    rule_type: &LemmaType,
655) -> LiteralValue {
656    let unit = rule_type
657        .unit()
658        .and_then(|name| rule_type.measure_units_table()?.get(name).ok())
659        .or_else(|| rule_type.measure_fallback_unit())
660        .expect(
661            "BUG: reconstructing a measure from a unit map requires a declared unit on the type",
662        );
663    let magnitude = measure
664        .get(&unit.name)
665        .unwrap_or_else(|| panic!("BUG: measure map missing unit '{}'", unit.name));
666    let rational = rational_from_parsed_decimal(*magnitude)
667        .expect("BUG: measure rule result value must lift to rational");
668    match unit.literal_factor() {
669        Some(factor) => {
670            let canonical = checked_mul(&rational, factor).unwrap_or_else(|failure| {
671                panic!(
672                    "BUG: measure canonicalization from RuleResultValue fields failed: {failure}"
673                )
674            });
675            LiteralValue::measure(canonical)
676        }
677        None => LiteralValue::new(ValueKind::UnscaledMeasure {
678            magnitude: rational,
679            unit: Arc::from(unit.name.as_str()),
680        }),
681    }
682}
683
684fn literal_from_ratio_map(
685    ratio: &BTreeMap<String, Decimal>,
686    rule_type: &LemmaType,
687) -> LiteralValue {
688    let ratio_type = ratio_element_type_for_api(rule_type);
689    let units = match &ratio_type.specifications {
690        TypeSpecification::Ratio { units, .. } => units,
691        _ => panic!(
692            "BUG: ratio rule result type must be Ratio, got {}",
693            rule_type.name()
694        ),
695    };
696    let unit = rule_type
697        .unit()
698        .and_then(|name| units.get(name).ok())
699        .or_else(|| units.iter().next())
700        .expect("BUG: ratio rule result type must declare at least one unit");
701    let magnitude = ratio
702        .get(&unit.name)
703        .unwrap_or_else(|| panic!("BUG: ratio map missing unit '{}'", unit.name));
704    let display_rational = rational_from_parsed_decimal(*magnitude)
705        .expect("BUG: ratio rule result value must lift to rational");
706    let canonical = checked_div(&display_rational, &unit.value).unwrap_or_else(|failure| {
707        panic!("BUG: ratio canonicalization from RuleResultValue fields failed: {failure}")
708    });
709    LiteralValue::ratio(canonical)
710}
711
712impl RuleResultValue {
713    /// Reconstruct the [`LiteralValue`] from this API value's fields.
714    ///
715    /// Panics if the fields cannot reconstruct a literal, or if a range endpoint is
716    /// itself a range (ranges do not nest; enforced here, not by convention).
717    /// A list row is not rebuilt: its value is its bindings, which the API value does not
718    /// carry. Read a row through its fields instead.
719    pub fn to_literal(&self, rule_type: &LemmaType) -> LiteralValue {
720        if let Some(row) = &self.row {
721            panic!(
722                "BUG: list row '{}' cannot be rebuilt from its API value",
723                row.instance.as_deref().unwrap_or("<appended>")
724            );
725        }
726        if let Some(spec) = &self.spec {
727            assert!(
728                !spec.path.is_empty(),
729                "BUG: spec result '{}' has no uses hop",
730                spec.instance
731            );
732            return LiteralValue::new(ValueKind::Spec(SpecValue::Fixed(SpecInstance {
733                prefix: spec
734                    .path
735                    .iter()
736                    .map(|segment| crate::planning::semantics::PathSegment {
737                        uses: Arc::from(segment.uses.as_str()),
738                        row: segment.row,
739                        repository: segment.repository.as_deref().map(Arc::from),
740                        spec: Arc::from(segment.spec.as_str()),
741                    })
742                    .collect(),
743            })));
744        }
745        if let Some(rows) = &self.list {
746            let TypeSpecification::List { element, .. } = &rule_type.specifications else {
747                panic!(
748                    "BUG: list result whose rule type is not a list ({})",
749                    rule_type.name()
750                );
751            };
752            return LiteralValue::new(ValueKind::List(
753                rows.iter()
754                    .map(|row| {
755                        let row_type =
756                            endpoint_type_with_written_unit(element, row.unit.as_deref());
757                        TypedLiteral {
758                            value: row.to_literal(&row_type).value,
759                            lemma_type: Arc::new(row_type),
760                        }
761                    })
762                    .collect(),
763            ));
764        }
765        if let Some(range) = &self.range {
766            if range.from.range.is_some() || range.to.range.is_some() {
767                panic!("BUG: range endpoint must not itself be a range");
768            }
769            let endpoint_schema =
770                element_type_from_range_rule(rule_type).unwrap_or_else(|| rule_type.clone());
771            let left_type =
772                endpoint_type_with_written_unit(&endpoint_schema, range.from.unit.as_deref());
773            let right_type =
774                endpoint_type_with_written_unit(&endpoint_schema, range.to.unit.as_deref());
775            let left = range.from.to_literal(&left_type);
776            let right = range.to.to_literal(&right_type);
777            return LiteralValue::range(
778                TypedLiteral {
779                    value: left.value,
780                    lemma_type: Arc::new(left_type),
781                },
782                TypedLiteral {
783                    value: right.value,
784                    lemma_type: Arc::new(right_type),
785                },
786            );
787        }
788
789        if let Some(b) = self.boolean {
790            return LiteralValue::from_bool(b);
791        }
792        let owned_rule_type = match self.unit.as_deref() {
793            Some(unit)
794                if matches!(
795                    &rule_type.specifications,
796                    TypeSpecification::Measure { .. } | TypeSpecification::Ratio { .. }
797                ) && rule_type.unit() != Some(unit) =>
798            {
799                Arc::new(rule_type.clone().with_unit(unit))
800            }
801            _ => Arc::new(rule_type.clone()),
802        };
803        if let Some(number) = self.number {
804            return LiteralValue::number_from_decimal(number);
805        }
806        if let Some(calendar) = &self.calendar {
807            let rational = rational_from_parsed_decimal(calendar.value)
808                .expect("BUG: calendar rule result value must lift to rational");
809            return LiteralValue::measure(rational);
810        }
811        if let Some(measure) = &self.measure {
812            return literal_from_measure_map(measure, owned_rule_type.as_ref());
813        }
814        if let Some(ratio) = &self.ratio {
815            return literal_from_ratio_map(ratio, owned_rule_type.as_ref());
816        }
817        if let Some(date) = &self.date {
818            return LiteralValue::date(date.clone());
819        }
820        if let Some(time) = &self.time {
821            return LiteralValue::time(time.clone());
822        }
823        if let Some(text) = &self.text {
824            return LiteralValue::text(text.clone());
825        }
826        panic!("BUG: rule result value fields cannot reconstruct literal");
827    }
828}
829
830fn endpoint_type_with_written_unit(endpoint_schema: &LemmaType, unit: Option<&str>) -> LemmaType {
831    match unit {
832        Some(unit)
833            if matches!(
834                &endpoint_schema.specifications,
835                TypeSpecification::Measure { .. } | TypeSpecification::Ratio { .. }
836            ) && endpoint_schema.unit() != Some(unit) =>
837        {
838            endpoint_schema.clone().with_unit(unit)
839        }
840        _ => endpoint_schema.clone(),
841    }
842}
843
844fn element_type_from_range_rule(rule_type: &LemmaType) -> Option<LemmaType> {
845    range_element_type_specification(&rule_type.specifications).map(LemmaType::primitive)
846}
847
848fn format_unit_map(map: &BTreeMap<String, Decimal>) -> String {
849    map.iter()
850        .map(|(unit, value)| format!("{value} {unit}"))
851        .collect::<Vec<_>>()
852        .join(", ")
853}
854
855impl fmt::Display for RuleResultValue {
856    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
857        if let Some(range) = &self.range {
858            return write!(f, "{}...{}", range.from, range.to);
859        }
860        if let Some(measure) = &self.measure {
861            return write!(f, "{}", format_unit_map(measure));
862        }
863        if let Some(ratio) = &self.ratio {
864            return write!(f, "{}", format_unit_map(ratio));
865        }
866        if let Some(number) = &self.number {
867            return write!(f, "{number}");
868        }
869        if let Some(b) = self.boolean {
870            return write!(f, "{b}");
871        }
872        if let Some(text) = &self.text {
873            return write!(f, "{text}");
874        }
875        if let Some(date) = &self.date {
876            return write!(f, "{date}");
877        }
878        if let Some(time) = &self.time {
879            return write!(f, "{time}");
880        }
881        if let Some(calendar) = &self.calendar {
882            return write!(f, "{} {}", calendar.value, calendar.unit);
883        }
884        if let Some(display) = &self.result {
885            return write!(f, "{display}");
886        }
887        if let Some(reference) = &self.reference {
888            return write!(f, "{reference}");
889        }
890        write!(f, "")
891    }
892}