lemma-engine 0.8.14

A language that means business.
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
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
//! Literal value types and string parsing. No dependency on parsing/ast.
//! AST and planning re-export these types where needed.

use chrono::{Datelike, Timelike};
use rust_decimal::Decimal;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::collections::BTreeMap;
use std::fmt;

use crate::computation::rational::{self, RationalInteger};

// -----------------------------------------------------------------------------
// Dimensional decomposition type
// -----------------------------------------------------------------------------

/// A dimensional decomposition vector. Maps quantity-type names to integer exponents.
/// For example, velocity `{length: 1, duration: -1}` or acceleration `{length: 1, duration: -2}`.
/// An empty map indicates a base quantity (no decomposition) until the decomposition pass runs,
/// after which every quantity carries a non-empty vector.
pub type BaseQuantityVector = BTreeMap<String, i32>;

// -----------------------------------------------------------------------------
// Unit tables for Quantity and Ratio types
// -----------------------------------------------------------------------------

pub fn rational_to_serialized_str(rational: &RationalInteger) -> Result<String, String> {
    rational::rational_to_wire_str(rational).map_err(|failure| failure.to_string())
}

pub fn rational_from_parsed_decimal(decimal: Decimal) -> Result<RationalInteger, String> {
    rational::decimal_to_rational(decimal).map_err(|failure| failure.to_string())
}

/// Serde for stored rationals: wire format is decimal string or JSON number (lifted at boundary).
pub mod stored_rational_serde {
    use super::{rational_from_parsed_decimal, rational_to_serialized_str, RationalInteger};
    use rust_decimal::Decimal;
    use serde::{Deserialize, Deserializer, Serializer};

    pub fn serialize<S: Serializer>(
        value: &RationalInteger,
        serializer: S,
    ) -> Result<S::Ok, S::Error> {
        serializer
            .serialize_str(&rational_to_serialized_str(value).map_err(serde::ser::Error::custom)?)
    }

    pub mod option {
        use super::*;

        pub fn serialize<S: Serializer>(
            value: &Option<RationalInteger>,
            serializer: S,
        ) -> Result<S::Ok, S::Error> {
            match value {
                Some(rational) => super::serialize(rational, serializer),
                None => serializer.serialize_none(),
            }
        }

        pub fn deserialize<'de, D: Deserializer<'de>>(
            deserializer: D,
        ) -> Result<Option<RationalInteger>, D::Error> {
            Option::<Decimal>::deserialize(deserializer)?
                .map(rational_from_parsed_decimal)
                .transpose()
                .map_err(serde::de::Error::custom)
        }
    }
}

/// A single unit within a Quantity type.
///
/// `factor` is the conversion factor: 1 of this unit equals `factor` canonical units.
/// `derived_quantity_factors` stores `(quantity_ref, exponent)` pairs from compound unit declarations
/// (e.g., `meter/second` produces `[("meter", 1), ("second", -1)]`). Empty for base units.
/// `decomposition` is the dimensional decomposition vector, populated during the planning
/// decomposition pass. It is empty until that pass completes.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct QuantityUnit {
    pub name: String,
    /// Conversion factor: 1 of this unit equals `value` canonical units.
    pub factor: RationalInteger,
    pub derived_quantity_factors: Vec<(String, i32)>,
    pub decomposition: BaseQuantityVector,
    /// Minimum magnitude in this unit (schema/UI); canonical bound is on the type.
    pub minimum: Option<RationalInteger>,
    /// Maximum magnitude in this unit (schema/UI).
    pub maximum: Option<RationalInteger>,
    /// Default suggestion magnitude in this unit (schema/UI).
    pub default_magnitude: Option<RationalInteger>,
}

impl Serialize for QuantityUnit {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        use quantity_unit_factor_serialization::FactorSerializer;
        use serde::ser::SerializeStruct;
        let mut state = serializer.serialize_struct("QuantityUnit", 7)?;
        state.serialize_field("name", &self.name)?;
        state.serialize_field("factor", &FactorSerializer::from_ratio(&self.factor))?;
        state.serialize_field("derived_quantity_factors", &self.derived_quantity_factors)?;
        state.serialize_field("decomposition", &self.decomposition)?;
        if let Some(minimum) = &self.minimum {
            state.serialize_field(
                "minimum",
                &rational_to_serialized_str(minimum).map_err(serde::ser::Error::custom)?,
            )?;
        }
        if let Some(maximum) = &self.maximum {
            state.serialize_field(
                "maximum",
                &rational_to_serialized_str(maximum).map_err(serde::ser::Error::custom)?,
            )?;
        }
        if let Some(default_magnitude) = &self.default_magnitude {
            state.serialize_field(
                "default",
                &rational_to_serialized_str(default_magnitude)
                    .map_err(serde::ser::Error::custom)?,
            )?;
        }
        state.end()
    }
}

