Skip to main content

lemma/planning/
unit_index.rs

1//! Expression-scope unit index: every declarer of each bare unit name in scope.
2//! Qualify with `Type.unit`, `alias.Type.unit`, nested import paths, or `alias.unit`
3//! when that import scope identifies the owner.
4//!
5//! Units of the rows of a list of a spec (`data lines: line list`) are named only
6//! qualified by the list (`lines.Type.unit`): a list imports no units, so a bare name
7//! never reaches them. In a list's arguments the row's own units come first (see the
8//! row scopes of the graph).
9
10use crate::planning::semantics::{
11    primitive_ratio_arc, LemmaType, SpecVersionKey, TypeFamily, TypeSpecification,
12};
13use indexmap::IndexMap;
14use std::collections::{BTreeMap, BTreeSet, HashMap};
15use std::sync::Arc;
16
17/// Owner recorded while types are still being resolved. Local types are names only;
18/// imported types keep the Arc the other spec already finalized.
19#[derive(Debug, Clone)]
20pub enum PlanningOwner {
21    PrimitiveRatio,
22    Local {
23        type_name: String,
24    },
25    Imported {
26        import_path: Vec<String>,
27        type_name: String,
28        lemma_type: Arc<LemmaType>,
29    },
30}
31
32impl PlanningOwner {
33    fn type_name(&self) -> &str {
34        match self {
35            Self::PrimitiveRatio => "ratio",
36            Self::Local { type_name } | Self::Imported { type_name, .. } => type_name,
37        }
38    }
39
40    fn import_path(&self) -> &[String] {
41        match self {
42            Self::PrimitiveRatio | Self::Local { .. } => &[],
43            Self::Imported { import_path, .. } => import_path.as_slice(),
44        }
45    }
46
47    fn same_slot(&self, type_name: &str, import_path: &[String]) -> bool {
48        match self {
49            Self::PrimitiveRatio => false,
50            Self::Local {
51                type_name: existing,
52            } => import_path.is_empty() && existing == type_name,
53            Self::Imported {
54                import_path: existing_path,
55                type_name: existing,
56                ..
57            } => existing_path.as_slice() == import_path && existing == type_name,
58        }
59    }
60
61    /// Local bodies come from `resolved`. Imported bodies are the other spec's final Arc.
62    pub fn lemma_type<'a>(
63        &'a self,
64        resolved: &'a IndexMap<String, Arc<LemmaType>>,
65    ) -> &'a LemmaType {
66        match self {
67            Self::PrimitiveRatio => primitive_ratio_arc().as_ref(),
68            Self::Local { type_name } => resolved
69                .get(type_name)
70                .expect("BUG: local unit owner missing from resolved")
71                .as_ref(),
72            Self::Imported { lemma_type, .. } => lemma_type.as_ref(),
73        }
74    }
75}
76
77/// Bound owner after magnitudes: eval and Show read Arcs from here.
78#[derive(Debug, Clone)]
79pub enum UnitOwner {
80    PrimitiveRatio,
81    Named {
82        import_path: Vec<String>,
83        type_name: String,
84        lemma_type: Arc<LemmaType>,
85    },
86}
87
88impl UnitOwner {
89    #[must_use]
90    pub fn lemma_type(&self) -> &Arc<LemmaType> {
91        match self {
92            Self::PrimitiveRatio => primitive_ratio_arc(),
93            Self::Named { lemma_type, .. } => lemma_type,
94        }
95    }
96
97    #[must_use]
98    pub fn type_name(&self) -> &str {
99        match self {
100            Self::PrimitiveRatio => "ratio",
101            Self::Named { type_name, .. } => type_name,
102        }
103    }
104
105    #[must_use]
106    pub fn import_path(&self) -> &[String] {
107        match self {
108            Self::PrimitiveRatio => &[],
109            Self::Named { import_path, .. } => import_path.as_slice(),
110        }
111    }
112}
113
114/// Conflict while merging a unit owner into the index during type resolution.
115#[derive(Debug, Clone, PartialEq, Eq)]
116pub enum UnitMergeConflict {
117    ConflictingFactors { unit: String, family: String },
118}
119
120/// Names of unit owners while `resolved` is still being mutated.
121#[derive(Debug, Clone, Default)]
122pub struct PlanningUnitIndex {
123    by_bare: IndexMap<String, Vec<PlanningOwner>>,
124    /// Owners reached through a list of a spec, named only with the list prefix.
125    list_rows: IndexMap<String, Vec<PlanningOwner>>,
126}
127
128impl PlanningUnitIndex {
129    #[must_use]
130    pub fn new() -> Self {
131        Self::default()
132    }
133
134    #[must_use]
135    pub fn has_unique_owner(&self, bare: &str) -> bool {
136        matches!(self.owners_for(bare), [_])
137    }
138
139    #[must_use]
140    pub fn owners_for(&self, bare: &str) -> &[PlanningOwner] {
141        self.by_bare.get(bare).map(Vec::as_slice).unwrap_or(&[])
142    }
143
144    pub fn iter_owners(&self) -> impl Iterator<Item = (&str, &PlanningOwner)> {
145        self.by_bare
146            .iter()
147            .flat_map(|(bare, owners)| owners.iter().map(move |owner| (bare.as_str(), owner)))
148    }
149
150    pub fn insert_owner(&mut self, bare: String, owner: PlanningOwner) {
151        insert_planning_owner(self.by_bare.entry(bare).or_default(), owner);
152    }
153
154    /// An owner the rows of a list of a spec declare, under the list's path: named only
155    /// as `list.Type.unit`, never by its bare name.
156    pub fn insert_list_row_owner(&mut self, bare: String, owner: PlanningOwner) {
157        insert_planning_owner(self.list_rows.entry(bare).or_default(), owner);
158    }
159
160    pub fn merge_measure_unit(
161        &mut self,
162        unit: String,
163        resolved_type: &Arc<LemmaType>,
164        type_name: &str,
165        import_path: &[String],
166        measure_family: &str,
167        locals: &HashMap<String, Arc<LemmaType>>,
168    ) -> Result<(), UnitMergeConflict> {
169        let owners = self.by_bare.entry(unit.clone()).or_default();
170        if owners
171            .iter()
172            .any(|owner| owner.same_slot(type_name, import_path))
173        {
174            return Ok(());
175        }
176
177        let resolved_ref = resolved_type.as_ref();
178        let mut skip_insert = false;
179        let mut reclaim_indices = Vec::new();
180        for (index, owner) in owners.iter().enumerate() {
181            let existing_type = planning_owner_type(owner, locals);
182            let existing_name = owner.type_name();
183            let existing_path = owner.import_path();
184            let parent_ref = resolved_ref.extends.parent_name();
185            let current_extends_existing = parent_ref
186                .is_some_and(|parent| parent_matches_owner(parent, existing_path, existing_name));
187            let existing_extends_current = existing_type
188                .extends
189                .parent_name()
190                .is_some_and(|parent| parent_matches_owner(parent, import_path, type_name));
191
192            if existing_type.is_measure() && (current_extends_existing || existing_extends_current)
193            {
194                if current_extends_existing {
195                    skip_insert = true;
196                } else {
197                    reclaim_indices.push(index);
198                }
199                continue;
200            }
201
202            if existing_type.is_measure() && existing_type.same_measure_family(resolved_ref) {
203                if let (
204                    TypeSpecification::Measure {
205                        units: existing_units,
206                        ..
207                    },
208                    TypeSpecification::Measure {
209                        units: new_units, ..
210                    },
211                ) = (&existing_type.specifications, &resolved_ref.specifications)
212                {
213                    let same_factor = existing_units
214                        .iter()
215                        .find(|existing_unit| existing_unit.name == unit)
216                        .zip(new_units.iter().find(|new_unit| new_unit.name == unit))
217                        .is_some_and(|(existing_unit, new_unit)| {
218                            existing_unit.same_scale(new_unit)
219                        });
220                    if same_factor {
221                        // Same family and same scale: keep one local declarer
222                        // (extension chain). Distinct scales are a conflict below.
223                        if import_path.is_empty() && existing_path.is_empty() {
224                            skip_insert = true;
225                        }
226                        continue;
227                    }
228                    return Err(UnitMergeConflict::ConflictingFactors {
229                        unit,
230                        family: measure_family.to_string(),
231                    });
232                }
233            }
234        }
235
236        for index in reclaim_indices.into_iter().rev() {
237            owners.remove(index);
238        }
239
240        if !skip_insert {
241            owners.push(planning_named_owner(type_name, import_path, resolved_type));
242        }
243        Ok(())
244    }
245
246    pub fn merge_ratio_unit(
247        &mut self,
248        unit: String,
249        resolved_type: &Arc<LemmaType>,
250        type_name: &str,
251        import_path: &[String],
252        locals: &HashMap<String, Arc<LemmaType>>,
253    ) -> Result<(), UnitMergeConflict> {
254        let owners = self.by_bare.entry(unit.clone()).or_default();
255        if let Some(existing) = owners
256            .iter_mut()
257            .find(|owner| owner.same_slot(type_name, import_path))
258        {
259            if let PlanningOwner::Imported { lemma_type, .. } = existing {
260                *lemma_type = Arc::clone(resolved_type);
261            }
262            return Ok(());
263        }
264
265        if owners.is_empty() {
266            owners.push(planning_named_owner(type_name, import_path, resolved_type));
267            return Ok(());
268        }
269
270        // Keep PrimitiveRatio for bare percent/permille; named owners stay for Type.unit.
271        let resolved_ref = resolved_type.as_ref();
272        let mut skip_insert = false;
273        for owner in owners.iter() {
274            if matches!(owner, PlanningOwner::PrimitiveRatio) {
275                continue;
276            }
277            let existing_type = planning_owner_type(owner, locals);
278            if !existing_type.is_ratio() || existing_type.name() == resolved_ref.name() {
279                continue;
280            }
281            if matches!(unit.as_str(), "percent" | "permille") {
282                if let (
283                    TypeSpecification::Ratio {
284                        units: existing_units,
285                        ..
286                    },
287                    TypeSpecification::Ratio {
288                        units: new_units, ..
289                    },
290                ) = (&existing_type.specifications, &resolved_ref.specifications)
291                {
292                    let same_factor = existing_units
293                        .iter()
294                        .find(|existing_unit| existing_unit.name == unit)
295                        .zip(new_units.iter().find(|new_unit| new_unit.name == unit))
296                        .is_some_and(|(existing_unit, new_unit)| {
297                            existing_unit.value == new_unit.value
298                        });
299                    if same_factor && import_path.is_empty() && owner.import_path().is_empty() {
300                        skip_insert = true;
301                    }
302                }
303            }
304        }
305        if !skip_insert {
306            owners.push(planning_named_owner(type_name, import_path, resolved_type));
307        }
308        Ok(())
309    }
310
311    pub fn resolve_owner(
312        &self,
313        unit_ref: &str,
314        resolved: &IndexMap<String, Arc<LemmaType>>,
315    ) -> Result<(String, &PlanningOwner), String> {
316        let bare_key = unit_ref_bare(unit_ref);
317        let owners = self.owners_for(&bare_key);
318        let list_rows = self
319            .list_rows
320            .get(&bare_key)
321            .map(Vec::as_slice)
322            .unwrap_or(&[]);
323        resolve_owners_for_ref(
324            owners,
325            list_rows,
326            unit_ref,
327            |owner| owner.type_name(),
328            |owner| owner.import_path(),
329            |owner| planning_owner_lemma_arc(owner, resolved),
330        )
331    }
332
333    pub fn resolve_with_named_types(
334        &self,
335        unit_ref: &str,
336        resolved: &IndexMap<String, Arc<LemmaType>>,
337    ) -> Result<(String, Arc<LemmaType>), String> {
338        match self.resolve_owner(unit_ref, resolved) {
339            Ok((bare, owner)) => Ok((
340                bare,
341                Arc::clone(match owner {
342                    PlanningOwner::PrimitiveRatio => primitive_ratio_arc(),
343                    PlanningOwner::Local { type_name } => resolved
344                        .get(type_name)
345                        .expect("BUG: local unit owner missing from resolved"),
346                    PlanningOwner::Imported { lemma_type, .. } => lemma_type,
347                }),
348            )),
349            Err(index_err) => {
350                UnitIndex::resolve_via_named_measure_type(unit_ref, resolved).ok_or(index_err)
351            }
352        }
353    }
354
355    pub fn into_iter_owners(self) -> impl Iterator<Item = (String, PlanningOwner)> {
356        self.by_bare
357            .into_iter()
358            .flat_map(|(bare, owners)| owners.into_iter().map(move |owner| (bare.clone(), owner)))
359    }
360
361    /// The owner of `unit_name` bound against final `resolved`; `None` when its type does
362    /// not declare the unit.
363    fn bind_owner(
364        unit_name: &str,
365        owner: PlanningOwner,
366        resolved: &IndexMap<String, Arc<LemmaType>>,
367    ) -> Option<UnitOwner> {
368        match owner {
369            PlanningOwner::PrimitiveRatio => Some(UnitOwner::PrimitiveRatio),
370            PlanningOwner::Local { type_name } => {
371                let lemma_type = Arc::clone(
372                    resolved
373                        .get(&type_name)
374                        .expect("BUG: local unit owner missing from resolved"),
375                );
376                type_declares_unit(lemma_type.as_ref(), unit_name).then_some(UnitOwner::Named {
377                    import_path: Vec::new(),
378                    type_name,
379                    lemma_type,
380                })
381            }
382            PlanningOwner::Imported {
383                import_path,
384                type_name,
385                lemma_type,
386            } => type_declares_unit(lemma_type.as_ref(), unit_name).then_some(UnitOwner::Named {
387                import_path,
388                type_name,
389                lemma_type,
390            }),
391        }
392    }
393
394    /// Attach local Arcs from final `resolved` and add missing family-root units.
395    #[must_use]
396    pub(crate) fn bind(
397        mut self,
398        resolved: &IndexMap<String, Arc<LemmaType>>,
399        this_spec: &SpecVersionKey,
400    ) -> UnitIndex {
401        let mut bound = UnitIndex::new();
402        for (unit_name, owners) in std::mem::take(&mut self.list_rows) {
403            for owner in owners {
404                if let Some(bound_owner) = Self::bind_owner(&unit_name, owner, resolved) {
405                    bound.insert_list_row_owner(unit_name.clone(), bound_owner);
406                }
407            }
408        }
409        for (unit_name, owner) in self.into_iter_owners() {
410            if let Some(bound_owner) = Self::bind_owner(&unit_name, owner, resolved) {
411                bound.insert_owner(unit_name, bound_owner);
412            }
413        }
414        for (type_name, lemma_type) in resolved {
415            let TypeSpecification::Measure { units, .. } = &lemma_type.specifications else {
416                continue;
417            };
418            let is_family_root = lemma_type.measure_family().is_some_and(|family| {
419                family.is_declared_in(this_spec) && family.name == *type_name
420            });
421            if !is_family_root {
422                continue;
423            }
424            for unit in units.iter() {
425                let already = bound
426                    .owners_for(&unit.name)
427                    .iter()
428                    .any(|owner| match owner {
429                        UnitOwner::Named {
430                            type_name: owner_name,
431                            import_path,
432                            ..
433                        } if import_path.is_empty() && owner_name == type_name => true,
434                        UnitOwner::Named {
435                            lemma_type: owner_type,
436                            ..
437                        } => owner_type.same_measure_family(lemma_type.as_ref()),
438                        UnitOwner::PrimitiveRatio => false,
439                    });
440                if !already {
441                    bound.insert_owner(
442                        unit.name.clone(),
443                        UnitOwner::Named {
444                            import_path: Vec::new(),
445                            type_name: type_name.clone(),
446                            lemma_type: Arc::clone(lemma_type),
447                        },
448                    );
449                }
450            }
451        }
452        bound
453    }
454}
455
456/// Unit `bare` as written through `owner`: its import path, type and name.
457fn written_unit(owner: &UnitOwner, bare: &str) -> String {
458    owner
459        .import_path()
460        .iter()
461        .map(String::as_str)
462        .chain([owner.type_name(), bare])
463        .collect::<Vec<_>>()
464        .join(".")
465}
466
467/// A written unit of the rows of a list whose size is a row's ([`UnitIndex::rows_unit`]).
468#[derive(Debug, Clone)]
469pub(crate) struct RowsUnit {
470    /// The unit as written.
471    pub written: String,
472    /// The list whose rows declare it.
473    pub list: String,
474    /// The same unit of the instances in scope, as written (`line.money.gbp`).
475    pub instance_units: Vec<String>,
476}
477
478impl RowsUnit {
479    fn instance_advice(&self, prefix: &str) -> String {
480        if self.instance_units.is_empty() {
481            return String::new();
482        }
483        let written: Vec<String> = self
484            .instance_units
485            .iter()
486            .map(|unit| format!("`{prefix}{unit}`"))
487            .collect();
488        format!(
489            " Write {} for the unit of an instance.",
490            written.join(" or ")
491        )
492    }
493
494    /// Why a value cannot be written in this unit where no row of the list is in scope.
495    #[must_use]
496    pub(crate) fn names_no_row(&self) -> String {
497        format!(
498            "Unit '{written}' is the unit of the rows of `{list}`, and this names no row of `{list}`.{advice} A value in the unit of a row is written in the argument of a command over `{list}`, for example `{list} -> where(<field> > 1 {written})`.",
499            written = self.written,
500            list = self.list,
501            advice = self.instance_advice(""),
502        )
503    }
504
505    /// Why a value that names no single row of the list cannot be converted to this
506    /// unit.
507    #[must_use]
508    pub(crate) fn converts_no_row_value(&self) -> String {
509        format!(
510            "Unit '{written}' is the unit of the rows of `{list}`, and the value converted `as {written}` names no single row of `{list}` to take its size from.{advice} {from_a_row}",
511            written = self.written,
512            list = self.list,
513            advice = self.instance_advice("as "),
514            from_a_row = self.value_of_a_row_advice(),
515        )
516    }
517
518    /// Why `as number` cannot read, in this unit, a value that names no single row of
519    /// the list.
520    #[must_use]
521    pub(crate) fn counts_no_row_value(&self) -> String {
522        format!(
523            "Unit '{written}' is the unit of the rows of `{list}`, and `as number` counts in it a value that names no single row of `{list}` to take its size from.{advice} {from_a_row}",
524            written = self.written,
525            list = self.list,
526            advice = self.instance_advice("as "),
527            from_a_row = self.value_of_a_row_advice(),
528        )
529    }
530
531    fn value_of_a_row_advice(&self) -> String {
532        format!(
533            "Or convert a value read from one row, for example `({list} -> first).<field> as {written}`, or convert in the argument of a command over `{list}`. A `sum`, `min` or `max` over rows, `abs` or rounding of a value, and a value combined from different rows or with a value of no row name no single row.",
534            written = self.written,
535            list = self.list,
536        )
537    }
538}
539
540/// Expression-scope units after bind: every declarer per bare unit name.
541#[derive(Debug, Clone, Default)]
542pub struct UnitIndex {
543    by_bare: IndexMap<String, Vec<UnitOwner>>,
544    /// Owners reached through a list of a spec, named only with the list prefix.
545    list_rows: IndexMap<String, Vec<UnitOwner>>,
546    /// Position in `by_bare[bare]` of the owner of each slot: an insert finds the owner
547    /// it replaces without scanning every route to the unit.
548    owner_positions: IndexMap<(String, OwnerSlotKey), usize>,
549    /// First-seen owning type per `(import_path, type_name)` slot.
550    distinct_types: IndexMap<(Vec<String>, String), Arc<LemmaType>>,
551    /// Family root Arc: type whose `.name == family.name`, keyed by full [`TypeFamily`].
552    family_roots: BTreeMap<TypeFamily, Arc<LemmaType>>,
553}
554
555impl UnitIndex {
556    #[must_use]
557    pub fn new() -> Self {
558        Self::default()
559    }
560
561    #[must_use]
562    pub fn unique_owner(&self, bare: &str) -> Option<&Arc<LemmaType>> {
563        let owners = self.by_bare.get(bare)?;
564        match owners.as_slice() {
565            [only] => Some(only.lemma_type()),
566            _ => None,
567        }
568    }
569
570    #[must_use]
571    pub fn owners_for(&self, bare: &str) -> &[UnitOwner] {
572        self.by_bare.get(bare).map(Vec::as_slice).unwrap_or(&[])
573    }
574
575    pub fn iter_entries(&self) -> impl Iterator<Item = (&str, &Arc<LemmaType>)> {
576        self.by_bare.iter().flat_map(|(bare, owners)| {
577            owners
578                .iter()
579                .map(move |owner| (bare.as_str(), owner.lemma_type()))
580        })
581    }
582
583    pub fn iter_owners(&self) -> impl Iterator<Item = (&str, &UnitOwner)> {
584        self.by_bare
585            .iter()
586            .flat_map(|(bare, owners)| owners.iter().map(move |owner| (bare.as_str(), owner)))
587    }
588
589    pub fn values(&self) -> impl Iterator<Item = &Arc<LemmaType>> {
590        self.distinct_types.values()
591    }
592
593    /// Family-root type for `family`, keyed by full [`TypeFamily`] identity.
594    #[must_use]
595    pub fn family_root(&self, family: &TypeFamily) -> Option<&Arc<LemmaType>> {
596        self.family_roots.get(family)
597    }
598
599    pub fn keys(&self) -> impl Iterator<Item = &String> {
600        self.by_bare.keys()
601    }
602
603    pub fn insert_owner(&mut self, bare: String, owner: UnitOwner) {
604        let slot = owner_slot(&owner);
605        let lemma_type = Arc::clone(owner.lemma_type());
606        let owners = self.by_bare.entry(bare.clone()).or_default();
607        match self.owner_positions.entry((bare, owner_slot_key(&owner))) {
608            indexmap::map::Entry::Occupied(position) => {
609                let existing = &mut owners[*position.get()];
610                assert!(
611                    bound_owners_same_slot(existing, &owner),
612                    "BUG: an owner position names an owner of another slot"
613                );
614                *existing = owner;
615                self.refresh_distinct_slot(slot, lemma_type);
616                return;
617            }
618            indexmap::map::Entry::Vacant(position) => {
619                position.insert(owners.len());
620            }
621        }
622        owners.push(owner);
623        if let indexmap::map::Entry::Vacant(entry) = self.distinct_types.entry(slot) {
624            let stored = entry.insert(lemma_type);
625            record_family_root(&mut self.family_roots, stored);
626        }
627    }
628
629    /// See [`PlanningUnitIndex::insert_list_row_owner`].
630    pub fn insert_list_row_owner(&mut self, bare: String, owner: UnitOwner) {
631        let owners = self.list_rows.entry(bare).or_default();
632        match owners
633            .iter_mut()
634            .find(|existing| bound_owners_same_slot(existing, &owner))
635        {
636            Some(existing) => *existing = owner,
637            None => owners.push(owner),
638        }
639    }
640
641    fn refresh_distinct_slot(&mut self, slot: (Vec<String>, String), lemma_type: Arc<LemmaType>) {
642        let previous = self
643            .distinct_types
644            .insert(slot, Arc::clone(&lemma_type))
645            .expect("BUG: same-slot replace requires an existing distinct owner");
646        if let Some(previous_family) = previous.family() {
647            if previous.name.as_deref() == Some(previous_family.name.as_str()) {
648                if let Some(root) = self.family_roots.get_mut(previous_family) {
649                    if Arc::ptr_eq(root, &previous) {
650                        *root = Arc::clone(&lemma_type);
651                    }
652                }
653            }
654        }
655        record_family_root(&mut self.family_roots, &lemma_type);
656    }
657
658    pub fn resolve(&self, unit_ref: &str) -> Result<(String, Arc<LemmaType>), String> {
659        self.resolve_owner(unit_ref)
660            .map(|(bare, owner)| (bare, Arc::clone(owner.lemma_type())))
661    }
662
663    /// One `alias.Type.unit` route per instance that declares the bare unit `bare`,
664    /// with its owner, in route order. Empty when `bare` names at most one instance.
665    #[must_use]
666    pub fn instance_routes(&self, bare: &str) -> Vec<(String, &UnitOwner)> {
667        let candidates: Vec<&UnitOwner> = self.owners_for(bare).iter().collect();
668        let groups = group_equivalent_owners(&candidates, bare, &|owner: &UnitOwner| {
669            Arc::clone(owner.lemma_type())
670        });
671        if groups.len() < 2 {
672            return Vec::new();
673        }
674        let mut routes: Vec<(String, &UnitOwner)> = groups
675            .iter()
676            .map(|members| {
677                instance_route(
678                    members,
679                    bare,
680                    |owner: &UnitOwner| owner.type_name(),
681                    |owner: &UnitOwner| owner.import_path(),
682                )
683            })
684            .collect();
685        routes.sort_by(|a, b| a.0.cmp(&b.0));
686        routes
687    }
688
689    /// The list whose rows `unit_ref` names the unit of (`lines.Type.unit`), when that
690    /// unit has a scale: the scale is data or a rule of a row, so the unit has a size
691    /// only in a row of the list. With it, the same unit as the instances in scope that
692    /// declare it name it.
693    #[must_use]
694    pub(crate) fn rows_unit(&self, unit_ref: &str) -> Option<RowsUnit> {
695        let (bare, owner) = self.resolve_owner(unit_ref).ok()?;
696        let of_rows = self
697            .list_rows
698            .get(&bare)
699            .is_some_and(|owners| owners.iter().any(|listed| std::ptr::eq(listed, owner)));
700        if !of_rows || !owner.lemma_type().unit_is_dynamic(&bare) {
701            return None;
702        }
703        Some(self.describe_rows_unit(unit_ref.to_string(), &bare, owner))
704    }
705
706    /// Unit `bare` of `owning_type`, sized by the same scales, as a unit of the rows of
707    /// each list whose rows declare it so.
708    #[must_use]
709    pub(crate) fn rows_units_of(&self, bare: &str, owning_type: &LemmaType) -> Vec<RowsUnit> {
710        self.list_rows
711            .get(bare)
712            .into_iter()
713            .flatten()
714            .filter(|owner| {
715                owner.lemma_type().same_measure_family(owning_type)
716                    && owner.lemma_type().unit_scale_factors(bare)
717                        == owning_type.unit_scale_factors(bare)
718            })
719            .map(|owner| self.describe_rows_unit(written_unit(owner, bare), bare, owner))
720            .collect()
721    }
722
723    /// [`RowsUnit`] of unit `bare`, written `written`, of the list row owner `owner`.
724    fn describe_rows_unit(&self, written: String, bare: &str, owner: &UnitOwner) -> RowsUnit {
725        let list = owner
726            .import_path()
727            .first()
728            .expect("BUG: a row unit owner is reached through its list")
729            .clone();
730        let instance_units = self
731            .owners_for(bare)
732            .iter()
733            .filter(|instance| {
734                instance
735                    .lemma_type()
736                    .same_measure_family(owner.lemma_type())
737            })
738            .map(|instance| written_unit(instance, bare))
739            .collect();
740        RowsUnit {
741            written,
742            list,
743            instance_units,
744        }
745    }
746
747    pub fn resolve_owner(&self, unit_ref: &str) -> Result<(String, &UnitOwner), String> {
748        let bare = unit_ref_bare(unit_ref);
749        resolve_owners_for_ref(
750            self.owners_for(&bare),
751            self.list_rows.get(&bare).map(Vec::as_slice).unwrap_or(&[]),
752            unit_ref,
753            |owner| owner.type_name(),
754            |owner| owner.import_path(),
755            |owner| Arc::clone(owner.lemma_type()),
756        )
757    }
758
759    #[must_use]
760    pub fn resolve_via_named_measure_type(
761        unit_ref: &str,
762        resolved: &IndexMap<String, Arc<LemmaType>>,
763    ) -> Option<(String, Arc<LemmaType>)> {
764        let segments: Vec<String> = unit_ref
765            .split('.')
766            .map(|segment| crate::parsing::ast::ascii_lowercase_logical_name(segment.to_string()))
767            .filter(|segment| !segment.is_empty())
768            .collect();
769        let (type_name, bare) = match segments.as_slice() {
770            [type_name, bare] => (type_name.as_str(), bare.as_str()),
771            _ => return None,
772        };
773        let lemma_type = resolved.get(type_name)?;
774        if !lemma_type.is_measure() {
775            return None;
776        }
777        let names = lemma_type.measure_unit_names()?;
778        if !names.contains(&bare) {
779            return None;
780        }
781        Some((bare.to_string(), Arc::clone(lemma_type)))
782    }
783
784    pub fn resolve_with_named_types(
785        &self,
786        unit_ref: &str,
787        resolved: &IndexMap<String, Arc<LemmaType>>,
788    ) -> Result<(String, Arc<LemmaType>), String> {
789        match self.resolve(unit_ref) {
790            Ok(hit) => Ok(hit),
791            Err(index_err) => {
792                Self::resolve_via_named_measure_type(unit_ref, resolved).ok_or(index_err)
793            }
794        }
795    }
796
797    #[must_use]
798    pub fn owning_type_for_signature_factor<'a>(
799        &'a self,
800        unit_name: &str,
801        typed_owners: &[&'a LemmaType],
802    ) -> Option<&'a LemmaType> {
803        for typed in typed_owners {
804            if type_declares_unit(typed, unit_name) {
805                return Some(typed);
806            }
807        }
808        match self.owners_for(unit_name) {
809            [only] => Some(only.lemma_type().as_ref()),
810            _ => None,
811        }
812    }
813}
814
815/// `owner` into `owners`, replacing the owner of the same slot.
816fn insert_planning_owner(owners: &mut Vec<PlanningOwner>, owner: PlanningOwner) {
817    if let Some(existing) = owners
818        .iter_mut()
819        .find(|existing| planning_owners_same_slot(existing, &owner))
820    {
821        *existing = owner;
822        return;
823    }
824    owners.push(owner);
825}
826
827fn planning_named_owner(
828    type_name: &str,
829    import_path: &[String],
830    resolved_type: &Arc<LemmaType>,
831) -> PlanningOwner {
832    if import_path.is_empty() {
833        PlanningOwner::Local {
834            type_name: type_name.to_string(),
835        }
836    } else {
837        PlanningOwner::Imported {
838            import_path: import_path.to_vec(),
839            type_name: type_name.to_string(),
840            lemma_type: Arc::clone(resolved_type),
841        }
842    }
843}
844
845fn parent_matches_owner(parent: &str, owner_path: &[String], owner_type_name: &str) -> bool {
846    if owner_path.is_empty() {
847        parent == owner_type_name
848    } else {
849        let mut segments = owner_path.to_vec();
850        segments.push(owner_type_name.to_string());
851        segments.join(".") == parent
852    }
853}
854
855fn planning_owner_type<'a>(
856    owner: &'a PlanningOwner,
857    locals: &'a HashMap<String, Arc<LemmaType>>,
858) -> &'a LemmaType {
859    match owner {
860        PlanningOwner::PrimitiveRatio => primitive_ratio_arc().as_ref(),
861        PlanningOwner::Local { type_name } => locals
862            .get(type_name)
863            .expect("BUG: local unit owner missing from resolved")
864            .as_ref(),
865        PlanningOwner::Imported { lemma_type, .. } => lemma_type.as_ref(),
866    }
867}
868
869fn planning_owner_lemma_arc(
870    owner: &PlanningOwner,
871    resolved: &IndexMap<String, Arc<LemmaType>>,
872) -> Arc<LemmaType> {
873    match owner {
874        PlanningOwner::PrimitiveRatio => Arc::clone(primitive_ratio_arc()),
875        PlanningOwner::Local { type_name } => Arc::clone(
876            resolved
877                .get(type_name)
878                .expect("BUG: local unit owner missing from resolved"),
879        ),
880        PlanningOwner::Imported { lemma_type, .. } => Arc::clone(lemma_type),
881    }
882}
883
884fn type_declares_unit(lemma_type: &LemmaType, unit_name: &str) -> bool {
885    match &lemma_type.specifications {
886        TypeSpecification::Measure { units, .. } => units.get(unit_name).is_ok(),
887        TypeSpecification::Ratio { units, .. } => units.get(unit_name).is_ok(),
888        _ => false,
889    }
890}
891
892fn planning_owners_same_slot(left: &PlanningOwner, right: &PlanningOwner) -> bool {
893    match (left, right) {
894        (PlanningOwner::PrimitiveRatio, PlanningOwner::PrimitiveRatio) => true,
895        (PlanningOwner::Local { type_name: a }, PlanningOwner::Local { type_name: b }) => a == b,
896        (
897            PlanningOwner::Imported {
898                import_path: path_a,
899                type_name: name_a,
900                ..
901            },
902            PlanningOwner::Imported {
903                import_path: path_b,
904                type_name: name_b,
905                ..
906            },
907        ) => path_a == path_b && name_a == name_b,
908        _ => false,
909    }
910}
911
912fn bound_owners_same_slot(left: &UnitOwner, right: &UnitOwner) -> bool {
913    match (left, right) {
914        (UnitOwner::PrimitiveRatio, UnitOwner::PrimitiveRatio) => true,
915        (
916            UnitOwner::Named {
917                type_name: name_a,
918                import_path: path_a,
919                ..
920            },
921            UnitOwner::Named {
922                type_name: name_b,
923                import_path: path_b,
924                ..
925            },
926        ) => name_a == name_b && path_a == path_b,
927        _ => false,
928    }
929}
930
931/// Identity of a bound owner's slot, as [`bound_owners_same_slot`] compares it.
932type OwnerSlotKey = Option<(Vec<String>, String)>;
933
934fn owner_slot_key(owner: &UnitOwner) -> OwnerSlotKey {
935    match owner {
936        UnitOwner::PrimitiveRatio => None,
937        UnitOwner::Named {
938            import_path,
939            type_name,
940            ..
941        } => Some((import_path.clone(), type_name.clone())),
942    }
943}
944
945fn owner_slot(owner: &UnitOwner) -> (Vec<String>, String) {
946    (owner.import_path().to_vec(), owner.type_name().to_string())
947}
948
949fn record_family_root(
950    family_roots: &mut BTreeMap<TypeFamily, Arc<LemmaType>>,
951    lemma_type: &Arc<LemmaType>,
952) {
953    let Some(family) = lemma_type.family() else {
954        return;
955    };
956    if lemma_type.name.as_deref() != Some(family.name.as_str()) {
957        return;
958    }
959    family_roots
960        .entry(family.clone())
961        .or_insert_with(|| Arc::clone(lemma_type));
962}
963
964fn unit_ref_bare(unit_ref: &str) -> String {
965    unit_ref
966        .split('.')
967        .map(|segment| crate::parsing::ast::ascii_lowercase_logical_name(segment.to_string()))
968        .rfind(|segment| !segment.is_empty())
969        .unwrap_or_default()
970}
971
972fn unit_scale_for_bare(lemma_type: &LemmaType, bare: &str) -> Option<UnitScalar> {
973    match &lemma_type.specifications {
974        TypeSpecification::Measure { units, .. } => units
975            .get(bare)
976            .ok()
977            .map(|unit| UnitScalar::Measure(unit.scale.clone())),
978        TypeSpecification::Ratio { units, .. } => units
979            .get(bare)
980            .ok()
981            .map(|unit| UnitScalar::Ratio(unit.value.clone())),
982        _ => None,
983    }
984}
985
986#[derive(Debug, Clone, PartialEq, Eq)]
987enum UnitScalar {
988    Measure(crate::literals::UnitScale),
989    Ratio(crate::computation::rational::RationalInteger),
990}
991
992/// `candidates` grouped by the instance they name: two owners are one when their types
993/// share a root (one type, one measure family, or one ratio family) and give `bare` the
994/// same scale. Every route that reaches one instance lands in one group; an owner whose
995/// type does not declare `bare` is a group of its own. Groups keep candidate order.
996fn group_equivalent_owners<'a, O>(
997    candidates: &[&'a O],
998    bare: &str,
999    lemma_type: &impl Fn(&O) -> Arc<LemmaType>,
1000) -> Vec<Vec<&'a O>> {
1001    let mut groups: Vec<(Arc<LemmaType>, Option<UnitScalar>, Vec<&'a O>)> = Vec::new();
1002    for owner in candidates.iter().copied() {
1003        let owner_type = lemma_type(owner);
1004        let scale = type_declares_unit(owner_type.as_ref(), bare)
1005            .then(|| unit_scale_for_bare(owner_type.as_ref(), bare))
1006            .flatten();
1007        let group = scale.as_ref().and_then(|scale| {
1008            groups.iter_mut().find(|(group_type, group_scale, _)| {
1009                let same_root = group_type.as_ref() == owner_type.as_ref()
1010                    || group_type.same_measure_family(owner_type.as_ref())
1011                    || (group_type.is_ratio()
1012                        && owner_type.is_ratio()
1013                        && group_type.ratio_family().is_some()
1014                        && group_type.ratio_family() == owner_type.ratio_family());
1015                same_root && group_scale.as_ref() == Some(scale)
1016            })
1017        });
1018        match group {
1019            Some((_, _, members)) => members.push(owner),
1020            None => groups.push((owner_type, scale, vec![owner])),
1021        }
1022    }
1023    groups.into_iter().map(|(_, _, members)| members).collect()
1024}
1025
1026/// The one instance `candidates` name for unit `bare` (written `written`): its first
1027/// owner. Several instances are ambiguous: the error lists one `alias.Type.unit` route
1028/// per instance, the spec's own route if it has one, else the shortest.
1029fn resolve_one_instance<'a, O>(
1030    candidates: &[&'a O],
1031    bare: String,
1032    written: &str,
1033    type_name: impl Fn(&O) -> &str + Copy,
1034    import_path: impl Fn(&O) -> &[String] + Copy,
1035    lemma_type: &impl Fn(&O) -> Arc<LemmaType>,
1036) -> Result<(String, &'a O), String> {
1037    let groups = group_equivalent_owners(candidates, &bare, lemma_type);
1038    if let [only] = groups.as_slice() {
1039        let first = *only.first().expect("BUG: an owner group has a member");
1040        return Ok((bare, first));
1041    }
1042    let routes: BTreeSet<String> = groups
1043        .iter()
1044        .map(|members| instance_route(members, &bare, type_name, import_path).0)
1045        .collect();
1046    Err(format!(
1047        "Unit '{written}' matches more than one type. Write one of: {}",
1048        routes.into_iter().collect::<Vec<_>>().join(", ")
1049    ))
1050}
1051
1052/// The `alias.Type.unit` route naming one instance (`members`, one group of
1053/// [`group_equivalent_owners`]): the spec's own route if it has one, else the shortest.
1054fn instance_route<'a, O>(
1055    members: &[&'a O],
1056    bare: &str,
1057    type_name: impl Fn(&O) -> &str + Copy,
1058    import_path: impl Fn(&O) -> &[String] + Copy,
1059) -> (String, &'a O) {
1060    let route = members
1061        .iter()
1062        .copied()
1063        .min_by(|a, b| {
1064            let (a_path, b_path) = (import_path(a), import_path(b));
1065            a_path
1066                .len()
1067                .cmp(&b_path.len())
1068                .then_with(|| a_path.cmp(b_path))
1069                .then_with(|| type_name(a).cmp(type_name(b)))
1070        })
1071        .expect("BUG: an owner group has a member");
1072    let name = import_path(route)
1073        .iter()
1074        .map(String::as_str)
1075        .chain([type_name(route), bare])
1076        .collect::<Vec<_>>()
1077        .join(".");
1078    (name, route)
1079}
1080
1081/// `list_rows` are owners named only qualified (see [`PlanningUnitIndex::list_rows`]):
1082/// a bare `unit_ref` never reaches them.
1083fn resolve_owners_for_ref<'a, O>(
1084    owners: &'a [O],
1085    list_rows: &'a [O],
1086    unit_ref: &str,
1087    type_name: impl Fn(&O) -> &str + Copy,
1088    import_path: impl Fn(&O) -> &[String] + Copy,
1089    lemma_type: impl Fn(&O) -> Arc<LemmaType>,
1090) -> Result<(String, &'a O), String> {
1091    let segments: Vec<String> = unit_ref
1092        .split('.')
1093        .map(|segment| crate::parsing::ast::ascii_lowercase_logical_name(segment.to_string()))
1094        .filter(|segment| !segment.is_empty())
1095        .collect();
1096    if segments.is_empty() {
1097        return Err("Unit path is empty".to_string());
1098    }
1099    let bare = segments
1100        .last()
1101        .expect("BUG: non-empty segments must have last")
1102        .clone();
1103    let prefix = &segments[..segments.len() - 1];
1104    if prefix.is_empty() {
1105        // Builtin percent/permille always bind PrimitiveRatio; named owners stay for Type.unit.
1106        if matches!(bare.as_str(), "percent" | "permille") {
1107            if let Some(primitive) = owners
1108                .iter()
1109                .find(|owner| Arc::ptr_eq(&lemma_type(owner), primitive_ratio_arc()))
1110            {
1111                return Ok((bare, primitive));
1112            }
1113        }
1114        return match owners {
1115            [] => Err(format!(
1116                "Unknown unit '{bare}'. Declare it on a measure or ratio type, or import it with uses."
1117            )),
1118            [only] => Ok((bare, only)),
1119            many => {
1120                let refs: Vec<&O> = many.iter().collect();
1121                let written = bare.clone();
1122                resolve_one_instance(&refs, bare, &written, type_name, import_path, &lemma_type)
1123            }
1124        };
1125    }
1126
1127    let candidates: Vec<&'a O> = owners.iter().chain(list_rows).collect();
1128    let mut matches = owners_matching_prefix(&candidates, prefix, type_name, import_path);
1129    dedupe_owner_matches(&mut matches, type_name, import_path);
1130    match matches.as_slice() {
1131        [only] => Ok((bare, *only)),
1132        [] => Err(format!(
1133            "Unknown unit '{unit_ref}'. Declare it on a measure or ratio type, or import it with uses."
1134        )),
1135        many => resolve_one_instance(many, bare, unit_ref, type_name, import_path, &lemma_type),
1136    }
1137}
1138
1139fn owners_matching_prefix<'a, O>(
1140    owners: &[&'a O],
1141    prefix: &[String],
1142    type_name: impl Fn(&O) -> &str + Copy,
1143    import_path: impl Fn(&O) -> &[String] + Copy,
1144) -> Vec<&'a O> {
1145    if prefix.len() == 1 {
1146        let want_type = &prefix[0];
1147        let local: Vec<&O> = owners
1148            .iter()
1149            .copied()
1150            .filter(|owner| import_path(owner).is_empty() && type_name(owner) == want_type)
1151            .collect();
1152        if !local.is_empty() {
1153            return local;
1154        }
1155        return owners
1156            .iter()
1157            .copied()
1158            .filter(|owner| {
1159                let path = import_path(owner);
1160                !path.is_empty() && path[0] == *want_type
1161            })
1162            .collect();
1163    }
1164
1165    if prefix.len() >= 2 {
1166        let type_segment = &prefix[prefix.len() - 1];
1167        let path_prefix = &prefix[..prefix.len() - 1];
1168        let exact: Vec<&O> = owners
1169            .iter()
1170            .copied()
1171            .filter(|owner| import_path(owner) == path_prefix && type_name(owner) == type_segment)
1172            .collect();
1173        if !exact.is_empty() {
1174            return exact;
1175        }
1176    }
1177
1178    owners
1179        .iter()
1180        .copied()
1181        .filter(|owner| {
1182            let path = import_path(owner);
1183            path.len() >= prefix.len() && path[..prefix.len()] == prefix[..]
1184        })
1185        .collect()
1186}
1187
1188fn dedupe_owner_matches<O>(
1189    matches: &mut Vec<&O>,
1190    type_name: impl Fn(&O) -> &str,
1191    import_path: impl Fn(&O) -> &[String],
1192) {
1193    let mut seen = BTreeSet::new();
1194    matches
1195        .retain(|owner| seen.insert((import_path(owner).to_vec(), type_name(owner).to_string())));
1196}
1197
1198#[cfg(test)]
1199mod tests {
1200    use super::*;
1201    use crate::computation::rational::rational_one;
1202    use crate::literals::{MeasureUnit, MeasureUnits, UnitScale};
1203    use crate::parsing::ast::EffectiveDate;
1204    use crate::planning::semantics::{
1205        LemmaType, PathSegment, SpecVersionKey, TypeExtends, TypeFamily, TypeSpecification,
1206    };
1207    use indexmap::IndexMap;
1208    use std::collections::HashMap;
1209    use std::str::FromStr;
1210    use std::sync::Arc;
1211
1212    fn test_spec() -> SpecVersionKey {
1213        SpecVersionKey {
1214            repository: None,
1215            spec: "test".into(),
1216            effective: EffectiveDate::Origin,
1217        }
1218    }
1219
1220    fn locals(pairs: &[(&str, &Arc<LemmaType>)]) -> HashMap<String, Arc<LemmaType>> {
1221        pairs
1222            .iter()
1223            .map(|(name, lemma_type)| ((*name).to_string(), Arc::clone(lemma_type)))
1224            .collect()
1225    }
1226
1227    fn bind_locals(planning: PlanningUnitIndex, pairs: &[(&str, &Arc<LemmaType>)]) -> UnitIndex {
1228        let mut resolved = IndexMap::new();
1229        for (name, lemma_type) in pairs {
1230            resolved.insert((*name).to_string(), Arc::clone(lemma_type));
1231        }
1232        planning.bind(&resolved, &test_spec())
1233    }
1234
1235    fn measure_type(name: &str, unit: &str) -> Arc<LemmaType> {
1236        let mut units = MeasureUnits::new();
1237        units.push(MeasureUnit {
1238            name: unit.to_string(),
1239            scale: crate::literals::UnitScale::Literal(rational_one()),
1240            derived_measure_factors: Vec::new(),
1241            decomposition: Default::default(),
1242            minimum: None,
1243            maximum: None,
1244            suggestion_magnitude: None,
1245        });
1246        Arc::new(LemmaType::new(
1247            name.to_string(),
1248            TypeSpecification::Measure {
1249                units,
1250                traits: vec![],
1251                decomposition: None,
1252                minimum: None,
1253                maximum: None,
1254                unit: None,
1255                help: String::new(),
1256            },
1257            TypeExtends::Primitive,
1258        ))
1259    }
1260
1261    fn family_measure_type(family: TypeFamily, units: &[&str]) -> Arc<LemmaType> {
1262        let mut measure_units = MeasureUnits::new();
1263        for unit in units {
1264            measure_units.push(MeasureUnit {
1265                name: (*unit).to_string(),
1266                scale: crate::literals::UnitScale::Literal(rational_one()),
1267                derived_measure_factors: Vec::new(),
1268                decomposition: Default::default(),
1269                minimum: None,
1270                maximum: None,
1271                suggestion_magnitude: None,
1272            });
1273        }
1274        Arc::new(LemmaType::new(
1275            family.name.clone(),
1276            TypeSpecification::Measure {
1277                units: measure_units,
1278                traits: vec![],
1279                decomposition: None,
1280                minimum: None,
1281                maximum: None,
1282                unit: None,
1283                help: String::new(),
1284            },
1285            TypeExtends::custom_local("measure".to_string(), family),
1286        ))
1287    }
1288
1289    #[test]
1290    fn values_dedupes_multiple_bare_units_of_one_owner() {
1291        let money = family_measure_type(
1292            crate::planning::semantics::tests::test_type_family("money"),
1293            &["eur", "cent"],
1294        );
1295        let mut index = UnitIndex::new();
1296        index.insert_owner(
1297            "eur".into(),
1298            UnitOwner::Named {
1299                import_path: Vec::new(),
1300                type_name: "money".into(),
1301                lemma_type: Arc::clone(&money),
1302            },
1303        );
1304        index.insert_owner(
1305            "cent".into(),
1306            UnitOwner::Named {
1307                import_path: Vec::new(),
1308                type_name: "money".into(),
1309                lemma_type: Arc::clone(&money),
1310            },
1311        );
1312        let values: Vec<_> = index.values().collect();
1313        assert_eq!(values.len(), 1);
1314        assert!(Arc::ptr_eq(values[0], &money));
1315    }
1316
1317    #[test]
1318    fn insert_owner_same_slot_replace_updates_distinct_arc() {
1319        let family = crate::planning::semantics::tests::test_type_family("money");
1320        let first = family_measure_type(family.clone(), &["eur"]);
1321        let second = family_measure_type(family.clone(), &["eur"]);
1322        assert!(!Arc::ptr_eq(&first, &second));
1323        let mut index = UnitIndex::new();
1324        index.insert_owner(
1325            "eur".into(),
1326            UnitOwner::Named {
1327                import_path: Vec::new(),
1328                type_name: "money".into(),
1329                lemma_type: Arc::clone(&first),
1330            },
1331        );
1332        index.insert_owner(
1333            "eur".into(),
1334            UnitOwner::Named {
1335                import_path: Vec::new(),
1336                type_name: "money".into(),
1337                lemma_type: Arc::clone(&second),
1338            },
1339        );
1340        let values: Vec<_> = index.values().collect();
1341        assert_eq!(values.len(), 1);
1342        assert!(Arc::ptr_eq(values[0], &second));
1343        assert!(Arc::ptr_eq(
1344            index.family_root(&family).expect("family root"),
1345            &second
1346        ));
1347    }
1348
1349    #[test]
1350    fn family_root_collapses_same_typefamily_across_import_paths() {
1351        let family = crate::planning::semantics::tests::test_type_family("money");
1352        let money = family_measure_type(family.clone(), &["eur"]);
1353        let mut index = UnitIndex::new();
1354        index.insert_owner(
1355            "eur".into(),
1356            UnitOwner::Named {
1357                import_path: vec!["pricing".into()],
1358                type_name: "money".into(),
1359                lemma_type: Arc::clone(&money),
1360            },
1361        );
1362        index.insert_owner(
1363            "eur".into(),
1364            UnitOwner::Named {
1365                import_path: vec!["billing".into()],
1366                type_name: "money".into(),
1367                lemma_type: Arc::clone(&money),
1368            },
1369        );
1370        assert_eq!(index.values().count(), 2);
1371        assert!(Arc::ptr_eq(
1372            index.family_root(&family).expect("one family root"),
1373            &money
1374        ));
1375    }
1376
1377    #[test]
1378    fn family_roots_keep_same_name_families_with_different_identity_distinct() {
1379        let local_family = TypeFamily {
1380            repository: None,
1381            spec: "shop".into(),
1382            effective: EffectiveDate::Origin,
1383            name: "money".into(),
1384        };
1385        let imported_family = TypeFamily {
1386            repository: Some("catalog".into()),
1387            spec: "pricing".into(),
1388            effective: EffectiveDate::DateTimeValue(
1389                crate::DateTimeValue::from_str("2024-01-01T00:00:00Z").expect("date"),
1390            ),
1391            name: "money".into(),
1392        };
1393        let local_money = family_measure_type(local_family.clone(), &["eur"]);
1394        let imported_money = family_measure_type(imported_family.clone(), &["eur"]);
1395        let mut index = UnitIndex::new();
1396        index.insert_owner(
1397            "eur".into(),
1398            UnitOwner::Named {
1399                import_path: Vec::new(),
1400                type_name: "money".into(),
1401                lemma_type: Arc::clone(&local_money),
1402            },
1403        );
1404        index.insert_owner(
1405            "eur".into(),
1406            UnitOwner::Named {
1407                import_path: vec!["pricing".into()],
1408                type_name: "money".into(),
1409                lemma_type: Arc::clone(&imported_money),
1410            },
1411        );
1412        assert!(Arc::ptr_eq(
1413            index.family_root(&local_family).expect("local root"),
1414            &local_money
1415        ));
1416        assert!(Arc::ptr_eq(
1417            index.family_root(&imported_family).expect("imported root"),
1418            &imported_money
1419        ));
1420        assert!(!Arc::ptr_eq(
1421            index.family_root(&local_family).expect("local root"),
1422            index.family_root(&imported_family).expect("imported root")
1423        ));
1424    }
1425
1426    #[test]
1427    fn merge_parent_reclaims_inherited_unit_from_child() {
1428        let mut index = PlanningUnitIndex::new();
1429        let money = measure_type("money", "eur");
1430        let money2 = Arc::new(LemmaType::new(
1431            "money2".to_string(),
1432            money.specifications.clone(),
1433            TypeExtends::custom_local(
1434                "money".to_string(),
1435                crate::planning::semantics::tests::test_type_family("money"),
1436            ),
1437        ));
1438        index
1439            .merge_measure_unit(
1440                "eur".into(),
1441                &money2,
1442                "money2",
1443                &[],
1444                "money",
1445                &locals(&[("money2", &money2)]),
1446            )
1447            .expect("child first");
1448        let bound = bind_locals(index.clone(), &[("money2", &money2)]);
1449        assert_eq!(
1450            bound.unique_owner("eur").map(|t| t.name()),
1451            Some("money2".into())
1452        );
1453        index
1454            .merge_measure_unit(
1455                "eur".into(),
1456                &money,
1457                "money",
1458                &[],
1459                "money",
1460                &locals(&[("money2", &money2), ("money", &money)]),
1461            )
1462            .expect("parent reclaim");
1463        let bound = bind_locals(index, &[("money2", &money2), ("money", &money)]);
1464        assert_eq!(
1465            bound.unique_owner("eur").map(|t| t.name()),
1466            Some("money".into()),
1467            "declarer must reclaim bare ownership"
1468        );
1469    }
1470
1471    #[test]
1472    fn bare_unique_resolves() {
1473        let mut index = UnitIndex::new();
1474        let mass = measure_type("mass", "kilogram");
1475        index.insert_owner(
1476            "kilogram".into(),
1477            UnitOwner::Named {
1478                lemma_type: Arc::clone(&mass),
1479                import_path: vec!["units".into()],
1480                type_name: "mass".into(),
1481            },
1482        );
1483        let (bare, owner) = index.resolve("kilogram").expect("unique");
1484        assert_eq!(bare, "kilogram");
1485        assert_eq!(owner.name(), "mass");
1486        let (bare, owner) = index.resolve("units.kilogram").expect("alias.unit sugar");
1487        assert_eq!(bare, "kilogram");
1488        assert_eq!(owner.name(), "mass");
1489        let (bare, owner) = index.resolve("units.mass.kilogram").expect("full");
1490        assert_eq!(bare, "kilogram");
1491        assert_eq!(owner.name(), "mass");
1492        index
1493            .resolve("mass.kilogram")
1494            .expect_err("Type.unit is local-only for imported owner");
1495    }
1496
1497    #[test]
1498    fn two_segment_import_alias_unit_resolves() {
1499        let mut index = UnitIndex::new();
1500        let mass = measure_type("mass", "kilogram");
1501        index.insert_owner(
1502            "kilogram".into(),
1503            UnitOwner::Named {
1504                lemma_type: Arc::clone(&mass),
1505                import_path: vec!["units".into()],
1506                type_name: "mass".into(),
1507            },
1508        );
1509        index
1510            .resolve("units.kilogram")
1511            .expect("alias.unit resolves when unique under alias");
1512        index
1513            .resolve("units.mass.kilogram")
1514            .expect("alias.Type.unit must resolve");
1515    }
1516
1517    #[test]
1518    fn nested_import_path_type_unit_resolves() {
1519        let mut index = UnitIndex::new();
1520        let mass = measure_type("mass", "kilogram");
1521        index.insert_owner(
1522            "kilogram".into(),
1523            UnitOwner::Named {
1524                lemma_type: Arc::clone(&mass),
1525                import_path: vec!["a".into(), "b".into()],
1526                type_name: "mass".into(),
1527            },
1528        );
1529        index
1530            .resolve("a.b.mass.kilogram")
1531            .expect("nested alias.Type.unit");
1532    }
1533
1534    #[test]
1535    fn merge_second_measure_declarer_keeps_both_and_bare_use_must_qualify() {
1536        let mut index = PlanningUnitIndex::new();
1537        let a = measure_type("money_a", "eur");
1538        let b = measure_type("money_b", "eur");
1539        index
1540            .merge_measure_unit(
1541                "eur".into(),
1542                &a,
1543                "money_a",
1544                &[],
1545                "money_a",
1546                &locals(&[("money_a", &a)]),
1547            )
1548            .expect("first declarer");
1549        index
1550            .merge_measure_unit(
1551                "eur".into(),
1552                &b,
1553                "money_b",
1554                &[],
1555                "money_b",
1556                &locals(&[("money_a", &a), ("money_b", &b)]),
1557            )
1558            .expect("second independent eur declarer is kept");
1559        assert_eq!(index.owners_for("eur").len(), 2);
1560
1561        let bound = bind_locals(index, &[("money_a", &a), ("money_b", &b)]);
1562        let err = bound
1563            .resolve("eur")
1564            .expect_err("bare eur with two declarers must be qualified");
1565        assert!(
1566            err.contains("money_a.eur") && err.contains("money_b.eur"),
1567            "got: {err}"
1568        );
1569        let (bare, owner) = bound.resolve("money_b.eur").expect("qualified eur");
1570        assert_eq!(bare, "eur");
1571        assert_eq!(owner.name(), "money_b");
1572    }
1573
1574    #[test]
1575    fn ratio_merge_inserts_second_alias_for_same_type() {
1576        let mut index = PlanningUnitIndex::new();
1577        let ratio = {
1578            let mut units = crate::literals::RatioUnits::new();
1579            units.push(crate::literals::RatioUnit {
1580                name: "percent".into(),
1581                value: rational_one(),
1582                minimum: None,
1583                maximum: None,
1584                suggestion_magnitude: None,
1585            });
1586            Arc::new(LemmaType::new(
1587                "rate".into(),
1588                TypeSpecification::Ratio {
1589                    minimum: None,
1590                    maximum: None,
1591                    units,
1592                    unit: None,
1593                    help: String::new(),
1594                },
1595                TypeExtends::Primitive,
1596            ))
1597        };
1598        index
1599            .merge_ratio_unit(
1600                "percent".into(),
1601                &ratio,
1602                "rate",
1603                &["alpha".into()],
1604                &HashMap::new(),
1605            )
1606            .expect("first alias");
1607        index
1608            .merge_ratio_unit(
1609                "percent".into(),
1610                &ratio,
1611                "rate",
1612                &["beta".into()],
1613                &HashMap::new(),
1614            )
1615            .expect("second alias");
1616        let bound = bind_locals(index, &[]);
1617        assert_eq!(bound.owners_for("percent").len(), 2);
1618        bound
1619            .resolve("alpha.percent")
1620            .expect("alias.unit sugar for ratio");
1621        bound.resolve("beta.percent").expect("beta alias.unit");
1622        bound
1623            .resolve("alpha.rate.percent")
1624            .expect("alpha.Type.unit");
1625        bound.resolve("beta.rate.percent").expect("beta.Type.unit");
1626        let type_unit_err = bound
1627            .resolve("rate.percent")
1628            .expect_err("Type.unit ambiguous when same type_name appears under two aliases");
1629        assert!(
1630            type_unit_err.contains("more than one type")
1631                || type_unit_err.contains("Write one of")
1632                || type_unit_err.contains("ambiguous")
1633                || type_unit_err.contains("Qualify")
1634                || type_unit_err.contains("Unknown"),
1635            "got: {type_unit_err}"
1636        );
1637    }
1638
1639    #[test]
1640    fn named_ratio_keeps_primitive_percent_and_bare_picks_it() {
1641        let mut index = PlanningUnitIndex::new();
1642        index.insert_owner("percent".into(), PlanningOwner::PrimitiveRatio);
1643        let ratio = {
1644            let mut units = crate::literals::RatioUnits::new();
1645            units.push(crate::literals::RatioUnit {
1646                name: "percent".into(),
1647                value: rational_one(),
1648                minimum: None,
1649                maximum: None,
1650                suggestion_magnitude: None,
1651            });
1652            Arc::new(LemmaType::new(
1653                "margin".into(),
1654                TypeSpecification::Ratio {
1655                    minimum: None,
1656                    maximum: None,
1657                    units,
1658                    unit: None,
1659                    help: String::new(),
1660                },
1661                TypeExtends::Primitive,
1662            ))
1663        };
1664        index
1665            .merge_ratio_unit(
1666                "percent".into(),
1667                &ratio,
1668                "margin",
1669                &[],
1670                &locals(&[("margin", &ratio)]),
1671            )
1672            .expect("named ratio merges beside builtin");
1673        let bound = bind_locals(index, &[("margin", &ratio)]);
1674        assert_eq!(bound.owners_for("percent").len(), 2);
1675        let (bare, owner) = bound.resolve("percent").expect("bare percent");
1676        assert_eq!(bare, "percent");
1677        assert!(Arc::ptr_eq(&owner, primitive_ratio_arc()));
1678        let (_, qualified) = bound.resolve("margin.percent").expect("Type.unit");
1679        assert!(Arc::ptr_eq(&qualified, &ratio));
1680    }
1681
1682    fn measure_type_scale(name: &str, unit: &str, scale: UnitScale) -> Arc<LemmaType> {
1683        let mut units = MeasureUnits::new();
1684        units.push(MeasureUnit {
1685            name: unit.to_string(),
1686            scale,
1687            derived_measure_factors: Vec::new(),
1688            decomposition: Default::default(),
1689            minimum: None,
1690            maximum: None,
1691            suggestion_magnitude: None,
1692        });
1693        Arc::new(LemmaType::new(
1694            name.to_string(),
1695            TypeSpecification::Measure {
1696                units,
1697                traits: vec![],
1698                decomposition: None,
1699                minimum: None,
1700                maximum: None,
1701                unit: None,
1702                help: String::new(),
1703            },
1704            TypeExtends::custom_local(
1705                "money".to_string(),
1706                crate::planning::semantics::tests::test_type_family("money"),
1707            ),
1708        ))
1709    }
1710
1711    fn reference_scale(name: &str) -> UnitScale {
1712        UnitScale::Reference {
1713            factors: vec![(
1714                crate::planning::semantics::ScaleTarget {
1715                    target: crate::planning::semantics::ReferenceTarget::Data(
1716                        crate::planning::semantics::DataPath::local(name.to_string()),
1717                    ),
1718                    owner: crate::planning::semantics::ScaleOwner::new(None, "priced"),
1719                },
1720                1,
1721            )],
1722            coefficient: crate::computation::rational::rational_one(),
1723        }
1724    }
1725
1726    #[test]
1727    fn merge_same_literal_scale_agrees() {
1728        let mut index = PlanningUnitIndex::new();
1729        let money = measure_type("money", "eur");
1730        index
1731            .merge_measure_unit(
1732                "eur".into(),
1733                &money,
1734                "money",
1735                &[],
1736                "money",
1737                &locals(&[("money", &money)]),
1738            )
1739            .expect("first");
1740        index
1741            .merge_measure_unit(
1742                "eur".into(),
1743                &money,
1744                "money",
1745                &[],
1746                "money",
1747                &locals(&[("money", &money)]),
1748            )
1749            .expect("same literal scale");
1750    }
1751
1752    #[test]
1753    fn merge_same_reference_scale_agrees() {
1754        let mut index = PlanningUnitIndex::new();
1755        let left = measure_type_scale("left", "gbp", reference_scale("rate"));
1756        let right = measure_type_scale("right", "gbp", reference_scale("rate"));
1757        index
1758            .merge_measure_unit(
1759                "gbp".into(),
1760                &left,
1761                "left",
1762                &[],
1763                "money",
1764                &locals(&[("left", &left)]),
1765            )
1766            .expect("first");
1767        index
1768            .merge_measure_unit(
1769                "gbp".into(),
1770                &right,
1771                "right",
1772                &[],
1773                "money",
1774                &locals(&[("left", &left), ("right", &right)]),
1775            )
1776            .expect("same reference scale");
1777    }
1778
1779    #[test]
1780    fn merge_literal_and_reference_conflict() {
1781        let mut index = PlanningUnitIndex::new();
1782        let literal = measure_type_scale("left", "gbp", UnitScale::Literal(rational_one()));
1783        let reference = measure_type_scale("right", "gbp", reference_scale("rate"));
1784        index
1785            .merge_measure_unit(
1786                "gbp".into(),
1787                &literal,
1788                "left",
1789                &[],
1790                "money",
1791                &locals(&[("left", &literal)]),
1792            )
1793            .expect("literal");
1794        let err = index
1795            .merge_measure_unit(
1796                "gbp".into(),
1797                &reference,
1798                "right",
1799                &[],
1800                "money",
1801                &locals(&[("left", &literal), ("right", &reference)]),
1802            )
1803            .expect_err("literal vs reference");
1804        assert_eq!(
1805            err,
1806            UnitMergeConflict::ConflictingFactors {
1807                unit: "gbp".into(),
1808                family: "money".into(),
1809            }
1810        );
1811    }
1812
1813    #[test]
1814    fn merge_different_reference_scales_conflict() {
1815        let mut index = PlanningUnitIndex::new();
1816        let left = measure_type_scale("left", "gbp", reference_scale("rate_left"));
1817        let right = measure_type_scale("right", "gbp", reference_scale("rate_right"));
1818        index
1819            .merge_measure_unit(
1820                "gbp".into(),
1821                &left,
1822                "left",
1823                &[],
1824                "money",
1825                &locals(&[("left", &left)]),
1826            )
1827            .expect("rate_left");
1828        let err = index
1829            .merge_measure_unit(
1830                "gbp".into(),
1831                &right,
1832                "right",
1833                &[],
1834                "money",
1835                &locals(&[("left", &left), ("right", &right)]),
1836            )
1837            .expect_err("different reference scales in one family conflict");
1838        assert_eq!(
1839            err,
1840            UnitMergeConflict::ConflictingFactors {
1841                unit: "gbp".into(),
1842                family: "money".into(),
1843            }
1844        );
1845    }
1846
1847    #[test]
1848    fn two_imported_owners_of_one_dynamic_unit_stay_distinct() {
1849        let declared = measure_type_scale("money", "gbp", reference_scale("rate"));
1850        let importer = crate::planning::semantics::ScaleOwner::new(None, "importer");
1851        let money_a = Arc::new(declared.with_scale_import_hop(
1852            &PathSegment {
1853                uses: Arc::from("a"),
1854                row: None,
1855                repository: None,
1856                spec: Arc::from("priced"),
1857            },
1858            &importer,
1859        ));
1860        let money_b = Arc::new(declared.with_scale_import_hop(
1861            &PathSegment {
1862                uses: Arc::from("b"),
1863                row: None,
1864                repository: None,
1865                spec: Arc::from("priced"),
1866            },
1867            &importer,
1868        ));
1869        let mut index = PlanningUnitIndex::new();
1870        index.insert_owner(
1871            "gbp".to_string(),
1872            PlanningOwner::Imported {
1873                import_path: vec!["a".to_string()],
1874                type_name: "money".to_string(),
1875                lemma_type: Arc::clone(&money_a),
1876            },
1877        );
1878        index.insert_owner(
1879            "gbp".to_string(),
1880            PlanningOwner::Imported {
1881                import_path: vec!["b".to_string()],
1882                type_name: "money".to_string(),
1883                lemma_type: Arc::clone(&money_b),
1884            },
1885        );
1886        let bound = bind_locals(index, &[]);
1887        let error = bound.resolve("gbp").expect_err("bare gbp is ambiguous");
1888        assert!(
1889            error.contains("Unit 'gbp' matches more than one type")
1890                && error.contains("a.money.gbp")
1891                && error.contains("b.money.gbp"),
1892            "two instances of one spec demand qualification, got: {error}"
1893        );
1894        let (_, owner) = bound
1895            .resolve_owner("a.money.gbp")
1896            .expect("qualification by alias a");
1897        assert_eq!(owner.import_path(), &["a".to_string()][..]);
1898        let (_, owner) = bound
1899            .resolve_owner("b.money.gbp")
1900            .expect("qualification by alias b");
1901        assert_eq!(owner.import_path(), &["b".to_string()][..]);
1902    }
1903}