1use crate::computation::rational::RationalInteger;
4use crate::literals::{
5 BaseMeasureVector, DateTimeValue, MeasureUnit as DomainMeasureUnit, MeasureUnits,
6 RatioUnit as DomainRatioUnit, RatioUnits, TimeValue,
7};
8use crate::planning::semantics::{
9 Dimension, LemmaType as DomainLemmaType, MeasureTrait as DomainMeasureTrait,
10 TypeDefiningSpec as DomainTypeDefiningSpec, TypeExtends as DomainTypeExtends,
11 TypeSpecification as DomainTypeSpecification,
12};
13use rust_decimal::Decimal;
14use serde::{Deserialize, Serialize};
15use std::collections::BTreeMap;
16
17#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
19pub struct RationalFactor {
20 pub numer: String,
21 pub denom: String,
22}
23
24impl RationalFactor {
25 fn from_ratio(value: &RationalInteger) -> Self {
26 let reduced = value
27 .clone()
28 .try_reduce()
29 .expect("BUG: stored measure unit factor must reduce");
30 Self {
31 numer: reduced.numer_to_string(),
32 denom: reduced.denom_to_string(),
33 }
34 }
35}
36
37#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
39pub struct NamedBound {
40 pub value: Decimal,
41 pub unit: String,
42}
43
44fn planned_bound_decimal(rational: &RationalInteger) -> Decimal {
45 rational
46 .try_to_decimal()
47 .expect("BUG: planned bound must convert to decimal")
48}
49
50fn named_bound_from(bound: &(RationalInteger, String)) -> NamedBound {
51 NamedBound {
52 value: planned_bound_decimal(&bound.0),
53 unit: bound.1.clone(),
54 }
55}
56
57fn optional_named_bound(bound: &Option<(RationalInteger, String)>) -> Option<NamedBound> {
58 bound.as_ref().map(named_bound_from)
59}
60
61fn optional_decimal_bound(bound: &Option<RationalInteger>) -> Option<Decimal> {
62 bound.as_ref().map(planned_bound_decimal)
63}
64
65pub type Decomposition = BTreeMap<String, i32>;
69
70fn decomposition_from(domain: &BaseMeasureVector) -> Decomposition {
71 let mut converted = Decomposition::new();
72 for (dimension, exponent) in domain {
73 let key = match dimension {
74 Dimension::Family(family) => family.to_string(),
75 Dimension::Duration | Dimension::Calendar => dimension.name().to_string(),
76 };
77 if converted.insert(key.clone(), *exponent).is_some() {
78 panic!("BUG: distinct dimensions share API key '{key}'");
79 }
80 }
81 converted
82}
83
84fn optional_decomposition_from(domain: &Option<BaseMeasureVector>) -> Option<Decomposition> {
85 domain.as_ref().map(decomposition_from)
86}
87
88#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
89#[serde(rename_all = "snake_case")]
90pub enum MeasureTrait {
91 Duration,
92 Calendar,
93}
94
95impl From<DomainMeasureTrait> for MeasureTrait {
96 fn from(value: DomainMeasureTrait) -> Self {
97 match value {
98 DomainMeasureTrait::Duration => Self::Duration,
99 DomainMeasureTrait::Calendar => Self::Calendar,
100 }
101 }
102}
103
104#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
105pub struct MeasureUnit {
106 pub name: String,
107 #[serde(skip_serializing_if = "Option::is_none", default)]
110 pub factor: Option<RationalFactor>,
111 #[serde(default, skip_serializing_if = "Vec::is_empty")]
115 pub scale_factors: Vec<(String, i32)>,
116 pub derived_measure_factors: Vec<(String, i32)>,
117 pub decomposition: Decomposition,
118 #[serde(skip_serializing_if = "Option::is_none", default)]
119 pub minimum: Option<Decimal>,
120 #[serde(skip_serializing_if = "Option::is_none", default)]
121 pub maximum: Option<Decimal>,
122 #[serde(
123 rename = "suggestion",
124 skip_serializing_if = "Option::is_none",
125 default
126 )]
127 pub suggestion_magnitude: Option<Decimal>,
128}
129
130impl From<&DomainMeasureUnit> for MeasureUnit {
131 fn from(unit: &DomainMeasureUnit) -> Self {
132 let (factor, scale_factors, omit_bounds) = match &unit.scale {
133 crate::literals::UnitScale::Literal(factor) => {
134 (Some(RationalFactor::from_ratio(factor)), Vec::new(), false)
135 }
136 crate::literals::UnitScale::Unresolved { written, .. } => {
137 (None, vec![(written.clone(), 1)], true)
138 }
139 crate::literals::UnitScale::Compound { .. } => {
140 panic!(
141 "BUG: MeasureUnit wire for compound unit '{}' that type resolution never resolved",
142 unit.name
143 )
144 }
145 crate::literals::UnitScale::Reference {
146 factors,
147 coefficient,
148 } => {
149 if factors.is_empty() {
150 panic!(
151 "BUG: MeasureUnit wire for '{}' got empty Reference factors",
152 unit.name
153 );
154 }
155 let factor = if *coefficient == crate::computation::rational::rational_one() {
156 None
157 } else {
158 Some(RationalFactor::from_ratio(coefficient))
159 };
160 let scale_factors = factors
161 .iter()
162 .map(|(target, exponent)| (target.to_string(), *exponent))
163 .collect();
164 (factor, scale_factors, true)
165 }
166 };
167 Self {
168 name: unit.name.clone(),
169 factor,
170 scale_factors,
171 derived_measure_factors: unit.derived_measure_factors.clone(),
172 decomposition: decomposition_from(&unit.decomposition),
173 minimum: if omit_bounds {
174 None
175 } else {
176 unit.minimum.as_ref().map(|minimum| {
177 minimum
178 .try_to_decimal()
179 .expect("BUG: planned measure unit minimum must convert to decimal")
180 })
181 },
182 maximum: if omit_bounds {
183 None
184 } else {
185 unit.maximum.as_ref().map(|maximum| {
186 maximum
187 .try_to_decimal()
188 .expect("BUG: planned measure unit maximum must convert to decimal")
189 })
190 },
191 suggestion_magnitude: if omit_bounds {
192 None
193 } else {
194 unit.suggestion_magnitude.as_ref().map(|suggestion| {
195 suggestion
196 .try_to_decimal()
197 .expect("BUG: planned measure unit suggestion must convert to decimal")
198 })
199 },
200 }
201 }
202}
203
204#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
205pub struct RatioUnit {
206 pub name: String,
207 pub value: RationalFactor,
208 #[serde(skip_serializing_if = "Option::is_none", default)]
209 pub minimum: Option<Decimal>,
210 #[serde(skip_serializing_if = "Option::is_none", default)]
211 pub maximum: Option<Decimal>,
212 #[serde(
213 rename = "suggestion",
214 skip_serializing_if = "Option::is_none",
215 default
216 )]
217 pub suggestion_magnitude: Option<Decimal>,
218}
219
220impl From<&DomainRatioUnit> for RatioUnit {
221 fn from(unit: &DomainRatioUnit) -> Self {
222 Self {
223 name: unit.name.clone(),
224 value: RationalFactor::from_ratio(&unit.value),
225 minimum: unit.minimum.as_ref().map(|minimum| {
226 minimum
227 .try_to_decimal()
228 .expect("BUG: planned ratio unit minimum must convert to decimal")
229 }),
230 maximum: unit.maximum.as_ref().map(|maximum| {
231 maximum
232 .try_to_decimal()
233 .expect("BUG: planned ratio unit maximum must convert to decimal")
234 }),
235 suggestion_magnitude: unit.suggestion_magnitude.as_ref().map(|suggestion| {
236 suggestion
237 .try_to_decimal()
238 .expect("BUG: planned ratio unit suggestion must convert to decimal")
239 }),
240 }
241 }
242}
243
244fn measure_units_from(units: &MeasureUnits) -> Vec<MeasureUnit> {
245 units.iter().map(MeasureUnit::from).collect()
246}
247
248fn ratio_units_from(units: &RatioUnits) -> Vec<RatioUnit> {
249 units.iter().map(RatioUnit::from).collect()
250}
251
252#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
253#[serde(tag = "kind", rename_all = "snake_case")]
254pub enum TypeDefiningSpec {
255 Local,
256 Import,
257}
258
259impl From<&DomainTypeDefiningSpec> for TypeDefiningSpec {
260 fn from(value: &DomainTypeDefiningSpec) -> Self {
261 match value {
262 DomainTypeDefiningSpec::Local => Self::Local,
263 DomainTypeDefiningSpec::Import => Self::Import,
264 }
265 }
266}
267
268#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
269#[serde(tag = "kind", rename_all = "snake_case")]
270pub enum TypeExtends {
271 Primitive,
272 Custom {
273 parent: String,
274 family: String,
275 defining_spec: TypeDefiningSpec,
276 },
277}
278
279impl From<&DomainTypeExtends> for TypeExtends {
280 fn from(value: &DomainTypeExtends) -> Self {
281 match value {
282 DomainTypeExtends::Primitive => Self::Primitive,
283 DomainTypeExtends::Custom {
284 parent,
285 family,
286 defining_spec,
287 } => Self::Custom {
288 parent: parent.clone(),
289 family: family.to_string(),
290 defining_spec: TypeDefiningSpec::from(defining_spec),
291 },
292 }
293 }
294}
295
296#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
297#[serde(tag = "kind", rename_all = "snake_case")]
298pub enum TypeSpecification {
299 Boolean {
300 help: String,
301 },
302 Measure {
303 #[serde(default)]
304 minimum: Option<NamedBound>,
305 #[serde(default)]
306 maximum: Option<NamedBound>,
307 units: Vec<MeasureUnit>,
308 #[serde(default)]
309 traits: Vec<MeasureTrait>,
310 #[serde(default)]
311 decomposition: Option<Decomposition>,
312 #[serde(default, skip_serializing_if = "Option::is_none")]
313 unit: Option<String>,
314 help: String,
315 },
316 Number {
317 #[serde(default)]
318 minimum: Option<Decimal>,
319 #[serde(default)]
320 maximum: Option<Decimal>,
321 decimals: Option<u8>,
322 help: String,
323 },
324 NumberRange {
325 #[serde(default)]
326 lower: Option<Decimal>,
327 #[serde(default)]
328 upper: Option<Decimal>,
329 #[serde(default)]
330 minimum: Option<Decimal>,
331 #[serde(default)]
332 maximum: Option<Decimal>,
333 help: String,
334 },
335 Ratio {
336 #[serde(default)]
337 minimum: Option<Decimal>,
338 #[serde(default)]
339 maximum: Option<Decimal>,
340 units: Vec<RatioUnit>,
341 #[serde(default, skip_serializing_if = "Option::is_none")]
342 unit: Option<String>,
343 help: String,
344 },
345 RatioRange {
346 #[serde(default)]
347 lower: Option<Decimal>,
348 #[serde(default)]
349 upper: Option<Decimal>,
350 #[serde(default)]
351 minimum: Option<Decimal>,
352 #[serde(default)]
353 maximum: Option<Decimal>,
354 units: Vec<RatioUnit>,
355 help: String,
356 },
357 Text {
358 length: Option<usize>,
359 options: Vec<String>,
360 help: String,
361 },
362 Date {
363 minimum: Option<DateTimeValue>,
364 maximum: Option<DateTimeValue>,
365 help: String,
366 },
367 DateRange {
368 lower: Option<DateTimeValue>,
369 upper: Option<DateTimeValue>,
370 #[serde(default)]
371 minimum: Option<NamedBound>,
372 #[serde(default)]
373 maximum: Option<NamedBound>,
374 help: String,
375 },
376 Time {
377 minimum: Option<TimeValue>,
378 maximum: Option<TimeValue>,
379 help: String,
380 },
381 TimeRange {
382 lower: Option<TimeValue>,
383 upper: Option<TimeValue>,
384 #[serde(default)]
385 minimum: Option<NamedBound>,
386 #[serde(default)]
387 maximum: Option<NamedBound>,
388 help: String,
389 },
390 MeasureRange {
391 #[serde(default)]
392 lower: Option<NamedBound>,
393 #[serde(default)]
394 upper: Option<NamedBound>,
395 #[serde(default)]
396 minimum: Option<NamedBound>,
397 #[serde(default)]
398 maximum: Option<NamedBound>,
399 units: Vec<MeasureUnit>,
400 #[serde(default)]
401 decomposition: Option<Decomposition>,
402 help: String,
403 },
404 Veto {
405 message: Option<String>,
406 },
407 Undetermined,
408 Spec {
409 #[serde(default, skip_serializing_if = "Option::is_none")]
410 repository: Option<String>,
411 spec: String,
412 effective: String,
413 },
414 List {
415 element: Box<TypeSpecification>,
416 key: ListKey,
417 },
418}
419
420#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
422#[serde(rename_all = "snake_case")]
423pub enum ListKey {
424 Numbered,
425 Fields(Vec<String>),
426}
427
428impl From<&crate::planning::semantics::ListKey> for ListKey {
429 fn from(key: &crate::planning::semantics::ListKey) -> Self {
430 match key {
431 crate::planning::semantics::ListKey::Numbered => Self::Numbered,
432 crate::planning::semantics::ListKey::Fields(fields) => {
433 Self::Fields(fields.iter().map(|field| field.name.clone()).collect())
434 }
435 }
436 }
437}
438
439impl From<&DomainTypeSpecification> for TypeSpecification {
440 fn from(spec: &DomainTypeSpecification) -> Self {
441 let mut list_keys = Vec::new();
442 let mut leaf = spec;
443 while let DomainTypeSpecification::List { element, key, .. } = leaf {
444 list_keys.push(ListKey::from(key));
445 leaf = &element.specifications;
446 }
447 let mut converted = Self::non_list_from(leaf);
448 while let Some(key) = list_keys.pop() {
449 converted = Self::List {
450 element: Box::new(converted),
451 key,
452 };
453 }
454 converted
455 }
456}
457
458impl TypeSpecification {
459 fn non_list_from(spec: &DomainTypeSpecification) -> Self {
460 match spec {
461 DomainTypeSpecification::Boolean { help } => Self::Boolean { help: help.clone() },
462 DomainTypeSpecification::Measure {
463 minimum,
464 maximum,
465 units,
466 traits,
467 decomposition,
468 unit,
469 help,
470 } => Self::Measure {
471 minimum: optional_named_bound(minimum),
472 maximum: optional_named_bound(maximum),
473 units: measure_units_from(units),
474 traits: traits.iter().copied().map(MeasureTrait::from).collect(),
475 decomposition: optional_decomposition_from(decomposition),
476 unit: unit.clone(),
477 help: help.clone(),
478 },
479 DomainTypeSpecification::Number {
480 minimum,
481 maximum,
482 decimals,
483 help,
484 } => Self::Number {
485 minimum: optional_decimal_bound(minimum),
486 maximum: optional_decimal_bound(maximum),
487 decimals: *decimals,
488 help: help.clone(),
489 },
490 DomainTypeSpecification::NumberRange {
491 lower,
492 upper,
493 minimum,
494 maximum,
495 help,
496 } => Self::NumberRange {
497 lower: optional_decimal_bound(lower),
498 upper: optional_decimal_bound(upper),
499 minimum: optional_decimal_bound(minimum),
500 maximum: optional_decimal_bound(maximum),
501 help: help.clone(),
502 },
503 DomainTypeSpecification::Ratio {
504 minimum,
505 maximum,
506 units,
507 unit,
508 help,
509 } => Self::Ratio {
510 minimum: optional_decimal_bound(minimum),
511 maximum: optional_decimal_bound(maximum),
512 units: ratio_units_from(units),
513 unit: unit.clone(),
514 help: help.clone(),
515 },
516 DomainTypeSpecification::RatioRange {
517 lower,
518 upper,
519 minimum,
520 maximum,
521 units,
522 help,
523 } => Self::RatioRange {
524 lower: optional_decimal_bound(lower),
525 upper: optional_decimal_bound(upper),
526 minimum: optional_decimal_bound(minimum),
527 maximum: optional_decimal_bound(maximum),
528 units: ratio_units_from(units),
529 help: help.clone(),
530 },
531 DomainTypeSpecification::Text { length, help } => Self::Text {
532 length: *length,
533 options: Vec::new(),
534 help: help.clone(),
535 },
536 DomainTypeSpecification::Date {
537 minimum,
538 maximum,
539 help,
540 } => Self::Date {
541 minimum: minimum.clone(),
542 maximum: maximum.clone(),
543 help: help.clone(),
544 },
545 DomainTypeSpecification::DateRange {
546 lower,
547 upper,
548 minimum,
549 maximum,
550 help,
551 } => Self::DateRange {
552 lower: lower.clone(),
553 upper: upper.clone(),
554 minimum: optional_named_bound(minimum),
555 maximum: optional_named_bound(maximum),
556 help: help.clone(),
557 },
558 DomainTypeSpecification::Time {
559 minimum,
560 maximum,
561 help,
562 } => Self::Time {
563 minimum: minimum.clone(),
564 maximum: maximum.clone(),
565 help: help.clone(),
566 },
567 DomainTypeSpecification::TimeRange {
568 lower,
569 upper,
570 minimum,
571 maximum,
572 help,
573 } => Self::TimeRange {
574 lower: lower.clone(),
575 upper: upper.clone(),
576 minimum: optional_named_bound(minimum),
577 maximum: optional_named_bound(maximum),
578 help: help.clone(),
579 },
580 DomainTypeSpecification::MeasureRange {
581 lower,
582 upper,
583 minimum,
584 maximum,
585 units,
586 decomposition,
587 help,
588 } => Self::MeasureRange {
589 lower: optional_named_bound(lower),
590 upper: optional_named_bound(upper),
591 minimum: optional_named_bound(minimum),
592 maximum: optional_named_bound(maximum),
593 units: measure_units_from(units),
594 decomposition: optional_decomposition_from(decomposition),
595 help: help.clone(),
596 },
597 DomainTypeSpecification::Veto { message } => Self::Veto {
598 message: message.clone(),
599 },
600 DomainTypeSpecification::Undetermined => Self::Undetermined,
601 DomainTypeSpecification::Spec { spec } => Self::Spec {
602 repository: spec.repository.clone(),
603 spec: spec.spec.clone(),
604 effective: spec.effective.to_string(),
605 },
606 DomainTypeSpecification::List { .. } => {
607 unreachable!("BUG: list specifications are unwound by TypeSpecification::from")
608 }
609 }
610 }
611}
612
613#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
614pub struct LemmaType {
615 pub name: Option<String>,
616 #[serde(flatten)]
617 pub specifications: TypeSpecification,
618 pub extends: TypeExtends,
619}
620
621impl From<&DomainLemmaType> for LemmaType {
622 fn from(lemma_type: &DomainLemmaType) -> Self {
623 let mut specifications = TypeSpecification::from(&lemma_type.specifications);
624 if let TypeSpecification::Text { options, .. } = &mut specifications {
625 *options = lemma_type
626 .options_for_check()
627 .values
628 .iter()
629 .filter_map(|option| match &option.value.value {
630 crate::planning::semantics::ValueKind::Text(text) => Some(text.to_string()),
631 _ => None,
632 })
633 .collect();
634 }
635 Self {
636 name: lemma_type.name.clone(),
637 specifications,
638 extends: TypeExtends::from(&lemma_type.extends),
639 }
640 }
641}
642
643#[cfg(test)]
644mod tests {
645 use super::*;
646 use crate::planning::semantics::TypeFamily;
647 use serde_json::json;
648
649 fn family(repository: Option<&str>, spec: &str, name: &str) -> Dimension {
650 Dimension::Family(TypeFamily {
651 repository: repository.map(str::to_string),
652 spec: spec.to_string(),
653 effective: crate::parsing::ast::EffectiveDate::Origin,
654 name: name.to_string(),
655 })
656 }
657
658 #[test]
659 fn decomposition_keys_families_by_declaring_spec() {
660 let mut domain = BaseMeasureVector::new();
661 domain.insert(family(None, "pricing", "money"), 1);
662 domain.insert(family(Some("lemma"), "units", "mass"), -1);
663 domain.insert(Dimension::Duration, -1);
664 let json = serde_json::to_value(decomposition_from(&domain)).expect("JSON");
665 assert_eq!(
666 json,
667 json!({ "pricing.money": 1, "lemma units.mass": -1, "duration": -1 })
668 );
669 }
670
671 #[test]
672 fn decomposition_keeps_same_named_families_apart() {
673 let mut domain = BaseMeasureVector::new();
674 domain.insert(family(None, "a", "money"), 1);
675 domain.insert(family(None, "b", "money"), -1);
676 let json = serde_json::to_value(decomposition_from(&domain)).expect("JSON");
677 assert_eq!(json, json!({ "a.money": 1, "b.money": -1 }));
678 }
679
680 #[test]
681 fn decomposition_keeps_builtin_apart_from_same_named_family() {
682 let mut domain = BaseMeasureVector::new();
683 domain.insert(family(None, "clock", "duration"), 1);
684 domain.insert(Dimension::Duration, -1);
685 let json = serde_json::to_value(decomposition_from(&domain)).expect("JSON");
686 assert_eq!(json, json!({ "clock.duration": 1, "duration": -1 }));
687 }
688}