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