Skip to main content

domainforge_core/units/
mod.rs

1use rust_decimal::prelude::FromPrimitive;
2use rust_decimal::Decimal;
3use serde::{Deserialize, Serialize};
4use std::collections::HashMap;
5use std::sync::{OnceLock, RwLock};
6
7#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
8pub enum Dimension {
9    Mass,
10    Length,
11    Volume,
12    Currency,
13    Time,
14    Temperature,
15    Count,
16    Custom(String),
17}
18
19impl Dimension {
20    /// Parse a dimension name in a case-insensitive way and map to builtin dimension
21    pub fn parse(name: &str) -> Self {
22        match name.to_ascii_lowercase().as_str() {
23            "mass" => Dimension::Mass,
24            "length" => Dimension::Length,
25            "volume" => Dimension::Volume,
26            "currency" => Dimension::Currency,
27            "time" => Dimension::Time,
28            "temperature" => Dimension::Temperature,
29            "count" => Dimension::Count,
30            other => Dimension::Custom(other.to_string()),
31        }
32    }
33}
34
35impl std::str::FromStr for Dimension {
36    type Err = ();
37
38    fn from_str(s: &str) -> Result<Self, Self::Err> {
39        Ok(Dimension::parse(s))
40    }
41}
42
43impl std::fmt::Display for Dimension {
44    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45        match self {
46            Dimension::Mass => write!(f, "Mass"),
47            Dimension::Length => write!(f, "Length"),
48            Dimension::Volume => write!(f, "Volume"),
49            Dimension::Currency => write!(f, "Currency"),
50            Dimension::Time => write!(f, "Time"),
51            Dimension::Temperature => write!(f, "Temperature"),
52            Dimension::Count => write!(f, "Count"),
53            Dimension::Custom(s) => write!(f, "{}", s),
54        }
55    }
56}
57
58#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
59pub struct Unit {
60    symbol: String,
61    name: String,
62    dimension: Dimension,
63    base_factor: Decimal,
64    base_unit: String,
65}
66
67impl std::fmt::Display for Unit {
68    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
69        write!(f, "{}", self.symbol)
70    }
71}
72
73impl Unit {
74    pub fn new(
75        symbol: impl Into<String>,
76        name: impl Into<String>,
77        dimension: Dimension,
78        base_factor: Decimal,
79        base_unit: impl Into<String>,
80    ) -> Self {
81        let symbol = symbol.into();
82        Self {
83            symbol,
84            name: name.into(),
85            dimension,
86            base_factor,
87            base_unit: base_unit.into(),
88        }
89    }
90
91    pub fn new_base(
92        symbol: impl Into<String>,
93        name: impl Into<String>,
94        dimension: Dimension,
95    ) -> Result<Self, UnitError> {
96        let symbol = symbol.into();
97        let base_unit = symbol.clone();
98        Ok(Self {
99            symbol,
100            name: name.into(),
101            dimension,
102            base_factor: Decimal::ONE,
103            base_unit,
104        })
105    }
106
107    pub fn with_base(mut self, base_unit: impl Into<String>) -> Self {
108        self.base_unit = base_unit.into();
109        self
110    }
111
112    pub fn symbol(&self) -> &str {
113        &self.symbol
114    }
115    pub fn name(&self) -> &str {
116        &self.name
117    }
118    pub fn dimension(&self) -> &Dimension {
119        &self.dimension
120    }
121    pub fn base_factor(&self) -> Decimal {
122        self.base_factor
123    }
124    pub fn base_unit(&self) -> &str {
125        &self.base_unit
126    }
127}
128
129pub trait UnitConversion {
130    fn convert_to_base(&self, value: Decimal) -> Decimal;
131    fn convert_from_base(&self, value: Decimal) -> Decimal;
132}
133
134impl UnitConversion for Unit {
135    fn convert_to_base(&self, value: Decimal) -> Decimal {
136        value * self.base_factor
137    }
138
139    fn convert_from_base(&self, value: Decimal) -> Decimal {
140        value / self.base_factor
141    }
142}
143
144#[derive(Debug, Clone, PartialEq)]
145#[non_exhaustive]
146pub enum UnitError {
147    UnitNotFound(String),
148    IncompatibleDimensions { from: Dimension, to: Dimension },
149    ConversionNotDefined { from: String, to: String },
150    ZeroBaseFactor,
151    DuplicateUnit(String),
152}
153
154impl std::fmt::Display for UnitError {
155    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
156        match self {
157            UnitError::UnitNotFound(symbol) => write!(f, "Unit not found: {}", symbol),
158            UnitError::IncompatibleDimensions { from, to } => {
159                write!(f, "Cannot convert between {:?} and {:?}", from, to)
160            }
161            UnitError::ConversionNotDefined { from, to } => {
162                write!(f, "Conversion not defined from {} to {}", from, to)
163            }
164            UnitError::ZeroBaseFactor => {
165                write!(f, "Unit base_factor cannot be zero")
166            }
167            UnitError::DuplicateUnit(symbol) => {
168                write!(f, "Unit already registered: {}", symbol)
169            }
170        }
171    }
172}
173
174impl std::error::Error for UnitError {}
175
176#[derive(Debug, Clone)]
177pub struct UnitRegistry {
178    units: HashMap<String, Unit>,
179    base_units: HashMap<Dimension, String>,
180}
181
182impl Default for UnitRegistry {
183    fn default() -> Self {
184        let mut registry = Self {
185            units: HashMap::new(),
186            base_units: HashMap::new(),
187        };
188
189        // Mass units
190        registry.register_base(Dimension::Mass, "kg");
191        registry.register_builtin(Unit::new(
192            "kg",
193            "kilogram",
194            Dimension::Mass,
195            Decimal::from(1),
196            "kg",
197        ));
198        registry.register_builtin(Unit::new(
199            "g",
200            "gram",
201            Dimension::Mass,
202            Decimal::new(1, 3),
203            "kg",
204        ));
205        registry.register_builtin(Unit::new(
206            "lb",
207            "pound",
208            Dimension::Mass,
209            Decimal::new(45359237, 8),
210            "kg",
211        ));
212
213        // Length units
214        registry.register_base(Dimension::Length, "m");
215        registry.register_builtin(Unit::new(
216            "m",
217            "meter",
218            Dimension::Length,
219            Decimal::from(1),
220            "m",
221        ));
222        registry.register_builtin(Unit::new(
223            "cm",
224            "centimeter",
225            Dimension::Length,
226            Decimal::new(1, 2),
227            "m",
228        ));
229        registry.register_builtin(Unit::new(
230            "in",
231            "inch",
232            Dimension::Length,
233            Decimal::new(254, 4),
234            "m",
235        ));
236
237        // Volume units
238        registry.register_base(Dimension::Volume, "L");
239        registry.register_builtin(Unit::new(
240            "L",
241            "liter",
242            Dimension::Volume,
243            Decimal::from(1),
244            "L",
245        ));
246        registry.register_builtin(Unit::new(
247            "mL",
248            "milliliter",
249            Dimension::Volume,
250            Decimal::new(1, 3),
251            "L",
252        ));
253
254        // Currency units (no conversion without exchange rates). U5: each
255        // currency below is its own `base_unit` with `base_factor: 1`, so
256        // `Unit::convert_to_base`/`convert_from_base` map every currency to
257        // itself at 1.0. That's only correct because `UnitRegistry::convert`
258        // special-cases `Dimension::Currency` and refuses cross-currency
259        // conversion outright (see below) rather than trusting
260        // `base_factor`. Any new code path that reads `base_factor`
261        // directly instead of going through `convert` would silently treat
262        // EUR/GBP as equal to USD at parity — keep the special-case in sync
263        // if this ever needs real exchange rates.
264        registry.register_base(Dimension::Currency, "USD");
265        registry.register_builtin(Unit::new(
266            "USD",
267            "US Dollar",
268            Dimension::Currency,
269            Decimal::from(1),
270            "USD",
271        ));
272        registry.register_builtin(Unit::new(
273            "EUR",
274            "Euro",
275            Dimension::Currency,
276            Decimal::from(1),
277            "EUR",
278        ));
279        registry.register_builtin(Unit::new(
280            "GBP",
281            "British Pound",
282            Dimension::Currency,
283            Decimal::from(1),
284            "GBP",
285        ));
286
287        // Time units
288        registry.register_base(Dimension::Time, "s");
289        registry.register_builtin(Unit::new(
290            "s",
291            "second",
292            Dimension::Time,
293            Decimal::from(1),
294            "s",
295        ));
296        registry.register_builtin(Unit::new(
297            "min",
298            "minute",
299            Dimension::Time,
300            Decimal::from(60),
301            "s",
302        ));
303        registry.register_builtin(Unit::new(
304            "h",
305            "hour",
306            Dimension::Time,
307            Decimal::from(3600),
308            "s",
309        ));
310        registry.register_builtin(Unit::new(
311            "ms",
312            "millisecond",
313            Dimension::Time,
314            Decimal::new(1, 3),
315            "s",
316        ));
317        registry.register_builtin(Unit::new(
318            "us",
319            "microsecond",
320            Dimension::Time,
321            Decimal::new(1, 6),
322            "s",
323        ));
324        registry.register_builtin(Unit::new(
325            "ns",
326            "nanosecond",
327            Dimension::Time,
328            Decimal::new(1, 9),
329            "s",
330        ));
331
332        // Count (dimensionless)
333        registry.register_base(Dimension::Count, "units");
334        registry.register_builtin(Unit::new(
335            "units",
336            "units",
337            Dimension::Count,
338            Decimal::from(1),
339            "units",
340        ));
341        registry.register_builtin(Unit::new(
342            "items",
343            "items",
344            Dimension::Count,
345            Decimal::from(1),
346            "items",
347        ));
348        // Common metric unit (M1): dimensionless, so it shares the Count
349        // dimension rather than inventing a new one just for a label.
350        registry.register_builtin(Unit::new(
351            "percent",
352            "percent",
353            Dimension::Count,
354            Decimal::from(1),
355            "units",
356        ));
357
358        registry
359    }
360}
361
362impl UnitRegistry {
363    pub fn new() -> Self {
364        Self {
365            units: HashMap::new(),
366            base_units: HashMap::new(),
367        }
368    }
369
370    /// U3: previously this only checked for a duplicate symbol. It now also
371    /// rejects a zero `base_factor` (division by zero in
372    /// `convert_from_base`; the JSON-registration path already caught this,
373    /// direct `register()` calls didn't) and a `base_unit` that references
374    /// an already-registered unit of a *different* dimension (a copy-paste
375    /// mistake that would silently cross-convert two unrelated dimensions).
376    /// It deliberately does not require `base_unit` to already be
377    /// registered — callers legitimately build a registry incrementally
378    /// (e.g. `register_from_json` into a fresh `UnitRegistry::new()`, where
379    /// the base symbol is asserted by convention, not by an existing
380    /// entry).
381    ///
382    /// U2: Temperature is rejected outright. `Unit::convert` is a pure
383    /// linear scale (`value * base_factor`), which cannot express the
384    /// affine Celsius/Fahrenheit conversions real temperature units need;
385    /// registering one here would silently produce wrong numbers rather
386    /// than erroring, which is worse than not supporting it.
387    pub fn register(&mut self, unit: Unit) -> Result<(), UnitError> {
388        if self.units.contains_key(&unit.symbol) {
389            return Err(UnitError::DuplicateUnit(unit.symbol.clone()));
390        }
391        if unit.base_factor == Decimal::ZERO {
392            return Err(UnitError::ZeroBaseFactor);
393        }
394        if matches!(unit.dimension, Dimension::Temperature) {
395            return Err(UnitError::ConversionNotDefined {
396                from: unit.symbol.clone(),
397                to: "Temperature (needs affine/offset conversion, unsupported by this linear unit model)"
398                    .to_string(),
399            });
400        }
401        if unit.base_unit != unit.symbol {
402            if let Some(base) = self.units.get(&unit.base_unit) {
403                if base.dimension != unit.dimension {
404                    return Err(UnitError::IncompatibleDimensions {
405                        from: unit.dimension.clone(),
406                        to: base.dimension.clone(),
407                    });
408                }
409            }
410        }
411        self.units.insert(unit.symbol.clone(), unit);
412        Ok(())
413    }
414
415    fn register_builtin(&mut self, unit: Unit) {
416        self.register(unit)
417            .expect("builtin unit registration must be valid");
418    }
419
420    /// Records that a dimension is known, without asserting a base unit for
421    /// it. Previously this inserted an empty-string placeholder into
422    /// `base_units` when the dimension had none yet (via `or_default`),
423    /// which poisoned any later `base_units()` consumer with a bogus ""
424    /// base symbol (U3). `register_base` is the only source of truth for a
425    /// dimension's actual base unit, so this is now a no-op until that's
426    /// called.
427    pub fn register_dimension(&mut self, _dimension: Dimension) {}
428
429    pub fn register_base(&mut self, dimension: Dimension, base_unit: impl Into<String>) {
430        self.base_units.insert(dimension, base_unit.into());
431    }
432
433    pub fn get_unit(&self, symbol: &str) -> Result<&Unit, UnitError> {
434        self.units
435            .get(symbol)
436            .ok_or_else(|| UnitError::UnitNotFound(symbol.to_string()))
437    }
438
439    pub fn units(&self) -> &HashMap<String, Unit> {
440        &self.units
441    }
442
443    pub fn base_units(&self) -> &HashMap<Dimension, String> {
444        &self.base_units
445    }
446
447    pub fn convert(&self, value: Decimal, from: &Unit, to: &Unit) -> Result<Decimal, UnitError> {
448        if from.dimension != to.dimension {
449            return Err(UnitError::IncompatibleDimensions {
450                from: from.dimension.clone(),
451                to: to.dimension.clone(),
452            });
453        }
454
455        if matches!(from.dimension, Dimension::Currency) && from.symbol != to.symbol {
456            return Err(UnitError::ConversionNotDefined {
457                from: from.symbol.clone(),
458                to: to.symbol.clone(),
459            });
460        }
461
462        // Cheap invariant check (debug builds only, zero release cost):
463        // same-dimension units should always share a base_unit symbol.
464        // `register()` enforces this at insertion time (U3), so tripping
465        // this in a test/dev build means the registry was built
466        // inconsistently — e.g. two units of the same dimension registered
467        // against different `base_unit` strings.
468        debug_assert_eq!(
469            from.base_unit, to.base_unit,
470            "same-dimension units '{}' and '{}' disagree on base_unit ('{}' vs '{}')",
471            from.symbol, to.symbol, from.base_unit, to.base_unit
472        );
473
474        let in_base = from.convert_to_base(value);
475        let in_target = to.convert_from_base(in_base);
476
477        Ok(in_target)
478    }
479
480    /// U4: this is a process-wide mutable singleton. Any model's custom
481    /// unit registrations (via the DSL's `Dimension`/`Unit` declarations,
482    /// see `parser/ast.rs`) persist for the lifetime of the process and are
483    /// visible to every other model parsed afterward in the same process —
484    /// harmless for the one-shot CLI, but a cross-request leak risk for any
485    /// long-lived host (an LSP server, a WASM/Python binding kept alive
486    /// across calls). If that ever becomes a problem, thread an explicit
487    /// `&UnitRegistry` through instead of reaching for this singleton.
488    pub fn global() -> &'static RwLock<UnitRegistry> {
489        static GLOBAL_REGISTRY: OnceLock<RwLock<UnitRegistry>> = OnceLock::new();
490        GLOBAL_REGISTRY.get_or_init(|| RwLock::new(UnitRegistry::default()))
491    }
492
493    /// Register units defined in a JSON string of the form:
494    /// [{ "symbol": "X", "name": "Name", "dimension": "Currency", "base_factor": 1.0, "base_unit": "USD" }]
495    pub fn register_from_json(&mut self, json: &str) -> Result<(), UnitError> {
496        #[derive(Deserialize)]
497        struct UnitConfig {
498            symbol: String,
499            name: String,
500            dimension: String,
501            base_factor: f64,
502            base_unit: String,
503        }
504
505        let parsed: Vec<UnitConfig> =
506            serde_json::from_str(json).map_err(|e| UnitError::ConversionNotDefined {
507                from: "json".to_string(),
508                to: e.to_string(),
509            })?;
510        for cfg in parsed {
511            let dim = Dimension::parse(&cfg.dimension);
512            let factor = Decimal::from_f64(cfg.base_factor).ok_or(UnitError::ZeroBaseFactor)?;
513            if factor == Decimal::ZERO {
514                return Err(UnitError::ZeroBaseFactor);
515            }
516            let unit = Unit::new(cfg.symbol, cfg.name, dim, factor, cfg.base_unit);
517            self.register(unit)?;
518        }
519        Ok(())
520    }
521}
522
523pub fn get_default_registry() -> &'static RwLock<UnitRegistry> {
524    UnitRegistry::global()
525}
526
527/// Fallible unit lookup (U1). Returns `UnitError::UnitNotFound` for an
528/// unregistered symbol instead of silently fabricating a Count-dimension
529/// unit. Prefer this in new code; `unit_from_string` exists only for the
530/// large pre-existing call-site surface that assumes an infallible lookup.
531pub fn try_unit_from_string(symbol: &str) -> Result<Unit, UnitError> {
532    let registry = get_default_registry();
533    let registry = registry.read().unwrap_or_else(|e| e.into_inner());
534    registry.get_unit(symbol).cloned()
535}
536
537/// Helper function to get a Unit from a string symbol, using the default
538/// registry. Fabricates a unit for an unregistered symbol instead of
539/// erroring (kept infallible for the large existing call-site surface —
540/// see [`try_unit_from_string`] for the fallible alternative).
541///
542/// U1 fix: the fabricated unit's dimension is `Custom(symbol)`, not
543/// `Count`. Previously every unregistered symbol landed in the shared
544/// `Count` dimension, so two different typos (or two unrelated free-form
545/// business units, e.g. "orders" vs "widgets") were treated as the same
546/// dimension and converted 1:1 with no error — the actual bug this gap
547/// caused. Keying the fabricated dimension by the symbol itself means
548/// `convert()` now correctly reports `IncompatibleDimensions` between any
549/// two distinct unregistered units, while a symbol converted against
550/// itself (the only sane use of an ad-hoc unit) still works.
551pub fn unit_from_string(symbol: impl Into<String>) -> Unit {
552    let symbol = symbol.into();
553    try_unit_from_string(&symbol).unwrap_or_else(|_| {
554        Unit::new(
555            symbol.clone(),
556            symbol.clone(),
557            Dimension::Custom(symbol.clone()),
558            Decimal::from(1),
559            symbol.clone(),
560        )
561    })
562}