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
10pub struct ReplayParser<'input> {
12 events: alloc::vec::IntoIter<(Event<'input>, Span)>,
13 anchor_offset: usize,
14}
15
16impl<'input> ReplayParser<'input> {
17 #[must_use]
19 pub fn new(events: Vec<(Event<'input>, Span)>, anchor_offset: usize) -> Self {
20 Self {
21 events: events.into_iter(),
22 anchor_offset,
23 }
24 }
25
26 #[must_use]
28 pub fn anchor_offset(&self) -> usize {
29 self.anchor_offset
30 }
31
32 pub fn set_anchor_offset(&mut self, offset: usize) {
34 self.anchor_offset = offset;
35 }
36
37 fn advance_anchor_offset(&mut self, event: &Event<'input>) {
38 let anchor_id = match event {
39 Event::Scalar(_, _, anchor_id, _)
40 | Event::SequenceStart(_, anchor_id, _)
41 | Event::MappingStart(_, anchor_id, _) => *anchor_id,
42 _ => 0,
43 };
44
45 if anchor_id > 0 {
46 self.anchor_offset = self.anchor_offset.max(anchor_id.saturating_add(1));
47 }
48 }
49}
50
51impl<'input> ParserTrait<'input> for ReplayParser<'input> {
52 fn peek(&mut self) -> Option<Result<&(Event<'input>, Span), ScanError>> {
53 self.events.as_slice().first().map(Ok)
54 }
55
56 fn next_event(&mut self) -> Option<ParseResult<'input>> {
57 let event = self.events.next()?;
58 self.advance_anchor_offset(&event.0);
59 Some(Ok(event))
60 }
61
62 fn load<R: SpannedEventReceiver<'input>>(
63 &mut self,
64 recv: &mut R,
65 multi: bool,
66 ) -> Result<(), ScanError> {
67 while let Some(res) = self.next_event() {
68 let (ev, span) = res?;
69 let is_doc_end = matches!(ev, Event::DocumentEnd);
70 let is_stream_end = matches!(ev, Event::StreamEnd);
71 recv.on_event(ev, span);
72 if is_stream_end {
73 break;
74 }
75 if !multi && is_doc_end {
76 break;
77 }
78 }
79 Ok(())
80 }
81}
82
83impl<'input> Iterator for ReplayParser<'input> {
84 type Item = ParseResult<'input>;
85
86 fn next(&mut self) -> Option<Self::Item> {
87 self.next_event()
88 }
89}
90
91impl core::iter::FusedIterator for ReplayParser<'_> {}
92
93enum AnyParser<'input, I, T>
95where
96 I: Iterator<Item = char>,
97 T: BorrowedInput<'input>,
98{
99 String {
101 parser: Parser<'input, StrInput<'input>>,
103 name: String,
105 },
106 Iter {
108 parser: Parser<'static, BufferedInput<I>>,
110 name: String,
112 },
113 Custom {
115 parser: Parser<'input, T>,
117 name: String,
119 },
120 Replay {
122 parser: ReplayParser<'input>,
124 name: String,
126 },
127}
128
129impl<'input, I, T> AnyParser<'input, I, T>
130where
131 I: Iterator<Item = char>,
132 T: BorrowedInput<'input>,
133{
134 fn anchor_offset(&self) -> usize {
135 match self {
136 AnyParser::String { parser, .. } => parser.anchor_offset(),
137 AnyParser::Iter { parser, .. } => parser.anchor_offset(),
138 AnyParser::Custom { parser, .. } => parser.anchor_offset(),
139 AnyParser::Replay { parser, .. } => parser.anchor_offset(),
140 }
141 }
142
143 fn set_anchor_offset(&mut self, offset: usize) {
144 match self {
145 AnyParser::String { parser, .. } => parser.set_anchor_offset(offset),
146 AnyParser::Iter { parser, .. } => parser.set_anchor_offset(offset),
147 AnyParser::Custom { parser, .. } => parser.set_anchor_offset(offset),
148 AnyParser::Replay { parser, .. } => parser.set_anchor_offset(offset),
149 }
150 }
151}
152
153pub struct ParserStack<'input, I = core::iter::Empty<char>, T = StrInput<'input>>
171where
172 I: Iterator<Item = char>,
173 T: BorrowedInput<'input>,
174{
175 options: Options,
176 parsers: Vec<AnyParser<'input, I, T>>,
177 #[cfg(feature = "comments")]
179 pending_document_ends: Vec<(usize, Span)>,
180 current: Option<(Event<'input>, Span)>,
181 current_error: Option<ScanError>,
182 stream_end_emitted: bool,
183 #[allow(clippy::type_complexity)]
184 include_resolver: Option<Box<dyn FnMut(&str) -> Result<Cow<'input, str>, ScanError> + 'input>>,
185}
186
187impl<'input, I, T> ParserStack<'input, I, T>
188where
189 I: Iterator<Item = char>,
190 T: BorrowedInput<'input>,
191{
192 #[must_use]
194 pub fn new() -> Self {
195 Self::with_options(Options::default())
196 }
197
198 #[must_use]
207 pub fn with_options(options: Options) -> Self {
208 Self {
209 options,
210 parsers: Vec::new(),
211 #[cfg(feature = "comments")]
212 pending_document_ends: Vec::new(),
213 current: None,
214 current_error: None,
215 stream_end_emitted: false,
216 include_resolver: None,
217 }
218 }
219
220 pub fn set_resolver(
224 &mut self,
225 mut resolver: impl FnMut(&str) -> Result<String, ScanError> + 'input,
226 ) {
227 self.include_resolver = Some(Box::new(move |name| resolver(name).map(Cow::Owned)));
228 }
229
230 pub fn set_borrowed_resolver(
237 &mut self,
238 mut resolver: impl FnMut(&str) -> Result<&'input str, ScanError> + 'input,
239 ) {
240 self.include_resolver = Some(Box::new(move |name| resolver(name).map(Cow::Borrowed)));
241 }
242
243 pub fn push_include(&mut self, include_str: &str) -> Result<(), ScanError> {
253 let resolved = match &mut self.include_resolver {
254 Some(resolver) => resolver(include_str),
255 None => {
256 return Err(self.contextualize_include_error(
257 ScanError::from_kind(
258 crate::scanner::Marker::new(0, 1, 0),
259 ErrorKind::MissingIncludeResolver,
260 ),
261 include_str,
262 ));
263 }
264 };
265 let content = match resolved {
266 Ok(content) => content,
267 Err(error) => return Err(self.contextualize_include_error(error, include_str)),
268 };
269 let inherited_anchor_offset = self.parsers.last().map(AnyParser::anchor_offset);
270
271 let (events, next_anchor_offset) = match content {
272 Cow::Borrowed(content) => {
273 let mut parser = Parser::new_from_str_with_options(content, self.options.clone());
274 if let Some(anchor_offset) = inherited_anchor_offset {
275 parser.set_anchor_offset(anchor_offset);
276 }
277 let mut events = Vec::new();
278 while let Some(event) = parser.next_event() {
279 match event {
280 Ok(event) => events.push(event),
281 Err(error) => {
282 return Err(self.contextualize_include_error(error, include_str));
283 }
284 }
285 }
286 (events, parser.anchor_offset())
287 }
288 Cow::Owned(content) => {
289 let mut parser =
290 Parser::new_from_iter_with_options(content.chars(), self.options.clone());
291 if let Some(anchor_offset) = inherited_anchor_offset {
292 parser.set_anchor_offset(anchor_offset);
293 }
294 let mut events = Vec::new();
295 while let Some(event) = parser.next_event() {
296 match event {
297 Ok(event) => events.push(event),
298 Err(error) => {
299 return Err(self.contextualize_include_error(error, include_str));
300 }
301 }
302 }
303 (events, parser.anchor_offset())
304 }
305 };
306
307 self.push_replay_parser(
308 ReplayParser::new(events, next_anchor_offset),
309 include_str.into(),
310 );
311 Ok(())
312 }
313
314 fn contextualize_include_error(&self, error: ScanError, include_str: &str) -> ScanError {
315 let mut source_stack = self.stack();
316 source_stack.push(include_str.into());
317 error.with_source_stack(source_stack)
318 }
319
320 fn prepare_for_push(&mut self) {
321 if matches!(self.current.as_ref(), Some((Event::StreamEnd, _))) {
322 self.current = None;
323 }
324 }
325
326 pub fn push_str_parser(&mut self, mut parser: Parser<'input, StrInput<'input>>, name: String) {
331 self.prepare_for_push();
332 if let Some(parent) = self.parsers.last() {
333 parser.set_anchor_offset(parent.anchor_offset());
334 }
335 self.parsers.push(AnyParser::String { parser, name });
336 }
337
338 pub fn push_iter_parser(
343 &mut self,
344 mut parser: Parser<'static, BufferedInput<I>>,
345 name: String,
346 ) {
347 self.prepare_for_push();
348 if let Some(parent) = self.parsers.last() {
349 parser.set_anchor_offset(parent.anchor_offset());
350 }
351 self.parsers.push(AnyParser::Iter { parser, name });
352 }
353
354 pub fn push_custom_parser(&mut self, mut parser: Parser<'input, T>, name: String) {
359 self.prepare_for_push();
360 if let Some(parent) = self.parsers.last() {
361 parser.set_anchor_offset(parent.anchor_offset());
362 }
363 self.parsers.push(AnyParser::Custom { parser, name });
364 }
365
366 pub fn push_replay_parser(&mut self, mut parser: ReplayParser<'input>, name: String) {
371 self.prepare_for_push();
372 if let Some(parent) = self.parsers.last() {
373 let inherited = parent.anchor_offset();
374 parser.set_anchor_offset(parser.anchor_offset().max(inherited));
375 }
376
377 self.parsers.push(AnyParser::Replay { parser, name });
378 }
379
380 pub fn push_custom_parser_with_current(
385 &mut self,
386 mut parser: Parser<'input, T>,
387 name: String,
388 current: (Event<'input>, Span),
389 ) {
390 self.prepare_for_push();
391 if let Some(parent) = self.parsers.last() {
392 parser.set_anchor_offset(parent.anchor_offset());
393 }
394 self.parsers.push(AnyParser::Custom { parser, name });
395 #[cfg(feature = "comments")]
396 {
397 self.current = if self.options.emit_comments || !matches!(current.0, Event::Comment(..))
398 {
399 Some(current)
400 } else {
401 None
402 };
403 }
404 #[cfg(not(feature = "comments"))]
405 {
406 self.current = Some(current);
407 }
408 }
409
410 #[must_use]
412 pub fn current_anchor_offset(&self) -> usize {
413 self.parsers.last().map_or(0, AnyParser::anchor_offset)
414 }
415
416 #[must_use]
418 pub fn stack(&self) -> Vec<String> {
419 self.parsers
420 .iter()
421 .map(|p| match p {
422 AnyParser::String { name, .. }
423 | AnyParser::Iter { name, .. }
424 | AnyParser::Custom { name, .. }
425 | AnyParser::Replay { name, .. } => name.clone(),
426 })
427 .collect()
428 }
429
430 fn contextualize_error(&self, error: ScanError) -> ScanError {
431 if self.parsers.len() > 1 {
432 error.with_source_stack(self.stack())
433 } else {
434 error
435 }
436 }
437
438 fn propagate_anchor_offset_from_popped(&mut self, popped: &AnyParser<'input, I, T>) {
439 if let Some(parent) = self.parsers.last_mut() {
440 let next_offset = parent.anchor_offset().max(popped.anchor_offset());
441 parent.set_anchor_offset(next_offset);
442 }
443 }
444
445 #[track_caller]
450 fn pop_parser_and_propagate_anchor_offset(&mut self) {
451 #[cfg(feature = "comments")]
452 if self
453 .pending_document_ends
454 .last()
455 .is_some_and(|(depth, _)| *depth == self.parsers.len())
456 {
457 self.pending_document_ends.pop();
458 }
459 let popped = self.parsers.pop().unwrap();
460 self.propagate_anchor_offset_from_popped(&popped);
461 }
462
463 fn next_event_impl(&mut self) -> Result<(Event<'input>, Span), ScanError> {
464 loop {
465 let Some(any_parser) = self.parsers.last_mut() else {
466 return Ok((
467 Event::StreamEnd,
468 Span::empty(crate::scanner::Marker::new(0, 1, 0)),
469 ));
470 };
471
472 let res = match any_parser {
473 AnyParser::String { parser, .. } => parser.next_event(),
474 AnyParser::Iter { parser, .. } => parser.next_event(),
475 AnyParser::Custom { parser, .. } => parser.next_event(),
476 AnyParser::Replay { parser, .. } => parser.next_event(),
477 };
478
479 #[cfg(feature = "comments")]
480 if let Some(&(depth, span)) = self.pending_document_ends.last() {
481 if depth == self.parsers.len()
482 && matches!(&res, Some(Ok((event, _)))
483 if !matches!(event, Event::Comment(..) | Event::StreamEnd))
484 {
485 let error = self.contextualize_error(ScanError::from_kind(
486 span.start,
487 ErrorKind::MultipleDocumentsUnsupported,
488 ));
489 self.pop_parser_and_propagate_anchor_offset();
490 return Err(error);
491 }
492 }
493
494 match res {
495 Some(Ok((Event::StreamEnd, span))) => {
496 if self.parsers.len() == 1 {
497 self.parsers.pop();
498 return Ok((Event::StreamEnd, span));
499 }
500 self.pop_parser_and_propagate_anchor_offset();
501 }
502 None => {
503 if self.parsers.len() == 1 {
504 self.parsers.pop();
505 return Ok((
506 Event::StreamEnd,
507 Span::empty(crate::scanner::Marker::new(0, 1, 0)),
508 ));
509 }
510 self.pop_parser_and_propagate_anchor_offset();
511 }
512 Some(Err(e)) => {
513 let e = self.contextualize_error(e);
514 self.pop_parser_and_propagate_anchor_offset();
515 return e.into_result();
516 }
517 Some(Ok((Event::DocumentEnd, span))) => {
518 if self.parsers.len() == 1 {
519 return Ok((Event::DocumentEnd, span));
520 }
521
522 #[cfg(feature = "comments")]
523 {
524 self.pending_document_ends.push((self.parsers.len(), span));
527 }
528 #[cfg(not(feature = "comments"))]
529 {
530 let next = match self.parsers.last_mut().unwrap() {
533 AnyParser::String { parser, .. } => parser.next_event(),
534 AnyParser::Iter { parser, .. } => parser.next_event(),
535 AnyParser::Custom { parser, .. } => parser.next_event(),
536 AnyParser::Replay { parser, .. } => parser.next_event(),
537 };
538 match next {
539 Some(Ok((Event::StreamEnd, _))) | None => {
540 self.pop_parser_and_propagate_anchor_offset();
541 }
542 Some(Err(error)) => {
543 let error = self.contextualize_error(error);
544 self.pop_parser_and_propagate_anchor_offset();
545 return Err(error);
546 }
547 Some(Ok(_)) => {
548 let error = self.contextualize_error(ScanError::from_kind(
549 span.start,
550 ErrorKind::MultipleDocumentsUnsupported,
551 ));
552 self.pop_parser_and_propagate_anchor_offset();
553 return Err(error);
554 }
555 }
556 }
557 }
558 Some(Ok(event)) => {
559 #[cfg(feature = "comments")]
560 if !self.options.emit_comments && matches!(event.0, Event::Comment(..)) {
561 continue;
562 }
563 if self.parsers.len() > 1
564 && matches!(event.0, Event::StreamStart | Event::DocumentStart(..))
565 {
566 continue;
567 }
568 return Ok(event);
569 }
570 }
571 }
572 }
573}
574
575impl<'input, I, T> Default for ParserStack<'input, I, T>
576where
577 I: Iterator<Item = char>,
578 T: BorrowedInput<'input>,
579{
580 fn default() -> Self {
581 Self::new()
582 }
583}
584
585impl<'input, I, T> ParserTrait<'input> for ParserStack<'input, I, T>
586where
587 I: Iterator<Item = char>,
588 T: BorrowedInput<'input>,
589{
590 fn peek(&mut self) -> Option<Result<&(Event<'input>, Span), ScanError>> {
591 if let Some(ref x) = self.current {
592 Some(Ok(x))
593 } else if let Some(error) = &self.current_error {
594 Some(Err(error.clone()))
595 } else {
596 if self.stream_end_emitted {
597 return None;
598 }
599 match self.next_event_impl() {
600 Ok(token) => {
601 self.current = Some(token);
602 Some(Ok(self.current.as_ref().unwrap()))
603 }
604 Err(e) => {
605 self.current_error = Some(e.clone());
606 Some(Err(e))
607 }
608 }
609 }
610 }
611
612 fn next_event(&mut self) -> Option<ParseResult<'input>> {
613 if let Some(error) = self.current_error.take() {
614 self.stream_end_emitted = true;
615 return Some(Err(error));
616 }
617
618 if let Some(token) = self.current.take() {
619 if let Event::StreamEnd = token.0 {
620 self.stream_end_emitted = true;
621 }
622 return Some(Ok(token));
623 }
624 if self.stream_end_emitted {
625 return None;
626 }
627 match self.next_event_impl() {
628 Ok(token) => {
629 if let Event::StreamEnd = token.0 {
630 self.stream_end_emitted = true;
631 }
632 Some(Ok(token))
633 }
634 Err(e) => {
635 self.stream_end_emitted = true;
636 Some(Err(e))
637 }
638 }
639 }
640
641 fn load<R: SpannedEventReceiver<'input>>(
642 &mut self,
643 recv: &mut R,
644 multi: bool,
645 ) -> Result<(), ScanError> {
646 while let Some(res) = self.next_event() {
647 let (ev, span) = res?;
649
650 let is_doc_end = matches!(ev, Event::DocumentEnd);
652 let is_stream_end = matches!(ev, Event::StreamEnd);
653
654 recv.on_event(ev, span);
655
656 if is_stream_end {
657 break;
658 }
659
660 if !multi && is_doc_end {
662 break;
663 }
664 }
665
666 Ok(())
667 }
668}
669
670impl<'input, I, T> Iterator for ParserStack<'input, I, T>
671where
672 I: Iterator<Item = char>,
673 T: BorrowedInput<'input>,
674{
675 type Item = Result<(Event<'input>, Span), ScanError>;
676
677 fn next(&mut self) -> Option<Self::Item> {
678 self.next_event()
679 }
680}
681
682impl<'input, I, T> core::iter::FusedIterator for ParserStack<'input, I, T>
683where
684 I: Iterator<Item = char>,
685 T: BorrowedInput<'input>,
686{
687}