dimvexa-core 0.2.2

Unit conversion core: dimensions, exact rationals, parser and prepared conversions. Exact factors. Loud failures. Zero guessing.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
// SPDX-License-Identifier: MIT OR Apache-2.0
//! Unit definitions (static data and owned form) and resolved unit expressions.

use core::fmt;

use crate::dim::Dim;
use crate::error::{Error, Result};
use crate::expr::{Expr, is_valid_symbol};
use crate::kind::{Exactness, Kind, Shape};
use crate::prefix::PrefixMode;
use crate::ratio::Ratio;

/// A unit as it appears in a compiled data table (plain data, `const`-constructible).
///
/// Fractions are `(numerator, denominator)` pairs; the registry validates and reduces them
/// when loading.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UnitDef {
    /// Primary symbol, for example `psi`.
    pub symbol: &'static str,
    /// Alternative symbols, for example `["\u{b0}C"]` for `degC`.
    pub aliases: &'static [&'static str],
    /// Dimension exponents of `[kg, m, s, A, K, mol, cd]`.
    pub dim: [i8; 7],
    /// Quantity kind.
    pub kind: Kind,
    /// Conversion shape to the coherent SI unit.
    pub shape: Shape,
    /// Factor `a` in `si = a * x + b`, as `(numerator, denominator)`.
    pub factor: (i128, i128),
    /// Offset `b` in `si = a * x + b`, as `(numerator, denominator)`.
    pub offset: (i128, i128),
    /// Defined or measured.
    pub exactness: Exactness,
    /// Accepted prefixes.
    pub prefixes: PrefixMode,
    /// Namespace, `si` or `std` for the core table.
    pub namespace: &'static str,
    /// Citation of the primary definition.
    pub source: &'static str,
    /// Free-text note (derivation, caveats).
    pub note: &'static str,
}

/// A bare symbol that is deliberately rejected, with the explicit symbols to use instead.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AmbiguousDef {
    /// The ambiguous bare symbol, for example `ton`.
    pub symbol: &'static str,
    /// Explicit unit symbols present in the table.
    pub candidates: &'static [&'static str],
    /// Explicit symbols that are planned but not yet in the table.
    pub planned: &'static [&'static str],
    /// Why the symbol is ambiguous.
    pub note: &'static str,
}

/// An owned unit definition held by a [`crate::Registry`].
///
/// `si_value = factor * x + offset`, where `x` is the value in this unit.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Unit {
    symbol: String,
    aliases: Vec<String>,
    dim: Dim,
    kind: Kind,
    factor: Ratio,
    offset: Ratio,
    exactness: Exactness,
    prefixes: PrefixMode,
    namespace: String,
    source: String,
    note: String,
}

impl Unit {
    /// A linear unit: `si = factor * x`, defined exactly, no prefixes, namespace `std`.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidDefinition`] for a malformed symbol or a non-positive factor.
    ///
    /// # Examples
    ///
    /// ```
    /// use dimvexa_core::{Dim, Ratio, Unit};
    /// let inch = Unit::linear("in", Dim::M, Ratio::new(127, 5000)?)?;
    /// assert_eq!(inch.symbol(), "in");
    /// # Ok::<(), dimvexa_core::Error>(())
    /// ```
    pub fn linear(symbol: &str, dim: Dim, factor: Ratio) -> Result<Self> {
        Self::new(symbol, dim, Kind::Plain, factor, Ratio::ZERO)
    }

    /// A general unit with an offset (affine when `offset` is non-zero).
    ///
    /// # Errors
    ///
    /// [`Error::InvalidDefinition`] for a malformed symbol, a non-positive factor, or an
    /// offset on a unit that is not a temperature.
    pub fn new(symbol: &str, dim: Dim, kind: Kind, factor: Ratio, offset: Ratio) -> Result<Self> {
        let bad = |message: &str| Error::InvalidDefinition {
            symbol: symbol.to_string(),
            message: message.to_string(),
        };
        if !is_valid_symbol(symbol) {
            return Err(bad(
                "symbol must be non-empty and contain only letters, '_' or the degree sign",
            ));
        }
        if factor.signum() <= 0 {
            return Err(bad("factor must be positive"));
        }
        if !offset.is_zero() && kind != Kind::AbsoluteTemperature {
            return Err(bad("only absolute temperature units may have an offset"));
        }
        Ok(Self {
            symbol: symbol.to_string(),
            aliases: Vec::new(),
            dim,
            kind,
            factor,
            offset,
            exactness: Exactness::Defined,
            prefixes: PrefixMode::None,
            namespace: "std".to_string(),
            source: String::new(),
            note: String::new(),
        })
    }

