graphcal-compiler 0.0.1-alpha.14

Type-safe, unit-aware, Git-friendly reactive programming language for engineering calculations
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
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
use std::collections::BTreeMap;
use std::fmt;

use thiserror::Error;

/// A rational number for dimension exponents (e.g., 1/2 for sqrt).
///
/// Always stored in reduced form with `den > 0`.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct Rational {
    num: i32,
    den: i32,
}

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

impl fmt::Display for Rational {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.den == 1 {
            write!(f, "{}", self.num)
        } else {
            write!(f, "{}/{}", self.num, self.den)
        }
    }
}

impl Rational {
    pub const ZERO: Self = Self { num: 0, den: 1 };
    pub const ONE: Self = Self { num: 1, den: 1 };
    /// `1/2` — used for square-root exponents.
    pub const HALF: Self = Self { num: 1, den: 2 };
    /// `1/3` — used for cube-root exponents.
    pub const THIRD: Self = Self { num: 1, den: 3 };

    /// Try to create a new rational number, automatically reduced.
    ///
    /// Returns `Err` if `den` is zero.
    pub fn try_new(num: i32, den: i32) -> Result<Self, RationalError> {
        if den == 0 {
            return Err(RationalError::ZeroDenominator);
        }
        if num == 0 {
            return Ok(Self::ZERO);
        }
        let g = gcd(num.unsigned_abs(), den.unsigned_abs()).cast_signed();
        let (n, d) = (num / g, den / g);
        // Normalize sign: denominator is always positive
        if d < 0 {
            Ok(Self { num: -n, den: -d })
        } else {
            Ok(Self { num: n, den: d })
        }
    }

    /// Create a rational from an integer.
    #[must_use]
    pub const fn from_int(n: i32) -> Self {
        if n == 0 {
            Self::ZERO
        } else {
            Self { num: n, den: 1 }
        }
    }

    /// Returns the numerator.
    #[must_use]
    pub const fn num(self) -> i32 {
        self.num
    }

    /// Returns the denominator (always positive).
    #[must_use]
    pub const fn den(self) -> i32 {
        self.den
    }

    #[must_use]
    pub const fn is_zero(self) -> bool {
        self.num == 0
    }

    #[must_use]
    pub const fn is_integer(self) -> bool {
        self.den == 1
    }
}

/// Error from `Rational` construction or arithmetic.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum RationalError {
    /// The denominator was zero.
    #[error("denominator must not be zero")]
    ZeroDenominator,
    /// The reduced numerator or denominator did not fit in `i32`.
    ///
    /// Dimension exponents are stored as `i32`; an operation produced a
    /// reduced value outside that range.
    #[error("dimension exponent overflowed i32")]
    Overflow,
}

/// Compute `num / den` in `i64` with GCD reduction, then narrow back to `i32`.
///
/// Returns `Err(RationalError::Overflow)` if the reduced result does not fit
/// in `i32`, and `Err(RationalError::ZeroDenominator)` if `den` is zero.
fn reduce_i64(num: i64, den: i64) -> Result<(i32, i32), RationalError> {
    if den == 0 {
        return Err(RationalError::ZeroDenominator);
    }
    if num == 0 {
        return Ok((0, 1));
    }
    let g = gcd64(num.unsigned_abs(), den.unsigned_abs()).cast_signed();
    let (mut n, mut d) = (num / g, den / g);
    if d < 0 {
        n = -n;
        d = -d;
    }
    let num = i32::try_from(n).map_err(|_| RationalError::Overflow)?;
    let den = i32::try_from(d).map_err(|_| RationalError::Overflow)?;
    Ok((num, den))
}

impl std::ops::Add for Rational {
    type Output = Result<Self, RationalError>;
    fn add(self, rhs: Self) -> Self::Output {
        // Widen to i64 to avoid intermediate overflow
        let num =
            i64::from(self.num) * i64::from(rhs.den) + i64::from(rhs.num) * i64::from(self.den);
        let den = i64::from(self.den) * i64::from(rhs.den);
        let (n, d) = reduce_i64(num, den)?;
        Ok(Self { num: n, den: d })
    }
}

impl std::ops::Sub for Rational {
    type Output = Result<Self, RationalError>;
    fn sub(self, rhs: Self) -> Self::Output {
        let num =
            i64::from(self.num) * i64::from(rhs.den) - i64::from(rhs.num) * i64::from(self.den);
        let den = i64::from(self.den) * i64::from(rhs.den);
        let (n, d) = reduce_i64(num, den)?;
        Ok(Self { num: n, den: d })
    }
}