impl<'de> Deserialize<'de> for QuantityUnit {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        struct QuantityUnitData {
            name: String,
            #[serde(with = "quantity_unit_factor_serialization")]
            factor: RationalInteger,
            #[serde(default)]
            derived_quantity_factors: Vec<(String, i32)>,
            #[serde(default)]
            decomposition: BaseQuantityVector,
            #[serde(default)]
            minimum: Option<Decimal>,
            #[serde(default)]
            maximum: Option<Decimal>,
            #[serde(default, rename = "default")]
            default_magnitude: Option<Decimal>,
        }
        let data = QuantityUnitData::deserialize(deserializer)?;
        Ok(Self {
            name: data.name,
            factor: data.factor,
            derived_quantity_factors: data.derived_quantity_factors,
            decomposition: data.decomposition,
            minimum: data
                .minimum
                .map(rational_from_parsed_decimal)
                .transpose()
                .map_err(serde::de::Error::custom)?,
            maximum: data
                .maximum
                .map(rational_from_parsed_decimal)
                .transpose()
                .map_err(serde::de::Error::custom)?,
            default_magnitude: data
                .default_magnitude
                .map(rational_from_parsed_decimal)
                .transpose()
                .map_err(serde::de::Error::custom)?,
        })
    }
}

impl QuantityUnit {
    pub fn from_decimal_factor(
        name: String,
        decimal_factor: Decimal,
        derived_quantity_factors: Vec<(String, i32)>,
    ) -> Result<Self, String> {
        let factor =
            rational::decimal_to_rational(decimal_factor).map_err(|failure| failure.to_string())?;
        Ok(QuantityUnit {
            name,
            factor,
            derived_quantity_factors,
            decomposition: BaseQuantityVector::new(),
            minimum: None,
            maximum: None,
            default_magnitude: None,
        })
    }

    pub fn clear_constraint_magnitudes(&mut self) {
        self.minimum = None;
        self.maximum = None;
        self.default_magnitude = None;
    }

    pub fn is_canonical_factor(&self) -> bool {
        self.factor == rational::rational_one()
    }

    pub fn is_positive_factor(&self) -> bool {
        let numerator = *self.factor.numer();
        let denominator = *self.factor.denom();
        numerator != 0 && (numerator > 0) == (denominator > 0)
    }
}

mod quantity_unit_factor_serialization {
    use super::RationalInteger;
    use serde::{Deserialize, Serialize};

    #[derive(Serialize, Deserialize)]
    pub struct FactorSerializer {
        numer: String,
        denom: String,
    }

    impl FactorSerializer {
        pub fn from_ratio(value: &RationalInteger) -> Self {
            let reduced = value.reduced();
            FactorSerializer {
                numer: reduced.numer().to_string(),
                denom: reduced.denom().to_string(),
            }
        }

        pub fn into_ratio(self) -> Result<RationalInteger, String> {
            let numer: i128 = self
                .numer
                .parse()
                .map_err(|error: std::num::ParseIntError| error.to_string())?;
            let denom: i128 = self
                .denom
                .parse()
                .map_err(|error: std::num::ParseIntError| error.to_string())?;
            if denom == 0 {
                return Err("QuantityUnit conversion factor denominator cannot be zero".to_string());
            }
            Ok(RationalInteger::new(numer, denom).reduced())
        }
    }

