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