Skip to main content

granit_parser/
scanner.rs

1//! Home to the YAML Scanner.
2//!
3//! The scanner is the lowest-level parsing utility. It is the lexer / tokenizer, reading input a
4//! character at a time and emitting tokens that can later be interpreted by the [`crate::parser`]
5//! to check for more context and validity.
6//!
7//! Due to the grammar of YAML, the scanner has to have some context and is not error-free.
8
9#![allow(clippy::cast_possible_wrap)]
10#![allow(clippy::cast_sign_loss)]
11
12use alloc::{
13    borrow::{Cow, ToOwned},
14    collections::VecDeque,
15    string::String,
16    vec::Vec,
17};
18use core::char;
19
20use crate::{
21    char_traits::{
22        as_hex, find_non_printable, is_anchor_char, is_blank_or_breakz, is_bom, is_break,
23        is_breakz, is_flow, is_hex, is_printable, is_tag_char, is_uri_char, is_yaml_non_space,
24        is_z,
25    },
26    error::{ErrorKind, ScanError},
27    input::{BorrowedInput, SkipTabs, WhitespaceResult},
28    Options,
29};
30
31/// The source style used for a YAML scalar.
32#[derive(Clone, Copy, PartialEq, Debug, Eq, Hash, PartialOrd, Ord)]
33pub enum ScalarStyle {
34    /// A YAML plain scalar.
35    Plain,
36    /// A YAML single quoted scalar.
37    SingleQuoted,
38    /// A YAML double quoted scalar.
39    DoubleQuoted,
40
41    /// A YAML literal block (`|` block).
42    ///
43    /// See [8.1.2](https://yaml.org/spec/1.2.2/#812-literal-style).
44    /// In literal blocks, any indented character is content, including white space characters.
45    /// There is no way to escape characters, nor to break a long line.
46    Literal,
47    /// A YAML folded block (`>` block).
48    ///
49    /// See [8.1.3](https://yaml.org/spec/1.2.2/#813-folded-style).
50    /// In folded blocks, any indented character is content, including white space characters.
51    /// There is no way to escape characters. Content is subject to line folding, allowing breaking
52    /// long lines.
53    Folded,
54}
55
56/// Offset information for a [`Marker`].
57///
58/// YAML inputs can come from either a full `&str` (stable backing storage) or a streaming
59/// character source. For stable inputs, we can track both a character index and a byte offset.
60/// For streaming inputs, byte offsets are not generally useful (and may not correspond to any
61/// meaningful underlying file/source), so they are optional.
62#[derive(Clone, Copy, Debug, Default)]
63struct MarkerOffsets {
64    /// The index (in characters) in the source.
65    chars: usize,
66    /// The offset (in bytes) in the source, if available.
67    bytes: Option<usize>,
68}
69
70impl PartialEq for MarkerOffsets {
71    fn eq(&self, other: &Self) -> bool {
72        // Byte offsets are an optional diagnostic enhancement and may differ between input
73        // backends (e.g., `&str` vs streaming). Equality is therefore based on the character
74        // position only.
75        self.chars == other.chars
76    }
77}
78
79impl Eq for MarkerOffsets {}
80
81/// A location in a YAML document.
82#[derive(Clone, Copy, PartialEq, Debug, Eq, Default)]
83pub struct Marker {
84    /// Offsets in the source.
85    offsets: MarkerOffsets,
86    /// The line (1-indexed).
87    line: usize,
88    /// The column (0-indexed).
89    col: usize,
90}
91
92impl Marker {
93    /// Create a new [`Marker`] at the given position.
94    #[must_use]
95    pub fn new(index: usize, line: usize, col: usize) -> Marker {
96        Marker {
97            offsets: MarkerOffsets {
98                chars: index,
99                bytes: None,
100            },
101            line,
102            col,
103        }
104    }
105
106    /// Return a copy of the marker with the given optional byte offset.
107    #[must_use]
108    pub fn with_byte_offset(mut self, byte_offset: Option<usize>) -> Marker {
109        self.offsets.bytes = byte_offset;
110        self
111    }
112
113    /// Return the index (in characters) of the marker in the source.
114    #[must_use]
115    pub fn index(&self) -> usize {
116        self.offsets.chars
117    }
118
119    /// Return the byte offset of the marker in the source, if available.
120    #[must_use]
121    pub fn byte_offset(&self) -> Option<usize> {
122        self.offsets.bytes
123    }
124
125    /// Return the line of the marker in the source.
126    #[must_use]
127    pub fn line(&self) -> usize {
128        self.line
129    }
130
131    /// Return the column of the marker in the source.
132    #[must_use]
133    pub fn col(&self) -> usize {
134        self.col
135    }
136}
137
138/// A range of locations in a YAML document.
139///
140/// Construct spans with [`Self::new`], [`Self::empty`], or [`Self::default`], then use
141/// [`Self::with_indent`] to attach optional indentation metadata. Public fields remain
142/// readable and writable, but the type is non-exhaustive so future releases can add metadata.
143/// Destructuring patterns must include `..`.
144///
145/// ```rust
146/// use granit_parser::{Marker, Span};
147///
148/// let start = Marker::new(0, 1, 0);
149/// let end = Marker::new(3, 1, 3);
150/// let span = Span::new(start, end).with_indent(Some(0));
151/// let Span { start: actual_start, end: actual_end, .. } = span;
152/// assert_eq!(actual_start, start);
153/// assert_eq!(actual_end, end);
154/// assert_eq!(span.indent, Some(0));
155/// ```
156///
157/// Direct struct construction outside this crate is not supported:
158///
159/// ```compile_fail,E0639
160/// use granit_parser::{Marker, Span};
161///
162/// let marker = Marker::new(0, 1, 0);
163/// let span = Span { start: marker, end: marker, indent: None, tag_start: None };
164/// ```
165///
166/// Struct-update syntax is likewise unavailable; use the builders or assign individual fields:
167///
168/// ```compile_fail,E0639
169/// use granit_parser::{Marker, Span};
170///
171/// let span = Span { indent: Some(2), ..Span::empty(Marker::new(0, 1, 0)) };
172/// ```
173#[non_exhaustive]
174#[derive(Clone, Copy, PartialEq, Debug, Eq, Default)]
175pub struct Span {
176    /// The start (inclusive) of the range.
177    pub start: Marker,
178    /// The end (exclusive) of the range.
179    pub end: Marker,
180
181    /// Optional indentation hint associated with this span.
182    ///
183    /// This is only meaningful for certain parser-emitted events (notably: block mapping keys).
184    /// When indentation is not meaningful or cannot be provided, it must be `None`.
185    pub indent: Option<usize>,
186
187    /// Optional source marker for the explicit tag token attached to this node.
188    ///
189    /// This is only meaningful for parser-emitted node events that carry a resolved tag, such as
190    /// [`Event::Scalar`](crate::Event::Scalar),
191    /// [`Event::SequenceStart`](crate::Event::SequenceStart), or
192    /// [`Event::MappingStart`](crate::Event::MappingStart). The normal [`Span::start`] and
193    /// [`Span::end`] continue to cover the node value or collection; `tag_start` points to the
194    /// tag token when that token appears at a different source location.
195    pub tag_start: Option<Marker>,
196
197    /// Raw ASCII tag-token length, including its delimiters and URI escapes.
198    /// Zero means the full tag range is unavailable.
199    tag_length: u32,
200}
201
202impl Span {
203    /// Create a new [`Span`] for the given range.
204    #[must_use]
205    pub fn new(start: Marker, end: Marker) -> Span {
206        Span {
207            start,
208            end,
209            indent: None,
210            tag_start: None,
211            tag_length: 0,
212        }
213    }
214
215    /// Create an empty [`Span`] at a given location.
216    ///
217    /// An empty span doesn't contain any characters, but its position may still be meaningful.
218    /// For example, for an indented sequence [`SequenceEnd`] has a location but an empty span.
219    ///
220    /// [`SequenceEnd`]: crate::Event::SequenceEnd
221    #[must_use]
222    pub fn empty(mark: Marker) -> Span {
223        Span {
224            start: mark,
225            end: mark,
226            indent: None,
227            tag_start: None,
228            tag_length: 0,
229        }
230    }
231
232    /// Return a copy of this [`Span`] with the given indentation hint.
233    #[must_use]
234    pub fn with_indent(mut self, indent: Option<usize>) -> Span {
235        self.indent = indent;
236        self
237    }
238
239    /// Return a copy of this [`Span`] with the given explicit tag-token start marker.
240    ///
241    /// Clears any stored tag length, so [`Self::tag_span`] returns `None` on the returned span.
242    /// Retained for compatibility. Parser-emitted spans provide complete tag-token ranges through
243    /// [`Self::tag_span`].
244    #[deprecated(
245        since = "2.1.0",
246        note = "Only sets a tag start (.tag_span() then returns None). Use with_tag_span."
247    )]
248    #[must_use]
249    pub fn with_tag_start(mut self, tag_start: Option<Marker>) -> Span {
250        self.tag_start = tag_start;
251        self.tag_length = 0;
252        self
253    }
254
255    /// Attach the start and raw source length of a single-line ASCII tag token.
256    #[must_use]
257    pub fn with_tag_span(mut self, tag_span: Option<(Marker, u32)>) -> Span {
258        let (start, length) = tag_span.map_or((None, 0), |(start, length)| (Some(start), length));
259        self.tag_start = start;
260        self.tag_length = length;
261        self
262    }
263
264    /// Return the source marker of the explicit tag token attached to this node, if any.
265    ///
266    /// The regular span still covers the node value or collection. This accessor is useful for
267    /// diagnostics that should point at the tag itself, especially when a tagged block collection
268    /// begins on a later line than the tag token.
269    #[must_use]
270    pub fn tag_start(&self) -> Option<Marker> {
271        self.tag_start
272    }
273
274    /// Return the complete source span of the explicit tag attached to this node, if available.
275    ///
276    /// Includes the leading `!`, any verbatim-tag delimiters, and URI escapes exactly as written.
277    /// The node's own [`Self::start`] and [`Self::end`] are unchanged. The returned span carries no
278    /// indentation or tag metadata. With byte offsets, use [`Self::slice`] on it to obtain the raw
279    /// tag spelling; streaming inputs retain character positions without requiring byte offsets.
280    ///
281    /// Returns `None` for untagged nodes and tag tokens longer than [`u32::MAX`] source characters,
282    /// or coordinates that would overflow. Oversized tags still parse normally and retain their
283    /// start marker.
284    ///
285    /// ```
286    /// use granit_parser::Parser;
287    ///
288    /// let source = "key: !note%20here value";
289    /// let tag_span = Parser::new_from_str(source)
290    ///     .filter_map(Result::ok)
291    ///     .find_map(|(_, span)| span.tag_span())
292    ///     .unwrap();
293    /// assert_eq!(tag_span.slice(source), Some("!note%20here"));
294    /// ```
295    #[must_use]
296    pub fn tag_span(&self) -> Option<Span> {
297        let start = self.tag_start?;
298        if self.tag_length == 0 {
299            return None;
300        }
301        let length = usize::try_from(self.tag_length).ok()?;
302        // Raw tag tokens contain only ASCII and cannot span lines. Unicode tag values use
303        // percent escapes, whose source length is preserved here rather than their decoded size.
304        let end = Marker::new(
305            start.index().checked_add(length)?,
306            start.line(),
307            start.col().checked_add(length)?,
308        )
309        .with_byte_offset(match start.byte_offset() {
310            Some(byte_offset) => Some(byte_offset.checked_add(length)?),
311            None => None,
312        });
313        Some(Span::new(start, end))
314    }
315
316    /// Return the length of the span (in characters).
317    ///
318    /// # Panics
319    /// Panics in debug builds if the end marker precedes the start marker.
320    #[track_caller]
321    #[must_use]
322    pub fn len(&self) -> usize {
323        self.end.index() - self.start.index()
324    }
325
326    /// Return whether the [`Span`] has a length of zero.
327    ///
328    /// # Panics
329    /// Panics in debug builds if the end marker precedes the start marker.
330    #[track_caller]
331    #[must_use]
332    pub fn is_empty(&self) -> bool {
333        self.len() == 0
334    }
335
336    /// Return the half-open UTF-8 byte range of the span, if both markers have byte offsets.
337    ///
338    /// Spans emitted by [`Parser::new_from_str`](crate::Parser::new_from_str) and its
339    /// options variant always return `Some`, including empty ranges. Iterator inputs and
340    /// manually constructed markers may lack offsets, so the return type is optional.
341    /// A missing range is not the same as an empty range; do not substitute `0..0` for `None`.
342    ///
343    /// Unlike [`Self::len`] and [`Marker::index`], this range counts bytes, not characters.
344    /// For manually constructed or modified spans, this method does not validate ordering,
345    /// bounds, or UTF-8 boundaries. Use [`Self::slice`] for checked access to source text.
346    #[must_use]
347    pub fn byte_range(&self) -> Option<core::ops::Range<usize>> {
348        Some(self.start.byte_offset()?..self.end.byte_offset()?)
349    }
350
351    /// Return the source text covered by this span, if byte offsets are available
352    /// and the range is valid for the provided input.
353    ///
354    /// Pass the same, unchanged source that produced the span. Bounds and UTF-8 boundaries
355    /// are checked, but a span does not record source identity. The returned text is the raw
356    /// event source, which can differ from a decoded scalar value or be empty for implicit events.
357    #[must_use]
358    pub fn slice<'source>(&self, source: &'source str) -> Option<&'source str> {
359        source.get(self.byte_range()?)
360    }
361}
362
363/// A positional hint for a YAML source comment.
364///
365/// The parser currently recognizes these placements:
366///
367/// ```yaml
368/// # Above
369/// key: value # Right
370///
371/// # Free
372///
373/// next: value
374///
375/// # Last
376/// ```
377#[non_exhaustive]
378#[derive(Clone, Copy, PartialEq, Debug, Eq, Default)]
379#[cfg(feature = "comments")]
380pub enum Placement {
381    /// An own-line comment immediately before another YAML token.
382    ///
383    /// This usually means the comment visually describes the following node.
384    /// Consecutive own-line comments without blank lines between them are also considered
385    /// `Above`, so a comment block can attach to the next YAML element as a group.
386    Above,
387    /// A same-line comment after YAML content or syntax. Examples include `key: value # Right`
388    /// and `- # Right` for an empty sequence entry.
389    Right,
390    /// A standalone own-line comment that is separated from nearby YAML tokens.
391    ///
392    /// This is the fallback for comments that are neither same-line comments, immediately above a
393    /// following token, nor the final comment in the stream. Consumers should treat `Free` as not
394    /// having an obvious neighboring node.
395    #[default]
396    Free,
397    /// An own-line comment at the end of the input stream.
398    ///
399    /// A `Last` comment may be followed by blank lines, but no further YAML token appears before
400    /// `StreamEnd`.
401    Last,
402}
403
404/// YAML comment metadata captured from the source.
405///
406/// Comments are presentation metadata, not YAML data. This type carries the raw comment payload and
407/// a best-effort [`Placement`] hint. The companion [`Token`] carries the comment's source span.
408#[derive(Clone, PartialEq, Debug, Eq)]
409#[cfg(feature = "comments")]
410pub struct Comment<'input> {
411    /// Raw comment payload exactly after `#`, excluding only the line break.
412    ///
413    /// Leading spaces are preserved, including a single space immediately after `#` when present.
414    text: Cow<'input, str>,
415    /// Best-effort placement of this comment relative to nearby YAML content.
416    placement: Placement,
417}
418
419#[cfg(feature = "comments")]
420impl<'input> Comment<'input> {
421    /// Create captured YAML comment metadata from a raw payload.
422    ///
423    /// The placement defaults to [`Placement::Free`]. Use [`Comment::with_placement`] when the
424    /// caller already knows a more specific placement.
425    #[must_use]
426    pub fn new(text: impl Into<Cow<'input, str>>) -> Self {
427        Self {
428            text: text.into(),
429            placement: Placement::Free,
430        }
431    }
432
433    /// Return this comment with the given placement.
434    #[must_use]
435    pub fn with_placement(mut self, placement: Placement) -> Self {
436        self.placement = placement;
437        self
438    }
439
440    /// Return the raw comment payload exactly after `#`, excluding only the line break.
441    #[must_use]
442    pub fn text(&self) -> &str {
443        self.text.as_ref()
444    }
445
446    /// Return the best-effort placement of this comment relative to nearby YAML content.
447    #[must_use]
448    pub const fn placement(&self) -> Placement {
449        self.placement
450    }
451
452    /// Consume the comment and return its raw payload without cloning.
453    #[must_use]
454    pub fn into_text(self) -> Cow<'input, str> {
455        self.text
456    }
457
458    /// Return the comment payload with surrounding whitespace removed.
459    ///
460    /// This helper is ergonomic only. The raw [`Self::text`] payload remains unchanged.
461    #[must_use]
462    pub fn trimmed_text(&self) -> &str {
463        self.text.trim()
464    }
465}
466
467#[cfg(feature = "comments")]
468impl AsRef<str> for Comment<'_> {
469    fn as_ref(&self) -> &str {
470        self.text.as_ref()
471    }
472}
473
474/// The contents of a scanner token.
475#[non_exhaustive]
476#[derive(Clone, PartialEq, Debug, Eq)]
477pub enum TokenType<'input> {
478    /// The start of the stream. Sent first, before even [`TokenType::DocumentStart`].
479    StreamStart,
480    /// The end of the stream, EOF.
481    StreamEnd,
482    /// A YAML version directive.
483    VersionDirective(
484        /// Major version number.
485        u32,
486        /// Minor version number.
487        u32,
488    ),
489    /// A YAML tag directive (e.g.: `!!str`, `!foo!bar`, ...).
490    TagDirective(
491        /// Tag directive handle, such as `!` or `!app!`.
492        Cow<'input, str>,
493        /// Tag URI prefix associated with the handle.
494        Cow<'input, str>,
495    ),
496    /// The start of a YAML document (`---`).
497    DocumentStart,
498    /// The end of a YAML document (`...`).
499    DocumentEnd,
500    /// The start of a sequence block.
501    ///
502    /// Sequence blocks are arrays starting with a `-`.
503    BlockSequenceStart,
504    /// The start of a block mapping.
505    ///
506    /// Block mappings are key-value collections written with `key: value` entries.
507    BlockMappingStart,
508    /// End of the corresponding `BlockSequenceStart` or `BlockMappingStart`.
509    BlockEnd,
510    /// Start of an inline sequence (`[ a, b ]`).
511    FlowSequenceStart,
512    /// End of an inline sequence.
513    FlowSequenceEnd,
514    /// Start of an inline mapping (`{ a: b, c: d }`).
515    FlowMappingStart,
516    /// End of an inline mapping.
517    FlowMappingEnd,
518    /// An entry in a block sequence (see [`TokenType::BlockSequenceStart`]).
519    BlockEntry,
520    /// An entry in a flow sequence (see [`TokenType::FlowSequenceStart`]).
521    FlowEntry,
522    /// A key in a mapping.
523    Key,
524    /// A value in a mapping.
525    Value,
526    /// A reference to a previously defined anchor.
527    Alias(Cow<'input, str>),
528    /// A YAML anchor definition introduced by `&`.
529    Anchor(Cow<'input, str>),
530    /// A YAML tag (starting with bangs `!`).
531    Tag(
532        /// The handle of the tag.
533        Cow<'input, str>,
534        /// The suffix of the tag.
535        Cow<'input, str>,
536    ),
537    /// A regular YAML scalar.
538    Scalar(ScalarStyle, Cow<'input, str>),
539    /// A YAML source comment.
540    ///
541    /// The token payload carries the raw text exactly after `#` and an initial [`Placement`] hint.
542    /// The companion [`Token`] span covers the whole source comment, including `#` and excluding the
543    /// line break.
544    #[cfg(feature = "comments")]
545    Comment(
546        /// Captured comment metadata.
547        Comment<'input>,
548    ),
549    /// A reserved YAML directive.
550    ReservedDirective(
551        /// Directive name.
552        String,
553        /// Directive parameters, split on YAML whitespace.
554        Vec<String>,
555    ),
556}
557
558/// A scanner token.
559#[derive(Clone, PartialEq, Debug, Eq)]
560pub struct Token<'input>(Span, TokenType<'input>);
561
562impl<'input> Token<'input> {
563    /// Create a scanner token from its source span and payload.
564    #[must_use]
565    pub const fn new(span: Span, token_type: TokenType<'input>) -> Self {
566        Self(span, token_type)
567    }
568
569    /// Return the source span covered by this token.
570    #[must_use]
571    pub const fn span(&self) -> Span {
572        self.0
573    }
574
575    /// Return the payload emitted by the scanner.
576    #[must_use]
577    pub const fn token_type(&self) -> &TokenType<'input> {
578        &self.1
579    }
580
581    /// Consume the token and return its source span and payload.
582    #[must_use]
583    pub fn into_parts(self) -> (Span, TokenType<'input>) {
584        (self.0, self.1)
585    }
586}
587
588/// Token payload used in the scanner's internal queue.
589///
590/// Public [`Token`] values are reconstructed when the scanner emits them.
591#[derive(Clone, PartialEq, Debug, Eq)]
592pub(crate) enum QueuedTokenType<'input> {
593    StreamStart,
594    StreamEnd,
595    VersionDirective(u32, u32),
596    TagDirective(Cow<'input, str>, Cow<'input, str>),
597    DocumentStart,
598    DocumentEnd,
599    BlockSequenceStart,
600    BlockMappingStart,
601    BlockEnd,
602    FlowSequenceStart,
603    FlowSequenceEnd,
604    FlowMappingStart,
605    FlowMappingEnd,
606    BlockEntry,
607    FlowEntry,
608    Key,
609    Value,
610    Alias(Cow<'input, str>),
611    Anchor(Cow<'input, str>),
612    Tag(Cow<'input, str>, Cow<'input, str>),
613    Scalar(ScalarStyle, Cow<'input, str>),
614    #[cfg(feature = "comments")]
615    Comment(Comment<'input>),
616    ReservedDirective(String, Vec<String>),
617}
618
619impl<'input> QueuedTokenType<'input> {
620    fn into_public(self) -> TokenType<'input> {
621        match self {
622            Self::StreamStart => TokenType::StreamStart,
623            Self::StreamEnd => TokenType::StreamEnd,
624            Self::VersionDirective(major, minor) => TokenType::VersionDirective(major, minor),
625            Self::TagDirective(handle, prefix) => TokenType::TagDirective(handle, prefix),
626            Self::DocumentStart => TokenType::DocumentStart,
627            Self::DocumentEnd => TokenType::DocumentEnd,
628            Self::BlockSequenceStart => TokenType::BlockSequenceStart,
629            Self::BlockMappingStart => TokenType::BlockMappingStart,
630            Self::BlockEnd => TokenType::BlockEnd,
631            Self::FlowSequenceStart => TokenType::FlowSequenceStart,
632            Self::FlowSequenceEnd => TokenType::FlowSequenceEnd,
633            Self::FlowMappingStart => TokenType::FlowMappingStart,
634            Self::FlowMappingEnd => TokenType::FlowMappingEnd,
635            Self::BlockEntry => TokenType::BlockEntry,
636            Self::FlowEntry => TokenType::FlowEntry,
637            Self::Key => TokenType::Key,
638            Self::Value => TokenType::Value,
639            Self::Alias(name) => TokenType::Alias(name),
640            Self::Anchor(name) => TokenType::Anchor(name),
641            Self::Tag(handle, suffix) => TokenType::Tag(handle, suffix),
642            Self::Scalar(style, value) => TokenType::Scalar(style, value),
643            #[cfg(feature = "comments")]
644            Self::Comment(comment) => TokenType::Comment(comment),
645            Self::ReservedDirective(name, params) => TokenType::ReservedDirective(name, params),
646        }
647    }
648}
649
650impl<'input> From<TokenType<'input>> for QueuedTokenType<'input> {
651    fn from(token: TokenType<'input>) -> Self {
652        match token {
653            TokenType::StreamStart => Self::StreamStart,
654            TokenType::StreamEnd => Self::StreamEnd,
655            TokenType::VersionDirective(major, minor) => Self::VersionDirective(major, minor),
656            TokenType::TagDirective(handle, prefix) => Self::TagDirective(handle, prefix),
657            TokenType::DocumentStart => Self::DocumentStart,
658            TokenType::DocumentEnd => Self::DocumentEnd,
659            TokenType::BlockSequenceStart => Self::BlockSequenceStart,
660            TokenType::BlockMappingStart => Self::BlockMappingStart,
661            TokenType::BlockEnd => Self::BlockEnd,
662            TokenType::FlowSequenceStart => Self::FlowSequenceStart,
663            TokenType::FlowSequenceEnd => Self::FlowSequenceEnd,
664            TokenType::FlowMappingStart => Self::FlowMappingStart,
665            TokenType::FlowMappingEnd => Self::FlowMappingEnd,
666            TokenType::BlockEntry => Self::BlockEntry,
667            TokenType::FlowEntry => Self::FlowEntry,
668            TokenType::Key => Self::Key,
669            TokenType::Value => Self::Value,
670            TokenType::Alias(name) => Self::Alias(name),
671            TokenType::Anchor(name) => Self::Anchor(name),
672            TokenType::Tag(handle, suffix) => Self::Tag(handle, suffix),
673            TokenType::Scalar(style, value) => Self::Scalar(style, value),
674            #[cfg(feature = "comments")]
675            TokenType::Comment(comment) => Self::Comment(comment),
676            TokenType::ReservedDirective(name, params) => Self::ReservedDirective(name, params),
677        }
678    }
679}
680
681/// A compact token stored by the scanner before it is emitted publicly.
682#[derive(Clone, PartialEq, Debug, Eq)]
683pub(crate) struct QueuedToken<'input>(pub(crate) Span, pub(crate) QueuedTokenType<'input>);
684
685impl<'input> QueuedToken<'input> {
686    fn into_public(self) -> Token<'input> {
687        Token(self.0, self.1.into_public())
688    }
689}
690
691impl<'input> From<Token<'input>> for QueuedToken<'input> {
692    fn from(token: Token<'input>) -> Self {
693        Self(token.0, token.1.into())
694    }
695}
696
697/// A scalar that was parsed and may correspond to a simple key.
698///
699/// Upon scanning the following YAML:
700/// ```yaml
701/// a: b
702/// ```
703/// We do not know that `a` is a key for a map until we have reached the following `:`. For this
704/// YAML, we would store `a` as a scalar token in the [`Scanner`], but not emit it yet. It would be
705/// kept inside the scanner until more context is fetched and we are able to know whether it is a
706/// plain scalar or a key.
707///
708/// For example, see the following two YAML documents:
709/// ```yaml
710/// ---
711/// a: b # Here, `a` is a key.
712/// ...
713/// ---
714/// a # Here, `a` is a plain scalar.
715/// ...
716/// ```
717/// An instance of [`SimpleKey`] is created in the [`Scanner`] when such ambiguity occurs.
718///
719/// In both documents, scanning `a` would lead to the creation of a [`SimpleKey`] with
720/// [`Self::possible`] set to `true`. The token for `a` would be pushed in the [`Scanner`] but not
721/// yet emitted. Instead, more context would be fetched (through [`Scanner::fetch_more_tokens`]).
722///
723/// In the first document, upon reaching the `:`, the [`SimpleKey`] would be inspected and our
724/// scalar `a` since it is a possible key, would be "turned" into a key. This is done by prepending
725/// a [`TokenType::Key`] to our scalar token in the [`Scanner`]. This way, the
726/// [`crate::parser::Parser`] would read the [`TokenType::Key`] token before the
727/// [`TokenType::Scalar`] token.
728///
729/// In the second document however, reaching EOF would mark the [`SimpleKey`] as no longer possible,
730/// and no [`TokenType::Key`] would be emitted by the scanner.
731#[derive(Clone, Copy, PartialEq, Debug, Eq)]
732struct SimpleKey {
733    /// Whether the token this [`SimpleKey`] refers to may still be a key.
734    ///
735    /// Sometimes, when we have more context, we notice that what we thought could be a key no
736    /// longer can be. In that case, [`Self::possible`] is set to `false`.
737    ///
738    /// For instance, let us consider the following invalid YAML:
739    /// ```yaml
740    /// key
741    ///   : value
742    /// ```
743    /// Upon reading the `\n` after `key`, the [`SimpleKey`] that was created for `key` is no longer
744    /// possible and [`Self::possible`] is set to `false`.
745    possible: bool,
746    /// Whether the token this [`SimpleKey`] refers to is required to be a key.
747    ///
748    /// With more context, we may know for sure that the token must be a key. If later input makes
749    /// that impossible, the scanner must report an error instead of silently treating the token as a
750    /// plain scalar.
751    ///
752    /// This happens for simple keys at the current block indentation where the surrounding
753    /// collection requires the next token to be a mapping key.
754    required: bool,
755    /// The index of the token referred to by the [`SimpleKey`].
756    ///
757    /// This is the index in the scanner, which takes into account both the tokens that have been
758    /// emitted and those about to be emitted. See [`Scanner::tokens_parsed`] and
759    /// [`Scanner::tokens`] for more details.
760    token_number: usize,
761    /// The position at which the token the [`SimpleKey`] refers to is.
762    mark: Marker,
763}
764
765impl SimpleKey {
766    /// Create a new [`SimpleKey`] at the given `Marker` and with the given flow level.
767    fn new(mark: Marker) -> SimpleKey {
768        SimpleKey {
769            possible: false,
770            required: false,
771            token_number: 0,
772            mark,
773        }
774    }
775}
776
777/// An indentation level on the stack of indentations.
778#[derive(Clone, Debug, Default)]
779struct Indent {
780    /// The former indentation level.
781    indent: isize,
782    /// Whether, upon closing, this indents generates a `BlockEnd` token.
783    ///
784    /// There are levels of indentation which do not start a block. Examples of this would be:
785    /// ```yaml
786    /// -
787    ///   foo # ok
788    /// -
789    /// bar # ko, bar needs to be indented further than the `-`.
790    /// - [
791    ///  baz, # ok
792    /// quux # accepted by default; invalid when `Options::strict_indentation` is true.
793    /// ] # accepted by default; invalid when `Options::strict_indentation` is true.
794    /// ```
795    ///
796    /// The indentation level created by the `-` is for a single entry in the sequence. Emitting a
797    /// `BlockEnd` when this indentation block ends would generate one `BlockEnd` per entry in the
798    /// sequence, although we must have exactly one to end the sequence.
799    needs_block_end: bool,
800}
801
802/// The knowledge we have about an implicit mapping.
803///
804/// Implicit mappings occur in flow sequences where the opening `{` for a mapping in a flow
805/// sequence is omitted:
806/// ```yaml
807/// [ a: b, c: d ]
808/// # Equivalent to
809/// [ { a: b }, { c: d } ]
810/// # Equivalent to
811/// - a: b
812/// - c: d
813/// ```
814///
815/// The state must be carefully tracked for each nested flow sequence since we must emit a
816/// [`FlowMappingStart`] event when encountering `a` and `c` in our previous example without a
817/// character hinting us. Similarly, we must emit a [`FlowMappingEnd`] event when we reach the `,`
818/// or the `]`. If the state is not properly tracked, we may omit to emit these events or emit them
819/// out-of-order.
820///
821/// [`FlowMappingStart`]: TokenType::FlowMappingStart
822/// [`FlowMappingEnd`]: TokenType::FlowMappingEnd
823#[derive(Debug, PartialEq)]
824enum ImplicitMappingState {
825    /// It is possible there is an implicit mapping.
826    ///
827    /// This state is the one when we have just encountered the opening `[`. We need more context
828    /// to know whether an implicit mapping follows.
829    Possible,
830    /// We are inside the implicit mapping.
831    ///
832    /// Note that this state is not set immediately (we need to have encountered the `:` to know).
833    Inside(usize),
834}
835
836/// The YAML scanner.
837///
838/// This corresponds to the low-level interface when reading YAML. The scanner emits tokens as they
839/// are read (akin to a lexer), but it also holds sufficient context to be able to disambiguate
840/// some of the constructs. It has understanding of indentation and whitespace and is able to
841/// generate error messages for some invalid YAML constructs.
842///
843/// It is however not a full parser and needs [`crate::parser::Parser`] to fully detect invalid
844/// YAML documents.
845///
846/// `Scanner` is a fallible iterator over [`Token`] values. A scanning failure is emitted as one
847/// [`Err`] item, after which the iterator is exhausted.
848#[derive(Debug)]
849#[allow(clippy::struct_excessive_bools)]
850pub struct Scanner<'input, T> {
851    /// The input source.
852    ///
853    /// This must implement [`Input`].
854    input: T,
855    /// Resource limits used while scanning.
856    options: Options,
857    /// The position of the cursor within the reader.
858    mark: Marker,
859    /// Buffer for tokens to be returned.
860    ///
861    /// This buffer can hold some temporary tokens that are not yet ready to be returned. For
862    /// instance, if we just read a scalar, it can be a value or a key if an implicit mapping
863    /// follows. In this case, the token stays in the `VecDeque` but cannot be returned from
864    /// [`Self::next`] until we have more context.
865    tokens: VecDeque<QueuedToken<'input>>,
866    /// Whether a terminal error has been emitted by the iterator.
867    failed: bool,
868    /// Terminal source failure retained even after its diagnostic has been returned.
869    source_error: Option<ScanError>,
870    /// Error found after one or more already-scanned comment tokens.
871    #[cfg(feature = "comments")]
872    deferred_error: Option<ScanError>,
873    /// Whether the input may contain `#` comment indicators.
874    ///
875    /// This remains a source-content hint when comment emission is disabled. In that mode it is
876    /// conservatively set to `true`, because the `false` fast path may only be used when the
877    /// source is known not to contain comments.
878    #[cfg(feature = "comments")]
879    comments_possible: bool,
880
881    /// Whether we have already emitted the `StreamStart` token.
882    stream_start_produced: bool,
883    /// Whether we have already emitted the `StreamEnd` token.
884    stream_end_produced: bool,
885    /// Whether the scanner is still in the prefix of the next document.
886    ///
887    /// A BOM may appear in a document prefix, before directives/comments/content. Once a document
888    /// start marker or any content token is scanned, another BOM is document content and must be
889    /// rejected unless it appears inside a quoted scalar.
890    document_prefix_allowed: bool,
891    /// Whether scanning has entered directives without reaching their document body.
892    in_directive_prefix: bool,
893    /// In some flow contexts, the value of a mapping is allowed to be adjacent to the `:`. When it
894    /// is, the index at which the `:` may be must be stored in `adjacent_value_allowed_at`.
895    adjacent_value_allowed_at: usize,
896    /// Whether a simple key could potentially start at the current position.
897    ///
898    /// Simple keys are the opposite of complex keys which are keys starting with `?`.
899    simple_key_allowed: bool,
900    /// A stack of potential simple keys.
901    ///
902    /// Refer to the documentation of [`SimpleKey`] for a more in-depth explanation of what they
903    /// are.
904    simple_keys: smallvec::SmallVec<[SimpleKey; 8]>,
905    /// Index of the oldest still-possible simple key, or `None` if there are none.
906    ///
907    /// Only the current flow level can save a key, so possible keys are ordered by source
908    /// position and token number. Keeping their first index avoids rescanning inactive levels
909    /// and lets expiry stop as soon as the oldest remaining candidate is still valid.
910    first_simple_key: Option<usize>,
911    /// The current indentation level.
912    indent: isize,
913    /// List of all block indentation levels we are in (except the current one).
914    indents: smallvec::SmallVec<[Indent; 8]>,
915    /// Level of nesting of flow collections.
916    flow_level: usize,
917    /// Number of open block collections that will each generate a `BlockEnd` token.
918    block_level: usize,
919    /// The number of tokens that have been returned from the scanner.
920    ///
921    /// This excludes the tokens from [`Self::tokens`].
922    tokens_parsed: usize,
923    /// Whether a token is ready to be taken from [`Self::tokens`].
924    token_available: bool,
925    /// Whether all characters encountered since the last newline were whitespace.
926    leading_whitespace: bool,
927    /// Whether we started a flow mapping at each flow nesting level.
928    ///
929    /// This is used to detect implicit flow mapping starts such as:
930    /// ```yaml
931    /// [ : foo ] # { null: "foo" }
932    /// ```
933    flow_mapping_started: smallvec::SmallVec<[bool; 8]>,
934    /// An array of states, representing whether flow sequences have implicit mappings.
935    ///
936    /// When a flow mapping is possible (when encountering the first `[` or a `,` in a sequence),
937    /// the state is set to [`Possible`].
938    /// When we encounter the `:`, we know we are in an implicit mapping and can set the state to
939    /// [`Inside`].
940    ///
941    /// There is one entry in this [`Vec`] for each nested flow sequence that we are in.
942    /// The entries are created with the opening `[` and popped with the closing `]`.
943    ///
944    /// [`Possible`]: ImplicitMappingState::Possible
945    /// [`Inside`]: ImplicitMappingState::Inside
946    implicit_flow_mapping_states: smallvec::SmallVec<[ImplicitMappingState; 8]>,
947    /// If a plain scalar was terminated by a `#` comment on its line, we set this
948    /// to detect an illegal multiline continuation on the following line.
949    interrupted_plain_by_comment: Option<Marker>,
950    /// Whether the scanner is still validating whitespace after an explicit `?` key indicator.
951    ///
952    /// This stays set across streamed comments, and across node properties in strict mode, to
953    /// distinguish tab separation from the space-only indentation required by a key node or
954    /// compact block collection.
955    explicit_key_tab_check_pending: bool,
956    /// A stack of markers for opening brackets `[` and `{`.
957    flow_markers: smallvec::SmallVec<[(Marker, char); 8]>,
958    buf_leading_break: String,
959    buf_trailing_breaks: String,
960    buf_whitespaces: String,
961}
962
963impl<'input, T: BorrowedInput<'input>> Iterator for Scanner<'input, T> {
964    type Item = Result<Token<'input>, ScanError>;
965
966    fn next(&mut self) -> Option<Self::Item> {
967        if self.failed {
968            return None;
969        }
970        match self.next_token() {
971            Ok(Some(tok)) => {
972                debug_print!(
973                    "    \x1B[;32m\u{21B3} {:?} \x1B[;36m{:?}\x1B[;m",
974                    tok.1,
975                    tok.0
976                );
977                Some(Ok(tok))
978            }
979            Ok(None) => None,
980            Err(error) => {
981                self.failed = true;
982                Some(Err(error))
983            }
984        }
985    }
986}
987
988impl<'input, T: BorrowedInput<'input>> core::iter::FusedIterator for Scanner<'input, T> {}
989
990/// A convenience alias for scanner functions that may fail without returning a value.
991type ScanResult = Result<(), ScanError>;
992
993/// Result of skipping inter-token whitespace and comments.
994///
995/// These facts are intentionally distinct: an ignored comment still changes some scanner
996/// decisions even though it did not produce a token that can be returned to the caller.
997#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
998struct SkipToNextTokenOutcome {
999    saw_comment: bool,
1000    #[cfg(feature = "comments")]
1001    queued_comment: bool,
1002}
1003
1004#[derive(Debug)]
1005enum FlowScalarBuf {
1006    /// Candidate for `Cow::Borrowed`.
1007    ///
1008    /// `start..end` is the committed verbatim range.
1009    /// `pending_ws_start..pending_ws_end` is a run of blanks that were seen but not yet
1010    /// committed (they must be dropped if followed by a line break).
1011    Borrowed {
1012        start: usize,
1013        end: usize,
1014        pending_ws_start: Option<usize>,
1015        pending_ws_end: usize,
1016    },
1017    Owned(String),
1018}
1019
1020impl FlowScalarBuf {
1021    #[inline]
1022    fn new_borrowed(start: usize) -> Self {
1023        Self::Borrowed {
1024            start,
1025            end: start,
1026            pending_ws_start: None,
1027            pending_ws_end: start,
1028        }
1029    }
1030
1031    #[inline]
1032    fn new_owned() -> Self {
1033        Self::Owned(String::new())
1034    }
1035
1036    #[inline]
1037    fn as_owned_mut(&mut self) -> Option<&mut String> {
1038        match self {
1039            Self::Owned(s) => Some(s),
1040            Self::Borrowed { .. } => None,
1041        }
1042    }
1043
1044    #[inline]
1045    fn commit_pending_ws(&mut self) {
1046        if let Self::Borrowed {
1047            end,
1048            pending_ws_start,
1049            pending_ws_end,
1050            ..
1051        } = self
1052        {
1053            if pending_ws_start.is_some() {
1054                *end = *pending_ws_end;
1055                *pending_ws_start = None;
1056            }
1057        }
1058    }
1059
1060    #[inline]
1061    fn note_pending_ws(&mut self, ws_start: usize, ws_end: usize) {
1062        if let Self::Borrowed {
1063            pending_ws_start,
1064            pending_ws_end,
1065            ..
1066        } = self
1067        {
1068            if pending_ws_start.is_none() {
1069                *pending_ws_start = Some(ws_start);
1070            }
1071            *pending_ws_end = ws_end;
1072        }
1073    }
1074
1075    #[inline]
1076    fn discard_pending_ws(&mut self) {
1077        if let Self::Borrowed {
1078            pending_ws_start,
1079            pending_ws_end,
1080            end,
1081            ..
1082        } = self
1083        {
1084            *pending_ws_start = None;
1085            *pending_ws_end = *end;
1086        }
1087    }
1088}
1089
1090impl<'input, T: BorrowedInput<'input>> Scanner<'input, T> {
1091    #[inline]
1092    fn promote_flow_scalar_buf_to_owned(
1093        &self,
1094        start_mark: &Marker,
1095        buf: &mut FlowScalarBuf,
1096    ) -> Result<(), ScanError> {
1097        let FlowScalarBuf::Borrowed {
1098            start,
1099            end,
1100            pending_ws_start: _,
1101            pending_ws_end: _,
1102        } = *buf
1103        else {
1104            return Ok(());
1105        };
1106
1107        let slice = self.input.slice_bytes(start, end).ok_or_else(|| {
1108            ScanError::from_kind(*start_mark, ErrorKind::InputOffsetsWithoutSlice)
1109        })?;
1110        *buf = FlowScalarBuf::Owned(slice.to_owned());
1111        Ok(())
1112    }
1113    /// Try to borrow a slice from the underlying input.
1114    ///
1115    /// This method uses the [`BorrowedInput`] trait to safely obtain a slice with the `'input`
1116    /// lifetime. For inputs that support zero-copy slicing (like `StrInput`), this returns
1117    /// `Some(&'input str)`. For streaming inputs, this returns `None`.
1118    #[inline]
1119    fn try_borrow_slice(&self, start: usize, end: usize) -> Option<&'input str> {
1120        self.input.slice_borrowed(start, end)
1121    }
1122
1123    /// Scan a tag handle for a `%TAG` directive as a `Cow<str>`.
1124    ///
1125    /// For `StrInput`, this will borrow from the input when possible. For other inputs, or if
1126    /// borrowing is not possible, it falls back to allocating.
1127    fn scan_tag_handle_directive_cow(
1128        &mut self,
1129        mark: &Marker,
1130        budget: &mut usize,
1131    ) -> Result<Cow<'input, str>, ScanError> {
1132        let Some(start) = self.input.byte_offset() else {
1133            return Ok(Cow::Owned(
1134                self.scan_tag_handle_directive_owned(mark, budget)?,
1135            ));
1136        };
1137
1138        if self.input.look_ch() != '!' {
1139            return Err(ScanError::from_kind(*mark, ErrorKind::ExpectedTagBang));
1140        }
1141
1142        // Consume the leading '!'.
1143        self.spend_directive_bytes(budget, 1, *mark)?;
1144        self.skip_non_blank();
1145
1146        // Consume ns-word-char (ASCII alphanumeric, '_' or '-') characters.
1147        // This mirrors `StrInput::fetch_while_is_alpha` but avoids allocation.
1148        self.input.lookahead(1);
1149        while self.input.next_is_alpha() {
1150            self.spend_directive_bytes(budget, 1, *mark)?;
1151            self.skip_non_blank();
1152            self.input.lookahead(1);
1153        }
1154
1155        // Optional trailing '!'.
1156        if self.input.peek() == '!' {
1157            self.spend_directive_bytes(budget, 1, *mark)?;
1158            self.skip_non_blank();
1159        }
1160
1161        let Some(end) = self.input.byte_offset() else {
1162            return Err(ScanError::from_kind(
1163                *mark,
1164                ErrorKind::InputSlicingUnavailable,
1165            ));
1166        };
1167
1168        let Some(slice) = self.try_borrow_slice(start, end) else {
1169            // Fall back to allocating if zero-copy borrow is not available.
1170            let slice = self
1171                .input
1172                .slice_bytes(start, end)
1173                .ok_or_else(|| ScanError::from_kind(*mark, ErrorKind::InputSlicingUnavailable))?;
1174            if !slice.ends_with('!') && slice != "!" {
1175                return Err(ScanError::from_kind(
1176                    *mark,
1177                    ErrorKind::ExpectedTagDirectiveBang,
1178                ));
1179            }
1180            return Ok(Cow::Owned(slice.to_owned()));
1181        };
1182
1183        if !slice.ends_with('!') && slice != "!" {
1184            return Err(ScanError::from_kind(
1185                *mark,
1186                ErrorKind::ExpectedTagDirectiveBang,
1187            ));
1188        }
1189
1190        Ok(Cow::Borrowed(slice))
1191    }
1192
1193    /// Owned `%TAG`-handle scanner for streaming inputs, with allocation bounded by `budget`.
1194    fn scan_tag_handle_directive_owned(
1195        &mut self,
1196        mark: &Marker,
1197        budget: &mut usize,
1198    ) -> Result<String, ScanError> {
1199        let mut string = String::new();
1200        if self.input.look_ch() != '!' {
1201            return Err(ScanError::from_kind(*mark, ErrorKind::ExpectedTagBang));
1202        }
1203
1204        self.spend_directive_bytes(budget, 1, *mark)?;
1205        string.push('!');
1206        self.skip_non_blank();
1207
1208        self.input.lookahead(1);
1209        while self.input.next_is_alpha() {
1210            self.spend_directive_bytes(budget, 1, *mark)?;
1211            string.push(self.input.peek());
1212            self.skip_non_blank();
1213            self.input.lookahead(1);
1214        }
1215
1216        if self.input.peek() == '!' {
1217            self.spend_directive_bytes(budget, 1, *mark)?;
1218            string.push('!');
1219            self.skip_non_blank();
1220        } else if string != "!" {
1221            return Err(ScanError::from_kind(
1222                *mark,
1223                ErrorKind::ExpectedTagDirectiveBang,
1224            ));
1225        }
1226
1227        Ok(string)
1228    }
1229
1230    /// Scan a tag prefix for a `%TAG` directive as a `Cow<str>`.
1231    ///
1232    /// This borrows from `StrInput` only when no URI escape sequences are encountered. If a `%`
1233    /// escape is present, the prefix must be decoded and therefore allocated.
1234    fn scan_tag_prefix_directive_cow(
1235        &mut self,
1236        start_mark: &Marker,
1237        budget: &mut usize,
1238    ) -> Result<Cow<'input, str>, ScanError> {
1239        let Some(start) = self.input.byte_offset() else {
1240            return Ok(Cow::Owned(
1241                self.scan_tag_prefix_directive_owned(start_mark, budget)?,
1242            ));
1243        };
1244
1245        // The prefix must start with either '!' (local) or a valid global tag char.
1246        if self.input.look_ch() == '!' {
1247            self.spend_directive_bytes(budget, 1, *start_mark)?;
1248            self.skip_non_blank();
1249        } else if !is_tag_char(self.input.peek()) {
1250            return Err(ScanError::from_kind(
1251                *start_mark,
1252                ErrorKind::InvalidGlobalTagCharacter,
1253            ));
1254        } else if self.input.peek() == '%' {
1255            // Needs decoding. Fall back to allocating path below.
1256        } else {
1257            self.spend_directive_bytes(budget, 1, *start_mark)?;
1258            self.skip_non_blank();
1259        }
1260
1261        // Consume URI chars while we can stay in the borrowed path.
1262        while is_uri_char(self.input.look_ch()) {
1263            if self.input.peek() == '%' {
1264                break;
1265            }
1266            self.spend_directive_bytes(budget, 1, *start_mark)?;
1267            self.skip_non_blank();
1268        }
1269
1270        // If we encountered an escape sequence, we must decode, therefore allocate.
1271        if self.input.peek() == '%' {
1272            let current = self
1273                .input
1274                .byte_offset()
1275                .expect("byte_offset() must remain available once enabled");
1276            let mut out = if let Some(slice) = self.input.slice_bytes(start, current) {
1277                slice.to_owned()
1278            } else {
1279                String::new()
1280            };
1281
1282            while is_uri_char(self.input.look_ch()) {
1283                if self.input.peek() == '%' {
1284                    out.push(self.scan_uri_escapes_with_budget(start_mark, Some(budget))?);
1285                } else {
1286                    self.spend_directive_bytes(budget, 1, *start_mark)?;
1287                    out.push(self.input.peek());
1288                    self.skip_non_blank();
1289                }
1290            }
1291            return Ok(Cow::Owned(out));
1292        }
1293
1294        let Some(end) = self.input.byte_offset() else {
1295            return Err(ScanError::from_kind(
1296                *start_mark,
1297                ErrorKind::InputSlicingUnavailable,
1298            ));
1299        };
1300
1301        let Some(slice) = self.try_borrow_slice(start, end) else {
1302            // Fall back to allocating if zero-copy borrow is not available.
1303            let slice = self.input.slice_bytes(start, end).ok_or_else(|| {
1304                ScanError::from_kind(*start_mark, ErrorKind::InputSlicingUnavailable)
1305            })?;
1306            return Ok(Cow::Owned(slice.to_owned()));
1307        };
1308
1309        Ok(Cow::Borrowed(slice))
1310    }
1311
1312    /// Owned `%TAG`-prefix scanner for streaming inputs, with allocation bounded by `budget`.
1313    fn scan_tag_prefix_directive_owned(
1314        &mut self,
1315        start_mark: &Marker,
1316        budget: &mut usize,
1317    ) -> Result<String, ScanError> {
1318        let mut string = String::new();
1319
1320        if self.input.look_ch() == '!' {
1321            self.spend_directive_bytes(budget, 1, *start_mark)?;
1322            string.push('!');
1323            self.skip_non_blank();
1324        } else if !is_tag_char(self.input.peek()) {
1325            return Err(ScanError::from_kind(
1326                *start_mark,
1327                ErrorKind::InvalidGlobalTagCharacter,
1328            ));
1329        } else if self.input.peek() == '%' {
1330            string.push(self.scan_uri_escapes_with_budget(start_mark, Some(budget))?);
1331        } else {
1332            self.spend_directive_bytes(budget, 1, *start_mark)?;
1333            string.push(self.input.peek());
1334            self.skip_non_blank();
1335        }
1336
1337        while is_uri_char(self.input.look_ch()) {
1338            if self.input.peek() == '%' {
1339                string.push(self.scan_uri_escapes_with_budget(start_mark, Some(budget))?);
1340            } else {
1341                self.spend_directive_bytes(budget, 1, *start_mark)?;
1342                string.push(self.input.peek());
1343                self.skip_non_blank();
1344            }
1345        }
1346
1347        Ok(string)
1348    }
1349    /// Create a scanner over the given input source.
1350    #[must_use]
1351    pub fn new(input: T) -> Self {
1352        Self::with_options(input, Options::default())
1353    }
1354
1355    /// Create a scanner over the given input source with configurable resource limits.
1356    #[cfg_attr(
1357        feature = "comments",
1358        doc = "\n[`Options::emit_comments`] controls comment emission. \
1359               [`Options::max_buffered_comment_events`] has no effect when using a scanner \
1360               directly, because comment-event buffering is performed by [`crate::Parser`]."
1361    )]
1362    #[must_use]
1363    pub fn with_options(input: T, options: Options) -> Self {
1364        let initial_byte_offset = input.byte_offset();
1365        // Avoid the full-string `may_contain_comments` pre-scan when comments will not be emitted.
1366        // `true` also keeps comment validation on the scanner's comment-aware path.
1367        #[cfg(feature = "comments")]
1368        let comments_possible = !options.emit_comments || input.may_contain_comments();
1369        Scanner {
1370            input,
1371            options,
1372            mark: Marker::new(0, 1, 0).with_byte_offset(initial_byte_offset),
1373            tokens: VecDeque::with_capacity(64),
1374            failed: false,
1375            source_error: None,
1376            #[cfg(feature = "comments")]
1377            deferred_error: None,
1378            #[cfg(feature = "comments")]
1379            comments_possible,
1380
1381            stream_start_produced: false,
1382            stream_end_produced: false,
1383            document_prefix_allowed: true,
1384            in_directive_prefix: false,
1385            adjacent_value_allowed_at: 0,
1386            simple_key_allowed: true,
1387            simple_keys: smallvec::SmallVec::new(),
1388            first_simple_key: None,
1389            indent: -1,
1390            indents: smallvec::SmallVec::new(),
1391            flow_level: 0,
1392            block_level: 0,
1393            tokens_parsed: 0,
1394            token_available: false,
1395            leading_whitespace: true,
1396            flow_mapping_started: smallvec::SmallVec::new(),
1397            implicit_flow_mapping_states: smallvec::SmallVec::new(),
1398            flow_markers: smallvec::SmallVec::new(),
1399            interrupted_plain_by_comment: None,
1400            explicit_key_tab_check_pending: false,
1401
1402            buf_leading_break: String::with_capacity(128),
1403            buf_trailing_breaks: String::with_capacity(128),
1404            buf_whitespaces: String::with_capacity(128),
1405        }
1406    }
1407
1408    #[cold]
1409    fn scan_error(&self, kind: ErrorKind) -> ScanError {
1410        ScanError::from_kind(self.mark, kind)
1411    }
1412
1413    #[inline]
1414    fn ensure_current_char_is_printable(&self) -> ScanResult {
1415        let character = self.input.peek();
1416        if self.input.next_is_z() || is_printable(character) {
1417            Ok(())
1418        } else {
1419            Err(self.scan_error(ErrorKind::UnexpectedCharacter { character }))
1420        }
1421    }
1422
1423    #[cold]
1424    fn simple_key_expected(mark: Marker) -> ScanError {
1425        ScanError::from_kind(mark, ErrorKind::SimpleKeyExpected)
1426    }
1427
1428    #[cold]
1429    fn unclosed_bracket(mark: Marker, bracket: char) -> ScanError {
1430        ScanError::from_kind(mark, ErrorKind::UnclosedFlowCollection { open: bracket })
1431    }
1432
1433    /// Consume the next character. It is assumed the next character is a blank.
1434    #[inline]
1435    fn skip_blank(&mut self) {
1436        self.input.skip();
1437
1438        self.mark.offsets.chars += 1;
1439        self.mark.col += 1;
1440        self.mark.offsets.bytes = self.input.byte_offset();
1441    }
1442
1443    /// Consume the next character. It is assumed the next character is not a blank.
1444    #[inline]
1445    fn skip_non_blank(&mut self) {
1446        self.input.skip();
1447
1448        self.mark.offsets.chars += 1;
1449        self.mark.col += 1;
1450        self.mark.offsets.bytes = self.input.byte_offset();
1451        self.leading_whitespace = false;
1452    }
1453
1454    /// Consume a byte order mark from a document prefix.
1455    ///
1456    /// The source index advances, but the logical column remains unchanged so directives and
1457    /// document markers immediately following the BOM are still recognized as line-start tokens.
1458    #[inline]
1459    fn skip_bom(&mut self) {
1460        self.input.skip();
1461
1462        self.mark.offsets.chars += 1;
1463        self.mark.offsets.bytes = self.input.byte_offset();
1464    }
1465
1466    /// Consume one character that belongs to a comment.
1467    ///
1468    /// Unlike [`Self::skip_non_blank`], this deliberately does not change
1469    /// `leading_whitespace`. Comments are presentation content, so consuming one for either
1470    /// tokenization or skipping should only advance position bookkeeping.
1471    #[inline]
1472    fn skip_comment_char(&mut self) {
1473        self.input.skip();
1474
1475        self.mark.offsets.chars += 1;
1476        self.mark.col += 1;
1477        self.mark.offsets.bytes = self.input.byte_offset();
1478    }
1479
1480    /// Consume the next characters. It is assumed none of the next characters are blanks.
1481    #[inline]
1482    fn skip_n_non_blank(&mut self, count: usize) {
1483        for _ in 0..count {
1484            self.input.skip();
1485            self.mark.offsets.chars += 1;
1486            self.mark.col += 1;
1487        }
1488        self.mark.offsets.bytes = self.input.byte_offset();
1489        self.leading_whitespace = false;
1490    }
1491
1492    /// Consume the next character. It is assumed the next character is a newline.
1493    #[inline]
1494    fn skip_nl(&mut self) {
1495        self.input.skip();
1496
1497        self.mark.offsets.chars += 1;
1498        self.mark.col = 0;
1499        self.mark.line += 1;
1500        self.mark.offsets.bytes = self.input.byte_offset();
1501        self.leading_whitespace = true;
1502    }
1503
1504    /// Consume a line break (either CR, LF, or CRLF), if any. Do nothing if there is none.
1505    #[inline]
1506    fn skip_linebreak(&mut self) {
1507        if self.input.next_2_are('\r', '\n') {
1508            // While technically not a blank, this does not matter as `self.leading_whitespace`
1509            // will be reset by `skip_nl`.
1510            self.skip_blank();
1511            self.skip_nl();
1512        } else if self.input.next_is_break() {
1513            self.skip_nl();
1514        }
1515    }
1516
1517    #[cfg(all(test, feature = "comments"))]
1518    fn scan_comment_token(&mut self) -> Result<Token<'input>, ScanError> {
1519        Ok(self.scan_comment_queued_token()?.into_public())
1520    }
1521
1522    #[cfg(feature = "comments")]
1523    fn scan_comment_queued_token(&mut self) -> Result<QueuedToken<'input>, ScanError> {
1524        let start_mark = self.mark;
1525        debug_assert_eq!(self.input.peek(), '#');
1526        let placement = if self.leading_whitespace {
1527            Placement::Free
1528        } else {
1529            Placement::Right
1530        };
1531
1532        self.skip_comment_char();
1533
1534        let text = if let Some(start) = self.input.byte_offset() {
1535            // Stable byte offsets are available; slice the payload once at the end.
1536            let n = self.input.skip_while_non_breakz();
1537            self.mark.offsets.chars += n;
1538            self.mark.col += n;
1539            let byte_offset = self.input.byte_offset();
1540            self.mark.offsets.bytes = byte_offset;
1541            let end = byte_offset.expect("byte_offset must remain available once enabled");
1542
1543            if let Some(slice) = self.try_borrow_slice(start, end) {
1544                Cow::Borrowed(slice)
1545            } else if let Some(slice) = self.input.slice_bytes(start, end) {
1546                // Defensive fallback for third-party inputs that expose offsets but cannot borrow.
1547                Cow::Owned(slice.to_owned())
1548            } else {
1549                return Err(ScanError::from_kind(
1550                    start_mark,
1551                    ErrorKind::InputOffsetsWithoutSlice,
1552                ));
1553            }
1554        } else {
1555            // Streaming input without stable offsets; collect into an owned string.
1556            let mut owned = String::new();
1557            while {
1558                let character = self.input.look_ch();
1559                !is_breakz(character) && is_printable(character)
1560            } {
1561                owned.push(self.input.peek());
1562                self.skip_comment_char();
1563            }
1564            Cow::Owned(owned)
1565        };
1566
1567        self.ensure_current_char_is_printable()?;
1568
1569        let end_mark = self.mark;
1570        let span = Span::new(start_mark, end_mark);
1571        Ok(QueuedToken(
1572            span,
1573            QueuedTokenType::Comment(Comment { text, placement }),
1574        ))
1575    }
1576
1577    #[cfg(feature = "comments")]
1578    fn push_comment_token(&mut self) -> ScanResult {
1579        let token = self.scan_comment_queued_token()?;
1580        self.tokens.push_back(token);
1581        Ok(())
1582    }
1583
1584    /// Consume the comment at the current position and return whether it was queued as a token.
1585    fn consume_comment(&mut self) -> Result<bool, ScanError> {
1586        #[cfg(feature = "comments")]
1587        if self.options.emit_comments {
1588            self.push_comment_token()?;
1589            return Ok(true);
1590        }
1591        self.skip_comment()?;
1592        Ok(false)
1593    }
1594
1595    fn skip_comment(&mut self) -> ScanResult {
1596        debug_assert_eq!(self.input.peek(), '#');
1597
1598        self.skip_comment_char();
1599        let n = self.input.skip_while_non_breakz();
1600        self.mark.offsets.chars += n;
1601        self.mark.col += n;
1602        self.mark.offsets.bytes = self.input.byte_offset();
1603        self.ensure_current_char_is_printable()
1604    }
1605
1606    /// Return whether the [`TokenType::StreamStart`] event has been emitted.
1607    #[inline]
1608    #[must_use]
1609    pub fn stream_started(&self) -> bool {
1610        self.stream_start_produced
1611    }
1612
1613    /// Return whether the [`TokenType::StreamEnd`] event has been emitted.
1614    #[inline]
1615    #[must_use]
1616    pub fn stream_ended(&self) -> bool {
1617        self.stream_end_produced
1618    }
1619
1620    /// Return the current position in the input stream.
1621    #[inline]
1622    #[must_use]
1623    pub fn mark(&self) -> Marker {
1624        self.mark
1625    }
1626
1627    /// Whether a failed scan is still inside a document's directive header.
1628    pub(crate) fn in_directive_prefix(&self) -> bool {
1629        self.in_directive_prefix
1630    }
1631
1632    /// Abandon scanner state and resume at the next document boundary after a parse error.
1633    ///
1634    /// The parser may already hold a boundary token, and scanner lookahead may have queued one.
1635    /// Preserve either before searching the unread input; the source cannot be rewound.
1636    pub(crate) fn proceed_next_document(
1637        &mut self,
1638        token: Option<QueuedToken<'input>>,
1639    ) -> ScanResult {
1640        self.check_source_error()?;
1641        self.input.lookahead(4);
1642        self.check_source_error()?;
1643
1644        let cursor = self.mark;
1645        let at_line_end = self.input.next_is_z() || self.input.next_is_break();
1646        let at_real_nul = !self.input.next_is_z() && self.input.peek() == '\0';
1647        let boundary = token
1648            .into_iter()
1649            .chain(self.tokens.drain(..))
1650            .find(|token| {
1651                match token.1 {
1652                    QueuedTokenType::DocumentStart => {
1653                        // A real NUL is invalid content, not the EOF delimiter used by input helpers.
1654                        cursor != token.0.end || !at_real_nul
1655                    }
1656                    QueuedTokenType::DocumentEnd => {
1657                        // An end marker is queued before its trailing line is validated. A scanner
1658                        // error can therefore leave an invalid `... trailing` in the token queue.
1659                        cursor.line > token.0.end.line || at_line_end
1660                    }
1661                    QueuedTokenType::StreamEnd => true,
1662                    _ => false,
1663                }
1664            });
1665        self.reset_document_state();
1666        if let Some(boundary) = boundary {
1667            self.queue_recovery_boundary(boundary);
1668            return Ok(());
1669        }
1670
1671        loop {
1672            self.input.lookahead(4);
1673            self.check_source_error()?;
1674            if self.input.next_is_z() {
1675                self.queue_recovery_boundary(QueuedToken(
1676                    Span::empty(self.mark),
1677                    QueuedTokenType::StreamEnd,
1678                ));
1679                return Ok(());
1680            }
1681
1682            if self.mark.col == 0 {
1683                if is_bom(self.input.peek()) {
1684                    self.skip_bom();
1685                    continue;
1686                }
1687                let start = self.input.next_is_document_start();
1688                if start || self.input.next_is_document_end() {
1689                    let mark = self.mark;
1690                    self.skip_n_non_blank(3);
1691                    let span = Span::new(mark, self.mark);
1692                    self.input.lookahead(1);
1693                    self.check_source_error()?;
1694                    // `next_is_document_*` also accepts NUL padding. Require actual EOF if the
1695                    // separator is NUL so invalid source characters never masquerade as padding.
1696                    if self.input.next_is_z()
1697                        || matches!(self.input.peek(), ' ' | '\t' | '\r' | '\n')
1698                    {
1699                        if start {
1700                            self.queue_recovery_boundary(QueuedToken(
1701                                span,
1702                                QueuedTokenType::DocumentStart,
1703                            ));
1704                            return Ok(());
1705                        }
1706                        if self.skip_recovery_document_end_line()? {
1707                            self.queue_recovery_boundary(QueuedToken(
1708                                span,
1709                                QueuedTokenType::DocumentEnd,
1710                            ));
1711                            return Ok(());
1712                        }
1713                    }
1714                }
1715            }
1716
1717            self.input.lookahead(2);
1718            self.check_source_error()?;
1719            if self.input.next_is_break() {
1720                self.skip_linebreak();
1721            } else if !self.input.next_is_z() {
1722                self.skip_non_blank();
1723            }
1724        }
1725    }
1726
1727    /// Consume only a valid end-marker suffix; malformed suffixes remain discarded document text.
1728    fn skip_recovery_document_end_line(&mut self) -> Result<bool, ScanError> {
1729        let mut comment = false;
1730        loop {
1731            self.input.lookahead(2);
1732            self.check_source_error()?;
1733            if self.input.next_is_z() || self.input.next_is_break() {
1734                return Ok(true);
1735            }
1736            let ch = self.input.peek();
1737            if !is_printable(ch) {
1738                return Ok(false);
1739            }
1740            if comment || matches!(ch, ' ' | '\t') {
1741                self.skip_non_blank();
1742            } else if ch == '#' {
1743                comment = true;
1744                self.skip_non_blank();
1745            } else {
1746                return Ok(false);
1747            }
1748        }
1749    }
1750
1751    /// Reset document-scoped syntax without changing the source cursor or parser options.
1752    fn reset_document_state(&mut self) {
1753        self.tokens.clear();
1754        self.failed = false;
1755        #[cfg(feature = "comments")]
1756        {
1757            self.deferred_error = None;
1758        }
1759        self.stream_start_produced = true;
1760        self.stream_end_produced = false;
1761        self.document_prefix_allowed = true;
1762        self.in_directive_prefix = false;
1763        self.adjacent_value_allowed_at = 0;
1764        self.simple_key_allowed = true;
1765        self.simple_keys.clear();
1766        self.simple_keys.push(SimpleKey::new(self.mark));
1767        self.first_simple_key = None;
1768        self.indent = -1;
1769        self.indents.clear();
1770        self.flow_level = 0;
1771        self.block_level = 0;
1772        self.tokens_parsed = 0;
1773        self.token_available = false;
1774        self.leading_whitespace = self.mark.col == 0;
1775        self.flow_mapping_started.clear();
1776        self.implicit_flow_mapping_states.clear();
1777        self.flow_markers.clear();
1778        self.interrupted_plain_by_comment = None;
1779        self.explicit_key_tab_check_pending = false;
1780        self.buf_leading_break.clear();
1781        self.buf_trailing_breaks.clear();
1782        self.buf_whitespaces.clear();
1783    }
1784
1785    fn queue_recovery_boundary(&mut self, token: QueuedToken<'input>) {
1786        self.document_prefix_allowed = matches!(token.1, QueuedTokenType::DocumentEnd);
1787        self.disallow_simple_key();
1788        self.tokens.push_back(token);
1789        self.token_available = true;
1790    }
1791
1792    /// Source failures cannot be recovered by discarding YAML syntax.
1793    pub(crate) fn check_source_error(&mut self) -> ScanResult {
1794        if let Some(kind) = self.input.take_source_error() {
1795            self.source_error
1796                .get_or_insert_with(|| ScanError::from_kind(self.mark, kind));
1797        }
1798        match &self.source_error {
1799            Some(error) => Err(error.clone()),
1800            None => Ok(()),
1801        }
1802    }
1803
1804    /// Return whether this scanner may emit comment tokens.
1805    #[cfg(feature = "comments")]
1806    #[inline]
1807    pub(crate) fn comments_possible(&self) -> bool {
1808        self.options.emit_comments && self.comments_possible
1809    }
1810
1811    // Read and consume a line break (either `\r`, `\n` or `\r\n`).
1812    //
1813    // A `\n` is pushed into `s`.
1814    //
1815    // # Panics (in debug)
1816    // If the next characters do not correspond to a line break.
1817    #[track_caller]
1818    #[inline]
1819    fn read_break(&mut self, s: &mut String) {
1820        self.skip_break();
1821        s.push('\n');
1822    }
1823
1824    // Read and consume a line break (either `\r`, `\n` or `\r\n`).
1825    //
1826    // # Panics (in debug)
1827    // If the next characters do not correspond to a line break.
1828    #[track_caller]
1829    #[inline]
1830    fn skip_break(&mut self) {
1831        let c = self.input.peek();
1832        let nc = self.input.peek_nth(1);
1833        debug_assert!(is_break(c));
1834        if c == '\r' && nc == '\n' {
1835            self.skip_blank();
1836        }
1837        self.skip_nl();
1838    }
1839
1840    /// Insert a token at the given position.
1841    ///
1842    /// # Panics
1843    /// Panics if `pos` is past the end of the token queue.
1844    #[track_caller]
1845    fn insert_token(&mut self, pos: usize, tok: Token<'input>) {
1846        let old_len = self.tokens.len();
1847        assert!(pos <= old_len);
1848        self.tokens.insert(pos, tok.into());
1849    }
1850
1851    fn simple_key_token_index(&self, sk: &SimpleKey, mark: Marker) -> Result<usize, ScanError> {
1852        let Some(index) = sk.token_number.checked_sub(self.tokens_parsed) else {
1853            return Err(ScanError::from_kind(mark, ErrorKind::InvalidSimpleKey));
1854        };
1855        if index > self.tokens.len() {
1856            return Err(ScanError::from_kind(mark, ErrorKind::InvalidSimpleKey));
1857        }
1858        Ok(index)
1859    }
1860
1861    #[inline]
1862    fn allow_simple_key(&mut self) {
1863        self.simple_key_allowed = true;
1864    }
1865
1866    #[inline]
1867    fn disallow_simple_key(&mut self) {
1868        self.simple_key_allowed = false;
1869    }
1870
1871    /// Scan enough input to append one next token to the internal token queue.
1872    ///
1873    /// # Errors
1874    /// Returns `ScanError` when the scanner does not find the next expected token.
1875    fn fetch_next_token(&mut self) -> ScanResult {
1876        let result = self.fetch_next_token_impl();
1877        self.check_source_error()?;
1878        result
1879    }
1880
1881    fn fetch_next_token_impl(&mut self) -> ScanResult {
1882        self.input.lookahead(1);
1883
1884        if !self.stream_start_produced {
1885            self.fetch_stream_start();
1886            return Ok(());
1887        }
1888        loop {
1889            let outcome = self.skip_to_next_token()?;
1890            #[cfg(feature = "comments")]
1891            if outcome.queued_comment {
1892                return Ok(());
1893            }
1894            if outcome.saw_comment && !self.tokens.is_empty() {
1895                return Ok(());
1896            }
1897            if !outcome.saw_comment {
1898                break;
1899            }
1900            // No token is waiting, so an ignored leading comment is not enough to satisfy this
1901            // fetch. Continue until a token is produced or another scanner condition stops us.
1902        }
1903
1904        debug_print!(
1905            "  \x1B[38;5;244m\u{2192} fetch_next_token after whitespace {:?} {:?}\x1B[m",
1906            self.mark,
1907            self.input.peek()
1908        );
1909
1910        self.stale_simple_keys()?;
1911
1912        let mark = self.mark;
1913        self.unroll_indent(mark.col as isize);
1914
1915        self.input.lookahead(4);
1916
1917        if self.input.next_is_z() {
1918            self.fetch_stream_end()?;
1919            return Ok(());
1920        }
1921
1922        self.ensure_current_char_is_printable()?;
1923
1924        if self.mark.col == 0 {
1925            if self.input.next_char_is('%') {
1926                self.in_directive_prefix = true;
1927                return self.fetch_directive();
1928            } else if self.input.next_is_document_start() {
1929                return self.fetch_document_indicator(TokenType::DocumentStart);
1930            } else if self.input.next_is_document_end() {
1931                self.fetch_document_indicator(TokenType::DocumentEnd)?;
1932                self.skip_ws_to_eol(SkipTabs::Yes)?;
1933                if !self.input.next_is_breakz() {
1934                    return Err(self.scan_error(ErrorKind::InvalidDocumentEnd));
1935                }
1936                return Ok(());
1937            }
1938        }
1939
1940        self.in_directive_prefix = false;
1941        if self.document_prefix_allowed {
1942            self.document_prefix_allowed = false;
1943        }
1944
1945        // Block indentation was handled by `unroll_indent`. Flow entries and delimiters
1946        // may be under-indented only when strict YAML indentation is disabled.
1947        if self.options.strict_indentation
1948            && self.flow_level > 0
1949            && (self.mark.col as isize) <= self.flow_block_indent()
1950        {
1951            return Err(self.scan_error(ErrorKind::InvalidIndentation));
1952        }
1953
1954        let c = self.input.peek();
1955        let nc = self.input.peek_nth(1);
1956        match c {
1957            '[' => self.fetch_flow_collection_start(TokenType::FlowSequenceStart),
1958            '{' => self.fetch_flow_collection_start(TokenType::FlowMappingStart),
1959            ']' => self.fetch_flow_collection_end(TokenType::FlowSequenceEnd, '[', ']'),
1960            '}' => self.fetch_flow_collection_end(TokenType::FlowMappingEnd, '{', '}'),
1961            ',' => self.fetch_flow_entry(),
1962            '-' if is_blank_or_breakz(nc) => self.fetch_block_entry(),
1963            '?' if is_blank_or_breakz(nc) => self.fetch_key(),
1964            ':' if is_blank_or_breakz(nc) => self.fetch_value(),
1965            ':' if self.flow_level > 0
1966                && (is_flow(nc) || self.mark.index() == self.adjacent_value_allowed_at) =>
1967            {
1968                self.fetch_flow_value()
1969            }
1970            // Is it an alias?
1971            '*' => self.fetch_anchor(true),
1972            // Is it an anchor?
1973            '&' => self.fetch_anchor(false),
1974            '!' => self.fetch_tag(),
1975            // Is it a literal scalar?
1976            '|' if self.flow_level == 0 => self.fetch_block_scalar(true),
1977            // Is it a folded scalar?
1978            '>' if self.flow_level == 0 => self.fetch_block_scalar(false),
1979            '\'' => self.fetch_flow_scalar(true),
1980            '"' => self.fetch_flow_scalar(false),
1981            // plain scalar
1982            '-' if !is_blank_or_breakz(nc) => self.fetch_plain_scalar(),
1983            ':' | '?' if !is_blank_or_breakz(nc) && self.flow_level == 0 => {
1984                self.fetch_plain_scalar()
1985            }
1986            // Opted-in BOMs fall through to `fetch_plain_scalar` as content characters.
1987            c if is_bom(c) && !self.options.bom_inside_document_as_content => {
1988                Err(self.scan_error(ErrorKind::BomInsideDocument))
1989            }
1990            '|' | '>' | '%' | '@' | '`' => {
1991                Err(self.scan_error(ErrorKind::UnexpectedCharacter { character: c }))
1992            }
1993            _ => self.fetch_plain_scalar(),
1994        }
1995    }
1996
1997    /// Return the next compact queued token, scanning more input when needed.
1998    ///
1999    /// # Errors
2000    /// Returns `ScanError` when scanning fails to find an expected next token.
2001    pub(crate) fn next_queued_token(&mut self) -> Result<Option<QueuedToken<'input>>, ScanError> {
2002        #[cfg(feature = "comments")]
2003        if self.deferred_error.is_some() {
2004            if !matches!(
2005                self.tokens.front().map(|token| &token.1),
2006                Some(QueuedTokenType::Comment(_))
2007            ) {
2008                if let Some(error) = self.deferred_error.take() {
2009                    return error.into_result();
2010                }
2011            }
2012            self.token_available = true;
2013        }
2014
2015        if self.stream_end_produced {
2016            return Ok(None);
2017        }
2018
2019        if !self.token_available {
2020            #[cfg(feature = "comments")]
2021            if let Err(error) = self.fetch_more_tokens() {
2022                if matches!(
2023                    self.tokens.front().map(|token| &token.1),
2024                    Some(QueuedTokenType::Comment(_))
2025                ) {
2026                    self.deferred_error = Some(error);
2027                } else {
2028                    return Err(error);
2029                }
2030            }
2031            #[cfg(not(feature = "comments"))]
2032            self.fetch_more_tokens()?;
2033        }
2034        let Some(t) = self.tokens.pop_front() else {
2035            unreachable!("fetch_more_tokens succeeded without producing a token")
2036        };
2037        self.token_available = false;
2038        self.tokens_parsed += 1;
2039
2040        let is_stream_end = matches!(t.1, QueuedTokenType::StreamEnd);
2041        if is_stream_end {
2042            self.stream_end_produced = true;
2043        }
2044        Ok(Some(t))
2045    }
2046
2047    /// Return the next queued token, scanning more input when needed.
2048    ///
2049    /// # Errors
2050    /// Returns `ScanError` when scanning fails to find an expected next token.
2051    fn next_token(&mut self) -> Result<Option<Token<'input>>, ScanError> {
2052        Ok(self.next_queued_token()?.map(QueuedToken::into_public))
2053    }
2054
2055    /// Scan more input until a token is ready to be returned.
2056    ///
2057    /// # Errors
2058    /// Returns `ScanError` when scanning fails.
2059    fn fetch_more_tokens(&mut self) -> ScanResult {
2060        let mut need_more;
2061        loop {
2062            if self.tokens.is_empty() {
2063                need_more = true;
2064            } else {
2065                #[cfg(feature = "comments")]
2066                {
2067                    need_more = false;
2068                }
2069                // Stale potential keys that we know won't be keys.
2070                self.stale_simple_keys()?;
2071                #[cfg(feature = "comments")]
2072                if !matches!(
2073                    self.tokens.front().map(|token| &token.1),
2074                    Some(QueuedTokenType::Comment(_))
2075                ) {
2076                    // Only the oldest possible key can refer to the next token to emit.
2077                    need_more = self.first_simple_key.is_some_and(|index| {
2078                        self.simple_keys[index].token_number == self.tokens_parsed
2079                    });
2080                }
2081                #[cfg(not(feature = "comments"))]
2082                {
2083                    need_more = self.first_simple_key.is_some_and(|index| {
2084                        self.simple_keys[index].token_number == self.tokens_parsed
2085                    });
2086                }
2087            }
2088
2089            // Stop fetching immediately after document end/start markers
2090            // to allow the parser to emit the event before reading more content.
2091            if let Some(token) = self.tokens.back() {
2092                if matches!(
2093                    token.1,
2094                    QueuedTokenType::DocumentEnd | QueuedTokenType::DocumentStart
2095                ) {
2096                    break;
2097                }
2098            }
2099
2100            if !need_more {
2101                break;
2102            }
2103            self.fetch_next_token()?;
2104        }
2105        self.token_available = true;
2106
2107        Ok(())
2108    }
2109
2110    /// Mark simple keys that can no longer be keys as such.
2111    ///
2112    /// This function sets `possible` to `false` to each key that, now we have more context, we
2113    /// know will not be keys.
2114    ///
2115    /// # Errors
2116    /// This function returns an error if one of the keys becoming impossible was required to be a
2117    /// key.
2118    fn stale_simple_keys(&mut self) -> ScanResult {
2119        while let Some(index) = self.first_simple_key {
2120            let sk = &mut self.simple_keys[index];
2121            debug_assert!(sk.possible);
2122            let is_line_stale = self.flow_level == 0 && sk.mark.line < self.mark.line;
2123            // The length cap applies in flow contexts too; otherwise token buffering can grow
2124            // without bound while the scanner waits to see whether a later ':' resolves the key.
2125            let is_length_stale = self.mark.index().saturating_sub(sk.mark.index())
2126                > self.options.simple_key_max_lookahead;
2127
2128            if !is_line_stale && !is_length_stale {
2129                // Inner candidates start no earlier, so they cannot have expired either.
2130                break;
2131            }
2132            if sk.required {
2133                return Err(Self::simple_key_expected(sk.mark));
2134            }
2135            sk.possible = false;
2136            // Skip inactive slots only when advancing past an expired candidate. Saving a key
2137            // at an earlier level requires popping its descendants, so this work is amortized.
2138            self.first_simple_key = self.simple_keys[index + 1..]
2139                .iter()
2140                .position(|key| key.possible)
2141                .map(|offset| index + 1 + offset);
2142        }
2143        Ok(())
2144    }
2145
2146    /// Skip over whitespace (`\t`, ` `, `\n`, `\r`) until the next non-comment token.
2147    ///
2148    /// The function returns after one comment, whether it was queued or ignored, so callers can
2149    /// publish completed syntax before scanning later input that may fail.
2150    #[cfg_attr(
2151        feature = "comments",
2152        doc = "\nWhen comment emission is enabled, encountered comments are queued as \
2153               [`TokenType::Comment`] tokens so the parser can emit presentation events."
2154    )]
2155    ///
2156    /// # Errors
2157    /// This function returns an error if a tab is encountered where there should not be
2158    /// one.
2159    fn skip_to_next_token(&mut self) -> Result<SkipToNextTokenOutcome, ScanError> {
2160        // Hot-path helper: consume a single logical line break and apply simple-key rules.
2161        // (Kept local to ensure the compiler can inline it easily.)
2162        let consume_linebreak = |this: &mut Self| {
2163            this.input.lookahead(2);
2164            this.skip_linebreak();
2165            if this.flow_level == 0 {
2166                this.allow_simple_key();
2167            }
2168        };
2169
2170        let mut outcome = SkipToNextTokenOutcome::default();
2171        loop {
2172            let ch = self.input.look_ch();
2173            if self.explicit_key_tab_check_pending {
2174                match ch {
2175                    '\t' => {
2176                        self.skip_explicit_key_tab()?;
2177                        continue;
2178                    }
2179                    ' ' | '\n' | '\r' | '#' => {}
2180                    '&' | '!' if self.options.strict_indentation => {}
2181                    _ => self.explicit_key_tab_check_pending = false,
2182                }
2183            }
2184
2185            match ch {
2186                // Tabs may separate flow entries, but cannot supply required indentation.
2187                '\t' => {
2188                    let indent = if self.options.strict_indentation && self.flow_level > 0 {
2189                        self.flow_block_indent() + 1
2190                    } else {
2191                        self.indent
2192                    };
2193                    if self.is_within_block()
2194                        && self.leading_whitespace
2195                        && (self.mark.col as isize) < indent
2196                    {
2197                        let (chars_consumed, _) = self.input.skip_ws_to_eol_blanks(SkipTabs::Yes);
2198                        self.mark.col += chars_consumed;
2199                        self.mark.offsets.chars += chars_consumed;
2200                        self.mark.offsets.bytes = self.input.byte_offset();
2201
2202                        // Let the ordinary comment branch record and yield after this comment.
2203                        if self.input.look_ch() == '#' {
2204                            continue;
2205                        }
2206
2207                        // If we have content on that line with a tab, return an error.
2208                        if !self.input.next_is_breakz() {
2209                            return Err(self.scan_error(ErrorKind::TabInBlockIndentation));
2210                        }
2211
2212                        // Micro-opt: if we stopped on a line break, consume it now (avoids another loop trip).
2213                        if matches!(self.input.look_ch(), '\n' | '\r') {
2214                            consume_linebreak(self);
2215                        }
2216                    } else {
2217                        // Non-indentation tab behaves like blank.
2218                        self.skip_blank();
2219                    }
2220                }
2221
2222                ' ' => self.skip_blank(),
2223
2224                '\n' | '\r' => consume_linebreak(self),
2225
2226                c if is_bom(c)
2227                    && self.document_prefix_allowed
2228                    && self.flow_level == 0
2229                    && self.mark.col == 0 =>
2230                {
2231                    self.skip_bom();
2232                }
2233
2234                '#' => {
2235                    outcome.saw_comment = true;
2236                    #[cfg(feature = "comments")]
2237                    {
2238                        outcome.queued_comment |= self.consume_comment()?;
2239                    }
2240                    #[cfg(not(feature = "comments"))]
2241                    self.skip_comment()?;
2242
2243                    // Micro-opt: comment-only lines are common; consume the following line break here.
2244                    if matches!(self.input.look_ch(), '\n' | '\r') {
2245                        consume_linebreak(self);
2246                    }
2247                    return Ok(outcome);
2248                }
2249
2250                _ => break,
2251            }
2252        }
2253
2254        // If a plain scalar was interrupted by a comment, and the next line could
2255        // continue the scalar in block context, this is invalid.
2256        if let Some(err_mark) = self.interrupted_plain_by_comment.take() {
2257            // BS4K should only trigger when the continuation would start on the immediate next
2258            // line (no intervening empty/comment-only lines). A blank line resets the folding
2259            // opportunity and thus should not error.
2260            let is_immediate_next_line = self.mark.line == err_mark.line + 1;
2261
2262            // Optimization: do the cheap checks first; only then request extra lookahead / do deeper checks.
2263            if self.flow_level == 0
2264                && is_immediate_next_line
2265                && (self.mark.col as isize) > self.indent
2266            {
2267                // Ensure enough lookahead for:
2268                // - the checks below (peek/peek_nth)
2269                // - document indicator detection which needs 4 chars.
2270                self.input.lookahead(4);
2271
2272                if !self.input.next_is_z()
2273                    && !self.input.next_is_document_indicator()
2274                    && self.input.next_can_be_plain_scalar(false)
2275                {
2276                    return Err(ScanError::from_kind(
2277                        err_mark,
2278                        ErrorKind::CommentInterceptedScalar,
2279                    ));
2280                }
2281            }
2282        }
2283
2284        Ok(outcome)
2285    }
2286
2287    /// Consume a tab in the separation following a block explicit-key indicator.
2288    fn skip_explicit_key_tab(&mut self) -> ScanResult {
2289        if self.leading_whitespace && (self.mark.col as isize) <= self.indent {
2290            let tab_mark = self.mark;
2291            let (chars_consumed, _) = self.input.skip_ws_to_eol_blanks(SkipTabs::Yes);
2292            self.mark.col += chars_consumed;
2293            self.mark.offsets.chars += chars_consumed;
2294            self.mark.offsets.bytes = self.input.byte_offset();
2295            // Blank and comment-only lines do not require key-node indentation.
2296            if self.input.look_ch() != '#' && !self.input.next_is_breakz() {
2297                return Err(ScanError::from_kind(tab_mark, ErrorKind::TabNotAllowed));
2298            }
2299        } else {
2300            self.skip_blank();
2301        }
2302        // Inline flow/scalar nodes accept tab separation. Compact block collections require
2303        // spaces, so no simple key or block entry may start until the next line.
2304        self.disallow_simple_key();
2305        Ok(())
2306    }
2307
2308    /// Skip separation whitespace after a block explicit-key indicator.
2309    ///
2310    /// The function returns after one separated comment, whether it was queued or ignored, so a
2311    /// caller can publish completed syntax before validating later input.
2312    ///
2313    /// # Errors
2314    /// This function returns an error if no whitespace was found or a tab supplies required
2315    /// indentation for the key node.
2316    fn skip_yaml_whitespace(&mut self) -> Result<bool, ScanError> {
2317        let mut need_whitespace = true;
2318        loop {
2319            match self.input.look_ch() {
2320                ' ' => {
2321                    self.skip_blank();
2322
2323                    need_whitespace = false;
2324                }
2325                '\t' => {
2326                    self.skip_explicit_key_tab()?;
2327                    need_whitespace = false;
2328                }
2329                '\n' | '\r' => {
2330                    self.input.lookahead(2);
2331                    self.skip_linebreak();
2332                    if self.flow_level == 0 {
2333                        self.allow_simple_key();
2334                    }
2335                    need_whitespace = false;
2336                }
2337                '#' => {
2338                    if need_whitespace {
2339                        self.skip_comment()?;
2340                    } else {
2341                        self.consume_comment()?;
2342                        return Ok(true);
2343                    }
2344                }
2345                _ => break,
2346            }
2347        }
2348
2349        // End of input also separates: `?` is a key indicator when followed by a blank, a line
2350        // break or the end of input (`is_blank_or_breakz`), so `?` as the last character is a
2351        // complete (empty) explicit key, like `?\n`.
2352        if need_whitespace && !self.input.next_is_z() {
2353            Err(self.scan_error(ErrorKind::ExpectedWhitespace))
2354        } else {
2355            Ok(false)
2356        }
2357    }
2358
2359    /// Skip YAML whitespace up to the end of the current line.
2360    fn skip_ws_to_eol(&mut self, skip_tabs: SkipTabs) -> Result<WhitespaceResult, ScanError> {
2361        #[cfg(feature = "comments")]
2362        if !self.comments_possible {
2363            let (chars_consumed, result) = self.input.skip_ws_to_eol(skip_tabs);
2364            self.mark.col += chars_consumed;
2365            self.mark.offsets.chars += chars_consumed;
2366            self.mark.offsets.bytes = self.input.byte_offset();
2367            return result.map_err(|kind| self.scan_error(kind));
2368        }
2369
2370        let (chars_consumed, whitespace) = self.input.skip_ws_to_eol_blanks(skip_tabs);
2371        self.mark.col += chars_consumed;
2372        self.mark.offsets.chars += chars_consumed;
2373        self.mark.offsets.bytes = self.input.byte_offset();
2374
2375        if self.input.look_ch() != '#' {
2376            return Ok(whitespace);
2377        }
2378
2379        if !whitespace.found_tabs() && !whitespace.has_valid_yaml_ws() {
2380            return Err(self.scan_error(ErrorKind::CommentNotSeparated));
2381        }
2382
2383        self.consume_comment()?;
2384        Ok(whitespace)
2385    }
2386
2387    fn fetch_stream_start(&mut self) {
2388        let mark = self.mark;
2389        self.indent = -1;
2390        self.stream_start_produced = true;
2391        self.allow_simple_key();
2392        self.tokens
2393            .push_back(Token(Span::empty(mark), TokenType::StreamStart).into());
2394        self.simple_keys.push(SimpleKey::new(Marker::new(0, 0, 0)));
2395    }
2396
2397    fn fetch_stream_end(&mut self) -> ScanResult {
2398        // Close blocks at the physical EOF position. No line break was consumed here;
2399        // moving the marker would also corrupt a pending fallible-input error's location.
2400        if let Some((mark, bracket)) = self.flow_markers.pop() {
2401            return Err(Self::unclosed_bracket(mark, bracket));
2402        }
2403
2404        // If the stream ended, we won't have more context. We can stall all the simple keys we
2405        // had. If one was required, however, that was an error and we must propagate it.
2406        for sk in &mut self.simple_keys {
2407            if sk.required && sk.possible {
2408                return Err(Self::simple_key_expected(sk.mark));
2409            }
2410            sk.possible = false;
2411        }
2412        self.first_simple_key = None;
2413
2414        self.unroll_indent(-1);
2415        self.remove_simple_key()?;
2416        self.disallow_simple_key();
2417
2418        self.tokens
2419            .push_back(Token(Span::empty(self.mark), TokenType::StreamEnd).into());
2420        Ok(())
2421    }
2422
2423    fn fetch_directive(&mut self) -> ScanResult {
2424        if self.options.disallow_directives {
2425            return Err(self.scan_error(ErrorKind::DirectiveDisallowed));
2426        }
2427
2428        self.unroll_indent(-1);
2429        self.remove_simple_key()?;
2430
2431        self.disallow_simple_key();
2432
2433        let token_index = self.tokens.len();
2434        let tok = self.scan_directive()?;
2435        self.insert_token(token_index, tok);
2436
2437        Ok(())
2438    }
2439
2440    fn scan_directive(&mut self) -> Result<Token<'input>, ScanError> {
2441        let start_mark = self.mark;
2442        self.skip_non_blank();
2443
2444        // Directives precede every event, so a document could otherwise make the scanner retain
2445        // memory proportional to the input before any event, node or scalar budget can apply.
2446        let mut budget = self.options.max_directive_bytes;
2447
2448        let name = self.scan_directive_name(&mut budget)?;
2449        let mut separated_comment = false;
2450        let tok = match name.as_ref() {
2451            "YAML" => self.scan_version_directive_value(&start_mark)?,
2452            "TAG" => self.scan_tag_directive_value(&start_mark, &mut budget)?,
2453            _ => {
2454                let mut params = Vec::new();
2455                while self.input.next_is_blank() {
2456                    let n_blanks = self.input.skip_while_blank();
2457                    self.mark.offsets.chars += n_blanks;
2458                    self.mark.col += n_blanks;
2459                    self.mark.offsets.bytes = self.input.byte_offset();
2460
2461                    if self.input.peek() == '#' {
2462                        separated_comment = true;
2463                        break;
2464                    }
2465
2466                    if !is_blank_or_breakz(self.input.peek()) {
2467                        self.spend_directive_bytes(&mut budget, n_blanks, start_mark)?;
2468                        if params.len() >= self.options.max_reserved_directive_params {
2469                            return Err(ScanError::from_kind(
2470                                start_mark,
2471                                ErrorKind::TooManyReservedDirectiveParams {
2472                                    limit: self.options.max_reserved_directive_params,
2473                                },
2474                            ));
2475                        }
2476
2477                        let mut param = String::new();
2478                        let Some(n_chars) = self.fetch_directive_word(&mut param, &mut budget)
2479                        else {
2480                            return Err(self.directive_byte_limit(start_mark));
2481                        };
2482                        self.mark.offsets.chars += n_chars;
2483                        self.mark.col += n_chars;
2484                        self.mark.offsets.bytes = self.input.byte_offset();
2485                        params.push(param);
2486                    }
2487                }
2488
2489                Token(
2490                    Span::new(start_mark, self.mark),
2491                    TokenType::ReservedDirective(name, params),
2492                )
2493            }
2494        };
2495
2496        if separated_comment {
2497            // The reserved-parameter loop already consumed the comment's separator.
2498            self.consume_comment()?;
2499        } else {
2500            self.skip_ws_to_eol(SkipTabs::Yes)?;
2501        }
2502
2503        if self.input.next_is_breakz() {
2504            self.input.lookahead(2);
2505            self.skip_linebreak();
2506            Ok(tok)
2507        } else {
2508            Err(ScanError::from_kind(
2509                start_mark,
2510                ErrorKind::InvalidDirectiveTerminator,
2511            ))
2512        }
2513    }
2514
2515    fn scan_version_directive_value(&mut self, mark: &Marker) -> Result<Token<'input>, ScanError> {
2516        let n_blanks = self.input.skip_while_blank();
2517        self.mark.offsets.chars += n_blanks;
2518        self.mark.col += n_blanks;
2519        self.mark.offsets.bytes = self.input.byte_offset();
2520
2521        let major = self.scan_version_directive_number(mark)?;
2522
2523        if self.input.peek() != '.' {
2524            return Err(ScanError::from_kind(
2525                *mark,
2526                ErrorKind::MissingYamlVersionSeparator,
2527            ));
2528        }
2529        self.skip_non_blank();
2530
2531        let minor = self.scan_version_directive_number(mark)?;
2532
2533        Ok(Token(
2534            Span::new(*mark, self.mark),
2535            TokenType::VersionDirective(major, minor),
2536        ))
2537    }
2538
2539    /// Build the error reported when a directive outgrows [`Options::max_directive_bytes`].
2540    fn directive_byte_limit(&self, start_mark: Marker) -> ScanError {
2541        ScanError::from_kind(
2542            start_mark,
2543            ErrorKind::DirectiveByteLimitExceeded {
2544                limit: self.options.max_directive_bytes,
2545            },
2546        )
2547    }
2548
2549    /// Spend source bytes from a directive-retention budget before growing owned storage.
2550    fn spend_directive_bytes(
2551        &self,
2552        budget: &mut usize,
2553        bytes: usize,
2554        start_mark: Marker,
2555    ) -> ScanResult {
2556        let Some(remaining) = budget.checked_sub(bytes) else {
2557            return Err(self.directive_byte_limit(start_mark));
2558        };
2559        *budget = remaining;
2560        Ok(())
2561    }
2562
2563    /// Fetch a run of [`is_yaml_non_space`] characters into `out`, spending `budget` bytes.
2564    ///
2565    /// This mirrors [`crate::input::Input::fetch_while_is_yaml_non_space`] but stops as soon as
2566    /// the run would outgrow `budget`, returning [`None`]. Checking before each push is what keeps
2567    /// the allocation bounded: a limit applied after the fetch would already have grown `out` to
2568    /// the size of the run.
2569    fn fetch_directive_word(&mut self, out: &mut String, budget: &mut usize) -> Option<usize> {
2570        let mut n_chars = 0;
2571
2572        loop {
2573            let c = self.input.look_ch();
2574            if !is_yaml_non_space(c) || is_z(c) {
2575                break;
2576            }
2577
2578            let len = c.len_utf8();
2579            if len > *budget {
2580                return None;
2581            }
2582            *budget -= len;
2583
2584            out.push(c);
2585            self.input.skip();
2586            n_chars += 1;
2587        }
2588
2589        Some(n_chars)
2590    }
2591
2592    fn scan_directive_name(&mut self, budget: &mut usize) -> Result<String, ScanError> {
2593        let start_mark = self.mark;
2594        let mut string = String::new();
2595
2596        let Some(n_chars) = self.fetch_directive_word(&mut string, budget) else {
2597            return Err(self.directive_byte_limit(start_mark));
2598        };
2599        self.mark.offsets.chars += n_chars;
2600        self.mark.col += n_chars;
2601        self.mark.offsets.bytes = self.input.byte_offset();
2602
2603        if string.is_empty() {
2604            return Err(ScanError::from_kind(
2605                start_mark,
2606                ErrorKind::MissingDirectiveName,
2607            ));
2608        }
2609
2610        if !is_blank_or_breakz(self.input.peek()) {
2611            return Err(ScanError::from_kind(
2612                start_mark,
2613                ErrorKind::InvalidDirectiveName,
2614            ));
2615        }
2616
2617        Ok(string)
2618    }
2619
2620    fn scan_version_directive_number(&mut self, mark: &Marker) -> Result<u32, ScanError> {
2621        let mut val = 0u32;
2622        let mut length = 0usize;
2623        while let Some(digit) = self.input.look_ch().to_digit(10) {
2624            if length + 1 > 9 {
2625                return Err(ScanError::from_kind(*mark, ErrorKind::YamlVersionTooLong));
2626            }
2627            length += 1;
2628            val = val * 10 + digit;
2629            self.skip_non_blank();
2630        }
2631
2632        if length == 0 {
2633            return Err(ScanError::from_kind(*mark, ErrorKind::MissingYamlVersion));
2634        }
2635
2636        Ok(val)
2637    }
2638
2639    fn scan_tag_directive_value(
2640        &mut self,
2641        mark: &Marker,
2642        budget: &mut usize,
2643    ) -> Result<Token<'input>, ScanError> {
2644        let n_blanks = self.input.skip_while_blank();
2645        self.mark.offsets.chars += n_blanks;
2646        self.mark.col += n_blanks;
2647        self.mark.offsets.bytes = self.input.byte_offset();
2648        self.spend_directive_bytes(budget, n_blanks, *mark)?;
2649
2650        let handle = self.scan_tag_handle_directive_cow(mark, budget)?;
2651
2652        let n_blanks = self.input.skip_while_blank();
2653        self.mark.offsets.chars += n_blanks;
2654        self.mark.col += n_blanks;
2655        self.mark.offsets.bytes = self.input.byte_offset();
2656        self.spend_directive_bytes(budget, n_blanks, *mark)?;
2657
2658        let prefix = self.scan_tag_prefix_directive_cow(mark, budget)?;
2659
2660        self.input.lookahead(1);
2661
2662        if self.input.next_is_blank_or_breakz() {
2663            Ok(Token(
2664                Span::new(*mark, self.mark),
2665                TokenType::TagDirective(handle, prefix),
2666            ))
2667        } else {
2668            Err(ScanError::from_kind(
2669                *mark,
2670                ErrorKind::InvalidTagDirectiveTerminator,
2671            ))
2672        }
2673    }
2674
2675    fn fetch_tag(&mut self) -> ScanResult {
2676        self.save_simple_key();
2677        self.disallow_simple_key();
2678
2679        let tok = self.scan_tag()?;
2680        self.tokens.push_back(tok.into());
2681        Ok(())
2682    }
2683
2684    fn scan_tag(&mut self) -> Result<Token<'input>, ScanError> {
2685        let start_mark = self.mark;
2686
2687        // Check if the tag is in the canonical form (verbatim).
2688        self.input.lookahead(2);
2689
2690        // If byte_offset is not available, use the original owned-only path.
2691        if self.input.byte_offset().is_none() {
2692            return self.scan_tag_owned(&start_mark);
2693        }
2694
2695        let (handle, suffix): (Cow<'input, str>, Cow<'input, str>) = if self
2696            .input
2697            .nth_char_is(1, '<')
2698        {
2699            // Verbatim tags always need owned strings (URI escapes).
2700            let suffix = self.scan_verbatim_tag(&start_mark)?;
2701            (Cow::Owned(String::new()), Cow::Owned(suffix))
2702        } else {
2703            // The tag has either the '!suffix' or the '!handle!suffix'
2704            let handle = self.scan_tag_handle_cow(&start_mark)?;
2705            // Check if it is, indeed, handle.
2706            if handle.len() >= 2 && handle.starts_with('!') && handle.ends_with('!') {
2707                // A tag handle starting with "!!" is a secondary tag handle.
2708                let suffix = self.scan_tag_shorthand_suffix_cow(&start_mark, true)?;
2709                (handle, suffix)
2710            } else {
2711                // Not a real handle, it's part of the suffix.
2712                // E.g., "!foo" -> handle="!", suffix="foo"
2713                // The "handle" we scanned is actually "!" + suffix_part1.
2714                // We need to also scan any remaining suffix characters.
2715                let remaining_suffix = self.scan_tag_shorthand_suffix_cow(&start_mark, false)?;
2716
2717                let suffix = self.combine_local_tag_suffix(&start_mark, handle, remaining_suffix);
2718
2719                // A special case: the '!' tag.  Set the handle to '' and the
2720                // suffix to '!'.
2721                if suffix.is_empty() {
2722                    (Cow::Borrowed(""), Cow::Borrowed("!"))
2723                } else {
2724                    (Cow::Borrowed("!"), suffix)
2725                }
2726            }
2727        };
2728
2729        if is_blank_or_breakz(self.input.look_ch())
2730            || (self.flow_level > 0 && matches!(self.input.peek(), ',' | ']' | '}'))
2731        {
2732            // YAML example 7.2 allows a tag to annotate an empty scalar when a separator or flow
2733            // delimiter follows.
2734            Ok(Token(
2735                Span::new(start_mark, self.mark),
2736                TokenType::Tag(handle, suffix),
2737            ))
2738        } else {
2739            Err(ScanError::from_kind(
2740                start_mark,
2741                ErrorKind::InvalidTagTerminator,
2742            ))
2743        }
2744    }
2745
2746    fn combine_local_tag_suffix(
2747        &self,
2748        start_mark: &Marker,
2749        handle: Cow<'input, str>,
2750        remaining: Cow<'input, str>,
2751    ) -> Cow<'input, str> {
2752        if handle.len() == 1 {
2753            return remaining;
2754        }
2755
2756        match (handle, remaining) {
2757            (Cow::Borrowed(handle), Cow::Borrowed(remaining)) => {
2758                if remaining.is_empty() {
2759                    return Cow::Borrowed(&handle[1..]);
2760                }
2761
2762                let borrowed = start_mark
2763                    .byte_offset()
2764                    .and_then(|start| start.checked_add(1))
2765                    .zip(self.input.byte_offset())
2766                    .and_then(|(start, end)| self.try_borrow_slice(start, end));
2767                borrowed.map_or_else(
2768                    || {
2769                        let mut combined =
2770                            String::with_capacity(handle.len() - 1 + remaining.len());
2771                        combined.push_str(&handle[1..]);
2772                        combined.push_str(remaining);
2773                        Cow::Owned(combined)
2774                    },
2775                    Cow::Borrowed,
2776                )
2777            }
2778            (Cow::Borrowed(handle), Cow::Owned(mut remaining)) => {
2779                remaining.reserve(handle.len() - 1);
2780                remaining.insert_str(0, &handle[1..]);
2781                Cow::Owned(remaining)
2782            }
2783            (Cow::Owned(mut handle), remaining) => {
2784                handle.remove(0);
2785                handle.push_str(&remaining);
2786                Cow::Owned(handle)
2787            }
2788        }
2789    }
2790
2791    /// Original owned-only tag scanning path for inputs without `byte_offset` support.
2792    fn scan_tag_owned(&mut self, start_mark: &Marker) -> Result<Token<'input>, ScanError> {
2793        let mut handle = String::new();
2794        let mut suffix;
2795
2796        if self.input.nth_char_is(1, '<') {
2797            suffix = self.scan_verbatim_tag(start_mark)?;
2798        } else {
2799            // The tag has either the '!suffix' or the '!handle!suffix'
2800            handle = self.scan_tag_handle(false, start_mark)?;
2801            // Check if it is, indeed, handle.
2802            if handle.len() >= 2 && handle.starts_with('!') && handle.ends_with('!') {
2803                // A tag handle starting with "!!" is a secondary tag handle.
2804                let is_secondary_handle = handle == "!!";
2805                suffix =
2806                    self.scan_tag_shorthand_suffix(false, is_secondary_handle, "", start_mark)?;
2807            } else {
2808                suffix = self.scan_tag_shorthand_suffix(false, false, &handle, start_mark)?;
2809                "!".clone_into(&mut handle);
2810                // A special case: the '!' tag.  Set the handle to '' and the
2811                // suffix to '!'.
2812                if suffix.is_empty() {
2813                    handle.clear();
2814                    "!".clone_into(&mut suffix);
2815                }
2816            }
2817        }
2818
2819        if is_blank_or_breakz(self.input.look_ch())
2820            || (self.flow_level > 0 && matches!(self.input.peek(), ',' | ']' | '}'))
2821        {
2822            // YAML example 7.2 allows a tag to annotate an empty scalar when a separator or flow
2823            // delimiter follows.
2824            Ok(Token(
2825                Span::new(*start_mark, self.mark),
2826                TokenType::Tag(handle.into(), suffix.into()),
2827            ))
2828        } else {
2829            Err(ScanError::from_kind(
2830                *start_mark,
2831                ErrorKind::InvalidTagTerminator,
2832            ))
2833        }
2834    }
2835
2836    /// Scan a tag handle as a `Cow<str>`, borrowing when possible.
2837    ///
2838    /// Tag handles are of the form `!`, `!!`, or `!name!` where name is ASCII alphanumeric.
2839    /// Since they contain no escape sequences, they can always be borrowed from `StrInput`.
2840    fn scan_tag_handle_cow(&mut self, mark: &Marker) -> Result<Cow<'input, str>, ScanError> {
2841        let Some(start) = self.input.byte_offset() else {
2842            return Ok(Cow::Owned(self.scan_tag_handle(false, mark)?));
2843        };
2844
2845        if self.input.look_ch() != '!' {
2846            return Err(ScanError::from_kind(*mark, ErrorKind::ExpectedTagBang));
2847        }
2848
2849        // Consume the leading '!'.
2850        self.skip_non_blank();
2851
2852        // Consume ns-word-char (ASCII alphanumeric, '_' or '-') characters.
2853        self.input.lookahead(1);
2854        while self.input.next_is_alpha() {
2855            self.skip_non_blank();
2856            self.input.lookahead(1);
2857        }
2858
2859        // Optional trailing '!'.
2860        if self.input.peek() == '!' {
2861            self.skip_non_blank();
2862        }
2863
2864        let Some(end) = self.input.byte_offset() else {
2865            return Ok(Cow::Owned(self.scan_tag_handle(false, mark)?));
2866        };
2867
2868        if let Some(slice) = self.try_borrow_slice(start, end) {
2869            Ok(Cow::Borrowed(slice))
2870        } else {
2871            let slice = self
2872                .input
2873                .slice_bytes(start, end)
2874                .ok_or_else(|| ScanError::from_kind(*mark, ErrorKind::InputSlicingUnavailable))?;
2875            Ok(Cow::Owned(slice.to_owned()))
2876        }
2877    }
2878
2879    /// Scan a tag shorthand suffix as a `Cow<str>`, borrowing when possible.
2880    ///
2881    /// The suffix can be borrowed only if no `%` URI escape sequences are present.
2882    fn scan_tag_shorthand_suffix_cow(
2883        &mut self,
2884        mark: &Marker,
2885        require_non_empty: bool,
2886    ) -> Result<Cow<'input, str>, ScanError> {
2887        let Some(start) = self.input.byte_offset() else {
2888            return Ok(Cow::Owned(
2889                self.scan_tag_shorthand_suffix(false, false, "", mark)?,
2890            ));
2891        };
2892
2893        // Scan tag characters, checking for URI escapes.
2894        while is_tag_char(self.input.look_ch()) {
2895            if self.input.peek() == '%' {
2896                // URI escape found - must decode, so fall back to owned path.
2897                let current = self
2898                    .input
2899                    .byte_offset()
2900                    .expect("byte_offset() must remain available once enabled");
2901                let mut out = if let Some(slice) = self.input.slice_bytes(start, current) {
2902                    slice.to_owned()
2903                } else {
2904                    String::new()
2905                };
2906
2907                // Continue scanning with owned buffer.
2908                while is_tag_char(self.input.look_ch()) {
2909                    if self.input.peek() == '%' {
2910                        out.push(self.scan_uri_escapes(mark)?);
2911                    } else {
2912                        out.push(self.input.peek());
2913                        self.skip_non_blank();
2914                    }
2915                }
2916                return Ok(Cow::Owned(out));
2917            }
2918            self.skip_non_blank();
2919        }
2920
2921        let Some(end) = self.input.byte_offset() else {
2922            return Ok(Cow::Owned(
2923                self.scan_tag_shorthand_suffix(false, false, "", mark)?,
2924            ));
2925        };
2926
2927        if require_non_empty && start == end {
2928            return Err(ScanError::from_kind(*mark, ErrorKind::MissingTagUri));
2929        }
2930
2931        if let Some(slice) = self.try_borrow_slice(start, end) {
2932            Ok(Cow::Borrowed(slice))
2933        } else {
2934            let slice = self
2935                .input
2936                .slice_bytes(start, end)
2937                .ok_or_else(|| ScanError::from_kind(*mark, ErrorKind::InputSlicingUnavailable))?;
2938            Ok(Cow::Owned(slice.to_owned()))
2939        }
2940    }
2941
2942    fn scan_tag_handle(&mut self, directive: bool, mark: &Marker) -> Result<String, ScanError> {
2943        let mut string = String::new();
2944        if self.input.look_ch() != '!' {
2945            return Err(ScanError::from_kind(*mark, ErrorKind::ExpectedTagBang));
2946        }
2947
2948        string.push(self.input.peek());
2949        self.skip_non_blank();
2950
2951        let n_chars = self.input.fetch_while_is_alpha(&mut string);
2952        self.mark.offsets.chars += n_chars;
2953        self.mark.col += n_chars;
2954        self.mark.offsets.bytes = self.input.byte_offset();
2955
2956        // Check if the trailing character is '!' and copy it.
2957        if self.input.peek() == '!' {
2958            string.push(self.input.peek());
2959            self.skip_non_blank();
2960        } else if directive && string != "!" {
2961            // It's either the '!' tag or not really a tag handle.  If it's a %TAG
2962            // directive, it's an error.  If it's a tag token, it must be a part of
2963            // URI.
2964            return Err(ScanError::from_kind(
2965                *mark,
2966                ErrorKind::ExpectedTagDirectiveBang,
2967            ));
2968        }
2969        Ok(string)
2970    }
2971
2972    /// Scan for a verbatim tag.
2973    ///
2974    /// The prefixing `!<` must _not_ have been skipped.
2975    fn scan_verbatim_tag(&mut self, start_mark: &Marker) -> Result<String, ScanError> {
2976        // Eat `!<`
2977        self.skip_non_blank();
2978        self.skip_non_blank();
2979
2980        let mut string = String::new();
2981        while is_uri_char(self.input.look_ch()) {
2982            if self.input.peek() == '%' {
2983                string.push(self.scan_uri_escapes(start_mark)?);
2984            } else {
2985                string.push(self.input.peek());
2986                self.skip_non_blank();
2987            }
2988        }
2989
2990        if string.is_empty() {
2991            return Err(ScanError::from_kind(*start_mark, ErrorKind::MissingTagUri));
2992        }
2993
2994        if self.input.peek() != '>' {
2995            return Err(ScanError::from_kind(
2996                *start_mark,
2997                ErrorKind::UnclosedVerbatimTag,
2998            ));
2999        }
3000        self.skip_non_blank();
3001
3002        Ok(string)
3003    }
3004
3005    fn scan_tag_shorthand_suffix(
3006        &mut self,
3007        _directive: bool,
3008        _is_secondary: bool,
3009        head: &str,
3010        mark: &Marker,
3011    ) -> Result<String, ScanError> {
3012        let mut length = head.len();
3013        let mut string = String::new();
3014
3015        // Copy the head if needed.
3016        // Note that we don't copy the leading '!' character.
3017        if length > 1 {
3018            string.extend(head.chars().skip(1));
3019        }
3020
3021        while is_tag_char(self.input.look_ch()) {
3022            // Check if it is a URI-escape sequence.
3023            if self.input.peek() == '%' {
3024                string.push(self.scan_uri_escapes(mark)?);
3025            } else {
3026                string.push(self.input.peek());
3027                self.skip_non_blank();
3028            }
3029
3030            length += 1;
3031        }
3032
3033        if length == 0 {
3034            return Err(ScanError::from_kind(*mark, ErrorKind::MissingTagUri));
3035        }
3036
3037        Ok(string)
3038    }
3039
3040    fn scan_uri_escapes(&mut self, mark: &Marker) -> Result<char, ScanError> {
3041        self.scan_uri_escapes_with_budget(mark, None)
3042    }
3043
3044    fn scan_uri_escapes_with_budget(
3045        &mut self,
3046        mark: &Marker,
3047        mut directive_budget: Option<&mut usize>,
3048    ) -> Result<char, ScanError> {
3049        let mut width = 0usize;
3050        let mut bytes = [0u8; 4];
3051        let mut bytes_len = 0usize;
3052        loop {
3053            self.input.lookahead(3);
3054
3055            let c = self.input.peek_nth(1);
3056            let nc = self.input.peek_nth(2);
3057
3058            if !(self.input.peek() == '%' && is_hex(c) && is_hex(nc)) {
3059                return Err(ScanError::from_kind(*mark, ErrorKind::InvalidTagEscape));
3060            }
3061
3062            if let Some(budget) = directive_budget.as_deref_mut() {
3063                self.spend_directive_bytes(budget, 3, *mark)?;
3064            }
3065
3066            let byte = u8::try_from((as_hex(c) << 4) + as_hex(nc))
3067                .expect("two hex nibbles always fit in a byte");
3068            if width == 0 {
3069                width = match byte {
3070                    _ if byte & 0x80 == 0x00 => 1,
3071                    _ if byte & 0xE0 == 0xC0 => 2,
3072                    _ if byte & 0xF0 == 0xE0 => 3,
3073                    _ if byte & 0xF8 == 0xF0 => 4,
3074                    _ => {
3075                        return Err(ScanError::from_kind(
3076                            *mark,
3077                            ErrorKind::InvalidTagUtf8LeadingByte,
3078                        ));
3079                    }
3080                };
3081            } else if byte & 0xc0 != 0x80 {
3082                return Err(ScanError::from_kind(
3083                    *mark,
3084                    ErrorKind::InvalidTagUtf8TrailingByte,
3085                ));
3086            }
3087
3088            bytes[bytes_len] = byte;
3089            bytes_len += 1;
3090
3091            self.skip_n_non_blank(3);
3092
3093            width -= 1;
3094            if width == 0 {
3095                break;
3096            }
3097        }
3098
3099        let s = core::str::from_utf8(&bytes[..bytes_len])
3100            .map_err(|_| ScanError::from_kind(*mark, ErrorKind::InvalidTagUtf8))?;
3101
3102        let Some(ch) = s.chars().next() else {
3103            unreachable!("a validated URI escape cannot decode to an empty string")
3104        };
3105        Ok(ch)
3106    }
3107
3108    fn fetch_anchor(&mut self, alias: bool) -> ScanResult {
3109        self.save_simple_key();
3110        self.disallow_simple_key();
3111
3112        let tok = self.scan_anchor(alias)?;
3113
3114        self.tokens.push_back(tok.into());
3115
3116        Ok(())
3117    }
3118
3119    fn scan_anchor(&mut self, alias: bool) -> Result<Token<'input>, ScanError> {
3120        let start_mark = self.mark;
3121
3122        // Skip `&` / `*`.
3123        self.skip_non_blank();
3124
3125        // Borrow from input when possible.
3126        if let Some(start) = self.input.byte_offset() {
3127            while is_anchor_char(self.input.look_ch()) {
3128                self.skip_non_blank();
3129            }
3130
3131            let end = self
3132                .input
3133                .byte_offset()
3134                .expect("byte_offset() must remain available once enabled");
3135
3136            if start == end {
3137                return Err(ScanError::from_kind(
3138                    start_mark,
3139                    ErrorKind::MissingAnchorOrAliasName,
3140                ));
3141            }
3142
3143            let cow = if let Some(slice) = self.try_borrow_slice(start, end) {
3144                Cow::Borrowed(slice)
3145            } else if let Some(slice) = self.input.slice_bytes(start, end) {
3146                Cow::Owned(slice.to_owned())
3147            } else {
3148                return Err(ScanError::from_kind(
3149                    start_mark,
3150                    ErrorKind::InputSlicingUnavailable,
3151                ));
3152            };
3153
3154            let tok = if alias {
3155                TokenType::Alias(cow)
3156            } else {
3157                TokenType::Anchor(cow)
3158            };
3159            return Ok(Token(Span::new(start_mark, self.mark), tok));
3160        }
3161
3162        let mut string = String::new();
3163        while is_anchor_char(self.input.look_ch()) {
3164            string.push(self.input.peek());
3165            self.skip_non_blank();
3166        }
3167
3168        if string.is_empty() {
3169            return Err(ScanError::from_kind(
3170                start_mark,
3171                ErrorKind::MissingAnchorOrAliasName,
3172            ));
3173        }
3174
3175        let tok = if alias {
3176            TokenType::Alias(string.into())
3177        } else {
3178            TokenType::Anchor(string.into())
3179        };
3180        Ok(Token(Span::new(start_mark, self.mark), tok))
3181    }
3182
3183    fn fetch_flow_collection_start(&mut self, tok: TokenType<'input>) -> ScanResult {
3184        // The indicators '[' and '{' may start a simple key.
3185        self.save_simple_key();
3186
3187        let start_mark = self.mark;
3188        let indicator = self.input.peek();
3189        self.flow_markers.push((start_mark, indicator));
3190
3191        self.roll_one_col_indent();
3192        self.increase_flow_level()?;
3193
3194        self.allow_simple_key();
3195
3196        self.skip_non_blank();
3197        let end_mark = self.mark;
3198
3199        if tok == TokenType::FlowMappingStart {
3200            self.flow_mapping_started.push(true);
3201        } else {
3202            self.flow_mapping_started.push(false);
3203            self.implicit_flow_mapping_states
3204                .push(ImplicitMappingState::Possible);
3205        }
3206
3207        let token_index = self.tokens.len();
3208        self.skip_ws_to_eol(SkipTabs::Yes)?;
3209
3210        self.insert_token(token_index, Token(Span::new(start_mark, end_mark), tok));
3211        Ok(())
3212    }
3213
3214    fn fetch_flow_collection_end(
3215        &mut self,
3216        tok: TokenType<'input>,
3217        expected_open: char,
3218        actual_close: char,
3219    ) -> ScanResult {
3220        // A closing bracket without a corresponding opening is invalid YAML.
3221        if self.flow_level == 0 {
3222            return Err(self.scan_error(ErrorKind::MisplacedFlowCollectionEnd));
3223        }
3224
3225        let Some((open_mark, open_ch)) = self.flow_markers.pop() else {
3226            return Err(self.scan_error(ErrorKind::MisplacedFlowCollectionEnd));
3227        };
3228
3229        if open_ch != expected_open {
3230            return Err(ScanError::from_kind(
3231                open_mark,
3232                ErrorKind::MismatchedFlowCollectionEnd {
3233                    open: open_ch,
3234                    close: actual_close,
3235                },
3236            ));
3237        }
3238
3239        let flow_level = self.flow_level;
3240
3241        self.remove_simple_key()?;
3242
3243        if matches!(tok, TokenType::FlowSequenceEnd) {
3244            self.end_implicit_mapping(self.mark, flow_level);
3245            // We are out exiting the flow sequence, nesting goes down 1 level.
3246            self.implicit_flow_mapping_states.pop();
3247        }
3248        self.flow_mapping_started.pop();
3249
3250        self.decrease_flow_level();
3251
3252        self.disallow_simple_key();
3253
3254        let start_mark = self.mark;
3255        self.skip_non_blank();
3256        let end_mark = self.mark;
3257        let token_index = self.tokens.len();
3258        self.skip_ws_to_eol(SkipTabs::Yes)?;
3259
3260        // A flow collection within a flow mapping can be a key. In that case, the value may be
3261        // adjacent to the `:`.
3262        // ```yaml
3263        // - [ {a: b}:value ]
3264        // ```
3265        if self.flow_level > 0 {
3266            self.adjacent_value_allowed_at = self.mark.index();
3267        }
3268
3269        self.insert_token(token_index, Token(Span::new(start_mark, end_mark), tok));
3270        Ok(())
3271    }
3272
3273    /// Push the `FlowEntry` token and skip over the `,`.
3274    fn fetch_flow_entry(&mut self) -> ScanResult {
3275        self.remove_simple_key()?;
3276        self.allow_simple_key();
3277
3278        self.end_implicit_mapping(self.mark, self.flow_level);
3279        if self.current_flow_collection_is_sequence() {
3280            self.set_current_flow_mapping_started(false);
3281        }
3282
3283        let start_mark = self.mark;
3284        self.skip_non_blank();
3285        let end_mark = self.mark;
3286        let token_index = self.tokens.len();
3287        self.skip_ws_to_eol(SkipTabs::Yes)?;
3288
3289        self.insert_token(
3290            token_index,
3291            Token(Span::new(start_mark, end_mark), TokenType::FlowEntry),
3292        );
3293        Ok(())
3294    }
3295
3296    fn increase_flow_level(&mut self) -> ScanResult {
3297        if self.flow_level >= self.options.flow_nesting_limit {
3298            return Err(self.scan_error(ErrorKind::RecursionLimitExceeded));
3299        }
3300
3301        self.simple_keys.push(SimpleKey::new(Marker::new(0, 0, 0)));
3302        self.flow_level += 1;
3303        Ok(())
3304    }
3305
3306    fn decrease_flow_level(&mut self) {
3307        if self.flow_level > 0 {
3308            // The closing delimiter removes this level's possible key before popping it.
3309            debug_assert!(!self.simple_keys.last().unwrap().possible);
3310            debug_assert_ne!(self.first_simple_key, Some(self.flow_level));
3311            self.flow_level -= 1;
3312            self.simple_keys.pop().unwrap();
3313        }
3314    }
3315
3316    /// Push the `Block*` token(s) and skip over the `-`.
3317    ///
3318    /// Add an indentation level and push a `BlockSequenceStart` token if needed, then push a
3319    /// `BlockEntry` token.
3320    /// This function only skips over the `-` and does not fetch the entry value.
3321    fn fetch_block_entry(&mut self) -> ScanResult {
3322        if self.flow_level > 0 {
3323            // - * only allowed in block
3324            return Err(self.scan_error(ErrorKind::BlockEntryInFlowCollection));
3325        }
3326        // Check if we are allowed to start a new entry.
3327        if !self.simple_key_allowed {
3328            return Err(self.scan_error(ErrorKind::BlockSequenceEntryNotAllowed));
3329        }
3330
3331        // Skip over the `-`.
3332        let mark = self.mark;
3333        self.skip_non_blank();
3334
3335        // generate BLOCK-SEQUENCE-START if indented
3336        self.roll_indent(mark.col, None, TokenType::BlockSequenceStart, mark)?;
3337        let token_index = self.tokens.len();
3338        let found_tabs = self.skip_ws_to_eol(SkipTabs::Yes)?.found_tabs();
3339        self.input.lookahead(2);
3340        if found_tabs && self.input.next_char_is('-') && is_blank_or_breakz(self.input.peek_nth(1))
3341        {
3342            return Err(self.scan_error(ErrorKind::InvalidBlockEntryWhitespace));
3343        }
3344
3345        self.skip_ws_to_eol(SkipTabs::No)?;
3346        self.input.lookahead(1);
3347        if self.input.next_is_break() || self.input.next_is_flow() {
3348            self.roll_one_col_indent();
3349        }
3350
3351        self.remove_simple_key()?;
3352        self.allow_simple_key();
3353
3354        self.insert_token(
3355            token_index,
3356            Token(Span::empty(self.mark), TokenType::BlockEntry),
3357        );
3358
3359        Ok(())
3360    }
3361
3362    fn fetch_document_indicator(&mut self, t: TokenType<'input>) -> ScanResult {
3363        self.in_directive_prefix = false;
3364        if let Some((mark, bracket)) = self.flow_markers.pop() {
3365            return Err(ScanError::from_kind(
3366                mark,
3367                ErrorKind::UnclosedFlowCollection { open: bracket },
3368            ));
3369        }
3370
3371        self.unroll_indent(-1);
3372        self.remove_simple_key()?;
3373        self.disallow_simple_key();
3374
3375        let mark = self.mark;
3376
3377        self.skip_n_non_blank(3);
3378
3379        self.document_prefix_allowed = matches!(t, TokenType::DocumentEnd);
3380        self.tokens
3381            .push_back(Token(Span::new(mark, self.mark), t).into());
3382        Ok(())
3383    }
3384
3385    fn fetch_block_scalar(&mut self, literal: bool) -> ScanResult {
3386        self.save_simple_key();
3387        self.allow_simple_key();
3388        let token_index = self.tokens.len();
3389        let tok = self.scan_block_scalar(literal)?;
3390
3391        self.insert_token(token_index, tok);
3392        Ok(())
3393    }
3394
3395    #[allow(clippy::too_many_lines)]
3396    fn scan_block_scalar(&mut self, literal: bool) -> Result<Token<'input>, ScanError> {
3397        let start_mark = self.mark;
3398        let mut chomping = Chomping::Clip;
3399        let mut increment: usize = 0;
3400        let mut indent: usize = 0;
3401        let mut trailing_blank: bool;
3402        let mut leading_blank: bool = false;
3403        let style = if literal {
3404            ScalarStyle::Literal
3405        } else {
3406            ScalarStyle::Folded
3407        };
3408
3409        let mut string = String::new();
3410        let mut leading_break = false;
3411        let mut trailing_breaks = 0;
3412        let mut chomping_break = false;
3413
3414        // skip '|' or '>'
3415        self.skip_non_blank();
3416        self.unroll_non_block_indents();
3417
3418        if self.input.look_ch() == '+' || self.input.peek() == '-' {
3419            if self.input.peek() == '+' {
3420                chomping = Chomping::Keep;
3421            } else {
3422                chomping = Chomping::Strip;
3423            }
3424            self.skip_non_blank();
3425            self.input.lookahead(1);
3426            if self.input.next_is_digit() {
3427                if self.input.peek() == '0' {
3428                    return Err(ScanError::from_kind(
3429                        start_mark,
3430                        ErrorKind::ZeroBlockScalarIndent,
3431                    ));
3432                }
3433                increment = (self.input.peek() as usize) - ('0' as usize);
3434                self.skip_non_blank();
3435            }
3436        } else if self.input.next_is_digit() {
3437            if self.input.peek() == '0' {
3438                return Err(ScanError::from_kind(
3439                    start_mark,
3440                    ErrorKind::ZeroBlockScalarIndent,
3441                ));
3442            }
3443
3444            increment = (self.input.peek() as usize) - ('0' as usize);
3445            self.skip_non_blank();
3446            self.input.lookahead(1);
3447            if self.input.peek() == '+' || self.input.peek() == '-' {
3448                if self.input.peek() == '+' {
3449                    chomping = Chomping::Keep;
3450                } else {
3451                    chomping = Chomping::Strip;
3452                }
3453                self.skip_non_blank();
3454            }
3455        }
3456
3457        self.skip_ws_to_eol(SkipTabs::Yes)?;
3458
3459        // Check if we are at the end of the line.
3460        self.input.lookahead(1);
3461        self.ensure_current_char_is_printable()?;
3462        if !self.input.next_is_breakz() {
3463            return Err(ScanError::from_kind(
3464                start_mark,
3465                ErrorKind::InvalidBlockScalarHeader,
3466            ));
3467        }
3468
3469        if self.input.next_is_break() {
3470            self.input.lookahead(2);
3471            self.skip_break();
3472            chomping_break = true;
3473        }
3474
3475        self.ensure_current_char_is_printable()?;
3476
3477        if self.input.look_ch() == '\t' {
3478            return Err(ScanError::from_kind(
3479                start_mark,
3480                ErrorKind::TabAtBlockScalarStart,
3481            ));
3482        }
3483
3484        if increment > 0 {
3485            indent = if self.indent >= 0 {
3486                (self.indent + increment as isize) as usize
3487            } else {
3488                increment
3489            }
3490        }
3491
3492        // Scan the leading line breaks and determine the indentation level if needed.
3493        if indent == 0 {
3494            self.skip_block_scalar_first_line_indent(&mut indent, &mut trailing_breaks);
3495        } else {
3496            self.skip_block_scalar_indent(indent, &mut trailing_breaks);
3497        }
3498
3499        self.ensure_current_char_is_printable()?;
3500
3501        // We have an end-of-stream with no content, e.g.:
3502        // ```yaml
3503        // - |+
3504        // ```
3505        if self.input.next_is_z() {
3506            let contents = match chomping {
3507                // We strip trailing line breaks. Nothing remains.
3508                Chomping::Strip => String::new(),
3509                // There was no newline after the chomping indicator.
3510                _ if self.mark.line == start_mark.line() => String::new(),
3511                // With no content lines, the header break is not scalar content.
3512                Chomping::Clip => String::new(),
3513                // Preserve the default synthetic break for an indented whitespace-only line
3514                // at EOF, unless the caller opted into libyaml's reading.
3515                Chomping::Keep if trailing_breaks == 0 && self.mark.col > 0 => {
3516                    if chomping_break && !self.options.block_scalar_eof_without_line_feed {
3517                        "\n".into()
3518                    } else {
3519                        String::new()
3520                    }
3521                }
3522                // Keep actual empty content lines, if any, but not the header break.
3523                Chomping::Keep => "\n".repeat(trailing_breaks),
3524            };
3525
3526            return Ok(Token(
3527                Span::new(start_mark, self.mark),
3528                TokenType::Scalar(style, contents.into()),
3529            ));
3530        }
3531
3532        if self.mark.col < indent && (self.mark.col as isize) > self.indent {
3533            if self.indent < 0 && self.mark.col == 0 {
3534                self.input.lookahead(4);
3535                if self.input.next_is_document_start()
3536                    || self.input.next_is_document_end()
3537                    || self.input.peek() == '#'
3538                {
3539                    // At the root level, an explicit indentation indicator can still yield an
3540                    // empty scalar when the next line is a document marker or comment.
3541                    // In this case, the scalar is terminated rather than under-indented.
3542                } else {
3543                    return Err(self.scan_error(ErrorKind::InvalidBlockScalarIndent));
3544                }
3545            } else {
3546                return Err(self.scan_error(ErrorKind::InvalidBlockScalarIndent));
3547            }
3548        }
3549
3550        let start_mark = self.mark;
3551        while self.mark.col == indent && !self.input.next_is_z() {
3552            self.ensure_current_char_is_printable()?;
3553
3554            if indent == 0 {
3555                self.input.lookahead(4);
3556                if self.input.next_is_document_indicator() {
3557                    break;
3558                }
3559            }
3560
3561            // We are at the first content character of a content line.
3562            trailing_blank = self.input.next_is_blank();
3563            if !literal && leading_break && !leading_blank && !trailing_blank {
3564                string.extend(core::iter::repeat('\n').take(trailing_breaks));
3565                if trailing_breaks == 0 {
3566                    string.push(' ');
3567                }
3568            } else {
3569                if leading_break {
3570                    string.push('\n');
3571                }
3572                string.extend(core::iter::repeat('\n').take(trailing_breaks));
3573            }
3574
3575            leading_break = false;
3576            trailing_breaks = 0;
3577
3578            leading_blank = self.input.next_is_blank();
3579
3580            self.scan_block_scalar_content_line(&mut string);
3581
3582            // break on EOF
3583            self.input.lookahead(2);
3584            if self.input.next_is_z() {
3585                break;
3586            }
3587
3588            self.ensure_current_char_is_printable()?;
3589
3590            self.skip_break();
3591            leading_break = true;
3592
3593            // Eat the following indentation spaces and line breaks.
3594            self.skip_block_scalar_indent(indent, &mut trailing_breaks);
3595        }
3596
3597        self.ensure_current_char_is_printable()?;
3598
3599        // Chomp the tail.
3600        if chomping != Chomping::Strip {
3601            // If we had reached an eof but the last content line wasn't terminated by a line
3602            // break, check if the last line was indented at least as the rest of the scalar, then
3603            // we need to consider there is a newline, unless the caller opted into libyaml's
3604            // reading. When that line already ended with a break (`leading_break`), the
3605            // indentation-only remainder at EOF is not a line (it has no break, so it is no
3606            // `l-empty`) and adds nothing.
3607            if !leading_break
3608                && !self.options.block_scalar_eof_without_line_feed
3609                && self.input.next_is_z()
3610                && self.mark.col >= indent.max(1)
3611            {
3612                string.push('\n');
3613            }
3614            if leading_break {
3615                string.push('\n');
3616            }
3617        }
3618
3619        if chomping == Chomping::Keep {
3620            string.extend(core::iter::repeat('\n').take(trailing_breaks));
3621        }
3622
3623        if let Some(character) = find_non_printable(&string) {
3624            return Err(ScanError::from_kind(
3625                start_mark,
3626                ErrorKind::UnexpectedCharacter { character },
3627            ));
3628        }
3629
3630        let span = if string.trim().is_empty() {
3631            Span::new(start_mark, self.mark)
3632        } else {
3633            Span::new(start_mark, self.mark).with_indent(Some(indent))
3634        };
3635
3636        Ok(Token(span, TokenType::Scalar(style, string.into())))
3637    }
3638
3639    /// Retrieve the contents of the line, parsing it as a block scalar.
3640    ///
3641    /// The input appends content directly to `string`, leaving the line break or NUL unconsumed.
3642    /// Callers handle indentation and line breaks and refresh lookahead after this operation.
3643    fn scan_block_scalar_content_line(&mut self, string: &mut String) {
3644        let chars_consumed = self.input.fetch_block_scalar_line(string);
3645        self.mark.col += chars_consumed;
3646        self.mark.offsets.chars += chars_consumed;
3647        self.mark.offsets.bytes = self.input.byte_offset();
3648        // Preserve leading_whitespace, as the per-character skip_blank path did. Reading the
3649        // following line break resets it before the scanner uses it again.
3650    }
3651
3652    /// Skip the block scalar indentation and empty lines.
3653    fn skip_block_scalar_indent(&mut self, indent: usize, breaks: &mut usize) {
3654        loop {
3655            // Consume all spaces. Tabs cannot be used as indentation.
3656            if indent < self.input.bufmaxlen().saturating_sub(2) {
3657                self.input.lookahead(self.input.bufmaxlen());
3658                while self.mark.col < indent && self.input.peek() == ' ' {
3659                    self.skip_blank();
3660                }
3661            } else {
3662                loop {
3663                    self.input.lookahead(self.input.bufmaxlen());
3664                    while !self.input.buf_is_empty()
3665                        && self.mark.col < indent
3666                        && self.input.peek() == ' '
3667                    {
3668                        self.skip_blank();
3669                    }
3670                    // If we reached our indent, we can break. We must also break if we have
3671                    // reached content or EOF; that is, the buffer is not empty and the next
3672                    // character is not a space.
3673                    if self.mark.col == indent
3674                        || (!self.input.buf_is_empty() && self.input.peek() != ' ')
3675                    {
3676                        break;
3677                    }
3678                }
3679                self.input.lookahead(2);
3680            }
3681
3682            // If our current line is empty, skip over the break and continue looping.
3683            if self.input.next_is_break() {
3684                self.skip_break();
3685                *breaks += 1;
3686            } else {
3687                // Otherwise, we have a content line. Return control.
3688                break;
3689            }
3690        }
3691    }
3692
3693    /// Determine the indentation level for a block scalar from the first line of its contents.
3694    ///
3695    /// The function skips over whitespace-only lines and sets `indent` to the longest
3696    /// whitespace line that was encountered.
3697    fn skip_block_scalar_first_line_indent(&mut self, indent: &mut usize, breaks: &mut usize) {
3698        let mut max_indent = 0;
3699        loop {
3700            // Consume all spaces. Tabs cannot be used as indentation.
3701            while self.input.look_ch() == ' ' {
3702                self.skip_blank();
3703            }
3704
3705            if self.mark.col > max_indent {
3706                max_indent = self.mark.col;
3707            }
3708
3709            if self.input.next_is_break() {
3710                // If our current line is empty, skip over the break and continue looping.
3711                self.input.lookahead(2);
3712                self.skip_break();
3713                *breaks += 1;
3714            } else {
3715                // Otherwise, we have a content line. Return control.
3716                break;
3717            }
3718        }
3719
3720        // In case a YAML document looks like:
3721        // ```yaml
3722        // |
3723        // foo
3724        // bar
3725        // ```
3726        // We need to set the indent to 0 and not 1. In all other cases, the indent must be at
3727        // least 1. When in the above example, `self.indent` will be set to -1.
3728        *indent = max_indent.max((self.indent + 1) as usize);
3729    }
3730
3731    fn fetch_flow_scalar(&mut self, single: bool) -> ScanResult {
3732        self.save_simple_key();
3733        self.disallow_simple_key();
3734
3735        let token_index = self.tokens.len();
3736        let tok = self.scan_flow_scalar(single)?;
3737
3738        // From spec: To ensure JSON compatibility, if a key inside a flow mapping is JSON-like,
3739        // YAML allows the following value to be specified adjacent to the “:”.
3740        if self.skip_to_next_token()?.saw_comment {
3741            self.adjacent_value_allowed_at = usize::MAX;
3742        } else {
3743            self.adjacent_value_allowed_at = self.mark.index();
3744        }
3745
3746        self.insert_token(token_index, tok);
3747        Ok(())
3748    }
3749
3750    #[allow(clippy::too_many_lines)]
3751    fn scan_flow_scalar(&mut self, single: bool) -> Result<Token<'input>, ScanError> {
3752        let start_mark = self.mark;
3753
3754        // Output scalar contents.
3755        let mut buf = match self.input.byte_offset() {
3756            Some(off) => FlowScalarBuf::new_borrowed(off + self.input.peek().len_utf8()),
3757            None => FlowScalarBuf::new_owned(),
3758        };
3759
3760        /* Eat the left quote. */
3761        self.skip_non_blank();
3762
3763        loop {
3764            /* Check for a document indicator. */
3765            self.input.lookahead(4);
3766
3767            if self.mark.col == 0 && self.input.next_is_document_indicator() {
3768                return Err(ScanError::from_kind(
3769                    start_mark,
3770                    ErrorKind::DocumentIndicatorInQuotedScalar,
3771                ));
3772            }
3773
3774            if self.input.next_is_z() {
3775                return Err(ScanError::from_kind(
3776                    start_mark,
3777                    ErrorKind::UnclosedQuotedScalar,
3778                ));
3779            }
3780
3781            self.ensure_current_char_is_printable()?;
3782
3783            // Consume content before handling continuation-line indentation below.
3784            let mut leading_blanks = false;
3785            self.consume_flow_scalar_non_whitespace_chars(
3786                single,
3787                &mut buf,
3788                &mut leading_blanks,
3789                &start_mark,
3790            )?;
3791
3792            match self.input.look_ch() {
3793                '\'' if single && !leading_blanks => break,
3794                '"' if !single && !leading_blanks => break,
3795                _ => {}
3796            }
3797
3798            // --- Faster whitespace / line break handling (no temporary Strings) ---
3799            //
3800            // Instead of:
3801            //   - collecting blanks into `whitespaces` and then copying them
3802            //   - collecting breaks into `leading_break` / `trailing_breaks` and then copying
3803            //
3804            // We do:
3805            //   - append trailing blanks directly to `string`, remember where they started,
3806            //     and truncate them if a line break follows.
3807            //   - for line breaks: consume the first break into a scratch (discarded),
3808            //     append subsequent breaks directly to `string`.
3809            //
3810            // These flags replace temporary-string emptiness checks:
3811            //   has_leading_break  <=> !leading_break.is_empty()
3812            //   has_trailing_breaks <=> !trailing_breaks.is_empty()
3813            let mut trailing_ws_start: Option<usize> = None;
3814            let mut has_leading_break = false;
3815            let mut has_trailing_breaks = false;
3816
3817            // For the borrowed path: track the (byte) start of a pending whitespace run.
3818            let mut pending_ws_start: Option<usize> = None;
3819
3820            // Consume blank characters.
3821            while self.input.next_is_blank() || self.input.next_is_break() {
3822                if self.input.next_is_blank() {
3823                    // Consume a space or a tab character.
3824                    if leading_blanks {
3825                        // A continuation line's leading blanks are never content, so relaxed
3826                        // mode accepts tabs there, as libyaml, PyYAML and ruamel.yaml do.
3827                        if self.options.strict_indentation && self.input.peek() == '\t' {
3828                            let indent = if self.flow_level > 0 {
3829                                self.flow_block_indent() + 1
3830                            } else {
3831                                self.indent
3832                            };
3833                            if (self.mark.col as isize) < indent {
3834                                return Err(self.scan_error(ErrorKind::TabInIndentation));
3835                            }
3836                        }
3837                        self.skip_blank();
3838                    } else {
3839                        // Append to output immediately; if a break appears next, we'll truncate.
3840                        match buf {
3841                            FlowScalarBuf::Owned(ref mut string) => {
3842                                if trailing_ws_start.is_none() {
3843                                    trailing_ws_start = Some(string.len());
3844                                }
3845                                string.push(self.input.peek());
3846                            }
3847                            FlowScalarBuf::Borrowed { .. } => {
3848                                if pending_ws_start.is_none() {
3849                                    pending_ws_start = self.input.byte_offset();
3850                                }
3851                            }
3852                        }
3853                        self.skip_blank();
3854
3855                        if let (FlowScalarBuf::Borrowed { .. }, Some(ws_start), Some(ws_end)) =
3856                            (&mut buf, pending_ws_start, self.input.byte_offset())
3857                        {
3858                            buf.note_pending_ws(ws_start, ws_end);
3859                        }
3860                    }
3861                } else {
3862                    self.input.lookahead(2);
3863
3864                    // Check if it is a first line break.
3865                    if leading_blanks {
3866                        // Second+ line break in a run: preserve it.
3867                        match buf {
3868                            FlowScalarBuf::Owned(ref mut string) => self.read_break(string),
3869                            FlowScalarBuf::Borrowed { .. } => {
3870                                self.promote_flow_scalar_buf_to_owned(&start_mark, &mut buf)?;
3871                                let Some(string) = buf.as_owned_mut() else {
3872                                    unreachable!()
3873                                };
3874                                self.read_break(string);
3875                            }
3876                        }
3877                        has_trailing_breaks = true;
3878                    } else {
3879                        // First break: drop any trailing blanks we appended, then consume the break.
3880                        if let Some(pos) = trailing_ws_start.take() {
3881                            if let FlowScalarBuf::Owned(ref mut string) = buf {
3882                                string.truncate(pos);
3883                            }
3884                        }
3885
3886                        if pending_ws_start.take().is_some() {
3887                            // Trailing blanks before a break are discarded => transformation.
3888                            if matches!(buf, FlowScalarBuf::Borrowed { .. }) {
3889                                self.promote_flow_scalar_buf_to_owned(&start_mark, &mut buf)?;
3890                            }
3891                            buf.discard_pending_ws();
3892                        } else {
3893                            buf.commit_pending_ws();
3894                        }
3895
3896                        self.skip_break();
3897
3898                        has_leading_break = true;
3899                        leading_blanks = true;
3900                    }
3901                }
3902
3903                self.input.lookahead(1);
3904            }
3905
3906            // In strict mode, continuations and closing quotes after a folded or escaped line break
3907            // must be indented past the enclosing block (s-flow-line-prefix(n), YAML 1.2.2 [69]),
3908            // ignoring the temporary one-column indent after `:` / `-`: `foo: "a\n b"` is valid.
3909            if leading_blanks
3910                && self.options.strict_indentation
3911                && (self.mark.col as isize) <= self.flow_block_indent()
3912            {
3913                let kind = if has_leading_break && self.flow_level == 0 {
3914                    ErrorKind::InvalidQuotedScalarIndent
3915                } else {
3916                    ErrorKind::InvalidIndentation
3917                };
3918                return Err(self.scan_error(kind));
3919            }
3920
3921            // Join the whitespace or fold line breaks.
3922            if leading_blanks {
3923                // Folding rule:
3924                //   if there was no leading break, preserve the pending whitespace already emitted
3925                //   if there was a leading break but no trailing breaks, fold to one space
3926                //   otherwise, preserve the trailing breaks already emitted
3927                if has_leading_break && !has_trailing_breaks {
3928                    match buf {
3929                        FlowScalarBuf::Owned(ref mut string) => string.push(' '),
3930                        FlowScalarBuf::Borrowed { .. } => {
3931                            self.promote_flow_scalar_buf_to_owned(&start_mark, &mut buf)?;
3932                            let Some(string) = buf.as_owned_mut() else {
3933                                unreachable!()
3934                            };
3935                            string.push(' ');
3936                        }
3937                    }
3938                }
3939            }
3940            // else: trailing blanks are already appended to `string`
3941        } // loop
3942
3943        // Eat the right quote.
3944        self.skip_non_blank();
3945        let end_mark = self.mark;
3946
3947        // Ensure there is no invalid trailing content.
3948        self.skip_ws_to_eol(SkipTabs::Yes)?;
3949        self.ensure_current_char_is_printable()?;
3950        match self.input.peek() {
3951            // These can be encountered in flow sequences or mappings.
3952            ',' | '}' | ']' if self.flow_level > 0 => {}
3953            // An end-of-line / end-of-stream is fine. No trailing content.
3954            c if is_breakz(c) => {}
3955            // ':' can be encountered if our scalar is a key.
3956            // Outside of flow contexts, keys cannot span multiple lines
3957            ':' if self.flow_level == 0 && start_mark.line == self.mark.line => {}
3958            // Inside a flow context, this is allowed.
3959            ':' if self.flow_level > 0 => {}
3960            _ => {
3961                let kind = if single {
3962                    ErrorKind::InvalidTrailingSingleQuotedScalar
3963                } else {
3964                    ErrorKind::InvalidTrailingDoubleQuotedScalar
3965                };
3966                return Err(self.scan_error(kind));
3967            }
3968        }
3969
3970        let style = if single {
3971            ScalarStyle::SingleQuoted
3972        } else {
3973            ScalarStyle::DoubleQuoted
3974        };
3975
3976        let contents = match buf {
3977            FlowScalarBuf::Owned(string) => Cow::Owned(string),
3978            FlowScalarBuf::Borrowed {
3979                start,
3980                mut end,
3981                pending_ws_start,
3982                pending_ws_end,
3983            } => {
3984                // If we ended after a whitespace run, it is part of the output (no break followed).
3985                if pending_ws_start.is_some() {
3986                    end = pending_ws_end;
3987                }
3988                if let Some(slice) = self.try_borrow_slice(start, end) {
3989                    Cow::Borrowed(slice)
3990                } else {
3991                    let slice = self.input.slice_bytes(start, end).ok_or_else(|| {
3992                        ScanError::from_kind(start_mark, ErrorKind::InputOffsetsWithoutSlice)
3993                    })?;
3994                    Cow::Owned(slice.to_owned())
3995                }
3996            }
3997        };
3998
3999        Ok(Token(
4000            Span::new(start_mark, end_mark),
4001            TokenType::Scalar(style, contents),
4002        ))
4003    }
4004
4005    /// Consume a printable run without per-character buffer and marker updates.
4006    fn consume_flow_scalar_chunk(&mut self, single: bool, buf: &mut FlowScalarBuf) -> bool {
4007        let (chunk, consumed) = self.input.take_quoted_scalar_chunk(single);
4008        if consumed == 0 {
4009            return false;
4010        }
4011
4012        match buf {
4013            FlowScalarBuf::Owned(string) => string.push_str(chunk),
4014            FlowScalarBuf::Borrowed { .. } => buf.commit_pending_ws(),
4015        }
4016
4017        // The input already consumed the run and counted its Unicode scalar values.
4018        self.mark.offsets.chars += consumed;
4019        self.mark.col += consumed;
4020        self.mark.offsets.bytes = self.input.byte_offset();
4021        self.leading_whitespace = false;
4022        if let (Some(new_end), FlowScalarBuf::Borrowed { end, .. }) = (self.mark.offsets.bytes, buf)
4023        {
4024            *end = new_end;
4025        }
4026        true
4027    }
4028
4029    /// Consume successive non-whitespace characters from a flow scalar.
4030    ///
4031    /// This function resolves escape sequences and stops upon encountering a whitespace, the end
4032    /// of the stream or the closing character for the scalar (`'` for single quoted scalars, `"`
4033    /// for double quoted scalars).
4034    ///
4035    /// # Errors
4036    /// Return an error if an invalid escape sequence is found.
4037    fn consume_flow_scalar_non_whitespace_chars(
4038        &mut self,
4039        single: bool,
4040        buf: &mut FlowScalarBuf,
4041        leading_blanks: &mut bool,
4042        start_mark: &Marker,
4043    ) -> Result<(), ScanError> {
4044        self.input.lookahead(2);
4045        loop {
4046            let character = self.input.peek();
4047            if is_blank_or_breakz(character) || !is_printable(character) {
4048                break;
4049            }
4050            match character {
4051                // Check for an escaped single quote.
4052                '\'' if self.input.peek_nth(1) == '\'' && single => {
4053                    if matches!(buf, FlowScalarBuf::Borrowed { .. }) {
4054                        buf.commit_pending_ws();
4055                        self.promote_flow_scalar_buf_to_owned(start_mark, buf)?;
4056                    }
4057                    let Some(string) = buf.as_owned_mut() else {
4058                        unreachable!()
4059                    };
4060                    string.push('\'');
4061                    self.skip_n_non_blank(2);
4062                }
4063                // Check for the right quote.
4064                '\'' if single => break,
4065                '"' if !single => break,
4066                // Check for an escaped line break.
4067                '\\' if !single && is_break(self.input.peek_nth(1)) => {
4068                    self.input.lookahead(3);
4069                    if matches!(buf, FlowScalarBuf::Borrowed { .. }) {
4070                        buf.commit_pending_ws();
4071                        self.promote_flow_scalar_buf_to_owned(start_mark, buf)?;
4072                    }
4073                    self.skip_non_blank();
4074                    self.skip_linebreak();
4075                    *leading_blanks = true;
4076                    break;
4077                }
4078                // Check for an escape sequence.
4079                '\\' if !single => {
4080                    if matches!(buf, FlowScalarBuf::Borrowed { .. }) {
4081                        buf.commit_pending_ws();
4082                        self.promote_flow_scalar_buf_to_owned(start_mark, buf)?;
4083                    }
4084                    let Some(string) = buf.as_owned_mut() else {
4085                        unreachable!()
4086                    };
4087                    string.push(self.resolve_flow_scalar_escape_sequence(start_mark)?);
4088                }
4089                c => {
4090                    if self.consume_flow_scalar_chunk(single, buf) {
4091                        self.input.lookahead(2);
4092                        continue;
4093                    }
4094                    match buf {
4095                        FlowScalarBuf::Owned(ref mut string) => {
4096                            string.push(c);
4097                        }
4098                        FlowScalarBuf::Borrowed { .. } => {
4099                            buf.commit_pending_ws();
4100                        }
4101                    }
4102                    self.skip_non_blank();
4103
4104                    if let Some(new_end) = self.input.byte_offset() {
4105                        if let FlowScalarBuf::Borrowed { end, .. } = buf {
4106                            *end = new_end;
4107                        }
4108                    }
4109                }
4110            }
4111            self.input.lookahead(2);
4112        }
4113        Ok(())
4114    }
4115
4116    /// Escape the sequence we encounter in a flow scalar.
4117    ///
4118    /// `self.input.peek()` must point to the `\` starting the escape sequence.
4119    ///
4120    /// # Errors
4121    /// Return an error if an invalid escape sequence is found.
4122    fn resolve_flow_scalar_escape_sequence(
4123        &mut self,
4124        start_mark: &Marker,
4125    ) -> Result<char, ScanError> {
4126        let mut code_length = 0usize;
4127        let mut ret = '\0';
4128
4129        match self.input.peek_nth(1) {
4130            '0' => ret = '\0',
4131            'a' => ret = '\x07',
4132            'b' => ret = '\x08',
4133            't' | '\t' => ret = '\t',
4134            'n' => ret = '\n',
4135            'v' => ret = '\x0b',
4136            'f' => ret = '\x0c',
4137            'r' => ret = '\x0d',
4138            'e' => ret = '\x1b',
4139            ' ' => ret = '\x20',
4140            '"' => ret = '"',
4141            '/' => ret = '/',
4142            '\\' => ret = '\\',
4143            // Unicode next line (#x85)
4144            'N' => ret = char::from_u32(0x85).unwrap(),
4145            // Unicode non-breaking space (#xA0)
4146            '_' => ret = char::from_u32(0xA0).unwrap(),
4147            // Unicode line separator (#x2028)
4148            'L' => ret = char::from_u32(0x2028).unwrap(),
4149            // Unicode paragraph separator (#x2029)
4150            'P' => ret = char::from_u32(0x2029).unwrap(),
4151            'x' => code_length = 2,
4152            'u' => code_length = 4,
4153            'U' => code_length = 8,
4154            _ => {
4155                return Err(ScanError::from_kind(
4156                    *start_mark,
4157                    ErrorKind::UnknownQuotedScalarEscape,
4158                ))
4159            }
4160        }
4161        self.skip_n_non_blank(2);
4162
4163        // Consume an arbitrary escape code.
4164        if code_length > 0 {
4165            self.input.lookahead(code_length);
4166            let mut value = 0u32;
4167            for i in 0..code_length {
4168                let c = self.input.peek_nth(i);
4169                if !is_hex(c) {
4170                    return Err(ScanError::from_kind(
4171                        *start_mark,
4172                        ErrorKind::InvalidQuotedScalarHexEscape,
4173                    ));
4174                }
4175                value = (value << 4) + as_hex(c);
4176            }
4177
4178            self.skip_n_non_blank(code_length);
4179
4180            // Handle JSON surrogate pairs: high surrogate followed by low surrogate
4181            if code_length == 4 && (0xD800..=0xDBFF).contains(&value) {
4182                self.input.lookahead(2);
4183                if self.input.peek() == '\\' && self.input.peek_nth(1) == 'u' {
4184                    self.skip_n_non_blank(2);
4185                    self.input.lookahead(4);
4186                    let mut low_value = 0u32;
4187                    for i in 0..4 {
4188                        let c = self.input.peek_nth(i);
4189                        if !is_hex(c) {
4190                            return Err(ScanError::from_kind(
4191                                *start_mark,
4192                                ErrorKind::InvalidLowSurrogateHexEscape,
4193                            ));
4194                        }
4195                        low_value = (low_value << 4) + as_hex(c);
4196                    }
4197                    if (0xDC00..=0xDFFF).contains(&low_value) {
4198                        value = 0x10000 + (((value - 0xD800) << 10) | (low_value - 0xDC00));
4199                        self.skip_n_non_blank(4);
4200                    } else {
4201                        return Err(ScanError::from_kind(
4202                            *start_mark,
4203                            ErrorKind::InvalidLowSurrogate,
4204                        ));
4205                    }
4206                } else {
4207                    return Err(ScanError::from_kind(
4208                        *start_mark,
4209                        ErrorKind::MissingLowSurrogate,
4210                    ));
4211                }
4212            } else if code_length == 4 && (0xDC00..=0xDFFF).contains(&value) {
4213                return Err(ScanError::from_kind(
4214                    *start_mark,
4215                    ErrorKind::UnpairedLowSurrogate,
4216                ));
4217            }
4218
4219            let Some(ch) = char::from_u32(value) else {
4220                return Err(ScanError::from_kind(
4221                    *start_mark,
4222                    ErrorKind::InvalidUnicodeEscape,
4223                ));
4224            };
4225            ret = ch;
4226        }
4227        Ok(ret)
4228    }
4229
4230    fn fetch_plain_scalar(&mut self) -> ScanResult {
4231        self.save_simple_key();
4232        self.disallow_simple_key();
4233
4234        let token_index = self.tokens.len();
4235        let tok = self.scan_plain_scalar()?;
4236
4237        self.insert_token(token_index, tok);
4238        Ok(())
4239    }
4240
4241    /// Scan for a plain scalar.
4242    ///
4243    /// Plain scalars are the most readable but restricted style. They may span multiple lines in
4244    /// some contexts.
4245    #[allow(clippy::too_many_lines)]
4246    fn scan_plain_scalar(&mut self) -> Result<Token<'input>, ScanError> {
4247        self.unroll_non_block_indents();
4248        let indent = self.indent + 1;
4249        let start_mark = self.mark;
4250
4251        let borrow_start = start_mark
4252            .byte_offset()
4253            .filter(|start| self.try_borrow_slice(*start, *start).is_some());
4254        let mut string = borrow_start.is_none().then(|| String::with_capacity(32));
4255        let mut has_content = false;
4256        self.buf_whitespaces.clear();
4257        self.buf_leading_break.clear();
4258        self.buf_trailing_breaks.clear();
4259        let mut end_mark = self.mark;
4260
4261        loop {
4262            self.input.lookahead(4);
4263            if (self.mark.col == 0 && self.input.next_is_document_indicator())
4264                || self.input.peek() == '#'
4265            {
4266                // BS4K: If a `#` starts a comment after some separation spaces following content
4267                // of a plain scalar in block context, and there is potential continuation on the
4268                // next line, this is invalid. We cannot decide yet if there will be continuation,
4269                // so record that a comment interrupted a plain scalar.
4270                if self.input.peek() == '#'
4271                    && has_content
4272                    && !self.buf_whitespaces.is_empty()
4273                    && self.flow_level == 0
4274                {
4275                    self.interrupted_plain_by_comment = Some(self.mark);
4276                }
4277                break;
4278            }
4279
4280            // The dash restriction applies only at the start of a plain scalar.
4281            if !has_content
4282                && self.flow_level > 0
4283                && self.input.peek() == '-'
4284                && is_flow(self.input.peek_nth(1))
4285            {
4286                return Err(self.scan_error(ErrorKind::PlainScalarStartsWithDashFlowIndicator));
4287            }
4288
4289            if !self.input.next_is_blank_or_breakz()
4290                && self.input.next_can_be_plain_scalar(self.flow_level > 0)
4291            {
4292                if self.leading_whitespace {
4293                    if has_content && string.is_none() {
4294                        let start = borrow_start.expect("borrowed scalar has a start offset");
4295                        let end = end_mark.byte_offset().ok_or_else(|| {
4296                            ScanError::from_kind(start_mark, ErrorKind::InputOffsetsWithoutSlice)
4297                        })?;
4298                        let prefix = self.try_borrow_slice(start, end).ok_or_else(|| {
4299                            ScanError::from_kind(start_mark, ErrorKind::InputOffsetsWithoutSlice)
4300                        })?;
4301                        string = Some(prefix.to_owned());
4302                    }
4303                    if self.buf_leading_break.is_empty() {
4304                        if let Some(output) = string.as_mut() {
4305                            output.push_str(&self.buf_leading_break);
4306                            output.push_str(&self.buf_trailing_breaks);
4307                        }
4308                        self.buf_trailing_breaks.clear();
4309                        self.buf_leading_break.clear();
4310                    } else {
4311                        if self.buf_trailing_breaks.is_empty() {
4312                            if let Some(output) = string.as_mut() {
4313                                output.push(' ');
4314                            }
4315                        } else {
4316                            if let Some(output) = string.as_mut() {
4317                                output.push_str(&self.buf_trailing_breaks);
4318                            }
4319                            self.buf_trailing_breaks.clear();
4320                        }
4321                        self.buf_leading_break.clear();
4322                    }
4323                    self.leading_whitespace = false;
4324                } else if !self.buf_whitespaces.is_empty() {
4325                    if let Some(output) = string.as_mut() {
4326                        output.push_str(&self.buf_whitespaces);
4327                    }
4328                    self.buf_whitespaces.clear();
4329                }
4330
4331                // We can unroll the first iteration of the loop.
4332                has_content = true;
4333                if let Some(output) = string.as_mut() {
4334                    output.push(self.input.peek());
4335                }
4336                self.skip_non_blank();
4337                if let Some(output) = string.as_mut() {
4338                    output.reserve(self.input.bufmaxlen());
4339                }
4340
4341                // Add content non-blank characters to the scalar.
4342                let mut end = false;
4343                while !end {
4344                    // Fill the buffer once and process all characters in the buffer until the next
4345                    // fetch. `next_can_be_plain_scalar` needs 2 lookahead characters, so keep one
4346                    // spare slot for normal inputs while still forcing progress for very small
4347                    // custom buffer lengths.
4348                    self.input.lookahead(self.input.bufmaxlen());
4349                    let chunk_len = self.input.bufmaxlen().saturating_sub(1).max(1);
4350                    let (stop, chars_consumed) = if let Some(output) = string.as_mut() {
4351                        self.input
4352                            .fetch_plain_scalar_chunk(output, chunk_len, self.flow_level > 0)
4353                    } else {
4354                        self.input
4355                            .skip_plain_scalar_chunk(chunk_len, self.flow_level > 0)
4356                    };
4357                    end = stop;
4358                    self.mark.offsets.chars += chars_consumed;
4359                    self.mark.col += chars_consumed;
4360                    self.mark.offsets.bytes = self.input.byte_offset();
4361                }
4362                end_mark = self.mark;
4363            }
4364
4365            // We may reach the end of a plain scalar if:
4366            //  - We reach eof
4367            //  - We reach ": "
4368            //  - We find a flow character in a flow context
4369            if !(self.input.next_is_blank() || self.input.next_is_break()) {
4370                break;
4371            }
4372
4373            // Process blank characters.
4374            self.input.lookahead(2);
4375            while self.input.next_is_blank_or_break() {
4376                if self.input.next_is_blank() {
4377                    if !self.leading_whitespace {
4378                        self.buf_whitespaces.push(self.input.peek());
4379                        self.skip_blank();
4380                    } else if (self.mark.col as isize) < indent && self.input.peek() == '\t' {
4381                        // Tabs in an indentation columns are allowed if and only if the line is
4382                        // empty. Skip to the end of the line.
4383                        self.skip_ws_to_eol(SkipTabs::Yes)?;
4384                        if !self.input.next_is_breakz() {
4385                            return Err(ScanError::from_kind(
4386                                start_mark,
4387                                ErrorKind::TabInPlainScalar,
4388                            ));
4389                        }
4390                    } else {
4391                        self.skip_blank();
4392                    }
4393                } else {
4394                    // Check if it is a first line break
4395                    if self.leading_whitespace {
4396                        self.skip_break();
4397                        self.buf_trailing_breaks.push('\n');
4398                    } else {
4399                        self.buf_whitespaces.clear();
4400                        self.skip_break();
4401                        self.buf_leading_break.push('\n');
4402                        self.leading_whitespace = true;
4403                    }
4404                }
4405                self.input.lookahead(2);
4406            }
4407
4408            // Stop before an under-indented continuation. In strict flow context the
4409            // next token fetch reports its indentation error without consuming the content.
4410            if (self.flow_level == 0 || self.options.strict_indentation)
4411                && (self.mark.col as isize) < indent
4412            {
4413                break;
4414            }
4415        }
4416
4417        if self.leading_whitespace {
4418            self.allow_simple_key();
4419        }
4420
4421        let borrowed_contents = if string.is_none() {
4422            let start = borrow_start.expect("borrowed scalar has a start offset");
4423            let end = end_mark.byte_offset().ok_or_else(|| {
4424                ScanError::from_kind(start_mark, ErrorKind::InputOffsetsWithoutSlice)
4425            })?;
4426            Some(self.try_borrow_slice(start, end).ok_or_else(|| {
4427                ScanError::from_kind(start_mark, ErrorKind::InputOffsetsWithoutSlice)
4428            })?)
4429        } else {
4430            None
4431        };
4432        let scalar_text = borrowed_contents.unwrap_or_else(|| {
4433            string
4434                .as_deref()
4435                .expect("owned plain scalar has an output buffer")
4436        });
4437        if let Some(character) = find_non_printable(scalar_text) {
4438            return Err(ScanError::from_kind(
4439                start_mark,
4440                ErrorKind::UnexpectedCharacter { character },
4441            ));
4442        }
4443        self.ensure_current_char_is_printable()?;
4444
4445        if has_content {
4446            let contents = if let Some(slice) = borrowed_contents {
4447                Cow::Borrowed(slice)
4448            } else {
4449                Cow::Owned(string.expect("owned plain scalar has an output buffer"))
4450            };
4451
4452            Ok(Token(
4453                Span::new(start_mark, end_mark),
4454                TokenType::Scalar(ScalarStyle::Plain, contents),
4455            ))
4456        } else {
4457            // `fetch_plain_scalar` must absolutely consume at least one byte. Otherwise,
4458            // `fetch_next_token` will never stop calling it. An empty plain scalar may happen with
4459            // erroneous inputs such as "{...".
4460            Err(ScanError::from_kind(
4461                start_mark,
4462                ErrorKind::UnexpectedEndOfPlainScalar,
4463            ))
4464        }
4465    }
4466
4467    fn fetch_key(&mut self) -> ScanResult {
4468        let start_mark = self.mark;
4469        if self.flow_level == 0 {
4470            // Check if we are allowed to start a new key (not necessarily simple).
4471            if !self.simple_key_allowed {
4472                return Err(self.scan_error(ErrorKind::MappingKeyNotAllowed));
4473            }
4474            self.roll_indent(
4475                start_mark.col,
4476                None,
4477                TokenType::BlockMappingStart,
4478                start_mark,
4479            )?;
4480        } else {
4481            // The scanner, upon emitting a `Key`, will prepend a `MappingStart` event.
4482            self.set_current_flow_mapping_started(true);
4483        }
4484
4485        self.remove_simple_key()?;
4486
4487        if self.flow_level == 0 {
4488            self.allow_simple_key();
4489        } else {
4490            self.disallow_simple_key();
4491        }
4492
4493        self.skip_non_blank();
4494        let end_mark = self.mark;
4495        let token_index = self.tokens.len();
4496        self.explicit_key_tab_check_pending = false;
4497        // Block keys permit tab separation for scalar/flow nodes, but require spaces for
4498        // compact collections and indentation on subsequent lines. Keep that validation active
4499        // across comments, and across properties in strict mode. Flow collections use the
4500        // ordinary whitespace skipper.
4501        if self.flow_level == 0 {
4502            let stopped_after_comment = self.skip_yaml_whitespace()?;
4503            self.explicit_key_tab_check_pending = stopped_after_comment
4504                || (self.options.strict_indentation && matches!(self.input.peek(), '&' | '!'));
4505        }
4506        self.insert_token(
4507            token_index,
4508            Token(Span::new(start_mark, end_mark), TokenType::Key),
4509        );
4510        Ok(())
4511    }
4512
4513    /// Fetch a value in a mapping inside of a flow collection.
4514    ///
4515    /// This must not be called if [`self.flow_level`] is 0. This ensures the rules surrounding
4516    /// values in flow collections are respected prior to calling [`fetch_value`].
4517    ///
4518    /// [`self.flow_level`]: Self::flow_level
4519    /// [`fetch_value`]: Self::fetch_value
4520    fn fetch_flow_value(&mut self) -> ScanResult {
4521        let nc = self.input.peek_nth(1);
4522
4523        // If we encounter a ':' inside a flow collection and it is not immediately
4524        // followed by a blank or breakz:
4525        //   - We must check whether an adjacent value is allowed
4526        //     `["a":[]]` is valid. If the key is double-quoted, no need for a space. This
4527        //     is needed for JSON compatibility.
4528        //   - If not, we must ensure there is a space after the ':' and before its value.
4529        //     `[a: []]` is valid while `[a:[]]` isn't. `[a:b]` is treated as `["a:b"]`.
4530        //   - But if the value is empty (null), then it's okay.
4531        // The last line is for YAMLs like `[a:]`. The ':' is followed by a ']' (which is a
4532        // flow character), but the ']' is not the value. The value is an invisible empty
4533        // space which is represented as null ('~').
4534        if self.mark.index() != self.adjacent_value_allowed_at && (nc == '[' || nc == '{') {
4535            return Err(self.scan_error(ErrorKind::FlowMappingValueAdjacentCollection));
4536        }
4537
4538        self.fetch_value()
4539    }
4540
4541    /// Fetch a value from a mapping (after a `:`).
4542    fn fetch_value(&mut self) -> ScanResult {
4543        let sk = *self.simple_keys.last().unwrap();
4544        let start_mark = self.mark;
4545        let is_implicit_flow_mapping = self.current_flow_collection_is_sequence()
4546            && !self.current_flow_mapping_started()
4547            && !self.implicit_flow_mapping_states.is_empty();
4548        if is_implicit_flow_mapping {
4549            *self.implicit_flow_mapping_states.last_mut().unwrap() =
4550                ImplicitMappingState::Inside(self.flow_level);
4551        }
4552
4553        // Skip over ':'.
4554        self.skip_non_blank();
4555        // Tabs after ':' are separation whitespace. Queue any following comment after the
4556        // Value token; indentation on subsequent lines is checked by `skip_to_next_token`.
4557        let mut trailing_comment = None;
4558        let mut found_tabs = false;
4559        if matches!(self.input.look_ch(), ' ' | '\t') {
4560            let trailing_token_index = self.tokens.len();
4561            found_tabs = self.skip_ws_to_eol(SkipTabs::Yes)?.found_tabs();
4562            // Scanning to the end of this line can enqueue at most one comment.
4563            debug_assert!(self.tokens.len() <= trailing_token_index + 1);
4564            if self.tokens.len() > trailing_token_index {
4565                trailing_comment = self.tokens.pop_back();
4566            }
4567        }
4568
4569        if sk.possible {
4570            // Under-indented flow entries are a compatibility extension, but implicit keys
4571            // spanning lines are rejected by both PyYAML and ruamel.yaml. Keep that extension
4572            // limited to single-line keys; explicitly marked `?` keys may span lines.
4573            let block_indent = self.flow_block_indent();
4574            if self.flow_level > 0
4575                && sk.mark.line < start_mark.line
4576                && (sk.mark.col as isize) <= block_indent
4577            {
4578                return Err(ScanError::from_kind(
4579                    start_mark,
4580                    ErrorKind::InvalidColonPlacement,
4581                ));
4582            }
4583            let token_index = self.simple_key_token_index(&sk, start_mark)?;
4584            self.validate_flow_key_indentation(&sk, token_index, start_mark)?;
4585            // insert simple key
4586            let tok = Token(Span::empty(sk.mark), TokenType::Key);
4587            self.insert_token(token_index, tok);
4588            if is_implicit_flow_mapping {
4589                if sk.mark.line < start_mark.line {
4590                    return Err(ScanError::from_kind(
4591                        start_mark,
4592                        ErrorKind::InvalidColonPlacement,
4593                    ));
4594                }
4595                self.insert_token(
4596                    token_index,
4597                    Token(Span::empty(sk.mark), TokenType::FlowMappingStart),
4598                );
4599            }
4600
4601            // Add the BLOCK-MAPPING-START token if needed.
4602            self.roll_indent(
4603                sk.mark.col,
4604                Some(sk.token_number),
4605                TokenType::BlockMappingStart,
4606                sk.mark,
4607            )?;
4608            self.roll_one_col_indent();
4609
4610            self.clear_simple_key();
4611            self.disallow_simple_key();
4612        } else {
4613            if is_implicit_flow_mapping {
4614                self.tokens
4615                    .push_back(Token(Span::empty(start_mark), TokenType::FlowMappingStart).into());
4616            }
4617            // The ':' indicator follows a complex key.
4618            if self.flow_level == 0 {
4619                if !self.simple_key_allowed {
4620                    return Err(ScanError::from_kind(
4621                        start_mark,
4622                        ErrorKind::MappingValueNotAllowed,
4623                    ));
4624                }
4625
4626                self.roll_indent(
4627                    start_mark.col,
4628                    None,
4629                    TokenType::BlockMappingStart,
4630                    start_mark,
4631                )?;
4632            }
4633            self.roll_one_col_indent();
4634
4635            // An explicit value may start a compact block collection on this line only when
4636            // its indentation contains only spaces. Tabs still separate scalar and flow values.
4637            if self.flow_level == 0 && !found_tabs {
4638                self.allow_simple_key();
4639            } else {
4640                self.disallow_simple_key();
4641            }
4642        }
4643        self.tokens
4644            .push_back(Token(Span::empty(start_mark), TokenType::Value).into());
4645        if let Some(comment) = trailing_comment {
4646            self.tokens.push_back(comment);
4647        }
4648
4649        Ok(())
4650    }
4651
4652    /// Keep under-indented implicit flow keys on one line, including their properties.
4653    fn validate_flow_key_indentation(
4654        &self,
4655        key: &SimpleKey,
4656        token_index: usize,
4657        colon: Marker,
4658    ) -> ScanResult {
4659        if self.flow_level == 0 || key.mark.line == colon.line {
4660            return Ok(());
4661        }
4662
4663        let block_indent = self.flow_block_indent();
4664        // The saved key mark may point to an anchor or tag before the actual content.
4665        // Check each property and the first content token; comments do not indent a key.
4666        // Stop at the content token so a collection key's children are not checked here.
4667        let mut under_indented = [key.mark.col, colon.col]
4668            .iter()
4669            .any(|&col| (col as isize) <= block_indent);
4670        for token in self.tokens.iter().skip(token_index) {
4671            #[cfg(feature = "comments")]
4672            if matches!(token.1, QueuedTokenType::Comment(_)) {
4673                continue;
4674            }
4675            under_indented |= (token.0.start.col as isize) <= block_indent;
4676            if !matches!(
4677                token.1,
4678                QueuedTokenType::Anchor(_) | QueuedTokenType::Tag(..)
4679            ) {
4680                break;
4681            }
4682        }
4683        if under_indented {
4684            return Err(ScanError::from_kind(
4685                colon,
4686                ErrorKind::InvalidColonPlacement,
4687            ));
4688        }
4689        Ok(())
4690    }
4691
4692    /// Return the enclosing block indentation, excluding a temporary one-column indent.
4693    fn flow_block_indent(&self) -> isize {
4694        self.indents
4695            .last()
4696            .filter(|indent| !indent.needs_block_end)
4697            .map_or(self.indent, |indent| indent.indent)
4698    }
4699
4700    /// Add an indentation level to the stack with the given block token, if needed.
4701    ///
4702    /// An indentation level is added only if:
4703    ///   - We are not in a flow-style construct (which don't have indentation per-se).
4704    ///   - The current column is further indented than the last indent we have registered.
4705    fn roll_indent(
4706        &mut self,
4707        col: usize,
4708        number: Option<usize>,
4709        tok: TokenType<'input>,
4710        mark: Marker,
4711    ) -> ScanResult {
4712        if self.flow_level > 0 {
4713            return Ok(());
4714        }
4715
4716        // If the last indent was a non-block indent, remove it.
4717        // This means that we prepared an indent that we thought we wouldn't use, but realized just
4718        // now that it is a block indent.
4719        if self.indent <= col as isize {
4720            if let Some(indent) = self.indents.last() {
4721                if !indent.needs_block_end {
4722                    self.indent = indent.indent;
4723                    self.indents.pop();
4724                }
4725            }
4726        }
4727
4728        if self.indent < col as isize {
4729            if self.block_level >= self.options.block_nesting_limit {
4730                return Err(ScanError::from_kind(
4731                    mark,
4732                    ErrorKind::RecursionLimitExceeded,
4733                ));
4734            }
4735            self.indents.push(Indent {
4736                indent: self.indent,
4737                needs_block_end: true,
4738            });
4739            self.block_level += 1;
4740            self.indent = col as isize;
4741            let tokens_parsed = self.tokens_parsed;
4742            match number {
4743                Some(n) => self.insert_token(n - tokens_parsed, Token(Span::empty(mark), tok)),
4744                None => self.tokens.push_back(Token(Span::empty(mark), tok).into()),
4745            }
4746        }
4747        Ok(())
4748    }
4749
4750    /// Pop indentation levels from the stack as much as needed.
4751    ///
4752    /// Indentation levels are popped from the stack while they are further indented than `col`.
4753    /// If we are in a flow-style construct (which don't have indentation per-se), this function
4754    /// does nothing.
4755    fn unroll_indent(&mut self, col: isize) {
4756        if self.flow_level > 0 {
4757            return;
4758        }
4759        while self.indent > col {
4760            let indent = self.indents.pop().unwrap();
4761            self.indent = indent.indent;
4762            if indent.needs_block_end {
4763                debug_assert!(self.block_level > 0);
4764                self.block_level -= 1;
4765                self.tokens
4766                    .push_back(Token(Span::empty(self.mark), TokenType::BlockEnd).into());
4767            }
4768        }
4769    }
4770
4771    /// Add an indentation level of 1 column that does not start a block.
4772    ///
4773    /// See the documentation of [`Indent::needs_block_end`] for more details.
4774    /// An indentation is not added if we are inside a flow level or if the last indent is already
4775    /// a non-block indent.
4776    fn roll_one_col_indent(&mut self) {
4777        if self.flow_level == 0 && self.indents.last().is_some_and(|x| x.needs_block_end) {
4778            self.indents.push(Indent {
4779                indent: self.indent,
4780                needs_block_end: false,
4781            });
4782            self.indent += 1;
4783        }
4784    }
4785
4786    /// Unroll all last indents created with [`Self::roll_one_col_indent`].
4787    fn unroll_non_block_indents(&mut self) {
4788        while let Some(indent) = self.indents.last() {
4789            if indent.needs_block_end {
4790                break;
4791            }
4792            self.indent = indent.indent;
4793            self.indents.pop();
4794        }
4795    }
4796
4797    /// Mark the next token to be inserted as a potential simple key.
4798    fn save_simple_key(&mut self) {
4799        if self.simple_key_allowed {
4800            let required = self.flow_level == 0
4801                && self.indent == (self.mark.col as isize)
4802                && self.indents.last().unwrap().needs_block_end;
4803
4804            if let Some(last) = self.simple_keys.last_mut() {
4805                *last = SimpleKey {
4806                    mark: self.mark,
4807                    possible: true,
4808                    required,
4809                    token_number: self.tokens_parsed + self.tokens.len(),
4810                };
4811                self.first_simple_key.get_or_insert(self.flow_level);
4812            }
4813        }
4814    }
4815
4816    fn remove_simple_key(&mut self) -> ScanResult {
4817        let last = self.simple_keys.last().unwrap();
4818        if last.possible && last.required {
4819            return Err(Self::simple_key_expected(last.mark));
4820        }
4821
4822        self.clear_simple_key();
4823        Ok(())
4824    }
4825
4826    /// Clear the current key after it is resolved or checked to be optional.
4827    fn clear_simple_key(&mut self) {
4828        self.simple_keys.last_mut().unwrap().possible = false;
4829        if self.first_simple_key == Some(self.flow_level) {
4830            // This is the top level, so no other possible keys follow it.
4831            self.first_simple_key = None;
4832        }
4833    }
4834
4835    /// Return whether the scanner is inside a block but outside of a flow sequence.
4836    fn is_within_block(&self) -> bool {
4837        !self.indents.is_empty()
4838    }
4839
4840    /// If an implicit mapping had started, end it.
4841    ///
4842    /// This function does not pop the state in [`implicit_flow_mapping_states`].
4843    ///
4844    /// [`implicit_flow_mapping_states`]: Self::implicit_flow_mapping_states
4845    fn end_implicit_mapping(&mut self, mark: Marker, flow_level: usize) {
4846        if self
4847            .implicit_flow_mapping_states
4848            .last()
4849            .is_some_and(|state| *state == ImplicitMappingState::Inside(flow_level))
4850        {
4851            *self.implicit_flow_mapping_states.last_mut().unwrap() = ImplicitMappingState::Possible;
4852            self.set_current_flow_mapping_started(false);
4853            self.tokens
4854                .push_back(Token(Span::empty(mark), TokenType::FlowMappingEnd).into());
4855        }
4856    }
4857
4858    fn current_flow_collection_is_sequence(&self) -> bool {
4859        self.flow_markers
4860            .last()
4861            .is_some_and(|(_, bracket)| *bracket == '[')
4862    }
4863
4864    fn current_flow_mapping_started(&self) -> bool {
4865        self.flow_mapping_started.last().copied().unwrap_or(false)
4866    }
4867
4868    fn set_current_flow_mapping_started(&mut self, started: bool) {
4869        if let Some(current) = self.flow_mapping_started.last_mut() {
4870            *current = started;
4871        }
4872    }
4873}
4874
4875/// Chomping, how final line breaks and trailing empty lines are interpreted.
4876///
4877/// See YAML spec 8.1.1.2.
4878#[derive(PartialEq, Eq)]
4879enum Chomping {
4880    /// The final line break and any trailing empty lines are excluded.
4881    Strip,
4882    /// The final line break is preserved, but trailing empty lines are excluded.
4883    Clip,
4884    /// The final line break and trailing empty lines are included.
4885    Keep,
4886}
4887
4888#[cfg(test)]
4889mod test {
4890    use alloc::{
4891        borrow::{Cow, ToOwned},
4892        rc::Rc,
4893        string::String,
4894        vec,
4895        vec::Vec,
4896    };
4897    use core::cell::Cell;
4898
4899    use crate::error::{ErrorKind, ScanError};
4900    #[cfg(feature = "comments")]
4901    use crate::scanner::{Comment, Placement};
4902    use crate::{
4903        input::{str::StrInput, BorrowedInput, BufferedInput, Input},
4904        scanner::{
4905            Marker, QueuedToken, QueuedTokenType, ScalarStyle, Scanner, Span, Token, TokenType,
4906        },
4907    };
4908
4909    #[test]
4910    fn tag_span_supports_the_full_u32_length_without_allocating() {
4911        let start = Marker::new(0, 1, 0).with_byte_offset(Some(0));
4912        let span = Span::empty(start).with_tag_span(Some((start, u32::MAX)));
4913        let tag_span = span.tag_span().unwrap();
4914        let length = usize::try_from(u32::MAX).unwrap();
4915        assert_eq!(tag_span.start, start);
4916        assert_eq!(tag_span.end.index(), length);
4917        assert_eq!(tag_span.end.col(), length);
4918        assert_eq!(tag_span.end.line(), 1);
4919        assert_eq!(tag_span.end.byte_offset(), Some(length));
4920    }
4921
4922    #[test]
4923    fn tag_span_rejects_overflow_in_each_reconstructed_coordinate() {
4924        for start in [
4925            Marker::new(usize::MAX, 1, 0),
4926            Marker::new(0, 1, usize::MAX),
4927            Marker::new(0, 1, 0).with_byte_offset(Some(usize::MAX)),
4928        ] {
4929            let span = Span::empty(start).with_tag_span(Some((start, 1)));
4930            assert_eq!(span.tag_span(), None);
4931        }
4932    }
4933
4934    #[test]
4935    fn recovery_ignores_invalid_document_marker_lookalikes() {
4936        let input = "@bad\n---# comment\n  ---\n---\0\n... trailing\n--- healthy\n";
4937        let mut scanner = Scanner::new(StrInput::new(input));
4938        assert!(matches!(
4939            scanner.next_token().unwrap().unwrap().1,
4940            TokenType::StreamStart
4941        ));
4942        assert!(scanner.next_token().is_err());
4943
4944        scanner.proceed_next_document(None).unwrap();
4945        let token = scanner.next_token().unwrap().unwrap();
4946        assert_eq!(token.1, TokenType::DocumentStart);
4947        assert_eq!(token.0.start.line(), 6);
4948        assert!(matches!(
4949            scanner.next_token().unwrap().unwrap().1,
4950            TokenType::Scalar(_, ref value) if value == "healthy"
4951        ));
4952    }
4953
4954    #[test]
4955    fn recovery_rejects_end_marker_queued_before_its_line_failed() {
4956        let mut scanner =
4957            Scanner::new(StrInput::new("... trailing\nnot_a_document\n--- healthy\n"));
4958        scanner.next_token().unwrap();
4959        assert_eq!(
4960            scanner.next_token().unwrap_err().kind(),
4961            &ErrorKind::InvalidDocumentEnd
4962        );
4963        assert!(scanner
4964            .tokens
4965            .iter()
4966            .any(|token| matches!(token.1, QueuedTokenType::DocumentEnd)));
4967
4968        scanner.proceed_next_document(None).unwrap();
4969        let token = scanner.next_token().unwrap().unwrap();
4970        assert_eq!(token.1, TokenType::DocumentStart);
4971        assert_eq!(token.0.start.line(), 3);
4972    }
4973
4974    #[test]
4975    fn recovery_preserves_boundary_already_held_by_parser() {
4976        let mut scanner = Scanner::new(StrInput::new("first\n--- second\n"));
4977        let boundary = loop {
4978            let token = scanner.next_queued_token().unwrap().unwrap();
4979            if matches!(token.1, QueuedTokenType::DocumentStart) {
4980                break token;
4981            }
4982        };
4983        let span = boundary.0;
4984        scanner.proceed_next_document(Some(boundary)).unwrap();
4985        assert_eq!(
4986            scanner.next_token().unwrap().unwrap(),
4987            Token(span, TokenType::DocumentStart)
4988        );
4989        assert!(matches!(
4990            scanner.next_token().unwrap().unwrap().1,
4991            TokenType::Scalar(_, ref value) if value == "second"
4992        ));
4993    }
4994
4995    #[test]
4996    fn recovery_retains_previously_reported_source_error() {
4997        let kind = ErrorKind::InputDecoding {
4998            message: "invalid encoding".into(),
4999        };
5000        let input = crate::FallibleBufferedInput::new(
5001            vec![Ok('['), Err(kind.clone()), Ok('\n')].into_iter(),
5002        );
5003        let mut scanner = Scanner::new(input);
5004        scanner.next_token().unwrap();
5005        let error = scanner.next_token().unwrap_err();
5006        assert_eq!(error.kind(), &kind);
5007        assert_eq!(scanner.proceed_next_document(None), Err(error));
5008    }
5009
5010    #[test]
5011    fn recovery_distinguishes_directive_header_errors_from_document_content() {
5012        for input in ["%YAML bad\n--- body\n", "%TAG invalid\n--- body\n"] {
5013            let mut scanner = Scanner::new(StrInput::new(input));
5014            scanner.next_token().unwrap();
5015            assert!(scanner.next_token().is_err());
5016            assert!(scanner.in_directive_prefix());
5017            scanner.proceed_next_document(None).unwrap();
5018            assert!(!scanner.in_directive_prefix());
5019        }
5020
5021        let mut scanner = Scanner::with_options(
5022            StrInput::new("%YAML 1.2\n--- body\n"),
5023            crate::options! { disallow_directives: true },
5024        );
5025        scanner.next_token().unwrap();
5026        assert!(scanner.next_token().is_err());
5027        assert!(scanner.in_directive_prefix());
5028
5029        for input in ["%YAML 1.2\n--- body\n", "%YAML 1.2\nbare\n"] {
5030            let mut scanner = Scanner::new(StrInput::new(input));
5031            scanner.next_token().unwrap();
5032            scanner.next_token().unwrap();
5033            assert!(scanner.in_directive_prefix());
5034            scanner.next_token().unwrap();
5035            assert!(!scanner.in_directive_prefix());
5036        }
5037    }
5038
5039    fn ignoring_comments_options() -> crate::Options {
5040        #[cfg(feature = "comments")]
5041        {
5042            crate::options! { emit_comments: false }
5043        }
5044        #[cfg(not(feature = "comments"))]
5045        {
5046            crate::Options::default()
5047        }
5048    }
5049
5050    struct CountingChars {
5051        chars: alloc::vec::IntoIter<char>,
5052        read: Rc<Cell<usize>>,
5053    }
5054
5055    impl Iterator for CountingChars {
5056        type Item = char;
5057
5058        fn next(&mut self) -> Option<Self::Item> {
5059            let next = self.chars.next();
5060            if next.is_some() {
5061                self.read.set(self.read.get() + 1);
5062            }
5063            next
5064        }
5065    }
5066
5067    struct SlicingOnlyInput<'input> {
5068        inner: StrInput<'input>,
5069        expose_slice: bool,
5070    }
5071
5072    impl<'input> SlicingOnlyInput<'input> {
5073        fn new(source: &'input str, expose_slice: bool) -> Self {
5074            Self {
5075                inner: StrInput::new(source),
5076                expose_slice,
5077            }
5078        }
5079    }
5080
5081    impl Input for SlicingOnlyInput<'_> {
5082        fn lookahead(&mut self, count: usize) {
5083            self.inner.lookahead(count);
5084        }
5085
5086        fn buflen(&self) -> usize {
5087            self.inner.buflen()
5088        }
5089
5090        fn bufmaxlen(&self) -> usize {
5091            self.inner.bufmaxlen()
5092        }
5093
5094        fn raw_read_ch(&mut self) -> char {
5095            self.inner.raw_read_ch()
5096        }
5097
5098        fn raw_read_non_breakz_ch(&mut self) -> Option<char> {
5099            self.inner.raw_read_non_breakz_ch()
5100        }
5101
5102        fn skip(&mut self) {
5103            self.inner.skip();
5104        }
5105
5106        fn skip_n(&mut self, count: usize) {
5107            self.inner.skip_n(count);
5108        }
5109
5110        fn peek(&self) -> char {
5111            self.inner.peek()
5112        }
5113
5114        fn peek_nth(&self, n: usize) -> char {
5115            self.inner.peek_nth(n)
5116        }
5117
5118        fn byte_offset(&self) -> Option<usize> {
5119            self.inner.byte_offset()
5120        }
5121
5122        fn slice_bytes(&self, start: usize, end: usize) -> Option<&str> {
5123            if self.expose_slice {
5124                self.inner.slice_bytes(start, end)
5125            } else {
5126                None
5127            }
5128        }
5129    }
5130
5131    impl<'input> BorrowedInput<'input> for SlicingOnlyInput<'input> {
5132        fn slice_borrowed(&self, _start: usize, _end: usize) -> Option<&'input str> {
5133            None
5134        }
5135    }
5136
5137    struct SmallReportedBufferInput<'input> {
5138        inner: StrInput<'input>,
5139        reported_bufmaxlen: usize,
5140    }
5141
5142    impl<'input> SmallReportedBufferInput<'input> {
5143        fn new(source: &'input str, reported_bufmaxlen: usize) -> Self {
5144            Self {
5145                inner: StrInput::new(source),
5146                reported_bufmaxlen,
5147            }
5148        }
5149    }
5150
5151    impl Input for SmallReportedBufferInput<'_> {
5152        fn lookahead(&mut self, count: usize) {
5153            self.inner.lookahead(count);
5154        }
5155
5156        fn buflen(&self) -> usize {
5157            self.inner.buflen()
5158        }
5159
5160        fn bufmaxlen(&self) -> usize {
5161            self.reported_bufmaxlen
5162        }
5163
5164        fn raw_read_ch(&mut self) -> char {
5165            self.inner.raw_read_ch()
5166        }
5167
5168        fn raw_read_non_breakz_ch(&mut self) -> Option<char> {
5169            self.inner.raw_read_non_breakz_ch()
5170        }
5171
5172        fn skip(&mut self) {
5173            self.inner.skip();
5174        }
5175
5176        fn skip_n(&mut self, count: usize) {
5177            self.inner.skip_n(count);
5178        }
5179
5180        fn peek(&self) -> char {
5181            self.inner.peek()
5182        }
5183
5184        fn peek_nth(&self, n: usize) -> char {
5185            self.inner.peek_nth(n)
5186        }
5187    }
5188
5189    impl<'input> BorrowedInput<'input> for SmallReportedBufferInput<'input> {
5190        fn slice_borrowed(&self, start: usize, end: usize) -> Option<&'input str> {
5191            self.inner.slice_borrowed(start, end)
5192        }
5193    }
5194
5195    #[test]
5196    fn anchor_character_set_allows_colon_and_rejects_flow_indicators() {
5197        use super::is_anchor_char;
5198
5199        assert!(is_anchor_char('x'));
5200        assert!(is_anchor_char('-'));
5201        assert!(is_anchor_char('_'));
5202        assert!(is_anchor_char(':'));
5203        assert!(is_anchor_char('#'));
5204        assert!(is_anchor_char('/'));
5205        assert!(is_anchor_char('?'));
5206
5207        for c in [',', '[', ']', '{', '}', ' ', '\t', '\n', '\r', '\0'] {
5208            assert!(
5209                !is_anchor_char(c),
5210                "character {c:?} must not be accepted in anchor/alias names"
5211            );
5212        }
5213    }
5214
5215    #[test]
5216    fn flow_simple_key_length_limit_bounds_buffering() {
5217        let mut yaml = String::from("[\n\"start\"\n");
5218        for _ in 0..600 {
5219            yaml.push_str("\"x\"\n");
5220        }
5221        let total_chars = yaml.chars().count();
5222        let read = Rc::new(Cell::new(0));
5223        let chars = yaml.chars().collect::<Vec<_>>().into_iter();
5224        let mut scanner = Scanner::new(BufferedInput::new(CountingChars {
5225            chars,
5226            read: Rc::clone(&read),
5227        }));
5228
5229        assert!(matches!(
5230            scanner.next_token().unwrap().unwrap().1,
5231            TokenType::StreamStart
5232        ));
5233
5234        let token = scanner.next_token().unwrap().unwrap();
5235        assert!(matches!(token.1, TokenType::FlowSequenceStart));
5236
5237        let token = scanner.next_token().unwrap().unwrap();
5238        assert!(matches!(
5239            token.1,
5240            TokenType::Scalar(_, ref value) if value == "start"
5241        ));
5242        assert!(
5243            read.get() < total_chars,
5244            "scanner consumed all {total_chars} chars before yielding the first flow scalar"
5245        );
5246        assert!(
5247            read.get() <= scanner.options.simple_key_max_lookahead + 128,
5248            "scanner read {} chars before yielding the first flow scalar",
5249            read.get()
5250        );
5251    }
5252
5253    #[test]
5254    fn block_scalar_indent_tolerates_small_reported_bufmaxlen() {
5255        let mut scanner = Scanner::new(SmallReportedBufferInput::new("|\n  value\n", 0));
5256
5257        let scalar = scanner
5258            .find_map(
5259                |token| match token.expect("valid YAML should scan without errors") {
5260                    Token(_, TokenType::Scalar(ScalarStyle::Literal, value)) => {
5261                        Some(value.into_owned())
5262                    }
5263                    _ => None,
5264                },
5265            )
5266            .expect("expected block scalar token");
5267
5268        assert_eq!(scalar, "value\n");
5269    }
5270
5271    #[test]
5272    fn plain_scalar_chunk_tolerates_small_reported_bufmaxlen() {
5273        let mut scanner = Scanner::new(SmallReportedBufferInput::new("plain\n", 0));
5274
5275        let scalar = scanner
5276            .find_map(
5277                |token| match token.expect("valid YAML should scan without errors") {
5278                    Token(_, TokenType::Scalar(ScalarStyle::Plain, value)) => {
5279                        Some(value.into_owned())
5280                    }
5281                    _ => None,
5282                },
5283            )
5284            .expect("expected plain scalar token");
5285
5286        assert_eq!(scalar, "plain");
5287    }
5288
5289    fn first_token_slice(
5290        yaml: &str,
5291        matches_token: impl Fn(&TokenType<'_>) -> bool,
5292    ) -> Option<String> {
5293        let mut scanner = Scanner::new(StrInput::new(yaml));
5294
5295        loop {
5296            let token = scanner
5297                .next_token()
5298                .expect("scanner should accept the test YAML")?;
5299            if matches_token(&token.1) {
5300                return token.0.slice(yaml).map(ToOwned::to_owned);
5301            }
5302        }
5303    }
5304
5305    #[test]
5306    fn flow_indicator_token_spans_cover_only_the_indicator() {
5307        assert_eq!(
5308            first_token_slice("[ # c\n  a]\n", |token| matches!(
5309                token,
5310                TokenType::FlowSequenceStart
5311            ))
5312            .as_deref(),
5313            Some("[")
5314        );
5315        assert_eq!(
5316            first_token_slice("{ # c\n  a: b}\n", |token| matches!(
5317                token,
5318                TokenType::FlowMappingStart
5319            ))
5320            .as_deref(),
5321            Some("{")
5322        );
5323        assert_eq!(
5324            first_token_slice("[a] # c\n", |token| matches!(
5325                token,
5326                TokenType::FlowSequenceEnd
5327            ))
5328            .as_deref(),
5329            Some("]")
5330        );
5331        assert_eq!(
5332            first_token_slice("{a: b} # c\n", |token| matches!(
5333                token,
5334                TokenType::FlowMappingEnd
5335            ))
5336            .as_deref(),
5337            Some("}")
5338        );
5339        assert_eq!(
5340            first_token_slice("[a, # c\nb]\n", |token| matches!(
5341                token,
5342                TokenType::FlowEntry
5343            ))
5344            .as_deref(),
5345            Some(",")
5346        );
5347    }
5348
5349    #[test]
5350    fn explicit_key_token_span_covers_only_the_indicator() {
5351        assert_eq!(
5352            first_token_slice("? # c\n: value\n", |token| matches!(token, TokenType::Key))
5353                .as_deref(),
5354            Some("?")
5355        );
5356    }
5357
5358    #[test]
5359    #[cfg(feature = "comments")]
5360    fn comment_capture_does_not_change_leading_whitespace() {
5361        let mut scanner = Scanner::new(StrInput::new("# comment\n"));
5362
5363        let token = scanner.scan_comment_token().unwrap();
5364
5365        assert!(scanner.leading_whitespace);
5366        assert!(matches!(token.1, TokenType::Comment(ref comment) if comment.text == " comment"));
5367
5368        let mut scanner = Scanner::new(BufferedInput::new("# streaming\n".chars()));
5369        scanner.input.lookahead(1);
5370
5371        let token = scanner.scan_comment_token().unwrap();
5372
5373        assert!(scanner.leading_whitespace);
5374        assert!(matches!(token.1, TokenType::Comment(ref comment) if comment.text == " streaming"));
5375    }
5376
5377    #[test]
5378    #[cfg(feature = "comments")]
5379    fn comment_capture_falls_back_to_owned_slice_when_borrow_unavailable() {
5380        let mut scanner = Scanner::new(SlicingOnlyInput::new("# sliced\n", true));
5381        scanner.input.lookahead(2);
5382        assert_eq!(scanner.input.peek_nth(1), ' ');
5383
5384        let token = scanner.scan_comment_token().unwrap();
5385
5386        assert!(matches!(token.1, TokenType::Comment(ref comment)
5387            if matches!(comment.text, Cow::Owned(ref text) if text == " sliced")));
5388    }
5389
5390    #[test]
5391    #[cfg(feature = "comments")]
5392    fn comment_capture_errors_when_offsets_have_no_slice() {
5393        let mut scanner = Scanner::new(SlicingOnlyInput::new("# broken\n", false));
5394
5395        let error = scanner.scan_comment_token().unwrap_err();
5396
5397        assert_eq!(error.kind(), &ErrorKind::InputOffsetsWithoutSlice);
5398    }
5399
5400    #[test]
5401    fn disabled_comments_do_not_require_input_slicing() {
5402        let options = ignoring_comments_options();
5403        let scanner = Scanner::with_options(
5404            SlicingOnlyInput::new("# ignored\nkey: value\n", false),
5405            options,
5406        );
5407
5408        let tokens = scanner
5409            .collect::<Result<Vec<_>, _>>()
5410            .expect("ignored comments should not capture their payload");
5411
5412        #[cfg(feature = "comments")]
5413        assert!(tokens
5414            .iter()
5415            .all(|token| !matches!(token.1, TokenType::Comment(_))));
5416        assert!(tokens.iter().any(|token| matches!(
5417            token.1,
5418            TokenType::Scalar(ScalarStyle::Plain, ref text) if text == "value"
5419        )));
5420    }
5421
5422    #[test]
5423    fn queued_token_roundtrips_public_token_variants() {
5424        let span = Span::new(Marker::new(0, 1, 0), Marker::new(7, 1, 7));
5425        let tokens = [
5426            Token(span, TokenType::StreamStart),
5427            Token(span, TokenType::StreamEnd),
5428            Token(span, TokenType::VersionDirective(1, 2)),
5429            Token(
5430                span,
5431                TokenType::TagDirective(Cow::Borrowed("!app!"), Cow::Borrowed("tag:app.example,")),
5432            ),
5433            Token(span, TokenType::DocumentStart),
5434            Token(span, TokenType::DocumentEnd),
5435            Token(span, TokenType::BlockSequenceStart),
5436            Token(span, TokenType::BlockMappingStart),
5437            Token(span, TokenType::BlockEnd),
5438            Token(span, TokenType::FlowSequenceStart),
5439            Token(span, TokenType::FlowSequenceEnd),
5440            Token(span, TokenType::FlowMappingStart),
5441            Token(span, TokenType::FlowMappingEnd),
5442            Token(span, TokenType::BlockEntry),
5443            Token(span, TokenType::FlowEntry),
5444            Token(span, TokenType::Key),
5445            Token(span, TokenType::Value),
5446            Token(span, TokenType::Alias(Cow::Borrowed("alias"))),
5447            Token(span, TokenType::Anchor(Cow::Borrowed("anchor"))),
5448            Token(
5449                span,
5450                TokenType::Tag(Cow::Borrowed("!"), Cow::Borrowed("tag")),
5451            ),
5452            Token(
5453                span,
5454                TokenType::Scalar(ScalarStyle::Literal, Cow::Borrowed("scalar")),
5455            ),
5456            #[cfg(feature = "comments")]
5457            Token(
5458                span,
5459                TokenType::Comment(
5460                    Comment::new(Cow::Borrowed(" comment")).with_placement(Placement::Right),
5461                ),
5462            ),
5463            Token(
5464                span,
5465                TokenType::ReservedDirective(
5466                    "reserved".to_owned(),
5467                    vec!["one".to_owned(), "two".to_owned()],
5468                ),
5469            ),
5470        ];
5471
5472        for token in tokens {
5473            let queued: QueuedToken = token.clone().into();
5474
5475            assert_eq!(queued.into_public(), token);
5476        }
5477    }
5478
5479    #[test]
5480    fn comment_skipping_path_consumes_comment_without_tokenizing_it() {
5481        let mut scanner = Scanner::new(StrInput::new("# skipped\nnext: value\n"));
5482
5483        scanner.skip_yaml_whitespace().unwrap();
5484
5485        assert!(scanner.tokens.is_empty());
5486        assert_eq!(scanner.mark.line(), 2);
5487        assert_eq!(scanner.mark.col(), 0);
5488    }
5489
5490    #[test]
5491    #[cfg(feature = "comments")]
5492    fn yaml_whitespace_can_stop_after_queued_comment() {
5493        let mut scanner = Scanner::new(StrInput::new(" # queued\n# later\n"));
5494
5495        assert!(scanner.skip_yaml_whitespace().unwrap());
5496
5497        assert_eq!(scanner.tokens.len(), 1);
5498        assert!(matches!(
5499            scanner.tokens.front().unwrap().1,
5500            QueuedTokenType::Comment(ref comment) if comment.text == " queued"
5501        ));
5502        assert_eq!(scanner.mark.line(), 1);
5503        assert_eq!(scanner.mark.col(), 9);
5504    }
5505
5506    #[test]
5507    #[cfg(feature = "comments")]
5508    fn token_skip_can_stop_after_queued_comment() {
5509        let mut scanner = Scanner::new(StrInput::new("# first\n# second\n"));
5510
5511        assert!(scanner.skip_to_next_token().unwrap().queued_comment);
5512
5513        assert_eq!(scanner.tokens.len(), 1);
5514        assert!(matches!(
5515            scanner.tokens.front().unwrap().1,
5516            QueuedTokenType::Comment(ref comment) if comment.text == " first"
5517        ));
5518        assert_eq!(scanner.mark.line(), 2);
5519        assert_eq!(scanner.mark.col(), 0);
5520    }
5521
5522    #[test]
5523    fn token_skip_stops_after_one_ignored_comment_without_queuing_it() {
5524        let options = ignoring_comments_options();
5525        let mut scanner =
5526            Scanner::with_options(StrInput::new("# first\n# second\nvalue\n"), options);
5527
5528        let outcome = scanner.skip_to_next_token().unwrap();
5529
5530        assert!(outcome.saw_comment);
5531        #[cfg(feature = "comments")]
5532        assert!(!outcome.queued_comment);
5533        assert!(scanner.tokens.is_empty());
5534        assert_eq!((scanner.mark.line(), scanner.mark.col()), (2, 0));
5535        assert_eq!(scanner.input.look_ch(), '#');
5536    }
5537
5538    #[test]
5539    fn yaml_whitespace_stops_after_one_separated_ignored_comment() {
5540        let options = ignoring_comments_options();
5541        let mut scanner =
5542            Scanner::with_options(StrInput::new(" # first\n# second\nvalue\n"), options);
5543
5544        assert!(scanner.skip_yaml_whitespace().unwrap());
5545
5546        assert!(scanner.tokens.is_empty());
5547        assert_eq!((scanner.mark.line(), scanner.mark.col()), (1, 8));
5548        assert_eq!(scanner.input.look_ch(), '\n');
5549    }
5550
5551    #[test]
5552    fn scanner_skips_consecutive_leading_ignored_comments_before_next_token() {
5553        let options = ignoring_comments_options();
5554        let mut scanner =
5555            Scanner::with_options(StrInput::new("# first\n# second\nvalue\n"), options);
5556
5557        assert!(matches!(
5558            scanner.next_token().unwrap().unwrap().1,
5559            TokenType::StreamStart
5560        ));
5561        assert!(matches!(
5562            scanner.next_token().unwrap().unwrap().1,
5563            TokenType::Scalar(ScalarStyle::Plain, ref value) if value == "value"
5564        ));
5565        #[cfg(feature = "comments")]
5566        assert!(scanner
5567            .tokens
5568            .iter()
5569            .all(|QueuedToken(_, token)| !matches!(token, QueuedTokenType::Comment(_))));
5570    }
5571
5572    #[test]
5573    #[cfg(feature = "comments")]
5574    fn scanner_emits_first_leading_comment_before_scanning_next_comment() {
5575        let mut scanner = Scanner::new(StrInput::new("# first\n# second\nkey: value\n"));
5576
5577        assert!(matches!(
5578            scanner.next_token().unwrap().unwrap().1,
5579            TokenType::StreamStart
5580        ));
5581        assert!(matches!(
5582            scanner.next_token().unwrap().unwrap().1,
5583            TokenType::Comment(ref comment) if comment.text == " first"
5584        ));
5585        assert!(scanner.tokens.is_empty());
5586        assert!(matches!(
5587            scanner.next_token().unwrap().unwrap().1,
5588            TokenType::Comment(ref comment) if comment.text == " second"
5589        ));
5590    }
5591
5592    #[test]
5593    #[cfg(feature = "comments")]
5594    fn scanner_emits_quoted_scalar_comment_before_scanning_following_value() {
5595        let mut scanner = Scanner::new(StrInput::new("\"key\" # quoted\n: value\n"));
5596
5597        assert!(matches!(
5598            scanner.next_token().unwrap().unwrap().1,
5599            TokenType::StreamStart
5600        ));
5601        assert!(matches!(
5602            scanner.next_token().unwrap().unwrap().1,
5603            TokenType::Scalar(ScalarStyle::DoubleQuoted, ref value) if value == "key"
5604        ));
5605        assert!(matches!(
5606            scanner.next_token().unwrap().unwrap().1,
5607            TokenType::Comment(ref comment) if comment.text == " quoted"
5608        ));
5609    }
5610
5611    #[test]
5612    #[cfg(feature = "comments")]
5613    fn flow_scalar_comment_disables_adjacent_value_lookahead() {
5614        let mut scanner = Scanner::new(StrInput::new("\"key\"\n# quoted\n: value\n"));
5615
5616        scanner.fetch_flow_scalar(false).unwrap();
5617
5618        assert_eq!(scanner.adjacent_value_allowed_at, usize::MAX);
5619        assert!(matches!(
5620            scanner.tokens.front().unwrap().1,
5621            QueuedTokenType::Scalar(ScalarStyle::DoubleQuoted, ref value) if value == "key"
5622        ));
5623        assert!(scanner.tokens.iter().any(|QueuedToken(_, token)| matches!(
5624            token,
5625            QueuedTokenType::Comment(comment) if comment.text == " quoted"
5626        )));
5627    }
5628
5629    #[test]
5630    fn ignored_flow_scalar_comment_still_disables_adjacent_value_lookahead() {
5631        let options = ignoring_comments_options();
5632        let mut scanner =
5633            Scanner::with_options(StrInput::new("\"key\"\n# ignored\n: value\n"), options);
5634
5635        scanner.fetch_flow_scalar(false).unwrap();
5636
5637        assert_eq!(scanner.adjacent_value_allowed_at, usize::MAX);
5638        assert_eq!(scanner.tokens.len(), 1);
5639        assert!(matches!(
5640            scanner.tokens.front().unwrap().1,
5641            QueuedTokenType::Scalar(ScalarStyle::DoubleQuoted, ref value) if value == "key"
5642        ));
5643    }
5644
5645    #[test]
5646    #[cfg(feature = "comments")]
5647    fn deferred_error_waits_for_all_comment_tokens() {
5648        let mut scanner = Scanner::new(StrInput::new("# first\n# second\n@\n"));
5649
5650        assert!(matches!(
5651            scanner.next_token().unwrap().unwrap().1,
5652            TokenType::StreamStart
5653        ));
5654        assert!(matches!(
5655            scanner.next_token().unwrap().unwrap().1,
5656            TokenType::Comment(ref comment) if comment.text == " first"
5657        ));
5658        assert!(matches!(
5659            scanner.next_token().unwrap().unwrap().1,
5660            TokenType::Comment(ref comment) if comment.text == " second"
5661        ));
5662
5663        let error = scanner.next_token().unwrap_err();
5664
5665        assert_eq!(
5666            error.kind(),
5667            &ErrorKind::UnexpectedCharacter { character: '@' }
5668        );
5669    }
5670
5671    /// Ensure anchors scanned from `StrInput` are returned as `Cow::Borrowed`.
5672    #[test]
5673    fn anchor_name_is_borrowed_for_str_input() {
5674        let mut scanner = Scanner::new(StrInput::new("&anch\n"));
5675
5676        loop {
5677            let tok = scanner
5678                .next_token()
5679                .expect("valid YAML must scan without errors")
5680                .expect("scanner must eventually produce a token");
5681            if let TokenType::Anchor(name) = tok.1 {
5682                assert!(matches!(name, Cow::Borrowed("anch")));
5683                break;
5684            }
5685        }
5686    }
5687
5688    #[test]
5689    fn anchor_name_rejects_non_printable_control_chars() {
5690        let mut scanner = Scanner::new(StrInput::new("&foo\u{0001}\n"));
5691
5692        scanner.next_token().unwrap();
5693        assert_eq!(
5694            scanner.next_token().unwrap_err().kind(),
5695            &ErrorKind::UnexpectedCharacter {
5696                character: '\u{0001}'
5697            }
5698        );
5699    }
5700
5701    #[test]
5702    fn alias_name_rejects_non_printable_control_chars() {
5703        let mut scanner = Scanner::new(StrInput::new("*foo\u{0001}\n"));
5704
5705        scanner.next_token().unwrap();
5706        assert_eq!(
5707            scanner.next_token().unwrap_err().kind(),
5708            &ErrorKind::UnexpectedCharacter {
5709                character: '\u{0001}'
5710            }
5711        );
5712    }
5713
5714    #[test]
5715    fn alias_name_is_borrowed_for_str_input() {
5716        let mut scanner = Scanner::new(StrInput::new("*anch\n"));
5717
5718        loop {
5719            let tok = scanner
5720                .next_token()
5721                .expect("valid YAML must scan without errors")
5722                .expect("scanner must eventually produce a token");
5723            if let TokenType::Alias(name) = tok.1 {
5724                assert!(matches!(name, Cow::Borrowed("anch")));
5725                break;
5726            }
5727        }
5728    }
5729
5730    #[test]
5731    fn alias_name_scans_colon_as_part_of_name() {
5732        let mut scanner = Scanner::new(StrInput::new("*foo: bar\n"));
5733
5734        loop {
5735            let tok = scanner
5736                .next_token()
5737                .expect("scanner must not fail before alias token")
5738                .expect("scanner must eventually emit an alias token");
5739
5740            if let TokenType::Alias(name) = tok.1 {
5741                assert_eq!(name.as_ref(), "foo:");
5742                break;
5743            }
5744        }
5745    }
5746
5747    #[test]
5748    fn anchor_name_scans_colon_as_part_of_name() {
5749        let mut scanner = Scanner::new(StrInput::new("&foo: bar\n"));
5750
5751        loop {
5752            let tok = scanner
5753                .next_token()
5754                .expect("scanner must not fail before anchor token")
5755                .expect("scanner must eventually emit an anchor token");
5756
5757            if let TokenType::Anchor(name) = tok.1 {
5758                assert_eq!(name.as_ref(), "foo:");
5759                break;
5760            }
5761        }
5762    }
5763
5764    /// Ensure `%TAG` directive handle and prefix are borrowed when they are verbatim (no escapes).
5765    #[test]
5766    fn tag_directive_parts_are_borrowed_for_str_input() {
5767        let mut scanner = Scanner::new(StrInput::new("%TAG !e! tag:example.com,2000:app/\n"));
5768
5769        loop {
5770            let tok = scanner
5771                .next_token()
5772                .expect("valid YAML must scan without errors")
5773                .expect("scanner must eventually produce a token");
5774            if let TokenType::TagDirective(handle, prefix) = tok.1 {
5775                assert!(matches!(handle, Cow::Borrowed("!e!")));
5776                assert!(matches!(prefix, Cow::Borrowed("tag:example.com,2000:app/")));
5777                break;
5778            }
5779        }
5780    }
5781
5782    #[test]
5783    fn tag_directive_parts_are_owned_for_buffered_input() {
5784        let mut scanner = Scanner::new(BufferedInput::new(
5785            "%TAG !e! tag:example.com,2000:app/\n".chars(),
5786        ));
5787
5788        loop {
5789            let tok = scanner
5790                .next_token()
5791                .expect("valid YAML must scan without errors")
5792                .expect("scanner must eventually produce a token");
5793            if let TokenType::TagDirective(handle, prefix) = tok.1 {
5794                assert!(matches!(handle, Cow::Owned(_)));
5795                assert_eq!(&*handle, "!e!");
5796                assert!(matches!(prefix, Cow::Owned(_)));
5797                assert_eq!(&*prefix, "tag:example.com,2000:app/");
5798                break;
5799            }
5800        }
5801    }
5802
5803    #[test]
5804    fn buffered_tag_directive_decodes_prefix_escape() {
5805        let mut scanner = Scanner::new(BufferedInput::new(
5806            "%TAG !e! %74ag:example.com,2000:app/\n".chars(),
5807        ));
5808
5809        loop {
5810            let tok = scanner
5811                .next_token()
5812                .expect("valid YAML must scan without errors")
5813                .expect("scanner must eventually produce a token");
5814            if let TokenType::TagDirective(handle, prefix) = tok.1 {
5815                assert_eq!(&*handle, "!e!");
5816                assert!(matches!(prefix, Cow::Owned(_)));
5817                assert_eq!(&*prefix, "tag:example.com,2000:app/");
5818                break;
5819            }
5820        }
5821    }
5822
5823    #[test]
5824    fn local_tag_combines_handle_text_with_escaped_suffix() {
5825        let mut scanner = Scanner::new(StrInput::new("!foo%20bar value\n"));
5826
5827        loop {
5828            let tok = scanner
5829                .next_token()
5830                .expect("valid YAML must scan without errors")
5831                .expect("scanner must eventually produce a token");
5832            if let TokenType::Tag(handle, suffix) = tok.1 {
5833                assert!(matches!(handle, Cow::Borrowed("!")));
5834                assert!(matches!(suffix, Cow::Owned(_)));
5835                assert_eq!(&*suffix, "foo bar");
5836                break;
5837            }
5838        }
5839    }
5840
5841    #[test]
5842    fn secondary_tag_requires_suffix_in_borrowed_and_buffered_paths() {
5843        assert_eq!(
5844            first_scanner_error_kind("!! value\n"),
5845            ErrorKind::MissingTagUri
5846        );
5847        assert_eq!(
5848            first_buffered_scanner_error_kind("!! value\n"),
5849            ErrorKind::MissingTagUri
5850        );
5851    }
5852
5853    #[test]
5854    fn plain_scalar_is_borrowed_when_whitespace_free_for_str_input() {
5855        let mut scanner = Scanner::new(StrInput::new("foo\n"));
5856
5857        loop {
5858            let tok = scanner
5859                .next_token()
5860                .expect("valid YAML must scan without errors")
5861                .expect("scanner must eventually produce a token");
5862            if let TokenType::Scalar(_, value) = tok.1 {
5863                assert!(matches!(value, Cow::Borrowed("foo")));
5864                break;
5865            }
5866        }
5867    }
5868
5869    #[test]
5870    fn plain_scalar_is_borrowed_when_whitespace_present_for_str_input() {
5871        let mut scanner = Scanner::new(StrInput::new("foo bar\n"));
5872
5873        loop {
5874            let tok = scanner
5875                .next_token()
5876                .expect("valid YAML must scan without errors")
5877                .expect("scanner must eventually produce a token");
5878            if let TokenType::Scalar(_, value) = tok.1 {
5879                assert!(matches!(value, Cow::Borrowed("foo bar")));
5880                break;
5881            }
5882        }
5883    }
5884
5885    #[test]
5886    fn single_quoted_scalar_is_borrowed_when_verbatim_for_str_input() {
5887        let mut scanner = Scanner::new(StrInput::new("'foo bar'\n"));
5888
5889        loop {
5890            let tok = scanner
5891                .next_token()
5892                .expect("valid YAML must scan without errors")
5893                .expect("scanner must eventually produce a token");
5894            if let TokenType::Scalar(_, value) = tok.1 {
5895                assert!(matches!(value, Cow::Borrowed("foo bar")));
5896                break;
5897            }
5898        }
5899    }
5900
5901    #[test]
5902    fn single_quoted_scalar_is_owned_when_quote_is_escaped_for_str_input() {
5903        let mut scanner = Scanner::new(StrInput::new("'foo''bar'\n"));
5904
5905        loop {
5906            let tok = scanner
5907                .next_token()
5908                .expect("valid YAML must scan without errors")
5909                .expect("scanner must eventually produce a token");
5910            if let TokenType::Scalar(_, value) = tok.1 {
5911                assert!(matches!(value, Cow::Owned(_)));
5912                assert_eq!(&*value, "foo'bar");
5913                break;
5914            }
5915        }
5916    }
5917
5918    #[test]
5919    fn double_quoted_scalar_is_borrowed_when_verbatim_for_str_input() {
5920        let mut scanner = Scanner::new(StrInput::new("\"foo bar\"\n"));
5921
5922        loop {
5923            let tok = scanner
5924                .next_token()
5925                .expect("valid YAML must scan without errors")
5926                .expect("scanner must eventually produce a token");
5927            if let TokenType::Scalar(_, value) = tok.1 {
5928                assert!(matches!(value, Cow::Borrowed("foo bar")));
5929                break;
5930            }
5931        }
5932    }
5933
5934    #[test]
5935    fn double_quoted_scalar_is_owned_when_escape_sequence_present_for_str_input() {
5936        let mut scanner = Scanner::new(StrInput::new("\"foo\\nbar\"\n"));
5937
5938        loop {
5939            let tok = scanner
5940                .next_token()
5941                .expect("valid YAML must scan without errors")
5942                .expect("scanner must eventually produce a token");
5943            if let TokenType::Scalar(_, value) = tok.1 {
5944                assert!(matches!(value, Cow::Owned(_)));
5945                assert_eq!(&*value, "foo\nbar");
5946                break;
5947            }
5948        }
5949    }
5950
5951    #[test]
5952    fn plain_key_is_borrowed_for_str_input() {
5953        // Keys are just scalars in a key position; they should also be borrowed.
5954        let mut scanner = Scanner::new(StrInput::new("mykey: value\n"));
5955
5956        let mut found_key = false;
5957        let mut key_value: Option<Cow<'_, str>> = None;
5958
5959        loop {
5960            let tok = scanner
5961                .next_token()
5962                .expect("valid YAML must scan without errors");
5963            let Some(tok) = tok else { break };
5964
5965            if matches!(tok.1, TokenType::Key) {
5966                found_key = true;
5967            } else if found_key {
5968                if let TokenType::Scalar(_, value) = tok.1 {
5969                    key_value = Some(value);
5970                    break;
5971                }
5972            }
5973        }
5974
5975        assert!(found_key, "expected to find a Key token");
5976        let key_value = key_value.expect("expected to find a scalar after Key token");
5977        assert!(
5978            matches!(key_value, Cow::Borrowed("mykey")),
5979            "key should be borrowed, got: {key_value:?}"
5980        );
5981    }
5982
5983    #[test]
5984    fn quoted_key_is_borrowed_when_verbatim_for_str_input() {
5985        let mut scanner = Scanner::new(StrInput::new("\"mykey\": value\n"));
5986
5987        let mut found_key = false;
5988        let mut key_value: Option<Cow<'_, str>> = None;
5989
5990        loop {
5991            let tok = scanner
5992                .next_token()
5993                .expect("valid YAML must scan without errors");
5994            let Some(tok) = tok else { break };
5995
5996            if matches!(tok.1, TokenType::Key) {
5997                found_key = true;
5998            } else if found_key {
5999                if let TokenType::Scalar(_, value) = tok.1 {
6000                    key_value = Some(value);
6001                    break;
6002                }
6003            }
6004        }
6005
6006        assert!(found_key, "expected to find a Key token");
6007        let key_value = key_value.expect("expected to find a scalar after Key token");
6008        assert!(
6009            matches!(key_value, Cow::Borrowed("mykey")),
6010            "quoted key should be borrowed when verbatim, got: {key_value:?}"
6011        );
6012    }
6013
6014    #[test]
6015    fn tag_handle_and_suffix_are_borrowed_for_str_input() {
6016        // Test a tag like !!str which should have handle="!!" and suffix="str"
6017        let mut scanner = Scanner::new(StrInput::new("!!str foo\n"));
6018
6019        loop {
6020            let tok = scanner
6021                .next_token()
6022                .expect("valid YAML must scan without errors")
6023                .expect("scanner must eventually produce a token");
6024            if let TokenType::Tag(handle, suffix) = tok.1 {
6025                assert!(
6026                    matches!(handle, Cow::Borrowed("!!")),
6027                    "tag handle should be borrowed, got: {handle:?}"
6028                );
6029                assert!(
6030                    matches!(suffix, Cow::Borrowed("str")),
6031                    "tag suffix should be borrowed, got: {suffix:?}"
6032                );
6033                break;
6034            }
6035        }
6036    }
6037
6038    #[test]
6039    fn local_tag_suffix_is_borrowed_for_str_input() {
6040        // Test a local tag like !mytag which should have handle="!" and suffix="mytag"
6041        let mut scanner = Scanner::new(StrInput::new("!mytag foo\n"));
6042
6043        loop {
6044            let tok = scanner
6045                .next_token()
6046                .expect("valid YAML must scan without errors")
6047                .expect("scanner must eventually produce a token");
6048            if let TokenType::Tag(handle, suffix) = tok.1 {
6049                assert!(
6050                    matches!(handle, Cow::Borrowed("!")),
6051                    "local tag handle should be '!', got: {handle:?}"
6052                );
6053                assert!(
6054                    matches!(suffix, Cow::Borrowed("mytag")),
6055                    "local tag suffix should be borrowed, got: {suffix:?}"
6056                );
6057                break;
6058            }
6059        }
6060    }
6061
6062    #[test]
6063    fn local_tag_suffix_with_punctuation_is_borrowed_for_str_input() {
6064        let mut scanner = Scanner::new(StrInput::new("!mytag/part foo\n"));
6065
6066        loop {
6067            let tok = scanner
6068                .next_token()
6069                .expect("valid YAML must scan without errors")
6070                .expect("scanner must eventually produce a token");
6071            if let TokenType::Tag(handle, suffix) = tok.1 {
6072                assert!(matches!(handle, Cow::Borrowed("!")));
6073                assert!(matches!(suffix, Cow::Borrowed("mytag/part")));
6074                break;
6075            }
6076        }
6077    }
6078
6079    #[test]
6080    fn tag_with_uri_escape_is_owned_for_str_input() {
6081        // Test a tag with URI escape like !my%20tag - suffix must be owned due to decoding
6082        let mut scanner = Scanner::new(StrInput::new("!!my%20tag foo\n"));
6083
6084        loop {
6085            let tok = scanner
6086                .next_token()
6087                .expect("valid YAML must scan without errors")
6088                .expect("scanner must eventually produce a token");
6089            if let TokenType::Tag(handle, suffix) = tok.1 {
6090                assert!(
6091                    matches!(handle, Cow::Borrowed("!!")),
6092                    "tag handle should still be borrowed, got: {handle:?}"
6093                );
6094                assert!(
6095                    matches!(suffix, Cow::Owned(_)),
6096                    "tag suffix with URI escape should be owned, got: {suffix:?}"
6097                );
6098                assert_eq!(&*suffix, "my tag");
6099                break;
6100            }
6101        }
6102    }
6103
6104    #[test]
6105    fn flow_scalar_buffer_tracks_pending_whitespace() {
6106        let mut borrowed = super::FlowScalarBuf::new_borrowed(2);
6107
6108        borrowed.note_pending_ws(5, 8);
6109        borrowed.commit_pending_ws();
6110        assert!(matches!(
6111            borrowed,
6112            super::FlowScalarBuf::Borrowed {
6113                end: 8,
6114                pending_ws_start: None,
6115                pending_ws_end: 8,
6116                ..
6117            }
6118        ));
6119
6120        borrowed.note_pending_ws(9, 11);
6121        borrowed.discard_pending_ws();
6122        assert!(matches!(
6123            borrowed,
6124            super::FlowScalarBuf::Borrowed {
6125                end: 8,
6126                pending_ws_start: None,
6127                pending_ws_end: 8,
6128                ..
6129            }
6130        ));
6131        assert!(borrowed.as_owned_mut().is_none());
6132
6133        let mut owned = super::FlowScalarBuf::new_owned();
6134        owned.as_owned_mut().unwrap().push_str("owned");
6135        assert!(matches!(owned, super::FlowScalarBuf::Owned(ref s) if s == "owned"));
6136    }
6137
6138    fn first_scanner_error_kind(input: &str) -> ErrorKind {
6139        first_scanner_error(input).kind().clone()
6140    }
6141
6142    fn first_buffered_scanner_error_kind(input: &str) -> ErrorKind {
6143        let mut scanner = Scanner::new(BufferedInput::new(input.chars()));
6144        loop {
6145            match scanner.next_token() {
6146                Ok(Some(_)) => {}
6147                Ok(None) => panic!("expected scanner error"),
6148                Err(error) => return error.kind().clone(),
6149            }
6150        }
6151    }
6152
6153    fn first_scanner_error(input: &str) -> ScanError {
6154        let mut scanner = Scanner::new(StrInput::new(input));
6155        loop {
6156            match scanner.next_token() {
6157                Ok(Some(_)) => {}
6158                Ok(None) => panic!("expected scanner error"),
6159                Err(error) => return error,
6160            }
6161        }
6162    }
6163
6164    fn first_scalar_value(input: &str) -> String {
6165        let mut scanner = Scanner::new(StrInput::new(input));
6166        loop {
6167            match scanner.next_token().expect("scanner should not error") {
6168                Some(Token(_, TokenType::Scalar(_, value))) => return value.into_owned(),
6169                Some(_) => {}
6170                None => panic!("expected scalar token"),
6171            }
6172        }
6173    }
6174
6175    fn first_buffered_scalar_value(input: &str) -> String {
6176        let mut scanner = Scanner::new(BufferedInput::new(input.chars()));
6177        loop {
6178            match scanner.next_token().expect("scanner should not error") {
6179                Some(Token(_, TokenType::Scalar(_, value))) => return value.into_owned(),
6180                Some(_) => {}
6181                None => panic!("expected scalar token"),
6182            }
6183        }
6184    }
6185
6186    #[test]
6187    fn iterator_next_emits_error_and_then_stays_empty() {
6188        let mut scanner = Scanner::new(StrInput::new("\"unterminated"));
6189
6190        let error = scanner
6191            .by_ref()
6192            .find_map(Result::err)
6193            .expect("scanner should emit the error");
6194        assert_eq!(error.kind(), &ErrorKind::UnclosedQuotedScalar);
6195        assert!(scanner.next().is_none());
6196    }
6197
6198    #[test]
6199    fn next_token_returns_none_after_stream_end() {
6200        let mut scanner = Scanner::new(StrInput::new(""));
6201
6202        while let Some(token) = scanner.next_token().unwrap() {
6203            if matches!(token.1, TokenType::StreamEnd) {
6204                break;
6205            }
6206        }
6207
6208        assert!(scanner.stream_started());
6209        assert!(scanner.stream_ended());
6210        assert!(scanner.next_token().unwrap().is_none());
6211    }
6212
6213    #[test]
6214    fn directive_name_must_be_present() {
6215        assert_eq!(
6216            first_scanner_error_kind("%\n"),
6217            ErrorKind::MissingDirectiveName
6218        );
6219    }
6220
6221    #[test]
6222    fn yaml_directive_requires_dot_between_version_numbers() {
6223        assert_eq!(
6224            first_scanner_error_kind("%YAML 1\n"),
6225            ErrorKind::MissingYamlVersionSeparator
6226        );
6227    }
6228
6229    #[test]
6230    fn yaml_directive_requires_major_version_number() {
6231        assert_eq!(
6232            first_scanner_error_kind("%YAML .2\n"),
6233            ErrorKind::MissingYamlVersion
6234        );
6235    }
6236
6237    #[test]
6238    fn yaml_directive_rejects_extremely_long_version_number() {
6239        assert_eq!(
6240            first_scanner_error_kind("%YAML 1234567890.2\n"),
6241            ErrorKind::YamlVersionTooLong
6242        );
6243    }
6244
6245    #[test]
6246    fn tag_directive_handle_must_end_with_bang() {
6247        assert_eq!(
6248            first_scanner_error_kind("%TAG !bad tag:example.com,2024:\n"),
6249            ErrorKind::ExpectedTagDirectiveBang
6250        );
6251    }
6252
6253    #[test]
6254    fn tag_directive_handle_must_start_with_bang() {
6255        assert_eq!(
6256            first_scanner_error_kind("%TAG bad! tag:example.com,2024:\n"),
6257            ErrorKind::ExpectedTagBang
6258        );
6259        assert_eq!(
6260            first_buffered_scanner_error_kind("%TAG bad! tag:example.com,2024:\n"),
6261            ErrorKind::ExpectedTagBang
6262        );
6263    }
6264
6265    #[test]
6266    fn tag_directive_prefix_must_start_with_tag_character() {
6267        assert_eq!(
6268            first_scanner_error_kind("%TAG !e! `bad\n"),
6269            ErrorKind::InvalidGlobalTagCharacter
6270        );
6271    }
6272
6273    #[test]
6274    fn tag_directive_prefix_must_end_before_invalid_content() {
6275        assert_eq!(
6276            first_scanner_error_kind("%TAG !e! tag:example.com^suffix\n"),
6277            ErrorKind::InvalidTagDirectiveTerminator
6278        );
6279    }
6280
6281    #[test]
6282    fn tag_directive_prefix_with_uri_escape_is_owned_and_decoded() {
6283        let mut scanner =
6284            Scanner::new(StrInput::new("%TAG !e! tag:example.com,2024:some%20app/\n"));
6285
6286        loop {
6287            let token = scanner
6288                .next_token()
6289                .expect("valid directive should scan")
6290                .expect("scanner must produce a directive token");
6291            if let TokenType::TagDirective(handle, prefix) = token.1 {
6292                assert!(matches!(handle, Cow::Borrowed("!e!")));
6293                assert!(matches!(prefix, Cow::Owned(_)));
6294                assert_eq!(&*prefix, "tag:example.com,2024:some app/");
6295                break;
6296            }
6297        }
6298    }
6299
6300    #[test]
6301    fn bare_bang_tag_scans_as_non_specific_tag() {
6302        let mut scanner = Scanner::new(StrInput::new("! foo\n"));
6303
6304        loop {
6305            let token = scanner
6306                .next_token()
6307                .expect("valid tag should scan")
6308                .expect("scanner must produce a tag token");
6309            if let TokenType::Tag(handle, suffix) = token.1 {
6310                assert_eq!(&*handle, "");
6311                assert_eq!(&*suffix, "!");
6312                break;
6313            }
6314        }
6315    }
6316
6317    #[test]
6318    fn tag_requires_separation_after_suffix() {
6319        assert_eq!(
6320            first_scanner_error_kind("!foo,bar\n"),
6321            ErrorKind::InvalidTagTerminator
6322        );
6323    }
6324
6325    #[test]
6326    fn verbatim_tag_requires_uri() {
6327        assert_eq!(
6328            first_scanner_error_kind("!<> foo\n"),
6329            ErrorKind::MissingTagUri
6330        );
6331    }
6332
6333    #[test]
6334    fn verbatim_tag_requires_closing_angle_bracket() {
6335        assert_eq!(
6336            first_scanner_error_kind("!<tag:yaml.org,2002:str foo\n"),
6337            ErrorKind::UnclosedVerbatimTag
6338        );
6339    }
6340
6341    #[test]
6342    fn tag_uri_escape_requires_hex_digits() {
6343        assert_eq!(
6344            first_scanner_error_kind("!!bad%zz foo\n"),
6345            ErrorKind::InvalidTagEscape
6346        );
6347    }
6348
6349    #[test]
6350    fn tag_uri_escape_rejects_bad_leading_utf8_byte() {
6351        assert_eq!(
6352            first_scanner_error_kind("!!bad%80 foo\n"),
6353            ErrorKind::InvalidTagUtf8LeadingByte
6354        );
6355    }
6356
6357    #[test]
6358    fn tag_uri_escape_rejects_bad_trailing_utf8_byte() {
6359        assert_eq!(
6360            first_scanner_error_kind("!!bad%C2%41 foo\n"),
6361            ErrorKind::InvalidTagUtf8TrailingByte
6362        );
6363    }
6364
6365    #[test]
6366    fn tag_uri_escape_rejects_invalid_utf8_codepoint() {
6367        assert_eq!(
6368            first_scanner_error_kind("!!bad%F4%90%80%80 foo\n"),
6369            ErrorKind::InvalidTagUtf8
6370        );
6371    }
6372
6373    #[test]
6374    fn anchors_and_aliases_require_names() {
6375        assert_eq!(
6376            first_scanner_error_kind("& \n"),
6377            ErrorKind::MissingAnchorOrAliasName
6378        );
6379        assert_eq!(
6380            first_scanner_error_kind("* \n"),
6381            ErrorKind::MissingAnchorOrAliasName
6382        );
6383    }
6384
6385    #[test]
6386    fn document_end_marker_rejects_trailing_content() {
6387        assert_eq!(
6388            first_scanner_error_kind("... trailing\n"),
6389            ErrorKind::InvalidDocumentEnd
6390        );
6391    }
6392
6393    #[test]
6394    fn reserved_indicators_are_rejected_outside_directives() {
6395        let error = first_scanner_error(" @\n");
6396
6397        assert_eq!(
6398            error.kind(),
6399            &ErrorKind::UnexpectedCharacter { character: '@' }
6400        );
6401    }
6402
6403    #[test]
6404    fn flow_block_entry_indicator_is_rejected() {
6405        assert_eq!(
6406            first_scanner_error_kind("[- ]\n"),
6407            ErrorKind::BlockEntryInFlowCollection
6408        );
6409    }
6410
6411    #[test]
6412    fn block_entry_after_tabbed_separator_reports_specific_error() {
6413        assert_eq!(
6414            first_scanner_error_kind("-\t- value\n"),
6415            ErrorKind::InvalidBlockEntryWhitespace
6416        );
6417    }
6418
6419    #[test]
6420    fn document_indicator_reports_unclosed_flow_collection() {
6421        let error = first_scanner_error("[\n---\n");
6422
6423        assert_eq!(
6424            error.kind(),
6425            &ErrorKind::UnclosedFlowCollection { open: '[' }
6426        );
6427    }
6428
6429    #[test]
6430    fn block_scalar_header_rejects_trailing_content() {
6431        assert_eq!(
6432            first_scanner_error_kind("|+ trailing\n"),
6433            ErrorKind::InvalidBlockScalarHeader
6434        );
6435    }
6436
6437    #[test]
6438    fn block_scalar_rejects_zero_indent_indicator() {
6439        assert_eq!(
6440            first_scanner_error_kind("|0\n"),
6441            ErrorKind::ZeroBlockScalarIndent
6442        );
6443        assert_eq!(
6444            first_scanner_error_kind("|+0\n"),
6445            ErrorKind::ZeroBlockScalarIndent
6446        );
6447    }
6448
6449    #[test]
6450    fn empty_block_scalar_at_eof_honors_chomping() {
6451        assert_eq!(first_scalar_value("|\n"), "");
6452        assert_eq!(first_scalar_value("|-\n"), "");
6453        assert_eq!(first_scalar_value("|+\n"), "");
6454        assert_eq!(first_scalar_value("|+\n\n"), "\n");
6455        assert_eq!(first_scalar_value("|+\n   "), "\n");
6456    }
6457
6458    #[test]
6459    fn buffered_block_scalar_reads_content_past_lookahead_window() {
6460        assert_eq!(
6461            first_buffered_scalar_value("|\n  abcdefghijklmnopqrstuvwxyz\n"),
6462            "abcdefghijklmnopqrstuvwxyz\n"
6463        );
6464    }
6465
6466    #[test]
6467    fn explicit_indent_block_scalar_can_end_at_document_marker() {
6468        assert_eq!(first_scalar_value("|1\n...\n"), "");
6469    }
6470
6471    #[test]
6472    fn root_explicit_indent_block_scalar_rejects_underindented_content() {
6473        assert_eq!(
6474            first_scanner_error_kind("|2\nx\n"),
6475            ErrorKind::InvalidBlockScalarIndent
6476        );
6477    }
6478
6479    #[test]
6480    fn quoted_scalar_rejects_document_indicator_at_line_start() {
6481        assert_eq!(
6482            first_scanner_error_kind("\"one\n---\ntwo\"\n"),
6483            ErrorKind::DocumentIndicatorInQuotedScalar
6484        );
6485    }
6486
6487    #[test]
6488    fn strict_quoted_scalar_rejects_tab_indentation_after_line_break() {
6489        let error = Scanner::with_options(
6490            StrInput::new("a: \"one\n\tbad\"\n"),
6491            crate::options! { strict_indentation: true },
6492        )
6493        .find_map(Result::err)
6494        .expect("strict mode must reject a tab indenting a quoted continuation");
6495        assert_eq!(error.kind(), &ErrorKind::TabInIndentation);
6496    }
6497
6498    #[test]
6499    fn strict_quoted_scalar_rejects_underindented_continuation() {
6500        for input in ["a: \"one\nbad\"\n", "a:\n  b: 'one\n  bad'\n"] {
6501            let error = Scanner::with_options(
6502                StrInput::new(input),
6503                crate::options! { strict_indentation: true },
6504            )
6505            .find_map(Result::err)
6506            .expect("strict mode must reject underindented quoted continuations");
6507            assert_eq!(error.kind(), &ErrorKind::InvalidQuotedScalarIndent);
6508        }
6509    }
6510
6511    #[test]
6512    fn quoted_scalar_continuation_one_column_past_block_indent() {
6513        // s-flow-line-prefix(n): a continuation line needs only n spaces, where n is one more
6514        // than the indentation of the enclosing block mapping or sequence.
6515        for input in [
6516            "a: \"one\n two\"\n",
6517            "a: 'one\n two'\n",
6518            "a:\n  b: \"one\n   two\"\n",
6519            "- a: \"one\n   two\"\n",
6520            "? k\n: \"one\n two\"\n",
6521        ] {
6522            let mut scanner = Scanner::new(StrInput::new(input));
6523            loop {
6524                match scanner.next_token() {
6525                    Ok(Some(_)) => {}
6526                    Ok(None) => break,
6527                    Err(error) => panic!("{input:?}: {error}"),
6528                }
6529            }
6530        }
6531    }
6532
6533    #[test]
6534    fn quoted_scalar_trailing_content_error_names_quote_style() {
6535        assert_eq!(
6536            first_scanner_error_kind("'foo' trailing\n"),
6537            ErrorKind::InvalidTrailingSingleQuotedScalar
6538        );
6539        assert_eq!(
6540            first_scanner_error_kind("\"foo\" trailing\n"),
6541            ErrorKind::InvalidTrailingDoubleQuotedScalar
6542        );
6543    }
6544
6545    #[test]
6546    fn quoted_scalar_escape_errors_cover_hex_and_surrogate_edges() {
6547        assert_eq!(
6548            first_scanner_error_kind("\"\\xG0\"\n"),
6549            ErrorKind::InvalidQuotedScalarHexEscape
6550        );
6551        assert_eq!(
6552            first_scanner_error_kind("\"\\uD800\\uGGGG\"\n"),
6553            ErrorKind::InvalidLowSurrogateHexEscape
6554        );
6555        assert_eq!(
6556            first_scanner_error_kind("\"\\uD800\\u0041\"\n"),
6557            ErrorKind::InvalidLowSurrogate
6558        );
6559        assert_eq!(
6560            first_scanner_error_kind("\"\\U00110000\"\n"),
6561            ErrorKind::InvalidUnicodeEscape
6562        );
6563    }
6564
6565    #[test]
6566    fn under_indented_flow_scalar_is_accepted() {
6567        let tokens: Vec<_> = Scanner::new(StrInput::new("a:\n  [\nfoo]\n"))
6568            .map(|result| result.expect("under-indented flow entry should scan").1)
6569            .collect();
6570        assert_eq!(
6571            tokens,
6572            [
6573                TokenType::StreamStart,
6574                TokenType::BlockMappingStart,
6575                TokenType::Key,
6576                TokenType::Scalar(ScalarStyle::Plain, "a".into()),
6577                TokenType::Value,
6578                TokenType::FlowSequenceStart,
6579                TokenType::Scalar(ScalarStyle::Plain, "foo".into()),
6580                TokenType::FlowSequenceEnd,
6581                TokenType::BlockEnd,
6582                TokenType::StreamEnd,
6583            ]
6584        );
6585    }
6586
6587    #[test]
6588    fn required_simple_key_requires_value_at_stream_end() {
6589        let error = first_scanner_error("a:\n&b\n- c\n");
6590
6591        assert_eq!(error.kind(), &ErrorKind::SimpleKeyExpected);
6592        assert_eq!(error.marker().index(), 3);
6593        assert_eq!(error.marker().line(), 2);
6594        assert_eq!(error.marker().col(), 0);
6595    }
6596
6597    #[test]
6598    fn first_simple_key_tracks_ordered_possible_candidates() {
6599        let deep = alloc::format!(
6600            "{}{}{{[é, z]: v}}{}\n",
6601            "[".repeat(240),
6602            "a, ".repeat(400),
6603            "]".repeat(240)
6604        );
6605        for source in [
6606            "",
6607            "a: b\nmissing",
6608            "a: b\nmissing\n# after\nnext: value\n",
6609            "{[a, {b: c}]: [d, e], []: f}\n",
6610            "[&a !tag [x, y], *a, {z: []}]\n",
6611            "key: {\n&anchor\nname: value}\n",
6612            "---\n{[a, b]: c} # end\n...\n# next\n---\nx: y\n",
6613            "a: b\n[unterminated",
6614            &deep,
6615        ] {
6616            for limit in [0, 4, 1024, usize::MAX] {
6617                #[cfg(feature = "comments")]
6618                let emission_modes = [false, true].as_slice();
6619                #[cfg(not(feature = "comments"))]
6620                let emission_modes = [false].as_slice();
6621                for &emit_comments in emission_modes {
6622                    let options = crate::options! { simple_key_max_lookahead: limit };
6623                    #[cfg(feature = "comments")]
6624                    let options = {
6625                        let mut options = options;
6626                        options.emit_comments = emit_comments;
6627                        options
6628                    };
6629                    let mut scanner = Scanner::with_options(StrInput::new(source), options);
6630                    loop {
6631                        let result = scanner.next();
6632                        assert_eq!(
6633                            scanner.first_simple_key,
6634                            scanner.simple_keys.iter().position(|key| key.possible),
6635                            "source: {source:?}, limit: {limit}, comments: {emit_comments}"
6636                        );
6637                        let mut previous = None;
6638                        for key in scanner.simple_keys.iter().filter(|key| key.possible) {
6639                            assert!(key.token_number >= scanner.tokens_parsed);
6640                            if let Some((index, token_number)) = previous {
6641                                assert!(key.mark.index() >= index);
6642                                assert!(key.token_number >= token_number);
6643                            }
6644                            previous = Some((key.mark.index(), key.token_number));
6645                        }
6646                        if result.is_none() {
6647                            break;
6648                        }
6649                    }
6650                }
6651            }
6652        }
6653    }
6654
6655    #[test]
6656    fn plain_scalar_rejects_dash_before_flow_indicator() {
6657        assert_eq!(
6658            first_scanner_error_kind("[-]\n"),
6659            ErrorKind::PlainScalarStartsWithDashFlowIndicator
6660        );
6661    }
6662
6663    #[test]
6664    fn explicit_key_rejects_tab_used_as_indentation() {
6665        assert_eq!(
6666            first_scanner_error_kind("?\n\tfoo\n"),
6667            ErrorKind::TabNotAllowed
6668        );
6669    }
6670
6671    #[test]
6672    fn flow_mapping_rejects_adjacent_collection_value_after_plain_key() {
6673        assert_eq!(
6674            first_scanner_error_kind("[a:[]]\n"),
6675            ErrorKind::FlowMappingValueAdjacentCollection
6676        );
6677    }
6678
6679    #[test]
6680    fn implicit_flow_mapping_colon_cannot_move_to_next_line() {
6681        assert_eq!(
6682            first_scanner_error_kind("[foo\n: bar]\n"),
6683            ErrorKind::InvalidColonPlacement
6684        );
6685    }
6686
6687    #[test]
6688    fn invalid_simple_key_token_positions_are_scan_errors() {
6689        for (tokens_parsed, token_number) in [(1, 0), (0, 1)] {
6690            let mut scanner = Scanner::new(StrInput::new(": value\n"));
6691            scanner.fetch_stream_start();
6692            scanner.tokens.clear();
6693            scanner.tokens_parsed = tokens_parsed;
6694
6695            let simple_key = scanner
6696                .simple_keys
6697                .last_mut()
6698                .expect("stream start should create a simple key slot");
6699            simple_key.possible = true;
6700            simple_key.token_number = token_number;
6701
6702            let error = scanner
6703                .fetch_value()
6704                .expect_err("invalid simple key position should be reported as a scan error");
6705            assert_eq!(error.kind(), &ErrorKind::InvalidSimpleKey);
6706            assert_eq!(error.marker(), &Marker::new(0, 1, 0));
6707        }
6708    }
6709
6710    #[test]
6711    fn issue14_alias_scanner_consumes_colon_as_name_character() {
6712        let mut scanner = Scanner::new(StrInput::new("*foo: bar\n"));
6713
6714        assert!(matches!(
6715            scanner.next_token().unwrap().unwrap().1,
6716            TokenType::StreamStart
6717        ));
6718
6719        let token = scanner.next_token().unwrap().unwrap();
6720
6721        assert!(
6722            matches!(token.1, TokenType::Alias(ref name) if name.as_ref() == "foo:"),
6723            "expected `*foo: bar` to start with Alias(\"foo:\"), got {token:?}"
6724        );
6725    }
6726
6727    #[test]
6728    fn issue14_anchor_scanner_consumes_colon_as_name_character() {
6729        let mut scanner = Scanner::new(StrInput::new("&foo: bar\n"));
6730
6731        assert!(matches!(
6732            scanner.next_token().unwrap().unwrap().1,
6733            TokenType::StreamStart
6734        ));
6735
6736        let token = scanner.next_token().unwrap().unwrap();
6737
6738        assert!(
6739            matches!(token.1, TokenType::Anchor(ref name) if name.as_ref() == "foo:"),
6740            "expected `&foo: bar` to start with Anchor(\"foo:\"), got {token:?}"
6741        );
6742    }
6743}