    pub fn deserialize<'de, D: serde::Deserializer<'de>>(
        deserializer: D,
    ) -> Result<RationalInteger, D::Error> {
        FactorSerializer::deserialize(deserializer)?
            .into_ratio()
            .map_err(serde::de::Error::custom)
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct QuantityUnits(pub Vec<QuantityUnit>);

impl QuantityUnits {
    pub fn new() -> Self {
        QuantityUnits(Vec::new())
    }
    pub fn get(&self, name: &str) -> Result<&QuantityUnit, String> {
        self.0.iter().find(|u| u.name == name).ok_or_else(|| {
            let valid: Vec<&str> = self.0.iter().map(|u| u.name.as_str()).collect();
            format!(
                "Unknown unit '{}' for this quantity type. Valid units: {}",
                name,
                valid.join(", ")
            )
        })
    }

    pub fn iter(&self) -> std::slice::Iter<'_, QuantityUnit> {
        self.0.iter()
    }
    pub fn push(&mut self, u: QuantityUnit) {
        self.0.push(u);
    }
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
    pub fn len(&self) -> usize {
        self.0.len()
    }
}

impl Default for QuantityUnits {
    fn default() -> Self {
        QuantityUnits::new()
    }
}

impl From<Vec<QuantityUnit>> for QuantityUnits {
    fn from(v: Vec<QuantityUnit>) -> Self {
        QuantityUnits(v)
    }
}

impl<'a> IntoIterator for &'a QuantityUnits {
    type Item = &'a QuantityUnit;
    type IntoIter = std::slice::Iter<'a, QuantityUnit>;
    fn into_iter(self) -> Self::IntoIter {
        self.0.iter()
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct RatioUnit {
    pub name: String,
    pub value: RationalInteger,
    pub minimum: Option<RationalInteger>,
    pub maximum: Option<RationalInteger>,
    pub default_magnitude: Option<RationalInteger>,
}

impl Serialize for RatioUnit {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        use quantity_unit_factor_serialization::FactorSerializer;
        use serde::ser::SerializeStruct;
        let mut state = serializer.serialize_struct("RatioUnit", 5)?;
        state.serialize_field("name", &self.name)?;
        state.serialize_field("value", &FactorSerializer::from_ratio(&self.value))?;
        if let Some(minimum) = &self.minimum {
            state.serialize_field(
                "minimum",
                &rational_to_serialized_str(minimum).map_err(serde::ser::Error::custom)?,
            )?;
        }
        if let Some(maximum) = &self.maximum {
            state.serialize_field(
                "maximum",
                &rational_to_serialized_str(maximum).map_err(serde::ser::Error::custom)?,
            )?;
        }
        if let Some(default_magnitude) = &self.default_magnitude {
            state.serialize_field(
                "default",
                &rational_to_serialized_str(default_magnitude)
                    .map_err(serde::ser::Error::custom)?,
            )?;
        }
        state.end()
    }
}

impl<'de> Deserialize<'de> for RatioUnit {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        struct RatioUnitData {
            name: String,
            #[serde(with = "quantity_unit_factor_serialization")]
            value: RationalInteger,
            #[serde(default)]
            minimum: Option<Decimal>,
            #[serde(default)]
            maximum: Option<Decimal>,
            #[serde(default, rename = "default")]
            default_magnitude: Option<Decimal>,
        }
        let data = RatioUnitData::deserialize(deserializer)?;
        Ok(Self {
            name: data.name,
            value: data.value,
            minimum: data
                .minimum
                .map(rational_from_parsed_decimal)
                .transpose()
                .map_err(serde::de::Error::custom)?,
            maximum: data
                .maximum
                .map(rational_from_parsed_decimal)
                .transpose()
                .map_err(serde::de::Error::custom)?,
            default_magnitude: data
                .default_magnitude
                .map(rational_from_parsed_decimal)
                .transpose()
                .map_err(serde::de::Error::custom)?,
        })
    }
}

impl RatioUnit {
    pub fn clear_constraint_magnitudes(&mut self) {
        self.minimum = None;
        self.maximum = None;
        self.default_magnitude = None;
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct RatioUnits(pub Vec<RatioUnit>);

impl RatioUnits {
    pub fn new() -> Self {
        RatioUnits(Vec::new())
    }
    pub fn get(&self, name: &str) -> Result<&RatioUnit, String> {
        self.0.iter().find(|u| u.name == name).ok_or_else(|| {
            let valid: Vec<&str> = self.0.iter().map(|u| u.name.as_str()).collect();
            format!(
                "Unknown unit '{}' for this ratio type. Valid units: {}",
                name,
                valid.join(", ")
            )
        })
    }

    pub fn iter(&self) -> std::slice::Iter<'_, RatioUnit> {
        self.0.iter()
    }
    pub fn push(&mut self, u: RatioUnit) {
        self.0.push(u);
    }
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
    pub fn len(&self) -> usize {
        self.0.len()
    }
}

impl Default for RatioUnits {
    fn default() -> Self {
        RatioUnits::new()
    }
}

impl From<Vec<RatioUnit>> for RatioUnits {
    fn from(v: Vec<RatioUnit>) -> Self {
        RatioUnits(v)
    }
}

impl<'a> IntoIterator for &'a RatioUnits {
    type Item = &'a RatioUnit;
    type IntoIter = std::slice::Iter<'a, RatioUnit>;
    fn into_iter(self) -> Self::IntoIter {
        self.0.iter()
    }
}

// -----------------------------------------------------------------------------
// Literal value types
// -----------------------------------------------------------------------------

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum BooleanValue {
    True,
    False,
    Yes,
    No,
    Accept,
    Reject,
}

impl From<BooleanValue> for bool {
    fn from(value: BooleanValue) -> bool {
        matches!(
            value,
            BooleanValue::True | BooleanValue::Yes | BooleanValue::Accept
        )
    }
}

impl From<&BooleanValue> for bool {
    fn from(value: &BooleanValue) -> bool {
        (*value).into() // Copy makes this ok
    }
}

impl From<bool> for BooleanValue {
    fn from(value: bool) -> BooleanValue {
        if value {
            BooleanValue::True
        } else {
            BooleanValue::False
        }
    }
}

impl std::ops::Not for BooleanValue {
    type Output = BooleanValue;

