Skip to main content

granit_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    error::{ErrorKind, ScanError},
9    input::{str::StrInput, BorrowedInput},
10    scanner::{Marker, QueuedToken, QueuedTokenType, ScalarStyle, Scanner, Span},
11    BufferedInput, FallibleBufferedInput, Options,
12};
13
14#[cfg(feature = "comments")]
15use crate::scanner::Placement;
16#[cfg(feature = "comments")]
17use alloc::collections::VecDeque;
18use alloc::{
19    borrow::Cow,
20    collections::{BTreeMap, BTreeSet},
21    string::{String, ToString},
22    vec::Vec,
23};
24use core::{
25    convert::Infallible,
26    fmt::{self, Display},
27};
28
29#[derive(Clone, Copy, PartialEq, Debug, Eq)]
30enum State {
31    StreamStart,
32    ImplicitDocumentStart,
33    DocumentStart,
34    DocumentContent,
35    DocumentEnd,
36    BlockNode,
37    BlockNodeOrIndentlessSequence,
38    FlowNode,
39    BlockSequenceFirstEntry,
40    BlockSequenceEntry,
41    IndentlessSequenceEntry,
42    IndentlessSequenceEntryNode,
43    BlockMappingFirstKey,
44    BlockMappingKey,
45    #[cfg(feature = "comments")]
46    BlockMappingKeyNode,
47    BlockMappingValue,
48    #[cfg(feature = "comments")]
49    BlockMappingValueNode,
50    FlowSequenceFirstEntry,
51    FlowSequenceEntry,
52    FlowSequenceEntryMappingKey,
53    FlowSequenceEntryMappingValue,
54    #[cfg(feature = "comments")]
55    FlowSequenceEntryMappingValueNode,
56    FlowSequenceEntryMappingEnd,
57    FlowMappingFirstKey,
58    FlowMappingKey,
59    #[cfg(feature = "comments")]
60    FlowMappingKeyNode,
61    FlowMappingValue,
62    #[cfg(feature = "comments")]
63    FlowMappingValueNode,
64    FlowMappingEmptyValue,
65    #[cfg(feature = "comments")]
66    BlockSequenceEntryNode,
67    End,
68}
69
70/// YAML version declared by a `%YAML` directive.
71#[derive(Copy, Clone, PartialEq, Debug, Eq, Hash)]
72pub struct YamlVersion {
73    /// Major version number.
74    pub major: u32,
75    /// Minor version number.
76    pub minor: u32,
77}
78
79impl YamlVersion {
80    /// Create a YAML version value.
81    #[must_use]
82    pub const fn new(major: u32, minor: u32) -> Self {
83        Self { major, minor }
84    }
85}
86
87/// An event generated by the YAML parser.
88///
89/// Events are used in the low-level event-based API (push parser). The API entrypoint is the
90/// [`EventReceiver`] trait.
91#[non_exhaustive]
92#[derive(Clone, PartialEq, Debug, Eq)]
93pub enum Event<'input> {
94    /// Event generated at the very beginning of parsing.
95    StreamStart,
96    /// Last event that will be generated by the parser. Signals EOF.
97    StreamEnd,
98    /// The start of a YAML document.
99    ///
100    DocumentStart(
101        /// Whether this is an explicit document start marker (`---`).
102        ///
103        /// When `false`, the document start is implicit.
104        bool,
105        /// YAML version declared by a preceding `%YAML` directive, if any.
106        Option<YamlVersion>,
107    ),
108    /// The end of a YAML document.
109    ///
110    /// This event is emitted for both explicit document end markers (`...`) and implicit document
111    /// ends.
112    DocumentEnd,
113    /// A YAML alias.
114    Alias(
115        /// The anchor ID the alias refers to.
116        usize,
117    ),
118    /// A YAML source comment.
119    ///
120    /// Comments are presentation metadata, not YAML data nodes. The payload is the raw text
121    /// exactly after `#`, excluding only the line break. The placement is a best-effort hint for
122    /// correlating the comment with nearby YAML presentation. The companion parser [`Span`] covers
123    /// the whole source comment, including `#` and excluding the line break.
124    #[cfg(feature = "comments")]
125    Comment(
126        /// Raw comment payload exactly after `#`, excluding only the line break.
127        Cow<'input, str>,
128        /// Best-effort placement relative to nearby YAML content.
129        Placement,
130    ),
131    /// A YAML scalar value.
132    Scalar(
133        /// The scalar value after YAML escape processing.
134        Cow<'input, str>,
135        /// The source notation used for the scalar.
136        ScalarStyle,
137        /// The anchor ID defined on this scalar, or `0` if it has no anchor.
138        usize,
139        /// The resolved tag attached to this scalar, if any.
140        Option<Cow<'input, Tag>>,
141    ),
142    /// The start of a YAML sequence (array).
143    SequenceStart(
144        /// The notation style used for the sequence.
145        StructureStyle,
146        /// The anchor ID defined on this sequence, or `0` if it has no anchor.
147        usize,
148        /// The resolved tag attached to this sequence, if any.
149        Option<Cow<'input, Tag>>,
150    ),
151    /// The end of a YAML sequence (array).
152    SequenceEnd,
153    /// The start of a YAML mapping (object, hash).
154    MappingStart(
155        /// The notation style used for the mapping (Flow or Block).
156        StructureStyle,
157        /// The anchor ID defined on this mapping, or `0` if it has no anchor.
158        usize,
159        /// The resolved tag attached to this mapping, if any.
160        Option<Cow<'input, Tag>>,
161    ),
162    /// The end of a YAML mapping (object, hash).
163    MappingEnd,
164}
165
166/// The notation style used for a YAML sequence or mapping.
167///
168/// [`StructureStyle::Block`] means block notation:
169///
170/// ```yaml
171/// items:
172///   - milk
173///   - bread
174/// mapping:
175///   name: Ada
176///   active: true
177/// ```
178///
179/// [`StructureStyle::Flow`] means flow notation:
180///
181/// ```yaml
182/// items: [milk, bread]
183/// mapping: {name: Ada, active: true}
184/// ```
185#[derive(Clone, Copy, PartialEq, Debug, Eq, Hash, PartialOrd, Ord)]
186pub enum StructureStyle {
187    /// Block notation, such as `- item` sequences and `key: value` mappings.
188    Block,
189    /// Flow notation, such as `[item]` sequences and `{key: value}` mappings.
190    Flow,
191}
192
193/// A YAML tag.
194#[derive(Clone, PartialEq, Debug, Eq, Ord, PartialOrd, Hash)]
195pub struct Tag {
196    /// Resolved tag handle or prefix.
197    ///
198    /// Examples include `tag:yaml.org,2002:` for core-schema tags and `!` for local tags.
199    handle: String,
200    /// Tag suffix following the resolved handle or prefix.
201    suffix: String,
202    /// Tag handle as written in the source before `%TAG` directive resolution.
203    ///
204    /// For example, with `%TAG !e! tag:example.com,2000:`, a source tag `!e!keep` is resolved
205    /// as `handle = "tag:example.com,2000:"` and `suffix = "keep"`, while
206    /// `original_handle = "!e!"`.
207    original_handle: String,
208}
209
210const YAML_CORE_SCHEMA_PREFIX: &str = "tag:yaml.org,2002:";
211
212// YAML 1.2.2 defines Core Schema tags by reference:
213// - §10.3.1 says Core Schema uses the same tags as YAML's JSON Schema.
214// - §10.2.1 adds null/bool/int/float to the Failsafe Schema.
215// - §10.1.1 defines the Failsafe Schema tags map/seq/str.
216// Therefore the YAML 1.2.2 Core Schema tag suffixes are:
217// bool, float, int, map, null, seq, and str.
218const YAML_CORE_SCHEMA_SUFFIXES: [&str; 7] = ["bool", "float", "int", "map", "null", "seq", "str"];
219
220fn known_yaml_core_schema_suffix(suffix: &str) -> Option<&str> {
221    YAML_CORE_SCHEMA_SUFFIXES
222        .contains(&suffix)
223        .then_some(suffix)
224}
225
226fn known_yaml_core_schema_suffix_from_split(
227    handle_tail: &str,
228    suffix: &str,
229) -> Option<&'static str> {
230    YAML_CORE_SCHEMA_SUFFIXES.iter().copied().find(|candidate| {
231        candidate
232            .strip_prefix(handle_tail)
233            .is_some_and(|candidate_tail| candidate_tail == suffix)
234    })
235}
236
237impl Tag {
238    /// Create a tag from resolved parts.
239    ///
240    /// This is mainly useful for tests and consumers constructing parser-compatible tags by hand.
241    /// When the original source handle matters, use [`Self::with_original_handle`].
242    #[must_use]
243    pub fn new(handle: impl Into<String>, suffix: impl Into<String>) -> Self {
244        let handle = handle.into();
245        Self {
246            original_handle: handle.clone(),
247            handle,
248            suffix: suffix.into(),
249        }
250    }
251
252    /// Create a tag from resolved parts and the handle as written in the source.
253    #[must_use]
254    pub fn with_original_handle(
255        handle: impl Into<String>,
256        suffix: impl Into<String>,
257        original_handle: impl Into<String>,
258    ) -> Self {
259        Self {
260            handle: handle.into(),
261            suffix: suffix.into(),
262            original_handle: original_handle.into(),
263        }
264    }
265
266    /// Return the resolved tag handle or prefix.
267    #[must_use]
268    pub fn handle(&self) -> &str {
269        &self.handle
270    }
271
272    /// Return the suffix following the resolved tag handle or prefix.
273    #[must_use]
274    pub fn suffix(&self) -> &str {
275        &self.suffix
276    }
277
278    /// Return the tag handle as written before `%TAG` directive resolution.
279    #[must_use]
280    pub fn original_handle(&self) -> &str {
281        &self.original_handle
282    }
283
284    /// Return the resolved YAML core-schema suffix for this tag, if it is a known core tag.
285    ///
286    /// The tag is matched by its resolved URI, not by the source handle spelling. For example,
287    /// `!!int`, `!<tag:yaml.org,2002:int>`, and a `%TAG` split such as
288    /// `%TAG !m! tag:yaml.org,2002:i` followed by `!m!nt` all return `Some("int")`.
289    ///
290    /// Authored tag parts are left unchanged; use [`Self::parts`], [`Self::original_parts`], or
291    /// [`Self::original`] to inspect those spellings.
292    #[must_use]
293    pub fn core_suffix(&self) -> Option<&str> {
294        // The handle ends at or before the namespace boundary. The remaining namespace
295        // prefix and the complete type name are both contained in `suffix`.
296        if let Some(remaining_prefix) = YAML_CORE_SCHEMA_PREFIX.strip_prefix(self.handle.as_str()) {
297            let suffix = self.suffix.strip_prefix(remaining_prefix)?;
298            return known_yaml_core_schema_suffix(suffix);
299        }
300
301        // The handle extends beyond the namespace boundary, so the type name is split
302        // between the end of `handle` and `suffix`. Compare against the seven fixed names
303        // directly instead of assembling an allocated String.
304        let handle_tail = self.handle.strip_prefix(YAML_CORE_SCHEMA_PREFIX)?;
305        known_yaml_core_schema_suffix_from_split(handle_tail, &self.suffix)
306    }
307
308    /// Return the type name this tag resolves to within `prefix`, or `None` outside it.
309    ///
310    /// Like [`Self::core_suffix`], the tag is matched by its resolved `handle ++ suffix` URI,
311    /// not the source spelling, so `!!omap`, `!<tag:yaml.org,2002:omap>`, and a `%TAG` split
312    /// such as `%TAG !o! tag:yaml.org,2002:o` then `!o!map` all resolve to `Some("omap")` for
313    /// the `tag:yaml.org,2002:` prefix — but the name is not limited to the seven core types.
314    ///
315    /// Borrows from `self`; allocates only when the handle extends past `prefix`.
316    #[must_use]
317    pub fn suffix_in_namespace(&self, prefix: &str) -> Option<Cow<'_, str>> {
318        if let Some(handle_tail) = self.handle.strip_prefix(prefix) {
319            // Handle spans the whole prefix; the name is its tail plus the suffix (the tail
320            // is empty unless a `%TAG` split pushed part of the name into the handle).
321            return Some(if handle_tail.is_empty() {
322                Cow::Borrowed(self.suffix.as_str())
323            } else {
324                let mut name = String::with_capacity(handle_tail.len() + self.suffix.len());
325                name.push_str(handle_tail);
326                name.push_str(&self.suffix);
327                Cow::Owned(name)
328            });
329        }
330
331        // Handle stops inside the prefix; the suffix supplies the rest of the prefix
332        // and then the name.
333        prefix
334            .strip_prefix(self.handle.as_str())
335            .and_then(|prefix_tail| self.suffix.strip_prefix(prefix_tail))
336            .map(Cow::Borrowed)
337    }
338
339    /// Returns whether the tag is a YAML tag from the core schema (`!!str`, `!!int`, ...).
340    ///
341    /// The YAML specification specifies [a list of
342    /// tags](https://yaml.org/spec/1.2.2/#103-core-schema) for the Core Schema. This function uses
343    /// the resolved tag URI, so it is independent of how the tag was split between handle and
344    /// suffix.
345    ///
346    /// # Return
347    /// Returns `true` if the resolved tag is a known YAML 1.2.2 Core Schema tag.
348    #[must_use]
349    pub fn is_yaml_core_schema(&self) -> bool {
350        self.core_suffix().is_some()
351    }
352
353    /// Return true for a YAML core-schema tag with the given suffix.
354    ///
355    /// For example, this matches core-schema tags such as `!!str`, `!!int`, `!!float`, `!!bool`,
356    /// `!!null`, `!!map`, or `!!seq` after tag resolution.
357    #[must_use]
358    pub fn is_yaml_core_schema_tag(&self, suffix: &str) -> bool {
359        self.core_suffix()
360            .is_some_and(|core_suffix| core_suffix == suffix)
361    }
362
363    /// Return true for a tag outside the YAML 1.2.2 Core Schema tag set.
364    ///
365    /// This checks the resolved tag URI, not just the tag handle spelling. For example,
366    /// `tag:yaml.org,2002:timestamp` is in the YAML tag namespace, but it is not a YAML 1.2.2
367    /// Core Schema tag.
368    #[must_use]
369    pub fn is_custom(&self) -> bool {
370        !self.is_yaml_core_schema()
371    }
372
373    /// Return the tag as `(handle, suffix)`.
374    #[must_use]
375    pub fn parts(&self) -> (&str, &str) {
376        (&self.handle, &self.suffix)
377    }
378
379    /// Return the tag as `(original_handle, suffix)` using the handle from the source token.
380    ///
381    /// This is useful when a consumer needs author spelling such as `!e!keep` instead of the
382    /// resolved URI tag `tag:example.com,2000:keep`.
383    #[must_use]
384    pub fn original_parts(&self) -> (&str, &str) {
385        (&self.original_handle, &self.suffix)
386    }
387
388    /// Return the tag spelling reconstructed from the source handle and suffix.
389    ///
390    /// For ordinary shorthand tags this returns the author-facing spelling, such as `!e!keep` or
391    /// `!!str`. For verbatim tags this returns a normalized verbatim spelling such as
392    /// `!<tag:example.com,2000:thing>`, not necessarily the byte-exact source token.
393    #[must_use]
394    pub fn original(&self) -> String {
395        if self.original_handle.is_empty() && self.suffix != "!" {
396            let mut tag = String::with_capacity(self.suffix.len() + 3);
397            tag.push_str("!<");
398            tag.push_str(&self.suffix);
399            tag.push('>');
400            return tag;
401        }
402
403        let mut tag = String::with_capacity(self.original_handle.len() + self.suffix.len());
404        tag.push_str(&self.original_handle);
405        tag.push_str(&self.suffix);
406        tag
407    }
408}
409
410impl Display for Tag {
411    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
412        if self.handle == "!" {
413            write!(f, "!{}", self.suffix)
414        } else {
415            write!(f, "{}{}", self.handle, self.suffix)
416        }
417    }
418}
419
420impl<'input> Event<'input> {
421    /// Return the anchor ID defined by this event, if any.
422    ///
423    /// Returns `Some(id)` when this event defines an anchor on a scalar, sequence, or mapping
424    /// node. Returns `None` for all other events, including `Alias` (which references an anchor
425    /// rather than defining one; use [`Self::alias_id`] to obtain the target anchor ID).
426    #[must_use]
427    pub fn anchor_id(&self) -> Option<usize> {
428        match self {
429            Self::Scalar(_, _, anchor_id, _)
430            | Self::SequenceStart(_, anchor_id, _)
431            | Self::MappingStart(_, anchor_id, _)
432                if *anchor_id != 0 =>
433            {
434                Some(*anchor_id)
435            }
436            _ => None,
437        }
438    }
439
440    /// Return the target anchor ID referenced by this alias event, if this event is an alias.
441    #[must_use]
442    pub fn alias_id(&self) -> Option<usize> {
443        match self {
444            Self::Alias(anchor_id) => Some(*anchor_id),
445            _ => None,
446        }
447    }
448
449    /// Return the resolved tag carried by this node event, if any.
450    #[must_use]
451    pub fn tag(&self) -> Option<&Tag> {
452        match self {
453            Self::Scalar(_, _, _, tag)
454            | Self::SequenceStart(_, _, tag)
455            | Self::MappingStart(_, _, tag) => tag.as_deref(),
456            _ => None,
457        }
458    }
459
460    /// Return the scalar value and style, if this event is a scalar.
461    #[must_use]
462    pub fn scalar(&self) -> Option<(&str, ScalarStyle)> {
463        match self {
464            Self::Scalar(value, style, _, _) => Some((value.as_ref(), *style)),
465            _ => None,
466        }
467    }
468
469    /// Return whether this event represents a YAML node (value).
470    ///
471    /// Returns `true` for scalars, collection starts, and aliases — all events that produce a
472    /// value in the document tree. Returns `false` for structural events such as `StreamStart`,
473    /// `DocumentStart`, collection ends, etc.
474    #[must_use]
475    pub fn is_node(&self) -> bool {
476        matches!(
477            self,
478            Self::Alias(_) | Self::Scalar(..) | Self::SequenceStart(..) | Self::MappingStart(..)
479        )
480    }
481
482    /// Create an empty scalar.
483    fn empty_scalar() -> Self {
484        // a null scalar
485        Event::Scalar("~".into(), ScalarStyle::Plain, 0, None)
486    }
487
488    /// Create an empty scalar with the given node properties.
489    fn empty_scalar_with_anchor(anchor: usize, tag: Option<Cow<'input, Tag>>) -> Self {
490        let value = if tag.is_some() {
491            Cow::default()
492        } else {
493            "~".into()
494        };
495
496        Event::Scalar(value, ScalarStyle::Plain, anchor, tag)
497    }
498}
499
500/// A YAML parser.
501#[derive(Debug)]
502pub struct Parser<'input, T: BorrowedInput<'input>> {
503    /// The underlying scanner from which we pull tokens.
504    scanner: Scanner<'input, T>,
505    /// Maximum number of comments retained while resolving an ambiguous collection entry.
506    #[cfg(feature = "comments")]
507    max_buffered_comment_events: usize,
508    /// Maximum number of simultaneously open block collections.
509    block_nesting_limit: usize,
510    /// Number of block collections currently open in the parser state machine.
511    block_level: usize,
512    /// The stack of _previous_ states we were in.
513    ///
514    /// States are pushed in the context of subobjects to this stack. The top-most element is the
515    /// state in which to come back to when exiting the current state.
516    states: Vec<State>,
517    /// The state in which we currently are.
518    state: State,
519    /// The next token from the scanner.
520    token: Option<QueuedToken<'input>>,
521    /// The next YAML event to emit.
522    current: Option<(Event<'input>, Span)>,
523    /// The next parser error to emit after it has been observed by `peek`.
524    current_error: Option<ScanError>,
525    /// A scanner error discovered while ordering events that must be emitted first.
526    ///
527    /// Unlike `current_error`, this has not been exposed through `peek`. It is consumed by
528    /// `next_event_impl` after already-buffered events so `peek`, iteration, and `load` all retain
529    /// the same ordering.
530    #[cfg(feature = "comments")]
531    deferred_error: Option<ScanError>,
532    /// YAML events buffered by parser states that need to emit an earlier synthetic node first.
533    #[cfg(feature = "comments")]
534    queued_events: VecDeque<(Event<'input>, Span)>,
535
536    /// Pending indentation hint to be attached to the next emitted event span.
537    ///
538    /// This is used to communicate indentation for block mapping keys. It is set when consuming a
539    /// `TokenType::Key` in block style, and is applied to the next emitted node event (the key
540    /// itself).
541    pending_key_indent: Option<usize>,
542    /// Pending anchor ID to attach to a node after an intervening comment.
543    #[cfg(feature = "comments")]
544    pending_node_anchor_id: usize,
545    /// Pending tag to attach to a node after an intervening comment.
546    #[cfg(feature = "comments")]
547    pending_node_tag: Option<Cow<'input, Tag>>,
548    /// Pending explicit tag token start to attach to a node after an intervening comment.
549    #[cfg(feature = "comments")]
550    pending_node_tag_start: Option<Marker>,
551    /// Pending end marker of the last node-property token before an intervening comment.
552    #[cfg(feature = "comments")]
553    pending_node_property_end: Option<Marker>,
554    /// Pending empty scalar span captured before an intervening comment.
555    pending_empty_scalar_span: Option<Span>,
556    /// End marker of the most recently produced non-comment event.
557    ///
558    /// Synthetic syntax events use this marker, so presentation-only comments must not affect it.
559    last_non_comment_event_end: Option<Marker>,
560    /// Pending YAML version captured before comments preceding an explicit document start.
561    #[cfg(feature = "comments")]
562    pending_document_version: Option<YamlVersion>,
563    /// Whether document directives were already initialized before comments preceding `---`.
564    #[cfg(feature = "comments")]
565    pending_document_directives: bool,
566    /// `%TAG` handles already seen before comments preceding an explicit document start.
567    #[cfg(feature = "comments")]
568    pending_document_tag_handles: BTreeSet<Cow<'input, str>>,
569    /// Anchors that have been encountered in the YAML document.
570    anchors: BTreeMap<Cow<'input, str>, usize>,
571    /// Next ID available for an anchor.
572    ///
573    /// Every anchor is given a unique ID. We use an incrementing ID and this is both the ID to
574    /// return for the next anchor and the count of anchor IDs emitted.
575    anchor_id_count: usize,
576    /// The tag directives (`%TAG`) the parser has encountered.
577    ///
578    /// Key is the handle, and value is the prefix.
579    tags: BTreeMap<Cow<'input, str>, Cow<'input, str>>,
580    /// Whether we have emitted a terminal iterator result.
581    ///
582    /// Terminal means either [`Event::StreamEnd`] or a [`ScanError`]. Emitted means that it has
583    /// been returned from [`Self::next_event`] or [`Self::next`]. If the terminal result is stored
584    /// in [`Self::current`], [`Self::current_error`], or internal comment buffers, this is set to
585    /// `false`.
586    stream_end_emitted: bool,
587    /// Make tags global across all documents.
588    keep_tags: bool,
589}
590
591/// Trait to be implemented in order to use the low-level parsing API.
592///
593/// The low-level parsing API is event-based (a push parser), calling [`EventReceiver::on_event`]
594/// for each YAML [`Event`] that occurs.
595/// The [`EventReceiver`] trait only receives events. In order to receive both events and their
596/// location in the source, use [`SpannedEventReceiver`]. Note that [`EventReceiver`]s implement
597/// [`SpannedEventReceiver`] automatically.
598/// With the `comments` feature, non-spanned receivers receive `Event::Comment(text, placement)` like any
599/// other event, but without source location. Spanned receivers receive the same comment event plus
600/// the comment [`Span`] in [`SpannedEventReceiver::on_event`]. For comments, that span covers the
601/// whole source comment, including `#` and excluding the line break. When parsing from an input
602/// with byte offsets, such as [`Parser::new_from_str`], [`Span::slice`] returns that source
603/// comment text.
604///
605/// # Event hierarchy
606/// The event stream starts with an [`Event::StreamStart`] event followed by an
607/// [`Event::DocumentStart`] event. If the YAML document starts with a mapping (an object), an
608/// [`Event::MappingStart`] event is emitted. If it starts with a sequence (an array), an
609/// [`Event::SequenceStart`] event is emitted. Otherwise, an [`Event::Scalar`] event is emitted.
610///
611/// In a mapping, key-values are sent as consecutive data events. Comments can appear in the raw
612/// event stream between a key and its value; they are presentation metadata, not YAML data nodes.
613/// Consumers building YAML data trees should ignore `Event::Comment`. Any key/value alternation
614/// shortcut applies only after filtering out comments and other presentation metadata. After that
615/// filtering, the first event after an [`Event::MappingStart`] will be the key, and the following
616/// event will be its value. If the mapping contains no sub-mapping or sub-sequence, then even events
617/// (starting from 0) will always be keys and odd ones will always be values. The mapping ends when
618/// an [`Event::MappingEnd`] event is received.
619///
620/// In a sequence, values are sent consecutively until the [`Event::SequenceEnd`] event.
621///
622/// If a value is a sub-mapping or a sub-sequence, an [`Event::MappingStart`] or
623/// [`Event::SequenceStart`] event will be sent respectively. Following events until the associated
624/// [`Event::MappingEnd`] or [`Event::SequenceEnd`] (beware of nested mappings or sequences) will
625/// be part of the value and not another key-value pair or element in the sequence.
626///
627/// For instance, the following YAML:
628/// ```yaml
629/// a: b
630/// c:
631///   d: e
632/// f:
633///   - g
634///   - h
635/// ```
636/// will emit (indented and commented for visibility):
637/// ```text
638/// StreamStart, DocumentStart, MappingStart,
639///   Scalar("a", ..), Scalar("b", ..)
640///   Scalar("c", ..), MappingStart, Scalar("d", ..), Scalar("e", ..), MappingEnd,
641///   Scalar("f", ..), SequenceStart, Scalar("g", ..), Scalar("h", ..), SequenceEnd,
642/// MappingEnd, DocumentEnd, StreamEnd
643/// ```
644///
645/// # Example
646/// ```
647/// # use granit_parser::{Event, EventReceiver, Parser};
648/// #
649/// /// Sink of events. Collects them into an array.
650/// struct EventSink<'input> {
651///     events: Vec<Event<'input>>,
652/// }
653///
654/// /// Implement `on_event`, pushing into `self.events`.
655/// impl<'input> EventReceiver<'input> for EventSink<'input> {
656///     fn on_event(&mut self, ev: Event<'input>) {
657///         self.events.push(ev);
658///     }
659/// }
660///
661/// /// Load events from a YAML string.
662/// fn str_to_events(yaml: &str) -> Vec<Event<'_>> {
663///     let mut sink = EventSink { events: Vec::new() };
664///     let mut parser = Parser::new_from_str(yaml);
665///     // Load events using our sink as the receiver.
666///     parser.load(&mut sink, true).unwrap();
667///     sink.events
668/// }
669/// ```
670pub trait EventReceiver<'input> {
671    /// Handler called for each YAML event that is emitted by the parser.
672    fn on_event(&mut self, ev: Event<'input>);
673}
674
675/// Trait to be implemented for using the low-level parsing API.
676///
677/// Functionally similar to [`EventReceiver`], but receives a [`Span`] as well as the event.
678/// With the `comments` feature, an `Event::Comment` span is the source range of the whole comment.
679pub trait SpannedEventReceiver<'input> {
680    /// Handler called for each event that occurs.
681    fn on_event(&mut self, ev: Event<'input>, span: Span);
682}
683
684impl<'input, R: EventReceiver<'input>> SpannedEventReceiver<'input> for R {
685    fn on_event(&mut self, ev: Event<'input>, _span: Span) {
686        self.on_event(ev);
687    }
688}
689
690/// Trait to be implemented for fallible event handling without source spans.
691///
692/// This is the fallible counterpart to [`EventReceiver`]. Use it with [`Parser::try_load`] when
693/// event handling may need to stop parsing by returning an application error.
694pub trait TryEventReceiver<'input> {
695    /// Error returned by this receiver.
696    type Error;
697
698    /// Handler called for each YAML event that is emitted by the parser.
699    ///
700    /// Returning an error stops [`Parser::try_load`] immediately.
701    ///
702    /// # Errors
703    /// Returns `Self::Error` when the receiver wants to stop parsing.
704    fn on_event(&mut self, ev: Event<'input>) -> Result<(), Self::Error>;
705}
706
707/// Trait to be implemented for fallible event handling with source spans.
708///
709/// This is the fallible counterpart to [`SpannedEventReceiver`]. Use it with
710/// [`Parser::try_load`] when event handling may need to stop parsing by returning an application
711/// error.
712pub trait TrySpannedEventReceiver<'input> {
713    /// Error returned by this receiver.
714    type Error;
715
716    /// Handler called for each event that occurs.
717    ///
718    /// Returning an error stops [`Parser::try_load`] immediately.
719    ///
720    /// # Errors
721    /// Returns `Self::Error` when the receiver wants to stop parsing.
722    fn on_event(&mut self, ev: Event<'input>, span: Span) -> Result<(), Self::Error>;
723}
724
725impl<'input, R: TryEventReceiver<'input>> TrySpannedEventReceiver<'input> for R {
726    type Error = R::Error;
727
728    fn on_event(&mut self, ev: Event<'input>, _span: Span) -> Result<(), Self::Error> {
729        TryEventReceiver::on_event(self, ev)
730    }
731}
732
733/// Error returned by [`Parser::try_load`] and [`ParserTrait::try_load`].
734#[derive(Clone, PartialEq, Debug, Eq)]
735pub enum TryLoadError<E> {
736    /// Scanning or parsing failed.
737    Scan(
738        /// The scanner or parser error.
739        ScanError,
740    ),
741    /// The receiver returned an application error.
742    Receiver(
743        /// The error returned by the receiver.
744        E,
745    ),
746}
747
748impl<E> TryLoadError<E> {
749    #[cold]
750    fn scan(error: ScanError) -> Self {
751        Self::Scan(error)
752    }
753
754    #[cold]
755    fn receiver(error: E) -> Self {
756        Self::Receiver(error)
757    }
758}
759
760impl<E> From<ScanError> for TryLoadError<E> {
761    #[cold]
762    fn from(error: ScanError) -> Self {
763        Self::scan(error)
764    }
765}
766
767impl<E: Display> Display for TryLoadError<E> {
768    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
769        match self {
770            Self::Scan(error) => write!(f, "parser error: {error}"),
771            Self::Receiver(error) => write!(f, "receiver error: {error}"),
772        }
773    }
774}
775
776impl<E> core::error::Error for TryLoadError<E>
777where
778    E: core::error::Error + 'static,
779{
780    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
781        match self {
782            Self::Scan(error) => Some(error),
783            Self::Receiver(error) => Some(error),
784        }
785    }
786}
787
788fn try_emit<'input, R>(
789    recv: &mut R,
790    ev: Event<'input>,
791    span: Span,
792) -> Result<(), TryLoadError<R::Error>>
793where
794    R: TrySpannedEventReceiver<'input>,
795{
796    recv.on_event(ev, span).map_err(TryLoadError::receiver)
797}
798
799struct InfallibleSpannedReceiver<'receiver, R>(&'receiver mut R);
800
801impl<'input, R: SpannedEventReceiver<'input>> TrySpannedEventReceiver<'input>
802    for InfallibleSpannedReceiver<'_, R>
803{
804    type Error = Infallible;
805
806    fn on_event(&mut self, ev: Event<'input>, span: Span) -> Result<(), Self::Error> {
807        self.0.on_event(ev, span);
808        Ok(())
809    }
810}
811
812fn into_scan_result(result: Result<(), TryLoadError<Infallible>>) -> Result<(), ScanError> {
813    match result {
814        Ok(()) => Ok(()),
815        Err(TryLoadError::Scan(error)) => error.into_result(),
816        Err(TryLoadError::Receiver(error)) => match error {},
817    }
818}
819
820/// A convenience alias for a parser event result.
821pub type ParseResult<'input> = Result<(Event<'input>, Span), ScanError>;
822
823/// Trait extracted from `Parser` to support mocking and alternative implementations.
824pub trait ParserTrait<'input> {
825    /// Try to load the next event and return it without consuming it from `self`.
826    fn peek(&mut self) -> Option<Result<&(Event<'input>, Span), ScanError>>;
827
828    /// Try to load the next event and return it, consuming it from `self`.
829    fn next_event(&mut self) -> Option<ParseResult<'input>>;
830
831    /// Load the YAML from the stream in `self`, pushing events into `recv`.
832    ///
833    /// Use this method when event handling is infallible. If receiver code can return an
834    /// application error and should stop parsing, use [`ParserTrait::try_load`] instead. If the
835    /// caller should directly control when the next event is read, use [`ParserTrait::next_event`]
836    /// or [`Parser`]'s [`core::iter::Iterator`] implementation.
837    ///
838    /// # Errors
839    /// Returns `ScanError` when scanning or parsing the stream fails.
840    fn load<R: SpannedEventReceiver<'input>>(
841        &mut self,
842        recv: &mut R,
843        multi: bool,
844    ) -> Result<(), ScanError>;
845
846    /// Load the YAML from the stream in `self`, stopping if `recv` returns an error.
847    ///
848    /// If `multi` is set to `true`, the parser will allow parsing of multiple YAML documents
849    /// inside the stream.
850    ///
851    /// If the receiver returns an error, the parser is left positioned immediately after the event
852    /// that caused the receiver error. Callers should treat the parser as partially consumed.
853    ///
854    /// # Errors
855    /// Returns [`TryLoadError::Scan`] when scanning or parsing the stream fails. Returns
856    /// [`TryLoadError::Receiver`] when `recv` returns an error.
857    fn try_load<R: TrySpannedEventReceiver<'input>>(
858        &mut self,
859        recv: &mut R,
860        multi: bool,
861    ) -> Result<(), TryLoadError<R::Error>> {
862        while let Some(res) = self.next_event() {
863            let (ev, span) = res?;
864            let is_doc_end = matches!(ev, Event::DocumentEnd);
865            let is_stream_end = matches!(ev, Event::StreamEnd);
866
867            try_emit(recv, ev, span)?;
868
869            if is_stream_end {
870                break;
871            }
872            if !multi && is_doc_end {
873                break;
874            }
875        }
876
877        Ok(())
878    }
879}
880
881impl<'input> Parser<'input, StrInput<'input>> {
882    /// Create a parser over a borrowed string slice.
883    #[must_use]
884    pub fn new_from_str(value: &'input str) -> Self {
885        Self::new_from_str_with_options(value, Options::default())
886    }
887
888    /// Create a parser over a borrowed string slice with configurable behavior and resource
889    /// limits.
890    #[must_use]
891    pub fn new_from_str_with_options(value: &'input str, options: Options) -> Self {
892        Parser::with_options(StrInput::new(value), options)
893    }
894}
895
896impl<T> Parser<'static, BufferedInput<T>>
897where
898    T: Iterator<Item = char>,
899{
900    /// Create a parser over an iterator of characters.
901    #[must_use]
902    pub fn new_from_iter(iter: T) -> Self {
903        Self::new_from_iter_with_options(iter, Options::default())
904    }
905
906    /// Create a parser over an iterator of characters with configurable behavior and resource
907    /// limits.
908    #[must_use]
909    pub fn new_from_iter_with_options(iter: T, options: Options) -> Self {
910        Parser::with_options(BufferedInput::new(iter), options)
911    }
912}
913
914impl<T> Parser<'static, FallibleBufferedInput<T>>
915where
916    T: Iterator<Item = Result<char, ErrorKind>>,
917{
918    /// Create a parser over a fallible iterator of characters.
919    ///
920    /// The iterator's `None` return value means clean end-of-input. An `Err` item reports a
921    /// terminal source failure and is returned by the parser as a [`ScanError`] carrying the same
922    /// [`ErrorKind`]. The iterator is not polled again after its first error.
923    #[must_use]
924    pub fn new_from_fallible_iter(iter: T) -> Self {
925        Self::new_from_fallible_iter_with_options(iter, Options::default())
926    }
927
928    /// Create a parser over a fallible iterator of characters with configurable behavior and
929    /// resource limits.
930    ///
931    /// The iterator's `None` return value means clean end-of-input. An `Err` item reports a
932    /// terminal source failure and is returned by the parser as a [`ScanError`] carrying the same
933    /// [`ErrorKind`]. The iterator is not polled again after its first error.
934    #[must_use]
935    pub fn new_from_fallible_iter_with_options(iter: T, options: Options) -> Self {
936        Parser::with_options(FallibleBufferedInput::new(iter), options)
937    }
938}
939
940impl<'input, T: BorrowedInput<'input>> Parser<'input, T> {
941    /// Return the next anchor ID that will be assigned by this parser.
942    #[must_use]
943    pub fn anchor_offset(&self) -> usize {
944        self.anchor_id_count
945    }
946
947    /// Set the next anchor ID that will be assigned by this parser.
948    pub fn set_anchor_offset(&mut self, offset: usize) {
949        self.anchor_id_count = offset;
950    }
951
952    /// Create a parser over a custom input source.
953    #[must_use]
954    pub fn new(src: T) -> Self {
955        Self::with_options(src, Options::default())
956    }
957
958    /// Create a parser over a custom input source with configurable behavior and resource limits.
959    ///
960    /// Use [`crate::options!`] to construct `options` without depending on exhaustive struct
961    /// literal syntax.
962    /// Without the `comments` feature, comment capture and emission are compiled out of both
963    /// the parser and its scanner. YAML comments are still skipped and validated.
964    #[must_use]
965    pub fn with_options(src: T, options: Options) -> Self {
966        #[cfg(feature = "comments")]
967        let max_buffered_comment_events = options.max_buffered_comment_events;
968        let block_nesting_limit = options.block_nesting_limit;
969        let scanner = Scanner::with_options(src, options);
970
971        Parser {
972            scanner,
973            #[cfg(feature = "comments")]
974            max_buffered_comment_events,
975            block_nesting_limit,
976            block_level: 0,
977            states: Vec::new(),
978            state: State::StreamStart,
979            token: None,
980            current: None,
981            current_error: None,
982            #[cfg(feature = "comments")]
983            deferred_error: None,
984            #[cfg(feature = "comments")]
985            queued_events: VecDeque::new(),
986
987            pending_key_indent: None,
988            #[cfg(feature = "comments")]
989            pending_node_anchor_id: 0,
990            #[cfg(feature = "comments")]
991            pending_node_tag: None,
992            #[cfg(feature = "comments")]
993            pending_node_tag_start: None,
994            #[cfg(feature = "comments")]
995            pending_node_property_end: None,
996            pending_empty_scalar_span: None,
997            last_non_comment_event_end: None,
998            #[cfg(feature = "comments")]
999            pending_document_version: None,
1000            #[cfg(feature = "comments")]
1001            pending_document_directives: false,
1002            #[cfg(feature = "comments")]
1003            pending_document_tag_handles: BTreeSet::new(),
1004
1005            anchors: BTreeMap::new(),
1006            // valid anchor_id starts from 1
1007            anchor_id_count: 1,
1008            tags: BTreeMap::new(),
1009            stream_end_emitted: false,
1010            keep_tags: false,
1011        }
1012    }
1013
1014    /// Configure whether tag directives remain active across document boundaries.
1015    ///
1016    /// This behavior is non-standard as per the YAML specification but can be encountered in the
1017    /// wild. Passing `true` enables this non-standard extension and allows the parser to accept
1018    /// input from [test
1019    /// QLJ7](https://github.com/yaml/yaml-test-suite/blob/ccfa74e56afb53da960847ff6e6976c0a0825709/src/QLJ7.yaml)
1020    /// of the yaml-test-suite:
1021    ///
1022    /// ```yaml
1023    /// %TAG !prefix! tag:example.com,2011:
1024    /// --- !prefix!A
1025    /// a: b
1026    /// --- !prefix!B
1027    /// c: d
1028    /// --- !prefix!C
1029    /// e: f
1030    /// ```
1031    ///
1032    /// With `keep_tags` set to `false`, the above YAML is rejected. As per the specification, tags
1033    /// only apply to the document immediately following them. This would error on `!prefix!B`.
1034    ///
1035    /// With `keep_tags` set to `true`, the above YAML is accepted by the parser.
1036    #[must_use]
1037    pub fn keep_tags(mut self, value: bool) -> Self {
1038        self.keep_tags = value;
1039        self
1040    }
1041
1042    /// Try to load the next event and return it without consuming it from `self`.
1043    ///
1044    /// Any subsequent call to [`Parser::peek`] will return the same value, until a call to
1045    /// [`Iterator::next`] or [`Parser::load`].
1046    /// If the buffered value is a [`ScanError`], [`Parser::next_event`] returns that error once
1047    /// and then the parser is exhausted.
1048    ///
1049    /// # Errors
1050    /// Returns `ScanError` when loading the next event fails.
1051    pub fn peek(&mut self) -> Option<Result<&(Event<'input>, Span), ScanError>> {
1052        ParserTrait::peek(self)
1053    }
1054
1055    /// Try to load the next event and return it, consuming it from `self`.
1056    ///
1057    /// After this returns a [`ScanError`], subsequent calls return [`None`].
1058    ///
1059    /// # Errors
1060    /// Returns `ScanError` when loading the next event fails.
1061    pub fn next_event(&mut self) -> Option<ParseResult<'input>> {
1062        ParserTrait::next_event(self)
1063    }
1064
1065    /// Implementation function for [`Self::next_event`] without the `Option`.
1066    ///
1067    /// [`Self::next_event`] should conform to the expectations of an [`Iterator`] and return an
1068    /// option. This burdens the parser code. This function is used internally when an option is
1069    /// undesirable.
1070    fn next_event_impl<'a>(&mut self) -> ParseResult<'a>
1071    where
1072        'input: 'a,
1073    {
1074        let event = match self.current.take() {
1075            None => {
1076                #[cfg(feature = "comments")]
1077                {
1078                    if let Some(event) = self.queued_events.pop_front() {
1079                        Ok(self.apply_pending_key_indent(event))
1080                    } else if let Some(error) = self.deferred_error.take() {
1081                        return Err(error);
1082                    } else if self.state == State::End {
1083                        self.parse()
1084                    } else if let Some(comment) = self.maybe_next_comment_event()? {
1085                        Ok(comment)
1086                    } else {
1087                        self.parse()
1088                    }
1089                }
1090                #[cfg(not(feature = "comments"))]
1091                {
1092                    self.parse()
1093                }
1094            }
1095            Some(v) => Ok(v),
1096        }?;
1097
1098        Ok(self.remember_non_comment_event_end(event))
1099    }
1100
1101    fn apply_pending_key_indent<'a>(&mut self, (ev, span): (Event<'a>, Span)) -> (Event<'a>, Span) {
1102        if ev.is_node() {
1103            if let Some(indent) = self.pending_key_indent.take() {
1104                return (ev, span.with_indent(Some(indent)));
1105            }
1106        }
1107
1108        (ev, span)
1109    }
1110
1111    fn remember_non_comment_event_end<'a>(
1112        &mut self,
1113        (event, span): (Event<'a>, Span),
1114    ) -> (Event<'a>, Span) {
1115        #[cfg(feature = "comments")]
1116        if matches!(event, Event::Comment(..)) {
1117            return (event, span);
1118        }
1119        self.last_non_comment_event_end = Some(span.end);
1120        (event, span)
1121    }
1122
1123    /// Peek at the next token from the scanner.
1124    fn peek_token(&mut self) -> Result<&QueuedToken<'_>, ScanError> {
1125        #[cfg(feature = "comments")]
1126        if let Some(error) = &self.deferred_error {
1127            return Err(error.clone());
1128        }
1129
1130        match self.token {
1131            None => {
1132                self.token = Some(self.scan_next_token()?);
1133                Ok(self.token.as_ref().unwrap())
1134            }
1135            Some(ref tok) => Ok(tok),
1136        }
1137    }
1138
1139    /// Extract and return the next token from the scanner.
1140    ///
1141    /// This function does _not_ make use of `self.token`.
1142    fn scan_next_token(&mut self) -> Result<QueuedToken<'input>, ScanError> {
1143        match self.scanner.next_queued_token()? {
1144            None => unreachable!("scanner ended before the parser consumed its stream-end token"),
1145            Some(tok) => Ok(tok),
1146        }
1147    }
1148
1149    #[cfg(feature = "comments")]
1150    #[inline]
1151    fn maybe_next_comment_event<'a>(&mut self) -> Result<Option<(Event<'a>, Span)>, ScanError>
1152    where
1153        'input: 'a,
1154    {
1155        if self.scanner.comments_possible() {
1156            self.next_comment_event()
1157        } else {
1158            Ok(None)
1159        }
1160    }
1161
1162    #[cfg(feature = "comments")]
1163    fn next_comment_event<'a>(&mut self) -> Result<Option<(Event<'a>, Span)>, ScanError>
1164    where
1165        'input: 'a,
1166    {
1167        let is_comment = {
1168            let token = self.peek_token()?;
1169            matches!(token.1, QueuedTokenType::Comment(_))
1170        };
1171
1172        if !is_comment {
1173            return Ok(None);
1174        }
1175
1176        let QueuedToken(span, token) = self.fetch_token();
1177        match token {
1178            QueuedTokenType::Comment(comment) => {
1179                let placement = self.refined_comment_placement(span, comment.placement());
1180                Ok(Some((Event::Comment(comment.into_text(), placement), span)))
1181            }
1182            _ => unreachable!("comment token disappeared after peek"),
1183        }
1184    }
1185
1186    #[cfg(feature = "comments")]
1187    #[inline]
1188    fn next_comment_events(&mut self) -> Result<Vec<(Event<'input>, Span)>, ScanError> {
1189        if !self.scanner.comments_possible() {
1190            return Ok(Vec::new());
1191        }
1192
1193        let mut events = Vec::new();
1194        loop {
1195            match self.peek_token() {
1196                Ok(token) if matches!(token.1, QueuedTokenType::Comment(_)) => {}
1197                Err(error) if events.is_empty() => return Err(error),
1198                Err(error) => {
1199                    debug_assert!(self.deferred_error.is_none());
1200                    self.deferred_error = Some(error);
1201                    return Ok(events);
1202                }
1203                Ok(_) => return Ok(events),
1204            }
1205
1206            if events.len() >= self.max_buffered_comment_events {
1207                return Err(ScanError::from_kind(
1208                    self.peek_token()?.0.start,
1209                    ErrorKind::TooManyComments,
1210                ));
1211            }
1212
1213            let comment = self
1214                .next_comment_event()?
1215                .expect("comment token disappeared after peek");
1216            events.push(comment);
1217            if self.deferred_error.is_some() {
1218                return Ok(events);
1219            }
1220        }
1221    }
1222
1223    #[cfg(feature = "comments")]
1224    fn queue_tail_and_return_first(
1225        &mut self,
1226        events: Vec<(Event<'input>, Span)>,
1227    ) -> (Event<'input>, Span) {
1228        let mut events = events.into_iter();
1229        let first = events
1230            .next()
1231            .expect("event queue must contain at least one event");
1232        self.queued_events.extend(events);
1233        first
1234    }
1235
1236    #[cfg(feature = "comments")]
1237    fn queue_event_by_span(
1238        &mut self,
1239        comments: Vec<(Event<'input>, Span)>,
1240        event: (Event<'input>, Span),
1241    ) -> (Event<'input>, Span) {
1242        let insert_at = comments
1243            .iter()
1244            .position(|(_, comment_span)| {
1245                comment_span.start.index() >= event.1.start.index()
1246                    && comment_span.end.index() >= event.1.end.index()
1247            })
1248            .unwrap_or(comments.len());
1249        let mut ordered = Vec::with_capacity(comments.len() + 1);
1250        let mut comments = comments.into_iter();
1251
1252        for _ in 0..insert_at {
1253            ordered.push(
1254                comments
1255                    .next()
1256                    .expect("comment disappeared while ordering queued events"),
1257            );
1258        }
1259        ordered.push(event);
1260        ordered.extend(comments);
1261
1262        self.queue_tail_and_return_first(ordered)
1263    }
1264
1265    #[cfg(feature = "comments")]
1266    fn queue_two_events_by_span(
1267        &mut self,
1268        comments: Vec<(Event<'input>, Span)>,
1269        first: (Event<'input>, Span),
1270        second: (Event<'input>, Span),
1271    ) -> (Event<'input>, Span) {
1272        let insert_at = comments
1273            .iter()
1274            .position(|(_, comment_span)| {
1275                comment_span.start.index() >= first.1.start.index()
1276                    && comment_span.end.index() >= first.1.end.index()
1277            })
1278            .unwrap_or(comments.len());
1279        let mut ordered = Vec::with_capacity(comments.len() + 2);
1280        let mut comments = comments.into_iter();
1281
1282        for _ in 0..insert_at {
1283            ordered.push(
1284                comments
1285                    .next()
1286                    .expect("comment disappeared while ordering queued events"),
1287            );
1288        }
1289        ordered.push(first);
1290        ordered.push(second);
1291        ordered.extend(comments);
1292
1293        self.queue_tail_and_return_first(ordered)
1294    }
1295
1296    #[cfg(feature = "comments")]
1297    fn refined_comment_placement(&mut self, span: Span, placement: Placement) -> Placement {
1298        if placement == Placement::Right {
1299            return Placement::Right;
1300        }
1301
1302        let next = match self.peek_token() {
1303            Ok(next) => next,
1304            Err(error) => {
1305                debug_assert!(self.deferred_error.is_none());
1306                self.deferred_error = Some(error);
1307                return placement;
1308            }
1309        };
1310        if matches!(next.1, QueuedTokenType::StreamEnd) {
1311            return Placement::Last;
1312        }
1313
1314        if next.0.start.line() == span.end.line() + 1 {
1315            Placement::Above
1316        } else {
1317            Placement::Free
1318        }
1319    }
1320
1321    /// Take the token buffered by [`Self::peek_token`].
1322    ///
1323    /// # Panics
1324    /// Panics if no token has been buffered.
1325    #[track_caller]
1326    fn fetch_token<'a>(&mut self) -> QueuedToken<'a>
1327    where
1328        'input: 'a,
1329    {
1330        self.token
1331            .take()
1332            .expect("fetch_token needs to be preceded by peek_token")
1333    }
1334
1335    /// Skip the next token from the scanner.
1336    fn skip(&mut self) {
1337        self.token = None;
1338    }
1339    /// Pops the top-most state and make it the current state.
1340    ///
1341    /// # Panics
1342    /// Panics if the state stack is empty.
1343    #[track_caller]
1344    fn pop_state(&mut self) {
1345        self.state = self.states.pop().unwrap();
1346    }
1347    /// Push a new state atop the state stack.
1348    fn push_state(&mut self, state: State) {
1349        self.states.push(state);
1350    }
1351
1352    fn start_block_collection(&mut self, mark: Marker) -> Result<(), ScanError> {
1353        if self.block_level >= self.block_nesting_limit {
1354            return Err(ScanError::from_kind(
1355                mark,
1356                ErrorKind::RecursionLimitExceeded,
1357            ));
1358        }
1359        self.block_level += 1;
1360        Ok(())
1361    }
1362
1363    fn end_block_collection(&mut self) {
1364        debug_assert!(self.block_level > 0);
1365        self.block_level -= 1;
1366    }
1367
1368    fn defer_parse_node<'a>(
1369        &mut self,
1370        node_state: State,
1371        return_state: State,
1372        block: bool,
1373        indentless_sequence: bool,
1374    ) -> ParseResult<'a>
1375    where
1376        'input: 'a,
1377    {
1378        self.push_state(return_state);
1379        self.state = node_state;
1380        #[cfg(feature = "comments")]
1381        if let Some(comment) = self.maybe_next_comment_event()? {
1382            return Ok(comment);
1383        }
1384        self.parse_node(block, indentless_sequence)
1385    }
1386
1387    fn parse<'a>(&mut self) -> ParseResult<'a>
1388    where
1389        'input: 'a,
1390    {
1391        if self.state == State::End {
1392            return Ok((Event::StreamEnd, Span::empty(self.scanner.mark())));
1393        }
1394        let event = self.state_machine()?;
1395        Ok(self.apply_pending_key_indent(event))
1396    }
1397
1398    /// Load the YAML from the stream in `self`, pushing events into `recv`.
1399    ///
1400    /// The contents of the stream are parsed and the corresponding events are sent into the
1401    /// receiver. For detailed explanations about how events work, see [`EventReceiver`].
1402    ///
1403    /// If `multi` is set to `true`, the parser will allow parsing of multiple YAML documents
1404    /// inside the stream.
1405    ///
1406    /// Use this method when event handling is infallible. If receiver code can return an
1407    /// application error and should stop parsing, use [`Parser::try_load`] instead. If the caller
1408    /// should directly control when the next event is read, use [`Parser`]'s
1409    /// [`core::iter::Iterator`] implementation.
1410    ///
1411    /// Note that any [`EventReceiver`] is also a [`SpannedEventReceiver`], so implementing the
1412    /// former is enough to call this function.
1413    ///
1414    /// # Example
1415    /// ```
1416    /// # use granit_parser::{Event, EventReceiver, Parser};
1417    /// # fn main() -> Result<(), granit_parser::ScanError> {
1418    /// struct EventSink<'input> {
1419    ///     events: Vec<Event<'input>>,
1420    /// }
1421    ///
1422    /// impl<'input> EventReceiver<'input> for EventSink<'input> {
1423    ///     fn on_event(&mut self, ev: Event<'input>) {
1424    ///         self.events.push(ev);
1425    ///     }
1426    /// }
1427    ///
1428    /// let mut parser = Parser::new_from_str("a: 1\n");
1429    /// let mut sink = EventSink { events: Vec::new() };
1430    ///
1431    /// parser.load(&mut sink, false)?;
1432    ///
1433    /// assert!(sink
1434    ///     .events
1435    ///     .iter()
1436    ///     .any(|ev| matches!(ev, Event::Scalar(value, ..) if value == "a")));
1437    /// # Ok(())
1438    /// # }
1439    /// ```
1440    ///
1441    /// # Errors
1442    /// Returns `ScanError` when loading fails.
1443    pub fn load<R: SpannedEventReceiver<'input>>(
1444        &mut self,
1445        recv: &mut R,
1446        multi: bool,
1447    ) -> Result<(), ScanError> {
1448        ParserTrait::load(self, recv, multi)
1449    }
1450
1451    /// Load the YAML from the stream in `self`, pushing events into `recv`.
1452    ///
1453    /// This is the fallible counterpart to [`Parser::load`]. If `recv` returns an error, parsing
1454    /// stops immediately and that error is returned as [`TryLoadError::Receiver`].
1455    ///
1456    /// If `multi` is set to `true`, the parser will allow parsing of multiple YAML documents
1457    /// inside the stream.
1458    ///
1459    /// If the receiver returns an error, the parser is left positioned immediately after the event
1460    /// that caused the receiver error. Callers should treat the parser as partially consumed.
1461    ///
1462    /// # Example
1463    /// ```
1464    /// # use granit_parser::{Event, Parser, TryEventReceiver, TryLoadError};
1465    /// #[derive(Debug, PartialEq, Eq)]
1466    /// enum ValidationError {
1467    ///     ForbiddenScalar,
1468    /// }
1469    ///
1470    /// struct Validator;
1471    ///
1472    /// impl<'input> TryEventReceiver<'input> for Validator {
1473    ///     type Error = ValidationError;
1474    ///
1475    ///     fn on_event(&mut self, ev: Event<'input>) -> Result<(), Self::Error> {
1476    ///         if matches!(ev, Event::Scalar(value, ..) if value.as_ref() == "bad") {
1477    ///             Err(ValidationError::ForbiddenScalar)
1478    ///         } else {
1479    ///             Ok(())
1480    ///         }
1481    ///     }
1482    /// }
1483    ///
1484    /// let mut parser = Parser::new_from_str("value: bad\n");
1485    /// let mut validator = Validator;
1486    ///
1487    /// let err = parser.try_load(&mut validator, false).unwrap_err();
1488    ///
1489    /// assert_eq!(err, TryLoadError::Receiver(ValidationError::ForbiddenScalar));
1490    /// ```
1491    ///
1492    /// # Errors
1493    /// Returns [`TryLoadError::Scan`] when scanning or parsing the stream fails. Returns
1494    /// [`TryLoadError::Receiver`] when `recv` returns an error.
1495    pub fn try_load<R: TrySpannedEventReceiver<'input>>(
1496        &mut self,
1497        recv: &mut R,
1498        multi: bool,
1499    ) -> Result<(), TryLoadError<R::Error>> {
1500        ParserTrait::try_load(self, recv, multi)
1501    }
1502
1503    fn state_machine<'a>(&mut self) -> ParseResult<'a>
1504    where
1505        'input: 'a,
1506    {
1507        debug_print!("\n\x1B[;33mParser state: {:?} \x1B[;0m", self.state);
1508
1509        match self.state {
1510            State::StreamStart => self.stream_start(),
1511
1512            State::ImplicitDocumentStart => self.document_start(true),
1513            State::DocumentStart => self.document_start(false),
1514            State::DocumentContent => self.document_content(),
1515            State::DocumentEnd => self.document_end(),
1516
1517            State::BlockNode => self.parse_node(true, false),
1518            State::BlockNodeOrIndentlessSequence => self.parse_node(true, true),
1519            State::FlowNode => self.parse_node(false, false),
1520            State::BlockMappingFirstKey => self.block_mapping_key(true),
1521            State::BlockMappingKey => self.block_mapping_key(false),
1522            #[cfg(feature = "comments")]
1523            State::BlockMappingKeyNode => self.block_mapping_key_node(),
1524            State::BlockMappingValue => self.block_mapping_value(),
1525            #[cfg(feature = "comments")]
1526            State::BlockMappingValueNode => self.block_mapping_value_node(),
1527
1528            State::BlockSequenceFirstEntry => self.block_sequence_entry(true),
1529            State::BlockSequenceEntry => self.block_sequence_entry(false),
1530            #[cfg(feature = "comments")]
1531            State::BlockSequenceEntryNode => self.block_sequence_entry_node(),
1532
1533            State::FlowSequenceFirstEntry => self.flow_sequence_entry(true),
1534            State::FlowSequenceEntry => self.flow_sequence_entry(false),
1535
1536            State::FlowMappingFirstKey => self.flow_mapping_key(true),
1537            State::FlowMappingKey => self.flow_mapping_key(false),
1538            #[cfg(feature = "comments")]
1539            State::FlowMappingKeyNode => self.flow_mapping_key_node(),
1540            State::FlowMappingValue => self.flow_mapping_value(false),
1541            #[cfg(feature = "comments")]
1542            State::FlowMappingValueNode => self.flow_mapping_value_node(),
1543
1544            State::IndentlessSequenceEntry => self.indentless_sequence_entry(),
1545            State::IndentlessSequenceEntryNode => self.indentless_sequence_entry_node(),
1546
1547            State::FlowSequenceEntryMappingKey => self.flow_sequence_entry_mapping_key(),
1548            State::FlowSequenceEntryMappingValue => self.flow_sequence_entry_mapping_value(),
1549            #[cfg(feature = "comments")]
1550            State::FlowSequenceEntryMappingValueNode => {
1551                self.flow_sequence_entry_mapping_value_node()
1552            }
1553            State::FlowSequenceEntryMappingEnd => self.flow_sequence_entry_mapping_end(),
1554            State::FlowMappingEmptyValue => self.flow_mapping_value(true),
1555
1556            State::End => unreachable!("end state is handled before state-machine dispatch"),
1557        }
1558    }
1559
1560    fn stream_start<'a>(&mut self) -> ParseResult<'a>
1561    where
1562        'input: 'a,
1563    {
1564        match *self.peek_token()? {
1565            QueuedToken(span, QueuedTokenType::StreamStart) => {
1566                self.state = State::ImplicitDocumentStart;
1567                self.skip();
1568                Ok((Event::StreamStart, span))
1569            }
1570            QueuedToken(span, _) => Err(ScanError::from_kind(
1571                span.start,
1572                ErrorKind::ExpectedStreamStart,
1573            )),
1574        }
1575    }
1576
1577    #[cfg(feature = "comments")]
1578    fn has_pending_document_directives(&self) -> bool {
1579        self.pending_document_directives
1580            || self.pending_document_version.is_some()
1581            || !self.pending_document_tag_handles.is_empty()
1582    }
1583
1584    fn document_start<'a>(&mut self, implicit: bool) -> ParseResult<'a>
1585    where
1586        'input: 'a,
1587    {
1588        // Resume a document start paused to emit comments before handling markers that are only
1589        // ignorable between documents. In particular, `...` is invalid while `---` is still
1590        // required after directives and must not be consumed by the loop below.
1591        #[cfg(feature = "comments")]
1592        if self.has_pending_document_directives() {
1593            return self.explicit_document_start();
1594        }
1595
1596        while let QueuedTokenType::DocumentEnd = self.peek_token()?.1 {
1597            self.skip();
1598        }
1599
1600        // Anchors are scoped to a single document.
1601        self.anchors.clear();
1602
1603        // Skipping a leading document-end marker can expose a comment that the normal
1604        // `next_event_impl` pre-dispatch check could not see yet. Emit it before deciding whether
1605        // another document starts; presentation-only comments must not create an implicit document.
1606        #[cfg(feature = "comments")]
1607        if let Some(comment) = self.maybe_next_comment_event()? {
1608            return Ok(comment);
1609        }
1610
1611        match *self.peek_token()? {
1612            QueuedToken(span, QueuedTokenType::StreamEnd) => {
1613                self.state = State::End;
1614                self.skip();
1615                Ok((Event::StreamEnd, span))
1616            }
1617            QueuedToken(
1618                _,
1619                QueuedTokenType::VersionDirective(..)
1620                | QueuedTokenType::TagDirective(..)
1621                | QueuedTokenType::ReservedDirective(..)
1622                | QueuedTokenType::DocumentStart,
1623            ) => {
1624                // explicit document
1625                self.explicit_document_start()
1626            }
1627            QueuedToken(span, _) if implicit => {
1628                self.parser_process_directives(None, false, BTreeSet::new())?;
1629                self.push_state(State::DocumentEnd);
1630                self.state = State::BlockNode;
1631                Ok((Event::DocumentStart(false, None), span))
1632            }
1633            _ => {
1634                // explicit document
1635                self.explicit_document_start()
1636            }
1637        }
1638    }
1639
1640    fn parser_process_directives(
1641        &mut self,
1642        mut version: Option<YamlVersion>,
1643        continuing: bool,
1644        mut document_tag_handles: BTreeSet<Cow<'input, str>>,
1645    ) -> Result<(Option<YamlVersion>, BTreeSet<Cow<'input, str>>), ScanError> {
1646        let mut tags = if continuing || self.keep_tags {
1647            core::mem::take(&mut self.tags)
1648        } else {
1649            BTreeMap::new()
1650        };
1651
1652        loop {
1653            let is_directive = matches!(
1654                self.peek_token()?.1,
1655                QueuedTokenType::VersionDirective(..)
1656                    | QueuedTokenType::TagDirective(..)
1657                    | QueuedTokenType::ReservedDirective(..)
1658            );
1659            if !is_directive {
1660                break;
1661            }
1662
1663            let QueuedToken(span, token) = self.fetch_token();
1664            match token {
1665                QueuedTokenType::VersionDirective(major, minor) => {
1666                    if version.is_some() {
1667                        return Err(ScanError::from_kind(
1668                            span.start,
1669                            ErrorKind::DuplicateVersionDirective,
1670                        ));
1671                    }
1672                    if major != 1 {
1673                        return Err(ScanError::from_kind(
1674                            span.start,
1675                            ErrorKind::UnsupportedYamlMajorVersion,
1676                        ));
1677                    }
1678                    version = Some(YamlVersion::new(major, minor));
1679                }
1680                QueuedTokenType::TagDirective(handle, prefix) => {
1681                    if !document_tag_handles.insert(handle.clone()) {
1682                        return Err(ScanError::from_kind(
1683                            span.start,
1684                            ErrorKind::DuplicateTagDirective,
1685                        ));
1686                    }
1687                    tags.insert(handle, prefix);
1688                }
1689                QueuedTokenType::ReservedDirective(_, _) => {
1690                    // Reserved directives are ignored
1691                }
1692                _ => unreachable!("non-directive token passed the directive guard"),
1693            }
1694        }
1695
1696        self.tags = tags;
1697        Ok((version, document_tag_handles))
1698    }
1699
1700    fn explicit_document_start<'a>(&mut self) -> ParseResult<'a>
1701    where
1702        'input: 'a,
1703    {
1704        #[cfg(feature = "comments")]
1705        let version = {
1706            let pending_version = self.pending_document_version.take();
1707            let continuing_directives = core::mem::take(&mut self.pending_document_directives);
1708            let pending_tag_handles = core::mem::take(&mut self.pending_document_tag_handles);
1709            let (version, document_tag_handles) = self.parser_process_directives(
1710                pending_version,
1711                continuing_directives,
1712                pending_tag_handles,
1713            )?;
1714            if let Some(comment) = self.maybe_next_comment_event()? {
1715                self.pending_document_version = version;
1716                self.pending_document_directives = true;
1717                self.pending_document_tag_handles = document_tag_handles;
1718                return Ok(comment);
1719            }
1720            version
1721        };
1722        #[cfg(not(feature = "comments"))]
1723        let (version, _) = self.parser_process_directives(None, false, BTreeSet::new())?;
1724        match *self.peek_token()? {
1725            QueuedToken(mark, QueuedTokenType::DocumentStart) => {
1726                self.push_state(State::DocumentEnd);
1727                self.state = State::DocumentContent;
1728                self.skip();
1729                Ok((Event::DocumentStart(true, version), mark))
1730            }
1731            QueuedToken(span, _) => Err(ScanError::from_kind(
1732                span.start,
1733                ErrorKind::ExpectedDocumentStart,
1734            )),
1735        }
1736    }
1737
1738    fn document_content<'a>(&mut self) -> ParseResult<'a>
1739    where
1740        'input: 'a,
1741    {
1742        if let QueuedToken(
1743            mark,
1744            QueuedTokenType::VersionDirective(..)
1745            | QueuedTokenType::TagDirective(..)
1746            | QueuedTokenType::ReservedDirective(..)
1747            | QueuedTokenType::DocumentStart
1748            | QueuedTokenType::DocumentEnd
1749            | QueuedTokenType::StreamEnd,
1750        ) = *self.peek_token()?
1751        {
1752            self.pop_state();
1753            let span = self
1754                .last_non_comment_event_end
1755                .map_or_else(|| Span::empty(mark.start), Span::empty);
1756            Ok((Event::empty_scalar(), span))
1757        } else {
1758            self.state = State::BlockNode;
1759            self.parse_node(true, false)
1760        }
1761    }
1762
1763    fn document_end<'a>(&mut self) -> ParseResult<'a>
1764    where
1765        'input: 'a,
1766    {
1767        let mut explicit_end = false;
1768        let span: Span = match *self.peek_token()? {
1769            QueuedToken(span, QueuedTokenType::DocumentEnd) => {
1770                explicit_end = true;
1771                self.skip();
1772                span
1773            }
1774            QueuedToken(span, _) => self
1775                .last_non_comment_event_end
1776                .map_or_else(|| Span::empty(span.start), Span::empty),
1777        };
1778
1779        if self.keep_tags {
1780            // Never persist default handles across document boundaries. Allowing `%TAG !! ...`
1781            // or `%TAG ! ...` to leak into following documents lets earlier documents alter how
1782            // explicit tags are interpreted later on.
1783            self.tags.remove("!!");
1784            self.tags.remove("!");
1785        } else {
1786            self.tags.clear();
1787        }
1788        if explicit_end {
1789            self.state = State::ImplicitDocumentStart;
1790        } else {
1791            if let QueuedToken(
1792                span,
1793                QueuedTokenType::VersionDirective(..)
1794                | QueuedTokenType::TagDirective(..)
1795                | QueuedTokenType::ReservedDirective(..),
1796            ) = *self.peek_token()?
1797            {
1798                return Err(ScanError::from_kind(
1799                    span.start,
1800                    ErrorKind::MissingDocumentEndBeforeDirective,
1801                ));
1802            }
1803            self.state = State::DocumentStart;
1804        }
1805
1806        Ok((Event::DocumentEnd, span))
1807    }
1808
1809    fn register_anchor(&mut self, name: Cow<'input, str>, mark: &Span) -> Result<usize, ScanError> {
1810        // YAML permits anchor names to be reused. Aliases resolve to the most recent definition.
1811        let new_id = self.anchor_id_count;
1812        self.anchor_id_count = self
1813            .anchor_id_count
1814            .checked_add(1)
1815            .ok_or_else(|| ScanError::from_kind(mark.start, ErrorKind::AnchorCountOverflow))?;
1816        self.anchors.insert(name, new_id);
1817        Ok(new_id)
1818    }
1819
1820    #[cfg(feature = "comments")]
1821    fn save_pending_node_properties(
1822        &mut self,
1823        anchor_id: usize,
1824        tag: Option<Cow<'input, Tag>>,
1825        tag_start: Option<Marker>,
1826        property_end: Option<Marker>,
1827    ) {
1828        self.pending_node_anchor_id = anchor_id;
1829        self.pending_node_tag = tag;
1830        self.pending_node_tag_start = tag_start;
1831        self.pending_node_property_end = property_end;
1832    }
1833
1834    fn attach_tag_start(event: Event<'_>, span: Span, start: Option<Marker>) -> (Event<'_>, Span) {
1835        (event, span.with_tag_start(start))
1836    }
1837
1838    #[allow(clippy::too_many_lines)]
1839    fn parse_node<'a>(&mut self, block: bool, indentless_sequence: bool) -> ParseResult<'a>
1840    where
1841        'input: 'a,
1842    {
1843        #[cfg(feature = "comments")]
1844        if let Some(comment) = self.maybe_next_comment_event()? {
1845            return Ok(comment);
1846        }
1847
1848        #[cfg(feature = "comments")]
1849        let (mut anchor_id, mut tag, mut tag_start, mut property_end) = (
1850            core::mem::take(&mut self.pending_node_anchor_id),
1851            self.pending_node_tag.take(),
1852            self.pending_node_tag_start.take(),
1853            self.pending_node_property_end.take(),
1854        );
1855        #[cfg(not(feature = "comments"))]
1856        let (mut anchor_id, mut tag, mut tag_start, mut property_end) = (0, None, None, None);
1857        match *self.peek_token()? {
1858            QueuedToken(_, QueuedTokenType::Alias(_)) if anchor_id == 0 && tag.is_none() => {
1859                self.pop_state();
1860                let QueuedToken(span, QueuedTokenType::Alias(name)) = self.fetch_token() else {
1861                    unreachable!("alias token disappeared after peek")
1862                };
1863                return match self.anchors.get(&*name) {
1864                    None => Err(ScanError::from_kind(span.start, ErrorKind::UnknownAnchor)),
1865                    Some(id) => Ok((Event::Alias(*id), span)),
1866                };
1867            }
1868            QueuedToken(_, QueuedTokenType::Anchor(_)) if anchor_id == 0 => {
1869                let QueuedToken(span, QueuedTokenType::Anchor(name)) = self.fetch_token() else {
1870                    unreachable!("anchor token disappeared after peek")
1871                };
1872                anchor_id = self.register_anchor(name, &span)?;
1873                property_end = Some(span.end);
1874                if tag.is_none() && matches!(self.peek_token()?.1, QueuedTokenType::Tag(..)) {
1875                    let QueuedToken(tag_span, QueuedTokenType::Tag(handle, suffix)) =
1876                        self.fetch_token()
1877                    else {
1878                        unreachable!("tag token disappeared after peek")
1879                    };
1880                    tag_start = Some(tag_span.start);
1881                    tag = Some(self.resolve_tag(tag_span, &handle, suffix)?);
1882                    property_end = Some(tag_span.end);
1883                }
1884                #[cfg(feature = "comments")]
1885                if let Some(comment) = self.maybe_next_comment_event()? {
1886                    self.save_pending_node_properties(anchor_id, tag, tag_start, property_end);
1887                    return Ok(comment);
1888                }
1889            }
1890            QueuedToken(mark, QueuedTokenType::Tag(..)) if tag.is_none() => {
1891                let QueuedTokenType::Tag(handle, suffix) = self.fetch_token().1 else {
1892                    unreachable!("tag token disappeared after peek")
1893                };
1894                tag_start = Some(mark.start);
1895                property_end = Some(mark.end);
1896                tag = Some(self.resolve_tag(mark, &handle, suffix)?);
1897                if anchor_id == 0 {
1898                    if let QueuedTokenType::Anchor(_) = &self.peek_token()?.1 {
1899                        let QueuedToken(mark, QueuedTokenType::Anchor(name)) = self.fetch_token()
1900                        else {
1901                            unreachable!("anchor token disappeared after peek")
1902                        };
1903                        anchor_id = self.register_anchor(name, &mark)?;
1904                        property_end = Some(mark.end);
1905                    }
1906                }
1907                #[cfg(feature = "comments")]
1908                if let Some(comment) = self.maybe_next_comment_event()? {
1909                    self.save_pending_node_properties(anchor_id, tag, tag_start, property_end);
1910                    return Ok(comment);
1911                }
1912            }
1913            _ => {}
1914        }
1915        match *self.peek_token()? {
1916            QueuedToken(mark, QueuedTokenType::BlockEntry) if indentless_sequence => {
1917                self.start_block_collection(mark.start)?;
1918                self.skip();
1919                let start = (
1920                    Event::SequenceStart(StructureStyle::Block, anchor_id, tag),
1921                    mark.with_tag_start(tag_start),
1922                );
1923                #[cfg(feature = "comments")]
1924                {
1925                    let comments = match self.next_comment_events() {
1926                        Ok(comments) => comments,
1927                        Err(error) if !matches!(error.kind(), ErrorKind::TooManyComments) => {
1928                            // `StrInput` can prove that a source has no comments and skips this
1929                            // lookahead, while streaming inputs must probe for one. If that probe
1930                            // discovers a later scanner error, the input backend must not determine
1931                            // whether this already-recognized sequence start is emitted first.
1932                            debug_assert!(self.deferred_error.is_none());
1933                            self.deferred_error = Some(error);
1934                            self.pending_empty_scalar_span = Some(mark);
1935                            self.state = State::IndentlessSequenceEntryNode;
1936                            return Ok(start);
1937                        }
1938                        Err(error) => return Err(error),
1939                    };
1940                    if comments.is_empty() {
1941                        self.pending_empty_scalar_span = Some(mark);
1942                        self.state = State::IndentlessSequenceEntryNode;
1943                        Ok(start)
1944                    } else if let Ok(QueuedToken(
1945                        _,
1946                        QueuedTokenType::BlockEntry
1947                        | QueuedTokenType::Key
1948                        | QueuedTokenType::Value
1949                        | QueuedTokenType::BlockEnd,
1950                    )) = self.peek_token()
1951                    {
1952                        self.state = State::IndentlessSequenceEntry;
1953                        Ok(self.queue_two_events_by_span(
1954                            comments,
1955                            start,
1956                            (Event::empty_scalar(), mark),
1957                        ))
1958                    } else {
1959                        self.pending_empty_scalar_span = Some(mark);
1960                        self.state = State::IndentlessSequenceEntryNode;
1961                        Ok(self.queue_event_by_span(comments, start))
1962                    }
1963                }
1964                #[cfg(not(feature = "comments"))]
1965                {
1966                    self.pending_empty_scalar_span = Some(mark);
1967                    self.state = State::IndentlessSequenceEntryNode;
1968                    Ok(start)
1969                }
1970            }
1971            QueuedToken(_, QueuedTokenType::Scalar(..)) => {
1972                self.pop_state();
1973                let QueuedToken(mark, QueuedTokenType::Scalar(style, v)) = self.fetch_token()
1974                else {
1975                    unreachable!("scalar token disappeared after peek")
1976                };
1977                Ok(Self::attach_tag_start(
1978                    Event::Scalar(v, style, anchor_id, tag),
1979                    mark,
1980                    tag_start,
1981                ))
1982            }
1983            QueuedToken(mark, QueuedTokenType::FlowSequenceStart) => {
1984                self.state = State::FlowSequenceFirstEntry;
1985                self.skip();
1986                Ok(Self::attach_tag_start(
1987                    Event::SequenceStart(StructureStyle::Flow, anchor_id, tag),
1988                    mark,
1989                    tag_start,
1990                ))
1991            }
1992            QueuedToken(mark, QueuedTokenType::FlowMappingStart) => {
1993                self.state = State::FlowMappingFirstKey;
1994                self.skip();
1995                Ok(Self::attach_tag_start(
1996                    Event::MappingStart(StructureStyle::Flow, anchor_id, tag),
1997                    mark,
1998                    tag_start,
1999                ))
2000            }
2001            QueuedToken(mark, QueuedTokenType::BlockSequenceStart) if block => {
2002                self.start_block_collection(mark.start)?;
2003                self.state = State::BlockSequenceFirstEntry;
2004                self.skip();
2005                Ok(Self::attach_tag_start(
2006                    Event::SequenceStart(StructureStyle::Block, anchor_id, tag),
2007                    mark,
2008                    tag_start,
2009                ))
2010            }
2011            QueuedToken(mark, QueuedTokenType::BlockMappingStart) if block => {
2012                self.start_block_collection(mark.start)?;
2013                self.state = State::BlockMappingFirstKey;
2014                self.skip();
2015                Ok(Self::attach_tag_start(
2016                    Event::MappingStart(StructureStyle::Block, anchor_id, tag),
2017                    mark,
2018                    tag_start,
2019                ))
2020            }
2021            // ex 7.2, an empty scalar can follow a secondary tag
2022            QueuedToken(mark, _) if tag.is_some() || anchor_id > 0 => {
2023                self.pop_state();
2024                let span = property_end.map_or_else(|| Span::empty(mark.start), Span::empty);
2025                Ok(Self::attach_tag_start(
2026                    Event::empty_scalar_with_anchor(anchor_id, tag),
2027                    span,
2028                    tag_start,
2029                ))
2030            }
2031            QueuedToken(span, _) => {
2032                let kind = match self.state {
2033                    State::FlowSequenceFirstEntry | State::FlowSequenceEntry => {
2034                        ErrorKind::UnexpectedEofFlowSequence
2035                    }
2036                    State::FlowMappingFirstKey
2037                    | State::FlowMappingKey
2038                    | State::FlowMappingValue
2039                    | State::FlowMappingEmptyValue => ErrorKind::UnexpectedEofFlowMapping,
2040                    State::FlowSequenceEntryMappingKey
2041                    | State::FlowSequenceEntryMappingValue
2042                    | State::FlowSequenceEntryMappingEnd
2043                    | State::FlowNode => ErrorKind::UnexpectedEofImplicitFlowMapping,
2044                    State::BlockSequenceFirstEntry
2045                    | State::BlockSequenceEntry
2046                    | State::BlockNode => ErrorKind::UnexpectedEofBlockSequence,
2047                    State::BlockMappingFirstKey
2048                    | State::BlockMappingKey
2049                    | State::BlockMappingValue
2050                    | State::BlockNodeOrIndentlessSequence => ErrorKind::UnexpectedEofBlockMapping,
2051                    _ => ErrorKind::ExpectedNodeContent,
2052                };
2053                Err(ScanError::from_kind(span.start, kind))
2054            }
2055        }
2056    }
2057
2058    fn block_mapping_key<'a>(&mut self, _first: bool) -> ParseResult<'a>
2059    where
2060        'input: 'a,
2061    {
2062        match *self.peek_token()? {
2063            QueuedToken(_, QueuedTokenType::Key) => {
2064                // Indentation is only meaningful for block mapping keys.
2065                if let QueuedToken(key_span, QueuedTokenType::Key) = *self.peek_token()? {
2066                    self.pending_key_indent = Some(key_span.start.col());
2067                }
2068                self.skip();
2069                #[cfg(feature = "comments")]
2070                if let Some(comment) = self.maybe_next_comment_event()? {
2071                    self.state = State::BlockMappingKeyNode;
2072                    return Ok(comment);
2073                }
2074                self.block_mapping_key_node()
2075            }
2076            // A missing block-mapping key before `:` is represented as an empty scalar.
2077            QueuedToken(mark, QueuedTokenType::Value) => {
2078                self.state = State::BlockMappingValue;
2079                Ok((Event::empty_scalar(), Span::empty(mark.start)))
2080            }
2081            QueuedToken(mark, QueuedTokenType::BlockEnd) => {
2082                self.end_block_collection();
2083                self.pop_state();
2084                self.skip();
2085                Ok((Event::MappingEnd, mark))
2086            }
2087            QueuedToken(span, _) => Err(ScanError::from_kind(
2088                span.start,
2089                ErrorKind::ExpectedBlockMappingKey,
2090            )),
2091        }
2092    }
2093
2094    fn block_mapping_key_node<'a>(&mut self) -> ParseResult<'a>
2095    where
2096        'input: 'a,
2097    {
2098        if let QueuedToken(
2099            mark,
2100            QueuedTokenType::Key | QueuedTokenType::Value | QueuedTokenType::BlockEnd,
2101        ) = *self.peek_token()?
2102        {
2103            self.state = State::BlockMappingValue;
2104            Ok((Event::empty_scalar(), Span::empty(mark.start)))
2105        } else {
2106            self.defer_parse_node(
2107                State::BlockNodeOrIndentlessSequence,
2108                State::BlockMappingValue,
2109                true,
2110                true,
2111            )
2112        }
2113    }
2114
2115    fn block_mapping_value<'a>(&mut self) -> ParseResult<'a>
2116    where
2117        'input: 'a,
2118    {
2119        match *self.peek_token()? {
2120            QueuedToken(mark, QueuedTokenType::Value) => {
2121                self.skip();
2122                #[cfg(feature = "comments")]
2123                {
2124                    let comments = self.next_comment_events()?;
2125                    if !comments.is_empty() {
2126                        if let Ok(QueuedToken(
2127                            _,
2128                            QueuedTokenType::Key
2129                            | QueuedTokenType::Value
2130                            | QueuedTokenType::BlockEnd,
2131                        )) = self.peek_token()
2132                        {
2133                            self.state = State::BlockMappingKey;
2134                            return Ok(
2135                                self.queue_event_by_span(comments, (Event::empty_scalar(), mark))
2136                            );
2137                        }
2138                        self.pending_empty_scalar_span = Some(mark);
2139                        self.state = State::BlockMappingValueNode;
2140                        return Ok(self.queue_tail_and_return_first(comments));
2141                    }
2142                }
2143                self.block_mapping_value_node_with_empty_span(mark)
2144            }
2145            QueuedToken(mark, _) => {
2146                self.state = State::BlockMappingKey;
2147                Ok((Event::empty_scalar(), Span::empty(mark.start)))
2148            }
2149        }
2150    }
2151
2152    #[cfg(feature = "comments")]
2153    fn block_mapping_value_node<'a>(&mut self) -> ParseResult<'a>
2154    where
2155        'input: 'a,
2156    {
2157        let Some(mark) = self.pending_empty_scalar_span.take() else {
2158            unreachable!(
2159                "block mapping value-node state entered without a pending empty-scalar span"
2160            )
2161        };
2162        self.block_mapping_value_node_with_empty_span(mark)
2163    }
2164
2165    fn block_mapping_value_node_with_empty_span<'a>(&mut self, mark: Span) -> ParseResult<'a>
2166    where
2167        'input: 'a,
2168    {
2169        if let QueuedToken(
2170            _,
2171            QueuedTokenType::Key | QueuedTokenType::Value | QueuedTokenType::BlockEnd,
2172        ) = *self.peek_token()?
2173        {
2174            self.state = State::BlockMappingKey;
2175            Ok((Event::empty_scalar(), mark))
2176        } else {
2177            self.defer_parse_node(
2178                State::BlockNodeOrIndentlessSequence,
2179                State::BlockMappingKey,
2180                true,
2181                true,
2182            )
2183        }
2184    }
2185
2186    fn flow_mapping_key<'a>(&mut self, first: bool) -> ParseResult<'a>
2187    where
2188        'input: 'a,
2189    {
2190        let span: Span =
2191            if let QueuedToken(mark, QueuedTokenType::FlowMappingEnd) = *self.peek_token()? {
2192                mark
2193            } else {
2194                if !first {
2195                    match *self.peek_token()? {
2196                        QueuedToken(_, QueuedTokenType::FlowEntry) => {
2197                            self.skip();
2198                            #[cfg(feature = "comments")]
2199                            if let Some(comment) = self.maybe_next_comment_event()? {
2200                                self.state = State::FlowMappingFirstKey;
2201                                return Ok(comment);
2202                            }
2203                        }
2204                        QueuedToken(span, _) => {
2205                            return Err(ScanError::from_kind(
2206                                span.start,
2207                                ErrorKind::ExpectedFlowMappingSeparator,
2208                            ))
2209                        }
2210                    }
2211                }
2212
2213                match *self.peek_token()? {
2214                    QueuedToken(_, QueuedTokenType::Key) => {
2215                        self.skip();
2216                        #[cfg(feature = "comments")]
2217                        if let Some(comment) = self.maybe_next_comment_event()? {
2218                            self.state = State::FlowMappingKeyNode;
2219                            return Ok(comment);
2220                        }
2221                        return self.flow_mapping_key_node();
2222                    }
2223                    QueuedToken(marker, QueuedTokenType::Value) => {
2224                        self.state = State::FlowMappingValue;
2225                        return Ok((Event::empty_scalar(), Span::empty(marker.start)));
2226                    }
2227                    QueuedToken(_, QueuedTokenType::FlowMappingEnd) => (),
2228                    _ => {
2229                        return self.defer_parse_node(
2230                            State::FlowNode,
2231                            State::FlowMappingEmptyValue,
2232                            false,
2233                            false,
2234                        );
2235                    }
2236                }
2237
2238                self.peek_token()?.0
2239            };
2240
2241        self.pop_state();
2242        self.skip();
2243        Ok((Event::MappingEnd, span))
2244    }
2245
2246    fn flow_mapping_key_node<'a>(&mut self) -> ParseResult<'a>
2247    where
2248        'input: 'a,
2249    {
2250        if let QueuedToken(
2251            mark,
2252            QueuedTokenType::Value | QueuedTokenType::FlowEntry | QueuedTokenType::FlowMappingEnd,
2253        ) = *self.peek_token()?
2254        {
2255            self.state = State::FlowMappingValue;
2256            Ok((Event::empty_scalar(), Span::empty(mark.start)))
2257        } else {
2258            self.defer_parse_node(State::FlowNode, State::FlowMappingValue, false, false)
2259        }
2260    }
2261
2262    fn flow_mapping_value<'a>(&mut self, empty: bool) -> ParseResult<'a>
2263    where
2264        'input: 'a,
2265    {
2266        let span: Span = {
2267            if empty {
2268                let QueuedToken(mark, _) = *self.peek_token()?;
2269                self.state = State::FlowMappingKey;
2270                return Ok((Event::empty_scalar(), Span::empty(mark.start)));
2271            }
2272            match *self.peek_token()? {
2273                QueuedToken(span, QueuedTokenType::Value) => {
2274                    self.skip();
2275                    #[cfg(feature = "comments")]
2276                    {
2277                        let comments = self.next_comment_events()?;
2278                        if comments.is_empty() {
2279                            return self.flow_mapping_value_node_with_empty_span(span);
2280                        }
2281                        if let Ok(QueuedToken(
2282                            _,
2283                            QueuedTokenType::FlowEntry | QueuedTokenType::FlowMappingEnd,
2284                        )) = self.peek_token()
2285                        {
2286                            self.state = State::FlowMappingKey;
2287                            return Ok(
2288                                self.queue_event_by_span(comments, (Event::empty_scalar(), span))
2289                            );
2290                        }
2291
2292                        self.pending_empty_scalar_span = Some(span);
2293                        self.state = State::FlowMappingValueNode;
2294                        return Ok(self.queue_tail_and_return_first(comments));
2295                    }
2296                    #[cfg(not(feature = "comments"))]
2297                    return self.flow_mapping_value_node_with_empty_span(span);
2298                }
2299                QueuedToken(marker, _) => Span::empty(marker.start),
2300            }
2301        };
2302
2303        self.state = State::FlowMappingKey;
2304        Ok((Event::empty_scalar(), span))
2305    }
2306
2307    #[cfg(feature = "comments")]
2308    fn flow_mapping_value_node<'a>(&mut self) -> ParseResult<'a>
2309    where
2310        'input: 'a,
2311    {
2312        let Some(mark) = self.pending_empty_scalar_span.take() else {
2313            unreachable!(
2314                "flow mapping value-node state entered without a pending empty-scalar span"
2315            )
2316        };
2317        self.flow_mapping_value_node_with_empty_span(mark)
2318    }
2319
2320    fn flow_mapping_value_node_with_empty_span<'a>(&mut self, mark: Span) -> ParseResult<'a>
2321    where
2322        'input: 'a,
2323    {
2324        match self.peek_token()?.1 {
2325            QueuedTokenType::FlowEntry | QueuedTokenType::FlowMappingEnd => {
2326                self.state = State::FlowMappingKey;
2327                Ok((Event::empty_scalar(), mark))
2328            }
2329            _ => self.defer_parse_node(State::FlowNode, State::FlowMappingKey, false, false),
2330        }
2331    }
2332
2333    fn flow_sequence_entry<'a>(&mut self, first: bool) -> ParseResult<'a>
2334    where
2335        'input: 'a,
2336    {
2337        match *self.peek_token()? {
2338            QueuedToken(mark, QueuedTokenType::FlowSequenceEnd) => {
2339                self.pop_state();
2340                self.skip();
2341                return Ok((Event::SequenceEnd, mark));
2342            }
2343            QueuedToken(_, QueuedTokenType::FlowEntry) if !first => {
2344                self.skip();
2345                #[cfg(feature = "comments")]
2346                if let Some(comment) = self.maybe_next_comment_event()? {
2347                    self.state = State::FlowSequenceFirstEntry;
2348                    return Ok(comment);
2349                }
2350            }
2351            QueuedToken(span, _) if !first => {
2352                return Err(ScanError::from_kind(
2353                    span.start,
2354                    ErrorKind::ExpectedFlowSequenceSeparator,
2355                ));
2356            }
2357            _ => { /* next */ }
2358        }
2359        match *self.peek_token()? {
2360            QueuedToken(mark, QueuedTokenType::FlowSequenceEnd) => {
2361                self.pop_state();
2362                self.skip();
2363                Ok((Event::SequenceEnd, mark))
2364            }
2365            QueuedToken(mark, QueuedTokenType::Key) => {
2366                self.state = State::FlowSequenceEntryMappingKey;
2367                self.skip();
2368                Ok((Event::MappingStart(StructureStyle::Flow, 0, None), mark))
2369            }
2370            _ => self.defer_parse_node(State::FlowNode, State::FlowSequenceEntry, false, false),
2371        }
2372    }
2373
2374    fn indentless_sequence_entry<'a>(&mut self) -> ParseResult<'a>
2375    where
2376        'input: 'a,
2377    {
2378        match *self.peek_token()? {
2379            QueuedToken(mark, QueuedTokenType::BlockEntry) => {
2380                self.skip();
2381                #[cfg(feature = "comments")]
2382                {
2383                    let comments = self.next_comment_events()?;
2384                    if !comments.is_empty() {
2385                        if let Ok(QueuedToken(
2386                            _,
2387                            QueuedTokenType::BlockEntry
2388                            | QueuedTokenType::Key
2389                            | QueuedTokenType::Value
2390                            | QueuedTokenType::BlockEnd,
2391                        )) = self.peek_token()
2392                        {
2393                            self.state = State::IndentlessSequenceEntry;
2394                            return Ok(
2395                                self.queue_event_by_span(comments, (Event::empty_scalar(), mark))
2396                            );
2397                        }
2398                        self.pending_empty_scalar_span = Some(mark);
2399                        self.state = State::IndentlessSequenceEntryNode;
2400                        return Ok(self.queue_tail_and_return_first(comments));
2401                    }
2402                }
2403                self.indentless_sequence_entry_node_with_empty_span(mark)
2404            }
2405            QueuedToken(mark, _) => {
2406                self.end_block_collection();
2407                self.pop_state();
2408                // The token that ends an indentless sequence belongs to the enclosing mapping
2409                // (`? key`, `key:`, block end); the end event is empty, at that token's start.
2410                Ok((Event::SequenceEnd, Span::empty(mark.start)))
2411            }
2412        }
2413    }
2414
2415    fn indentless_sequence_entry_node<'a>(&mut self) -> ParseResult<'a>
2416    where
2417        'input: 'a,
2418    {
2419        let Some(mark) = self.pending_empty_scalar_span.take() else {
2420            unreachable!(
2421                "indentless sequence entry-node state entered without a pending empty-scalar span"
2422            )
2423        };
2424        self.indentless_sequence_entry_node_with_empty_span(mark)
2425    }
2426
2427    fn indentless_sequence_entry_node_with_empty_span<'a>(&mut self, mark: Span) -> ParseResult<'a>
2428    where
2429        'input: 'a,
2430    {
2431        if let QueuedToken(
2432            _,
2433            QueuedTokenType::BlockEntry
2434            | QueuedTokenType::Key
2435            | QueuedTokenType::Value
2436            | QueuedTokenType::BlockEnd,
2437        ) = *self.peek_token()?
2438        {
2439            self.state = State::IndentlessSequenceEntry;
2440            Ok((Event::empty_scalar(), mark))
2441        } else {
2442            self.defer_parse_node(
2443                State::BlockNode,
2444                State::IndentlessSequenceEntry,
2445                true,
2446                false,
2447            )
2448        }
2449    }
2450
2451    fn block_sequence_entry<'a>(&mut self, _first: bool) -> ParseResult<'a>
2452    where
2453        'input: 'a,
2454    {
2455        match *self.peek_token()? {
2456            QueuedToken(mark, QueuedTokenType::BlockEnd) => {
2457                self.end_block_collection();
2458                self.pop_state();
2459                self.skip();
2460                Ok((Event::SequenceEnd, mark))
2461            }
2462            QueuedToken(mark, QueuedTokenType::BlockEntry) => {
2463                self.skip();
2464                #[cfg(feature = "comments")]
2465                {
2466                    let comments = self.next_comment_events()?;
2467                    if !comments.is_empty() {
2468                        if let Ok(QueuedToken(
2469                            _,
2470                            QueuedTokenType::BlockEntry | QueuedTokenType::BlockEnd,
2471                        )) = self.peek_token()
2472                        {
2473                            self.state = State::BlockSequenceEntry;
2474                            return Ok(
2475                                self.queue_event_by_span(comments, (Event::empty_scalar(), mark))
2476                            );
2477                        }
2478                        self.pending_empty_scalar_span = Some(mark);
2479                        self.state = State::BlockSequenceEntryNode;
2480                        return Ok(self.queue_tail_and_return_first(comments));
2481                    }
2482                }
2483                self.block_sequence_entry_node_with_empty_span(mark)
2484            }
2485            QueuedToken(span, _) => Err(ScanError::from_kind(
2486                span.start,
2487                ErrorKind::ExpectedBlockSequenceEntry,
2488            )),
2489        }
2490    }
2491
2492    #[cfg(feature = "comments")]
2493    fn block_sequence_entry_node<'a>(&mut self) -> ParseResult<'a>
2494    where
2495        'input: 'a,
2496    {
2497        let Some(mark) = self.pending_empty_scalar_span.take() else {
2498            unreachable!(
2499                "block sequence entry-node state entered without a pending empty-scalar span"
2500            )
2501        };
2502        self.block_sequence_entry_node_with_empty_span(mark)
2503    }
2504
2505    fn block_sequence_entry_node_with_empty_span<'a>(&mut self, mark: Span) -> ParseResult<'a>
2506    where
2507        'input: 'a,
2508    {
2509        if let QueuedToken(_, QueuedTokenType::BlockEntry | QueuedTokenType::BlockEnd) =
2510            *self.peek_token()?
2511        {
2512            self.state = State::BlockSequenceEntry;
2513            Ok((Event::empty_scalar(), mark))
2514        } else {
2515            self.defer_parse_node(State::BlockNode, State::BlockSequenceEntry, true, false)
2516        }
2517    }
2518
2519    fn flow_sequence_entry_mapping_key<'a>(&mut self) -> ParseResult<'a>
2520    where
2521        'input: 'a,
2522    {
2523        if let QueuedToken(mark, QueuedTokenType::FlowEntry | QueuedTokenType::FlowSequenceEnd) =
2524            *self.peek_token()?
2525        {
2526            self.state = State::FlowSequenceEntryMappingValue;
2527            Ok((Event::empty_scalar(), Span::empty(mark.start)))
2528        } else {
2529            self.defer_parse_node(
2530                State::FlowNode,
2531                State::FlowSequenceEntryMappingValue,
2532                false,
2533                false,
2534            )
2535        }
2536    }
2537
2538    fn flow_sequence_entry_mapping_value<'a>(&mut self) -> ParseResult<'a>
2539    where
2540        'input: 'a,
2541    {
2542        match *self.peek_token()? {
2543            QueuedToken(_, QueuedTokenType::Value) => {
2544                self.skip();
2545                #[cfg(feature = "comments")]
2546                if let Some(comment) = self.maybe_next_comment_event()? {
2547                    self.state = State::FlowSequenceEntryMappingValueNode;
2548                    return Ok(comment);
2549                }
2550                self.flow_sequence_entry_mapping_value_node()
2551            }
2552            QueuedToken(mark, _) => {
2553                self.state = State::FlowSequenceEntryMappingEnd;
2554                Ok((Event::empty_scalar(), Span::empty(mark.start)))
2555            }
2556        }
2557    }
2558
2559    fn flow_sequence_entry_mapping_value_node<'a>(&mut self) -> ParseResult<'a>
2560    where
2561        'input: 'a,
2562    {
2563        let QueuedToken(span, ref tok) = *self.peek_token()?;
2564        if matches!(
2565            tok,
2566            QueuedTokenType::FlowEntry | QueuedTokenType::FlowSequenceEnd
2567        ) {
2568            self.state = State::FlowSequenceEntryMappingEnd;
2569            Ok((Event::empty_scalar(), Span::empty(span.start)))
2570        } else {
2571            self.defer_parse_node(
2572                State::FlowNode,
2573                State::FlowSequenceEntryMappingEnd,
2574                false,
2575                false,
2576            )
2577        }
2578    }
2579
2580    #[allow(clippy::unnecessary_wraps)]
2581    fn flow_sequence_entry_mapping_end<'a>(&mut self) -> ParseResult<'a>
2582    where
2583        'input: 'a,
2584    {
2585        self.state = State::FlowSequenceEntry;
2586        let QueuedToken(span, _) = *self.peek_token()?;
2587        Ok((Event::MappingEnd, Span::empty(span.start)))
2588    }
2589
2590    /// Resolve a tag from the handle and the suffix.
2591    fn resolve_tag(
2592        &self,
2593        span: Span,
2594        handle: &Cow<'input, str>,
2595        suffix: Cow<'input, str>,
2596    ) -> Result<Cow<'input, Tag>, ScanError> {
2597        let original_handle = handle.to_string();
2598        let suffix = suffix.into_owned();
2599        let tag = if handle == "!!" {
2600            // "!!" is a shorthand for "tag:yaml.org,2002:". However, that default can be
2601            // overridden.
2602            Tag::with_original_handle(
2603                self.tags
2604                    .get("!!")
2605                    .map_or_else(|| "tag:yaml.org,2002:".to_string(), ToString::to_string),
2606                suffix,
2607                original_handle,
2608            )
2609        } else if handle.is_empty() && suffix == "!" {
2610            // Bare "!" is a non-specific tag, not a primary handle to expand with %TAG.
2611            Tag::with_original_handle(String::new(), suffix, original_handle)
2612        } else {
2613            // Lookup handle in our tag directives.
2614            let prefix = self.tags.get(&**handle);
2615            if let Some(prefix) = prefix {
2616                Tag::with_original_handle(prefix.to_string(), suffix, original_handle)
2617            } else {
2618                // Otherwise, it may be a local handle. With a local handle, the handle is set to
2619                // "!" and the suffix to whatever follows it ("!foo" -> ("!", "foo")).
2620                // If the handle is of the form "!foo!", this cannot be a local handle and we need
2621                // to error.
2622                if handle.len() >= 2 && handle.starts_with('!') && handle.ends_with('!') {
2623                    return Err(ScanError::from_kind(
2624                        span.start,
2625                        ErrorKind::UndeclaredTagHandle,
2626                    ));
2627                }
2628                Tag::with_original_handle(handle.to_string(), suffix, original_handle)
2629            }
2630        };
2631        Ok(Cow::Owned(tag))
2632    }
2633}
2634
2635impl<'input, T: BorrowedInput<'input>> ParserTrait<'input> for Parser<'input, T> {
2636    fn peek(&mut self) -> Option<Result<&(Event<'input>, Span), ScanError>> {
2637        if let Some(ref x) = self.current {
2638            Some(Ok(x))
2639        } else if let Some(error) = &self.current_error {
2640            Some(Err(error.clone()))
2641        } else {
2642            if self.stream_end_emitted {
2643                return None;
2644            }
2645            match self.next_event_impl() {
2646                Ok(token) => self.current = Some(token),
2647                Err(error) => {
2648                    self.current_error = Some(error.clone());
2649                    return Some(Err(error));
2650                }
2651            }
2652            self.current.as_ref().map(Ok)
2653        }
2654    }
2655
2656    fn next_event(&mut self) -> Option<ParseResult<'input>> {
2657        if let Some(error) = self.current_error.take() {
2658            self.stream_end_emitted = true;
2659            return Some(Err(error));
2660        }
2661
2662        if self.stream_end_emitted {
2663            return None;
2664        }
2665
2666        let tok = self.next_event_impl();
2667        if matches!(tok, Ok((Event::StreamEnd, _)) | Err(_)) {
2668            self.stream_end_emitted = true;
2669        }
2670        Some(tok)
2671    }
2672
2673    fn load<R: SpannedEventReceiver<'input>>(
2674        &mut self,
2675        recv: &mut R,
2676        multi: bool,
2677    ) -> Result<(), ScanError> {
2678        let mut recv = InfallibleSpannedReceiver(recv);
2679        into_scan_result(ParserTrait::try_load(self, &mut recv, multi))
2680    }
2681
2682    fn try_load<R: TrySpannedEventReceiver<'input>>(
2683        &mut self,
2684        recv: &mut R,
2685        multi: bool,
2686    ) -> Result<(), TryLoadError<R::Error>> {
2687        let stream_start_buffered = matches!(self.current.as_ref(), Some((Event::StreamStart, _)));
2688        if !self.scanner.stream_started() || stream_start_buffered {
2689            let (ev, span) = self.next_event_impl()?;
2690            if ev != Event::StreamStart {
2691                return Err(TryLoadError::scan(ScanError::from_kind(
2692                    span.start,
2693                    ErrorKind::ExpectedStreamStart,
2694                )));
2695            }
2696            try_emit(recv, ev, span)?;
2697        }
2698
2699        let has_buffered_result = self.current.is_some() || self.current_error.is_some();
2700        #[cfg(feature = "comments")]
2701        let has_buffered_result =
2702            has_buffered_result || self.deferred_error.is_some() || !self.queued_events.is_empty();
2703        if self.scanner.stream_ended() && !has_buffered_result {
2704            // The scanner has already reached EOF before the document loop, so emit the terminal
2705            // event and stop.
2706            try_emit(recv, Event::StreamEnd, Span::empty(self.scanner.mark()))?;
2707            self.stream_end_emitted = true;
2708            return Ok(());
2709        }
2710
2711        loop {
2712            let (ev, span) = if let Some(error) = self.current_error.take() {
2713                self.stream_end_emitted = true;
2714                return Err(TryLoadError::scan(error));
2715            } else {
2716                self.next_event_impl()?
2717            };
2718            let is_doc_end = matches!(ev, Event::DocumentEnd);
2719            let is_stream_end = matches!(ev, Event::StreamEnd);
2720
2721            try_emit(recv, ev, span)?;
2722
2723            if is_stream_end {
2724                self.stream_end_emitted = true;
2725                return Ok(());
2726            }
2727            if !multi && is_doc_end {
2728                return Ok(());
2729            }
2730        }
2731    }
2732}
2733
2734impl<'input, T: BorrowedInput<'input>> Iterator for Parser<'input, T> {
2735    type Item = Result<(Event<'input>, Span), ScanError>;
2736
2737    fn next(&mut self) -> Option<Self::Item> {
2738        self.next_event()
2739    }
2740}
2741
2742impl<'input, T: BorrowedInput<'input>> core::iter::FusedIterator for Parser<'input, T> {}
2743
2744#[cfg(test)]
2745mod test {
2746    #[cfg(feature = "error_messages")]
2747    use alloc::string::String;
2748    use alloc::{borrow::Cow, format, string::ToString, vec, vec::Vec};
2749    #[cfg(feature = "error_messages")]
2750    use core::{error::Error as _, fmt};
2751
2752    #[cfg(feature = "error_messages")]
2753    use crate::error::{ErrorKind, ScanError};
2754    use crate::scanner::{Marker, ScalarStyle, Span};
2755
2756    use super::{
2757        Event, EventReceiver, Parser, State, StructureStyle, Tag, TryEventReceiver, TryLoadError,
2758        TrySpannedEventReceiver, YamlVersion,
2759    };
2760
2761    #[derive(Default)]
2762    struct CollectingSink<'input> {
2763        events: Vec<Event<'input>>,
2764    }
2765
2766    impl<'input> EventReceiver<'input> for CollectingSink<'input> {
2767        fn on_event(&mut self, ev: Event<'input>) {
2768            self.events.push(ev);
2769        }
2770    }
2771
2772    #[cfg(feature = "error_messages")]
2773    fn first_error_info(input: &str) -> String {
2774        for event in Parser::new_from_str(input) {
2775            if let Err(err) = event {
2776                return err.info();
2777            }
2778        }
2779        panic!("expected parser error")
2780    }
2781
2782    fn first_tagged_scalar_tag(input: &str) -> Tag {
2783        Parser::new_from_str(input)
2784            .find_map(|event| match event.expect("input should parse").0 {
2785                Event::Scalar(_, _, _, Some(tag)) => Some(tag.into_owned()),
2786                _ => None,
2787            })
2788            .expect("expected tagged scalar")
2789    }
2790
2791    #[cfg(feature = "comments")]
2792    #[test]
2793    fn deferred_parse_node_can_emit_comment_before_flow_node() {
2794        let mut parser = Parser::new_from_str("---\n# deferred\nvalue\n");
2795        assert_eq!(parser.stream_start().unwrap().0, Event::StreamStart);
2796        assert_eq!(
2797            parser.document_start(true).unwrap().0,
2798            Event::DocumentStart(true, None)
2799        );
2800
2801        let (event, _) = parser
2802            .defer_parse_node(State::FlowNode, State::FlowMappingKey, false, false)
2803            .unwrap();
2804
2805        assert!(matches!(event, Event::Comment(text, _) if text == " deferred"));
2806        assert_eq!(parser.state, State::FlowNode);
2807    }
2808
2809    #[cfg(feature = "comments")]
2810    #[test]
2811    fn queued_node_event_gets_pending_key_indent() {
2812        let mut parser = Parser::new_from_str("");
2813        let span = Span::empty(Marker::new(0, 1, 0));
2814
2815        parser.pending_key_indent = Some(3);
2816        parser
2817            .queued_events
2818            .push_back((Event::SequenceStart(StructureStyle::Block, 0, None), span));
2819
2820        let (event, span) = parser.next_event_impl().unwrap();
2821
2822        assert!(matches!(
2823            event,
2824            Event::SequenceStart(StructureStyle::Block, 0, None)
2825        ));
2826        assert_eq!(span.indent, Some(3));
2827        assert_eq!(parser.pending_key_indent, None);
2828    }
2829
2830    #[test]
2831    fn state_machine_handles_deferred_flow_node_states() {
2832        let mut parser = Parser::new_from_str("value\n");
2833        assert_eq!(parser.stream_start().unwrap().0, Event::StreamStart);
2834        assert_eq!(
2835            parser.document_start(true).unwrap().0,
2836            Event::DocumentStart(false, None)
2837        );
2838        parser.state = State::FlowNode;
2839        parser.push_state(State::End);
2840
2841        let (event, _) = parser.state_machine().unwrap();
2842
2843        assert!(matches!(event, Event::Scalar(value, ..) if value == "value"));
2844    }
2845
2846    #[cfg(feature = "comments")]
2847    #[test]
2848    fn state_machine_handles_deferred_flow_mapping_value_node() {
2849        let mut parser = Parser::new_from_str("value\n");
2850        assert_eq!(parser.stream_start().unwrap().0, Event::StreamStart);
2851        assert_eq!(
2852            parser.document_start(true).unwrap().0,
2853            Event::DocumentStart(false, None)
2854        );
2855        parser.state = State::FlowSequenceEntryMappingValueNode;
2856
2857        let (event, _) = parser.state_machine().unwrap();
2858
2859        assert!(matches!(event, Event::Scalar(value, ..) if value == "value"));
2860    }
2861
2862    #[test]
2863    fn display_resolved_core_tag_without_extra_bang() {
2864        let tag = Tag::with_original_handle("tag:yaml.org,2002:", "str", "!!");
2865
2866        assert_eq!(tag.to_string(), "tag:yaml.org,2002:str");
2867    }
2868
2869    #[test]
2870    fn tag_helpers_distinguish_core_and_local_tags() {
2871        let core = Tag::with_original_handle("tag:yaml.org,2002:", "int", "!!");
2872        let local = Tag::new("!", "thing");
2873        let non_specific = Tag::with_original_handle("", "!", "");
2874        let verbatim = Tag::with_original_handle("", "tag:example.com,2000:thing", "");
2875        let unknown_yaml_org = Tag::with_original_handle("", "tag:yaml.org,2002:application", "");
2876
2877        assert_eq!(core.core_suffix(), Some("int"));
2878        assert!(core.is_yaml_core_schema());
2879        assert!(core.is_yaml_core_schema_tag("int"));
2880        assert!(!core.is_yaml_core_schema_tag("str"));
2881        assert!(!core.is_custom());
2882        assert_eq!(core.parts(), ("tag:yaml.org,2002:", "int"));
2883        assert_eq!(core.original_parts(), ("!!", "int"));
2884        assert_eq!(core.original(), "!!int");
2885
2886        assert_eq!(local.core_suffix(), None);
2887        assert!(!local.is_yaml_core_schema());
2888        assert!(!local.is_yaml_core_schema_tag("thing"));
2889        assert!(local.is_custom());
2890        assert_eq!(local.parts(), ("!", "thing"));
2891        assert_eq!(local.original_parts(), ("!", "thing"));
2892        assert_eq!(local.original(), "!thing");
2893        assert_eq!(local.to_string(), "!thing");
2894
2895        assert_eq!(non_specific.parts(), ("", "!"));
2896        assert_eq!(non_specific.original_parts(), ("", "!"));
2897        assert_eq!(non_specific.original(), "!");
2898
2899        assert_eq!(verbatim.parts(), ("", "tag:example.com,2000:thing"));
2900        assert_eq!(
2901            verbatim.original_parts(),
2902            ("", "tag:example.com,2000:thing")
2903        );
2904        assert_eq!(verbatim.original(), "!<tag:example.com,2000:thing>");
2905
2906        assert_eq!(unknown_yaml_org.core_suffix(), None);
2907        assert!(!unknown_yaml_org.is_yaml_core_schema());
2908        assert!(unknown_yaml_org.is_custom());
2909    }
2910
2911    #[test]
2912    fn core_suffix_uses_resolved_tag_uri_for_common_spellings() {
2913        let cases = [
2914            ("shorthand", "v: !!int 1\n", ("tag:yaml.org,2002:", "int")),
2915            (
2916                "verbatim",
2917                "v: !<tag:yaml.org,2002:int> 1\n",
2918                ("", "tag:yaml.org,2002:int"),
2919            ),
2920            (
2921                "full prefix",
2922                "%TAG !e! tag:yaml.org,2002:\n---\nv: !e!int 1\n",
2923                ("tag:yaml.org,2002:", "int"),
2924            ),
2925            (
2926                "mid-split",
2927                "%TAG !m! tag:yaml.org,2002:i\n---\nv: !m!nt 1\n",
2928                ("tag:yaml.org,2002:i", "nt"),
2929            ),
2930        ];
2931
2932        for (label, input, expected_parts) in cases {
2933            let tag = first_tagged_scalar_tag(input);
2934
2935            assert_eq!(tag.parts(), expected_parts, "{label}");
2936            assert_eq!(tag.core_suffix(), Some("int"), "{label}");
2937            assert!(tag.is_yaml_core_schema(), "{label}");
2938            assert!(tag.is_yaml_core_schema_tag("int"), "{label}");
2939            assert!(!tag.is_yaml_core_schema_tag("str"), "{label}");
2940            assert!(!tag.is_custom(), "{label}");
2941        }
2942    }
2943
2944    #[test]
2945    fn core_suffix_rejects_non_core_yaml_org_tags() {
2946        let cases = [
2947            "binary",
2948            "merge",
2949            "omap",
2950            "pairs",
2951            "set",
2952            "timestamp",
2953            "value",
2954            "yaml",
2955        ];
2956
2957        for suffix in cases {
2958            let tag = Tag::with_original_handle("tag:yaml.org,2002:", suffix, "!!");
2959
2960            assert_eq!(tag.core_suffix(), None, "{suffix}");
2961            assert!(!tag.is_yaml_core_schema(), "{suffix}");
2962            assert!(tag.is_custom(), "{suffix}");
2963        }
2964    }
2965
2966    #[test]
2967    fn core_suffix_rejects_non_core_tags() {
2968        let cases = [
2969            ("local", "v: !local 1\n"),
2970            ("verbatim custom", "v: !<tag:example.com,2000:int> 1\n"),
2971            (
2972                "custom directive",
2973                "%TAG !e! tag:example.com,2000:\n---\nv: !e!int 1\n",
2974            ),
2975            (
2976                "overridden secondary handle",
2977                "%TAG !! tag:example.com,2000:app/\n---\nv: !!int 1\n",
2978            ),
2979        ];
2980
2981        for (label, input) in cases {
2982            let tag = first_tagged_scalar_tag(input);
2983
2984            assert_eq!(tag.core_suffix(), None, "{label}");
2985            assert!(!tag.is_yaml_core_schema(), "{label}");
2986            assert!(!tag.is_yaml_core_schema_tag("int"), "{label}");
2987            assert!(tag.is_custom(), "{label}");
2988        }
2989    }
2990
2991    #[test]
2992    fn suffix_in_namespace_resolves_across_spellings() {
2993        const NS: &str = "tag:yaml.org,2002:";
2994
2995        // Every spelling of `tag:yaml.org,2002:omap` resolves to the same name, even though
2996        // `omap` is not a Core Schema type (so `core_suffix` reports `None`). `mid_split` cuts
2997        // the URI after the namespace prefix (handle longer than `NS`); `inside_split` cuts it
2998        // before the prefix ends (handle a non-empty prefix of `NS`), exercising both branches.
2999        let shorthand = Tag::with_original_handle(NS, "omap", "!!");
3000        let verbatim = Tag::with_original_handle("", "tag:yaml.org,2002:omap", "");
3001        let mid_split = Tag::with_original_handle("tag:yaml.org,2002:o", "map", "!o!");
3002        let inside_split = Tag::with_original_handle("tag:yaml.org,", "2002:omap", "!y!");
3003        for tag in [&shorthand, &verbatim, &mid_split, &inside_split] {
3004            assert_eq!(tag.suffix_in_namespace(NS).as_deref(), Some("omap"));
3005            assert_eq!(tag.core_suffix(), None);
3006        }
3007
3008        // Borrow whenever the resolved name is a contiguous slice of `handle` or `suffix`;
3009        // allocate only when a split lands inside the name itself (handle extends past `NS`).
3010        assert!(matches!(
3011            shorthand.suffix_in_namespace(NS),
3012            Some(Cow::Borrowed(_))
3013        ));
3014        assert!(matches!(
3015            verbatim.suffix_in_namespace(NS),
3016            Some(Cow::Borrowed(_))
3017        ));
3018        assert!(matches!(
3019            inside_split.suffix_in_namespace(NS),
3020            Some(Cow::Borrowed(_))
3021        ));
3022        assert!(matches!(
3023            mid_split.suffix_in_namespace(NS),
3024            Some(Cow::Owned(_))
3025        ));
3026
3027        // The non-core `merge` type resolves the same way; core types still flow through
3028        // `core_suffix`.
3029        let merge = Tag::with_original_handle(NS, "merge", "!!");
3030        assert_eq!(merge.suffix_in_namespace(NS).as_deref(), Some("merge"));
3031        assert_eq!(merge.core_suffix(), None);
3032        assert_eq!(
3033            Tag::new(NS, "int").suffix_in_namespace(NS).as_deref(),
3034            Some("int")
3035        );
3036
3037        // Tags outside the namespace do not resolve into it.
3038        assert_eq!(Tag::new("!", "omap").suffix_in_namespace(NS), None);
3039        assert_eq!(
3040            Tag::with_original_handle("", "tag:example.com,2000:omap", "").suffix_in_namespace(NS),
3041            None
3042        );
3043    }
3044
3045    #[test]
3046    fn attach_tag_start_applies_marker_to_span() {
3047        let event = Event::Scalar("value".into(), ScalarStyle::Plain, 0, None);
3048        let span = Span::new(Marker::new(6, 1, 6), Marker::new(11, 1, 11));
3049        let tag_start = Marker::new(0, 1, 0);
3050
3051        let (attached_event, attached_span) =
3052            Parser::<crate::input::str::StrInput<'_>>::attach_tag_start(
3053                event.clone(),
3054                span,
3055                Some(tag_start),
3056            );
3057
3058        assert_eq!(attached_event, event);
3059        assert_eq!(attached_span.start, span.start);
3060        assert_eq!(attached_span.end, span.end);
3061        assert_eq!(attached_span.tag_start(), Some(tag_start));
3062    }
3063
3064    #[test]
3065    fn event_inspection_helpers_report_node_metadata() {
3066        let tag = Tag::new("!", "thing");
3067        let scalar = Event::Scalar(
3068            "value".into(),
3069            ScalarStyle::DoubleQuoted,
3070            7,
3071            Some(Cow::Borrowed(&tag)),
3072        );
3073        let sequence =
3074            Event::SequenceStart(StructureStyle::Block, 8, Some(Cow::Owned(tag.clone())));
3075        let mapping = Event::MappingStart(StructureStyle::Block, 9, Some(Cow::Borrowed(&tag)));
3076
3077        assert_eq!(scalar.anchor_id(), Some(7));
3078        assert_eq!(scalar.alias_id(), None);
3079        assert_eq!(scalar.tag(), Some(&tag));
3080        assert_eq!(scalar.scalar(), Some(("value", ScalarStyle::DoubleQuoted)));
3081        assert!(scalar.is_node());
3082
3083        assert_eq!(sequence.anchor_id(), Some(8));
3084        assert_eq!(sequence.alias_id(), None);
3085        assert_eq!(sequence.tag(), Some(&tag));
3086        assert_eq!(sequence.scalar(), None);
3087        assert!(sequence.is_node());
3088
3089        assert_eq!(mapping.anchor_id(), Some(9));
3090        assert_eq!(mapping.alias_id(), None);
3091        assert_eq!(mapping.tag(), Some(&tag));
3092        assert_eq!(mapping.scalar(), None);
3093        assert!(mapping.is_node());
3094
3095        let alias = Event::Alias(10);
3096        assert_eq!(alias.anchor_id(), None);
3097        assert_eq!(alias.alias_id(), Some(10));
3098        assert_eq!(alias.tag(), None);
3099        assert_eq!(alias.scalar(), None);
3100        assert!(alias.is_node());
3101
3102        let unanchored_scalar = Event::Scalar("x".into(), ScalarStyle::Plain, 0, None);
3103        assert_eq!(unanchored_scalar.anchor_id(), None);
3104        assert_eq!(unanchored_scalar.alias_id(), None);
3105
3106        let stream_start = Event::StreamStart;
3107        assert_eq!(stream_start.anchor_id(), None);
3108        assert_eq!(stream_start.alias_id(), None);
3109        assert_eq!(stream_start.tag(), None);
3110        assert_eq!(stream_start.scalar(), None);
3111        assert!(!stream_start.is_node());
3112    }
3113
3114    #[test]
3115    fn test_peek_eq_parse() {
3116        let s = "
3117a0 bb: val
3118a1: &x
3119    b1: 4
3120    b2: d
3121a2: 4
3122a3: [1, 2, 3]
3123a4:
3124    - [a1, a2]
3125    - 2
3126a5: *x
3127";
3128        let mut p = Parser::new_from_str(s);
3129        loop {
3130            let event_peek = p.peek().unwrap().unwrap().clone();
3131            let event = p.next_event().unwrap().unwrap();
3132            assert_eq!(event, event_peek);
3133            if event.0 == Event::StreamEnd {
3134                break;
3135            }
3136        }
3137    }
3138
3139    #[test]
3140    fn test_repeated_peek_returns_buffered_event() {
3141        let mut parser = Parser::new_from_str("key: value\n");
3142
3143        let first_peek = parser.peek().unwrap().unwrap().clone();
3144        let second_peek = parser.peek().unwrap().unwrap().clone();
3145        let next = parser.next_event().unwrap().unwrap();
3146
3147        assert_eq!(first_peek, second_peek);
3148        assert_eq!(first_peek, next);
3149    }
3150
3151    #[cfg(feature = "error_messages")]
3152    #[test]
3153    fn test_peek_surfaces_scan_error_without_consuming_stream_end_state() {
3154        let mut parser = Parser::new_from_str("a: [1, 2");
3155
3156        loop {
3157            match parser.peek() {
3158                Some(Ok(_)) => {
3159                    parser.next_event().unwrap().unwrap();
3160                }
3161                Some(Err(error)) => {
3162                    assert_eq!(error.info(), "unclosed bracket '['");
3163                    break;
3164                }
3165                None => panic!("expected parse error"),
3166            }
3167        }
3168    }
3169
3170    #[test]
3171    fn test_iterator_terminates_after_scan_error() {
3172        let parser = Parser::new_from_str("foo:\n  bar\ninvalid\n");
3173        let mut errors = 0usize;
3174        let mut events = 0usize;
3175
3176        for item in parser {
3177            events += 1;
3178            if item.is_err() {
3179                errors += 1;
3180            }
3181            assert!(
3182                events < 1000,
3183                "parser iterator did not terminate after a scan error"
3184            );
3185        }
3186
3187        assert_eq!(errors, 1);
3188    }
3189
3190    #[cfg(feature = "error_messages")]
3191    #[test]
3192    fn test_iterator_terminates_after_node_property_error() {
3193        let parser = Parser::new_from_str("- *nope\n- 2\n");
3194        let mut errors = 0usize;
3195        let mut saw_later_node = false;
3196        let mut events = 0usize;
3197
3198        for item in parser {
3199            events += 1;
3200            match item {
3201                Ok((Event::Scalar(value, ..), _)) if value == "2" => saw_later_node = true,
3202                Ok(_) => {}
3203                Err(error) => {
3204                    assert_eq!(error.info(), "while parsing node, found unknown anchor");
3205                    errors += 1;
3206                }
3207            }
3208            assert!(
3209                events < 1000,
3210                "parser iterator did not terminate after a node-property error"
3211            );
3212        }
3213
3214        assert_eq!(errors, 1);
3215        assert!(!saw_later_node, "parser resumed after the alias error");
3216    }
3217
3218    #[test]
3219    fn test_peeked_scan_error_is_returned_once_by_next_event() {
3220        let mut parser = Parser::new_from_str("a: [1, 2");
3221
3222        let first_error = loop {
3223            match parser.peek() {
3224                Some(Ok(_)) => {
3225                    parser.next_event().unwrap().unwrap();
3226                }
3227                Some(Err(error)) => break error,
3228                None => panic!("expected parse error"),
3229            }
3230        };
3231        let Some(Err(second_error)) = parser.peek() else {
3232            panic!("expected cached parse error");
3233        };
3234
3235        assert_eq!(first_error, second_error);
3236        assert_eq!(parser.next_event().unwrap().unwrap_err(), first_error);
3237        assert!(parser.next_event().is_none());
3238        assert!(parser.peek().is_none());
3239    }
3240
3241    #[cfg(feature = "error_messages")]
3242    #[test]
3243    fn test_peeked_node_property_error_is_stable_and_terminal() {
3244        let mut parser = Parser::new_from_str("a: *nope\nb: 2\n");
3245
3246        for _ in 0..4 {
3247            parser.next_event().unwrap().unwrap();
3248        }
3249
3250        let Some(Err(first_error)) = parser.peek() else {
3251            panic!("expected unknown alias error");
3252        };
3253        let Some(Err(second_error)) = parser.peek() else {
3254            panic!("expected cached unknown alias error");
3255        };
3256
3257        assert_eq!(first_error, second_error);
3258        assert_eq!(
3259            first_error.info(),
3260            "while parsing node, found unknown anchor"
3261        );
3262        assert_eq!(parser.next_event().unwrap().unwrap_err(), first_error);
3263        assert!(parser.next_event().is_none());
3264        assert!(parser.peek().is_none());
3265    }
3266
3267    #[test]
3268    fn test_peek_and_next_return_none_after_stream_end() {
3269        let mut parser = Parser::new_from_str("");
3270
3271        assert!(matches!(
3272            parser.next_event().unwrap().unwrap().0,
3273            Event::StreamStart
3274        ));
3275        assert!(matches!(
3276            parser.next_event().unwrap().unwrap().0,
3277            Event::StreamEnd
3278        ));
3279        assert!(parser.next_event().is_none());
3280        assert!(parser.peek().is_none());
3281    }
3282
3283    #[test]
3284    fn test_load_after_stream_already_ended_emits_stream_end() {
3285        let mut parser = Parser::new_from_str("");
3286        while parser.next_event().is_some() {}
3287
3288        let mut sink = CollectingSink::default();
3289        parser.load(&mut sink, true).unwrap();
3290
3291        assert_eq!(sink.events, vec![Event::StreamEnd]);
3292    }
3293
3294    #[test]
3295    fn test_load_full_stream_fuses_iterator_after_stream_end() {
3296        let mut parser = Parser::new_from_str("a: 1\n");
3297        let mut sink = CollectingSink::default();
3298
3299        parser.load(&mut sink, true).unwrap();
3300
3301        assert!(matches!(sink.events.last(), Some(Event::StreamEnd)));
3302        assert!(parser.next_event().is_none());
3303        assert!(parser.peek().is_none());
3304    }
3305
3306    #[test]
3307    fn test_load_after_peek_delivers_buffered_document_end_before_stream_end() {
3308        let mut parser = Parser::new_from_str("a");
3309        for _ in 0..3 {
3310            parser.next_event().unwrap().unwrap();
3311        }
3312
3313        assert_eq!(parser.peek().unwrap().unwrap().0, Event::DocumentEnd);
3314
3315        let mut sink = CollectingSink::default();
3316        parser.load(&mut sink, true).unwrap();
3317
3318        assert_eq!(sink.events, vec![Event::DocumentEnd, Event::StreamEnd]);
3319        assert!(parser.next_event().is_none());
3320    }
3321
3322    #[test]
3323    fn test_load_visits_nested_collection_events() {
3324        let mut parser = Parser::new_from_str("root:\n  - item: value\n  - [a, b]\n");
3325        let mut sink = CollectingSink::default();
3326
3327        parser.load(&mut sink, true).unwrap();
3328
3329        assert_eq!(
3330            sink.events,
3331            vec![
3332                Event::StreamStart,
3333                Event::DocumentStart(false, None),
3334                Event::MappingStart(StructureStyle::Block, 0, None),
3335                Event::Scalar("root".into(), ScalarStyle::Plain, 0, None),
3336                Event::SequenceStart(StructureStyle::Block, 0, None),
3337                Event::MappingStart(StructureStyle::Block, 0, None),
3338                Event::Scalar("item".into(), ScalarStyle::Plain, 0, None),
3339                Event::Scalar("value".into(), ScalarStyle::Plain, 0, None),
3340                Event::MappingEnd,
3341                Event::SequenceStart(StructureStyle::Flow, 0, None),
3342                Event::Scalar("a".into(), ScalarStyle::Plain, 0, None),
3343                Event::Scalar("b".into(), ScalarStyle::Plain, 0, None),
3344                Event::SequenceEnd,
3345                Event::SequenceEnd,
3346                Event::MappingEnd,
3347                Event::DocumentEnd,
3348                Event::StreamEnd,
3349            ]
3350        );
3351    }
3352
3353    #[derive(Clone, Debug, PartialEq, Eq)]
3354    enum ValidationError {
3355        ForbiddenValue,
3356    }
3357
3358    #[cfg(feature = "error_messages")]
3359    #[derive(Debug)]
3360    struct ReceiverFailure;
3361
3362    #[cfg(feature = "error_messages")]
3363    impl fmt::Display for ReceiverFailure {
3364        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3365            write!(f, "receiver failed")
3366        }
3367    }
3368
3369    #[cfg(feature = "error_messages")]
3370    impl core::error::Error for ReceiverFailure {}
3371
3372    struct FailingSink<'input> {
3373        events: Vec<Event<'input>>,
3374    }
3375
3376    impl<'input> TryEventReceiver<'input> for FailingSink<'input> {
3377        type Error = ValidationError;
3378
3379        fn on_event(&mut self, ev: Event<'input>) -> Result<(), Self::Error> {
3380            let should_fail = matches!(&ev, Event::Scalar(value, ..) if value.as_ref() == "bad");
3381            self.events.push(ev);
3382            if should_fail {
3383                Err(ValidationError::ForbiddenValue)
3384            } else {
3385                Ok(())
3386            }
3387        }
3388    }
3389
3390    #[test]
3391    fn test_try_load_stops_on_receiver_error() {
3392        let mut parser = Parser::new_from_str("ok: bad\nafter: value\n");
3393        let mut sink = FailingSink { events: Vec::new() };
3394
3395        let err = parser.try_load(&mut sink, true).unwrap_err();
3396
3397        assert_eq!(err, TryLoadError::Receiver(ValidationError::ForbiddenValue));
3398        assert!(sink
3399            .events
3400            .iter()
3401            .any(|event| matches!(event, Event::Scalar(value, ..) if value == "ok")));
3402        assert!(sink
3403            .events
3404            .iter()
3405            .any(|event| matches!(event, Event::Scalar(value, ..) if value == "bad")));
3406        assert!(!sink
3407            .events
3408            .iter()
3409            .any(|event| matches!(event, Event::Scalar(value, ..) if value == "after")));
3410    }
3411
3412    struct SpannedFailingSink {
3413        failed_span: Option<Span>,
3414    }
3415
3416    impl<'input> TrySpannedEventReceiver<'input> for SpannedFailingSink {
3417        type Error = Span;
3418
3419        fn on_event(&mut self, ev: Event<'input>, span: Span) -> Result<(), Self::Error> {
3420            if matches!(ev, Event::Scalar(value, ..) if value.as_ref() == "bad") {
3421                self.failed_span = Some(span);
3422                Err(span)
3423            } else {
3424                Ok(())
3425            }
3426        }
3427    }
3428
3429    #[test]
3430    fn test_try_load_spanned_receiver_gets_span() {
3431        let mut parser = Parser::new_from_str("value: bad\n");
3432        let mut sink = SpannedFailingSink { failed_span: None };
3433
3434        let err = parser.try_load(&mut sink, false).unwrap_err();
3435
3436        let TryLoadError::Receiver(span) = err else {
3437            panic!("expected receiver error");
3438        };
3439
3440        assert_eq!(Some(span), sink.failed_span);
3441        assert!(!span.is_empty());
3442    }
3443
3444    #[cfg(feature = "error_messages")]
3445    struct NeverFails {
3446        count: usize,
3447    }
3448
3449    #[cfg(feature = "error_messages")]
3450    impl<'input> TryEventReceiver<'input> for NeverFails {
3451        type Error = ValidationError;
3452
3453        fn on_event(&mut self, _ev: Event<'input>) -> Result<(), Self::Error> {
3454            self.count += 1;
3455            Ok(())
3456        }
3457    }
3458
3459    #[cfg(feature = "error_messages")]
3460    #[test]
3461    fn test_try_load_returns_scan_error() {
3462        let mut parser = Parser::new_from_str("%YAML 1.2\n%YAML 1.2\n---\n");
3463        let mut sink = NeverFails { count: 0 };
3464
3465        let err = parser.try_load(&mut sink, true).unwrap_err();
3466
3467        let TryLoadError::Scan(err) = err else {
3468            panic!("expected scan error");
3469        };
3470        assert_eq!(err.kind(), &ErrorKind::DuplicateVersionDirective);
3471        assert_eq!(err.info(), "duplicate version directive");
3472    }
3473
3474    #[cfg(feature = "error_messages")]
3475    #[test]
3476    fn test_try_load_error_display_and_source_cover_both_variants() {
3477        let scan = ScanError::from_kind(Marker::new(3, 1, 3), ErrorKind::UnexpectedEof);
3478        let scan_err: TryLoadError<ReceiverFailure> = scan.into();
3479
3480        assert!(scan_err
3481            .to_string()
3482            .starts_with("parser error: unexpected eof"));
3483        assert!(scan_err.source().is_some());
3484
3485        let receiver_err = TryLoadError::Receiver(ReceiverFailure);
3486
3487        assert_eq!(receiver_err.to_string(), "receiver error: receiver failed");
3488        assert!(receiver_err.source().is_some());
3489    }
3490
3491    #[cfg(feature = "error_messages")]
3492    #[test]
3493    fn test_try_load_requires_buffered_stream_start() {
3494        let mut parser = Parser::new_from_str("");
3495        let span = Span::empty(Marker::new(0, 1, 0));
3496        parser.current = Some((
3497            Event::Scalar("value".into(), ScalarStyle::Plain, 0, None),
3498            span,
3499        ));
3500        let mut sink = NeverFails { count: 0 };
3501
3502        let err = parser.try_load(&mut sink, true).unwrap_err();
3503
3504        let TryLoadError::Scan(err) = err else {
3505            panic!("expected scan error");
3506        };
3507        assert_eq!(err.info(), "did not find expected <stream-start>");
3508    }
3509
3510    #[test]
3511    fn test_try_load_after_stream_already_ended_emits_stream_end() {
3512        let mut parser = Parser::new_from_str("");
3513        while parser.next_event().is_some() {}
3514
3515        let mut sink = FailingSink { events: Vec::new() };
3516        parser.try_load(&mut sink, true).unwrap();
3517
3518        assert_eq!(sink.events, vec![Event::StreamEnd]);
3519    }
3520
3521    #[test]
3522    fn test_try_load_full_stream_fuses_iterator_after_stream_end() {
3523        let mut parser = Parser::new_from_str("a: 1\n");
3524        let mut sink = FailingSink { events: Vec::new() };
3525
3526        parser.try_load(&mut sink, true).unwrap();
3527
3528        assert!(matches!(sink.events.last(), Some(Event::StreamEnd)));
3529        assert!(parser.next_event().is_none());
3530        assert!(parser.peek().is_none());
3531    }
3532
3533    #[test]
3534    fn test_try_load_after_peek_delivers_buffered_document_end_before_stream_end() {
3535        let mut parser = Parser::new_from_str("a");
3536        for _ in 0..3 {
3537            parser.next_event().unwrap().unwrap();
3538        }
3539
3540        assert_eq!(parser.peek().unwrap().unwrap().0, Event::DocumentEnd);
3541
3542        let mut sink = FailingSink { events: Vec::new() };
3543        parser.try_load(&mut sink, true).unwrap();
3544
3545        assert_eq!(sink.events, vec![Event::DocumentEnd, Event::StreamEnd]);
3546        assert!(parser.next_event().is_none());
3547    }
3548
3549    #[test]
3550    fn test_load_single_document_stops_before_next_document() {
3551        let mut parser = Parser::new_from_str("a: 1\n---\nb: 2\n");
3552        let mut sink = CollectingSink::default();
3553
3554        parser.load(&mut sink, false).unwrap();
3555
3556        assert!(sink
3557            .events
3558            .iter()
3559            .any(|event| matches!(event, Event::Scalar(value, ..) if value == "a")));
3560        assert!(!sink
3561            .events
3562            .iter()
3563            .any(|event| matches!(event, Event::Scalar(value, ..) if value == "b")));
3564        assert!(matches!(sink.events.last(), Some(Event::DocumentEnd)));
3565    }
3566
3567    #[cfg(feature = "error_messages")]
3568    #[test]
3569    fn test_duplicate_version_directive_errors() {
3570        assert_eq!(
3571            first_error_info("%YAML 1.2\n%YAML 1.2\n---\n"),
3572            "duplicate version directive"
3573        );
3574    }
3575
3576    #[cfg(feature = "error_messages")]
3577    #[test]
3578    fn test_unsupported_yaml_major_version_errors() {
3579        assert_eq!(
3580            first_error_info("%YAML 9.9\n--- a\n"),
3581            "unsupported YAML major version"
3582        );
3583    }
3584
3585    #[test]
3586    fn test_document_start_emits_yaml_version() {
3587        let events = Parser::new_from_str("%YAML 1.2\n---\nvalue\n")
3588            .map(|event| event.unwrap().0)
3589            .collect::<Vec<_>>();
3590
3591        assert!(matches!(
3592            events.get(1),
3593            Some(Event::DocumentStart(
3594                true,
3595                Some(YamlVersion { major: 1, minor: 2 })
3596            ))
3597        ));
3598    }
3599
3600    #[test]
3601    fn test_document_start_allows_supported_major_future_minor_version() {
3602        let events = Parser::new_from_str("%YAML 1.9\n---\nvalue\n")
3603            .map(|event| event.unwrap().0)
3604            .collect::<Vec<_>>();
3605
3606        assert!(matches!(
3607            events.get(1),
3608            Some(Event::DocumentStart(
3609                true,
3610                Some(YamlVersion { major: 1, minor: 9 })
3611            ))
3612        ));
3613    }
3614
3615    #[test]
3616    fn test_document_start_keeps_version_and_tags_across_comment() {
3617        let events = Parser::new_from_str(
3618            "%YAML 1.2\n# directive comment\n%TAG !e! tag:example.com,2026:\n---\nkey: !e!thing value\n",
3619        )
3620        .map(|event| event.unwrap().0)
3621        .filter(|event| {
3622            #[cfg(feature = "comments")]
3623            {
3624                !matches!(event, Event::Comment(..))
3625            }
3626            #[cfg(not(feature = "comments"))]
3627            {
3628                let _ = event;
3629                true
3630            }
3631        })
3632        .collect::<Vec<_>>();
3633
3634        assert!(matches!(
3635            events.get(1),
3636            Some(Event::DocumentStart(
3637                true,
3638                Some(YamlVersion { major: 1, minor: 2 })
3639            ))
3640        ));
3641
3642        let tag = events
3643            .iter()
3644            .find_map(|event| match event {
3645                Event::Scalar(value, _, _, Some(tag)) if value == "value" => Some(tag),
3646                _ => None,
3647            })
3648            .expect("expected tagged scalar after comment-separated directives");
3649
3650        assert_eq!(tag.handle, "tag:example.com,2026:");
3651        assert_eq!(tag.suffix, "thing");
3652    }
3653
3654    #[cfg(feature = "comments")]
3655    #[test]
3656    fn tag_directive_state_borrows_str_input_across_comment() {
3657        let mut parser = Parser::new_from_str(
3658            "%TAG !e! tag:example.com,2026:\n# directive comment\n---\nkey: value\n",
3659        );
3660
3661        while let Some(event) = parser.next_event() {
3662            if matches!(event.unwrap().0, Event::Comment(..)) {
3663                break;
3664            }
3665        }
3666
3667        assert!(matches!(
3668            parser.tags.get("!e!"),
3669            Some(Cow::Borrowed("tag:example.com,2026:"))
3670        ));
3671        assert!(parser
3672            .pending_document_tag_handles
3673            .iter()
3674            .any(|handle| matches!(handle, Cow::Borrowed("!e!"))));
3675    }
3676
3677    #[test]
3678    fn test_each_document_can_declare_own_yaml_version() {
3679        let document_starts = Parser::new_from_str(
3680            "%YAML 1.2\n---\na\n...\n%YAML 1.2\n---\nb\n...\n%YAML 1.1\n---\nc\n",
3681        )
3682        .filter_map(|event| match event.unwrap().0 {
3683            Event::DocumentStart(explicit, version) => Some((explicit, version)),
3684            _ => None,
3685        })
3686        .collect::<Vec<_>>();
3687
3688        assert_eq!(
3689            document_starts,
3690            vec![
3691                (true, Some(YamlVersion::new(1, 2))),
3692                (true, Some(YamlVersion::new(1, 2))),
3693                (true, Some(YamlVersion::new(1, 1))),
3694            ]
3695        );
3696    }
3697
3698    #[cfg(feature = "error_messages")]
3699    #[test]
3700    fn test_duplicate_tag_directive_errors() {
3701        assert_eq!(
3702            first_error_info("%TAG !t! tag:test,2024:\n%TAG !t! tag:other,2024:\n---\n"),
3703            "the TAG directive must only be given at most once per handle in the same document"
3704        );
3705    }
3706
3707    #[cfg(feature = "error_messages")]
3708    #[test]
3709    fn duplicate_tag_directive_across_comment_is_rejected() {
3710        let input = concat!(
3711            "%TAG !e! tag:example.com,2000:one/\n",
3712            "# separator\n",
3713            "%TAG !e! tag:example.com,2000:two/\n",
3714            "---\n",
3715        );
3716
3717        assert_eq!(
3718            first_error_info(input),
3719            "the TAG directive must only be given at most once per handle in the same document"
3720        );
3721    }
3722
3723    #[test]
3724    fn test_keep_tags_inherited_handle_can_be_redeclared_in_next_document() {
3725        let input = concat!(
3726            "%TAG !e! tag:example.com,2000:one/\n",
3727            "---\n",
3728            "first: !e!thing value\n",
3729            "...\n",
3730            "%TAG !e! tag:example.com,2000:two/\n",
3731            "---\n",
3732            "second: !e!thing value\n",
3733        );
3734
3735        let tags = Parser::new_from_str(input)
3736            .keep_tags(true)
3737            .filter_map(|event| match event.expect("input should parse").0 {
3738                Event::Scalar(value, _, _, Some(tag)) if value == "value" => {
3739                    Some(tag.handle.clone())
3740                }
3741                _ => None,
3742            })
3743            .collect::<Vec<_>>();
3744
3745        assert_eq!(
3746            tags,
3747            vec!["tag:example.com,2000:one/", "tag:example.com,2000:two/"]
3748        );
3749    }
3750
3751    #[cfg(feature = "error_messages")]
3752    #[test]
3753    fn test_directive_after_implicit_document_requires_explicit_end() {
3754        assert_eq!(
3755            first_error_info("---\nkey: value\n%YAML 1.2\n---\n"),
3756            "missing explicit document end marker before directive"
3757        );
3758    }
3759
3760    #[cfg(feature = "error_messages")]
3761    #[test]
3762    fn test_anchor_offset_overflow_reports_error() {
3763        let mut parser = Parser::new_from_str("&a value");
3764        parser.set_anchor_offset(usize::MAX);
3765
3766        let err = parser
3767            .find_map(Result::err)
3768            .expect("anchor registration should overflow");
3769
3770        assert_eq!(
3771            err.info(),
3772            "while parsing anchor, anchor count exceeded supported limit"
3773        );
3774    }
3775
3776    #[test]
3777    fn test_alias_resolves_to_registered_anchor_id() {
3778        let events = Parser::new_from_str("- &a value\n- *a\n")
3779            .map(|event| event.unwrap().0)
3780            .collect::<Vec<_>>();
3781
3782        assert!(events.iter().any(|event| matches!(event, Event::Alias(1))));
3783    }
3784
3785    #[test]
3786    fn test_anchor_then_tag_applies_both_to_scalar() {
3787        let events = Parser::new_from_str("&a !!str value")
3788            .map(|event| event.unwrap().0)
3789            .collect::<Vec<_>>();
3790
3791        let Some(Event::Scalar(value, _, anchor_id, Some(tag))) = events
3792            .iter()
3793            .find(|event| matches!(event, Event::Scalar(value, ..) if value == "value"))
3794        else {
3795            panic!("expected tagged anchored scalar");
3796        };
3797
3798        assert_eq!(value, "value");
3799        assert_eq!(*anchor_id, 1);
3800        assert_eq!(tag.handle, "tag:yaml.org,2002:");
3801        assert_eq!(tag.suffix, "str");
3802        assert_eq!(tag.original_handle, "!!");
3803        assert_eq!(tag.original(), "!!str");
3804    }
3805
3806    #[test]
3807    fn test_tag_then_anchor_applies_both_to_scalar() {
3808        let events = Parser::new_from_str("!!str &a value")
3809            .map(|event| event.unwrap().0)
3810            .collect::<Vec<_>>();
3811
3812        let Some(Event::Scalar(value, _, anchor_id, Some(tag))) = events
3813            .iter()
3814            .find(|event| matches!(event, Event::Scalar(value, ..) if value == "value"))
3815        else {
3816            panic!("expected tagged anchored scalar");
3817        };
3818
3819        assert_eq!(value, "value");
3820        assert_eq!(*anchor_id, 1);
3821        assert_eq!(tag.handle, "tag:yaml.org,2002:");
3822        assert_eq!(tag.suffix, "str");
3823        assert_eq!(tag.original_handle, "!!");
3824        assert_eq!(tag.original(), "!!str");
3825    }
3826
3827    #[test]
3828    fn test_tag_directive_preserves_original_handle() {
3829        let events =
3830            Parser::new_from_str("%TAG !e! tag:example.com,2000:\n---\nconfig: !e!keep value\n")
3831                .map(|event| event.unwrap().0)
3832                .collect::<Vec<_>>();
3833
3834        let (value, tag) = events
3835            .iter()
3836            .find_map(|event| match event {
3837                Event::Scalar(value, _, _, Some(tag)) if value == "value" => Some((value, tag)),
3838                _ => None,
3839            })
3840            .expect("expected tagged scalar");
3841
3842        assert_eq!(value, "value");
3843        assert_eq!(tag.handle, "tag:example.com,2000:");
3844        assert_eq!(tag.suffix, "keep");
3845        assert_eq!(tag.original_handle, "!e!");
3846        assert_eq!(tag.parts(), ("tag:example.com,2000:", "keep"));
3847        assert_eq!(tag.original_parts(), ("!e!", "keep"));
3848        assert_eq!(tag.original(), "!e!keep");
3849    }
3850
3851    #[test]
3852    fn test_verbatim_tag_original_is_normalized_author_spelling() {
3853        let events = Parser::new_from_str("key: !<tag:example.com,2000:thing> value\n")
3854            .map(|event| event.unwrap().0)
3855            .collect::<Vec<_>>();
3856
3857        let Some(Event::Scalar(value, _, _, Some(tag))) = events
3858            .iter()
3859            .find(|event| matches!(event, Event::Scalar(value, ..) if value == "value"))
3860        else {
3861            panic!("expected tagged scalar");
3862        };
3863
3864        assert_eq!(value, "value");
3865        assert_eq!(tag.handle, "");
3866        assert_eq!(tag.suffix, "tag:example.com,2000:thing");
3867        assert_eq!(tag.original_handle, "");
3868        assert_eq!(tag.parts(), ("", "tag:example.com,2000:thing"));
3869        assert_eq!(tag.original_parts(), ("", "tag:example.com,2000:thing"));
3870        assert_eq!(tag.original(), "!<tag:example.com,2000:thing>");
3871    }
3872
3873    #[test]
3874    fn test_multiple_tag_directives_are_kept_within_document() {
3875        let text = r"
3876%TAG !a! tag:a,2024:
3877%TAG !b! tag:b,2024:
3878---
3879first: !a!x foo
3880second: !b!y bar
3881";
3882
3883        let mut seen_a = false;
3884        let mut seen_b = false;
3885        for event in Parser::new_from_str(text) {
3886            let (event, _) = event.unwrap();
3887            if let Event::Scalar(_, _, _, Some(tag)) = event {
3888                if tag.handle == "tag:a,2024:" {
3889                    seen_a = true;
3890                } else if tag.handle == "tag:b,2024:" {
3891                    seen_b = true;
3892                }
3893            }
3894        }
3895
3896        assert!(seen_a);
3897        assert!(seen_b);
3898    }
3899
3900    #[cfg(feature = "error_messages")]
3901    #[test]
3902    fn test_tags_are_cleared_when_next_document_has_no_directives() {
3903        let text = r"
3904%TAG !t! tag:test,2024:
3905--- !t!1
3906foo
3907--- !t!2
3908bar
3909";
3910
3911        let mut parser = Parser::new_from_str(text);
3912        for event in parser.by_ref() {
3913            let (event, _) = event.unwrap();
3914            if let Event::DocumentEnd = event {
3915                break;
3916            }
3917        }
3918
3919        match parser.next().unwrap().unwrap().0 {
3920            Event::DocumentStart(true, None) => {}
3921            _ => panic!("expected explicit second document start"),
3922        }
3923
3924        let err = parser.next().unwrap().unwrap_err();
3925        assert!(format!("{err}").contains("the handle wasn't declared"));
3926    }
3927
3928    #[cfg(feature = "error_messages")]
3929    #[test]
3930    fn test_pull_parser_clears_anchors_between_documents() {
3931        let mut parser = Parser::new_from_str(
3932            "--- &a value
3933--- *a
3934",
3935        );
3936
3937        for event in parser.by_ref() {
3938            let (event, _) = event.unwrap();
3939            if matches!(event, Event::DocumentEnd) {
3940                break;
3941            }
3942        }
3943
3944        match parser.next().unwrap().unwrap().0 {
3945            Event::DocumentStart(true, None) => {}
3946            _ => panic!("expected explicit second document start"),
3947        }
3948
3949        let err = parser.next().unwrap().unwrap_err();
3950        assert!(format!("{err}").contains("unknown anchor"));
3951    }
3952
3953    #[test]
3954    fn test_keep_tags_across_multiple_documents() {
3955        let text = r#"
3956%YAML 1.1
3957%TAG !t! tag:test,2024:
3958--- !t!1 &1
3959foo: "bar"
3960--- !t!2 &2
3961baz: "qux"
3962"#;
3963        for x in Parser::new_from_str(text).keep_tags(true) {
3964            let x = x.unwrap();
3965            if let Event::MappingStart(_, _, tag) = x.0 {
3966                let tag = tag.unwrap();
3967                assert_eq!(tag.handle, "tag:test,2024:");
3968            }
3969        }
3970
3971        for x in Parser::new_from_str(text).keep_tags(false) {
3972            if x.is_err() {
3973                // Test successful
3974                return;
3975            }
3976        }
3977        panic!("Test failed, did not encounter error")
3978    }
3979
3980    #[test]
3981    fn test_flow_sequence_mapping_allows_empty_key() {
3982        let parser = Parser::new_from_str("[?: value]");
3983        for event in parser {
3984            event.expect("parser should accept flow sequence mappings with empty keys");
3985        }
3986    }
3987
3988    #[test]
3989    fn test_keep_tags_does_not_persist_default_tag_handles() {
3990        let text = "%TAG !! tag:evil,2024:\n--- !!int 1\n--- !!int 2\n";
3991
3992        let mut int_tags = Vec::new();
3993        for event in Parser::new_from_str(text).keep_tags(true) {
3994            let event = event.unwrap().0;
3995            if let Event::Scalar(_, _, _, Some(tag)) = event {
3996                if tag.suffix == "int" {
3997                    int_tags.push(tag.handle.clone());
3998                }
3999            }
4000        }
4001
4002        assert_eq!(int_tags, vec!["tag:evil,2024:", "tag:yaml.org,2002:"]);
4003    }
4004
4005    #[test]
4006    fn test_keep_tags_does_not_persist_primary_tag_handle() {
4007        let text = "%TAG ! tag:evil,2024:\n--- !int 1\n--- !int 2\n";
4008
4009        let tags = Parser::new_from_str(text)
4010            .keep_tags(true)
4011            .filter_map(|event| match event.expect("input should parse").0 {
4012                Event::Scalar(_, _, _, Some(tag)) if tag.suffix == "int" => {
4013                    Some(tag.handle.clone())
4014                }
4015                _ => None,
4016            })
4017            .collect::<Vec<_>>();
4018
4019        assert_eq!(tags, vec!["tag:evil,2024:", "!"]);
4020    }
4021
4022    #[test]
4023    fn test_resolve_tag_distinguishes_non_specific_and_primary_handle_tags() {
4024        let mut parser = Parser::new_from_str("");
4025        parser
4026            .tags
4027            .insert("!".into(), "tag:local.example,2024:".into());
4028
4029        for (handle, suffix, expected_prefix, original) in [
4030            ("", "!", "", "!"),
4031            ("!", "foo", "tag:local.example,2024:", "!foo"),
4032        ] {
4033            let tag = parser
4034                .resolve_tag(
4035                    Span::empty(Marker::new(0, 1, 0)),
4036                    &Cow::Borrowed(handle),
4037                    Cow::Borrowed(suffix),
4038                )
4039                .unwrap();
4040
4041            assert_eq!(tag.parts(), (expected_prefix, suffix));
4042            assert_eq!(tag.original_parts(), (handle, suffix));
4043            assert_eq!(tag.original(), original);
4044            assert_eq!(tag.to_string(), format!("{expected_prefix}{suffix}"));
4045        }
4046    }
4047
4048    #[test]
4049    fn test_load_after_peek_stream_start() {
4050        #[derive(Default)]
4051        struct Sink<'input> {
4052            events: Vec<Event<'input>>,
4053        }
4054
4055        impl<'input> EventReceiver<'input> for Sink<'input> {
4056            fn on_event(&mut self, ev: Event<'input>) {
4057                self.events.push(ev);
4058            }
4059        }
4060
4061        let mut parser = Parser::new_from_str("key: value\n");
4062        let mut sink = Sink::default();
4063
4064        assert_eq!(parser.peek().unwrap().unwrap().0, Event::StreamStart);
4065        parser.load(&mut sink, false).unwrap();
4066
4067        assert!(matches!(sink.events.first(), Some(Event::StreamStart)));
4068        assert!(matches!(sink.events.get(1), Some(Event::DocumentStart(..))));
4069    }
4070}