    /// Validates and converts a static table row.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidDefinition`] when the row is inconsistent (shape/offset mismatch,
    /// bad fraction, bad symbol or alias), or [`Error::DivisionByZero`] for a zero denominator.
    pub fn from_def(def: &UnitDef) -> Result<Self> {
        let factor = Ratio::new(def.factor.0, def.factor.1)?;
        let offset = Ratio::new(def.offset.0, def.offset.1)?;
        let mut unit = Self::new(def.symbol, Dim::new(def.dim), def.kind, factor, offset)?;
        let bad = |message: &str| Error::InvalidDefinition {
            symbol: def.symbol.to_string(),
            message: message.to_string(),
        };
        match (def.shape, offset.is_zero()) {
            (Shape::Linear, false) => return Err(bad("linear shape requires a zero offset")),
            (Shape::Affine, true) => return Err(bad("affine shape requires a non-zero offset")),
            _ => {}
        }
        if !offset.is_zero() && def.prefixes != PrefixMode::None {
            return Err(bad("affine units cannot take prefixes"));
        }
        for alias in def.aliases {
            if !is_valid_symbol(alias) {
                return Err(bad(
                    "alias contains characters that cannot appear in a symbol",
                ));
            }
            unit.aliases.push((*alias).to_string());
        }
        unit.exactness = def.exactness;
        unit.prefixes = def.prefixes;
        unit.namespace = def.namespace.to_string();
        unit.source = def.source.to_string();
        unit.note = def.note.to_string();
        Ok(unit)
    }

    /// Adds aliases (alternative symbols).
    ///
    /// # Errors
    ///
    /// [`Error::InvalidDefinition`] if an alias is not a well-formed symbol.
    pub fn with_aliases(mut self, aliases: &[&str]) -> Result<Self> {
        for a in aliases {
            if !is_valid_symbol(a) {
                return Err(Error::InvalidDefinition {
                    symbol: self.symbol,
                    message: format!("alias '{a}' is not a well-formed symbol"),
                });
            }
            self.aliases.push((*a).to_string());
        }
        Ok(self)
    }

    /// Sets the accepted prefixes (ignored for units with an offset, which never take any).
    #[must_use]
    pub const fn with_prefixes(mut self, prefixes: PrefixMode) -> Self {
        if self.offset.is_zero() {
            self.prefixes = prefixes;
        }
        self
    }

    /// Sets exactness, source and note.
    #[must_use]
    pub fn with_provenance(mut self, exactness: Exactness, source: &str, note: &str) -> Self {
        self.exactness = exactness;
        self.source = source.to_string();
        self.note = note.to_string();
        self
    }

    /// Sets the namespace.
    #[must_use]
    pub fn with_namespace(mut self, namespace: &str) -> Self {
        self.namespace = namespace.to_string();
        self
    }

    /// Primary symbol.
    #[must_use]
    pub fn symbol(&self) -> &str {
        &self.symbol
    }

    /// Alternative symbols.
    #[must_use]
    pub fn aliases(&self) -> &[String] {
        &self.aliases
    }

    /// Dimension.
    #[must_use]
    pub const fn dim(&self) -> Dim {
        self.dim
    }

    /// Quantity kind.
    #[must_use]
    pub const fn kind(&self) -> Kind {
        self.kind
    }

    /// Conversion shape.
    #[must_use]
    pub const fn shape(&self) -> Shape {
        if self.offset.is_zero() {
            Shape::Linear
        } else {
            Shape::Affine
        }
    }

    /// Factor to the coherent SI unit.
    #[must_use]
    pub const fn factor(&self) -> Ratio {
        self.factor
    }

    /// Offset to the coherent SI unit.
    #[must_use]
    pub const fn offset(&self) -> Ratio {
        self.offset
    }

    /// Defined or measured.
    #[must_use]
    pub const fn exactness(&self) -> Exactness {
        self.exactness
    }

    /// Accepted prefixes.
    #[must_use]
    pub const fn prefixes(&self) -> PrefixMode {
        self.prefixes
    }

    /// Namespace.
    #[must_use]
    pub fn namespace(&self) -> &str {
        &self.namespace
    }

    /// Citation of the definition.
    #[must_use]
    pub fn source(&self) -> &str {
        &self.source
    }

    /// Note.
    #[must_use]
    pub fn note(&self) -> &str {
        &self.note
    }
}

/// A resolved unit expression such as `km/h` or `kW.h`: dimension, kind and the exact
/// relation to the coherent SI unit, composed once.
///
/// `si_value = factor * x + offset`. Only a single (possibly prefixed) unit can have a
/// non-zero offset; compound expressions are linear.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnitExpr {
    expr: Expr,
    dim: Dim,
    kind: Kind,
    factor: Ratio,
    offset: Ratio,
    exactness: Exactness,
    sources: Vec<String>,
    /// Symbol of the registered temperature-difference unit of the same scale (`delta_K`
    /// for `K`), only set for a plain absolute temperature unit.
    difference: Option<String>,
}