    fn not(self) -> Self::Output {
        if self.into() {
            BooleanValue::False
        } else {
            BooleanValue::True
        }
    }
}

impl std::ops::Not for &BooleanValue {
    type Output = BooleanValue;

    fn not(self) -> Self::Output {
        if (*self).into() {
            BooleanValue::False
        } else {
            BooleanValue::True
        }
    }
}

impl std::str::FromStr for BooleanValue {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.trim().to_lowercase().as_str() {
            "true" => Ok(BooleanValue::True),
            "false" => Ok(BooleanValue::False),
            "yes" => Ok(BooleanValue::Yes),
            "no" => Ok(BooleanValue::No),
            "accept" => Ok(BooleanValue::Accept),
            "reject" => Ok(BooleanValue::Reject),
            _ => Err(format!("Invalid boolean: '{}'", s)),
        }
    }
}

impl BooleanValue {
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            BooleanValue::True => "true",
            BooleanValue::False => "false",
            BooleanValue::Yes => "yes",
            BooleanValue::No => "no",
            BooleanValue::Accept => "accept",
            BooleanValue::Reject => "reject",
        }
    }
}

impl fmt::Display for BooleanValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum CalendarUnit {
    Month,
    Year,
}

impl CalendarUnit {
    #[must_use]
    pub fn from_keyword(s: &str) -> Option<Self> {
        match s.trim().to_lowercase().as_str() {
            "month" | "months" => Some(Self::Month),
            "year" | "years" => Some(Self::Year),
            _ => None,
        }
    }

    #[must_use]
    pub fn canonical_factor(&self) -> RationalInteger {
        match self {
            Self::Month => rational::rational_one(),
            Self::Year => RationalInteger::new(12, 1),
        }
    }
}

impl Serialize for CalendarUnit {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(&self.to_string())
    }
}

impl<'de> Deserialize<'de> for CalendarUnit {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        s.parse().map_err(serde::de::Error::custom)
    }
}

impl fmt::Display for CalendarUnit {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            CalendarUnit::Month => "months",
            CalendarUnit::Year => "years",
        };
        write!(f, "{}", s)
    }
}

impl std::str::FromStr for CalendarUnit {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::from_keyword(s).ok_or_else(|| format!("Unknown calendar unit: '{}'", s))
    }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct TimezoneValue {
    pub offset_hours: i8,
    pub offset_minutes: u8,
}

impl fmt::Display for TimezoneValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.offset_hours == 0 && self.offset_minutes == 0 {
            write!(f, "Z")
        } else {
            let sign = if self.offset_hours >= 0 { "+" } else { "-" };
            let hours = self.offset_hours.abs();
            write!(f, "{}{:02}:{:02}", sign, hours, self.offset_minutes)
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize)]
pub struct TimeValue {
    pub hour: u8,
    pub minute: u8,
    pub second: u8,
    #[serde(default)]
    pub microsecond: u32,
    pub timezone: Option<TimezoneValue>,
}

