Skip to main content

ocpi_tariffs/json/
parser.rs

1//! Hand-rolled single-pass recursive-descent JSON parser.
2//!
3//! # Responsibilities
4//!
5//! The parser is responsible for structural correctness only: balanced delimiters,
6//! valid top-level values, and well-formed numbers. String content is captured as
7//! [`RawStr`] slices of the source — escape sequences and control characters are
8//! left untouched. Validation of string content is the responsibility of
9//! [`crate::json::decode`].
10//!
11//! # Output
12//!
13//! [`parse`] returns a [`Document`] that wraps the root [`Element`] and the shared
14//! [`DocumentInner`]. Every element carries an `Rc<DocumentInner>` so it can resolve
15//! its own path after the [`Document`] has been dropped.
16//!
17//! # Limits
18//!
19//! - **Nesting depth**: capped at [`MAX_DEPTH`]. Inputs that exceed this are rejected with
20//!   [`ErrorKind::DepthLimitExceeded`].
21//! - **Element count**: capped at `u32::MAX` by the [`ElemId`] counter, enforced via
22//!   [`ErrorKind::MaxElements`]. In practice, the 5 megabytes [`string::ReasonableLen`] gate makes
23//!   this limit unreachable at the moment.
24//!
25//! # Two-phase construction
26//!
27//! The [`Parser`] builds a private [`RawElement`] tree and a [`PathTable`] in one
28//! pass. Once the full tree is available, [`into_element`] threads the shared
29//! `Rc<DocumentInner>` through every node to produce the public [`Element`] tree.
30//! This keeps the hot parsing loop free of reference-counting overhead.
31
32#![expect(
33    clippy::arithmetic_side_effects,
34    reason = "pos is bounded by source.len() and only advances after a successful byte read; arithmetic is safe within parser state machine invariants"
35)]
36#![expect(
37    clippy::as_conversions,
38    reason = "byte position casts between usize and u32 are safe: usize->u32 is bounded by available memory, u32->usize always fits"
39)]
40#![expect(
41    clippy::cast_possible_truncation,
42    reason = "source length is bounded by available memory, so byte positions always fit in u32"
43)]
44#![expect(
45    clippy::string_slice,
46    reason = "span boundaries are always at ASCII JSON token boundaries, so slices are valid UTF-8"
47)]
48
49#[cfg(test)]
50mod test_send_and_sync;
51
52#[cfg(test)]
53mod test_basics;
54
55#[cfg(test)]
56mod test_parser;
57
58#[cfg(test)]
59mod test_type_sizes;
60
61use std::rc::Rc;
62
63use crate::{string, warning};
64
65use super::{
66    Document, DocumentInner, ElemId, Element, Field, Location, PathEntry, PathTable, RawStr, Span,
67    Value,
68};
69
70/// Maximum nesting depth for arrays and objects.
71///
72/// `parse_array` and `parse_object` recurse through `parse_value`, so without a limit the
73/// input decides how deep the stack goes. RFC 8259 does not mandate a depth: section 9 permits
74/// a parser to set a limit without recommending one, so this limit is the library's. Inputs
75/// that exceed the limit are rejected with [`ErrorKind::DepthLimitExceeded`].
76const MAX_DEPTH: usize = 16;
77
78// JSON whitespace characters `RFC 8259 s2`.
79const SPACE: u8 = b' ';
80const TAB: u8 = b'\t';
81const LF: u8 = b'\n';
82const CR: u8 = b'\r';
83
84// The string `quotation-mark` and `escape` of `RFC 8259 s7`.
85const QUOTE: u8 = b'"';
86const BACKSLASH: u8 = b'\\';
87
88// Structural characters `RFC 8259 s2`.
89const COMMA: u8 = b',';
90const COLON: u8 = b':';
91const ARRAY_OPEN: u8 = b'[';
92const ARRAY_CLOSE: u8 = b']';
93const OBJECT_OPEN: u8 = b'{';
94const OBJECT_CLOSE: u8 = b'}';
95
96// Number-grammar characters `RFC 8259 s6`.
97const MINUS: u8 = b'-';
98const PLUS: u8 = b'+';
99const DECIMAL_POINT: u8 = b'.';
100const EXP_LOWER: u8 = b'e';
101const EXP_UPPER: u8 = b'E';
102const DIGIT_0: u8 = b'0';
103const DIGIT_1: u8 = b'1';
104const DIGIT_9: u8 = b'9';
105
106// JSON keyword literals `RFC 8259 s3`.
107const NULL: &str = "null";
108const TRUE: &str = "true";
109const FALSE: &str = "false";
110
111// UTF-8 BOM (`U+FEFF`, encoded as 0xEF 0xBB 0xBF).
112const BOM: &[u8; 3] = b"\xEF\xBB\xBF";
113
114/// Parse a JSON document from `source`.
115///
116/// All string content in the returned tree borrows from `source`.
117///
118/// Call [`Element::path`] on any element for the [`Path`](super::Path) locating it.
119pub(crate) fn parse(source: string::ReasonableLen<'_>) -> Result<Document<'_>, Error> {
120    let mut p = Parser::new(source.into_inner());
121    // Skip a UTF-8 BOM if present. An editor hides the BOM, so `location` stays at the
122    // start of line 1. Calling `chomp` on each byte would count the BOM as a column.
123    if p.bytes.starts_with(BOM) {
124        p.pos = BOM.len();
125    }
126    let raw_root = p.parse_value(PathEntry::Root)?;
127    p.skip_ws();
128    if p.pos < p.bytes.len() {
129        return Err(p.error(ErrorKind::TrailingContent));
130    }
131    let inner = Rc::new(DocumentInner {
132        source: source.into_inner(),
133        paths: p.table,
134    });
135    let root = into_element(raw_root, &inner);
136    Ok(Document { inner, root })
137}
138
139/// A parse error produced when the input is not well-formed JSON.
140///
141/// Carries the byte offset and line/column position of the failure, and an
142/// [`ErrorKind`] that describes what was wrong.
143#[derive(Debug, Eq, PartialEq)]
144pub struct Error {
145    /// Byte offset of the error location.
146    byte_offset: usize,
147    /// A file location expressed as line and column.
148    position: Location,
149    /// The details about the error that occurred.
150    kind: ErrorKind,
151}
152
153impl Error {
154    /// Byte offset of the error location.
155    pub fn byte_offset(&self) -> usize {
156        self.byte_offset
157    }
158
159    /// Return a reference to the details about the error that occurred.
160    pub fn kind(&self) -> &ErrorKind {
161        &self.kind
162    }
163
164    /// Consume the `Error` and return the details about the error that occurred.
165    pub fn into_kind(self) -> ErrorKind {
166        self.kind
167    }
168
169    /// Consume the `Error` and return the byte offset of the error location and the details of the
170    /// error that occurred.
171    pub fn into_parts(self) -> (usize, ErrorKind) {
172        (self.byte_offset, self.kind)
173    }
174}
175
176/// The specific reason a [`crate::json::parse_object`] call failed.
177#[derive(Debug, Eq, PartialEq)]
178pub enum ErrorKind {
179    /// A character that cannot be a JSON number was encountered.
180    ExpectedNumeral,
181    /// A character that cannot start a JSON value was encountered.
182    ExpectedStart,
183    /// A literal that cannot start or continue a JSON value was encountered.
184    ExpectedLiteral {
185        /// The literal the parser was part-way through matching.
186        expected: &'static str,
187    },
188    /// An array wasn't terminated correctly.
189    ExpectedEndArray,
190    /// An object wasn't terminated correctly.
191    ExpectedEndObject,
192    /// A character that cannot continue a JSON value was encountered.
193    UnexpectedChar {
194        /// The character the grammar required at this position.
195        expected: char,
196    },
197    /// The input ended before the value was complete.
198    UnexpectedEOF,
199    /// Non-whitespace bytes follow the root value.
200    TrailingContent,
201    /// The input exceeds the maximum supported nesting depth.
202    DepthLimitExceeded,
203    /// The input contains more than [`u32::MAX`] JSON elements.
204    MaxElements,
205}
206
207impl crate::Warning for Error {
208    fn id(&self) -> warning::Id {
209        let s = match self.kind {
210            ErrorKind::ExpectedNumeral => "expected_numeral",
211            ErrorKind::ExpectedStart => "expected_start",
212            ErrorKind::ExpectedLiteral { expected: _ } => "expected_literal",
213            ErrorKind::ExpectedEndArray => "expected_end_array",
214            ErrorKind::ExpectedEndObject => "expected_end_object",
215            ErrorKind::UnexpectedChar { expected: _ } => "unexpected_char",
216            ErrorKind::UnexpectedEOF => "unexpected_eof",
217            ErrorKind::TrailingContent => "trailing_content",
218            ErrorKind::DepthLimitExceeded => "depth_limit_exceeded",
219            ErrorKind::MaxElements => "max_elements",
220        };
221
222        warning::Id::from_static(s)
223    }
224}
225
226impl std::fmt::Display for Error {
227    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
228        let Self {
229            byte_offset,
230            position,
231            kind,
232        } = self;
233
234        match kind {
235            ErrorKind::ExpectedLiteral { expected } => {
236                write!(
237                    f,
238                    "unexpected literal found at location `{position}`, byte `{byte_offset}`; expected: `{expected:?}`"
239                )
240            }
241            ErrorKind::ExpectedNumeral => {
242                write!(
243                    f,
244                    "unexpected numeral found at location `{position}`, byte `{byte_offset}`; expected: `0-9`"
245                )
246            }
247            ErrorKind::ExpectedStart => {
248                write!(
249                    f,
250                    "unexpected start character found at location `{position}`, byte `{byte_offset}`; expected one of: `[n, t, f, \", -, 0-9, [, {{]`"
251                )
252            }
253            ErrorKind::ExpectedEndArray => {
254                write!(
255                    f,
256                    "unexpected character found at location `{position}`, byte `{byte_offset}`; expected: `,` or `]`"
257                )
258            }
259            ErrorKind::ExpectedEndObject => {
260                write!(
261                    f,
262                    "unexpected character found at location `{position}`, byte `{byte_offset}`; expected: `,` or `}}`"
263                )
264            }
265            ErrorKind::UnexpectedChar { expected } => {
266                write!(
267                    f,
268                    "unexpected character `{expected}` found at location `{position}`, byte `{byte_offset}``"
269                )
270            }
271            ErrorKind::UnexpectedEOF => write!(
272                f,
273                "unexpected end of input found at location `{position}`, byte `{byte_offset}`"
274            ),
275            ErrorKind::TrailingContent => write!(
276                f,
277                "trailing content found at location `{position}`, byte `{byte_offset}`"
278            ),
279            ErrorKind::DepthLimitExceeded => {
280                write!(f, "nesting depth exceeds the {MAX_DEPTH}-level limit")
281            }
282            ErrorKind::MaxElements => write!(f, "document exceeds {} JSON elements", u32::MAX),
283        }
284    }
285}
286
287impl std::error::Error for Error {}
288
289/// Parser-private element tree; carries no reference to [`DocumentInner`].
290///
291/// Converted to the public [`Element`] tree by [`into_element`] after
292/// [`DocumentInner`] is constructed.
293struct RawElement<'buf> {
294    /// Unique identifier within the document; sequentially assigned depth-first.
295    id: ElemId,
296    /// Byte range of the value only; use for replacement edits.
297    span: Span,
298    /// End of the value plus any trailing comma and whitespace; use for removal edits.
299    /// Equal to `span.end` when there is no trailing comma (root element, or last sibling).
300    full_span_end: u32,
301    /// Parsed value, borrowing from the source `&str`.
302    value: RawValue<'buf>,
303}
304
305/// The parsed content of a [`RawElement`], mirroring [`Value`] but without [`DocumentInner`].
306///
307/// Strings are kept as [`RawStr`] slices of the source; numbers are kept as
308/// raw `&str` slices. Both are converted to their public forms by [`into_element`].
309enum RawValue<'buf> {
310    /// JSON `null` literal.
311    Null,
312    /// JSON `true` literal.
313    True,
314    /// JSON `false` literal.
315    False,
316    /// String content with quotes removed; escape sequences are not decoded.
317    String(RawStr<'buf>),
318    /// Raw number text; not guaranteed to fit any specific numeric type.
319    Number(&'buf str),
320    /// Ordered list of child elements.
321    Array(Vec<RawElement<'buf>>),
322    /// Ordered list of key-value fields.
323    Object(Vec<RawField<'buf>>),
324}
325
326/// A key-value pair inside a JSON object, mirroring [`Field`] but without [`DocumentInner`].
327///
328/// `key_span` covers the quoted key bytes in the source, including the surrounding
329/// double-quotes. The value is stored as a [`RawElement`].
330struct RawField<'buf> {
331    /// Span of the key token, including surrounding `"` delimiters.
332    key_span: Span,
333    /// The value element; its path ends with the key from `key_span`.
334    element: RawElement<'buf>,
335}
336
337/// Single-pass recursive-descent JSON parser.
338///
339/// Holds all mutable state for one parse: the source string, a byte cursor, an
340/// [`ElemId`] counter, the [`PathTable`] being built, and a nesting-depth guard.
341///
342/// Call [`Parser::new`] to create an instance, then [`Parser::parse_value`] to
343/// drive the parse. The result is a [`RawElement`] tree; pass it together with
344/// the completed [`PathTable`] to [`into_element`] to obtain the public
345/// [`Element`] tree with shared [`DocumentInner`] attached.
346struct Parser<'buf> {
347    /// The full source string; all span byte positions are relative to this.
348    source: &'buf str,
349    /// Byte view of `source`; used for index-based reads without UTF-8 overhead.
350    bytes: &'buf [u8],
351    /// Current read position in bytes.
352    pos: usize,
353    /// Counter for assigning sequential [`ElemId`]s depth-first.
354    next_id: usize,
355    /// Path table being built as elements are parsed.
356    table: PathTable<'buf>,
357    /// Current nesting depth; checked against [`MAX_DEPTH`] on each container open.
358    depth: usize,
359    /// The location of the byte at `pos`, counted the way an editor counts.
360    /// `chomp` moves `pos` and steps this location over each byte it passes.
361    /// `parse` moves `pos` alone once, past a leading byte order mark, because an editor hides
362    /// the mark. Moving `pos` any other way would leave this location behind.
363    location: Location,
364}
365
366impl<'buf> Parser<'buf> {
367    /// Creates a `Parser` that will read from `source`.
368    fn new(source: &'buf str) -> Self {
369        Self {
370            source,
371            bytes: source.as_bytes(),
372            pos: 0,
373            next_id: 0,
374            table: PathTable::default(),
375            depth: 0,
376            location: Location { line: 0, col: 0 },
377        }
378    }
379
380    /// Allocates the next sequential [`ElemId`] and advances the counter.
381    fn alloc_id(&mut self) -> Result<ElemId, Error> {
382        let id = ElemId(self.next_id);
383        self.next_id = self
384            .next_id
385            .checked_add(1)
386            .ok_or_else(|| self.error(ErrorKind::MaxElements))?;
387        Ok(id)
388    }
389
390    /// Advances past any JSON whitespace (`space`, `tab`, `CR`, `LF`) at the current position.
391    fn skip_ws(&mut self) {
392        while matches!(self.bytes.get(self.pos), Some(&SPACE | &TAB | &LF | &CR)) {
393            self.chomp();
394        }
395    }
396
397    /// Returns the byte at the current position without advancing, or `None` at end of input.
398    fn peek(&self) -> Option<u8> {
399        self.bytes.get(self.pos).copied()
400    }
401
402    /// Advances the cursor by one byte.
403    #[inline]
404    fn chomp(&mut self) {
405        if let Some(&byte) = self.bytes.get(self.pos) {
406            self.location = self.location.advance(byte);
407        }
408        self.pos += 1;
409    }
410
411    /// Create and return an `Error`.
412    fn error(&self, kind: ErrorKind) -> Error {
413        Error {
414            byte_offset: self.pos,
415            position: self.location,
416            kind,
417        }
418    }
419
420    /// Returns the byte at the current position and advances past it, or `None` at end of input.
421    fn advance(&mut self) -> Option<u8> {
422        let b = self.bytes.get(self.pos).copied();
423        if b.is_some() {
424            self.chomp();
425        }
426        b
427    }
428
429    /// Asserts that the next byte equals `byte` and advances past it.
430    ///
431    /// Returns [`ErrorKind::UnexpectedChar`] if a different byte is present, or
432    /// [`ErrorKind::UnexpectedEOF`] if the input is exhausted.
433    fn expect_byte(&mut self, byte: u8) -> Result<(), Error> {
434        match self.bytes.get(self.pos) {
435            Some(&b) if b == byte => {
436                self.chomp();
437                Ok(())
438            }
439            Some(_) => Err(self.error(ErrorKind::UnexpectedChar {
440                expected: char::from(byte),
441            })),
442            None => Err(self.error(ErrorKind::UnexpectedEOF)),
443        }
444    }
445
446    /// Asserts that the next bytes match `literal` byte-for-byte, advancing past them.
447    ///
448    /// Used for JSON keywords (`null`, `true`, `false`). The caller dispatches via
449    /// [`Self::peek`] without consuming the first byte, so `literal` must include it.
450    fn expect_literal(&mut self, literal: &'static str) -> Result<(), Error> {
451        for &expected in literal.as_bytes() {
452            match self.peek() {
453                Some(b) if b == expected => self.chomp(),
454                Some(_) => {
455                    return Err(self.error(ErrorKind::ExpectedLiteral { expected: literal }));
456                }
457                None => return Err(self.error(ErrorKind::UnexpectedEOF)),
458            }
459        }
460        Ok(())
461    }
462
463    /// Parses one JSON value preceded by optional whitespace and returns a fully-formed [`Element`].
464    ///
465    /// Allocates an [`ElemId`] and records the path `entry` and the value's location before
466    /// dispatching to [`Self::parse_value_kind`], so child elements produced during that call
467    /// already find this element's id in the table as their parent.
468    fn parse_value(&mut self, entry: PathEntry<'buf>) -> Result<RawElement<'buf>, Error> {
469        self.skip_ws();
470        // ID and table entry are registered before recursing so that child elements
471        // produced by parse_value_kind see this id as their parent.
472        let id = self.alloc_id()?;
473        self.table.push(entry, self.location);
474        let start = self.pos;
475        let value = self.parse_value_kind(id)?;
476        let span = Span::new(start as u32, self.pos as u32);
477        Ok(RawElement {
478            id,
479            span,
480            // The parent container extends this past the trailing comma and whitespace
481            // when it exists, so that the element's removal span covers its own separator.
482            full_span_end: span.end,
483            value,
484        })
485    }
486
487    /// Dispatches to the type-specific parser based on the first byte of the value.
488    ///
489    /// `id` is this element's own [`ElemId`], threaded down to [`Self::parse_array`]
490    /// and [`Self::parse_object`] so they can record it as the parent of their children.
491    fn parse_value_kind(&mut self, id: ElemId) -> Result<RawValue<'buf>, Error> {
492        match self
493            .peek()
494            .ok_or_else(|| self.error(ErrorKind::UnexpectedEOF))?
495        {
496            b'n' => {
497                self.expect_literal(NULL)?;
498                Ok(RawValue::Null)
499            }
500            b't' => {
501                self.expect_literal(TRUE)?;
502                Ok(RawValue::True)
503            }
504            b'f' => {
505                self.expect_literal(FALSE)?;
506                Ok(RawValue::False)
507            }
508            QUOTE => Ok(RawValue::String(self.parse_raw_str()?)),
509            MINUS | DIGIT_0..=DIGIT_9 => Ok(RawValue::Number(self.parse_number_str()?)),
510            ARRAY_OPEN => self.parse_array(id),
511            OBJECT_OPEN => self.parse_object(id),
512            _ => Err(self.error(ErrorKind::ExpectedStart)),
513        }
514    }
515
516    /// Parses a JSON number and returns the raw source slice.
517    ///
518    /// Grammar `RFC 8259 s6`:
519    /// ```text
520    /// number = [ '-' ] int [ frac ] [ exp ]
521    /// int    = '0' | [1-9] DIGIT*
522    /// frac   = '.' DIGIT+
523    /// exp    = ('e'|'E') ['+'|'-'] DIGIT+
524    /// ```
525    fn parse_number_str(&mut self) -> Result<&'buf str, Error> {
526        let start = self.pos;
527
528        if self.peek() == Some(MINUS) {
529            self.chomp();
530        }
531
532        match self
533            .peek()
534            .ok_or_else(|| self.error(ErrorKind::UnexpectedEOF))?
535        {
536            // A lone '0' is the only valid integer starting with zero; more digits
537            // after it would be a leading-zero violation (e.g. "01" is invalid JSON).
538            DIGIT_0 => self.chomp(),
539            DIGIT_1..=DIGIT_9 => {
540                while matches!(self.peek(), Some(DIGIT_0..=DIGIT_9)) {
541                    self.chomp();
542                }
543            }
544            _ => return Err(self.error(ErrorKind::ExpectedNumeral)),
545        }
546
547        if self.peek() == Some(DECIMAL_POINT) {
548            self.chomp();
549            // At least one digit is required after the decimal point.
550            if !matches!(self.peek(), Some(DIGIT_0..=DIGIT_9)) {
551                return Err(match self.peek() {
552                    Some(_) => self.error(ErrorKind::ExpectedNumeral),
553                    None => self.error(ErrorKind::UnexpectedEOF),
554                });
555            }
556            while matches!(self.peek(), Some(DIGIT_0..=DIGIT_9)) {
557                self.chomp();
558            }
559        }
560
561        if matches!(self.peek(), Some(EXP_LOWER | EXP_UPPER)) {
562            self.chomp();
563            if matches!(self.peek(), Some(PLUS | MINUS)) {
564                self.chomp();
565            }
566            // At least one digit is required after the exponent indicator (and optional sign).
567            if !matches!(self.peek(), Some(DIGIT_0..=DIGIT_9)) {
568                return Err(match self.peek() {
569                    Some(_) => self.error(ErrorKind::ExpectedNumeral),
570                    None => self.error(ErrorKind::UnexpectedEOF),
571                });
572            }
573            while matches!(self.peek(), Some(DIGIT_0..=DIGIT_9)) {
574                self.chomp();
575            }
576        }
577
578        Ok(&self.source[start..self.pos])
579    }
580
581    /// Parses a JSON string and returns a [`RawStr`] with quotes stripped.
582    ///
583    /// Scans for the closing `"` delimiter, skipping one byte after every `\`
584    /// so that `\"` does not terminate the string. Escape sequences and control
585    /// characters are not validated here; callers use [`RawStr::decode_escapes`].
586    fn parse_raw_str(&mut self) -> Result<RawStr<'buf>, Error> {
587        self.expect_byte(QUOTE)?;
588        let content_start = self.pos; // First byte after the opening `"`.
589
590        loop {
591            match self
592                .advance()
593                .ok_or_else(|| self.error(ErrorKind::UnexpectedEOF))?
594            {
595                QUOTE => break,
596                BACKSLASH => {
597                    // Consume whatever follows so that `\"` does not close the string.
598                    self.advance()
599                        .ok_or_else(|| self.error(ErrorKind::UnexpectedEOF))?;
600                }
601                _ => {}
602            }
603        }
604
605        // `advance()` left `pos` one past the closing '"', so `pos-1` is the '"' itself;
606        // `content_start..pos-1` therefore captures content without either delimiter.
607        Ok(RawStr(&self.source[content_start..self.pos - 1]))
608    }
609
610    /// Parses a JSON array `[...]` and returns [`Value::Array`].
611    ///
612    /// Increments the depth counter before consuming `[` and returns
613    /// [`ErrorKind::DepthLimitExceeded`] if the limit is exceeded.
614    fn parse_array(&mut self, parent_id: ElemId) -> Result<RawValue<'buf>, Error> {
615        self.depth += 1;
616        if self.depth > MAX_DEPTH {
617            return Err(self.error(ErrorKind::DepthLimitExceeded));
618        }
619        self.expect_byte(ARRAY_OPEN)?;
620        self.skip_ws();
621        let mut elements: Vec<RawElement<'buf>> = Vec::new();
622
623        if self.peek() != Some(ARRAY_CLOSE) {
624            loop {
625                let entry = PathEntry::Item {
626                    parent: parent_id,
627                    index: elements.len() as u32,
628                };
629                let mut elem = self.parse_value(entry)?;
630                self.skip_ws();
631                match self
632                    .peek()
633                    .ok_or_else(|| self.error(ErrorKind::UnexpectedEOF))?
634                {
635                    COMMA => {
636                        self.chomp();
637                        self.skip_ws();
638                        if self.peek() == Some(ARRAY_CLOSE) {
639                            return Err(self.error(ErrorKind::ExpectedEndArray));
640                        }
641                        // Extend past the comma and leading whitespace of the next sibling
642                        // so that removing this element also removes its own separator.
643                        elem.full_span_end = self.pos as u32;
644                        elements.push(elem);
645                    }
646                    ARRAY_CLOSE => {
647                        elements.push(elem);
648                        break;
649                    }
650                    _ => return Err(self.error(ErrorKind::ExpectedEndArray)),
651                }
652            }
653        }
654
655        self.expect_byte(ARRAY_CLOSE)?;
656        self.depth -= 1;
657        Ok(RawValue::Array(elements))
658    }
659
660    /// Parses a JSON object `{...}` and returns [`Value::Object`].
661    ///
662    /// Increments the depth counter before consuming `{` and returns
663    /// [`ErrorKind::DepthLimitExceeded`] if the limit is exceeded.
664    fn parse_object(&mut self, parent_id: ElemId) -> Result<RawValue<'buf>, Error> {
665        self.depth += 1;
666        if self.depth > MAX_DEPTH {
667            return Err(self.error(ErrorKind::DepthLimitExceeded));
668        }
669        self.expect_byte(OBJECT_OPEN)?;
670        self.skip_ws();
671        let mut fields: Vec<RawField<'buf>> = Vec::new();
672
673        if self.peek() != Some(OBJECT_CLOSE) {
674            loop {
675                let key_start = self.pos;
676                let key = self.parse_raw_str()?;
677                let key_span = Span::new(key_start as u32, self.pos as u32);
678                self.skip_ws();
679                self.expect_byte(COLON)?;
680                let entry = PathEntry::Field {
681                    parent: parent_id,
682                    key,
683                };
684                let mut elem = self.parse_value(entry)?;
685                self.skip_ws();
686                match self
687                    .peek()
688                    .ok_or_else(|| self.error(ErrorKind::UnexpectedEOF))?
689                {
690                    COMMA => {
691                        self.chomp();
692                        self.skip_ws();
693                        if self.peek() == Some(OBJECT_CLOSE) {
694                            return Err(self.error(ErrorKind::ExpectedEndObject));
695                        }
696                        // Same as in parse_array: extend past the comma and whitespace
697                        // so that removing this field also removes its own separator.
698                        elem.full_span_end = self.pos as u32;
699                        fields.push(RawField {
700                            key_span,
701                            element: elem,
702                        });
703                    }
704                    OBJECT_CLOSE => {
705                        fields.push(RawField {
706                            key_span,
707                            element: elem,
708                        });
709                        break;
710                    }
711                    _ => return Err(self.error(ErrorKind::ExpectedEndObject)),
712                }
713            }
714        }
715
716        self.expect_byte(OBJECT_CLOSE)?;
717        self.depth -= 1;
718        Ok(RawValue::Object(fields))
719    }
720}
721
722/// Converts a [`RawElement`] tree into the public [`Element`] tree, loading every
723/// node with a clone of `inner` at construction time.
724///
725/// Uses an explicit work stack instead of recursion. Children are pushed in
726/// reverse so they are processed in order; each `Build*` task then pops its
727/// children off `done` and assembles the parent.
728fn into_element<'buf>(raw: RawElement<'buf>, inner: &Rc<DocumentInner<'buf>>) -> Element<'buf> {
729    enum Task<'buf> {
730        Process(RawElement<'buf>),
731        BuildArray {
732            id: ElemId,
733            span: Span,
734            full_span_end: u32,
735            count: usize,
736        },
737        BuildObject {
738            id: ElemId,
739            span: Span,
740            full_span_end: u32,
741            key_spans: Vec<Span>,
742        },
743    }
744
745    let mut work: Vec<Task<'buf>> = vec![Task::Process(raw)];
746    let mut done: Vec<Element<'buf>> = Vec::new();
747
748    while let Some(task) = work.pop() {
749        match task {
750            Task::Process(raw) => {
751                let value = match raw.value {
752                    RawValue::Null => Value::Null,
753                    RawValue::True => Value::True,
754                    RawValue::False => Value::False,
755                    RawValue::String(s) => Value::String(s),
756                    RawValue::Number(n) => Value::Number(n),
757                    RawValue::Array(items) => {
758                        work.push(Task::BuildArray {
759                            id: raw.id,
760                            span: raw.span,
761                            full_span_end: raw.full_span_end,
762                            count: items.len(),
763                        });
764                        for item in items.into_iter().rev() {
765                            work.push(Task::Process(item));
766                        }
767                        continue;
768                    }
769                    RawValue::Object(fields) => {
770                        let key_spans = fields.iter().map(|f| f.key_span).collect();
771                        work.push(Task::BuildObject {
772                            id: raw.id,
773                            span: raw.span,
774                            full_span_end: raw.full_span_end,
775                            key_spans,
776                        });
777                        for field in fields.into_iter().rev() {
778                            work.push(Task::Process(field.element));
779                        }
780                        continue;
781                    }
782                };
783                done.push(Element {
784                    doc: Rc::clone(inner),
785                    id: raw.id,
786                    span: raw.span,
787                    full_span_end: raw.full_span_end,
788                    value,
789                });
790            }
791            Task::BuildArray {
792                id,
793                span,
794                full_span_end,
795                count,
796            } => {
797                let start = done.len() - count;
798                let items: Vec<Element<'buf>> = done.drain(start..).collect();
799                done.push(Element {
800                    doc: Rc::clone(inner),
801                    id,
802                    span,
803                    full_span_end,
804                    value: Value::Array(items),
805                });
806            }
807            Task::BuildObject {
808                id,
809                span,
810                full_span_end,
811                key_spans,
812            } => {
813                let count = key_spans.len();
814                let start = done.len() - count;
815                let elements: Vec<Element<'buf>> = done.drain(start..).collect();
816                let fields = key_spans
817                    .into_iter()
818                    .zip(elements)
819                    .map(|(key_span, element)| Field { key_span, element })
820                    .collect();
821                done.push(Element {
822                    doc: Rc::clone(inner),
823                    id,
824                    span,
825                    full_span_end,
826                    value: Value::Object(fields),
827                });
828            }
829        }
830    }
831
832    // Each Process task produces exactly one element in `done`, either directly
833    // (scalars) or via a Build task (containers). Starting with one root Process
834    // task guarantees exactly one element remains here.
835    done.swap_remove(0)
836}