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