impl fmt::Display for TimeValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:02}:{:02}:{:02}", self.hour, self.minute, self.second)?;
        if self.microsecond != 0 {
            write!(f, ".{:06}", self.microsecond)?;
        }
        if let Some(timezone) = &self.timezone {
            write!(f, "{}", timezone)?;
        }
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct DateTimeValue {
    pub year: i32,
    pub month: u32,
    pub day: u32,
    pub hour: u32,
    pub minute: u32,
    pub second: u32,
    #[serde(default)]
    pub microsecond: u32,
    pub timezone: Option<TimezoneValue>,
}

impl DateTimeValue {
    pub fn now() -> Self {
        let now = chrono::Local::now();
        let offset_secs = now.offset().local_minus_utc();
        Self {
            year: now.year(),
            month: now.month(),
            day: now.day(),
            hour: now.time().hour(),
            minute: now.time().minute(),
            second: now.time().second(),
            microsecond: now.time().nanosecond() / 1000 % 1_000_000,
            timezone: Some(TimezoneValue {
                offset_hours: (offset_secs / 3600) as i8,
                offset_minutes: ((offset_secs.abs() % 3600) / 60) as u8,
            }),
        }
    }

    fn parse_iso_week(s: &str) -> Option<Self> {
        let parts: Vec<&str> = s.split("-W").collect();
        if parts.len() != 2 {
            return None;
        }
        let year: i32 = parts[0].parse().ok()?;
        let week: u32 = parts[1].parse().ok()?;
        if week == 0 || week > 53 {
            return None;
        }
        let date = chrono::NaiveDate::from_isoywd_opt(year, week, chrono::Weekday::Mon)?;
        Some(Self {
            year: date.year(),
            month: date.month(),
            day: date.day(),
            hour: 0,
            minute: 0,
            second: 0,
            microsecond: 0,
            timezone: None,
        })
    }
}

impl fmt::Display for DateTimeValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let has_time = self.hour != 0
            || self.minute != 0
            || self.second != 0
            || self.microsecond != 0
            || self.timezone.is_some();
        if !has_time {
            write!(f, "{:04}-{:02}-{:02}", self.year, self.month, self.day)
        } else {
            write!(
                f,
                "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}",
                self.year, self.month, self.day, self.hour, self.minute, self.second
            )?;
            if self.microsecond != 0 {
                write!(f, ".{:06}", self.microsecond)?;
            }
            if let Some(tz) = &self.timezone {
                write!(f, "{}", tz)?;
            }
            Ok(())
        }
    }
}

/// Literal value data (no type information). Single source of truth in literals.
///
/// `NumberWithUnit` is type-agnostic at parse time (`10 eur` and `50%` share this shape).
/// Planning resolves ratio vs quantity via the unit index and target [`TypeSpecification`].
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Value {
    Number(Decimal),
    NumberWithUnit(Decimal, String),
    Text(String),
    Date(DateTimeValue),
    Time(TimeValue),
    Boolean(BooleanValue),
    Calendar(Decimal, CalendarUnit),
    Range(Box<Value>, Box<Value>),
}

impl fmt::Display for Value {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Value::Number(n) => write!(f, "{}", n),
            Value::Text(s) => write!(f, "{}", s),
            Value::Date(dt) => write!(f, "{}", dt),
            Value::Boolean(b) => write!(f, "{}", b),
            Value::Time(time) => write!(f, "{}", time),
            Value::NumberWithUnit(n, u) => match u.as_str() {
                "percent" => {
                    let norm = n.normalize();
                    let s = if norm.fract().is_zero() {
                        norm.trunc().to_string()
                    } else {
                        norm.to_string()
                    };
                    write!(f, "{}%", s)
                }
                "permille" => {
                    let norm = n.normalize();
                    let s = if norm.fract().is_zero() {
                        norm.trunc().to_string()
                    } else {
                        norm.to_string()
                    };
                    write!(f, "{}%%", s)
                }
                unit => {
                    let norm = n.normalize();
                    let s = if norm.fract().is_zero() {
                        norm.trunc().to_string()
                    } else {
                        norm.to_string()
                    };
                    write!(f, "{} {}", s, unit)
                }
            },
            Value::Calendar(n, u) => write!(f, "{} {}", n, u),
            Value::Range(left, right) => write!(f, "{}...{}", left, right),
        }
    }
}