impl std::ops::Neg for Rational {
    type Output = Self;
    fn neg(self) -> Self {
        Self {
            num: -self.num,
            den: self.den,
        }
    }
}

impl std::ops::Mul for Rational {
    type Output = Result<Self, RationalError>;
    fn mul(self, rhs: Self) -> Self::Output {
        let num = i64::from(self.num) * i64::from(rhs.num);
        let den = i64::from(self.den) * i64::from(rhs.den);
        let (n, d) = reduce_i64(num, den)?;
        Ok(Self { num: n, den: d })
    }
}

fn gcd(a: u32, b: u32) -> u32 {
    if b == 0 { a } else { gcd(b, a % b) }
}

fn gcd64(a: u64, b: u64) -> u64 {
    if b == 0 { a } else { gcd64(b, a % b) }
}

/// A unique identifier for a base dimension.
///
/// Identity is name-based rather than auto-incremented, ensuring consistency
/// across per-file compilation units (important for diamond imports).
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum BaseDimId {
    /// Built-in prelude dimension (e.g., "Length", "Time", "Mass").
    Prelude(String),
    /// User-defined dimension, identified by the defining DAG's identity + name.
    UserDefined {
        dag: crate::dag_id::DagId,
        name: String,
    },
}

impl BaseDimId {
    /// A human-readable fallback name when no symbol/name map is available.
    #[must_use]
    pub fn fallback_symbol(&self) -> String {
        match self {
            Self::Prelude(name) | Self::UserDefined { name, .. } => name.clone(),
        }
    }
}

/// A physical dimension represented as a sparse vector of rational exponents
/// over base dimensions.
///
/// For example, Velocity = Length^1 * Time^-1 is represented as
/// `{BaseDimId::Prelude("Length"): 1, BaseDimId::Prelude("Time"): -1}`.
///
/// Only non-zero exponents are stored. An empty map represents the dimensionless
/// dimension.
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct Dimension {
    /// Non-zero exponents only. Sorted by `BaseDimId` for deterministic equality/hash.
    exponents: BTreeMap<BaseDimId, Rational>,
}

impl fmt::Debug for Dimension {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.is_dimensionless() {
            write!(f, "Dimension(Dimensionless)")
        } else {
            write!(f, "Dimension(")?;
            let mut first = true;
            for (id, exp) in &self.exponents {
                if !first {
                    write!(f, " * ")?;
                }
                first = false;
                match id {
                    BaseDimId::Prelude(name) | BaseDimId::UserDefined { name, .. } => {
                        write!(f, "{name}")?;
                    }
                }
                if *exp != Rational::ONE {
                    write!(f, "^{exp}")?;
                }
            }
            write!(f, ")")
        }
    }
}

impl Dimension {
    /// The dimensionless dimension (empty exponent map).
    #[must_use]
    pub const fn dimensionless() -> Self {
        Self {
            exponents: BTreeMap::new(),
        }
    }

    /// A dimension with a single base dimension at exponent 1.
    #[must_use]
    pub fn base(id: BaseDimId) -> Self {
        let mut exponents = BTreeMap::new();
        exponents.insert(id, Rational::ONE);
        Self { exponents }
    }

    #[must_use]
    pub fn is_dimensionless(&self) -> bool {
        self.exponents.is_empty()
    }

    /// Get the exponent for a specific base dimension (zero if absent).
    #[must_use]
    pub fn get_exponent(&self, id: &BaseDimId) -> Rational {
        self.exponents.get(id).copied().unwrap_or(Rational::ZERO)
    }

    /// Returns an iterator over the non-zero `(BaseDimId, Rational)` pairs.
    pub fn iter(&self) -> impl Iterator<Item = (&BaseDimId, &Rational)> {
        self.exponents.iter()
    }

    /// Raise a dimension to a rational power (multiply all exponents).
    ///
    /// Returns `Err(RationalError::Overflow)` if any exponent multiplication
    /// produces a reduced value outside the `i32` range.
    pub fn pow(&self, exp: Rational) -> Result<Self, RationalError> {
        if exp.is_zero() {
            return Ok(Self::dimensionless());
        }
        let mut exponents = BTreeMap::new();
        for (id, &e) in &self.exponents {
            let new_exp = (e * exp)?;
            if !new_exp.is_zero() {
                exponents.insert(id.clone(), new_exp);
            }
        }
        Ok(Self { exponents })
    }

