Skip to main content

ocpi_tariffs/lint/
tariff.rs

1//! Lint a tariff by reading the schema intermediate representation.
2//!
3//! The walk deconstructs the IR itself rather than going through a whole-object lowering. Such a
4//! lowering abandons the object as soon as a required field is missing or invalid, which is right
5//! for a feature that needs a usable value but wrong here: a linter has to keep inspecting every
6//! remaining field and report everything it finds. Leaf lowerings
7//! (a `Str` to a `civil::Time`, a `Number` to a `Decimal`) are used as-is - they are pure, they
8//! anchor their warnings at the right element, and reimplementing them would duplicate parsing
9//! that belongs in one place.
10//!
11//! Fields that were absent from the document, or that the schema walk could not build, are
12//! skipped without comment. Checking the document against the OCPI schema is a separate step
13//! with its own warning set, which [`tariff::check`] returns to the caller.
14
15#[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
44/// Lint the given tariff and return a report of any [`Warning`]s found.
45///
46/// A [`tariff::Checked`] is what [`tariff::check`] returns, beside the schema warnings
47/// `check` raises. This reports only what linting adds.
48///
49/// * See: [OCPI spec 2.2.1: Tariff](<https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_tariffs.asciidoc#mod_tariffs_tariff_object>)
50/// * See: [OCPI spec 2.1.1: Tariff](<https://github.com/ocpi/ocpi/blob/28ea45329a50c3dbfd790505b97860854db1d4a6/mod_tariffs.md#31-tariff-object>)
51pub(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/// A tariff linting report.
65#[derive(Debug)]
66pub struct Report {
67    /// What the linter found: the judgments a schema cannot express, and the warnings raised
68    /// while lowering a leaf it wanted to inspect.
69    pub warnings: warning::Set<Warning>,
70}
71
72/// The warnings the tariff linter can raise.
73///
74/// The variants that wrap another module's warning are raised by the leaf lowering the
75/// linter called to read a field, not by the linter itself.
76#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
77pub enum Warning {
78    /// The bounded time of day is the entire day, which is the same as leaving it out.
79    ContainsEntireDay,
80
81    /// The `day_of_week` list holds all seven days, which is the same as leaving it out.
82    ContainsEntireWeek,
83
84    /// Raised while reading a country code.
85    Country(country::Warning),
86
87    /// Both the CDR and tariff have a `country_code` that should be an alpha-2.
88    CpoCountryCodeShouldBeAlpha2,
89
90    /// Raised while reading a currency code.
91    Currency(currency::Warning),
92
93    /// Raised while reading a date, a time or a timestamp.
94    DateTime(datetime::Warning),
95
96    /// The `day_of_week` list names the same day more than once.
97    DayOfWeekDuplicates,
98
99    /// The `day_of_week` list is present but empty, which OCPI reads the same as leaving it out, so
100    /// the list restricts no day.
101    DayOfWeekEmpty,
102
103    /// The `day_of_week` list is not in Monday-to-Sunday order.
104    DayOfWeekUnsorted,
105
106    /// Raised while reading a duration.
107    Duration(duration::Warning),
108
109    /// The element's restrictions exclude every session, so pricing never uses it.
110    ///
111    /// `lint` recognizes three kinds: a `max_duration` of `0`, a `start_time` equal to its
112    /// `end_time` other than `00:00`, and a `start_date`, `min_duration` or `min_kwh` at or above
113    /// its upper bound.
114    ///
115    /// `lint` doesn't report an element restricted to `reservation`. Such an element is about
116    /// a kind of session pricing doesn't cover. Pricing skips the element and raises
117    /// `price::Warning::ReservationElementSkipped`, so removing the element would change what
118    /// pricing reports.
119    ///
120    /// `lint --fix` removes the element only when the warning states
121    /// `OtherElements::SomeMayMatch`, because the tariff then still has an element that may match
122    /// a session. Under the other two values, `lint` can't confirm that, so the fix keeps the
123    /// element.
124    ElementExcludesEverySession(OtherElements),
125
126    /// The element's price components price more than one dimension.
127    ///
128    /// The element's shape suggests that its components apply together as a unit, but pricing
129    /// doesn't treat them as one. For each dimension, pricing uses the first element that has a
130    /// component for that dimension and whose restrictions match, as OCPI specifies.
131    ///
132    /// `lint` doesn't report an element with several components of one dimension. That element
133    /// prices one dimension.
134    ///
135    /// * See: [OCPI spec 2.2.1: TariffElement](<https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_tariffs.asciidoc#mod_tariffs_tariffelement_class>)
136    ElementPricesMoreThanOneDimension,
137
138    /// The `end_time` restriction is set to `23:59`.
139    ///
140    /// The spec states: "To stop at end of the day use: 00:00.".
141    ///
142    /// * See: [OCPI spec 2.2.1: Tariff Restrictions](<https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_tariffs.asciidoc#mod_tariffs_tariffrestrictions_class>).
143    EndTimeIsNearEndOfDay,
144
145    /// A restriction's upper bound is at or below its lower bound, so the element doesn't match any
146    /// session.
147    ///
148    /// The pairs checked are `start_date` and `end_date`, `min_duration` and `max_duration`, and
149    /// `min_kwh` and `max_kwh`. Pricing excludes the value an upper bound states, so a pair whose
150    /// bounds are equal doesn't match any session either.
151    ///
152    /// `lint` doesn't report a reversed `min_power` and `max_power`, or `min_current` and
153    /// `max_current`. Pricing compares the lower bound with the highest value a charging period
154    /// reports and the upper bound with the lowest, so a period whose readings span both bounds
155    /// still matches.
156    LowerBoundAtOrAboveUpper,
157
158    /// A `max_*` restriction is zero, so the element can never match.
159    MaxZeroNeverMatch,
160
161    /// A `min_duration` restriction is `0`, so it allows every session.
162    MinDurationZeroAllowsEverySession,
163
164    /// The `min_price` is greater than `max_price`.
165    MinPriceIsGreaterThanMax,
166
167    /// A `min_kwh`, `min_power` or `min_current` restriction is `0`, so it excludes only a
168    /// negative value.
169    MinZeroExcludesOnlyNegative,
170
171    /// The `start_time` and `end_time` are equal, so the element is never valid.
172    NeverValid,
173
174    /// Raised while reading a price.
175    Money(money::Warning),
176
177    /// Raised while reading a number.
178    Number(number::Warning),
179
180    /// The `restrictions` object is present but holds no restriction.
181    RestrictionsEmpty,
182
183    /// The `start_date_time` is after the `end_date_time`.
184    StartDateTimeIsAfterEndDateTime,
185
186    /// Raised while reading a string.
187    String(string::Warning),
188}
189
190/// Whether another element of the tariff may still match a session, as far as pricing can tell.
191#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
192pub enum OtherElements {
193    /// At least one other element may match a session. An element restricted to `reservation` never
194    /// matches one.
195    SomeMayMatch,
196
197    /// No other element may match a session. Each other element excludes every session or is
198    /// restricted to `reservation`.
199    NoneMayMatch,
200
201    /// Pricing rejects the whole tariff, for example because one of its fields doesn't read. No
202    /// element prices a session until the author fixes that.
203    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    /// A leaf lowering that could not build a value seeds this marker rather than restating
263    /// the structural cause, which the schema walk already located.
264    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/// Lint a `v2.2.1` tariff.
371///
372/// * See: [OCPI spec 2.2.1: Tariff](<https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_tariffs.asciidoc#mod_tariffs_tariff_object>)
373#[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        // The IR element doesn't keep the JSON element it was built from, so a warning on one
396        // anchors to the item at the same index in the `elements` array. Keeping it with
397        // `ir_object!(@keep_element ...)` would copy each element's whole JSON subtree into the IR.
398        // The item is looked up only to raise `ElementExcludesEverySession` and
399        // `ElementPricesMoreThanOneDimension`, so the other lints in this loop don't depend on the
400        // array.
401        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            // The check runs before the `restrictions` match, because an element with no
411            // restrictions can price several dimensions too. A component that can't be read, or
412            // whose `type` can't, adds no dimension, and the schema walk reports that component.
413            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            // Of the bounds `lint_zero` checks, only a `max_duration` of `0` excludes every session.
473            // Negative accumulated energy passes a `max_kwh` of `0`, and a charging period that
474            // reports no power or current passes a `max_power` or `max_current` of `0`. #596 tracks
475            // `MaxZeroNeverMatch`, which says otherwise.
476            let exclusions = [
477                max_duration_exclusion(max_duration),
478                times,
479                dates,
480                durations,
481                kwh,
482            ];
483
484            // `Warning::ElementExcludesEverySession` says why an element restricted to `reservation`
485            // isn't reported.
486            //
487            // A `reservation` the schema walk couldn't build is skipped too. Its author still meant
488            // the element for reservations.
489            //
490            // No session matches such an element, so the `continue` leaves `others` as it is.
491            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/// Lint a `v2.1.1` tariff.
509///
510/// A `v2.1.1` tariff carries only `currency`, `id` and `elements`, so the lints that read
511/// `country_code`, `party_id`, the price bounds or the active window do not apply to it.
512///
513/// * See: [OCPI spec 2.1.1: Tariff](<https://github.com/ocpi/ocpi/blob/28ea45329a50c3dbfd790505b97860854db1d4a6/mod_tariffs.md#31-tariff-object>)
514#[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        // The IR element doesn't keep the JSON element it was built from, so a warning on one
526        // anchors to the item at the same index in the `elements` array. Keeping it with
527        // `ir_object!(@keep_element ...)` would copy each element's whole JSON subtree into the IR.
528        // The item is looked up only to raise `ElementExcludesEverySession` and
529        // `ElementPricesMoreThanOneDimension`, so the other lints in this loop don't depend on the
530        // array.
531        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            // The check runs before the `restrictions` match, because an element with no
541            // restrictions can price several dimensions too. A component that can't be read, or
542            // whose `type` can't, adds no dimension, and the schema walk reports that component.
543            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            // `v2.1.1` restrictions have no `min_current` or `max_current`.
576            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            // Of the bounds `lint_zero` checks, only a `max_duration` of `0` excludes every session.
601            // Negative accumulated energy passes a `max_kwh` of `0`, and a charging period that
602            // reports no power or current passes a `max_power` or `max_current` of `0`. #596 tracks
603            // `MaxZeroNeverMatch`, which says otherwise.
604            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/// Lint a `restrictions` object that holds no restriction.
626///
627/// Every field of a `restrictions` object is optional, so an object written empty restricts
628/// nothing. This has the same semantic meaning as leaving the object out.
629#[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/// Lint an element whose price components price more than one dimension.
646///
647/// `item` is the element's JSON, and `dimensions` holds the dimension of each of its components.
648#[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/// Lint the `country_code` field.
668///
669/// An alpha-3 code is accepted and converted, but the caller is told to use alpha-2. The
670/// remaining findings - a bad code, an unusable length, escapes, lower case - come from the
671/// lowering rather than from this function.
672#[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
689/// The `party_id` is the three character ISO-15118 ID of the CPO.
690type PartyId<'buf> = string::AsciiExactLen<'buf, 3>;
691
692/// Lint the `party_id` field.
693///
694/// The length and lexical checks come from the lowering. The case advice is this layer's
695/// own: `AsciiExactLen` is case-insensitive by definition, so it has no opinion on it.
696#[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    // The value is held as written, so an escape sequence still reads as its own letters -
707    // the `n` of a `\n` would otherwise be taken for lower case. A string carrying escapes
708    // is already reported by the lowering, and its casing is not the useful thing to say
709    // about it.
710    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/// Lint the `currency` field.
723///
724/// Every finding comes from the lowering: an unknown code, a code the ISO standard reserves,
725/// and the case advice.
726#[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/// The `min_price` should not be greater than the `max_price`.
740///
741/// Both bounds are lowered even when only one is present, so a problem with the value itself
742/// is still reported; the comparison only happens when both are usable.
743#[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
761/// Lower an optional `Price` field, keeping the element its warnings anchor to.
762fn 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/// Lint both `start_date_time` and `end_date_time`.
782///
783/// The two may be equal - a tariff active for an instant is odd but not wrong - so only a
784/// `start_date_time` strictly after the `end_date_time` is reported.
785#[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
803/// Lower an optional `DateTime` field, keeping the element its warnings anchor to.
804fn 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
823/// Lower an optional `YYYY-MM-DD` field, keeping the element its warnings anchor to.
824fn 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/// The time of day as hour and minute.
844///
845/// Seconds are deliberately not compared: OCPI writes these restrictions as `HH:MM`, and the
846/// spec's advice about the end of the day is phrased in those terms.
847#[derive(Copy, Clone, Eq, PartialEq)]
848struct HourMin {
849    hour: i8,
850    min: i8,
851}
852
853/// Midnight, which OCPI uses to mean both the start and the end of a day.
854const DAY_BOUNDARY: HourMin = HourMin { hour: 0, min: 0 };
855
856/// The spec asks for `00:00` to end a day, so `23:59` is a near miss worth flagging.
857const NEAR_END_OF_DAY: HourMin = HourMin { hour: 23, min: 59 };
858
859/// True if the time is at, or as good as at, the end of the day.
860fn is_day_end(time: HourMin) -> bool {
861    time == NEAR_END_OF_DAY || time == DAY_BOUNDARY
862}
863
864/// Lint the `start_time` and `end_time` restrictions.
865///
866/// Returns `Exclusion::ExcludesEverySession` when it raised `NeverValid`. A `00:00` pair raises
867/// `ContainsEntireDay` instead, because the pricer reads it as the whole day.
868///
869/// * See: [OCPI spec 2.2.1: Tariff Restrictions](<https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_tariffs.asciidoc#mod_tariffs_tariffrestrictions_class>)
870#[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    // With both bounds present the pair is judged together; with only one, that bound alone
877    // can still describe the whole day.
878    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
906/// Lower an optional `HH:MM` field, keeping the element its warnings anchor to.
907fn 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
931/// Every day of the week; a list holding all of them says the same as no list at all.
932const ALL_DAYS: usize = 7;
933
934/// Lint the `day_of_week` restriction.
935///
936/// A day the schema could not read is skipped rather than abandoning the list, so the
937/// ordering and duplicate checks still describe the days that are readable. Every warning
938/// here is about the list as a whole, so all of them anchor to the array.
939///
940/// * See: [OCPI spec 2.2.1: Tariff DayOfWeek](<https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_tariffs.asciidoc#mod_tariffs_dayofweek_enum>)
941#[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    // An empty list restricts no day, so the checks below have nothing to describe.
956    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/// Lint a restriction whose bound makes it pointless when it is `0`, reporting `warning` if so.
987///
988/// A `max_*` restriction of `0` never matches anything.
989///
990/// A `min_duration` of `0` allows every session.
991/// `price::tariff::Restriction::snapshot_validity_exclusive` compares the bound with `>=` against
992/// how long the session has lasted. That duration is never negative, so a bound of `0` allows
993/// every session, which is what leaving the field out does.
994///
995/// The zero test for a duration is exact because `number::IsZero for Seconds` is exact, where the
996/// same trait allows a tolerance for `Kwh`, `Kw` and `Ampere`. `duration::Seconds::from_schema`
997/// reads the digits as a `u64`, so a fractional or negative bound never lowers and the lowering
998/// reports it as a `Duration` warning instead.
999///
1000/// `min_kwh`, `min_power` and `min_current` go through `lint_min_zero` instead, because a bound of
1001/// `0` there excludes a negative value.
1002#[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
1017/// Whether a `max_duration` excludes every session, which a bound of `0` does because a duration is
1018/// never negative. The test is the exact `number::IsZero for Seconds` that `lint_zero` uses, so
1019/// this agrees with `MaxZeroNeverMatch` on `max_duration`.
1020fn 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/// Lint a `min_kwh`, `min_power` or `min_current` restriction of exactly `0`.
1033///
1034/// The pricer compares each bound with `>=`. It compares `min_kwh` with the energy the session has
1035/// consumed so far, in `price::tariff::Restriction::snapshot_validity_exclusive`. It compares
1036/// `min_power` and `min_current` with the highest power and current a charging period reports, in
1037/// `period_validity`. A CDR can report a negative value for each, and the library prices that CDR.
1038///
1039/// OCPI 2.2.1 says a negative `ENERGY`, `MIN_POWER` or `MIN_CURRENT` is flow from the vehicle to
1040/// the grid, so a period whose highest power or current is negative had that flow for its whole
1041/// length. OCPI 2.1.1 does not say whether any of these values can be negative.
1042///
1043/// An author who takes `0` to be the lowest value writes a bound of `0` expecting it to allow every
1044/// session. The bound excludes a negative value, so removing it changes what a session reporting
1045/// one costs. That is why `fix::Fixable` proposes no edit for this warning.
1046///
1047/// The zero test is exact. `number::IsZero` allows a tolerance of `0.001` for `Kwh`, `Kw` and
1048/// `Ampere`, which would report a `min_power` of `0.0005` as `0`. That bound excludes a value of
1049/// `0.0001` as well as a negative one, so `MinZeroExcludesOnlyNegative` would claim the bound
1050/// excludes only a negative value, which is false.
1051///
1052/// A negative bound is not reported. An author who writes one knows a value can be negative, where
1053/// a bound of `0` suggests the author took `0` to be the lowest value.
1054#[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/// Lint a pair of restriction bounds whose lower bound is at or above its upper bound.
1071///
1072/// `price::tariff::Restriction::snapshot_validity_exclusive` compares a session with the lower
1073/// bound using `>=` and with the upper bound using `<`. A pair whose bounds are equal therefore
1074/// doesn't match any session, which is why the comparison here is `>=` rather than the `>` that
1075/// `lint_start_end_date_time` uses.
1076///
1077/// `Warning::LowerBoundAtOrAboveUpper` names the pairs this checks and why the power and current
1078/// pairs are left out. The pricer compares those two pairs in `Restriction::period_validity`.
1079///
1080/// The comparison is exact, with none of the tolerance `number::IsZero` allows, because a pair
1081/// that is close but not reversed still matches a session.
1082///
1083/// Returns `Exclusion::ExcludesEverySession` when it raised `LowerBoundAtOrAboveUpper`.
1084#[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/// Whether a restriction, or an element's restrictions together, exclude every session.
1103#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1104enum Exclusion {
1105    ExcludesEverySession,
1106    MayMatch,
1107}
1108
1109/// Lint each element whose restrictions exclude every session.
1110///
1111/// `fix::Fixable` sees only the element a warning sits on, so it can't tell whether removing that
1112/// element would leave the tariff with none. The warning records it as an `OtherElements` instead.
1113///
1114/// The walk passes `SomeMayMatch` when some element isn't restricted to `reservation` and doesn't
1115/// exclude every session, and `NoneMayMatch` otherwise. This function then asks
1116/// `tariff::Checked::lower_to_v221`, the lowering pricing runs on a tariff, and states `TariffRejected`
1117/// if pricing rejects the tariff.
1118///
1119/// If `lint --fix` removed an element from a tariff pricing rejects, it could leave a tariff with no
1120/// element that matches a session. A `null` is the sharpest case, because `lint --fix` removes it in
1121/// the same pass, which would leave `elements` empty. Once the `null` is gone, the next pass sees a
1122/// tariff pricing accepts and can remove the element.
1123///
1124/// The check runs only when some element is reported. Only whether the tariff lowers matters, so
1125/// this function drops the lowering's warnings.
1126#[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
1149/// Lower an optional number field, keeping the element its warnings anchor to.
1150///
1151/// The walk lowers each bound once and passes the value to every check that reads it.
1152/// `warning::Gatherer` keeps every warning it is given, so a check that lowered the field
1153/// itself would report a bound that fails to lower once per check.
1154fn 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}