// -----------------------------------------------------------------------------
// FromStr (single source of truth per type)
// -----------------------------------------------------------------------------

impl std::str::FromStr for DateTimeValue {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if let Ok(dt) = s.parse::<chrono::DateTime<chrono::FixedOffset>>() {
            let offset = dt.offset().local_minus_utc();
            let microsecond = dt.nanosecond() / 1000 % 1_000_000;
            return Ok(DateTimeValue {
                year: dt.year(),
                month: dt.month(),
                day: dt.day(),
                hour: dt.hour(),
                minute: dt.minute(),
                second: dt.second(),
                microsecond,
                timezone: Some(TimezoneValue {
                    offset_hours: (offset / 3600) as i8,
                    offset_minutes: ((offset.abs() % 3600) / 60) as u8,
                }),
            });
        }
        if let Ok(dt) = s.parse::<chrono::NaiveDateTime>() {
            let microsecond = dt.nanosecond() / 1000 % 1_000_000;
            return Ok(DateTimeValue {
                year: dt.year(),
                month: dt.month(),
                day: dt.day(),
                hour: dt.hour(),
                minute: dt.minute(),
                second: dt.second(),
                microsecond,
                timezone: None,
            });
        }
        if let Ok(d) = s.parse::<chrono::NaiveDate>() {
            return Ok(DateTimeValue {
                year: d.year(),
                month: d.month(),
                day: d.day(),
                hour: 0,
                minute: 0,
                second: 0,
                microsecond: 0,
                timezone: None,
            });
        }
        if let Some(week_val) = Self::parse_iso_week(s) {
            return Ok(week_val);
        }
        if let Ok(ym) = chrono::NaiveDate::parse_from_str(&format!("{}-01", s), "%Y-%m-%d") {
            return Ok(Self {
                year: ym.year(),
                month: ym.month(),
                day: 1,
                hour: 0,
                minute: 0,
                second: 0,
                microsecond: 0,
                timezone: None,
            });
        }
        if let Ok(year) = s.parse::<i32>() {
            if (1..=9999).contains(&year) {
                return Ok(Self {
                    year,
                    month: 1,
                    day: 1,
                    hour: 0,
                    minute: 0,
                    second: 0,
                    microsecond: 0,
                    timezone: None,
                });
            }
        }
        Err(format!("Invalid date format: '{}'", s))
    }
}

impl std::str::FromStr for TimeValue {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let trimmed = s.trim();

        let (time_text, timezone) = if trimmed.ends_with('Z') || trimmed.ends_with('z') {
            (
                &trimmed[..trimmed.len() - 1],
                Some(TimezoneValue {
                    offset_hours: 0,
                    offset_minutes: 0,
                }),
            )
        } else if trimmed.len() > 1 {
            if let Some(sign_index) = trimmed[1..].rfind(['+', '-']).map(|index| index + 1) {
                let timezone_text = &trimmed[sign_index..];
                if timezone_text.len() == 6
                    && (timezone_text.starts_with('+') || timezone_text.starts_with('-'))
                    && timezone_text.as_bytes()[3] == b':'
                {
                    let offset_hours: i8 = timezone_text[1..3]
                        .parse()
                        .map_err(|_| format!("Invalid time format: '{}'", s))?;
                    let offset_minutes: u8 = timezone_text[4..6]
                        .parse()
                        .map_err(|_| format!("Invalid time format: '{}'", s))?;
                    let signed_hours = if timezone_text.starts_with('-') {
                        -offset_hours
                    } else {
                        offset_hours
                    };
                    (
                        &trimmed[..sign_index],
                        Some(TimezoneValue {
                            offset_hours: signed_hours,
                            offset_minutes,
                        }),
                    )
                } else {
                    (trimmed, None)
                }
            } else {
                (trimmed, None)
            }
        } else {
            (trimmed, None)
        };

