Skip to main content

ocpi_tariffs/
json.rs

1//! JSON parsing and typed decoding for the OCPI CDR pricing/generating and CDR/Tariff linting pipeline.
2//!
3//! # Parsing vs decoding
4//!
5//! Parsing and decoding are intentionally separated so the linter can emit
6//! actionable warnings rather than hard parse errors.
7//!
8//! **Parsing** ([`parse_object`]) converts a raw JSON `&str` into an
9//! element tree. The parser is deliberately lenient about string content:
10//! it only verifies structural correctness (balanced delimiters, valid
11//! top-level values) and leaves escape sequences and control characters
12//! untouched inside a raw string.
13//!
14//! **Decoding** ([`decode`]) interprets the raw JSON String as a `&str`.
15//! The crate decodes a string's escape sequences itself, when a feature reads the string.
16//! It reports each invalid escape sequence or control character as a [`decode::Warning`]
17//! rather than failing. This lets the linter pinpoint the exact field, report what is wrong,
18//! and suggest a corrected encoding.
19//! The `price` and `generate` mods can choose to hard fail on specific `Warning`s.
20//!
21pub mod decode;
22mod parser;
23pub mod write;
24
25#[cfg(test)]
26pub(crate) mod test;
27
28#[cfg(test)]
29mod test_element_location;
30
31#[cfg(test)]
32mod test_path;
33
34#[cfg(test)]
35mod test_path_matches_glob;
36
37#[cfg(test)]
38mod test_removal;
39
40#[cfg(test)]
41mod test_repeated_key;
42
43use std::{
44    borrow::{Borrow, Cow},
45    collections::{BTreeMap, BTreeSet, btree_set},
46    fmt::{self, Write as _},
47    rc::Rc,
48};
49
50use crate::{string, warning};
51
52pub(crate) use parser::parse;
53pub use parser::{Error, ErrorKind as ParseErrorKind};
54
55/// Parse a raw JSON `&str` into a [`Document`] and require the root value to be a JSON object.
56///
57/// Parsing is the first step for a CDR or a tariff.
58/// The next is [`cdr::check`](crate::cdr::check) or [`tariff::check`](crate::tariff::check),
59/// which takes the version as well as the document.
60/// When the version isn't known, [`cdr::infer_version`](crate::cdr::infer_version) or
61/// [`tariff::infer_version`](crate::tariff::infer_version) guesses it from the document first.
62///
63/// The input size is gated: 5 MB (5,000,000 bytes) or more returns
64/// [`ParseError::SizeExceedsMax`].
65pub fn parse_object(json: &str) -> Result<Document<'_>, ParseError> {
66    let json = string::ReasonableLen::new(json).map_err(|_e| ParseError::SizeExceedsMax)?;
67    let doc = parse(json).map_err(ParseError::Json)?;
68
69    if !doc.root().is_object() {
70        return Err(ParseError::ShouldBeAnObject);
71    }
72
73    Ok(doc)
74}
75
76#[derive(Debug)]
77/// Why a raw JSON `&str` could not be turned into a [`Document`].
78pub enum ParseError {
79    /// The JSON parser was unable to parse the JSON str.
80    Json(Error),
81
82    /// The OCPI object should be a JSON object.
83    ShouldBeAnObject,
84
85    /// The size of the input `str` exceeds the maximum deemed reasonable.
86    SizeExceedsMax,
87}
88
89impl fmt::Display for ParseError {
90    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91        match self {
92            Self::Json(error) => write!(f, "{error}"),
93            Self::ShouldBeAnObject => f.write_str("The CDR should be an object."),
94            Self::SizeExceedsMax => write!(
95                f,
96                "The input `&str` exceeds the reasonable maximum `{} MB`.",
97                string::ReasonableLen::FACTOR
98            ),
99        }
100    }
101}
102
103impl std::error::Error for ParseError {
104    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
105        match &self {
106            ParseError::Json(err) => Some(err),
107            ParseError::ShouldBeAnObject | ParseError::SizeExceedsMax => None,
108        }
109    }
110}
111
112/// The output of [`parse_object`]: the element tree with path resolution embedded in each
113/// element.
114#[derive(Clone, Debug)]
115pub struct Document<'buf> {
116    /// Shared inner state; also held by every element in the tree.
117    inner: Rc<DocumentInner<'buf>>,
118    /// Root element of the parsed tree.
119    root: Element<'buf>,
120}
121
122impl<'buf> Document<'buf> {
123    /// Returns the source JSON string this document was parsed from.
124    pub fn source(&self) -> &'buf str {
125        self.inner.source
126    }
127
128    /// Returns the root element of this document.
129    pub(crate) fn root(&self) -> &Element<'buf> {
130        &self.root
131    }
132
133    /// Returns the root element of this document, without copying the element tree.
134    ///
135    /// The element can still resolve its path once the document is dropped, because every
136    /// element holds an `Rc` of the document's shared state.
137    pub(crate) fn into_root(self) -> Element<'buf> {
138        self.root
139    }
140
141    /// Returns the element with `id`, or `None` if this document has no such element.
142    ///
143    /// Walks the parent chain up from `id` and then descends back down the tree, finding
144    /// each ancestor among its siblings by binary search, so the cost is O(depth * log width).
145    ///
146    /// NOTE: an [`ElemId`] produced by a different parse of the same source `&str`
147    /// cannot be told apart from one of this document's own ids.
148    pub(crate) fn element(&self, id: ElemId) -> Option<&Element<'buf>> {
149        let ancestry = self.inner.paths.ancestry(id)?;
150        let (root_id, descent) = ancestry.split_first()?;
151
152        if *root_id != self.root.id {
153            return None;
154        }
155
156        let mut element = &self.root;
157
158        for child_id in descent {
159            element = child_of(element, *child_id)?;
160        }
161
162        Some(element)
163    }
164
165    /// Resolves the source spans to erase in order to remove every element in `ids`.
166    ///
167    /// The returned spans are sorted by start offset and never overlap, so erasing them
168    /// from [`Document::source`] leaves JSON that still parses.
169    ///
170    /// Siblings are resolved as a group, because which span removes a child depends on
171    /// which of its siblings survive:
172    ///
173    /// | Case | Span erased |
174    /// |---|---|
175    /// | Run of children followed by a surviving sibling | the run's first key or value, up to the start of that sibling |
176    /// | Run of children reaching the closing delimiter | the end of the last surviving sibling's value, up to the end of the run |
177    /// | Every child of an object or array | everything between the `{}` or `[]` delimiters |
178    ///
179    /// A run that reaches the closing delimiter carries no trailing comma of its own, so
180    /// it has to swallow the comma of the sibling before it. Resolving each id on its own
181    /// and merging the spans afterwards gets that case wrong: it leaves the earlier
182    /// sibling's comma dangling.
183    ///
184    /// An id nested inside another id in the same set needs nothing beyond being dropped,
185    /// since the ancestor's span already covers it.
186    pub fn removal_spans(&self, ids: &BTreeSet<ElemId>) -> Result<Vec<Span>, RemovalError> {
187        let mut by_parent: BTreeMap<ElemId, BTreeSet<ElemId>> = BTreeMap::new();
188
189        for id in ids {
190            let parent = self.parent_of(*id)?;
191            by_parent.entry(parent).or_default().insert(*id);
192        }
193
194        let mut spans: Vec<Span> = Vec::new();
195
196        for (parent_id, removed) in by_parent {
197            let parent = self
198                .element(parent_id)
199                .ok_or(RemovalError::UnknownElement(parent_id))?;
200
201            spans.extend(sibling_removal_spans(parent, &removed)?);
202        }
203
204        spans.sort_unstable();
205
206        Ok(without_nested(spans))
207    }
208
209    /// Returns the id of the last field for each key that occurs more than once in an object,
210    /// across every object in the document. The id is that of the field's value, the element a
211    /// warning on the field is anchored to.
212    ///
213    /// This method decodes the escapes in a key before comparing it, so `"\u006b"` repeats the key
214    /// `k`, as RFC 8259 requires. The schema walk compares keys the same way when it matches a
215    /// field and when it raises `schema::Warning::DuplicateField`. This method and the walk have to
216    /// agree on which fields repeat a key.
217    ///
218    /// This makes one pass over the document, so a caller asking about many fields builds the set
219    /// once. Answering per field by scanning its siblings costs time quadratic in the number of
220    /// fields.
221    pub(crate) fn last_of_repeated_keys(&self) -> BTreeSet<ElemId> {
222        // For each object and key, the number of fields with that key and the id of the latest
223        // one seen.
224        let mut seen: BTreeMap<(ElemId, Key<'buf>), (usize, ElemId)> = BTreeMap::new();
225
226        // Entries are indexed by id, and the parser allocates ids in document order, so the latest
227        // field seen for a key is its last occurrence.
228        for (index, entry) in self.inner.paths.entries.iter().enumerate() {
229            let PathEntry::Field { parent, key } = entry else {
230                continue;
231            };
232
233            let counted = seen
234                .entry((*parent, key.to_key()))
235                .or_insert((0, ElemId(index)));
236            counted.0 = counted.0.saturating_add(1);
237            counted.1 = ElemId(index);
238        }
239
240        seen.into_values()
241            .filter(|(count, _last)| *count > 1)
242            .map(|(_count, last)| last)
243            .collect()
244    }
245
246    /// Returns the span of the field's quoted key, for the field whose value is the element with
247    /// `id`. Returns `None` if this document has no such element, or if the element is not the
248    /// value of an object field.
249    pub(crate) fn key_span(&self, id: ElemId) -> Option<Span> {
250        let parent = self.object_of_field(id)?;
251        let fields = self.element(parent)?.as_object_fields()?;
252        // Fields have ascending ids in source order, as `child_of` relies on.
253        // Scanning instead would make renaming each of `n` fields of one object
254        // cost `n^2` in total.
255        let index = fields
256            .binary_search_by_key(&id, |field| field.element.id)
257            .ok()?;
258        let field = fields.get(index)?;
259
260        Some(field.key_span)
261    }
262
263    /// Returns the id of the object holding the field whose value is the element with `id`.
264    /// Returns `None` if this document has no such element, or if the element is not
265    /// the value of an object field.
266    pub(crate) fn object_of_field(&self, id: ElemId) -> Option<ElemId> {
267        let Some(PathEntry::Field { parent, key: _ }) = self.inner.paths.entries.get(id.0) else {
268            return None;
269        };
270
271        Some(*parent)
272    }
273
274    /// Return the id of the parent of the [`Element`] with the given `id`.
275    fn parent_of(&self, id: ElemId) -> Result<ElemId, RemovalError> {
276        match self.inner.paths.entries.get(id.0) {
277            None => Err(RemovalError::UnknownElement(id)),
278            Some(PathEntry::Root) => Err(RemovalError::Root),
279            Some(PathEntry::Field { parent, key: _ } | PathEntry::Item { parent, index: _ }) => {
280                Ok(*parent)
281            }
282        }
283    }
284}
285
286/// Why a set of elements could not be resolved to removal spans.
287#[derive(Copy, Clone, Debug, Eq, PartialEq)]
288pub enum RemovalError {
289    /// The root element has no parent, so removing it would leave no document behind.
290    Root,
291
292    /// No element in this document has this id.
293    UnknownElement(ElemId),
294}
295
296impl fmt::Display for RemovalError {
297    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
298        match self {
299            Self::Root => f.write_str("The root element can not be removed."),
300            Self::UnknownElement(id) => write!(f, "The document has no element with id `{id}`."),
301        }
302    }
303}
304
305impl std::error::Error for RemovalError {}
306
307/// Returns the direct child of `parent` that has `id`.
308///
309/// The parser gives an element its id before it parses the element's children, so the children
310/// of any parent have ascending ids in source order. That lets this function find the child by
311/// binary search. Scanning the children instead would make looking up each of `n` fields of one
312/// object cost `n^2` in total.
313fn child_of<'a, 'buf>(parent: &'a Element<'buf>, id: ElemId) -> Option<&'a Element<'buf>> {
314    match parent.value() {
315        Value::Object(fields) => {
316            let index = fields
317                .binary_search_by_key(&id, |field| field.element().id)
318                .ok()?;
319            fields.get(index).map(Field::element)
320        }
321        Value::Array(items) => {
322            let index = items.binary_search_by_key(&id, |item| item.id).ok()?;
323            items.get(index)
324        }
325        Value::Null | Value::True | Value::False | Value::String(_) | Value::Number(_) => None,
326    }
327}
328
329/// Resolves the spans to erase to remove `removed` from `parent`, in source order.
330fn sibling_removal_spans(
331    parent: &Element<'_>,
332    removed: &BTreeSet<ElemId>,
333) -> Result<Vec<Span>, RemovalError> {
334    let children = child_spans(parent);
335
336    // `children` is in source order, so its ids ascend, as `child_of` relies on too.
337    for id in removed {
338        if children.binary_search_by_key(id, |child| child.id).is_err() {
339            return Err(RemovalError::UnknownElement(*id));
340        }
341    }
342
343    let mut spans: Vec<Span> = Vec::new();
344    let mut kept_end: Option<u32> = None;
345    let mut run: Option<Run> = None;
346
347    for child in &children {
348        if removed.contains(&child.id) {
349            let start = run.map(|open| open.start).unwrap_or(child.start);
350            run = Some(Run {
351                start,
352                end: child.end,
353                next_sibling_start: child.next_sibling_start,
354            });
355            continue;
356        }
357
358        // A surviving sibling closes the open run: erase up to where that sibling starts,
359        // which takes the run's own trailing comma with it.
360        if let Some(open) = run.take() {
361            spans.push(Span::new(open.start, open.next_sibling_start));
362        }
363
364        kept_end = Some(child.end);
365    }
366
367    let Some(open) = run else {
368        return Ok(spans);
369    };
370
371    // A run still open here runs up to the closing delimiter, so it has no trailing comma
372    // of its own and has to swallow the comma of the sibling before it. With no surviving
373    // sibling before it, every child was removed and the whole interior goes.
374    let span = match kept_end {
375        Some(end) => Span::new(end, open.end),
376        None => interior_span(parent),
377    };
378
379    spans.push(span);
380
381    Ok(spans)
382}
383
384/// A maximal run of adjacent children being removed from the same parent.
385#[derive(Copy, Clone, Debug)]
386struct Run {
387    /// First byte to erase; the `start` of the run's first child.
388    start: u32,
389    /// One past the last byte of the run's last value.
390    end: u32,
391    /// The `next_sibling_start` of the run's last child.
392    next_sibling_start: u32,
393}
394
395/// Where a child of an object or array sits in the source, as far as removal is concerned.
396#[derive(Copy, Clone, Debug)]
397struct ChildSpan {
398    id: ElemId,
399    /// First byte to erase: the key of an object field, the value of an array item.
400    start: u32,
401    /// One past the last byte of the child's value.
402    end: u32,
403    /// Where the next sibling starts: one past this child's trailing comma and the
404    /// whitespace after it. Equal to `end` for the last child, which has no comma.
405    next_sibling_start: u32,
406}
407
408/// The removal spans of every child of `parent`, in source order.
409fn child_spans(parent: &Element<'_>) -> Vec<ChildSpan> {
410    match parent.value() {
411        Value::Object(fields) => fields
412            .iter()
413            .map(|field| ChildSpan {
414                id: field.element.id,
415                start: field.key_span.start,
416                end: field.element.span.end,
417                next_sibling_start: field.element.full_span_end,
418            })
419            .collect(),
420        Value::Array(items) => items
421            .iter()
422            .map(|item| ChildSpan {
423                id: item.id,
424                start: item.span.start,
425                end: item.span.end,
426                next_sibling_start: item.full_span_end,
427            })
428            .collect(),
429        Value::Null | Value::True | Value::False | Value::String(_) | Value::Number(_) => {
430            Vec::new()
431        }
432    }
433}
434
435/// The span between an object's or array's delimiters, each of which is one byte wide.
436fn interior_span(element: &Element<'_>) -> Span {
437    let end = element.span.end.saturating_sub(1);
438    let start = element.span.start.saturating_add(1).min(end);
439
440    Span::new(start, end)
441}
442
443/// Drops the spans that sit inside an earlier span.
444///
445/// A removed element nested inside another removed element is already covered by its
446/// ancestor's span. JSON is a tree, so two removal spans either nest or are disjoint;
447/// they never partially overlap.
448fn without_nested(spans: Vec<Span>) -> Vec<Span> {
449    let mut kept: Vec<Span> = Vec::new();
450
451    for span in spans {
452        let Some(last) = kept.last_mut() else {
453            kept.push(span);
454            continue;
455        };
456
457        if span.start >= last.end {
458            kept.push(span);
459            continue;
460        }
461
462        // Nesting means `last` already reaches past `span`, so this leaves it as it is.
463        // Extending rather than ignoring keeps a partial overlap from under-erasing.
464        last.end = last.end.max(span.end);
465    }
466
467    kept
468}
469
470/// A JSON [`Element`] with identity, source span, and value.
471///
472/// Each element carries a shared reference to the document it was parsed from,
473/// so [`Element::path()`] can resolve its path.
474#[derive(Clone, Debug)]
475pub(crate) struct Element<'buf> {
476    /// Shared document state.
477    doc: Rc<DocumentInner<'buf>>,
478    /// Unique identifier within the document; sequentially assigned depth-first.
479    id: ElemId,
480    /// Byte range of the value only; use for replacement edits.
481    span: Span,
482    /// End of the value plus any trailing comma and whitespace; use for removal edits.
483    /// Equal to `span.end` when there is no trailing comma (root element, or last sibling).
484    full_span_end: u32,
485    /// Parsed value, borrowing from the source `&str`.
486    value: Value<'buf>,
487}
488
489impl PartialEq for Element<'_> {
490    fn eq(&self, other: &Self) -> bool {
491        self.id == other.id
492            && self.span == other.span
493            && self.full_span_end == other.full_span_end
494            && self.value == other.value
495    }
496}
497
498impl Eq for Element<'_> {}
499
500impl<'buf> Element<'buf> {
501    /// Returns this element's identity within its [`Document`].
502    pub fn id(&self) -> ElemId {
503        self.id
504    }
505
506    /// Returns the span covering this element's value alone, without any trailing comma.
507    pub fn span(&self) -> Span {
508        self.span
509    }
510
511    /// Returns this element's JSON value.
512    pub fn value(&self) -> &Value<'buf> {
513        &self.value
514    }
515
516    /// Returns the [`Path`] locating this element.
517    ///
518    /// NOTE: The `Path` is constructed anew every time this function is called.
519    pub fn path(&self) -> Path {
520        self.doc.paths.path_of(self)
521    }
522
523    /// The full source string; all element spans are relative to this.
524    pub fn source(&self) -> &'buf str {
525        self.doc.source
526    }
527
528    /// Return the location that this element begins at.
529    #[expect(
530        clippy::indexing_slicing,
531        reason = "the parser records a location for every id it allocates"
532    )]
533    pub fn location(&self) -> Location {
534        self.doc.paths.locations[self.id.0]
535    }
536
537    /// Returns the name of the field whose value is this element, as written with its escapes.
538    /// Returns `None` for the root and for an array item.
539    pub(crate) fn key(&self) -> Option<RawStr<'buf>> {
540        match self.doc.paths.entries.get(self.id.0) {
541            Some(PathEntry::Field { parent: _, key }) => Some(*key),
542            _ => None,
543        }
544    }
545
546    /// Return `Some(&[Field])` if the `Value` is a `Object`.
547    pub fn as_object_fields(&self) -> Option<&[Field<'buf>]> {
548        self.value.as_object_fields()
549    }
550
551    /// Return true if the `Element`s `Value` is null.
552    pub fn is_null(&self) -> bool {
553        self.value.is_null()
554    }
555
556    /// Return true if the `Element`s `Value` is an object.
557    pub fn is_object(&self) -> bool {
558        self.value.is_object()
559    }
560}
561
562/// A JSON value that borrows its content from the source JSON `&str`.
563#[derive(Clone, Debug, Eq, PartialEq)]
564pub(crate) enum Value<'buf> {
565    /// JSON `null` literal.
566    Null,
567    /// JSON `true` literal.
568    True,
569    /// JSON `false` literal.
570    False,
571    /// String content with quotes removed; escape sequences are not decoded.
572    String(RawStr<'buf>),
573    /// Raw number text; not guaranteed to fit any specific numeric type.
574    Number(&'buf str),
575    /// Ordered list of child elements.
576    Array(Vec<Element<'buf>>),
577    /// Ordered list of key-value fields.
578    Object(Vec<Field<'buf>>),
579}
580
581impl fmt::Display for Value<'_> {
582    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
583        match self {
584            Self::Null => write!(f, "null"),
585            Self::True => write!(f, "true"),
586            Self::False => write!(f, "false"),
587            Self::String(s) => write!(f, "{}", s.as_unescaped_str()),
588            Self::Number(s) => write!(f, "{s}"),
589            Self::Array(..) => f.write_str("[...]"),
590            Self::Object(..) => f.write_str("{...}"),
591        }
592    }
593}
594
595/// Byte range of a JSON token within the source string.
596#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Ord, PartialOrd)]
597pub struct Span {
598    /// Byte offset of the first byte of the token.
599    pub start: u32,
600    /// Byte offset one past the last byte of the token.
601    pub end: u32,
602}
603
604impl Span {
605    fn new(start: u32, end: u32) -> Self {
606        Self { start, end }
607    }
608}
609
610/// A file location expressed as line and column.
611///
612/// The fields count from 0, while `Display` writes `line:col` counting from 1,
613/// the form an editor or a compiler message gives.
614#[derive(Clone, Copy, Debug, PartialEq, Eq)]
615pub struct Location {
616    /// The line index is 0 based.
617    pub line: u32,
618
619    /// The col index is 0 based.
620    pub col: u32,
621}
622
623impl From<(u32, u32)> for Location {
624    fn from(value: (u32, u32)) -> Self {
625        Self {
626            line: value.0,
627            col: value.1,
628        }
629    }
630}
631
632impl From<Location> for (u32, u32) {
633    fn from(value: Location) -> Self {
634        (value.line, value.col)
635    }
636}
637
638impl PartialEq<(u32, u32)> for Location {
639    fn eq(&self, other: &(u32, u32)) -> bool {
640        self.line == other.0 && self.col == other.1
641    }
642}
643
644impl Location {
645    /// Returns the location after `byte`, given that `self` is the location before it.
646    ///
647    /// The column counts chars. A UTF-8 continuation byte, `0b10xxxxxx`, belongs to the char before
648    /// it. In that case the column stays the same. Counting bytes would put every column after a
649    /// multibyte char too far right.
650    fn advance(self, byte: u8) -> Self {
651        if byte == b'\n' {
652            return Self {
653                line: self.line.saturating_add(1),
654                col: 0,
655            };
656        }
657
658        let is_continuation = byte & 0b1100_0000 == 0b1000_0000;
659        if is_continuation {
660            return self;
661        }
662
663        Self {
664            line: self.line,
665            col: self.col.saturating_add(1),
666        }
667    }
668}
669
670impl fmt::Display for Location {
671    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
672        // Adding 1 in `u32` would overflow at `u32::MAX`, which `From<(u32, u32)>`
673        // allows, and `saturating_add` would print two locations the same.
674        let line = u64::from(self.line) + 1;
675        let col = u64::from(self.col) + 1;
676        write!(f, "{line}:{col}")
677    }
678}
679
680/// Unique sequential index of a JSON element within a document.
681///
682/// Assigned depth-first by the parser. `Parser::alloc_id` uses `checked_add`
683/// so the counter never wraps silently — overflow becomes `ParseError::TooLarge`.
684#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, Ord, PartialOrd)]
685pub struct ElemId(usize);
686
687impl fmt::Display for ElemId {
688    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
689        fmt::Display::fmt(&self.0, f)
690    }
691}
692
693/// Records how one element was reached from its parent.
694#[derive(Debug)]
695enum PathEntry<'buf> {
696    /// The root element; has no parent.
697    Root,
698    /// An object field; the element's path ends with a key segment.
699    Field {
700        /// Id of the parent object element.
701        parent: ElemId,
702        /// Key text borrowed from the source JSON, without surrounding quotes.
703        key: RawStr<'buf>,
704    },
705    /// An array item; the element's path ends with an index segment.
706    Item {
707        /// Id of the parent array element.
708        parent: ElemId,
709        /// Zero-based position within the parent array.
710        index: u32,
711    },
712}
713
714/// Shared state carried by every [`Element`] produced from the same parse.
715///
716/// Wrapped in [`Rc`] so that each element can resolve its own path without
717/// holding a live reference to the original [`Document`].
718#[derive(Debug)]
719struct DocumentInner<'buf> {
720    /// The full source string; all element spans are relative to this.
721    source: &'buf str,
722    /// Parent-pointer table used to reconstruct element paths.
723    paths: PathTable<'buf>,
724}
725
726/// A table recording the parentage and the location of every [`Element`] produced by a parse.
727#[derive(Debug, Default)]
728struct PathTable<'buf> {
729    /// The `entries` `Vec` is indexed using `ElemId`.
730    entries: Vec<PathEntry<'buf>>,
731    /// Where each element's value begins, indexed by `ElemId` like `entries`. The parser
732    /// records it as it reaches the value.
733    locations: Vec<Location>,
734}
735
736impl<'buf> PathTable<'buf> {
737    fn push(&mut self, entry: PathEntry<'buf>, location: Location) {
738        self.entries.push(entry);
739        self.locations.push(location);
740    }
741
742    /// Returns the chain of ids from the root down to `id`, both included.
743    ///
744    /// Cost is O(depth). Returns `None` if `id` is not in this table. The walk always
745    /// terminates because a parent is allocated before its children, so every parent id
746    /// is smaller than the id it was reached from.
747    fn ancestry(&self, id: ElemId) -> Option<Vec<ElemId>> {
748        let mut chain = vec![id];
749        let mut current = id;
750
751        loop {
752            match self.entries.get(current.0)? {
753                PathEntry::Root => break,
754                PathEntry::Field { parent, key: _ } | PathEntry::Item { parent, index: _ } => {
755                    chain.push(*parent);
756                    current = *parent;
757                }
758            }
759        }
760
761        chain.reverse();
762
763        Some(chain)
764    }
765
766    /// Build the full [`Path`] to `element` by walking the parent-pointer chain.
767    ///
768    /// Cost is O(depth) per path construction.
769    ///
770    /// NOTE: The `'buf` lifetime shared by `element` and `self` prevents cross-document
771    /// misuse at compile time for documents with distinct source lifetimes.
772    ///
773    /// # Panics
774    ///
775    /// Panics if `element` was not produced by the same parse that created this table.
776    fn path_of(&self, element: &Element<'buf>) -> Path {
777        let mut entries: Vec<&PathEntry<'buf>> = Vec::new();
778        let mut elem_id = element.id;
779
780        // Walk back up the path chain.
781        loop {
782            let entry = self
783                .entries
784                .get(elem_id.0)
785                .expect("ElemId always refers to a valid PathEntry");
786
787            match entry {
788                PathEntry::Root => {
789                    entries.push(entry);
790                    break;
791                }
792                PathEntry::Field { parent, key: _ } | PathEntry::Item { parent, index: _ } => {
793                    entries.push(entry);
794                    elem_id = *parent;
795                }
796            }
797        }
798
799        // Reverse the elements so we can walk forward along the chain.
800        entries.reverse();
801
802        let mut out = String::with_capacity(30);
803
804        for entry in entries {
805            let res = match entry {
806                PathEntry::Root => write!(out, "$"),
807                PathEntry::Field { parent: _, key } => {
808                    let (key, _warning) = key.decode_escapes();
809                    write!(out, ".{key}")
810                }
811                PathEntry::Item { parent: _, index } => {
812                    // Array indices use bracket notation per RFC 9535, e.g.
813                    // `$.elements[0]`, rather than a dotted `.0` segment.
814                    write!(out, "[{index}]")
815                }
816            };
817
818            res.expect("Writing to a String can only fail if the system runs out of heap memory");
819        }
820
821        Path(out)
822    }
823}
824
825#[derive(Clone, PartialOrd, Ord, PartialEq, Eq)]
826/// The path locating an element in its [`Document`], such as
827/// `$.charging_periods[0].dimensions`.
828///
829/// A warning is reported against a path, so this is what tells a caller which field a
830/// warning is about.
831///
832/// The notation is an RFC 9535 singular query, the RFC's term for an expression that selects
833/// at most one node. The RFC's Normalized Path is the one canonical spelling of such a query
834/// and writes this same location as `$['charging_periods'][0]['dimensions']`, so the shorthand
835/// here is a choice about legibility.
836///
837/// That holds for every field OCPI defines. A key holding a `.` or a `[` is written after a dot
838/// like any other, so a document carrying one can produce two elements with the same path.
839///
840/// A path holds a field name with its escapes decoded, so the field `"\u0061ge"`
841/// has the path `$.age`.
842pub struct Path(String);
843
844impl Path {
845    /// Consume the `Path` and return the underlying `String`.
846    pub fn into_string(self) -> String {
847        self.0
848    }
849
850    /// Return the path as a `str`.
851    pub fn as_str(&self) -> &str {
852        &self.0
853    }
854
855    /// Iterate the [`Component`]s of this path in order, skipping the `$` root.
856    ///
857    /// For example, `$.elements[0].id` yields `Member("elements")`,
858    /// `Index("0")`, `Member("id")`. The root path `$` yields nothing.
859    pub fn components(&self) -> Components<'_> {
860        Components::over(&self.0)
861    }
862}
863
864/// A single [`Path`] component: an object member or an array index.
865#[derive(Clone, Copy, Debug, PartialEq, Eq)]
866pub enum Component<'a> {
867    /// An object member, the `name` in a `.name` segment.
868    Member(&'a str),
869    /// An array index, the decimal digits in a `[n]` segment.
870    Index(&'a str),
871}
872
873/// Iterator over the [`Component`]s of a [`Path`]; see [`Path::components`].
874#[derive(Clone, Debug)]
875pub struct Components<'a> {
876    rest: &'a str,
877}
878
879impl<'a> Components<'a> {
880    /// Iterate the components of a raw `JSONPath` string, skipping a leading `$`.
881    pub(crate) fn over(path: &'a str) -> Self {
882        Self {
883            rest: path.strip_prefix('$').unwrap_or(path),
884        }
885    }
886}
887
888impl<'a> Iterator for Components<'a> {
889    type Item = Component<'a>;
890
891    fn next(&mut self) -> Option<Self::Item> {
892        if let Some(after) = self.rest.strip_prefix('.') {
893            // `.name`: read up to the next segment delimiter.
894            let end = after.find(['.', '[']).unwrap_or(after.len());
895            let (name, tail) = after.split_at(end);
896            self.rest = tail;
897            Some(Component::Member(name))
898        } else if let Some(after) = self.rest.strip_prefix('[') {
899            // `[index]`: read up to the closing bracket.
900            let end = after.find(']').unwrap_or(after.len());
901            let (index, tail) = after.split_at(end);
902            self.rest = tail.strip_prefix(']').unwrap_or(tail);
903            Some(Component::Index(index))
904        } else {
905            // Empty (root) or malformed input: stop iterating.
906            None
907        }
908    }
909}
910
911impl PartialEq<str> for Path {
912    fn eq(&self, other: &str) -> bool {
913        self.0 == other
914    }
915}
916
917impl PartialEq<&str> for Path {
918    fn eq(&self, other: &&str) -> bool {
919        self.0 == *other
920    }
921}
922
923impl fmt::Debug for Path {
924    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
925        f.write_str(&self.0)
926    }
927}
928
929impl fmt::Display for Path {
930    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
931        fmt::Display::fmt(&self.0, f)
932    }
933}
934
935/// Set of path with a common issue.
936#[derive(Debug)]
937pub struct PathSet<'set>(BTreeSet<&'set Path>);
938
939impl<'set> PathSet<'set> {
940    pub(crate) fn new(paths: BTreeSet<&'set Path>) -> Self {
941        Self(paths)
942    }
943
944    /// Return the field paths as a `Vec` of `String`s.
945    pub fn to_strings(&self) -> Vec<String> {
946        self.0.iter().map(ToString::to_string).collect()
947    }
948
949    /// Return the field paths as a `Vec` of `String`s.
950    pub fn into_strings(self) -> Vec<String> {
951        self.0.into_iter().map(ToString::to_string).collect()
952    }
953
954    /// Return true if the list of unexpected fields is empty.
955    pub fn is_empty(&self) -> bool {
956        self.0.is_empty()
957    }
958
959    /// Return the number of unexpected fields.
960    pub fn len(&self) -> usize {
961        self.0.len()
962    }
963
964    /// Return an Iterator over the unexpected fields.
965    pub fn iter(&self) -> btree_set::Iter<'_, &Path> {
966        self.0.iter()
967    }
968}
969
970impl<'set> IntoIterator for PathSet<'set> {
971    type Item = &'set Path;
972
973    type IntoIter = btree_set::IntoIter<&'set Path>;
974
975    fn into_iter(self) -> Self::IntoIter {
976        self.0.into_iter()
977    }
978}
979
980impl<'a, 'set> IntoIterator for &'a PathSet<'set> {
981    type Item = &'a &'set Path;
982
983    type IntoIter = btree_set::Iter<'a, &'set Path>;
984
985    fn into_iter(self) -> Self::IntoIter {
986        self.0.iter()
987    }
988}
989
990#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
991/// Which of the six JSON kinds a value is, without its content.
992///
993/// A schema mismatch is reported in terms of these, saying which kind was expected and
994/// which was found.
995pub enum ValueKind {
996    /// The JSON `null` literal.
997    Null,
998    /// The JSON `true` or `false` literal.
999    Bool,
1000    /// A JSON number.
1001    Number,
1002    /// A JSON string.
1003    String,
1004    /// A JSON array.
1005    Array,
1006    /// A JSON object.
1007    Object,
1008}
1009
1010impl fmt::Display for ValueKind {
1011    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1012        match self {
1013            ValueKind::Null => write!(f, "null"),
1014            ValueKind::Bool => write!(f, "bool"),
1015            ValueKind::Number => write!(f, "number"),
1016            ValueKind::String => write!(f, "string"),
1017            ValueKind::Array => write!(f, "array"),
1018            ValueKind::Object => write!(f, "object"),
1019        }
1020    }
1021}
1022
1023impl<'buf> Value<'buf> {
1024    /// Returns which JSON kind this value is, discarding its content.
1025    pub fn kind(&self) -> ValueKind {
1026        match self {
1027            Value::Null => ValueKind::Null,
1028            Value::True | Value::False => ValueKind::Bool,
1029            Value::String(_) => ValueKind::String,
1030            Value::Number(_) => ValueKind::Number,
1031            Value::Array(_) => ValueKind::Array,
1032            Value::Object(_) => ValueKind::Object,
1033        }
1034    }
1035
1036    /// Return true if the `Value` is null.
1037    pub fn is_null(&self) -> bool {
1038        matches!(self, Value::Null)
1039    }
1040
1041    /// Return true if the `Value` is an object.
1042    pub fn is_object(&self) -> bool {
1043        matches!(self, Value::Object(..))
1044    }
1045
1046    /// Returns the items if this is a JSON array, `None` otherwise.
1047    pub fn as_array(&self) -> Option<&[Element<'buf>]> {
1048        if let Value::Array(elems) = self {
1049            Some(elems)
1050        } else {
1051            None
1052        }
1053    }
1054
1055    /// Return `Some(&str)` if the `Value` is a `String`.
1056    pub fn to_raw_str(&self) -> Option<RawStr<'buf>> {
1057        if let Value::String(s) = self {
1058            Some(*s)
1059        } else {
1060            None
1061        }
1062    }
1063
1064    /// Return `Some(&[Field])` if the `Value` is a `Object`.
1065    pub fn as_object_fields(&self) -> Option<&[Field<'buf>]> {
1066        if let Value::Object(fields) = self {
1067            Some(fields)
1068        } else {
1069            None
1070        }
1071    }
1072}
1073
1074/// An object field; upholds the invariant that the inner [`Element`]'s path ends with a key.
1075#[derive(Clone, Debug, Eq, PartialEq)]
1076pub(crate) struct Field<'buf> {
1077    /// Span of the key token, including surrounding `"` delimiters.
1078    key_span: Span,
1079    /// The value element; its path ends with the key from `key_span`.
1080    element: Element<'buf>,
1081}
1082
1083impl<'buf> Field<'buf> {
1084    /// Return the inner `Element`.
1085    pub fn element(&self) -> &Element<'buf> {
1086        &self.element
1087    }
1088
1089    /// Returns the key text without surrounding `"` delimiters.
1090    #[expect(
1091        clippy::arithmetic_side_effects,
1092        reason = "key_span always spans a quoted string, so +1/-1 to strip the surrounding quote bytes is safe"
1093    )]
1094    #[expect(
1095        clippy::string_slice,
1096        reason = "key_span is produced by the parser from the same source; +1/-1 strips the ASCII quote bytes"
1097    )]
1098    #[expect(
1099        clippy::as_conversions,
1100        reason = "The index is guaranteed within bounds by the parser"
1101    )]
1102    pub fn key(&self) -> RawStr<'buf> {
1103        let src = self.element.source();
1104        let s = &src[self.key_span.start as usize + 1..self.key_span.end as usize - 1];
1105        RawStr::from_str(s)
1106    }
1107}
1108
1109/// A `&str` with surrounding quotes removed; escape sequences are not decoded.
1110#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
1111pub(crate) struct RawStr<'buf>(&'buf str);
1112
1113/// Impl `Borrow` so `RawStr` plays well with hashed collections.
1114impl Borrow<str> for RawStr<'_> {
1115    fn borrow(&self) -> &str {
1116        self.0
1117    }
1118}
1119
1120/// Impl `Borrow` so `RawStr` plays well with hashed collections.
1121impl Borrow<str> for &RawStr<'_> {
1122    fn borrow(&self) -> &str {
1123        self.0
1124    }
1125}
1126
1127impl<'buf> RawStr<'buf> {
1128    fn from_str(source: &'buf str) -> Self {
1129        Self(source)
1130    }
1131
1132    /// Compare this raw `&str` against a list of `&str`s, decoding any JSON escape
1133    /// sequences in the `&str` on the fly without allocating.
1134    ///
1135    /// Returns true if any of the `other` `&str`s match self.
1136    pub fn eq_any_escape_aware(&self, other: &[&str]) -> bool {
1137        other
1138            .iter()
1139            .any(|s| decode::eq(self.0, s).ok().unwrap_or(false))
1140    }
1141
1142    /// Like [`RawStr::eq_any_escape_aware`], but compares ASCII letters case-insensitively.
1143    pub fn eq_any_escape_aware_ignore_ascii_case(&self, other: &[&str]) -> bool {
1144        other.iter().any(|s| {
1145            decode::eq_ignore_ascii_case(self.0, s)
1146                .ok()
1147                .unwrap_or(false)
1148        })
1149    }
1150
1151    /// Return the raw unescaped `&str`.
1152    pub fn as_unescaped_str(&self) -> &'buf str {
1153        self.0
1154    }
1155
1156    /// Return the `&str` with all escapes decoded, and any warning that decoding raised.
1157    ///
1158    /// When decoding raises a warning, the `&str` is returned as written, escapes included.
1159    pub(crate) fn decode_escapes(&self) -> (Cow<'buf, str>, Option<decode::Warning>) {
1160        decode::from_raw(self.0)
1161    }
1162
1163    /// Return this field name as a [`Key`].
1164    pub(crate) fn to_key(self) -> Key<'buf> {
1165        let (decoded, _warning) = self.decode_escapes();
1166
1167        // `decode_escapes` returns an owned name only when every escape decoded. It borrows the name
1168        // as written both when it has no escapes and when an escape fails to decode. Of those two,
1169        // only the second still has a backslash.
1170        match decoded {
1171            Cow::Owned(decoded) => Key::Decoded(decoded),
1172            Cow::Borrowed(raw) if raw.contains('\\') => Key::Malformed(raw),
1173            Cow::Borrowed(raw) => Key::Plain(raw),
1174        }
1175    }
1176
1177    /// Return a `&str` marked as either having escapes or not.
1178    pub(crate) fn has_escapes(
1179        &self,
1180        elem: &Element<'buf>,
1181        warnings: &mut dyn warning::Gather<decode::Warning>,
1182    ) -> PendingStr<'buf> {
1183        decode::analyze(self.0, elem, warnings)
1184    }
1185
1186    /// Report whether the string contains escape sequences and whether its decoded form
1187    /// contains non-printable ASCII, in a single pass without allocating.
1188    ///
1189    /// This combines the test for escape sequences with a printability check of the decoded
1190    /// string.
1191    pub fn lexical_issues(&self) -> LexicalIssues {
1192        decode::lexical_issues(self.0)
1193    }
1194}
1195
1196/// The lexical issues a [`RawStr`] may contain, discovered in a single pass by
1197/// [`RawStr::lexical_issues`].
1198#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1199pub(crate) struct LexicalIssues {
1200    /// The raw string contains one or more JSON escape sequences.
1201    pub escapes: bool,
1202
1203    /// The decoded string contains non-printable ASCII: an ASCII control character or
1204    /// ASCII whitespace.
1205    pub non_printable_ascii: bool,
1206}
1207
1208/// A field name, classified by whether it has escapes and whether they decode. The schema walk and
1209/// [`Document::last_of_repeated_keys`] both compare field names as `Key`s, which keeps the two in
1210/// agreement on which names are equal.
1211///
1212/// A `Plain` and a `Decoded` key are equal when their text is, so `"age"` and `"\u0061ge"` are the
1213/// same key, as RFC 8259 requires.
1214#[derive(Clone, Debug)]
1215pub(crate) enum Key<'buf> {
1216    /// A field name written without escapes.
1217    Plain(&'buf str),
1218
1219    /// A field name whose escapes all decode, stored decoded, so `"min\u005fkwh"` is the key
1220    /// `min_kwh`.
1221    Decoded(String),
1222
1223    /// A field name with an escape that fails to decode, stored as written. A `Malformed` key
1224    /// equals only another `Malformed` key written the same way.
1225    ///
1226    /// An object holding both `"a\\q"` and `"a\q"` has two different field names. The first
1227    /// decodes to the text `a\q`, which is how the second is written. Comparing a `Malformed` key
1228    /// as text would make the walk report the two as one field name written twice.
1229    Malformed(&'buf str),
1230}
1231
1232/// The form a [`Key`] is compared in. Two keys are equal when they are equal in this form.
1233///
1234/// `Key` has three variants because the schema walk raises a different warning for each, so `Key`
1235/// can't derive its comparisons. A derived `PartialEq` would make `Key::Plain("age")` unequal to
1236/// `Key::Decoded("age")`. Mapping both of those to `Text` lets this type derive the comparisons
1237/// instead, so equality and ordering can't disagree, which `BTreeSet` and `BTreeMap` rely on. A
1238/// `Malformed` key never equals a `Text` one, because the two are different variants.
1239#[derive(Eq, Ord, PartialEq, PartialOrd)]
1240enum ComparedKey<'a> {
1241    Text(&'a str),
1242    Malformed(&'a str),
1243}
1244
1245impl Key<'_> {
1246    /// Returns the field name, with any escapes decoded. Returns `None` for a `Malformed` key,
1247    /// because one of its escapes fails to decode and the name it stands for is unknown.
1248    pub(crate) fn name(&self) -> Option<&str> {
1249        match self {
1250            Self::Plain(name) => Some(name),
1251            Self::Decoded(name) => Some(name),
1252            Self::Malformed(_raw) => None,
1253        }
1254    }
1255
1256    fn compared(&self) -> ComparedKey<'_> {
1257        match self {
1258            Self::Plain(name) => ComparedKey::Text(name),
1259            Self::Decoded(name) => ComparedKey::Text(name),
1260            Self::Malformed(raw) => ComparedKey::Malformed(raw),
1261        }
1262    }
1263}
1264
1265impl PartialEq for Key<'_> {
1266    fn eq(&self, other: &Self) -> bool {
1267        self.compared() == other.compared()
1268    }
1269}
1270
1271impl Eq for Key<'_> {}
1272
1273impl PartialOrd for Key<'_> {
1274    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1275        Some(self.cmp(other))
1276    }
1277}
1278
1279impl Ord for Key<'_> {
1280    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
1281        self.compared().cmp(&other.compared())
1282    }
1283}
1284
1285/// Marks a `&str` as having escapes or not.
1286pub(crate) enum PendingStr<'buf> {
1287    /// The `&str` has no escapes and can be used as is.
1288    NoEscapes(&'buf str),
1289
1290    /// The `&str` has escape chars and needs to be unescaped before trying to parse into another form.
1291    HasEscapes,
1292}