impl UnitExpr {
    /// The unit `1` (dimensionless, factor one).
    #[must_use]
    pub const fn unity() -> Self {
        Self {
            expr: Expr::One,
            dim: Dim::NONE,
            kind: Kind::Plain,
            factor: Ratio::ONE,
            offset: Ratio::ZERO,
            exactness: Exactness::Defined,
            sources: Vec::new(),
            difference: None,
        }
    }

    pub(crate) const fn from_parts(
        expr: Expr,
        dim: Dim,
        kind: Kind,
        factor: Ratio,
        offset: Ratio,
        exactness: Exactness,
        sources: Vec<String>,
    ) -> Self {
        Self {
            expr,
            dim,
            kind,
            factor,
            offset,
            exactness,
            sources,
            difference: None,
        }
    }

    pub(crate) fn with_difference(mut self, difference: Option<String>) -> Self {
        self.difference = difference;
        self
    }

    /// Symbol of the registered temperature-difference unit that goes with this absolute
    /// temperature unit (`delta_K` for `K`, `delta_degC` for `degC`). `None` for every other
    /// unit expression, including prefixed temperatures such as `mK`.
    #[must_use]
    pub fn difference_symbol(&self) -> Option<&str> {
        self.difference.as_deref()
    }

    /// True for the plain scalar `1`.
    #[must_use]
    pub fn is_unity(&self) -> bool {
        self.dim.is_dimensionless()
            && self.kind == Kind::Plain
            && self.factor == Ratio::ONE
            && self.offset.is_zero()
    }

    /// The syntax tree this expression was resolved from.
    #[must_use]
    pub const fn expr(&self) -> &Expr {
        &self.expr
    }

    /// Dimension.
    #[must_use]
    pub const fn dim(&self) -> Dim {
        self.dim
    }

    /// Kind.
    #[must_use]
    pub const fn kind(&self) -> Kind {
        self.kind
    }

    /// Exact factor to the coherent SI unit.
    #[must_use]
    pub const fn factor(&self) -> Ratio {
        self.factor
    }

    /// Exact offset to the coherent SI unit.
    #[must_use]
    pub const fn offset(&self) -> Ratio {
        self.offset
    }

    /// Conversion shape relative to SI.
    #[must_use]
    pub const fn shape(&self) -> Shape {
        if self.offset.is_zero() {
            Shape::Linear
        } else {
            Shape::Affine
        }
    }

    /// Defined, or measured if any component is measured.
    #[must_use]
    pub const fn exactness(&self) -> Exactness {
        self.exactness
    }

    /// Distinct source citations of all components, in order of first use.
    #[must_use]
    pub fn sources(&self) -> &[String] {
        &self.sources
    }

    fn merged_sources(&self, other: &Self) -> Vec<String> {
        let mut out = self.sources.clone();
        for s in &other.sources {
            if !out.contains(s) {
                out.push(s.clone());
            }
        }
        out
    }

    fn refuse_affine(&self, other: &Self) -> Result<()> {
        for u in [self, other] {
            if !u.offset.is_zero() {
                let suggestions: Vec<String> = u.difference.iter().cloned().collect();
                let advice = suggestions.first().map_or_else(
                    || {
                        String::from(
                            "use a difference unit (delta_...) for a temperature difference",
                        )
                    },
                    |d| format!("use the difference unit {d} for a temperature difference"),
                );
                return Err(Error::Refused {
                    reason: format!(
                        "'{}' has an offset (temperature scale) and cannot be part of a compound unit; {advice}",
                        u.expr
                    ),
                    suggestions,
                });
            }
        }
        Ok(())
    }

    /// Product of two unit expressions. Multiplying by the plain scalar `1` returns the
    /// other operand unchanged.
    ///
    /// # Errors
    ///
    /// [`Error::Refused`] if an operand has an offset, [`Error::Overflow`] on overflow.
    pub fn mul(&self, rhs: &Self) -> Result<Self> {
        if self.is_unity() {
            return Ok(rhs.clone());
        }
        if rhs.is_unity() {
            return Ok(self.clone());
        }
        self.refuse_affine(rhs)?;
        Ok(Self {
            expr: Expr::Mul(Box::new(self.expr.clone()), Box::new(rhs.expr.clone())),
            dim: self.dim.checked_add(rhs.dim)?,
            kind: Kind::Plain,
            factor: self.factor.checked_mul(rhs.factor)?,
            offset: Ratio::ZERO,
            exactness: self.exactness.combine(rhs.exactness),
            sources: self.merged_sources(rhs),
            difference: None,
        })
    }