        if let Ok(t) = chrono::NaiveTime::parse_from_str(time_text, "%H:%M:%S%.f") {
            return Ok(TimeValue {
                hour: t.hour() as u8,
                minute: t.minute() as u8,
                second: t.second() as u8,
                microsecond: t.nanosecond() / 1000 % 1_000_000,
                timezone,
            });
        }
        if let Ok(t) = chrono::NaiveTime::parse_from_str(time_text, "%H:%M:%S") {
            return Ok(TimeValue {
                hour: t.hour() as u8,
                minute: t.minute() as u8,
                second: t.second() as u8,
                microsecond: 0,
                timezone,
            });
        }
        if let Ok(t) = chrono::NaiveTime::parse_from_str(time_text, "%H:%M") {
            return Ok(TimeValue {
                hour: t.hour() as u8,
                minute: t.minute() as u8,
                second: 0,
                microsecond: 0,
                timezone,
            });
        }
        Err(format!("Invalid time format: '{}'", s))
    }
}

/// Number literal with Lemma rules (strip _ and ,; MAX_NUMBER_DIGITS).
pub(crate) struct NumberLiteral(pub Decimal);

impl std::str::FromStr for NumberLiteral {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let clean = s.trim().replace(['_', ','], "");
        let digit_count = clean.chars().filter(|c| c.is_ascii_digit()).count();
        if digit_count > crate::limits::MAX_NUMBER_DIGITS {
            return Err(format!(
                "Number has too many digits (max {})",
                crate::limits::MAX_NUMBER_DIGITS
            ));
        }
        Decimal::from_str(&clean)
            .map_err(|_| format!("Invalid number: '{}'", s))
            .map(NumberLiteral)
    }
}

/// Text literal with length limit.
pub(crate) struct TextLiteral(pub String);

impl std::str::FromStr for TextLiteral {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s.len() > crate::limits::MAX_TEXT_VALUE_LENGTH {
            return Err(format!(
                "Text value exceeds maximum length (max {} characters)",
                crate::limits::MAX_TEXT_VALUE_LENGTH
            ));
        }
        Ok(TextLiteral(s.to_string()))
    }
}

/// Calendar magnitude: number + unit (e.g. "10 months").
pub(crate) struct CalendarLiteral(pub Decimal, pub CalendarUnit);

impl std::str::FromStr for CalendarLiteral {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let trimmed = s.trim();
        let mut parts: Vec<&str> = trimmed.split_whitespace().collect();
        if parts.len() < 2 {
            return Err(format!(
                "Invalid calendar value: '{}'. Expected format: <number> <unit> (e.g. 10 months, 2 years)",
                s
            ));
        }
        let unit_str = parts.pop().unwrap();
        let number_str = parts.join(" ");
        let n = number_str
            .parse::<NumberLiteral>()
            .map_err(|_| format!("Invalid calendar number: '{}'", number_str))?
            .0;
        let unit = unit_str.parse()?;
        Ok(CalendarLiteral(n, unit))
    }
}

/// Parsed `<number> <unit-name>` for runtime string input (quantity and ratio types).
pub(crate) struct NumberWithUnit(pub Decimal, pub String);

impl std::str::FromStr for NumberWithUnit {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let trimmed = s.trim();
        if trimmed.is_empty() {
            return Err(
                "Quantity value cannot be empty. Use a number followed by a unit (e.g. '10 eur')."
                    .to_string(),
            );
        }

        let mut parts = trimmed.split_whitespace();
        let number_part = parts
            .next()
            .expect("split_whitespace yields >=1 token after non-empty guard");
        let unit_part = parts.next().ok_or_else(|| {
            format!(
                "Quantity value must include a unit (e.g. '{} eur').",
                number_part
            )
        })?;
        if parts.next().is_some() {
            return Err(format!(
                "Invalid quantity value: '{}'. Expected exactly '<number> <unit>', got extra tokens.",
                s
            ));
        }
        let n = number_part
            .parse::<NumberLiteral>()
            .map_err(|_| format!("Invalid quantity: '{}'", s))?
            .0;
        Ok(NumberWithUnit(n, unit_part.to_string()))
    }
}

