1use crate::computation::arithmetic::{SignatureFactor, SignatureIndex};
8use crate::computation::rational::{NumericFailure, RationalInteger};
9use crate::engine::Context;
10use crate::limits::MAX_UNIT_EXPONENT;
11use crate::literals::{MeasureUnit, MeasureUnits};
12use crate::parsing::ast::{
13 self as ast, CommandArg, Constraint, EffectiveDate, LemmaRepository, LemmaSpec, ParentType,
14 PrimitiveKind, TypeConstraintCommand, Value,
15};
16use crate::parsing::source::Source;
17use crate::planning::discovery;
18use crate::planning::execution_plan;
19use crate::planning::instance_list;
20use crate::planning::semantics::{
21 self, apply_list_with_rows, apply_option_constraint, apply_spec_member_command,
22 bound_value_kind_from_raw_suggestion, calendar_decomposition, calendar_unit_factor,
23 canonicalize_signature, duration_decomposition, value_kind_matches_spec, BaseMeasureVector,
24 BoundValueKind, ConstraintNames, DataPath, GlobalKey, LemmaType, ListKey, LiteralValue,
25 PathSegment, RawSuggestion, ReferenceTarget, RulePath, ScaleOwner, ScaleTarget, SpecIdentity,
26 SpecVersionKey, TypeDefiningSpec, TypeExtends, TypeFamily, TypeOptions, TypeSpecification,
27 TypedLiteral, UnitTokenResolver, ValueKind,
28};
29use crate::planning::unit_index::{
30 PlanningOwner, PlanningUnitIndex, UnitIndex, UnitMergeConflict, UnitOwner,
31};
32use crate::Error;
33use ast::DataValue as ParsedDataValue;
34use indexmap::IndexMap;
35use rust_decimal::Decimal;
36use std::cmp::Ordering;
37use std::collections::{BTreeSet, HashMap, HashSet, VecDeque};
38use std::fmt;
39use std::sync::Arc;
40
41pub(crate) type ResolvedTypesMap<'a> =
42 Vec<(Arc<LemmaRepository>, &'a LemmaSpec, Arc<ResolvedSpecTypes>)>;
43
44type ParentLookupOk = (
46 TypeSpecification,
47 Option<RawSuggestion>,
48 Option<RawSuggestion>,
49 Arc<LemmaType>,
50);
51
52type ResolvedTypeEntry = (Arc<LemmaType>, Option<RawSuggestion>, Option<RawSuggestion>);
54
55fn local_type_entries(resolved_types: &ResolvedSpecTypes) -> HashMap<String, ResolvedTypeEntry> {
56 resolved_types
57 .resolved
58 .iter()
59 .map(|(name, lemma_type)| {
60 (
61 name.clone(),
62 (
63 Arc::clone(lemma_type),
64 resolved_types.source_defaults.get(name).cloned(),
65 resolved_types.source_value_defaults.get(name).cloned(),
66 ),
67 )
68 })
69 .collect()
70}
71
72pub(crate) fn constraint_application_type_name(parent: &ParentType, data_name: &str) -> String {
74 let mut current = parent;
75 loop {
76 match current {
77 ParentType::Custom { name, .. } => return name.clone(),
78 ParentType::Qualified { inner, .. }
79 | ParentType::Ranged { inner, .. }
80 | ParentType::List { inner, .. } => current = inner.as_ref(),
81 ParentType::Primitive { .. } => return data_name.to_string(),
82 }
83 }
84}
85
86pub(crate) fn preserve_measure_binding(
89 schema_type: &Arc<LemmaType>,
90 previous: &LemmaType,
91) -> Arc<LemmaType> {
92 match previous.unit() {
93 Some(unit)
94 if matches!(
95 &schema_type.specifications,
96 TypeSpecification::Measure { .. } | TypeSpecification::Ratio { .. }
97 ) =>
98 {
99 Arc::new(schema_type.as_ref().clone().with_unit(unit))
100 }
101 Some(_) | None => Arc::clone(schema_type),
102 }
103}
104
105pub(crate) fn coerce_literal_to_schema_type(
106 lit: &TypedLiteral,
107 schema_type: &Arc<LemmaType>,
108) -> Result<TypedLiteral, String> {
109 fn range_endpoint_schema_type(schema_type: &LemmaType) -> Option<Arc<LemmaType>> {
110 schema_type
111 .specifications
112 .element_from_range()
113 .map(|element_spec| Arc::new(LemmaType::primitive(element_spec)))
114 }
115
116 let schema_ref = schema_type.as_ref();
117 match (&schema_ref.specifications, &lit.value) {
118 (
119 TypeSpecification::NumberRange { .. }
120 | TypeSpecification::DateRange { .. }
121 | TypeSpecification::TimeRange { .. }
122 | TypeSpecification::RatioRange { .. }
123 | TypeSpecification::MeasureRange { .. },
124 ValueKind::Range(left, right),
125 ) if !lit
126 .lemma_type
127 .specifications
128 .equal_ignoring_unit(&schema_ref.specifications) =>
129 {
130 let endpoint_schema_type =
131 range_endpoint_schema_type(schema_ref).unwrap_or_else(|| {
132 unreachable!("BUG: range_endpoint_schema_type missing range schema arm")
133 });
134 let left_schema =
135 preserve_measure_binding(&endpoint_schema_type, left.lemma_type.as_ref());
136 let right_schema =
137 preserve_measure_binding(&endpoint_schema_type, right.lemma_type.as_ref());
138 let coerced_left = coerce_scalar_literal(left, &left_schema)?;
139 let coerced_right = coerce_scalar_literal(right, &right_schema)?;
140 Ok(TypedLiteral {
141 value: ValueKind::Range(Box::new(coerced_left), Box::new(coerced_right)),
142 lemma_type: Arc::clone(schema_type),
143 })
144 }
145 _ => coerce_scalar_literal(lit, schema_type),
146 }
147}
148
149pub(crate) fn coerce_scalar_literal(
152 lit: &TypedLiteral,
153 schema_type: &Arc<LemmaType>,
154) -> Result<TypedLiteral, String> {
155 let schema_ref = schema_type.as_ref();
156 if lit
157 .lemma_type
158 .specifications
159 .equal_ignoring_unit(&schema_ref.specifications)
160 {
161 if !value_kind_matches_spec(&lit.value, &schema_ref.specifications) {
162 panic!(
163 "BUG: LiteralValue value kind {:?} inconsistent with lemma_type {:?}",
164 lit.value, lit.lemma_type.specifications
165 );
166 }
167 let mut out = lit.clone();
168 out.lemma_type = preserve_measure_binding(schema_type, &lit.lemma_type);
169 return Ok(out);
170 }
171 match (&schema_ref.specifications, &lit.value) {
172 (TypeSpecification::Number { .. }, ValueKind::Number(_))
173 | (TypeSpecification::Text { .. }, ValueKind::Text(_))
174 | (TypeSpecification::Boolean { .. }, ValueKind::Boolean(_))
175 | (TypeSpecification::Date { .. }, ValueKind::Date(_))
176 | (TypeSpecification::Time { .. }, ValueKind::Time(_)) => {
177 let mut out = lit.clone();
178 out.lemma_type = Arc::clone(schema_type);
179 Ok(out)
180 }
181 (TypeSpecification::Measure { .. }, ValueKind::Measure(_)) => {
182 if !lit.lemma_type.same_measure_family(schema_ref)
183 && !lit.lemma_type.compatible_with_anonymous_measure(schema_ref)
184 && !lit
185 .lemma_type
186 .specifications
187 .equal_ignoring_unit(&schema_ref.specifications)
188 {
189 return Err(format!(
190 "value {} cannot be used as type {}: incompatible measure families",
191 lit,
192 schema_ref.name()
193 ));
194 }
195 let mut out = lit.clone();
196 out.lemma_type = preserve_measure_binding(schema_type, &lit.lemma_type);
197 Ok(out)
198 }
199 (TypeSpecification::Ratio { .. }, ValueKind::Ratio(_)) => {
200 let mut out = lit.clone();
201 out.lemma_type = preserve_measure_binding(schema_type, &lit.lemma_type);
202 Ok(out)
203 }
204 _ => Err(format!(
205 "value {} cannot be used as type {}",
206 lit,
207 schema_ref.name()
208 )),
209 }
210}
211
212fn should_defer_ranged_constraints(parent: &ParentType) -> bool {
216 matches!(parent, ParentType::Ranged { .. })
217 && matches!(
218 element_parent_type(parent),
219 ParentType::Custom { .. } | ParentType::Qualified { .. }
220 )
221}
222
223fn derives_from_local_named_range(
226 parent: &ParentType,
227 data_defs: &HashMap<String, DataTypeDef>,
228) -> bool {
229 let mut current = parent;
230 loop {
231 if should_defer_ranged_constraints(current) {
232 return true;
233 }
234 let ParentType::Custom { name } = current else {
235 return false;
236 };
237 let Some(def) = data_defs.get(name) else {
238 return false;
239 };
240 current = &def.parent;
241 }
242}
243
244pub(crate) struct ConstraintSuggestionSink<'a> {
249 pub(crate) suggestion: &'a mut Option<RawSuggestion>,
250 pub(crate) value: &'a mut Option<RawSuggestion>,
251 pub(crate) resolve_unit: Option<&'a UnitTokenResolver<'a>>,
252}
253
254pub(crate) fn apply_constraints_to_spec(
255 spec: &LemmaSpec,
256 type_name: &str,
257 data_name: &str,
258 lemma_type: &mut LemmaType,
259 constraints: &[Constraint],
260 source: &Source,
261 sink: ConstraintSuggestionSink<'_>,
262) -> Result<(), Vec<Error>> {
263 let mut errors = Vec::new();
264
265 let mut seen_unit_names: std::collections::HashSet<String> = Default::default();
266 let mut seen_singleton_commands: std::collections::HashSet<TypeConstraintCommand> =
267 Default::default();
268 let mut has_suggest = false;
269 let mut has_value = false;
270 for row in constraints.iter() {
271 let command = row.command;
272 let args = &row.args;
273 if command == TypeConstraintCommand::Suggest {
274 has_suggest = true;
275 }
276 if command == TypeConstraintCommand::With {
277 has_value = true;
278 }
279 if command == TypeConstraintCommand::Unit {
280 if let Some(CommandArg::Label(name)) = args.first() {
281 if !seen_unit_names.insert(name.clone()) {
282 errors.push(Error::validation_with_context(
283 format!(
284 "Duplicate unit '{}': each unit name may appear at most once per type definition",
285 name
286 ),
287 Some(source.clone()),
288 None::<String>,
289 Some(spec),
290 None,
291 ));
292 }
293 }
294 }
295 if matches!(
296 command,
297 TypeConstraintCommand::Minimum
298 | TypeConstraintCommand::Maximum
299 | TypeConstraintCommand::Decimals
300 | TypeConstraintCommand::Suggest
301 | TypeConstraintCommand::With
302 ) && !(command == TypeConstraintCommand::With
303 && matches!(lemma_type.specifications, TypeSpecification::List { .. }))
304 && !seen_singleton_commands.insert(command)
305 {
306 errors.push(Error::validation_with_context(
307 format!(
308 "Duplicate '{command}' constraint: each may appear at most once per type declaration"
309 ),
310 Some(source.clone()),
311 None::<String>,
312 Some(spec),
313 None,
314 ));
315 }
316 }
317 if has_suggest && has_value {
318 errors.push(Error::validation_with_context(
319 "Cannot use both 'with' and 'suggest' on the same data declaration".to_string(),
320 Some(source.clone()),
321 None::<String>,
322 Some(spec),
323 None,
324 ));
325 }
326 if !errors.is_empty() {
327 return Err(errors);
328 }
329
330 let ConstraintSuggestionSink {
331 suggestion: declared_suggestion,
332 value: declared_value,
333 resolve_unit,
334 } = sink;
335 let names = ConstraintNames {
336 type_name,
337 data_name,
338 };
339
340 let mut apply_one = |lemma_type: &mut LemmaType,
341 command: TypeConstraintCommand,
342 args: &[CommandArg],
343 declared_suggestion: &mut Option<RawSuggestion>,
344 declared_value: &mut Option<RawSuggestion>| {
345 let mut suggestion_before = declared_suggestion.clone();
346 let mut value_before = declared_value.clone();
347 let applied = if matches!(
348 command,
349 TypeConstraintCommand::Option | TypeConstraintCommand::Options
350 ) {
351 apply_option_constraint(lemma_type, command, args, resolve_unit, spec)
352 } else if matches!(
353 command,
354 TypeConstraintCommand::Suggest | TypeConstraintCommand::With
355 ) && matches!(lemma_type.specifications, TypeSpecification::Spec { .. })
356 {
357 let target = match command {
358 TypeConstraintCommand::Suggest => &mut suggestion_before,
359 TypeConstraintCommand::With => &mut value_before,
360 _ => unreachable!("BUG: only Suggest or With in this arm"),
361 };
362 apply_spec_member_command(lemma_type, command, args, spec, target)
363 } else if matches!(lemma_type.specifications, TypeSpecification::List { .. })
364 && command == TypeConstraintCommand::With
365 {
366 apply_list_with_rows(
367 lemma_type,
368 names,
369 args,
370 &mut value_before,
371 resolve_unit,
372 spec,
373 )
374 } else {
375 lemma_type.apply_constraint(
376 names,
377 command,
378 args,
379 &mut suggestion_before,
380 &mut value_before,
381 resolve_unit,
382 )
383 };
384 match applied {
385 Ok(()) => {
386 *declared_suggestion = suggestion_before;
387 *declared_value = value_before;
388 }
389 Err(e) => {
390 errors.push(Error::validation_with_context(
391 format!("Failed to apply constraint '{}': {}", command, e),
392 Some(source.clone()),
393 None::<String>,
394 Some(spec),
395 None,
396 ));
397 }
398 }
399 };
400
401 for row in constraints {
402 let command = row.command;
403 let args = &row.args;
404 if matches!(
405 command,
406 TypeConstraintCommand::Unit | TypeConstraintCommand::Trait
407 ) {
408 apply_one(
409 lemma_type,
410 command,
411 args,
412 declared_suggestion,
413 declared_value,
414 );
415 }
416 }
417 for row in constraints {
418 let command = row.command;
419 let args = &row.args;
420 if !matches!(
421 command,
422 TypeConstraintCommand::Unit | TypeConstraintCommand::Trait
423 ) {
424 apply_one(
425 lemma_type,
426 command,
427 args,
428 declared_suggestion,
429 declared_value,
430 );
431 }
432 }
433 if !errors.is_empty() {
434 return Err(errors);
435 }
436 Ok(())
437}
438
439type UnitDecompLookup = HashMap<String, (Option<String>, BaseMeasureVector, RationalInteger)>;
440
441fn local_owner_name(owner: &PlanningOwner) -> Option<String> {
442 match owner {
443 PlanningOwner::Local { type_name } => Some(type_name.clone()),
444 PlanningOwner::PrimitiveRatio | PlanningOwner::Imported { .. } => None,
445 }
446}
447
448fn unwrap_unique_resolved_type(arc: Arc<LemmaType>) -> LemmaType {
449 Arc::try_unwrap(arc).expect("BUG: resolved LemmaType Arc unique during type resolution")
450}
451
452fn declared_measure_decomposition(lemma_type: &LemmaType) -> BaseMeasureVector {
453 match &lemma_type.specifications {
454 TypeSpecification::Measure { traits, .. }
455 if traits.contains(&semantics::MeasureTrait::Duration) =>
456 {
457 duration_decomposition()
458 }
459 TypeSpecification::Measure { traits, .. }
460 if traits.contains(&semantics::MeasureTrait::Calendar) =>
461 {
462 calendar_decomposition()
463 }
464 _ => {
465 let family = lemma_type
466 .measure_family()
467 .expect("BUG: named measure type must carry a family");
468 [(semantics::Dimension::Family(family.clone()), 1i32)]
469 .into_iter()
470 .collect()
471 }
472 }
473}
474
475fn local_owning_measure_type_for_unit(
477 unit_name: &str,
478 lookup: &UnitDecompLookup,
479 unit_index: &PlanningUnitIndex,
480 resolved: &IndexMap<String, Arc<LemmaType>>,
481) -> Option<String> {
482 if let Some((owning_measure_name, _, _)) = lookup.get(unit_name) {
483 return owning_measure_name.clone();
484 }
485 unit_index
486 .resolve_owner(unit_name, resolved)
487 .ok()
488 .and_then(|(_, owner)| local_owner_name(owner))
489}
490
491fn sort_derived_measure_types_for_resolution(
493 spec_name: &str,
494 derived_measure_type_names: Vec<String>,
495 resolved: &IndexMap<String, Arc<LemmaType>>,
496 lookup: &UnitDecompLookup,
497 unit_index: &PlanningUnitIndex,
498 type_sources: &HashMap<String, Source>,
499) -> Result<Vec<String>, Error> {
500 let derived_measure_type_count = derived_measure_type_names.len();
501 if derived_measure_type_count == 0 {
502 return Ok(derived_measure_type_names);
503 }
504
505 let type_index: HashMap<&str, usize> = derived_measure_type_names
506 .iter()
507 .enumerate()
508 .map(|(index, name)| (name.as_str(), index))
509 .collect();
510
511 let mut dependency_sets: Vec<BTreeSet<usize>> =
512 vec![BTreeSet::new(); derived_measure_type_count];
513
514 for (dependent_index, type_name) in derived_measure_type_names.iter().enumerate() {
515 let TypeSpecification::Measure { units, .. } = &resolved[type_name].specifications else {
516 continue;
517 };
518 for unit in units.iter() {
519 for (factor_unit_name, _) in &unit.derived_measure_factors {
520 let Some(owning_measure_name) = local_owning_measure_type_for_unit(
521 factor_unit_name,
522 lookup,
523 unit_index,
524 resolved,
525 ) else {
526 continue;
527 };
528 let Some(dependency_index) = type_index.get(owning_measure_name.as_str()).copied()
529 else {
530 continue;
531 };
532 if dependency_index == dependent_index {
533 continue;
534 }
535 dependency_sets[dependent_index].insert(dependency_index);
536 }
537 }
538 }
539
540 let mut in_degree = vec![0usize; derived_measure_type_count];
541 let mut dependents: Vec<Vec<usize>> = vec![Vec::new(); derived_measure_type_count];
542
543 for (dependent_index, dependencies) in dependency_sets.iter().enumerate() {
544 for &dependency_index in dependencies {
545 in_degree[dependent_index] += 1;
546 dependents[dependency_index].push(dependent_index);
547 }
548 }
549
550 let mut queue: VecDeque<usize> = (0..derived_measure_type_count)
551 .filter(|&index| in_degree[index] == 0)
552 .collect();
553 let mut sorted_indices: Vec<usize> = Vec::with_capacity(derived_measure_type_count);
554
555 while let Some(index) = queue.pop_front() {
556 sorted_indices.push(index);
557 for &dependent_index in &dependents[index] {
558 in_degree[dependent_index] -= 1;
559 if in_degree[dependent_index] == 0 {
560 queue.push_back(dependent_index);
561 }
562 }
563 }
564
565 if sorted_indices.len() != derived_measure_type_count {
566 let mut cycle_type_names: Vec<String> = (0..derived_measure_type_count)
567 .filter(|&index| in_degree[index] > 0)
568 .map(|index| derived_measure_type_names[index].clone())
569 .collect();
570 cycle_type_names.sort();
571 return Err(Error::validation(
572 format!(
573 "In spec '{}': circular compound measure type dependency among: {}",
574 spec_name,
575 cycle_type_names.join(", ")
576 ),
577 type_sources.get(&cycle_type_names[0]).cloned(),
578 None::<String>,
579 ));
580 }
581
582 Ok(sorted_indices
583 .into_iter()
584 .map(|index| derived_measure_type_names[index].clone())
585 .collect())
586}
587
588pub(crate) struct SignatureIndexBuild {
594 pub index: SignatureIndex,
595 pub deferred_cross_type: Vec<(String, BaseMeasureVector)>,
596}
597
598pub(crate) fn build_signature_index(
599 spec_name: &str,
600 unit_index: &UnitIndex,
601 already_resolved: &ResolvedTypesMap<'_>,
602) -> Result<SignatureIndexBuild, Error> {
603 use crate::computation::arithmetic::SignatureIndex;
604 let mut signature_index: SignatureIndex = SignatureIndex::new();
605 let mut deferred_cross_type = Vec::new();
606 let mut sorted_units: Vec<_> = unit_index.iter_owners().collect();
607 sorted_units.sort_by_key(|(name, _)| *name);
608 for (unit_name, owner) in sorted_units {
609 let unit_name = unit_name.to_string();
610 let lemma_type = owner.lemma_type();
611 let TypeSpecification::Measure { units, .. } = &lemma_type.specifications else {
612 continue;
613 };
614 let unit = units.get(unit_name.as_str()).map_err(|_| {
615 Error::validation(
616 format!(
617 "In spec '{}': unit_index entry '{}' is not declared on measure type '{}'",
618 spec_name,
619 unit_name,
620 lemma_type.name()
621 ),
622 None::<Source>,
623 None::<String>,
624 )
625 })?;
626 if lemma_type.measure_type_decomposition().is_none() {
627 continue;
628 }
629 if measure_unit_is_simple(unit) && unit_index.owners_for(&unit_name).len() != 1 {
633 continue;
634 }
635 let owning_type_name = lemma_type.name();
636 let signature = if owner.import_path().is_empty() {
637 resolved_signature_key(
638 &unit.derived_measure_factors,
639 &unit_name,
640 lemma_type,
641 unit_index,
642 )
643 } else if let Some(key) = imported_signature_key(already_resolved, &unit_name, lemma_type) {
644 key
645 } else if measure_unit_is_simple(unit) {
646 resolved_signature_key(
649 &unit.derived_measure_factors,
650 &unit_name,
651 lemma_type,
652 unit_index,
653 )
654 } else {
655 continue;
658 };
659 match signature_index.get(&signature) {
660 Some((existing_unit_name, existing_owning_type))
661 if existing_owning_type.name() != lemma_type.name() =>
662 {
663 let existing_type_name = existing_owning_type.name();
664 let decomposition = lemma_type
665 .measure_type_decomposition()
666 .expect("BUG: indexed measure unit has no decomposition")
667 .clone();
668 deferred_cross_type.push((
669 format!(
670 "In spec '{spec_name}': ambiguous unit signature {signature:?}: matched by '{existing_unit_name}' in type '{existing_type_name}' and '{unit_name}' in type '{owning_type_name}'. \
671 Rename one or differentiate factors."
672 ),
673 decomposition,
674 ));
675 }
676 _ => {
677 signature_index.insert(signature, (unit_name.clone(), Arc::clone(lemma_type)));
678 }
679 }
680 }
681 Ok(SignatureIndexBuild {
682 index: signature_index,
683 deferred_cross_type,
684 })
685}
686
687fn resolved_signature_key(
688 factors: &[(String, i32)],
689 unit_name: &str,
690 lemma_type: &LemmaType,
691 unit_index: &UnitIndex,
692) -> Vec<SignatureFactor> {
693 use crate::computation::arithmetic::SignatureFactor;
694 let mut key = Vec::with_capacity(factors.len());
695 for (factor_name, exponent) in factors {
696 let (name, family) = if factor_name == unit_name {
697 (
698 factor_name.clone(),
699 lemma_type
700 .measure_family()
701 .expect("BUG: indexed measure unit has no family")
702 .clone(),
703 )
704 } else {
705 let (bare, owner) = unit_index.resolve_owner(factor_name).unwrap_or_else(|err| {
706 panic!(
707 "BUG: compound factor '{factor_name}' on unit '{unit_name}' must resolve: {err}"
708 )
709 });
710 (
711 bare,
712 owner
713 .lemma_type()
714 .measure_family()
715 .expect("BUG: resolved factor owner is not a named measure")
716 .clone(),
717 )
718 };
719 key.push(SignatureFactor {
720 name,
721 family,
722 exponent: *exponent,
723 });
724 }
725 key.sort_by(|left, right| {
726 (&left.family, left.name.as_str(), left.exponent).cmp(&(
727 &right.family,
728 right.name.as_str(),
729 right.exponent,
730 ))
731 });
732 key
733}
734
735fn imported_signature_key(
738 already_resolved: &ResolvedTypesMap<'_>,
739 unit_name: &str,
740 lemma_type: &Arc<LemmaType>,
741) -> Option<Vec<SignatureFactor>> {
742 for (_, _, types) in already_resolved {
743 for (key, (name, owner)) in &types.signature_index {
744 if name == unit_name && Arc::ptr_eq(owner, lemma_type) {
745 return Some(key.clone());
746 }
747 }
748 }
749 None
750}
751
752pub(crate) fn deferred_signature_errors(
753 main_spec: &LemmaSpec,
754 resolved_types: &ResolvedTypesMap,
755 inferred: &HashMap<RulePath, Arc<LemmaType>>,
756) -> Vec<Error> {
757 let Some(types) = resolved_types
758 .iter()
759 .find_map(|(_, spec, types)| discovery::same_loaded_spec(spec, main_spec).then_some(types))
760 else {
761 return Vec::new();
762 };
763 let mut errors = Vec::new();
764 for (message, decomposition) in &types.deferred_signature_collisions {
765 let produced = inferred.values().any(|lemma_type| {
766 lemma_type.is_anonymous_measure()
767 && lemma_type.measure_type_decomposition() == Some(decomposition)
768 });
769 if produced {
770 continue;
771 }
772 errors.push(Error::validation(
773 message.clone(),
774 None::<Source>,
775 None::<String>,
776 ));
777 }
778 errors
779}
780
781fn refresh_named_range_specs(
786 resolver: &TypeResolver<'_>,
787 spec: &LemmaSpec,
788 data_defs: &HashMap<String, DataTypeDef>,
789 resolved_types: &mut ResolvedSpecTypes,
790 already_resolved: &ResolvedTypesMap<'_>,
791 at: &EffectiveDate,
792) -> Vec<Error> {
793 let local = local_type_entries(resolved_types);
794 let (scalar_names, _) = partition_list_type_names(data_defs);
795 let ordered = topo_sort_type_names(spec, data_defs, scalar_names)
796 .expect("BUG: type resolution rejects circular types before their ranges are finalized");
797 let mut endpoint_types: HashMap<&str, Arc<LemmaType>> = HashMap::new();
799 let mut errors = Vec::new();
800 for type_name in &ordered {
801 let def = &data_defs[type_name];
802 if !derives_from_local_named_range(&def.parent, data_defs) {
803 continue;
804 }
805 let (range_spec, endpoint_type, inherited_suggestion, inherited_value) =
806 if should_defer_ranged_constraints(&def.parent) {
807 let scope = ParentLookup {
808 resolver,
809 spec,
810 source: &def.source,
811 at,
812 already_resolved,
813 resolved: &local,
814 site: TypeUseSite::DataDefinition,
815 };
816 let element = element_parent_type(&def.parent);
817 let endpoint_type = match lookup_parent_type(&scope, element) {
818 Ok((.., endpoint_type)) => endpoint_type,
819 Err(lookup_errors) => {
820 errors.extend(lookup_errors);
821 continue;
822 }
823 };
824 let range_spec = endpoint_type
825 .specifications
826 .range_from_element()
827 .expect("BUG: ranged element was checked rangeable when the type was resolved");
828 (range_spec, endpoint_type, None, None)
829 } else {
830 let ParentType::Custom { name: parent } = &def.parent else {
831 unreachable!("BUG: a type derived from a local named range names its parent");
832 };
833 let Some(endpoint_type) = endpoint_types.get(parent.as_str()).cloned() else {
835 continue;
836 };
837 (
838 resolved_types.resolved[parent.as_str()]
839 .specifications
840 .clone(),
841 endpoint_type,
842 resolved_types.source_defaults.get(parent).cloned(),
843 resolved_types.source_value_defaults.get(parent).cloned(),
844 )
845 };
846 let lemma_type = resolved_types
847 .resolved
848 .get(type_name.as_str())
849 .expect("BUG: ranged type resolved before its range spec is refreshed");
850 let mut updated = lemma_type.as_ref().clone();
851 updated.specifications = range_spec;
852
853 if let Some(BoundValueKind {
854 value: ValueKind::Range(left, right),
855 ..
856 }) = resolved_types
857 .declared_suggestions
858 .get_mut(type_name.as_str())
859 {
860 let mut coerced = Vec::with_capacity(2);
861 for (side, endpoint) in [("left", left.as_ref()), ("right", right.as_ref())] {
862 match coerce_literal_to_schema_type(endpoint, &endpoint_type) {
863 Ok(value) => coerced.push(Box::new(value)),
864 Err(message) => errors.push(Error::validation_with_context(
865 format!(
866 "In spec '{}': named range default {side} endpoint for '{type_name}': {message}",
867 spec.name
868 ),
869 Some(def.source.clone()),
870 None::<String>,
871 Some(spec),
872 None,
873 )),
874 }
875 }
876 let Ok([coerced_left, coerced_right]) = <[_; 2]>::try_from(coerced) else {
877 continue;
878 };
879 *left = coerced_left;
880 *right = coerced_right;
881 }
882
883 let mut suggestion: Option<RawSuggestion> = inherited_suggestion;
884 let mut value: Option<RawSuggestion> = inherited_value;
885 if let Some(constraints) = &def.constraints {
886 let resolve = UnitTokenResolver::Planning {
887 unit_index: &resolved_types.planning_unit_index,
888 named_types: &resolved_types.resolved,
889 };
890 if let Err(constraint_errors) = apply_constraints_to_spec(
891 spec,
892 &constraint_application_type_name(&def.parent, type_name),
893 type_name,
894 &mut updated,
895 constraints,
896 &def.source,
897 ConstraintSuggestionSink {
898 suggestion: &mut suggestion,
899 value: &mut value,
900 resolve_unit: Some(&resolve),
901 },
902 ) {
903 errors.extend(constraint_errors);
904 continue;
905 }
906 }
907 for (raw, declared, source_raws) in [
908 (
909 suggestion,
910 &mut resolved_types.declared_suggestions,
911 &mut resolved_types.source_defaults,
912 ),
913 (
914 value,
915 &mut resolved_types.declared_values,
916 &mut resolved_types.source_value_defaults,
917 ),
918 ] {
919 let Some(raw) = raw else {
920 continue;
921 };
922 source_raws.insert(type_name.clone(), raw.clone());
924 match bound_value_kind_from_raw_suggestion(raw, &updated.specifications, type_name) {
925 Ok(value_kind) => {
926 declared.insert(type_name.clone(), value_kind);
927 }
928 Err(message) => errors.push(Error::validation_with_context(
929 message,
930 Some(def.source.clone()),
931 None::<String>,
932 Some(spec),
933 None,
934 )),
935 }
936 }
937 resolved_types
938 .resolved
939 .insert(type_name.clone(), Arc::new(updated));
940 endpoint_types.insert(type_name.as_str(), endpoint_type);
941 }
942 errors
943}
944
945#[derive(Clone, Copy)]
947enum TypeUseSite {
948 DataDefinition,
949 RuleListType,
950}
951
952impl fmt::Display for TypeUseSite {
953 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
954 match self {
955 TypeUseSite::DataDefinition => write!(f, "data definition"),
956 TypeUseSite::RuleListType => write!(f, "list type in a rule"),
957 }
958 }
959}
960
961#[derive(Clone, Copy)]
964struct ParentLookup<'s, 'a> {
965 resolver: &'s TypeResolver<'a>,
966 spec: &'s LemmaSpec,
967 source: &'s Source,
968 at: &'s EffectiveDate,
969 already_resolved: &'s ResolvedTypesMap<'a>,
970 resolved: &'s HashMap<String, ResolvedTypeEntry>,
971 site: TypeUseSite,
972}
973
974fn lookup_parent_type(
975 scope: &ParentLookup<'_, '_>,
976 parent: &ParentType,
977) -> Result<ParentLookupOk, Vec<Error>> {
978 let mut wrappers = Vec::new();
979 let mut leaf = parent;
980 while let ParentType::List { inner } | ParentType::Ranged { inner } = leaf {
981 wrappers.push(leaf);
982 leaf = inner.as_ref();
983 }
984 let mut lookup = lookup_leaf_parent_type(scope, leaf)?;
985 while let Some(wrapper) = wrappers.pop() {
986 lookup = lookup_wrapper_parent_type(scope, wrapper, lookup)?;
987 }
988 Ok(lookup)
989}
990
991fn lookup_wrapper_parent_type(
993 scope: &ParentLookup<'_, '_>,
994 wrapper: &ParentType,
995 inner_lookup: ParentLookupOk,
996) -> Result<ParentLookupOk, Vec<Error>> {
997 let ParentLookup { spec, source, .. } = *scope;
998 let (element_specs, .., element_type) = inner_lookup;
999 match wrapper {
1000 ParentType::List { inner } => {
1001 let element = if matches!(inner.as_ref(), ParentType::Ranged { .. }) {
1002 Arc::new(LemmaType {
1004 specifications: element_specs,
1005 ..element_type.as_ref().clone()
1006 })
1007 } else {
1008 element_type
1009 };
1010 let lemma_type = Arc::new(LemmaType::list_of(element));
1011 Ok((lemma_type.specifications.clone(), None, None, lemma_type))
1012 }
1013 ParentType::Ranged { inner } => {
1014 let range_spec = element_specs.range_from_element().ok_or_else(|| {
1015 vec![Error::validation_with_context(
1016 format!(
1017 "'{inner}' is not rangeable: only measure, number, ratio, date, and time types support ranges"
1018 ),
1019 Some(source.clone()),
1020 None::<String>,
1021 Some(spec),
1022 None,
1023 )]
1024 })?;
1025 Ok((range_spec, None, None, element_type))
1026 }
1027 ParentType::Primitive { .. } | ParentType::Custom { .. } | ParentType::Qualified { .. } => {
1028 unreachable!("BUG: lookup_wrapper_parent_type called on a leaf parent")
1029 }
1030 }
1031}
1032
1033fn lookup_leaf_parent_type(
1035 scope: &ParentLookup<'_, '_>,
1036 parent: &ParentType,
1037) -> Result<ParentLookupOk, Vec<Error>> {
1038 let ParentLookup {
1039 resolver,
1040 spec,
1041 source,
1042 at,
1043 already_resolved,
1044 resolved,
1045 site,
1046 } = *scope;
1047 match parent {
1048 ParentType::List { .. } | ParentType::Ranged { .. } => {
1049 unreachable!("BUG: list and range wrappers are unwound before the leaf lookup")
1050 }
1051 ParentType::Primitive { primitive: kind } => {
1052 let lemma_type = Arc::clone(semantics::lemma_type_for_primitive(*kind));
1053 Ok((
1054 lemma_type.as_ref().specifications.clone(),
1055 None,
1056 None,
1057 lemma_type,
1058 ))
1059 }
1060 ParentType::Custom { name, .. } => {
1061 if let Some((parent_type, parent_suggestion, parent_value)) =
1062 resolved.get(name.as_str())
1063 {
1064 return Ok((
1065 parent_type.as_ref().specifications.clone(),
1066 parent_suggestion.clone(),
1067 parent_value.clone(),
1068 Arc::clone(parent_type),
1069 ));
1070 }
1071 let type_exists = resolver
1072 .data_types
1073 .iter()
1074 .find(|(s, _)| discovery::same_loaded_spec(s, spec))
1075 .map(|(_, type_map)| type_map.contains_key(name.as_str()))
1076 .unwrap_or(false);
1077 if !type_exists {
1078 if spec.data.iter().any(|data| {
1079 data.reference.is_local()
1080 && data.reference.name == name.as_str()
1081 && data.value.uses_spec_ref().is_some()
1082 }) {
1083 return Err(vec![Error::validation_with_context(
1084 format!(
1085 "'{name}' names a spec import alias, not a type. Use `data x: {name}.TypeName` after `uses`"
1086 ),
1087 Some(source.clone()),
1088 None::<String>,
1089 Some(spec),
1090 None,
1091 )]);
1092 }
1093 if spec.rules.iter().any(|rule| rule.name == name.as_str()) {
1094 return Err(vec![Error::validation_with_context(
1095 format!(
1096 "Unknown parent '{parent}' for {site}: '{name}' is a local rule, not a type. Use a type name, or a reference expression if you meant the rule's value."
1097 ),
1098 Some(source.clone()),
1099 None::<String>,
1100 Some(spec),
1101 None,
1102 )]);
1103 }
1104 let mut imported_aliases: Vec<&str> = Vec::new();
1105 for data_row in &spec.data {
1106 let Some(spec_ref) = data_row.value.uses_spec_ref() else {
1107 continue;
1108 };
1109 let import_alias = &data_row.reference.name;
1110 let (_, imported_spec) =
1111 match resolver.resolve_spec_for_import(spec, spec_ref, source, at) {
1112 Ok(pair) => pair,
1113 Err(_) => continue,
1114 };
1115 let Some(imported_resolved) = already_resolved
1116 .iter()
1117 .find(|(_, s, _)| discovery::same_loaded_spec(s, imported_spec))
1118 .map(|(_, _, r)| r)
1119 else {
1120 continue;
1121 };
1122 if imported_resolved.resolved.contains_key(name.as_str()) {
1123 imported_aliases.push(import_alias.as_str());
1124 }
1125 }
1126 if !imported_aliases.is_empty() {
1127 let forms = imported_aliases
1128 .iter()
1129 .map(|alias| format!("{alias}.{name}"))
1130 .collect::<Vec<_>>()
1131 .join(", ");
1132 return Err(vec![Error::validation_with_context(
1133 format!(
1134 "Unknown parent '{parent}' for {site}: '{name}' is declared by import{}; write {forms}",
1135 if imported_aliases.len() == 1 {
1136 format!(" '{}'", imported_aliases[0])
1137 } else {
1138 format!("s {}", imported_aliases.join(", "))
1139 }
1140 ),
1141 Some(source.clone()),
1142 None::<String>,
1143 Some(spec),
1144 None,
1145 )]);
1146 }
1147 if resolver
1148 .context
1149 .spec_set(resolver.registered_repository(spec), name)
1150 .is_some()
1151 {
1152 return Err(vec![Error::validation_with_context(
1153 format!(
1154 "Unknown parent '{parent}' for {site}: '{name}' is a spec, not a name in spec '{}'. Only the local names of `uses` lines exist inside a spec",
1155 spec.name
1156 ),
1157 Some(source.clone()),
1158 Some(format!(
1159 "Add `uses {name}`, or write the local name of the `uses` line that imports '{name}'."
1160 )),
1161 Some(spec),
1162 None,
1163 )]);
1164 }
1165 return Err(vec![Error::validation_with_context(
1166 format!(
1167 "Unknown parent '{parent}' for {site}. Parent must be defined before use. Valid primitive types are: boolean, measure, number, ratio, text, date, time"
1168 ),
1169 Some(source.clone()),
1170 None::<String>,
1171 Some(spec),
1172 None,
1173 )]);
1174 }
1175 Err(vec![Error::validation_with_context(
1176 format!(
1177 "Circular dependency detected in type resolution: {}::{}",
1178 spec.name, name
1179 ),
1180 Some(source.clone()),
1181 None::<String>,
1182 Some(spec),
1183 None,
1184 )])
1185 }
1186 ParentType::Qualified { spec_alias, inner } => {
1187 let import_row = spec
1188 .data
1189 .iter()
1190 .find(|row| row.reference.segments.is_empty() && row.reference.name == *spec_alias);
1191 let spec_ref = import_row.and_then(|row| {
1192 row.value
1193 .uses_spec_ref()
1194 .cloned()
1195 .or_else(|| discovery::data_instance_list_spec_ref(spec, row))
1196 });
1197 let Some(spec_ref) = spec_ref else {
1198 if spec.rules.iter().any(|rule| rule.name == *spec_alias) {
1199 return Err(vec![Error::validation_with_context(
1200 format!(
1201 "'{spec_alias}' is a local rule, not a type path. Row fields in type position name a `uses` import or a `data` instance list, not a rule."
1202 ),
1203 Some(source.clone()),
1204 None::<String>,
1205 Some(spec),
1206 None,
1207 )]);
1208 }
1209 return Err(vec![Error::validation_with_context(
1210 format!("'{spec_alias}' is not a `uses` import alias in this spec"),
1211 Some(source.clone()),
1212 Some(format!(
1213 "Add `uses {spec_alias}: <target_spec>`, then write `{spec_alias}.<type>`."
1214 )),
1215 Some(spec),
1216 None,
1217 )]);
1218 };
1219 let dynamic_effective = matches!(
1220 import_row.map(|row| &row.value),
1221 Some(ParsedDataValue::Import {
1222 effective_ref: Some(_),
1223 ..
1224 })
1225 );
1226 match inner.as_ref() {
1227 ParentType::Primitive { primitive: kind } => {
1228 let lemma_type = Arc::clone(semantics::lemma_type_for_primitive(*kind));
1229 Ok((
1230 lemma_type.as_ref().specifications.clone(),
1231 None,
1232 None,
1233 lemma_type,
1234 ))
1235 }
1236 ParentType::Custom { name, .. } if dynamic_effective => {
1237 union_dynamic_import_parent_type(
1238 resolver,
1239 spec,
1240 source,
1241 already_resolved,
1242 &spec_ref,
1243 spec_alias,
1244 name.as_str(),
1245 )
1246 }
1247 ParentType::Custom { name, .. } => {
1248 let (import_repository, target_spec) =
1249 match resolver.resolve_spec_for_import(spec, &spec_ref, source, at) {
1250 Ok(import_pair) => import_pair,
1251 Err(error) => return Err(vec![error]),
1252 };
1253 let Some(resolved_spec_types) = already_resolved
1254 .iter()
1255 .find(|(_, imported, _)| discovery::same_loaded_spec(imported, target_spec))
1256 .map(|(_, _, resolved_spec_types)| resolved_spec_types)
1257 else {
1258 return Err(vec![Error::validation_with_context(
1259 format!(
1260 "Cannot resolve type '{name}' from spec '{}' (via import '{spec_alias}'): spec '{}' failed type resolution",
1261 target_spec.name, target_spec.name
1262 ),
1263 Some(source.clone()),
1264 None::<String>,
1265 Some(spec),
1266 None,
1267 )]);
1268 };
1269 let Some(parent_type) = resolved_spec_types.resolved.get(name.as_str()) else {
1270 let type_exists = resolver
1271 .data_types
1272 .iter()
1273 .find(|(s, _)| discovery::same_loaded_spec(s, target_spec))
1274 .map(|(_, type_map)| type_map.contains_key(name.as_str()))
1275 .unwrap_or(false);
1276 if !type_exists {
1277 return Err(vec![Error::validation_with_context(
1278 format!(
1279 "Type '{name}' is not defined in spec '{}' (via import '{spec_alias}')",
1280 target_spec.name
1281 ),
1282 Some(source.clone()),
1283 None::<String>,
1284 Some(spec),
1285 None,
1286 )]);
1287 }
1288 return Err(vec![Error::validation_with_context(
1289 format!(
1290 "Circular dependency detected in type resolution: {}::{}",
1291 target_spec.name, name
1292 ),
1293 Some(source.clone()),
1294 None::<String>,
1295 Some(spec),
1296 None,
1297 )]);
1298 };
1299 if let Some(list_row) = import_row.filter(|row| {
1303 row.value.uses_spec_ref().is_none()
1304 && matches!(site, TypeUseSite::DataDefinition)
1305 }) {
1306 let rows_unit = parent_type
1307 .held_value_type()
1308 .measure_units_table()
1309 .and_then(|units| units.iter().find(|unit| unit.is_dynamic()));
1310 if let Some(unit) = rows_unit {
1311 let element = discovery::data_instance_list_element(list_row)
1312 .unwrap_or_else(|| {
1313 panic!("BUG: list '{spec_alias}' names no row spec")
1314 });
1315 return Err(vec![Error::validation_with_context(
1316 format!(
1317 "'{spec_alias}' is not a `uses` import alias in this spec: it is a list, and unit '{unit}' of `{spec_alias}.{name}` is the unit of its rows, which a value declared here belongs to none of",
1318 unit = unit.name
1319 ),
1320 Some(source.clone()),
1321 Some(format!(
1322 "Write `{element}.{name}`, the type of the `uses` that '{spec_alias}' lists."
1323 )),
1324 Some(spec),
1325 None,
1326 )]);
1327 }
1328 }
1329 let import_effective = spec_ref.at(at);
1330 let identity =
1331 SpecIdentity::of(&import_repository, target_spec, import_effective);
1332 let hop = PathSegment::import(spec_alias, &identity);
1333 let into = ScaleOwner::new(
1334 resolver.registered_repository(spec).name.as_deref(),
1335 &spec.name,
1336 );
1337 let parent_type = Arc::new(parent_type.with_scale_import_hop(&hop, &into));
1338 Ok((
1339 parent_type.as_ref().specifications.clone(),
1340 resolved_spec_types
1341 .source_defaults
1342 .get(name.as_str())
1343 .cloned(),
1344 resolved_spec_types
1345 .source_value_defaults
1346 .get(name.as_str())
1347 .cloned(),
1348 parent_type,
1349 ))
1350 }
1351 ParentType::Qualified { .. } => Err(vec![Error::validation_with_context(
1352 "Nested qualified parent types are invalid",
1353 Some(source.clone()),
1354 None::<String>,
1355 Some(spec),
1356 None,
1357 )]),
1358 ParentType::Ranged { .. } => Err(vec![Error::validation_with_context(
1359 "Nested ranged parent types are invalid",
1360 Some(source.clone()),
1361 None::<String>,
1362 Some(spec),
1363 None,
1364 )]),
1365 ParentType::List { .. } => Err(vec![Error::validation_with_context(
1366 "Nested list parent types are invalid",
1367 Some(source.clone()),
1368 None::<String>,
1369 Some(spec),
1370 None,
1371 )]),
1372 }
1373 }
1374 }
1375}
1376
1377fn union_dynamic_import_parent_type(
1381 resolver: &TypeResolver<'_>,
1382 spec: &LemmaSpec,
1383 source: &Source,
1384 already_resolved: &ResolvedTypesMap<'_>,
1385 spec_ref: &ast::SpecRef,
1386 spec_alias: &str,
1387 type_name: &str,
1388) -> Result<ParentLookupOk, Vec<Error>> {
1389 let resolved_repo = match discovery::resolve_spec_ref_repository(
1390 resolver.context,
1391 spec_ref,
1392 Some(source),
1393 spec.name.as_str(),
1394 Some(spec),
1395 ) {
1396 Ok(resolved) => resolved,
1397 Err(error) => return Err(vec![error]),
1398 };
1399 let repository = match &resolved_repo.repository {
1400 Some(explicit) => Arc::clone(explicit),
1401 None => Arc::clone(resolver.registered_repository(spec)),
1402 };
1403 let dep_name = crate::parsing::ast::ascii_lowercase_logical_name(spec_ref.name.clone());
1404 let mut candidates: Vec<&Arc<LemmaType>> = Vec::new();
1405 for (repo, imported, resolved_types) in already_resolved {
1406 if !Arc::ptr_eq(repo, &repository) {
1407 continue;
1408 }
1409 if crate::parsing::ast::ascii_lowercase_logical_name(imported.name.clone()) != dep_name {
1410 continue;
1411 }
1412 let Some(parent_type) = resolved_types.resolved.get(type_name) else {
1413 let type_exists = resolver
1414 .data_types
1415 .iter()
1416 .find(|(s, _)| discovery::same_loaded_spec(s, imported))
1417 .map(|(_, type_map)| type_map.contains_key(type_name))
1418 .unwrap_or(false);
1419 if !type_exists {
1420 return Err(vec![Error::validation_with_context(
1421 format!(
1422 "Type '{type_name}' is not defined in spec '{}' (via import '{spec_alias}')",
1423 imported.name
1424 ),
1425 Some(source.clone()),
1426 None::<String>,
1427 Some(spec),
1428 None,
1429 )]);
1430 }
1431 return Err(vec![Error::validation_with_context(
1432 format!(
1433 "Circular dependency detected in type resolution: {}::{type_name}",
1434 imported.name
1435 ),
1436 Some(source.clone()),
1437 None::<String>,
1438 Some(spec),
1439 None,
1440 )]);
1441 };
1442 candidates.push(parent_type);
1443 }
1444 if candidates.is_empty() {
1445 return Err(vec![Error::validation_with_context(
1446 format!(
1447 "Cannot resolve type '{type_name}' from dependency '{}' (via import '{spec_alias}'): no candidate body has completed type resolution",
1448 spec_ref.name
1449 ),
1450 Some(source.clone()),
1451 None::<String>,
1452 Some(spec),
1453 None,
1454 )]);
1455 }
1456 let first = candidates[0];
1457 for later in &candidates[1..] {
1458 if !first.same_interface_ignoring_options(later) {
1459 return Err(vec![Error::validation_with_context(
1460 format!(
1461 "'{spec_alias}.{type_name}' changes across versions of '{}' under `-> effective`",
1462 spec_ref.name
1463 ),
1464 Some(source.clone()),
1465 Some(format!(
1466 "Keep '{type_name}' interface-compatible across every temporal version of '{}', or pin the import to a literal date.",
1467 spec_ref.name
1468 )),
1469 Some(spec),
1470 None,
1471 )]);
1472 }
1473 if first.options.rule != later.options.rule {
1474 return Err(vec![Error::validation_with_context(
1475 format!(
1476 "'{spec_alias}.{type_name}' has different `-> options` rules across versions of '{}' under `-> effective`",
1477 spec_ref.name
1478 ),
1479 Some(source.clone()),
1480 Some(
1481 "Use the same options rule name on every version, or only inline `-> option` values."
1482 .to_string(),
1483 ),
1484 Some(spec),
1485 None,
1486 )]);
1487 }
1488 }
1489 let mut unioned = first.as_ref().clone();
1490 let mut values: Vec<semantics::OptionValue> = Vec::new();
1491 for candidate in &candidates {
1492 for option in &candidate.options.values {
1493 if !values.iter().any(|seen| seen == option) {
1494 values.push(option.clone());
1495 }
1496 }
1497 }
1498 values.sort_by(|left, right| {
1499 left.value
1500 .value
1501 .to_string()
1502 .cmp(&right.value.value.to_string())
1503 .then_with(|| left.value.unit.cmp(&right.value.unit))
1504 });
1505 unioned.options.values = values;
1506 let first_imported = already_resolved
1507 .iter()
1508 .find(|(repo, imported, _)| {
1509 Arc::ptr_eq(repo, &repository)
1510 && crate::parsing::ast::ascii_lowercase_logical_name(imported.name.clone())
1511 == dep_name
1512 })
1513 .map(|(_, imported, _)| *imported)
1514 .expect("BUG: union candidates require a resolved import body");
1515 let identity = SpecIdentity::of(
1516 &repository,
1517 first_imported,
1518 first_imported.effective_from.clone(),
1519 );
1520 let hop = PathSegment::import(spec_alias, &identity);
1521 let into = ScaleOwner::new(
1522 resolver.registered_repository(spec).name.as_deref(),
1523 &spec.name,
1524 );
1525 let unioned = unioned.with_scale_import_hop(&hop, &into);
1526 Ok((
1527 unioned.specifications.clone(),
1528 None,
1529 None,
1530 Arc::new(unioned),
1531 ))
1532}
1533
1534fn topo_sort_type_names(
1536 spec: &LemmaSpec,
1537 data_defs: &HashMap<String, DataTypeDef>,
1538 mut type_names: Vec<String>,
1539) -> Result<Vec<String>, Vec<Error>> {
1540 type_names.sort();
1541 if type_names.is_empty() {
1542 return Ok(type_names);
1543 }
1544 let type_index: HashMap<&str, usize> = type_names
1545 .iter()
1546 .enumerate()
1547 .map(|(index, name)| (name.as_str(), index))
1548 .collect();
1549 let type_count = type_names.len();
1550 let mut in_degree = vec![0usize; type_count];
1551 let mut dependents: Vec<Vec<usize>> = vec![Vec::new(); type_count];
1552 for (child_index, type_name) in type_names.iter().enumerate() {
1553 let custom_parent = match element_parent_type(&data_defs[type_name].parent) {
1554 ParentType::Custom { name, .. } => Some(name.as_str()),
1555 _ => None,
1556 };
1557 let Some(parent_name) = custom_parent else {
1558 continue;
1559 };
1560 let Some(&parent_index) = type_index.get(parent_name) else {
1561 continue;
1562 };
1563 if parent_index == child_index {
1564 continue;
1565 }
1566 in_degree[child_index] += 1;
1567 dependents[parent_index].push(child_index);
1568 }
1569 let mut queue: std::collections::VecDeque<usize> = (0..type_count)
1570 .filter(|&index| in_degree[index] == 0)
1571 .collect();
1572 let mut sorted = Vec::with_capacity(type_count);
1573 while let Some(index) = queue.pop_front() {
1574 sorted.push(type_names[index].clone());
1575 for &dependent_index in &dependents[index] {
1576 in_degree[dependent_index] -= 1;
1577 if in_degree[dependent_index] == 0 {
1578 queue.push_back(dependent_index);
1579 }
1580 }
1581 }
1582 if sorted.len() != type_count {
1583 let cycle_type_name = type_names
1584 .iter()
1585 .find(|name| in_degree[type_index[name.as_str()]] > 0)
1586 .expect("BUG: incomplete topo sort without cycle participant");
1587 return Err(vec![Error::validation_with_context(
1588 format!(
1589 "Circular dependency detected in type resolution: {}::{}",
1590 spec.name, cycle_type_name
1591 ),
1592 Some(data_defs[cycle_type_name].source.clone()),
1593 None::<String>,
1594 Some(spec),
1595 None,
1596 )]);
1597 }
1598 Ok(sorted)
1599}
1600
1601fn partition_list_type_names(
1606 data_defs: &HashMap<String, DataTypeDef>,
1607) -> (Vec<String>, Vec<String>) {
1608 fn has_list(parent: &ParentType) -> bool {
1609 let mut current = parent;
1610 loop {
1611 match current {
1612 ParentType::List { .. } => return true,
1613 ParentType::Ranged { inner } | ParentType::Qualified { inner, .. } => {
1614 current = inner.as_ref();
1615 }
1616 ParentType::Primitive { .. } | ParentType::Custom { .. } => return false,
1617 }
1618 }
1619 }
1620 let mut list_names: HashSet<String> = data_defs
1621 .iter()
1622 .filter(|(_, def)| has_list(&def.parent))
1623 .map(|(name, _)| name.clone())
1624 .collect();
1625 loop {
1626 let before = list_names.len();
1627 for (name, def) in data_defs {
1628 if let ParentType::Custom { name: parent, .. } = element_parent_type(&def.parent) {
1629 if list_names.contains(parent) {
1630 list_names.insert(name.clone());
1631 }
1632 }
1633 }
1634 if list_names.len() == before {
1635 break;
1636 }
1637 }
1638 let scalar_names = data_defs
1639 .keys()
1640 .filter(|name| !list_names.contains(*name))
1641 .cloned()
1642 .collect();
1643 (scalar_names, list_names.into_iter().collect())
1644}
1645
1646type TypeMap = IndexMap<String, Arc<LemmaType>>;
1647
1648fn local_data_or_rule(spec: &LemmaSpec, name: &str) -> bool {
1650 let is_data = spec
1651 .data
1652 .iter()
1653 .any(|d| d.reference.is_local() && d.reference.name == name);
1654 let is_rule = spec.rules.iter().any(|r| r.name == name);
1655 is_data || is_rule
1656}
1657
1658fn is_uses_alias(spec: &LemmaSpec, alias: &str) -> bool {
1660 spec.data.iter().any(|d| {
1661 d.reference.is_local()
1662 && d.reference.name == alias
1663 && matches!(d.value, ParsedDataValue::Import { .. })
1664 })
1665}
1666
1667fn classify_unit_payload_reference(
1672 reference: &ast::Reference,
1673 spec: &LemmaSpec,
1674 unit_index: &PlanningUnitIndex,
1675 resolved: &TypeMap,
1676) -> Result<UnitPayloadClass, String> {
1677 let local = reference.segments.is_empty() && local_data_or_rule(spec, &reference.name);
1678 let unit_ref = reference.to_string();
1679 let resolves_as_unit = unit_index
1680 .resolve_with_named_types(&unit_ref, resolved)
1681 .is_ok();
1682 if local && resolves_as_unit {
1683 return Err(format!(
1684 "unit scale reference '{reference}' is ambiguous: it names both a local data or rule and a unit path"
1685 ));
1686 }
1687 if local {
1688 return Ok(UnitPayloadClass::Scale);
1689 }
1690 if resolves_as_unit {
1691 return Ok(UnitPayloadClass::Compound);
1692 }
1693 if matches!(reference.segments.as_slice(), [alias] if is_uses_alias(spec, alias)) {
1694 return Ok(UnitPayloadClass::Scale);
1695 }
1696 Err(format!(
1697 "Unknown unit '{unit_ref}'. Declare it on a measure or ratio type, or import it with uses."
1698 ))
1699}
1700
1701enum UnitPayloadClass {
1702 Scale,
1703 Compound,
1704}
1705
1706fn rewrite_unit_path_scale_payloads(
1711 resolver: &TypeResolver<'_>,
1712 spec: &LemmaSpec,
1713 at: &EffectiveDate,
1714 already_resolved: &ResolvedTypesMap<'_>,
1715 resolved: &mut TypeMap,
1716 unit_index: &PlanningUnitIndex,
1717 type_sources: &HashMap<String, Source>,
1718) -> Vec<Error> {
1719 let mut errors = Vec::new();
1720 let type_names: Vec<String> = resolved.keys().cloned().collect();
1721 for type_name in type_names {
1722 let lemma_type = resolved
1723 .get(&type_name)
1724 .expect("BUG: type_name comes from resolved keys");
1725 let TypeSpecification::Measure { units, .. } = &lemma_type.specifications else {
1726 continue;
1727 };
1728 let unit_owned_locally = |unit_name: &str| {
1729 unit_index.owners_for(unit_name).iter().any(|owner| {
1730 matches!(
1731 owner,
1732 PlanningOwner::Local {
1733 type_name: local_name
1734 } if local_name == type_name.as_str()
1735 )
1736 })
1737 };
1738 let source = type_sources.get(&type_name).cloned();
1739 let mut compounds: Vec<(usize, String)> = Vec::new();
1740 let mut scale_targets: Vec<(usize, ReferenceTarget)> = Vec::new();
1741 for (idx, unit) in units.iter().enumerate() {
1742 let Some((segments, name)) = unit.scale_reference_parts() else {
1743 continue;
1744 };
1745 if !unit.resolved_scale_factors().is_empty() {
1746 continue;
1747 }
1748 let reference = ast::Reference {
1749 segments: segments.to_vec(),
1750 name: name.to_string(),
1751 };
1752 let source = source.clone().unwrap_or_else(|| {
1753 panic!("BUG: measure type '{type_name}' with a unit payload has no type source")
1754 });
1755 if !unit_owned_locally(&unit.name) {
1758 if let Ok(target) = resolve_number_scale_reference(
1760 resolver,
1761 spec,
1762 at,
1763 already_resolved,
1764 &reference,
1765 &source,
1766 ) {
1767 scale_targets.push((idx, target));
1768 }
1769 continue;
1770 }
1771 match classify_unit_payload_reference(&reference, spec, unit_index, resolved) {
1772 Ok(UnitPayloadClass::Scale) => {
1773 match resolve_number_scale_reference(
1774 resolver,
1775 spec,
1776 at,
1777 already_resolved,
1778 &reference,
1779 &source,
1780 ) {
1781 Ok(target) => scale_targets.push((idx, target)),
1782 Err(error) => errors.push(error),
1783 }
1784 }
1785 Ok(UnitPayloadClass::Compound) => {
1786 compounds.push((idx, reference.to_string()));
1787 }
1788 Err(message) => {
1789 errors.push(Error::validation(
1790 format!(
1791 "In spec '{}': unit '{}' in measure type '{}': {}",
1792 spec.name, unit.name, type_name, message
1793 ),
1794 Some(source),
1795 None::<String>,
1796 ));
1797 }
1798 }
1799 }
1800 if compounds.is_empty() && scale_targets.is_empty() {
1801 continue;
1802 }
1803 let mut owned = lemma_type.as_ref().clone();
1804 let TypeSpecification::Measure { units, .. } = &mut owned.specifications else {
1805 unreachable!("BUG: measure type still a measure after clone");
1806 };
1807 for (idx, target) in scale_targets {
1808 let owner = ScaleOwner::new(
1809 resolver.registered_repository(spec).name.as_deref(),
1810 &spec.name,
1811 );
1812 units.0[idx] = units.0[idx]
1813 .clone()
1814 .with_resolved_scale(ScaleTarget { target, owner });
1815 }
1816 for (idx, referenced) in compounds {
1817 let name = units.0[idx].name.clone();
1818 units.0[idx] =
1819 MeasureUnit::from_decimal_factor(name, Decimal::ONE, vec![(referenced, 1)])
1820 .expect("BUG: prefix 1 always converts to a rational");
1821 }
1822 resolved.insert(type_name, Arc::new(owned));
1823 }
1824 errors
1825}
1826
1827fn resolve_number_scale_reference(
1831 resolver: &TypeResolver<'_>,
1832 spec: &LemmaSpec,
1833 at: &EffectiveDate,
1834 already_resolved: &ResolvedTypesMap<'_>,
1835 reference: &ast::Reference,
1836 source: &Source,
1837) -> Result<ReferenceTarget, Error> {
1838 let scale_reference_error = |message: String| {
1839 Error::validation_with_context(
1840 message,
1841 Some(source.clone()),
1842 None::<String>,
1843 Some(spec),
1844 None,
1845 )
1846 };
1847 if reference.segments.is_empty() {
1848 let is_data = spec
1849 .data
1850 .iter()
1851 .any(|d| d.reference.is_local() && d.reference.name == reference.name);
1852 let is_rule = spec.rules.iter().any(|r| r.name == reference.name);
1853 if is_data && is_rule {
1854 return Err(scale_reference_error(format!(
1855 "Reference target '{}' is ambiguous: both a data and a rule in spec '{}'",
1856 reference.name, spec.name
1857 )));
1858 }
1859 if is_data {
1860 let is_import = spec.data.iter().any(|d| {
1861 d.reference.is_local()
1862 && d.reference.name == reference.name
1863 && matches!(d.value, ParsedDataValue::Import { .. })
1864 });
1865 if is_import {
1866 return Err(scale_reference_error(format!(
1867 "cannot supply spec instance '{}' as a value",
1868 reference.name
1869 )));
1870 }
1871 return Ok(ReferenceTarget::Data(DataPath::local(
1872 reference.name.clone(),
1873 )));
1874 }
1875 if is_rule {
1876 return Ok(ReferenceTarget::Rule(RulePath::new(
1877 Vec::new(),
1878 reference.name.clone(),
1879 )));
1880 }
1881 return Err(scale_reference_error(format!(
1882 "Reference target '{}' not found in spec '{}'",
1883 reference.name, spec.name
1884 )));
1885 }
1886 let [alias] = reference.segments.as_slice() else {
1887 return Err(scale_reference_error(format!(
1888 "unit scale reference '{reference}' is not a data or rule path in spec '{}'",
1889 spec.name
1890 )));
1891 };
1892 let Some(import_row) = spec.data.iter().find(|d| {
1893 d.reference.is_local()
1894 && d.reference.name == *alias
1895 && matches!(d.value, ParsedDataValue::Import { .. })
1896 }) else {
1897 return Err(scale_reference_error(format!(
1898 "Reference target '{}' not found in spec '{}'",
1899 reference, spec.name
1900 )));
1901 };
1902 let Some(spec_ref) = import_row.value.uses_spec_ref() else {
1903 return Err(scale_reference_error(format!(
1904 "Reference target '{}' not found in spec '{}'",
1905 reference, spec.name
1906 )));
1907 };
1908 let (import_repository, target_spec) =
1909 resolver.resolve_spec_for_import(spec, spec_ref, source, at)?;
1910 let Some((_, _, _)) = already_resolved
1911 .iter()
1912 .find(|(_, imported, _)| discovery::same_loaded_spec(imported, target_spec))
1913 else {
1914 return Err(scale_reference_error(format!(
1915 "Reference target '{}' not found in spec '{}'",
1916 reference.name, target_spec.name
1917 )));
1918 };
1919 let is_data = target_spec
1920 .data
1921 .iter()
1922 .any(|d| d.reference.is_local() && d.reference.name == reference.name);
1923 let is_rule = target_spec.rules.iter().any(|r| r.name == reference.name);
1924 if is_data && is_rule {
1925 return Err(scale_reference_error(format!(
1926 "Reference target '{}' is ambiguous: both a data and a rule in spec '{}'",
1927 reference.name, target_spec.name
1928 )));
1929 }
1930 let import_effective = spec_ref.at(at);
1931 let identity = SpecIdentity::of(&import_repository, target_spec, import_effective);
1932 let hop = PathSegment::import(alias, &identity);
1933 if is_data {
1934 return Ok(ReferenceTarget::Data(DataPath {
1935 segments: vec![hop],
1936 data: reference.name.clone(),
1937 }));
1938 }
1939 if is_rule {
1940 return Ok(ReferenceTarget::Rule(RulePath {
1941 segments: vec![hop],
1942 rule: reference.name.clone(),
1943 }));
1944 }
1945 Err(scale_reference_error(format!(
1946 "Reference target '{}' not found in spec '{}'",
1947 reference.name, target_spec.name
1948 )))
1949}
1950
1951fn assert_compound_units_resolved(spec_name: &str, resolved: &TypeMap) {
1953 for (type_name, lemma_type) in resolved {
1954 let Some(units) = lemma_type.measure_units_table() else {
1955 continue;
1956 };
1957 if let Some(unit) = units
1958 .iter()
1959 .find(|unit| matches!(unit.scale, crate::literals::UnitScale::Compound { .. }))
1960 {
1961 panic!(
1962 "BUG: compound unit '{}' on '{type_name}' in spec '{spec_name}' survived type resolution",
1963 unit.name
1964 );
1965 }
1966 }
1967}
1968
1969fn resolve_measure_decompositions(
1970 spec_name: &str,
1971 this_spec: &SpecVersionKey,
1972 mut resolved: TypeMap,
1973 unit_index: &PlanningUnitIndex,
1974 type_sources: &HashMap<String, Source>,
1975) -> (TypeMap, Vec<Error>) {
1976 let mut errors: Vec<Error> = Vec::new();
1977
1978 let source_for = |type_name: &str| -> Option<Source> { type_sources.get(type_name).cloned() };
1979
1980 let base_type_names: Vec<String> = resolved
1981 .iter()
1982 .filter_map(|(name, lt)| {
1983 if let TypeSpecification::Measure { units, .. } = <.specifications {
1984 if units.iter().all(measure_unit_is_simple) {
1985 return Some(name.clone());
1986 }
1987 }
1988 None
1989 })
1990 .collect();
1991
1992 for type_name in &base_type_names {
1993 let owned = unwrap_unique_resolved_type(
1994 resolved
1995 .shift_remove(type_name)
1996 .expect("BUG: type_name comes from resolved's own keys"),
1997 );
1998 let base_decomp = declared_measure_decomposition(&owned);
1999
2000 let reserved_collision = reserved_calendar_units_in_measure(&owned);
2001 if !reserved_collision.is_empty() && !owned.has_trait_calendar() {
2002 errors.push(Error::validation(
2003 format!(
2004 "In spec '{}': measure type '{}' declares unit(s) {:?} which are reserved calendar unit names.",
2005 spec_name, type_name, reserved_collision
2006 ),
2007 source_for(type_name),
2008 None::<String>,
2009 ));
2010 resolved.insert(type_name.clone(), Arc::new(owned));
2011 continue;
2012 }
2013
2014 let updated = owned.map_measure(|units, _| {
2015 let units = units.map(|u| u.with_decomposition(base_decomp.clone()));
2016 (units, Some(base_decomp.clone()))
2017 });
2018 resolved.insert(type_name.clone(), Arc::new(updated));
2019 }
2020
2021 let mut lookup = UnitDecompLookup::new();
2022
2023 for (unit_name, owner) in unit_index.iter_owners() {
2024 let unit_name = unit_name.to_string();
2025 let lemma_type = owner.lemma_type(&resolved);
2026 if let TypeSpecification::Measure {
2027 decomposition: Some(decomposition),
2028 units,
2029 ..
2030 } = &lemma_type.specifications
2031 {
2032 let measure_name = local_owner_name(owner);
2033 let unit = units
2034 .iter()
2035 .find(|u| u.name == unit_name)
2036 .unwrap_or_else(|| {
2037 panic!(
2038 "BUG: unit_name '{}' from unit_index must be in its owning type's units",
2039 unit_name
2040 )
2041 });
2042 let Some(factor) = unit.literal_factor().cloned() else {
2043 continue;
2044 };
2045 if unit_index.has_unique_owner(unit_name.as_str()) {
2047 lookup.insert(
2048 unit_name.clone(),
2049 (measure_name, decomposition.clone(), factor),
2050 );
2051 }
2052 }
2053 }
2054
2055 for (type_name, lemma_type) in resolved.iter() {
2056 if let TypeSpecification::Measure {
2057 units,
2058 decomposition: Some(decomposition),
2059 ..
2060 } = &lemma_type.specifications
2061 {
2062 let is_defining_type = lemma_type.measure_family().is_some_and(|family| {
2063 family.is_declared_in(this_spec) && family.name == *type_name
2064 });
2065 if !is_defining_type {
2066 continue;
2067 }
2068 for unit in units.iter() {
2069 let declared_by_other_family =
2070 unit_index.owners_for(&unit.name).iter().any(|owner| {
2071 !owner
2072 .lemma_type(&resolved)
2073 .same_measure_family(lemma_type.as_ref())
2074 });
2075 if declared_by_other_family {
2076 continue;
2077 }
2078 let Some(factor) = unit.literal_factor().cloned() else {
2079 continue;
2080 };
2081 lookup.insert(
2082 unit.name.clone(),
2083 (Some(type_name.clone()), decomposition.clone(), factor),
2084 );
2085 }
2086 }
2087 }
2088
2089 let derived_measure_type_names_unsorted: Vec<String> = resolved
2090 .iter()
2091 .filter_map(|(name, lemma_type)| {
2092 if let TypeSpecification::Measure { units, .. } = &lemma_type.specifications {
2093 if units.iter().any(|unit| !measure_unit_is_simple(unit)) {
2094 return Some(name.clone());
2095 }
2096 }
2097 None
2098 })
2099 .collect();
2100
2101 let derived_measure_type_names = match sort_derived_measure_types_for_resolution(
2102 spec_name,
2103 derived_measure_type_names_unsorted,
2104 &resolved,
2105 &lookup,
2106 unit_index,
2107 type_sources,
2108 ) {
2109 Ok(sorted) => sorted,
2110 Err(error) => {
2111 errors.push(error);
2112 return (resolved, errors);
2113 }
2114 };
2115
2116 for type_name in &derived_measure_type_names {
2117 let type_source = source_for(type_name);
2118
2119 let (units_snapshot, already_resolved_body) = match &resolved[type_name].specifications {
2120 TypeSpecification::Measure {
2121 units,
2122 decomposition,
2123 ..
2124 } => (units.clone(), decomposition.clone()),
2125 _ => continue,
2126 };
2127
2128 let body_already_resolved = already_resolved_body.is_some();
2132 let unit_owned_locally = |unit_name: &str| {
2133 unit_index.owners_for(unit_name).iter().any(|owner| {
2134 matches!(
2135 owner,
2136 PlanningOwner::Local {
2137 type_name: local_name
2138 } if local_name == type_name
2139 )
2140 })
2141 };
2142 if body_already_resolved && !units_snapshot.iter().any(|u| unit_owned_locally(&u.name)) {
2143 for unit in units_snapshot.iter() {
2144 if matches!(&unit.scale, crate::literals::UnitScale::Unresolved { .. }) {
2145 panic!(
2146 "BUG: inherited unit '{}' on '{}' still has Unresolved scale; declaring family must classify and resolve unit payloads before dependents clone",
2147 unit.name, type_name
2148 );
2149 }
2150 }
2151 continue;
2152 }
2153
2154 let mut resolved_type_decomp: Option<BaseMeasureVector> = already_resolved_body;
2155 let mut unit_errors: Vec<Error> = Vec::new();
2156 let mut resolved_unit_scales: Vec<Option<ResolvedCompoundScale>> =
2157 vec![None; units_snapshot.len()];
2158 let mut resolve_to_simple: Vec<bool> = vec![false; units_snapshot.len()];
2159
2160 for (unit_idx, unit) in units_snapshot.iter().enumerate() {
2161 if calendar_unit_factor(&unit.name).is_some()
2162 && !resolved[type_name].has_trait_calendar()
2163 {
2164 unit_errors.push(Error::validation(
2165 format!(
2166 "In spec '{}': measure type '{}' declares unit '{}' which is a reserved calendar unit name.",
2167 spec_name, type_name, unit.name
2168 ),
2169 type_source.clone(),
2170 None::<String>,
2171 ));
2172 continue;
2173 }
2174 if measure_unit_is_simple(unit) {
2175 let simple_decomp = declared_measure_decomposition(&resolved[type_name]);
2176
2177 if let Some(existing) = &resolved_type_decomp {
2178 if existing != &simple_decomp {
2179 unit_errors.push(Error::validation(
2180 format!(
2181 "In spec '{}': measure type '{}' has inconsistent unit decompositions. \
2182 Unit '{}' is a simple unit (decomposition {}) but other units \
2183 have decomposition {}.",
2184 spec_name,
2185 type_name,
2186 unit.name,
2187 semantics::format_signature_operator_style(
2188 &semantics::base_measure_vector_as_signature(&simple_decomp)
2189 ),
2190 semantics::format_signature_operator_style(
2191 &semantics::base_measure_vector_as_signature(existing)
2192 )
2193 ),
2194 type_source.clone(),
2195 None::<String>,
2196 ));
2197 }
2198 } else {
2199 resolved_type_decomp = Some(simple_decomp);
2200 }
2201
2202 if let Some(factor) = unit.literal_factor() {
2203 resolved_unit_scales[unit_idx] =
2204 Some(ResolvedCompoundScale::Literal(factor.clone()));
2205 }
2206 continue;
2207 }
2208
2209 if body_already_resolved && !unit_owned_locally(&unit.name) {
2210 if let Some(factor) = unit.literal_factor() {
2211 resolved_unit_scales[unit_idx] =
2212 Some(ResolvedCompoundScale::Literal(factor.clone()));
2213 } else if unit.is_dynamic() {
2214 let factors = unit.resolved_scale_factors().to_vec();
2215 if factors.is_empty() {
2216 panic!(
2217 "BUG: inherited dynamic unit '{}' on '{type_name}' still has unresolved scale factors after the declaring type's resolution",
2218 unit.name
2219 );
2220 }
2221 resolved_unit_scales[unit_idx] = Some(ResolvedCompoundScale::Dynamic {
2222 factors,
2223 coefficient: unit.scale_coefficient(),
2224 });
2225 }
2226 continue;
2227 }
2228
2229 match resolve_compound_unit(
2230 spec_name,
2231 type_name,
2232 unit,
2233 &lookup,
2234 unit_index,
2235 &resolved,
2236 type_source.as_ref(),
2237 ) {
2238 Ok((unit_decomp, derived_scale)) => {
2239 if let [(referenced, 1)] = unit.derived_measure_factors.as_slice() {
2240 let (bare_name, owner) = unit_index
2241 .resolve_owner(referenced, &resolved)
2242 .unwrap_or_else(|err| {
2243 panic!(
2244 "BUG: factor '{referenced}' resolved for its conversion but not for its owner: {err}"
2245 )
2246 });
2247 let owning_type = owner.lemma_type(&resolved);
2248 let owner_family = owning_type
2249 .measure_family()
2250 .expect("BUG: resolved unit owner is not a named measure");
2251 let declaring_family = resolved[type_name]
2252 .measure_family()
2253 .expect("BUG: declaring measure has no family");
2254 if owner_family != declaring_family {
2255 unit_errors.push(Error::validation(
2256 format!(
2257 "In spec '{spec_name}': unit '{}' in measure type '{type_name}' cannot use a single unit from another measure. '{bare_name}' belongs to '{}'.",
2258 unit.name, owner_family.name
2259 ),
2260 type_source.clone(),
2261 None::<String>,
2262 ));
2263 }
2264 }
2265 if unit_decomp == declared_measure_decomposition(resolved[type_name].as_ref()) {
2268 resolve_to_simple[unit_idx] = true;
2269 }
2270 if let Some(existing) = &resolved_type_decomp {
2271 if existing != &unit_decomp {
2272 unit_errors.push(Error::validation(
2273 format!(
2274 "In spec '{}': measure type '{}' has inconsistent unit \
2275 decompositions. Unit '{}' resolved to {:?} but other units \
2276 resolved to {:?}. All units of a measure must measure the same \
2277 physical measure.",
2278 spec_name, type_name, unit.name, unit_decomp, existing
2279 ),
2280 type_source.clone(),
2281 None::<String>,
2282 ));
2283 }
2284 } else {
2285 resolved_type_decomp = Some(unit_decomp);
2286 }
2287
2288 resolved_unit_scales[unit_idx] = Some(derived_scale);
2289 }
2290 Err(err) => unit_errors.push(err),
2291 }
2292 }
2293
2294 if !unit_errors.is_empty() {
2295 errors.extend(unit_errors);
2296 continue;
2297 }
2298
2299 let type_decomp = match resolved_type_decomp {
2300 Some(d) => d,
2301 None => continue,
2302 };
2303
2304 let owned = unwrap_unique_resolved_type(
2305 resolved
2306 .shift_remove(type_name)
2307 .expect("BUG: type_name comes from resolved's own keys"),
2308 );
2309
2310 let updated = owned.map_measure(|units, _| {
2311 let units = MeasureUnits(
2312 units
2313 .0
2314 .into_iter()
2315 .enumerate()
2316 .map(|(idx, u)| {
2317 let u = u.with_decomposition(type_decomp.clone());
2318 let u = match resolved_unit_scales[idx].clone() {
2319 Some(ResolvedCompoundScale::Literal(factor)) => u.with_factor(factor),
2320 Some(ResolvedCompoundScale::Dynamic {
2321 factors,
2322 coefficient,
2323 }) => u.with_reference_scale(factors, coefficient),
2324 None => u,
2325 };
2326 if resolve_to_simple[idx] {
2327 u.with_derived_measure_factors(Vec::new())
2328 } else {
2329 u
2330 }
2331 })
2332 .collect(),
2333 );
2334 (units, Some(type_decomp.clone()))
2335 });
2336
2337 if let TypeSpecification::Measure { units, .. } = &updated.specifications {
2338 for unit in units.iter() {
2339 if body_already_resolved && !unit_owned_locally(&unit.name) {
2342 continue;
2343 }
2344 let Some(factor) = unit.literal_factor().cloned() else {
2345 continue;
2346 };
2347 lookup.insert(
2348 unit.name.clone(),
2349 (Some(type_name.clone()), type_decomp.clone(), factor),
2350 );
2351 }
2352 }
2353 resolved.insert(type_name.clone(), Arc::new(updated));
2354 }
2355
2356 let resolved = canonicalize_unit_signatures(resolved);
2357
2358 (resolved, errors)
2359}
2360
2361fn finalize_lemma_measure_magnitudes(
2366 lemma_type: LemmaType,
2367 declared_suggestion: Option<&BoundValueKind>,
2368 type_name: &str,
2369) -> Result<LemmaType, String> {
2370 let LemmaType {
2371 name,
2372 mut specifications,
2373 extends,
2374 options,
2375 } = lemma_type;
2376 semantics::finalize_measure_unit_constraint_magnitudes(
2377 &mut specifications,
2378 declared_suggestion.map(|bound| &bound.value),
2379 type_name,
2380 )?;
2381 Ok(LemmaType {
2382 name,
2383 specifications,
2384 extends,
2385 options,
2386 })
2387}
2388
2389fn finalize_measure_magnitudes_in_resolved(
2390 resolved: IndexMap<String, Arc<LemmaType>>,
2391 declared_suggestions: &IndexMap<String, BoundValueKind>,
2392 type_sources: &HashMap<String, Source>,
2393 spec_name: &str,
2394 spec: &LemmaSpec,
2395) -> (IndexMap<String, Arc<LemmaType>>, Vec<Error>) {
2396 resolved.into_iter().fold(
2397 (IndexMap::new(), Vec::new()),
2398 |(mut acc, mut errors), (type_name, arc)| {
2399 let source = type_sources.get(&type_name).cloned().unwrap_or_else(|| {
2400 unreachable!(
2401 "BUG: resolved type '{}' has no corresponding DataTypeDef in spec '{}'",
2402 type_name, spec_name
2403 )
2404 });
2405 let owned = unwrap_unique_resolved_type(arc);
2406 let lemma_type = match finalize_lemma_measure_magnitudes(
2407 owned.clone(),
2408 declared_suggestions.get(&type_name),
2409 &type_name,
2410 ) {
2411 Ok(lt) => lt,
2412 Err(message) => {
2413 errors.push(Error::validation_with_context(
2414 format!(
2415 "Type '{}' has invalid measure unit constraints: {}",
2416 type_name, message
2417 ),
2418 Some(source),
2419 None::<String>,
2420 Some(spec),
2421 None,
2422 ));
2423 owned
2424 }
2425 };
2426 acc.insert(type_name, Arc::new(lemma_type));
2427 (acc, errors)
2428 },
2429 )
2430}
2431
2432fn canonicalize_unit_signatures(types: TypeMap) -> TypeMap {
2440 types
2441 .into_iter()
2442 .map(|(name, arc)| {
2443 (
2444 name,
2445 Arc::new(canonicalize_lemma_unit_signatures(
2446 unwrap_unique_resolved_type(arc),
2447 )),
2448 )
2449 })
2450 .collect()
2451}
2452
2453fn canonicalize_lemma_unit_signatures(lemma_type: LemmaType) -> LemmaType {
2454 lemma_type.map_measure(|units, decomposition| {
2455 let units = units.map(canonicalize_unit_for_measure);
2456 (units, decomposition)
2457 })
2458}
2459
2460fn reserved_calendar_units_in_measure(lemma_type: &LemmaType) -> Vec<String> {
2461 let TypeSpecification::Measure { units, .. } = &lemma_type.specifications else {
2462 return Vec::new();
2463 };
2464 units
2465 .iter()
2466 .filter(|u| calendar_unit_factor(&u.name).is_some())
2467 .map(|u| u.name.clone())
2468 .collect()
2469}
2470
2471fn measure_unit_is_simple(unit: &MeasureUnit) -> bool {
2472 unit.derived_measure_factors.is_empty()
2473 || (unit.derived_measure_factors.len() == 1
2474 && unit.derived_measure_factors[0].0 == unit.name
2475 && unit.derived_measure_factors[0].1 == 1)
2476}
2477
2478fn canonicalize_unit_for_measure(unit: MeasureUnit) -> MeasureUnit {
2479 let factors = if measure_unit_is_simple(&unit) {
2480 vec![(unit.name.clone(), 1)]
2481 } else {
2482 canonicalize_signature(&unit.derived_measure_factors)
2483 };
2484 unit.with_derived_measure_factors(factors)
2485}
2486
2487#[derive(Clone, Debug)]
2489enum ResolvedCompoundScale {
2490 Literal(RationalInteger),
2491 Dynamic {
2494 factors: Vec<(ScaleTarget, i32)>,
2495 coefficient: RationalInteger,
2496 },
2497}
2498
2499fn resolve_compound_unit(
2500 spec_name: &str,
2501 declaring_type_name: &str,
2502 unit: &MeasureUnit,
2503 lookup: &UnitDecompLookup,
2504 unit_index: &PlanningUnitIndex,
2505 resolved: &IndexMap<String, Arc<LemmaType>>,
2506 source: Option<&Source>,
2507) -> Result<(BaseMeasureVector, ResolvedCompoundScale), Error> {
2508 use crate::computation::bigint::BigInt;
2509 use crate::computation::rational::{checked_mul, checked_pow_integer};
2510
2511 let mut result: BaseMeasureVector = BaseMeasureVector::new();
2512 let crate::literals::UnitScale::Compound { prefix } = &unit.scale else {
2513 panic!(
2514 "BUG: compound unit '{}' on '{declaring_type_name}' resolved with scale {:?}",
2515 unit.name, unit.scale
2516 );
2517 };
2518 let mut coefficient = prefix.clone();
2519 let mut dynamic_factors: Vec<(ScaleTarget, i32)> = Vec::new();
2520
2521 for (measure_ref, exponent) in &unit.derived_measure_factors {
2522 if local_owning_measure_type_for_unit(measure_ref, lookup, unit_index, resolved).as_deref()
2525 == Some(declaring_type_name)
2526 {
2527 return Err(Error::validation(
2528 format!(
2529 "In spec '{}': unit '{}' in measure type '{}' references unit '{}' which \
2530 belongs to the same measure type. A measure cannot reference its own units \
2531 in a compound expression.",
2532 spec_name, unit.name, declaring_type_name, measure_ref
2533 ),
2534 source.cloned(),
2535 None::<String>,
2536 ));
2537 }
2538
2539 let (owning_decomp, component) = if let Some(entry) = lookup.get(measure_ref.as_str()) {
2540 (entry.1.clone(), CompoundComponent::Literal(entry.2.clone()))
2541 } else {
2542 let (bare, owner) = unit_index
2543 .resolve_owner(measure_ref, resolved)
2544 .map_err(|err| {
2545 Error::validation(
2546 format!(
2547 "In spec '{}': unit '{}' in measure type '{}' references '{}': {}. \
2548 Add `uses <spec>` (or declare the owning measure type in this spec) \
2549 so its units are in scope.",
2550 spec_name, unit.name, declaring_type_name, measure_ref, err
2551 ),
2552 source.cloned(),
2553 None::<String>,
2554 )
2555 })?;
2556 let owning_type = owner.lemma_type(resolved);
2557 let TypeSpecification::Measure {
2558 decomposition: Some(decomposition),
2559 units,
2560 ..
2561 } = &owning_type.specifications
2562 else {
2563 return Err(Error::validation(
2564 format!(
2565 "In spec '{}': unit '{}' in measure type '{}' references '{}' which did not resolve to a measure unit",
2566 spec_name, unit.name, declaring_type_name, measure_ref
2567 ),
2568 source.cloned(),
2569 None::<String>,
2570 ));
2571 };
2572 let referenced = units.iter().find(|u| u.name == bare).unwrap_or_else(|| {
2573 panic!(
2574 "BUG: resolved unit '{}' must be declared on type '{}'",
2575 bare,
2576 owning_type.name()
2577 )
2578 });
2579 let component = if let Some(factor) = referenced.literal_factor().cloned() {
2580 CompoundComponent::Literal(factor)
2581 } else {
2582 let factors = referenced.resolved_scale_factors();
2583 if factors.is_empty() {
2584 panic!(
2585 "BUG: dynamic unit '{bare}' on '{}' must be Reference-scaled before compounds that inherit it resolve",
2586 owning_type.name()
2587 );
2588 }
2589 CompoundComponent::Dynamic {
2590 bare: bare.to_string(),
2591 factors: factors.to_vec(),
2592 coefficient: referenced.scale_coefficient(),
2593 }
2594 };
2595 (decomposition.clone(), component)
2596 };
2597 let owning_decomp = &owning_decomp;
2598
2599 for (dim, &dim_exp) in owning_decomp {
2600 let combined = dim_exp
2601 .checked_mul(*exponent)
2602 .and_then(|value| accumulate(&mut result, dim, value));
2603 if combined.is_none() {
2604 return Err(unit_exponent_limit_error(
2605 spec_name,
2606 &unit.name,
2607 declaring_type_name,
2608 source,
2609 ));
2610 }
2611 }
2612
2613 match component {
2614 CompoundComponent::Literal(unit_factor) => {
2615 let component_contribution =
2616 checked_pow_integer(&unit_factor, &BigInt::from_i64(i64::from(*exponent)))
2617 .map_err(|error| {
2618 overflow_to_validation_error(
2619 spec_name,
2620 &unit.name,
2621 declaring_type_name,
2622 measure_ref,
2623 error,
2624 source,
2625 )
2626 })?;
2627 coefficient =
2628 checked_mul(&coefficient, &component_contribution).map_err(|error| {
2629 overflow_to_validation_error(
2630 spec_name,
2631 &unit.name,
2632 declaring_type_name,
2633 measure_ref,
2634 error,
2635 source,
2636 )
2637 })?;
2638 }
2639 CompoundComponent::Dynamic {
2640 bare,
2641 factors: base_factors,
2642 coefficient: base_coefficient,
2643 } => {
2644 let raised_coefficient =
2645 checked_pow_integer(&base_coefficient, &BigInt::from_i64(i64::from(*exponent)))
2646 .map_err(|error| {
2647 overflow_to_validation_error(
2648 spec_name,
2649 &unit.name,
2650 declaring_type_name,
2651 measure_ref,
2652 error,
2653 source,
2654 )
2655 })?;
2656 coefficient = checked_mul(&coefficient, &raised_coefficient).map_err(|error| {
2657 overflow_to_validation_error(
2658 spec_name,
2659 &unit.name,
2660 declaring_type_name,
2661 measure_ref,
2662 error,
2663 source,
2664 )
2665 })?;
2666 for (target, base_exponent) in base_factors {
2667 let component_exponent = base_exponent.checked_mul(*exponent).ok_or_else(|| {
2668 Error::validation(
2669 format!(
2670 "In spec '{spec_name}': unit '{}' in measure type '{declaring_type_name}' overflowed combining dynamic unit '{bare}' exponents.",
2671 unit.name
2672 ),
2673 source.cloned(),
2674 None::<String>,
2675 )
2676 })?;
2677 dynamic_factors.push((target, component_exponent));
2678 }
2679 }
2680 }
2681 }
2682
2683 let factors = merge_compound_scale_factors(
2684 spec_name,
2685 declaring_type_name,
2686 &unit.name,
2687 &dynamic_factors,
2688 source,
2689 )?;
2690 let derived_scale = if factors.is_empty() {
2691 ResolvedCompoundScale::Literal(coefficient)
2692 } else {
2693 ResolvedCompoundScale::Dynamic {
2694 factors,
2695 coefficient,
2696 }
2697 };
2698 Ok((result, derived_scale))
2699}
2700
2701fn merge_compound_scale_factors(
2702 spec_name: &str,
2703 declaring_type_name: &str,
2704 unit_name: &str,
2705 factors: &[(ScaleTarget, i32)],
2706 source: Option<&Source>,
2707) -> Result<Vec<(ScaleTarget, i32)>, Error> {
2708 use std::collections::BTreeMap;
2709 let mut accumulator: BTreeMap<ScaleTarget, i32> = BTreeMap::new();
2710 for (target, exponent) in factors {
2711 let entry = accumulator.entry(target.clone()).or_insert(0);
2712 *entry = entry.checked_add(*exponent).ok_or_else(|| {
2713 Error::validation(
2714 format!(
2715 "In spec '{spec_name}': unit '{unit_name}' in measure type '{declaring_type_name}' overflowed combining dynamic scale factor exponents."
2716 ),
2717 source.cloned(),
2718 None::<String>,
2719 )
2720 })?;
2721 }
2722 Ok(accumulator
2723 .into_iter()
2724 .filter(|(_, exponent)| *exponent != 0)
2725 .collect())
2726}
2727
2728enum CompoundComponent {
2729 Literal(RationalInteger),
2730 Dynamic {
2731 bare: String,
2732 factors: Vec<(ScaleTarget, i32)>,
2733 coefficient: RationalInteger,
2734 },
2735}
2736
2737fn overflow_to_validation_error(
2738 spec_name: &str,
2739 unit_name: &str,
2740 declaring_type_name: &str,
2741 measure_ref: &str,
2742 failure: NumericFailure,
2743 source: Option<&Source>,
2744) -> Error {
2745 Error::validation(
2746 format!(
2747 "In spec '{}': unit '{}' in measure type '{}' overflowed while combining '{}': {}",
2748 spec_name, unit_name, declaring_type_name, measure_ref, failure
2749 ),
2750 source.cloned(),
2751 None::<String>,
2752 )
2753}
2754
2755fn unit_exponent_limit_error(
2756 spec_name: &str,
2757 unit_name: &str,
2758 declaring_type_name: &str,
2759 source: Option<&Source>,
2760) -> Error {
2761 Error::validation(
2762 format!(
2763 "In spec '{}': unit '{}' in measure type '{}' has a unit exponent exceeding the maximum of {}",
2764 spec_name,
2765 unit_name,
2766 declaring_type_name,
2767 MAX_UNIT_EXPONENT
2768 ),
2769 source.cloned(),
2770 None::<String>,
2771 )
2772}
2773
2774fn accumulate(
2776 result: &mut BaseMeasureVector,
2777 dim: &semantics::Dimension,
2778 value: i32,
2779) -> Option<()> {
2780 let entry = result.entry(dim.clone()).or_insert(0);
2781 *entry = entry.checked_add(value)?;
2782 if entry.unsigned_abs() > MAX_UNIT_EXPONENT.unsigned_abs() {
2783 return None;
2784 }
2785 if *entry == 0 {
2786 result.remove(dim);
2787 }
2788 Some(())
2789}
2790
2791#[derive(Debug, Clone, Default)]
2797pub struct ResolvedSpecTypes {
2798 pub resolved: IndexMap<String, Arc<LemmaType>>,
2801
2802 pub declared_suggestions: IndexMap<String, BoundValueKind>,
2808
2809 pub declared_values: IndexMap<String, BoundValueKind>,
2813
2814 pub(crate) raw_suggestions: Vec<(String, RawSuggestion)>,
2816
2817 pub(crate) raw_values: Vec<(String, RawSuggestion)>,
2819
2820 pub(crate) source_defaults: IndexMap<String, RawSuggestion>,
2822
2823 pub(crate) source_value_defaults: IndexMap<String, RawSuggestion>,
2825
2826 pub(crate) rule_list_types: Vec<(ParentType, Arc<LemmaType>)>,
2829
2830 pub unit_index: crate::planning::unit_index::UnitIndex,
2833
2834 pub(crate) deferred_signature_collisions:
2837 Vec<(String, crate::planning::semantics::BaseMeasureVector)>,
2838
2839 planning_unit_index: PlanningUnitIndex,
2841
2842 pub signature_index: crate::computation::arithmetic::SignatureIndex,
2845}
2846
2847impl ResolvedSpecTypes {
2848 fn declared_units(&self) -> HashSet<(Option<&semantics::TypeFamily>, &str)> {
2851 let mut units = HashSet::new();
2852 for declared in self.resolved.values() {
2853 let held = declared.held_value_type();
2854 let names: Vec<&str> = match &held.specifications {
2855 TypeSpecification::Measure { units, .. }
2856 | TypeSpecification::MeasureRange { units, .. } => {
2857 units.iter().map(|unit| unit.name.as_str()).collect()
2858 }
2859 TypeSpecification::Ratio { units, .. }
2860 | TypeSpecification::RatioRange { units, .. } => {
2861 units.iter().map(|unit| unit.name.as_str()).collect()
2862 }
2863 _ => Vec::new(),
2864 };
2865 units.extend(names.into_iter().map(|name| (held.family(), name)));
2866 }
2867 units
2868 }
2869}
2870
2871#[derive(Debug, Clone, PartialEq)]
2873pub(crate) struct DataTypeDef {
2874 pub parent: ParentType,
2875 pub constraints: Option<Vec<Constraint>>,
2876 pub source: crate::parsing::source::Source,
2877 pub name: String,
2878 pub bound_literal: Option<ast::Value>,
2880}
2881
2882#[derive(Debug, Clone)]
2886pub(crate) struct TypeResolver<'a> {
2887 data_types: Vec<(&'a LemmaSpec, HashMap<String, DataTypeDef>)>,
2888 context: &'a Context,
2889 all_registered_specs: Vec<(Arc<LemmaRepository>, &'a LemmaSpec)>,
2890 specs_with_failed_registration: Vec<&'a LemmaSpec>,
2895 slices: HashMap<SpecVersionKey, Arc<instance_list::VersionSlices>>,
2897}
2898
2899fn element_parent_type(parent: &ParentType) -> &ParentType {
2901 let mut current = parent;
2902 while let ParentType::Ranged { inner } | ParentType::List { inner } = current {
2903 current = inner.as_ref();
2904 }
2905 current
2906}
2907
2908pub(crate) fn time_range_endpoints_share_timezone(
2909 left: &semantics::SemanticTime,
2910 right: &semantics::SemanticTime,
2911) -> bool {
2912 match (&left.timezone, &right.timezone) {
2913 (None, None) => true,
2914 (Some(left_tz), Some(right_tz)) => left_tz.offset_minutes == right_tz.offset_minutes,
2915 _ => false,
2916 }
2917}
2918
2919fn parser_value_base_type_display_name(value: &ast::Value) -> &'static str {
2923 match value {
2924 ast::Value::Number(_) => "number",
2925 ast::Value::Text(_) => "text",
2926 ast::Value::Boolean(_) => "boolean",
2927 ast::Value::Date(_) => "date",
2928 ast::Value::Time(_) => "time",
2929 ast::Value::NumberWithUnit(_, unit) => match unit.as_str() {
2930 "percent" | "permille" => "ratio",
2931 _ => "measure",
2932 },
2933 ast::Value::Range(_, _) => "range",
2934 }
2935}
2936
2937fn inferred_parent_type_from_literal(value: &ast::Value) -> Result<ParentType, String> {
2942 let parent_type = match value {
2943 ast::Value::Number(_) => ParentType::Primitive {
2944 primitive: PrimitiveKind::Number,
2945 },
2946 ast::Value::Text(_) => ParentType::Primitive {
2947 primitive: PrimitiveKind::Text,
2948 },
2949 ast::Value::Boolean(_) => ParentType::Primitive {
2950 primitive: PrimitiveKind::Boolean,
2951 },
2952 ast::Value::Date(_) => ParentType::Primitive {
2953 primitive: PrimitiveKind::Date,
2954 },
2955 ast::Value::Time(_) => ParentType::Primitive {
2956 primitive: PrimitiveKind::Time,
2957 },
2958 ast::Value::NumberWithUnit(_, _) => ParentType::Primitive {
2959 primitive: PrimitiveKind::Measure,
2960 },
2961 ast::Value::Range(left, right) => {
2962 let primitive = match (left.as_ref(), right.as_ref()) {
2963 (ast::Value::Number(_), ast::Value::Number(_)) => PrimitiveKind::NumberRange,
2964 (ast::Value::Date(_), ast::Value::Date(_)) => PrimitiveKind::DateRange,
2965 (ast::Value::Time(_), ast::Value::Time(_)) => PrimitiveKind::TimeRange,
2966 (ast::Value::NumberWithUnit(_, u1), ast::Value::NumberWithUnit(_, u2))
2967 if u1 == u2 && matches!(u1.as_str(), "percent" | "permille") =>
2968 {
2969 PrimitiveKind::RatioRange
2970 }
2971 (ast::Value::NumberWithUnit(_, _), ast::Value::NumberWithUnit(_, _)) => {
2972 PrimitiveKind::MeasureRange
2973 }
2974 (left_value, right_value) => {
2975 return Err(format!(
2976 "range endpoints must have the same supported base type, got {} and {}",
2977 parser_value_base_type_display_name(left_value),
2978 parser_value_base_type_display_name(right_value)
2979 ));
2980 }
2981 };
2982 ParentType::Primitive { primitive }
2983 }
2984 };
2985 Ok(parent_type)
2986}
2987
2988impl<'a> TypeResolver<'a> {
2989 pub fn new(
2990 context: &'a Context,
2991 slices: HashMap<SpecVersionKey, Arc<instance_list::VersionSlices>>,
2992 ) -> Self {
2993 TypeResolver {
2994 data_types: Vec::new(),
2995 context,
2996 all_registered_specs: Vec::new(),
2997 specs_with_failed_registration: Vec::new(),
2998 slices,
2999 }
3000 }
3001
3002 pub(crate) fn identity_at(
3004 &self,
3005 repository: &LemmaRepository,
3006 spec: &LemmaSpec,
3007 at: &EffectiveDate,
3008 ) -> SpecIdentity {
3009 self.slices
3010 .get(&SpecVersionKey::of(repository, spec))
3011 .expect("BUG: a spec type resolution reaches is in the graph's dependency order")
3012 .identity_at(repository, spec, at)
3013 }
3014
3015 fn rule_spec_element_list_type(
3018 &self,
3019 spec: &LemmaSpec,
3020 parent: &ParentType,
3021 source: &Source,
3022 at: &EffectiveDate,
3023 ) -> Option<Arc<LemmaType>> {
3024 let (name, spec_ref) = Self::list_of_spec_name(spec, parent)?;
3025 let (row_repository, row_spec) = match discovery::resolve_spec_ref_or_self(
3026 self.context,
3027 &spec_ref,
3028 self.registered_repository(spec),
3029 spec,
3030 at,
3031 Some(source.clone()),
3032 ) {
3033 Ok(pair) => pair,
3034 Err(_) => return None,
3035 };
3036 let identity = self.identity_at(&row_repository, row_spec, &spec_ref.at(at));
3037 let element = Arc::new(LemmaType::primitive(TypeSpecification::Spec {
3038 spec: identity,
3039 }));
3040 Some(Arc::new(LemmaType {
3041 name: Some(format!("{name} list")),
3042 specifications: TypeSpecification::List {
3043 element,
3044 key: ListKey::Numbered,
3045 help: String::new(),
3046 },
3047 extends: TypeExtends::Primitive,
3048 options: TypeOptions::default(),
3049 }))
3050 }
3051
3052 fn list_of_spec_name<'p>(
3056 spec: &LemmaSpec,
3057 parent: &'p ParentType,
3058 ) -> Option<(&'p str, ast::SpecRef)> {
3059 let ParentType::List { inner } = parent else {
3060 return None;
3061 };
3062 let ParentType::Custom { name } = inner.as_ref() else {
3063 return None;
3064 };
3065 discovery::list_element_spec_ref(spec, inner).map(|spec_ref| (name.as_str(), spec_ref))
3066 }
3067
3068 pub fn is_registered(&self, spec: &LemmaSpec) -> bool {
3069 self.all_registered_specs
3070 .iter()
3071 .any(|(_, s)| discovery::same_loaded_spec(s, spec))
3072 }
3073
3074 fn registered_repository(&self, spec: &LemmaSpec) -> &Arc<LemmaRepository> {
3076 self.all_registered_specs
3077 .iter()
3078 .find(|(_, registered)| discovery::same_loaded_spec(registered, spec))
3079 .map(|(repository, _)| repository)
3080 .expect("BUG: types are resolved only for specs registered with their repository")
3081 }
3082
3083 fn mark_registration_failure(&mut self, spec: &'a LemmaSpec) {
3085 if !self
3086 .specs_with_failed_registration
3087 .iter()
3088 .any(|s| discovery::same_loaded_spec(s, spec))
3089 {
3090 self.specs_with_failed_registration.push(spec);
3091 }
3092 }
3093
3094 pub fn registration_failed(&self, spec: &LemmaSpec) -> bool {
3099 self.specs_with_failed_registration
3100 .iter()
3101 .any(|s| discovery::same_loaded_spec(s, spec))
3102 }
3103
3104 pub fn register_all(
3106 &mut self,
3107 repository: &Arc<LemmaRepository>,
3108 spec: &'a LemmaSpec,
3109 ) -> Vec<Error> {
3110 self.record_repository(repository, spec);
3111
3112 let mut errors = Vec::new();
3113 for data in &spec.data {
3114 match &data.value {
3115 ParsedDataValue::Definition {
3116 base,
3117 constraints,
3118 value,
3119 list: _,
3120 } => {
3121 if matches!(
3122 (base.as_ref(), constraints.as_ref(), value.as_ref()),
3123 (None, None, Some(Value::NumberWithUnit(_, _)),)
3124 ) {
3125 continue;
3126 }
3127 let name = &data.reference.name;
3128 let parent = match (base.as_ref(), value.as_ref()) {
3129 (Some(b), _) => b.clone(),
3130 (None, Some(v)) => match inferred_parent_type_from_literal(v) {
3131 Ok(parent) => parent,
3132 Err(message) => {
3133 errors.push(Error::validation_with_context(
3134 message,
3135 Some(data.source_location.clone()),
3136 None::<String>,
3137 Some(spec),
3138 None,
3139 ));
3140 self.mark_registration_failure(spec);
3141 continue;
3142 }
3143 },
3144 (None, None) => {
3145 errors.push(Error::validation_with_context(
3146 format!(
3147 "Data '{name}' in spec '{}' must declare a type or a literal value",
3148 spec.name
3149 ),
3150 Some(data.source_location.clone()),
3151 None::<String>,
3152 Some(spec),
3153 None,
3154 ));
3155 self.mark_registration_failure(spec);
3156 continue;
3157 }
3158 };
3159 if Self::list_of_spec_name(spec, &parent).is_some() {
3162 continue;
3163 }
3164 let ftd = DataTypeDef {
3165 parent,
3166 constraints: constraints.clone(),
3167 source: data.source_location.clone(),
3168 name: name.clone(),
3169 bound_literal: value.clone(),
3170 };
3171 if let Err(e) = self.register_type(repository, spec, ftd) {
3172 errors.push(e);
3173 }
3174 }
3175 ParsedDataValue::Import { .. }
3176 | ParsedDataValue::ImportList { .. }
3177 | ParsedDataValue::OwnRows { .. } => {}
3178 }
3179 }
3180 errors
3181 }
3182
3183 fn record_repository(&mut self, repository: &Arc<LemmaRepository>, spec: &'a LemmaSpec) {
3184 if !self
3185 .all_registered_specs
3186 .iter()
3187 .any(|(_, s)| discovery::same_loaded_spec(s, spec))
3188 {
3189 self.all_registered_specs
3190 .push((Arc::clone(repository), spec));
3191 }
3192 }
3193
3194 pub fn register_type(
3196 &mut self,
3197 repository: &Arc<LemmaRepository>,
3198 spec: &'a LemmaSpec,
3199 def: DataTypeDef,
3200 ) -> Result<(), Error> {
3201 self.record_repository(repository, spec);
3202 let spec_types = if let Some(pos) = self
3203 .data_types
3204 .iter()
3205 .position(|(s, _)| discovery::same_loaded_spec(s, spec))
3206 {
3207 &mut self.data_types[pos].1
3208 } else {
3209 self.data_types.push((spec, HashMap::new()));
3210 let last = self.data_types.len() - 1;
3211 &mut self.data_types[last].1
3212 };
3213 if spec_types.contains_key(&def.name) {
3214 return Err(Error::validation_with_context(
3215 format!(
3216 "The name '{}' is already used for data in this spec.",
3217 def.name
3218 ),
3219 Some(def.source.clone()),
3220 None::<String>,
3221 Some(spec),
3222 None,
3223 ));
3224 }
3225 spec_types.insert(def.name.clone(), def);
3226 Ok(())
3227 }
3228
3229 pub fn resolve_and_validate(
3232 &self,
3233 spec: &LemmaSpec,
3234 at: &EffectiveDate,
3235 already_resolved: &ResolvedTypesMap,
3236 ) -> Result<ResolvedSpecTypes, Vec<Error>> {
3237 let (mut resolved_types, list_type_names) =
3238 self.resolve_types_internal(spec, at, already_resolved)?;
3239 resolved_types.source_defaults = resolved_types
3240 .raw_suggestions
3241 .iter()
3242 .map(|(name, raw)| (name.clone(), raw.clone()))
3243 .collect();
3244 resolved_types.source_value_defaults = resolved_types
3245 .raw_values
3246 .iter()
3247 .map(|(name, raw)| (name.clone(), raw.clone()))
3248 .collect();
3249 let mut errors = Vec::new();
3250
3251 let type_sources: std::collections::HashMap<String, Source> = resolved_types
3253 .resolved
3254 .keys()
3255 .chain(list_type_names.iter())
3256 .filter_map(|type_name| {
3257 self.data_types
3258 .iter()
3259 .find(|(s, _)| discovery::same_loaded_spec(s, spec))
3260 .and_then(|(_, defs)| defs.get(type_name.as_str()))
3261 .map(|ftd| (type_name.clone(), ftd.source.clone()))
3262 })
3263 .collect();
3264
3265 errors.extend(rewrite_unit_path_scale_payloads(
3267 self,
3268 spec,
3269 at,
3270 already_resolved,
3271 &mut resolved_types.resolved,
3272 &resolved_types.planning_unit_index,
3273 &type_sources,
3274 ));
3275 if !errors.is_empty() {
3276 return Err(errors);
3279 }
3280 let this_spec = SpecVersionKey::of(self.registered_repository(spec), spec);
3281 let (new_resolved, decomp_errors) = resolve_measure_decompositions(
3282 &spec.name,
3283 &this_spec,
3284 std::mem::take(&mut resolved_types.resolved),
3285 &resolved_types.planning_unit_index,
3286 &type_sources,
3287 );
3288 resolved_types.resolved = new_resolved;
3289 if !decomp_errors.is_empty() {
3290 errors.extend(decomp_errors);
3293 return Err(errors);
3294 }
3295
3296 for (type_name, raw) in std::mem::take(&mut resolved_types.raw_suggestions) {
3297 let lemma_type = resolved_types
3298 .resolved
3299 .get(&type_name)
3300 .expect("BUG: raw default for type not in resolved");
3301 match bound_value_kind_from_raw_suggestion(raw, &lemma_type.specifications, &type_name)
3302 {
3303 Ok(value_kind) => {
3304 resolved_types
3305 .declared_suggestions
3306 .insert(type_name, value_kind);
3307 }
3308 Err(message) => {
3309 let source = type_sources
3310 .get(&type_name)
3311 .cloned()
3312 .unwrap_or_else(|| unreachable!("BUG: type '{}' has no source", type_name));
3313 errors.push(Error::validation_with_context(
3314 message,
3315 Some(source),
3316 None::<String>,
3317 Some(spec),
3318 None,
3319 ));
3320 }
3321 }
3322 }
3323
3324 for (type_name, raw) in std::mem::take(&mut resolved_types.raw_values) {
3325 let lemma_type = resolved_types
3326 .resolved
3327 .get(&type_name)
3328 .expect("BUG: raw fill for type not in resolved");
3329 match bound_value_kind_from_raw_suggestion(raw, &lemma_type.specifications, &type_name)
3330 {
3331 Ok(value_kind) => {
3332 resolved_types.declared_values.insert(type_name, value_kind);
3333 }
3334 Err(message) => {
3335 let source = type_sources
3336 .get(&type_name)
3337 .cloned()
3338 .unwrap_or_else(|| unreachable!("BUG: type '{}' has no source", type_name));
3339 errors.push(Error::validation_with_context(
3340 message,
3341 Some(source),
3342 None::<String>,
3343 Some(spec),
3344 None,
3345 ));
3346 }
3347 }
3348 }
3349
3350 if let Some((_, data_defs)) = self
3351 .data_types
3352 .iter()
3353 .find(|(s, _)| discovery::same_loaded_spec(s, spec))
3354 {
3355 errors.extend(refresh_named_range_specs(
3356 self,
3357 spec,
3358 data_defs,
3359 &mut resolved_types,
3360 already_resolved,
3361 at,
3362 ));
3363 }
3364
3365 if errors.is_empty() {
3366 assert_compound_units_resolved(&spec.name, &resolved_types.resolved);
3367 }
3368
3369 let (new_resolved, resolved_errors) = finalize_measure_magnitudes_in_resolved(
3370 std::mem::take(&mut resolved_types.resolved),
3371 &resolved_types.declared_suggestions,
3372 &type_sources,
3373 &spec.name,
3374 spec,
3375 );
3376 resolved_types.resolved = new_resolved;
3377
3378 resolved_types.unit_index = std::mem::take(&mut resolved_types.planning_unit_index)
3379 .bind(&resolved_types.resolved, &this_spec);
3380
3381 match build_signature_index(&spec.name, &resolved_types.unit_index, already_resolved) {
3382 Ok(built) => {
3383 resolved_types.signature_index = built.index;
3384 resolved_types.deferred_signature_collisions = built.deferred_cross_type;
3385 }
3386 Err(error) => errors.push(error),
3387 }
3388
3389 if !resolved_errors.is_empty() {
3390 errors.extend(resolved_errors);
3391 return Err(errors);
3392 }
3393
3394 if let Err(list_errors) = self.resolve_list_types(
3395 spec,
3396 at,
3397 already_resolved,
3398 &list_type_names,
3399 &mut resolved_types,
3400 ) {
3401 errors.extend(list_errors);
3402 return Err(errors);
3403 }
3404
3405 if let Err(rule_list_errors) =
3406 self.resolve_rule_list_types(spec, at, already_resolved, &mut resolved_types)
3407 {
3408 errors.extend(rule_list_errors);
3409 return Err(errors);
3410 }
3411
3412 let mut validated_in_unit_index: HashSet<String> = HashSet::new();
3413 for lemma_type in resolved_types.unit_index.values() {
3414 let Some(measure_family) = lemma_type.measure_family_name() else {
3415 continue;
3416 };
3417 if !lemma_type.is_measure()
3418 || !validated_in_unit_index.insert(measure_family.to_string())
3419 {
3420 continue;
3421 }
3422 let type_name = lemma_type
3423 .name
3424 .as_deref()
3425 .filter(|name| *name == measure_family)
3426 .unwrap_or(measure_family);
3427 let source = type_sources
3428 .get(type_name)
3429 .cloned()
3430 .or_else(|| {
3431 self.data_types
3432 .iter()
3433 .find_map(|(_, defs)| defs.get(type_name).map(|def| def.source.clone()))
3434 })
3435 .unwrap_or_else(|| {
3436 unreachable!(
3437 "BUG: measure type '{}' in unit_index has no DataTypeDef source",
3438 type_name
3439 )
3440 });
3441 errors.extend(validate_type_specifications(
3442 &lemma_type.specifications,
3443 resolved_types.declared_suggestions.get(type_name),
3444 "suggestion",
3445 type_name,
3446 &source,
3447 Some(spec),
3448 &resolved_types.unit_index,
3449 ));
3450 errors.extend(validate_type_specifications(
3451 &lemma_type.specifications,
3452 resolved_types.declared_values.get(type_name),
3453 "with",
3454 type_name,
3455 &source,
3456 Some(spec),
3457 &resolved_types.unit_index,
3458 ));
3459 }
3460
3461 for (type_name, lemma_type) in &resolved_types.resolved {
3462 let source = type_sources.get(type_name).cloned().unwrap_or_else(|| {
3463 unreachable!(
3464 "BUG: resolved type '{}' has no corresponding DataTypeDef in spec '{}'",
3465 type_name, spec.name
3466 )
3467 });
3468 let mut spec_errors = validate_type_specifications(
3469 &lemma_type.specifications,
3470 resolved_types.declared_suggestions.get(type_name),
3471 "suggestion",
3472 type_name,
3473 &source,
3474 Some(spec),
3475 &resolved_types.unit_index,
3476 );
3477 errors.append(&mut spec_errors);
3478 let mut fill_errors = validate_type_specifications(
3479 &lemma_type.specifications,
3480 resolved_types.declared_values.get(type_name),
3481 "with",
3482 type_name,
3483 &source,
3484 Some(spec),
3485 &resolved_types.unit_index,
3486 );
3487 errors.append(&mut fill_errors);
3488 errors.extend(validate_type_options(
3489 lemma_type,
3490 resolved_types.declared_suggestions.get(type_name),
3491 "suggestion",
3492 type_name,
3493 &source,
3494 Some(spec),
3495 &resolved_types.unit_index,
3496 ));
3497 errors.extend(validate_type_options(
3498 lemma_type,
3499 resolved_types.declared_values.get(type_name),
3500 "with",
3501 type_name,
3502 &source,
3503 Some(spec),
3504 &resolved_types.unit_index,
3505 ));
3506 }
3507
3508 for (type_name, lemma_type) in &resolved_types.resolved {
3509 let is_range = matches!(
3510 &lemma_type.specifications,
3511 TypeSpecification::NumberRange { .. }
3512 | TypeSpecification::DateRange { .. }
3513 | TypeSpecification::TimeRange { .. }
3514 | TypeSpecification::MeasureRange { .. }
3515 | TypeSpecification::RatioRange { .. }
3516 );
3517 if !is_range {
3518 continue;
3519 }
3520 let source = type_sources.get(type_name).cloned().unwrap_or_else(|| {
3521 unreachable!(
3522 "BUG: resolved type '{}' has no corresponding DataTypeDef in spec '{}'",
3523 type_name, spec.name
3524 )
3525 });
3526 if let Some(default_kind) = resolved_types.declared_suggestions.get(type_name.as_str())
3527 {
3528 let lit = TypedLiteral {
3529 value: default_kind.value.clone(),
3530 lemma_type: Arc::clone(lemma_type),
3531 };
3532 if let Err(message) = crate::planning::execution_plan::validate_value_against_type(
3533 lemma_type.as_ref(),
3534 &lit.to_literal(),
3535 &resolved_types.unit_index,
3536 None,
3537 ) {
3538 errors.push(Error::validation_with_context(
3539 format!("Type '{}' suggestion is invalid: {}", type_name, message),
3540 Some(source.clone()),
3541 None::<String>,
3542 Some(spec),
3543 None,
3544 ));
3545 }
3546 }
3547 if let Some(default_kind) = resolved_types.declared_values.get(type_name.as_str()) {
3548 let lit = TypedLiteral {
3549 value: default_kind.value.clone(),
3550 lemma_type: Arc::clone(lemma_type),
3551 };
3552 if let Err(message) = crate::planning::execution_plan::validate_value_against_type(
3553 lemma_type.as_ref(),
3554 &lit.to_literal(),
3555 &resolved_types.unit_index,
3556 None,
3557 ) {
3558 errors.push(Error::validation_with_context(
3559 format!("Type '{}' with is invalid: {}", type_name, message),
3560 Some(source),
3561 None::<String>,
3562 Some(spec),
3563 None,
3564 ));
3565 }
3566 }
3567 }
3568
3569 if errors.is_empty() {
3570 Ok(resolved_types)
3571 } else {
3572 Err(errors)
3573 }
3574 }
3575
3576 fn resolve_list_types(
3582 &self,
3583 spec: &LemmaSpec,
3584 at: &EffectiveDate,
3585 already_resolved: &ResolvedTypesMap,
3586 list_type_names: &[String],
3587 resolved_types: &mut ResolvedSpecTypes,
3588 ) -> Result<(), Vec<Error>> {
3589 if list_type_names.is_empty() {
3590 return Ok(());
3591 }
3592 let data_defs = self
3593 .data_types
3594 .iter()
3595 .find(|(s, _)| discovery::same_loaded_spec(s, spec))
3596 .map(|(_, defs)| defs)
3597 .expect("BUG: list type names come from this spec's type definitions");
3598 let mut local = local_type_entries(resolved_types);
3599 let mut errors = Vec::new();
3600 for type_name in list_type_names {
3601 let ftd = data_defs
3602 .get(type_name.as_str())
3603 .expect("BUG: topo-sorted list type missing from registry");
3604 let (lemma_type, suggestion, value) =
3605 self.resolve_type_def(spec, type_name, ftd, at, already_resolved, &local)?;
3606 let to_error = |message: String| {
3607 Error::validation_with_context(
3608 message,
3609 Some(ftd.source.clone()),
3610 None::<String>,
3611 Some(spec),
3612 None,
3613 )
3614 };
3615 if let Some(raw) = &suggestion {
3616 resolved_types
3617 .source_defaults
3618 .insert(type_name.clone(), raw.clone());
3619 match bound_value_kind_from_raw_suggestion(
3620 raw.clone(),
3621 &lemma_type.specifications,
3622 type_name,
3623 ) {
3624 Ok(bound) => {
3625 resolved_types
3626 .declared_suggestions
3627 .insert(type_name.clone(), bound);
3628 }
3629 Err(message) => errors.push(to_error(message)),
3630 }
3631 }
3632 if let Some(raw) = &value {
3633 resolved_types
3634 .source_value_defaults
3635 .insert(type_name.clone(), raw.clone());
3636 match bound_value_kind_from_raw_suggestion(
3637 raw.clone(),
3638 &lemma_type.specifications,
3639 type_name,
3640 ) {
3641 Ok(bound) => {
3642 resolved_types
3643 .declared_values
3644 .insert(type_name.clone(), bound);
3645 }
3646 Err(message) => errors.push(to_error(message)),
3647 }
3648 }
3649 resolved_types
3650 .resolved
3651 .insert(type_name.clone(), Arc::clone(&lemma_type));
3652 local.insert(type_name.clone(), (lemma_type, suggestion, value));
3653 }
3654 if errors.is_empty() {
3655 Ok(())
3656 } else {
3657 Err(errors)
3658 }
3659 }
3660
3661 fn resolve_rule_list_types<'s>(
3664 &self,
3665 spec: &'s LemmaSpec,
3666 at: &EffectiveDate,
3667 already_resolved: &ResolvedTypesMap,
3668 resolved_types: &mut ResolvedSpecTypes,
3669 ) -> Result<(), Vec<Error>> {
3670 let mut written: Vec<(&'s ParentType, &'s Source)> = Vec::new();
3671 for rule in &spec.rules {
3672 let trees = std::iter::once(&rule.expression).chain(
3673 rule.unless_clauses
3674 .iter()
3675 .flat_map(|clause| [&clause.condition, &clause.result]),
3676 );
3677 for tree in trees {
3678 let mut pending = vec![tree.root()];
3679 while let Some(node) = pending.pop() {
3680 if let ast::ExpressionKind::ListType { element } = node.kind() {
3681 if written.iter().all(|(seen, _)| *seen != element) {
3682 let source = node
3683 .source()
3684 .expect("BUG: AST expression missing source location");
3685 written.push((element, source));
3686 }
3687 }
3688 node.push_children(&mut pending);
3689 }
3690 }
3691 }
3692 if written.is_empty() {
3693 return Ok(());
3694 }
3695 let local = local_type_entries(resolved_types);
3696 let mut errors = Vec::new();
3697 for (element, source) in written {
3698 let scope = ParentLookup {
3699 resolver: self,
3700 spec,
3701 source,
3702 at,
3703 already_resolved,
3704 resolved: &local,
3705 site: TypeUseSite::RuleListType,
3706 };
3707 match lookup_parent_type(&scope, element) {
3708 Ok((.., lemma_type)) => {
3709 resolved_types
3710 .rule_list_types
3711 .push((element.clone(), lemma_type));
3712 }
3713 Err(lookup_errors) => {
3714 if let Some(list_type) =
3715 self.rule_spec_element_list_type(spec, element, source, at)
3716 {
3717 resolved_types
3718 .rule_list_types
3719 .push((element.clone(), list_type));
3720 } else {
3721 errors.extend(lookup_errors);
3722 }
3723 }
3724 }
3725 }
3726 if errors.is_empty() {
3727 Ok(())
3728 } else {
3729 Err(errors)
3730 }
3731 }
3732
3733 fn resolve_type_def(
3735 &self,
3736 spec: &LemmaSpec,
3737 type_name: &str,
3738 ftd: &DataTypeDef,
3739 at: &EffectiveDate,
3740 already_resolved: &ResolvedTypesMap,
3741 resolved: &HashMap<String, ResolvedTypeEntry>,
3742 ) -> Result<ResolvedTypeEntry, Vec<Error>> {
3743 let parent = &ftd.parent;
3744 let constraints = &ftd.constraints;
3745
3746 let scope = ParentLookup {
3747 resolver: self,
3748 spec,
3749 source: &ftd.source,
3750 at,
3751 already_resolved,
3752 resolved,
3753 site: TypeUseSite::DataDefinition,
3754 };
3755 let (parent_specs, parent_suggestion, parent_value, parent_type) =
3756 lookup_parent_type(&scope, parent)?;
3757
3758 let mut declared_suggestion = parent_suggestion;
3759 let mut declared_value = parent_value;
3760 let mut final_type = (*parent_type).clone();
3761 final_type.specifications = parent_specs;
3762 let defs_of_spec = self
3763 .data_types
3764 .iter()
3765 .find(|(s, _)| discovery::same_loaded_spec(s, spec))
3766 .map(|(_, defs)| defs);
3767 let is_finalized_later =
3768 defs_of_spec.is_some_and(|data_defs| derives_from_local_named_range(parent, data_defs));
3769 if !is_finalized_later {
3770 if let Some(constraints) = &constraints {
3771 let resolve_unit = UnitTokenResolver::Search(
3772 already_resolved
3773 .iter()
3774 .map(|(_, _, rts)| (&rts.unit_index, &rts.resolved))
3775 .collect(),
3776 );
3777 apply_constraints_to_spec(
3778 spec,
3779 &constraint_application_type_name(parent, type_name),
3780 type_name,
3781 &mut final_type,
3782 constraints,
3783 &ftd.source,
3784 ConstraintSuggestionSink {
3785 suggestion: &mut declared_suggestion,
3786 value: &mut declared_value,
3787 resolve_unit: Some(&resolve_unit),
3788 },
3789 )?;
3790 }
3791 }
3792 let final_specs = final_type.specifications;
3793 let final_options = final_type.options;
3794
3795 if matches!(&final_specs, TypeSpecification::List { .. }) && declared_value.is_none() {
3796 declared_value = Some(RawSuggestion::List(Vec::new()));
3797 }
3798
3799 let this_spec = SpecVersionKey::of(self.registered_repository(spec), spec);
3800 let family = match (element_parent_type(parent), parent_type.family()) {
3801 (ParentType::Primitive { .. }, _) | (_, None) => {
3802 TypeFamily::declared_in(&this_spec, type_name)
3803 }
3804 (_, Some(parent_family)) => parent_family.clone(),
3805 };
3806 let defining_spec = match element_parent_type(parent) {
3807 ParentType::Qualified { .. } => TypeDefiningSpec::Import,
3808 _ => TypeDefiningSpec::Local,
3809 };
3810 let extends = TypeExtends::Custom {
3811 parent: parent.to_string(),
3812 family,
3813 defining_spec,
3814 };
3815
3816 let lemma_type = Arc::new(LemmaType {
3817 name: Some(type_name.to_string()),
3818 specifications: final_specs,
3819 extends,
3820 options: final_options,
3821 });
3822
3823 let declared_suggestion = match &ftd.bound_literal {
3824 Some(literal) => {
3825 let resolve_unit = UnitTokenResolver::Search(
3826 already_resolved
3827 .iter()
3828 .map(|(_, _, rts)| (&rts.unit_index, &rts.resolved))
3829 .collect(),
3830 );
3831 match semantics::parser_value_to_value_kind(
3832 literal,
3833 lemma_type.as_ref(),
3834 Some(&resolve_unit),
3835 ) {
3836 Ok(value_kind) => Some(RawSuggestion::Value(value_kind)),
3837 Err(message) => {
3838 return Err(vec![Error::validation_with_context(
3839 message,
3840 Some(ftd.source.clone()),
3841 None::<String>,
3842 Some(spec),
3843 None,
3844 )]);
3845 }
3846 }
3847 }
3848 None => declared_suggestion,
3849 };
3850
3851 Ok((lemma_type, declared_suggestion, declared_value))
3852 }
3853
3854 fn resolve_types_internal(
3857 &self,
3858 spec: &LemmaSpec,
3859 at: &EffectiveDate,
3860 already_resolved: &ResolvedTypesMap,
3861 ) -> Result<(ResolvedSpecTypes, Vec<String>), Vec<Error>> {
3862 let data_defs = self
3863 .data_types
3864 .iter()
3865 .find(|(s, _)| discovery::same_loaded_spec(s, spec))
3866 .map(|(_, defs)| defs)
3867 .cloned()
3868 .unwrap_or_default();
3869
3870 let (scalar_names, list_names) = partition_list_type_names(&data_defs);
3871 let sorted_type_names = topo_sort_type_names(spec, &data_defs, scalar_names)?;
3872 let list_type_names = topo_sort_type_names(spec, &data_defs, list_names)?;
3873
3874 let mut resolved: HashMap<String, ResolvedTypeEntry> = HashMap::new();
3875
3876 for type_name in &sorted_type_names {
3877 let ftd = data_defs
3878 .get(type_name.as_str())
3879 .expect("BUG: topo-sorted type missing from registry");
3880 let entry =
3881 self.resolve_type_def(spec, type_name, ftd, at, already_resolved, &resolved)?;
3882 resolved.insert(type_name.clone(), entry);
3883 }
3884
3885 let mut unit_index = PlanningUnitIndex::new();
3886 let mut errors = Vec::new();
3887 for unit in Self::extract_units_from_type(&semantics::primitive_ratio_arc().specifications)
3888 {
3889 unit_index.insert_owner(unit, PlanningOwner::PrimitiveRatio);
3890 }
3891
3892 let locals: HashMap<String, Arc<LemmaType>> = resolved
3893 .iter()
3894 .map(|(name, (type_arc, _, _))| (name.clone(), Arc::clone(type_arc)))
3895 .collect();
3896
3897 for type_name in &sorted_type_names {
3898 let (type_arc, _, _) = resolved
3899 .get(type_name)
3900 .expect("BUG: type was resolved but missing from map");
3901 let data_type_def = data_defs
3902 .get(type_name.as_str())
3903 .expect("BUG: type was resolved but not in registry");
3904 let merge_result = if type_arc.is_measure() {
3905 if let ParentType::Qualified { spec_alias, inner } = &data_type_def.parent {
3906 match Self::parent_units_for_qualified_extension(
3907 self,
3908 spec,
3909 data_type_def,
3910 already_resolved,
3911 at,
3912 spec_alias,
3913 inner,
3914 ) {
3915 Ok(None) => Ok(()),
3916 Ok(Some(parent_units)) => Self::merge_additive_measure_units(
3917 spec,
3918 &mut unit_index,
3919 type_arc,
3920 data_type_def,
3921 &[],
3922 &parent_units,
3923 &locals,
3924 ),
3925 Err(error) => Err(error),
3926 }
3927 } else {
3928 Self::add_measure_units_to_index(
3929 spec,
3930 &mut unit_index,
3931 type_arc,
3932 data_type_def,
3933 &[],
3934 &locals,
3935 )
3936 }
3937 } else if type_arc.is_ratio() {
3938 Self::add_ratio_units_to_index(
3939 spec,
3940 &mut unit_index,
3941 type_arc,
3942 data_type_def,
3943 &[],
3944 &locals,
3945 )
3946 } else {
3947 Ok(())
3948 };
3949 if let Err(error) = merge_result {
3950 errors.push(error);
3951 }
3952 }
3953
3954 let spec_repository_name = self.registered_repository(spec).name.as_deref();
3955 for data_row in &spec.data {
3956 let import_alias = data_row.reference.name.clone();
3957 let import_is_global = matches!(
3958 &data_row.value,
3959 ParsedDataValue::Import { global: true, .. }
3960 );
3961 let mut merge_imported_units =
3962 |import_repository: &Arc<LemmaRepository>,
3963 imported_spec: &LemmaSpec,
3964 imported_resolved: &ResolvedSpecTypes,
3965 list_rows: bool| {
3966 let scale_hop = {
3975 let identity = SpecIdentity::of(
3976 import_repository,
3977 imported_spec,
3978 imported_spec.effective_from.clone(),
3979 );
3980 let hop_name = if import_is_global {
3981 GlobalKey {
3982 repository: spec_repository_name.map(Arc::from),
3983 spec: Arc::from(identity.spec.as_str()),
3984 }
3985 .alias_in(spec_repository_name)
3986 } else {
3987 import_alias.clone()
3988 };
3989 PathSegment::import(&hop_name, &identity)
3990 };
3991 let imported_repository_name = import_repository.name.as_deref();
3992 let imported_owner =
3993 ScaleOwner::new(imported_repository_name, &imported_spec.name);
3994 let this_owner = ScaleOwner::new(spec_repository_name, &spec.name);
3995 let map_scale = |segments: &mut Vec<PathSegment>| {
3996 if let Some(first) = segments.first_mut() {
3997 if semantics::is_global_slot_name(&first.uses) {
3998 let key =
3999 GlobalKey::from_alias(&first.uses, imported_repository_name)
4000 .expect("BUG: a global slot name names a global");
4001 first.uses = Arc::from(key.alias_in(spec_repository_name));
4002 return;
4003 }
4004 }
4005 segments.insert(0, scale_hop.clone());
4006 };
4007 let mut rewritten: HashMap<*const LemmaType, Arc<LemmaType>> = HashMap::new();
4011 let given_on = imported_resolved.declared_units();
4012 for (bare, owner) in imported_resolved.unit_index.iter_owners() {
4013 if let UnitOwner::Named {
4014 import_path,
4015 lemma_type,
4016 ..
4017 } = owner
4018 {
4019 if !import_path.is_empty()
4020 && !given_on.contains(&(lemma_type.family(), bare))
4021 {
4022 continue;
4023 }
4024 }
4025 let planning_owner = match owner {
4026 UnitOwner::PrimitiveRatio => PlanningOwner::PrimitiveRatio,
4027 UnitOwner::Named {
4028 import_path,
4029 type_name,
4030 lemma_type,
4031 } => {
4032 let mut path = vec![import_alias.clone()];
4033 path.extend(import_path.iter().cloned());
4034 let lemma_type = if list_rows || !lemma_type.has_dynamic_units() {
4035 Arc::clone(lemma_type)
4036 } else {
4037 Arc::clone(
4038 rewritten.entry(Arc::as_ptr(lemma_type)).or_insert_with(
4039 || {
4040 Arc::new(lemma_type.with_scale_targets_mapped(
4041 &imported_owner,
4042 &this_owner,
4043 &map_scale,
4044 ))
4045 },
4046 ),
4047 )
4048 };
4049 PlanningOwner::Imported {
4050 import_path: path,
4051 type_name: type_name.clone(),
4052 lemma_type,
4053 }
4054 }
4055 };
4056 if list_rows {
4057 unit_index.insert_list_row_owner(bare.to_string(), planning_owner);
4058 } else {
4059 unit_index.insert_owner(bare.to_string(), planning_owner);
4060 }
4061 }
4062 };
4063 match &data_row.value {
4064 ParsedDataValue::Import {
4065 spec_ref,
4066 effective_ref: Some(_),
4067 ..
4068 } => {
4069 let resolved = match discovery::resolve_spec_ref_repository(
4071 self.context,
4072 spec_ref,
4073 Some(&data_row.source_location),
4074 spec.name.as_str(),
4075 Some(spec),
4076 ) {
4077 Ok(resolved) => resolved,
4078 Err(error) => {
4079 errors.push(error);
4080 continue;
4081 }
4082 };
4083 let repository = match &resolved.repository {
4084 Some(explicit) => Arc::clone(explicit),
4085 None => Arc::clone(self.registered_repository(spec)),
4086 };
4087 let dep_name =
4088 crate::parsing::ast::ascii_lowercase_logical_name(spec_ref.name.clone());
4089 for (repo, imported, imported_resolved) in already_resolved {
4090 if !Arc::ptr_eq(repo, &repository) {
4091 continue;
4092 }
4093 if crate::parsing::ast::ascii_lowercase_logical_name(imported.name.clone())
4094 != dep_name
4095 {
4096 continue;
4097 }
4098 if discovery::same_loaded_spec(imported, spec) {
4099 continue;
4100 }
4101 merge_imported_units(repo, imported, imported_resolved, false);
4102 }
4103 }
4104 ParsedDataValue::Import { .. } => {
4105 let Some(spec_ref) = data_row.value.uses_spec_ref() else {
4106 continue;
4107 };
4108 let (import_repository, imported_spec) = match self.resolve_spec_for_import(
4109 spec,
4110 spec_ref,
4111 &data_row.source_location,
4112 at,
4113 ) {
4114 Ok(pair) => pair,
4115 Err(error) => {
4116 errors.push(error);
4117 continue;
4118 }
4119 };
4120 if discovery::same_loaded_spec(imported_spec, spec) {
4121 continue;
4122 }
4123 let Some(imported_resolved) = already_resolved
4124 .iter()
4125 .find(|(_, imported, _)| {
4126 discovery::same_loaded_spec(imported, imported_spec)
4127 })
4128 .map(|(_, _, resolved_spec_types)| resolved_spec_types)
4129 else {
4130 continue;
4131 };
4132 merge_imported_units(
4133 &import_repository,
4134 imported_spec,
4135 imported_resolved,
4136 false,
4137 );
4138 }
4139 ParsedDataValue::Definition { .. } => {
4140 let Some(spec_ref) = discovery::data_instance_list_spec_ref(spec, data_row)
4141 else {
4142 continue;
4143 };
4144 let ParsedDataValue::Definition {
4145 base: Some(parent), ..
4146 } = &data_row.value
4147 else {
4148 continue;
4149 };
4150 if Self::list_of_spec_name(spec, parent).is_none() {
4151 continue;
4152 }
4153 let (import_repository, imported_spec) = match self
4154 .resolve_list_spec_for_import(
4155 spec,
4156 &spec_ref,
4157 &data_row.source_location,
4158 at,
4159 ) {
4160 Ok(pair) => pair,
4161 Err(error) => {
4162 errors.push(error);
4163 continue;
4164 }
4165 };
4166 if discovery::same_loaded_spec(imported_spec, spec) {
4167 continue;
4168 }
4169 let Some(imported_resolved) = already_resolved
4170 .iter()
4171 .find(|(_, imported, _)| {
4172 discovery::same_loaded_spec(imported, imported_spec)
4173 })
4174 .map(|(_, _, resolved_spec_types)| resolved_spec_types)
4175 else {
4176 continue;
4177 };
4178 merge_imported_units(
4179 &import_repository,
4180 imported_spec,
4181 imported_resolved,
4182 true,
4183 );
4184 }
4185 ParsedDataValue::ImportList { .. } => {
4186 panic!(
4187 "BUG: uses list is rejected at parse and must not reach type resolution"
4188 );
4189 }
4190 ParsedDataValue::OwnRows { .. } => {}
4191 }
4192 }
4193
4194 if !errors.is_empty() {
4195 return Err(errors);
4196 }
4197
4198 let mut raw_suggestions = Vec::new();
4199 let mut raw_values = Vec::new();
4200 let mut resolved_types = IndexMap::new();
4201 for type_name in &sorted_type_names {
4202 let (lemma_type, default, fill) = resolved
4203 .remove(type_name)
4204 .expect("BUG: every sorted type name must exist in resolved");
4205 if let Some(raw_suggestion) = default {
4206 raw_suggestions.push((type_name.clone(), raw_suggestion));
4207 }
4208 if let Some(raw_value) = fill {
4209 raw_values.push((type_name.clone(), raw_value));
4210 }
4211 resolved_types.insert(type_name.clone(), lemma_type);
4212 }
4213 if !resolved.is_empty() {
4214 panic!(
4215 "BUG: resolved types remain after draining sorted_type_names: {:?}",
4216 resolved.keys().collect::<Vec<_>>()
4217 );
4218 }
4219
4220 Ok((
4221 ResolvedSpecTypes {
4222 resolved: resolved_types,
4223 declared_suggestions: IndexMap::new(),
4224 declared_values: IndexMap::new(),
4225 raw_suggestions,
4226 raw_values,
4227 source_defaults: IndexMap::new(),
4228 source_value_defaults: IndexMap::new(),
4229 rule_list_types: Vec::new(),
4230 unit_index: UnitIndex::new(),
4231 planning_unit_index: unit_index,
4232 signature_index: crate::computation::arithmetic::SignatureIndex::new(),
4233 deferred_signature_collisions: Vec::new(),
4234 },
4235 list_type_names,
4236 ))
4237 }
4238
4239 fn resolve_spec_for_import(
4240 &self,
4241 spec: &LemmaSpec,
4242 from: &crate::parsing::ast::SpecRef,
4243 import_site: &crate::parsing::source::Source,
4244 at: &EffectiveDate,
4245 ) -> Result<(Arc<LemmaRepository>, &'a LemmaSpec), Error> {
4246 discovery::resolve_spec_ref(
4247 self.context,
4248 from,
4249 self.registered_repository(spec),
4250 spec,
4251 at,
4252 Some(import_site.clone()),
4253 )
4254 }
4255
4256 fn resolve_list_spec_for_import(
4258 &self,
4259 spec: &LemmaSpec,
4260 from: &crate::parsing::ast::SpecRef,
4261 import_site: &crate::parsing::source::Source,
4262 at: &EffectiveDate,
4263 ) -> Result<(Arc<LemmaRepository>, &'a LemmaSpec), Error> {
4264 discovery::resolve_spec_ref_or_self(
4265 self.context,
4266 from,
4267 self.registered_repository(spec),
4268 spec,
4269 at,
4270 Some(import_site.clone()),
4271 )
4272 }
4273
4274 fn add_measure_units_to_index(
4279 spec: &LemmaSpec,
4280 unit_index: &mut PlanningUnitIndex,
4281 resolved_type: &Arc<LemmaType>,
4282 defined_by: &DataTypeDef,
4283 import_path: &[String],
4284 locals: &HashMap<String, Arc<LemmaType>>,
4285 ) -> Result<(), Error> {
4286 if matches!(defined_by.parent, ParentType::Qualified { .. }) {
4287 unreachable!(
4288 "BUG: Qualified parents must use parent_units_for_qualified_extension + merge_additive_measure_units"
4289 );
4290 }
4291 let measure_family = resolved_type
4292 .measure_family_name()
4293 .expect("BUG: add_measure_units_to_index requires measure type with family");
4294 for unit in Self::extract_units_from_type(&resolved_type.specifications) {
4295 unit_index
4296 .merge_measure_unit(
4297 unit,
4298 resolved_type,
4299 &defined_by.name,
4300 import_path,
4301 measure_family,
4302 locals,
4303 )
4304 .map_err(|conflict| {
4305 Self::unit_merge_conflict_to_error(conflict, defined_by, spec)
4306 })?;
4307 }
4308 Ok(())
4309 }
4310
4311 fn parent_units_for_qualified_extension(
4313 resolver: &TypeResolver<'_>,
4314 spec: &LemmaSpec,
4315 defined_by: &DataTypeDef,
4316 already_resolved: &ResolvedTypesMap<'_>,
4317 at: &EffectiveDate,
4318 spec_alias: &str,
4319 inner: &ParentType,
4320 ) -> Result<Option<BTreeSet<String>>, Error> {
4321 let ParentType::Custom {
4322 name: parent_type_name,
4323 ..
4324 } = inner
4325 else {
4326 return Ok(None);
4327 };
4328 let Some(spec_ref) = spec.data.iter().find_map(|row| {
4329 if row.reference.segments.is_empty() && row.reference.name == spec_alias {
4330 row.value.uses_spec_ref()
4331 } else {
4332 None
4333 }
4334 }) else {
4335 return Err(Error::validation_with_context(
4336 format!("'{spec_alias}' is not a `uses` import alias in this spec"),
4337 Some(defined_by.source.clone()),
4338 Some(format!(
4339 "Add `uses {spec_alias}: <target_spec>`, then write `{spec_alias}.<type>`."
4340 )),
4341 Some(spec),
4342 None,
4343 ));
4344 };
4345 let (_, target_spec) =
4346 resolver.resolve_spec_for_import(spec, spec_ref, &defined_by.source, at)?;
4347 let Some(imported_resolved) = already_resolved
4348 .iter()
4349 .find(|(_, imported, _)| discovery::same_loaded_spec(imported, target_spec))
4350 .map(|(_, _, types)| types)
4351 else {
4352 return Ok(None);
4353 };
4354 let Some(parent_type) = imported_resolved.resolved.get(parent_type_name.as_str()) else {
4355 return Ok(None);
4356 };
4357 Ok(Some(
4358 Self::extract_units_from_type(&parent_type.specifications)
4359 .into_iter()
4360 .collect(),
4361 ))
4362 }
4363
4364 fn merge_additive_measure_units(
4366 spec: &LemmaSpec,
4367 unit_index: &mut PlanningUnitIndex,
4368 resolved_type: &Arc<LemmaType>,
4369 defined_by: &DataTypeDef,
4370 import_path: &[String],
4371 parent_units: &BTreeSet<String>,
4372 locals: &HashMap<String, Arc<LemmaType>>,
4373 ) -> Result<(), Error> {
4374 let measure_family = resolved_type
4375 .measure_family_name()
4376 .expect("BUG: additive measure registration requires family");
4377 for unit in Self::extract_units_from_type(&resolved_type.specifications) {
4378 if parent_units.contains(&unit) {
4379 continue;
4380 }
4381 unit_index
4382 .merge_measure_unit(
4383 unit,
4384 resolved_type,
4385 &defined_by.name,
4386 import_path,
4387 measure_family,
4388 locals,
4389 )
4390 .map_err(|conflict| {
4391 Self::unit_merge_conflict_to_error(conflict, defined_by, spec)
4392 })?;
4393 }
4394 Ok(())
4395 }
4396
4397 fn add_ratio_units_to_index(
4398 spec: &LemmaSpec,
4399 unit_index: &mut PlanningUnitIndex,
4400 resolved_type: &Arc<LemmaType>,
4401 defined_by: &DataTypeDef,
4402 import_path: &[String],
4403 locals: &HashMap<String, Arc<LemmaType>>,
4404 ) -> Result<(), Error> {
4405 for unit in Self::extract_units_from_type(&resolved_type.specifications) {
4406 unit_index
4407 .merge_ratio_unit(unit, resolved_type, &defined_by.name, import_path, locals)
4408 .map_err(|conflict| {
4409 Self::unit_merge_conflict_to_error(conflict, defined_by, spec)
4410 })?;
4411 }
4412 Ok(())
4413 }
4414
4415 fn unit_merge_conflict_to_error(
4416 conflict: UnitMergeConflict,
4417 defined_by: &DataTypeDef,
4418 spec: &LemmaSpec,
4419 ) -> Error {
4420 let message = match conflict {
4421 UnitMergeConflict::ConflictingFactors { unit, family } => format!(
4422 "Unit '{unit}' has different values on related measure types in '{family}'. \
4423 Use the same unit value on each type, or use different unit names."
4424 ),
4425 };
4426 Error::validation_with_context(
4427 message,
4428 Some(defined_by.source.clone()),
4429 None::<String>,
4430 Some(spec),
4431 None,
4432 )
4433 }
4434
4435 fn extract_units_from_type(specs: &TypeSpecification) -> Vec<String> {
4436 match specs {
4437 TypeSpecification::Measure { units, .. } => {
4438 units.iter().map(|unit| unit.name.clone()).collect()
4439 }
4440 TypeSpecification::Ratio { units, .. } => {
4441 units.iter().map(|unit| unit.name.clone()).collect()
4442 }
4443 _ => Vec::new(),
4444 }
4445 }
4446}
4447
4448pub(crate) fn instance_list_option_errors(
4453 lemma_type: &LemmaType,
4454 raw: &RawSuggestion,
4455 source: &Source,
4456 spec: &LemmaSpec,
4457) -> Vec<Error> {
4458 let owner = match &lemma_type.specifications {
4459 TypeSpecification::List { element, .. } => element.as_ref(),
4460 _ => lemma_type,
4461 };
4462 let mut values = Vec::new();
4463 let mut errors = Vec::new();
4464 if let Err(message) = collect_raw_values(raw, &mut values) {
4465 errors.push(Error::validation_with_context(
4466 message,
4467 Some(source.clone()),
4468 None::<String>,
4469 Some(spec),
4470 None,
4471 ));
4472 return errors;
4473 }
4474 for value in values {
4475 if let Err(message) = owner.reject_disallowed(&value, None) {
4476 errors.push(Error::validation_with_context(
4477 message,
4478 Some(source.clone()),
4479 None::<String>,
4480 Some(spec),
4481 None,
4482 ));
4483 }
4484 }
4485 errors
4486}
4487
4488fn collect_raw_values(raw: &RawSuggestion, out: &mut Vec<ValueKind>) -> Result<(), String> {
4489 let mut pending = vec![raw];
4490 while let Some(current) = pending.pop() {
4491 match current {
4492 RawSuggestion::Value(value) => out.push(value.clone()),
4493 RawSuggestion::List(rows) => {
4494 for row in rows.iter().rev() {
4495 pending.push(row);
4496 }
4497 }
4498 RawSuggestion::Measure { .. } | RawSuggestion::UnitBound { .. } => {
4499 return Err(
4500 "an instance-list option row is a value, not a measure bound still awaiting a unit"
4501 .to_string(),
4502 );
4503 }
4504 }
4505 }
4506 Ok(())
4507}
4508
4509pub(crate) fn validate_type_options(
4510 lemma_type: &LemmaType,
4511 declared_default: Option<&BoundValueKind>,
4512 default_label: &str,
4513 type_name: &str,
4514 source: &Source,
4515 spec_context: Option<&LemmaSpec>,
4516 unit_index: &UnitIndex,
4517) -> Vec<Error> {
4518 let owner = match &lemma_type.specifications {
4519 TypeSpecification::List { element, .. } if !element.options.is_empty() => element.as_ref(),
4520 _ => lemma_type,
4521 };
4522 let mut errors = Vec::new();
4523 let mut bare = owner.clone();
4524 bare.options = TypeOptions::default();
4525 for option in &owner.options.values {
4526 let literal = LiteralValue {
4527 value: option.value.value.clone(),
4528 };
4529 if let Err(message) =
4530 execution_plan::validate_value_against_type(&bare, &literal, unit_index, None)
4531 {
4532 errors.push(Error::validation_with_context(
4533 format!(
4534 "Type '{type_name}' option '{}': {message}",
4535 owner.display_bound(&option.value)
4536 ),
4537 Some(source.clone()),
4538 None::<String>,
4539 spec_context,
4540 None,
4541 ));
4542 }
4543 }
4544 if let Some(default) = declared_default {
4545 if let Err(message) = execution_plan::validate_value_against_type(
4546 lemma_type,
4547 &default.to_literal(),
4548 unit_index,
4549 None,
4550 ) {
4551 errors.push(Error::validation_with_context(
4552 format!("Type '{type_name}' {default_label} value {message}"),
4553 Some(source.clone()),
4554 None::<String>,
4555 spec_context,
4556 None,
4557 ));
4558 }
4559 }
4560 errors
4561}
4562
4563pub fn validate_type_specifications(
4574 specs: &TypeSpecification,
4575 declared_default: Option<&BoundValueKind>,
4576 default_label: &str,
4577 type_name: &str,
4578 source: &Source,
4579 spec_context: Option<&LemmaSpec>,
4580 unit_index: &UnitIndex,
4581) -> Vec<Error> {
4582 let mut errors = Vec::new();
4583 let declared_default = declared_default.map(|bound| &bound.value);
4584
4585 match specs {
4586 TypeSpecification::Measure {
4587 minimum,
4588 maximum,
4589 units,
4590 ..
4591 } => {
4592 if let (Some(min), Some(max)) = (minimum, maximum) {
4594 match (
4595 semantics::measure_declared_bound_to_canonical(
4596 &min.0, &min.1, units, type_name, "minimum",
4597 ),
4598 semantics::measure_declared_bound_to_canonical(
4599 &max.0, &max.1, units, type_name, "maximum",
4600 ),
4601 ) {
4602 (Ok(min_canonical), Ok(max_canonical)) => {
4603 match min_canonical.try_cmp(&max_canonical) {
4604 Ok(std::cmp::Ordering::Greater) => {
4605 errors.push(Error::validation_with_context(
4606 format!(
4607 "Type '{}' has invalid range: minimum {} {} is greater than maximum {} {}",
4608 type_name,
4609 min.0,
4610 min.1,
4611 max.0,
4612 max.1
4613 ),
4614 Some(source.clone()),
4615 None::<String>,
4616 spec_context,
4617 None,
4618 ));
4619 }
4620 Ok(std::cmp::Ordering::Less | std::cmp::Ordering::Equal) => {}
4621 Err(failure) => {
4622 errors.push(Error::validation_with_context(
4623 format!(
4624 "Type '{}' has invalid measure bound: range compare failed: {failure}",
4625 type_name
4626 ),
4627 Some(source.clone()),
4628 None::<String>,
4629 spec_context,
4630 None,
4631 ));
4632 }
4633 }
4634 }
4635 (Err(message), _) | (_, Err(message)) => {
4636 errors.push(Error::validation_with_context(
4637 format!(
4638 "Type '{}' has invalid measure bound: {}",
4639 type_name, message
4640 ),
4641 Some(source.clone()),
4642 None::<String>,
4643 spec_context,
4644 None,
4645 ));
4646 }
4647 }
4648 }
4649
4650 if units.is_empty() {
4654 errors.push(Error::validation_with_context(
4655 format!(
4656 "Type '{}' is a measure type but has no units. Measure types must define at least one unit (e.g. -> unit eur: 1).",
4657 type_name
4658 ),
4659 Some(source.clone()),
4660 None::<String>,
4661 spec_context,
4662 None,
4663 ));
4664 }
4665
4666 if !units.is_empty() {
4668 let mut seen_names: Vec<String> = Vec::new();
4669 for unit in units.iter() {
4670 if unit.name.trim().is_empty() {
4672 errors.push(Error::validation_with_context(
4673 format!(
4674 "Type '{}' has a unit with empty name. Unit names cannot be empty.",
4675 type_name
4676 ),
4677 Some(source.clone()),
4678 None::<String>,
4679 spec_context,
4680 None,
4681 ));
4682 }
4683
4684 if seen_names.contains(&unit.name) {
4686 errors.push(Error::validation_with_context(
4687 format!("Type '{}' has duplicate unit name '{}'. Unit names must be unique within a type.", type_name, unit.name),
4688 Some(source.clone()),
4689 None::<String>,
4690 spec_context,
4691 None,
4692 ));
4693 } else {
4694 seen_names.push(unit.name.clone());
4695 }
4696
4697 if !unit.is_positive_factor() {
4698 let factor = unit.declared_factor().expect(
4699 "BUG: a unit with a non-positive factor declares a number",
4700 );
4701 errors.push(Error::validation_with_context(
4702 format!("Type '{}' has unit '{}' with invalid value {}/{}. Unit values must be positive (conversion factor relative to type base).", type_name, unit.name, factor.numer_to_string(), factor.denom_to_string()),
4703 Some(source.clone()),
4704 None::<String>,
4705 spec_context,
4706 None,
4707 ));
4708 }
4709 }
4710 }
4711 }
4712 TypeSpecification::Number {
4713 minimum,
4714 maximum,
4715 decimals,
4716 ..
4717 } => {
4718 if let (Some(min), Some(max)) = (minimum, maximum) {
4720 match min.try_cmp(max) {
4721 Ok(std::cmp::Ordering::Greater) => {
4722 errors.push(Error::validation_with_context(
4723 format!(
4724 "Type '{}' has invalid range: minimum {} is greater than maximum {}",
4725 type_name, min, max
4726 ),
4727 Some(source.clone()),
4728 None::<String>,
4729 spec_context,
4730 None,
4731 ));
4732 }
4733 Ok(std::cmp::Ordering::Less | std::cmp::Ordering::Equal) => {}
4734 Err(failure) => {
4735 errors.push(Error::validation_with_context(
4736 format!(
4737 "Type '{}' has invalid range: bound compare failed: {failure}",
4738 type_name
4739 ),
4740 Some(source.clone()),
4741 None::<String>,
4742 spec_context,
4743 None,
4744 ));
4745 }
4746 }
4747 }
4748
4749 if let Some(d) = decimals {
4751 if *d > 28 {
4752 errors.push(Error::validation_with_context(
4753 format!(
4754 "Type '{}' has invalid decimals value: {}. Must be between 0 and 28",
4755 type_name, d
4756 ),
4757 Some(source.clone()),
4758 None::<String>,
4759 spec_context,
4760 None,
4761 ));
4762 }
4763 }
4764
4765 if let Some(ValueKind::Number(def)) = declared_default {
4766 if let Some(min) = minimum {
4767 match def.try_cmp(min) {
4768 Ok(std::cmp::Ordering::Less) => {
4769 errors.push(Error::validation_with_context(
4770 format!(
4771 "Type '{}' {default_label} value {} is less than minimum {}",
4772 type_name, def, min
4773 ),
4774 Some(source.clone()),
4775 None::<String>,
4776 spec_context,
4777 None,
4778 ));
4779 }
4780 Ok(std::cmp::Ordering::Equal | std::cmp::Ordering::Greater) => {}
4781 Err(failure) => {
4782 errors.push(Error::validation_with_context(
4783 format!(
4784 "Type '{}' {default_label} bound compare failed: {failure}",
4785 type_name
4786 ),
4787 Some(source.clone()),
4788 None::<String>,
4789 spec_context,
4790 None,
4791 ));
4792 }
4793 }
4794 }
4795 if let Some(max) = maximum {
4796 match def.try_cmp(max) {
4797 Ok(std::cmp::Ordering::Greater) => {
4798 errors.push(Error::validation_with_context(
4799 format!(
4800 "Type '{}' {default_label} value {} is greater than maximum {}",
4801 type_name, def, max
4802 ),
4803 Some(source.clone()),
4804 None::<String>,
4805 spec_context,
4806 None,
4807 ));
4808 }
4809 Ok(std::cmp::Ordering::Less | std::cmp::Ordering::Equal) => {}
4810 Err(failure) => {
4811 errors.push(Error::validation_with_context(
4812 format!(
4813 "Type '{}' {default_label} bound compare failed: {failure}",
4814 type_name
4815 ),
4816 Some(source.clone()),
4817 None::<String>,
4818 spec_context,
4819 None,
4820 ));
4821 }
4822 }
4823 }
4824 }
4825 }
4827
4828 TypeSpecification::Ratio {
4829 minimum,
4830 maximum,
4831 units,
4832 ..
4833 } => {
4834 if let (Some(min), Some(max)) = (minimum, maximum) {
4836 match min.try_cmp(max) {
4837 Ok(std::cmp::Ordering::Greater) => {
4838 errors.push(Error::validation_with_context(
4839 format!(
4840 "Type '{}' has invalid range: minimum {} is greater than maximum {}",
4841 type_name, min, max
4842 ),
4843 Some(source.clone()),
4844 None::<String>,
4845 spec_context,
4846 None,
4847 ));
4848 }
4849 Ok(std::cmp::Ordering::Less | std::cmp::Ordering::Equal) => {}
4850 Err(failure) => {
4851 errors.push(Error::validation_with_context(
4852 format!(
4853 "Type '{}' has invalid range: bound compare failed: {failure}",
4854 type_name
4855 ),
4856 Some(source.clone()),
4857 None::<String>,
4858 spec_context,
4859 None,
4860 ));
4861 }
4862 }
4863 }
4864
4865 if let Some(ValueKind::Ratio(def)) = declared_default {
4866 if let Some(min) = minimum {
4867 match def.try_cmp(min) {
4868 Ok(std::cmp::Ordering::Less) => {
4869 errors.push(Error::validation_with_context(
4870 format!(
4871 "Type '{}' {default_label} value {} is less than minimum {}",
4872 type_name, def, min
4873 ),
4874 Some(source.clone()),
4875 None::<String>,
4876 spec_context,
4877 None,
4878 ));
4879 }
4880 Ok(std::cmp::Ordering::Equal | std::cmp::Ordering::Greater) => {}
4881 Err(failure) => {
4882 errors.push(Error::validation_with_context(
4883 format!(
4884 "Type '{}' {default_label} bound compare failed: {failure}",
4885 type_name
4886 ),
4887 Some(source.clone()),
4888 None::<String>,
4889 spec_context,
4890 None,
4891 ));
4892 }
4893 }
4894 }
4895 if let Some(max) = maximum {
4896 match def.try_cmp(max) {
4897 Ok(std::cmp::Ordering::Greater) => {
4898 errors.push(Error::validation_with_context(
4899 format!(
4900 "Type '{}' {default_label} value {} is greater than maximum {}",
4901 type_name, def, max
4902 ),
4903 Some(source.clone()),
4904 None::<String>,
4905 spec_context,
4906 None,
4907 ));
4908 }
4909 Ok(std::cmp::Ordering::Less | std::cmp::Ordering::Equal) => {}
4910 Err(failure) => {
4911 errors.push(Error::validation_with_context(
4912 format!(
4913 "Type '{}' {default_label} bound compare failed: {failure}",
4914 type_name
4915 ),
4916 Some(source.clone()),
4917 None::<String>,
4918 spec_context,
4919 None,
4920 ));
4921 }
4922 }
4923 }
4924 }
4925
4926 if !units.is_empty() {
4930 let mut seen_names: Vec<String> = Vec::new();
4931 for unit in units.iter() {
4932 if unit.name.trim().is_empty() {
4934 errors.push(Error::validation_with_context(
4935 format!(
4936 "Type '{}' has a unit with empty name. Unit names cannot be empty.",
4937 type_name
4938 ),
4939 Some(source.clone()),
4940 None::<String>,
4941 spec_context,
4942 None,
4943 ));
4944 }
4945
4946 if seen_names.contains(&unit.name) {
4948 errors.push(Error::validation_with_context(
4949 format!("Type '{}' has duplicate unit name '{}'. Unit names must be unique within a type.", type_name, unit.name),
4950 Some(source.clone()),
4951 None::<String>,
4952 spec_context,
4953 None,
4954 ));
4955 } else {
4956 seen_names.push(unit.name.clone());
4957 }
4958
4959 if !unit.value.numer_is_positive() {
4960 errors.push(Error::validation_with_context(
4961 format!("Type '{}' has unit '{}' with invalid value {}/{}. Unit values must be positive (conversion factor relative to type base).", type_name, unit.name, unit.value.numer_to_string(), unit.value.denom_to_string()),
4962 Some(source.clone()),
4963 None::<String>,
4964 spec_context,
4965 None,
4966 ));
4967 }
4968 }
4969 }
4970 }
4971
4972 TypeSpecification::Text { length, .. } => {
4973 if let Some(ValueKind::Text(def)) = declared_default {
4974 let def_len = def.len();
4975
4976 if let Some(len) = length {
4977 if def_len != *len {
4978 errors.push(Error::validation_with_context(
4979 format!("Type '{}' {default_label} value length {} does not match required length {}", type_name, def_len, len),
4980 Some(source.clone()),
4981 None::<String>,
4982 spec_context,
4983 None,
4984 ));
4985 }
4986 }
4987 }
4988 }
4989
4990 TypeSpecification::Date {
4991 minimum, maximum, ..
4992 } => {
4993 if let (Some(min), Some(max)) = (minimum, maximum) {
4995 let min_sem = semantics::date_time_to_semantic(min);
4996 let max_sem = semantics::date_time_to_semantic(max);
4997 if semantics::compare_semantic_dates(&min_sem, &max_sem) == Ordering::Greater {
4998 errors.push(Error::validation_with_context(
4999 format!(
5000 "Type '{}' has invalid date range: minimum {} is after maximum {}",
5001 type_name, min, max
5002 ),
5003 Some(source.clone()),
5004 None::<String>,
5005 spec_context,
5006 None,
5007 ));
5008 }
5009 }
5010
5011 if let Some(ValueKind::Date(def)) = declared_default {
5012 if let Some(min) = minimum {
5013 let min_sem = semantics::date_time_to_semantic(min);
5014 if semantics::compare_semantic_dates(def, &min_sem) == Ordering::Less {
5015 errors.push(Error::validation_with_context(
5016 format!(
5017 "Type '{}' default date {} is before minimum {}",
5018 type_name, def, min
5019 ),
5020 Some(source.clone()),
5021 None::<String>,
5022 spec_context,
5023 None,
5024 ));
5025 }
5026 }
5027 if let Some(max) = maximum {
5028 let max_sem = semantics::date_time_to_semantic(max);
5029 if semantics::compare_semantic_dates(def, &max_sem) == Ordering::Greater {
5030 errors.push(Error::validation_with_context(
5031 format!(
5032 "Type '{}' default date {} is after maximum {}",
5033 type_name, def, max
5034 ),
5035 Some(source.clone()),
5036 None::<String>,
5037 spec_context,
5038 None,
5039 ));
5040 }
5041 }
5042 }
5043 }
5044
5045 TypeSpecification::Time {
5046 minimum, maximum, ..
5047 } => {
5048 if let (Some(min), Some(max)) = (minimum, maximum) {
5050 let min_sem = semantics::time_to_semantic(min);
5051 let max_sem = semantics::time_to_semantic(max);
5052 if semantics::compare_semantic_times(&min_sem, &max_sem) == Ordering::Greater {
5053 errors.push(Error::validation_with_context(
5054 format!(
5055 "Type '{}' has invalid time range: minimum {} is after maximum {}",
5056 type_name, min, max
5057 ),
5058 Some(source.clone()),
5059 None::<String>,
5060 spec_context,
5061 None,
5062 ));
5063 }
5064 }
5065
5066 if let Some(ValueKind::Time(def)) = declared_default {
5067 if let Some(min) = minimum {
5068 let min_sem = semantics::time_to_semantic(min);
5069 if semantics::compare_semantic_times(def, &min_sem) == Ordering::Less {
5070 errors.push(Error::validation_with_context(
5071 format!(
5072 "Type '{}' default time {} is before minimum {}",
5073 type_name, def, min
5074 ),
5075 Some(source.clone()),
5076 None::<String>,
5077 spec_context,
5078 None,
5079 ));
5080 }
5081 }
5082 if let Some(max) = maximum {
5083 let max_sem = semantics::time_to_semantic(max);
5084 if semantics::compare_semantic_times(def, &max_sem) == Ordering::Greater {
5085 errors.push(Error::validation_with_context(
5086 format!(
5087 "Type '{}' default time {} is after maximum {}",
5088 type_name, def, max
5089 ),
5090 Some(source.clone()),
5091 None::<String>,
5092 spec_context,
5093 None,
5094 ));
5095 }
5096 }
5097 }
5098 }
5099
5100 TypeSpecification::NumberRange { .. }
5101 | TypeSpecification::DateRange { .. }
5102 | TypeSpecification::TimeRange { .. }
5103 | TypeSpecification::MeasureRange { .. }
5104 | TypeSpecification::RatioRange { .. } => {
5105 if let Err(message) = semantics::check_range_bound_consistency(specs, unit_index) {
5106 errors.push(Error::validation_with_context(
5107 format!("Type '{}' has {message}", type_name),
5108 Some(source.clone()),
5109 None::<String>,
5110 spec_context,
5111 None,
5112 ));
5113 }
5114 }
5115 TypeSpecification::Boolean { .. } => {
5116 }
5118 TypeSpecification::Veto { .. } => {
5119 }
5122 TypeSpecification::Undetermined => unreachable!(
5123 "BUG: validate_type_specification_constraints called with Undetermined sentinel type; this type exists only during type inference"
5124 ),
5125 TypeSpecification::Spec { .. } | TypeSpecification::List { .. } => {}
5126 }
5127
5128 errors
5129}
5130
5131#[cfg(test)]
5132mod tests {
5133 use super::*;
5134
5135 mod type_resolution {
5136 use super::*;
5137 use crate::computation::rational::rational_new;
5138 use crate::parsing::ast::{
5139 CommandArg, LemmaSpec, ParentType, PrimitiveKind, TypeConstraintCommand,
5140 };
5141 use crate::parsing::parse;
5142 use crate::planning::typing::{find_unique_measure_type_in_unit_index, DecompositionMatch};
5143 use crate::ResourceLimits;
5144 use rust_decimal::Decimal;
5145 use std::sync::Arc;
5146
5147 fn test_context_and_effective(
5148 specs: &[&LemmaSpec],
5149 ) -> (&'static Context, &'static EffectiveDate) {
5150 use crate::engine::Context;
5151 let mut ctx = Context::new();
5152 let repository = ctx.workspace();
5153 for s in specs {
5154 ctx.insert_spec(Arc::clone(&repository), (*s).clone())
5155 .unwrap();
5156 }
5157 let ctx = Box::leak(Box::new(ctx));
5158 let eff = Box::leak(Box::new(EffectiveDate::Origin));
5159 (ctx, eff)
5160 }
5161
5162 fn context_with_test_spec() -> (&'static Context, &'static LemmaSpec) {
5163 use crate::engine::Context;
5164 let mut ctx = Context::new();
5165 let repository = ctx.workspace();
5166 let spec = LemmaSpec::new("test_spec".to_string());
5167 ctx.insert_spec(Arc::clone(&repository), spec).unwrap();
5168 let ctx: &'static Context = Box::leak(Box::new(ctx));
5169 let repository = ctx.workspace();
5170 let spec = ctx
5171 .spec_set(&repository, "test_spec")
5172 .and_then(|ss| ss.get_exact(None))
5173 .expect("inserted");
5174 (ctx, spec)
5175 }
5176
5177 fn resolver_for_code(code: &str) -> (TypeResolver<'static>, Vec<&'static LemmaSpec>) {
5178 use crate::engine::Context;
5179 let owned = parse(
5180 code,
5181 crate::parsing::source::SourceType::Volatile,
5182 &ResourceLimits::default(),
5183 )
5184 .unwrap()
5185 .into_flattened_specs();
5186 let mut ctx = Context::new();
5187 let repository = ctx.workspace();
5188 for s in owned {
5189 ctx.insert_spec(Arc::clone(&repository), s).unwrap();
5190 }
5191 let ctx = Box::leak(Box::new(ctx));
5192 let repository = ctx.workspace();
5193 let mut spec_refs: Vec<&'static LemmaSpec> = Vec::new();
5194 for ss in ctx.spec_sets_for(&repository) {
5195 for s in ss.iter_specs() {
5196 spec_refs.push(s);
5197 }
5198 }
5199 let mut resolver = TypeResolver::new(ctx, HashMap::new());
5200 for spec in &spec_refs {
5201 resolver.register_all(&repository, spec);
5202 }
5203 (resolver, spec_refs)
5204 }
5205
5206 fn resolver_single_spec(code: &str) -> (TypeResolver<'static>, &LemmaSpec) {
5207 let (resolver, spec_arcs) = resolver_for_code(code);
5208 let spec = spec_arcs.into_iter().next().expect("at least one spec");
5209 (resolver, spec)
5210 }
5211
5212 #[test]
5213 fn test_type_spec_for_primitive_covers_all_variants() {
5214 use crate::parsing::ast::PrimitiveKind;
5215 use crate::planning::semantics::type_spec_for_primitive;
5216
5217 for kind in [
5218 PrimitiveKind::Boolean,
5219 PrimitiveKind::Measure,
5220 PrimitiveKind::MeasureRange,
5221 PrimitiveKind::Number,
5222 PrimitiveKind::NumberRange,
5223 PrimitiveKind::Ratio,
5224 PrimitiveKind::RatioRange,
5225 PrimitiveKind::Text,
5226 PrimitiveKind::Date,
5227 PrimitiveKind::DateRange,
5228 PrimitiveKind::Time,
5229 PrimitiveKind::TimeRange,
5230 ] {
5231 let spec = type_spec_for_primitive(kind);
5232 assert!(
5233 !matches!(
5234 spec,
5235 crate::planning::semantics::TypeSpecification::Undetermined
5236 ),
5237 "type_spec_for_primitive({:?}) returned Undetermined",
5238 kind
5239 );
5240 }
5241 }
5242
5243 #[test]
5244 fn test_register_data_type_def() {
5245 let (ctx, spec) = context_with_test_spec();
5246 let mut resolver = TypeResolver::new(ctx, HashMap::new());
5247 let ftd = DataTypeDef {
5248 parent: ParentType::Primitive {
5249 primitive: PrimitiveKind::Number,
5250 },
5251 constraints: Some(vec![
5252 Constraint::new(
5253 TypeConstraintCommand::Minimum,
5254 vec![CommandArg::Literal(crate::literals::Value::Number(
5255 Decimal::ZERO,
5256 ))],
5257 crate::parsing::source::Source::new(
5258 crate::parsing::source::SourceType::Volatile,
5259 crate::parsing::ast::Span {
5260 start: 0,
5261 end: 0,
5262 line: 1,
5263 col: 0,
5264 },
5265 ),
5266 ),
5267 Constraint::new(
5268 TypeConstraintCommand::Maximum,
5269 vec![CommandArg::Literal(crate::literals::Value::Number(
5270 Decimal::from(150),
5271 ))],
5272 crate::parsing::source::Source::new(
5273 crate::parsing::source::SourceType::Volatile,
5274 crate::parsing::ast::Span {
5275 start: 0,
5276 end: 0,
5277 line: 1,
5278 col: 0,
5279 },
5280 ),
5281 ),
5282 ]),
5283 source: crate::parsing::source::Source::new(
5284 crate::parsing::source::SourceType::Volatile,
5285 crate::parsing::ast::Span {
5286 start: 0,
5287 end: 0,
5288 line: 1,
5289 col: 0,
5290 },
5291 ),
5292 name: "age".to_string(),
5293 bound_literal: None,
5294 };
5295
5296 let result = resolver.register_type(&ctx.workspace(), spec, ftd);
5297 assert!(result.is_ok());
5298 let resolved = resolver
5299 .resolve_and_validate(spec, &EffectiveDate::Origin, &Vec::new())
5300 .unwrap();
5301 assert!(resolved.resolved.contains_key("age"));
5302 }
5303
5304 #[test]
5305 fn test_register_duplicate_type_fails() {
5306 let (ctx, spec) = context_with_test_spec();
5307 let mut resolver = TypeResolver::new(ctx, HashMap::new());
5308 let ftd = DataTypeDef {
5309 parent: ParentType::Primitive {
5310 primitive: PrimitiveKind::Number,
5311 },
5312 constraints: None,
5313 source: crate::parsing::source::Source::new(
5314 crate::parsing::source::SourceType::Volatile,
5315 crate::parsing::ast::Span {
5316 start: 0,
5317 end: 0,
5318 line: 1,
5319 col: 0,
5320 },
5321 ),
5322 name: "money".to_string(),
5323 bound_literal: None,
5324 };
5325 let repository = ctx.workspace();
5326 resolver
5327 .register_type(&repository, spec, ftd.clone())
5328 .unwrap();
5329 let result = resolver.register_type(&repository, spec, ftd);
5330 assert!(result.is_err());
5331 }
5332
5333 #[test]
5334 fn test_resolve_custom_type_from_primitive() {
5335 let (ctx, spec) = context_with_test_spec();
5336 let mut resolver = TypeResolver::new(ctx, HashMap::new());
5337 let ftd = DataTypeDef {
5338 parent: ParentType::Primitive {
5339 primitive: PrimitiveKind::Number,
5340 },
5341 constraints: None,
5342 source: crate::parsing::source::Source::new(
5343 crate::parsing::source::SourceType::Volatile,
5344 crate::parsing::ast::Span {
5345 start: 0,
5346 end: 0,
5347 line: 1,
5348 col: 0,
5349 },
5350 ),
5351 name: "money".to_string(),
5352 bound_literal: None,
5353 };
5354
5355 resolver.register_type(&ctx.workspace(), spec, ftd).unwrap();
5356 let resolved = resolver
5357 .resolve_and_validate(spec, &EffectiveDate::Origin, &Vec::new())
5358 .unwrap();
5359
5360 assert!(resolved.resolved.contains_key("money"));
5361 let money_type = resolved.resolved.get("money").unwrap();
5362 assert_eq!(money_type.name, Some("money".to_string()));
5363 }
5364
5365 #[test]
5366 fn test_child_measure_type_keeps_declared_name_and_child_units() {
5367 let (resolver, spec) = resolver_single_spec(
5368 r#"spec test
5369 data length: measure
5370 -> unit meter: 1
5371 data road_length: length
5372 -> unit kilometer: 1000"#,
5373 );
5374
5375 let resolved_types = resolver
5376 .resolve_and_validate(spec, &EffectiveDate::Origin, &Vec::new())
5377 .unwrap();
5378
5379 let road_length_type = resolved_types.resolved.get("road_length").unwrap();
5380 assert_eq!(road_length_type.name.as_deref(), Some("road_length"));
5381
5382 match &road_length_type.specifications {
5383 TypeSpecification::Measure { units, .. } => {
5384 assert!(units.iter().any(|unit| unit.name == "kilometer"));
5385 }
5386 _ => panic!("Expected Measure type specifications"),
5387 }
5388
5389 let kilometer_owner = resolved_types.unit_index.unique_owner("kilometer").unwrap();
5390 assert_eq!(kilometer_owner.name.as_deref(), Some("road_length"));
5391 assert!(
5392 Arc::ptr_eq(
5393 kilometer_owner,
5394 resolved_types.resolved.get("road_length").unwrap()
5395 ),
5396 "bound kilometer owner must be the resolved road_length Arc"
5397 );
5398 }
5399
5400 #[test]
5401 fn test_type_definition_resolution() {
5402 let (resolver, spec) = resolver_single_spec(
5403 r#"spec test
5404 data dice: number -> minimum 0 -> maximum 6"#,
5405 );
5406
5407 let resolved_types = resolver
5408 .resolve_and_validate(spec, &EffectiveDate::Origin, &Vec::new())
5409 .unwrap();
5410 let dice_type = resolved_types.resolved.get("dice").unwrap();
5411
5412 match &dice_type.specifications {
5413 TypeSpecification::Number {
5414 minimum, maximum, ..
5415 } => {
5416 assert_eq!(minimum, &Some(rational_new(0, 1)));
5417 assert_eq!(maximum, &Some(rational_new(6, 1)));
5418 }
5419 _ => panic!("Expected Number type specifications"),
5420 }
5421 }
5422
5423 #[test]
5424 fn test_type_definition_with_multiple_commands() {
5425 let (resolver, spec) = resolver_single_spec(
5426 r#"spec test
5427 data money: measure -> unit eur: 1.0 -> unit usd: 1.18 -> minimum 0 eur"#,
5428 );
5429
5430 let resolved_types = resolver
5431 .resolve_and_validate(spec, &EffectiveDate::Origin, &Vec::new())
5432 .unwrap();
5433 let money_type = resolved_types.resolved.get("money").unwrap();
5434
5435 match &money_type.specifications {
5436 TypeSpecification::Measure { minimum, units, .. } => {
5437 assert_eq!(minimum.as_ref().map(|(_, unit)| unit.as_str()), Some("eur"));
5438 assert_eq!(units.len(), 2);
5439 assert!(units.iter().any(|u| u.name == "eur"));
5440 assert!(units.iter().any(|u| u.name == "usd"));
5441 }
5442 _ => panic!("Expected Measure type specifications"),
5443 }
5444 }
5445
5446 #[test]
5447 fn test_number_type_with_decimals() {
5448 let (resolver, spec) = resolver_single_spec(
5449 r#"spec test
5450 data price: number -> decimals 2 -> minimum 0"#,
5451 );
5452
5453 let resolved_types = resolver
5454 .resolve_and_validate(spec, &EffectiveDate::Origin, &Vec::new())
5455 .unwrap();
5456 let price_type = resolved_types.resolved.get("price").unwrap();
5457
5458 match &price_type.specifications {
5459 TypeSpecification::Number {
5460 decimals, minimum, ..
5461 } => {
5462 assert_eq!(*decimals, Some(2));
5463 assert_eq!(minimum, &Some(rational_new(0, 1)));
5464 }
5465 _ => panic!("Expected Number type specifications with decimals"),
5466 }
5467 }
5468
5469 #[test]
5470 fn test_number_type_decimals_only() {
5471 let (resolver, spec) = resolver_single_spec(
5472 r#"spec test
5473 data precise_number: number -> decimals 4"#,
5474 );
5475
5476 let resolved_types = resolver
5477 .resolve_and_validate(spec, &EffectiveDate::Origin, &Vec::new())
5478 .unwrap();
5479 let precise_type = resolved_types.resolved.get("precise_number").unwrap();
5480
5481 match &precise_type.specifications {
5482 TypeSpecification::Number { decimals, .. } => {
5483 assert_eq!(*decimals, Some(4));
5484 }
5485 _ => panic!("Expected Number type with decimals 4"),
5486 }
5487 }
5488
5489 #[test]
5490 fn test_measure_type_rejects_decimals() {
5491 let (resolver, spec) = resolver_single_spec(
5492 r#"spec test
5493 data weight: measure -> unit kg: 1 -> decimals 3"#,
5494 );
5495
5496 let errors = resolver
5497 .resolve_and_validate(spec, &EffectiveDate::Origin, &Vec::new())
5498 .expect_err("decimals on a measure must be a planning error");
5499 let messages: Vec<String> = errors.iter().map(|e| e.to_string()).collect();
5500 assert!(
5501 messages.iter().any(|m| m.contains(
5502 "'decimals' is not valid on measure type 'weight': precision depends on the unit. Round in a rule instead, for example 'weight -> round 0.001 kg'."
5503 )),
5504 "got: {messages:?}"
5505 );
5506 }
5507
5508 #[test]
5509 fn test_ratio_type_rejects_decimals() {
5510 let (resolver, spec) = resolver_single_spec(
5511 r#"spec test
5512 data ratio_type: ratio -> decimals 2"#,
5513 );
5514
5515 let errors = resolver
5516 .resolve_and_validate(spec, &EffectiveDate::Origin, &Vec::new())
5517 .expect_err("decimals on a ratio must be a planning error");
5518 let messages: Vec<String> = errors.iter().map(|e| e.to_string()).collect();
5519 assert!(
5520 messages.iter().any(|m| m.contains(
5521 "'decimals' is not valid on ratio type 'ratio_type': precision depends on the unit. Round in a rule instead, for example 'ratio_type -> round 0.01 percent'."
5522 )),
5523 "got: {messages:?}"
5524 );
5525 }
5526
5527 #[test]
5528 fn typedef_default_inherits_through_extension_chain() {
5529 let (resolver, spec) = resolver_single_spec(
5530 r#"spec test
5531 data money: measure -> unit eur: 1 -> suggest 4 eur
5532 data price: money
5533 data final_price: price"#,
5534 );
5535
5536 let resolved = resolver
5537 .resolve_and_validate(spec, &EffectiveDate::Origin, &Vec::new())
5538 .expect("extension chain must resolve");
5539
5540 assert!(
5541 resolved.declared_suggestions.contains_key("money"),
5542 "base typedef default must convert to ValueKind"
5543 );
5544 assert!(
5545 resolved.declared_suggestions.contains_key("final_price"),
5546 "suggestion must inherit through extension chain (money → price → final_price)"
5547 );
5548 }
5549
5550 #[test]
5551 fn test_ratio_type_with_default_command() {
5552 let (resolver, spec) = resolver_single_spec(
5553 r#"spec test
5554 data percentage: ratio -> minimum 0% -> maximum 100% -> suggest 50%"#,
5555 );
5556
5557 let resolved_types = resolver
5558 .resolve_and_validate(spec, &EffectiveDate::Origin, &Vec::new())
5559 .unwrap();
5560 let percentage_type = resolved_types.resolved.get("percentage").unwrap();
5561
5562 match &percentage_type.specifications {
5563 TypeSpecification::Ratio {
5564 minimum, maximum, ..
5565 } => {
5566 assert_eq!(
5567 *minimum,
5568 Some(rational_new(0, 1)),
5569 "ratio type should have minimum 0"
5570 );
5571 assert_eq!(
5572 *maximum,
5573 Some(rational_new(1, 1)),
5574 "ratio type should have maximum 1"
5575 );
5576 }
5577 _ => panic!("Expected Ratio type with minimum and maximum"),
5578 }
5579
5580 let declared = resolved_types
5581 .declared_suggestions
5582 .get("percentage")
5583 .expect("declared default must be tracked for percentage");
5584 match &declared.value {
5585 ValueKind::Ratio(v) => {
5586 assert_eq!(v, &rational_new(1, 2));
5587 }
5588 other => panic!("expected Ratio declared default, got {:?}", other),
5589 }
5590 }
5591
5592 #[test]
5593 fn test_measure_extension_chain_same_family_units_allowed() {
5594 let (resolver, spec) = resolver_single_spec(
5595 r#"spec test
5596 data money: measure -> unit eur: 1
5597 data money2: money -> unit usd: 1.24"#,
5598 );
5599
5600 let result = resolver.resolve_and_validate(spec, &EffectiveDate::Origin, &Vec::new());
5601 assert!(
5602 result.is_ok(),
5603 "Measure extension chain should resolve: {:?}",
5604 result.err()
5605 );
5606
5607 let resolved = result.unwrap();
5608 assert!(
5609 resolved.unit_index.unique_owner("eur").is_some(),
5610 "eur should be in unit_index"
5611 );
5612 assert!(
5613 resolved.unit_index.unique_owner("usd").is_some(),
5614 "usd should be in unit_index"
5615 );
5616 let eur_type = resolved.unit_index.unique_owner("eur").unwrap();
5617 let usd_type = resolved.unit_index.unique_owner("usd").unwrap();
5618 assert_eq!(
5619 eur_type.name.as_deref(),
5620 Some("money"),
5621 "declarer money must own inherited eur, not extension"
5622 );
5623 assert_eq!(
5624 usd_type.name.as_deref(),
5625 Some("money2"),
5626 "usd defined on money2 should be owned by money2"
5627 );
5628 assert!(
5629 Arc::ptr_eq(eur_type, resolved.resolved.get("money").unwrap()),
5630 "bound eur owner must be the resolved money Arc"
5631 );
5632 assert!(
5633 Arc::ptr_eq(usd_type, resolved.resolved.get("money2").unwrap()),
5634 "bound usd owner must be the resolved money2 Arc"
5635 );
5636 }
5637
5638 #[test]
5639 fn test_invalid_parent_type_in_named_type_should_error() {
5640 let (resolver, spec) = resolver_single_spec(
5641 r#"spec test
5642 data invalid: nonexistent_type -> minimum 0"#,
5643 );
5644
5645 let result = resolver.resolve_and_validate(spec, &EffectiveDate::Origin, &Vec::new());
5646 assert!(result.is_err(), "Should reject invalid parent type");
5647
5648 let errs = result.unwrap_err();
5649 assert!(!errs.is_empty(), "expected at least one error");
5650 let error_msg = errs[0].to_string();
5651 assert!(
5652 error_msg.contains("Unknown parent") && error_msg.contains("nonexistent_type"),
5653 "Error should mention unknown type. Got: {}",
5654 error_msg
5655 );
5656 }
5657
5658 #[test]
5659 fn test_invalid_primitive_type_name_should_error() {
5660 let (resolver, spec) = resolver_single_spec(
5661 r#"spec test
5662 data invalid: choice -> option "a""#,
5663 );
5664
5665 let result = resolver.resolve_and_validate(spec, &EffectiveDate::Origin, &Vec::new());
5666 assert!(result.is_err(), "Should reject invalid type base 'choice'");
5667
5668 let errs = result.unwrap_err();
5669 assert!(!errs.is_empty(), "expected at least one error");
5670 let error_msg = errs[0].to_string();
5671 assert!(
5672 error_msg.contains("Unknown parent") && error_msg.contains("choice"),
5673 "Error should mention unknown type 'choice'. Got: {}",
5674 error_msg
5675 );
5676 }
5677
5678 #[test]
5679 fn extension_unit_factor_override_errors() {
5680 let (resolver, spec) = resolver_single_spec(
5681 r#"spec test
5682 data money: measure
5683 -> unit eur: 1
5684 data money2: money
5685 -> unit eur: 1.10"#,
5686 );
5687
5688 let result = resolver.resolve_and_validate(spec, &EffectiveDate::Origin, &Vec::new());
5689 assert!(
5690 result.is_err(),
5691 "extension child must not override inherited unit factor"
5692 );
5693 let error_msg = result
5694 .unwrap_err()
5695 .iter()
5696 .map(ToString::to_string)
5697 .collect::<Vec<_>>()
5698 .join("; ");
5699 assert!(
5700 error_msg.contains("eur"),
5701 "error must name unit eur, got: {error_msg}"
5702 );
5703 assert!(
5704 error_msg.contains("inherited") || error_msg.contains("cannot change"),
5705 "error must reject inherited unit redefinition, got: {error_msg}"
5706 );
5707 }
5708
5709 #[test]
5710 fn inherited_unit_idempotent_redeclare_ok() {
5711 let (resolver, spec) = resolver_single_spec(
5712 r#"spec test
5713 data money: measure
5714 -> unit eur: 1
5715 data money2: money
5716 -> unit eur: 1"#,
5717 );
5718
5719 let resolved = resolver
5720 .resolve_and_validate(spec, &EffectiveDate::Origin, &Vec::new())
5721 .expect("idempotent inherited unit redeclare must resolve");
5722 let money2 = resolved.resolved.get("money2").expect("money2");
5723 match &money2.specifications {
5724 TypeSpecification::Measure { units, .. } => {
5725 let eur = units.iter().find(|u| u.name == "eur").expect("eur");
5726 assert_eq!(
5727 eur.require_literal_factor().try_to_decimal().unwrap(),
5728 Decimal::ONE,
5729 "eur factor must remain 1"
5730 );
5731 }
5732 other => panic!("expected Measure, got {other:?}"),
5733 }
5734 }
5735
5736 #[test]
5737 fn extension_additive_unit_registers_in_unit_index() {
5738 let (resolver, spec) = resolver_single_spec(
5739 r#"spec test
5740 data money: measure
5741 -> unit eur: 1
5742 data money2: money
5743 -> unit usd: 1.24"#,
5744 );
5745
5746 let resolved = resolver
5747 .resolve_and_validate(spec, &EffectiveDate::Origin, &Vec::new())
5748 .expect("additive extension unit must resolve");
5749 let money = resolved
5750 .resolved
5751 .get("money")
5752 .expect("money resolved")
5753 .clone();
5754 let money2 = resolved
5755 .resolved
5756 .get("money2")
5757 .expect("money2 resolved")
5758 .clone();
5759 assert!(
5760 resolved.unit_index.unique_owner("eur").is_some(),
5761 "eur must be in unit_index"
5762 );
5763 assert!(
5764 resolved.unit_index.unique_owner("usd").is_some(),
5765 "usd must be in unit_index"
5766 );
5767 let eur_owner = resolved.unit_index.unique_owner("eur").expect("eur owner");
5768 let usd_owner = resolved.unit_index.unique_owner("usd").expect("usd owner");
5769 assert_eq!(
5770 eur_owner.name.as_deref(),
5771 Some("money"),
5772 "declarer money must own eur, not extension money2"
5773 );
5774 assert_eq!(
5775 usd_owner.name.as_deref(),
5776 Some("money2"),
5777 "money2 must own new unit usd"
5778 );
5779 assert_eq!(eur_owner.as_ref(), money.as_ref());
5780 assert_eq!(usd_owner.as_ref(), money2.as_ref());
5781 }
5782
5783 #[test]
5787 fn merged_import_owners_share_one_type_arc_per_type() {
5788 let code = r#"spec units
5789 data usd_per_eur: number
5790 data mass: measure
5791 -> unit kilogram: 1
5792 -> unit gram: 0.001
5793 -> unit tonne: 1000
5794 data money: measure
5795 -> unit eur: 1
5796 -> unit cent: 0.01
5797 -> unit usd: usd_per_eur
5798
5799 spec consumer
5800 uses u: units
5801 "#;
5802 let (resolver, spec_arcs) = resolver_for_code(code);
5803 let units_arc = spec_arcs
5804 .iter()
5805 .find(|spec| spec.name == "units")
5806 .cloned()
5807 .expect("units spec");
5808 let consumer_arc = spec_arcs
5809 .iter()
5810 .find(|spec| spec.name == "consumer")
5811 .cloned()
5812 .expect("consumer spec");
5813 let (context, _) = test_context_and_effective(&spec_arcs);
5814 let repository = context.workspace();
5815
5816 let mut already_resolved = ResolvedTypesMap::new();
5817 let units_types = resolver
5818 .resolve_and_validate(units_arc, &EffectiveDate::Origin, &already_resolved)
5819 .expect("units spec resolves");
5820 let declared_mass = units_types
5821 .unit_index
5822 .unique_owner("kilogram")
5823 .expect("kilogram in units")
5824 .clone();
5825 already_resolved.push((Arc::clone(&repository), units_arc, Arc::new(units_types)));
5826 let consumer_types = resolver
5827 .resolve_and_validate(consumer_arc, &EffectiveDate::Origin, &already_resolved)
5828 .expect("consumer spec resolves");
5829 let owner = |bare: &str| {
5830 consumer_types
5831 .unit_index
5832 .unique_owner(bare)
5833 .unwrap_or_else(|| panic!("{bare} has one owner in consumer"))
5834 .clone()
5835 };
5836
5837 let mass = owner("kilogram");
5838 assert!(
5839 Arc::ptr_eq(&mass, &declared_mass),
5840 "a type without dynamic units is shared, not cloned"
5841 );
5842 assert!(Arc::ptr_eq(&mass, &owner("gram")));
5843 assert!(Arc::ptr_eq(&mass, &owner("tonne")));
5844
5845 let money = owner("eur");
5846 assert!(money.has_dynamic_units());
5847 assert!(
5848 Arc::ptr_eq(&money, &owner("cent")) && Arc::ptr_eq(&money, &owner("usd")),
5849 "every unit of one dynamic type shares the one rewrite"
5850 );
5851 }
5852
5853 #[test]
5854 fn unit_index_maps_family_root_not_binding_alias() {
5855 let code = r#"spec units
5856 data money: measure
5857 -> unit eur: 1
5858 data mass: measure
5859 -> unit kg: 1
5860 data price_per_weight: measure
5861 -> unit eur_per_kg: eur/kg
5862
5863 spec consumer
5864 uses u: units
5865 data starch_levy_per_kg: u.price_per_weight
5866 -> suggest 0.1 eur_per_kg
5867 data amortization_per_kg: u.price_per_weight
5868 -> suggest 0.2 eur_per_kg
5869 "#;
5870 let (resolver, spec_arcs) = resolver_for_code(code);
5871 let units_arc = spec_arcs
5872 .iter()
5873 .find(|spec| spec.name == "units")
5874 .cloned()
5875 .expect("units spec");
5876 let consumer_arc = spec_arcs
5877 .iter()
5878 .find(|spec| spec.name == "consumer")
5879 .cloned()
5880 .expect("consumer spec");
5881 let (context, _) = test_context_and_effective(&spec_arcs);
5882 let repository = context.workspace();
5883
5884 let mut already_resolved = ResolvedTypesMap::new();
5885 let units_types = resolver
5886 .resolve_and_validate(units_arc, &EffectiveDate::Origin, &already_resolved)
5887 .expect("units spec resolves");
5888 let units_price_per_weight = units_types
5889 .resolved
5890 .get("price_per_weight")
5891 .expect("units defines price_per_weight")
5892 .clone();
5893 already_resolved.push((Arc::clone(&repository), units_arc, Arc::new(units_types)));
5894
5895 let consumer_types = resolver
5896 .resolve_and_validate(consumer_arc, &EffectiveDate::Origin, &already_resolved)
5897 .expect("consumer spec resolves");
5898
5899 let eur_per_kg_owner = consumer_types
5900 .unit_index
5901 .unique_owner("eur_per_kg")
5902 .expect("eur_per_kg in unit_index");
5903 assert_eq!(
5904 eur_per_kg_owner.name.as_deref(),
5905 Some("price_per_weight"),
5906 "unit must belong to family root, not binding alias row name"
5907 );
5908 assert_eq!(
5909 eur_per_kg_owner.measure_family_name(),
5910 Some("price_per_weight")
5911 );
5912 assert_eq!(eur_per_kg_owner.as_ref(), units_price_per_weight.as_ref());
5913
5914 let starch_alias = consumer_types
5915 .resolved
5916 .get("starch_levy_per_kg")
5917 .expect("alias row in resolved");
5918 assert!(
5919 !std::ptr::eq(eur_per_kg_owner.as_ref(), starch_alias.as_ref()),
5920 "unit_index must not store binding alias arc"
5921 );
5922 }
5923
5924 #[test]
5925 fn same_named_local_root_does_not_hide_imported_units() {
5926 let code = r#"spec std_units
5927 data mass: measure
5928 -> unit kilogram: 1
5929 -> unit kilograms: 1
5930 -> unit gram: 0.001
5931
5932 spec s
5933 uses u: std_units
5934 data mass: measure
5935 -> unit kg: 1
5936 -> unit tonne: 1000
5937 rule smoke: true
5938 "#;
5939 let (resolver, spec_arcs) = resolver_for_code(code);
5940 let std_units_arc = spec_arcs
5941 .iter()
5942 .find(|spec| spec.name == "std_units")
5943 .cloned()
5944 .expect("std_units spec");
5945 let consumer_arc = spec_arcs
5946 .iter()
5947 .find(|spec| spec.name == "s")
5948 .cloned()
5949 .expect("consumer spec");
5950 let (context, _) = test_context_and_effective(&spec_arcs);
5951 let repository = context.workspace();
5952
5953 let mut already_resolved = ResolvedTypesMap::new();
5954 let std_units_types = resolver
5955 .resolve_and_validate(std_units_arc, &EffectiveDate::Origin, &already_resolved)
5956 .expect("std_units resolves");
5957 already_resolved.push((
5958 Arc::clone(&repository),
5959 std_units_arc,
5960 Arc::new(std_units_types),
5961 ));
5962
5963 let consumer_types = resolver
5964 .resolve_and_validate(consumer_arc, &EffectiveDate::Origin, &already_resolved)
5965 .expect("consumer resolves");
5966
5967 let local_mass = consumer_types
5968 .resolved
5969 .get("mass")
5970 .expect("consumer defines mass")
5971 .clone();
5972
5973 assert!(
5974 consumer_types.unit_index.unique_owner("kg").is_some(),
5975 "local kg must be indexed"
5976 );
5977 assert!(
5978 consumer_types.unit_index.unique_owner("tonne").is_some(),
5979 "local tonne must be indexed"
5980 );
5981 for imported_unit in ["kilogram", "kilograms", "gram"] {
5982 let owner = consumer_types
5983 .unit_index
5984 .unique_owner(imported_unit)
5985 .unwrap_or_else(|| panic!("imported {imported_unit} must stay in scope"));
5986 assert_eq!(
5987 owner.measure_family().map(|family| family.spec.as_str()),
5988 Some("std_units"),
5989 "{imported_unit} must belong to std_units.mass, not the local mass"
5990 );
5991 }
5992
5993 let kg_owner = consumer_types
5994 .unit_index
5995 .unique_owner("kg")
5996 .expect("kg owner");
5997 let tonne_owner = consumer_types
5998 .unit_index
5999 .unique_owner("tonne")
6000 .expect("tonne owner");
6001 assert_eq!(kg_owner.as_ref(), local_mass.as_ref());
6002 assert_eq!(tonne_owner.as_ref(), local_mass.as_ref());
6003 }
6004
6005 #[test]
6006 fn same_family_same_unit_same_factor_is_idempotent() {
6007 let code = r#"spec units_a
6008 data duration: measure
6009 -> unit hour: 1
6010
6011 spec consumer
6012 uses a: units_a
6013 uses b: units_a
6014 rule smoke: true
6015 "#;
6016 let (resolver, spec_arcs) = resolver_for_code(code);
6017 let units_a_arc = spec_arcs
6018 .iter()
6019 .find(|spec| spec.name == "units_a")
6020 .cloned()
6021 .expect("units_a spec");
6022 let consumer_arc = spec_arcs
6023 .iter()
6024 .find(|spec| spec.name == "consumer")
6025 .cloned()
6026 .expect("consumer spec");
6027 let (context, _) = test_context_and_effective(&spec_arcs);
6028 let repository = context.workspace();
6029
6030 let mut already_resolved = ResolvedTypesMap::new();
6031 let units_a_types = resolver
6032 .resolve_and_validate(units_a_arc, &EffectiveDate::Origin, &already_resolved)
6033 .expect("units_a resolves");
6034 already_resolved.push((
6035 Arc::clone(&repository),
6036 units_a_arc,
6037 Arc::new(units_a_types),
6038 ));
6039
6040 let consumer_types = resolver
6041 .resolve_and_validate(consumer_arc, &EffectiveDate::Origin, &already_resolved)
6042 .expect("double import of same duration must be idempotent");
6043
6044 assert_eq!(
6045 consumer_types.unit_index.owners_for("hour").len(),
6046 2,
6047 "each import path keeps its hour owner"
6048 );
6049 consumer_types
6050 .unit_index
6051 .resolve("hour")
6052 .expect("bare hour collapses across identical import paths");
6053 }
6054
6055 #[test]
6056 fn different_version_families_keep_separate_hour_owners() {
6057 let code = r#"spec units 2024-01-01
6060 data duration: measure
6061 -> unit hour: 1
6062
6063 spec units 2025-01-01
6064 data duration: measure
6065 -> unit hour: 60
6066
6067 spec consumer
6068 uses a: units 2024-01-01
6069 uses b: units 2025-01-01
6070 rule smoke: true
6071 "#;
6072 let (resolver, spec_arcs) = resolver_for_code(code);
6073 let consumer_arc = spec_arcs
6074 .iter()
6075 .find(|spec| spec.name == "consumer")
6076 .cloned()
6077 .expect("consumer spec");
6078 let (context, _) = test_context_and_effective(&spec_arcs);
6079 let repository = context.workspace();
6080
6081 let mut already_resolved = ResolvedTypesMap::new();
6082 for units_arc in spec_arcs.iter().filter(|spec| spec.name == "units") {
6083 let units_types = resolver
6084 .resolve_and_validate(units_arc, &units_arc.effective_from, &already_resolved)
6085 .expect("units version resolves");
6086 already_resolved.push((Arc::clone(&repository), units_arc, Arc::new(units_types)));
6087 }
6088
6089 let consumer_types = resolver
6090 .resolve_and_validate(consumer_arc, &EffectiveDate::Origin, &already_resolved)
6091 .expect("different version families resolve without merge conflict");
6092 assert_eq!(
6093 consumer_types.unit_index.owners_for("hour").len(),
6094 2,
6095 "each version keeps its own hour owner"
6096 );
6097 }
6098
6099 #[test]
6100 fn test_spec_level_same_unit_names_keep_every_declarer() {
6101 let (resolver, spec) = resolver_single_spec(
6102 r#"spec test
6103 data money_a: measure
6104 -> unit eur: 1.00
6105 -> unit usd: 0.84
6106
6107 data money_b: measure
6108 -> unit eur: 1.00
6109 -> unit usd: 1.20
6110
6111 data length_a: measure
6112 -> unit meter: 1.0
6113
6114 data length_b: measure
6115 -> unit meter: 1.0"#,
6116 );
6117
6118 let resolved = resolver
6119 .resolve_and_validate(spec, &EffectiveDate::Origin, &Vec::new())
6120 .expect("independent declarers of one unit name must load");
6121 assert_eq!(
6122 resolved.unit_index.owners_for("eur").len(),
6123 2,
6124 "every declarer of 'eur' stays in scope"
6125 );
6126 assert!(
6127 resolved.unit_index.resolve("eur").is_err(),
6128 "bare 'eur' with two declarers must be qualified"
6129 );
6130 assert_eq!(
6131 resolved.unit_index.owners_for("usd").len(),
6132 2,
6133 "every declarer of 'usd' stays in scope"
6134 );
6135 assert!(
6136 resolved.unit_index.resolve("usd").is_err(),
6137 "bare 'usd' with two declarers must be qualified"
6138 );
6139 assert_eq!(
6140 resolved.unit_index.owners_for("meter").len(),
6141 2,
6142 "every declarer of 'meter' stays in scope"
6143 );
6144 assert!(
6145 resolved.unit_index.resolve("meter").is_err(),
6146 "bare 'meter' with two declarers must be qualified"
6147 );
6148 let (_, owner) = resolved
6149 .unit_index
6150 .resolve("money_b.usd")
6151 .expect("qualified unit must resolve");
6152 assert_eq!(owner.name(), "money_b");
6153 }
6154
6155 #[test]
6156 fn test_measure_and_ratio_sharing_a_unit_name_keep_both_declarers() {
6157 let (resolver, spec) = resolver_single_spec(
6158 r#"spec test
6159 data q: measure
6160 -> unit foo: 1
6161
6162 data r: ratio
6163 -> unit foo: 100"#,
6164 );
6165
6166 let resolved = resolver
6167 .resolve_and_validate(spec, &EffectiveDate::Origin, &Vec::new())
6168 .expect("independent declarers of one unit name must load");
6169 assert_eq!(
6170 resolved.unit_index.owners_for("foo").len(),
6171 2,
6172 "every declarer of 'foo' stays in scope"
6173 );
6174 assert!(
6175 resolved.unit_index.resolve("foo").is_err(),
6176 "bare 'foo' with two declarers must be qualified"
6177 );
6178 let (_, owner) = resolved
6179 .unit_index
6180 .resolve("r.foo")
6181 .expect("qualified unit must resolve");
6182 assert_eq!(owner.name(), "r");
6183 }
6184
6185 #[test]
6186 fn test_same_ratio_unit_across_types_keeps_both_declarers() {
6187 let (resolver, spec) = resolver_single_spec(
6188 r#"spec test
6189 data spread_a: ratio
6190 -> unit basis_points: 10000
6191
6192 data spread_b: ratio
6193 -> unit basis_points: 10000"#,
6194 );
6195
6196 let resolved = resolver
6197 .resolve_and_validate(spec, &EffectiveDate::Origin, &Vec::new())
6198 .expect("independent declarers of one unit name must load");
6199 assert_eq!(
6200 resolved.unit_index.owners_for("basis_points").len(),
6201 2,
6202 "every declarer of 'basis_points' stays in scope"
6203 );
6204 assert!(
6205 resolved.unit_index.resolve("basis_points").is_err(),
6206 "bare 'basis_points' with two declarers must be qualified"
6207 );
6208 let (_, owner) = resolved
6209 .unit_index
6210 .resolve("spread_a.basis_points")
6211 .expect("qualified unit must resolve");
6212 assert_eq!(owner.name(), "spread_a");
6213 }
6214
6215 #[test]
6216 fn test_different_ratio_unit_factor_across_types_keeps_both_declarers() {
6217 let (resolver, spec) = resolver_single_spec(
6218 r#"spec test
6219 data spread_a: ratio
6220 -> unit basis_points: 10000
6221
6222 data spread_b: ratio
6223 -> unit basis_points: 5000"#,
6224 );
6225
6226 let resolved = resolver
6227 .resolve_and_validate(spec, &EffectiveDate::Origin, &Vec::new())
6228 .expect("independent declarers of one unit name must load");
6229 assert_eq!(
6230 resolved.unit_index.owners_for("basis_points").len(),
6231 2,
6232 "every declarer of 'basis_points' stays in scope"
6233 );
6234 assert!(
6235 resolved.unit_index.resolve("basis_points").is_err(),
6236 "bare 'basis_points' with two declarers must be qualified"
6237 );
6238 let (_, owner) = resolved
6239 .unit_index
6240 .resolve("spread_b.basis_points")
6241 .expect("qualified unit must resolve");
6242 assert_eq!(owner.name(), "spread_b");
6243 }
6244
6245 #[test]
6246 fn test_multiple_builtin_ratio_types_share_percent_in_unit_index() {
6247 let (resolver, spec) = resolver_single_spec(
6248 r#"spec targets
6249 data standard_margin_pct: ratio
6250 -> minimum 0%
6251 -> suggest 15%
6252
6253 data default_credit_insurance_pct: ratio
6254 -> suggest 1.5%"#,
6255 );
6256
6257 resolver
6258 .resolve_and_validate(spec, &EffectiveDate::Origin, &Vec::new())
6259 .expect("multiple ratio types with built-in percent must not conflict");
6260 }
6261
6262 #[test]
6263 fn test_three_ratio_types_share_builtin_and_custom_unit() {
6264 let (resolver, spec) = resolver_single_spec(
6265 r#"spec test
6266 data margin: ratio -> suggest 10%
6267 data fee: ratio
6268 -> unit tenths: 10
6269 data tax: ratio -> suggest 1%"#,
6270 );
6271
6272 resolver
6273 .resolve_and_validate(spec, &EffectiveDate::Origin, &Vec::new())
6274 .expect("builtin percent/permille plus custom tenths on second type must load");
6275 }
6276
6277 #[test]
6278 fn test_ratio_unit_index_allows_builtin_after_two_named_types() {
6279 let (resolver, spec) = resolver_single_spec(
6280 r#"spec test
6281 data first_ratio: ratio -> suggest 5%
6282 data second_ratio: ratio -> suggest 10%"#,
6283 );
6284
6285 let resolved = resolver
6286 .resolve_and_validate(spec, &EffectiveDate::Origin, &Vec::new())
6287 .expect("two ratio types with only builtin units");
6288
6289 let (_, percent) = resolved
6290 .unit_index
6291 .resolve("percent")
6292 .expect("bare percent binds PrimitiveRatio");
6293 assert_eq!(percent.name(), "ratio");
6294 let (_, permille) = resolved
6295 .unit_index
6296 .resolve("permille")
6297 .expect("bare permille binds PrimitiveRatio");
6298 assert_eq!(permille.name(), "ratio");
6299 }
6300
6301 #[test]
6302 fn test_number_type_cannot_have_units() {
6303 let (resolver, spec) = resolver_single_spec(
6304 r#"spec test
6305 data price: number
6306 -> unit eur: 1.00"#,
6307 );
6308
6309 let result = resolver.resolve_and_validate(spec, &EffectiveDate::Origin, &Vec::new());
6310 assert!(result.is_err(), "Number types must reject unit commands");
6311
6312 let errs = result.unwrap_err();
6313 assert!(!errs.is_empty(), "expected at least one error");
6314 let error_msg = errs[0].to_string();
6315 assert!(
6316 error_msg.contains("unit") && error_msg.contains("number"),
6317 "Error should mention units are invalid on number. Got: {}",
6318 error_msg
6319 );
6320 }
6321
6322 #[test]
6323 fn test_extending_type_inherits_units() {
6324 let (resolver, spec) = resolver_single_spec(
6325 r#"spec test
6326 data money: measure
6327 -> unit eur: 1.00
6328 -> unit usd: 0.84
6329
6330 data my_money: money
6331 -> unit gbp: 1.30"#,
6332 );
6333
6334 let resolved = resolver
6335 .resolve_and_validate(spec, &EffectiveDate::Origin, &Vec::new())
6336 .unwrap();
6337 let my_money_type = resolved.resolved.get("my_money").unwrap();
6338
6339 match &my_money_type.specifications {
6340 TypeSpecification::Measure { units, .. } => {
6341 assert_eq!(units.len(), 3);
6342 assert!(units.iter().any(|u| u.name == "eur"));
6343 assert!(units.iter().any(|u| u.name == "usd"));
6344 assert!(units.iter().any(|u| u.name == "gbp"));
6345 }
6346 other => panic!("Expected Measure type specifications, got {:?}", other),
6347 }
6348 }
6349
6350 #[test]
6351 fn binding_unit_factor_override_errors() {
6352 let (resolver, spec) = resolver_single_spec(
6353 r#"spec test
6354 data source_measure: measure
6355 -> unit usd: 1.00
6356 data z: source_measure
6357 -> unit usd: 0.84"#,
6358 );
6359
6360 let result = resolver.resolve_and_validate(spec, &EffectiveDate::Origin, &Vec::new());
6361 assert!(
6362 result.is_err(),
6363 "binding row must not override inherited unit factor"
6364 );
6365 let error_msg = result
6366 .unwrap_err()
6367 .iter()
6368 .map(ToString::to_string)
6369 .collect::<Vec<_>>()
6370 .join("; ");
6371 assert!(
6372 error_msg.contains("usd"),
6373 "error must name unit usd, got: {error_msg}"
6374 );
6375 }
6376
6377 #[test]
6378 fn ratio_extension_unit_factor_override_errors() {
6379 let (resolver, spec) = resolver_single_spec(
6380 r#"spec test
6381 data parent: ratio
6382 -> unit basis: 1
6383 data child: parent
6384 -> unit basis: 100"#,
6385 );
6386
6387 let result = resolver.resolve_and_validate(spec, &EffectiveDate::Origin, &Vec::new());
6388 assert!(
6389 result.is_err(),
6390 "ratio extension must not override inherited unit factor"
6391 );
6392 let error_msg = result
6393 .unwrap_err()
6394 .iter()
6395 .map(ToString::to_string)
6396 .collect::<Vec<_>>()
6397 .join("; ");
6398 assert!(
6399 error_msg.contains("basis"),
6400 "error must name unit basis, got: {error_msg}"
6401 );
6402 }
6403
6404 #[test]
6405 fn test_duplicate_unit_name_in_same_type_is_error() {
6406 let (resolver, spec) = resolver_single_spec(
6407 r#"spec test
6408 data money: measure
6409 -> unit eur: 1.00
6410 -> unit eur: 1.19"#,
6411 );
6412
6413 let result = resolver.resolve_and_validate(spec, &EffectiveDate::Origin, &Vec::new());
6414 assert!(result.is_err(), "duplicate unit name must be rejected");
6415 let errs = result.unwrap_err();
6416 assert!(!errs.is_empty());
6417 let msg = errs[0].to_string();
6418 assert!(
6419 msg.contains("eur"),
6420 "error must name the duplicate unit; got: {msg}"
6421 );
6422 }
6423
6424 #[test]
6425 fn test_duplicate_unit_name_compound_is_error() {
6426 let (resolver, spec) = resolver_single_spec(
6427 r#"spec test
6428 data currency: measure
6429 -> unit usd: 1.00
6430 -> unit eur: 0.92
6431
6432 data time_period: measure
6433 -> unit year: 1
6434
6435 data run_rate: measure
6436 -> unit arr: usd/year
6437 -> unit arr: eur/year"#,
6438 );
6439
6440 let result = resolver.resolve_and_validate(spec, &EffectiveDate::Origin, &Vec::new());
6441 assert!(
6442 result.is_err(),
6443 "duplicate compound unit name must be rejected"
6444 );
6445 let errs = result.unwrap_err();
6446 assert!(!errs.is_empty());
6447 let msg = errs[0].to_string();
6448 assert!(
6449 msg.contains("arr"),
6450 "error must name the duplicate unit; got: {msg}"
6451 );
6452 }
6453
6454 #[test]
6455 fn find_unique_reports_multiple_families_with_same_decomposition() {
6456 let code = r#"spec units
6457 data money: measure
6458 -> unit eur: 1
6459 -> unit usd: 0.86
6460 data mass: measure
6461 -> unit kg: 1
6462 data price_eur_per_kg: measure
6463 -> unit eur_per_kg: eur/kg
6464 data price_usd_per_kg: measure
6465 -> unit usd_per_kg: usd/kg
6466 "#;
6467 let (resolver, spec_arcs) = resolver_for_code(code);
6468 let units_arc = spec_arcs
6469 .iter()
6470 .find(|spec| spec.name == "units")
6471 .cloned()
6472 .expect("units spec");
6473 let (context, _) = test_context_and_effective(&spec_arcs);
6474 let repository = context.workspace();
6475 let resolved = resolver
6476 .resolve_and_validate(units_arc, &EffectiveDate::Origin, &ResolvedTypesMap::new())
6477 .expect("units resolves");
6478 let eur_decomp = resolved
6479 .unit_index
6480 .unique_owner("eur_per_kg")
6481 .expect("eur_per_kg")
6482 .measure_type_decomposition()
6483 .expect("eur_per_kg decomposition")
6484 .clone();
6485 let map = [(repository, units_arc, resolved)];
6486
6487 let units_types = map
6488 .iter()
6489 .find(|(_, s, _)| discovery::same_loaded_spec(s, units_arc))
6490 .map(|(_, _, t)| t)
6491 .expect("units in map");
6492 let unique =
6493 find_unique_measure_type_in_unit_index(&units_types.unit_index, &eur_decomp);
6494 match unique {
6495 DecompositionMatch::Multiple(families) => {
6496 assert_eq!(families.len(), 2);
6497 assert!(families.contains(&"price_eur_per_kg".to_string()));
6498 assert!(families.contains(&"price_usd_per_kg".to_string()));
6499 }
6500 other => panic!("expected Multiple families, got {other:?}"),
6501 }
6502 }
6503 }
6504
6505 mod type_validation {
6506 use super::*;
6507 use crate::computation::rational::rational_new;
6508 use crate::literals::UnitScale;
6509 use crate::parsing::ast::{CommandArg, TypeConstraintCommand};
6510 use crate::planning::semantics::TypeSpecification;
6511 use rust_decimal::Decimal;
6512
6513 fn test_source() -> Source {
6514 Source::new(
6515 crate::parsing::source::SourceType::Volatile,
6516 crate::parsing::ast::Span {
6517 start: 0,
6518 end: 0,
6519 line: 1,
6520 col: 0,
6521 },
6522 )
6523 }
6524
6525 fn apply(
6526 mut specs: TypeSpecification,
6527 command: TypeConstraintCommand,
6528 args: &[CommandArg],
6529 ) -> TypeSpecification {
6530 let mut suggestion: Option<RawSuggestion> = None;
6531 specs
6532 .apply_constraint(
6533 ConstraintNames {
6534 type_name: "test",
6535 data_name: "test",
6536 },
6537 command,
6538 args,
6539 &mut suggestion,
6540 &mut None,
6541 None,
6542 )
6543 .unwrap();
6544 specs
6545 }
6546
6547 fn number_arg(n: i64) -> CommandArg {
6548 CommandArg::Literal(crate::literals::Value::Number(Decimal::from(n)))
6549 }
6550
6551 fn date_arg(s: &str) -> CommandArg {
6552 let dt = s.parse::<crate::literals::DateTimeValue>().expect("date");
6553 CommandArg::Literal(crate::literals::Value::Date(dt))
6554 }
6555
6556 fn time_arg(s: &str) -> CommandArg {
6557 let t = s.parse::<crate::literals::TimeValue>().expect("time");
6558 CommandArg::Literal(crate::literals::Value::Time(t))
6559 }
6560
6561 #[test]
6562 fn validate_number_minimum_greater_than_maximum() {
6563 let mut specs = TypeSpecification::number();
6564 specs = apply(specs, TypeConstraintCommand::Minimum, &[number_arg(100)]);
6565 specs = apply(specs, TypeConstraintCommand::Maximum, &[number_arg(50)]);
6566
6567 let src = test_source();
6568 let errors = validate_type_specifications(
6569 &specs,
6570 None,
6571 "suggestion",
6572 "test",
6573 &src,
6574 None,
6575 &UnitIndex::new(),
6576 );
6577 assert_eq!(errors.len(), 1);
6578 assert!(errors[0]
6579 .to_string()
6580 .contains("minimum 100 is greater than maximum 50"));
6581 }
6582
6583 #[test]
6584 fn validate_number_default_below_minimum() {
6585 let specs = TypeSpecification::Number {
6586 minimum: Some(rational_new(10, 1)),
6587 maximum: None,
6588 decimals: None,
6589 help: String::new(),
6590 };
6591 let default = BoundValueKind::unbound(ValueKind::Number(rational_new(5, 1)));
6592
6593 let src = test_source();
6594 let errors = validate_type_specifications(
6595 &specs,
6596 Some(&default),
6597 "suggestion",
6598 "test",
6599 &src,
6600 None,
6601 &UnitIndex::new(),
6602 );
6603 assert_eq!(errors.len(), 1);
6604 assert!(errors[0]
6605 .to_string()
6606 .contains("suggestion value 5 is less than minimum 10"));
6607 }
6608
6609 #[test]
6610 fn validate_number_default_above_maximum() {
6611 let specs = TypeSpecification::Number {
6612 minimum: None,
6613 maximum: Some(rational_new(100, 1)),
6614 decimals: None,
6615 help: String::new(),
6616 };
6617 let default = BoundValueKind::unbound(ValueKind::Number(rational_new(150, 1)));
6618
6619 let src = test_source();
6620 let errors = validate_type_specifications(
6621 &specs,
6622 Some(&default),
6623 "suggestion",
6624 "test",
6625 &src,
6626 None,
6627 &UnitIndex::new(),
6628 );
6629 assert_eq!(errors.len(), 1);
6630 assert!(errors[0]
6631 .to_string()
6632 .contains("suggestion value 150 is greater than maximum 100"));
6633 }
6634
6635 #[test]
6636 fn validate_number_default_valid() {
6637 let specs = TypeSpecification::Number {
6638 minimum: Some(rational_new(0, 1)),
6639 maximum: Some(rational_new(100, 1)),
6640 decimals: None,
6641 help: String::new(),
6642 };
6643 let default = BoundValueKind::unbound(ValueKind::Number(rational_new(50, 1)));
6644
6645 let src = test_source();
6646 let errors = validate_type_specifications(
6647 &specs,
6648 Some(&default),
6649 "suggestion",
6650 "test",
6651 &src,
6652 None,
6653 &UnitIndex::new(),
6654 );
6655 assert!(errors.is_empty());
6656 }
6657
6658 #[test]
6659 fn validate_ratio_minimum_greater_than_maximum() {
6660 let specs = TypeSpecification::Ratio {
6661 minimum: Some(rational_new(2, 1)),
6662 maximum: Some(rational_new(1, 1)),
6663 units: crate::planning::semantics::RatioUnits::new(),
6664 unit: None,
6665 help: String::new(),
6666 };
6667
6668 let src = test_source();
6669 let errors = validate_type_specifications(
6670 &specs,
6671 None,
6672 "suggestion",
6673 "test",
6674 &src,
6675 None,
6676 &UnitIndex::new(),
6677 );
6678 assert_eq!(errors.len(), 1);
6679 assert!(errors[0]
6680 .to_string()
6681 .contains("minimum 2 is greater than maximum 1"));
6682 }
6683
6684 #[test]
6685 fn validate_date_minimum_after_maximum() {
6686 let mut specs = TypeSpecification::date();
6687 specs = apply(
6688 specs,
6689 TypeConstraintCommand::Minimum,
6690 &[date_arg("2024-12-31")],
6691 );
6692 specs = apply(
6693 specs,
6694 TypeConstraintCommand::Maximum,
6695 &[date_arg("2024-01-01")],
6696 );
6697
6698 let src = test_source();
6699 let errors = validate_type_specifications(
6700 &specs,
6701 None,
6702 "suggestion",
6703 "test",
6704 &src,
6705 None,
6706 &UnitIndex::new(),
6707 );
6708 assert_eq!(errors.len(), 1);
6709 assert!(
6710 errors[0].to_string().contains("minimum")
6711 && errors[0].to_string().contains("is after maximum")
6712 );
6713 }
6714
6715 #[test]
6716 fn validate_date_valid_range() {
6717 let mut specs = TypeSpecification::date();
6718 specs = apply(
6719 specs,
6720 TypeConstraintCommand::Minimum,
6721 &[date_arg("2024-01-01")],
6722 );
6723 specs = apply(
6724 specs,
6725 TypeConstraintCommand::Maximum,
6726 &[date_arg("2024-12-31")],
6727 );
6728
6729 let src = test_source();
6730 let errors = validate_type_specifications(
6731 &specs,
6732 None,
6733 "suggestion",
6734 "test",
6735 &src,
6736 None,
6737 &UnitIndex::new(),
6738 );
6739 assert!(errors.is_empty());
6740 }
6741
6742 #[test]
6743 fn validate_time_minimum_after_maximum() {
6744 let mut specs = TypeSpecification::time();
6745 specs = apply(
6746 specs,
6747 TypeConstraintCommand::Minimum,
6748 &[time_arg("23:00:00")],
6749 );
6750 specs = apply(
6751 specs,
6752 TypeConstraintCommand::Maximum,
6753 &[time_arg("10:00:00")],
6754 );
6755
6756 let src = test_source();
6757 let errors = validate_type_specifications(
6758 &specs,
6759 None,
6760 "suggestion",
6761 "test",
6762 &src,
6763 None,
6764 &UnitIndex::new(),
6765 );
6766 assert_eq!(errors.len(), 1);
6767 assert!(
6768 errors[0].to_string().contains("minimum")
6769 && errors[0].to_string().contains("is after maximum")
6770 );
6771 }
6772
6773 fn magnitude_beyond_decimal_max() -> crate::computation::rational::RationalInteger {
6774 use crate::computation::rational::{decimal_to_rational, rational_new, try_mul};
6775 use rust_decimal::Decimal;
6776 let max = Decimal::MAX.normalize();
6777 let max_rational = decimal_to_rational(max).expect("BUG: Decimal::MAX must lift to Q");
6778 try_mul(&max_rational, &rational_new(2, 1))
6779 .expect("BUG: test rational multiply must succeed")
6780 }
6781
6782 #[test]
6783 fn large_magnitude_minimum_does_not_fail_type_validation() {
6784 use crate::computation::rational::rational_one;
6785 use crate::literals::MeasureUnits;
6786 use crate::planning::semantics::TypeSpecification;
6787
6788 let too_large = magnitude_beyond_decimal_max();
6789 assert_eq!(
6790 too_large.try_to_decimal().unwrap_err(),
6791 crate::computation::rational::NumericFailure::Overflow,
6792 );
6793
6794 let spec = TypeSpecification::Measure {
6795 minimum: Some((too_large, "eur".to_string())),
6796 maximum: None,
6797 units: MeasureUnits(vec![crate::literals::MeasureUnit {
6798 name: "eur".to_string(),
6799 scale: UnitScale::Literal(rational_one()),
6800 derived_measure_factors: Default::default(),
6801 decomposition: Default::default(),
6802 minimum: None,
6803 maximum: None,
6804 suggestion_magnitude: None,
6805 }]),
6806 traits: vec![],
6807 decomposition: None,
6808 unit: None,
6809 help: String::new(),
6810 };
6811
6812 let src = test_source();
6813 let errors = validate_type_specifications(
6814 &spec,
6815 None,
6816 "suggestion",
6817 "money",
6818 &src,
6819 None,
6820 &UnitIndex::new(),
6821 );
6822 assert!(
6823 errors.is_empty(),
6824 "internal Q bounds must not fail type validation; API decimal rounding: {:?}",
6825 errors.iter().map(|e| e.to_string()).collect::<Vec<_>>()
6826 );
6827 }
6828
6829 #[test]
6830 fn large_magnitude_maximum_does_not_fail_type_validation() {
6831 use crate::computation::rational::rational_one;
6832 use crate::literals::MeasureUnits;
6833 use crate::planning::semantics::TypeSpecification;
6834
6835 let too_large = magnitude_beyond_decimal_max();
6836 assert_eq!(
6837 too_large.try_to_decimal().unwrap_err(),
6838 crate::computation::rational::NumericFailure::Overflow,
6839 );
6840
6841 let spec = TypeSpecification::Measure {
6842 minimum: None,
6843 maximum: Some((too_large, "eur".to_string())),
6844 units: MeasureUnits(vec![crate::literals::MeasureUnit {
6845 name: "eur".to_string(),
6846 scale: UnitScale::Literal(rational_one()),
6847 derived_measure_factors: Default::default(),
6848 decomposition: Default::default(),
6849 minimum: None,
6850 maximum: None,
6851 suggestion_magnitude: None,
6852 }]),
6853 traits: vec![],
6854 decomposition: None,
6855 unit: None,
6856 help: String::new(),
6857 };
6858
6859 let src = test_source();
6860 let errors = validate_type_specifications(
6861 &spec,
6862 None,
6863 "suggestion",
6864 "money",
6865 &src,
6866 None,
6867 &UnitIndex::new(),
6868 );
6869 assert!(errors.is_empty(), "got: {:?}", errors);
6870 }
6871
6872 #[test]
6873 fn large_magnitude_default_does_not_fail_type_validation() {
6874 use crate::computation::rational::rational_one;
6875 use crate::literals::MeasureUnits;
6876 use crate::planning::semantics::TypeSpecification;
6877
6878 let too_large = magnitude_beyond_decimal_max();
6879 assert_eq!(
6880 too_large.try_to_decimal().unwrap_err(),
6881 crate::computation::rational::NumericFailure::Overflow,
6882 );
6883
6884 let spec = TypeSpecification::Measure {
6885 minimum: None,
6886 maximum: None,
6887 units: MeasureUnits(vec![crate::literals::MeasureUnit {
6888 name: "eur".to_string(),
6889 scale: UnitScale::Literal(rational_one()),
6890 derived_measure_factors: Default::default(),
6891 decomposition: Default::default(),
6892 minimum: None,
6893 maximum: None,
6894 suggestion_magnitude: Some(too_large),
6895 }]),
6896 traits: vec![],
6897 decomposition: None,
6898 unit: None,
6899 help: String::new(),
6900 };
6901
6902 let src = test_source();
6903 let errors = validate_type_specifications(
6904 &spec,
6905 None,
6906 "suggestion",
6907 "money",
6908 &src,
6909 None,
6910 &UnitIndex::new(),
6911 );
6912 assert!(errors.is_empty(), "got: {:?}", errors);
6913 }
6914
6915 #[test]
6916 fn refresh_named_range_specs_missing_element_must_not_leave_unconverted_measure() {
6917 use crate::engine::Context;
6918 use crate::parsing::ast::{LemmaSpec, ParentType, Span};
6919 use crate::parsing::source::{Source, SourceType};
6920 use crate::planning::semantics::tests::primitive_measure_arc;
6921
6922 let mut ctx = Context::new();
6923 let repository = ctx.workspace();
6924 ctx.insert_spec(Arc::clone(&repository), LemmaSpec::new("t".to_string()))
6925 .unwrap();
6926 let ctx: &'static Context = Box::leak(Box::new(ctx));
6927 let mut resolver = TypeResolver::new(ctx, HashMap::new());
6928 let spec = ctx
6929 .spec_set(&ctx.workspace(), "t")
6930 .and_then(|ss| ss.get_exact(None))
6931 .expect("inserted");
6932 assert!(resolver.register_all(&ctx.workspace(), spec).is_empty());
6933 let source = Source::new(
6934 SourceType::Volatile,
6935 Span {
6936 start: 0,
6937 end: 0,
6938 line: 1,
6939 col: 0,
6940 },
6941 );
6942 let mut data_defs = HashMap::new();
6943 data_defs.insert(
6944 "band".to_string(),
6945 DataTypeDef {
6946 parent: ParentType::Ranged {
6947 inner: Box::new(ParentType::custom("ghost")),
6948 },
6949 constraints: None,
6950 source: source.clone(),
6951 name: "band".to_string(),
6952 bound_literal: None,
6953 },
6954 );
6955 let mut resolved_types = ResolvedSpecTypes::default();
6956 resolved_types
6957 .resolved
6958 .insert("band".to_string(), primitive_measure_arc().clone());
6959 let already_resolved = ResolvedTypesMap::new();
6960
6961 let errors = refresh_named_range_specs(
6962 &resolver,
6963 spec,
6964 &data_defs,
6965 &mut resolved_types,
6966 &already_resolved,
6967 &EffectiveDate::Origin,
6968 );
6969
6970 assert!(
6971 !errors.is_empty(),
6972 "planning must error when ranged inner type is missing"
6973 );
6974 assert!(
6975 errors[0]
6976 .to_string()
6977 .contains("Unknown parent 'ghost' for data definition"),
6978 "got: {}",
6979 errors[0]
6980 );
6981 }
6982 }
6983}