Skip to main content

lemma/planning/
execution_plan.rs

1//! Execution plan for evaluated specs
2//!
3//! Provides a complete self-contained execution plan ready for the evaluator.
4//! The plan holds an expanded shared normal-form graph in a dense table
5//! ([`ExecutionPlan::normal_forms`]) addressed by [`NormalFormId`], plus all data —
6//! no spec structure needed during evaluation.
7//!
8//! Imports are flattened at planning: every data and rule of an imported spec is an
9//! entry of the consumer plan under its `uses` hop, and a row written in a data list is
10//! an instance under the list path (`staff.1`). Evaluation has one context.
11//!
12//! Reliability model:
13//! - [`Show`] is the IO contract surface for consumers (data and rule outputs).
14//!   IO compatibility is the consumer-facing guarantee.
15
16use crate::computation::arithmetic::SignatureIndex;
17use crate::computation::rational::RationalInteger;
18use crate::computation::units::{conversion_target_declares_unit, owning_type_declares_unit_name};
19use crate::computation::{OperationResult, VetoType};
20use crate::engine::write_effective_window;
21use crate::limits::ResourceLimits;
22use crate::literals::Value;
23use crate::parsing::ast::{
24    canonical_logical_name, ConversionTypeKind, DateTimeValue, EffectiveDate, LemmaSpec,
25};
26use crate::parsing::source::{Source, SourceType};
27use crate::planning::graph::Graph;
28use crate::planning::graph::ResolvedSpecTypes;
29use crate::planning::instance_list::InstanceListSource;
30use crate::planning::normalize::{
31    build_normalized_rule, data_path_result_type, DispatchRegion, NormalForm, NormalFormId,
32    NormalFormInterner, NormalizeContext, NormalizedRule,
33};
34use crate::planning::semantics::{
35    lemma_type_with_display_binding, option_detail_line, primitive_number_arc, primitive_ratio_arc,
36    value_kind_matches_spec, ArithmeticComputation, BoundValueKind, ComparisonComputation,
37    DataDefinition, DataPath, GlobalKey, InstanceKey, LemmaType, LiteralValue, PathSegment,
38    ReferenceEnd, ReferenceTarget, RowBinding, RowEnd, RowInstance, RulePath, ScaleTarget,
39    SemanticConversionTarget, SpecIdentity, TypeSpecification, TypedLiteral, ValueKind,
40};
41use crate::planning::show_expression::{project_depends_on_rules, show_branches_from, ShowScope};
42use crate::planning::spec_set::LemmaSpecSet;
43use crate::planning::spec_value::{RowFieldRead, SpecCandidates};
44use crate::planning::typing::MeasureScope;
45use crate::planning::unit_family::FamilyUnitCatalog;
46use crate::planning::unit_index::{RowsUnit, UnitIndex};
47use crate::result_value::{
48    rule_result_value_failure_message, type_scoped_result_value_from_literal, RuleResultValue,
49};
50use crate::Error;
51use indexmap::IndexMap;
52use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
53use std::sync::Arc;
54
55pub use crate::planning::show_expression::{
56    ShowBranch, ShowConversionTarget, ShowExpression, ShowListCommand, ShowRule, SortDirection,
57};
58
59/// Rule positions that need one [`ExecutionPlan::data`] slot.
60///
61/// For an instance list, [`Self::fields`] is parallel to the row template's row fields
62/// ([`ExecutionPlan::row_field_count`]): which rules need each row field of
63/// evaluation-data rows through this list.
64/// Otherwise `fields` is empty.
65#[derive(Debug, Clone, Default)]
66pub(crate) struct NeededByRules {
67    pub rules: Vec<u32>,
68    pub fields: Vec<Vec<u32>>,
69}
70
71/// A complete execution plan ready for the evaluator
72///
73/// Contains drift-free normal-form equations in a table, named rule roots, and all data.
74/// Self-contained structure - no spec lookups required during evaluation.
75///
76/// A plan is immutable once stored. A committed plan is reused only when its own spec's
77/// bytes are still the spec set's `Arc` (kept while the version's bytes are unchanged),
78/// its version's boundaries (show-cache fields such as `effective_to`) and the
79/// slices its edges resolve to are unchanged, and every one of those slices is reused.
80#[derive(Debug, Clone)]
81pub struct ExecutionPlan {
82    /// Main spec name
83    pub spec_name: String,
84
85    /// Optional commentary from the `"""..."""` block in the spec source.
86    pub commentary: Option<String>,
87
88    /// This spec's own data slots in definition order, every path local. A `uses`
89    /// import is one [`DataDefinition::Import`] slot holding its row over the
90    /// template plan; spec-written list rows live in their [`RowStore`].
91    pub data: IndexMap<DataPath, DataDefinition>,
92
93    /// Dense table of interned NormalForm cells — the expanded shared graph.
94    /// Index = [`NormalFormId`].
95    pub normal_forms: Vec<NormalForm>,
96
97    /// This spec's own rules → root of that rule in [`Self::normal_forms`].
98    /// Insertion order is planning topo order (deps before consumers).
99    pub rules: IndexMap<RulePath, ExecutableRule>,
100
101    /// Data→data [`DataDefinition::Reference`] paths in dependency order for
102    /// evaluation prepop (chained reference → reference → data). Empty when the
103    /// plan has none. Rule-target references are not included.
104    pub data_reference_order: Vec<DataPath>,
105
106    /// Spec metadata, in declaration order.
107    pub meta: IndexMap<String, Value>,
108
109    /// Main-spec types from planning. [`ResolvedSpecTypes::unit_index`] is expression-scope
110    /// units (local types plus direct `uses` imports). Rule-result unit maps use
111    /// [`Self::family_units`]; Show data inputs stay declared-only.
112    pub resolved_types: Arc<ResolvedSpecTypes>,
113
114    /// Precomputed measure/ratio family unit expansion for rule results and show rule schemas.
115    pub(crate) family_units: Arc<FamilyUnitCatalog>,
116
117    /// Reverse index: canonical-form unit signature `Vec<(unit_name, exponent)>` →
118    /// (unit_name, owning type). Built from expression-scope units during planning so
119    /// cross-type Multiply/Divide arithmetic can deterministically resolve a combined
120    /// signature back to a single named unit. Ambiguous signatures (the same key matched
121    /// by units in two distinct types) are rejected at planning time.
122    pub signature_index: SignatureIndex,
123
124    pub effective: EffectiveDate,
125
126    /// Declared temporal window `[effective_from, effective_to)` of the LemmaSpec
127    /// version this plan was built from. Filled by [`attach_show_cache`].
128    pub effective_from: Option<DateTimeValue>,
129    pub effective_to: Option<DateTimeValue>,
130
131    /// Source start line of the LemmaSpec version this plan was built from.
132    pub start_line: usize,
133
134    /// Source type of the LemmaSpec version this plan was built from.
135    pub source_type: Option<SourceType>,
136
137    /// Per [`Self::data`] position: [`Self::rules`] positions that need that slot
138    /// (through rule references). Non-promptable slots have empty `rules`.
139    /// Instance-list slots also carry `fields` parallel to the row template's `data`.
140    /// `len() == data.len()`. Built in [`build_execution_plan`].
141    pub(crate) needed_by_rules: Vec<NeededByRules>,
142
143    /// Prefill/suggestion [`BoundValueKind`]s for show, keyed by data path.
144    /// Built once at plan time; [`RuleResultValue`] is expanded at show.
145    pub(crate) data_display: IndexMap<DataPath, ShowDataCache>,
146
147    /// Public Show rule catalog: this spec's own rules only (empty path). Built in
148    /// [`build_execution_plan`]. Reachable import rules stay on Graph `show_edges` /
149    /// `show_imports` for planning and nested-data attribution.
150    pub(crate) show_rules: IndexMap<RulePath, ShowRule>,
151
152    /// Positions in [`Self::show_rules`] of the Show rules that need each data path, in
153    /// input-key order: every reader of data of `uses` imports by composed path (`i.x`),
154    /// and the readers of data of this plan that [`Self::needed_by_rules`] does not list
155    /// (local rules that need it only through an import).
156    pub(crate) show_needed_by: IndexMap<DataPath, Vec<u32>>,
157
158    /// Template identity of every import data path in [`Self::show_needed_by`].
159    pub(crate) show_import_data: IndexMap<DataPath, SpecIdentity>,
160
161    /// Every [`DataDefinition::Reference`] path → where its chain ends.
162    /// Copied from [`Graph::reference_ends`] in [`build_execution_plan`].
163    /// Missing key after planning is a bug.
164    pub(crate) reference_ends: IndexMap<DataPath, ReferenceEnd>,
165
166    /// Precomputed `input_key` → `DataPath` index for [`EvaluateData::resolve`].
167    /// One entry per [`Self::data`] slot. Keyed lookups index this map; they do not
168    /// walk the data tree.
169    pub input_key_index: IndexMap<String, DataPath>,
170
171    /// Precomputed `input_key` → `RulePath` for [`Self::show_rules`].
172    /// Built once so [`Self::get_rule`] is O(1) without allocating per candidate.
173    pub(crate) show_rule_index: IndexMap<String, RulePath>,
174
175    /// Every [`Self::data`] path → its [`LeafKind::DataPath`] cell in
176    /// [`Self::normal_forms`]. Built once so evaluation writes bindings into
177    /// the value table by [`NormalFormId`] instead of a parallel path map.
178    pub(crate) data_leaf: IndexMap<DataPath, NormalFormId>,
179
180    /// Every reference target through `uses` hops (`i.x`, `i.j.r`) that a binding
181    /// resolving in this plan's context names → its member cell: the read of the
182    /// target on the import row this plan holds.
183    pub(crate) member_targets: IndexMap<ReferenceTarget, NormalFormId>,
184
185    /// Template plans of instance-list row specs, by row spec. Rows supplied by
186    /// evaluation data (and option rows) are checked and evaluated against them.
187    pub(crate) row_templates: BTreeMap<SpecIdentity, Arc<ExecutionPlan>>,
188
189    /// Every global this plan reaches ([`DataDefinition::Import::global`]) → its one spec
190    /// body. A plan holding this one as a template adds these to its own globals.
191    pub(crate) globals: IndexMap<GlobalKey, SpecIdentity>,
192    /// The writes this plan makes through paths ([`crate::planning::fill`]).
193    pub(crate) writes: crate::planning::fill::Writes,
194    /// The writes through paths of this plan and of every plan of a spec it holds, by
195    /// spec: what evaluation looks a field up in ([`crate::evaluation::lookup::field`]).
196    pub(crate) writes_by_spec: Arc<crate::planning::fill::WritesIndex>,
197    /// This plan's spec, shared with each request that looks a field up in
198    /// [`Self::writes_by_spec`].
199    pub(crate) writes_root: Arc<SpecIdentity>,
200
201    /// This plan's own spec. Rows of its self-lists read this plan as their template.
202    pub(crate) identity: SpecIdentity,
203
204    /// The `Arc` of this plan's own spec version, shared with its [`LemmaSpecSet`].
205    pub(crate) own_spec: Arc<LemmaSpec>,
206
207    /// Slices this plan's dependency edges resolved to, in edge order, self-edges left
208    /// out.
209    pub(crate) edges: Vec<SpecIdentity>,
210
211    /// Instances each rule can yield (empty when not spec-valued). Copied from
212    /// [`Graph::rule_candidates`].
213    pub(crate) rule_candidates: BTreeMap<RulePath, SpecCandidates>,
214
215    /// Rules read on evaluation-data rows of this plan's self-lists, in [`Self::rules`]
216    /// order. A row tree fills them bottom-up, so a parent reads its children's values
217    /// without evaluating down the tree.
218    pub(crate) self_row_rules: Vec<RulePath>,
219
220    /// Source rows of every [`DataDefinition::InstanceList`] path.
221    pub(crate) instance_lists: IndexMap<DataPath, InstanceListSource>,
222
223    /// Per [`Self::normal_forms`] cell: bit `L` is set when the cell reads the current
224    /// list row at level `L` that encloses it (`RowField` or `RowValue`). Such cells
225    /// differ per row and are never cached in the value table.
226    pub(crate) row_mask: Vec<u32>,
227
228    /// Precomputed initial value table (length = `normal_forms.len()`): plan defaults
229    /// and pre-evaluated data-target reference chains in their data-leaf slots, `None` elsewhere.
230    pub(crate) initial_values: Vec<Option<OperationResult>>,
231
232    /// Data-leaf cell ids that must run a walk step before `ready` returns their
233    /// stored value: an options check, or a stored `UnscaledMeasure` to settle.
234    pub(crate) walk_settled_leaves: Vec<NormalFormId>,
235
236    /// The plan's call graph ([`crate::planning::graph::Graph::call_graph_export`]): the
237    /// starts evaluation may make between pieces, which the `call-graph-check` feature
238    /// checks every start against.
239    #[cfg(feature = "call-graph-check")]
240    pub(crate) call_graph: CallGraph,
241
242    /// Per [`Self::normal_forms`] cell: the [`RuleIndex`] of the rule a `rule_ref`
243    /// cell reads, `None` for every other cell.
244    pub(crate) rule_ref_indexes: Vec<Option<RuleIndex>>,
245
246    /// Per [`Self::data`] slot: its [`Self::data_leaf`] cell. Row bindings travel by
247    /// slot and land in the value table through this.
248    pub(crate) data_slot_leaves: Vec<NormalFormId>,
249
250    /// Per [`Self::data`] slot: the scale targets of the dynamic units on that slot's
251    /// type (this plan's coordinates). A read of the slot needs exactly these, and
252    /// planning orders and cycle-checks the same edges.
253    pub(crate) slot_scale_targets: Vec<Vec<ScaleTarget>>,
254}
255
256/// Plan-time prefill/suggestion for one data path (show cache).
257///
258/// Stores domain [`BoundValueKind`]. [`RuleResultValue`] is built at
259/// show time (JSON / API boundary).
260#[derive(Debug, Clone)]
261pub(crate) struct ShowDataCache {
262    pub value: Option<BoundValueKind>,
263    pub suggestion: Option<BoundValueKind>,
264}
265
266/// A named rule's root in the normal-form table, plus declaration metadata.
267#[derive(Debug, Clone)]
268pub struct ExecutableRule {
269    /// Unique identifier for this rule
270    pub path: RulePath,
271
272    /// Root of this rule in the shared [`ExecutionPlan::normal_forms`] graph.
273    pub normal_form: NormalFormId,
274
275    /// Source location for error messages (always present for rules from parsed specs)
276    pub source: Source,
277
278    /// Type of the rule as written: the lowered source expression typed at
279    /// planning, equal to validation's inferred type. The root cell at
280    /// `normal_form` has the same value type but may carry a different name
281    /// after rewrites (`x + 0` → `x`), so the API type reads this field.
282    pub rule_type: Arc<LemmaType>,
283
284    /// Scale targets of every dynamic unit this rule's nodes hold or write, in this
285    /// plan's coordinates. Evaluated before the rule body; topological order puts
286    /// local scale rules first.
287    pub scale_dependencies: Vec<ScaleTarget>,
288}
289
290impl ExecutableRule {
291    pub fn name(&self) -> &str {
292        &self.path.rule
293    }
294}
295
296/// Position of a rule in [`ExecutionPlan::rules`]; indexes the evaluation
297/// context's `rule_values` table. Plain `Copy` so the evaluation walk can
298/// unwind to a rule without cloning its [`RulePath`].
299#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
300pub(crate) struct RuleIndex(usize);
301
302/// The starts evaluation may make between pieces of a plan, by site: the pieces each
303/// piece can start, and the longest chain of nested starts.
304#[cfg(feature = "call-graph-check")]
305#[derive(Clone, Default)]
306pub(crate) struct CallGraph {
307    pub(crate) callees: HashMap<CallSite, Vec<CallSite>>,
308    pub(crate) depth: usize,
309}
310
311/// Sites name rows by address, which differs between two plannings of one spec: a plan's
312/// debug form shows the graph's size and bound only.
313#[cfg(feature = "call-graph-check")]
314impl std::fmt::Debug for CallGraph {
315    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
316        f.debug_struct("CallGraph")
317            .field("edges", &self.callees.values().map(Vec::len).sum::<usize>())
318            .field("depth", &self.depth)
319            .finish()
320    }
321}
322
323/// A piece of evaluation: a rule of the plan, run in its context, or a read of an end on
324/// a row, its context named by the addresses of its rows, outermost first.
325#[cfg(feature = "call-graph-check")]
326#[derive(Clone, Debug, PartialEq, Eq, Hash)]
327pub(crate) enum CallSite {
328    Rule(RulePath),
329    Read(Vec<usize>, RowEnd),
330}
331
332/// What resolving a reference target in its owner's context evaluates first.
333#[derive(Clone, Copy, Debug, PartialEq, Eq)]
334pub(crate) enum TargetForce {
335    /// The rule the target ends at.
336    Rule(RuleIndex),
337    /// The member cell of a target read through `uses` hops (`i.x`).
338    Member(NormalFormId),
339}
340
341impl RuleIndex {
342    pub(crate) fn index(self) -> usize {
343        self.0
344    }
345}
346
347/// Select the plan whose half-open `[effective, next.effective)` covers `instant`
348/// (greatest key `<= instant` in the map).
349pub(crate) fn plan_at<'a>(
350    plans: &'a BTreeMap<EffectiveDate, std::sync::Arc<ExecutionPlan>>,
351    instant: &EffectiveDate,
352) -> Option<&'a ExecutionPlan> {
353    plans
354        .range(..=instant.clone())
355        .next_back()
356        .map(|(_, plan)| plan.as_ref())
357}
358
359fn assert_list_elements_determined(root: &LemmaType) {
360    let mut stack = vec![root];
361    while let Some(lemma_type) = stack.pop() {
362        if let TypeSpecification::List { element, .. } = &lemma_type.specifications {
363            assert!(
364                !element.is_undetermined(),
365                "BUG: validated List type '{}' has an Undetermined element type",
366                lemma_type.name()
367            );
368            stack.push(element);
369        }
370    }
371}
372
373/// Builds an execution plan from a Graph for one temporal slice.
374///
375/// `interner` dedups cons cells while the plan is built. The plan's dense `normal_forms`
376/// table is extracted from it with [`NormalFormInterner::extract_reachable`], so the
377/// result does not depend on what else the interner holds.
378pub(crate) fn build_execution_plan(
379    graph: &Graph<'_>,
380    resolved_types: Arc<ResolvedSpecTypes>,
381    effective: &EffectiveDate,
382    limits: &ResourceLimits,
383    interner: &mut NormalFormInterner,
384    own_spec: Arc<LemmaSpec>,
385    edges: Vec<SpecIdentity>,
386) -> Result<ExecutionPlan, Vec<Error>> {
387    let rule_order = &graph.rule_order;
388
389    let main_spec = graph.main_spec;
390    let data = graph.build_data(&resolved_types.resolved)?;
391
392    // Planning gate: every data-target reference and plain data declaration
393    // must carry a fully resolved type. Rule-target references are exempt:
394    // they deliberately ship `Undetermined` so runtime veto propagation
395    // surfaces the target rule's veto reason directly. A residual
396    // `Undetermined` anywhere else would violate the invariant evaluation
397    // and show consumers rely on — report it instead of shipping the plan.
398    let undetermined_errors: Vec<Error> = data
399        .iter()
400        .filter_map(|(path, definition)| {
401            let (resolved_type, source) = match definition {
402                DataDefinition::TypeDeclaration {
403                    resolved_type,
404                    source,
405                    ..
406                } => (resolved_type, source),
407                DataDefinition::Reference {
408                    target: ReferenceTarget::Data(_),
409                    resolved_type,
410                    source,
411                    ..
412                } => (resolved_type, source),
413                DataDefinition::Reference {
414                    target: ReferenceTarget::Rule(_),
415                    ..
416                }
417                | DataDefinition::Value { .. }
418                | DataDefinition::InstanceList { .. }
419                | DataDefinition::Import { .. } => return None,
420            };
421            if resolved_type.is_undetermined() {
422                Some(Error::validation(
423                    format!("could not determine the type of '{path}'"),
424                    Some(source.clone()),
425                    None::<String>,
426                ))
427            } else {
428                None
429            }
430        })
431        .collect();
432    if !undetermined_errors.is_empty() {
433        return Err(undetermined_errors);
434    }
435
436    for lemma_type in resolved_types.resolved.values() {
437        assert_list_elements_determined(lemma_type);
438    }
439
440    let signature_index = resolved_types.signature_index.clone();
441
442    let family_units = Arc::new(FamilyUnitCatalog::build(&resolved_types.unit_index));
443
444    let rule_types: HashMap<RulePath, Arc<LemmaType>> = graph
445        .rules
446        .iter()
447        .map(|(path, node)| (path.clone(), Arc::clone(&node.rule_type)))
448        .collect();
449    let mut rules: IndexMap<RulePath, ExecutableRule> = IndexMap::new();
450    let mut completed_rules: HashMap<RulePath, NormalFormId> = HashMap::new();
451    let mut local_show_rules: HashMap<RulePath, ShowRule> = HashMap::new();
452
453    let show_imports = &graph.show_imports;
454    let show_edges = &graph.show_edges;
455    let show_order = &graph.show_order;
456    let show_keys: HashSet<RulePath> = show_edges.keys().cloned().collect();
457    let catalog_keys: HashSet<RulePath> = rule_order.iter().cloned().collect();
458
459    for rule_path in rule_order {
460        let rule_node = graph.rules.get(rule_path).expect(
461            "bug: rule from topological sort not in graph - validation should have caught this",
462        );
463
464        let measure_scope = MeasureScope {
465            unit_index: &resolved_types.unit_index,
466            signature_index: &resolved_types.signature_index,
467            named_types: &resolved_types.resolved,
468        };
469        let normalize_ctx = NormalizeContext {
470            data: &data,
471            row_templates: &graph.instance_lists.templates,
472            self_identity: &graph.instance_lists.self_identity,
473            rule_order,
474            measure_scope,
475            max_normalized_expression_nodes: limits.max_normalized_expression_nodes,
476        };
477        let normalized = build_normalized_rule(
478            &normalize_ctx,
479            &completed_rules,
480            &rule_types,
481            &rule_node.expression,
482            Some(rule_node.source.clone()),
483            interner,
484        )
485        .map_err(|error| vec![error])?;
486        let NormalizedRule { body, source_type } = normalized;
487        assert_eq!(
488            &source_type, &rule_node.rule_type,
489            "BUG: rule '{}' typed differently by planning and validation",
490            rule_path.rule
491        );
492        assert!(
493            interner
494                .result_type(body)
495                .same_value_type(&rule_node.rule_type),
496            "BUG: rewrites changed the value type of rule '{}': {:?} from {:?}",
497            rule_path.rule,
498            interner.result_type(body),
499            rule_node.rule_type
500        );
501        completed_rules.insert(rule_path.clone(), body);
502
503        local_show_rules.insert(
504            rule_path.clone(),
505            ShowRule {
506                lemma_type: family_units.rule_type_for_show(rule_node.rule_type.as_ref()),
507                path: rule_path.segments.clone(),
508                branches: show_branches_from(
509                    &rule_node.expression,
510                    &rule_node.branches,
511                    &ShowScope {
512                        show_keys: &show_keys,
513                        data: &data,
514                        templates: &graph.instance_lists.templates,
515                    },
516                ),
517                depends_on_rules: project_depends_on_rules(&show_edges[rule_path], &catalog_keys),
518            },
519        );
520
521        rules.insert(
522            rule_path.clone(),
523            ExecutableRule {
524                path: rule_path.clone(),
525                normal_form: body,
526                source: rule_node.source.clone(),
527                rule_type: source_type,
528                scale_dependencies: Vec::new(),
529            },
530        );
531    }
532
533    for (rule_path, rule) in rules.iter_mut() {
534        rule.scale_dependencies = graph
535            .rules
536            .get(rule_path)
537            .expect("BUG: executable rule missing from its graph")
538            .scale_targets
539            .clone();
540    }
541    let mut member_target_paths: Vec<&ReferenceTarget> = Vec::new();
542    crate::planning::graph::for_each_owned_reference(
543        &data,
544        &graph.instance_lists,
545        |_, _, target| {
546            if !reference_target_segments(target).is_empty()
547                && !member_target_paths.contains(&target)
548            {
549                member_target_paths.push(target);
550            }
551        },
552    );
553    for (_, write) in graph.writes.iter() {
554        if let RowBinding::Deferred { target } = &write.binding {
555            if !reference_target_segments(target).is_empty()
556                && !member_target_paths.contains(&target)
557            {
558                member_target_paths.push(target);
559            }
560        }
561    }
562    let mut owned_scale_member_targets: Vec<ReferenceTarget> = Vec::new();
563    let mut push_uses_scale_member = |scale: &ScaleTarget| {
564        let target = &scale.target;
565        if !scale.owner.is(&graph.instance_lists.self_identity)
566            || reference_target_segments(target).is_empty()
567        {
568            return;
569        }
570        if !first_hop_is_uses_import(&data, target) {
571            return;
572        }
573        if member_target_paths.contains(&target) || owned_scale_member_targets.contains(target) {
574            return;
575        }
576        owned_scale_member_targets.push(target.clone());
577    };
578    for rule in rules.values() {
579        for target in &rule.scale_dependencies {
580            push_uses_scale_member(target);
581        }
582    }
583    for definition in data.values() {
584        let Some(lemma_type) = definition.schema_type() else {
585            continue;
586        };
587        for target in lemma_type.dynamic_scale_targets() {
588            push_uses_scale_member(&target);
589        }
590    }
591    for target in &owned_scale_member_targets {
592        member_target_paths.push(target);
593    }
594    let mut member_target_roots: Vec<NormalFormId> = Vec::new();
595    for target in &member_target_paths {
596        let normalize_ctx = NormalizeContext {
597            data: &data,
598            row_templates: &graph.instance_lists.templates,
599            self_identity: &graph.instance_lists.self_identity,
600            rule_order,
601            measure_scope: MeasureScope {
602                unit_index: &resolved_types.unit_index,
603                signature_index: &resolved_types.signature_index,
604                named_types: &resolved_types.resolved,
605            },
606            max_normalized_expression_nodes: limits.max_normalized_expression_nodes,
607        };
608        let normalized = build_normalized_rule(
609            &normalize_ctx,
610            &completed_rules,
611            &rule_types,
612            &member_target_expression(target),
613            None,
614            interner,
615        )
616        .map_err(|error| vec![error])?;
617        member_target_roots.push(normalized.body);
618    }
619
620    let root_ids: Vec<NormalFormId> = rules
621        .values()
622        .map(|rule| rule.normal_form)
623        .chain(member_target_roots)
624        .collect();
625    let (normal_forms, mut remapped_roots) = interner.extract_reachable(&root_ids);
626    let remapped_members = remapped_roots.split_off(rules.len());
627    for (rule, remapped) in rules.values_mut().zip(remapped_roots) {
628        rule.normal_form = remapped;
629    }
630    let member_targets: IndexMap<ReferenceTarget, NormalFormId> = member_target_paths
631        .into_iter()
632        .cloned()
633        .zip(remapped_members)
634        .collect();
635
636    let mut show_rules: IndexMap<RulePath, ShowRule> =
637        IndexMap::with_capacity(local_show_rules.len());
638    for path in show_order {
639        if let Some(local) = local_show_rules.remove(path) {
640            show_rules.insert(path.clone(), local);
641        }
642    }
643    assert!(
644        local_show_rules.is_empty(),
645        "BUG: local rules missing from the Show order"
646    );
647
648    let mut plan = ExecutionPlan {
649        spec_name: main_spec.name.clone(),
650        commentary: main_spec.commentary.clone(),
651        data,
652        normal_forms,
653        rules,
654        data_reference_order: graph.data_reference_order.to_vec(),
655        meta: main_spec
656            .meta_fields
657            .iter()
658            .map(|f| (f.key.clone(), f.value.clone()))
659            .collect(),
660        resolved_types,
661        family_units,
662        signature_index,
663        effective: effective.clone(),
664        // Filled by attach_show_cache after this returns.
665        effective_from: None,
666        effective_to: None,
667        start_line: 1,
668        source_type: None,
669        needed_by_rules: Vec::new(),
670        data_display: IndexMap::new(),
671        show_rules,
672        // Filled below after validation succeeds.
673        show_needed_by: IndexMap::new(),
674        show_import_data: show_imports
675            .data
676            .iter()
677            .map(|(path, identity)| (path.clone(), identity.clone()))
678            .collect(),
679        reference_ends: IndexMap::new(),
680        input_key_index: IndexMap::new(),
681        show_rule_index: IndexMap::new(),
682        data_leaf: IndexMap::new(),
683        member_targets,
684        row_templates: graph.instance_lists.templates.clone(),
685        globals: graph.globals.clone(),
686        writes: graph.writes.clone(),
687        writes_root: Arc::new(graph.instance_lists.self_identity.clone()),
688        writes_by_spec: Arc::new(crate::planning::fill::WritesIndex::new(
689            std::iter::once((graph.instance_lists.self_identity.clone(), &graph.writes))
690                .chain(
691                    graph
692                        .instance_lists
693                        .templates
694                        .iter()
695                        .map(|(identity, template)| (identity.clone(), &template.writes)),
696                )
697                .filter(|(_, writes)| !writes.is_empty())
698                .map(|(identity, writes)| (identity, writes.clone()))
699                .collect(),
700        )),
701        identity: graph.instance_lists.self_identity.clone(),
702        own_spec,
703        edges,
704        rule_candidates: graph
705            .rule_candidates
706            .iter()
707            .map(|(rule, candidates)| (rule.clone(), candidates.clone()))
708            .collect(),
709        self_row_rules: Vec::new(),
710        instance_lists: graph.instance_lists.sources.clone(),
711        row_mask: Vec::new(),
712        initial_values: Vec::new(),
713        walk_settled_leaves: Vec::new(),
714        #[cfg(feature = "call-graph-check")]
715        call_graph: graph.call_graph_export(),
716        rule_ref_indexes: Vec::new(),
717        data_slot_leaves: Vec::new(),
718        slot_scale_targets: Vec::new(),
719    };
720    plan.slot_scale_targets = slot_scale_targets(&plan.data, &plan.identity);
721
722    let mut plan_errors = validate_literal_data_against_types(&plan);
723    if let Err(error) = validate_unit_conversion_targets(&plan) {
724        plan_errors.push(error);
725    }
726    if !plan_errors.is_empty() {
727        return Err(plan_errors);
728    }
729
730    plan.reference_ends = graph.reference_ends.clone();
731    let input_keys: Vec<DataPath> = plan.data.keys().cloned().collect();
732    plan.data_leaf = ensure_data_leaves(&mut plan.normal_forms, &input_keys, &plan.data);
733    plan.input_key_index = input_keys
734        .iter()
735        .map(|path| (path.input_key(), path.clone()))
736        .collect();
737    plan.show_rule_index = plan
738        .show_rules
739        .keys()
740        .map(|path| (path.input_key(), path.clone()))
741        .collect();
742    for (path, &id) in &plan.data_leaf {
743        debug_assert_eq!(
744            plan.result_type(id).as_ref(),
745            data_path_result_type(&plan.data, path).as_ref(),
746            "BUG: DataPath leaf result_type drift for {path}"
747        );
748    }
749    let bits_by_rule = plan.build_needed_by_rules();
750    plan.show_needed_by =
751        plan.build_show_needed_by(show_order, show_edges, show_imports, &bits_by_rule);
752    plan.fill_row_field_needs(&bits_by_rule);
753    plan.row_mask = build_row_mask(&plan.normal_forms).map_err(|error| vec![error])?;
754    check_rows_unit_conversions(&plan)?;
755    mark_row_unit_cells(&mut plan);
756    plan.self_row_rules = self_row_rules(&plan);
757    plan.populate_evaluation_tables();
758    validate_option_rules(&plan)?;
759    crate::planning::program::check_program(&plan);
760    Ok(plan)
761}
762
763/// The `uses` hops a reference target is read through; empty for a target of the plan itself.
764pub(crate) fn reference_target_segments(target: &ReferenceTarget) -> &[PathSegment] {
765    match target {
766        ReferenceTarget::Data(path) => &path.segments,
767        ReferenceTarget::Rule(rule) => &rule.segments,
768    }
769}
770
771/// Whether `target`'s first hop is a `uses` Import of this plan (not a list name).
772fn first_hop_is_uses_import(
773    data: &IndexMap<DataPath, DataDefinition>,
774    target: &ReferenceTarget,
775) -> bool {
776    let Some(first) = reference_target_segments(target).first() else {
777        return false;
778    };
779    matches!(
780        data.get(&DataPath::local(first.uses.to_string())),
781        Some(DataDefinition::Import { .. })
782    )
783}
784
785/// Per data slot, in slot order: the dynamic scale targets of the spec `identity`
786/// declared on its type, each once. Units of a list's rows are sized by their rows.
787fn slot_scale_targets(
788    data: &IndexMap<DataPath, DataDefinition>,
789    identity: &SpecIdentity,
790) -> Vec<Vec<ScaleTarget>> {
791    data.values()
792        .map(|definition| {
793            let Some(lemma_type) = definition.schema_type() else {
794                return Vec::new();
795            };
796            let mut targets: Vec<ScaleTarget> = Vec::new();
797            for target in lemma_type.dynamic_scale_targets() {
798                if target.owner.is(identity) && !targets.contains(&target) {
799                    targets.push(target);
800                }
801            }
802            targets
803        })
804        .collect()
805}
806
807/// `i.j.x` as a member read on the plan's import slot `i`: the expression a member
808/// target cell lowers.
809fn member_target_expression(target: &ReferenceTarget) -> crate::planning::semantics::Expression {
810    let (first, rest) = reference_target_segments(target)
811        .split_first()
812        .expect("BUG: a member target has a `uses` hop");
813    let name = match target {
814        ReferenceTarget::Data(path) => path.data.clone(),
815        ReferenceTarget::Rule(rule) => rule.rule.clone(),
816    };
817    let mut table = crate::parsing::arena::ExprTable::default();
818    let base = table.push(
819        crate::planning::semantics::ExpressionKind::DataPath(DataPath::local(
820            first.uses.to_string(),
821        )),
822        None,
823    );
824    let root = table.push(
825        crate::planning::semantics::ExpressionKind::SpecMember {
826            base,
827            path: rest
828                .iter()
829                .map(|segment| segment.uses.to_string())
830                .collect(),
831            name,
832        },
833        None,
834    );
835    crate::planning::semantics::Expression::new(table, root)
836}
837
838/// Rule the options of data `path` come from: the rule named by the slot's type, in
839/// the spec that declared the slot (the hops of `path`). `None` when the type has no
840/// options rule.
841pub(crate) fn options_rule_path(data_path: &DataPath, lemma_type: &LemmaType) -> Option<RulePath> {
842    let name = lemma_type.options_rule()?;
843    Some(RulePath {
844        segments: data_path.segments.clone(),
845        rule: name.to_string(),
846    })
847}
848
849fn validate_option_rules(plan: &ExecutionPlan) -> Result<(), Vec<Error>> {
850    let mut errors = Vec::new();
851    for (path, definition) in &plan.data {
852        let Some(lemma_type) = definition.schema_type() else {
853            continue;
854        };
855        let owners = option_owners(lemma_type);
856        for owner in owners {
857            // The owner's own rule: a list's element is checked as its own owner.
858            let Some(name) = &owner.options.rule else {
859                continue;
860            };
861            let rule_path = RulePath {
862                segments: path.segments.clone(),
863                rule: name.clone(),
864            };
865            let Some(rule) = plan.rules.get(&rule_path) else {
866                errors.push(Error::validation(
867                    format!("options rule '{name}' does not exist"),
868                    None,
869                    None::<String>,
870                ));
871                continue;
872            };
873            let TypeSpecification::List { element, .. } = &rule.rule_type.specifications else {
874                errors.push(Error::validation(
875                    format!("options rule '{name}' must return a list"),
876                    None,
877                    None::<String>,
878                ));
879                continue;
880            };
881            if !option_element_matches(owner, element) {
882                errors.push(Error::validation(
883                    format!(
884                        "options rule '{name}' returns {}, not a list of {}",
885                        rule.rule_type.name(),
886                        owner.name()
887                    ),
888                    None,
889                    None::<String>,
890                ));
891            }
892        }
893    }
894    if errors.is_empty() {
895        Ok(())
896    } else {
897        Err(errors)
898    }
899}
900
901fn option_owners(lemma_type: &LemmaType) -> Vec<&LemmaType> {
902    let mut owners = vec![lemma_type];
903    if let TypeSpecification::List { element, .. } = &lemma_type.specifications {
904        owners.push(element.as_ref());
905    }
906    owners
907}
908
909fn option_element_matches(owner: &LemmaType, element: &LemmaType) -> bool {
910    match (&owner.specifications, &element.specifications) {
911        (TypeSpecification::Spec { spec: left }, TypeSpecification::Spec { spec: right }) => {
912            left == right
913        }
914        _ => {
915            owner.has_same_base_type(element)
916                && !matches!(owner.specifications, TypeSpecification::Spec { .. })
917        }
918    }
919}
920
921/// Bitset over the row fields ([`ExecutionPlan::row_field_position`]) of rows of `identity`.
922fn row_bits_entry<'a>(
923    plan: &ExecutionPlan,
924    row_bits: &'a mut BTreeMap<SpecIdentity, Vec<u64>>,
925    identity: &SpecIdentity,
926) -> &'a mut Vec<u64> {
927    let words = plan.row_template(identity).row_field_count().div_ceil(64);
928    row_bits
929        .entry(identity.clone())
930        .or_insert_with(|| vec![0u64; words])
931}
932
933/// Set the bit of the slot an evaluation-data row binds when a rule reads `path` on it.
934fn mark_template_data_path(template: &ExecutionPlan, path: &DataPath, bits: &mut [u64]) {
935    if let Some(target) = template.bindable_row_field(path) {
936        let data_pos = template
937            .data
938            .get_index_of(target)
939            .unwrap_or_else(|| panic!("BUG: bindable row field '{target}' absent from plan.data"));
940        bits[data_pos / 64] |= 1u64 << (data_pos % 64);
941    }
942}
943
944/// Row fields a finished template's rule needs: its data (from `needed_by_rules`) and
945/// the data of its `uses` imports (from `show_needed_by`).
946fn mark_template_rule_data(template: &ExecutionPlan, rule: &RulePath, bits: &mut [u64]) {
947    let rule_pos = u32::try_from(template.rules.get_index_of(rule).unwrap_or_else(|| {
948        panic!(
949            "BUG: row rule '{rule}' missing from template plan '{}'",
950            template.spec_name
951        )
952    }))
953    .expect("BUG: rule count exceeds u32");
954    for (data_pos, consumers) in template.needed_by_rules.iter().enumerate() {
955        if consumers.rules.contains(&rule_pos) {
956            bits[data_pos / 64] |= 1u64 << (data_pos % 64);
957        }
958    }
959    mark_template_import_data(template, rule, bits);
960}
961
962/// Row fields of `uses` imports of `template` that its Show rule `rule` (a path composed
963/// from import hops) needs.
964fn mark_template_import_data(template: &ExecutionPlan, rule: &RulePath, bits: &mut [u64]) {
965    let Some(rule_pos) = template.show_rule_position(rule) else {
966        return;
967    };
968    for (index, path) in template.show_import_data.keys().enumerate() {
969        let needed = template
970            .show_needed_by
971            .get(path)
972            .expect("BUG: Show import data has readers");
973        if needed.contains(&rule_pos) {
974            let field_pos = template.data.len() + index;
975            bits[field_pos / 64] |= 1u64 << (field_pos % 64);
976        }
977    }
978}
979
980/// One `uses` level below a row spec in [`mark_row_end_needs`]: the instance the slot
981/// holds there (a consumer-written override or the template's own) and its template.
982#[derive(Clone)]
983struct MemberLevel<'p> {
984    segment: PathSegment,
985    row: &'p RowInstance,
986    template: &'p ExecutionPlan,
987}
988
989/// A read on rows of a row spec, at a chain of `uses` levels below it.
990enum MemberNeed<'p> {
991    Data(Vec<MemberLevel<'p>>, DataPath),
992    Rule(Vec<MemberLevel<'p>>, RulePath),
993}
994
995/// `chain` extended by the `uses` slots `aliases`, starting at the template of the
996/// chain's last level (or `holder` for an empty chain).
997fn member_levels<'p, 'a>(
998    plan: &'p ExecutionPlan,
999    holder: &'p ExecutionPlan,
1000    mut chain: Vec<MemberLevel<'p>>,
1001    aliases: impl IntoIterator<Item = &'a str>,
1002) -> Vec<MemberLevel<'p>> {
1003    for alias in aliases {
1004        let template = chain.last().map_or(holder, |level| level.template);
1005        let slot = DataPath::local(alias.to_string());
1006        let Some(DataDefinition::Import { row, .. }) = template.data.get(&slot) else {
1007            panic!("BUG: member hop '{slot}' is not a `uses` slot");
1008        };
1009        if let Some(other) = chain
1010            .last()
1011            .and_then(|level| level.row.get_binding(template, &slot))
1012        {
1013            panic!("BUG: `uses` slot '{slot}' bound to {other:?}");
1014        }
1015        chain.push(MemberLevel {
1016            segment: PathSegment::import(&slot.data, &row.identity),
1017            row,
1018            template: plan.row_template(&row.identity),
1019        });
1020    }
1021    chain
1022}
1023
1024/// Record what reading the member chain `ends` on evaluation-data rows of `identity`
1025/// needs. Every end but the last reads a `uses` slot.
1026fn mark_row_end_needs(
1027    plan: &ExecutionPlan,
1028    identity: &SpecIdentity,
1029    ends: &[RowEnd],
1030    bits_by_rule: &[Vec<u64>],
1031    row_bits: &mut BTreeMap<SpecIdentity, Vec<u64>>,
1032    consumer_rule: &RulePath,
1033) {
1034    let bits = row_bits_entry(plan, row_bits, identity);
1035    let holder = plan.row_template(identity);
1036    let (end, hops) = ends.split_last().expect("BUG: a row read has a last end");
1037    let chain = member_levels(
1038        plan,
1039        holder,
1040        Vec::new(),
1041        hops.iter().map(|hop| match hop {
1042            RowEnd::Data(slot) => slot.data.as_str(),
1043            RowEnd::Rule(rule) => panic!("BUG: a row read hop is a `uses` slot, got rule '{rule}'"),
1044        }),
1045    );
1046    let mut pending = vec![match end {
1047        RowEnd::Data(path) => MemberNeed::Data(chain, path.clone()),
1048        RowEnd::Rule(rule) => MemberNeed::Rule(chain, rule.clone()),
1049    }];
1050    while let Some(need) = pending.pop() {
1051        match need {
1052            MemberNeed::Data(chain, path) if !path.segments.is_empty() => {
1053                let chain = member_levels(
1054                    plan,
1055                    holder,
1056                    chain,
1057                    path.segments.iter().map(|segment| &*segment.uses),
1058                );
1059                pending.push(MemberNeed::Data(chain, DataPath::local(path.data)));
1060            }
1061            MemberNeed::Rule(chain, rule) if !rule.segments.is_empty() => {
1062                let chain = member_levels(
1063                    plan,
1064                    holder,
1065                    chain,
1066                    rule.segments.iter().map(|segment| &*segment.uses),
1067                );
1068                pending.push(MemberNeed::Rule(
1069                    chain,
1070                    RulePath::new(Vec::new(), rule.rule),
1071                ));
1072            }
1073            MemberNeed::Data(chain, path) if chain.is_empty() => {
1074                mark_holder_data(plan, identity, &path, bits_by_rule, bits, consumer_rule);
1075            }
1076            MemberNeed::Rule(chain, rule) if chain.is_empty() => {
1077                mark_holder_rule(plan, identity, &rule, bits_by_rule, bits, consumer_rule);
1078            }
1079            MemberNeed::Data(mut chain, path) => {
1080                let level = chain.last().expect("BUG: non-empty member chain");
1081                match level.row.get_binding(level.template, &path) {
1082                    None => match level.template.data.get(&path) {
1083                        Some(DataDefinition::Reference { .. }) => {
1084                            match level.template.reference_ends.get(&path) {
1085                                Some(ReferenceEnd::Promptable(target)) => {
1086                                    pending.push(MemberNeed::Data(chain, target.clone()));
1087                                }
1088                                Some(ReferenceEnd::Rule(rule)) => {
1089                                    pending.push(MemberNeed::Rule(chain, rule.clone()));
1090                                }
1091                                None => panic!(
1092                                    "BUG: reference '{path}' missing from reference_ends after planning"
1093                                ),
1094                            }
1095                        }
1096                        Some(_) => {
1097                            let composed = DataPath {
1098                                segments: chain.iter().map(|level| level.segment.clone()).collect(),
1099                                data: path.data,
1100                            };
1101                            if let Some(index) = holder.show_import_data.get_index_of(&composed) {
1102                                let field_pos = holder.data.len() + index;
1103                                bits[field_pos / 64] |= 1u64 << (field_pos % 64);
1104                            }
1105                        }
1106                        None => panic!("BUG: member data '{path}' absent from its template"),
1107                    },
1108                    Some(RowBinding::Deferred { target }) => {
1109                        let frame = chain
1110                            .len()
1111                            .checked_sub(1)
1112                            .expect("BUG: a `uses` binding hops above the row spec");
1113                        let target = target.clone();
1114                        chain.truncate(frame);
1115                        pending.push(match target {
1116                            ReferenceTarget::Data(path) => MemberNeed::Data(chain, path),
1117                            ReferenceTarget::Rule(rule) => MemberNeed::Rule(chain, rule),
1118                        });
1119                    }
1120                    Some(RowBinding::Bound(_)) => {}
1121                }
1122            }
1123            MemberNeed::Rule(chain, rule) => {
1124                let template = chain.last().expect("BUG: non-empty member chain").template;
1125                let rule_pos =
1126                    u32::try_from(template.rules.get_index_of(&rule).unwrap_or_else(|| {
1127                        panic!("BUG: member rule '{rule}' missing from its template")
1128                    }))
1129                    .expect("BUG: rule count exceeds u32");
1130                let show_pos = template
1131                    .show_rule_position(&rule)
1132                    .expect("BUG: a local rule is a Show rule of its plan");
1133                for ((path, _), needed) in template.data.iter().zip(&template.needed_by_rules) {
1134                    if needed.rules.contains(&rule_pos) {
1135                        pending.push(MemberNeed::Data(chain.clone(), path.clone()));
1136                    }
1137                }
1138                for (path, needed) in &template.show_needed_by {
1139                    if !path.segments.is_empty() && needed.contains(&show_pos) {
1140                        pending.push(MemberNeed::Data(chain.clone(), path.clone()));
1141                    }
1142                }
1143            }
1144        }
1145    }
1146}
1147
1148/// What reading data `path` on rows of the row spec `identity` itself needs.
1149fn mark_holder_data(
1150    plan: &ExecutionPlan,
1151    identity: &SpecIdentity,
1152    path: &DataPath,
1153    bits_by_rule: &[Vec<u64>],
1154    bits: &mut [u64],
1155    consumer_rule: &RulePath,
1156) {
1157    let template = plan.row_template(identity);
1158    match template.reference_ends.get(path) {
1159        Some(ReferenceEnd::Rule(rule)) => {
1160            mark_holder_rule(plan, identity, rule, bits_by_rule, bits, consumer_rule);
1161        }
1162        Some(ReferenceEnd::Promptable(_)) | None => mark_template_data_path(template, path, bits),
1163    }
1164}
1165
1166/// What reading rule `rule` on rows of the row spec `identity` itself needs.
1167fn mark_holder_rule(
1168    plan: &ExecutionPlan,
1169    identity: &SpecIdentity,
1170    rule: &RulePath,
1171    bits_by_rule: &[Vec<u64>],
1172    bits: &mut [u64],
1173    consumer_rule: &RulePath,
1174) {
1175    let template = plan.row_template(identity);
1176    if *identity == plan.identity {
1177        let rule_pos = plan.rules.get_index_of(rule).unwrap_or_else(|| {
1178            panic!("BUG: row rule '{rule}' missing from plan.rules (rule '{consumer_rule}')")
1179        });
1180        for (word, dep) in bits.iter_mut().zip(bits_by_rule[rule_pos].iter()) {
1181            *word |= *dep;
1182        }
1183        mark_template_import_data(template, rule, bits);
1184    } else {
1185        mark_template_rule_data(template, rule, bits);
1186    }
1187}
1188
1189fn mark_list_key_fields(
1190    plan: &ExecutionPlan,
1191    list: NormalFormId,
1192    row_bits: &mut BTreeMap<SpecIdentity, Vec<u64>>,
1193    consumer_rule: &RulePath,
1194) {
1195    use crate::planning::semantics::ListKey;
1196
1197    let list_type = plan.result_type(list);
1198    let TypeSpecification::List { element, key, .. } = &list_type.specifications else {
1199        panic!(
1200            "BUG: Find/WithRow list cell is not a list type (rule '{consumer_rule}'): {list_type:?}"
1201        );
1202    };
1203    let TypeSpecification::Spec { spec: identity } = &element.specifications else {
1204        return;
1205    };
1206    let ListKey::Fields(fields) = key else {
1207        return;
1208    };
1209    let template = plan.row_template(identity);
1210    let bits = row_bits_entry(plan, row_bits, identity);
1211    for key_field in fields {
1212        mark_template_data_path(template, &key_field.path, bits);
1213    }
1214}
1215
1216/// [`ExecutionPlan::self_row_rules`]: every rule a row field or row member read of a
1217/// self-list names, directly or through a data reference to a rule.
1218fn self_row_rules(plan: &ExecutionPlan) -> Vec<RulePath> {
1219    use crate::planning::normalize::NormalFormKind;
1220    use crate::planning::semantics::RowEnd;
1221
1222    let mut rules_read: HashSet<&RulePath> = HashSet::new();
1223    for (index, cell) in plan.normal_forms.iter().enumerate() {
1224        let end = match &cell.kind {
1225            NormalFormKind::RowField { identity, end, .. } if *identity == plan.identity => end,
1226            NormalFormKind::SpecMember { base, row, .. } => match &plan
1227                .result_type(*base)
1228                .specifications
1229            {
1230                TypeSpecification::Spec { spec } if *spec == plan.identity => {
1231                    row.ends.first().expect("BUG: a row read has a first end")
1232                }
1233                TypeSpecification::Spec { .. } => continue,
1234                other => panic!("BUG: row member read on cell {index} of non-spec type {other:?}"),
1235            },
1236            _ => continue,
1237        };
1238        match end {
1239            RowEnd::Rule(rule) => {
1240                rules_read.insert(rule);
1241            }
1242            RowEnd::Data(path) => {
1243                if let Some(ReferenceEnd::Rule(rule)) = plan.reference_ends.get(path) {
1244                    rules_read.insert(rule);
1245                }
1246            }
1247        }
1248    }
1249    plan.rules
1250        .keys()
1251        .filter(|rule| rules_read.contains(rule))
1252        .cloned()
1253        .collect()
1254}
1255
1256/// The instances the global slots of one request read ([`ExecutionPlan::import_key`]).
1257#[derive(Debug)]
1258pub(crate) struct RequestGlobals {
1259    /// The root plan's one instance per global, fed by evaluation data.
1260    roots: HashMap<GlobalKey, Arc<RowInstance>>,
1261}
1262
1263impl RequestGlobals {
1264    /// The instance of global `key` a global slot read anywhere lands on: the root plan's
1265    /// one instance, which holds every write on the global.
1266    pub(crate) fn instance(&self, key: &GlobalKey) -> InstanceKey {
1267        let row = self.roots.get(key).unwrap_or_else(|| {
1268            panic!("BUG: request reaches global '{key}' its root plan does not hold")
1269        });
1270        InstanceKey::new(Arc::clone(row), None)
1271    }
1272}
1273
1274impl ExecutionPlan {
1275    /// Whether `target` is a cell of this plan: local data or a local rule, or a member
1276    /// read through `uses` hops that the plan registers.
1277    pub(crate) fn holds_scale_target(&self, scale: &ScaleTarget) -> bool {
1278        if !scale.owner.is(&self.identity) {
1279            return false;
1280        }
1281        let target = &scale.target;
1282        if self.member_targets.contains_key(target) {
1283            return true;
1284        }
1285        match target {
1286            ReferenceTarget::Data(path) => self.data_leaf.contains_key(path),
1287            ReferenceTarget::Rule(path) => self.rules.contains_key(path),
1288        }
1289    }
1290
1291    /// Scale targets of the dynamic units cell `id` writes itself: those of its literal,
1292    /// or of the unit it converts to, or converts a number from.
1293    pub(crate) fn written_scale_targets(&self, id: NormalFormId) -> Vec<ScaleTarget> {
1294        use crate::planning::normalize::{LeafKind, NormalFormKind};
1295        let factors_of = |lemma_type: &LemmaType, unit: &str| {
1296            lemma_type
1297                .unit_scale_factors(unit)
1298                .iter()
1299                .map(|(target, _)| target.clone())
1300                .collect()
1301        };
1302        match &self.normal_form(id).kind {
1303            NormalFormKind::Leaf(LeafKind::Literal(literal)) => {
1304                crate::planning::graph::scale_targets_of_unscaled(
1305                    &literal.value,
1306                    self.result_type(id),
1307                )
1308            }
1309            NormalFormKind::UnitConversion(
1310                _,
1311                SemanticConversionTarget::Unit {
1312                    unit_name,
1313                    owning_type,
1314                },
1315            ) => factors_of(owning_type, unit_name),
1316            NormalFormKind::UnitConversion(
1317                inner,
1318                SemanticConversionTarget::Type(ConversionTypeKind::Number),
1319            ) => {
1320                let source = self.result_type(*inner);
1321                if !source.is_measure() {
1322                    return Vec::new();
1323                }
1324                match source.measure_runtime_signature().first() {
1325                    Some((unit, _)) => factors_of(source, unit),
1326                    None => Vec::new(),
1327                }
1328            }
1329            _ => Vec::new(),
1330        }
1331    }
1332
1333    /// Scale targets a read of data `path` of this plan needs: the dynamic units of its
1334    /// type ([`Self::slot_scale_targets`]).
1335    pub(crate) fn data_scale_targets(&self, path: &DataPath) -> &[ScaleTarget] {
1336        let slot = self
1337            .data
1338            .get_index_of(path)
1339            .unwrap_or_else(|| panic!("BUG: data '{path}' is not a slot of '{}'", self.spec_name));
1340        &self.slot_scale_targets[slot]
1341    }
1342
1343    /// What resolving `target` in this plan's context evaluates first: the member cell
1344    /// of a target read through `uses` hops (`i.x`), the rule a target ends at, or
1345    /// nothing for data that resolves as is.
1346    pub(crate) fn target_force(&self, target: &ReferenceTarget) -> Option<TargetForce> {
1347        if let Some(&cell) = self.member_targets.get(target) {
1348            return Some(TargetForce::Member(cell));
1349        }
1350        let rule = match target {
1351            ReferenceTarget::Rule(rule) => rule,
1352            ReferenceTarget::Data(path) => match self.reference_ends.get(path) {
1353                Some(ReferenceEnd::Rule(rule)) => rule,
1354                Some(ReferenceEnd::Promptable(_)) | None => return None,
1355            },
1356        };
1357        Some(TargetForce::Rule(self.rule_index(rule)))
1358    }
1359
1360    /// Slots of this template a read of `end` on one of its rows touches: the end's own
1361    /// reads (a data end that references a rule reads as that rule), and the reads of
1362    /// the local scale targets the read forces before its body runs. Member scale targets
1363    /// (`j.rate`) read their own row.
1364    pub(crate) fn row_read_slots(&self, end: &RowEnd) -> Vec<DataPath> {
1365        let mut slots: Vec<DataPath> = Vec::new();
1366        let push = |slot: DataPath, slots: &mut Vec<DataPath>| {
1367            if !slots.contains(&slot) {
1368                slots.push(slot);
1369            }
1370        };
1371        let rule = match end {
1372            RowEnd::Rule(rule) => Some(rule),
1373            RowEnd::Data(path) => match self.reference_ends.get(path) {
1374                Some(ReferenceEnd::Rule(rule)) => Some(rule),
1375                Some(ReferenceEnd::Promptable(_)) | None => None,
1376            },
1377        };
1378        let scale_targets: &[ScaleTarget] = match (rule, end) {
1379            (Some(rule), _) => {
1380                for read in self.row_end_reads(&RowEnd::Rule(rule.clone())) {
1381                    push(read.slot, &mut slots);
1382                }
1383                &self
1384                    .rules
1385                    .get(rule)
1386                    .expect("BUG: row read rule missing from its template")
1387                    .scale_dependencies
1388            }
1389            (None, RowEnd::Data(path)) => {
1390                push(path.clone(), &mut slots);
1391                self.data_scale_targets(path)
1392            }
1393            (None, RowEnd::Rule(_)) => unreachable!("BUG: a rule end reads as its rule"),
1394        };
1395        for scale in scale_targets {
1396            if !scale.owner.is(&self.identity) {
1397                continue;
1398            }
1399            let end = match &scale.target {
1400                ReferenceTarget::Data(path) if path.segments.is_empty() => {
1401                    RowEnd::Data(path.clone())
1402                }
1403                ReferenceTarget::Rule(rule) if rule.segments.is_empty() => {
1404                    RowEnd::Rule(rule.clone())
1405                }
1406                ReferenceTarget::Data(_) | ReferenceTarget::Rule(_) => continue,
1407            };
1408            for read in self.row_end_reads(&end) {
1409                push(read.slot, &mut slots);
1410            }
1411        }
1412        slots
1413    }
1414
1415    /// Template plan rows of `identity` read: this plan for its own self-lists.
1416    pub(crate) fn row_template(&self, identity: &SpecIdentity) -> &ExecutionPlan {
1417        if *identity == self.identity {
1418            return self;
1419        }
1420        self.row_templates
1421            .get(identity)
1422            .unwrap_or_else(|| panic!("BUG: rows of '{identity}' without a template plan"))
1423    }
1424
1425    /// The import row of this plan's `uses` slot `slot`. `selected` is the body evaluation
1426    /// selected for a `uses … -> effective` slot; `None` for any other slot.
1427    pub(crate) fn import_row<'a>(
1428        &'a self,
1429        slot: &DataPath,
1430        selected: Option<&'a Arc<RowInstance>>,
1431    ) -> &'a Arc<RowInstance> {
1432        let definition = self
1433            .data
1434            .get(slot)
1435            .unwrap_or_else(|| panic!("BUG: `uses` slot '{slot}' is not data of its plan"));
1436        let DataDefinition::Import { row, pin, .. } = definition else {
1437            panic!("BUG: data '{slot}' read as a `uses` slot is not an import");
1438        };
1439        if pin.is_some() {
1440            return selected.unwrap_or_else(|| {
1441                panic!("BUG: dynamic import '{slot}' hop without a selected body")
1442            });
1443        }
1444        row
1445    }
1446
1447    /// The instance a read of `uses` slot `slot` of this plan lands on, as read on
1448    /// `holder` (`None` for the plan's own context). A global slot reads the request's one
1449    /// instance of that global ([`RequestGlobals::instance`]). `selected` is the body
1450    /// evaluation selected for a `-> effective` slot on `holder`.
1451    pub(crate) fn import_key(
1452        &self,
1453        holder: Option<&InstanceKey>,
1454        slot: &DataPath,
1455        selected: Option<&Arc<RowInstance>>,
1456        globals: &RequestGlobals,
1457    ) -> InstanceKey {
1458        if let Some(DataDefinition::Import {
1459            global: Some(key), ..
1460        }) = self.data.get(slot)
1461        {
1462            return globals.instance(key);
1463        }
1464        InstanceKey::new(Arc::clone(self.import_row(slot, selected)), holder.cloned())
1465    }
1466
1467    /// The instances the global slots of a request of this plan read: the rows of its
1468    /// `global.x` slots.
1469    pub(crate) fn request_globals(&self) -> RequestGlobals {
1470        RequestGlobals {
1471            roots: self
1472                .data
1473                .iter()
1474                .filter_map(|(path, definition)| match definition {
1475                    DataDefinition::Import {
1476                        global: Some(key),
1477                        row,
1478                        ..
1479                    } if crate::planning::semantics::is_global_slot_name(&path.data) => {
1480                        Some((key.clone(), Arc::clone(row)))
1481                    }
1482                    _ => None,
1483                })
1484                .collect(),
1485        }
1486    }
1487
1488    /// Select the candidate body of a dynamic import active at `at`.
1489    pub(crate) fn select_dynamic_import_row(
1490        &self,
1491        slot: &DataPath,
1492        at: &crate::parsing::ast::EffectiveDate,
1493    ) -> Option<&Arc<RowInstance>> {
1494        let DataDefinition::Import {
1495            pin: Some(_),
1496            candidates,
1497            ..
1498        } = self.data.get(slot)?
1499        else {
1500            return None;
1501        };
1502        candidates
1503            .iter()
1504            .filter(|(identity, _)| identity.slice <= *at)
1505            .max_by(|a, b| a.0.slice.cmp(&b.0.slice))
1506            .map(|(_, row)| row)
1507    }
1508
1509    /// Every [`Self::data`] slot that is not an Import marker: the members show and
1510    /// the row field sets expose.
1511    pub(crate) fn input_slots(&self) -> impl Iterator<Item = (&DataPath, &DataDefinition)> {
1512        self.data
1513            .iter()
1514            .filter(|(_, definition)| !matches!(definition, DataDefinition::Import { .. }))
1515    }
1516
1517    /// Row-suppliable slots a read of `end` on a row of this plan touches: the slot
1518    /// `end` is, or every slot the rule `end` names (or the data reference `end`
1519    /// resolves to) reads. `unbound` marks slots the spec gives no value: a row
1520    /// appended inline must write each of them.
1521    pub(crate) fn row_end_reads(&self, end: &RowEnd) -> Vec<RowFieldRead> {
1522        let rule_reads = |rule: &RulePath| -> Vec<&DataPath> {
1523            let rule_pos = u32::try_from(self.rules.get_index_of(rule).unwrap_or_else(|| {
1524                panic!(
1525                    "BUG: row rule '{rule}' missing from plan '{}'",
1526                    self.spec_name
1527                )
1528            }))
1529            .expect("BUG: rule count exceeds u32");
1530            self.needed_by_rules
1531                .iter()
1532                .enumerate()
1533                .filter(|(_, consumers)| consumers.rules.contains(&rule_pos))
1534                .map(|(data_pos, _)| {
1535                    self.data
1536                        .get_index(data_pos)
1537                        .expect("BUG: needed_by_rules position outside plan.data")
1538                        .0
1539                })
1540                .collect()
1541        };
1542        let slots: Vec<&DataPath> = match end {
1543            RowEnd::Data(path) => match self.reference_ends.get(path) {
1544                Some(ReferenceEnd::Rule(rule)) => rule_reads(rule),
1545                Some(ReferenceEnd::Promptable(_)) | None => {
1546                    self.bindable_row_field(path).into_iter().collect()
1547                }
1548            },
1549            RowEnd::Rule(rule) => rule_reads(rule),
1550        };
1551        slots
1552            .into_iter()
1553            .map(|slot| RowFieldRead {
1554                slot: slot.clone(),
1555                unbound: self.data[slot].value().is_none(),
1556            })
1557            .collect()
1558    }
1559
1560    /// Slot an evaluation-data row of this plan binds when a field read lands on
1561    /// `path`: the slot itself, or the end of its reference chain. `None` when the slot
1562    /// is bound by the spec, computed by a rule, or an instance marker.
1563    fn bindable_row_field<'a>(&'a self, path: &'a DataPath) -> Option<&'a DataPath> {
1564        match self
1565            .data
1566            .get(path)
1567            .unwrap_or_else(|| panic!("BUG: row field '{path}' absent from plan.data"))
1568        {
1569            DataDefinition::Value { .. }
1570            | DataDefinition::TypeDeclaration { .. }
1571            | DataDefinition::InstanceList { .. } => Some(path),
1572            DataDefinition::Reference { .. } => match self.reference_ends.get(path) {
1573                Some(ReferenceEnd::Promptable(target)) => Some(target),
1574                Some(ReferenceEnd::Rule(_)) => None,
1575                None => {
1576                    panic!("BUG: reference '{path}' missing from reference_ends after planning")
1577                }
1578            },
1579            DataDefinition::Import { .. } => None,
1580        }
1581        .filter(|target| !self.data[*target].is_bound())
1582    }
1583}
1584
1585/// Which row sizes a value. Two values of one row carry equal factors.
1586#[derive(Debug, Clone, PartialEq, Eq)]
1587enum RowOfValue {
1588    /// The current row of the list command at this level.
1589    Current(u32),
1590    /// The row reached from what `base` yields through the `uses` hops `path`.
1591    Member {
1592        base: NormalFormId,
1593        path: Vec<String>,
1594    },
1595    /// The row the branches of this cell pick: they read different rows.
1596    Picked(NormalFormId),
1597}
1598
1599/// Whether the values of a cell carry the unit factors of a row
1600/// ([`BoundValueKind::instance_factors`]).
1601#[derive(Debug, Clone, PartialEq, Eq)]
1602enum Carried {
1603    /// The cell is never a value.
1604    Never,
1605    /// A value of the cell may carry no factors.
1606    Nothing,
1607    /// Every value of the cell carries the factors of one row.
1608    Row(RowOfValue),
1609}
1610
1611impl Carried {
1612    /// Factors two operands agree on: those of the row both come from.
1613    fn agreed(self, other: Carried) -> Carried {
1614        if self == other {
1615            self
1616        } else {
1617            Carried::Nothing
1618        }
1619    }
1620}
1621
1622/// [`Carried`] of the value of `left op right`, a value of type `result`, as
1623/// [`crate::computation::arithmetic_operation`] passes factors on.
1624fn carried_through(
1625    op: ArithmeticComputation,
1626    result: &LemmaType,
1627    (left, left_type): (Carried, &LemmaType),
1628    (right, right_type): (Carried, &LemmaType),
1629) -> Carried {
1630    if left == Carried::Never || right == Carried::Never {
1631        return Carried::Never;
1632    }
1633    if !result.is_measure() || left_type.is_calendar_like() || right_type.is_calendar_like() {
1634        return Carried::Nothing;
1635    }
1636    match (left_type.is_measure(), right_type.is_measure()) {
1637        (true, true) => match op {
1638            ArithmeticComputation::Add | ArithmeticComputation::Subtract => left.agreed(right),
1639            _ if left_type.same_measure_family(right_type) => left.agreed(right),
1640            _ => Carried::Nothing,
1641        },
1642        (true, false) => left,
1643        (false, true)
1644            if matches!(op, ArithmeticComputation::Multiply)
1645                && (left_type.is_number() || left_type.is_ratio()) =>
1646        {
1647            right
1648        }
1649        (false, _) => Carried::Nothing,
1650    }
1651}
1652
1653/// The cells [`carried_by`] reads for cell `id`.
1654fn carried_operands(plan: &ExecutionPlan, id: NormalFormId) -> Vec<NormalFormId> {
1655    use crate::planning::normalize::{LeafKind, NormalFormKind, NormalFormListOp};
1656
1657    let rule_root = |rule: &RulePath| {
1658        plan.rules
1659            .get(rule)
1660            .unwrap_or_else(|| panic!("BUG: read rule '{rule}' missing from plan"))
1661            .normal_form
1662    };
1663    // A rule read is the value of the rule.
1664    if let Some(rule) = &plan.normal_form(id).rule_ref {
1665        return vec![rule_root(rule)];
1666    }
1667    match &plan.normal_form(id).kind {
1668        NormalFormKind::Sum(terms) | NormalFormKind::Product(terms) => {
1669            terms.iter().map(|term| term.operand).collect()
1670        }
1671        NormalFormKind::Subtract(left, right)
1672        | NormalFormKind::Divide(left, right)
1673        | NormalFormKind::Power(left, right) => vec![*left, *right],
1674        NormalFormKind::UnitConversion(inner, _) => vec![*inner],
1675        NormalFormKind::Piecewise(arms) => arms.iter().map(|(_, body)| *body).collect(),
1676        // The scrutinee, then every region body.
1677        kind @ NormalFormKind::OrderedDispatch { .. } => {
1678            let mut children = Vec::new();
1679            kind.for_each_child(|child| children.push(child));
1680            children.split_off(1)
1681        }
1682        NormalFormKind::ListCommand {
1683            op: NormalFormListOp::Avg,
1684            args,
1685            row_level: Some(_),
1686            ..
1687        } => args.clone(),
1688        NormalFormKind::Leaf(LeafKind::DataPath(path)) => match plan.reference_ends.get(path) {
1689            Some(ReferenceEnd::Rule(rule)) => vec![rule_root(rule)],
1690            Some(ReferenceEnd::Promptable(end)) => plan
1691                .member_targets
1692                .get(&ReferenceTarget::Data(end.clone()))
1693                .copied()
1694                .into_iter()
1695                .collect(),
1696            None => Vec::new(),
1697        },
1698        _ => Vec::new(),
1699    }
1700}
1701
1702/// [`Carried`] of cell `id`, `known` holding that of its [`carried_operands`].
1703fn carried_by(
1704    plan: &ExecutionPlan,
1705    id: NormalFormId,
1706    known: &HashMap<NormalFormId, Carried>,
1707) -> Carried {
1708    use crate::planning::normalize::{NormalFormKind, NormalFormListOp};
1709
1710    let of = |cell: NormalFormId| known[&cell].clone();
1711    let typed = |cell: NormalFormId| (of(cell), plan.result_type(cell).as_ref());
1712    let result = plan.result_type(id).as_ref();
1713    if plan.normal_form(id).rule_ref.is_some() {
1714        return of(carried_operands(plan, id)[0]);
1715    }
1716    let read_of = |row: RowOfValue| {
1717        if result.is_measure() || result.is_measure_range() {
1718            Carried::Row(row)
1719        } else {
1720            Carried::Nothing
1721        }
1722    };
1723    match &plan.normal_form(id).kind {
1724        NormalFormKind::Veto(_) => Carried::Never,
1725        NormalFormKind::RowField { level, .. } => read_of(RowOfValue::Current(*level)),
1726        NormalFormKind::SpecMember { base, path, .. } => read_of(RowOfValue::Member {
1727            base: *base,
1728            path: path.clone(),
1729        }),
1730        kind @ (NormalFormKind::Sum(terms) | NormalFormKind::Product(terms)) => {
1731            let (direct, inverse) = match kind {
1732                NormalFormKind::Sum(_) => {
1733                    (ArithmeticComputation::Add, ArithmeticComputation::Subtract)
1734                }
1735                _ => (
1736                    ArithmeticComputation::Multiply,
1737                    ArithmeticComputation::Divide,
1738                ),
1739            };
1740            let fold_types = &plan.normal_form(id).fold_types;
1741            let mut carried = of(terms[0].operand);
1742            for (index, term) in terms.iter().enumerate().skip(1) {
1743                let op = if term.inverse { &inverse } else { &direct };
1744                carried = carried_through(
1745                    op.clone(),
1746                    &fold_types[index],
1747                    (carried, &fold_types[index - 1]),
1748                    typed(term.operand),
1749                );
1750            }
1751            carried
1752        }
1753        NormalFormKind::Subtract(left, right) => carried_through(
1754            ArithmeticComputation::Subtract,
1755            result,
1756            typed(*left),
1757            typed(*right),
1758        ),
1759        NormalFormKind::Divide(left, right) => carried_through(
1760            ArithmeticComputation::Divide,
1761            result,
1762            typed(*left),
1763            typed(*right),
1764        ),
1765        NormalFormKind::Power(left, right) => carried_through(
1766            ArithmeticComputation::Power,
1767            result,
1768            typed(*left),
1769            typed(*right),
1770        ),
1771        // A cast of a measure keeps its factors; every other cast starts without.
1772        NormalFormKind::UnitConversion(inner, target) => {
1773            let carried = of(*inner);
1774            let keeps = matches!(target, SemanticConversionTarget::Unit { .. })
1775                && plan.result_type(*inner).is_measure()
1776                && result.is_measure();
1777            if keeps || carried == Carried::Never {
1778                carried
1779            } else {
1780                Carried::Nothing
1781            }
1782        }
1783        NormalFormKind::Piecewise(_) | NormalFormKind::OrderedDispatch { .. } => {
1784            carried_operands(plan, id)
1785                .into_iter()
1786                .map(of)
1787                .filter(|branch| *branch != Carried::Never)
1788                .reduce(|first, next| match (&first, &next) {
1789                    (Carried::Row(_), Carried::Row(_)) if first != next => {
1790                        Carried::Row(RowOfValue::Picked(id))
1791                    }
1792                    _ => first.agreed(next),
1793                })
1794                .unwrap_or(Carried::Never)
1795        }
1796        // The average of what reads no row of its command: every row gives that value.
1797        NormalFormKind::ListCommand {
1798            op: NormalFormListOp::Avg,
1799            args,
1800            row_level: Some(level),
1801            ..
1802        } => match args.as_slice() {
1803            [arg] if plan.row_mask[arg.index()] & (1 << level) == 0 => of(*arg),
1804            _ => Carried::Nothing,
1805        },
1806        // A reference is the value of the rule or member it ends at.
1807        NormalFormKind::Leaf(_) => match carried_operands(plan, id).as_slice() {
1808            [end] => of(*end),
1809            _ => Carried::Nothing,
1810        },
1811        _ => Carried::Nothing,
1812    }
1813}
1814
1815/// [`Carried`] of cell `root`, added to `known` with every cell it is read from.
1816fn carried_factors(
1817    plan: &ExecutionPlan,
1818    root: NormalFormId,
1819    known: &mut HashMap<NormalFormId, Carried>,
1820) -> Carried {
1821    let mut stack: Vec<(NormalFormId, bool)> = vec![(root, false)];
1822    while let Some((id, operands_done)) = stack.pop() {
1823        if known.contains_key(&id) {
1824            continue;
1825        }
1826        if operands_done {
1827            let carried = carried_by(plan, id, known);
1828            known.insert(id, carried);
1829            continue;
1830        }
1831        stack.push((id, true));
1832        stack.extend(
1833            carried_operands(plan, id)
1834                .into_iter()
1835                .filter(|operand| !known.contains_key(operand))
1836                .map(|operand| (operand, false)),
1837        );
1838    }
1839    known[&root].clone()
1840}
1841
1842/// A conversion into or out of a unit sized by a row takes that size from the converted
1843/// value, read from one row, or from a row of an enclosing list command. A conversion
1844/// with neither names no row, and is a planning error.
1845fn check_rows_unit_conversions(plan: &ExecutionPlan) -> Result<(), Vec<Error>> {
1846    use crate::planning::normalize::NormalFormKind;
1847
1848    let mut errors = Vec::new();
1849    let mut known: HashMap<NormalFormId, Carried> = HashMap::new();
1850    let mut reported: HashSet<NormalFormId> = HashSet::new();
1851    // Cells with the row specs of the list commands around them.
1852    let mut seen: HashSet<(NormalFormId, BTreeSet<&SpecIdentity>)> = HashSet::new();
1853    for (rule_path, rule) in &plan.rules {
1854        let mut stack = vec![(rule.normal_form, BTreeSet::new())];
1855        while let Some((id, rows)) = stack.pop() {
1856            if !seen.insert((id, rows.clone())) {
1857                continue;
1858            }
1859            let cell = plan.normal_form(id);
1860            // A rule read is the rule's own work, checked from its root: no row of its
1861            // reader is around it.
1862            if cell.rule_ref.is_some() {
1863                continue;
1864            }
1865            if let NormalFormKind::UnitConversion(inner, target) = &cell.kind {
1866                let outside: Vec<ScaleTarget> = plan
1867                    .written_scale_targets(id)
1868                    .into_iter()
1869                    .filter(|scale| !plan.holds_scale_target(scale))
1870                    .collect();
1871                if !outside.is_empty() {
1872                    let (unit, owning_type) = scaled_unit(plan, *inner, target);
1873                    let rows_units = plan
1874                        .resolved_types
1875                        .unit_index
1876                        .rows_units_of(unit.as_str(), owning_type);
1877                    // The row specs of the lists the unit is of; none for a unit of the
1878                    // rows of a nested list, which has no name in this spec.
1879                    let unit_rows: Vec<&SpecIdentity> = rows_units
1880                        .iter()
1881                        .filter_map(|rows_unit| {
1882                            plan.instance_lists
1883                                .get(&DataPath::local(rows_unit.list.clone()))
1884                        })
1885                        .map(|source| &source.identity)
1886                        .collect();
1887                    let in_rows = outside.iter().all(|scale| {
1888                        rows.iter()
1889                            .filter(|identity| unit_rows.is_empty() || unit_rows.contains(identity))
1890                            .any(|identity| plan.row_template(identity).holds_scale_target(scale))
1891                    });
1892                    // Every instance of a global sizes its unit alike, so no row is
1893                    // needed: without a factor such a conversion vetoes.
1894                    let sized_by_a_row = outside
1895                        .iter()
1896                        .any(|scale| !sized_by_global(plan, &unit_rows, &scale.target));
1897                    if sized_by_a_row
1898                        && !in_rows
1899                        && carried_factors(plan, *inner, &mut known) == Carried::Nothing
1900                        && reported.insert(id)
1901                    {
1902                        errors.push(Error::validation(
1903                            rows_unit_conversion_message(
1904                                target,
1905                                &unit,
1906                                owning_type,
1907                                rows_units.first(),
1908                            ),
1909                            cell.source.clone(),
1910                            Some(format!("see rule '{rule_path}'")),
1911                        ));
1912                    }
1913                }
1914            }
1915            match &cell.kind {
1916                NormalFormKind::ListCommand {
1917                    list,
1918                    args,
1919                    row_level: Some(_),
1920                    ..
1921                } => {
1922                    let mut inner_rows = rows.clone();
1923                    // A value predicate has a row level over the values of a value list.
1924                    if let TypeSpecification::List { element, .. } =
1925                        &plan.result_type(*list).specifications
1926                    {
1927                        if let TypeSpecification::Spec { spec } = &element.specifications {
1928                            inner_rows.insert(spec);
1929                        }
1930                    }
1931                    stack.push((*list, rows));
1932                    stack.extend(args.iter().map(|arg| (*arg, inner_rows.clone())));
1933                }
1934                kind => kind.for_each_child(|child| stack.push((child, rows.clone()))),
1935            }
1936        }
1937    }
1938    if errors.is_empty() {
1939        Ok(())
1940    } else {
1941        Err(errors)
1942    }
1943}
1944
1945/// Whether the rows of `unit_rows` read scale `target` through a `uses global` of
1946/// their spec.
1947fn sized_by_global(
1948    plan: &ExecutionPlan,
1949    unit_rows: &[&SpecIdentity],
1950    target: &ReferenceTarget,
1951) -> bool {
1952    let Some(hop) = reference_target_segments(target).first() else {
1953        return false;
1954    };
1955    let alias = DataPath::local(hop.uses.to_string());
1956    unit_rows.iter().any(|identity| {
1957        matches!(
1958            plan.row_template(identity).data.get(&alias),
1959            Some(DataDefinition::Import {
1960                global: Some(_),
1961                ..
1962            })
1963        )
1964    })
1965}
1966
1967/// The unit whose scales the conversion of cell `inner` to `target` reads, and the type
1968/// declaring it there: the target's, or for `as number` the source's.
1969fn scaled_unit<'a>(
1970    plan: &'a ExecutionPlan,
1971    inner: NormalFormId,
1972    target: &'a SemanticConversionTarget,
1973) -> (String, &'a LemmaType) {
1974    match target {
1975        SemanticConversionTarget::Unit {
1976            unit_name,
1977            owning_type,
1978        } => (unit_name.clone(), owning_type.as_ref()),
1979        SemanticConversionTarget::Type(ConversionTypeKind::Number) => {
1980            let source = plan.result_type(inner).as_ref();
1981            let (unit, _) = source
1982                .measure_runtime_signature()
1983                .into_iter()
1984                .next()
1985                .expect("BUG: `as number` reading a scale counts in a unit of its source");
1986            (unit, source)
1987        }
1988        SemanticConversionTarget::Type(kind) => {
1989            unreachable!("BUG: a conversion to {kind:?} reads no unit scale")
1990        }
1991    }
1992}
1993
1994/// Why a conversion to `target`, reading the scales of `unit` of `owning_type`, names
1995/// no row to take them from. `rows_unit` is `None` for a unit of the rows of a nested
1996/// list.
1997fn rows_unit_conversion_message(
1998    target: &SemanticConversionTarget,
1999    unit: &str,
2000    owning_type: &LemmaType,
2001    rows_unit: Option<&RowsUnit>,
2002) -> String {
2003    match (rows_unit, target) {
2004        (Some(rows_unit), SemanticConversionTarget::Unit { .. }) => {
2005            rows_unit.converts_no_row_value()
2006        }
2007        (Some(rows_unit), SemanticConversionTarget::Type(_)) => rows_unit.counts_no_row_value(),
2008        (None, _) => format!(
2009            "Unit '{unit}' of `{}` is sized by the rows of a list, and the converted value names no single row to take its size from. Convert a value read from one row, or convert in the argument of a command over the rows.",
2010            owning_type.name()
2011        ),
2012    }
2013}
2014
2015/// In the arguments of a list command, a literal or conversion written in a unit sized by
2016/// the row reads the row though it reads none of its fields: every cell on the way to it
2017/// takes the command's level in [`ExecutionPlan::row_mask`].
2018fn mark_row_unit_cells(plan: &mut ExecutionPlan) {
2019    use crate::planning::normalize::NormalFormKind;
2020
2021    let mut marks: Vec<(usize, u32)> = Vec::new();
2022    for cell in &plan.normal_forms {
2023        let NormalFormKind::ListCommand {
2024            list,
2025            args,
2026            row_level: Some(level),
2027            ..
2028        } = &cell.kind
2029        else {
2030            continue;
2031        };
2032        let TypeSpecification::List { element, .. } = &plan.result_type(*list).specifications
2033        else {
2034            panic!("BUG: a row command reads a list");
2035        };
2036        // A value predicate has a row level over the values of a value list.
2037        let TypeSpecification::Spec { spec } = &element.specifications else {
2038            continue;
2039        };
2040        let rows = plan.row_template(spec);
2041        // Whether each cell of the arguments names a unit of the rows, children first.
2042        let mut names: HashMap<NormalFormId, bool> = HashMap::new();
2043        let mut stack: Vec<(NormalFormId, bool)> = args.iter().map(|arg| (*arg, false)).collect();
2044        while let Some((id, children_done)) = stack.pop() {
2045            if names.contains_key(&id) {
2046                continue;
2047            }
2048            // A rule read in an argument is the rule's own work.
2049            if plan.normal_form(id).rule_ref.is_some() {
2050                names.insert(id, false);
2051                continue;
2052            }
2053            let kind = &plan.normal_form(id).kind;
2054            if !children_done {
2055                stack.push((id, true));
2056                kind.for_each_child(|child| {
2057                    if !names.contains_key(&child) {
2058                        stack.push((child, false));
2059                    }
2060                });
2061                continue;
2062            }
2063            let mut named = plan
2064                .written_scale_targets(id)
2065                .iter()
2066                .any(|target| !plan.holds_scale_target(target) && rows.holds_scale_target(target));
2067            kind.for_each_child(|child| named |= names[&child]);
2068            names.insert(id, named);
2069            if named {
2070                marks.push((id.index(), *level));
2071            }
2072        }
2073    }
2074    for (index, level) in marks {
2075        plan.row_mask[index] |= 1u32
2076            .checked_shl(level)
2077            .expect("BUG: row masks bound the levels of a plan");
2078    }
2079}
2080
2081/// Nesting of list commands a plan supports: one bit per level in [`ExecutionPlan::row_mask`].
2082const MAX_ROW_LEVELS: u32 = u32::BITS;
2083
2084/// [`ExecutionPlan::row_mask`]: a list-row leaf (`RowField` or `RowValue`) sets its
2085/// level, a list command clears its own level, every other cell takes the union of
2086/// its children.
2087fn build_row_mask(normal_forms: &[NormalForm]) -> Result<Vec<u32>, Error> {
2088    use crate::planning::normalize::{LeafKind, NormalFormKind};
2089
2090    let mut mask: Vec<Option<u32>> = vec![None; normal_forms.len()];
2091    let mut stack: Vec<(usize, bool)> = Vec::new();
2092    for root in 0..normal_forms.len() {
2093        if mask[root].is_some() {
2094            continue;
2095        }
2096        stack.push((root, false));
2097        while let Some((index, children_done)) = stack.pop() {
2098            if mask[index].is_some() {
2099                continue;
2100            }
2101            let cell = &normal_forms[index];
2102            if !children_done {
2103                stack.push((index, true));
2104                cell.kind.for_each_child(|child| {
2105                    if mask[child.index()].is_none() {
2106                        stack.push((child.index(), false));
2107                    }
2108                });
2109                continue;
2110            }
2111            let mut union = 0u32;
2112            cell.kind.for_each_child(|child| {
2113                union |= mask[child.index()]
2114                    .expect("BUG: child row mask missing after post-order visit");
2115            });
2116            let level = match &cell.kind {
2117                NormalFormKind::RowField { level, .. }
2118                | NormalFormKind::Leaf(LeafKind::RowValue { level }) => Some(*level),
2119                _ => None,
2120            };
2121            let bits = match (level, &cell.kind) {
2122                (Some(level), _) => {
2123                    if level >= MAX_ROW_LEVELS {
2124                        return Err(Error::validation(
2125                            format!(
2126                                "list commands nest {} levels deep; at most {MAX_ROW_LEVELS} are supported",
2127                                level + 1
2128                            ),
2129                            cell.source.clone(),
2130                            None::<String>,
2131                        ));
2132                    }
2133                    union | (1u32 << level)
2134                }
2135                (
2136                    None,
2137                    NormalFormKind::ListCommand {
2138                        row_level: Some(level),
2139                        ..
2140                    },
2141                ) if *level < MAX_ROW_LEVELS => union & !(1u32 << level),
2142                (None, _) => union,
2143            };
2144            mask[index] = Some(bits);
2145        }
2146    }
2147    Ok(mask
2148        .into_iter()
2149        .map(|bits| bits.expect("BUG: row mask missing for a cell"))
2150        .collect())
2151}
2152
2153/// What evaluating one input cell needs: a data slot or a rule.
2154enum InputNeed {
2155    Data(DataPath),
2156    Rule(RulePath),
2157}
2158
2159/// Pass-1 accumulator of [`ExecutionPlan::build_needed_by_rules`] for one rule.
2160struct NeedsMarker<'a> {
2161    plan: &'a ExecutionPlan,
2162    rule_pos: usize,
2163    bits: &'a mut [u64],
2164    bits_by_rule: &'a [Vec<u64>],
2165}
2166
2167impl NeedsMarker<'_> {
2168    fn mark(&mut self, need: InputNeed) {
2169        match need {
2170            InputNeed::Rule(rule) => {
2171                let ref_pos =
2172                    self.plan.rules.get_index_of(&rule).unwrap_or_else(|| {
2173                        panic!("BUG: needed rule '{rule}' missing from plan.rules")
2174                    });
2175                if ref_pos >= self.rule_pos {
2176                    panic!(
2177                        "BUG: needed rule '{rule}' must precede '{}' in topo order",
2178                        self.plan.rules[self.rule_pos].path
2179                    );
2180                }
2181                for (word, dep_word) in self.bits.iter_mut().zip(&self.bits_by_rule[ref_pos]) {
2182                    *word |= *dep_word;
2183                }
2184            }
2185            InputNeed::Data(path) => {
2186                let data_pos =
2187                    self.plan.data.get_index_of(&path).unwrap_or_else(|| {
2188                        panic!("BUG: needed data '{path}' missing from plan.data")
2189                    });
2190                self.bits[data_pos / 64] |= 1u64 << (data_pos % 64);
2191            }
2192        }
2193    }
2194
2195    fn mark_scale_target(&mut self, stack: &mut Vec<NormalFormId>, target: &ReferenceTarget) {
2196        if let Some(&cell) = self.plan.member_targets.get(target) {
2197            stack.push(cell);
2198            return;
2199        }
2200        let segments = reference_target_segments(target);
2201        if segments.is_empty() {
2202            match target {
2203                ReferenceTarget::Rule(rule) => self.mark(InputNeed::Rule(rule.clone())),
2204                ReferenceTarget::Data(path) => {
2205                    if let Some(need) = self.plan.data_read_needs(path) {
2206                        self.mark(need);
2207                    }
2208                }
2209            }
2210            return;
2211        }
2212        // Uses-qualified target that is a `uses` Import of this plan must have a
2213        // member cell. A first hop that is not this plan's import (list name, nested
2214        // element's uses) settles in that row template — not as a SpecMember here.
2215        if first_hop_is_uses_import(&self.plan.data, target) {
2216            panic!(
2217                "BUG: uses-qualified scale target '{target}' missing from member_targets of plan '{}'",
2218                self.plan.spec_name
2219            );
2220        }
2221    }
2222}
2223
2224/// Ensure every [`ExecutionPlan::data`] path has a [`LeafKind::DataPath`] cell in `normal_forms`
2225/// and return the path → id index. Expression lowering already creates leaves for
2226/// referenced paths; unused paths get orphan leaves appended so evaluation can
2227/// still store bindings/defaults/reference copies in the value table.
2228///
2229/// Rule reference cells share a body's Kind, so a `Leaf(DataPath)` cell may carry
2230/// `rule_ref`. Those cells hold the referenced rule's value in the value table and
2231/// must never be the binding slot for the path.
2232///
2233/// Fold survivors also share a body's Kind and carry `origin` (identity elim of
2234/// `x * 1` → DataPath `x` with the Product as pre-image). Those cells are the
2235/// rule body's explanation root, not the binding slot: intake must land on the
2236/// origin-free leaf so an explain walk still visits the pre-image.
2237fn ensure_data_leaves(
2238    normal_forms: &mut Vec<NormalForm>,
2239    input_keys: &[DataPath],
2240    data: &IndexMap<DataPath, DataDefinition>,
2241) -> IndexMap<DataPath, NormalFormId> {
2242    use crate::planning::normalize::LeafKind;
2243    use crate::planning::normalize::NormalFormKind;
2244
2245    let mut data_leaf: IndexMap<DataPath, NormalFormId> = IndexMap::new();
2246    for (index, cell) in normal_forms.iter().enumerate() {
2247        if cell.rule_ref.is_some() || cell.origin.is_some() {
2248            continue;
2249        }
2250        if let NormalFormKind::Leaf(LeafKind::DataPath(path)) = &cell.kind {
2251            data_leaf.insert(path.clone(), NormalFormId::from_index(index));
2252        }
2253    }
2254    for path in input_keys {
2255        if data_leaf.contains_key(path) {
2256            continue;
2257        }
2258        let id = NormalFormId::from_index(normal_forms.len());
2259        normal_forms.push(NormalForm {
2260            kind: NormalFormKind::Leaf(LeafKind::DataPath(path.clone())),
2261            result_type: data_path_result_type(data, path),
2262            fold_types: Vec::new(),
2263            source: None,
2264            origin: None,
2265            rule_ref: None,
2266        });
2267        data_leaf.insert(path.clone(), id);
2268    }
2269    data_leaf
2270}
2271
2272/// Fill show/response cache fields that are pure functions of the plan and its
2273/// owning LemmaSpec / LemmaSpecSet. Called once after [`build_execution_plan`]
2274/// succeeds so [`Engine::show`] / [`Engine::evaluate`] only look up the plan.
2275pub(crate) fn attach_show_cache(
2276    plan: &mut ExecutionPlan,
2277    lemma_spec_set: &LemmaSpecSet,
2278    spec: &LemmaSpec,
2279) {
2280    let (effective_from, effective_to) = lemma_spec_set.effective_range(spec);
2281    plan.effective_from = effective_from;
2282    plan.effective_to = effective_to;
2283    plan.start_line = spec.start_line;
2284    plan.source_type = spec.source_type.clone();
2285    plan.data_display = build_data_display(plan);
2286}
2287
2288fn build_data_display(plan: &ExecutionPlan) -> IndexMap<DataPath, ShowDataCache> {
2289    let mut out = IndexMap::new();
2290    for (path, data) in &plan.data {
2291        insert_data_display_entry(&mut out, path, data);
2292    }
2293    out
2294}
2295
2296fn insert_data_display_entry(
2297    out: &mut IndexMap<DataPath, ShowDataCache>,
2298    path: &DataPath,
2299    data: &DataDefinition,
2300) {
2301    if data.schema_type().is_none() || matches!(data, DataDefinition::Reference { .. }) {
2302        return;
2303    }
2304    let value = match data {
2305        DataDefinition::Value {
2306            value,
2307            resolved_type,
2308            ..
2309        } => Some(BoundValueKind {
2310            value: value.value.clone(),
2311            unit: resolved_type.unit().map(Arc::from),
2312            instance_factors: None,
2313        }),
2314        _ => data.bound_value().cloned(),
2315    };
2316    let suggestion = data.bound_suggestion().cloned();
2317    if value.is_some() || suggestion.is_some() {
2318        out.insert(path.clone(), ShowDataCache { value, suggestion });
2319    }
2320}
2321
2322/// Whether a show bound value is the fill or the suggestion for a data path.
2323#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2324pub(crate) enum ShowBoundRole {
2325    Value,
2326    Suggestion,
2327}
2328
2329pub(crate) fn show_bound_result_value(
2330    bound: &BoundValueKind,
2331    schema_type: &LemmaType,
2332    input_key: &str,
2333    role: ShowBoundRole,
2334) -> RuleResultValue {
2335    let (fill, suggestion) = match role {
2336        ShowBoundRole::Value => (Some(bound), None),
2337        ShowBoundRole::Suggestion => (None, Some(bound)),
2338    };
2339    let display_type = lemma_type_with_display_binding(schema_type, None, fill, suggestion);
2340    type_scoped_result_value_from_literal(&bound.to_literal(), &display_type)
2341        .unwrap_or_else(|failure| {
2342            let role_name = match role {
2343                ShowBoundRole::Value => "value",
2344                ShowBoundRole::Suggestion => "suggestion",
2345            };
2346            panic!(
2347                "BUG: show {role_name} value for '{input_key}' failed type_scoped_result_value_from_literal: {}",
2348                rule_result_value_failure_message(failure)
2349            )
2350        })
2351}
2352
2353/// Show value of instance list `path`: its spec-written rows in order, each with the
2354/// fields the row binds and no `result` (a row has no value of its own to display).
2355/// Literal fields carry their value; referenced fields carry
2356/// [`RuleResultValue::reference`]. `None` when the list has no spec-written rows.
2357pub(crate) fn show_instance_list_value(
2358    plan: &ExecutionPlan,
2359    path: &DataPath,
2360) -> Option<RuleResultValue> {
2361    let source = plan
2362        .instance_lists
2363        .get(path)
2364        .expect("BUG: instance list data without a source");
2365    if source.store.rows.is_empty() {
2366        return None;
2367    }
2368    let template = plan
2369        .row_templates
2370        .get(&source.identity)
2371        .expect("BUG: list with spec-written rows has a row template");
2372    let mut items = Vec::with_capacity(source.store.rows.len());
2373    for (index, row) in source.store.rows.iter().enumerate() {
2374        // A copy shows the fields of what it copies (rule 4).
2375        let copied = plan
2376            .writes
2377            .copy_of(&[path.data.clone(), (index + 1).to_string()], row);
2378        let mut fields =
2379            show_written_row_fields(copied.map_or(row.as_ref(), AsRef::as_ref), template);
2380        // What the plan writes through the row (`-> with item.price: 3`).
2381        let at = [path.data.clone(), (index + 1).to_string()];
2382        for (instance, write) in plan.writes.iter() {
2383            let Some(below) = instance.strip_prefix(at.as_slice()) else {
2384                continue;
2385            };
2386            let key: String = below
2387                .iter()
2388                .map(String::as_str)
2389                .chain(std::iter::once(write.field.data.as_str()))
2390                .collect::<Vec<_>>()
2391                .join(".");
2392            let value = match &write.binding {
2393                RowBinding::Bound(OperationResult::Value(bound)) => {
2394                    let schema = plan
2395                        .row_template(&write.spec)
2396                        .data
2397                        .get(&write.field)
2398                        .and_then(DataDefinition::resolved_type_arc)
2399                        .expect("BUG: a written field has a resolved type");
2400                    show_bound_result_value(bound, schema, &key, ShowBoundRole::Value)
2401                }
2402                RowBinding::Bound(OperationResult::Veto(_)) => {
2403                    unreachable!("BUG: a written literal is never a Veto")
2404                }
2405                RowBinding::Deferred { target } => RuleResultValue {
2406                    reference: Some(match target {
2407                        ReferenceTarget::Data(target) => target.input_key(),
2408                        ReferenceTarget::Rule(target) => target.input_key(),
2409                    }),
2410                    ..Default::default()
2411                },
2412            };
2413            fields.insert(key, value);
2414        }
2415        items.push(RuleResultValue {
2416            fields: Some(fields),
2417            ..Default::default()
2418        });
2419    }
2420    Some(RuleResultValue {
2421        list: Some(items),
2422        ..Default::default()
2423    })
2424}
2425
2426/// Fields a spec-written row binds, keyed by their path under the row.
2427fn show_written_row_fields(
2428    row: &RowInstance,
2429    template: &ExecutionPlan,
2430) -> IndexMap<String, RuleResultValue> {
2431    let mut fields = IndexMap::new();
2432    for (slot, binding) in row.bindings.iter().enumerate() {
2433        let Some(binding) = binding else {
2434            continue;
2435        };
2436        let (field_path, definition) = template
2437            .data
2438            .get_index(slot)
2439            .expect("BUG: row binding slot is template data");
2440        let key = field_path.input_key();
2441        let value = match binding {
2442            RowBinding::Bound(OperationResult::Value(bound)) => {
2443                let schema = definition
2444                    .resolved_type_arc()
2445                    .expect("BUG: stored row bound field has a resolved type");
2446                show_bound_result_value(bound, schema, &key, ShowBoundRole::Value)
2447            }
2448            RowBinding::Bound(OperationResult::Veto(_)) => {
2449                unreachable!("BUG: stored row literal binding is never a Veto")
2450            }
2451            RowBinding::Deferred { target } => RuleResultValue {
2452                reference: Some(match target {
2453                    ReferenceTarget::Data(target) => target.input_key(),
2454                    ReferenceTarget::Rule(target) => target.input_key(),
2455                }),
2456                ..Default::default()
2457            },
2458        };
2459        fields.insert(key, value);
2460    }
2461    fields
2462}
2463
2464/// One data entry in a [`Show`].
2465///
2466/// A named struct instead of a tuple so JSON-native consumers (TypeScript, Python, ...)
2467/// get stable field names. `fill` is a spec literal or literal `with` binding;
2468/// `suggestion` is a `-> suggest ...` hint only.
2469/// Empty `needed_by_rules` means the slot is offered for reuse (`data x: alias.slot`),
2470/// not needed by this spec's remaining rules after normalize.
2471#[derive(Debug, Clone, PartialEq)]
2472pub struct ShowData {
2473    pub lemma_type: LemmaType,
2474    /// Import hops to this slot (`[]` = this spec). Clone of [`DataPath::segments`].
2475    pub path: Vec<PathSegment>,
2476    pub value: Option<RuleResultValue>,
2477    pub suggestion: Option<RuleResultValue>,
2478    /// Show.rules keys that transitively need this data after normalize.
2479    /// Show.data only includes slots where this is non-empty.
2480    pub needed_by_rules: Vec<String>,
2481    /// For an instance list whose `uses` writes on every row: those fields (rule 2), which
2482    /// are no inputs of its rows.
2483    pub list_writes: Option<ListWrites>,
2484}
2485
2486/// The fields the `uses` an instance list names writes on every row of it.
2487#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
2488pub struct ListWrites {
2489    /// The list: the spec declaring it and its name there. Unique among lists.
2490    pub list: String,
2491    /// Input keys of the fields, from the row. Evaluation data cannot supply them.
2492    pub fields: std::collections::BTreeSet<String>,
2493}
2494
2495/// What list `path` of `plan` writes on every row; `None` when it writes nothing.
2496pub(crate) fn show_list_writes(plan: &ExecutionPlan, path: &DataPath) -> Option<ListWrites> {
2497    let source = plan
2498        .instance_lists
2499        .get(path)
2500        .expect("BUG: instance list data without a source");
2501    let written = source.row_writes.as_ref()?;
2502    let template = if source.identity == plan.identity {
2503        plan
2504    } else {
2505        plan.row_template(&source.identity)
2506    };
2507    // The list is data of `plan` itself, so the `uses` it names has no holder above it.
2508    let uses = crate::planning::semantics::InstanceKey::new(Arc::clone(written), None);
2509    let writes = &plan.writes_by_spec;
2510    // The row's own fields, then the fields of instances inside it (`b.d`), as Show
2511    // lists them and as evaluation data for a row names them.
2512    let own = template
2513        .data
2514        .iter()
2515        .enumerate()
2516        .filter(|(_, (_, definition))| !matches!(definition, DataDefinition::Import { .. }))
2517        .filter(|&(slot, _)| {
2518            crate::evaluation::lookup::list_writes_field(
2519                &uses,
2520                None,
2521                template,
2522                slot,
2523                writes,
2524                &plan.identity,
2525            )
2526        })
2527        .map(|(_, (path, _))| path.input_key());
2528    let inside = template
2529        .show_import_data
2530        .keys()
2531        .map(DataPath::input_key)
2532        .filter(|key| {
2533            crate::evaluation::evaluate_data::list_writes_row_key(
2534                template,
2535                &uses,
2536                key,
2537                writes,
2538                &plan.identity,
2539            )
2540        });
2541    let fields: std::collections::BTreeSet<String> = own.chain(inside).collect();
2542    if fields.is_empty() {
2543        return None;
2544    }
2545    Some(ListWrites {
2546        list: format!("{}.{}", plan.identity, path.input_key()),
2547        fields,
2548    })
2549}
2550
2551impl ShowData {
2552    /// Whether this is data of a global: given once at the top, never in a row.
2553    #[must_use]
2554    pub fn is_global(&self) -> bool {
2555        crate::planning::semantics::reads_global(&self.path)
2556    }
2557}
2558
2559/// Consumer [`Engine::show`] result: local offered types, inputs rules need,
2560/// this spec's own rules (empty path), and resolved temporal window.
2561/// Source: [`Engine::source`]. Branch Rule leaves may name reachable imports that
2562/// are not keys of [`Self::rules`]; follow those via `show` on the imported spec.
2563#[derive(Debug, Clone, PartialEq)]
2564pub struct Show {
2565    /// Interned repository name (`specs()` string). `None` = unnamed workspace.
2566    pub repository: Option<String>,
2567    pub spec: String,
2568    pub commentary: Option<String>,
2569    pub effective_from: Option<DateTimeValue>,
2570    pub effective_to: Option<DateTimeValue>,
2571    /// Planning instant of the execution-plan slice that produced this Show.
2572    /// Distinguishes temporal dependency slices that share the same declared window.
2573    pub plan_effective: EffectiveDate,
2574    pub start_line: usize,
2575    pub source_type: Option<SourceType>,
2576    /// Local `data` declarations (empty path; type or value), declaration order.
2577    pub types: indexmap::IndexMap<String, LemmaType>,
2578    /// Inputs rules need (`needed_by_rules` non-empty), local or imported.
2579    pub data: indexmap::IndexMap<String, ShowData>,
2580    pub rules: indexmap::IndexMap<String, ShowRule>,
2581    /// Spec metadata, in declaration order.
2582    pub meta: IndexMap<String, Value>,
2583}
2584
2585impl std::fmt::Display for Show {
2586    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2587        match &self.repository {
2588            Some(repository) => write!(f, "Spec: {} {}", repository, self.spec)?,
2589            None => write!(f, "Spec: {}", self.spec)?,
2590        }
2591        write_effective_window(f, self.effective_from.as_ref(), self.effective_to.as_ref())?;
2592
2593        if let Some(commentary) = &self.commentary {
2594            for line in commentary.lines() {
2595                if line.is_empty() {
2596                    writeln!(f)?;
2597                } else {
2598                    write!(f, "\n  {line}")?;
2599                }
2600            }
2601        }
2602
2603        if !self.meta.is_empty() {
2604            write!(f, "\n\nMeta:")?;
2605            let mut entries: Vec<(&String, &Value)> = self.meta.iter().collect();
2606            entries.sort_by_key(|(k, _)| *k);
2607            for (key, value) in entries {
2608                write!(f, "\n  {}: {}", key, value)?;
2609            }
2610        }
2611
2612        if !self.types.is_empty() {
2613            write!(f, "\n\nTypes:")?;
2614            for (name, lemma_type) in &self.types {
2615                write!(f, "\n  {} ({})", name, lemma_type.specifications)?;
2616                for line in type_detail_lines(&lemma_type.specifications) {
2617                    write!(f, "\n    {}", line)?;
2618                }
2619                let help = lemma_type.specifications.help();
2620                if !help.is_empty() {
2621                    write!(f, "\n    help: {}", help)?;
2622                }
2623            }
2624        }
2625
2626        if !self.data.is_empty() {
2627            write!(f, "\n\nData:")?;
2628            for (name, entry) in &self.data {
2629                write!(f, "\n  {} ({})", name, entry.lemma_type.specifications)?;
2630                for line in type_detail_lines(&entry.lemma_type.specifications) {
2631                    write!(f, "\n    {}", line)?;
2632                }
2633                if let Some(line) = option_detail_line(&entry.lemma_type) {
2634                    write!(f, "\n    {}", line)?;
2635                }
2636                let help = entry.lemma_type.specifications.help();
2637                if !help.is_empty() {
2638                    write!(f, "\n    help: {}", help)?;
2639                }
2640                match &entry.value {
2641                    Some(RuleResultValue {
2642                        list: Some(rows), ..
2643                    }) if rows.iter().all(|row| row.fields.is_some()) => {
2644                        write!(f, "\n    value:")?;
2645                        for (index, row) in rows.iter().enumerate() {
2646                            let fields = row
2647                                .fields
2648                                .as_ref()
2649                                .expect("BUG: guard checked every row has fields")
2650                                .iter()
2651                                .map(|(name, field)| format!("{name} {field}"))
2652                                .collect::<Vec<_>>()
2653                                .join(", ");
2654                            write!(f, "\n      {}: {fields}", index + 1)?;
2655                        }
2656                    }
2657                    Some(val) => write!(f, "\n    value: {}", val)?,
2658                    None => {}
2659                }
2660                if let Some(val) = &entry.suggestion {
2661                    write!(f, "\n    suggestion: {}", val)?;
2662                }
2663                if !entry.needed_by_rules.is_empty() {
2664                    write!(
2665                        f,
2666                        "\n    needed_by_rules: {}",
2667                        entry.needed_by_rules.join(", ")
2668                    )?;
2669                }
2670            }
2671        }
2672
2673        if !self.rules.is_empty() {
2674            write!(f, "\n\nRules:")?;
2675            for (name, rule) in &self.rules {
2676                write!(f, "\n  {} ({})", name, rule.lemma_type.specifications)?;
2677                if !rule.depends_on_rules.is_empty() {
2678                    write!(
2679                        f,
2680                        "\n    depends_on_rules: {}",
2681                        rule.depends_on_rules
2682                            .iter()
2683                            .map(|path| path.input_key())
2684                            .collect::<Vec<_>>()
2685                            .join(", ")
2686                    )?;
2687                }
2688            }
2689        }
2690
2691        if self.types.is_empty() && self.data.is_empty() && self.rules.is_empty() {
2692            write!(f, "\n  (no types, data, or rules)")?;
2693        }
2694
2695        Ok(())
2696    }
2697}
2698
2699/// Produce a human-readable summary of type constraints, or `None` when there
2700/// are no constraints worth showing (e.g. bare `boolean`).
2701/// Returns one formatted string per constraint or property of the type specification.
2702/// Uses `display_str` for all rational bounds so they render as decimals,
2703/// not as raw fractions.
2704pub fn type_detail_lines(spec: &TypeSpecification) -> Vec<String> {
2705    let mut lines = Vec::new();
2706    match spec {
2707        TypeSpecification::Measure {
2708            minimum,
2709            maximum,
2710            units,
2711            ..
2712        } => {
2713            let unit_names: Vec<&str> = units.0.iter().map(|u| u.name.as_str()).collect();
2714            if !unit_names.is_empty() {
2715                lines.push(format!("units: {}", unit_names.join(", ")));
2716            }
2717            if let Some((magnitude, unit_name)) = minimum {
2718                lines.push(format!(
2719                    "minimum: {} {}",
2720                    magnitude.display_str(),
2721                    unit_name
2722                ));
2723            }
2724            if let Some((magnitude, unit_name)) = maximum {
2725                lines.push(format!(
2726                    "maximum: {} {}",
2727                    magnitude.display_str(),
2728                    unit_name
2729                ));
2730            }
2731        }
2732        TypeSpecification::Number {
2733            minimum,
2734            maximum,
2735            decimals,
2736            ..
2737        } => {
2738            if let Some(d) = decimals {
2739                lines.push(format!("decimals: {}", d));
2740            }
2741            if let Some(v) = minimum {
2742                lines.push(format!("minimum: {}", v.display_str()));
2743            }
2744            if let Some(v) = maximum {
2745                lines.push(format!("maximum: {}", v.display_str()));
2746            }
2747        }
2748        TypeSpecification::Ratio {
2749            minimum,
2750            maximum,
2751            units,
2752            ..
2753        } => {
2754            let unit_names: Vec<&str> = units.0.iter().map(|u| u.name.as_str()).collect();
2755            if !unit_names.is_empty() {
2756                lines.push(format!("units: {}", unit_names.join(", ")));
2757            }
2758            if let Some(v) = minimum {
2759                lines.push(format!("minimum: {}", v.display_str()));
2760            }
2761            if let Some(v) = maximum {
2762                lines.push(format!("maximum: {}", v.display_str()));
2763            }
2764        }
2765        TypeSpecification::Text { length, .. } => {
2766            if let Some(l) = length {
2767                lines.push(format!("length: {}", l));
2768            }
2769        }
2770        TypeSpecification::Date {
2771            minimum, maximum, ..
2772        } => {
2773            if let Some(v) = minimum {
2774                lines.push(format!("minimum: {}", v));
2775            }
2776            if let Some(v) = maximum {
2777                lines.push(format!("maximum: {}", v));
2778            }
2779        }
2780        TypeSpecification::Time {
2781            minimum, maximum, ..
2782        } => {
2783            if let Some(v) = minimum {
2784                lines.push(format!("minimum: {}", v));
2785            }
2786            if let Some(v) = maximum {
2787                lines.push(format!("maximum: {}", v));
2788            }
2789        }
2790        TypeSpecification::MeasureRange {
2791            lower,
2792            upper,
2793            minimum,
2794            maximum,
2795            units,
2796            ..
2797        } => {
2798            let unit_names: Vec<&str> = units.0.iter().map(|u| u.name.as_str()).collect();
2799            if !unit_names.is_empty() {
2800                lines.push(format!("units: {}", unit_names.join(", ")));
2801            }
2802            if let Some((magnitude, unit_name)) = lower {
2803                lines.push(format!("lower: {} {}", magnitude.display_str(), unit_name));
2804            }
2805            if let Some((magnitude, unit_name)) = upper {
2806                lines.push(format!("upper: {} {}", magnitude.display_str(), unit_name));
2807            }
2808            if let Some((magnitude, unit_name)) = minimum {
2809                lines.push(format!(
2810                    "minimum: {} {}",
2811                    magnitude.display_str(),
2812                    unit_name
2813                ));
2814            }
2815            if let Some((magnitude, unit_name)) = maximum {
2816                lines.push(format!(
2817                    "maximum: {} {}",
2818                    magnitude.display_str(),
2819                    unit_name
2820                ));
2821            }
2822        }
2823        TypeSpecification::RatioRange {
2824            lower,
2825            upper,
2826            minimum,
2827            maximum,
2828            units,
2829            ..
2830        } => {
2831            let unit_names: Vec<&str> = units.0.iter().map(|u| u.name.as_str()).collect();
2832            if !unit_names.is_empty() {
2833                lines.push(format!("units: {}", unit_names.join(", ")));
2834            }
2835            if let Some(v) = lower {
2836                lines.push(format!("lower: {}", v.display_str()));
2837            }
2838            if let Some(v) = upper {
2839                lines.push(format!("upper: {}", v.display_str()));
2840            }
2841            if let Some(v) = minimum {
2842                lines.push(format!("minimum: {}", v.display_str()));
2843            }
2844            if let Some(v) = maximum {
2845                lines.push(format!("maximum: {}", v.display_str()));
2846            }
2847        }
2848        TypeSpecification::NumberRange {
2849            lower,
2850            upper,
2851            minimum,
2852            maximum,
2853            ..
2854        } => {
2855            if let Some(v) = lower {
2856                lines.push(format!("lower: {}", v.display_str()));
2857            }
2858            if let Some(v) = upper {
2859                lines.push(format!("upper: {}", v.display_str()));
2860            }
2861            if let Some(v) = minimum {
2862                lines.push(format!("minimum: {}", v.display_str()));
2863            }
2864            if let Some(v) = maximum {
2865                lines.push(format!("maximum: {}", v.display_str()));
2866            }
2867        }
2868        TypeSpecification::DateRange {
2869            lower,
2870            upper,
2871            minimum,
2872            maximum,
2873            ..
2874        } => {
2875            if let Some(v) = lower {
2876                lines.push(format!("lower: {}", v));
2877            }
2878            if let Some(v) = upper {
2879                lines.push(format!("upper: {}", v));
2880            }
2881            if let Some((magnitude, unit_name)) = minimum {
2882                lines.push(format!(
2883                    "minimum: {} {}",
2884                    magnitude.display_str(),
2885                    unit_name
2886                ));
2887            }
2888            if let Some((magnitude, unit_name)) = maximum {
2889                lines.push(format!(
2890                    "maximum: {} {}",
2891                    magnitude.display_str(),
2892                    unit_name
2893                ));
2894            }
2895        }
2896        TypeSpecification::TimeRange {
2897            lower,
2898            upper,
2899            minimum,
2900            maximum,
2901            ..
2902        } => {
2903            if let Some(v) = lower {
2904                lines.push(format!("lower: {}", v));
2905            }
2906            if let Some(v) = upper {
2907                lines.push(format!("upper: {}", v));
2908            }
2909            if let Some((magnitude, unit_name)) = minimum {
2910                lines.push(format!(
2911                    "minimum: {} {}",
2912                    magnitude.display_str(),
2913                    unit_name
2914                ));
2915            }
2916            if let Some((magnitude, unit_name)) = maximum {
2917                lines.push(format!(
2918                    "maximum: {} {}",
2919                    magnitude.display_str(),
2920                    unit_name
2921                ));
2922            }
2923        }
2924        TypeSpecification::Boolean { .. }
2925        | TypeSpecification::Veto { .. }
2926        | TypeSpecification::Undetermined
2927        | TypeSpecification::Spec { .. } => {}
2928        TypeSpecification::List { element, key, help } => {
2929            lines.push(format!("element: {element}"));
2930            if !help.is_empty() {
2931                lines.push(format!("help: {help}"));
2932            }
2933            match key {
2934                crate::planning::semantics::ListKey::Numbered => {
2935                    lines.push("key: numbered".to_string());
2936                }
2937                crate::planning::semantics::ListKey::Fields(fields) => {
2938                    lines.push(format!(
2939                        "key: {}",
2940                        fields
2941                            .iter()
2942                            .map(|field| field.name.as_str())
2943                            .collect::<Vec<_>>()
2944                            .join(", ")
2945                    ));
2946                }
2947            }
2948        }
2949    }
2950    lines
2951}
2952
2953impl ExecutionPlan {
2954    /// Expression-scope unit index (local types plus direct `uses` imports).
2955    pub(crate) fn expression_unit_index(&self) -> &UnitIndex {
2956        &self.resolved_types.unit_index
2957    }
2958
2959    /// [`Self::show_needed_by`], each list in input-key order: a catalog rule needs the
2960    /// data it reads that no binding fills, the data `bits_by_rule` gives a local rule,
2961    /// and the needs of every rule it reads (including reachable imports walked in
2962    /// `show_order`). A local rule is not listed for the data `bits_by_rule` already
2963    /// gives it. Reader positions are catalog ([`Self::show_rules`]) indices only.
2964    fn build_show_needed_by(
2965        &self,
2966        show_order: &[RulePath],
2967        show_edges: &BTreeMap<RulePath, BTreeSet<RulePath>>,
2968        show_imports: &crate::planning::graph::ShowImports,
2969        bits_by_rule: &[Vec<u64>],
2970    ) -> IndexMap<DataPath, Vec<u32>> {
2971        let mut paths: indexmap::IndexSet<&DataPath> = self.data.keys().collect();
2972        for reads in show_imports.data_reads.values() {
2973            paths.extend(reads);
2974        }
2975        let words = paths.len().div_ceil(64);
2976        let mut needs: HashMap<&RulePath, Vec<u64>> = HashMap::with_capacity(show_order.len());
2977        for path in show_order {
2978            let mut bits = match self.rules.get_index_of(path) {
2979                Some(rule_pos) => {
2980                    let mut bits = bits_by_rule[rule_pos].clone();
2981                    bits.resize(words, 0);
2982                    bits
2983                }
2984                None => vec![0u64; words],
2985            };
2986            for read in show_imports.data_reads.get(path).into_iter().flatten() {
2987                let position = paths
2988                    .get_index_of(read)
2989                    .expect("BUG: Show data read indexed above");
2990                bits[position / 64] |= 1u64 << (position % 64);
2991            }
2992            let reads = match show_imports.need_edges.get(path) {
2993                Some(edges) => edges,
2994                None => &show_edges[path],
2995            };
2996            for dependency in reads {
2997                let dependency_bits = needs
2998                    .get(dependency)
2999                    .expect("BUG: Show dependency needs computed before its reader");
3000                for (word, dependency_word) in bits.iter_mut().zip(dependency_bits) {
3001                    *word |= *dependency_word;
3002                }
3003            }
3004            needs.insert(path, bits);
3005        }
3006        let mut readers: Vec<(usize, &RulePath)> = self.show_rules.keys().enumerate().collect();
3007        readers.sort_by_cached_key(|(_, path)| path.input_key());
3008        let mut lists: Vec<Vec<u32>> = vec![Vec::new(); paths.len()];
3009        for (rule_pos, path) in readers {
3010            let rule_pos = u32::try_from(rule_pos).expect("BUG: Show rule count exceeds u32");
3011            // `bits_by_rule` covers this plan's data only; import data is never listed.
3012            let listed: &[u64] = match self.rules.get_index_of(path) {
3013                Some(local_pos) => &bits_by_rule[local_pos],
3014                None => &[],
3015            };
3016            for (word_idx, &word) in needs[path].iter().enumerate() {
3017                let mut remaining = word & !listed.get(word_idx).copied().unwrap_or(0);
3018                while remaining != 0 {
3019                    let bit = remaining.trailing_zeros() as usize;
3020                    lists[word_idx * 64 + bit].push(rule_pos);
3021                    remaining &= remaining - 1;
3022                }
3023            }
3024        }
3025        paths
3026            .into_iter()
3027            .zip(lists)
3028            .filter(|(_, list)| !list.is_empty())
3029            .map(|(path, list)| (path.clone(), list))
3030            .collect()
3031    }
3032
3033    /// Per [`Self::data`] position: [`Self::rules`] positions that transitively
3034    /// need that slot (through rule references). Row-field columns are sized and left
3035    /// empty for [`Self::fill_row_field_needs`]. Returns the per-rule data-slot bitsets.
3036    ///
3037    /// Built in plan topological order: at a rule-ref cell, OR the target rule's
3038    /// already-computed bitsets instead of descending Kind (rule references are
3039    /// evaluation boundaries). Walks the normalized body so constant-dead unless
3040    /// arms removed by normalize stay out of the index. Fields read on
3041    /// evaluation-data rows land on the instance-list slot's [`NeededByRules::fields`]
3042    /// column; fields read on spec-written rows are ordinary slots of this plan.
3043    fn build_needed_by_rules(&mut self) -> Vec<Vec<u64>> {
3044        use crate::planning::normalize::{LeafKind, NormalFormKind};
3045
3046        let data_len = self.data.len();
3047        let words = data_len.div_ceil(64);
3048        let mut bits_by_rule: Vec<Vec<u64>> = Vec::with_capacity(self.rules.len());
3049
3050        let mut visited = HashSet::new();
3051        let mut stack = Vec::new();
3052
3053        // Pass 1: data-slot bitsets (topo / rule_ref OR). Evaluation-data row reads ignored here.
3054        for (rule_pos, (_, rule)) in self.rules.iter().enumerate() {
3055            let mut bits = vec![0u64; words];
3056            visited.clear();
3057            stack.push(rule.normal_form);
3058            {
3059                let mut needs = NeedsMarker {
3060                    plan: self,
3061                    rule_pos,
3062                    bits: &mut bits,
3063                    bits_by_rule: &bits_by_rule,
3064                };
3065                for scale in &rule.scale_dependencies {
3066                    needs.mark_scale_target(&mut stack, &scale.target);
3067                }
3068            }
3069            while let Some(id) = stack.pop() {
3070                if !visited.insert(id) {
3071                    continue;
3072                }
3073                let nf = self.normal_form(id);
3074                let mut needs = NeedsMarker {
3075                    plan: self,
3076                    rule_pos,
3077                    bits: &mut bits,
3078                    bits_by_rule: &bits_by_rule,
3079                };
3080                if let Some(ref_path) = &nf.rule_ref {
3081                    needs.mark(InputNeed::Rule(ref_path.clone()));
3082                    continue;
3083                }
3084                match &nf.kind {
3085                    NormalFormKind::Leaf(LeafKind::DataPath(path)) => {
3086                        // Local slots only. Uses-qualified paths are SpecMember /
3087                        // member-target cells; `data_read_needs` keys `plan.data` by
3088                        // local name and must not see nested import FX scales.
3089                        if path.segments.is_empty() {
3090                            if let Some(need) = self.data_read_needs(path) {
3091                                needs.mark(need);
3092                            }
3093                            if let Some(rule) = self.options_rule_of(path) {
3094                                needs.mark(InputNeed::Rule(rule));
3095                            }
3096                        }
3097                    }
3098                    NormalFormKind::OrderedDispatch { .. } => {
3099                        let origin = nf.origin.unwrap_or_else(|| {
3100                            panic!(
3101                                "BUG: non-rule_ref OrderedDispatch must carry origin (rule '{}')",
3102                                rule.path
3103                            )
3104                        });
3105                        stack.push(origin);
3106                    }
3107                    _ => nf.kind.for_each_child(|child| stack.push(child)),
3108                }
3109            }
3110            bits_by_rule.push(bits);
3111        }
3112
3113        let mut consumers: Vec<usize> = (0..self.rules.len()).collect();
3114        consumers.sort_by(|&a, &b| {
3115            self.rules[a]
3116                .path
3117                .input_key()
3118                .cmp(&self.rules[b].path.input_key())
3119        });
3120
3121        let mut needed_by_rules: Vec<NeededByRules> = self
3122            .data
3123            .iter()
3124            .map(|(path, definition)| {
3125                let fields = match definition {
3126                    DataDefinition::InstanceList { .. } => {
3127                        let identity = &self
3128                            .instance_lists
3129                            .get(path)
3130                            .unwrap_or_else(|| {
3131                                panic!("BUG: InstanceList '{path}' missing from instance_lists")
3132                            })
3133                            .identity;
3134                        vec![Vec::new(); self.row_template(identity).row_field_count()]
3135                    }
3136                    _ => Vec::new(),
3137                };
3138                NeededByRules {
3139                    rules: Vec::new(),
3140                    fields,
3141                }
3142            })
3143            .collect();
3144
3145        for &rule_pos in &consumers {
3146            let rule_id = u32::try_from(rule_pos).expect("BUG: rule count exceeds u32");
3147            let bits = &bits_by_rule[rule_pos];
3148            for (word_idx, &word) in bits.iter().enumerate() {
3149                let mut remaining = word;
3150                while remaining != 0 {
3151                    let bit = remaining.trailing_zeros() as usize;
3152                    let data_pos = word_idx * 64 + bit;
3153                    needed_by_rules[data_pos].rules.push(rule_id);
3154                    remaining &= remaining - 1;
3155                }
3156            }
3157        }
3158        self.needed_by_rules = needed_by_rules;
3159        bits_by_rule
3160    }
3161
3162    /// Fills the row-field columns of [`Self::needed_by_rules`]: which rules need each row
3163    /// field of evaluation-data rows. Runs after [`Self::show_needed_by`] so reads of a
3164    /// self-recursive row see the needs of its `uses` imports.
3165    fn fill_row_field_needs(&mut self, bits_by_rule: &[Vec<u64>]) {
3166        use crate::planning::normalize::{LeafKind, NormalFormKind, NormalFormListOp};
3167
3168        let mut visited = HashSet::new();
3169        let mut stack = Vec::new();
3170        // Evaluation-data row-field bitsets per row spec. Self RowEnd::Rule
3171        // expands via completed bits_by_rule (row rule reads are not topo edges).
3172        let mut row_bits_by_rule: Vec<BTreeMap<SpecIdentity, Vec<u64>>> =
3173            Vec::with_capacity(self.rules.len());
3174        for (rule_pos, (_, rule)) in self.rules.iter().enumerate() {
3175            let mut row_bits: BTreeMap<SpecIdentity, Vec<u64>> = BTreeMap::new();
3176            visited.clear();
3177            stack.push(rule.normal_form);
3178            while let Some(id) = stack.pop() {
3179                if !visited.insert(id) {
3180                    continue;
3181                }
3182                let nf = self.normal_form(id);
3183                if let Some(ref_path) = &nf.rule_ref {
3184                    let ref_pos = self.rules.get_index_of(ref_path).unwrap_or_else(|| {
3185                        panic!(
3186                            "BUG: rule_ref target '{ref_path}' missing from plan.rules (rule '{}')",
3187                            rule.path
3188                        )
3189                    });
3190                    if ref_pos >= rule_pos {
3191                        panic!(
3192                            "BUG: rule_ref target '{ref_path}' must precede '{}' in topo order",
3193                            rule.path
3194                        );
3195                    }
3196                    for (identity, dep_row) in &row_bits_by_rule[ref_pos] {
3197                        let entry = row_bits_entry(self, &mut row_bits, identity);
3198                        for (word, dep_word) in entry.iter_mut().zip(dep_row.iter()) {
3199                            *word |= *dep_word;
3200                        }
3201                    }
3202                    continue;
3203                }
3204                match &nf.kind {
3205                    NormalFormKind::RowField { identity, end, .. } => {
3206                        if self.has_row_template(identity) {
3207                            mark_row_end_needs(
3208                                self,
3209                                identity,
3210                                std::slice::from_ref(end),
3211                                bits_by_rule,
3212                                &mut row_bits,
3213                                &rule.path,
3214                            );
3215                        }
3216                        nf.kind.for_each_child(|child| stack.push(child));
3217                    }
3218                    NormalFormKind::SpecMember { base, row, .. } => {
3219                        let on_import_slot = match &self.normal_form(*base).kind {
3220                            NormalFormKind::Leaf(LeafKind::DataPath(path)) => {
3221                                matches!(self.data.get(path), Some(DataDefinition::Import { .. }))
3222                            }
3223                            _ => false,
3224                        };
3225                        if !on_import_slot {
3226                            let identity = match &self.result_type(*base).specifications {
3227                                TypeSpecification::Spec { spec } => spec,
3228                                other => panic!(
3229                                    "BUG: SpecMember row read on non-spec type {other:?} (rule '{}')",
3230                                    rule.path
3231                                ),
3232                            };
3233                            mark_row_end_needs(
3234                                self,
3235                                identity,
3236                                &row.ends,
3237                                bits_by_rule,
3238                                &mut row_bits,
3239                                &rule.path,
3240                            );
3241                        }
3242                        nf.kind.for_each_child(|child| stack.push(child));
3243                    }
3244                    NormalFormKind::ListCommand {
3245                        list,
3246                        op: NormalFormListOp::Find | NormalFormListOp::WithRow { .. },
3247                        row_level: Some(_),
3248                        ..
3249                    } => {
3250                        mark_list_key_fields(self, *list, &mut row_bits, &rule.path);
3251                        nf.kind.for_each_child(|child| stack.push(child));
3252                    }
3253                    NormalFormKind::OrderedDispatch { .. } => {
3254                        let origin = nf.origin.unwrap_or_else(|| {
3255                            panic!(
3256                                "BUG: non-rule_ref OrderedDispatch must carry origin (rule '{}')",
3257                                rule.path
3258                            )
3259                        });
3260                        stack.push(origin);
3261                    }
3262                    _ => nf.kind.for_each_child(|child| stack.push(child)),
3263                }
3264            }
3265            row_bits_by_rule.push(row_bits);
3266        }
3267
3268        let mut consumers: Vec<usize> = (0..self.rules.len()).collect();
3269        consumers.sort_by(|&a, &b| {
3270            self.rules[a]
3271                .path
3272                .input_key()
3273                .cmp(&self.rules[b].path.input_key())
3274        });
3275        let mut row_fields: Vec<(usize, usize, u32)> = Vec::new();
3276        for &rule_pos in &consumers {
3277            let rule_id = u32::try_from(rule_pos).expect("BUG: rule count exceeds u32");
3278            for (identity, row_bits) in &row_bits_by_rule[rule_pos] {
3279                let list_positions = self.instance_list_data_positions(identity);
3280                let template_len = self.row_template(identity).row_field_count();
3281                for (word_idx, &word) in row_bits.iter().enumerate() {
3282                    let mut remaining = word;
3283                    while remaining != 0 {
3284                        let bit = remaining.trailing_zeros() as usize;
3285                        let field_pos = word_idx * 64 + bit;
3286                        assert!(
3287                            field_pos < template_len,
3288                            "BUG: row field bit {field_pos} past the row fields of '{identity}'"
3289                        );
3290                        for &list_pos in &list_positions {
3291                            row_fields.push((list_pos, field_pos, rule_id));
3292                        }
3293                        remaining &= remaining - 1;
3294                    }
3295                }
3296            }
3297        }
3298        for (list_pos, field_pos, rule_id) in row_fields {
3299            self.needed_by_rules[list_pos].fields[field_pos].push(rule_id);
3300        }
3301    }
3302
3303    /// Position of `rule` in [`Self::show_rules`].
3304    fn show_rule_position(&self, rule: &RulePath) -> Option<u32> {
3305        self.show_rules
3306            .get_index_of(rule)
3307            .map(|position| u32::try_from(position).expect("BUG: Show rule count exceeds u32"))
3308    }
3309
3310    /// Row fields of rows of this spec: its data, then the data of its `uses` imports
3311    /// Show reads ([`Self::show_import_data`]).
3312    pub(crate) fn row_field_count(&self) -> usize {
3313        self.data.len() + self.show_import_data.len()
3314    }
3315
3316    /// Position of row field `input_key` among [`Self::row_field_count`].
3317    fn row_field_position(&self, input_key: &str) -> Option<usize> {
3318        if let Some(path) = self.input_key_index.get(input_key) {
3319            return self.data.get_index_of(path);
3320        }
3321        self.show_import_data
3322            .keys()
3323            .position(|path| path.input_key() == input_key)
3324            .map(|index| self.data.len() + index)
3325    }
3326
3327    /// Whether rows of `identity` can come from evaluation data on this plan: it is this
3328    /// spec or a row spec of one of its data lists.
3329    fn has_row_template(&self, identity: &SpecIdentity) -> bool {
3330        *identity == self.identity || self.row_templates.contains_key(identity)
3331    }
3332
3333    /// [`Self::data`] positions of instance lists whose element identity is `identity`.
3334    fn instance_list_data_positions(&self, identity: &SpecIdentity) -> Vec<usize> {
3335        self.instance_lists
3336            .iter()
3337            .filter(|(_, source)| source.identity == *identity)
3338            .map(|(path, _)| {
3339                self.data
3340                    .get_index_of(path)
3341                    .unwrap_or_else(|| panic!("BUG: instance list '{path}' absent from plan.data"))
3342            })
3343            .collect()
3344    }
3345
3346    /// Union of [`NeededByRules::fields`] across instance lists of `identity`
3347    /// (alphabetical rule-name order already on each list column).
3348    pub(crate) fn row_field_needed_by_rules(
3349        &self,
3350        identity: &SpecIdentity,
3351        field_input_key: &str,
3352    ) -> Vec<u32> {
3353        let field_pos = self
3354            .row_template(identity)
3355            .row_field_position(field_input_key)
3356            .unwrap_or_else(|| {
3357                panic!("BUG: row field '{field_input_key}' is not a row field of '{identity}'")
3358            });
3359        let mut seen = HashSet::new();
3360        let mut union = Vec::new();
3361        for list_pos in self.instance_list_data_positions(identity) {
3362            let fields = &self.needed_by_rules[list_pos].fields;
3363            let consumers = fields.get(field_pos).unwrap_or_else(|| {
3364                panic!(
3365                    "BUG: needed_by_rules.fields len {} < field {field_pos} for list data pos {list_pos}",
3366                    fields.len()
3367                )
3368            });
3369            for &rule_id in consumers {
3370                if seen.insert(rule_id) {
3371                    union.push(rule_id);
3372                }
3373            }
3374        }
3375        union.sort_by(|&a, &b| {
3376            self.rules
3377                .get_index(a as usize)
3378                .expect("BUG: needed_by_rules rule id out of range")
3379                .1
3380                .path
3381                .input_key()
3382                .cmp(
3383                    &self
3384                        .rules
3385                        .get_index(b as usize)
3386                        .expect("BUG: needed_by_rules rule id out of range")
3387                        .1
3388                        .path
3389                        .input_key(),
3390                )
3391        });
3392        union
3393    }
3394
3395    /// Promptable [`DataPath`] for a normal-form data leaf, following reference
3396    /// chain ends for references. `None` when the leaf is a rule-target, import
3397    /// marker, instance list, or a slot bound by the spec (not caller-promptable).
3398    ///
3399    /// Reference paths must appear in [`Self::reference_ends`].
3400    pub(crate) fn promptable_data_path<'a>(&'a self, path: &'a DataPath) -> Option<&'a DataPath> {
3401        let target = match self.data.get(path).unwrap_or_else(|| {
3402            panic!("BUG: normal-form DataPath leaf absent from plan.data: {path}")
3403        }) {
3404            DataDefinition::Value { .. } | DataDefinition::TypeDeclaration { .. } => path,
3405            DataDefinition::Reference { .. } => match self.reference_ends.get(path) {
3406                Some(ReferenceEnd::Promptable(target)) => target,
3407                Some(ReferenceEnd::Rule(_)) => return None,
3408                None => {
3409                    panic!("BUG: reference '{path}' missing from reference_ends after planning")
3410                }
3411            },
3412            DataDefinition::Import { .. } | DataDefinition::InstanceList { .. } => return None,
3413        };
3414        match self
3415            .data
3416            .get(target)
3417            .unwrap_or_else(|| panic!("BUG: reference end '{target}' absent from plan.data"))
3418        {
3419            DataDefinition::Value { .. } | DataDefinition::TypeDeclaration { .. }
3420                if !self.data[target].is_bound() =>
3421            {
3422                Some(target)
3423            }
3424            DataDefinition::Value { .. } | DataDefinition::TypeDeclaration { .. } => None,
3425            DataDefinition::InstanceList { .. } => None,
3426            DataDefinition::Reference { .. } | DataDefinition::Import { .. } => {
3427                panic!("BUG: reference end '{target}' is not a slot")
3428            }
3429        }
3430    }
3431
3432    /// What reading `path` needs: the slot itself, the end of its reference chain, or
3433    /// the rule a reference chain ends at. An import marker needs nothing (its value
3434    /// is the instance).
3435    fn data_read_needs(&self, path: &DataPath) -> Option<InputNeed> {
3436        match self
3437            .data
3438            .get(path)
3439            .unwrap_or_else(|| panic!("BUG: data '{path}' missing from plan '{}'", self.spec_name))
3440        {
3441            DataDefinition::Value { .. }
3442            | DataDefinition::TypeDeclaration { .. }
3443            | DataDefinition::InstanceList { .. } => Some(InputNeed::Data(path.clone())),
3444            DataDefinition::Import { .. } => None,
3445            DataDefinition::Reference { .. } => {
3446                match self.reference_ends.get(path).unwrap_or_else(|| {
3447                    panic!("BUG: reference '{path}' missing from reference_ends")
3448                }) {
3449                    ReferenceEnd::Promptable(target) => Some(InputNeed::Data(target.clone())),
3450                    ReferenceEnd::Rule(rule) => Some(InputNeed::Rule(rule.clone())),
3451                }
3452            }
3453        }
3454    }
3455
3456    /// Options rule of data `path`, when its type names one ([`options_rule_path`]).
3457    pub(crate) fn options_rule_of(&self, path: &DataPath) -> Option<RulePath> {
3458        let lemma_type = self.data.get(path)?.schema_type()?;
3459        let rule = options_rule_path(path, lemma_type)?;
3460        assert!(
3461            self.rules.contains_key(&rule),
3462            "BUG: options rule '{rule}' missing after planning validated it"
3463        );
3464        Some(rule)
3465    }
3466
3467    /// Validate caller-requested rule names and return resolved [`RulePath`]s in
3468    /// [`Self::show_rules`] order, each once.
3469    ///
3470    /// `None` means all local rules (this spec's outputs). `Some(&[])` is an error.
3471    /// Unknown names in `Some` slice error. Explicit names are this spec's Show.rules
3472    /// keys only (empty path).
3473    pub fn validated_response_rule_paths(
3474        &self,
3475        rules: Option<&[String]>,
3476    ) -> Result<Vec<&RulePath>, Error> {
3477        let show_position = |path: &RulePath| {
3478            self.show_rules
3479                .get_index_of(path)
3480                .unwrap_or_else(|| panic!("BUG: response rule '{path}' missing from show_rules"))
3481        };
3482        let mut positions: Vec<usize> = match rules {
3483            None => self.rules.keys().map(show_position).collect(),
3484            Some([]) => {
3485                return Err(Error::request(
3486                    "at least one rule required".to_string(),
3487                    None::<String>,
3488                ));
3489            }
3490            Some(rules) => {
3491                let mut positions = Vec::with_capacity(rules.len());
3492                for rule_name in rules {
3493                    let path = self
3494                        .show_rule_index
3495                        .get(canonical_logical_name(rule_name).as_ref())
3496                        .ok_or_else(|| {
3497                            Error::request(
3498                                format!(
3499                                    "Rule '{rule_name}' not found in spec '{}'",
3500                                    self.spec_name
3501                                ),
3502                                None::<String>,
3503                            )
3504                        })?;
3505                    positions.push(show_position(path));
3506                }
3507                positions
3508            }
3509        };
3510        positions.sort_unstable();
3511        positions.dedup();
3512        Ok(positions
3513            .into_iter()
3514            .map(|position| {
3515                self.show_rules
3516                    .get_index(position)
3517                    .expect("BUG: show_rules position taken from show_rules")
3518                    .0
3519            })
3520            .collect())
3521    }
3522
3523    /// Look up a Show.rules key (`RulePath::input_key`) among this spec's local rules.
3524    pub fn get_rule(&self, name: &str) -> Option<&ExecutableRule> {
3525        let canonical = canonical_logical_name(name);
3526        let path = self.show_rule_index.get(canonical.as_ref())?;
3527        self.rules.get(path)
3528    }
3529
3530    /// Look up a normal-form cell by id.
3531    pub fn normal_form(&self, id: NormalFormId) -> &NormalForm {
3532        self.normal_forms.get(id.index()).unwrap_or_else(|| {
3533            panic!(
3534                "BUG: NormalFormId {} out of range (table len {})",
3535                id.index(),
3536                self.normal_forms.len()
3537            )
3538        })
3539    }
3540
3541    /// Stamped result type of the cell at `id`.
3542    pub(crate) fn result_type(&self, id: NormalFormId) -> &Arc<LemmaType> {
3543        &self.normal_form(id).result_type
3544    }
3545
3546    /// Position of `path` in [`Self::rules`]. Every rule path a plan cell
3547    /// references was planned, so absence is a bug.
3548    pub(crate) fn rule_index(&self, path: &RulePath) -> RuleIndex {
3549        RuleIndex(
3550            self.rules
3551                .get_index_of(path)
3552                .unwrap_or_else(|| panic!("BUG: rule '{}' missing from execution plan", path.rule)),
3553        )
3554    }
3555
3556    pub(crate) fn rule_at(&self, index: RuleIndex) -> &ExecutableRule {
3557        self.rules
3558            .get_index(index.0)
3559            .map(|(_, rule)| rule)
3560            .unwrap_or_else(|| {
3561                panic!(
3562                    "BUG: rule index {} out of plan.rules range ({} rules)",
3563                    index.0,
3564                    self.rules.len()
3565                )
3566            })
3567    }
3568
3569    fn compute_initial_values(&self) -> Vec<Option<OperationResult>> {
3570        let mut values: Vec<Option<OperationResult>> = vec![None; self.normal_forms.len()];
3571        for (path, definition) in &self.data {
3572            let leaf = *self
3573                .data_leaf
3574                .get(path)
3575                .expect("BUG: every plan.data path must have a data_leaf entry");
3576            if let Some(fill) = definition.bound_value() {
3577                values[leaf.index()] = Some(OperationResult::from_bound(fill.clone()));
3578            } else if let Some(literal) = definition.value() {
3579                let unit = definition
3580                    .schema_type()
3581                    .and_then(|schema| schema.unit().map(Arc::from));
3582                values[leaf.index()] = Some(OperationResult::from_bound(BoundValueKind {
3583                    value: literal.value,
3584                    unit,
3585                    instance_factors: None,
3586                }));
3587            }
3588        }
3589        self.copy_reference_targets(&mut values, |_, _| false);
3590        values
3591    }
3592
3593    /// Copy each data-target reference's target value into its leaf, in
3594    /// `data_reference_order`, checked against the reference's declared type. A
3595    /// reference bound by the caller (`is_bound` of its data slot and path) or
3596    /// holding its own value keeps it.
3597    pub(crate) fn copy_reference_targets(
3598        &self,
3599        values: &mut [Option<OperationResult>],
3600        is_bound: impl Fn(usize, &DataPath) -> bool,
3601    ) {
3602        for reference_path in &self.data_reference_order {
3603            let Some((
3604                slot,
3605                _,
3606                DataDefinition::Reference {
3607                    target: ReferenceTarget::Data(target_path),
3608                    resolved_type,
3609                    local_value,
3610                    ..
3611                },
3612            )) = self.data.get_full(reference_path)
3613            else {
3614                unreachable!("BUG: data_reference_order holds only data-target references");
3615            };
3616            if local_value.is_some() || is_bound(slot, reference_path) {
3617                continue;
3618            }
3619            let leaf = self.data_slot_leaves[slot];
3620            let target_leaf = *self
3621                .data_leaf
3622                .get(target_path)
3623                .expect("BUG: reference target missing from data_leaf");
3624            let copied = values[target_leaf.index()].clone();
3625            values[leaf.index()] =
3626                match &copied {
3627                    None => None,
3628                    Some(OperationResult::Veto(veto)) => Some(OperationResult::Veto(veto.clone())),
3629                    Some(OperationResult::Value(value)) => Some(match validate_value_against_type(
3630                        resolved_type.as_ref(),
3631                        &value.to_literal(),
3632                        &self.resolved_types.unit_index,
3633                        None,
3634                    ) {
3635                        Ok(()) => OperationResult::from_bound(value.clone()),
3636                        Err(msg) => OperationResult::Veto(VetoType::computation(format!(
3637                            "Reference '{reference_path}' violates its declared constraint: {msg}"
3638                        ))),
3639                    }),
3640                };
3641        }
3642    }
3643
3644    pub(crate) fn populate_evaluation_tables(&mut self) {
3645        self.data_slot_leaves = self
3646            .data
3647            .keys()
3648            .map(|path| {
3649                *self
3650                    .data_leaf
3651                    .get(path)
3652                    .expect("BUG: every plan.data path must have a data_leaf entry")
3653            })
3654            .collect();
3655        self.initial_values = self.compute_initial_values();
3656        self.rule_ref_indexes = self
3657            .normal_forms
3658            .iter()
3659            .map(|cell| cell.rule_ref.as_ref().map(|path| self.rule_index(path)))
3660            .collect();
3661        self.walk_settled_leaves = self
3662            .data
3663            .iter()
3664            .filter_map(|(path, definition)| {
3665                let options = definition
3666                    .schema_type()
3667                    .is_some_and(|schema| schema.needs_runtime_option_check());
3668                let unscaled = definition
3669                    .value()
3670                    .is_some_and(|literal| literal.value.has_unscaled_measure())
3671                    || definition
3672                        .bound_value()
3673                        .is_some_and(|bound| bound.value.has_unscaled_measure())
3674                    || definition
3675                        .schema_type()
3676                        .is_some_and(LemmaType::has_dynamic_units);
3677                if options || unscaled {
3678                    Some(
3679                        *self
3680                            .data_leaf
3681                            .get(path)
3682                            .expect("BUG: every plan.data path must have a data_leaf entry"),
3683                    )
3684                } else {
3685                    None
3686                }
3687            })
3688            .collect();
3689    }
3690}
3691
3692/// Follow an [`NormalFormKind::OrderedDispatch`] region to the origin arm body it selects,
3693/// using filled slots: a nested dispatch by its scrutinee slot, a conjunctive region by
3694/// its residual arms. Stops at rule-reference cells: those borrow another rule's Kind and
3695/// must compare as the origin arm body, not the body that rule would itself select.
3696/// `None` when a slot the walk reads is unset or vetoed (not decided yet).
3697pub(crate) fn resolve_nested_dispatch_body(
3698    plan: &ExecutionPlan,
3699    values: &[Option<OperationResult>],
3700    mut region: DispatchRegion,
3701) -> Option<NormalFormId> {
3702    use crate::computation::OperationResult;
3703    use crate::planning::normalize::NormalFormKind;
3704    use crate::planning::ordered_dispatch::region_of_scrutinee;
3705
3706    for _ in 0..=plan.normal_forms.len() {
3707        let body = match region {
3708            DispatchRegion::Body(body) => body,
3709            DispatchRegion::Conjunctive(group) => {
3710                region = DispatchRegion::Body(conjunctive_winner_body(plan, values, group)?);
3711                continue;
3712            }
3713        };
3714        let cell = plan.normal_form(body);
3715        if cell.rule_ref.is_some() {
3716            return Some(body);
3717        }
3718        let (scrutinee, boundaries, regions) = match &cell.kind {
3719            NormalFormKind::OrderedDispatch {
3720                scrutinee,
3721                boundaries,
3722                regions,
3723            } => (scrutinee, boundaries, regions),
3724            NormalFormKind::Piecewise(_) => {
3725                panic!("BUG: single-scrutinee region body is a Piecewise, not a conjunctive group")
3726            }
3727            NormalFormKind::Leaf(_)
3728            | NormalFormKind::RowField { .. }
3729            | NormalFormKind::Sum(_)
3730            | NormalFormKind::Product(_)
3731            | NormalFormKind::Subtract(_, _)
3732            | NormalFormKind::Divide(_, _)
3733            | NormalFormKind::Power(_, _)
3734            | NormalFormKind::Modulo(_, _)
3735            | NormalFormKind::Negate(_)
3736            | NormalFormKind::Reciprocal(_)
3737            | NormalFormKind::Comparison(_, _, _)
3738            | NormalFormKind::Logical(_, _)
3739            | NormalFormKind::Not(_)
3740            | NormalFormKind::MathOp(_, _)
3741            | NormalFormKind::StepRounding(_, _, _)
3742            | NormalFormKind::UnitConversion(_, _)
3743            | NormalFormKind::Veto(_)
3744            | NormalFormKind::DateRelative(_, _)
3745            | NormalFormKind::DateCalendar(_, _, _)
3746            | NormalFormKind::RangeLiteral(_, _)
3747            | NormalFormKind::PastFutureRange(_, _)
3748            | NormalFormKind::RangeContainment(_, _)
3749            | NormalFormKind::RangeBound(_, _)
3750            | NormalFormKind::ResultIsVeto(_)
3751            | NormalFormKind::Now
3752            | NormalFormKind::SpecMember { .. }
3753            | NormalFormKind::ListCommand { .. } => return Some(body),
3754        };
3755        let literal = match values.get(scrutinee.index()).and_then(|slot| slot.as_ref()) {
3756            Some(OperationResult::Value(literal)) => literal,
3757            Some(OperationResult::Veto(_)) | None => return None,
3758        };
3759        let index = region_of_scrutinee(boundaries, &literal.value).ok()?;
3760        region = regions[index];
3761    }
3762    panic!("BUG: nested OrderedDispatch chain longer than the normal-form table");
3763}
3764
3765/// Origin arm body a conjunctive region's residual arms select, scanned like the origin
3766/// Piecewise. `None` while a residual condition is unset or vetoed. A group that
3767/// normalization rewrote (into a dispatch or a collapsed value) is itself the body.
3768fn conjunctive_winner_body(
3769    plan: &ExecutionPlan,
3770    values: &[Option<OperationResult>],
3771    group: NormalFormId,
3772) -> Option<NormalFormId> {
3773    use crate::evaluation::branch_semantics::{
3774        condition_outcome, piecewise_decision, PiecewiseDecision,
3775    };
3776    use crate::planning::normalize::NormalFormKind;
3777
3778    let NormalFormKind::Piecewise(arms) = &plan.normal_form(group).kind else {
3779        return Some(group);
3780    };
3781    let outcome = |arm: usize| {
3782        values
3783            .get(arms[arm].0.index())
3784            .and_then(|slot| slot.as_ref())
3785            .map(condition_outcome)
3786    };
3787    match piecewise_decision(arms.len(), outcome) {
3788        PiecewiseDecision::Taken { arm } => Some(arms[arm].1),
3789        PiecewiseDecision::Default => Some(arms[0].1),
3790        PiecewiseDecision::Undecided { .. } => None,
3791    }
3792}
3793
3794/// DataPath leaves reachable from `root` in evaluator decision-tree preorder.
3795///
3796/// Control liveness is derived from `values` (the evaluation value table), matching
3797/// the evaluator's own decisions:
3798/// - A cell that has its value or its veto: nothing under it.
3799/// - [`NormalFormKind::Piecewise`]: the arms [`open_arms`] reaches.
3800/// - [`NormalFormKind::OrderedDispatch`]: only the region for the scrutinee slot. Without
3801///   a scrutinee value, the rule the table was built from.
3802///
3803/// [`open_arms`]: crate::evaluation::branch_semantics::open_arms
3804///
3805/// Every cell the evaluator visits owns its slot, including rule reference cells
3806/// (they hold the referenced rule's value).
3807///
3808/// Order matches the evaluator walk (`tree.rs`): first-seen [`DataPath`] wins
3809/// (rule references may share a leaf under distinct cell ids). Iterative DFS with
3810/// pop-time visited; children pushed in reverse evaluation order. Instance-list
3811/// commands and row member reads appear as [`ReachableInput::RowReads`]: their
3812/// missing row fields are recorded during evaluation, not in the plan.
3813pub(crate) fn reachable_data_paths(
3814    plan: &ExecutionPlan,
3815    root: NormalFormId,
3816    values: &[Option<OperationResult>],
3817) -> Vec<ReachableInput> {
3818    let mut inputs = ReachableInputs::default();
3819    live_walk(plan, root, values, |id| inputs.visit(plan, id));
3820    inputs.out
3821}
3822
3823/// [`reachable_data_paths`] and whether [`unsettled_live_work`] is not empty, in one
3824/// walk: both use the same liveness over the same `values`.
3825pub(crate) fn reachable_data_paths_and_unsettled(
3826    plan: &ExecutionPlan,
3827    root: NormalFormId,
3828    values: &[Option<OperationResult>],
3829) -> (Vec<ReachableInput>, bool) {
3830    let mut inputs = ReachableInputs::default();
3831    let mut unsettled = false;
3832    live_walk(plan, root, values, |id| {
3833        inputs.visit(plan, id);
3834        unsettled = unsettled || unsettled_work_at(plan, values, id).is_some();
3835    });
3836    (inputs.out, unsettled)
3837}
3838
3839/// Accumulator of [`reachable_data_paths`].
3840#[derive(Default)]
3841struct ReachableInputs {
3842    out: Vec<ReachableInput>,
3843    seen_paths: HashSet<DataPath>,
3844}
3845
3846impl ReachableInputs {
3847    fn visit(&mut self, plan: &ExecutionPlan, id: NormalFormId) {
3848        use crate::planning::normalize::LeafKind;
3849        use crate::planning::normalize::NormalFormKind;
3850
3851        // A reference to a rule has that rule's inputs, visited on the rule itself.
3852        if plan.normal_form(id).rule_ref.is_some() {
3853            return;
3854        }
3855        match &plan.normal_form(id).kind {
3856            NormalFormKind::Leaf(LeafKind::DataPath(path)) => {
3857                if !matches!(plan.reference_ends.get(path), Some(ReferenceEnd::Rule(_)))
3858                    && self.seen_paths.insert(path.clone())
3859                {
3860                    self.out.push(ReachableInput::Data(path.clone()));
3861                }
3862            }
3863            NormalFormKind::ListCommand {
3864                row_level: Some(_), ..
3865            }
3866            | NormalFormKind::SpecMember { .. } => self.out.push(ReachableInput::RowReads(id)),
3867            _ => {}
3868        }
3869    }
3870}
3871
3872/// Live work under `root` on `plan` that `values` does not hold yet, in evaluation
3873/// order: the cells and rules whose values decide which inputs of `root` are live.
3874/// Same liveness as [`reachable_data_paths`]. Data leaves (an unbound input stays
3875/// unfilled), literals, and cells that read a list row (never stored) are not work.
3876/// A data slot bound to a rule is that rule's value.
3877pub(crate) fn unsettled_live_work(
3878    plan: &ExecutionPlan,
3879    root: NormalFormId,
3880    values: &[Option<OperationResult>],
3881) -> Vec<LiveWork> {
3882    let mut out = Vec::new();
3883    live_walk(plan, root, values, |id| {
3884        out.extend(unsettled_work_at(plan, values, id));
3885    });
3886    out
3887}
3888
3889/// The live work cell `id` is when `values` does not hold it yet (see
3890/// [`unsettled_live_work`]).
3891fn unsettled_work_at(
3892    plan: &ExecutionPlan,
3893    values: &[Option<OperationResult>],
3894    id: NormalFormId,
3895) -> Option<LiveWork> {
3896    use crate::planning::normalize::LeafKind;
3897    use crate::planning::normalize::NormalFormKind;
3898
3899    let filled = values.get(id.index()).is_some_and(Option::is_some);
3900    if filled || plan.row_mask[id.index()] != 0 {
3901        return None;
3902    }
3903    if plan.normal_form(id).rule_ref.is_some() {
3904        return Some(LiveWork::Cell(id));
3905    }
3906    match &plan.normal_form(id).kind {
3907        NormalFormKind::Leaf(LeafKind::DataPath(path)) => match plan.reference_ends.get(path) {
3908            Some(ReferenceEnd::Rule(rule)) => Some(LiveWork::Rule(plan.rule_index(rule))),
3909            _ => None,
3910        },
3911        NormalFormKind::Leaf(_) | NormalFormKind::RowField { .. } => None,
3912        _ => Some(LiveWork::Cell(id)),
3913    }
3914}
3915
3916/// Live work [`unsettled_live_work`] found.
3917#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3918pub(crate) enum LiveWork {
3919    Cell(NormalFormId),
3920    Rule(RuleIndex),
3921}
3922
3923/// Visits every cell live under `root` once, in evaluation order (see
3924/// [`reachable_data_paths`] for the liveness rules).
3925fn live_walk(
3926    plan: &ExecutionPlan,
3927    root: NormalFormId,
3928    values: &[Option<OperationResult>],
3929    mut visit: impl FnMut(NormalFormId),
3930) {
3931    use crate::computation::OperationResult;
3932    use crate::evaluation::branch_semantics::{condition_outcome, open_arms, BranchOutcome};
3933    use crate::planning::normalize::LeafKind;
3934    use crate::planning::normalize::NormalFormKind;
3935    use crate::planning::ordered_dispatch::region_of_scrutinee;
3936
3937    fn slot(values: &[Option<OperationResult>], id: NormalFormId) -> Option<&OperationResult> {
3938        values.get(id.index()).and_then(|slot| slot.as_ref())
3939    }
3940
3941    fn slot_outcome(values: &[Option<OperationResult>], id: NormalFormId) -> Option<BranchOutcome> {
3942        slot(values, id).map(condition_outcome)
3943    }
3944
3945    let mut visited = HashSet::new();
3946    let mut stack = vec![root];
3947
3948    while let Some(id) = stack.pop() {
3949        if !visited.insert(id) {
3950            continue;
3951        }
3952        visit(id);
3953        // A cell that has its value or its veto needs nothing more.
3954        if slot(values, id).is_some_and(|result| !result.is_missing_data()) {
3955            continue;
3956        }
3957        let nf = plan.normal_form(id);
3958        if let Some(rule) = &nf.rule_ref {
3959            stack.push(plan.rule_at(plan.rule_index(rule)).normal_form);
3960            continue;
3961        }
3962        let live: Vec<NormalFormId> = match &nf.kind {
3963            // A slot bound to a rule has that rule's inputs.
3964            NormalFormKind::Leaf(LeafKind::DataPath(path)) => match plan.reference_ends.get(path) {
3965                Some(ReferenceEnd::Rule(rule)) => vec![
3966                    plan.rules
3967                        .get(rule)
3968                        .unwrap_or_else(|| {
3969                            panic!("BUG: rule-bound slot '{path}' names missing rule '{rule}'")
3970                        })
3971                        .normal_form,
3972                ],
3973                Some(ReferenceEnd::Promptable(_)) | None => Vec::new(),
3974            },
3975            NormalFormKind::RowField { .. } => Vec::new(),
3976            NormalFormKind::Leaf(LeafKind::RowValue { .. }) => Vec::new(),
3977            NormalFormKind::ListCommand { .. } => nf.kind.children(),
3978            NormalFormKind::Piecewise(arms) => {
3979                open_arms(arms.len(), |arm| slot_outcome(values, arms[arm].0))
3980                    .into_iter()
3981                    .flat_map(|open| {
3982                        let (condition, body) = arms[open.arm];
3983                        let read = if open.arm == 0 { None } else { Some(condition) };
3984                        read.into_iter().chain(open.body.then_some(body))
3985                    })
3986                    .collect()
3987            }
3988            NormalFormKind::OrderedDispatch {
3989                scrutinee,
3990                boundaries,
3991                regions,
3992            } => match slot(values, *scrutinee) {
3993                Some(OperationResult::Value(literal)) => {
3994                    match region_of_scrutinee(boundaries, &literal.value) {
3995                        Ok(region) => vec![*scrutinee, regions[region].cell()],
3996                        Err(_) => vec![*scrutinee],
3997                    }
3998                }
3999                // Without a scrutinee value the table decides nothing: the rule does.
4000                _ => vec![nf.dispatched_rule()],
4001            },
4002            NormalFormKind::SpecMember { base, .. } => vec![*base],
4003            NormalFormKind::Leaf(LeafKind::Literal(_))
4004            | NormalFormKind::Now
4005            | NormalFormKind::Veto(_)
4006            | NormalFormKind::Logical(_, _)
4007            | NormalFormKind::Sum(_)
4008            | NormalFormKind::Product(_)
4009            | NormalFormKind::Subtract(_, _)
4010            | NormalFormKind::Divide(_, _)
4011            | NormalFormKind::Power(_, _)
4012            | NormalFormKind::Modulo(_, _)
4013            | NormalFormKind::Comparison(_, _, _)
4014            | NormalFormKind::RangeLiteral(_, _)
4015            | NormalFormKind::RangeContainment(_, _)
4016            | NormalFormKind::StepRounding(_, _, _)
4017            | NormalFormKind::Negate(_)
4018            | NormalFormKind::Reciprocal(_)
4019            | NormalFormKind::Not(_)
4020            | NormalFormKind::MathOp(_, _)
4021            | NormalFormKind::UnitConversion(_, _)
4022            | NormalFormKind::DateRelative(_, _)
4023            | NormalFormKind::DateCalendar(_, _, _)
4024            | NormalFormKind::PastFutureRange(_, _)
4025            | NormalFormKind::RangeBound(_, _)
4026            | NormalFormKind::ResultIsVeto(_) => nf.kind.children(),
4027        };
4028        stack.extend(live.into_iter().rev());
4029    }
4030}
4031
4032/// One input [`reachable_data_paths`] found, in evaluation order.
4033pub(crate) enum ReachableInput {
4034    Data(DataPath),
4035    /// A cell that reads list rows; its missing row fields are in the request state.
4036    RowReads(NormalFormId),
4037}
4038
4039pub(crate) fn validate_value_against_type(
4040    expected_type: &LemmaType,
4041    value: &LiteralValue,
4042    unit_index: &UnitIndex,
4043    runtime_scales: Option<
4044        &std::collections::HashMap<String, crate::computation::rational::RationalInteger>,
4045    >,
4046) -> Result<(), String> {
4047    use std::borrow::Cow;
4048
4049    let mut pending = vec![(expected_type, Cow::Borrowed(value))];
4050    while let Some((expected, value)) = pending.pop() {
4051        match (&expected.specifications, &value.value) {
4052            (TypeSpecification::List { element, .. }, ValueKind::List(rows)) => {
4053                for row in rows.iter().rev() {
4054                    pending.push((element.as_ref(), Cow::Owned(row.to_literal())));
4055                }
4056            }
4057            (TypeSpecification::Measure { .. }, ValueKind::UnscaledMeasure { .. }) => {}
4058            (TypeSpecification::MeasureRange { .. }, ValueKind::Range(left, right))
4059                if matches!(
4060                    (&left.value, &right.value),
4061                    (
4062                        ValueKind::UnscaledMeasure { .. },
4063                        ValueKind::UnscaledMeasure { .. }
4064                    ) | (ValueKind::UnscaledMeasure { .. }, ValueKind::Measure(_))
4065                        | (ValueKind::Measure(_), ValueKind::UnscaledMeasure { .. })
4066                ) => {}
4067            (
4068                range_spec @ (TypeSpecification::NumberRange { .. }
4069                | TypeSpecification::DateRange { .. }
4070                | TypeSpecification::TimeRange { .. }
4071                | TypeSpecification::MeasureRange { .. }
4072                | TypeSpecification::RatioRange { .. }),
4073                ValueKind::Range(left, right),
4074            ) => validate_range_literal(
4075                expected,
4076                range_spec,
4077                left.as_ref(),
4078                right.as_ref(),
4079                unit_index,
4080            )?,
4081            _ => {
4082                validate_scalar_against_type(expected, &value, runtime_scales)?;
4083                expected.reject_disallowed(&value.value, runtime_scales)?;
4084            }
4085        }
4086    }
4087    Ok(())
4088}
4089
4090fn validate_scalar_against_type(
4091    expected_type: &LemmaType,
4092    value: &LiteralValue,
4093    runtime_scales: Option<
4094        &std::collections::HashMap<String, crate::computation::rational::RationalInteger>,
4095    >,
4096) -> Result<(), String> {
4097    use crate::computation::bigint::BigInt;
4098    use crate::computation::rational::{
4099        checked_mul, rational_new, try_pow_integer, RationalInteger,
4100    };
4101
4102    fn exceeds_decimal_places(magnitude: &RationalInteger, max_decimals: u8) -> bool {
4103        let scale = match try_pow_integer(
4104            &rational_new(10, 1),
4105            &BigInt::from_i64(i64::from(max_decimals)),
4106        ) {
4107            Ok(value) => value,
4108            Err(_) => return true,
4109        };
4110        let scaled = match checked_mul(magnitude, &scale) {
4111            Ok(value) => value,
4112            Err(_) => return true,
4113        };
4114        match RationalInteger::try_reduce_ref(&scaled) {
4115            Ok(reduced) => !reduced.is_integer(),
4116            Err(_) => true,
4117        }
4118    }
4119
4120    fn format_rational_for_validation_message(
4121        expected_type: &LemmaType,
4122        magnitude: &RationalInteger,
4123    ) -> String {
4124        expected_type
4125            .try_rational_as_decimal(magnitude)
4126            .map(|decimal| decimal.to_string())
4127            .unwrap_or_else(|_| magnitude.display_str())
4128    }
4129
4130    match (&expected_type.specifications, &value.value) {
4131        (
4132            TypeSpecification::Number {
4133                minimum,
4134                maximum,
4135                decimals,
4136                ..
4137            },
4138            ValueKind::Number(n),
4139        ) => {
4140            use std::cmp::Ordering;
4141            if let Some(d) = decimals {
4142                if exceeds_decimal_places(n, *d) {
4143                    return Err(format!(
4144                        "{} exceeds the decimals constraint of {d}.",
4145                        n.display_str()
4146                    ));
4147                }
4148            }
4149            if let Some(min) = minimum {
4150                if n.try_cmp(min).map_err(|failure| {
4151                    format!("Comparing against the minimum bound failed: {failure}.")
4152                })? == Ordering::Less
4153                {
4154                    return Err(format!(
4155                        "{} is below the minimum of {}.",
4156                        format_rational_for_validation_message(expected_type, n),
4157                        format_rational_for_validation_message(expected_type, min)
4158                    ));
4159                }
4160            }
4161            if let Some(max) = maximum {
4162                if n.try_cmp(max).map_err(|failure| {
4163                    format!("Comparing against the maximum bound failed: {failure}.")
4164                })? == Ordering::Greater
4165                {
4166                    return Err(format!(
4167                        "{} is above the maximum of {}.",
4168                        format_rational_for_validation_message(expected_type, n),
4169                        format_rational_for_validation_message(expected_type, max)
4170                    ));
4171                }
4172            }
4173            Ok(())
4174        }
4175        (
4176            TypeSpecification::Measure {
4177                minimum,
4178                maximum,
4179                units,
4180                ..
4181            },
4182            ValueKind::Measure(magnitude),
4183        ) => {
4184            use crate::computation::rational::{checked_div, checked_mul};
4185            use std::cmp::Ordering;
4186            for (bound, label, violation, relation) in [
4187                (minimum, "minimum", Ordering::Less, "below"),
4188                (maximum, "maximum", Ordering::Greater, "above"),
4189            ] {
4190                let Some((bound_magnitude, bound_unit)) = bound else {
4191                    continue;
4192                };
4193                let bound_unit_def = units.get(bound_unit.as_str())?;
4194                // 0 is 0 in every unit of the family: it needs no scale.
4195                let canonical_bound = if bound_magnitude.numer_is_zero() {
4196                    bound_magnitude.clone()
4197                } else if let Some(factor) = bound_unit_def.literal_factor() {
4198                    checked_mul(bound_magnitude, factor).map_err(|failure| {
4199                        format!("{label}: unit conversion overflow: {failure}")
4200                    })?
4201                } else {
4202                    let factor = runtime_scales
4203                        .and_then(|scales| scales.get(bound_unit.as_str()))
4204                        .ok_or_else(|| {
4205                            format!(
4206                                "{label} cannot use unit '{bound_unit}' on '{}': its conversion factor is not settled.",
4207                                expected_type.name()
4208                            )
4209                        })?;
4210                    checked_mul(bound_magnitude, factor).map_err(|failure| {
4211                        format!("{label}: unit conversion overflow: {failure}")
4212                    })?
4213                };
4214                if magnitude.try_cmp(&canonical_bound).map_err(|failure| {
4215                    format!("Comparing against the {label} bound failed: {failure}.")
4216                })? != violation
4217                {
4218                    continue;
4219                }
4220                let display_unit = match expected_type.unit() {
4221                    Some(written) => units.get(written)?,
4222                    None => units.get(bound_unit)?,
4223                };
4224                let factor = if let Some(factor) = display_unit.literal_factor() {
4225                    factor.clone()
4226                } else {
4227                    runtime_scales
4228                        .and_then(|scales| scales.get(display_unit.name.as_str()))
4229                        .cloned()
4230                        .ok_or_else(|| {
4231                            format!(
4232                                "Cannot de-canonicalize the measure for validation: unit '{}' scale is not settled.",
4233                                display_unit.name
4234                            )
4235                        })?
4236                };
4237                let value_in_unit = checked_div(magnitude, &factor).map_err(|failure| {
4238                    format!("Cannot de-canonicalize the measure for validation: {failure}.")
4239                })?;
4240                let bound_in_unit = checked_div(&canonical_bound, &factor).map_err(|failure| {
4241                    format!("Cannot de-canonicalize the {label} for validation: {failure}.")
4242                })?;
4243                return Err(format!(
4244                    "{} {unit} is {relation} the {label} of {} {unit}.",
4245                    format_rational_for_validation_message(expected_type, &value_in_unit),
4246                    format_rational_for_validation_message(expected_type, &bound_in_unit),
4247                    unit = display_unit.name
4248                ));
4249            }
4250            Ok(())
4251        }
4252        (TypeSpecification::Text { length, .. }, ValueKind::Text(s)) => {
4253            let len = s.chars().count();
4254            if let Some(exact) = length {
4255                if len != *exact {
4256                    return Err(format!(
4257                        "'{}' has length {}, but the required length is {}.",
4258                        s, len, exact
4259                    ));
4260                }
4261            }
4262            Ok(())
4263        }
4264        (
4265            TypeSpecification::Ratio {
4266                minimum,
4267                maximum,
4268                units,
4269                ..
4270            },
4271            ValueKind::Ratio(r),
4272        ) => {
4273            use crate::computation::rational::checked_mul;
4274            use std::cmp::Ordering;
4275
4276            let written_unit = expected_type.unit();
4277
4278            if let Some(type_minimum) = minimum {
4279                if r.try_cmp(type_minimum).map_err(|failure| {
4280                    format!("Comparing against the minimum bound failed: {failure}.")
4281                })? == Ordering::Less
4282                {
4283                    let message = match written_unit {
4284                        Some(unit) => {
4285                            let ratio_unit = units.get(unit)?;
4286                            let value_per_unit = checked_mul(r, &ratio_unit.value)
4287                                .map_err(|failure| failure.to_string())?;
4288                            let bound_per_unit = ratio_unit.minimum.clone().expect(
4289                                "BUG: RatioUnit.minimum missing after type minimum set by sync_ratio_units_from_canonical",
4290                            );
4291                            format!(
4292                                "{} {unit} is below the minimum of {} {unit}.",
4293                                format_rational_for_validation_message(
4294                                    expected_type,
4295                                    &value_per_unit
4296                                ),
4297                                format_rational_for_validation_message(
4298                                    expected_type,
4299                                    &bound_per_unit.clone()
4300                                ),
4301                            )
4302                        }
4303                        None => format!(
4304                            "{} is below the minimum of {}.",
4305                            format_rational_for_validation_message(expected_type, r),
4306                            format_rational_for_validation_message(expected_type, type_minimum),
4307                        ),
4308                    };
4309                    return Err(message);
4310                }
4311            }
4312            if let Some(type_maximum) = maximum {
4313                if r.try_cmp(type_maximum).map_err(|failure| {
4314                    format!("Comparing against the maximum bound failed: {failure}.")
4315                })? == Ordering::Greater
4316                {
4317                    let message = match written_unit {
4318                        Some(unit) => {
4319                            let ratio_unit = units.get(unit)?;
4320                            let value_per_unit = checked_mul(r, &ratio_unit.value)
4321                                .map_err(|failure| failure.to_string())?;
4322                            let bound_per_unit = ratio_unit.maximum.clone().expect(
4323                                "BUG: RatioUnit.maximum missing after type maximum set by sync_ratio_units_from_canonical",
4324                            );
4325                            format!(
4326                                "{} {unit} is above the maximum of {} {unit}.",
4327                                format_rational_for_validation_message(
4328                                    expected_type,
4329                                    &value_per_unit
4330                                ),
4331                                format_rational_for_validation_message(
4332                                    expected_type,
4333                                    &bound_per_unit.clone()
4334                                ),
4335                            )
4336                        }
4337                        None => format!(
4338                            "{} is above the maximum of {}.",
4339                            format_rational_for_validation_message(expected_type, r),
4340                            format_rational_for_validation_message(expected_type, type_maximum),
4341                        ),
4342                    };
4343                    return Err(message);
4344                }
4345            }
4346            Ok(())
4347        }
4348        (
4349            TypeSpecification::Date {
4350                minimum, maximum, ..
4351            },
4352            ValueKind::Date(dt),
4353        ) => {
4354            use crate::planning::semantics::{compare_semantic_dates, date_time_to_semantic};
4355            use std::cmp::Ordering;
4356            if let Some(min) = minimum {
4357                let min_sem = date_time_to_semantic(min);
4358                if compare_semantic_dates(dt, &min_sem) == Ordering::Less {
4359                    return Err(format!("{} is below the minimum of {}.", dt, min));
4360                }
4361            }
4362            if let Some(max) = maximum {
4363                let max_sem = date_time_to_semantic(max);
4364                if compare_semantic_dates(dt, &max_sem) == Ordering::Greater {
4365                    return Err(format!("{} is above the maximum of {}.", dt, max));
4366                }
4367            }
4368            Ok(())
4369        }
4370        (
4371            TypeSpecification::Time {
4372                minimum, maximum, ..
4373            },
4374            ValueKind::Time(t),
4375        ) => {
4376            use crate::planning::semantics::{compare_semantic_times, time_to_semantic};
4377            use std::cmp::Ordering;
4378            if let Some(min) = minimum {
4379                let min_sem = time_to_semantic(min);
4380                if compare_semantic_times(t, &min_sem) == Ordering::Less {
4381                    return Err(format!("{} is below the minimum of {}.", t, min));
4382                }
4383            }
4384            if let Some(max) = maximum {
4385                let max_sem = time_to_semantic(max);
4386                if compare_semantic_times(t, &max_sem) == Ordering::Greater {
4387                    return Err(format!("{} is above the maximum of {}.", t, max));
4388                }
4389            }
4390            Ok(())
4391        }
4392        (TypeSpecification::Boolean { .. }, ValueKind::Boolean(_)) => Ok(()),
4393        (TypeSpecification::List { .. }, ValueKind::List(_))
4394        | (
4395            TypeSpecification::NumberRange { .. }
4396            | TypeSpecification::DateRange { .. }
4397            | TypeSpecification::TimeRange { .. }
4398            | TypeSpecification::MeasureRange { .. }
4399            | TypeSpecification::RatioRange { .. },
4400            ValueKind::Range(_, _),
4401        ) => unreachable!("BUG: list and range values are walked by validate_value_against_type"),
4402        (TypeSpecification::Veto { .. }, _) | (TypeSpecification::Undetermined, _) => Ok(()),
4403        (TypeSpecification::Spec { .. }, ValueKind::Spec(_)) => Ok(()),
4404        (spec, value_kind) if !value_kind_matches_spec(value_kind, spec) => unreachable!(
4405            "BUG: validate_value_against_type called with mismatched type/value: \
4406             spec={:?}, value={:?} — typing must be enforced before validation",
4407            spec, value_kind
4408        ),
4409        (spec, value_kind) => unreachable!(
4410            "BUG: validate_value_against_type missed a value_kind_matches_spec pair: \
4411             spec={:?}, value={:?}",
4412            spec, value_kind
4413        ),
4414    }
4415}
4416
4417fn validate_range_literal(
4418    expected_type: &LemmaType,
4419    range_spec: &TypeSpecification,
4420    left: &TypedLiteral,
4421    right: &TypedLiteral,
4422    unit_index: &UnitIndex,
4423) -> Result<(), String> {
4424    use crate::computation::{comparison_operation, OperationResult};
4425    use crate::planning::semantics::{
4426        compare_semantic_dates, compare_semantic_times, measure_declared_bound_to_canonical,
4427        ValueKind,
4428    };
4429    use std::cmp::Ordering;
4430    use std::sync::Arc;
4431
4432    let element_spec = range_spec
4433        .element_from_range()
4434        .expect("BUG: element_from_range missing arm for validated range");
4435    if let TypeSpecification::Measure {
4436        units,
4437        decomposition,
4438        ..
4439    } = &element_spec
4440    {
4441        assert!(
4442            decomposition.is_some() || units.is_empty(),
4443            "BUG: measure range '{}' with units must carry a decomposition after planning",
4444            expected_type.name()
4445        );
4446    }
4447    let element_type = Arc::new(LemmaType::primitive(element_spec));
4448    validate_scalar_against_type(element_type.as_ref(), &left.to_literal(), None)?;
4449    validate_scalar_against_type(element_type.as_ref(), &right.to_literal(), None)?;
4450
4451    let ordering = match (&left.value, &right.value) {
4452        (ValueKind::Number(l), ValueKind::Number(r)) => l
4453            .try_cmp(r)
4454            .map_err(|failure| format!("Comparing range endpoints failed: {failure}."))?,
4455        (ValueKind::Date(l), ValueKind::Date(r)) => compare_semantic_dates(l, r),
4456        (ValueKind::Time(l), ValueKind::Time(r)) => compare_semantic_times(l, r),
4457        (ValueKind::Ratio(l), ValueKind::Ratio(r)) => l
4458            .try_cmp(r)
4459            .map_err(|failure| format!("Comparing range endpoints failed: {failure}."))?,
4460        (ValueKind::Measure(l), ValueKind::Measure(r)) => l
4461            .try_cmp(r)
4462            .map_err(|failure| format!("Comparing range endpoints failed: {failure}."))?,
4463        (left_kind, right_kind) => unreachable!(
4464            "BUG: range endpoints have mismatched value kinds after typing: {left_kind:?} vs {right_kind:?}"
4465        ),
4466    };
4467    if ordering == Ordering::Greater {
4468        return Err(format!(
4469            "The range left endpoint {} is above the right endpoint {}.",
4470            left.display_value(),
4471            right.display_value()
4472        ));
4473    }
4474
4475    let range_lit = LiteralValue {
4476        value: ValueKind::Range(Box::new(left.clone()), Box::new(right.clone())),
4477    };
4478    let range_type = Arc::new(expected_type.clone());
4479
4480    let compare_width = |bound: &LiteralValue,
4481                         bound_type: &Arc<LemmaType>,
4482                         op: ComparisonComputation,
4483                         fail_msg: String|
4484     -> Result<(), String> {
4485        match comparison_operation(&range_lit.value, &range_type, &op, &bound.value, bound_type) {
4486            OperationResult::Value(result) => match &result.value {
4487                ValueKind::Boolean(true) => Ok(()),
4488                ValueKind::Boolean(false) => Err(fail_msg),
4489                other => unreachable!("BUG: width comparison must return boolean, got {other:?}"),
4490            },
4491            OperationResult::Veto(veto) => Err(veto.to_string()),
4492        }
4493    };
4494
4495    match range_spec {
4496        TypeSpecification::NumberRange {
4497            minimum, maximum, ..
4498        } => {
4499            if let Some(min_w) = minimum {
4500                compare_width(
4501                    &LiteralValue::number(min_w.clone()),
4502                    primitive_number_arc(),
4503                    ComparisonComputation::GreaterThanOrEqual,
4504                    format!(
4505                        "The span is below the minimum width of {}.",
4506                        min_w.display_str()
4507                    ),
4508                )?;
4509            }
4510            if let Some(max_w) = maximum {
4511                compare_width(
4512                    &LiteralValue::number(max_w.clone()),
4513                    primitive_number_arc(),
4514                    ComparisonComputation::LessThanOrEqual,
4515                    format!(
4516                        "The span is above the maximum width of {}.",
4517                        max_w.display_str()
4518                    ),
4519                )?;
4520            }
4521        }
4522        TypeSpecification::RatioRange {
4523            minimum, maximum, ..
4524        } => {
4525            if let Some(min_w) = minimum {
4526                compare_width(
4527                    &LiteralValue::ratio(min_w.clone()),
4528                    primitive_ratio_arc(),
4529                    ComparisonComputation::GreaterThanOrEqual,
4530                    format!(
4531                        "The span is below the minimum width of {}.",
4532                        min_w.display_str()
4533                    ),
4534                )?;
4535            }
4536            if let Some(max_w) = maximum {
4537                compare_width(
4538                    &LiteralValue::ratio(max_w.clone()),
4539                    primitive_ratio_arc(),
4540                    ComparisonComputation::LessThanOrEqual,
4541                    format!(
4542                        "The span is above the maximum width of {}.",
4543                        max_w.display_str()
4544                    ),
4545                )?;
4546            }
4547        }
4548        TypeSpecification::MeasureRange {
4549            minimum,
4550            maximum,
4551            units,
4552            ..
4553        } => {
4554            if let Some(min_w) = minimum {
4555                let canonical = measure_declared_bound_to_canonical(
4556                    &min_w.0, &min_w.1, units, "range", "minimum",
4557                )?;
4558                let bound = LiteralValue::measure(canonical);
4559                compare_width(
4560                    &bound,
4561                    &element_type,
4562                    ComparisonComputation::GreaterThanOrEqual,
4563                    format!(
4564                        "The span is below the minimum width of {} {}.",
4565                        min_w.0.display_str(),
4566                        min_w.1
4567                    ),
4568                )?;
4569            }
4570            if let Some(max_w) = maximum {
4571                let canonical = measure_declared_bound_to_canonical(
4572                    &max_w.0, &max_w.1, units, "range", "maximum",
4573                )?;
4574                let bound = LiteralValue::measure(canonical);
4575                compare_width(
4576                    &bound,
4577                    &element_type,
4578                    ComparisonComputation::LessThanOrEqual,
4579                    format!(
4580                        "The span is above the maximum width of {} {}.",
4581                        max_w.0.display_str(),
4582                        max_w.1
4583                    ),
4584                )?;
4585            }
4586        }
4587        TypeSpecification::DateRange {
4588            minimum, maximum, ..
4589        }
4590        | TypeSpecification::TimeRange {
4591            minimum, maximum, ..
4592        } => {
4593            let allow_calendar = matches!(range_spec, TypeSpecification::DateRange { .. });
4594            let resolve_bound = |bound: &(RationalInteger, String),
4595                                 command: &str|
4596             -> Result<(LiteralValue, Arc<LemmaType>), String> {
4597                let (bare, owner) = unit_index
4598                    .resolve(bound.1.as_str())
4599                    .map_err(|err| format!("{command} width unit '{}': {err}", bound.1))?;
4600                if allow_calendar {
4601                    if !owner.is_duration_like() && !owner.is_calendar_like() {
4602                        return Err(format!(
4603                                "The {command} width unit '{bare}' must be a duration or calendar unit.",
4604                            ));
4605                    }
4606                } else if !owner.is_duration_like() {
4607                    return Err(format!(
4608                        "The {command} width unit '{bare}' must be a duration unit.",
4609                    ));
4610                }
4611                let TypeSpecification::Measure { units, .. } = &owner.specifications else {
4612                    return Err(format!(
4613                        "The {command} width unit '{bare}' must resolve to a measure type.",
4614                    ));
4615                };
4616                let type_name = owner.name();
4617                let canonical = measure_declared_bound_to_canonical(
4618                    &bound.0,
4619                    &bare,
4620                    units,
4621                    type_name.as_str(),
4622                    command,
4623                )?;
4624                Ok((LiteralValue::measure(canonical), Arc::clone(&owner)))
4625            };
4626            if let Some(min_w) = minimum {
4627                let (bound, bound_type) = resolve_bound(min_w, "minimum")?;
4628                compare_width(
4629                    &bound,
4630                    &bound_type,
4631                    ComparisonComputation::GreaterThanOrEqual,
4632                    format!(
4633                        "The span is below the minimum width of {} {}.",
4634                        min_w.0.display_str(),
4635                        min_w.1
4636                    ),
4637                )?;
4638            }
4639            if let Some(max_w) = maximum {
4640                let (bound, bound_type) = resolve_bound(max_w, "maximum")?;
4641                compare_width(
4642                    &bound,
4643                    &bound_type,
4644                    ComparisonComputation::LessThanOrEqual,
4645                    format!(
4646                        "The span is above the maximum width of {} {}.",
4647                        max_w.0.display_str(),
4648                        max_w.1
4649                    ),
4650                )?;
4651            }
4652        }
4653        _ => {}
4654    }
4655
4656    Ok(())
4657}
4658
4659/// Literal plan data against its declared type. Written row values are validated
4660/// when their row is built (`source_row_literal` in the graph builder).
4661fn validate_literal_data_against_types(plan: &ExecutionPlan) -> Vec<Error> {
4662    let mut errors = Vec::new();
4663
4664    for (data_path, data_definition) in &plan.data {
4665        let (expected_type, lit) = match data_definition {
4666            DataDefinition::Value {
4667                value,
4668                resolved_type,
4669                ..
4670            } => (resolved_type, value),
4671            DataDefinition::Import { .. }
4672            | DataDefinition::TypeDeclaration { .. }
4673            | DataDefinition::InstanceList { .. }
4674            | DataDefinition::Reference { .. } => continue,
4675        };
4676
4677        if let Err(msg) =
4678            validate_value_against_type(expected_type, lit, plan.expression_unit_index(), None)
4679        {
4680            let source = data_definition.source().clone();
4681            errors.push(Error::validation(
4682                format!(
4683                    "Invalid value for data {} (expected {}): {}",
4684                    data_path,
4685                    expected_type.name().as_str(),
4686                    msg
4687                ),
4688                Some(source),
4689                None::<String>,
4690            ));
4691        }
4692    }
4693
4694    errors
4695}
4696
4697fn validate_unit_conversion_targets(plan: &ExecutionPlan) -> Result<(), Error> {
4698    use crate::planning::normalize::NormalFormKind;
4699
4700    let mut errors: Vec<Error> = Vec::new();
4701    let mut visited = HashSet::new();
4702    let mut worklist: Vec<NormalFormId> =
4703        plan.rules.values().map(|rule| rule.normal_form).collect();
4704    while let Some(id) = worklist.pop() {
4705        if !visited.insert(id) {
4706            continue;
4707        }
4708        let nf = plan.normal_form(id);
4709        nf.kind.for_each_child(|child| worklist.push(child));
4710        if let NormalFormKind::UnitConversion(_, target) = &nf.kind {
4711            if let Some((unit_name, owning_type)) = conversion_target_declares_unit(target) {
4712                if !owning_type_declares_unit_name(owning_type.as_ref(), unit_name) {
4713                    errors.push(Error::validation(
4714                        format!(
4715                            "Unit conversion target '{unit_name}' is not declared on owning type '{}'",
4716                            owning_type.name()
4717                        ),
4718                        None::<Source>,
4719                        Some(plan.spec_name.clone()),
4720                    ));
4721                }
4722            }
4723        }
4724    }
4725    if let Some(error) = errors.into_iter().next() {
4726        return Err(error);
4727    }
4728    Ok(())
4729}
4730
4731#[cfg(test)]
4732mod tests {
4733    use super::*;
4734    use crate::computation::rational::rational_new;
4735    use crate::computation::{OperationResult, VetoType};
4736    use crate::evaluation::evaluate_data::EvaluateData;
4737    use crate::literals::DateGranularity;
4738    use crate::literals::TimezoneValue;
4739    use crate::parsing::ast::DateTimeValue;
4740    use crate::planning::semantics::{DataDefinition, DataPath, TypeSpecification};
4741    use crate::Engine;
4742    use crate::{EvaluateDataValue, ResourceLimits};
4743    use serde_json;
4744    use std::sync::Arc;
4745
4746    fn default_limits() -> ResourceLimits {
4747        ResourceLimits::default()
4748    }
4749
4750    fn resolve_evaluate_data(
4751        plan: &ExecutionPlan,
4752        values: IndexMap<String, EvaluateDataValue>,
4753    ) -> EvaluateData {
4754        EvaluateData::resolve(plan, values, &default_limits()).expect("resolve")
4755    }
4756
4757    fn binding<'a>(
4758        plan: &ExecutionPlan,
4759        evaluate_data: &'a EvaluateData,
4760        path: &DataPath,
4761    ) -> Option<&'a OperationResult> {
4762        let slot = plan
4763            .data
4764            .get_index_of(path)
4765            .expect("BUG: test path is plan data");
4766        evaluate_data.bindings.get(&slot)
4767    }
4768
4769    fn veto_reason<'a>(
4770        plan: &ExecutionPlan,
4771        evaluate_data: &'a EvaluateData,
4772        path: &DataPath,
4773    ) -> Option<&'a str> {
4774        match binding(plan, evaluate_data, path) {
4775            Some(OperationResult::Veto(veto)) => Some(match veto {
4776                VetoType::Computation { message } => message.as_str(),
4777                other => panic!("expected Computation veto, got {other:?}"),
4778            }),
4779            _ => None,
4780        }
4781    }
4782
4783    fn bound_value<'a>(
4784        plan: &ExecutionPlan,
4785        evaluate_data: &'a EvaluateData,
4786        path: &DataPath,
4787    ) -> Option<&'a crate::planning::semantics::BoundValueKind> {
4788        binding(plan, evaluate_data, path).and_then(OperationResult::value)
4789    }
4790
4791    fn input_data(pairs: &[(&str, &str)]) -> IndexMap<String, EvaluateDataValue> {
4792        pairs
4793            .iter()
4794            .map(|(k, v)| (k.to_string(), EvaluateDataValue::string(*v)))
4795            .collect()
4796    }
4797
4798    #[test]
4799    fn test_with_raw_values() {
4800        let mut engine = Engine::new();
4801        engine
4802            .load([(
4803                crate::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
4804                    "test.lemma",
4805                ))),
4806                r#"
4807                spec test
4808                data age: number -> suggest 25
4809                "#
4810                .to_string(),
4811            )])
4812            .unwrap();
4813
4814        let plans = engine
4815            .plans
4816            .get_plans(None, "test")
4817            .expect("plans for test");
4818        let plan = plans.values().next().expect("plan");
4819        let data_path = DataPath::new(vec![], "age".to_string());
4820
4821        let values = input_data(&[("age", "30")]);
4822
4823        let evaluate_data = resolve_evaluate_data(plan, values);
4824        let updated_value = bound_value(plan, &evaluate_data, &data_path).expect("bound value");
4825        match &updated_value.value {
4826            crate::planning::semantics::ValueKind::Number(n) => {
4827                assert_eq!(n, &rational_new(30, 1));
4828            }
4829            other => panic!("Expected number literal, got {:?}", other),
4830        }
4831    }
4832
4833    #[test]
4834    fn test_with_raw_values_type_mismatch() {
4835        let mut engine = Engine::new();
4836        engine
4837            .load([(
4838                crate::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
4839                    "test.lemma",
4840                ))),
4841                r#"
4842                spec test
4843                data age: number
4844                "#
4845                .to_string(),
4846            )])
4847            .unwrap();
4848
4849        let plans = engine
4850            .plans
4851            .get_plans(None, "test")
4852            .expect("plans for test");
4853        let plan = plans.values().next().expect("plan");
4854
4855        let values = input_data(&[("age", "thirty")]);
4856
4857        let evaluate_data = resolve_evaluate_data(plan, values);
4858        let data_path = DataPath::new(vec![], "age".to_string());
4859        match veto_reason(plan, &evaluate_data, &data_path) {
4860            Some(reason) => {
4861                assert!(
4862                    reason.contains("number"),
4863                    "type mismatch must record violation reason, got: {reason}"
4864                );
4865            }
4866            None => panic!("expected veto-bound data for age=thirty"),
4867        }
4868    }
4869
4870    #[test]
4871    fn test_with_raw_values_unknown_data_ignored() {
4872        let mut engine = Engine::new();
4873        engine
4874            .load([(
4875                crate::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
4876                    "test.lemma",
4877                ))),
4878                r#"
4879                spec test
4880                data known: number
4881                "#
4882                .to_string(),
4883            )])
4884            .unwrap();
4885
4886        let plans = engine
4887            .plans
4888            .get_plans(None, "test")
4889            .expect("plans for test");
4890        let plan = plans.values().next().expect("plan");
4891
4892        let values = input_data(&[("unknown", "30")]);
4893
4894        let evaluate_data = resolve_evaluate_data(plan, values);
4895        assert!(evaluate_data.bindings.is_empty());
4896        assert!(evaluate_data.ignored_unknown.iter().any(|k| k == "unknown"));
4897    }
4898
4899    #[test]
4900    fn test_with_raw_values_nested() {
4901        let mut engine = Engine::new();
4902        engine
4903            .load([(
4904                crate::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
4905                    "test.lemma",
4906                ))),
4907                r#"
4908                spec private
4909                data base_price: number
4910
4911                spec test
4912                uses rules: private
4913                "#
4914                .to_string(),
4915            )])
4916            .unwrap();
4917
4918        let plans = engine
4919            .plans
4920            .get_plans(None, "test")
4921            .expect("plans for test");
4922        let plan = plans.values().next().expect("plan");
4923
4924        let values = input_data(&[("rules.base_price", "100")]);
4925
4926        let evaluate_data = resolve_evaluate_data(plan, values);
4927        let Some(DataDefinition::Import { row, .. }) =
4928            plan.data.get(&DataPath::local("rules".into()))
4929        else {
4930            panic!("`rules` is the import slot of the plan");
4931        };
4932        let instance = crate::planning::semantics::InstanceKey::new(Arc::clone(row), None);
4933        let slot = plan
4934            .row_template(&row.identity)
4935            .data
4936            .get_index_of(&DataPath::local("base_price".into()))
4937            .expect("`base_price` is data of the imported template");
4938        let updated_value = evaluate_data
4939            .supplied
4940            .get(&instance, slot)
4941            .and_then(OperationResult::value)
4942            .expect("bound value");
4943        match &updated_value.value {
4944            crate::planning::semantics::ValueKind::Number(n) => {
4945                assert_eq!(n, &rational_new(100, 1));
4946            }
4947            other => panic!("Expected number literal, got {:?}", other),
4948        }
4949    }
4950
4951    #[test]
4952    fn evaluate_data_should_enforce_number_maximum_constraint() {
4953        // Higher-standard requirement: user input must be validated against type constraints.
4954        // If this test fails, Lemma accepts invalid values and gives false reassurance.
4955        let data_path = DataPath::new(vec![], "x".to_string());
4956
4957        let max10 = crate::planning::semantics::LemmaType::primitive(
4958            crate::planning::semantics::TypeSpecification::Number {
4959                minimum: None,
4960                maximum: Some(rational_new(10, 1)),
4961                decimals: None,
4962                help: String::new(),
4963            },
4964        );
4965        let source = Source::new(
4966            crate::parsing::source::SourceType::Volatile,
4967            crate::parsing::ast::Span {
4968                start: 0,
4969                end: 0,
4970                line: 1,
4971                col: 0,
4972            },
4973        );
4974        let mut data = IndexMap::new();
4975        data.insert(
4976            data_path.clone(),
4977            crate::planning::semantics::DataDefinition::Value {
4978                value: crate::planning::semantics::LiteralValue::number(rational_new(0, 1)),
4979                resolved_type: Arc::new(max10.clone()),
4980                source: source.clone(),
4981                origin: crate::planning::semantics::DataOrigin::Declared,
4982            },
4983        );
4984
4985        let input_key_index = data.keys().map(|p| (p.input_key(), p.clone())).collect();
4986        let data_len = data.len();
4987        let plan = ExecutionPlan {
4988            spec_name: "test".to_string(),
4989            commentary: None,
4990            data,
4991            normal_forms: Vec::new(),
4992            rules: IndexMap::new(),
4993            data_reference_order: Vec::new(),
4994            meta: IndexMap::new(),
4995            resolved_types: Arc::default(),
4996            family_units: Arc::new(FamilyUnitCatalog::default()),
4997            signature_index: IndexMap::new(),
4998            effective: EffectiveDate::Origin,
4999            effective_from: None,
5000            effective_to: None,
5001            start_line: 1,
5002            source_type: None,
5003            needed_by_rules: vec![NeededByRules::default(); data_len],
5004            data_display: IndexMap::new(),
5005            show_rules: IndexMap::new(),
5006            show_needed_by: IndexMap::new(),
5007            show_import_data: IndexMap::new(),
5008            reference_ends: IndexMap::new(),
5009            input_key_index,
5010            show_rule_index: IndexMap::new(),
5011            data_leaf: IndexMap::new(),
5012            member_targets: IndexMap::new(),
5013            row_templates: std::collections::BTreeMap::new(),
5014            globals: IndexMap::new(),
5015            writes: crate::planning::fill::Writes::default(),
5016            writes_by_spec: Arc::default(),
5017            writes_root: Arc::new(SpecIdentity {
5018                repository: None,
5019                spec: "test".to_string(),
5020                effective: EffectiveDate::Origin,
5021                slice: EffectiveDate::Origin,
5022            }),
5023            own_spec: Arc::new(LemmaSpec::new("test".to_string())),
5024            edges: Vec::new(),
5025            identity: SpecIdentity {
5026                repository: None,
5027                spec: "test".to_string(),
5028                effective: EffectiveDate::Origin,
5029                slice: EffectiveDate::Origin,
5030            },
5031            rule_candidates: std::collections::BTreeMap::new(),
5032            self_row_rules: Vec::new(),
5033            instance_lists: IndexMap::new(),
5034            row_mask: Vec::new(),
5035            initial_values: Vec::new(),
5036            walk_settled_leaves: Vec::new(),
5037            #[cfg(feature = "call-graph-check")]
5038            call_graph: CallGraph::default(),
5039            rule_ref_indexes: Vec::new(),
5040            data_slot_leaves: Vec::new(),
5041            slot_scale_targets: Vec::new(),
5042        };
5043
5044        let values = input_data(&[("x", "11")]);
5045
5046        let evaluate_data = resolve_evaluate_data(&plan, values);
5047        match veto_reason(&plan, &evaluate_data, &data_path) {
5048            Some(reason) => {
5049                assert!(
5050                    reason.contains("maximum") || reason.contains("10"),
5051                    "x=11 must violate maximum 10, got: {reason}"
5052                );
5053            }
5054            None => panic!("expected veto-bound data for x=11"),
5055        }
5056    }
5057
5058    #[test]
5059    fn evaluate_data_should_enforce_text_enum_options() {
5060        // Higher-standard requirement: enum options must be enforced for text types.
5061        let data_path = DataPath::new(vec![], "tier".to_string());
5062
5063        let mut tier = crate::planning::semantics::LemmaType::primitive(
5064            crate::planning::semantics::TypeSpecification::Text {
5065                length: None,
5066                help: String::new(),
5067            },
5068        );
5069        tier.options.values = vec![
5070            crate::planning::semantics::OptionValue {
5071                value: crate::planning::semantics::BoundValueKind::unbound(
5072                    crate::planning::semantics::ValueKind::Text(Arc::from("silver")),
5073                ),
5074            },
5075            crate::planning::semantics::OptionValue {
5076                value: crate::planning::semantics::BoundValueKind::unbound(
5077                    crate::planning::semantics::ValueKind::Text(Arc::from("gold")),
5078                ),
5079            },
5080        ];
5081        let source = Source::new(
5082            crate::parsing::source::SourceType::Volatile,
5083            crate::parsing::ast::Span {
5084                start: 0,
5085                end: 0,
5086                line: 1,
5087                col: 0,
5088            },
5089        );
5090        let mut data = IndexMap::new();
5091        data.insert(
5092            data_path.clone(),
5093            crate::planning::semantics::DataDefinition::Value {
5094                value: crate::planning::semantics::LiteralValue::text("silver".to_string()),
5095                resolved_type: Arc::new(tier.clone()),
5096                origin: crate::planning::semantics::DataOrigin::Declared,
5097                source,
5098            },
5099        );
5100
5101        let input_key_index = data.keys().map(|p| (p.input_key(), p.clone())).collect();
5102        let data_len = data.len();
5103        let plan = ExecutionPlan {
5104            spec_name: "test".to_string(),
5105            commentary: None,
5106            data,
5107            normal_forms: Vec::new(),
5108            rules: IndexMap::new(),
5109            data_reference_order: Vec::new(),
5110            meta: IndexMap::new(),
5111            resolved_types: Arc::default(),
5112            family_units: Arc::new(FamilyUnitCatalog::default()),
5113            signature_index: IndexMap::new(),
5114            effective: EffectiveDate::Origin,
5115            effective_from: None,
5116            effective_to: None,
5117            start_line: 1,
5118            source_type: None,
5119            needed_by_rules: vec![NeededByRules::default(); data_len],
5120            data_display: IndexMap::new(),
5121            show_rules: IndexMap::new(),
5122            show_needed_by: IndexMap::new(),
5123            show_import_data: IndexMap::new(),
5124            reference_ends: IndexMap::new(),
5125            input_key_index,
5126            show_rule_index: IndexMap::new(),
5127            data_leaf: IndexMap::new(),
5128            member_targets: IndexMap::new(),
5129            row_templates: std::collections::BTreeMap::new(),
5130            globals: IndexMap::new(),
5131            writes: crate::planning::fill::Writes::default(),
5132            writes_by_spec: Arc::default(),
5133            writes_root: Arc::new(SpecIdentity {
5134                repository: None,
5135                spec: "test".to_string(),
5136                effective: EffectiveDate::Origin,
5137                slice: EffectiveDate::Origin,
5138            }),
5139            own_spec: Arc::new(LemmaSpec::new("test".to_string())),
5140            edges: Vec::new(),
5141            identity: SpecIdentity {
5142                repository: None,
5143                spec: "test".to_string(),
5144                effective: EffectiveDate::Origin,
5145                slice: EffectiveDate::Origin,
5146            },
5147            rule_candidates: std::collections::BTreeMap::new(),
5148            self_row_rules: Vec::new(),
5149            instance_lists: IndexMap::new(),
5150            row_mask: Vec::new(),
5151            initial_values: Vec::new(),
5152            walk_settled_leaves: Vec::new(),
5153            #[cfg(feature = "call-graph-check")]
5154            call_graph: CallGraph::default(),
5155            rule_ref_indexes: Vec::new(),
5156            data_slot_leaves: Vec::new(),
5157            slot_scale_targets: Vec::new(),
5158        };
5159
5160        let values = input_data(&[("tier", "platinum")]);
5161
5162        let evaluate_data = resolve_evaluate_data(&plan, values);
5163        match veto_reason(&plan, &evaluate_data, &data_path) {
5164            Some(reason) => {
5165                assert!(
5166                    reason.contains("allowed options") || reason.contains("platinum"),
5167                    "invalid enum must record violation, got: {reason}"
5168                );
5169            }
5170            None => panic!("expected veto-bound data for tier=platinum"),
5171        }
5172    }
5173
5174    fn empty_plan(effective: crate::parsing::ast::EffectiveDate) -> ExecutionPlan {
5175        ExecutionPlan {
5176            spec_name: "s".into(),
5177            commentary: None,
5178            data: IndexMap::new(),
5179            normal_forms: Vec::new(),
5180            rules: IndexMap::new(),
5181            data_reference_order: Vec::new(),
5182            meta: IndexMap::new(),
5183            resolved_types: Arc::default(),
5184            family_units: Arc::new(FamilyUnitCatalog::default()),
5185            signature_index: IndexMap::new(),
5186            effective,
5187            effective_from: None,
5188            effective_to: None,
5189            start_line: 1,
5190            source_type: None,
5191            needed_by_rules: Vec::new(),
5192            data_display: IndexMap::new(),
5193            show_rules: IndexMap::new(),
5194            show_needed_by: IndexMap::new(),
5195            show_import_data: IndexMap::new(),
5196            reference_ends: IndexMap::new(),
5197            input_key_index: IndexMap::new(),
5198            show_rule_index: IndexMap::new(),
5199            data_leaf: IndexMap::new(),
5200            member_targets: IndexMap::new(),
5201            row_templates: std::collections::BTreeMap::new(),
5202            globals: IndexMap::new(),
5203            writes: crate::planning::fill::Writes::default(),
5204            writes_by_spec: Arc::default(),
5205            writes_root: Arc::new(SpecIdentity {
5206                repository: None,
5207                spec: "test".to_string(),
5208                effective: EffectiveDate::Origin,
5209                slice: EffectiveDate::Origin,
5210            }),
5211            own_spec: Arc::new(LemmaSpec::new("test".to_string())),
5212            edges: Vec::new(),
5213            identity: SpecIdentity {
5214                repository: None,
5215                spec: "s".to_string(),
5216                effective: EffectiveDate::Origin,
5217                slice: EffectiveDate::Origin,
5218            },
5219            rule_candidates: std::collections::BTreeMap::new(),
5220            self_row_rules: Vec::new(),
5221            instance_lists: IndexMap::new(),
5222            row_mask: Vec::new(),
5223            initial_values: Vec::new(),
5224            walk_settled_leaves: Vec::new(),
5225            #[cfg(feature = "call-graph-check")]
5226            call_graph: CallGraph::default(),
5227            rule_ref_indexes: Vec::new(),
5228            data_slot_leaves: Vec::new(),
5229            slot_scale_targets: Vec::new(),
5230        }
5231    }
5232
5233    fn plans_by_effective(
5234        plans: impl IntoIterator<Item = ExecutionPlan>,
5235    ) -> BTreeMap<EffectiveDate, std::sync::Arc<ExecutionPlan>> {
5236        plans
5237            .into_iter()
5238            .map(|plan| (plan.effective.clone(), std::sync::Arc::new(plan)))
5239            .collect()
5240    }
5241
5242    /// Compiled plans for one spec name are ordered by `effective` key.
5243    #[test]
5244    fn plan_set_plans_are_in_ascending_effective_order() {
5245        let june = DateTimeValue {
5246            year: 2025,
5247            month: 6,
5248            day: 1,
5249            hour: 0,
5250            minute: 0,
5251            second: 0,
5252            microsecond: 0,
5253            timezone: None,
5254            granularity: DateGranularity::Full,
5255        };
5256        let dec = DateTimeValue {
5257            year: 2025,
5258            month: 12,
5259            day: 1,
5260            hour: 0,
5261            minute: 0,
5262            second: 0,
5263            microsecond: 0,
5264            timezone: None,
5265            granularity: DateGranularity::Full,
5266        };
5267
5268        let plans = plans_by_effective([
5269            empty_plan(EffectiveDate::Origin),
5270            empty_plan(EffectiveDate::DateTimeValue(june)),
5271            empty_plan(EffectiveDate::DateTimeValue(dec)),
5272        ]);
5273
5274        let effectives: Vec<_> = plans.keys().cloned().collect();
5275        for window in effectives.windows(2) {
5276            assert!(
5277                window[0] < window[1],
5278                "plans must be strictly ascending: {:?} >= {:?}",
5279                window[0],
5280                window[1]
5281            );
5282        }
5283    }
5284
5285    #[test]
5286    fn plan_at_exact_boundary_selects_later_slice() {
5287        use crate::parsing::ast::{DateTimeValue, EffectiveDate};
5288
5289        let june = DateTimeValue {
5290            year: 2025,
5291            month: 6,
5292            day: 1,
5293            hour: 0,
5294            minute: 0,
5295            second: 0,
5296            microsecond: 0,
5297            timezone: None,
5298
5299            granularity: DateGranularity::Full,
5300        };
5301        let dec = DateTimeValue {
5302            year: 2025,
5303            month: 12,
5304            day: 1,
5305            hour: 0,
5306            minute: 0,
5307            second: 0,
5308            microsecond: 0,
5309            timezone: None,
5310
5311            granularity: DateGranularity::Full,
5312        };
5313
5314        let june_key = EffectiveDate::DateTimeValue(june.clone());
5315        let dec_key = EffectiveDate::DateTimeValue(dec.clone());
5316        let plans = plans_by_effective([
5317            empty_plan(EffectiveDate::Origin),
5318            empty_plan(june_key.clone()),
5319            empty_plan(dec_key.clone()),
5320        ]);
5321
5322        let june_plan = plan_at(&plans, &june_key).expect("boundary instant");
5323        assert!(std::ptr::eq(
5324            june_plan,
5325            plans.get(&june_key).expect("june slice").as_ref()
5326        ));
5327
5328        let dec_plan = plan_at(&plans, &dec_key).expect("dec boundary");
5329        assert!(std::ptr::eq(
5330            dec_plan,
5331            plans.get(&dec_key).expect("dec slice").as_ref()
5332        ));
5333    }
5334
5335    #[test]
5336    fn plan_at_day_before_boundary_stays_in_earlier_slice() {
5337        use crate::parsing::ast::{DateTimeValue, EffectiveDate};
5338
5339        let june = DateTimeValue {
5340            year: 2025,
5341            month: 6,
5342            day: 1,
5343            hour: 0,
5344            minute: 0,
5345            second: 0,
5346            microsecond: 0,
5347            timezone: None,
5348
5349            granularity: DateGranularity::Full,
5350        };
5351        let may_end = DateTimeValue {
5352            year: 2025,
5353            month: 5,
5354            day: 31,
5355            hour: 23,
5356            minute: 59,
5357            second: 59,
5358            microsecond: 0,
5359            timezone: None,
5360
5361            granularity: DateGranularity::DateTime,
5362        };
5363
5364        let origin = EffectiveDate::Origin;
5365        let plans = plans_by_effective([
5366            empty_plan(origin.clone()),
5367            empty_plan(EffectiveDate::DateTimeValue(june)),
5368        ]);
5369
5370        let may_instant = EffectiveDate::DateTimeValue(may_end);
5371        let may_plan = plan_at(&plans, &may_instant).expect("may 31");
5372        assert!(std::ptr::eq(
5373            may_plan,
5374            plans.get(&origin).expect("origin slice").as_ref()
5375        ));
5376    }
5377
5378    #[test]
5379    fn plan_at_single_plan_matches_any_instant_after_start() {
5380        use crate::parsing::ast::{DateTimeValue, EffectiveDate};
5381
5382        let t = DateTimeValue {
5383            year: 2025,
5384            month: 3,
5385            day: 1,
5386            hour: 0,
5387            minute: 0,
5388            second: 0,
5389            microsecond: 0,
5390            timezone: None,
5391
5392            granularity: DateGranularity::Full,
5393        };
5394        let start = EffectiveDate::DateTimeValue(DateTimeValue {
5395            year: 2025,
5396            month: 1,
5397            day: 1,
5398            hour: 0,
5399            minute: 0,
5400            second: 0,
5401            microsecond: 0,
5402            timezone: None,
5403
5404            granularity: DateGranularity::Full,
5405        });
5406        let plans = plans_by_effective([empty_plan(start.clone())]);
5407        let instant = EffectiveDate::DateTimeValue(t);
5408        let selected = plan_at(&plans, &instant).expect("inside single slice");
5409        assert!(std::ptr::eq(
5410            selected,
5411            plans.get(&start).expect("single slice").as_ref()
5412        ));
5413    }
5414
5415    /// The show JSON shape is the IO contract for every non-Rust consumer
5416    /// (WASM playground, Hex, HTTP, TypeScript). Nail the exact envelope.
5417    #[test]
5418    fn show_json_shape_contract() {
5419        let mut engine = Engine::new();
5420        engine
5421            .load([(
5422                crate::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
5423                    "test.lemma",
5424                ))),
5425                r#"
5426                spec pricing
5427                data bridge_height: measure
5428                  -> unit meter: 1
5429                  -> suggest 100 meter
5430                data quantity: number -> minimum 0
5431                rule cost: bridge_height * quantity
5432                "#
5433                .to_string(),
5434            )])
5435            .unwrap();
5436        let now = DateTimeValue::now();
5437        let schema = engine.show(None, "pricing", Some(&now)).unwrap();
5438
5439        let value = crate::api::show_document(&engine, &schema);
5440
5441        let bh = &value["properties"]["bridge_height"];
5442        assert!(
5443            bh.is_object(),
5444            "data entry must be a named object, not tuple"
5445        );
5446        assert!(
5447            bh.get("x-lemma-type").is_some(),
5448            "data entry must expose `x-lemma-type` field"
5449        );
5450        assert!(
5451            bh.get("x-lemma-suggestion").is_some(),
5452            "bridge_height exposes `-> suggest` as schema suggestion"
5453        );
5454        assert!(
5455            bh.get("x-lemma-value").is_none(),
5456            "bridge_height is not filled from spec"
5457        );
5458
5459        let ty = &bh["x-lemma-type"];
5460        assert_eq!(
5461            ty["kind"], "measure",
5462            "kind tag sits on the type object itself"
5463        );
5464        assert!(
5465            ty["units"].is_array(),
5466            "measure-only fields flatten up to top level"
5467        );
5468        assert!(
5469            ty.get("options").is_none(),
5470            "text-only fields must not leak"
5471        );
5472
5473        let quantity = &value["properties"]["quantity"];
5474        assert_eq!(quantity["x-lemma-type"]["kind"], "number");
5475        assert!(
5476            quantity.get("x-lemma-suggestion").is_none(),
5477            "quantity has no suggestion"
5478        );
5479        assert!(
5480            quantity.get("x-lemma-value").is_none(),
5481            "quantity has no fill literal"
5482        );
5483
5484        let cost = &value["x-lemma-rules"]["cost"];
5485        assert_eq!(
5486            cost["type"]["kind"], "measure",
5487            "rule types nest under type"
5488        );
5489        assert!(
5490            cost["type"]["units"].is_array()
5491                && !cost["type"]["units"].as_array().unwrap().is_empty(),
5492            "measure rule result types expose declared units"
5493        );
5494        assert!(
5495            cost["type"]["units"][0].get("factor").is_some(),
5496            "measure rule units use factor field"
5497        );
5498        assert!(cost.get("branches").is_some(), "ShowRule exposes branches");
5499        assert!(
5500            cost.get("depends_on_rules").is_some(),
5501            "ShowRule exposes depends_on_rules"
5502        );
5503    }
5504
5505    #[test]
5506    fn show_rule_result_units_contract() {
5507        let mut engine = Engine::new();
5508        engine
5509            .load([(
5510                crate::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
5511                    "units_contract.lemma",
5512                ))),
5513                r#"
5514                spec units_contract
5515                data money: measure
5516                  -> unit eur: 1
5517                  -> unit usd: 0.91
5518                data rate: ratio
5519                  -> unit basis_points: 10000
5520                  -> unit percent: 100
5521                  -> suggest 500 basis_points
5522                rule total: money
5523                rule rate_out: rate
5524                "#
5525                .to_string(),
5526            )])
5527            .unwrap();
5528        let now = DateTimeValue::now();
5529        let schema = engine.show(None, "units_contract", Some(&now)).unwrap();
5530        let value = crate::api::show_document(&engine, &schema);
5531
5532        let money_units = &value["properties"]["money"]["x-lemma-type"]["units"];
5533        assert!(money_units.is_array() && !money_units.as_array().unwrap().is_empty());
5534        assert!(money_units[0].get("name").is_some());
5535        assert!(money_units[0].get("factor").is_some());
5536        assert!(money_units[0]["factor"].get("numer").is_some());
5537        assert!(money_units[0]["factor"].get("denom").is_some());
5538
5539        let rate_units = &value["properties"]["rate"]["x-lemma-type"]["units"];
5540        assert!(rate_units.is_array() && !rate_units.as_array().unwrap().is_empty());
5541        assert!(rate_units[0].get("name").is_some());
5542        assert!(rate_units[0].get("value").is_some());
5543        assert!(rate_units[0]["value"].get("numer").is_some());
5544        assert!(rate_units[0]["value"].get("denom").is_some());
5545
5546        let total_rule_units = &value["x-lemma-rules"]["total"]["type"]["units"];
5547        let money_unit_names: Vec<_> = money_units
5548            .as_array()
5549            .unwrap()
5550            .iter()
5551            .map(|u| u["name"].as_str().unwrap())
5552            .collect();
5553        let total_rule_unit_names: Vec<_> = total_rule_units
5554            .as_array()
5555            .unwrap()
5556            .iter()
5557            .map(|u| u["name"].as_str().unwrap())
5558            .collect();
5559        assert_eq!(total_rule_unit_names, money_unit_names);
5560
5561        let rate_out_rule_units = &value["x-lemma-rules"]["rate_out"]["type"]["units"];
5562        let rate_unit_names: Vec<_> = rate_units
5563            .as_array()
5564            .unwrap()
5565            .iter()
5566            .map(|u| u["name"].as_str().unwrap())
5567            .collect();
5568        let rate_out_rule_unit_names: Vec<_> = rate_out_rule_units
5569            .as_array()
5570            .unwrap()
5571            .iter()
5572            .map(|u| u["name"].as_str().unwrap())
5573            .collect();
5574        assert_eq!(rate_out_rule_unit_names, rate_unit_names);
5575    }
5576
5577    #[test]
5578    fn show_document_rules_round_trip_as_show_rule() {
5579        let mut engine = Engine::new();
5580        engine
5581            .load([(
5582                crate::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("s.lemma"))),
5583                r#"
5584                spec s
5585                data age: number -> minimum 0 -> suggest 18
5586                data grade: text -> options "A", "B", "C"
5587                rule adult: age >= 18
5588                "#
5589                .to_string(),
5590            )])
5591            .unwrap();
5592        let now = DateTimeValue::now();
5593        let schema = engine.show(None, "s", Some(&now)).unwrap();
5594
5595        let document = crate::api::show_document(&engine, &schema);
5596        let rule_json = document["x-lemma-rules"]["adult"].clone();
5597        let rule: crate::api::ShowRule = serde_json::from_value(rule_json.clone()).unwrap();
5598        assert_eq!(serde_json::to_value(&rule).unwrap(), rule_json);
5599        assert!(
5600            document["properties"].get("grade").is_none(),
5601            "unused grade is Types-only, not Data"
5602        );
5603        let grade = &document["x-lemma-types"]["grade"];
5604        assert_eq!(grade["options"], serde_json::json!(["A", "B", "C"]));
5605        assert_eq!(grade["kind"], "text");
5606    }
5607
5608    const COST_PRICE_SPEC: &str = r#"
5609spec cost_price
5610uses lemma units
5611
5612data money: measure
5613  -> unit eur: 1.00
5614  -> unit inr: 0.0092
5615
5616data labor_cost: measure
5617  -> unit eur_per_hour: eur/hour
5618  -> unit inr_per_hour: inr/hour
5619  -> suggest 25 eur_per_hour
5620
5621data product_cost: measure
5622  -> unit eur_per_kg: eur/kilogram
5623  -> unit inr_per_kg: inr/kilogram
5624  -> suggest 4 eur_per_kg
5625
5626data throughput: measure
5627  -> unit kg_per_hour: kilogram/hour
5628  -> suggest 12 kg_per_hour
5629
5630rule cost_price: product_cost + labor_cost / throughput
5631"#;
5632
5633    fn cost_price_inputs() -> IndexMap<String, EvaluateDataValue> {
5634        let mut data = IndexMap::new();
5635        data.insert(
5636            "product_cost".into(),
5637            EvaluateDataValue::string("4 eur_per_kg"),
5638        );
5639        data.insert(
5640            "labor_cost".into(),
5641            EvaluateDataValue::string("25 eur_per_hour"),
5642        );
5643        data.insert(
5644            "throughput".into(),
5645            EvaluateDataValue::string("12 kg_per_hour"),
5646        );
5647        data
5648    }
5649
5650    const FILM_ACCESS: &str = r#"
5651spec premium_membership
5652uses lemma units
5653data start: date
5654data length: units.calendar
5655rule valid: now in start...start + length
5656
5657spec film_access
5658uses premium_membership
5659data type: text
5660  -> option "rental"
5661  -> option "purchase"
5662data views_consumed: number
5663data premium_member: boolean
5664rule max_views: 3
5665  unless premium_membership.valid then 10
5666  unless premium_member then 5
5667rule can_view: no
5668  unless type is "rental" and views_consumed < max_views then yes
5669  unless type is "purchase" then yes
5670"#;
5671
5672    fn film_access_effective() -> DateTimeValue {
5673        DateTimeValue {
5674            year: 2027,
5675            month: 2,
5676            day: 14,
5677            hour: 12,
5678            minute: 0,
5679            second: 0,
5680            microsecond: 0,
5681            timezone: Some(TimezoneValue { offset_minutes: 0 }),
5682            granularity: DateGranularity::DateTime,
5683        }
5684    }
5685
5686    #[test]
5687    fn evaluate_data_accepts_per_unit_measure_equivalent_to_canonical_magnitude() {
5688        let mut engine = Engine::new();
5689        engine
5690            .load([(
5691                crate::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
5692                    "cost_price.lemma",
5693                ))),
5694                COST_PRICE_SPEC.to_string(),
5695            )])
5696            .expect("load");
5697        let plans = engine
5698            .plans
5699            .get_plans(None, "cost_price")
5700            .expect("plans for cost_price");
5701        let plan = plans.values().next().expect("plan");
5702        let mut data = IndexMap::new();
5703        data.insert(
5704            "product_cost".into(),
5705            EvaluateDataValue::string("4 eur_per_kg"),
5706        );
5707        data.insert(
5708            "labor_cost".into(),
5709            EvaluateDataValue::string("0.0069444444444444444444444444 eur_per_hour"),
5710        );
5711        data.insert(
5712            "throughput".into(),
5713            EvaluateDataValue::string("0.0033333333333333333333333333 kg_per_hour"),
5714        );
5715        let evaluate_data = resolve_evaluate_data(plan, data);
5716        assert!(
5717            !evaluate_data
5718                .bindings
5719                .values()
5720                .any(|b| matches!(b, OperationResult::Veto(_))),
5721            "parsed decimal run data values must not be veto-bound after input boundary: {:?}",
5722            evaluate_data.bindings
5723        );
5724    }
5725
5726    #[test]
5727    fn evaluate_data_accepts_per_unit_measure() {
5728        let mut engine = Engine::new();
5729        engine
5730            .load([(
5731                crate::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
5732                    "cost_price.lemma",
5733                ))),
5734                COST_PRICE_SPEC.to_string(),
5735            )])
5736            .expect("load");
5737        let plans = engine
5738            .plans
5739            .get_plans(None, "cost_price")
5740            .expect("plans for cost_price");
5741        let plan = plans.values().next().expect("plan");
5742        let evaluate_data = resolve_evaluate_data(plan, cost_price_inputs());
5743        assert!(!evaluate_data
5744            .bindings
5745            .values()
5746            .any(|b| matches!(b, OperationResult::Veto(_))));
5747    }
5748
5749    #[test]
5750    fn evaluate_data_rejects_oversize_input() {
5751        let mut engine = Engine::new();
5752        engine
5753            .load([(
5754                crate::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
5755                    "cost_price.lemma",
5756                ))),
5757                COST_PRICE_SPEC.to_string(),
5758            )])
5759            .expect("load");
5760        let plans = engine
5761            .plans
5762            .get_plans(None, "cost_price")
5763            .expect("plans for cost_price");
5764        let plan = plans.values().next().expect("plan");
5765        let mut data = cost_price_inputs();
5766        data.insert(
5767            "labor_cost".into(),
5768            EvaluateDataValue::string(
5769                "1000000000000000000000000000000000000000000000000000000000000 eur_per_hour",
5770            ),
5771        );
5772        let evaluate_data = resolve_evaluate_data(plan, data);
5773        assert!(matches!(
5774            binding(plan, &evaluate_data, &DataPath::local("labor_cost".into())),
5775            Some(OperationResult::Veto(_))
5776        ));
5777    }
5778    #[test]
5779    fn typedecl_default_stays_typedecl_on_immutable_plan() {
5780        let mut engine = Engine::new();
5781        engine
5782            .load([(
5783                crate::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("s.lemma"))),
5784                r#"
5785        spec s
5786        data n: number -> suggest 42
5787        rule r: n
5788    "#
5789                .to_string(),
5790            )])
5791            .expect("load");
5792
5793        let plans = engine.plans.get_plans(None, "s").expect("plans for s");
5794        let plan = plans.values().next().expect("plan");
5795        let path = DataPath::local("n".into());
5796        match plan.data.get(&path).expect("n") {
5797            DataDefinition::TypeDeclaration {
5798                declared_suggestion: Some(_),
5799                ..
5800            } => {}
5801            other => panic!("expected TypeDeclaration with default, got {other:?}"),
5802        }
5803    }
5804
5805    fn response_missing_data_union(response: &crate::Response) -> Vec<String> {
5806        let mut seen = std::collections::HashSet::new();
5807        let mut names = Vec::new();
5808        for result in response.results.values() {
5809            for key in result.missing_data() {
5810                if seen.insert(key.clone()) {
5811                    names.push(key.clone());
5812                }
5813            }
5814        }
5815        names
5816    }
5817
5818    #[test]
5819    fn evaluate_prunes_inactive_kind_branches_for_total_price() {
5820        let code = r#"
5821spec bag
5822uses lemma units
5823
5824data weight: measure
5825  -> unit kg: 1
5826
5827data money: measure
5828  -> unit eur: 1
5829
5830data price_per_weight: measure
5831  -> unit eur_per_kg: eur/kg
5832
5833data item_cost: price_per_weight
5834data finish_a: price_per_weight
5835data finish_b: price_per_weight
5836
5837rule total_price: weight * (item_cost + finish_a + finish_b)
5838
5839spec calc
5840uses bag
5841  -> with item_cost: item_cost
5842  -> with finish_a: finish_a
5843
5844data kind: text -> options "red", "blue"
5845
5846rule price_red: 1.5 eur_per_kg
5847rule price_red_finish_a: 0.45 eur_per_kg
5848
5849rule price_blue: 2.0 eur_per_kg
5850rule price_blue_finish_a: 0.55 eur_per_kg
5851
5852rule item_cost: veto "No item cost"
5853  unless kind is "red" then price_red
5854  unless kind is "blue" then price_blue
5855
5856rule finish_a: veto "No finish_a"
5857  unless kind is "red" then price_red_finish_a
5858  unless kind is "blue" then price_blue_finish_a
5859
5860rule total_price: bag.total_price
5861"#;
5862
5863        let mut engine = Engine::new();
5864        engine
5865            .load([(
5866                crate::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
5867                    "calc.lemma",
5868                ))),
5869                code.to_string(),
5870            )])
5871            .unwrap();
5872
5873        let now = DateTimeValue::now();
5874        let mut inputs = IndexMap::new();
5875        inputs.insert("kind".to_string(), "red".into());
5876        let response = engine
5877            .evaluate(
5878                None,
5879                "calc",
5880                Some(&now),
5881                inputs,
5882                Some(&["total_price".to_string()]),
5883                false,
5884            )
5885            .expect("evaluate must succeed");
5886
5887        assert_eq!(
5888            response_missing_data_union(&response),
5889            vec!["bag.weight".to_string(), "bag.finish_b".to_string(),],
5890            "supplied kind and with-bound finish_a/item_cost omitted"
5891        );
5892    }
5893
5894    #[test]
5895    fn evaluate_includes_membership_dates_when_premium_member_false() {
5896        let mut engine = Engine::new();
5897        engine
5898            .load([(crate::SourceType::Volatile, FILM_ACCESS.to_string())])
5899            .expect("film_access spec must load");
5900        let now = film_access_effective();
5901        let mut inputs = IndexMap::new();
5902        inputs.insert("type".to_string(), "rental".into());
5903        inputs.insert("views_consumed".to_string(), "6".into());
5904        inputs.insert("premium_member".to_string(), "false".into());
5905        let response = engine
5906            .evaluate(
5907                None,
5908                "film_access",
5909                Some(&now),
5910                inputs,
5911                Some(&["can_view".to_string()]),
5912                false,
5913            )
5914            .expect("evaluate must succeed");
5915
5916        assert_eq!(
5917            response_missing_data_union(&response),
5918            vec![
5919                "premium_membership.start".to_string(),
5920                "premium_membership.length".to_string(),
5921            ],
5922            "membership dates when premium_member is false"
5923        );
5924    }
5925
5926    #[test]
5927    fn evaluate_includes_membership_dates_when_premium_member_unknown() {
5928        let mut engine = Engine::new();
5929        engine
5930            .load([(crate::SourceType::Volatile, FILM_ACCESS.to_string())])
5931            .expect("film_access spec must load");
5932        let now = film_access_effective();
5933        let mut inputs = IndexMap::new();
5934        inputs.insert("type".to_string(), "rental".into());
5935        inputs.insert("views_consumed".to_string(), "6".into());
5936        let response = engine
5937            .evaluate(
5938                None,
5939                "film_access",
5940                Some(&now),
5941                inputs,
5942                Some(&["can_view".to_string()]),
5943                false,
5944            )
5945            .expect("evaluate must succeed");
5946
5947        assert_eq!(
5948            response_missing_data_union(&response),
5949            vec![
5950                "premium_member".to_string(),
5951                "premium_membership.start".to_string(),
5952                "premium_membership.length".to_string(),
5953            ],
5954            "premium_member plus membership dates when unknown"
5955        );
5956    }
5957
5958    const UNITS_SPEC: &str = r#"
5959spec units
5960uses lemma units
5961data money: measure
5962  -> unit eur: 1
5963"#;
5964
5965    const WAREHOUSING_SPEC: &str = r#"
5966spec warehousing
5967uses units
5968uses si: lemma units
5969
5970data units_per_pallet: number
5971  -> minimum 1
5972  -> suggest 1
5973
5974data storage_duration: si.duration
5975  -> minimum 0 week
5976  -> suggest 10 day
5977
5978data interbranch_transport_per_pallet: units.money
5979  -> minimum 0 eur
5980  -> suggest 0 eur
5981
5982data inbound_handling_per_pallet: units.money
5983  -> minimum 0 eur
5984  -> suggest 0 eur
5985
5986data storage_per_pallet_per_week: units.money
5987  -> minimum 0 eur
5988  -> suggest 10 eur
5989
5990data labeling_per_pallet: units.money
5991  -> minimum 0 eur
5992  -> suggest 0 eur
5993
5994data outbound_handling_per_pallet: units.money
5995  -> minimum 0 eur
5996  -> suggest 0 eur
5997
5998rule storage_cost_per_pallet:
5999  storage_per_pallet_per_week
6000  * (storage_duration as week as number -> ceil)
6001
6002rule total_logistics_per_pallet:
6003  interbranch_transport_per_pallet
6004  + inbound_handling_per_pallet
6005  + storage_cost_per_pallet
6006  + labeling_per_pallet
6007  + outbound_handling_per_pallet
6008
6009rule total_logistics_per_ce:
6010  total_logistics_per_pallet / units_per_pallet
6011"#;
6012
6013    const QUOTATION_SPEC: &str = r#"
6014spec quotation
6015uses wh: warehousing
6016rule total: wh.total_logistics_per_ce
6017"#;
6018
6019    fn load_cross_spec_fixtures(engine: &mut Engine) {
6020        engine
6021            .load([(crate::SourceType::Volatile, UNITS_SPEC.to_string())])
6022            .expect("units spec must load");
6023        engine
6024            .load([(crate::SourceType::Volatile, WAREHOUSING_SPEC.to_string())])
6025            .expect("warehousing spec must load");
6026    }
6027
6028    #[test]
6029    fn quotation_inherits_unit_scope_from_warehousing_import() {
6030        let mut engine = Engine::new();
6031        load_cross_spec_fixtures(&mut engine);
6032        engine
6033            .load([(crate::SourceType::Volatile, QUOTATION_SPEC.to_string())])
6034            .expect("quotation must plan without uses lemma units");
6035        let plans = engine
6036            .plans
6037            .get_plans(None, "quotation")
6038            .expect("plans for quotation");
6039        let plan = plans.values().next().expect("plan");
6040
6041        let expression_units = &plan.resolved_types.unit_index;
6042        expression_units
6043            .resolve("week")
6044            .expect("week reaches quotation via wh → si");
6045        expression_units
6046            .resolve("wh.week")
6047            .expect("alias.unit resolves week in warehousing scope");
6048        expression_units
6049            .resolve("minute")
6050            .expect("minute reaches quotation via transitive unit scope");
6051    }
6052
6053    fn warehousing_default_inputs(prefix: &str) -> IndexMap<String, EvaluateDataValue> {
6054        let key = |name: &str| {
6055            if prefix.is_empty() {
6056                name.to_string()
6057            } else {
6058                format!("{prefix}.{name}")
6059            }
6060        };
6061        IndexMap::from([
6062            (key("units_per_pallet"), EvaluateDataValue::string("1")),
6063            (key("storage_duration"), EvaluateDataValue::string("10 day")),
6064            (
6065                key("interbranch_transport_per_pallet"),
6066                EvaluateDataValue::string("0 eur"),
6067            ),
6068            (
6069                key("inbound_handling_per_pallet"),
6070                EvaluateDataValue::string("0 eur"),
6071            ),
6072            (
6073                key("storage_per_pallet_per_week"),
6074                EvaluateDataValue::string("10 eur"),
6075            ),
6076            (
6077                key("labeling_per_pallet"),
6078                EvaluateDataValue::string("0 eur"),
6079            ),
6080            (
6081                key("outbound_handling_per_pallet"),
6082                EvaluateDataValue::string("0 eur"),
6083            ),
6084        ])
6085    }
6086
6087    #[test]
6088    fn quotation_evaluates_cross_spec_duration_conversion() {
6089        let mut engine = Engine::new();
6090        load_cross_spec_fixtures(&mut engine);
6091        engine
6092            .load([(crate::SourceType::Volatile, QUOTATION_SPEC.to_string())])
6093            .expect("quotation must load");
6094        let plans = engine
6095            .plans
6096            .get_plans(None, "quotation")
6097            .expect("plans for quotation");
6098        let plan = plans.values().next().expect("plan");
6099        assert!(
6100            plan.resolved_types
6101                .unit_index
6102                .unique_owner("week")
6103                .is_some(),
6104            "week is in scope once, through a type the used spec declares"
6105        );
6106        let now = DateTimeValue::now();
6107        let response = engine
6108            .evaluate(
6109                None,
6110                "quotation",
6111                Some(&now),
6112                warehousing_default_inputs("wh"),
6113                None,
6114                false,
6115            )
6116            .expect("quotation must evaluate");
6117        let display = response
6118            .results
6119            .get("total")
6120            .expect("rule total must be present")
6121            .result()
6122            .expect("total must have display")
6123            .to_string();
6124        assert_eq!(
6125            display, "20 eur",
6126            "10 eur/week * ceil(10 day as week) / 1 CE must be 20 eur, got: {display}"
6127        );
6128    }
6129
6130    #[test]
6131    fn ratio_range_default_endpoints_must_be_ratio_not_measure() {
6132        let code = r#"
6133spec policy
6134data allowed_band: ratio range -> suggest 10%...50%
6135rule band: allowed_band
6136"#;
6137        let mut engine = Engine::new();
6138        engine
6139            .load([(
6140                crate::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
6141                    "ratio_range_endpoint_typing.lemma",
6142                ))),
6143                code.to_string(),
6144            )])
6145            .unwrap();
6146
6147        let plans = engine
6148            .plans
6149            .get_plans(None, "policy")
6150            .expect("plans for policy");
6151        let plan = plans.values().next().expect("plan");
6152        let path = DataPath::local("allowed_band".into());
6153        let def = plan.data.get(&path).expect("allowed_band in plan.data");
6154        let suggestion = def
6155            .bound_suggestion()
6156            .expect("declared default must exist")
6157            .to_literal();
6158
6159        let (left, right) = match &suggestion.value {
6160            crate::planning::semantics::ValueKind::Range(l, r) => (l.as_ref(), r.as_ref()),
6161            other => panic!("expected Range, got {other:?}"),
6162        };
6163        for (label, endpoint) in [("left", left), ("right", right)] {
6164            assert!(
6165                matches!(
6166                    &endpoint.value,
6167                    crate::planning::semantics::ValueKind::Ratio(_)
6168                ),
6169                "{label} endpoint must be Ratio for a percent literal in a ratio range default, got {:?}",
6170                endpoint.value
6171            );
6172            assert!(
6173                matches!(
6174                    &endpoint.value,
6175                    crate::planning::semantics::ValueKind::Ratio(_)
6176                ),
6177                "{label} endpoint ValueKind must be Ratio (got {:?})",
6178                endpoint.value
6179            );
6180        }
6181    }
6182
6183    #[test]
6184    fn ratio_range_typedef_with_second_ratio_field_loads() {
6185        let code = r#"
6186spec policy
6187data margin_pct: ratio -> suggest 15%
6188data allowed_band: ratio range
6189rule margin: margin_pct
6190rule band_slot: allowed_band
6191"#;
6192        let mut engine = Engine::new();
6193        engine
6194            .load([(
6195                crate::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
6196                    "ratio_range_load.lemma",
6197                ))),
6198                code.to_string(),
6199            )])
6200            .unwrap();
6201
6202        let plans = engine
6203            .plans
6204            .get_plans(None, "policy")
6205            .expect("plans for policy");
6206        let plan = plans.values().next().expect("plan");
6207        let path = DataPath::local("allowed_band".into());
6208        let def = plan.data.get(&path).expect("allowed_band in plan.data");
6209        let lemma_type = def
6210            .schema_type()
6211            .expect("allowed_band must be a typed data slot");
6212        match &lemma_type.specifications {
6213            TypeSpecification::RatioRange { units, .. } => {
6214                let names: Vec<&str> = units.iter().map(|u| u.name.as_str()).collect();
6215                assert!(
6216                    names.contains(&"percent"),
6217                    "ratio range must inherit builtin percent, got {names:?}"
6218                );
6219            }
6220            other => panic!("allowed_band must be RatioRange, got {other:?}"),
6221        }
6222    }
6223
6224    #[test]
6225    fn show_display_indents_every_commentary_line() {
6226        let mut engine = Engine::new();
6227        engine
6228            .load([(
6229                crate::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
6230                    "alpha2.lemma",
6231                ))),
6232                "spec alpha2\n\"\"\"\nAdded:\nSS: South Sudan\n\nRemoved:\nYU: Yugoslavia\n\"\"\"\ndata code: text\nrule name: code\n"
6233                    .to_string(),
6234            )])
6235            .unwrap();
6236        let now = DateTimeValue::now();
6237        let text = engine.show(None, "alpha2", Some(&now)).unwrap().to_string();
6238        assert!(
6239            text.starts_with(
6240                "Spec: alpha2\n  Added:\n  SS: South Sudan\n\n  Removed:\n  YU: Yugoslavia\n"
6241            ),
6242            "{text}"
6243        );
6244    }
6245
6246    #[test]
6247    fn show_display_puts_effective_window_on_header_without_other_versions() {
6248        let mut engine = Engine::new();
6249        engine
6250            .load([(
6251                crate::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
6252                    "rates.lemma",
6253                ))),
6254                "spec rates 2024-01-01\n\"\"\"\nStandard rate\n\"\"\"\ndata x: 1\nrule r: x\n\nspec rates 2025-01-01\ndata x: 2\nrule r: x\n"
6255                    .to_string(),
6256            )])
6257            .unwrap();
6258        let effective: DateTimeValue = "2024-06-01".parse().expect("date must parse");
6259        let text = engine
6260            .show(None, "rates", Some(&effective))
6261            .unwrap()
6262            .to_string();
6263        assert!(
6264            text.starts_with("Spec: rates 2024-01-01...2025-01-01\n  Standard rate\n"),
6265            "{text}"
6266        );
6267        assert!(!text.contains("versions"), "{text}");
6268        assert!(!text.contains("effective_"), "{text}");
6269    }
6270
6271    #[test]
6272    fn show_display_undated_predecessor_uses_until() {
6273        let mut engine = Engine::new();
6274        engine
6275            .load([(
6276                crate::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
6277                    "calc.lemma",
6278                ))),
6279                "spec calc\ndata x: 1\nrule r: x\n\nspec calc 2027\ndata x: 2\nrule r: x\n"
6280                    .to_string(),
6281            )])
6282            .unwrap();
6283        let effective: DateTimeValue = "2026-01-01".parse().expect("date must parse");
6284        let text = engine
6285            .show(None, "calc", Some(&effective))
6286            .unwrap()
6287            .to_string();
6288        assert!(text.starts_with("Spec: calc ...2027\n"), "{text}");
6289        assert!(!text.contains('→'), "{text}");
6290    }
6291
6292    fn nested_import_plan() -> (Engine, Arc<ExecutionPlan>) {
6293        let mut engine = Engine::new();
6294        engine
6295            .load([(
6296                crate::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(
6297                    "peel.lemma",
6298                ))),
6299                r#"
6300spec leaf
6301data x: number
6302rule rx: x
6303
6304spec mid
6305uses nested: leaf
6306data y: number
6307rule ry: y
6308
6309spec outer
6310uses m: mid
6311"#
6312                .to_string(),
6313            )])
6314            .expect("load nested import fixture");
6315        let plans = engine
6316            .plans
6317            .get_plans(None, "outer")
6318            .expect("plans for outer");
6319        let plan = Arc::clone(plans.values().next().expect("outer plan"));
6320        (engine, plan)
6321    }
6322
6323    /// Template plan of import `alias` of `plan`.
6324    fn import_template<'a>(plan: &'a ExecutionPlan, alias: &str) -> &'a ExecutionPlan {
6325        let Some(DataDefinition::Import { row, .. }) =
6326            plan.data.get(&DataPath::local(alias.to_string()))
6327        else {
6328            panic!("`{alias}` must be an import of `{}`", plan.spec_name);
6329        };
6330        plan.row_template(&row.identity)
6331    }
6332
6333    #[test]
6334    fn input_key_index_covers_own_slots_only() {
6335        let (_, plan) = nested_import_plan();
6336
6337        let mut entry_keys: Vec<String> = plan.data.keys().map(DataPath::input_key).collect();
6338        let mut index_keys: Vec<String> = plan.input_key_index.keys().cloned().collect();
6339        entry_keys.sort();
6340        index_keys.sort();
6341        assert_eq!(entry_keys, index_keys);
6342        assert_eq!(entry_keys, vec!["m".to_string()]);
6343        assert_eq!(plan.input_slots().count(), 0);
6344    }
6345
6346    #[test]
6347    fn import_rows_carry_their_template_data() {
6348        let (_, plan) = nested_import_plan();
6349
6350        let mid = import_template(&plan, "m");
6351        assert_eq!(mid.spec_name, "mid");
6352        assert!(matches!(
6353            mid.data.get(&DataPath::local("y".into())),
6354            Some(DataDefinition::Value { .. } | DataDefinition::TypeDeclaration { .. })
6355        ));
6356        let leaf = import_template(mid, "nested");
6357        assert_eq!(leaf.spec_name, "leaf");
6358        assert!(matches!(
6359            leaf.data.get(&DataPath::local("x".into())),
6360            Some(DataDefinition::Value { .. } | DataDefinition::TypeDeclaration { .. })
6361        ));
6362        assert!(plan
6363            .data
6364            .keys()
6365            .chain(mid.data.keys())
6366            .chain(leaf.data.keys())
6367            .all(|path| path.segments.is_empty()));
6368    }
6369
6370    #[test]
6371    fn rules_of_imports_stay_in_their_templates() {
6372        let (_, plan) = nested_import_plan();
6373
6374        assert!(plan.rules.is_empty());
6375        let mid = import_template(&plan, "m");
6376        let leaf = import_template(mid, "nested");
6377        let keys = |template: &ExecutionPlan| -> Vec<String> {
6378            template.rules.keys().map(RulePath::input_key).collect()
6379        };
6380        assert_eq!(keys(mid), vec!["ry".to_string()]);
6381        assert_eq!(keys(leaf), vec!["rx".to_string()]);
6382        assert!(plan.get_rule("m.ry").is_none());
6383    }
6384
6385    #[test]
6386    fn dotted_key_resolves_through_import_templates() {
6387        let (_, plan) = nested_import_plan();
6388        let fields = crate::evaluation::evaluate_data::row_field_definitions(
6389            &plan,
6390            &plan.request_globals(),
6391            "m.nested.x",
6392            Vec::new(),
6393        );
6394        assert_eq!(
6395            fields.len(),
6396            1,
6397            "`m.nested.x` names data of the leaf template"
6398        );
6399        let (template, definition, _, field) = &fields[0];
6400        assert_eq!(template.spec_name, "leaf");
6401        assert_eq!(field.data, "x");
6402        assert!(matches!(
6403            definition,
6404            DataDefinition::Value { .. } | DataDefinition::TypeDeclaration { .. }
6405        ));
6406        assert!(crate::evaluation::evaluate_data::row_field_definitions(
6407            &plan,
6408            &plan.request_globals(),
6409            "m.x",
6410            Vec::new()
6411        )
6412        .is_empty());
6413        let fields = crate::evaluation::evaluate_data::row_field_definitions(
6414            &plan,
6415            &plan.request_globals(),
6416            "m.nested",
6417            Vec::new(),
6418        );
6419        assert_eq!(
6420            fields.len(),
6421            1,
6422            "`m.nested` names the `uses` slot of the mid template"
6423        );
6424        let (template, definition, _, _) = &fields[0];
6425        assert_eq!(template.spec_name, "mid");
6426        assert!(matches!(definition, DataDefinition::Import { .. }));
6427    }
6428}