Skip to main content

saphyr_parser/
parser.rs

1//! Home to the YAML Parser.
2//!
3//! The parser takes input from the [`crate::scanner::Scanner`], performs final checks for YAML
4//! compliance, and emits a stream of YAML events. This stream can for instance be used to create
5//! YAML objects.
6
7use crate::{
8    input::{str::StrInput, Input},
9    scanner::{ScalarStyle, ScanError, Scanner, Span, Token, TokenType},
10    BufferedInput, Marker,
11};
12
13use alloc::{
14    borrow::Cow,
15    collections::BTreeMap,
16    string::{String, ToString},
17    vec::Vec,
18};
19use core::fmt::Display;
20
21#[derive(Clone, Copy, PartialEq, Debug, Eq)]
22enum State {
23    StreamStart,
24    ImplicitDocumentStart,
25    DocumentStart,
26    DocumentContent,
27    DocumentEnd,
28    BlockNode,
29    BlockSequenceFirstEntry,
30    BlockSequenceEntry,
31    IndentlessSequenceEntry,
32    BlockMappingFirstKey,
33    BlockMappingKey,
34    BlockMappingValue,
35    FlowSequenceFirstEntry,
36    FlowSequenceEntry,
37    FlowSequenceEntryMappingKey,
38    FlowSequenceEntryMappingValue,
39    FlowSequenceEntryMappingEnd(Marker),
40    FlowMappingFirstKey,
41    FlowMappingKey,
42    FlowMappingValue,
43    FlowMappingEmptyValue,
44    End,
45}
46
47/// An event generated by the YAML parser.
48///
49/// Events are used in the low-level event-based API (push parser). The API entrypoint is the
50/// [`EventReceiver`] trait.
51#[derive(Clone, PartialEq, Debug, Eq)]
52pub enum Event<'input> {
53    /// Reserved for internal use.
54    Nothing,
55    /// Event generated at the very beginning of parsing.
56    StreamStart,
57    /// Last event that will be generated by the parser. Signals EOF.
58    StreamEnd,
59    /// The start of a YAML document.
60    ///
61    /// When the boolean is `true`, it is an explicit document start
62    /// directive (`---`).
63    ///
64    /// When the boolean is `false`, it is an implicit document start
65    /// (without `---`).
66    DocumentStart(bool),
67    /// The YAML end document directive (`...`).
68    DocumentEnd,
69    /// A YAML Alias.
70    Alias(
71        /// The anchor ID the alias refers to.
72        usize,
73    ),
74    /// Value, style, `anchor_id`, tag
75    Scalar(
76        Cow<'input, str>,
77        ScalarStyle,
78        usize,
79        Option<Cow<'input, Tag>>,
80    ),
81    /// The start of a YAML sequence (array).
82    SequenceStart(
83        /// The anchor ID of the start of the sequence.
84        usize,
85        /// An optional tag
86        Option<Cow<'input, Tag>>,
87    ),
88    /// The end of a YAML sequence (array).
89    SequenceEnd,
90    /// The start of a YAML mapping (object, hash).
91    MappingStart(
92        /// The anchor ID of the start of the mapping.
93        usize,
94        /// An optional tag
95        Option<Cow<'input, Tag>>,
96    ),
97    /// The end of a YAML mapping (object, hash).
98    MappingEnd,
99}
100
101/// A YAML tag.
102#[derive(Clone, PartialEq, Debug, Eq, Ord, PartialOrd, Hash)]
103pub struct Tag {
104    /// Handle of the tag (`!` included).
105    pub handle: String,
106    /// The suffix of the tag.
107    pub suffix: String,
108}
109
110impl Tag {
111    /// Returns whether the tag is a YAML tag from the core schema (`!!str`, `!!int`, ...).
112    ///
113    /// The YAML specification specifies [a list of
114    /// tags](https://yaml.org/spec/1.2.2/#103-core-schema) for the Core Schema. This function
115    /// checks whether _the handle_ (but not the suffix) is the handle for the YAML Core Schema.
116    ///
117    /// # Return
118    /// Returns `true` if the handle is `tag:yaml.org,2002`, `false` otherwise.
119    #[must_use]
120    pub fn is_yaml_core_schema(&self) -> bool {
121        self.handle == "tag:yaml.org,2002:"
122    }
123}
124
125impl Display for Tag {
126    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
127        if self.handle == "!" {
128            write!(f, "!{}", self.suffix)
129        } else {
130            write!(f, "{}!{}", self.handle, self.suffix)
131        }
132    }
133}
134
135impl<'input> Event<'input> {
136    /// Create an empty scalar.
137    fn empty_scalar() -> Self {
138        // a null scalar
139        Event::Scalar("~".into(), ScalarStyle::Plain, 0, None)
140    }
141
142    /// Create an empty scalar with the given anchor.
143    fn empty_scalar_with_anchor(anchor: usize, tag: Option<Cow<'input, Tag>>) -> Self {
144        Event::Scalar(Cow::default(), ScalarStyle::Plain, anchor, tag)
145    }
146}
147
148/// A YAML parser.
149#[derive(Debug)]
150pub struct Parser<'input, T: Input> {
151    /// The underlying scanner from which we pull tokens.
152    scanner: Scanner<'input, T>,
153    /// The stack of _previous_ states we were in.
154    ///
155    /// States are pushed in the context of subobjects to this stack. The top-most element is the
156    /// state in which to come back to when exiting the current state.
157    states: Vec<State>,
158    /// The state in which we currently are.
159    state: State,
160    /// The next token from the scanner.
161    token: Option<Token<'input>>,
162    /// The next YAML event to emit.
163    current: Option<(Event<'input>, Span)>,
164    /// Anchors that have been encountered in the YAML document.
165    anchors: BTreeMap<Cow<'input, str>, usize>,
166    /// Next ID available for an anchor.
167    ///
168    /// Every anchor is given a unique ID. We use an incrementing ID and this is both the ID to
169    /// return for the next anchor and the count of anchor IDs emitted.
170    anchor_id_count: usize,
171    /// The tag directives (`%TAG`) the parser has encountered.
172    ///
173    /// Key is the handle, and value is the prefix.
174    tags: BTreeMap<String, String>,
175    /// Whether we have emitted [`Event::StreamEnd`].
176    ///
177    /// Emitted means that it has been returned from [`Self::next`]. If it is stored in
178    /// [`Self::token`], this is set to `false`.
179    stream_end_emitted: bool,
180    /// Make tags global across all documents.
181    keep_tags: bool,
182}
183
184/// Trait to be implemented in order to use the low-level parsing API.
185///
186/// The low-level parsing API is event-based (a push parser), calling [`EventReceiver::on_event`]
187/// for each YAML [`Event`] that occurs.
188/// The [`EventReceiver`] trait only receives events. In order to receive both events and their
189/// location in the source, use [`SpannedEventReceiver`]. Note that [`EventReceiver`]s implement
190/// [`SpannedEventReceiver`] automatically.
191///
192/// # Event hierarchy
193/// The event stream starts with an [`Event::StreamStart`] event followed by an
194/// [`Event::DocumentStart`] event. If the YAML document starts with a mapping (an object), an
195/// [`Event::MappingStart`] event is emitted. If it starts with a sequence (an array), an
196/// [`Event::SequenceStart`] event is emitted. Otherwise, an [`Event::Scalar`] event is emitted.
197///
198/// In a mapping, key-values are sent as consecutive events. The first event after an
199/// [`Event::MappingStart`] will be the key, and following its value. If the mapping contains no
200/// sub-mapping or sub-sequence, then even events (starting from 0) will always be keys and odd
201/// ones will always be values. The mapping ends when an [`Event::MappingEnd`] event is received.
202///
203/// In a sequence, values are sent consecutively until the [`Event::SequenceEnd`] event.
204///
205/// If a value is a sub-mapping or a sub-sequence, an [`Event::MappingStart`] or
206/// [`Event::SequenceStart`] event will be sent respectively. Following events until the associated
207/// [`Event::MappingStart`] or [`Event::SequenceEnd`] (beware of nested mappings or sequences) will
208/// be part of the value and not another key-value pair or element in the sequence.
209///
210/// For instance, the following yaml:
211/// ```yaml
212/// a: b
213/// c:
214///   d: e
215/// f:
216///   - g
217///   - h
218/// ```
219/// will emit (indented and commented for lisibility):
220/// ```text
221/// StreamStart, DocumentStart, MappingStart,
222///   Scalar("a", ..), Scalar("b", ..)
223///   Scalar("c", ..), MappingStart, Scalar("d", ..), Scalar("e", ..), MappingEnd,
224///   Scalar("f", ..), SequenceStart, Scalar("g", ..), Scalar("h", ..), SequenceEnd,
225/// MappingEnd, DocumentEnd, StreamEnd
226/// ```
227///
228/// # Example
229/// ```
230/// # use saphyr_parser::{Event, EventReceiver, Parser};
231/// #
232/// /// Sink of events. Collects them into an array.
233/// struct EventSink<'input> {
234///     events: Vec<Event<'input>>,
235/// }
236///
237/// /// Implement `on_event`, pushing into `self.events`.
238/// impl<'input> EventReceiver<'input> for EventSink<'input> {
239///     fn on_event(&mut self, ev: Event<'input>) {
240///         self.events.push(ev);
241///     }
242/// }
243///
244/// /// Load events from a yaml string.
245/// fn str_to_events(yaml: &str) -> Vec<Event<'_>> {
246///     let mut sink = EventSink { events: Vec::new() };
247///     let mut parser = Parser::new_from_str(yaml);
248///     // Load events using our sink as the receiver.
249///     parser.load(&mut sink, true).unwrap();
250///     sink.events
251/// }
252/// ```
253pub trait EventReceiver<'input> {
254    /// Handler called for each YAML event that is emitted by the parser.
255    fn on_event(&mut self, ev: Event<'input>);
256}
257
258/// Trait to be implemented for using the low-level parsing API.
259///
260/// Functionally similar to [`EventReceiver`], but receives a [`Span`] as well as the event.
261pub trait SpannedEventReceiver<'input> {
262    /// Handler called for each event that occurs.
263    fn on_event(&mut self, ev: Event<'input>, span: Span);
264}
265
266impl<'input, R: EventReceiver<'input>> SpannedEventReceiver<'input> for R {
267    fn on_event(&mut self, ev: Event<'input>, _span: Span) {
268        self.on_event(ev);
269    }
270}
271
272/// A convenience alias for a `Result` of a parser event.
273pub type ParseResult<'input> = Result<(Event<'input>, Span), ScanError>;
274
275impl<'input> Parser<'input, StrInput<'input>> {
276    /// Create a new instance of a parser from a &str.
277    #[must_use]
278    pub fn new_from_str(value: &'input str) -> Self {
279        debug_print!("\x1B[;31m>>>>>>>>>> New parser from str\x1B[;0m");
280        Parser::new(StrInput::new(value))
281    }
282}
283
284impl<'input, T> Parser<'input, BufferedInput<T>>
285where
286    T: Iterator<Item = char> + 'input,
287{
288    /// Create a new instance of a parser from an iterator of `char`s.
289    #[must_use]
290    pub fn new_from_iter(iter: T) -> Self {
291        debug_print!("\x1B[;31m>>>>>>>>>> New parser from iter\x1B[;0m");
292        Parser::new(BufferedInput::new(iter))
293    }
294}
295
296impl<'input, T: Input> Parser<'input, T> {
297    /// Create a new instance of a parser from the given input of characters.
298    pub fn new(src: T) -> Self {
299        Parser {
300            scanner: Scanner::new(src),
301            states: Vec::new(),
302            state: State::StreamStart,
303            token: None,
304            current: None,
305
306            anchors: BTreeMap::new(),
307            // valid anchor_id starts from 1
308            anchor_id_count: 1,
309            tags: BTreeMap::new(),
310            stream_end_emitted: false,
311            keep_tags: false,
312        }
313    }
314
315    /// Whether to keep tags across multiple documents when parsing.
316    ///
317    /// This behavior is non-standard as per the YAML specification but can be encountered in the
318    /// wild. This boolean allows enabling this non-standard extension. This would result in the
319    /// parser accepting input from [test
320    /// QLJ7](https://github.com/yaml/yaml-test-suite/blob/ccfa74e56afb53da960847ff6e6976c0a0825709/src/QLJ7.yaml)
321    /// of the yaml-test-suite:
322    ///
323    /// ```yaml
324    /// %TAG !prefix! tag:example.com,2011:
325    /// --- !prefix!A
326    /// a: b
327    /// --- !prefix!B
328    /// c: d
329    /// --- !prefix!C
330    /// e: f
331    /// ```
332    ///
333    /// With `keep_tags` set to `false`, the above YAML is rejected. As per the specification, tags
334    /// only apply to the document immediately following them. This would error on `!prefix!B`.
335    ///
336    /// With `keep_tags` set to `true`, the above YAML is accepted by the parser.
337    #[must_use]
338    pub fn keep_tags(mut self, value: bool) -> Self {
339        self.keep_tags = value;
340        self
341    }
342
343    /// Try to load the next event and return it, but do not consuming it from `self`.
344    ///
345    /// Any subsequent call to [`Parser::peek`] will return the same value, until a call to
346    /// [`Iterator::next`] or [`Parser::load`].
347    ///
348    /// # Errors
349    /// Returns `ScanError` when loading the next event fails.
350    pub fn peek(&mut self) -> Option<Result<&(Event<'input>, Span), ScanError>> {
351        if let Some(ref x) = self.current {
352            Some(Ok(x))
353        } else {
354            if self.stream_end_emitted {
355                return None;
356            }
357            match self.next_event_impl() {
358                Ok(token) => self.current = Some(token),
359                Err(e) => return Some(Err(e)),
360            }
361            self.current.as_ref().map(Ok)
362        }
363    }
364
365    /// Try to load the next event and return it, consuming it from `self`.
366    ///
367    /// # Errors
368    /// Returns `ScanError` when loading the next event fails.
369    pub fn next_event(&mut self) -> Option<ParseResult<'input>> {
370        if self.stream_end_emitted {
371            return None;
372        }
373
374        let tok = self.next_event_impl();
375        if matches!(tok, Ok((Event::StreamEnd, _))) {
376            self.stream_end_emitted = true;
377        }
378        Some(tok)
379    }
380
381    /// Implementation function for [`Self::next_event`] without the `Option`.
382    ///
383    /// [`Self::next_event`] should conform to the expectations of an [`Iterator`] and return an
384    /// option. This burdens the parser code. This function is used internally when an option is
385    /// undesirable.
386    fn next_event_impl<'a>(&mut self) -> ParseResult<'a>
387    where
388        'input: 'a,
389    {
390        match self.current.take() {
391            None => self.parse(),
392            Some(v) => Ok(v),
393        }
394    }
395
396    /// Peek at the next token from the scanner.
397    fn peek_token(&mut self) -> Result<&Token<'_>, ScanError> {
398        match self.token {
399            None => {
400                self.token = Some(self.scan_next_token()?);
401                Ok(self.token.as_ref().unwrap())
402            }
403            Some(ref tok) => Ok(tok),
404        }
405    }
406
407    /// Extract and return the next token from the scanner.
408    ///
409    /// This function does _not_ make use of `self.token`.
410    fn scan_next_token(&mut self) -> Result<Token<'input>, ScanError> {
411        let token = self.scanner.next();
412        match token {
413            None => match self.scanner.get_error() {
414                None => Err(ScanError::new_str(self.scanner.mark(), "unexpected eof")),
415                Some(e) => Err(e),
416            },
417            Some(tok) => Ok(tok),
418        }
419    }
420
421    fn fetch_token<'a>(&mut self) -> Token<'a>
422    where
423        'input: 'a,
424    {
425        self.token
426            .take()
427            .expect("fetch_token needs to be preceded by peek_token")
428    }
429
430    /// Skip the next token from the scanner.
431    fn skip(&mut self) {
432        self.token = None;
433    }
434    /// Pops the top-most state and make it the current state.
435    fn pop_state(&mut self) {
436        self.state = self.states.pop().unwrap();
437    }
438    /// Push a new state atop the state stack.
439    fn push_state(&mut self, state: State) {
440        self.states.push(state);
441    }
442
443    fn parse<'a>(&mut self) -> ParseResult<'a>
444    where
445        'input: 'a,
446    {
447        if self.state == State::End {
448            return Ok((Event::StreamEnd, Span::empty(self.scanner.mark())));
449        }
450        let (ev, mark) = self.state_machine()?;
451        Ok((ev, mark))
452    }
453
454    /// Load the YAML from the stream in `self`, pushing events into `recv`.
455    ///
456    /// The contents of the stream are parsed and the corresponding events are sent into the
457    /// recveiver. For detailed explanations about how events work, see [`EventReceiver`].
458    ///
459    /// If `multi` is set to `true`, the parser will allow parsing of multiple YAML documents
460    /// inside the stream.
461    ///
462    /// Note that any [`EventReceiver`] is also a [`SpannedEventReceiver`], so implementing the
463    /// former is enough to call this function.
464    /// # Errors
465    /// Returns `ScanError` when loading fails.
466    pub fn load<R: SpannedEventReceiver<'input>>(
467        &mut self,
468        recv: &mut R,
469        multi: bool,
470    ) -> Result<(), ScanError> {
471        if !self.scanner.stream_started() {
472            let (ev, span) = self.next_event_impl()?;
473            if ev != Event::StreamStart {
474                return Err(ScanError::new_str(
475                    span.start,
476                    "did not find expected <stream-start>",
477                ));
478            }
479            recv.on_event(ev, span);
480        }
481
482        if self.scanner.stream_ended() {
483            // XXX has parsed?
484            recv.on_event(Event::StreamEnd, Span::empty(self.scanner.mark()));
485            return Ok(());
486        }
487        loop {
488            let (ev, span) = self.next_event_impl()?;
489            if ev == Event::StreamEnd {
490                recv.on_event(ev, span);
491                return Ok(());
492            }
493            // clear anchors before a new document
494            self.anchors.clear();
495            self.load_document(ev, span, recv)?;
496            if !multi {
497                break;
498            }
499        }
500        Ok(())
501    }
502
503    fn load_document<R: SpannedEventReceiver<'input>>(
504        &mut self,
505        first_ev: Event<'input>,
506        span: Span,
507        recv: &mut R,
508    ) -> Result<(), ScanError> {
509        if !matches!(first_ev, Event::DocumentStart(_)) {
510            return Err(ScanError::new_str(
511                span.start,
512                "did not find expected <document-start>",
513            ));
514        }
515        recv.on_event(first_ev, span);
516
517        let (ev, span) = self.next_event_impl()?;
518        self.load_node(ev, span, recv)?;
519
520        // DOCUMENT-END is expected.
521        let (ev, mark) = self.next_event_impl()?;
522        assert_eq!(ev, Event::DocumentEnd);
523        recv.on_event(ev, mark);
524
525        Ok(())
526    }
527
528    fn load_node<R: SpannedEventReceiver<'input>>(
529        &mut self,
530        first_ev: Event<'input>,
531        span: Span,
532        recv: &mut R,
533    ) -> Result<(), ScanError> {
534        match first_ev {
535            Event::Alias(..) | Event::Scalar(..) => {
536                recv.on_event(first_ev, span);
537                Ok(())
538            }
539            Event::SequenceStart(..) => {
540                recv.on_event(first_ev, span);
541                self.load_sequence(recv)
542            }
543            Event::MappingStart(..) => {
544                recv.on_event(first_ev, span);
545                self.load_mapping(recv)
546            }
547            _ => {
548                #[cfg(feature = "debug_prints")]
549                std::println!("UNREACHABLE EVENT: {first_ev:?}");
550                unreachable!();
551            }
552        }
553    }
554
555    fn load_mapping<R: SpannedEventReceiver<'input>>(
556        &mut self,
557        recv: &mut R,
558    ) -> Result<(), ScanError> {
559        let (mut key_ev, mut key_mark) = self.next_event_impl()?;
560        while key_ev != Event::MappingEnd {
561            // key
562            self.load_node(key_ev, key_mark, recv)?;
563
564            // value
565            let (ev, mark) = self.next_event_impl()?;
566            self.load_node(ev, mark, recv)?;
567
568            // next event
569            let (ev, mark) = self.next_event_impl()?;
570            key_ev = ev;
571            key_mark = mark;
572        }
573        recv.on_event(key_ev, key_mark);
574        Ok(())
575    }
576
577    fn load_sequence<R: SpannedEventReceiver<'input>>(
578        &mut self,
579        recv: &mut R,
580    ) -> Result<(), ScanError> {
581        let (mut ev, mut mark) = self.next_event_impl()?;
582        while ev != Event::SequenceEnd {
583            self.load_node(ev, mark, recv)?;
584
585            // next event
586            let (next_ev, next_mark) = self.next_event_impl()?;
587            ev = next_ev;
588            mark = next_mark;
589        }
590        recv.on_event(ev, mark);
591        Ok(())
592    }
593
594    fn state_machine<'a>(&mut self) -> ParseResult<'a>
595    where
596        'input: 'a,
597    {
598        // let next_tok = self.peek_token().cloned()?;
599        // println!("cur_state {:?}, next tok: {:?}", self.state, next_tok);
600        debug_print!("\n\x1B[;33mParser state: {:?} \x1B[;0m", self.state);
601
602        match self.state {
603            State::StreamStart => self.stream_start(),
604
605            State::ImplicitDocumentStart => self.document_start(true),
606            State::DocumentStart => self.document_start(false),
607            State::DocumentContent => self.document_content(),
608            State::DocumentEnd => self.document_end(),
609
610            State::BlockNode => self.parse_node(true, false),
611            // State::BlockNodeOrIndentlessSequence => self.parse_node(true, true),
612            // State::FlowNode => self.parse_node(false, false),
613            State::BlockMappingFirstKey => self.block_mapping_key(true),
614            State::BlockMappingKey => self.block_mapping_key(false),
615            State::BlockMappingValue => self.block_mapping_value(),
616
617            State::BlockSequenceFirstEntry => self.block_sequence_entry(true),
618            State::BlockSequenceEntry => self.block_sequence_entry(false),
619
620            State::FlowSequenceFirstEntry => self.flow_sequence_entry(true),
621            State::FlowSequenceEntry => self.flow_sequence_entry(false),
622
623            State::FlowMappingFirstKey => self.flow_mapping_key(true),
624            State::FlowMappingKey => self.flow_mapping_key(false),
625            State::FlowMappingValue => self.flow_mapping_value(false),
626
627            State::IndentlessSequenceEntry => self.indentless_sequence_entry(),
628
629            State::FlowSequenceEntryMappingKey => self.flow_sequence_entry_mapping_key(),
630            State::FlowSequenceEntryMappingValue => self.flow_sequence_entry_mapping_value(),
631            State::FlowSequenceEntryMappingEnd(mark) => self.flow_sequence_entry_mapping_end(mark),
632            State::FlowMappingEmptyValue => self.flow_mapping_value(true),
633
634            /* impossible */
635            State::End => unreachable!(),
636        }
637    }
638
639    fn stream_start<'a>(&mut self) -> ParseResult<'a>
640    where
641        'input: 'a,
642    {
643        match *self.peek_token()? {
644            Token(span, TokenType::StreamStart(_)) => {
645                self.state = State::ImplicitDocumentStart;
646                self.skip();
647                Ok((Event::StreamStart, span))
648            }
649            Token(span, _) => Err(ScanError::new_str(
650                span.start,
651                "did not find expected <stream-start>",
652            )),
653        }
654    }
655
656    fn document_start<'a>(&mut self, implicit: bool) -> ParseResult<'a>
657    where
658        'input: 'a,
659    {
660        while let TokenType::DocumentEnd = self.peek_token()?.1 {
661            self.skip();
662        }
663
664        match *self.peek_token()? {
665            Token(span, TokenType::StreamEnd) => {
666                self.state = State::End;
667                self.skip();
668                Ok((Event::StreamEnd, span))
669            }
670            Token(
671                _,
672                TokenType::VersionDirective(..)
673                | TokenType::TagDirective(..)
674                | TokenType::DocumentStart,
675            ) => {
676                // explicit document
677                self.explicit_document_start()
678            }
679            Token(span, _) if implicit => {
680                self.parser_process_directives()?;
681                self.push_state(State::DocumentEnd);
682                self.state = State::BlockNode;
683                Ok((Event::DocumentStart(false), span))
684            }
685            _ => {
686                // explicit document
687                self.explicit_document_start()
688            }
689        }
690    }
691
692    fn parser_process_directives(&mut self) -> Result<(), ScanError> {
693        let mut version_directive_received = false;
694        loop {
695            let mut tags = BTreeMap::new();
696            match self.peek_token()? {
697                Token(span, TokenType::VersionDirective(_, _)) => {
698                    // XXX parsing with warning according to spec
699                    //if major != 1 || minor > 2 {
700                    //    return Err(ScanError::new_str(tok.0,
701                    //        "found incompatible YAML document"));
702                    //}
703                    if version_directive_received {
704                        return Err(ScanError::new_str(
705                            span.start,
706                            "duplicate version directive",
707                        ));
708                    }
709                    version_directive_received = true;
710                }
711                Token(mark, TokenType::TagDirective(handle, prefix)) => {
712                    if tags.contains_key(&**handle) {
713                        return Err(ScanError::new_str(mark.start, "the TAG directive must only be given at most once per handle in the same document"));
714                    }
715                    tags.insert(handle.to_string(), prefix.to_string());
716                }
717                _ => break,
718            }
719            self.tags = tags;
720            self.skip();
721        }
722        Ok(())
723    }
724
725    fn explicit_document_start<'a>(&mut self) -> ParseResult<'a>
726    where
727        'input: 'a,
728    {
729        self.parser_process_directives()?;
730        match *self.peek_token()? {
731            Token(mark, TokenType::DocumentStart) => {
732                self.push_state(State::DocumentEnd);
733                self.state = State::DocumentContent;
734                self.skip();
735                Ok((Event::DocumentStart(true), mark))
736            }
737            Token(span, _) => Err(ScanError::new_str(
738                span.start,
739                "did not find expected <document start>",
740            )),
741        }
742    }
743
744    fn document_content<'a>(&mut self) -> ParseResult<'a>
745    where
746        'input: 'a,
747    {
748        match *self.peek_token()? {
749            Token(
750                mark,
751                TokenType::VersionDirective(..)
752                | TokenType::TagDirective(..)
753                | TokenType::DocumentStart
754                | TokenType::DocumentEnd
755                | TokenType::StreamEnd,
756            ) => {
757                self.pop_state();
758                // empty scalar
759                Ok((Event::empty_scalar(), mark))
760            }
761            _ => self.parse_node(true, false),
762        }
763    }
764
765    fn document_end<'a>(&mut self) -> ParseResult<'a>
766    where
767        'input: 'a,
768    {
769        let mut explicit_end = false;
770        let span: Span = match *self.peek_token()? {
771            Token(span, TokenType::DocumentEnd) => {
772                explicit_end = true;
773                self.skip();
774                span
775            }
776            Token(span, _) => span,
777        };
778
779        if !self.keep_tags {
780            self.tags.clear();
781        }
782        if explicit_end {
783            self.state = State::ImplicitDocumentStart;
784        } else {
785            if let Token(span, TokenType::VersionDirective(..) | TokenType::TagDirective(..)) =
786                *self.peek_token()?
787            {
788                return Err(ScanError::new_str(
789                    span.start,
790                    "missing explicit document end marker before directive",
791                ));
792            }
793            self.state = State::DocumentStart;
794        }
795
796        Ok((Event::DocumentEnd, span))
797    }
798
799    fn register_anchor(&mut self, name: Cow<'input, str>, _: &Span) -> usize {
800        // anchors can be overridden/reused
801        // if self.anchors.contains_key(name) {
802        //     return Err(ScanError::new_str(*mark,
803        //         "while parsing anchor, found duplicated anchor"));
804        // }
805        let new_id = self.anchor_id_count;
806        self.anchor_id_count += 1;
807        self.anchors.insert(name, new_id);
808        new_id
809    }
810
811    fn parse_node<'a>(&mut self, block: bool, indentless_sequence: bool) -> ParseResult<'a>
812    where
813        'input: 'a,
814    {
815        let mut anchor_id = 0;
816        let mut tag = None;
817        match *self.peek_token()? {
818            Token(_, TokenType::Alias(_)) => {
819                self.pop_state();
820                if let Token(span, TokenType::Alias(name)) = self.fetch_token() {
821                    match self.anchors.get(&*name) {
822                        None => {
823                            return Err(ScanError::new_str(
824                                span.start,
825                                "while parsing node, found unknown anchor",
826                            ))
827                        }
828                        Some(id) => return Ok((Event::Alias(*id), span)),
829                    }
830                }
831                unreachable!()
832            }
833            Token(_, TokenType::Anchor(_)) => {
834                if let Token(span, TokenType::Anchor(name)) = self.fetch_token() {
835                    anchor_id = self.register_anchor(name, &span);
836                    if let TokenType::Tag(..) = self.peek_token()?.1 {
837                        if let TokenType::Tag(handle, suffix) = self.fetch_token().1 {
838                            tag = Some(self.resolve_tag(span, &handle, suffix)?);
839                        } else {
840                            unreachable!()
841                        }
842                    }
843                } else {
844                    unreachable!()
845                }
846            }
847            Token(mark, TokenType::Tag(..)) => {
848                if let TokenType::Tag(handle, suffix) = self.fetch_token().1 {
849                    tag = Some(self.resolve_tag(mark, &handle, suffix)?);
850                    if let TokenType::Anchor(_) = &self.peek_token()?.1 {
851                        if let Token(mark, TokenType::Anchor(name)) = self.fetch_token() {
852                            anchor_id = self.register_anchor(name, &mark);
853                        } else {
854                            unreachable!()
855                        }
856                    }
857                } else {
858                    unreachable!()
859                }
860            }
861            _ => {}
862        }
863        match *self.peek_token()? {
864            Token(mark, TokenType::BlockEntry) if indentless_sequence => {
865                self.state = State::IndentlessSequenceEntry;
866                Ok((Event::SequenceStart(anchor_id, tag), mark))
867            }
868            Token(_, TokenType::Scalar(..)) => {
869                self.pop_state();
870                if let Token(mark, TokenType::Scalar(style, v)) = self.fetch_token() {
871                    Ok((Event::Scalar(v, style, anchor_id, tag), mark))
872                } else {
873                    unreachable!()
874                }
875            }
876            Token(mark, TokenType::FlowSequenceStart) => {
877                self.state = State::FlowSequenceFirstEntry;
878                Ok((Event::SequenceStart(anchor_id, tag), mark))
879            }
880            Token(mark, TokenType::FlowMappingStart) => {
881                self.state = State::FlowMappingFirstKey;
882                Ok((Event::MappingStart(anchor_id, tag), mark))
883            }
884            Token(mark, TokenType::BlockSequenceStart) if block => {
885                self.state = State::BlockSequenceFirstEntry;
886                Ok((Event::SequenceStart(anchor_id, tag), mark))
887            }
888            Token(mark, TokenType::BlockMappingStart) if block => {
889                self.state = State::BlockMappingFirstKey;
890                Ok((Event::MappingStart(anchor_id, tag), mark))
891            }
892            // ex 7.2, an empty scalar can follow a secondary tag
893            Token(mark, _) if tag.is_some() || anchor_id > 0 => {
894                self.pop_state();
895                Ok((Event::empty_scalar_with_anchor(anchor_id, tag), mark))
896            }
897            Token(span, _) => Err(ScanError::new_str(
898                span.start,
899                "while parsing a node, did not find expected node content",
900            )),
901        }
902    }
903
904    fn block_mapping_key<'a>(&mut self, first: bool) -> ParseResult<'a>
905    where
906        'input: 'a,
907    {
908        // skip BlockMappingStart
909        if first {
910            let _ = self.peek_token()?;
911            //self.marks.push(tok.0);
912            self.skip();
913        }
914        match *self.peek_token()? {
915            Token(_, TokenType::Key) => {
916                self.skip();
917                if let Token(mark, TokenType::Key | TokenType::Value | TokenType::BlockEnd) =
918                    *self.peek_token()?
919                {
920                    self.state = State::BlockMappingValue;
921                    // empty scalar
922                    Ok((Event::empty_scalar(), mark))
923                } else {
924                    self.push_state(State::BlockMappingValue);
925                    self.parse_node(true, true)
926                }
927            }
928            // XXX(chenyh): libyaml failed to parse spec 1.2, ex8.18
929            Token(mark, TokenType::Value) => {
930                self.state = State::BlockMappingValue;
931                Ok((Event::empty_scalar(), mark))
932            }
933            Token(mark, TokenType::BlockEnd) => {
934                self.pop_state();
935                self.skip();
936                Ok((Event::MappingEnd, mark))
937            }
938            Token(span, _) => Err(ScanError::new_str(
939                span.start,
940                "while parsing a block mapping, did not find expected key",
941            )),
942        }
943    }
944
945    fn block_mapping_value<'a>(&mut self) -> ParseResult<'a>
946    where
947        'input: 'a,
948    {
949        match *self.peek_token()? {
950            Token(mark, TokenType::Value) => {
951                self.skip();
952                if let Token(_, TokenType::Key | TokenType::Value | TokenType::BlockEnd) =
953                    *self.peek_token()?
954                {
955                    self.state = State::BlockMappingKey;
956                    // empty scalar
957                    Ok((Event::empty_scalar(), mark))
958                } else {
959                    self.push_state(State::BlockMappingKey);
960                    self.parse_node(true, true)
961                }
962            }
963            Token(mark, _) => {
964                self.state = State::BlockMappingKey;
965                // empty scalar
966                Ok((Event::empty_scalar(), mark))
967            }
968        }
969    }
970
971    fn flow_mapping_key<'a>(&mut self, first: bool) -> ParseResult<'a>
972    where
973        'input: 'a,
974    {
975        if first {
976            let _ = self.peek_token()?;
977            self.skip();
978        }
979        let span: Span = {
980            match *self.peek_token()? {
981                Token(mark, TokenType::FlowMappingEnd) => mark,
982                Token(mark, _) => {
983                    if !first {
984                        match *self.peek_token()? {
985                            Token(_, TokenType::FlowEntry) => self.skip(),
986                            Token(span, _) => return Err(ScanError::new_str(
987                                span.start,
988                                "while parsing a flow mapping, did not find expected ',' or '}'",
989                            )),
990                        }
991                    }
992
993                    match *self.peek_token()? {
994                        Token(_, TokenType::Key) => {
995                            self.skip();
996                            if let Token(
997                                mark,
998                                TokenType::Value | TokenType::FlowEntry | TokenType::FlowMappingEnd,
999                            ) = *self.peek_token()?
1000                            {
1001                                self.state = State::FlowMappingValue;
1002                                return Ok((Event::empty_scalar(), mark));
1003                            }
1004                            self.push_state(State::FlowMappingValue);
1005                            return self.parse_node(false, false);
1006                        }
1007                        Token(marker, TokenType::Value) => {
1008                            self.state = State::FlowMappingValue;
1009                            return Ok((Event::empty_scalar(), marker));
1010                        }
1011                        Token(_, TokenType::FlowMappingEnd) => (),
1012                        _ => {
1013                            self.push_state(State::FlowMappingEmptyValue);
1014                            return self.parse_node(false, false);
1015                        }
1016                    }
1017
1018                    mark
1019                }
1020            }
1021        };
1022
1023        self.pop_state();
1024        self.skip();
1025        Ok((Event::MappingEnd, span))
1026    }
1027
1028    fn flow_mapping_value<'a>(&mut self, empty: bool) -> ParseResult<'a>
1029    where
1030        'input: 'a,
1031    {
1032        let span: Span = {
1033            if empty {
1034                let Token(mark, _) = *self.peek_token()?;
1035                self.state = State::FlowMappingKey;
1036                return Ok((Event::empty_scalar(), mark));
1037            }
1038            match *self.peek_token()? {
1039                Token(span, TokenType::Value) => {
1040                    self.skip();
1041                    match self.peek_token()?.1 {
1042                        TokenType::FlowEntry | TokenType::FlowMappingEnd => {}
1043                        _ => {
1044                            self.push_state(State::FlowMappingKey);
1045                            return self.parse_node(false, false);
1046                        }
1047                    }
1048                    span
1049                }
1050                Token(marker, _) => marker,
1051            }
1052        };
1053
1054        self.state = State::FlowMappingKey;
1055        Ok((Event::empty_scalar(), span))
1056    }
1057
1058    fn flow_sequence_entry<'a>(&mut self, first: bool) -> ParseResult<'a>
1059    where
1060        'input: 'a,
1061    {
1062        // skip FlowMappingStart
1063        if first {
1064            let _ = self.peek_token()?;
1065            //self.marks.push(tok.0);
1066            self.skip();
1067        }
1068        match *self.peek_token()? {
1069            Token(mark, TokenType::FlowSequenceEnd) => {
1070                self.pop_state();
1071                self.skip();
1072                return Ok((Event::SequenceEnd, mark));
1073            }
1074            Token(_, TokenType::FlowEntry) if !first => {
1075                self.skip();
1076            }
1077            Token(span, _) if !first => {
1078                return Err(ScanError::new_str(
1079                    span.start,
1080                    "while parsing a flow sequence, expected ',' or ']'",
1081                ));
1082            }
1083            _ => { /* next */ }
1084        }
1085        match *self.peek_token()? {
1086            Token(mark, TokenType::FlowSequenceEnd) => {
1087                self.pop_state();
1088                self.skip();
1089                Ok((Event::SequenceEnd, mark))
1090            }
1091            Token(mark, TokenType::Key) => {
1092                self.state = State::FlowSequenceEntryMappingKey;
1093                self.skip();
1094                Ok((Event::MappingStart(0, None), mark))
1095            }
1096            _ => {
1097                self.push_state(State::FlowSequenceEntry);
1098                self.parse_node(false, false)
1099            }
1100        }
1101    }
1102
1103    fn indentless_sequence_entry<'a>(&mut self) -> ParseResult<'a>
1104    where
1105        'input: 'a,
1106    {
1107        match *self.peek_token()? {
1108            Token(mark, TokenType::BlockEntry) => {
1109                self.skip();
1110                if let Token(
1111                    _,
1112                    TokenType::BlockEntry | TokenType::Key | TokenType::Value | TokenType::BlockEnd,
1113                ) = *self.peek_token()?
1114                {
1115                    self.state = State::IndentlessSequenceEntry;
1116                    Ok((Event::empty_scalar(), mark))
1117                } else {
1118                    self.push_state(State::IndentlessSequenceEntry);
1119                    self.parse_node(true, false)
1120                }
1121            }
1122            Token(mark, _) => {
1123                self.pop_state();
1124                Ok((Event::SequenceEnd, mark))
1125            }
1126        }
1127    }
1128
1129    fn block_sequence_entry<'a>(&mut self, first: bool) -> ParseResult<'a>
1130    where
1131        'input: 'a,
1132    {
1133        // BLOCK-SEQUENCE-START
1134        if first {
1135            let _ = self.peek_token()?;
1136            //self.marks.push(tok.0);
1137            self.skip();
1138        }
1139        match *self.peek_token()? {
1140            Token(mark, TokenType::BlockEnd) => {
1141                self.pop_state();
1142                self.skip();
1143                Ok((Event::SequenceEnd, mark))
1144            }
1145            Token(mark, TokenType::BlockEntry) => {
1146                self.skip();
1147                if let Token(_, TokenType::BlockEntry | TokenType::BlockEnd) = *self.peek_token()? {
1148                    self.state = State::BlockSequenceEntry;
1149                    Ok((Event::empty_scalar(), mark))
1150                } else {
1151                    self.push_state(State::BlockSequenceEntry);
1152                    self.parse_node(true, false)
1153                }
1154            }
1155            Token(span, _) => Err(ScanError::new_str(
1156                span.start,
1157                "while parsing a block collection, did not find expected '-' indicator",
1158            )),
1159        }
1160    }
1161
1162    fn flow_sequence_entry_mapping_key<'a>(&mut self) -> ParseResult<'a>
1163    where
1164        'input: 'a,
1165    {
1166        if let Token(mark, TokenType::Value | TokenType::FlowEntry | TokenType::FlowSequenceEnd) =
1167            *self.peek_token()?
1168        {
1169            self.skip();
1170            self.state = State::FlowSequenceEntryMappingValue;
1171            Ok((Event::empty_scalar(), mark))
1172        } else {
1173            self.push_state(State::FlowSequenceEntryMappingValue);
1174            self.parse_node(false, false)
1175        }
1176    }
1177
1178    fn flow_sequence_entry_mapping_value<'a>(&mut self) -> ParseResult<'a>
1179    where
1180        'input: 'a,
1181    {
1182        match *self.peek_token()? {
1183            Token(_, TokenType::Value) => {
1184                self.skip();
1185                self.state = State::FlowSequenceEntryMappingValue;
1186                let Token(span, ref tok) = *self.peek_token()?;
1187                if matches!(tok, TokenType::FlowEntry | TokenType::FlowSequenceEnd) {
1188                    self.state = State::FlowSequenceEntryMappingEnd(span.end);
1189                    Ok((Event::empty_scalar(), span))
1190                } else {
1191                    self.push_state(State::FlowSequenceEntryMappingEnd(span.end));
1192                    self.parse_node(false, false)
1193                }
1194            }
1195            Token(mark, _) => {
1196                self.state = State::FlowSequenceEntryMappingEnd(mark.end);
1197                Ok((Event::empty_scalar(), mark))
1198            }
1199        }
1200    }
1201
1202    #[allow(clippy::unnecessary_wraps)]
1203    fn flow_sequence_entry_mapping_end<'a>(&mut self, mark: Marker) -> ParseResult<'a>
1204    where
1205        'input: 'a,
1206    {
1207        self.state = State::FlowSequenceEntry;
1208        Ok((Event::MappingEnd, Span::empty(mark)))
1209    }
1210
1211    /// Resolve a tag from the handle and the suffix.
1212    fn resolve_tag(
1213        &self,
1214        span: Span,
1215        handle: &str,
1216        suffix: String,
1217    ) -> Result<Cow<'input, Tag>, ScanError> {
1218        let tag = if handle == "!!" {
1219            // "!!" is a shorthand for "tag:yaml.org,2002:". However, that default can be
1220            // overridden.
1221            Tag {
1222                handle: self
1223                    .tags
1224                    .get("!!")
1225                    .map_or_else(|| "tag:yaml.org,2002:".to_string(), ToString::to_string),
1226                suffix,
1227            }
1228        } else if handle.is_empty() && suffix == "!" {
1229            // "!" introduces a local tag. Local tags may have their prefix overridden.
1230            match self.tags.get("") {
1231                Some(prefix) => Tag {
1232                    handle: prefix.clone(),
1233                    suffix,
1234                },
1235                None => Tag {
1236                    handle: String::new(),
1237                    suffix,
1238                },
1239            }
1240        } else {
1241            // Lookup handle in our tag directives.
1242            let prefix = self.tags.get(handle);
1243            if let Some(prefix) = prefix {
1244                Tag {
1245                    handle: prefix.clone(),
1246                    suffix,
1247                }
1248            } else {
1249                // Otherwise, it may be a local handle. With a local handle, the handle is set to
1250                // "!" and the suffix to whatever follows it ("!foo" -> ("!", "foo")).
1251                // If the handle is of the form "!foo!", this cannot be a local handle and we need
1252                // to error.
1253                if handle.len() >= 2 && handle.starts_with('!') && handle.ends_with('!') {
1254                    return Err(ScanError::new_str(span.start, "the handle wasn't declared"));
1255                }
1256                Tag {
1257                    handle: handle.to_string(),
1258                    suffix,
1259                }
1260            }
1261        };
1262        Ok(Cow::Owned(tag))
1263    }
1264}
1265
1266impl<'input, T: Input> Iterator for Parser<'input, T> {
1267    type Item = Result<(Event<'input>, Span), ScanError>;
1268
1269    fn next(&mut self) -> Option<Self::Item> {
1270        self.next_event()
1271    }
1272}
1273
1274#[cfg(test)]
1275mod test {
1276    use super::{Event, Parser};
1277
1278    #[test]
1279    fn test_peek_eq_parse() {
1280        let s = "
1281a0 bb: val
1282a1: &x
1283    b1: 4
1284    b2: d
1285a2: 4
1286a3: [1, 2, 3]
1287a4:
1288    - [a1, a2]
1289    - 2
1290a5: *x
1291";
1292        let mut p = Parser::new_from_str(s);
1293        loop {
1294            let event_peek = p.peek().unwrap().unwrap().clone();
1295            let event = p.next_event().unwrap().unwrap();
1296            assert_eq!(event, event_peek);
1297            if event.0 == Event::StreamEnd {
1298                break;
1299            }
1300        }
1301    }
1302
1303    #[test]
1304    fn test_keep_tags_across_multiple_documents() {
1305        let text = r#"
1306%YAML 1.1
1307%TAG !t! tag:test,2024:
1308--- !t!1 &1
1309foo: "bar"
1310--- !t!2 &2
1311baz: "qux"
1312"#;
1313        for x in Parser::new_from_str(text).keep_tags(true) {
1314            let x = x.unwrap();
1315            if let Event::MappingStart(_, tag) = x.0 {
1316                let tag = tag.unwrap();
1317                assert_eq!(tag.handle, "tag:test,2024:");
1318            }
1319        }
1320
1321        for x in Parser::new_from_str(text).keep_tags(false) {
1322            if x.is_err() {
1323                // Test successful
1324                return;
1325            }
1326        }
1327        panic!("Test failed, did not encounter error")
1328    }
1329}