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