1#[cfg(test)]
16mod test;
17
18#[cfg(test)]
19mod test_bound_read_once;
20
21#[cfg(test)]
22mod test_element_excludes_every_session;
23
24#[cfg(test)]
25mod test_rejected;
26
27use std::fmt;
28
29use tracing::{debug, instrument};
30
31use jiff::{Timestamp, civil};
32use rust_decimal::Decimal;
33
34use crate::{
35 Ampere, FromSchema, Kw, Kwh, Price, Weekday, country, currency, datetime,
36 duration::{self, Seconds},
37 from_warning_all, json, money, number,
38 schema::{self, HasElement as _, Integrity, OcpiEnum},
39 string,
40 tariff::{self, v2x::DimensionType},
41 warning,
42};
43
44pub(crate) fn lint(tariff: &tariff::Checked<'_>) -> Report {
52 let mut warnings = warning::Gatherer::new();
53
54 match tariff.schema() {
55 tariff::Version::V221(schema) => lint_v221(tariff, schema, &mut warnings),
56 tariff::Version::V211(schema) => lint_v211(tariff, schema, &mut warnings),
57 }
58
59 Report {
60 warnings: warnings.into_set(),
61 }
62}
63
64#[derive(Debug)]
66pub struct Report {
67 pub warnings: warning::Set<Warning>,
70}
71
72#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
77pub enum Warning {
78 ContainsEntireDay,
80
81 ContainsEntireWeek,
83
84 Country(country::Warning),
86
87 CpoCountryCodeShouldBeAlpha2,
89
90 Currency(currency::Warning),
92
93 DateTime(datetime::Warning),
95
96 DayOfWeekDuplicates,
98
99 DayOfWeekEmpty,
102
103 DayOfWeekUnsorted,
105
106 Duration(duration::Warning),
108
109 ElementExcludesEverySession(OtherElements),
125
126 ElementPricesMoreThanOneDimension,
137
138 EndTimeIsNearEndOfDay,
144
145 LowerBoundAtOrAboveUpper,
157
158 MaxZeroNeverMatch,
160
161 MinDurationZeroAllowsEverySession,
163
164 MinPriceIsGreaterThanMax,
166
167 MinZeroExcludesOnlyNegative,
170
171 NeverValid,
173
174 Money(money::Warning),
176
177 Number(number::Warning),
179
180 RestrictionsEmpty,
182
183 StartDateTimeIsAfterEndDateTime,
185
186 String(string::Warning),
188}
189
190#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
192pub enum OtherElements {
193 SomeMayMatch,
196
197 NoneMayMatch,
200
201 TariffRejected,
204}
205
206from_warning_all!(
207 country::Warning => Warning::Country,
208 currency::Warning => Warning::Currency,
209 datetime::Warning => Warning::DateTime,
210 duration::Warning => Warning::Duration,
211 money::Warning => Warning::Money,
212 number::Warning => Warning::Number,
213 string::Warning => Warning::String
214);
215
216impl crate::Warning for Warning {
217 fn id(&self) -> warning::Id {
218 match self {
219 Self::ContainsEntireDay => warning::Id::from_static("contains_entire_day"),
220 Self::ContainsEntireWeek => warning::Id::from_static("contains_entire_week"),
221 Self::Country(kind) => kind.id(),
222 Self::CpoCountryCodeShouldBeAlpha2 => {
223 warning::Id::from_static("cpo_country_code_should_be_alpha2")
224 }
225 Self::Currency(kind) => kind.id(),
226 Self::DateTime(kind) => kind.id(),
227 Self::DayOfWeekDuplicates => warning::Id::from_static("duplicates"),
228 Self::DayOfWeekEmpty => warning::Id::from_static("empty"),
229 Self::DayOfWeekUnsorted => warning::Id::from_static("unsorted"),
230 Self::Duration(kind) => kind.id(),
231 Self::ElementExcludesEverySession(_) => {
232 warning::Id::from_static("element_excludes_every_session")
233 }
234 Self::ElementPricesMoreThanOneDimension => {
235 warning::Id::from_static("element_prices_more_than_one_dimension")
236 }
237 Self::EndTimeIsNearEndOfDay => warning::Id::from_static("end_time_is_near_end_of_day"),
238 Self::LowerBoundAtOrAboveUpper => {
239 warning::Id::from_static("lower_bound_at_or_above_upper")
240 }
241 Self::MaxZeroNeverMatch => warning::Id::from_static("max_zero_will_never_match"),
242 Self::MinDurationZeroAllowsEverySession => {
243 warning::Id::from_static("min_duration_zero_allows_every_session")
244 }
245 Self::MinPriceIsGreaterThanMax => {
246 warning::Id::from_static("min_price_is_greater_than_max")
247 }
248 Self::MinZeroExcludesOnlyNegative => {
249 warning::Id::from_static("min_zero_excludes_only_negative")
250 }
251 Self::NeverValid => warning::Id::from_static("never_valid"),
252 Self::Money(kind) => kind.id(),
253 Self::Number(kind) => kind.id(),
254 Self::RestrictionsEmpty => warning::Id::from_static("restrictions_empty"),
255 Self::StartDateTimeIsAfterEndDateTime => {
256 warning::Id::from_static("start_date_time_is_after_end_date_time")
257 }
258 Self::String(kind) => kind.id(),
259 }
260 }
261
262 fn is_rejected(&self) -> bool {
265 match self {
266 Self::Country(kind) => kind.is_rejected(),
267 Self::Currency(kind) => kind.is_rejected(),
268 Self::DateTime(kind) => kind.is_rejected(),
269 Self::Duration(kind) => kind.is_rejected(),
270 Self::Money(kind) => kind.is_rejected(),
271 Self::Number(kind) => kind.is_rejected(),
272 Self::String(kind) => kind.is_rejected(),
273 Self::ContainsEntireDay
274 | Self::ContainsEntireWeek
275 | Self::CpoCountryCodeShouldBeAlpha2
276 | Self::DayOfWeekDuplicates
277 | Self::DayOfWeekEmpty
278 | Self::DayOfWeekUnsorted
279 | Self::ElementExcludesEverySession(_)
280 | Self::ElementPricesMoreThanOneDimension
281 | Self::EndTimeIsNearEndOfDay
282 | Self::LowerBoundAtOrAboveUpper
283 | Self::MaxZeroNeverMatch
284 | Self::MinDurationZeroAllowsEverySession
285 | Self::MinPriceIsGreaterThanMax
286 | Self::MinZeroExcludesOnlyNegative
287 | Self::NeverValid
288 | Self::RestrictionsEmpty
289 | Self::StartDateTimeIsAfterEndDateTime => false,
290 }
291 }
292}
293
294impl fmt::Display for Warning {
295 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
296 match self {
297 Self::ContainsEntireDay => f.write_str("The bounded time of day is the entire day."),
298 Self::ContainsEntireWeek => f.write_str(
299 "All days of the week are defined. You can simply leave out the \
300 `day_of_week` field.",
301 ),
302 Self::Country(kind) => fmt::Display::fmt(kind, f),
303 Self::CpoCountryCodeShouldBeAlpha2 => {
304 f.write_str("The value should be an alpha-2 ISO 3166-1 country code")
305 }
306 Self::Currency(kind) => fmt::Display::fmt(kind, f),
307 Self::DateTime(kind) => fmt::Display::fmt(kind, f),
308 Self::DayOfWeekDuplicates => f.write_str("There's at least one duplicate day."),
309 Self::DayOfWeekEmpty => f.write_str(
310 "An empty list of days restricts no day. You can simply leave out the \
311 `day_of_week` field.",
312 ),
313 Self::DayOfWeekUnsorted => f.write_str("The days are unsorted."),
314 Self::Duration(kind) => fmt::Display::fmt(kind, f),
315 Self::ElementExcludesEverySession(OtherElements::SomeMayMatch) => f.write_str(
316 "This element's restrictions exclude every session, so pricing never uses it.",
317 ),
318 Self::ElementExcludesEverySession(OtherElements::NoneMayMatch) => f.write_str(
319 "This element's restrictions exclude every session, so pricing never uses it. \
320 No other element may match a session either.",
321 ),
322 Self::ElementExcludesEverySession(OtherElements::TariffRejected) => f.write_str(
323 "This element's restrictions exclude every session, so pricing never uses it. \
324 Pricing also rejects the tariff as a whole.",
325 ),
326 Self::ElementPricesMoreThanOneDimension => f.write_str(
327 "This element prices more than one dimension. Pricing looks up each dimension \
328 separately, so it doesn't treat the element's components as a unit.",
329 ),
330 Self::EndTimeIsNearEndOfDay => f.write_str(
331 "The `end_time` restriction is set to `23:59`. The spec states: \"To stop at \
332 end of the day use: 00:00.\".",
333 ),
334 Self::LowerBoundAtOrAboveUpper => f.write_str(
335 "This upper bound is at or below the lower bound it pairs with, so the element \
336 never matches a session.",
337 ),
338 Self::MaxZeroNeverMatch => f.write_str(
339 "This element contains a zero `max_*` restriction and so will never match. \
340 This element can be removed.",
341 ),
342 Self::MinDurationZeroAllowsEverySession => f.write_str(
343 "A `min_duration` of `0` allows every session, which is what leaving the \
344 field out means.",
345 ),
346 Self::MinPriceIsGreaterThanMax => {
347 f.write_str("The `min_price` is greater than `max_price`.")
348 }
349 Self::MinZeroExcludesOnlyNegative => f.write_str(
350 "A lower bound of `0` excludes only a negative value. Removing the field \
351 would change what a session reporting one costs.",
352 ),
353 Self::NeverValid => f.write_str(
354 "The `start_time` and `end_time` are equal and so the element is never valid.",
355 ),
356 Self::Money(kind) => fmt::Display::fmt(kind, f),
357 Self::Number(kind) => fmt::Display::fmt(kind, f),
358 Self::RestrictionsEmpty => f.write_str(
359 "The `restrictions` object holds no restriction, which is what leaving it out \
360 means.",
361 ),
362 Self::StartDateTimeIsAfterEndDateTime => {
363 f.write_str("The `start_date_time` is after the `end_date_time`.")
364 }
365 Self::String(kind) => fmt::Display::fmt(kind, f),
366 }
367 }
368}
369
370#[instrument(skip_all)]
374fn lint_v221(
375 checked: &tariff::Checked<'_>,
376 tariff: &schema::v221::Tariff<'_>,
377 warnings: &mut dyn warning::Gather<Warning>,
378) {
379 if let Integrity::Ok(country_code) = &tariff.country_code {
380 lint_country_code(country_code, warnings);
381 }
382
383 if let Integrity::Ok(party_id) = &tariff.party_id {
384 lint_party_id(party_id, warnings);
385 }
386
387 if let Integrity::Ok(currency) = &tariff.currency {
388 lint_currency(currency, warnings);
389 }
390
391 lint_min_max_price(&tariff.min_price, &tariff.max_price, warnings);
392 lint_start_end_date_time(&tariff.start_date_time, &tariff.end_date_time, warnings);
393
394 if let Integrity::Ok(elements) = &tariff.elements {
395 let items = elements.element().value().as_array().unwrap_or(&[]);
402 let mut excluding_every_session = Vec::new();
403 let mut others = OtherElements::NoneMayMatch;
404
405 for (index, element) in elements.into_iter().enumerate() {
406 let Integrity::Ok(element) = element else {
407 continue;
408 };
409
410 let mut dimensions = Vec::new();
414
415 if let Integrity::Ok(components) = &element.price_components {
416 for component in components {
417 let Integrity::Ok(component) = component else {
418 continue;
419 };
420 let Integrity::Ok(dimension_type) = &component.dimension_type else {
421 continue;
422 };
423 dimensions.push(DimensionType::from(&dimension_type.value()));
424 }
425 }
426
427 lint_more_than_one_dimension(items.get(index), &dimensions, warnings);
428
429 let restrictions = match &element.restrictions {
430 Integrity::Ok(Some(restrictions)) => restrictions,
431 Integrity::Ok(None) => {
432 others = OtherElements::SomeMayMatch;
433 continue;
434 }
435 Integrity::Missing(_) | Integrity::Err(_) => continue,
436 };
437
438 lint_restrictions_empty(restrictions, warnings);
439 let start_time = lower_time(&restrictions.start_time, warnings);
440 let end_time = lower_time(&restrictions.end_time, warnings);
441 let times = lint_times(start_time, end_time, warnings);
442 lint_day_of_week(&restrictions.day_of_week, warnings);
443
444 let start_date = lower_date(&restrictions.start_date, warnings);
445 let end_date = lower_date(&restrictions.end_date, warnings);
446 let min_current = lower_number::<Ampere>(&restrictions.min_current, warnings);
447 let max_current = lower_number::<Ampere>(&restrictions.max_current, warnings);
448 let min_duration = lower_number::<Seconds>(&restrictions.min_duration, warnings);
449 let max_duration = lower_number::<Seconds>(&restrictions.max_duration, warnings);
450 let min_kwh = lower_number::<Kwh>(&restrictions.min_kwh, warnings);
451 let max_kwh = lower_number::<Kwh>(&restrictions.max_kwh, warnings);
452 let min_power = lower_number::<Kw>(&restrictions.min_power, warnings);
453 let max_power = lower_number::<Kw>(&restrictions.max_power, warnings);
454
455 lint_zero(max_current, Warning::MaxZeroNeverMatch, warnings);
456 lint_zero(max_duration, Warning::MaxZeroNeverMatch, warnings);
457 lint_zero(max_kwh, Warning::MaxZeroNeverMatch, warnings);
458 lint_zero(max_power, Warning::MaxZeroNeverMatch, warnings);
459 lint_zero(
460 min_duration,
461 Warning::MinDurationZeroAllowsEverySession,
462 warnings,
463 );
464 lint_min_zero(min_current, warnings);
465 lint_min_zero(min_kwh, warnings);
466 lint_min_zero(min_power, warnings);
467 let dates = lint_lower_bound_at_or_above_upper(start_date, end_date, warnings);
468 let durations =
469 lint_lower_bound_at_or_above_upper(min_duration, max_duration, warnings);
470 let kwh = lint_lower_bound_at_or_above_upper(min_kwh, max_kwh, warnings);
471
472 let exclusions = [
477 max_duration_exclusion(max_duration),
478 times,
479 dates,
480 durations,
481 kwh,
482 ];
483
484 if let Integrity::Ok(Some(_)) | Integrity::Err(_) = restrictions.reservation {
492 continue;
493 }
494
495 if exclusions.contains(&Exclusion::ExcludesEverySession) {
496 if let Some(item) = items.get(index) {
497 excluding_every_session.push(item);
498 }
499 } else {
500 others = OtherElements::SomeMayMatch;
501 }
502 }
503
504 lint_elements_excluding_every_session(checked, &excluding_every_session, others, warnings);
505 }
506}
507
508#[instrument(skip_all)]
515fn lint_v211(
516 checked: &tariff::Checked<'_>,
517 tariff: &schema::v211::Tariff<'_>,
518 warnings: &mut dyn warning::Gather<Warning>,
519) {
520 if let Integrity::Ok(currency) = &tariff.currency {
521 lint_currency(currency, warnings);
522 }
523
524 if let Integrity::Ok(elements) = &tariff.elements {
525 let items = elements.element().value().as_array().unwrap_or(&[]);
532 let mut excluding_every_session = Vec::new();
533 let mut others = OtherElements::NoneMayMatch;
534
535 for (index, element) in elements.into_iter().enumerate() {
536 let Integrity::Ok(element) = element else {
537 continue;
538 };
539
540 let mut dimensions = Vec::new();
544
545 if let Integrity::Ok(components) = &element.price_components {
546 for component in components {
547 let Integrity::Ok(component) = component else {
548 continue;
549 };
550 let Integrity::Ok(dimension_type) = &component.dimension_type else {
551 continue;
552 };
553 dimensions.push(DimensionType::from(&dimension_type.value()));
554 }
555 }
556
557 lint_more_than_one_dimension(items.get(index), &dimensions, warnings);
558
559 let restrictions = match &element.restrictions {
560 Integrity::Ok(Some(restrictions)) => restrictions,
561 Integrity::Ok(None) => {
562 others = OtherElements::SomeMayMatch;
563 continue;
564 }
565 Integrity::Missing(_) | Integrity::Err(_) => continue,
566 };
567
568 lint_restrictions_empty(restrictions, warnings);
569
570 let start_time = lower_time(&restrictions.start_time, warnings);
571 let end_time = lower_time(&restrictions.end_time, warnings);
572 let times = lint_times(start_time, end_time, warnings);
573 lint_day_of_week(&restrictions.day_of_week, warnings);
574
575 let start_date = lower_date(&restrictions.start_date, warnings);
577 let end_date = lower_date(&restrictions.end_date, warnings);
578 let min_duration = lower_number::<Seconds>(&restrictions.min_duration, warnings);
579 let max_duration = lower_number::<Seconds>(&restrictions.max_duration, warnings);
580 let min_kwh = lower_number::<Kwh>(&restrictions.min_kwh, warnings);
581 let max_kwh = lower_number::<Kwh>(&restrictions.max_kwh, warnings);
582 let min_power = lower_number::<Kw>(&restrictions.min_power, warnings);
583 let max_power = lower_number::<Kw>(&restrictions.max_power, warnings);
584
585 lint_zero(max_duration, Warning::MaxZeroNeverMatch, warnings);
586 lint_zero(max_kwh, Warning::MaxZeroNeverMatch, warnings);
587 lint_zero(max_power, Warning::MaxZeroNeverMatch, warnings);
588 lint_zero(
589 min_duration,
590 Warning::MinDurationZeroAllowsEverySession,
591 warnings,
592 );
593 lint_min_zero(min_kwh, warnings);
594 lint_min_zero(min_power, warnings);
595 let dates = lint_lower_bound_at_or_above_upper(start_date, end_date, warnings);
596 let durations =
597 lint_lower_bound_at_or_above_upper(min_duration, max_duration, warnings);
598 let kwh = lint_lower_bound_at_or_above_upper(min_kwh, max_kwh, warnings);
599
600 let exclusions = [
605 max_duration_exclusion(max_duration),
606 times,
607 dates,
608 durations,
609 kwh,
610 ];
611
612 if exclusions.contains(&Exclusion::ExcludesEverySession) {
613 if let Some(item) = items.get(index) {
614 excluding_every_session.push(item);
615 }
616 } else {
617 others = OtherElements::SomeMayMatch;
618 }
619 }
620
621 lint_elements_excluding_every_session(checked, &excluding_every_session, others, warnings);
622 }
623}
624
625#[instrument(skip_all)]
630fn lint_restrictions_empty<'buf>(
631 restrictions: &impl schema::HasElement<'buf>,
632 warnings: &mut dyn warning::Gather<Warning>,
633) {
634 let elem = restrictions.element();
635
636 let Some(fields) = elem.value().as_object_fields() else {
637 return;
638 };
639
640 if fields.is_empty() {
641 warnings.insert(elem, Warning::RestrictionsEmpty);
642 }
643}
644
645#[instrument(skip_all)]
649fn lint_more_than_one_dimension(
650 item: Option<&json::Element<'_>>,
651 dimensions: &[DimensionType],
652 warnings: &mut dyn warning::Gather<Warning>,
653) {
654 let Some(item) = item else {
655 return;
656 };
657
658 let Some((first, rest)) = dimensions.split_first() else {
659 return;
660 };
661
662 if rest.iter().any(|dimension| dimension != first) {
663 warnings.insert(item, Warning::ElementPricesMoreThanOneDimension);
664 }
665}
666
667#[instrument(skip_all)]
673fn lint_country_code(source: &schema::Str<'_>, warnings: &mut dyn warning::Gather<Warning>) {
674 let lowered = match country::CodeSet::from_schema(source, warnings) {
675 Ok(lowered) => lowered,
676 Err(error) => {
677 warnings.deescalate(error);
678 return;
679 }
680 };
681
682 debug!("code_set: {lowered:?}");
683
684 if let country::CodeSet::Alpha3(_) = lowered {
685 warnings.insert(source.element(), Warning::CpoCountryCodeShouldBeAlpha2);
686 }
687}
688
689type PartyId<'buf> = string::AsciiExactLen<'buf, 3>;
691
692#[instrument(skip_all)]
697fn lint_party_id(source: &schema::Str<'_>, warnings: &mut dyn warning::Gather<Warning>) {
698 let lowered = match PartyId::from_schema(source, warnings) {
699 Ok(lowered) => lowered,
700 Err(error) => {
701 warnings.deescalate(error);
702 return;
703 }
704 };
705
706 if source.value().lexical_issues().escapes {
711 return;
712 }
713
714 if lowered.chars().any(char::is_lowercase) {
715 warnings.insert(
716 source.element(),
717 Warning::String(string::Warning::IncorrectCase),
718 );
719 }
720}
721
722#[instrument(skip_all)]
727fn lint_currency(source: &schema::Str<'_>, warnings: &mut dyn warning::Gather<Warning>) {
728 let lowered = match currency::Code::from_schema(source, warnings) {
729 Ok(lowered) => lowered,
730 Err(error) => {
731 warnings.deescalate(error);
732 return;
733 }
734 };
735
736 debug!("code: {lowered:?}");
737}
738
739#[instrument(skip_all)]
744fn lint_min_max_price(
745 min_price: &Integrity<Option<schema::v221::Price<'_>>>,
746 max_price: &Integrity<Option<schema::v221::Price<'_>>>,
747 warnings: &mut dyn warning::Gather<Warning>,
748) {
749 let min = lower_price(min_price, warnings);
750 let max = lower_price(max_price, warnings);
751
752 let (Some((min, min_elem)), Some((max, _))) = (min, max) else {
753 return;
754 };
755
756 if min.exceeds_on_either_value(max) {
757 warnings.insert(min_elem, Warning::MinPriceIsGreaterThanMax);
758 }
759}
760
761fn lower_price<'a, 'buf>(
763 price: &'a Integrity<Option<schema::v221::Price<'buf>>>,
764 warnings: &mut dyn warning::Gather<Warning>,
765) -> Option<(Price, &'a json::Element<'buf>)> {
766 let Integrity::Ok(Some(price)) = price else {
767 return None;
768 };
769
770 let lowered = match Price::from_schema(price, warnings) {
771 Ok(lowered) => lowered,
772 Err(error) => {
773 warnings.deescalate(error);
774 return None;
775 }
776 };
777
778 Some((lowered, price.element()))
779}
780
781#[instrument(skip_all)]
786fn lint_start_end_date_time(
787 start_date_time: &Integrity<Option<schema::Str<'_>>>,
788 end_date_time: &Integrity<Option<schema::Str<'_>>>,
789 warnings: &mut dyn warning::Gather<Warning>,
790) {
791 let start = lower_date_time(start_date_time, warnings);
792 let end = lower_date_time(end_date_time, warnings);
793
794 let (Some((start, start_elem)), Some((end, _))) = (start, end) else {
795 return;
796 };
797
798 if start > end {
799 warnings.insert(start_elem, Warning::StartDateTimeIsAfterEndDateTime);
800 }
801}
802
803fn lower_date_time<'a, 'buf>(
805 date_time: &'a Integrity<Option<schema::Str<'buf>>>,
806 warnings: &mut dyn warning::Gather<Warning>,
807) -> Option<(Timestamp, &'a json::Element<'buf>)> {
808 let Integrity::Ok(Some(date_time)) = date_time else {
809 return None;
810 };
811
812 let lowered = match Timestamp::from_schema(date_time, warnings) {
813 Ok(lowered) => lowered,
814 Err(error) => {
815 warnings.deescalate(error);
816 return None;
817 }
818 };
819
820 Some((lowered, date_time.element()))
821}
822
823fn lower_date<'a, 'buf>(
825 date: &'a Integrity<Option<schema::Str<'buf>>>,
826 warnings: &mut dyn warning::Gather<Warning>,
827) -> Option<(civil::Date, &'a json::Element<'buf>)> {
828 let Integrity::Ok(Some(date)) = date else {
829 return None;
830 };
831
832 let lowered = match civil::Date::from_schema(date, warnings) {
833 Ok(lowered) => lowered,
834 Err(error) => {
835 warnings.deescalate(error);
836 return None;
837 }
838 };
839
840 Some((lowered, date.element()))
841}
842
843#[derive(Copy, Clone, Eq, PartialEq)]
848struct HourMin {
849 hour: i8,
850 min: i8,
851}
852
853const DAY_BOUNDARY: HourMin = HourMin { hour: 0, min: 0 };
855
856const NEAR_END_OF_DAY: HourMin = HourMin { hour: 23, min: 59 };
858
859fn is_day_end(time: HourMin) -> bool {
861 time == NEAR_END_OF_DAY || time == DAY_BOUNDARY
862}
863
864#[instrument(skip_all)]
871fn lint_times(
872 start: Option<(HourMin, &json::Element<'_>)>,
873 end: Option<(HourMin, &json::Element<'_>)>,
874 warnings: &mut dyn warning::Gather<Warning>,
875) -> Exclusion {
876 if let (Some((start, start_elem)), Some((end, end_elem))) = (start, end) {
879 if end == NEAR_END_OF_DAY {
880 warnings.insert(end_elem, Warning::EndTimeIsNearEndOfDay);
881 }
882
883 if start == DAY_BOUNDARY && is_day_end(end) {
884 warnings.insert(start_elem, Warning::ContainsEntireDay);
885 } else if start == end {
886 warnings.insert(start_elem, Warning::NeverValid);
887 return Exclusion::ExcludesEverySession;
888 }
889
890 return Exclusion::MayMatch;
891 }
892
893 if let Some((start, start_elem)) = start {
894 if start == DAY_BOUNDARY {
895 warnings.insert(start_elem, Warning::ContainsEntireDay);
896 }
897 } else if let Some((end, end_elem)) = end
898 && is_day_end(end)
899 {
900 warnings.insert(end_elem, Warning::ContainsEntireDay);
901 }
902
903 Exclusion::MayMatch
904}
905
906fn lower_time<'a, 'buf>(
908 time: &'a Integrity<Option<schema::Str<'buf>>>,
909 warnings: &mut dyn warning::Gather<Warning>,
910) -> Option<(HourMin, &'a json::Element<'buf>)> {
911 let Integrity::Ok(Some(time)) = time else {
912 return None;
913 };
914
915 let lowered = match civil::Time::from_schema(time, warnings) {
916 Ok(lowered) => lowered,
917 Err(error) => {
918 warnings.deescalate(error);
919 return None;
920 }
921 };
922
923 let hour_min = HourMin {
924 hour: lowered.hour(),
925 min: lowered.minute(),
926 };
927
928 Some((hour_min, time.element()))
929}
930
931const ALL_DAYS: usize = 7;
933
934#[instrument(skip_all)]
942fn lint_day_of_week<T>(
943 day_of_week: &Integrity<Option<schema::List<'_, schema::Enum<'_, T>>>>,
944 warnings: &mut dyn warning::Gather<Warning>,
945) where
946 T: OcpiEnum,
947 Weekday: for<'a> From<&'a T>,
948{
949 let Integrity::Ok(Some(days)) = day_of_week else {
950 return;
951 };
952
953 let elem = days.element();
954
955 if days.is_empty() {
957 warnings.insert(elem, Warning::DayOfWeekEmpty);
958 return;
959 }
960
961 let mut lowered: Vec<Weekday> = Vec::with_capacity(days.len());
962
963 for day in days {
964 let Integrity::Ok(day) = day else {
965 continue;
966 };
967
968 lowered.push(Weekday::from(&day.value()));
969 }
970
971 if !lowered.is_sorted() {
972 warnings.insert(elem, Warning::DayOfWeekUnsorted);
973 }
974
975 let unique: std::collections::BTreeSet<_> = lowered.iter().copied().collect();
976
977 if unique.len() != lowered.len() {
978 warnings.insert(elem, Warning::DayOfWeekDuplicates);
979 }
980
981 if unique.len() == ALL_DAYS {
982 warnings.insert(elem, Warning::ContainsEntireWeek);
983 }
984}
985
986#[instrument(skip_all)]
1003fn lint_zero<T: number::IsZero>(
1004 bound: Option<(T, &json::Element<'_>)>,
1005 warning: Warning,
1006 warnings: &mut dyn warning::Gather<Warning>,
1007) {
1008 let Some((value, elem)) = bound else {
1009 return;
1010 };
1011
1012 if value.is_zero() {
1013 warnings.insert(elem, warning);
1014 }
1015}
1016
1017fn max_duration_exclusion(max_duration: Option<(Seconds, &json::Element<'_>)>) -> Exclusion {
1021 let Some((max_duration, _)) = max_duration else {
1022 return Exclusion::MayMatch;
1023 };
1024
1025 if number::IsZero::is_zero(&max_duration) {
1026 Exclusion::ExcludesEverySession
1027 } else {
1028 Exclusion::MayMatch
1029 }
1030}
1031
1032#[instrument(skip_all)]
1055fn lint_min_zero<T: Into<Decimal>>(
1056 bound: Option<(T, &json::Element<'_>)>,
1057 warnings: &mut dyn warning::Gather<Warning>,
1058) {
1059 let Some((value, elem)) = bound else {
1060 return;
1061 };
1062
1063 let value: Decimal = value.into();
1064
1065 if value.is_zero() {
1066 warnings.insert(elem, Warning::MinZeroExcludesOnlyNegative);
1067 }
1068}
1069
1070#[instrument(skip_all)]
1085fn lint_lower_bound_at_or_above_upper<T: PartialOrd>(
1086 lower: Option<(T, &json::Element<'_>)>,
1087 upper: Option<(T, &json::Element<'_>)>,
1088 warnings: &mut dyn warning::Gather<Warning>,
1089) -> Exclusion {
1090 let (Some((lower, _)), Some((upper, upper_elem))) = (lower, upper) else {
1091 return Exclusion::MayMatch;
1092 };
1093
1094 if lower < upper {
1095 return Exclusion::MayMatch;
1096 }
1097
1098 warnings.insert(upper_elem, Warning::LowerBoundAtOrAboveUpper);
1099 Exclusion::ExcludesEverySession
1100}
1101
1102#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1104enum Exclusion {
1105 ExcludesEverySession,
1106 MayMatch,
1107}
1108
1109#[instrument(skip_all)]
1127fn lint_elements_excluding_every_session(
1128 tariff: &tariff::Checked<'_>,
1129 excluding_every_session: &[&json::Element<'_>],
1130 others: OtherElements,
1131 warnings: &mut dyn warning::Gather<Warning>,
1132) {
1133 if excluding_every_session.is_empty() {
1134 return;
1135 }
1136
1137 let mut lowering_warnings = warning::Gatherer::new();
1138 let others = if tariff.lower_to_v221(&mut lowering_warnings).is_err() {
1139 OtherElements::TariffRejected
1140 } else {
1141 others
1142 };
1143
1144 for elem in excluding_every_session {
1145 warnings.insert(elem, Warning::ElementExcludesEverySession(others));
1146 }
1147}
1148
1149fn lower_number<'a, 'buf, T>(
1155 bound: &'a Integrity<Option<schema::Number<'buf>>>,
1156 warnings: &mut dyn warning::Gather<Warning>,
1157) -> Option<(T, &'a json::Element<'buf>)>
1158where
1159 T: FromSchema<'buf, schema::Number<'buf>>,
1160 T::Warning: Into<Warning>,
1161{
1162 let Integrity::Ok(Some(bound)) = bound else {
1163 return None;
1164 };
1165
1166 let lowered = match T::from_schema(bound, warnings) {
1167 Ok(lowered) => lowered,
1168 Err(error) => {
1169 warnings.deescalate(error);
1170 return None;
1171 }
1172 };
1173
1174 Some((lowered, bound.element()))
1175}