Skip to main content

granit_parser/
parser_stack.rs

1use crate::{
2    error::{ErrorKind, ScanError},
3    input::{str::StrInput, BorrowedInput, BufferedInput},
4    parser::{Event, ParseResult, Parser, ParserTrait, SpannedEventReceiver},
5    scanner::Span,
6    Options,
7};
8use alloc::{borrow::Cow, boxed::Box, string::String, vec::Vec};
9
10/// An opaque source key supplied by a caller of [`ParserStack`].
11///
12/// The parser does not interpret this value or assign meaning to equal source names.
13/// Callers can use different keys for separate inclusions of the same named source.
14#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
15pub struct SourceId(pub u64);
16
17/// A value together with the source that produced it.
18///
19/// Sources pushed without an explicit key have `source_id: None`. On an error,
20/// the key still identifies the failing source even if its parser has been popped.
21#[derive(Clone, Debug)]
22#[non_exhaustive]
23pub struct Sourced<T> {
24    /// The caller-supplied source key, if any.
25    pub source_id: Option<SourceId>,
26    /// The event, parse result, or error associated with the source.
27    pub value: T,
28}
29
30/// A lightweight parser that replays a pre-collected event stream.
31pub struct ReplayParser<'input> {
32    events: alloc::vec::IntoIter<(Event<'input>, Span)>,
33    anchor_offset: usize,
34}
35
36impl<'input> ReplayParser<'input> {
37    /// Replay `events` with their recorded anchor IDs and start the counter at `anchor_offset`.
38    ///
39    /// The counter advances as anchored events are consumed. If another parser may be pushed
40    /// during replay, pass the recording parser's [`Parser::anchor_offset`] after collecting
41    /// the events to reserve the IDs in unread events as well.
42    #[must_use]
43    pub fn new(events: Vec<(Event<'input>, Span)>, anchor_offset: usize) -> Self {
44        Self {
45            events: events.into_iter(),
46            anchor_offset,
47        }
48    }
49
50    /// Return the next anchor ID that should be assigned after replayed events.
51    #[must_use]
52    pub fn anchor_offset(&self) -> usize {
53        self.anchor_offset
54    }
55
56    /// Set the next anchor ID that should be assigned after replayed events.
57    pub fn set_anchor_offset(&mut self, offset: usize) {
58        self.anchor_offset = offset;
59    }
60
61    fn advance_anchor_offset(&mut self, event: &Event<'input>) {
62        if let Some(anchor_id) = event.anchor_id() {
63            self.anchor_offset = self.anchor_offset.max(anchor_id.saturating_add(1));
64        }
65    }
66}
67
68impl<'input> ParserTrait<'input> for ReplayParser<'input> {
69    fn peek(&mut self) -> Option<Result<&(Event<'input>, Span), ScanError>> {
70        self.events.as_slice().first().map(Ok)
71    }
72
73    fn next_event(&mut self) -> Option<ParseResult<'input>> {
74        let event = self.events.next()?;
75        self.advance_anchor_offset(&event.0);
76        Some(Ok(event))
77    }
78
79    fn load<R: SpannedEventReceiver<'input>>(
80        &mut self,
81        recv: &mut R,
82        multi: bool,
83    ) -> Result<(), ScanError> {
84        while let Some(res) = self.next_event() {
85            let (ev, span) = res?;
86            let is_doc_end = matches!(ev, Event::DocumentEnd { .. });
87            let is_stream_end = matches!(ev, Event::StreamEnd);
88            recv.on_event(ev, span);
89            if is_stream_end {
90                break;
91            }
92            if !multi && is_doc_end {
93                break;
94            }
95        }
96        Ok(())
97    }
98}
99
100impl<'input> Iterator for ReplayParser<'input> {
101    type Item = ParseResult<'input>;
102
103    fn next(&mut self) -> Option<Self::Item> {
104        self.next_event()
105    }
106}
107
108impl core::iter::FusedIterator for ReplayParser<'_> {}
109
110/// A wrapper for different types of parsers.
111enum AnyParser<'input, I, T>
112where
113    I: Iterator<Item = char>,
114    T: BorrowedInput<'input>,
115{
116    /// A parser over borrowed string input.
117    String {
118        /// Parser currently producing events for this stack entry.
119        parser: Parser<'input, StrInput<'input>>,
120        /// Human-readable source name returned by [`ParserStack::stack`].
121        name: String,
122        /// Opaque caller-supplied source identity.
123        source_id: Option<SourceId>,
124    },
125    /// A parser over an iterator of characters.
126    Iter {
127        /// Parser currently producing events for this stack entry.
128        parser: Parser<'static, BufferedInput<I>>,
129        /// Human-readable source name returned by [`ParserStack::stack`].
130        name: String,
131        /// Opaque caller-supplied source identity.
132        source_id: Option<SourceId>,
133    },
134    /// A parser over a custom input.
135    Custom {
136        /// Parser currently producing events for this stack entry.
137        parser: Parser<'input, T>,
138        /// Event consumed by the caller before pushing this parser.
139        primed: Option<(Event<'input>, Span)>,
140        /// First ID available to a primed child at push time. Zero disables the check.
141        anchor_floor: usize,
142        /// Human-readable source name returned by [`ParserStack::stack`].
143        name: String,
144        /// Opaque caller-supplied source identity.
145        source_id: Option<SourceId>,
146    },
147    /// A parser over a replayed event stream.
148    Replay {
149        /// Replay parser currently producing pre-collected events for this stack entry.
150        parser: ReplayParser<'input>,
151        /// Human-readable source name returned by [`ParserStack::stack`].
152        name: String,
153        /// Opaque caller-supplied source identity.
154        source_id: Option<SourceId>,
155    },
156}
157
158impl<'input, I, T> AnyParser<'input, I, T>
159where
160    I: Iterator<Item = char>,
161    T: BorrowedInput<'input>,
162{
163    fn name(&self) -> &str {
164        match self {
165            Self::String { name, .. }
166            | Self::Iter { name, .. }
167            | Self::Custom { name, .. }
168            | Self::Replay { name, .. } => name,
169        }
170    }
171
172    fn next_event(&mut self) -> Option<ParseResult<'input>> {
173        match self {
174            Self::String { parser, .. } => parser.next_event(),
175            Self::Iter { parser, .. } => parser.next_event(),
176            Self::Custom {
177                parser,
178                primed,
179                anchor_floor,
180                ..
181            } => {
182                let result = primed.take().map(Ok).or_else(|| parser.next_event());
183                if *anchor_floor == 0 {
184                    return result;
185                }
186                let Some(Ok((event, span))) = &result else {
187                    return result;
188                };
189                match event.anchor_id().or_else(|| event.alias_id()) {
190                    Some(anchor_id) if anchor_id < *anchor_floor => {
191                        let kind = ErrorKind::AnchorIdCollision {
192                            anchor_id,
193                            first_free_id: *anchor_floor,
194                        };
195                        Some(Err(ScanError::from_kind(span.start, kind)))
196                    }
197                    _ => result,
198                }
199            }
200            Self::Replay { parser, .. } => parser.next_event(),
201        }
202    }
203
204    fn source_id(&self) -> Option<SourceId> {
205        match self {
206            Self::String { source_id, .. }
207            | Self::Iter { source_id, .. }
208            | Self::Custom { source_id, .. }
209            | Self::Replay { source_id, .. } => *source_id,
210        }
211    }
212
213    fn set_source_id(&mut self, id: SourceId) {
214        match self {
215            Self::String { source_id, .. }
216            | Self::Iter { source_id, .. }
217            | Self::Custom { source_id, .. }
218            | Self::Replay { source_id, .. } => *source_id = Some(id),
219        }
220    }
221
222    fn anchor_offset(&self) -> usize {
223        match self {
224            AnyParser::String { parser, .. } => parser.anchor_offset(),
225            AnyParser::Iter { parser, .. } => parser.anchor_offset(),
226            AnyParser::Custom { parser, .. } => parser.anchor_offset(),
227            AnyParser::Replay { parser, .. } => parser.anchor_offset(),
228        }
229    }
230
231    fn set_anchor_offset(&mut self, offset: usize) {
232        match self {
233            AnyParser::String { parser, .. } => parser.set_anchor_offset(offset),
234            AnyParser::Iter { parser, .. } => parser.set_anchor_offset(offset),
235            AnyParser::Custom { parser, .. } => parser.set_anchor_offset(offset),
236            AnyParser::Replay { parser, .. } => parser.set_anchor_offset(offset),
237        }
238    }
239}
240
241/// Borrowed names of active parser sources, from bottom to top.
242///
243/// Created by [`ParserStack::source_names`] without allocating.
244pub struct SourceNames<'stack, 'input, I, T>
245where
246    I: Iterator<Item = char>,
247    T: BorrowedInput<'input>,
248{
249    parsers: core::slice::Iter<'stack, AnyParser<'input, I, T>>,
250}
251
252impl<'stack, 'input, I, T> Iterator for SourceNames<'stack, 'input, I, T>
253where
254    I: Iterator<Item = char>,
255    T: BorrowedInput<'input>,
256{
257    type Item = &'stack str;
258
259    fn next(&mut self) -> Option<Self::Item> {
260        self.parsers.next().map(AnyParser::name)
261    }
262
263    fn size_hint(&self) -> (usize, Option<usize>) {
264        self.parsers.size_hint()
265    }
266}
267
268impl<'input, I, T> DoubleEndedIterator for SourceNames<'_, 'input, I, T>
269where
270    I: Iterator<Item = char>,
271    T: BorrowedInput<'input>,
272{
273    fn next_back(&mut self) -> Option<Self::Item> {
274        self.parsers.next_back().map(AnyParser::name)
275    }
276}
277
278impl<'input, I, T> ExactSizeIterator for SourceNames<'_, 'input, I, T>
279where
280    I: Iterator<Item = char>,
281    T: BorrowedInput<'input>,
282{
283}
284
285impl<'input, I, T> core::iter::FusedIterator for SourceNames<'_, 'input, I, T>
286where
287    I: Iterator<Item = char>,
288    T: BorrowedInput<'input>,
289{
290}
291
292/// Caller-supplied keys of active parser sources, from bottom to top.
293///
294/// Created by [`ParserStack::source_ids`] without allocating.
295pub struct SourceIds<'stack, 'input, I, T>
296where
297    I: Iterator<Item = char>,
298    T: BorrowedInput<'input>,
299{
300    parsers: core::slice::Iter<'stack, AnyParser<'input, I, T>>,
301}
302
303impl<'input, I, T> Iterator for SourceIds<'_, 'input, I, T>
304where
305    I: Iterator<Item = char>,
306    T: BorrowedInput<'input>,
307{
308    type Item = Option<SourceId>;
309
310    fn next(&mut self) -> Option<Self::Item> {
311        self.parsers.next().map(AnyParser::source_id)
312    }
313
314    fn size_hint(&self) -> (usize, Option<usize>) {
315        self.parsers.size_hint()
316    }
317}
318
319impl<'input, I, T> DoubleEndedIterator for SourceIds<'_, 'input, I, T>
320where
321    I: Iterator<Item = char>,
322    T: BorrowedInput<'input>,
323{
324    fn next_back(&mut self) -> Option<Self::Item> {
325        self.parsers.next_back().map(AnyParser::source_id)
326    }
327}
328
329impl<'input, I, T> ExactSizeIterator for SourceIds<'_, 'input, I, T>
330where
331    I: Iterator<Item = char>,
332    T: BorrowedInput<'input>,
333{
334}
335
336impl<'input, I, T> core::iter::FusedIterator for SourceIds<'_, 'input, I, T>
337where
338    I: Iterator<Item = char>,
339    T: BorrowedInput<'input>,
340{
341}
342
343/// A parser implementation that uses a stack for include-style parsing.
344///
345/// Note: `ParserStack` deliberately suppresses nested [`Event::StreamStart`] /
346/// [`Event::DocumentStart`] events when more than one parser is stacked, and the tests assert
347/// outputs where a nested parser starts directly with [`Event::MappingStart`] before the parent
348/// stream/document wrapper appears.
349///
350/// That is exactly what we want for `!include`-style subtree injection.
351///
352/// Included parser events are replayed through the same event stream as parent events. With the
353/// `comments` Cargo feature, this includes comment events unless emission is disabled through
354/// [`ParserStack::with_options`]. Without the feature, comment events and their continuation state
355/// are absent.
356///
357/// Anchor metadata is passed through from parsers that enable it. Each [`Parser`] emits
358/// [`Event::Anchor`] immediately after its anchored node. Pushing another parser between
359/// consuming that node and consuming its metadata can insert events between them in the
360/// combined stream. If relying on adjacency, consume any pending anchor metadata before
361/// calling [`Self::push_include`] or another push method.
362///
363/// Included [`Span`] values remain local to the included source. Use source-aware push methods
364/// such as [`Self::push_str_parser_with_source_id`] and consume [`Self::next_sourced`] to associate
365/// each result with an opaque caller-supplied key. This does not change events or spans, and the
366/// existing iterator continues to return ordinary parse results. Errors also retain the nested
367/// source names through [`ScanError::source_stack`].
368pub struct ParserStack<'input, I = core::iter::Empty<char>, T = StrInput<'input>>
369where
370    I: Iterator<Item = char>,
371    T: BorrowedInput<'input>,
372{
373    options: Options,
374    parsers: Vec<AnyParser<'input, I, T>>,
375    /// Stack depths and end spans of nested documents whose trailing comments are being read.
376    #[cfg(feature = "comments")]
377    pending_document_ends: Vec<(usize, Span)>,
378    peeked: Option<ParseResult<'input>>,
379    /// Source of the buffered or most recently emitted result, including popped sources.
380    emitted_source_id: Option<SourceId>,
381    stream_end_emitted: bool,
382    #[allow(clippy::type_complexity)]
383    include_resolver: Option<Box<dyn FnMut(&str) -> Result<Cow<'input, str>, ScanError> + 'input>>,
384}
385
386impl<'input, I, T> ParserStack<'input, I, T>
387where
388    I: Iterator<Item = char>,
389    T: BorrowedInput<'input>,
390{
391    /// Creates a new, empty parser stack.
392    #[must_use]
393    pub fn new() -> Self {
394        Self::with_options(Options::default())
395    }
396
397    /// Creates a new, empty parser stack with the supplied parsing options.
398    ///
399    /// Options are applied to sources parsed internally by [`Self::push_include`]. Caller-supplied
400    /// parsers retain their own parsing options, including [`Options::emit_unresolved_aliases`]
401    /// and [`Options::emit_anchor_events`]. Unresolved alias and anchor metadata events from
402    /// caller-supplied parsers and replay streams are passed through.
403    /// With the `comments` Cargo feature, disabling comment emission also suppresses comment
404    /// events from parsers and replay streams supplied by the caller. Construct caller-supplied
405    /// parsers with emission disabled as well to avoid capturing comments before filtering them.
406    /// Without the feature, comment events are absent and [`Options::emit_comments`] has no effect.
407    #[must_use]
408    pub fn with_options(options: Options) -> Self {
409        Self {
410            options,
411            parsers: Vec::new(),
412            #[cfg(feature = "comments")]
413            pending_document_ends: Vec::new(),
414            peeked: None,
415            emitted_source_id: None,
416            stream_end_emitted: false,
417            include_resolver: None,
418        }
419    }
420
421    /// Set the resolver used by [`Self::push_include`].
422    ///
423    /// The resolver receives the include name and returns the included YAML source text.
424    pub fn set_resolver(
425        &mut self,
426        mut resolver: impl FnMut(&str) -> Result<String, ScanError> + 'input,
427    ) {
428        self.include_resolver = Some(Box::new(move |name| resolver(name).map(Cow::Owned)));
429    }
430
431    /// Set an include resolver whose source text can be borrowed for the stack's input lifetime.
432    ///
433    /// Unlike [`Self::set_resolver`], this path lets scalar, anchor, and tag token text in included
434    /// documents borrow directly from the returned source, as well as comment text when the
435    /// `comments` Cargo feature is enabled. The included document is still validated eagerly so
436    /// resolution errors retain the same timing and source-stack context.
437    pub fn set_borrowed_resolver(
438        &mut self,
439        mut resolver: impl FnMut(&str) -> Result<&'input str, ScanError> + 'input,
440    ) {
441        self.include_resolver = Some(Box::new(move |name| resolver(name).map(Cow::Borrowed)));
442    }
443
444    /// Resolve an include by name and push the resulting parser onto the stack.
445    ///
446    /// With the `comments` Cargo feature, comment events from the included content follow the
447    /// setting passed to [`Self::with_options`]. Anchor metadata events likewise follow
448    /// [`Options::emit_anchor_events`]. All event spans are local to the included content returned
449    /// by the resolver.
450    ///
451    /// # Errors
452    /// Returns `ScanError` if no resolver is configured, include resolution fails, or the
453    /// included content cannot be parsed.
454    pub fn push_include(&mut self, include_str: &str) -> Result<(), ScanError> {
455        let resolved = match &mut self.include_resolver {
456            Some(resolver) => resolver(include_str),
457            None => {
458                return Err(self.contextualize_include_error(
459                    ScanError::from_kind(
460                        crate::scanner::Marker::new(0, 1, 0),
461                        ErrorKind::MissingIncludeResolver,
462                    ),
463                    include_str,
464                ));
465            }
466        };
467        let content = match resolved {
468            Ok(content) => content,
469            Err(error) => return Err(self.contextualize_include_error(error, include_str)),
470        };
471        let inherited_anchor_offset = self.parsers.last().map(AnyParser::anchor_offset);
472
473        let (events, next_anchor_offset) = match content {
474            Cow::Borrowed(content) => {
475                let mut parser = Parser::new_from_str_with_options(content, self.options.clone());
476                if let Some(anchor_offset) = inherited_anchor_offset {
477                    parser.set_anchor_offset(anchor_offset);
478                }
479                let mut events = Vec::new();
480                while let Some(event) = parser.next_event() {
481                    match event {
482                        Ok(event) => events.push(event),
483                        Err(error) => {
484                            return Err(self.contextualize_include_error(error, include_str));
485                        }
486                    }
487                }
488                (events, parser.anchor_offset())
489            }
490            Cow::Owned(content) => {
491                let mut parser =
492                    Parser::new_from_iter_with_options(content.chars(), self.options.clone());
493                if let Some(anchor_offset) = inherited_anchor_offset {
494                    parser.set_anchor_offset(anchor_offset);
495                }
496                let mut events = Vec::new();
497                while let Some(event) = parser.next_event() {
498                    match event {
499                        Ok(event) => events.push(event),
500                        Err(error) => {
501                            return Err(self.contextualize_include_error(error, include_str));
502                        }
503                    }
504                }
505                (events, parser.anchor_offset())
506            }
507        };
508
509        self.push_replay_parser(
510            ReplayParser::new(events, next_anchor_offset),
511            include_str.into(),
512        );
513        Ok(())
514    }
515
516    /// Resolve and push an include with a caller-supplied source key.
517    ///
518    /// Eager resolution or parsing failures carry the supplied key. Successfully pushed content
519    /// carries it on every result returned by [`Self::next_sourced`].
520    ///
521    /// # Errors
522    /// Returns a sourced error under the same conditions as [`Self::push_include`].
523    pub fn push_include_with_source_id(
524        &mut self,
525        include_str: &str,
526        source_id: SourceId,
527    ) -> Result<(), Sourced<ScanError>> {
528        self.push_include(include_str).map_err(|value| Sourced {
529            source_id: Some(source_id),
530            value,
531        })?;
532        self.set_pushed_source_id(source_id);
533        Ok(())
534    }
535
536    fn set_pushed_source_id(&mut self, source_id: SourceId) {
537        // Every caller has just successfully pushed a parser.
538        if let Some(parser) = self.parsers.last_mut() {
539            parser.set_source_id(source_id);
540        }
541    }
542
543    fn contextualize_include_error(&self, error: ScanError, include_str: &str) -> ScanError {
544        let mut source_stack = self.stack();
545        source_stack.push(include_str.into());
546        error.with_source_stack(source_stack)
547    }
548
549    fn prepare_for_push(&mut self) {
550        if matches!(self.peeked, Some(Ok((Event::StreamEnd, _)))) {
551            self.peeked = None;
552        }
553    }
554
555    /// Push a string parser onto the stack.
556    ///
557    /// The pushed parser inherits the current anchor offset so anchors remain unique across stacked
558    /// sources. `name` is returned by [`Self::stack`] for diagnostics.
559    pub fn push_str_parser(&mut self, mut parser: Parser<'input, StrInput<'input>>, name: String) {
560        self.prepare_for_push();
561        if let Some(parent) = self.parsers.last() {
562            parser.set_anchor_offset(parent.anchor_offset());
563        }
564        self.parsers.push(AnyParser::String {
565            parser,
566            name,
567            source_id: None,
568        });
569    }
570
571    /// Push an iterator-backed parser onto the stack.
572    ///
573    /// The pushed parser inherits the current anchor offset so anchors remain unique across stacked
574    /// sources. `name` is returned by [`Self::stack`] for diagnostics.
575    pub fn push_iter_parser(
576        &mut self,
577        mut parser: Parser<'static, BufferedInput<I>>,
578        name: String,
579    ) {
580        self.prepare_for_push();
581        if let Some(parent) = self.parsers.last() {
582            parser.set_anchor_offset(parent.anchor_offset());
583        }
584        self.parsers.push(AnyParser::Iter {
585            parser,
586            name,
587            source_id: None,
588        });
589    }
590
591    /// Push a custom-input parser onto the stack.
592    ///
593    /// The pushed parser inherits the current anchor offset so anchors remain unique across stacked
594    /// sources. `name` is returned by [`Self::stack`] for diagnostics.
595    pub fn push_custom_parser(&mut self, mut parser: Parser<'input, T>, name: String) {
596        self.prepare_for_push();
597        if let Some(parent) = self.parsers.last() {
598            parser.set_anchor_offset(parent.anchor_offset());
599        }
600        self.parsers.push(AnyParser::Custom {
601            parser,
602            primed: None,
603            anchor_floor: 0,
604            name,
605            source_id: None,
606        });
607    }
608
609    /// Push a replay parser onto the stack.
610    ///
611    /// Replay parsers are used for included content that has already been parsed into events.
612    /// `name` is returned by [`Self::stack`] for diagnostics.
613    pub fn push_replay_parser(&mut self, mut parser: ReplayParser<'input>, name: String) {
614        self.prepare_for_push();
615        if let Some(parent) = self.parsers.last() {
616            let inherited = parent.anchor_offset();
617            parser.set_anchor_offset(parser.anchor_offset().max(inherited));
618        }
619
620        self.parsers.push(AnyParser::Replay {
621            parser,
622            name,
623            source_id: None,
624        });
625    }
626
627    /// Push a custom parser and set the first event that should be returned from it.
628    ///
629    /// This is used when the caller has already consumed the parser's first event before deciding
630    /// to place it on the stack. The event follows the same filtering rules as subsequent events
631    /// from this source. Before reading anchored nodes, call
632    /// `parser.set_anchor_offset(parser.anchor_offset().max(stack.current_anchor_offset()))`.
633    /// This preserves the parser's starting ID when the stack's offset is zero. For a replay
634    /// parent, reserve its unread anchor IDs as described in [`ReplayParser::new`].
635    /// If [`Event::anchor_id`] or [`Event::alias_id`] yields an ID below the stack's offset
636    /// at push time, reading that event returns [`ErrorKind::AnchorIdCollision`]. This can
637    /// happen if the child read an anchor before being seeded, or if the parent advanced
638    /// after seeding.
639    pub fn push_custom_parser_with_current(
640        &mut self,
641        mut parser: Parser<'input, T>,
642        name: String,
643        current: (Event<'input>, Span),
644    ) {
645        self.prepare_for_push();
646        let anchor_floor = self.current_anchor_offset();
647        parser.set_anchor_offset(parser.anchor_offset().max(anchor_floor));
648        self.parsers.push(AnyParser::Custom {
649            parser,
650            primed: Some(current),
651            anchor_floor,
652            name,
653            source_id: None,
654        });
655    }
656
657    /// Push a string parser with a source key returned by [`Self::next_sourced`].
658    pub fn push_str_parser_with_source_id(
659        &mut self,
660        parser: Parser<'input, StrInput<'input>>,
661        name: String,
662        source_id: SourceId,
663    ) {
664        self.push_str_parser(parser, name);
665        self.set_pushed_source_id(source_id);
666    }
667
668    /// Push an iterator parser with a source key returned by [`Self::next_sourced`].
669    pub fn push_iter_parser_with_source_id(
670        &mut self,
671        parser: Parser<'static, BufferedInput<I>>,
672        name: String,
673        source_id: SourceId,
674    ) {
675        self.push_iter_parser(parser, name);
676        self.set_pushed_source_id(source_id);
677    }
678
679    /// Push a custom parser with a source key returned by [`Self::next_sourced`].
680    pub fn push_custom_parser_with_source_id(
681        &mut self,
682        parser: Parser<'input, T>,
683        name: String,
684        source_id: SourceId,
685    ) {
686        self.push_custom_parser(parser, name);
687        self.set_pushed_source_id(source_id);
688    }
689
690    /// Push replayed events with a source key returned by [`Self::next_sourced`].
691    pub fn push_replay_parser_with_source_id(
692        &mut self,
693        parser: ReplayParser<'input>,
694        name: String,
695        source_id: SourceId,
696    ) {
697        self.push_replay_parser(parser, name);
698        self.set_pushed_source_id(source_id);
699    }
700
701    /// Push a custom parser and its already consumed first event with a source key.
702    ///
703    /// Both the supplied event and subsequent parser results retain `source_id`.
704    /// See [`Self::push_custom_parser_with_current`] for anchor preparation and event filtering.
705    pub fn push_custom_parser_with_current_and_source_id(
706        &mut self,
707        parser: Parser<'input, T>,
708        name: String,
709        current: (Event<'input>, Span),
710        source_id: SourceId,
711    ) {
712        self.push_custom_parser_with_current(parser, name, current);
713        self.set_pushed_source_id(source_id);
714    }
715
716    /// Return the anchor offset that a newly pushed parser should inherit.
717    #[must_use]
718    pub fn current_anchor_offset(&self) -> usize {
719        self.parsers.last().map_or(0, AnyParser::anchor_offset)
720    }
721
722    /// Return the number of active parsers without allocating.
723    #[must_use]
724    pub fn depth(&self) -> usize {
725        self.parsers.len()
726    }
727
728    /// Borrow active source names from bottom to top without allocating.
729    #[must_use]
730    pub fn source_names(&self) -> SourceNames<'_, 'input, I, T> {
731        SourceNames {
732            parsers: self.parsers.iter(),
733        }
734    }
735
736    /// Return active source keys from bottom to top without allocating.
737    #[must_use]
738    pub fn source_ids(&self) -> SourceIds<'_, 'input, I, T> {
739        SourceIds {
740            parsers: self.parsers.iter(),
741        }
742    }
743
744    /// Return the key of the currently active top parser, if one was supplied.
745    ///
746    /// This describes the active stack, not the source of a previously emitted event or error.
747    /// Use [`Self::next_sourced`] for that association, which survives source removal.
748    #[must_use]
749    pub fn current_source_id(&self) -> Option<SourceId> {
750        self.parsers.last().and_then(AnyParser::source_id)
751    }
752
753    /// Return owned names of active sources, from bottom to top.
754    ///
755    /// Use [`Self::source_names`] to inspect names without cloning, or [`Self::depth`] when only
756    /// the number of active parsers is needed.
757    #[must_use]
758    pub fn stack(&self) -> Vec<String> {
759        self.source_names().map(String::from).collect()
760    }
761
762    /// Consume the next parse result together with its caller-supplied source key.
763    ///
764    /// This shares iteration and lookahead state with [`ParserTrait::peek`] and
765    /// [`Iterator::next`]. A result buffered by `peek` retains its original key even if another
766    /// parser is subsequently pushed. Pushing after a peeked stream end replaces that end with
767    /// the new source. An error retains the failing key after that source is popped. Sources
768    /// pushed through the ordinary methods have no key.
769    pub fn next_sourced(&mut self) -> Option<Sourced<ParseResult<'input>>> {
770        let value = self.next_event()?;
771        Some(Sourced {
772            source_id: self.emitted_source_id,
773            value,
774        })
775    }
776
777    fn contextualize_error(&self, error: ScanError) -> ScanError {
778        if self.parsers.len() > 1 {
779            error.with_source_stack(self.stack())
780        } else {
781            error
782        }
783    }
784
785    fn propagate_anchor_offset_from_popped(&mut self, popped: &AnyParser<'input, I, T>) {
786        if let Some(parent) = self.parsers.last_mut() {
787            let next_offset = parent.anchor_offset().max(popped.anchor_offset());
788            parent.set_anchor_offset(next_offset);
789        }
790    }
791
792    /// Pop the current parser and propagate its anchor offset to its parent.
793    ///
794    /// # Panics
795    /// Panics if the parser stack is empty.
796    #[track_caller]
797    fn pop_parser_and_propagate_anchor_offset(&mut self) {
798        #[cfg(feature = "comments")]
799        if self
800            .pending_document_ends
801            .last()
802            .is_some_and(|(depth, _)| *depth == self.parsers.len())
803        {
804            self.pending_document_ends.pop();
805        }
806        let popped = self.parsers.pop().unwrap();
807        self.propagate_anchor_offset_from_popped(&popped);
808    }
809
810    // Keep source transitions and their comment-aware completion checks together.
811    #[allow(clippy::too_many_lines)]
812    fn next_event_impl(&mut self) -> Result<(Event<'input>, Span), ScanError> {
813        loop {
814            let Some(any_parser) = self.parsers.last_mut() else {
815                self.emitted_source_id = None;
816                return Ok((
817                    Event::StreamEnd,
818                    Span::empty(crate::scanner::Marker::new(0, 1, 0)),
819                ));
820            };
821
822            self.emitted_source_id = any_parser.source_id();
823            let res = any_parser.next_event();
824
825            #[cfg(feature = "comments")]
826            if let Some(&(depth, span)) = self.pending_document_ends.last() {
827                if depth == self.parsers.len()
828                    && matches!(&res, Some(Ok((event, _)))
829                        if !matches!(event, Event::Comment { .. } | Event::StreamEnd))
830                {
831                    let error = self.contextualize_error(ScanError::from_kind(
832                        span.start,
833                        ErrorKind::MultipleDocumentsUnsupported,
834                    ));
835                    self.pop_parser_and_propagate_anchor_offset();
836                    return Err(error);
837                }
838            }
839
840            match res {
841                Some(Ok((event @ Event::StreamEnd, span))) => {
842                    if self.parsers.len() == 1 {
843                        self.parsers.pop();
844                        return Ok((event, span));
845                    }
846                    self.pop_parser_and_propagate_anchor_offset();
847                }
848                None => {
849                    if self.parsers.len() == 1 {
850                        self.parsers.pop();
851                        return Ok((
852                            Event::StreamEnd,
853                            Span::empty(crate::scanner::Marker::new(0, 1, 0)),
854                        ));
855                    }
856                    self.pop_parser_and_propagate_anchor_offset();
857                }
858                Some(Err(e)) => {
859                    let e = self.contextualize_error(e);
860                    self.pop_parser_and_propagate_anchor_offset();
861                    return e.into_result();
862                }
863                Some(Ok((event @ Event::DocumentEnd { .. }, span))) => {
864                    if self.parsers.len() == 1 {
865                        return Ok((event, span));
866                    }
867
868                    #[cfg(feature = "comments")]
869                    {
870                        // Retain the end span while emitting trailing comments across calls and
871                        // pushes of other parsers.
872                        self.pending_document_ends.push((self.parsers.len(), span));
873                    }
874                    #[cfg(not(feature = "comments"))]
875                    {
876                        // Without comment events, completion can be checked immediately without
877                        // retaining a pending end span or allocating continuation state.
878                        let next = self.parsers.last_mut().unwrap().next_event();
879                        match next {
880                            Some(Ok((Event::StreamEnd, _))) | None => {
881                                self.pop_parser_and_propagate_anchor_offset();
882                            }
883                            Some(Err(error)) => {
884                                let error = self.contextualize_error(error);
885                                self.pop_parser_and_propagate_anchor_offset();
886                                return Err(error);
887                            }
888                            Some(Ok(_)) => {
889                                let error = self.contextualize_error(ScanError::from_kind(
890                                    span.start,
891                                    ErrorKind::MultipleDocumentsUnsupported,
892                                ));
893                                self.pop_parser_and_propagate_anchor_offset();
894                                return Err(error);
895                            }
896                        }
897                    }
898                }
899                Some(Ok(event)) => {
900                    #[cfg(feature = "comments")]
901                    if !self.options.emit_comments && matches!(event.0, Event::Comment { .. }) {
902                        continue;
903                    }
904                    if self.parsers.len() > 1
905                        && matches!(event.0, Event::StreamStart | Event::DocumentStart { .. })
906                    {
907                        continue;
908                    }
909                    return Ok(event);
910                }
911            }
912        }
913    }
914}
915
916impl<'input, I, T> Default for ParserStack<'input, I, T>
917where
918    I: Iterator<Item = char>,
919    T: BorrowedInput<'input>,
920{
921    fn default() -> Self {
922        Self::new()
923    }
924}
925
926impl<'input, I, T> ParserTrait<'input> for ParserStack<'input, I, T>
927where
928    I: Iterator<Item = char>,
929    T: BorrowedInput<'input>,
930{
931    fn peek(&mut self) -> Option<Result<&(Event<'input>, Span), ScanError>> {
932        if self.stream_end_emitted {
933            return None;
934        }
935        if self.peeked.is_none() {
936            self.peeked = Some(self.next_event_impl());
937        }
938        Some(self.peeked.as_ref()?.as_ref().map_err(Clone::clone))
939    }
940
941    fn next_event(&mut self) -> Option<ParseResult<'input>> {
942        if self.stream_end_emitted {
943            return None;
944        }
945        let result = self.peeked.take().unwrap_or_else(|| self.next_event_impl());
946        self.stream_end_emitted = matches!(result, Err(_) | Ok((Event::StreamEnd, _)));
947        Some(result)
948    }
949
950    fn load<R: SpannedEventReceiver<'input>>(
951        &mut self,
952        recv: &mut R,
953        multi: bool,
954    ) -> Result<(), ScanError> {
955        while let Some(res) = self.next_event() {
956            // Fetch the next event from the active stack entry.
957            let (ev, span) = res?;
958
959            // Track whether to stop based on `multi`.
960            let is_doc_end = matches!(ev, Event::DocumentEnd { .. });
961            let is_stream_end = matches!(ev, Event::StreamEnd);
962
963            recv.on_event(ev, span);
964
965            if is_stream_end {
966                break;
967            }
968
969            // Stop after one document when multi-document parsing is disabled.
970            if !multi && is_doc_end {
971                break;
972            }
973        }
974
975        Ok(())
976    }
977}
978
979impl<'input, I, T> Iterator for ParserStack<'input, I, T>
980where
981    I: Iterator<Item = char>,
982    T: BorrowedInput<'input>,
983{
984    type Item = Result<(Event<'input>, Span), ScanError>;
985
986    fn next(&mut self) -> Option<Self::Item> {
987        self.next_event()
988    }
989}
990
991impl<'input, I, T> core::iter::FusedIterator for ParserStack<'input, I, T>
992where
993    I: Iterator<Item = char>,
994    T: BorrowedInput<'input>,
995{
996}