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,
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///
92/// Inspect events with `matches!`, `if let`, or `match`, using `{ .. }` for every variant,
93/// including those that currently have no fields. Ignoring unneeded fields allows future
94/// metadata to be added without breaking these patterns. A complete `match` needs a fallback
95/// arm because new event variants may also be added.
96///
97/// Normal builds provide no whole-event equality. Classify an event by its variant, then inspect
98/// only the fields you need. The opt-in `test_equality` feature enables equality for tests,
99/// comparing the event variant and its core fields. It ignores scalar implicitness and
100/// `extended_details` metadata (block-header syntax and document-end explicitness). Source
101/// information may be unavailable on synthetic events; enabling optional capture (including
102/// through another dependency) must not change equality. Compare those fields explicitly
103/// when testing source syntax. Existing document-start explicitness and version are compared.
104///
105/// Constructors support synthetic events, [`ParserTrait`] implementations, and
106/// [`crate::ReplayParser`] streams. To retain an existing event beyond its source's lifetime,
107/// use [`Self::into_owned`], which preserves all metadata. [`Self::as_borrowed`] provides a view
108/// without cloning owned payloads. Construction does not enable equality in normal builds.
109///
110/// ```
111/// use granit_parser::{Event, Parser};
112/// let (event, _) = Parser::new_from_str("hello").nth(2).unwrap().unwrap();
113/// assert!(matches!(event, Event::Scalar { .. }));
114/// if let Event::Scalar { value, .. } = event {
115///     assert_eq!(value, "hello");
116/// }
117/// ```
118///
119#[cfg_attr(
120    not(feature = "test_equality"),
121    doc = r"
122Whole-event equality is intentionally unavailable by default:
123
124```compile_fail,E0369
125use granit_parser::Event;
126fn equal_events(left: Event<'_>, right: Event<'_>) -> bool {
127    left == right
128}
129```
130"
131)]
132/// Direct struct-literal construction outside this crate is not supported:
133///
134/// ```compile_fail,E0639
135/// use granit_parser::Event;
136/// let event = Event::Alias { anchor_id: 1 };
137/// ```
138///
139/// Use constructors to rebuild an event or provide synthetic parser input:
140///
141/// ```
142/// use granit_parser::{Event, Marker, ParserTrait, ReplayParser, ScalarStyle, Span};
143/// let event = Event::new_scalar("generated".into(), ScalarStyle::plain(), 0, None);
144/// let span = Span::empty(Marker::new(0, 1, 0));
145/// let mut replay = ReplayParser::new(vec![(event, span)], 0);
146/// let (event, _) = replay.next_event().unwrap().unwrap();
147/// assert!(matches!(event, Event::Scalar { value, .. } if value == "generated"));
148/// ```
149#[non_exhaustive]
150#[derive(Clone, Debug)]
151pub enum Event<'input> {
152    /// Event generated at the very beginning of parsing.
153    #[non_exhaustive]
154    StreamStart,
155    /// Last event that will be generated by the parser. Signals EOF.
156    #[non_exhaustive]
157    StreamEnd,
158    /// The start of a YAML document.
159    ///
160    #[non_exhaustive]
161    DocumentStart {
162        /// Whether this is an explicit document start marker (`---`).
163        ///
164        /// When `false`, the document start is implicit.
165        explicit: bool,
166        /// YAML version declared by a preceding `%YAML` directive, if any.
167        version: Option<YamlVersion>,
168    },
169    /// The end of a YAML document.
170    ///
171    /// This event is emitted for both explicit document end markers (`...`) and implicit document
172    /// ends. The `extended_details` feature exposes whether the marker was written.
173    #[non_exhaustive]
174    DocumentEnd {
175        /// Whether the source contains an explicit `...` end marker.
176        #[cfg(feature = "extended_details")]
177        explicit: bool,
178    },
179    /// A resolved YAML alias.
180    ///
181    /// The companion [`Span`] covers the complete `*name` token, preserving the original name
182    /// through its source range. With [`Options::emit_anchor_events`], [`Self::Anchor`] connects
183    /// the target ID to its definition's name and source range.
184    #[non_exhaustive]
185    Alias {
186        /// The anchor ID the alias refers to.
187        anchor_id: usize,
188    },
189    /// Metadata for an anchor definition on the immediately preceding node in its parser's stream.
190    ///
191    /// Emitted only when [`Options::emit_anchor_events`] is `true`, immediately after the
192    /// anchored [`Self::Scalar`], [`Self::SequenceStart`], or [`Self::MappingStart`], before any
193    /// collection children. This is presentation metadata, not an additional YAML node.
194    /// The companion [`Span`] covers the complete `&name` token, whose source position precedes
195    /// the node content. Comments between properties and content can precede the node event.
196    /// Emitting the node first ensures that a failure before its event is emitted cannot leave
197    /// anchor metadata without an associated node event, even during document recovery.
198    ///
199    /// This adjacency guarantee applies to an individual [`Parser`]. See [`crate::ParserStack`]
200    /// for ordering when sources are interleaved.
201    ///
202    /// Repeated names receive distinct IDs; aliases refer to the most recent preceding
203    /// definition in the same document. IDs match those on node and [`Self::Alias`] events,
204    /// including when [`Parser::set_anchor_offset`] is used.
205    #[non_exhaustive]
206    Anchor {
207        /// The assigned internal anchor ID.
208        anchor_id: usize,
209        /// The original anchor name, without the leading `&`.
210        name: Cow<'input, str>,
211    },
212    /// An alias without a preceding anchor definition in its document.
213    ///
214    /// Emitted only when [`Options::emit_unresolved_aliases`] is `true`. The companion [`Span`]
215    /// covers the complete alias token, including `*`. This event occupies a node position but
216    /// represents an invalid reference; a later anchor definition does not resolve it retroactively.
217    #[non_exhaustive]
218    UnresolvedAlias {
219        /// The original alias name, without the leading `*`.
220        name: Cow<'input, str>,
221    },
222    /// A YAML source comment.
223    ///
224    /// Comments are presentation metadata, not YAML data nodes. The payload is the raw text
225    /// exactly after `#`, excluding only the line break. The placement is a best-effort hint for
226    /// correlating the comment with nearby YAML presentation. The companion parser [`Span`] covers
227    /// the whole source comment, including `#` and excluding the line break.
228    #[cfg(feature = "comments")]
229    #[non_exhaustive]
230    Comment {
231        /// Raw comment payload exactly after `#`, excluding only the line break.
232        value: Cow<'input, str>,
233        /// Best-effort placement relative to nearby YAML content.
234        placement: Placement,
235    },
236    /// A YAML scalar value.
237    #[non_exhaustive]
238    Scalar {
239        /// The scalar value after YAML escape processing.
240        value: Cow<'input, str>,
241        /// The source notation used for the scalar.
242        style: ScalarStyle,
243        /// The anchor ID defined on this scalar, or `0` if it has no anchor.
244        anchor_id: usize,
245        /// The resolved tag attached to this scalar, if any.
246        tag: Option<Cow<'input, Tag>>,
247    },
248    /// The start of a YAML sequence (array).
249    #[non_exhaustive]
250    SequenceStart {
251        /// The notation style used for the sequence.
252        style: StructureStyle,
253        /// The anchor ID defined on this sequence, or `0` if it has no anchor.
254        anchor_id: usize,
255        /// The resolved tag attached to this sequence, if any.
256        tag: Option<Cow<'input, Tag>>,
257    },
258    /// The end of a YAML sequence (array).
259    #[non_exhaustive]
260    SequenceEnd,
261    /// The start of a YAML mapping (object, hash).
262    #[non_exhaustive]
263    MappingStart {
264        /// The notation style used for the mapping (Flow or Block).
265        style: StructureStyle,
266        /// The anchor ID defined on this mapping, or `0` if it has no anchor.
267        anchor_id: usize,
268        /// The resolved tag attached to this mapping, if any.
269        tag: Option<Cow<'input, Tag>>,
270    },
271    /// The end of a YAML mapping (object, hash).
272    #[non_exhaustive]
273    MappingEnd,
274}
275
276#[cfg(feature = "test_equality")]
277impl PartialEq for Event<'_> {
278    fn eq(&self, other: &Self) -> bool {
279        // Keep this match and its field patterns exhaustive so new variants and fields
280        // require an explicit equality policy. Optional source details are ignored.
281        match self {
282            Self::StreamStart => matches!(other, Self::StreamStart),
283            Self::StreamEnd => matches!(other, Self::StreamEnd),
284            Self::DocumentStart { explicit, version } => matches!(
285                other,
286                Self::DocumentStart { explicit: other_explicit, version: other_version }
287                    if explicit == other_explicit && version == other_version
288            ),
289            Self::DocumentEnd {
290                #[cfg(feature = "extended_details")]
291                    explicit: _,
292            } => matches!(other, Self::DocumentEnd { .. }),
293            Self::Alias { anchor_id } => matches!(
294                other, Self::Alias { anchor_id: other_id } if anchor_id == other_id
295            ),
296            Self::Anchor { anchor_id, name } => matches!(
297                other, Self::Anchor { anchor_id: other_id, name: other_name }
298                    if anchor_id == other_id && name == other_name
299            ),
300            Self::UnresolvedAlias { name } => matches!(
301                other, Self::UnresolvedAlias { name: other_name } if name == other_name
302            ),
303            #[cfg(feature = "comments")]
304            Self::Comment { value, placement } => matches!(
305                other, Self::Comment { value: other_value, placement: other_placement }
306                    if value == other_value && placement == other_placement
307            ),
308            Self::Scalar {
309                value,
310                style,
311                anchor_id,
312                tag,
313            } => matches!(
314                other,
315                Self::Scalar {
316                    value: other_value, style: other_style,
317                    anchor_id: other_id, tag: other_tag,
318                } if value == other_value && style == other_style
319                    && anchor_id == other_id && tag == other_tag
320            ),
321            Self::SequenceStart {
322                style,
323                anchor_id,
324                tag,
325            } => matches!(
326                other,
327                Self::SequenceStart {
328                    style: other_style, anchor_id: other_id, tag: other_tag,
329                } if style == other_style && anchor_id == other_id && tag == other_tag
330            ),
331            Self::SequenceEnd => matches!(other, Self::SequenceEnd),
332            Self::MappingStart {
333                style,
334                anchor_id,
335                tag,
336            } => matches!(
337                other,
338                Self::MappingStart {
339                    style: other_style, anchor_id: other_id, tag: other_tag,
340                } if style == other_style && anchor_id == other_id && tag == other_tag
341            ),
342            Self::MappingEnd => matches!(other, Self::MappingEnd),
343        }
344    }
345}
346
347#[cfg(feature = "test_equality")]
348impl Eq for Event<'_> {}
349
350/// The notation style used for a YAML sequence or mapping.
351///
352/// [`StructureStyle::Block`] means block notation:
353///
354/// ```yaml
355/// items:
356///   - milk
357///   - bread
358/// mapping:
359///   name: Ada
360///   active: true
361/// ```
362///
363/// [`StructureStyle::Flow`] means flow notation:
364///
365/// ```yaml
366/// items: [milk, bread]
367/// mapping: {name: Ada, active: true}
368/// ```
369#[derive(Clone, Copy, PartialEq, Debug, Eq, Hash, PartialOrd, Ord)]
370#[non_exhaustive]
371pub enum StructureStyle {
372    /// Block notation, such as `- item` sequences and `key: value` mappings.
373    Block,
374    /// Flow notation, such as `[item]` sequences and `{key: value}` mappings.
375    Flow,
376}
377
378/// A YAML tag.
379#[derive(Clone, PartialEq, Debug, Eq, Ord, PartialOrd, Hash)]
380pub struct Tag {
381    /// Resolved tag handle or prefix.
382    ///
383    /// Examples include `tag:yaml.org,2002:` for core-schema tags and `!` for local tags.
384    handle: Cow<'static, str>,
385    /// Tag suffix following the resolved handle or prefix.
386    suffix: Cow<'static, str>,
387    /// Tag handle as written in the source before `%TAG` directive resolution.
388    ///
389    /// For example, with `%TAG !e! tag:example.com,2000:`, a source tag `!e!keep` is resolved
390    /// as `handle = "tag:example.com,2000:"` and `suffix = "keep"`, while
391    /// `original_handle = "!e!"`.
392    original_handle: Cow<'static, str>,
393}
394
395const YAML_CORE_SCHEMA_PREFIX: &str = "tag:yaml.org,2002:";
396
397// YAML 1.2.2 defines Core Schema tags by reference:
398// - §10.3.1 says Core Schema uses the same tags as YAML's JSON Schema.
399// - §10.2.1 adds null/bool/int/float to the Failsafe Schema.
400// - §10.1.1 defines the Failsafe Schema tags map/seq/str.
401// Therefore the YAML 1.2.2 Core Schema tag suffixes are:
402// bool, float, int, map, null, seq, and str.
403const YAML_CORE_SCHEMA_SUFFIXES: [&str; 7] = ["bool", "float", "int", "map", "null", "seq", "str"];
404
405fn known_yaml_core_schema_suffix(suffix: &str) -> Option<&str> {
406    YAML_CORE_SCHEMA_SUFFIXES
407        .contains(&suffix)
408        .then_some(suffix)
409}
410
411fn known_yaml_core_schema_suffix_from_split(
412    handle_tail: &str,
413    suffix: &str,
414) -> Option<&'static str> {
415    YAML_CORE_SCHEMA_SUFFIXES.iter().copied().find(|candidate| {
416        candidate
417            .strip_prefix(handle_tail)
418            .is_some_and(|candidate_tail| candidate_tail == suffix)
419    })
420}
421
422/// Retain common tag components without allocating, and reuse owned scanner strings otherwise.
423fn own_tag_component(component: Cow<'_, str>) -> Cow<'static, str> {
424    let known = match component.as_ref() {
425        "" => "",
426        "!" => "!",
427        "!!" => "!!",
428        "tag:yaml.org,2002:" => YAML_CORE_SCHEMA_PREFIX,
429        "bool" => "bool",
430        "float" => "float",
431        "int" => "int",
432        "map" => "map",
433        "null" => "null",
434        "seq" => "seq",
435        "str" => "str",
436        _ => return Cow::Owned(component.into_owned()),
437    };
438    Cow::Borrowed(known)
439}
440
441impl Tag {
442    /// Create a tag from resolved parts.
443    ///
444    /// This is mainly useful for tests and consumers constructing parser-compatible tags by hand.
445    /// When the original source handle matters, use [`Self::with_original_handle`].
446    #[must_use]
447    pub fn new(handle: impl Into<String>, suffix: impl Into<String>) -> Self {
448        let handle = handle.into();
449        Self {
450            original_handle: Cow::Owned(handle.clone()),
451            handle: Cow::Owned(handle),
452            suffix: Cow::Owned(suffix.into()),
453        }
454    }
455
456    /// Create a tag from resolved parts and the handle as written in the source.
457    #[must_use]
458    pub fn with_original_handle(
459        handle: impl Into<String>,
460        suffix: impl Into<String>,
461        original_handle: impl Into<String>,
462    ) -> Self {
463        Self {
464            handle: Cow::Owned(handle.into()),
465            suffix: Cow::Owned(suffix.into()),
466            original_handle: Cow::Owned(original_handle.into()),
467        }
468    }
469
470    /// Return the resolved tag handle or prefix.
471    #[must_use]
472    pub fn handle(&self) -> &str {
473        &self.handle
474    }
475
476    /// Return the suffix following the resolved tag handle or prefix.
477    #[must_use]
478    pub fn suffix(&self) -> &str {
479        &self.suffix
480    }
481
482    /// Return the tag handle as written before `%TAG` directive resolution.
483    #[must_use]
484    pub fn original_handle(&self) -> &str {
485        &self.original_handle
486    }
487
488    /// Return the resolved YAML core-schema suffix for this tag, if it is a known core tag.
489    ///
490    /// The tag is matched by its resolved URI, not by the source handle spelling. For example,
491    /// `!!int`, `!<tag:yaml.org,2002:int>`, and a `%TAG` split such as
492    /// `%TAG !m! tag:yaml.org,2002:i` followed by `!m!nt` all return `Some("int")`.
493    ///
494    /// Authored tag parts are left unchanged; use [`Self::parts`], [`Self::original_parts`], or
495    /// [`Self::original`] to inspect those spellings.
496    #[must_use]
497    pub fn core_suffix(&self) -> Option<&str> {
498        // The handle ends at or before the namespace boundary. The remaining namespace
499        // prefix and the complete type name are both contained in `suffix`.
500        if let Some(remaining_prefix) = YAML_CORE_SCHEMA_PREFIX.strip_prefix(self.handle.as_ref()) {
501            let suffix = self.suffix.strip_prefix(remaining_prefix)?;
502            return known_yaml_core_schema_suffix(suffix);
503        }
504
505        // The handle extends beyond the namespace boundary, so the type name is split
506        // between the end of `handle` and `suffix`. Compare against the seven fixed names
507        // directly instead of assembling an allocated String.
508        let handle_tail = self.handle.strip_prefix(YAML_CORE_SCHEMA_PREFIX)?;
509        known_yaml_core_schema_suffix_from_split(handle_tail, &self.suffix)
510    }
511
512    /// Return the type name this tag resolves to within `prefix`, or `None` outside it.
513    ///
514    /// Like [`Self::core_suffix`], the tag is matched by its resolved `handle ++ suffix` URI,
515    /// not the source spelling, so `!!omap`, `!<tag:yaml.org,2002:omap>`, and a `%TAG` split
516    /// such as `%TAG !o! tag:yaml.org,2002:o` then `!o!map` all resolve to `Some("omap")` for
517    /// the `tag:yaml.org,2002:` prefix — but the name is not limited to the seven core types.
518    ///
519    /// Borrows from `self`; allocates only when the handle extends past `prefix`.
520    #[must_use]
521    pub fn suffix_in_namespace(&self, prefix: &str) -> Option<Cow<'_, str>> {
522        if let Some(handle_tail) = self.handle.strip_prefix(prefix) {
523            // Handle spans the whole prefix; the name is its tail plus the suffix (the tail
524            // is empty unless a `%TAG` split pushed part of the name into the handle).
525            return Some(if handle_tail.is_empty() {
526                Cow::Borrowed(self.suffix.as_ref())
527            } else {
528                let mut name = String::with_capacity(handle_tail.len() + self.suffix.len());
529                name.push_str(handle_tail);
530                name.push_str(&self.suffix);
531                Cow::Owned(name)
532            });
533        }
534
535        // Handle stops inside the prefix; the suffix supplies the rest of the prefix
536        // and then the name.
537        prefix
538            .strip_prefix(self.handle.as_ref())
539            .and_then(|prefix_tail| self.suffix.strip_prefix(prefix_tail))
540            .map(Cow::Borrowed)
541    }
542
543    /// Returns whether the tag is a YAML tag from the core schema (`!!str`, `!!int`, ...).
544    ///
545    /// The YAML specification specifies [a list of
546    /// tags](https://yaml.org/spec/1.2.2/#103-core-schema) for the Core Schema. This function uses
547    /// the resolved tag URI, so it is independent of how the tag was split between handle and
548    /// suffix.
549    ///
550    /// # Return
551    /// Returns `true` if the resolved tag is a known YAML 1.2.2 Core Schema tag.
552    #[must_use]
553    pub fn is_yaml_core_schema(&self) -> bool {
554        self.core_suffix().is_some()
555    }
556
557    /// Return true for a YAML core-schema tag with the given suffix.
558    ///
559    /// For example, this matches core-schema tags such as `!!str`, `!!int`, `!!float`, `!!bool`,
560    /// `!!null`, `!!map`, or `!!seq` after tag resolution.
561    #[must_use]
562    pub fn is_yaml_core_schema_tag(&self, suffix: &str) -> bool {
563        self.core_suffix()
564            .is_some_and(|core_suffix| core_suffix == suffix)
565    }
566
567    /// Return true for a tag outside the YAML 1.2.2 Core Schema tag set.
568    ///
569    /// This checks the resolved tag URI, not just the tag handle spelling. For example,
570    /// `tag:yaml.org,2002:timestamp` is in the YAML tag namespace, but it is not a YAML 1.2.2
571    /// Core Schema tag.
572    #[must_use]
573    pub fn is_custom(&self) -> bool {
574        !self.is_yaml_core_schema()
575    }
576
577    /// Return the tag as `(handle, suffix)`.
578    #[must_use]
579    pub fn parts(&self) -> (&str, &str) {
580        (&self.handle, &self.suffix)
581    }
582
583    /// Return the tag as `(original_handle, suffix)` using the handle from the source token.
584    ///
585    /// This is useful when a consumer needs author spelling such as `!e!keep` instead of the
586    /// resolved URI tag `tag:example.com,2000:keep`.
587    #[must_use]
588    pub fn original_parts(&self) -> (&str, &str) {
589        (&self.original_handle, &self.suffix)
590    }
591
592    /// Return the tag spelling reconstructed from the source handle and suffix.
593    ///
594    /// For ordinary shorthand tags this returns the author-facing spelling, such as `!e!keep` or
595    /// `!!str`. For verbatim tags this returns a normalized verbatim spelling such as
596    /// `!<tag:example.com,2000:thing>`, not necessarily the byte-exact source token.
597    #[must_use]
598    pub fn original(&self) -> String {
599        if self.original_handle.is_empty() && self.suffix != "!" {
600            let mut tag = String::with_capacity(self.suffix.len() + 3);
601            tag.push_str("!<");
602            tag.push_str(&self.suffix);
603            tag.push('>');
604            return tag;
605        }
606
607        let mut tag = String::with_capacity(self.original_handle.len() + self.suffix.len());
608        tag.push_str(&self.original_handle);
609        tag.push_str(&self.suffix);
610        tag
611    }
612}
613
614impl Display for Tag {
615    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
616        if self.handle == "!" {
617            write!(f, "!{}", self.suffix)
618        } else {
619            write!(f, "{}{}", self.handle, self.suffix)
620        }
621    }
622}
623
624impl<'input> Event<'input> {
625    /// Retain this event independently of its source, preserving every field.
626    ///
627    /// Owned strings and tags are moved without cloning. Borrowed payloads are copied into
628    /// owned storage. All source metadata is retained, including optional extended details.
629    ///
630    /// ```
631    /// use granit_parser::{Event, Parser};
632    /// let events: Vec<Event<'static>> = {
633    ///     let input = String::from("message: hello");
634    ///     Parser::new_from_str(&input)
635    ///         .map(|result| result.unwrap().0.into_owned())
636    ///         .collect()
637    /// };
638    /// assert!(events.iter().any(|event| event.scalar().is_some()));
639    /// ```
640    #[must_use]
641    pub fn into_owned(self) -> Event<'static> {
642        // Exhaustive field patterns ensure new metadata receives an ownership policy.
643        match self {
644            Self::StreamStart => Event::StreamStart,
645            Self::StreamEnd => Event::StreamEnd,
646            Self::DocumentStart { explicit, version } => Event::DocumentStart { explicit, version },
647            Self::DocumentEnd {
648                #[cfg(feature = "extended_details")]
649                explicit,
650            } => Event::DocumentEnd {
651                #[cfg(feature = "extended_details")]
652                explicit,
653            },
654            Self::Alias { anchor_id } => Event::Alias { anchor_id },
655            Self::Anchor { anchor_id, name } => Event::Anchor {
656                anchor_id,
657                name: Cow::Owned(name.into_owned()),
658            },
659            Self::UnresolvedAlias { name } => Event::UnresolvedAlias {
660                name: Cow::Owned(name.into_owned()),
661            },
662            #[cfg(feature = "comments")]
663            Self::Comment { value, placement } => Event::Comment {
664                value: Cow::Owned(value.into_owned()),
665                placement,
666            },
667            Self::Scalar {
668                value,
669                style,
670                anchor_id,
671                tag,
672            } => Event::Scalar {
673                value: Cow::Owned(value.into_owned()),
674                style,
675                anchor_id,
676                tag: tag.map(|tag| Cow::Owned(tag.into_owned())),
677            },
678            Self::SequenceStart {
679                style,
680                anchor_id,
681                tag,
682            } => Event::SequenceStart {
683                style,
684                anchor_id,
685                tag: tag.map(|tag| Cow::Owned(tag.into_owned())),
686            },
687            Self::SequenceEnd => Event::SequenceEnd,
688            Self::MappingStart {
689                style,
690                anchor_id,
691                tag,
692            } => Event::MappingStart {
693                style,
694                anchor_id,
695                tag: tag.map(|tag| Cow::Owned(tag.into_owned())),
696            },
697            Self::MappingEnd => Event::MappingEnd,
698        }
699    }
700
701    /// Borrow this event's payloads without allocating, preserving every field.
702    ///
703    /// The returned event borrows from `self`, even when its payloads are owned. Use
704    /// [`Self::into_owned`] on the result if it must outlive this borrow.
705    ///
706    /// ```
707    /// use granit_parser::{Event, ScalarStyle};
708    /// let event = Event::new_scalar(String::from("hello").into(), ScalarStyle::plain(), 0, None);
709    /// let borrowed = event.as_borrowed();
710    /// assert_eq!(borrowed.scalar().unwrap().0, "hello");
711    /// ```
712    #[must_use]
713    pub fn as_borrowed(&self) -> Event<'_> {
714        // Exhaustive field patterns ensure new metadata is included in borrowed views.
715        match self {
716            Self::StreamStart => Event::StreamStart,
717            Self::StreamEnd => Event::StreamEnd,
718            Self::DocumentStart { explicit, version } => Event::DocumentStart {
719                explicit: *explicit,
720                version: *version,
721            },
722            Self::DocumentEnd {
723                #[cfg(feature = "extended_details")]
724                explicit,
725            } => Event::DocumentEnd {
726                #[cfg(feature = "extended_details")]
727                explicit: *explicit,
728            },
729            Self::Alias { anchor_id } => Event::Alias {
730                anchor_id: *anchor_id,
731            },
732            Self::Anchor { anchor_id, name } => Event::Anchor {
733                anchor_id: *anchor_id,
734                name: Cow::Borrowed(name.as_ref()),
735            },
736            Self::UnresolvedAlias { name } => Event::UnresolvedAlias {
737                name: Cow::Borrowed(name.as_ref()),
738            },
739            #[cfg(feature = "comments")]
740            Self::Comment { value, placement } => Event::Comment {
741                value: Cow::Borrowed(value.as_ref()),
742                placement: *placement,
743            },
744            Self::Scalar {
745                value,
746                style,
747                anchor_id,
748                tag,
749            } => Event::Scalar {
750                value: Cow::Borrowed(value.as_ref()),
751                style: *style,
752                anchor_id: *anchor_id,
753                tag: tag.as_deref().map(Cow::Borrowed),
754            },
755            Self::SequenceStart {
756                style,
757                anchor_id,
758                tag,
759            } => Event::SequenceStart {
760                style: *style,
761                anchor_id: *anchor_id,
762                tag: tag.as_deref().map(Cow::Borrowed),
763            },
764            Self::SequenceEnd => Event::SequenceEnd,
765            Self::MappingStart {
766                style,
767                anchor_id,
768                tag,
769            } => Event::MappingStart {
770                style: *style,
771                anchor_id: *anchor_id,
772                tag: tag.as_deref().map(Cow::Borrowed),
773            },
774            Self::MappingEnd => Event::MappingEnd,
775        }
776    }
777
778    /// Create a stream-start event.
779    #[must_use]
780    pub const fn stream_start() -> Self {
781        Self::StreamStart
782    }
783
784    /// Create a stream-end event.
785    #[must_use]
786    pub const fn stream_end() -> Self {
787        Self::StreamEnd
788    }
789
790    /// Create a sequence-end event.
791    #[must_use]
792    pub const fn sequence_end() -> Self {
793        Self::SequenceEnd
794    }
795
796    /// Create a mapping-end event.
797    #[must_use]
798    pub const fn mapping_end() -> Self {
799        Self::MappingEnd
800    }
801
802    /// Create a document-start event with its explicit-marker flag and declared YAML version.
803    #[must_use]
804    pub const fn document_start(explicit: bool, version: Option<YamlVersion>) -> Self {
805        Self::DocumentStart { explicit, version }
806    }
807
808    /// Create a document-end event with no written end marker.
809    ///
810    /// This constructor takes no parameters in every feature configuration. With
811    /// `extended_details`, use `with_explicit_end` to describe a written `...` marker.
812    #[must_use]
813    pub const fn document_end() -> Self {
814        Self::DocumentEnd {
815            #[cfg(feature = "extended_details")]
816            explicit: false,
817        }
818    }
819
820    /// Set whether a document-end event has a written `...` marker.
821    ///
822    /// Returns this event with the supplied flag. Events other than [`Self::DocumentEnd`]
823    /// are returned unchanged.
824    #[cfg(feature = "extended_details")]
825    #[must_use]
826    pub fn with_explicit_end(mut self, explicit: bool) -> Self {
827        if let Self::DocumentEnd { explicit: value } = &mut self {
828            *value = explicit;
829        }
830        self
831    }
832
833    /// Create a resolved alias referring to `anchor_id`.
834    #[must_use]
835    pub const fn alias(anchor_id: usize) -> Self {
836        Self::Alias { anchor_id }
837    }
838
839    /// Create anchor metadata with the assigned ID and original name (without `&`).
840    #[must_use]
841    pub fn anchor(anchor_id: usize, name: Cow<'input, str>) -> Self {
842        Self::Anchor { anchor_id, name }
843    }
844
845    /// Create an unresolved alias with its original name (without `*`).
846    #[must_use]
847    pub fn unresolved_alias(name: Cow<'input, str>) -> Self {
848        Self::UnresolvedAlias { name }
849    }
850
851    /// Create a comment with its raw text (without `#`) and placement hint.
852    #[cfg(feature = "comments")]
853    #[must_use]
854    pub fn comment(value: Cow<'input, str>, placement: Placement) -> Self {
855        Self::Comment { value, placement }
856    }
857
858    /// Create a scalar event.
859    ///
860    /// # Parameters
861    /// - `value`: decoded scalar content.
862    /// - `style`: source notation and its syntax metadata.
863    /// - `anchor_id`: anchor defined on this node, or zero for none.
864    /// - `tag`: resolved explicit tag, if present.
865    ///
866    /// # Returns
867    /// A scalar event containing the supplied value and properties.
868    #[must_use]
869    pub fn new_scalar(
870        value: Cow<'input, str>,
871        style: ScalarStyle,
872        anchor_id: usize,
873        tag: Option<Cow<'input, Tag>>,
874    ) -> Self {
875        Self::Scalar {
876            value,
877            style,
878            anchor_id,
879            tag,
880        }
881    }
882
883    /// Create a sequence-start event.
884    ///
885    /// # Parameters
886    /// - `style`: block or flow notation.
887    /// - `anchor_id`: anchor defined on this node, or zero for none.
888    /// - `tag`: resolved explicit tag, if present.
889    ///
890    /// # Returns
891    /// A sequence-start event containing the supplied properties.
892    #[must_use]
893    pub fn sequence_start(
894        style: StructureStyle,
895        anchor_id: usize,
896        tag: Option<Cow<'input, Tag>>,
897    ) -> Self {
898        Self::SequenceStart {
899            style,
900            anchor_id,
901            tag,
902        }
903    }
904
905    /// Create a mapping-start event.
906    ///
907    /// # Parameters
908    /// - `style`: block or flow notation.
909    /// - `anchor_id`: anchor defined on this node, or zero for none.
910    /// - `tag`: resolved explicit tag, if present.
911    ///
912    /// # Returns
913    /// A mapping-start event containing the supplied properties.
914    #[must_use]
915    pub fn mapping_start(
916        style: StructureStyle,
917        anchor_id: usize,
918        tag: Option<Cow<'input, Tag>>,
919    ) -> Self {
920        Self::MappingStart {
921            style,
922            anchor_id,
923            tag,
924        }
925    }
926
927    /// Return the anchor ID defined by this event, if any.
928    ///
929    /// Returns `Some(id)` when this event defines an anchor on a scalar, sequence, or mapping
930    /// node, or describes that definition with [`Self::Anchor`]. The reserved ID `0` returns
931    /// `None`. Returns `None` for all other events, including resolved and unresolved aliases
932    /// (which reference anchors rather than defining them; use [`Self::alias_id`] to obtain a
933    /// resolved target anchor ID).
934    /// To count anchored nodes once, also require [`Self::is_node`], since [`Self::Anchor`]
935    /// repeats the node's ID.
936    #[must_use]
937    pub fn anchor_id(&self) -> Option<usize> {
938        match self {
939            Self::Scalar { anchor_id, .. }
940            | Self::SequenceStart { anchor_id, .. }
941            | Self::MappingStart { anchor_id, .. }
942            | Self::Anchor { anchor_id, .. }
943                if *anchor_id != 0 =>
944            {
945                Some(*anchor_id)
946            }
947            _ => None,
948        }
949    }
950
951    /// Return the target anchor ID if this event is a resolved alias.
952    ///
953    /// Returns `None` for unresolved aliases and non-alias events. Use [`Self::is_alias`] to
954    /// recognize either kind of alias, or match [`Self::UnresolvedAlias`] to obtain its name.
955    #[must_use]
956    pub fn alias_id(&self) -> Option<usize> {
957        match self {
958            Self::Alias { anchor_id } => Some(*anchor_id),
959            _ => None,
960        }
961    }
962
963    /// Return whether this event is a resolved or unresolved alias.
964    #[must_use]
965    pub fn is_alias(&self) -> bool {
966        matches!(self, Self::Alias { .. } | Self::UnresolvedAlias { .. })
967    }
968
969    /// Return the resolved tag carried by this node event, if any.
970    #[must_use]
971    pub fn tag(&self) -> Option<&Tag> {
972        match self {
973            Self::Scalar { tag, .. }
974            | Self::SequenceStart { tag, .. }
975            | Self::MappingStart { tag, .. } => tag.as_deref(),
976            _ => None,
977        }
978    }
979
980    /// Return the scalar value and style, if this event is a scalar.
981    #[must_use]
982    pub fn scalar(&self) -> Option<(&str, ScalarStyle)> {
983        match self {
984            Self::Scalar { value, style, .. } => Some((value.as_ref(), *style)),
985            _ => None,
986        }
987    }
988
989    /// Return whether this event represents a YAML node (value).
990    ///
991    /// Returns `true` for scalars, collection starts, and resolved or unresolved aliases, all of
992    /// which occupy a node position. Returns `false` for structural events such as `StreamStart`,
993    /// `DocumentStart`, collection ends, and presentation metadata such as [`Self::Anchor`].
994    #[must_use]
995    pub fn is_node(&self) -> bool {
996        matches!(
997            self,
998            Self::Alias { .. }
999                | Self::UnresolvedAlias { .. }
1000                | Self::Scalar { .. }
1001                | Self::SequenceStart { .. }
1002                | Self::MappingStart { .. }
1003        )
1004    }
1005
1006    /// Create an empty scalar.
1007    fn empty_scalar() -> Self {
1008        // a null scalar
1009        Event::Scalar {
1010            value: "~".into(),
1011            style: ScalarStyle::implicit_plain(),
1012            anchor_id: 0,
1013            tag: None,
1014        }
1015    }
1016
1017    /// Create an empty scalar with the given node properties.
1018    fn empty_scalar_with_anchor(anchor: usize, tag: Option<Cow<'input, Tag>>) -> Self {
1019        let value = if tag.is_some() {
1020            Cow::default()
1021        } else {
1022            "~".into()
1023        };
1024
1025        Event::Scalar {
1026            value,
1027            style: ScalarStyle::implicit_plain(),
1028            anchor_id: anchor,
1029            tag,
1030        }
1031    }
1032}
1033
1034/// Anchor metadata retained until its node event has been returned, including through comments.
1035#[derive(Debug)]
1036struct PendingAnchor<'input> {
1037    id: usize,
1038    name: Cow<'input, str>,
1039    span: Span,
1040    node_emitted: bool,
1041}
1042
1043/// A YAML parser.
1044#[derive(Debug)]
1045#[allow(clippy::struct_excessive_bools)] // Independent parsing policies and state flags.
1046pub struct Parser<'input, T: BorrowedInput<'input>> {
1047    /// The underlying scanner from which we pull tokens.
1048    scanner: Scanner<'input, T>,
1049    /// Whether unknown anchors produce unresolved alias nodes instead of terminal errors.
1050    emit_unresolved_aliases: bool,
1051    /// Whether anchor definition metadata is emitted after the associated node event.
1052    emit_anchor_events: bool,
1053    /// The anchor token waiting for its node, or ready to emit immediately after that node.
1054    pending_anchor: Option<PendingAnchor<'input>>,
1055    /// Maximum number of comments retained while resolving an ambiguous collection entry.
1056    #[cfg(feature = "comments")]
1057    max_buffered_comment_events: usize,
1058    /// Maximum number of simultaneously open block collections.
1059    block_nesting_limit: usize,
1060    /// Number of block collections currently open in the parser state machine.
1061    block_level: usize,
1062    /// The stack of _previous_ states we were in.
1063    ///
1064    /// States are pushed in the context of subobjects to this stack. The top-most element is the
1065    /// state in which to come back to when exiting the current state.
1066    states: Vec<State>,
1067    /// The state in which we currently are.
1068    state: State,
1069    /// The next token from the scanner.
1070    token: Option<QueuedToken<'input>>,
1071    /// The next YAML event to emit.
1072    current: Option<(Event<'input>, Span)>,
1073    /// The next parser error to emit after it has been observed by `peek`.
1074    current_error: Option<ScanError>,
1075    /// A scanner error discovered while ordering events that must be emitted first.
1076    ///
1077    /// Unlike `current_error`, this has not been exposed through `peek`. It is consumed by
1078    /// `next_event_impl` after already-buffered events so `peek`, iteration, and `load` all retain
1079    /// the same ordering.
1080    #[cfg(feature = "comments")]
1081    deferred_error: Option<ScanError>,
1082    /// YAML events buffered by parser states that need to emit an earlier synthetic node first.
1083    #[cfg(feature = "comments")]
1084    queued_events: VecDeque<(Event<'input>, Span)>,
1085    /// Retained storage for collecting and ordering comments between syntax events.
1086    #[cfg(feature = "comments")]
1087    comment_scratch: Vec<(Event<'input>, Span)>,
1088
1089    /// Pending indentation hint to be attached to the next emitted event span.
1090    ///
1091    /// This is used to communicate indentation for block mapping keys. It is set when consuming a
1092    /// `TokenType::Key` in block style, and is applied to the next emitted node event (the key
1093    /// itself).
1094    pending_key_indent: Option<usize>,
1095    /// Pending anchor ID to attach to a node after an intervening comment.
1096    /// `Some(0)` retains an anchor property when the anchor offset is zero.
1097    #[cfg(feature = "comments")]
1098    pending_node_anchor_id: Option<usize>,
1099    /// Pending tag to attach to a node after an intervening comment.
1100    #[cfg(feature = "comments")]
1101    pending_node_tag: Option<Cow<'input, Tag>>,
1102    /// Pending explicit tag token start and raw length after an intervening comment.
1103    #[cfg(feature = "comments")]
1104    pending_node_tag_span: Option<(Marker, u32)>,
1105    /// Pending end marker of the last node-property token before an intervening comment.
1106    #[cfg(feature = "comments")]
1107    pending_node_property_end: Option<Marker>,
1108    /// Pending empty scalar span captured before an intervening comment.
1109    pending_empty_scalar_span: Option<Span>,
1110    /// End marker of the most recently produced non-metadata event.
1111    ///
1112    /// Synthetic syntax events use this marker, so presentation metadata must not affect it.
1113    last_non_comment_event_end: Option<Marker>,
1114    /// Pending YAML version captured before comments preceding an explicit document start.
1115    #[cfg(feature = "comments")]
1116    pending_document_version: Option<YamlVersion>,
1117    /// Whether document directives were already initialized before comments preceding `---`.
1118    #[cfg(feature = "comments")]
1119    pending_document_directives: bool,
1120    /// `%TAG` handles already seen before comments preceding an explicit document start.
1121    #[cfg(feature = "comments")]
1122    pending_document_tag_handles: BTreeSet<Cow<'input, str>>,
1123    /// Anchors that have been encountered in the YAML document.
1124    anchors: BTreeMap<Cow<'input, str>, usize>,
1125    /// Next ID available for an anchor.
1126    ///
1127    /// Every anchor is given a unique ID. We use an incrementing ID and this is both the ID to
1128    /// return for the next anchor and the count of anchor IDs emitted.
1129    anchor_id_count: usize,
1130    /// The tag directives (`%TAG`) the parser has encountered.
1131    ///
1132    /// Key is the handle, and value is the prefix.
1133    tags: BTreeMap<Cow<'input, str>, Cow<'input, str>>,
1134    /// Whether we have emitted a terminal iterator result.
1135    ///
1136    /// Terminal means either [`Event::StreamEnd`] or a [`ScanError`]. Emitted means that it has
1137    /// been returned from [`Self::next_event`] or [`Self::next`]. If the terminal result is stored
1138    /// in [`Self::current`], [`Self::current_error`], or internal comment buffers, this is set to
1139    /// `false`.
1140    stream_end_emitted: bool,
1141    /// Whether parsing stopped on an error, including an error observed only through `peek`.
1142    failed: bool,
1143    /// Whether the current document has ended without starting the next one yet.
1144    at_document_end: bool,
1145    /// Make tags global across all documents.
1146    keep_tags: bool,
1147}
1148
1149/// Trait to be implemented in order to use the low-level parsing API.
1150///
1151/// The low-level parsing API is event-based (a push parser), calling [`EventReceiver::on_event`]
1152/// for each YAML [`Event`] that occurs.
1153/// The [`EventReceiver`] trait only receives events. In order to receive both events and their
1154/// location in the source, use [`SpannedEventReceiver`]. Note that [`EventReceiver`]s implement
1155/// [`SpannedEventReceiver`] automatically.
1156/// With the `comments` feature, non-spanned receivers receive `Event::Comment { value: text, placement }` like any
1157/// other event, but without source location. Spanned receivers receive the same comment event plus
1158/// the comment [`Span`] in [`SpannedEventReceiver::on_event`]. For comments, that span covers the
1159/// whole source comment, including `#` and excluding the line break. When parsing from an input
1160/// with byte offsets, such as [`Parser::new_from_str`], [`Span::slice`] returns that source
1161/// comment text.
1162///
1163/// # Event hierarchy
1164/// The event stream starts with an [`Event::StreamStart`] event followed by an
1165/// [`Event::DocumentStart`] event. If the YAML document starts with a mapping (an object), an
1166/// [`Event::MappingStart`] event is emitted. If it starts with a sequence (an array), an
1167/// [`Event::SequenceStart`] event is emitted. Otherwise, an [`Event::Scalar`] event is emitted.
1168///
1169/// In a mapping, key-values are sent as consecutive data events. Comments can appear in the raw
1170/// event stream between a key and its value; they are presentation metadata, not YAML data nodes.
1171/// Consumers building YAML data trees should ignore `Event::Comment` and [`Event::Anchor`].
1172/// With [`Options::emit_anchor_events`], anchor metadata immediately follows its scalar or
1173/// collection-start event and carries the same ID plus the original name and anchor-token span.
1174/// Any key/value alternation shortcut applies only after filtering out comments and other
1175/// presentation metadata. After that
1176/// filtering, the first event after an [`Event::MappingStart`] will be the key, and the following
1177/// event will be its value. If the mapping contains no sub-mapping or sub-sequence, then even events
1178/// (starting from 0) will always be keys and odd ones will always be values. The mapping ends when
1179/// an [`Event::MappingEnd`] event is received.
1180///
1181/// In a sequence, values are sent consecutively until the [`Event::SequenceEnd`] event.
1182///
1183/// If a value is a sub-mapping or a sub-sequence, an [`Event::MappingStart`] or
1184/// [`Event::SequenceStart`] event will be sent respectively. Following events until the associated
1185/// [`Event::MappingEnd`] or [`Event::SequenceEnd`] (beware of nested mappings or sequences) will
1186/// be part of the value and not another key-value pair or element in the sequence.
1187///
1188/// For instance, the following YAML:
1189/// ```yaml
1190/// a: b
1191/// c:
1192///   d: e
1193/// f:
1194///   - g
1195///   - h
1196/// ```
1197/// will emit (indented and commented for visibility):
1198/// ```text
1199/// StreamStart, DocumentStart, MappingStart,
1200///   Scalar("a", ..), Scalar("b", ..)
1201///   Scalar("c", ..), MappingStart, Scalar("d", ..), Scalar("e", ..), MappingEnd,
1202///   Scalar("f", ..), SequenceStart, Scalar("g", ..), Scalar("h", ..), SequenceEnd,
1203/// MappingEnd, DocumentEnd, StreamEnd
1204/// ```
1205///
1206/// # Example
1207/// ```
1208/// # use granit_parser::{Event, EventReceiver, Parser};
1209/// #
1210/// /// Sink of events. Collects them into an array.
1211/// struct EventSink<'input> {
1212///     events: Vec<Event<'input>>,
1213/// }
1214///
1215/// /// Implement `on_event`, pushing into `self.events`.
1216/// impl<'input> EventReceiver<'input> for EventSink<'input> {
1217///     fn on_event(&mut self, ev: Event<'input>) {
1218///         self.events.push(ev);
1219///     }
1220/// }
1221///
1222/// /// Load events from a YAML string.
1223/// fn str_to_events(yaml: &str) -> Vec<Event<'_>> {
1224///     let mut sink = EventSink { events: Vec::new() };
1225///     let mut parser = Parser::new_from_str(yaml);
1226///     // Load events using our sink as the receiver.
1227///     parser.load(&mut sink, true).unwrap();
1228///     sink.events
1229/// }
1230/// ```
1231pub trait EventReceiver<'input> {
1232    /// Handler called for each YAML event that is emitted by the parser.
1233    fn on_event(&mut self, ev: Event<'input>);
1234}
1235
1236/// Trait to be implemented for using the low-level parsing API.
1237///
1238/// Functionally similar to [`EventReceiver`], but receives a [`Span`] as well as the event.
1239/// With the `comments` feature, an `Event::Comment` span is the source range of the whole comment.
1240pub trait SpannedEventReceiver<'input> {
1241    /// Handler called for each event that occurs.
1242    fn on_event(&mut self, ev: Event<'input>, span: Span);
1243}
1244
1245impl<'input, R: EventReceiver<'input>> SpannedEventReceiver<'input> for R {
1246    fn on_event(&mut self, ev: Event<'input>, _span: Span) {
1247        self.on_event(ev);
1248    }
1249}
1250
1251/// Trait to be implemented for fallible event handling without source spans.
1252///
1253/// This is the fallible counterpart to [`EventReceiver`]. Use it with [`Parser::try_load`] when
1254/// event handling may need to stop parsing by returning an application error.
1255pub trait TryEventReceiver<'input> {
1256    /// Error returned by this receiver.
1257    type Error;
1258
1259    /// Handler called for each YAML event that is emitted by the parser.
1260    ///
1261    /// Returning an error stops [`Parser::try_load`] immediately.
1262    ///
1263    /// # Errors
1264    /// Returns `Self::Error` when the receiver wants to stop parsing.
1265    fn on_event(&mut self, ev: Event<'input>) -> Result<(), Self::Error>;
1266}
1267
1268/// Trait to be implemented for fallible event handling with source spans.
1269///
1270/// This is the fallible counterpart to [`SpannedEventReceiver`]. Use it with
1271/// [`Parser::try_load`] when event handling may need to stop parsing by returning an application
1272/// error.
1273pub trait TrySpannedEventReceiver<'input> {
1274    /// Error returned by this receiver.
1275    type Error;
1276
1277    /// Handler called for each event that occurs.
1278    ///
1279    /// Returning an error stops [`Parser::try_load`] immediately.
1280    ///
1281    /// # Errors
1282    /// Returns `Self::Error` when the receiver wants to stop parsing.
1283    fn on_event(&mut self, ev: Event<'input>, span: Span) -> Result<(), Self::Error>;
1284}
1285
1286impl<'input, R: TryEventReceiver<'input>> TrySpannedEventReceiver<'input> for R {
1287    type Error = R::Error;
1288
1289    fn on_event(&mut self, ev: Event<'input>, _span: Span) -> Result<(), Self::Error> {
1290        TryEventReceiver::on_event(self, ev)
1291    }
1292}
1293
1294/// Error returned by [`Parser::try_load`] and [`ParserTrait::try_load`].
1295#[derive(Clone, PartialEq, Debug, Eq)]
1296pub enum TryLoadError<E> {
1297    /// Scanning or parsing failed.
1298    Scan(
1299        /// The scanner or parser error.
1300        ScanError,
1301    ),
1302    /// The receiver returned an application error.
1303    Receiver(
1304        /// The error returned by the receiver.
1305        E,
1306    ),
1307}
1308
1309impl<E> TryLoadError<E> {
1310    #[cold]
1311    fn scan(error: ScanError) -> Self {
1312        Self::Scan(error)
1313    }
1314
1315    #[cold]
1316    fn receiver(error: E) -> Self {
1317        Self::Receiver(error)
1318    }
1319}
1320
1321impl<E> From<ScanError> for TryLoadError<E> {
1322    #[cold]
1323    fn from(error: ScanError) -> Self {
1324        Self::scan(error)
1325    }
1326}
1327
1328impl<E: Display> Display for TryLoadError<E> {
1329    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1330        match self {
1331            Self::Scan(error) => write!(f, "parser error: {error}"),
1332            Self::Receiver(error) => write!(f, "receiver error: {error}"),
1333        }
1334    }
1335}
1336
1337impl<E> core::error::Error for TryLoadError<E>
1338where
1339    E: core::error::Error + 'static,
1340{
1341    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
1342        match self {
1343            Self::Scan(error) => Some(error),
1344            Self::Receiver(error) => Some(error),
1345        }
1346    }
1347}
1348
1349fn try_emit<'input, R>(
1350    recv: &mut R,
1351    ev: Event<'input>,
1352    span: Span,
1353) -> Result<(), TryLoadError<R::Error>>
1354where
1355    R: TrySpannedEventReceiver<'input>,
1356{
1357    recv.on_event(ev, span).map_err(TryLoadError::receiver)
1358}
1359
1360struct InfallibleSpannedReceiver<'receiver, R>(&'receiver mut R);
1361
1362impl<'input, R: SpannedEventReceiver<'input>> TrySpannedEventReceiver<'input>
1363    for InfallibleSpannedReceiver<'_, R>
1364{
1365    type Error = Infallible;
1366
1367    fn on_event(&mut self, ev: Event<'input>, span: Span) -> Result<(), Self::Error> {
1368        self.0.on_event(ev, span);
1369        Ok(())
1370    }
1371}
1372
1373fn into_scan_result(result: Result<(), TryLoadError<Infallible>>) -> Result<(), ScanError> {
1374    match result {
1375        Ok(()) => Ok(()),
1376        Err(TryLoadError::Scan(error)) => error.into_result(),
1377        Err(TryLoadError::Receiver(error)) => match error {},
1378    }
1379}
1380
1381/// A convenience alias for a parser event result.
1382pub type ParseResult<'input> = Result<(Event<'input>, Span), ScanError>;
1383
1384/// Trait extracted from `Parser` to support mocking and alternative implementations.
1385pub trait ParserTrait<'input> {
1386    /// Try to load the next event and return it without consuming it from `self`.
1387    fn peek(&mut self) -> Option<Result<&(Event<'input>, Span), ScanError>>;
1388
1389    /// Try to load the next event and return it, consuming it from `self`.
1390    fn next_event(&mut self) -> Option<ParseResult<'input>>;
1391
1392    /// Load the YAML from the stream in `self`, pushing events into `recv`.
1393    ///
1394    /// Use this method when event handling is infallible. If receiver code can return an
1395    /// application error and should stop parsing, use [`ParserTrait::try_load`] instead. If the
1396    /// caller should directly control when the next event is read, use [`ParserTrait::next_event`]
1397    /// or [`Parser`]'s [`core::iter::Iterator`] implementation.
1398    ///
1399    /// After a scan error, the parser is exhausted: [`ParserTrait::peek`] and
1400    /// [`ParserTrait::next_event`] return [`None`], and further calls to `load` or
1401    /// [`ParserTrait::try_load`] return `Ok(())` without emitting events.
1402    ///
1403    /// # Errors
1404    /// Returns `ScanError` when scanning or parsing the stream fails.
1405    fn load<R: SpannedEventReceiver<'input>>(
1406        &mut self,
1407        recv: &mut R,
1408        multi: bool,
1409    ) -> Result<(), ScanError>;
1410
1411    /// Load the YAML from the stream in `self`, stopping if `recv` returns an error.
1412    ///
1413    /// If `multi` is set to `true`, the parser will allow parsing of multiple YAML documents
1414    /// inside the stream.
1415    ///
1416    /// If the receiver returns an error, the parser is left positioned immediately after the event
1417    /// that caused the receiver error. Callers should treat the parser as partially consumed.
1418    ///
1419    /// After a scan error, the parser is exhausted: [`ParserTrait::peek`] and
1420    /// [`ParserTrait::next_event`] return [`None`], and further calls to `try_load` or
1421    /// [`ParserTrait::load`] return `Ok(())` without emitting events.
1422    ///
1423    /// # Errors
1424    /// Returns [`TryLoadError::Scan`] when scanning or parsing the stream fails. Returns
1425    /// [`TryLoadError::Receiver`] when `recv` returns an error.
1426    fn try_load<R: TrySpannedEventReceiver<'input>>(
1427        &mut self,
1428        recv: &mut R,
1429        multi: bool,
1430    ) -> Result<(), TryLoadError<R::Error>> {
1431        while let Some(res) = self.next_event() {
1432            let (ev, span) = res?;
1433            let is_doc_end = matches!(ev, Event::DocumentEnd { .. });
1434            let is_stream_end = matches!(ev, Event::StreamEnd);
1435
1436            try_emit(recv, ev, span)?;
1437
1438            if is_stream_end {
1439                break;
1440            }
1441            if !multi && is_doc_end {
1442                break;
1443            }
1444        }
1445
1446        Ok(())
1447    }
1448}
1449
1450impl<'input> Parser<'input, StrInput<'input>> {
1451    /// Create a parser over a borrowed string slice.
1452    ///
1453    /// Every emitted event span has UTF-8 byte offsets into `value`:
1454    /// [`Span::byte_range`] returns `Some(start..end)`, with ordered, in-bounds UTF-8
1455    /// boundaries. This includes zero-length spans for implicit events and end-of-input.
1456    /// [`Span::slice`] returns `Some` when given the same, unchanged source string.
1457    ///
1458    /// This guarantee applies to spans as emitted, before callers modify their markers.
1459    /// Byte offsets remain optional in [`Span`] because other inputs, such as
1460    /// [`Self::new_from_iter`], do not provide them. Missing offsets must not be replaced
1461    /// with zero or with [`Marker::index`], which counts characters rather than bytes.
1462    #[must_use]
1463    pub fn new_from_str(value: &'input str) -> Self {
1464        Self::new_from_str_with_options(value, Options::default())
1465    }
1466
1467    /// Create a parser over a borrowed string slice with configurable behavior and resource
1468    /// limits.
1469    ///
1470    /// The byte-offset guarantee of [`Self::new_from_str`] also applies with custom options.
1471    #[must_use]
1472    pub fn new_from_str_with_options(value: &'input str, options: Options) -> Self {
1473        Parser::with_options(StrInput::new(value), options)
1474    }
1475}
1476
1477impl<T> Parser<'static, BufferedInput<T>>
1478where
1479    T: Iterator<Item = char>,
1480{
1481    /// Create a parser over an iterator of characters.
1482    #[must_use]
1483    pub fn new_from_iter(iter: T) -> Self {
1484        Self::new_from_iter_with_options(iter, Options::default())
1485    }
1486
1487    /// Create a parser over an iterator of characters with configurable behavior and resource
1488    /// limits.
1489    #[must_use]
1490    pub fn new_from_iter_with_options(iter: T, options: Options) -> Self {
1491        Parser::with_options(BufferedInput::new(iter), options)
1492    }
1493}
1494
1495impl<T> Parser<'static, FallibleBufferedInput<T>>
1496where
1497    T: Iterator<Item = Result<char, ErrorKind>>,
1498{
1499    /// Create a parser over a fallible iterator of characters.
1500    ///
1501    /// The iterator's `None` return value means clean end-of-input. An `Err` item reports a
1502    /// terminal source failure and is returned by the parser as a [`ScanError`] carrying the same
1503    /// [`ErrorKind`]. The iterator is not polled again after its first error.
1504    #[must_use]
1505    pub fn new_from_fallible_iter(iter: T) -> Self {
1506        Self::new_from_fallible_iter_with_options(iter, Options::default())
1507    }
1508
1509    /// Create a parser over a fallible iterator of characters with configurable behavior and
1510    /// resource limits.
1511    ///
1512    /// The iterator's `None` return value means clean end-of-input. An `Err` item reports a
1513    /// terminal source failure and is returned by the parser as a [`ScanError`] carrying the same
1514    /// [`ErrorKind`]. The iterator is not polled again after its first error.
1515    #[must_use]
1516    pub fn new_from_fallible_iter_with_options(iter: T, options: Options) -> Self {
1517        Parser::with_options(FallibleBufferedInput::new(iter), options)
1518    }
1519}
1520
1521impl<'input, T: BorrowedInput<'input>> Parser<'input, T> {
1522    /// Return the next anchor ID that will be assigned by this parser.
1523    #[must_use]
1524    pub fn anchor_offset(&self) -> usize {
1525        self.anchor_id_count
1526    }
1527
1528    /// Set the next anchor ID that will be assigned by this parser.
1529    pub fn set_anchor_offset(&mut self, offset: usize) {
1530        self.anchor_id_count = offset;
1531    }
1532
1533    /// Create a parser over a custom input source.
1534    #[must_use]
1535    pub fn new(src: T) -> Self {
1536        Self::with_options(src, Options::default())
1537    }
1538
1539    /// Create a parser over a custom input source with configurable behavior and resource limits.
1540    ///
1541    /// Use [`crate::options!`] to construct `options` without depending on exhaustive struct
1542    /// literal syntax.
1543    /// Without the `comments` feature, comment capture and emission are compiled out of both
1544    /// the parser and its scanner. YAML comments are still skipped and validated.
1545    #[must_use]
1546    pub fn with_options(src: T, options: Options) -> Self {
1547        #[cfg(feature = "comments")]
1548        let max_buffered_comment_events = options.max_buffered_comment_events;
1549        let block_nesting_limit = options.block_nesting_limit;
1550        let emit_unresolved_aliases = options.emit_unresolved_aliases;
1551        let emit_anchor_events = options.emit_anchor_events;
1552        let scanner = Scanner::with_options(src, options);
1553
1554        Parser {
1555            scanner,
1556            emit_unresolved_aliases,
1557            emit_anchor_events,
1558            pending_anchor: None,
1559            #[cfg(feature = "comments")]
1560            max_buffered_comment_events,
1561            block_nesting_limit,
1562            block_level: 0,
1563            states: Vec::new(),
1564            state: State::StreamStart,
1565            token: None,
1566            current: None,
1567            current_error: None,
1568            #[cfg(feature = "comments")]
1569            deferred_error: None,
1570            #[cfg(feature = "comments")]
1571            queued_events: VecDeque::new(),
1572            #[cfg(feature = "comments")]
1573            comment_scratch: Vec::new(),
1574
1575            pending_key_indent: None,
1576            #[cfg(feature = "comments")]
1577            pending_node_anchor_id: None,
1578            #[cfg(feature = "comments")]
1579            pending_node_tag: None,
1580            #[cfg(feature = "comments")]
1581            pending_node_tag_span: None,
1582            #[cfg(feature = "comments")]
1583            pending_node_property_end: None,
1584            pending_empty_scalar_span: None,
1585            last_non_comment_event_end: None,
1586            #[cfg(feature = "comments")]
1587            pending_document_version: None,
1588            #[cfg(feature = "comments")]
1589            pending_document_directives: false,
1590            #[cfg(feature = "comments")]
1591            pending_document_tag_handles: BTreeSet::new(),
1592
1593            anchors: BTreeMap::new(),
1594            // valid anchor_id starts from 1
1595            anchor_id_count: 1,
1596            tags: BTreeMap::new(),
1597            stream_end_emitted: false,
1598            failed: false,
1599            at_document_end: false,
1600            keep_tags: false,
1601        }
1602    }
1603
1604    /// Configure whether tag directives remain active across document boundaries.
1605    ///
1606    /// This behavior is non-standard as per the YAML specification but can be encountered in the
1607    /// wild. Passing `true` enables this non-standard extension and allows the parser to accept
1608    /// input from [test
1609    /// QLJ7](https://github.com/yaml/yaml-test-suite/blob/ccfa74e56afb53da960847ff6e6976c0a0825709/src/QLJ7.yaml)
1610    /// of the yaml-test-suite:
1611    ///
1612    /// ```yaml
1613    /// %TAG !prefix! tag:example.com,2011:
1614    /// --- !prefix!A
1615    /// a: b
1616    /// --- !prefix!B
1617    /// c: d
1618    /// --- !prefix!C
1619    /// e: f
1620    /// ```
1621    ///
1622    /// With `keep_tags` set to `false`, the above YAML is rejected. As per the specification, tags
1623    /// only apply to the document immediately following them. This would error on `!prefix!B`.
1624    ///
1625    /// With `keep_tags` set to `true`, the above YAML is accepted by the parser.
1626    #[must_use]
1627    pub fn keep_tags(mut self, value: bool) -> Self {
1628        self.keep_tags = value;
1629        self
1630    }
1631
1632    /// Try to load the next event and return it without consuming it from `self`.
1633    ///
1634    /// Any subsequent call to [`Parser::peek`] will return the same value, until a call to
1635    /// [`Iterator::next`], [`Parser::load`], or [`Self::proceed_next_document`].
1636    /// If the buffered value is a [`ScanError`], [`Parser::next_event`] returns that error once
1637    /// and then the parser is exhausted.
1638    ///
1639    /// # Errors
1640    /// Returns `ScanError` when loading the next event fails.
1641    pub fn peek(&mut self) -> Option<Result<&(Event<'input>, Span), ScanError>> {
1642        ParserTrait::peek(self)
1643    }
1644
1645    /// Try to load the next event and return it, consuming it from `self`.
1646    ///
1647    /// After this returns a [`ScanError`], subsequent calls return [`None`] unless
1648    /// [`Self::proceed_next_document`] is called to recover at a document boundary.
1649    ///
1650    /// # Errors
1651    /// Returns `ScanError` when loading the next event fails.
1652    pub fn next_event(&mut self) -> Option<ParseResult<'input>> {
1653        ParserTrait::next_event(self)
1654    }
1655
1656    /// Abandon the current document and resume at the next document boundary.
1657    ///
1658    /// This can be called after an error from iteration, [`Self::peek`], or [`Self::load`], or
1659    /// during successful parsing to skip the remainder of a document. Before parsing starts it
1660    /// skips the first document. Immediately after [`Event::DocumentEnd`] it leaves the next
1661    /// document ready to read. Repeated calls skip successive documents.
1662    ///
1663    /// Returns `true` when another document remains, including an empty or malformed document,
1664    /// and `false` at clean EOF. This looks past inter-document comments and end markers without
1665    /// consuming the next document's events. Comments inspected by this lookahead are buffered
1666    /// for subsequent reads; with comment emission enabled, the configured comment-buffer limit
1667    /// applies. Syntax errors encountered in the next document remain available to normal parsing.
1668    ///
1669    /// Read subsequent events using the usual parser methods. They start with the next
1670    /// [`Event::DocumentStart`] (possibly preceded by comments), or [`Event::StreamEnd`] if no
1671    /// document remains. An already consumed stream end stays exhausted. This method does not
1672    /// emit another [`Event::StreamStart`].
1673    ///
1674    /// After a syntax error, recovery scans forward from the scanner's current position to a
1675    /// separated `---` or valid `...` at column zero, or EOF. An explicit end marker also permits
1676    /// a following implicit document and its directive prefix. Indented markers, inline markers,
1677    /// and scalar text such as `---suffix` are not synchronization points. Input is never rewound;
1678    /// event spans retain their original source positions.
1679    /// If a directive prefix fails before its opening `---`, that document's body is skipped too.
1680    ///
1681    /// Open collections, buffered events/comments, and anchor definitions of an abandoned
1682    /// document are discarded. No synthetic collection ends, document end, or error node are
1683    /// emitted for it: consumers building a tree must abandon or mark their own partial nodes.
1684    /// Anchor IDs remain unique across documents. Directives are reset as at a normal document
1685    /// boundary, including the [`Self::keep_tags`] policy.
1686    ///
1687    /// Skipped syntax errors are suppressed. Recovery does not repair content within a document,
1688    /// preserve its anchors for another document, or validate the next document in advance.
1689    /// Ordinary parsing still stops at the first error unless this method is explicitly called.
1690    /// Scanning moves forward with work proportional to the skipped input; no diagnostic list
1691    /// is accumulated. Cancellation can be supplied through a fallible input source.
1692    ///
1693    /// # Example
1694    /// ```
1695    /// use granit_parser::{Event, Parser};
1696    /// # fn main() -> Result<(), granit_parser::ScanError> {
1697    /// let mut parser = Parser::new_from_str("broken: [1, 2\n---\nhealthy: true\n");
1698    /// let error = parser.by_ref().find_map(Result::err).unwrap();
1699    /// assert!(parser.next().is_none());
1700    /// // Record the diagnostic and abandon any open nodes in the consumer's partial tree.
1701    /// assert!(parser.proceed_next_document()?);
1702    /// assert!(matches!(parser.next().unwrap()?.0, Event::DocumentStart { explicit: true, .. }));
1703    /// let rest = parser.collect::<Result<Vec<_>, _>>()?;
1704    /// assert!(rest.iter().any(|(event, _)| event.scalar().is_some_and(|(v, _)| v == "healthy")));
1705    /// # Ok(())
1706    /// # }
1707    /// ```
1708    ///
1709    /// # Errors
1710    /// Returns a source failure (including I/O, decoding, or cancellation errors supplied by the
1711    /// input). Source failures cannot be recovered and leave the parser exhausted.
1712    /// With comment emission enabled, also returns `ErrorKind::TooManyComments` if looking ahead
1713    /// would exceed the comment-buffer limit; parsing then stays exhausted until recovery is
1714    /// requested again.
1715    pub fn proceed_next_document(&mut self) -> Result<bool, ScanError> {
1716        // A consumed StreamEnd stays exhausted. A terminal error still needs recovery below.
1717        if self.stream_end_emitted && !self.failed {
1718            return Ok(false);
1719        }
1720
1721        self.skip_document()?;
1722        let result = self.next_document_exists();
1723        match result {
1724            Ok(false) => {
1725                // Stay between documents so repeated calls preserve unread trailing comments
1726                // as well as StreamEnd instead of consuming them in the skip loop.
1727                self.at_document_end = true;
1728            }
1729            Err(_) => {
1730                self.current = None;
1731                self.current_error = None;
1732                #[cfg(feature = "comments")]
1733                {
1734                    self.queued_events.clear();
1735                    self.comment_scratch.clear();
1736                    self.deferred_error = None;
1737                }
1738                self.failed = true;
1739                self.stream_end_emitted = true;
1740            }
1741            Ok(true) => {}
1742        }
1743        result
1744    }
1745
1746    fn skip_document(&mut self) -> Result<(), ScanError> {
1747        loop {
1748            if !self.failed {
1749                if self.at_document_end {
1750                    // The boundary was already reached, possibly by peek(). Discard its cached
1751                    // end event and let another proceed call skip the following document.
1752                    if matches!(self.current, Some((Event::DocumentEnd { .. }, _))) {
1753                        self.current = None;
1754                    }
1755                    self.at_document_end = false;
1756                    return Ok(());
1757                }
1758                // While the grammar state is valid, consume events through the current document.
1759                // If parsing fails, next_event_impl records the failure and we synchronize below.
1760                loop {
1761                    match self.next_event_impl() {
1762                        Ok((Event::DocumentEnd { .. }, _)) => {
1763                            self.at_document_end = false;
1764                            return Ok(());
1765                        }
1766                        Ok(event @ (Event::StreamEnd, _)) => {
1767                            // Leave EOF available for the caller's next read, just like peek().
1768                            self.current = Some(event);
1769                            return Ok(());
1770                        }
1771                        Ok(_) => {}
1772                        Err(_) => break,
1773                    }
1774                }
1775            }
1776
1777            // A directive belongs to the document whose opening marker follows it. Abandon
1778            // that body as well, rather than accepting it after silently dropping its header.
1779            let failed_header = matches!(
1780                self.state,
1781                State::ImplicitDocumentStart | State::DocumentStart
1782            ) && self.scanner.in_directive_prefix();
1783            // Discard the failed grammar state and seek a boundary, retaining any marker that
1784            // lookahead already consumed. Source failures propagate instead of becoming EOF.
1785            self.recover_document()?;
1786            if !failed_header || !matches!(self.peek_token()?.1, QueuedTokenType::DocumentStart) {
1787                return Ok(());
1788            }
1789            // This opening marker belongs to the failed header. Loop to skip its body too.
1790        }
1791    }
1792
1793    /// Probe only the next document's prefix, retaining comments and any syntax error for readers.
1794    fn next_document_exists(&mut self) -> Result<bool, ScanError> {
1795        if matches!(self.current, Some((Event::StreamEnd, _))) {
1796            return Ok(false);
1797        }
1798
1799        #[cfg(feature = "comments")]
1800        if self.has_pending_document_directives() {
1801            // A header paused at a comment already establishes document presence. Leave EOF
1802            // or an invalid end marker for normal parsing, but retain terminal source failures.
1803            self.scanner.check_source_error()?;
1804            return Ok(true);
1805        }
1806
1807        loop {
1808            let token = match self.peek_token() {
1809                Ok(token) => token,
1810                Err(error) => {
1811                    // Source failures can carry any ErrorKind. Consult the scanner's source
1812                    // latch rather than classifying the error by its kind.
1813                    self.scanner.check_source_error()?;
1814                    #[cfg(feature = "comments")]
1815                    {
1816                        self.deferred_error = Some(error);
1817                    }
1818                    #[cfg(not(feature = "comments"))]
1819                    {
1820                        self.current_error = Some(error);
1821                        self.failed = true;
1822                    }
1823                    return Ok(true);
1824                }
1825            };
1826            match token.1 {
1827                QueuedTokenType::StreamEnd => return Ok(false),
1828                QueuedTokenType::DocumentEnd => self.skip(),
1829                #[cfg(feature = "comments")]
1830                QueuedTokenType::Comment(_) => {
1831                    let mark = token.0.start;
1832                    if self.queued_events.len() >= self.max_buffered_comment_events {
1833                        return Err(ScanError::from_kind(mark, ErrorKind::TooManyComments));
1834                    }
1835                    let comment = self
1836                        .next_comment_event()?
1837                        .expect("comment token disappeared after peek");
1838                    self.queued_events.push_back(comment);
1839                }
1840                _ => return Ok(true),
1841            }
1842        }
1843    }
1844
1845    fn recover_document(&mut self) -> Result<(), ScanError> {
1846        let result = self.scanner.proceed_next_document(self.token.take());
1847        self.current = None;
1848        self.current_error = None;
1849        self.pending_anchor = None;
1850        if let Err(error) = result {
1851            self.stream_end_emitted = true;
1852            return Err(error);
1853        }
1854
1855        self.states.clear();
1856        self.state = State::ImplicitDocumentStart;
1857        self.block_level = 0;
1858        self.pending_key_indent = None;
1859        self.pending_empty_scalar_span = None;
1860        self.last_non_comment_event_end = None;
1861        #[cfg(feature = "comments")]
1862        {
1863            self.deferred_error = None;
1864            self.queued_events.clear();
1865            self.comment_scratch.clear();
1866            self.pending_node_anchor_id = None;
1867            self.pending_node_tag = None;
1868            self.pending_node_tag_span = None;
1869            self.pending_node_property_end = None;
1870            self.pending_document_version = None;
1871            self.pending_document_directives = false;
1872            self.pending_document_tag_handles.clear();
1873        }
1874        self.anchors.clear();
1875        self.clear_document_tags();
1876        self.failed = false;
1877        self.at_document_end = false;
1878        self.stream_end_emitted = false;
1879        Ok(())
1880    }
1881
1882    /// Implementation function for [`Self::next_event`] without the `Option`.
1883    ///
1884    /// [`Self::next_event`] should conform to the expectations of an [`Iterator`] and return an
1885    /// option. This burdens the parser code. This function is used internally when an option is
1886    /// undesirable.
1887    fn next_event_impl<'a>(&mut self) -> ParseResult<'a>
1888    where
1889        'input: 'a,
1890    {
1891        let result = self.next_event_inner();
1892        if result.is_err() {
1893            self.failed = true;
1894        }
1895        result
1896    }
1897
1898    fn next_event_inner<'a>(&mut self) -> ParseResult<'a>
1899    where
1900        'input: 'a,
1901    {
1902        let event = match self.current.take() {
1903            None if self
1904                .pending_anchor
1905                .as_ref()
1906                .is_some_and(|anchor| anchor.node_emitted) =>
1907            {
1908                let anchor = self
1909                    .pending_anchor
1910                    .take()
1911                    .expect("anchor metadata is ready");
1912                Ok((
1913                    Event::Anchor {
1914                        anchor_id: anchor.id,
1915                        name: anchor.name,
1916                    },
1917                    anchor.span,
1918                ))
1919            }
1920            None => {
1921                #[cfg(feature = "comments")]
1922                {
1923                    if let Some(event) = self.queued_events.pop_front() {
1924                        Ok(self.apply_pending_key_indent(event))
1925                    } else if let Some(error) = self.deferred_error.take() {
1926                        return Err(error);
1927                    } else if self.state == State::End {
1928                        self.parse()
1929                    } else if let Some(comment) = self.maybe_next_comment_event()? {
1930                        Ok(comment)
1931                    } else {
1932                        self.parse()
1933                    }
1934                }
1935                #[cfg(not(feature = "comments"))]
1936                {
1937                    self.parse()
1938                }
1939            }
1940            Some(v) => Ok(v),
1941        }?;
1942
1943        // A node can be buffered behind comments. Wait until that exact node reaches the public
1944        // event stream before emitting its metadata, ahead of any further comments or children.
1945        if let Some(anchor) = &mut self.pending_anchor {
1946            anchor.node_emitted |= matches!(
1947                &event.0,
1948                Event::Scalar { anchor_id: id, .. }
1949                    | Event::SequenceStart { anchor_id: id, .. }
1950                    | Event::MappingStart { anchor_id: id, .. }
1951                    if *id == anchor.id
1952            );
1953        }
1954
1955        Ok(self.remember_non_comment_event_end(event))
1956    }
1957
1958    /// Load the next event for [`ParserTrait::try_load`], exhausting the parser on a scan error.
1959    ///
1960    /// A scan error can interrupt a state transition, so the state machine must never run again
1961    /// afterwards. [`ParserTrait::next_event`] latches this itself; `try_load` bypasses it to
1962    /// avoid the `Option` wrapper and needs the same latch.
1963    fn next_event_for_load<'a>(&mut self) -> ParseResult<'a>
1964    where
1965        'input: 'a,
1966    {
1967        let result = self.next_event_impl();
1968        if result.is_err() {
1969            self.stream_end_emitted = true;
1970        }
1971        result
1972    }
1973
1974    fn apply_pending_key_indent<'a>(&mut self, (ev, span): (Event<'a>, Span)) -> (Event<'a>, Span) {
1975        if ev.is_node() {
1976            if let Some(indent) = self.pending_key_indent.take() {
1977                return (ev, span.with_indent(Some(indent)));
1978            }
1979        }
1980
1981        (ev, span)
1982    }
1983
1984    fn remember_non_comment_event_end<'a>(
1985        &mut self,
1986        (event, span): (Event<'a>, Span),
1987    ) -> (Event<'a>, Span) {
1988        if matches!(event, Event::Anchor { .. }) {
1989            return (event, span);
1990        }
1991        #[cfg(feature = "comments")]
1992        if matches!(event, Event::Comment { .. }) {
1993            return (event, span);
1994        }
1995        self.last_non_comment_event_end = Some(span.end);
1996        if matches!(
1997            event,
1998            Event::DocumentStart { .. } | Event::DocumentEnd { .. }
1999        ) {
2000            self.at_document_end = matches!(event, Event::DocumentEnd { .. });
2001        }
2002        (event, span)
2003    }
2004
2005    /// Peek at the next token from the scanner.
2006    fn peek_token(&mut self) -> Result<&QueuedToken<'_>, ScanError> {
2007        #[cfg(feature = "comments")]
2008        if let Some(error) = &self.deferred_error {
2009            return Err(error.clone());
2010        }
2011
2012        match self.token {
2013            None => {
2014                self.token = Some(self.scan_next_token()?);
2015                Ok(self.token.as_ref().unwrap())
2016            }
2017            Some(ref tok) => Ok(tok),
2018        }
2019    }
2020
2021    /// Extract and return the next token from the scanner.
2022    ///
2023    /// This function does _not_ make use of `self.token`.
2024    fn scan_next_token(&mut self) -> Result<QueuedToken<'input>, ScanError> {
2025        match self.scanner.next_queued_token()? {
2026            None => unreachable!("scanner ended before the parser consumed its stream-end token"),
2027            Some(tok) => Ok(tok),
2028        }
2029    }
2030
2031    #[cfg(feature = "comments")]
2032    #[inline]
2033    fn maybe_next_comment_event<'a>(&mut self) -> Result<Option<(Event<'a>, Span)>, ScanError>
2034    where
2035        'input: 'a,
2036    {
2037        if self.scanner.comments_possible() {
2038            self.next_comment_event()
2039        } else {
2040            Ok(None)
2041        }
2042    }
2043
2044    #[cfg(feature = "comments")]
2045    fn next_comment_event<'a>(&mut self) -> Result<Option<(Event<'a>, Span)>, ScanError>
2046    where
2047        'input: 'a,
2048    {
2049        let is_comment = {
2050            let token = self.peek_token()?;
2051            matches!(token.1, QueuedTokenType::Comment(_))
2052        };
2053
2054        if !is_comment {
2055            return Ok(None);
2056        }
2057
2058        let QueuedToken(span, token) = self.fetch_token();
2059        match token {
2060            QueuedTokenType::Comment(comment) => {
2061                let placement = self.refined_comment_placement(span, comment.placement());
2062                Ok(Some((
2063                    Event::Comment {
2064                        value: comment.into_text(),
2065                        placement,
2066                    },
2067                    span,
2068                )))
2069            }
2070            _ => unreachable!("comment token disappeared after peek"),
2071        }
2072    }
2073
2074    #[cfg(feature = "comments")]
2075    #[inline]
2076    fn next_comment_events(&mut self) -> Result<Vec<(Event<'input>, Span)>, ScanError> {
2077        if !self.scanner.comments_possible() {
2078            return Ok(Vec::new());
2079        }
2080
2081        debug_assert_eq!(self.comment_scratch.len(), 0);
2082        loop {
2083            match self
2084                .peek_token()
2085                .map(|token| matches!(token.1, QueuedTokenType::Comment(_)))
2086            {
2087                Ok(true) => {}
2088                Err(error) if self.comment_scratch.is_empty() => return Err(error),
2089                Err(error) => {
2090                    debug_assert!(self.deferred_error.is_none());
2091                    self.deferred_error = Some(error);
2092                    return Ok(core::mem::take(&mut self.comment_scratch));
2093                }
2094                Ok(_) => {
2095                    // Keep the allocation when this position has no comments.
2096                    return Ok(if self.comment_scratch.is_empty() {
2097                        Vec::new()
2098                    } else {
2099                        core::mem::take(&mut self.comment_scratch)
2100                    });
2101                }
2102            }
2103
2104            if self.comment_scratch.len() >= self.max_buffered_comment_events {
2105                self.comment_scratch.clear();
2106                return Err(ScanError::from_kind(
2107                    self.peek_token()?.0.start,
2108                    ErrorKind::TooManyComments,
2109                ));
2110            }
2111
2112            let comment = match self.next_comment_event() {
2113                Ok(comment) => comment.expect("comment token disappeared after peek"),
2114                Err(error) => {
2115                    self.comment_scratch.clear();
2116                    return Err(error);
2117                }
2118            };
2119            self.comment_scratch.push(comment);
2120            if self.deferred_error.is_some() {
2121                return Ok(core::mem::take(&mut self.comment_scratch));
2122            }
2123        }
2124    }
2125
2126    #[cfg(feature = "comments")]
2127    fn queue_tail_and_return_first(
2128        &mut self,
2129        mut events: Vec<(Event<'input>, Span)>,
2130    ) -> (Event<'input>, Span) {
2131        let first = {
2132            let mut drained = events.drain(..);
2133            let first = drained
2134                .next()
2135                .expect("event queue must contain at least one event");
2136            self.queued_events.extend(drained);
2137            first
2138        };
2139        self.comment_scratch = events;
2140        first
2141    }
2142
2143    #[cfg(feature = "comments")]
2144    fn queue_event_by_span(
2145        &mut self,
2146        mut comments: Vec<(Event<'input>, Span)>,
2147        event: (Event<'input>, Span),
2148    ) -> (Event<'input>, Span) {
2149        let insert_at = comments
2150            .iter()
2151            .position(|(_, comment_span)| {
2152                comment_span.start.index() >= event.1.start.index()
2153                    && comment_span.end.index() >= event.1.end.index()
2154            })
2155            .unwrap_or(comments.len());
2156        comments.insert(insert_at, event);
2157        self.queue_tail_and_return_first(comments)
2158    }
2159
2160    #[cfg(feature = "comments")]
2161    fn queue_two_events_by_span(
2162        &mut self,
2163        mut comments: Vec<(Event<'input>, Span)>,
2164        first: (Event<'input>, Span),
2165        second: (Event<'input>, Span),
2166    ) -> (Event<'input>, Span) {
2167        let insert_at = comments
2168            .iter()
2169            .position(|(_, comment_span)| {
2170                comment_span.start.index() >= first.1.start.index()
2171                    && comment_span.end.index() >= first.1.end.index()
2172            })
2173            .unwrap_or(comments.len());
2174        comments.reserve(2);
2175        comments.insert(insert_at, first);
2176        comments.insert(insert_at + 1, second);
2177        self.queue_tail_and_return_first(comments)
2178    }
2179
2180    #[cfg(feature = "comments")]
2181    fn refined_comment_placement(&mut self, span: Span, placement: Placement) -> Placement {
2182        if placement == Placement::Right {
2183            return Placement::Right;
2184        }
2185
2186        let next = match self.peek_token() {
2187            Ok(next) => next,
2188            Err(error) => {
2189                debug_assert!(self.deferred_error.is_none());
2190                self.deferred_error = Some(error);
2191                return placement;
2192            }
2193        };
2194        if matches!(next.1, QueuedTokenType::StreamEnd) {
2195            return Placement::Last;
2196        }
2197
2198        if next.0.start.line() == span.end.line() + 1 {
2199            Placement::Above
2200        } else {
2201            Placement::Free
2202        }
2203    }
2204
2205    /// Take the token buffered by [`Self::peek_token`].
2206    ///
2207    /// # Panics
2208    /// Panics if no token has been buffered.
2209    #[track_caller]
2210    fn fetch_token<'a>(&mut self) -> QueuedToken<'a>
2211    where
2212        'input: 'a,
2213    {
2214        self.token
2215            .take()
2216            .expect("fetch_token needs to be preceded by peek_token")
2217    }
2218
2219    /// Skip the next token from the scanner.
2220    fn skip(&mut self) {
2221        self.token = None;
2222    }
2223    /// Pops the top-most state and make it the current state.
2224    ///
2225    /// # Panics
2226    /// Panics if the state stack is empty.
2227    #[track_caller]
2228    fn pop_state(&mut self) {
2229        self.state = self.states.pop().unwrap();
2230    }
2231    /// Push a new state atop the state stack.
2232    fn push_state(&mut self, state: State) {
2233        self.states.push(state);
2234    }
2235
2236    fn start_block_collection(&mut self, mark: Marker) -> Result<(), ScanError> {
2237        if self.block_level >= self.block_nesting_limit {
2238            return Err(ScanError::from_kind(
2239                mark,
2240                ErrorKind::RecursionLimitExceeded,
2241            ));
2242        }
2243        self.block_level += 1;
2244        Ok(())
2245    }
2246
2247    fn end_block_collection(&mut self) {
2248        debug_assert!(self.block_level > 0);
2249        self.block_level -= 1;
2250    }
2251
2252    fn defer_parse_node<'a>(
2253        &mut self,
2254        node_state: State,
2255        return_state: State,
2256        block: bool,
2257        indentless_sequence: bool,
2258    ) -> ParseResult<'a>
2259    where
2260        'input: 'a,
2261    {
2262        self.push_state(return_state);
2263        self.state = node_state;
2264        #[cfg(feature = "comments")]
2265        if let Some(comment) = self.maybe_next_comment_event()? {
2266            return Ok(comment);
2267        }
2268        self.parse_node(block, indentless_sequence)
2269    }
2270
2271    fn parse<'a>(&mut self) -> ParseResult<'a>
2272    where
2273        'input: 'a,
2274    {
2275        if self.state == State::End {
2276            return Ok((Event::StreamEnd, Span::empty(self.scanner.mark())));
2277        }
2278        let event = self.state_machine()?;
2279        Ok(self.apply_pending_key_indent(event))
2280    }
2281
2282    /// Load the YAML from the stream in `self`, pushing events into `recv`.
2283    ///
2284    /// The contents of the stream are parsed and the corresponding events are sent into the
2285    /// receiver. For detailed explanations about how events work, see [`EventReceiver`].
2286    ///
2287    /// If `multi` is set to `true`, the parser will allow parsing of multiple YAML documents
2288    /// inside the stream.
2289    ///
2290    /// Use this method when event handling is infallible. If receiver code can return an
2291    /// application error and should stop parsing, use [`Parser::try_load`] instead. If the caller
2292    /// should directly control when the next event is read, use [`Parser`]'s
2293    /// [`core::iter::Iterator`] implementation.
2294    ///
2295    /// Note that any [`EventReceiver`] is also a [`SpannedEventReceiver`], so implementing the
2296    /// former is enough to call this function.
2297    ///
2298    /// After a scan error, the parser is exhausted: [`Parser::peek`] and [`Parser::next_event`]
2299    /// return [`None`], and further calls to `load` or [`Parser::try_load`] return `Ok(())`
2300    /// without emitting events.
2301    ///
2302    /// # Example
2303    /// ```
2304    /// # use granit_parser::{Event, EventReceiver, Parser};
2305    /// # fn main() -> Result<(), granit_parser::ScanError> {
2306    /// struct EventSink<'input> {
2307    ///     events: Vec<Event<'input>>,
2308    /// }
2309    ///
2310    /// impl<'input> EventReceiver<'input> for EventSink<'input> {
2311    ///     fn on_event(&mut self, ev: Event<'input>) {
2312    ///         self.events.push(ev);
2313    ///     }
2314    /// }
2315    ///
2316    /// let mut parser = Parser::new_from_str("a: 1\n");
2317    /// let mut sink = EventSink { events: Vec::new() };
2318    ///
2319    /// parser.load(&mut sink, false)?;
2320    ///
2321    /// assert!(sink
2322    ///     .events
2323    ///     .iter()
2324    ///     .any(|ev| matches!(ev, Event::Scalar { value, .. } if value == "a")));
2325    /// # Ok(())
2326    /// # }
2327    /// ```
2328    ///
2329    /// # Errors
2330    /// Returns `ScanError` when loading fails.
2331    pub fn load<R: SpannedEventReceiver<'input>>(
2332        &mut self,
2333        recv: &mut R,
2334        multi: bool,
2335    ) -> Result<(), ScanError> {
2336        ParserTrait::load(self, recv, multi)
2337    }
2338
2339    /// Load the YAML from the stream in `self`, pushing events into `recv`.
2340    ///
2341    /// This is the fallible counterpart to [`Parser::load`]. If `recv` returns an error, parsing
2342    /// stops immediately and that error is returned as [`TryLoadError::Receiver`].
2343    ///
2344    /// If `multi` is set to `true`, the parser will allow parsing of multiple YAML documents
2345    /// inside the stream.
2346    ///
2347    /// If the receiver returns an error, the parser is left positioned immediately after the event
2348    /// that caused the receiver error. Callers should treat the parser as partially consumed.
2349    ///
2350    /// After a scan error, the parser is exhausted: [`Parser::peek`] and [`Parser::next_event`]
2351    /// return [`None`], and further calls to `try_load` or [`Parser::load`] return `Ok(())`
2352    /// without emitting events.
2353    ///
2354    /// # Example
2355    /// ```
2356    /// # use granit_parser::{Event, Parser, TryEventReceiver, TryLoadError};
2357    /// #[derive(Debug, PartialEq, Eq)]
2358    /// enum ValidationError {
2359    ///     ForbiddenScalar,
2360    /// }
2361    ///
2362    /// struct Validator;
2363    ///
2364    /// impl<'input> TryEventReceiver<'input> for Validator {
2365    ///     type Error = ValidationError;
2366    ///
2367    ///     fn on_event(&mut self, ev: Event<'input>) -> Result<(), Self::Error> {
2368    ///         if matches!(ev, Event::Scalar { value, .. } if value.as_ref() == "bad") {
2369    ///             Err(ValidationError::ForbiddenScalar)
2370    ///         } else {
2371    ///             Ok(())
2372    ///         }
2373    ///     }
2374    /// }
2375    ///
2376    /// let mut parser = Parser::new_from_str("value: bad\n");
2377    /// let mut validator = Validator;
2378    ///
2379    /// let err = parser.try_load(&mut validator, false).unwrap_err();
2380    ///
2381    /// assert_eq!(err, TryLoadError::Receiver(ValidationError::ForbiddenScalar));
2382    /// ```
2383    ///
2384    /// # Errors
2385    /// Returns [`TryLoadError::Scan`] when scanning or parsing the stream fails. Returns
2386    /// [`TryLoadError::Receiver`] when `recv` returns an error.
2387    pub fn try_load<R: TrySpannedEventReceiver<'input>>(
2388        &mut self,
2389        recv: &mut R,
2390        multi: bool,
2391    ) -> Result<(), TryLoadError<R::Error>> {
2392        ParserTrait::try_load(self, recv, multi)
2393    }
2394
2395    fn state_machine<'a>(&mut self) -> ParseResult<'a>
2396    where
2397        'input: 'a,
2398    {
2399        debug_print!("\n\x1B[;33mParser state: {:?} \x1B[;0m", self.state);
2400
2401        match self.state {
2402            State::StreamStart => self.stream_start(),
2403
2404            State::ImplicitDocumentStart => self.document_start(true),
2405            State::DocumentStart => self.document_start(false),
2406            State::DocumentContent => self.document_content(),
2407            State::DocumentEnd => self.document_end(),
2408
2409            State::BlockNode => self.parse_node(true, false),
2410            State::BlockNodeOrIndentlessSequence => self.parse_node(true, true),
2411            State::FlowNode => self.parse_node(false, false),
2412            State::BlockMappingFirstKey => self.block_mapping_key(true),
2413            State::BlockMappingKey => self.block_mapping_key(false),
2414            #[cfg(feature = "comments")]
2415            State::BlockMappingKeyNode => self.block_mapping_key_node(),
2416            State::BlockMappingValue => self.block_mapping_value(),
2417            #[cfg(feature = "comments")]
2418            State::BlockMappingValueNode => self.block_mapping_value_node(),
2419
2420            State::BlockSequenceFirstEntry => self.block_sequence_entry(true),
2421            State::BlockSequenceEntry => self.block_sequence_entry(false),
2422            #[cfg(feature = "comments")]
2423            State::BlockSequenceEntryNode => self.block_sequence_entry_node(),
2424
2425            State::FlowSequenceFirstEntry => self.flow_sequence_entry(true),
2426            State::FlowSequenceEntry => self.flow_sequence_entry(false),
2427
2428            State::FlowMappingFirstKey => self.flow_mapping_key(true),
2429            State::FlowMappingKey => self.flow_mapping_key(false),
2430            #[cfg(feature = "comments")]
2431            State::FlowMappingKeyNode => self.flow_mapping_key_node(),
2432            State::FlowMappingValue => self.flow_mapping_value(false),
2433            #[cfg(feature = "comments")]
2434            State::FlowMappingValueNode => self.flow_mapping_value_node(),
2435
2436            State::IndentlessSequenceEntry => self.indentless_sequence_entry(),
2437            State::IndentlessSequenceEntryNode => self.indentless_sequence_entry_node(),
2438
2439            State::FlowSequenceEntryMappingKey => self.flow_sequence_entry_mapping_key(),
2440            State::FlowSequenceEntryMappingValue => self.flow_sequence_entry_mapping_value(),
2441            #[cfg(feature = "comments")]
2442            State::FlowSequenceEntryMappingValueNode => {
2443                self.flow_sequence_entry_mapping_value_node()
2444            }
2445            State::FlowSequenceEntryMappingEnd => self.flow_sequence_entry_mapping_end(),
2446            State::FlowMappingEmptyValue => self.flow_mapping_value(true),
2447
2448            State::End => unreachable!("end state is handled before state-machine dispatch"),
2449        }
2450    }
2451
2452    fn stream_start<'a>(&mut self) -> ParseResult<'a>
2453    where
2454        'input: 'a,
2455    {
2456        match *self.peek_token()? {
2457            QueuedToken(span, QueuedTokenType::StreamStart) => {
2458                self.state = State::ImplicitDocumentStart;
2459                self.skip();
2460                Ok((Event::StreamStart, span))
2461            }
2462            QueuedToken(span, _) => Err(ScanError::from_kind(
2463                span.start,
2464                ErrorKind::ExpectedStreamStart,
2465            )),
2466        }
2467    }
2468
2469    #[cfg(feature = "comments")]
2470    fn has_pending_document_directives(&self) -> bool {
2471        self.pending_document_directives
2472            || self.pending_document_version.is_some()
2473            || !self.pending_document_tag_handles.is_empty()
2474    }
2475
2476    fn document_start<'a>(&mut self, implicit: bool) -> ParseResult<'a>
2477    where
2478        'input: 'a,
2479    {
2480        // Resume a document start paused to emit comments before handling markers that are only
2481        // ignorable between documents. In particular, `...` is invalid while `---` is still
2482        // required after directives and must not be consumed by the loop below.
2483        #[cfg(feature = "comments")]
2484        if self.has_pending_document_directives() {
2485            return self.explicit_document_start();
2486        }
2487
2488        while let QueuedTokenType::DocumentEnd = self.peek_token()?.1 {
2489            self.skip();
2490        }
2491
2492        // Anchors are scoped to a single document.
2493        self.anchors.clear();
2494
2495        // Skipping a leading document-end marker can expose a comment that the normal
2496        // `next_event_impl` pre-dispatch check could not see yet. Emit it before deciding whether
2497        // another document starts; presentation-only comments must not create an implicit document.
2498        #[cfg(feature = "comments")]
2499        if let Some(comment) = self.maybe_next_comment_event()? {
2500            return Ok(comment);
2501        }
2502
2503        match *self.peek_token()? {
2504            QueuedToken(span, QueuedTokenType::StreamEnd) => {
2505                self.state = State::End;
2506                self.skip();
2507                Ok((Event::StreamEnd, span))
2508            }
2509            QueuedToken(
2510                _,
2511                QueuedTokenType::VersionDirective(..)
2512                | QueuedTokenType::TagDirective(..)
2513                | QueuedTokenType::ReservedDirective(..)
2514                | QueuedTokenType::DocumentStart,
2515            ) => {
2516                // explicit document
2517                self.explicit_document_start()
2518            }
2519            QueuedToken(span, _) if implicit => {
2520                self.parser_process_directives(None, false, BTreeSet::new())?;
2521                self.push_state(State::DocumentEnd);
2522                self.state = State::BlockNode;
2523                Ok((
2524                    Event::DocumentStart {
2525                        explicit: false,
2526                        version: None,
2527                    },
2528                    span,
2529                ))
2530            }
2531            _ => {
2532                // explicit document
2533                self.explicit_document_start()
2534            }
2535        }
2536    }
2537
2538    fn parser_process_directives(
2539        &mut self,
2540        mut version: Option<YamlVersion>,
2541        continuing: bool,
2542        mut document_tag_handles: BTreeSet<Cow<'input, str>>,
2543    ) -> Result<(Option<YamlVersion>, BTreeSet<Cow<'input, str>>), ScanError> {
2544        // Keep retained handles on the parser so any early error, including scanner errors,
2545        // leaves them available for document recovery. Comment pauses continue the same header.
2546        if !continuing && !self.keep_tags {
2547            self.tags.clear();
2548        }
2549
2550        loop {
2551            let is_directive = matches!(
2552                self.peek_token()?.1,
2553                QueuedTokenType::VersionDirective(..)
2554                    | QueuedTokenType::TagDirective(..)
2555                    | QueuedTokenType::ReservedDirective(..)
2556            );
2557            if !is_directive {
2558                break;
2559            }
2560
2561            let QueuedToken(span, token) = self.fetch_token();
2562            match token {
2563                QueuedTokenType::VersionDirective(major, minor) => {
2564                    if version.is_some() {
2565                        return Err(ScanError::from_kind(
2566                            span.start,
2567                            ErrorKind::DuplicateVersionDirective,
2568                        ));
2569                    }
2570                    if major != 1 {
2571                        return Err(ScanError::from_kind(
2572                            span.start,
2573                            ErrorKind::UnsupportedYamlMajorVersion,
2574                        ));
2575                    }
2576                    version = Some(YamlVersion::new(major, minor));
2577                }
2578                QueuedTokenType::TagDirective(handle, prefix) => {
2579                    if !document_tag_handles.insert(handle.clone()) {
2580                        return Err(ScanError::from_kind(
2581                            span.start,
2582                            ErrorKind::DuplicateTagDirective,
2583                        ));
2584                    }
2585                    self.tags.insert(handle, prefix);
2586                }
2587                QueuedTokenType::ReservedDirective(_, _) => {
2588                    // Reserved directives are ignored
2589                }
2590                _ => unreachable!("non-directive token passed the directive guard"),
2591            }
2592        }
2593
2594        Ok((version, document_tag_handles))
2595    }
2596
2597    fn explicit_document_start<'a>(&mut self) -> ParseResult<'a>
2598    where
2599        'input: 'a,
2600    {
2601        #[cfg(feature = "comments")]
2602        let version = {
2603            let pending_version = self.pending_document_version.take();
2604            let continuing_directives = core::mem::take(&mut self.pending_document_directives);
2605            let pending_tag_handles = core::mem::take(&mut self.pending_document_tag_handles);
2606            let (version, document_tag_handles) = self.parser_process_directives(
2607                pending_version,
2608                continuing_directives,
2609                pending_tag_handles,
2610            )?;
2611            if let Some(comment) = self.maybe_next_comment_event()? {
2612                self.pending_document_version = version;
2613                self.pending_document_directives = true;
2614                self.pending_document_tag_handles = document_tag_handles;
2615                return Ok(comment);
2616            }
2617            version
2618        };
2619        #[cfg(not(feature = "comments"))]
2620        let (version, _) = self.parser_process_directives(None, false, BTreeSet::new())?;
2621        match *self.peek_token()? {
2622            QueuedToken(mark, QueuedTokenType::DocumentStart) => {
2623                self.push_state(State::DocumentEnd);
2624                self.state = State::DocumentContent;
2625                self.skip();
2626                Ok((
2627                    Event::DocumentStart {
2628                        explicit: true,
2629                        version,
2630                    },
2631                    mark,
2632                ))
2633            }
2634            QueuedToken(span, _) => Err(ScanError::from_kind(
2635                span.start,
2636                ErrorKind::ExpectedDocumentStart,
2637            )),
2638        }
2639    }
2640
2641    fn document_content<'a>(&mut self) -> ParseResult<'a>
2642    where
2643        'input: 'a,
2644    {
2645        if let QueuedToken(
2646            mark,
2647            QueuedTokenType::VersionDirective(..)
2648            | QueuedTokenType::TagDirective(..)
2649            | QueuedTokenType::ReservedDirective(..)
2650            | QueuedTokenType::DocumentStart
2651            | QueuedTokenType::DocumentEnd
2652            | QueuedTokenType::StreamEnd,
2653        ) = *self.peek_token()?
2654        {
2655            self.pop_state();
2656            let span = self
2657                .last_non_comment_event_end
2658                .map_or_else(|| Span::empty(mark.start), Span::empty);
2659            Ok((Event::empty_scalar(), span))
2660        } else {
2661            self.state = State::BlockNode;
2662            self.parse_node(true, false)
2663        }
2664    }
2665
2666    fn document_end<'a>(&mut self) -> ParseResult<'a>
2667    where
2668        'input: 'a,
2669    {
2670        let mut explicit_end = false;
2671        let span: Span = match *self.peek_token()? {
2672            QueuedToken(span, QueuedTokenType::DocumentEnd) => {
2673                explicit_end = true;
2674                self.skip();
2675                span
2676            }
2677            QueuedToken(span, _) => self
2678                .last_non_comment_event_end
2679                .map_or_else(|| Span::empty(span.start), Span::empty),
2680        };
2681
2682        self.clear_document_tags();
2683        if explicit_end {
2684            self.state = State::ImplicitDocumentStart;
2685        } else {
2686            if let QueuedToken(
2687                span,
2688                QueuedTokenType::VersionDirective(..)
2689                | QueuedTokenType::TagDirective(..)
2690                | QueuedTokenType::ReservedDirective(..),
2691            ) = *self.peek_token()?
2692            {
2693                return Err(ScanError::from_kind(
2694                    span.start,
2695                    ErrorKind::MissingDocumentEndBeforeDirective,
2696                ));
2697            }
2698            self.state = State::DocumentStart;
2699        }
2700
2701        Ok((
2702            Event::DocumentEnd {
2703                #[cfg(feature = "extended_details")]
2704                explicit: explicit_end,
2705            },
2706            span,
2707        ))
2708    }
2709
2710    fn clear_document_tags(&mut self) {
2711        if self.keep_tags {
2712            // Default handles never persist, even with the non-standard keep_tags policy.
2713            self.tags.remove("!!");
2714            self.tags.remove("!");
2715        } else {
2716            self.tags.clear();
2717        }
2718    }
2719
2720    fn register_anchor(&mut self, name: Cow<'input, str>, mark: &Span) -> Result<usize, ScanError> {
2721        // YAML permits anchor names to be reused. Aliases resolve to the most recent definition.
2722        let new_id = self.anchor_id_count;
2723        self.anchor_id_count = self
2724            .anchor_id_count
2725            .checked_add(1)
2726            .ok_or_else(|| ScanError::from_kind(mark.start, ErrorKind::AnchorCountOverflow))?;
2727        if self.emit_anchor_events {
2728            debug_assert!(self.pending_anchor.is_none());
2729            self.pending_anchor = Some(PendingAnchor {
2730                id: new_id,
2731                name: name.clone(),
2732                span: *mark,
2733                node_emitted: false,
2734            });
2735        }
2736        self.anchors.insert(name, new_id);
2737        Ok(new_id)
2738    }
2739
2740    #[cfg(feature = "comments")]
2741    fn save_pending_node_properties(
2742        &mut self,
2743        anchor_id: Option<usize>,
2744        tag: Option<Cow<'input, Tag>>,
2745        tag_span: Option<(Marker, u32)>,
2746        property_end: Option<Marker>,
2747    ) {
2748        self.pending_node_anchor_id = anchor_id;
2749        self.pending_node_tag = tag;
2750        self.pending_node_tag_span = tag_span;
2751        self.pending_node_property_end = property_end;
2752    }
2753
2754    fn attach_tag_span(
2755        event: Event<'_>,
2756        span: Span,
2757        tag_span: Option<(Marker, u32)>,
2758    ) -> (Event<'_>, Span) {
2759        (event, span.with_tag_span(tag_span))
2760    }
2761
2762    #[allow(clippy::too_many_lines)]
2763    fn parse_node<'a>(&mut self, block: bool, indentless_sequence: bool) -> ParseResult<'a>
2764    where
2765        'input: 'a,
2766    {
2767        #[cfg(feature = "comments")]
2768        if let Some(comment) = self.maybe_next_comment_event()? {
2769            return Ok(comment);
2770        }
2771
2772        #[cfg(feature = "comments")]
2773        let (mut anchor_id, mut tag, mut tag_span, mut property_end) = (
2774            self.pending_node_anchor_id.take(),
2775            self.pending_node_tag.take(),
2776            self.pending_node_tag_span.take(),
2777            self.pending_node_property_end.take(),
2778        );
2779        #[cfg(not(feature = "comments"))]
2780        let (mut anchor_id, mut tag, mut tag_span, mut property_end) = (None, None, None, None);
2781        match *self.peek_token()? {
2782            QueuedToken(_, QueuedTokenType::Alias(_)) if anchor_id.is_none() && tag.is_none() => {
2783                self.pop_state();
2784                let QueuedToken(span, QueuedTokenType::Alias(name)) = self.fetch_token() else {
2785                    unreachable!("alias token disappeared after peek")
2786                };
2787                return match self.anchors.get(&*name) {
2788                    None if self.emit_unresolved_aliases => {
2789                        Ok((Event::UnresolvedAlias { name }, span))
2790                    }
2791                    None => Err(ScanError::from_kind(span.start, ErrorKind::UnknownAnchor)),
2792                    Some(id) => Ok((Event::Alias { anchor_id: *id }, span)),
2793                };
2794            }
2795            QueuedToken(_, QueuedTokenType::Anchor(_)) if anchor_id.is_none() => {
2796                let QueuedToken(span, QueuedTokenType::Anchor(name)) = self.fetch_token() else {
2797                    unreachable!("anchor token disappeared after peek")
2798                };
2799                anchor_id = Some(self.register_anchor(name, &span)?);
2800                property_end = Some(span.end);
2801                if tag.is_none() && matches!(self.peek_token()?.1, QueuedTokenType::Tag(..)) {
2802                    let QueuedToken(tag_mark, QueuedTokenType::Tag(handle, suffix)) =
2803                        self.fetch_token()
2804                    else {
2805                        unreachable!("tag token disappeared after peek")
2806                    };
2807                    tag_span = Some((tag_mark.start, u32::try_from(tag_mark.len()).unwrap_or(0)));
2808                    tag = Some(self.resolve_tag(tag_mark, handle, suffix)?);
2809                    property_end = Some(tag_mark.end);
2810                }
2811                #[cfg(feature = "comments")]
2812                if let Some(comment) = self.maybe_next_comment_event()? {
2813                    self.save_pending_node_properties(anchor_id, tag, tag_span, property_end);
2814                    return Ok(comment);
2815                }
2816            }
2817            QueuedToken(mark, QueuedTokenType::Tag(..)) if tag.is_none() => {
2818                let QueuedTokenType::Tag(handle, suffix) = self.fetch_token().1 else {
2819                    unreachable!("tag token disappeared after peek")
2820                };
2821                tag_span = Some((mark.start, u32::try_from(mark.len()).unwrap_or(0)));
2822                property_end = Some(mark.end);
2823                tag = Some(self.resolve_tag(mark, handle, suffix)?);
2824                if anchor_id.is_none() {
2825                    if let QueuedTokenType::Anchor(_) = &self.peek_token()?.1 {
2826                        let QueuedToken(mark, QueuedTokenType::Anchor(name)) = self.fetch_token()
2827                        else {
2828                            unreachable!("anchor token disappeared after peek")
2829                        };
2830                        anchor_id = Some(self.register_anchor(name, &mark)?);
2831                        property_end = Some(mark.end);
2832                    }
2833                }
2834                #[cfg(feature = "comments")]
2835                if let Some(comment) = self.maybe_next_comment_event()? {
2836                    self.save_pending_node_properties(anchor_id, tag, tag_span, property_end);
2837                    return Ok(comment);
2838                }
2839            }
2840            _ => {}
2841        }
2842        let has_anchor = anchor_id.is_some();
2843        let anchor_id = anchor_id.unwrap_or(0);
2844        match *self.peek_token()? {
2845            QueuedToken(mark, QueuedTokenType::BlockEntry) if indentless_sequence => {
2846                self.start_block_collection(mark.start)?;
2847                self.skip();
2848                let start = (
2849                    Event::SequenceStart {
2850                        style: StructureStyle::Block,
2851                        anchor_id,
2852                        tag,
2853                    },
2854                    mark.with_tag_span(tag_span),
2855                );
2856                #[cfg(feature = "comments")]
2857                {
2858                    let comments = match self.next_comment_events() {
2859                        Ok(comments) => comments,
2860                        Err(error) if !matches!(error.kind(), ErrorKind::TooManyComments) => {
2861                            // `StrInput` can prove that a source has no comments and skips this
2862                            // lookahead, while streaming inputs must probe for one. If that probe
2863                            // discovers a later scanner error, the input backend must not determine
2864                            // whether this already-recognized sequence start is emitted first.
2865                            debug_assert!(self.deferred_error.is_none());
2866                            self.deferred_error = Some(error);
2867                            self.pending_empty_scalar_span = Some(mark);
2868                            self.state = State::IndentlessSequenceEntryNode;
2869                            return Ok(start);
2870                        }
2871                        Err(error) => return Err(error),
2872                    };
2873                    if comments.is_empty() {
2874                        self.pending_empty_scalar_span = Some(mark);
2875                        self.state = State::IndentlessSequenceEntryNode;
2876                        Ok(start)
2877                    } else if let Ok(QueuedToken(
2878                        _,
2879                        QueuedTokenType::BlockEntry
2880                        | QueuedTokenType::Key
2881                        | QueuedTokenType::Value
2882                        | QueuedTokenType::BlockEnd,
2883                    )) = self.peek_token()
2884                    {
2885                        self.state = State::IndentlessSequenceEntry;
2886                        Ok(self.queue_two_events_by_span(
2887                            comments,
2888                            start,
2889                            (Event::empty_scalar(), mark),
2890                        ))
2891                    } else {
2892                        self.pending_empty_scalar_span = Some(mark);
2893                        self.state = State::IndentlessSequenceEntryNode;
2894                        Ok(self.queue_event_by_span(comments, start))
2895                    }
2896                }
2897                #[cfg(not(feature = "comments"))]
2898                {
2899                    self.pending_empty_scalar_span = Some(mark);
2900                    self.state = State::IndentlessSequenceEntryNode;
2901                    Ok(start)
2902                }
2903            }
2904            QueuedToken(_, QueuedTokenType::Scalar(..)) => {
2905                self.pop_state();
2906                let QueuedToken(mark, QueuedTokenType::Scalar(style, v)) = self.fetch_token()
2907                else {
2908                    unreachable!("scalar token disappeared after peek")
2909                };
2910                Ok(Self::attach_tag_span(
2911                    Event::Scalar {
2912                        value: v,
2913                        style,
2914                        anchor_id,
2915                        tag,
2916                    },
2917                    mark,
2918                    tag_span,
2919                ))
2920            }
2921            QueuedToken(mark, QueuedTokenType::FlowSequenceStart) => {
2922                self.state = State::FlowSequenceFirstEntry;
2923                self.skip();
2924                Ok(Self::attach_tag_span(
2925                    Event::SequenceStart {
2926                        style: StructureStyle::Flow,
2927                        anchor_id,
2928                        tag,
2929                    },
2930                    mark,
2931                    tag_span,
2932                ))
2933            }
2934            QueuedToken(mark, QueuedTokenType::FlowMappingStart) => {
2935                self.state = State::FlowMappingFirstKey;
2936                self.skip();
2937                Ok(Self::attach_tag_span(
2938                    Event::MappingStart {
2939                        style: StructureStyle::Flow,
2940                        anchor_id,
2941                        tag,
2942                    },
2943                    mark,
2944                    tag_span,
2945                ))
2946            }
2947            QueuedToken(mark, QueuedTokenType::BlockSequenceStart) if block => {
2948                self.start_block_collection(mark.start)?;
2949                self.state = State::BlockSequenceFirstEntry;
2950                self.skip();
2951                Ok(Self::attach_tag_span(
2952                    Event::SequenceStart {
2953                        style: StructureStyle::Block,
2954                        anchor_id,
2955                        tag,
2956                    },
2957                    mark,
2958                    tag_span,
2959                ))
2960            }
2961            QueuedToken(mark, QueuedTokenType::BlockMappingStart) if block => {
2962                self.start_block_collection(mark.start)?;
2963                self.state = State::BlockMappingFirstKey;
2964                self.skip();
2965                Ok(Self::attach_tag_span(
2966                    Event::MappingStart {
2967                        style: StructureStyle::Block,
2968                        anchor_id,
2969                        tag,
2970                    },
2971                    mark,
2972                    tag_span,
2973                ))
2974            }
2975            // ex 7.2, an empty scalar can follow a secondary tag
2976            QueuedToken(mark, _) if tag.is_some() || has_anchor => {
2977                self.pop_state();
2978                let span = property_end.map_or_else(|| Span::empty(mark.start), Span::empty);
2979                Ok(Self::attach_tag_span(
2980                    Event::empty_scalar_with_anchor(anchor_id, tag),
2981                    span,
2982                    tag_span,
2983                ))
2984            }
2985            QueuedToken(span, _) => {
2986                let kind = match self.state {
2987                    State::FlowSequenceFirstEntry | State::FlowSequenceEntry => {
2988                        ErrorKind::UnexpectedEofFlowSequence
2989                    }
2990                    State::FlowMappingFirstKey
2991                    | State::FlowMappingKey
2992                    | State::FlowMappingValue
2993                    | State::FlowMappingEmptyValue => ErrorKind::UnexpectedEofFlowMapping,
2994                    State::FlowSequenceEntryMappingKey
2995                    | State::FlowSequenceEntryMappingValue
2996                    | State::FlowSequenceEntryMappingEnd
2997                    | State::FlowNode => ErrorKind::UnexpectedEofImplicitFlowMapping,
2998                    State::BlockSequenceFirstEntry
2999                    | State::BlockSequenceEntry
3000                    | State::BlockNode => ErrorKind::UnexpectedEofBlockSequence,
3001                    State::BlockMappingFirstKey
3002                    | State::BlockMappingKey
3003                    | State::BlockMappingValue
3004                    | State::BlockNodeOrIndentlessSequence => ErrorKind::UnexpectedEofBlockMapping,
3005                    _ => ErrorKind::ExpectedNodeContent,
3006                };
3007                Err(ScanError::from_kind(span.start, kind))
3008            }
3009        }
3010    }
3011
3012    fn block_mapping_key<'a>(&mut self, _first: bool) -> ParseResult<'a>
3013    where
3014        'input: 'a,
3015    {
3016        match *self.peek_token()? {
3017            QueuedToken(_, QueuedTokenType::Key) => {
3018                // Indentation is only meaningful for block mapping keys.
3019                if let QueuedToken(key_span, QueuedTokenType::Key) = *self.peek_token()? {
3020                    self.pending_key_indent = Some(key_span.start.col());
3021                }
3022                self.skip();
3023                #[cfg(feature = "comments")]
3024                if let Some(comment) = self.maybe_next_comment_event()? {
3025                    self.state = State::BlockMappingKeyNode;
3026                    return Ok(comment);
3027                }
3028                self.block_mapping_key_node()
3029            }
3030            // A missing block-mapping key before `:` is represented as an empty scalar.
3031            QueuedToken(mark, QueuedTokenType::Value) => {
3032                self.state = State::BlockMappingValue;
3033                Ok((Event::empty_scalar(), Span::empty(mark.start)))
3034            }
3035            QueuedToken(mark, QueuedTokenType::BlockEnd) => {
3036                self.end_block_collection();
3037                self.pop_state();
3038                self.skip();
3039                Ok((Event::MappingEnd, mark))
3040            }
3041            QueuedToken(span, _) => Err(ScanError::from_kind(
3042                span.start,
3043                ErrorKind::ExpectedBlockMappingKey,
3044            )),
3045        }
3046    }
3047
3048    fn block_mapping_key_node<'a>(&mut self) -> ParseResult<'a>
3049    where
3050        'input: 'a,
3051    {
3052        if let QueuedToken(
3053            mark,
3054            QueuedTokenType::Key | QueuedTokenType::Value | QueuedTokenType::BlockEnd,
3055        ) = *self.peek_token()?
3056        {
3057            self.state = State::BlockMappingValue;
3058            Ok((Event::empty_scalar(), Span::empty(mark.start)))
3059        } else {
3060            self.defer_parse_node(
3061                State::BlockNodeOrIndentlessSequence,
3062                State::BlockMappingValue,
3063                true,
3064                true,
3065            )
3066        }
3067    }
3068
3069    fn block_mapping_value<'a>(&mut self) -> ParseResult<'a>
3070    where
3071        'input: 'a,
3072    {
3073        match *self.peek_token()? {
3074            QueuedToken(mark, QueuedTokenType::Value) => {
3075                self.skip();
3076                #[cfg(feature = "comments")]
3077                {
3078                    let comments = self.next_comment_events()?;
3079                    if !comments.is_empty() {
3080                        if let Ok(QueuedToken(
3081                            _,
3082                            QueuedTokenType::Key
3083                            | QueuedTokenType::Value
3084                            | QueuedTokenType::BlockEnd,
3085                        )) = self.peek_token()
3086                        {
3087                            self.state = State::BlockMappingKey;
3088                            return Ok(
3089                                self.queue_event_by_span(comments, (Event::empty_scalar(), mark))
3090                            );
3091                        }
3092                        self.pending_empty_scalar_span = Some(mark);
3093                        self.state = State::BlockMappingValueNode;
3094                        return Ok(self.queue_tail_and_return_first(comments));
3095                    }
3096                }
3097                self.block_mapping_value_node_with_empty_span(mark)
3098            }
3099            QueuedToken(mark, _) => {
3100                self.state = State::BlockMappingKey;
3101                Ok((Event::empty_scalar(), Span::empty(mark.start)))
3102            }
3103        }
3104    }
3105
3106    #[cfg(feature = "comments")]
3107    fn block_mapping_value_node<'a>(&mut self) -> ParseResult<'a>
3108    where
3109        'input: 'a,
3110    {
3111        // Peek before taking the span so that a scanner error leaves this state intact.
3112        self.peek_token()?;
3113        let Some(mark) = self.pending_empty_scalar_span.take() else {
3114            unreachable!(
3115                "block mapping value-node state entered without a pending empty-scalar span"
3116            )
3117        };
3118        self.block_mapping_value_node_with_empty_span(mark)
3119    }
3120
3121    fn block_mapping_value_node_with_empty_span<'a>(&mut self, mark: Span) -> ParseResult<'a>
3122    where
3123        'input: 'a,
3124    {
3125        if let QueuedToken(
3126            _,
3127            QueuedTokenType::Key | QueuedTokenType::Value | QueuedTokenType::BlockEnd,
3128        ) = *self.peek_token()?
3129        {
3130            self.state = State::BlockMappingKey;
3131            Ok((Event::empty_scalar(), mark))
3132        } else {
3133            self.defer_parse_node(
3134                State::BlockNodeOrIndentlessSequence,
3135                State::BlockMappingKey,
3136                true,
3137                true,
3138            )
3139        }
3140    }
3141
3142    fn flow_mapping_key<'a>(&mut self, first: bool) -> ParseResult<'a>
3143    where
3144        'input: 'a,
3145    {
3146        let span: Span =
3147            if let QueuedToken(mark, QueuedTokenType::FlowMappingEnd) = *self.peek_token()? {
3148                mark
3149            } else {
3150                if !first {
3151                    match *self.peek_token()? {
3152                        QueuedToken(_, QueuedTokenType::FlowEntry) => {
3153                            self.skip();
3154                            #[cfg(feature = "comments")]
3155                            if let Some(comment) = self.maybe_next_comment_event()? {
3156                                self.state = State::FlowMappingFirstKey;
3157                                return Ok(comment);
3158                            }
3159                        }
3160                        QueuedToken(span, _) => {
3161                            return Err(ScanError::from_kind(
3162                                span.start,
3163                                ErrorKind::ExpectedFlowMappingSeparator,
3164                            ))
3165                        }
3166                    }
3167                }
3168
3169                match *self.peek_token()? {
3170                    QueuedToken(_, QueuedTokenType::Key) => {
3171                        self.skip();
3172                        #[cfg(feature = "comments")]
3173                        if let Some(comment) = self.maybe_next_comment_event()? {
3174                            self.state = State::FlowMappingKeyNode;
3175                            return Ok(comment);
3176                        }
3177                        return self.flow_mapping_key_node();
3178                    }
3179                    QueuedToken(marker, QueuedTokenType::Value) => {
3180                        self.state = State::FlowMappingValue;
3181                        return Ok((Event::empty_scalar(), Span::empty(marker.start)));
3182                    }
3183                    QueuedToken(_, QueuedTokenType::FlowMappingEnd) => (),
3184                    _ => {
3185                        return self.defer_parse_node(
3186                            State::FlowNode,
3187                            State::FlowMappingEmptyValue,
3188                            false,
3189                            false,
3190                        );
3191                    }
3192                }
3193
3194                self.peek_token()?.0
3195            };
3196
3197        self.pop_state();
3198        self.skip();
3199        Ok((Event::MappingEnd, span))
3200    }
3201
3202    fn flow_mapping_key_node<'a>(&mut self) -> ParseResult<'a>
3203    where
3204        'input: 'a,
3205    {
3206        if let QueuedToken(
3207            mark,
3208            QueuedTokenType::Value | QueuedTokenType::FlowEntry | QueuedTokenType::FlowMappingEnd,
3209        ) = *self.peek_token()?
3210        {
3211            self.state = State::FlowMappingValue;
3212            Ok((Event::empty_scalar(), Span::empty(mark.start)))
3213        } else {
3214            self.defer_parse_node(State::FlowNode, State::FlowMappingValue, false, false)
3215        }
3216    }
3217
3218    fn flow_mapping_value<'a>(&mut self, empty: bool) -> ParseResult<'a>
3219    where
3220        'input: 'a,
3221    {
3222        let span: Span = {
3223            if empty {
3224                let QueuedToken(mark, _) = *self.peek_token()?;
3225                self.state = State::FlowMappingKey;
3226                return Ok((Event::empty_scalar(), Span::empty(mark.start)));
3227            }
3228            match *self.peek_token()? {
3229                QueuedToken(span, QueuedTokenType::Value) => {
3230                    self.skip();
3231                    #[cfg(feature = "comments")]
3232                    {
3233                        let comments = self.next_comment_events()?;
3234                        if comments.is_empty() {
3235                            return self.flow_mapping_value_node_with_empty_span(span);
3236                        }
3237                        if let Ok(QueuedToken(
3238                            _,
3239                            QueuedTokenType::FlowEntry | QueuedTokenType::FlowMappingEnd,
3240                        )) = self.peek_token()
3241                        {
3242                            self.state = State::FlowMappingKey;
3243                            return Ok(
3244                                self.queue_event_by_span(comments, (Event::empty_scalar(), span))
3245                            );
3246                        }
3247
3248                        self.pending_empty_scalar_span = Some(span);
3249                        self.state = State::FlowMappingValueNode;
3250                        return Ok(self.queue_tail_and_return_first(comments));
3251                    }
3252                    #[cfg(not(feature = "comments"))]
3253                    return self.flow_mapping_value_node_with_empty_span(span);
3254                }
3255                QueuedToken(marker, _) => Span::empty(marker.start),
3256            }
3257        };
3258
3259        self.state = State::FlowMappingKey;
3260        Ok((Event::empty_scalar(), span))
3261    }
3262
3263    #[cfg(feature = "comments")]
3264    fn flow_mapping_value_node<'a>(&mut self) -> ParseResult<'a>
3265    where
3266        'input: 'a,
3267    {
3268        // Peek before taking the span so that a scanner error leaves this state intact.
3269        self.peek_token()?;
3270        let Some(mark) = self.pending_empty_scalar_span.take() else {
3271            unreachable!(
3272                "flow mapping value-node state entered without a pending empty-scalar span"
3273            )
3274        };
3275        self.flow_mapping_value_node_with_empty_span(mark)
3276    }
3277
3278    fn flow_mapping_value_node_with_empty_span<'a>(&mut self, mark: Span) -> ParseResult<'a>
3279    where
3280        'input: 'a,
3281    {
3282        match self.peek_token()?.1 {
3283            QueuedTokenType::FlowEntry | QueuedTokenType::FlowMappingEnd => {
3284                self.state = State::FlowMappingKey;
3285                Ok((Event::empty_scalar(), mark))
3286            }
3287            _ => self.defer_parse_node(State::FlowNode, State::FlowMappingKey, false, false),
3288        }
3289    }
3290
3291    fn flow_sequence_entry<'a>(&mut self, first: bool) -> ParseResult<'a>
3292    where
3293        'input: 'a,
3294    {
3295        match *self.peek_token()? {
3296            QueuedToken(mark, QueuedTokenType::FlowSequenceEnd) => {
3297                self.pop_state();
3298                self.skip();
3299                return Ok((Event::SequenceEnd, mark));
3300            }
3301            QueuedToken(_, QueuedTokenType::FlowEntry) if !first => {
3302                self.skip();
3303                #[cfg(feature = "comments")]
3304                if let Some(comment) = self.maybe_next_comment_event()? {
3305                    self.state = State::FlowSequenceFirstEntry;
3306                    return Ok(comment);
3307                }
3308            }
3309            QueuedToken(span, _) if !first => {
3310                return Err(ScanError::from_kind(
3311                    span.start,
3312                    ErrorKind::ExpectedFlowSequenceSeparator,
3313                ));
3314            }
3315            _ => { /* next */ }
3316        }
3317        match *self.peek_token()? {
3318            QueuedToken(mark, QueuedTokenType::FlowSequenceEnd) => {
3319                self.pop_state();
3320                self.skip();
3321                Ok((Event::SequenceEnd, mark))
3322            }
3323            QueuedToken(mark, QueuedTokenType::Key) => {
3324                self.state = State::FlowSequenceEntryMappingKey;
3325                self.skip();
3326                Ok((
3327                    Event::MappingStart {
3328                        style: StructureStyle::Flow,
3329                        anchor_id: 0,
3330                        tag: None,
3331                    },
3332                    mark,
3333                ))
3334            }
3335            _ => self.defer_parse_node(State::FlowNode, State::FlowSequenceEntry, false, false),
3336        }
3337    }
3338
3339    fn indentless_sequence_entry<'a>(&mut self) -> ParseResult<'a>
3340    where
3341        'input: 'a,
3342    {
3343        match *self.peek_token()? {
3344            QueuedToken(mark, QueuedTokenType::BlockEntry) => {
3345                self.skip();
3346                #[cfg(feature = "comments")]
3347                {
3348                    let comments = self.next_comment_events()?;
3349                    if !comments.is_empty() {
3350                        if let Ok(QueuedToken(
3351                            _,
3352                            QueuedTokenType::BlockEntry
3353                            | QueuedTokenType::Key
3354                            | QueuedTokenType::Value
3355                            | QueuedTokenType::BlockEnd,
3356                        )) = self.peek_token()
3357                        {
3358                            self.state = State::IndentlessSequenceEntry;
3359                            return Ok(
3360                                self.queue_event_by_span(comments, (Event::empty_scalar(), mark))
3361                            );
3362                        }
3363                        self.pending_empty_scalar_span = Some(mark);
3364                        self.state = State::IndentlessSequenceEntryNode;
3365                        return Ok(self.queue_tail_and_return_first(comments));
3366                    }
3367                }
3368                self.indentless_sequence_entry_node_with_empty_span(mark)
3369            }
3370            QueuedToken(mark, _) => {
3371                self.end_block_collection();
3372                self.pop_state();
3373                // The token that ends an indentless sequence belongs to the enclosing mapping
3374                // (`? key`, `key:`, block end); the end event is empty, at that token's start.
3375                Ok((Event::SequenceEnd, Span::empty(mark.start)))
3376            }
3377        }
3378    }
3379
3380    fn indentless_sequence_entry_node<'a>(&mut self) -> ParseResult<'a>
3381    where
3382        'input: 'a,
3383    {
3384        // Peek before taking the span so that a scanner error leaves this state intact.
3385        self.peek_token()?;
3386        let Some(mark) = self.pending_empty_scalar_span.take() else {
3387            unreachable!(
3388                "indentless sequence entry-node state entered without a pending empty-scalar span"
3389            )
3390        };
3391        self.indentless_sequence_entry_node_with_empty_span(mark)
3392    }
3393
3394    fn indentless_sequence_entry_node_with_empty_span<'a>(&mut self, mark: Span) -> ParseResult<'a>
3395    where
3396        'input: 'a,
3397    {
3398        if let QueuedToken(
3399            _,
3400            QueuedTokenType::BlockEntry
3401            | QueuedTokenType::Key
3402            | QueuedTokenType::Value
3403            | QueuedTokenType::BlockEnd,
3404        ) = *self.peek_token()?
3405        {
3406            self.state = State::IndentlessSequenceEntry;
3407            Ok((Event::empty_scalar(), mark))
3408        } else {
3409            self.defer_parse_node(
3410                State::BlockNode,
3411                State::IndentlessSequenceEntry,
3412                true,
3413                false,
3414            )
3415        }
3416    }
3417
3418    fn block_sequence_entry<'a>(&mut self, _first: bool) -> ParseResult<'a>
3419    where
3420        'input: 'a,
3421    {
3422        match *self.peek_token()? {
3423            QueuedToken(mark, QueuedTokenType::BlockEnd) => {
3424                self.end_block_collection();
3425                self.pop_state();
3426                self.skip();
3427                Ok((Event::SequenceEnd, mark))
3428            }
3429            QueuedToken(mark, QueuedTokenType::BlockEntry) => {
3430                self.skip();
3431                #[cfg(feature = "comments")]
3432                {
3433                    let comments = self.next_comment_events()?;
3434                    if !comments.is_empty() {
3435                        if let Ok(QueuedToken(
3436                            _,
3437                            QueuedTokenType::BlockEntry | QueuedTokenType::BlockEnd,
3438                        )) = self.peek_token()
3439                        {
3440                            self.state = State::BlockSequenceEntry;
3441                            return Ok(
3442                                self.queue_event_by_span(comments, (Event::empty_scalar(), mark))
3443                            );
3444                        }
3445                        self.pending_empty_scalar_span = Some(mark);
3446                        self.state = State::BlockSequenceEntryNode;
3447                        return Ok(self.queue_tail_and_return_first(comments));
3448                    }
3449                }
3450                self.block_sequence_entry_node_with_empty_span(mark)
3451            }
3452            QueuedToken(span, _) => Err(ScanError::from_kind(
3453                span.start,
3454                ErrorKind::ExpectedBlockSequenceEntry,
3455            )),
3456        }
3457    }
3458
3459    #[cfg(feature = "comments")]
3460    fn block_sequence_entry_node<'a>(&mut self) -> ParseResult<'a>
3461    where
3462        'input: 'a,
3463    {
3464        // Peek before taking the span so that a scanner error leaves this state intact.
3465        self.peek_token()?;
3466        let Some(mark) = self.pending_empty_scalar_span.take() else {
3467            unreachable!(
3468                "block sequence entry-node state entered without a pending empty-scalar span"
3469            )
3470        };
3471        self.block_sequence_entry_node_with_empty_span(mark)
3472    }
3473
3474    fn block_sequence_entry_node_with_empty_span<'a>(&mut self, mark: Span) -> ParseResult<'a>
3475    where
3476        'input: 'a,
3477    {
3478        if let QueuedToken(_, QueuedTokenType::BlockEntry | QueuedTokenType::BlockEnd) =
3479            *self.peek_token()?
3480        {
3481            self.state = State::BlockSequenceEntry;
3482            Ok((Event::empty_scalar(), mark))
3483        } else {
3484            self.defer_parse_node(State::BlockNode, State::BlockSequenceEntry, true, false)
3485        }
3486    }
3487
3488    fn flow_sequence_entry_mapping_key<'a>(&mut self) -> ParseResult<'a>
3489    where
3490        'input: 'a,
3491    {
3492        if let QueuedToken(mark, QueuedTokenType::FlowEntry | QueuedTokenType::FlowSequenceEnd) =
3493            *self.peek_token()?
3494        {
3495            self.state = State::FlowSequenceEntryMappingValue;
3496            Ok((Event::empty_scalar(), Span::empty(mark.start)))
3497        } else {
3498            self.defer_parse_node(
3499                State::FlowNode,
3500                State::FlowSequenceEntryMappingValue,
3501                false,
3502                false,
3503            )
3504        }
3505    }
3506
3507    fn flow_sequence_entry_mapping_value<'a>(&mut self) -> ParseResult<'a>
3508    where
3509        'input: 'a,
3510    {
3511        match *self.peek_token()? {
3512            QueuedToken(_, QueuedTokenType::Value) => {
3513                self.skip();
3514                #[cfg(feature = "comments")]
3515                if let Some(comment) = self.maybe_next_comment_event()? {
3516                    self.state = State::FlowSequenceEntryMappingValueNode;
3517                    return Ok(comment);
3518                }
3519                self.flow_sequence_entry_mapping_value_node()
3520            }
3521            QueuedToken(mark, _) => {
3522                self.state = State::FlowSequenceEntryMappingEnd;
3523                Ok((Event::empty_scalar(), Span::empty(mark.start)))
3524            }
3525        }
3526    }
3527
3528    fn flow_sequence_entry_mapping_value_node<'a>(&mut self) -> ParseResult<'a>
3529    where
3530        'input: 'a,
3531    {
3532        let QueuedToken(span, ref tok) = *self.peek_token()?;
3533        if matches!(
3534            tok,
3535            QueuedTokenType::FlowEntry | QueuedTokenType::FlowSequenceEnd
3536        ) {
3537            self.state = State::FlowSequenceEntryMappingEnd;
3538            Ok((Event::empty_scalar(), Span::empty(span.start)))
3539        } else {
3540            self.defer_parse_node(
3541                State::FlowNode,
3542                State::FlowSequenceEntryMappingEnd,
3543                false,
3544                false,
3545            )
3546        }
3547    }
3548
3549    #[allow(clippy::unnecessary_wraps)]
3550    fn flow_sequence_entry_mapping_end<'a>(&mut self) -> ParseResult<'a>
3551    where
3552        'input: 'a,
3553    {
3554        self.state = State::FlowSequenceEntry;
3555        let QueuedToken(span, _) = *self.peek_token()?;
3556        Ok((Event::MappingEnd, Span::empty(span.start)))
3557    }
3558
3559    /// Resolve a tag from the handle and the suffix.
3560    fn resolve_tag(
3561        &self,
3562        span: Span,
3563        handle: Cow<'input, str>,
3564        suffix: Cow<'input, str>,
3565    ) -> Result<Cow<'input, Tag>, ScanError> {
3566        let original_handle = own_tag_component(handle);
3567        let suffix = own_tag_component(suffix);
3568        let handle = if original_handle.is_empty() && suffix == "!" {
3569            // Bare "!" is a non-specific tag, not a primary handle to expand with %TAG.
3570            Cow::Borrowed("")
3571        } else if let Some(prefix) = self.tags.get(original_handle.as_ref()) {
3572            // Explicit directives also override the default "!!" prefix.
3573            own_tag_component(Cow::Borrowed(prefix.as_ref()))
3574        } else if original_handle == "!!" {
3575            Cow::Borrowed(YAML_CORE_SCHEMA_PREFIX)
3576        } else {
3577            // An undeclared named handle cannot be treated as a local tag.
3578            if original_handle.len() >= 2
3579                && original_handle.starts_with('!')
3580                && original_handle.ends_with('!')
3581            {
3582                return Err(ScanError::from_kind(
3583                    span.start,
3584                    ErrorKind::UndeclaredTagHandle,
3585                ));
3586            }
3587            original_handle.clone()
3588        };
3589        Ok(Cow::Owned(Tag {
3590            handle,
3591            suffix,
3592            original_handle,
3593        }))
3594    }
3595}
3596
3597impl<'input, T: BorrowedInput<'input>> ParserTrait<'input> for Parser<'input, T> {
3598    fn peek(&mut self) -> Option<Result<&(Event<'input>, Span), ScanError>> {
3599        if let Some(ref x) = self.current {
3600            Some(Ok(x))
3601        } else if let Some(error) = &self.current_error {
3602            Some(Err(error.clone()))
3603        } else {
3604            if self.stream_end_emitted {
3605                return None;
3606            }
3607            match self.next_event_impl() {
3608                Ok(token) => self.current = Some(token),
3609                Err(error) => {
3610                    self.current_error = Some(error.clone());
3611                    return Some(Err(error));
3612                }
3613            }
3614            self.current.as_ref().map(Ok)
3615        }
3616    }
3617
3618    fn next_event(&mut self) -> Option<ParseResult<'input>> {
3619        if let Some(error) = self.current_error.take() {
3620            self.stream_end_emitted = true;
3621            return Some(Err(error));
3622        }
3623
3624        if self.stream_end_emitted {
3625            return None;
3626        }
3627
3628        let tok = self.next_event_impl();
3629        if matches!(tok, Ok((Event::StreamEnd, _)) | Err(_)) {
3630            self.stream_end_emitted = true;
3631        }
3632        Some(tok)
3633    }
3634
3635    fn load<R: SpannedEventReceiver<'input>>(
3636        &mut self,
3637        recv: &mut R,
3638        multi: bool,
3639    ) -> Result<(), ScanError> {
3640        let mut recv = InfallibleSpannedReceiver(recv);
3641        into_scan_result(ParserTrait::try_load(self, &mut recv, multi))
3642    }
3643
3644    fn try_load<R: TrySpannedEventReceiver<'input>>(
3645        &mut self,
3646        recv: &mut R,
3647        multi: bool,
3648    ) -> Result<(), TryLoadError<R::Error>> {
3649        let stream_start_buffered = matches!(self.current.as_ref(), Some((Event::StreamStart, _)));
3650        if !self.scanner.stream_started() || stream_start_buffered {
3651            let (ev, span) = self.next_event_for_load()?;
3652            if !matches!(ev, Event::StreamStart) {
3653                self.stream_end_emitted = true;
3654                return Err(TryLoadError::scan(ScanError::from_kind(
3655                    span.start,
3656                    ErrorKind::ExpectedStreamStart,
3657                )));
3658            }
3659            try_emit(recv, ev, span)?;
3660        }
3661
3662        let has_buffered_result = self.current.is_some() || self.current_error.is_some();
3663        #[cfg(feature = "comments")]
3664        let has_buffered_result =
3665            has_buffered_result || self.deferred_error.is_some() || !self.queued_events.is_empty();
3666        if self.state == State::End && !has_buffered_result {
3667            // The parser already completed the stream, so emit the terminal event again and stop.
3668            // Only success reaches `State::End`. The scanner's own stream-end flag is not a
3669            // substitute: it is also set when an error is raised at the end of the stream, such as
3670            // `ExpectedDocumentStart` for a directive-only document, and `StreamEnd` must not be
3671            // re-emitted after such an error.
3672            try_emit(recv, Event::StreamEnd, Span::empty(self.scanner.mark()))?;
3673            self.stream_end_emitted = true;
3674            return Ok(());
3675        }
3676        if self.stream_end_emitted && self.current_error.is_none() {
3677            // Only a scan error reaches this point with the latch set: a clean end of stream was
3678            // handled above. The error may have interrupted a state transition, so the state
3679            // machine must not run again. Mirror the fused iterator, which returns `None` here.
3680            return Ok(());
3681        }
3682
3683        loop {
3684            let (ev, span) = if let Some(error) = self.current_error.take() {
3685                self.stream_end_emitted = true;
3686                return Err(TryLoadError::scan(error));
3687            } else {
3688                self.next_event_for_load()?
3689            };
3690            let is_doc_end = matches!(ev, Event::DocumentEnd { .. });
3691            let is_stream_end = matches!(ev, Event::StreamEnd);
3692
3693            try_emit(recv, ev, span)?;
3694
3695            if is_stream_end {
3696                self.stream_end_emitted = true;
3697                return Ok(());
3698            }
3699            if !multi && is_doc_end {
3700                return Ok(());
3701            }
3702        }
3703    }
3704}
3705
3706impl<'input, T: BorrowedInput<'input>> Iterator for Parser<'input, T> {
3707    type Item = Result<(Event<'input>, Span), ScanError>;
3708
3709    fn next(&mut self) -> Option<Self::Item> {
3710        self.next_event()
3711    }
3712}
3713
3714impl<'input, T: BorrowedInput<'input>> core::iter::FusedIterator for Parser<'input, T> {}
3715
3716#[cfg(test)]
3717mod test {
3718    #[cfg(feature = "error_messages")]
3719    use alloc::string::String;
3720    use alloc::{borrow::Cow, format, string::ToString, vec, vec::Vec};
3721    #[cfg(feature = "error_messages")]
3722    use core::{error::Error as _, fmt};
3723
3724    #[cfg(feature = "error_messages")]
3725    use crate::error::{ErrorKind, ScanError};
3726    use crate::scanner::{Marker, ScalarStyle, Span};
3727
3728    use super::{
3729        Event, EventReceiver, Parser, State, StructureStyle, Tag, TryEventReceiver, TryLoadError,
3730        TrySpannedEventReceiver, YamlVersion,
3731    };
3732
3733    #[derive(Default)]
3734    struct CollectingSink<'input> {
3735        events: Vec<Event<'input>>,
3736    }
3737
3738    impl<'input> EventReceiver<'input> for CollectingSink<'input> {
3739        fn on_event(&mut self, ev: Event<'input>) {
3740            self.events.push(ev);
3741        }
3742    }
3743
3744    #[cfg(feature = "error_messages")]
3745    fn first_error_info(input: &str) -> String {
3746        for event in Parser::new_from_str(input) {
3747            if let Err(err) = event {
3748                return err.info();
3749            }
3750        }
3751        panic!("expected parser error")
3752    }
3753
3754    fn first_tagged_scalar_tag(input: &str) -> Tag {
3755        Parser::new_from_str(input)
3756            .find_map(|event| match event.expect("input should parse").0 {
3757                Event::Scalar { tag: Some(tag), .. } => Some(tag.into_owned()),
3758                _ => None,
3759            })
3760            .expect("expected tagged scalar")
3761    }
3762
3763    #[test]
3764    fn document_end_constructor_is_feature_independent() {
3765        let end = Event::document_end();
3766        assert!(matches!(end, Event::DocumentEnd { .. }));
3767
3768        #[cfg(feature = "extended_details")]
3769        assert!(matches!(end, Event::DocumentEnd { explicit: false }));
3770    }
3771
3772    #[cfg(feature = "extended_details")]
3773    #[test]
3774    fn explicit_end_builder_changes_only_document_end_metadata() {
3775        let end = Event::document_end().with_explicit_end(true);
3776        assert!(matches!(end, Event::DocumentEnd { explicit: true }));
3777        assert!(matches!(
3778            end.with_explicit_end(false),
3779            Event::DocumentEnd { explicit: false }
3780        ));
3781        let start = Event::document_start(true, None).with_explicit_end(false);
3782        assert!(matches!(start, Event::DocumentStart { explicit: true, .. }));
3783    }
3784
3785    #[cfg(feature = "extended_details")]
3786    #[test]
3787    fn document_end_reports_explicit_markers() {
3788        for (source, expected) in [
3789            ("value\n", vec![false]),
3790            ("value\n...\n", vec![true]),
3791            ("value\n---\nnext\n...\n", vec![false, true]),
3792            ("---\n...\n", vec![true]),
3793            ("value\n... # end\n", vec![true]),
3794        ] {
3795            let ends: Vec<_> = Parser::new_from_str(source)
3796                .map(Result::unwrap)
3797                .filter_map(|(event, span)| match event {
3798                    Event::DocumentEnd { explicit } => {
3799                        if explicit {
3800                            assert_eq!(span.slice(source), Some("..."));
3801                        } else {
3802                            assert!(span.is_empty());
3803                        }
3804                        Some(explicit)
3805                    }
3806                    _ => None,
3807                })
3808                .collect();
3809            assert_eq!(ends, expected, "{source:?}");
3810        }
3811    }
3812
3813    #[test]
3814    fn omitted_plain_scalars_are_distinct_from_written_nulls() {
3815        let source = "explicit: ~\nmissing:\nsequence:\n  -\ntagged: !!str\n";
3816        let scalars: Vec<_> = Parser::new_from_str(source)
3817            .map(Result::unwrap)
3818            .filter_map(|(event, _)| match event {
3819                Event::Scalar {
3820                    value,
3821                    style: ScalarStyle::Plain { implicit },
3822                    ..
3823                } => Some((value, implicit)),
3824                _ => None,
3825            })
3826            .collect();
3827        let nulls: Vec<_> = scalars
3828            .iter()
3829            .filter(|(value, _)| value == "~")
3830            .map(|(_, implicit)| *implicit)
3831            .collect();
3832        assert_eq!(nulls, vec![false, true, true]);
3833        let (value, implicit) = scalars.last().unwrap();
3834        assert!(value.is_empty());
3835        assert!(*implicit);
3836    }
3837
3838    #[cfg(feature = "comments")]
3839    #[test]
3840    fn deferred_parse_node_can_emit_comment_before_flow_node() {
3841        let mut parser = Parser::new_from_str("---\n# deferred\nvalue\n");
3842        assert_eq!(parser.stream_start().unwrap().0, Event::StreamStart);
3843        assert_eq!(
3844            parser.document_start(true).unwrap().0,
3845            Event::DocumentStart {
3846                explicit: true,
3847                version: None
3848            }
3849        );
3850
3851        let (event, _) = parser
3852            .defer_parse_node(State::FlowNode, State::FlowMappingKey, false, false)
3853            .unwrap();
3854
3855        assert!(matches!(event, Event::Comment { value: text, .. } if text == " deferred"));
3856        assert_eq!(parser.state, State::FlowNode);
3857    }
3858
3859    #[cfg(feature = "comments")]
3860    #[test]
3861    fn queued_node_event_gets_pending_key_indent() {
3862        let mut parser = Parser::new_from_str("");
3863        let span = Span::empty(Marker::new(0, 1, 0));
3864
3865        parser.pending_key_indent = Some(3);
3866        parser.queued_events.push_back((
3867            Event::SequenceStart {
3868                style: StructureStyle::Block,
3869                anchor_id: 0,
3870                tag: None,
3871            },
3872            span,
3873        ));
3874
3875        let (event, span) = parser.next_event_impl().unwrap();
3876
3877        assert!(matches!(
3878            event,
3879            Event::SequenceStart {
3880                style: StructureStyle::Block,
3881                anchor_id: 0,
3882                tag: None
3883            }
3884        ));
3885        assert_eq!(span.indent, Some(3));
3886        assert_eq!(parser.pending_key_indent, None);
3887    }
3888
3889    #[test]
3890    fn state_machine_handles_deferred_flow_node_states() {
3891        let mut parser = Parser::new_from_str("value\n");
3892        assert_eq!(parser.stream_start().unwrap().0, Event::StreamStart);
3893        assert_eq!(
3894            parser.document_start(true).unwrap().0,
3895            Event::DocumentStart {
3896                explicit: false,
3897                version: None
3898            }
3899        );
3900        parser.state = State::FlowNode;
3901        parser.push_state(State::End);
3902
3903        let (event, _) = parser.state_machine().unwrap();
3904
3905        assert!(matches!(event, Event::Scalar { value, .. } if value == "value"));
3906    }
3907
3908    #[cfg(feature = "comments")]
3909    #[test]
3910    fn state_machine_handles_deferred_flow_mapping_value_node() {
3911        let mut parser = Parser::new_from_str("value\n");
3912        assert_eq!(parser.stream_start().unwrap().0, Event::StreamStart);
3913        assert_eq!(
3914            parser.document_start(true).unwrap().0,
3915            Event::DocumentStart {
3916                explicit: false,
3917                version: None
3918            }
3919        );
3920        parser.state = State::FlowSequenceEntryMappingValueNode;
3921
3922        let (event, _) = parser.state_machine().unwrap();
3923
3924        assert!(matches!(event, Event::Scalar { value, .. } if value == "value"));
3925    }
3926
3927    #[test]
3928    fn display_resolved_core_tag_without_extra_bang() {
3929        let tag = Tag::with_original_handle("tag:yaml.org,2002:", "str", "!!");
3930
3931        assert_eq!(tag.to_string(), "tag:yaml.org,2002:str");
3932    }
3933
3934    #[test]
3935    fn tag_helpers_distinguish_core_and_local_tags() {
3936        let core = Tag::with_original_handle("tag:yaml.org,2002:", "int", "!!");
3937        let local = Tag::new("!", "thing");
3938        let non_specific = Tag::with_original_handle("", "!", "");
3939        let verbatim = Tag::with_original_handle("", "tag:example.com,2000:thing", "");
3940        let unknown_yaml_org = Tag::with_original_handle("", "tag:yaml.org,2002:application", "");
3941
3942        assert_eq!(core.core_suffix(), Some("int"));
3943        assert!(core.is_yaml_core_schema());
3944        assert!(core.is_yaml_core_schema_tag("int"));
3945        assert!(!core.is_yaml_core_schema_tag("str"));
3946        assert!(!core.is_custom());
3947        assert_eq!(core.parts(), ("tag:yaml.org,2002:", "int"));
3948        assert_eq!(core.original_parts(), ("!!", "int"));
3949        assert_eq!(core.original(), "!!int");
3950
3951        assert_eq!(local.core_suffix(), None);
3952        assert!(!local.is_yaml_core_schema());
3953        assert!(!local.is_yaml_core_schema_tag("thing"));
3954        assert!(local.is_custom());
3955        assert_eq!(local.parts(), ("!", "thing"));
3956        assert_eq!(local.original_parts(), ("!", "thing"));
3957        assert_eq!(local.original(), "!thing");
3958        assert_eq!(local.to_string(), "!thing");
3959
3960        assert_eq!(non_specific.parts(), ("", "!"));
3961        assert_eq!(non_specific.original_parts(), ("", "!"));
3962        assert_eq!(non_specific.original(), "!");
3963
3964        assert_eq!(verbatim.parts(), ("", "tag:example.com,2000:thing"));
3965        assert_eq!(
3966            verbatim.original_parts(),
3967            ("", "tag:example.com,2000:thing")
3968        );
3969        assert_eq!(verbatim.original(), "!<tag:example.com,2000:thing>");
3970
3971        assert_eq!(unknown_yaml_org.core_suffix(), None);
3972        assert!(!unknown_yaml_org.is_yaml_core_schema());
3973        assert!(unknown_yaml_org.is_custom());
3974    }
3975
3976    #[test]
3977    fn core_suffix_uses_resolved_tag_uri_for_common_spellings() {
3978        let cases = [
3979            ("shorthand", "v: !!int 1\n", ("tag:yaml.org,2002:", "int")),
3980            (
3981                "verbatim",
3982                "v: !<tag:yaml.org,2002:int> 1\n",
3983                ("", "tag:yaml.org,2002:int"),
3984            ),
3985            (
3986                "full prefix",
3987                "%TAG !e! tag:yaml.org,2002:\n---\nv: !e!int 1\n",
3988                ("tag:yaml.org,2002:", "int"),
3989            ),
3990            (
3991                "mid-split",
3992                "%TAG !m! tag:yaml.org,2002:i\n---\nv: !m!nt 1\n",
3993                ("tag:yaml.org,2002:i", "nt"),
3994            ),
3995        ];
3996
3997        for (label, input, expected_parts) in cases {
3998            let tag = first_tagged_scalar_tag(input);
3999
4000            assert_eq!(tag.parts(), expected_parts, "{label}");
4001            assert_eq!(tag.core_suffix(), Some("int"), "{label}");
4002            assert!(tag.is_yaml_core_schema(), "{label}");
4003            assert!(tag.is_yaml_core_schema_tag("int"), "{label}");
4004            assert!(!tag.is_yaml_core_schema_tag("str"), "{label}");
4005            assert!(!tag.is_custom(), "{label}");
4006        }
4007    }
4008
4009    #[test]
4010    fn core_suffix_rejects_non_core_yaml_org_tags() {
4011        let cases = [
4012            "binary",
4013            "merge",
4014            "omap",
4015            "pairs",
4016            "set",
4017            "timestamp",
4018            "value",
4019            "yaml",
4020        ];
4021
4022        for suffix in cases {
4023            let tag = Tag::with_original_handle("tag:yaml.org,2002:", suffix, "!!");
4024
4025            assert_eq!(tag.core_suffix(), None, "{suffix}");
4026            assert!(!tag.is_yaml_core_schema(), "{suffix}");
4027            assert!(tag.is_custom(), "{suffix}");
4028        }
4029    }
4030
4031    #[test]
4032    fn core_suffix_rejects_non_core_tags() {
4033        let cases = [
4034            ("local", "v: !local 1\n"),
4035            ("verbatim custom", "v: !<tag:example.com,2000:int> 1\n"),
4036            (
4037                "custom directive",
4038                "%TAG !e! tag:example.com,2000:\n---\nv: !e!int 1\n",
4039            ),
4040            (
4041                "overridden secondary handle",
4042                "%TAG !! tag:example.com,2000:app/\n---\nv: !!int 1\n",
4043            ),
4044        ];
4045
4046        for (label, input) in cases {
4047            let tag = first_tagged_scalar_tag(input);
4048
4049            assert_eq!(tag.core_suffix(), None, "{label}");
4050            assert!(!tag.is_yaml_core_schema(), "{label}");
4051            assert!(!tag.is_yaml_core_schema_tag("int"), "{label}");
4052            assert!(tag.is_custom(), "{label}");
4053        }
4054    }
4055
4056    #[test]
4057    fn suffix_in_namespace_resolves_across_spellings() {
4058        const NS: &str = "tag:yaml.org,2002:";
4059
4060        // Every spelling of `tag:yaml.org,2002:omap` resolves to the same name, even though
4061        // `omap` is not a Core Schema type (so `core_suffix` reports `None`). `mid_split` cuts
4062        // the URI after the namespace prefix (handle longer than `NS`); `inside_split` cuts it
4063        // before the prefix ends (handle a non-empty prefix of `NS`), exercising both branches.
4064        let shorthand = Tag::with_original_handle(NS, "omap", "!!");
4065        let verbatim = Tag::with_original_handle("", "tag:yaml.org,2002:omap", "");
4066        let mid_split = Tag::with_original_handle("tag:yaml.org,2002:o", "map", "!o!");
4067        let inside_split = Tag::with_original_handle("tag:yaml.org,", "2002:omap", "!y!");
4068        for tag in [&shorthand, &verbatim, &mid_split, &inside_split] {
4069            assert_eq!(tag.suffix_in_namespace(NS).as_deref(), Some("omap"));
4070            assert_eq!(tag.core_suffix(), None);
4071        }
4072
4073        // Borrow whenever the resolved name is a contiguous slice of `handle` or `suffix`;
4074        // allocate only when a split lands inside the name itself (handle extends past `NS`).
4075        assert!(matches!(
4076            shorthand.suffix_in_namespace(NS),
4077            Some(Cow::Borrowed(_))
4078        ));
4079        assert!(matches!(
4080            verbatim.suffix_in_namespace(NS),
4081            Some(Cow::Borrowed(_))
4082        ));
4083        assert!(matches!(
4084            inside_split.suffix_in_namespace(NS),
4085            Some(Cow::Borrowed(_))
4086        ));
4087        assert!(matches!(
4088            mid_split.suffix_in_namespace(NS),
4089            Some(Cow::Owned(_))
4090        ));
4091
4092        // The non-core `merge` type resolves the same way; core types still flow through
4093        // `core_suffix`.
4094        let merge = Tag::with_original_handle(NS, "merge", "!!");
4095        assert_eq!(merge.suffix_in_namespace(NS).as_deref(), Some("merge"));
4096        assert_eq!(merge.core_suffix(), None);
4097        assert_eq!(
4098            Tag::new(NS, "int").suffix_in_namespace(NS).as_deref(),
4099            Some("int")
4100        );
4101
4102        // Tags outside the namespace do not resolve into it.
4103        assert_eq!(Tag::new("!", "omap").suffix_in_namespace(NS), None);
4104        assert_eq!(
4105            Tag::with_original_handle("", "tag:example.com,2000:omap", "").suffix_in_namespace(NS),
4106            None
4107        );
4108    }
4109
4110    #[test]
4111    fn attach_tag_span_preserves_node_span() {
4112        let event = Event::Scalar {
4113            value: "value".into(),
4114            style: ScalarStyle::plain(),
4115            anchor_id: 0,
4116            tag: None,
4117        };
4118        let span = Span::new(Marker::new(6, 1, 6), Marker::new(11, 1, 11));
4119        let tag_start = Marker::new(0, 1, 0);
4120
4121        let (attached_event, attached_span) =
4122            Parser::<crate::input::str::StrInput<'_>>::attach_tag_span(
4123                event.clone(),
4124                span,
4125                Some((tag_start, 4)),
4126            );
4127
4128        assert_eq!(attached_event, event);
4129        assert_eq!(attached_span.start, span.start);
4130        assert_eq!(attached_span.end, span.end);
4131        assert_eq!(attached_span.tag_start(), Some(tag_start));
4132        assert_eq!(
4133            attached_span.tag_span(),
4134            Some(Span::new(tag_start, Marker::new(4, 1, 4)))
4135        );
4136    }
4137
4138    #[test]
4139    fn event_inspection_helpers_report_node_metadata() {
4140        let tag = Tag::new("!", "thing");
4141        let scalar = Event::Scalar {
4142            value: "value".into(),
4143            style: ScalarStyle::DoubleQuoted,
4144            anchor_id: 7,
4145            tag: Some(Cow::Borrowed(&tag)),
4146        };
4147        let sequence = Event::SequenceStart {
4148            style: StructureStyle::Block,
4149            anchor_id: 8,
4150            tag: Some(Cow::Owned(tag.clone())),
4151        };
4152        let mapping = Event::MappingStart {
4153            style: StructureStyle::Block,
4154            anchor_id: 9,
4155            tag: Some(Cow::Borrowed(&tag)),
4156        };
4157
4158        assert_eq!(scalar.anchor_id(), Some(7));
4159        assert_eq!(scalar.alias_id(), None);
4160        assert_eq!(scalar.tag(), Some(&tag));
4161        assert_eq!(scalar.scalar(), Some(("value", ScalarStyle::DoubleQuoted)));
4162        assert!(scalar.is_node());
4163
4164        assert_eq!(sequence.anchor_id(), Some(8));
4165        assert_eq!(sequence.alias_id(), None);
4166        assert_eq!(sequence.tag(), Some(&tag));
4167        assert_eq!(sequence.scalar(), None);
4168        assert!(sequence.is_node());
4169
4170        assert_eq!(mapping.anchor_id(), Some(9));
4171        assert_eq!(mapping.alias_id(), None);
4172        assert_eq!(mapping.tag(), Some(&tag));
4173        assert_eq!(mapping.scalar(), None);
4174        assert!(mapping.is_node());
4175
4176        let alias = Event::Alias { anchor_id: 10 };
4177        assert_eq!(alias.anchor_id(), None);
4178        assert_eq!(alias.alias_id(), Some(10));
4179        assert_eq!(alias.tag(), None);
4180        assert_eq!(alias.scalar(), None);
4181        assert!(alias.is_node());
4182
4183        let unanchored_scalar = Event::Scalar {
4184            value: "x".into(),
4185            style: ScalarStyle::plain(),
4186            anchor_id: 0,
4187            tag: None,
4188        };
4189        assert_eq!(unanchored_scalar.anchor_id(), None);
4190        assert_eq!(unanchored_scalar.alias_id(), None);
4191
4192        let stream_start = Event::StreamStart;
4193        assert_eq!(stream_start.anchor_id(), None);
4194        assert_eq!(stream_start.alias_id(), None);
4195        assert_eq!(stream_start.tag(), None);
4196        assert_eq!(stream_start.scalar(), None);
4197        assert!(!stream_start.is_node());
4198    }
4199
4200    #[test]
4201    fn test_peek_eq_parse() {
4202        let s = "
4203a0 bb: val
4204a1: &x
4205    b1: 4
4206    b2: d
4207a2: 4
4208a3: [1, 2, 3]
4209a4:
4210    - [a1, a2]
4211    - 2
4212a5: *x
4213";
4214        let mut p = Parser::new_from_str(s);
4215        loop {
4216            let event_peek = p.peek().unwrap().unwrap().clone();
4217            let event = p.next_event().unwrap().unwrap();
4218            assert_eq!(event, event_peek);
4219            if matches!(event.0, Event::StreamEnd) {
4220                break;
4221            }
4222        }
4223    }
4224
4225    #[test]
4226    fn test_repeated_peek_returns_buffered_event() {
4227        let mut parser = Parser::new_from_str("key: value\n");
4228
4229        let first_peek = parser.peek().unwrap().unwrap().clone();
4230        let second_peek = parser.peek().unwrap().unwrap().clone();
4231        let next = parser.next_event().unwrap().unwrap();
4232
4233        assert_eq!(first_peek, second_peek);
4234        assert_eq!(first_peek, next);
4235    }
4236
4237    #[cfg(feature = "error_messages")]
4238    #[test]
4239    fn test_peek_surfaces_scan_error_without_consuming_stream_end_state() {
4240        let mut parser = Parser::new_from_str("a: [1, 2");
4241
4242        loop {
4243            match parser.peek() {
4244                Some(Ok(_)) => {
4245                    parser.next_event().unwrap().unwrap();
4246                }
4247                Some(Err(error)) => {
4248                    assert_eq!(error.info(), "unclosed bracket '['");
4249                    break;
4250                }
4251                None => panic!("expected parse error"),
4252            }
4253        }
4254    }
4255
4256    #[test]
4257    fn test_iterator_terminates_after_scan_error() {
4258        let parser = Parser::new_from_str("foo:\n  bar\ninvalid\n");
4259        let mut errors = 0usize;
4260        let mut events = 0usize;
4261
4262        for item in parser {
4263            events += 1;
4264            if item.is_err() {
4265                errors += 1;
4266            }
4267            assert!(
4268                events < 1000,
4269                "parser iterator did not terminate after a scan error"
4270            );
4271        }
4272
4273        assert_eq!(errors, 1);
4274    }
4275
4276    #[cfg(feature = "error_messages")]
4277    #[test]
4278    fn test_iterator_terminates_after_node_property_error() {
4279        let parser = Parser::new_from_str("- *nope\n- 2\n");
4280        let mut errors = 0usize;
4281        let mut saw_later_node = false;
4282        let mut events = 0usize;
4283
4284        for item in parser {
4285            events += 1;
4286            match item {
4287                Ok((Event::Scalar { value, .. }, _)) if value == "2" => saw_later_node = true,
4288                Ok(_) => {}
4289                Err(error) => {
4290                    assert_eq!(error.info(), "while parsing node, found unknown anchor");
4291                    errors += 1;
4292                }
4293            }
4294            assert!(
4295                events < 1000,
4296                "parser iterator did not terminate after a node-property error"
4297            );
4298        }
4299
4300        assert_eq!(errors, 1);
4301        assert!(!saw_later_node, "parser resumed after the alias error");
4302    }
4303
4304    #[test]
4305    fn test_peeked_scan_error_is_returned_once_by_next_event() {
4306        let mut parser = Parser::new_from_str("a: [1, 2");
4307
4308        let first_error = loop {
4309            match parser.peek() {
4310                Some(Ok(_)) => {
4311                    parser.next_event().unwrap().unwrap();
4312                }
4313                Some(Err(error)) => break error,
4314                None => panic!("expected parse error"),
4315            }
4316        };
4317        let Some(Err(second_error)) = parser.peek() else {
4318            panic!("expected cached parse error");
4319        };
4320
4321        assert_eq!(first_error, second_error);
4322        assert_eq!(parser.next_event().unwrap().unwrap_err(), first_error);
4323        assert!(parser.next_event().is_none());
4324        assert!(parser.peek().is_none());
4325    }
4326
4327    #[cfg(feature = "error_messages")]
4328    #[test]
4329    fn test_peeked_node_property_error_is_stable_and_terminal() {
4330        let mut parser = Parser::new_from_str("a: *nope\nb: 2\n");
4331
4332        for _ in 0..4 {
4333            parser.next_event().unwrap().unwrap();
4334        }
4335
4336        let Some(Err(first_error)) = parser.peek() else {
4337            panic!("expected unknown alias error");
4338        };
4339        let Some(Err(second_error)) = parser.peek() else {
4340            panic!("expected cached unknown alias error");
4341        };
4342
4343        assert_eq!(first_error, second_error);
4344        assert_eq!(
4345            first_error.info(),
4346            "while parsing node, found unknown anchor"
4347        );
4348        assert_eq!(parser.next_event().unwrap().unwrap_err(), first_error);
4349        assert!(parser.next_event().is_none());
4350        assert!(parser.peek().is_none());
4351    }
4352
4353    #[test]
4354    fn test_peek_and_next_return_none_after_stream_end() {
4355        let mut parser = Parser::new_from_str("");
4356
4357        assert!(matches!(
4358            parser.next_event().unwrap().unwrap().0,
4359            Event::StreamStart
4360        ));
4361        assert!(matches!(
4362            parser.next_event().unwrap().unwrap().0,
4363            Event::StreamEnd
4364        ));
4365        assert!(parser.next_event().is_none());
4366        assert!(parser.peek().is_none());
4367    }
4368
4369    #[test]
4370    fn test_load_after_stream_already_ended_emits_stream_end() {
4371        let mut parser = Parser::new_from_str("");
4372        while parser.next_event().is_some() {}
4373
4374        let mut sink = CollectingSink::default();
4375        parser.load(&mut sink, true).unwrap();
4376
4377        assert_eq!(sink.events, vec![Event::StreamEnd]);
4378    }
4379
4380    #[test]
4381    fn test_load_full_stream_fuses_iterator_after_stream_end() {
4382        let mut parser = Parser::new_from_str("a: 1\n");
4383        let mut sink = CollectingSink::default();
4384
4385        parser.load(&mut sink, true).unwrap();
4386
4387        assert!(matches!(sink.events.last(), Some(Event::StreamEnd)));
4388        assert!(parser.next_event().is_none());
4389        assert!(parser.peek().is_none());
4390    }
4391
4392    #[test]
4393    fn test_load_after_peek_delivers_buffered_document_end_before_stream_end() {
4394        let mut parser = Parser::new_from_str("a");
4395        for _ in 0..3 {
4396            parser.next_event().unwrap().unwrap();
4397        }
4398
4399        assert_eq!(parser.peek().unwrap().unwrap().0, Event::document_end());
4400
4401        let mut sink = CollectingSink::default();
4402        parser.load(&mut sink, true).unwrap();
4403
4404        assert_eq!(sink.events, vec![Event::document_end(), Event::StreamEnd]);
4405        assert!(parser.next_event().is_none());
4406    }
4407
4408    #[test]
4409    fn test_load_visits_nested_collection_events() {
4410        let mut parser = Parser::new_from_str("root:\n  - item: value\n  - [a, b]\n");
4411        let mut sink = CollectingSink::default();
4412
4413        parser.load(&mut sink, true).unwrap();
4414
4415        assert_eq!(
4416            sink.events,
4417            vec![
4418                Event::StreamStart,
4419                Event::DocumentStart {
4420                    explicit: false,
4421                    version: None
4422                },
4423                Event::MappingStart {
4424                    style: StructureStyle::Block,
4425                    anchor_id: 0,
4426                    tag: None
4427                },
4428                Event::Scalar {
4429                    value: "root".into(),
4430                    style: ScalarStyle::plain(),
4431                    anchor_id: 0,
4432                    tag: None
4433                },
4434                Event::SequenceStart {
4435                    style: StructureStyle::Block,
4436                    anchor_id: 0,
4437                    tag: None
4438                },
4439                Event::MappingStart {
4440                    style: StructureStyle::Block,
4441                    anchor_id: 0,
4442                    tag: None
4443                },
4444                Event::Scalar {
4445                    value: "item".into(),
4446                    style: ScalarStyle::plain(),
4447                    anchor_id: 0,
4448                    tag: None
4449                },
4450                Event::Scalar {
4451                    value: "value".into(),
4452                    style: ScalarStyle::plain(),
4453                    anchor_id: 0,
4454                    tag: None
4455                },
4456                Event::MappingEnd,
4457                Event::SequenceStart {
4458                    style: StructureStyle::Flow,
4459                    anchor_id: 0,
4460                    tag: None
4461                },
4462                Event::Scalar {
4463                    value: "a".into(),
4464                    style: ScalarStyle::plain(),
4465                    anchor_id: 0,
4466                    tag: None
4467                },
4468                Event::Scalar {
4469                    value: "b".into(),
4470                    style: ScalarStyle::plain(),
4471                    anchor_id: 0,
4472                    tag: None
4473                },
4474                Event::SequenceEnd,
4475                Event::SequenceEnd,
4476                Event::MappingEnd,
4477                Event::document_end(),
4478                Event::StreamEnd,
4479            ]
4480        );
4481    }
4482
4483    #[derive(Clone, Debug, PartialEq, Eq)]
4484    enum ValidationError {
4485        ForbiddenValue,
4486    }
4487
4488    #[cfg(feature = "error_messages")]
4489    #[derive(Debug)]
4490    struct ReceiverFailure;
4491
4492    #[cfg(feature = "error_messages")]
4493    impl fmt::Display for ReceiverFailure {
4494        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4495            write!(f, "receiver failed")
4496        }
4497    }
4498
4499    #[cfg(feature = "error_messages")]
4500    impl core::error::Error for ReceiverFailure {}
4501
4502    struct FailingSink<'input> {
4503        events: Vec<Event<'input>>,
4504    }
4505
4506    impl<'input> TryEventReceiver<'input> for FailingSink<'input> {
4507        type Error = ValidationError;
4508
4509        fn on_event(&mut self, ev: Event<'input>) -> Result<(), Self::Error> {
4510            let should_fail = matches!(&ev, Event::Scalar { value, .. } if value.as_ref() == "bad");
4511            self.events.push(ev);
4512            if should_fail {
4513                Err(ValidationError::ForbiddenValue)
4514            } else {
4515                Ok(())
4516            }
4517        }
4518    }
4519
4520    #[test]
4521    fn test_try_load_stops_on_receiver_error() {
4522        let mut parser = Parser::new_from_str("ok: bad\nafter: value\n");
4523        let mut sink = FailingSink { events: Vec::new() };
4524
4525        let err = parser.try_load(&mut sink, true).unwrap_err();
4526
4527        assert_eq!(err, TryLoadError::Receiver(ValidationError::ForbiddenValue));
4528        assert!(sink
4529            .events
4530            .iter()
4531            .any(|event| matches!(event, Event::Scalar { value, .. } if value == "ok")));
4532        assert!(sink
4533            .events
4534            .iter()
4535            .any(|event| matches!(event, Event::Scalar { value, .. } if value == "bad")));
4536        assert!(!sink
4537            .events
4538            .iter()
4539            .any(|event| matches!(event, Event::Scalar { value, .. } if value == "after")));
4540    }
4541
4542    struct SpannedFailingSink {
4543        failed_span: Option<Span>,
4544    }
4545
4546    impl<'input> TrySpannedEventReceiver<'input> for SpannedFailingSink {
4547        type Error = Span;
4548
4549        fn on_event(&mut self, ev: Event<'input>, span: Span) -> Result<(), Self::Error> {
4550            if matches!(ev, Event::Scalar { value, .. } if value.as_ref() == "bad") {
4551                self.failed_span = Some(span);
4552                Err(span)
4553            } else {
4554                Ok(())
4555            }
4556        }
4557    }
4558
4559    #[test]
4560    fn test_try_load_spanned_receiver_gets_span() {
4561        let mut parser = Parser::new_from_str("value: bad\n");
4562        let mut sink = SpannedFailingSink { failed_span: None };
4563
4564        let err = parser.try_load(&mut sink, false).unwrap_err();
4565
4566        let TryLoadError::Receiver(span) = err else {
4567            panic!("expected receiver error");
4568        };
4569
4570        assert_eq!(Some(span), sink.failed_span);
4571        assert!(!span.is_empty());
4572    }
4573
4574    #[cfg(feature = "error_messages")]
4575    struct NeverFails {
4576        count: usize,
4577    }
4578
4579    #[cfg(feature = "error_messages")]
4580    impl<'input> TryEventReceiver<'input> for NeverFails {
4581        type Error = ValidationError;
4582
4583        fn on_event(&mut self, _ev: Event<'input>) -> Result<(), Self::Error> {
4584            self.count += 1;
4585            Ok(())
4586        }
4587    }
4588
4589    #[cfg(feature = "error_messages")]
4590    #[test]
4591    fn test_try_load_returns_scan_error() {
4592        let mut parser = Parser::new_from_str("%YAML 1.2\n%YAML 1.2\n---\n");
4593        let mut sink = NeverFails { count: 0 };
4594
4595        let err = parser.try_load(&mut sink, true).unwrap_err();
4596
4597        let TryLoadError::Scan(err) = err else {
4598            panic!("expected scan error");
4599        };
4600        assert_eq!(err.kind(), &ErrorKind::DuplicateVersionDirective);
4601        assert_eq!(err.info(), "duplicate version directive");
4602    }
4603
4604    #[cfg(feature = "error_messages")]
4605    #[test]
4606    fn test_try_load_error_display_and_source_cover_both_variants() {
4607        let scan = ScanError::from_kind(Marker::new(3, 1, 3), ErrorKind::UnexpectedEof);
4608        let scan_err: TryLoadError<ReceiverFailure> = scan.into();
4609
4610        assert!(scan_err
4611            .to_string()
4612            .starts_with("parser error: unexpected eof"));
4613        assert!(scan_err.source().is_some());
4614
4615        let receiver_err = TryLoadError::Receiver(ReceiverFailure);
4616
4617        assert_eq!(receiver_err.to_string(), "receiver error: receiver failed");
4618        assert!(receiver_err.source().is_some());
4619    }
4620
4621    #[cfg(feature = "error_messages")]
4622    #[test]
4623    fn test_try_load_requires_buffered_stream_start() {
4624        let mut parser = Parser::new_from_str("");
4625        let span = Span::empty(Marker::new(0, 1, 0));
4626        parser.current = Some((
4627            Event::Scalar {
4628                value: "value".into(),
4629                style: ScalarStyle::plain(),
4630                anchor_id: 0,
4631                tag: None,
4632            },
4633            span,
4634        ));
4635        let mut sink = NeverFails { count: 0 };
4636
4637        let err = parser.try_load(&mut sink, true).unwrap_err();
4638
4639        let TryLoadError::Scan(err) = err else {
4640            panic!("expected scan error");
4641        };
4642        assert_eq!(err.info(), "did not find expected <stream-start>");
4643    }
4644
4645    #[test]
4646    fn test_try_load_after_stream_already_ended_emits_stream_end() {
4647        let mut parser = Parser::new_from_str("");
4648        while parser.next_event().is_some() {}
4649
4650        let mut sink = FailingSink { events: Vec::new() };
4651        parser.try_load(&mut sink, true).unwrap();
4652
4653        assert_eq!(sink.events, vec![Event::StreamEnd]);
4654    }
4655
4656    #[test]
4657    fn test_try_load_full_stream_fuses_iterator_after_stream_end() {
4658        let mut parser = Parser::new_from_str("a: 1\n");
4659        let mut sink = FailingSink { events: Vec::new() };
4660
4661        parser.try_load(&mut sink, true).unwrap();
4662
4663        assert!(matches!(sink.events.last(), Some(Event::StreamEnd)));
4664        assert!(parser.next_event().is_none());
4665        assert!(parser.peek().is_none());
4666    }
4667
4668    #[test]
4669    fn test_try_load_after_peek_delivers_buffered_document_end_before_stream_end() {
4670        let mut parser = Parser::new_from_str("a");
4671        for _ in 0..3 {
4672            parser.next_event().unwrap().unwrap();
4673        }
4674
4675        assert_eq!(parser.peek().unwrap().unwrap().0, Event::document_end());
4676
4677        let mut sink = FailingSink { events: Vec::new() };
4678        parser.try_load(&mut sink, true).unwrap();
4679
4680        assert_eq!(sink.events, vec![Event::document_end(), Event::StreamEnd]);
4681        assert!(parser.next_event().is_none());
4682    }
4683
4684    #[test]
4685    fn test_load_single_document_stops_before_next_document() {
4686        let mut parser = Parser::new_from_str("a: 1\n---\nb: 2\n");
4687        let mut sink = CollectingSink::default();
4688
4689        parser.load(&mut sink, false).unwrap();
4690
4691        assert!(sink
4692            .events
4693            .iter()
4694            .any(|event| matches!(event, Event::Scalar { value, .. } if value == "a")));
4695        assert!(!sink
4696            .events
4697            .iter()
4698            .any(|event| matches!(event, Event::Scalar { value, .. } if value == "b")));
4699        assert!(matches!(
4700            sink.events.last(),
4701            Some(Event::DocumentEnd { .. })
4702        ));
4703    }
4704
4705    #[cfg(feature = "error_messages")]
4706    #[test]
4707    fn test_duplicate_version_directive_errors() {
4708        assert_eq!(
4709            first_error_info("%YAML 1.2\n%YAML 1.2\n---\n"),
4710            "duplicate version directive"
4711        );
4712    }
4713
4714    #[cfg(feature = "error_messages")]
4715    #[test]
4716    fn test_unsupported_yaml_major_version_errors() {
4717        assert_eq!(
4718            first_error_info("%YAML 9.9\n--- a\n"),
4719            "unsupported YAML major version"
4720        );
4721    }
4722
4723    #[test]
4724    fn test_document_start_emits_yaml_version() {
4725        let events = Parser::new_from_str("%YAML 1.2\n---\nvalue\n")
4726            .map(|event| event.unwrap().0)
4727            .collect::<Vec<_>>();
4728
4729        assert!(matches!(
4730            events.get(1),
4731            Some(Event::DocumentStart {
4732                explicit: true,
4733                version: Some(YamlVersion { major: 1, minor: 2 })
4734            })
4735        ));
4736    }
4737
4738    #[test]
4739    fn test_document_start_allows_supported_major_future_minor_version() {
4740        let events = Parser::new_from_str("%YAML 1.9\n---\nvalue\n")
4741            .map(|event| event.unwrap().0)
4742            .collect::<Vec<_>>();
4743
4744        assert!(matches!(
4745            events.get(1),
4746            Some(Event::DocumentStart {
4747                explicit: true,
4748                version: Some(YamlVersion { major: 1, minor: 9 })
4749            })
4750        ));
4751    }
4752
4753    #[test]
4754    fn test_document_start_keeps_version_and_tags_across_comment() {
4755        let events = Parser::new_from_str(
4756            "%YAML 1.2\n# directive comment\n%TAG !e! tag:example.com,2026:\n---\nkey: !e!thing value\n",
4757        )
4758        .map(|event| event.unwrap().0)
4759        .filter(|event| {
4760            #[cfg(feature = "comments")]
4761            {
4762                !matches!(event, Event::Comment { .. })
4763            }
4764            #[cfg(not(feature = "comments"))]
4765            {
4766                let _ = event;
4767                true
4768            }
4769        })
4770        .collect::<Vec<_>>();
4771
4772        assert!(matches!(
4773            events.get(1),
4774            Some(Event::DocumentStart {
4775                explicit: true,
4776                version: Some(YamlVersion { major: 1, minor: 2 })
4777            })
4778        ));
4779
4780        let tag = events
4781            .iter()
4782            .find_map(|event| match event {
4783                Event::Scalar {
4784                    value,
4785                    tag: Some(tag),
4786                    ..
4787                } if value == "value" => Some(tag),
4788                _ => None,
4789            })
4790            .expect("expected tagged scalar after comment-separated directives");
4791
4792        assert_eq!(tag.handle, "tag:example.com,2026:");
4793        assert_eq!(tag.suffix, "thing");
4794    }
4795
4796    #[cfg(feature = "comments")]
4797    #[test]
4798    fn tag_directive_state_borrows_str_input_across_comment() {
4799        let mut parser = Parser::new_from_str(
4800            "%TAG !e! tag:example.com,2026:\n# directive comment\n---\nkey: value\n",
4801        );
4802
4803        while let Some(event) = parser.next_event() {
4804            if matches!(event.unwrap().0, Event::Comment { .. }) {
4805                break;
4806            }
4807        }
4808
4809        assert!(matches!(
4810            parser.tags.get("!e!"),
4811            Some(Cow::Borrowed("tag:example.com,2026:"))
4812        ));
4813        assert!(parser
4814            .pending_document_tag_handles
4815            .iter()
4816            .any(|handle| matches!(handle, Cow::Borrowed("!e!"))));
4817    }
4818
4819    #[test]
4820    fn test_each_document_can_declare_own_yaml_version() {
4821        let document_starts = Parser::new_from_str(
4822            "%YAML 1.2\n---\na\n...\n%YAML 1.2\n---\nb\n...\n%YAML 1.1\n---\nc\n",
4823        )
4824        .filter_map(|event| match event.unwrap().0 {
4825            Event::DocumentStart { explicit, version } => Some((explicit, version)),
4826            _ => None,
4827        })
4828        .collect::<Vec<_>>();
4829
4830        assert_eq!(
4831            document_starts,
4832            vec![
4833                (true, Some(YamlVersion::new(1, 2))),
4834                (true, Some(YamlVersion::new(1, 2))),
4835                (true, Some(YamlVersion::new(1, 1))),
4836            ]
4837        );
4838    }
4839
4840    #[cfg(feature = "error_messages")]
4841    #[test]
4842    fn test_duplicate_tag_directive_errors() {
4843        assert_eq!(
4844            first_error_info("%TAG !t! tag:test,2024:\n%TAG !t! tag:other,2024:\n---\n"),
4845            "the TAG directive must only be given at most once per handle in the same document"
4846        );
4847    }
4848
4849    #[cfg(feature = "error_messages")]
4850    #[test]
4851    fn duplicate_tag_directive_across_comment_is_rejected() {
4852        let input = concat!(
4853            "%TAG !e! tag:example.com,2000:one/\n",
4854            "# separator\n",
4855            "%TAG !e! tag:example.com,2000:two/\n",
4856            "---\n",
4857        );
4858
4859        assert_eq!(
4860            first_error_info(input),
4861            "the TAG directive must only be given at most once per handle in the same document"
4862        );
4863    }
4864
4865    #[test]
4866    fn test_keep_tags_inherited_handle_can_be_redeclared_in_next_document() {
4867        let input = concat!(
4868            "%TAG !e! tag:example.com,2000:one/\n",
4869            "---\n",
4870            "first: !e!thing value\n",
4871            "...\n",
4872            "%TAG !e! tag:example.com,2000:two/\n",
4873            "---\n",
4874            "second: !e!thing value\n",
4875        );
4876
4877        let tags = Parser::new_from_str(input)
4878            .keep_tags(true)
4879            .filter_map(|event| match event.expect("input should parse").0 {
4880                Event::Scalar {
4881                    value,
4882                    tag: Some(tag),
4883                    ..
4884                } if value == "value" => Some(tag.handle.clone()),
4885                _ => None,
4886            })
4887            .collect::<Vec<_>>();
4888
4889        assert_eq!(
4890            tags,
4891            vec!["tag:example.com,2000:one/", "tag:example.com,2000:two/"]
4892        );
4893    }
4894
4895    #[cfg(feature = "error_messages")]
4896    #[test]
4897    fn test_directive_after_implicit_document_requires_explicit_end() {
4898        assert_eq!(
4899            first_error_info("---\nkey: value\n%YAML 1.2\n---\n"),
4900            "missing explicit document end marker before directive"
4901        );
4902    }
4903
4904    #[cfg(feature = "error_messages")]
4905    #[test]
4906    fn test_anchor_offset_overflow_reports_error() {
4907        let mut parser = Parser::new_from_str("&a value");
4908        parser.set_anchor_offset(usize::MAX);
4909
4910        let err = parser
4911            .find_map(Result::err)
4912            .expect("anchor registration should overflow");
4913
4914        assert_eq!(
4915            err.info(),
4916            "while parsing anchor, anchor count exceeded supported limit"
4917        );
4918    }
4919
4920    #[test]
4921    fn test_alias_resolves_to_registered_anchor_id() {
4922        let events = Parser::new_from_str("- &a value\n- *a\n")
4923            .map(|event| event.unwrap().0)
4924            .collect::<Vec<_>>();
4925
4926        assert!(events
4927            .iter()
4928            .any(|event| matches!(event, Event::Alias { anchor_id: 1 })));
4929    }
4930
4931    #[test]
4932    fn test_anchor_then_tag_applies_both_to_scalar() {
4933        let events = Parser::new_from_str("&a !!str value")
4934            .map(|event| event.unwrap().0)
4935            .collect::<Vec<_>>();
4936
4937        let Some(Event::Scalar {
4938            value,
4939            anchor_id,
4940            tag: Some(tag),
4941            ..
4942        }) = events
4943            .iter()
4944            .find(|event| matches!(event, Event::Scalar { value, .. } if value == "value"))
4945        else {
4946            panic!("expected tagged anchored scalar");
4947        };
4948
4949        assert_eq!(value, "value");
4950        assert_eq!(*anchor_id, 1);
4951        assert_eq!(tag.handle, "tag:yaml.org,2002:");
4952        assert_eq!(tag.suffix, "str");
4953        assert_eq!(tag.original_handle, "!!");
4954        assert_eq!(tag.original(), "!!str");
4955    }
4956
4957    #[test]
4958    fn test_tag_then_anchor_applies_both_to_scalar() {
4959        let events = Parser::new_from_str("!!str &a value")
4960            .map(|event| event.unwrap().0)
4961            .collect::<Vec<_>>();
4962
4963        let Some(Event::Scalar {
4964            value,
4965            anchor_id,
4966            tag: Some(tag),
4967            ..
4968        }) = events
4969            .iter()
4970            .find(|event| matches!(event, Event::Scalar { value, .. } if value == "value"))
4971        else {
4972            panic!("expected tagged anchored scalar");
4973        };
4974
4975        assert_eq!(value, "value");
4976        assert_eq!(*anchor_id, 1);
4977        assert_eq!(tag.handle, "tag:yaml.org,2002:");
4978        assert_eq!(tag.suffix, "str");
4979        assert_eq!(tag.original_handle, "!!");
4980        assert_eq!(tag.original(), "!!str");
4981    }
4982
4983    #[test]
4984    fn test_tag_directive_preserves_original_handle() {
4985        let events =
4986            Parser::new_from_str("%TAG !e! tag:example.com,2000:\n---\nconfig: !e!keep value\n")
4987                .map(|event| event.unwrap().0)
4988                .collect::<Vec<_>>();
4989
4990        let (value, tag) = events
4991            .iter()
4992            .find_map(|event| match event {
4993                Event::Scalar {
4994                    value,
4995                    tag: Some(tag),
4996                    ..
4997                } if value == "value" => Some((value, tag)),
4998                _ => None,
4999            })
5000            .expect("expected tagged scalar");
5001
5002        assert_eq!(value, "value");
5003        assert_eq!(tag.handle, "tag:example.com,2000:");
5004        assert_eq!(tag.suffix, "keep");
5005        assert_eq!(tag.original_handle, "!e!");
5006        assert_eq!(tag.parts(), ("tag:example.com,2000:", "keep"));
5007        assert_eq!(tag.original_parts(), ("!e!", "keep"));
5008        assert_eq!(tag.original(), "!e!keep");
5009    }
5010
5011    #[test]
5012    fn test_verbatim_tag_original_is_normalized_author_spelling() {
5013        let events = Parser::new_from_str("key: !<tag:example.com,2000:thing> value\n")
5014            .map(|event| event.unwrap().0)
5015            .collect::<Vec<_>>();
5016
5017        let Some(Event::Scalar {
5018            value,
5019            tag: Some(tag),
5020            ..
5021        }) = events
5022            .iter()
5023            .find(|event| matches!(event, Event::Scalar { value, .. } if value == "value"))
5024        else {
5025            panic!("expected tagged scalar");
5026        };
5027
5028        assert_eq!(value, "value");
5029        assert_eq!(tag.handle, "");
5030        assert_eq!(tag.suffix, "tag:example.com,2000:thing");
5031        assert_eq!(tag.original_handle, "");
5032        assert_eq!(tag.parts(), ("", "tag:example.com,2000:thing"));
5033        assert_eq!(tag.original_parts(), ("", "tag:example.com,2000:thing"));
5034        assert_eq!(tag.original(), "!<tag:example.com,2000:thing>");
5035    }
5036
5037    #[test]
5038    fn test_multiple_tag_directives_are_kept_within_document() {
5039        let text = r"
5040%TAG !a! tag:a,2024:
5041%TAG !b! tag:b,2024:
5042---
5043first: !a!x foo
5044second: !b!y bar
5045";
5046
5047        let mut seen_a = false;
5048        let mut seen_b = false;
5049        for event in Parser::new_from_str(text) {
5050            let (event, _) = event.unwrap();
5051            if let Event::Scalar { tag: Some(tag), .. } = event {
5052                if tag.handle == "tag:a,2024:" {
5053                    seen_a = true;
5054                } else if tag.handle == "tag:b,2024:" {
5055                    seen_b = true;
5056                }
5057            }
5058        }
5059
5060        assert!(seen_a);
5061        assert!(seen_b);
5062    }
5063
5064    #[cfg(feature = "error_messages")]
5065    #[test]
5066    fn test_tags_are_cleared_when_next_document_has_no_directives() {
5067        let text = r"
5068%TAG !t! tag:test,2024:
5069--- !t!1
5070foo
5071--- !t!2
5072bar
5073";
5074
5075        let mut parser = Parser::new_from_str(text);
5076        for event in parser.by_ref() {
5077            let (event, _) = event.unwrap();
5078            if let Event::DocumentEnd { .. } = event {
5079                break;
5080            }
5081        }
5082
5083        match parser.next().unwrap().unwrap().0 {
5084            Event::DocumentStart {
5085                explicit: true,
5086                version: None,
5087            } => {}
5088            _ => panic!("expected explicit second document start"),
5089        }
5090
5091        let err = parser.next().unwrap().unwrap_err();
5092        assert!(format!("{err}").contains("the handle wasn't declared"));
5093    }
5094
5095    #[cfg(feature = "error_messages")]
5096    #[test]
5097    fn test_pull_parser_clears_anchors_between_documents() {
5098        let mut parser = Parser::new_from_str(
5099            "--- &a value
5100--- *a
5101",
5102        );
5103
5104        for event in parser.by_ref() {
5105            let (event, _) = event.unwrap();
5106            if matches!(event, Event::DocumentEnd { .. }) {
5107                break;
5108            }
5109        }
5110
5111        match parser.next().unwrap().unwrap().0 {
5112            Event::DocumentStart {
5113                explicit: true,
5114                version: None,
5115            } => {}
5116            _ => panic!("expected explicit second document start"),
5117        }
5118
5119        let err = parser.next().unwrap().unwrap_err();
5120        assert!(format!("{err}").contains("unknown anchor"));
5121    }
5122
5123    #[test]
5124    fn test_keep_tags_across_multiple_documents() {
5125        let text = r#"
5126%YAML 1.1
5127%TAG !t! tag:test,2024:
5128--- !t!1 &1
5129foo: "bar"
5130--- !t!2 &2
5131baz: "qux"
5132"#;
5133        for x in Parser::new_from_str(text).keep_tags(true) {
5134            let x = x.unwrap();
5135            if let Event::MappingStart { tag, .. } = x.0 {
5136                let tag = tag.unwrap();
5137                assert_eq!(tag.handle, "tag:test,2024:");
5138            }
5139        }
5140
5141        for x in Parser::new_from_str(text).keep_tags(false) {
5142            if x.is_err() {
5143                // Test successful
5144                return;
5145            }
5146        }
5147        panic!("Test failed, did not encounter error")
5148    }
5149
5150    #[test]
5151    fn test_flow_sequence_mapping_allows_empty_key() {
5152        let parser = Parser::new_from_str("[?: value]");
5153        for event in parser {
5154            event.expect("parser should accept flow sequence mappings with empty keys");
5155        }
5156    }
5157
5158    #[test]
5159    fn test_keep_tags_does_not_persist_default_tag_handles() {
5160        let text = "%TAG !! tag:evil,2024:\n--- !!int 1\n--- !!int 2\n";
5161
5162        let mut int_tags = Vec::new();
5163        for event in Parser::new_from_str(text).keep_tags(true) {
5164            let event = event.unwrap().0;
5165            if let Event::Scalar { tag: Some(tag), .. } = event {
5166                if tag.suffix == "int" {
5167                    int_tags.push(tag.handle.clone());
5168                }
5169            }
5170        }
5171
5172        assert_eq!(int_tags, vec!["tag:evil,2024:", "tag:yaml.org,2002:"]);
5173    }
5174
5175    #[test]
5176    fn test_keep_tags_does_not_persist_primary_tag_handle() {
5177        let text = "%TAG ! tag:evil,2024:\n--- !int 1\n--- !int 2\n";
5178
5179        let tags = Parser::new_from_str(text)
5180            .keep_tags(true)
5181            .filter_map(|event| match event.expect("input should parse").0 {
5182                Event::Scalar { tag: Some(tag), .. } if tag.suffix == "int" => {
5183                    Some(tag.handle.clone())
5184                }
5185                _ => None,
5186            })
5187            .collect::<Vec<_>>();
5188
5189        assert_eq!(tags, vec!["tag:evil,2024:", "!"]);
5190    }
5191
5192    #[test]
5193    fn common_tag_storage_preserves_comparison_and_hashing() {
5194        let parsed = first_tagged_scalar_tag("!!str value");
5195        let constructed = Tag::with_original_handle("tag:yaml.org,2002:", "str", "!!");
5196        assert!(matches!(parsed.handle, Cow::Borrowed(_)));
5197        assert!(matches!(parsed.suffix, Cow::Borrowed(_)));
5198        assert!(matches!(parsed.original_handle, Cow::Borrowed(_)));
5199        assert_eq!(parsed, constructed);
5200        assert_eq!(parsed.cmp(&constructed), core::cmp::Ordering::Equal);
5201        #[cfg(feature = "std")]
5202        {
5203            use core::hash::{Hash, Hasher};
5204            use std::collections::hash_map::DefaultHasher;
5205
5206            let hash = |tag: &Tag| {
5207                let mut hasher = DefaultHasher::new();
5208                tag.hash(&mut hasher);
5209                hasher.finish()
5210            };
5211            assert_eq!(hash(&parsed), hash(&constructed));
5212        }
5213    }
5214
5215    #[test]
5216    fn test_resolve_tag_distinguishes_non_specific_and_primary_handle_tags() {
5217        let mut parser = Parser::new_from_str("");
5218        parser
5219            .tags
5220            .insert("!".into(), "tag:local.example,2024:".into());
5221
5222        for (handle, suffix, expected_prefix, original) in [
5223            ("", "!", "", "!"),
5224            ("!", "foo", "tag:local.example,2024:", "!foo"),
5225        ] {
5226            let tag = parser
5227                .resolve_tag(
5228                    Span::empty(Marker::new(0, 1, 0)),
5229                    Cow::Borrowed(handle),
5230                    Cow::Borrowed(suffix),
5231                )
5232                .unwrap();
5233
5234            assert_eq!(tag.parts(), (expected_prefix, suffix));
5235            assert_eq!(tag.original_parts(), (handle, suffix));
5236            assert_eq!(tag.original(), original);
5237            assert_eq!(tag.to_string(), format!("{expected_prefix}{suffix}"));
5238        }
5239    }
5240
5241    #[test]
5242    fn test_load_after_peek_stream_start() {
5243        #[derive(Default)]
5244        struct Sink<'input> {
5245            events: Vec<Event<'input>>,
5246        }
5247
5248        impl<'input> EventReceiver<'input> for Sink<'input> {
5249            fn on_event(&mut self, ev: Event<'input>) {
5250                self.events.push(ev);
5251            }
5252        }
5253
5254        let mut parser = Parser::new_from_str("key: value\n");
5255        let mut sink = Sink::default();
5256
5257        assert_eq!(parser.peek().unwrap().unwrap().0, Event::StreamStart);
5258        parser.load(&mut sink, false).unwrap();
5259
5260        assert!(matches!(sink.events.first(), Some(Event::StreamStart)));
5261        assert!(matches!(
5262            sink.events.get(1),
5263            Some(Event::DocumentStart { .. })
5264        ));
5265    }
5266}