/// Strict ratio runtime literal.
///
/// Grammar (all inputs trimmed first):
/// - `<number>`                      → `Bare(n)`
/// - `<number>%`  (glued, no inner whitespace) → `Percent(n)` raw magnitude
/// - `<number>%%` (glued, no inner whitespace) → `Permille(n)` raw magnitude
/// - `<number> <unit-name>`          → `Named { value: n, unit: <unit-name> }`
///
/// `<number>` is parsed by [`NumberLiteral`] (signed, allows `_`/`,` separators).
/// Whitespace between the number and a keyword unit may be any non-empty run
/// (`"50 percent"`, `"50    percent"`, `"50\tpercent"` are all accepted).
///
/// The sigils `%` / `%%` are language-level constants meaning "divide by 100 / 1000"
/// and unconditionally produce the canonical unit names `"percent"` / `"permille"`.
/// They are NOT accepted as standalone unit-position tokens (i.e. `"5 %"` is rejected).
///
/// Signedness is intentionally not constrained at this layer: bounds are the
/// type-system's job (`-> minimum 0%`), and the evaluator can produce signed
/// ratios from non-negative inputs (e.g. `this_year - last_year` on `percent`).
/// The parser must accept everything the evaluator can emit (round-trip symmetry).
///
/// `Named` carries the raw unit name; the caller in `parse_number_unit::Ratio`
/// resolves it against the type's [`RatioUnits`] table (covering built-in
/// `percent`/`permille` and any user-defined units like `basis_points`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum RatioLiteral {
    Bare(Decimal),
    Percent(Decimal),
    Permille(Decimal),
    Named { value: Decimal, unit: String },
}

impl std::str::FromStr for RatioLiteral {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let trimmed = s.trim();
        if trimmed.is_empty() {
            return Err(
                "Ratio value cannot be empty. Use a number, optionally followed by '%', '%%', or a unit name (e.g. '0.5', '50%', '25%%', '50 percent')."
                    .to_string(),
            );
        }

        let mut parts = trimmed.split_whitespace();
        let first = parts
            .next()
            .expect("split_whitespace yields >=1 token after non-empty guard");
        let second = parts.next();
        if parts.next().is_some() {
            return Err(format!(
                "Invalid ratio value: '{}'. Expected '<number>', '<number>%', '<number>%%', or '<number> <unit>'.",
                s
            ));
        }

        match second {
            // 1-token forms: bare number, or sigil-suffixed number.
            None => {
                if let Some(rest) = first.strip_suffix("%%") {
                    if rest.is_empty() {
                        return Err(format!(
                            "Invalid ratio value: '{}'. '%%' must follow a number (e.g. '25%%').",
                            s
                        ));
                    }
                    let n = rest
                        .parse::<NumberLiteral>()
                        .map_err(|_| {
                            format!(
                            "Invalid ratio value: '{}'. '{}' is not a valid number before '%%'.",
                            s, rest
                        )
                        })?
                        .0;
                    return Ok(RatioLiteral::Permille(n));
                }
                if let Some(rest) = first.strip_suffix('%') {
                    if rest.is_empty() {
                        return Err(format!(
                            "Invalid ratio value: '{}'. '%' must follow a number (e.g. '50%').",
                            s
                        ));
                    }
                    let n = rest
                        .parse::<NumberLiteral>()
                        .map_err(|_| {
                            format!(
                                "Invalid ratio value: '{}'. '{}' is not a valid number before '%'.",
                                s, rest
                            )
                        })?
                        .0;
                    return Ok(RatioLiteral::Percent(n));
                }
                let n = first.parse::<NumberLiteral>().map_err(|_| {
                    format!(
                        "Invalid ratio value: '{}'. Must be a number, '<n>%', '<n>%%', '<n> percent', '<n> permille', or '<n> <unit>'.",
                        s
                    )
                })?.0;
                Ok(RatioLiteral::Bare(n))
            }
            // 2-token form: <number> <unit-name>. Sigils are not accepted as unit-position tokens.
            Some(unit) => {
                if unit == "%" || unit == "%%" {
                    return Err(format!(
                        "Invalid ratio value: '{}'. '{}' must be glued to the number (e.g. '{}{}'), not separated by whitespace.",
                        s, unit, first, unit
                    ));
                }
                let n = first
                    .parse::<NumberLiteral>()
                    .map_err(|_| {
                        format!(
                            "Invalid ratio value: '{}'. '{}' is not a valid number.",
                            s, first
                        )
                    })?
                    .0;
                Ok(RatioLiteral::Named {
                    value: n,
                    unit: unit.to_string(),
                })
            }
        }
    }
}