    /// Raise a dimension to an integer power.
    ///
    /// Returns `Err(RationalError::Overflow)` if any exponent multiplication
    /// overflows `i32`.
    pub fn pow_int(&self, n: i32) -> Result<Self, RationalError> {
        self.pow(Rational::from_int(n))
    }

    /// Format this dimension using named base dimensions for display.
    ///
    /// The `names` map provides `BaseDimId → name` mappings.
    /// Unknown IDs are displayed as `D{id}`.
    #[must_use]
    pub const fn display_with<'a>(
        &'a self,
        names: &'a BTreeMap<BaseDimId, String>,
    ) -> DimensionDisplay<'a> {
        DimensionDisplay { dim: self, names }
    }

    /// Write the dimension's exponents to a [`fmt::Write`] sink.
    ///
    /// `mul_sep` is placed between positive-exponent terms (e.g., `"*"` or `" * "`).
    /// `div_sep` is placed before each negative-exponent term when positive terms exist
    /// (e.g., `"/"` or `" / "`).
    fn write_exponents(
        &self,
        w: &mut impl fmt::Write,
        names: &BTreeMap<BaseDimId, String>,
        mul_sep: &str,
        div_sep: &str,
    ) -> fmt::Result {
        let mut first = true;

        // Positive exponents (numerator)
        for (id, &exp) in &self.exponents {
            if exp.num() <= 0 {
                continue;
            }
            if !first {
                w.write_str(mul_sep)?;
            }
            first = false;
            let name = names
                .get(id)
                .map_or_else(|| id.fallback_symbol(), String::clone);
            write!(w, "{name}")?;
            if exp != Rational::ONE {
                write!(w, "^{exp}")?;
            }
        }

        // Negative exponents (denominator)
        for (id, &exp) in &self.exponents {
            if exp.num() >= 0 {
                continue;
            }
            let name = names
                .get(id)
                .map_or_else(|| id.fallback_symbol(), String::clone);
            if first {
                // Only negative exponents (e.g., Frequency = s^-1)
                write!(w, "{name}^{exp}")?;
                first = false;
            } else {
                w.write_str(div_sep)?;
                write!(w, "{name}")?;
                let pos_exp = -exp;
                if pos_exp != Rational::ONE {
                    write!(w, "^{pos_exp}")?;
                }
            }
        }

        Ok(())
    }
}

/// A wrapper for displaying a `Dimension` with named base dimensions.
pub struct DimensionDisplay<'a> {
    dim: &'a Dimension,
    names: &'a BTreeMap<BaseDimId, String>,
}

impl fmt::Display for DimensionDisplay<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.dim.is_dimensionless() {
            return write!(f, "Dimensionless");
        }
        self.dim.write_exponents(f, self.names, " * ", " / ")
    }
}

/// Whether to add or subtract exponents when combining dimensions.
#[derive(Clone, Copy)]
enum CombineOp {
    /// Add exponents (dimension multiplication).
    Add,
    /// Subtract exponents (dimension division).
    Sub,
}

impl Dimension {
    /// Combine two dimensions by adding or subtracting exponents.
    fn combine(self, other: &Self, op: CombineOp) -> Result<Self, RationalError> {
        let mut exponents = self.exponents;
        for (id, exp) in &other.exponents {
            let entry = exponents.entry(id.clone()).or_insert(Rational::ZERO);
            *entry = match op {
                CombineOp::Add => (*entry + *exp)?,
                CombineOp::Sub => (*entry - *exp)?,
            };
            if entry.is_zero() {
                exponents.remove(id);
            }
        }
        Ok(Self { exponents })
    }
}

impl std::ops::Mul for Dimension {
    type Output = Result<Self, RationalError>;
    /// Multiply two dimensions (add exponents).
    fn mul(self, other: Self) -> Self::Output {
        self.combine(&other, CombineOp::Add)
    }
}

impl std::ops::Div for Dimension {
    type Output = Result<Self, RationalError>;
    /// Divide two dimensions (subtract exponents).
    fn div(self, other: Self) -> Self::Output {
        self.combine(&other, CombineOp::Sub)
    }
}

impl std::ops::Mul for &Dimension {
    type Output = Result<Dimension, RationalError>;
    fn mul(self, other: Self) -> Self::Output {
        self.clone().combine(other, CombineOp::Add)
    }
}