    /// Quotient of two unit expressions. Dividing by the plain scalar `1` returns `self`.
    ///
    /// # Errors
    ///
    /// [`Error::Refused`] if an operand has an offset, [`Error::Overflow`] on overflow.
    pub fn div(&self, rhs: &Self) -> Result<Self> {
        if rhs.is_unity() {
            return Ok(self.clone());
        }
        self.refuse_affine(rhs)?;
        Ok(Self {
            expr: Expr::Div(Box::new(self.expr.clone()), Box::new(rhs.expr.clone())),
            dim: self.dim.checked_sub(rhs.dim)?,
            kind: Kind::Plain,
            factor: self.factor.checked_div(rhs.factor)?,
            offset: Ratio::ZERO,
            exactness: self.exactness.combine(rhs.exactness),
            sources: self.merged_sources(rhs),
            difference: None,
        })
    }

    /// Integer power. The power 1 returns `self` unchanged (so `degC^1` stays valid), the
    /// power 0 returns the scalar `1`.
    ///
    /// # Errors
    ///
    /// [`Error::Refused`] for an offset unit with a power other than 1,
    /// [`Error::Overflow`] on overflow.
    pub fn pow(&self, exp: i32) -> Result<Self> {
        if exp == 1 {
            return Ok(self.clone());
        }
        self.refuse_affine(&Self::unity())?;
        Ok(Self {
            expr: Expr::Pow(Box::new(self.expr.clone()), exp),
            dim: self.dim.checked_scale(exp)?,
            kind: Kind::Plain,
            factor: self.factor.checked_pow(exp)?,
            offset: Ratio::ZERO,
            exactness: self.exactness,
            sources: self.sources.clone(),
            difference: None,
        })
    }
}

impl fmt::Display for UnitExpr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.expr.fmt(f)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn m() -> UnitExpr {
        UnitExpr::from_parts(
            Expr::Unit("m".into()),
            Dim::M,
            Kind::Plain,
            Ratio::ONE,
            Ratio::ZERO,
            Exactness::Defined,
            vec!["SI".into()],
        )
    }

    #[test]
    fn unity_is_identity_for_mul_and_div() {
        let u = UnitExpr::unity();
        assert_eq!(u.mul(&m()).unwrap(), m());
        assert_eq!(m().mul(&u).unwrap(), m());
        assert_eq!(m().div(&u).unwrap(), m());
        assert!(m().pow(0).unwrap().is_unity() || m().pow(0).unwrap().dim().is_dimensionless());
    }

    #[test]
    fn products_compose_exactly() {
        let sq = m().mul(&m()).unwrap();
        assert_eq!(sq.dim(), Dim::new([0, 2, 0, 0, 0, 0, 0]));
        assert_eq!(sq.to_string(), "m.m");
        let inv = UnitExpr::unity().div(&m()).unwrap();
        assert_eq!(inv.dim(), Dim::new([0, -1, 0, 0, 0, 0, 0]));
        assert_eq!(inv.sources(), ["SI"]);
    }

    #[test]
    fn rejects_bad_definitions() {
        assert!(Unit::linear("", Dim::M, Ratio::ONE).is_err());
        assert!(Unit::linear("m2", Dim::M, Ratio::ONE).is_err());
        assert!(Unit::linear("m", Dim::M, Ratio::ZERO).is_err());
        assert!(Unit::linear("m", Dim::M, Ratio::from_int(-1)).is_err());
        assert!(Unit::new("x", Dim::M, Kind::Plain, Ratio::ONE, Ratio::ONE).is_err());
        assert!(
            Unit::linear("m", Dim::M, Ratio::ONE)
                .unwrap()
                .with_aliases(&["a b"])
                .is_err()
        );
    }

    #[test]
    fn from_def_checks_shape() {
        let mut d = UnitDef {
            symbol: "x",
            aliases: &[],
            dim: [0, 1, 0, 0, 0, 0, 0],
            kind: Kind::Plain,
            shape: Shape::Linear,
            factor: (2, 4),
            offset: (0, 1),
            exactness: Exactness::Defined,
            prefixes: PrefixMode::Si,
            namespace: "std",
            source: "test",
            note: "",
        };
        assert_eq!(
            Unit::from_def(&d).unwrap().factor(),
            Ratio::new(1, 2).unwrap()
        );
        d.shape = Shape::Affine;
        assert!(Unit::from_def(&d).is_err());
        d.shape = Shape::Linear;
        d.offset = (1, 1);
        assert!(Unit::from_def(&d).is_err());
        d.factor = (1, 0);
        assert!(Unit::from_def(&d).is_err());
    }
}