impl std::ops::Div for &Dimension {
    type Output = Result<Dimension, RationalError>;
    fn div(self, other: Self) -> Self::Output {
        self.clone().combine(other, CombineOp::Sub)
    }
}

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

    /// Test helper: build a `Rational` from integer literals, panicking on
    /// zero denominator. Tests are the only place panicking is acceptable.
    fn r(num: i32, den: i32) -> Rational {
        Rational::try_new(num, den).expect("non-zero denominator")
    }

    // Helper: well-known base dimension IDs matching prelude dimensions.
    fn length() -> BaseDimId {
        BaseDimId::Prelude("Length".to_string())
    }
    fn time() -> BaseDimId {
        BaseDimId::Prelude("Time".to_string())
    }
    fn mass() -> BaseDimId {
        BaseDimId::Prelude("Mass".to_string())
    }

    /// Build a names map for display tests.
    fn test_names() -> BTreeMap<BaseDimId, String> {
        let mut m = BTreeMap::new();
        m.insert(
            BaseDimId::Prelude("Length".to_string()),
            "Length".to_string(),
        );
        m.insert(BaseDimId::Prelude("Time".to_string()), "Time".to_string());
        m.insert(BaseDimId::Prelude("Mass".to_string()), "Mass".to_string());
        m.insert(
            BaseDimId::Prelude("Temperature".to_string()),
            "Temperature".to_string(),
        );
        m.insert(
            BaseDimId::Prelude("ElectricCurrent".to_string()),
            "ElectricCurrent".to_string(),
        );
        m.insert(
            BaseDimId::Prelude("Amount".to_string()),
            "Amount".to_string(),
        );
        m.insert(
            BaseDimId::Prelude("LuminousIntensity".to_string()),
            "LuminousIntensity".to_string(),
        );
        m.insert(BaseDimId::Prelude("Angle".to_string()), "Angle".to_string());
        m
    }

    #[test]
    fn rational_creation_and_reduction() {
        assert_eq!(r(2, 4), r(1, 2));
        assert_eq!(r(-3, 6), r(-1, 2));
        assert_eq!(r(6, -4), r(-3, 2));
        assert_eq!(r(0, 5), Rational::ZERO);
    }

    #[test]
    fn rational_arithmetic() {
        let half = r(1, 2);
        let third = r(1, 3);

        // 1/2 + 1/3 = 5/6
        let sum = (half + third).unwrap();
        assert_eq!(sum, r(5, 6));

        // 1/2 - 1/3 = 1/6
        let diff = (half - third).unwrap();
        assert_eq!(diff, r(1, 6));

        // 1/2 * 1/3 = 1/6
        let prod = (half * third).unwrap();
        assert_eq!(prod, r(1, 6));

        // -1/2
        assert_eq!(-half, r(-1, 2));
    }

    #[test]
    fn rational_from_int() {
        assert_eq!(Rational::from_int(3), r(3, 1));
        assert_eq!(Rational::from_int(0), Rational::ZERO);
        assert_eq!(Rational::from_int(-2), r(-2, 1));
    }

    #[test]
    fn dimension_base() {
        let len = Dimension::base(length());
        assert_eq!(len.get_exponent(&length()), Rational::ONE);
        assert!(len.get_exponent(&time()).is_zero());
        assert!(len.get_exponent(&mass()).is_zero());
    }

    #[test]
    fn dimension_dimensionless() {
        assert!(Dimension::dimensionless().is_dimensionless());
        assert!(!Dimension::base(length()).is_dimensionless());
    }

    #[test]
    fn dimension_velocity() {
        // Velocity = Length / Time
        let l = Dimension::base(length());
        let t = Dimension::base(time());
        let velocity = (l / t).unwrap();

        assert_eq!(velocity.get_exponent(&length()), Rational::ONE);
        assert_eq!(velocity.get_exponent(&time()), Rational::from_int(-1));
    }

    #[test]
    fn dimension_acceleration() {
        // Acceleration = Length / Time^2
        let l = Dimension::base(length());
        let t = Dimension::base(time());
        let accel = (l / t.pow_int(2).unwrap()).unwrap();

        assert_eq!(accel.get_exponent(&length()), Rational::ONE);
        assert_eq!(accel.get_exponent(&time()), Rational::from_int(-2));
    }

    #[test]
    fn dimension_force() {
        // Force = Mass * Length / Time^2
        let m = Dimension::base(mass());
        let l = Dimension::base(length());
        let t = Dimension::base(time());
        let force = ((m * l).unwrap() / t.pow_int(2).unwrap()).unwrap();

        assert_eq!(force.get_exponent(&mass()), Rational::ONE);
        assert_eq!(force.get_exponent(&length()), Rational::ONE);
        assert_eq!(force.get_exponent(&time()), Rational::from_int(-2));
    }

    #[test]
    fn dimension_sqrt() {
        // sqrt(Area) = sqrt(Length^2) = Length
        let area = Dimension::base(length()).pow_int(2).unwrap();
        let sqrt_area = area.pow(Rational::HALF).unwrap();
        assert_eq!(sqrt_area, Dimension::base(length()));
    }

    #[test]
    fn dimension_mul_div_inverse() {
        let l = Dimension::base(length());
        let t = Dimension::base(time());
        let velocity = (l.clone() / t.clone()).unwrap();

        // velocity * time = length
        assert_eq!((velocity.clone() * t.clone()).unwrap(), l);

        // length / velocity = time
        assert_eq!((l / velocity).unwrap(), t);
    }

    #[test]
    fn dimension_dimensionless_mul() {
        let l = Dimension::base(length());
        assert_eq!((Dimension::dimensionless() * l.clone()).unwrap(), l);
        assert_eq!((l.clone() * Dimension::dimensionless()).unwrap(), l);
    }

    #[test]
    fn dimension_display_simple() {
        let names = test_names();
        assert_eq!(
            format!("{}", Dimension::dimensionless().display_with(&names)),
            "Dimensionless"
        );
        assert_eq!(
            format!("{}", Dimension::base(length()).display_with(&names)),
            "Length"
        );
    }

    #[test]
    fn dimension_display_velocity() {
        let names = test_names();
        let velocity = (Dimension::base(length()) / Dimension::base(time())).unwrap();
        assert_eq!(
            format!("{}", velocity.display_with(&names)),
            "Length / Time"
        );
    }

    #[test]
    fn dimension_display_force() {
        let names = test_names();
        let force = ((Dimension::base(mass()) * Dimension::base(length())).unwrap()
            / Dimension::base(time()).pow_int(2).unwrap())
        .unwrap();
        assert_eq!(
            format!("{}", force.display_with(&names)),
            "Length * Mass / Time^2"
        );
    }

    #[test]
    fn dimension_display_area() {
        let names = test_names();
        let area = Dimension::base(length()).pow_int(2).unwrap();
        assert_eq!(format!("{}", area.display_with(&names)), "Length^2");
    }

    #[test]
    fn dimension_display_frequency() {
        let names = test_names();
        // Frequency = Time^-1 (only negative exponent)
        let freq = (Dimension::dimensionless() / Dimension::base(time())).unwrap();
        assert_eq!(format!("{}", freq.display_with(&names)), "Time^-1");
    }

    #[test]
    fn dimension_user_defined_base() {
        // User-defined base dimension gets a new ID
        let info_id = BaseDimId::UserDefined {
            dag: crate::dag_id::DagId::root("test"),
            name: "Information".to_string(),
        };
        let information = Dimension::base(info_id.clone());
        let t = Dimension::base(time());
        let bandwidth = (information / t).unwrap();

        assert_eq!(bandwidth.get_exponent(&info_id), Rational::ONE);
        assert_eq!(bandwidth.get_exponent(&time()), Rational::from_int(-1));

        // Display with names
        let mut names = test_names();
        names.insert(info_id, "Information".to_string());
        assert_eq!(
            format!("{}", bandwidth.display_with(&names)),
            "Information / Time"
        );
    }

    #[test]
    fn dimension_hash_consistency() {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        let a = (Dimension::base(length()) / Dimension::base(time())).unwrap();
        let b = (Dimension::base(length()) / Dimension::base(time())).unwrap();
        assert_eq!(a, b);

        let mut ha = DefaultHasher::new();
        a.hash(&mut ha);
        let mut hb = DefaultHasher::new();
        b.hash(&mut hb);
        assert_eq!(ha.finish(), hb.finish());
    }

    mod prop {
        use super::*;
        use proptest::prelude::*;

        /// Strategy for generating Rational values with small numerators/denominators
        /// to avoid i32 overflow in intermediate calculations.
        fn arb_rational() -> impl Strategy<Value = Rational> {
            (-50i32..=50, -50i32..=50)
                .prop_filter("denominator must be non-zero", |&(_, d)| d != 0)
                .prop_map(|(n, d)| Rational::try_new(n, d).expect("filtered d != 0"))
        }

        /// The 8 prelude dimension names for property testing.
        const PRELUDE_DIMS: [&str; 8] = [
            "Length",
            "Time",
            "Mass",
            "Temperature",
            "ElectricCurrent",
            "Amount",
            "LuminousIntensity",
            "Angle",
        ];

        /// Strategy for generating Dimension values with small exponents.
        /// Uses a fixed set of prelude base dimension IDs.
        fn arb_dimension() -> impl Strategy<Value = Dimension> {
            proptest::collection::btree_map(0usize..8, arb_rational(), 0..=8).prop_map(|map| {
                let exponents = map
                    .into_iter()
                    .filter(|(_, r)| !r.is_zero())
                    .map(|(idx, r)| (BaseDimId::Prelude(PRELUDE_DIMS[idx].to_string()), r))
                    .collect();
                Dimension { exponents }
            })
        }

        proptest! {
            // --- Rational invariants ---

            #[test]
            fn rational_always_reduced(n in -100i32..=100, d in -100i32..=100) {
                prop_assume!(d != 0);
                let r = Rational::try_new(n, d).expect("d != 0 by prop_assume");
                // den is always positive
                prop_assert!(r.den() > 0, "den must be positive, got {}", r.den());
                // gcd(|num|, den) == 1 (reduced form)
                if r.num() != 0 {
                    let g = gcd(r.num().unsigned_abs(), r.den().unsigned_abs());
                    prop_assert_eq!(g, 1, "not reduced: {}/{}", r.num(), r.den());
                } else {
                    prop_assert_eq!(r.den(), 1, "zero should have den=1, got {}", r.den());
                }
            }

            #[test]
            fn rational_add_commutative(a in arb_rational(), b in arb_rational()) {
                prop_assert_eq!((a + b).unwrap(), (b + a).unwrap());
            }

            #[test]
            fn rational_mul_commutative(a in arb_rational(), b in arb_rational()) {
                prop_assert_eq!((a * b).unwrap(), (b * a).unwrap());
            }

            #[test]
            fn rational_additive_identity(a in arb_rational()) {
                prop_assert_eq!((a + Rational::ZERO).unwrap(), a);
            }

            #[test]
            fn rational_multiplicative_identity(a in arb_rational()) {
                prop_assert_eq!((a * Rational::ONE).unwrap(), a);
            }

            #[test]
            fn rational_additive_inverse(a in arb_rational()) {
                prop_assert_eq!((a + (-a)).unwrap(), Rational::ZERO);
            }

            #[test]
            fn rational_sub_self_is_zero(a in arb_rational()) {
                prop_assert_eq!((a - a).unwrap(), Rational::ZERO);
            }

            // --- Dimension invariants ---

            #[test]
            fn dimension_mul_commutative(a in arb_dimension(), b in arb_dimension()) {
                prop_assert_eq!((a.clone() * b.clone()).unwrap(), (b * a).unwrap());
            }

            #[test]
            fn dimension_dimensionless_is_mul_identity(a in arb_dimension()) {
                prop_assert_eq!((a.clone() * Dimension::dimensionless()).unwrap(), a);
            }

            #[test]
            fn dimension_self_div_is_dimensionless(a in arb_dimension()) {
                prop_assert_eq!((a.clone() / a).unwrap(), Dimension::dimensionless());
            }

            #[test]
            fn dimension_div_inverse(a in arb_dimension(), b in arb_dimension()) {
                // (a / b) * b == a
                prop_assert_eq!(((a.clone() / b.clone()).unwrap() * b).unwrap(), a);
            }

            #[test]
            fn dimension_pow_int_consistent_with_pow(a in arb_dimension(), n in -3i32..=3) {
                prop_assert_eq!(a.pow_int(n).unwrap(), a.pow(Rational::from_int(n)).unwrap());
            }

            #[test]
            fn dimension_pow_distributes_over_mul(
                a in arb_dimension(),
                b in arb_dimension(),
                r in arb_rational(),
            ) {
                // (a * b).pow(r) == a.pow(r) * b.pow(r)
                prop_assert_eq!(
                    (a.clone() * b.clone()).unwrap().pow(r).unwrap(),
                    (a.pow(r).unwrap() * b.pow(r).unwrap()).unwrap(),
                );
            }
        }
    }
}