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 start_mark = self.mark;
3624        #[cfg(feature = "extended_details")]
3625        let header_start = start_mark;
3626        #[cfg(feature = "extended_details")]
3627        let mut digit_first = false;
3628        let mut chomping = Chomping::Clip;
3629        let mut increment: u8 = 0;
3630        let mut indent: usize = 0;
3631        let mut trailing_blank: bool;
3632        let mut leading_blank: bool = false;
3633
3634        let mut string = String::new();
3635        let mut leading_break = false;
3636        let mut trailing_breaks = 0;
3637        let mut chomping_break = false;
3638
3639        // skip '|' or '>'
3640        self.skip_non_blank();
3641        self.unroll_non_block_indents();
3642
3643        if self.input.look_ch() == '+' || self.input.peek() == '-' {
3644            if self.input.peek() == '+' {
3645                chomping = Chomping::Keep;
3646            } else {
3647                chomping = Chomping::Strip;
3648            }
3649            self.skip_non_blank();
3650            self.input.lookahead(1);
3651            if self.input.next_is_digit() {
3652                if self.input.peek() == '0' {
3653                    return Err(ScanError::from_kind(
3654                        start_mark,
3655                        ErrorKind::ZeroBlockScalarIndent,
3656                    ));
3657                }
3658                increment = (self.input.peek() as u8) - b'0';
3659                self.skip_non_blank();
3660            }
3661        } else if self.input.next_is_digit() {
3662            if self.input.peek() == '0' {
3663                return Err(ScanError::from_kind(
3664                    start_mark,
3665                    ErrorKind::ZeroBlockScalarIndent,
3666                ));
3667            }
3668
3669            increment = (self.input.peek() as u8) - b'0';
3670            self.skip_non_blank();
3671            self.input.lookahead(1);
3672            if self.input.peek() == '+' || self.input.peek() == '-' {
3673                #[cfg(feature = "extended_details")]
3674                {
3675                    digit_first = true;
3676                }
3677                if self.input.peek() == '+' {
3678                    chomping = Chomping::Keep;
3679                } else {
3680                    chomping = Chomping::Strip;
3681                }
3682                self.skip_non_blank();
3683            }
3684        }
3685
3686        self.skip_ws_to_eol(SkipTabs::Yes)?;
3687
3688        // Check if we are at the end of the line.
3689        self.input.lookahead(1);
3690        self.ensure_current_char_is_printable()?;
3691        if !self.input.next_is_breakz() {
3692            return Err(ScanError::from_kind(
3693                start_mark,
3694                ErrorKind::InvalidBlockScalarHeader,
3695            ));
3696        }
3697
3698        if self.input.next_is_break() {
3699            self.input.lookahead(2);
3700            self.skip_break();
3701            chomping_break = true;
3702        }
3703
3704        self.ensure_current_char_is_printable()?;
3705
3706        if self.input.look_ch() == '\t' {
3707            return Err(ScanError::from_kind(
3708                start_mark,
3709                ErrorKind::TabAtBlockScalarStart,
3710            ));
3711        }
3712
3713        if increment > 0 {
3714            indent = if self.indent >= 0 {
3715                (self.indent + isize::from(increment)) as usize
3716            } else {
3717                usize::from(increment)
3718            }
3719        }
3720
3721        // Scan the leading line breaks and determine the indentation level if needed.
3722        if indent == 0 {
3723            self.skip_block_scalar_first_line_indent(&mut indent, &mut trailing_breaks);
3724        } else {
3725            self.skip_block_scalar_indent(indent, &mut trailing_breaks);
3726        }
3727
3728        // Only a floor raised from zero ends an unindented root scalar. Indentation
3729        // inferred from leading blank lines must still be validated below.
3730        let indent_floor_applied = self.options.block_scalar_indent_at_least_one && indent == 0;
3731        if indent_floor_applied {
3732            indent = 1;
3733        }
3734
3735        // Without a header line break there are no content lines from which to infer
3736        // indentation. The scanner's cursor is still on the header (possibly after a
3737        // comment), so its column must not become the reported content indentation.
3738        #[cfg(feature = "extended_details")]
3739        let syntax = {
3740            let content_indent = if increment == 0 && self.mark.line() == header_start.line() {
3741                (self.indent + 1).max(0) as usize
3742            } else {
3743                indent
3744            };
3745            BlockScalarSyntax::new(
3746                chomping,
3747                (increment > 0).then_some(increment),
3748                content_indent,
3749            )
3750            .map(|mut syntax| {
3751                syntax.digit_first = digit_first;
3752                syntax
3753            })
3754        };
3755        self.ensure_current_char_is_printable()?;
3756
3757        // We have an end-of-stream with no content, e.g.:
3758        // ```yaml
3759        // - |+
3760        // ```
3761        if self.input.next_is_z() {
3762            let contents = match chomping {
3763                // We strip trailing line breaks. Nothing remains.
3764                Chomping::Strip => String::new(),
3765                // There was no newline after the chomping indicator.
3766                _ if self.mark.line == start_mark.line() => String::new(),
3767                // With no content lines, the header break is not scalar content.
3768                Chomping::Clip => String::new(),
3769                // Preserve the default synthetic break for an indented whitespace-only line
3770                // at EOF, unless the caller opted into libyaml's reading.
3771                Chomping::Keep if trailing_breaks == 0 && self.mark.col > 0 => {
3772                    if chomping_break && !self.options.block_scalar_eof_without_line_feed {
3773                        "\n".into()
3774                    } else {
3775                        String::new()
3776                    }
3777                }
3778                // Keep actual empty content lines, if any, but not the header break.
3779                Chomping::Keep => "\n".repeat(trailing_breaks),
3780            };
3781
3782            let style = if literal {
3783                ScalarStyle::literal()
3784            } else {
3785                ScalarStyle::folded()
3786            };
3787            #[cfg(feature = "extended_details")]
3788            let style = syntax.map_or(style, |syntax| style.with_block_syntax(syntax));
3789            return Ok(Token(
3790                Span::new(start_mark, self.mark),
3791                TokenType::Scalar {
3792                    style,
3793                    value: contents.into(),
3794                },
3795            ));
3796        }
3797
3798        if !indent_floor_applied && self.mark.col < indent && (self.mark.col as isize) > self.indent
3799        {
3800            if self.indent < 0 && self.mark.col == 0 {
3801                self.input.lookahead(4);
3802                if self.input.next_is_document_start()
3803                    || self.input.next_is_document_end()
3804                    || self.input.peek() == '#'
3805                {
3806                    // At the root level, an explicit indentation indicator can still yield an
3807                    // empty scalar when the next line is a document marker or comment.
3808                    // In this case, the scalar is terminated rather than under-indented.
3809                } else {
3810                    return Err(self.scan_error(ErrorKind::InvalidBlockScalarIndent));
3811                }
3812            } else {
3813                return Err(self.scan_error(ErrorKind::InvalidBlockScalarIndent));
3814            }
3815        }
3816
3817        let start_mark = self.mark;
3818        #[cfg(feature = "extended_details")]
3819        let syntax = syntax.and_then(|syntax| {
3820            let header_chars_before_span = start_mark.index() - header_start.index();
3821            let header_bytes_before_span = start_mark
3822                .byte_offset()
3823                .zip(header_start.byte_offset())
3824                .map_or(0, |(body, header)| body - header);
3825            syntax.with_header_offsets(header_chars_before_span, header_bytes_before_span)
3826        });
3827        while self.mark.col == indent && !self.input.next_is_z() {
3828            self.ensure_current_char_is_printable()?;
3829
3830            if indent == 0 {
3831                self.input.lookahead(4);
3832                if self.input.next_is_document_indicator() {
3833                    break;
3834                }
3835            }
3836
3837            // We are at the first content character of a content line.
3838            trailing_blank = self.input.next_is_blank();
3839            if !literal && leading_break && !leading_blank && !trailing_blank {
3840                string.extend(core::iter::repeat('\n').take(trailing_breaks));
3841                if trailing_breaks == 0 {
3842                    string.push(' ');
3843                }
3844            } else {
3845                if leading_break {
3846                    string.push('\n');
3847                }
3848                string.extend(core::iter::repeat('\n').take(trailing_breaks));
3849            }
3850
3851            leading_break = false;
3852            trailing_breaks = 0;
3853
3854            leading_blank = self.input.next_is_blank();
3855
3856            self.scan_block_scalar_content_line(&mut string);
3857
3858            // break on EOF
3859            self.input.lookahead(2);
3860            if self.input.next_is_z() {
3861                break;
3862            }
3863
3864            self.ensure_current_char_is_printable()?;
3865
3866            self.skip_break();
3867            leading_break = true;
3868
3869            // Eat the following indentation spaces and line breaks.
3870            self.skip_block_scalar_indent(indent, &mut trailing_breaks);
3871        }
3872
3873        self.ensure_current_char_is_printable()?;
3874
3875        // Chomp the tail.
3876        if chomping != Chomping::Strip {
3877            // If we had reached an eof but the last content line wasn't terminated by a line
3878            // break, check if the last line was indented at least as the rest of the scalar, then
3879            // we need to consider there is a newline, unless the caller opted into libyaml's
3880            // reading. When that line already ended with a break (`leading_break`), the
3881            // indentation-only remainder at EOF is not a line (it has no break, so it is no
3882            // `l-empty`) and adds nothing.
3883            if !leading_break
3884                && !self.options.block_scalar_eof_without_line_feed
3885                && self.input.next_is_z()
3886                && self.mark.col >= indent.max(1)
3887            {
3888                string.push('\n');
3889            }
3890            if leading_break {
3891                string.push('\n');
3892            }
3893        }
3894
3895        if chomping == Chomping::Keep {
3896            string.extend(core::iter::repeat('\n').take(trailing_breaks));
3897        }
3898
3899        if let Some(character) = find_non_printable(&string) {
3900            return Err(ScanError::from_kind(
3901                start_mark,
3902                ErrorKind::UnexpectedCharacter { character },
3903            ));
3904        }
3905
3906        let span = if string.trim().is_empty() {
3907            Span::new(start_mark, self.mark)
3908        } else {
3909            Span::new(start_mark, self.mark).with_indent(Some(indent))
3910        };
3911
3912        let style = if literal {
3913            ScalarStyle::literal()
3914        } else {
3915            ScalarStyle::folded()
3916        };
3917        #[cfg(feature = "extended_details")]
3918        let style = syntax.map_or(style, |syntax| style.with_block_syntax(syntax));
3919        Ok(Token(
3920            span,
3921            TokenType::Scalar {
3922                style,
3923                value: string.into(),
3924            },
3925        ))
3926    }
3927
3928    /// Retrieve the contents of the line, parsing it as a block scalar.
3929    ///
3930    /// The input appends content directly to `string`, leaving the line break or NUL unconsumed.
3931    /// Callers handle indentation and line breaks and refresh lookahead after this operation.
3932    fn scan_block_scalar_content_line(&mut self, string: &mut String) {
3933        let chars_consumed = self.input.fetch_block_scalar_line(string);
3934        self.mark.col += chars_consumed;
3935        self.mark.offsets.chars += chars_consumed;
3936        self.mark.offsets.bytes = self.input.byte_offset();
3937        // Preserve leading_whitespace, as the per-character skip_blank path did. Reading the
3938        // following line break resets it before the scanner uses it again.
3939    }
3940
3941    /// Skip the block scalar indentation and empty lines.
3942    fn skip_block_scalar_indent(&mut self, indent: usize, breaks: &mut usize) {
3943        loop {
3944            // Consume all spaces. Tabs cannot be used as indentation.
3945            if indent < self.input.bufmaxlen().saturating_sub(2) {
3946                self.input.lookahead(self.input.bufmaxlen());
3947                while self.mark.col < indent && self.input.peek() == ' ' {
3948                    self.skip_blank();
3949                }
3950            } else {
3951                loop {
3952                    self.input.lookahead(self.input.bufmaxlen());
3953                    while !self.input.buf_is_empty()
3954                        && self.mark.col < indent
3955                        && self.input.peek() == ' '
3956                    {
3957                        self.skip_blank();
3958                    }
3959                    // If we reached our indent, we can break. We must also break if we have
3960                    // reached content or EOF; that is, the buffer is not empty and the next
3961                    // character is not a space.
3962                    if self.mark.col == indent
3963                        || (!self.input.buf_is_empty() && self.input.peek() != ' ')
3964                    {
3965                        break;
3966                    }
3967                }
3968                self.input.lookahead(2);
3969            }
3970
3971            // If our current line is empty, skip over the break and continue looping.
3972            if self.input.next_is_break() {
3973                self.skip_break();
3974                *breaks += 1;
3975            } else {
3976                // Otherwise, we have a content line. Return control.
3977                break;
3978            }
3979        }
3980    }
3981
3982    /// Determine the indentation level for a block scalar from the first line of its contents.
3983    ///
3984    /// The function skips over whitespace-only lines and sets `indent` to the longest
3985    /// whitespace line that was encountered.
3986    fn skip_block_scalar_first_line_indent(&mut self, indent: &mut usize, breaks: &mut usize) {
3987        let mut max_indent = 0;
3988        loop {
3989            // Consume all spaces. Tabs cannot be used as indentation.
3990            while self.input.look_ch() == ' ' {
3991                self.skip_blank();
3992            }
3993
3994            if self.mark.col > max_indent {
3995                max_indent = self.mark.col;
3996            }
3997
3998            if self.input.next_is_break() {
3999                // If our current line is empty, skip over the break and continue looping.
4000                self.input.lookahead(2);
4001                self.skip_break();
4002                *breaks += 1;
4003            } else {
4004                // Otherwise, we have a content line. Return control.
4005                break;
4006            }
4007        }
4008
4009        // In case a YAML document looks like:
4010        // ```yaml
4011        // |
4012        // foo
4013        // bar
4014        // ```
4015        // We need to set the indent to 0 and not 1. In all other cases, the indent must be at
4016        // least 1. When in the above example, `self.indent` will be set to -1.
4017        *indent = max_indent.max((self.indent + 1) as usize);
4018    }
4019
4020    fn fetch_flow_scalar(&mut self, single: bool) -> ScanResult {
4021        self.save_simple_key();
4022        self.disallow_simple_key();
4023
4024        let token_index = self.tokens.len();
4025        let tok = self.scan_flow_scalar(single)?;
4026
4027        // From spec: To ensure JSON compatibility, if a key inside a flow mapping is JSON-like,
4028        // YAML allows the following value to be specified adjacent to the “:”.
4029        if self.skip_to_next_token()?.saw_comment {
4030            self.adjacent_value_allowed_at = usize::MAX;
4031        } else {
4032            self.adjacent_value_allowed_at = self.mark.index();
4033        }
4034
4035        self.insert_token(token_index, tok);
4036        Ok(())
4037    }
4038
4039    #[allow(clippy::too_many_lines)]
4040    fn scan_flow_scalar(&mut self, single: bool) -> Result<Token<'input>, ScanError> {
4041        let start_mark = self.mark;
4042
4043        // Output scalar contents.
4044        let mut buf = match self.input.byte_offset() {
4045            Some(off) => FlowScalarBuf::new_borrowed(off + self.input.peek().len_utf8()),
4046            None => FlowScalarBuf::new_owned(),
4047        };
4048
4049        /* Eat the left quote. */
4050        self.skip_non_blank();
4051
4052        loop {
4053            /* Check for a document indicator. */
4054            self.input.lookahead(4);
4055
4056            if self.mark.col == 0 && self.input.next_is_document_indicator() {
4057                return Err(ScanError::from_kind(
4058                    start_mark,
4059                    ErrorKind::DocumentIndicatorInQuotedScalar,
4060                ));
4061            }
4062
4063            if self.input.next_is_z() {
4064                return Err(ScanError::from_kind(
4065                    start_mark,
4066                    ErrorKind::UnclosedQuotedScalar,
4067                ));
4068            }
4069
4070            self.ensure_current_char_is_printable()?;
4071
4072            // Consume content before handling continuation-line indentation below.
4073            let mut leading_blanks = false;
4074            self.consume_flow_scalar_non_whitespace_chars(
4075                single,
4076                &mut buf,
4077                &mut leading_blanks,
4078                &start_mark,
4079            )?;
4080
4081            match self.input.look_ch() {
4082                '\'' if single && !leading_blanks => break,
4083                '"' if !single && !leading_blanks => break,
4084                _ => {}
4085            }
4086
4087            // --- Faster whitespace / line break handling (no temporary Strings) ---
4088            //
4089            // Instead of:
4090            //   - collecting blanks into `whitespaces` and then copying them
4091            //   - collecting breaks into `leading_break` / `trailing_breaks` and then copying
4092            //
4093            // We do:
4094            //   - append trailing blanks directly to `string`, remember where they started,
4095            //     and truncate them if a line break follows.
4096            //   - for line breaks: consume the first break into a scratch (discarded),
4097            //     append subsequent breaks directly to `string`.
4098            //
4099            // These flags replace temporary-string emptiness checks:
4100            //   has_leading_break  <=> !leading_break.is_empty()
4101            //   has_trailing_breaks <=> !trailing_breaks.is_empty()
4102            let mut trailing_ws_start: Option<usize> = None;
4103            let mut has_leading_break = false;
4104            let mut has_trailing_breaks = false;
4105
4106            // For the borrowed path: track the (byte) start of a pending whitespace run.
4107            let mut pending_ws_start: Option<usize> = None;
4108
4109            // Consume blank characters.
4110            while self.input.next_is_blank() || self.input.next_is_break() {
4111                if self.input.next_is_blank() {
4112                    // Consume a space or a tab character.
4113                    if leading_blanks {
4114                        // A continuation line's leading blanks are never content, so relaxed
4115                        // mode accepts tabs there, as libyaml, PyYAML and ruamel.yaml do.
4116                        if self.options.strict_indentation && self.input.peek() == '\t' {
4117                            let indent = if self.flow_level > 0 {
4118                                self.flow_block_indent() + 1
4119                            } else {
4120                                self.indent
4121                            };
4122                            if (self.mark.col as isize) < indent {
4123                                return Err(self.scan_error(ErrorKind::TabInIndentation));
4124                            }
4125                        }
4126                        self.skip_blank();
4127                    } else {
4128                        // Append to output immediately; if a break appears next, we'll truncate.
4129                        match buf {
4130                            FlowScalarBuf::Owned(ref mut string) => {
4131                                if trailing_ws_start.is_none() {
4132                                    trailing_ws_start = Some(string.len());
4133                                }
4134                                string.push(self.input.peek());
4135                            }
4136                            FlowScalarBuf::Borrowed { .. } => {
4137                                if pending_ws_start.is_none() {
4138                                    pending_ws_start = self.input.byte_offset();
4139                                }
4140                            }
4141                        }
4142                        self.skip_blank();
4143
4144                        if let (FlowScalarBuf::Borrowed { .. }, Some(ws_start), Some(ws_end)) =
4145                            (&mut buf, pending_ws_start, self.input.byte_offset())
4146                        {
4147                            buf.note_pending_ws(ws_start, ws_end);
4148                        }
4149                    }
4150                } else {
4151                    self.input.lookahead(2);
4152
4153                    // Check if it is a first line break.
4154                    if leading_blanks {
4155                        // Second+ line break in a run: preserve it.
4156                        match buf {
4157                            FlowScalarBuf::Owned(ref mut string) => self.read_break(string),
4158                            FlowScalarBuf::Borrowed { .. } => {
4159                                self.promote_flow_scalar_buf_to_owned(&start_mark, &mut buf)?;
4160                                let Some(string) = buf.as_owned_mut() else {
4161                                    unreachable!()
4162                                };
4163                                self.read_break(string);
4164                            }
4165                        }
4166                        has_trailing_breaks = true;
4167                    } else {
4168                        // First break: drop any trailing blanks we appended, then consume the break.
4169                        if let Some(pos) = trailing_ws_start.take() {
4170                            if let FlowScalarBuf::Owned(ref mut string) = buf {
4171                                string.truncate(pos);
4172                            }
4173                        }
4174
4175                        if pending_ws_start.take().is_some() {
4176                            // Trailing blanks before a break are discarded => transformation.
4177                            if matches!(buf, FlowScalarBuf::Borrowed { .. }) {
4178                                self.promote_flow_scalar_buf_to_owned(&start_mark, &mut buf)?;
4179                            }
4180                            buf.discard_pending_ws();
4181                        } else {
4182                            buf.commit_pending_ws();
4183                        }
4184
4185                        self.skip_break();
4186
4187                        has_leading_break = true;
4188                        leading_blanks = true;
4189                    }
4190                }
4191
4192                self.input.lookahead(1);
4193            }
4194
4195            // In strict mode, continuations and closing quotes after a folded or escaped line break
4196            // must be indented past the enclosing block (s-flow-line-prefix(n), YAML 1.2.2 [69]),
4197            // ignoring the temporary one-column indent after `:` / `-`: `foo: "a\n b"` is valid.
4198            if leading_blanks
4199                && self.options.strict_indentation
4200                && (self.mark.col as isize) <= self.flow_block_indent()
4201            {
4202                let kind = if has_leading_break && self.flow_level == 0 {
4203                    ErrorKind::InvalidQuotedScalarIndent
4204                } else {
4205                    ErrorKind::InvalidIndentation
4206                };
4207                return Err(self.scan_error(kind));
4208            }
4209
4210            // Join the whitespace or fold line breaks.
4211            if leading_blanks {
4212                // Folding rule:
4213                //   if there was no leading break, preserve the pending whitespace already emitted
4214                //   if there was a leading break but no trailing breaks, fold to one space
4215                //   otherwise, preserve the trailing breaks already emitted
4216                if has_leading_break && !has_trailing_breaks {
4217                    match buf {
4218                        FlowScalarBuf::Owned(ref mut string) => string.push(' '),
4219                        FlowScalarBuf::Borrowed { .. } => {
4220                            self.promote_flow_scalar_buf_to_owned(&start_mark, &mut buf)?;
4221                            let Some(string) = buf.as_owned_mut() else {
4222                                unreachable!()
4223                            };
4224                            string.push(' ');
4225                        }
4226                    }
4227                }
4228            }
4229            // else: trailing blanks are already appended to `string`
4230        } // loop
4231
4232        // Eat the right quote.
4233        self.skip_non_blank();
4234        let end_mark = self.mark;
4235
4236        // Ensure there is no invalid trailing content.
4237        self.skip_ws_to_eol(SkipTabs::Yes)?;
4238        self.ensure_current_char_is_printable()?;
4239        match self.input.peek() {
4240            // These can be encountered in flow sequences or mappings.
4241            ',' | '}' | ']' if self.flow_level > 0 => {}
4242            // An end-of-line / end-of-stream is fine. No trailing content.
4243            c if is_breakz(c) => {}
4244            // ':' can be encountered if our scalar is a key.
4245            // Outside of flow contexts, keys cannot span multiple lines
4246            ':' if self.flow_level == 0 && start_mark.line == self.mark.line => {}
4247            // Inside a flow context, this is allowed.
4248            ':' if self.flow_level > 0 => {}
4249            _ => {
4250                let kind = if single {
4251                    ErrorKind::InvalidTrailingSingleQuotedScalar
4252                } else {
4253                    ErrorKind::InvalidTrailingDoubleQuotedScalar
4254                };
4255                return Err(self.scan_error(kind));
4256            }
4257        }
4258
4259        let style = if single {
4260            ScalarStyle::SingleQuoted
4261        } else {
4262            ScalarStyle::DoubleQuoted
4263        };
4264
4265        let contents = match buf {
4266            FlowScalarBuf::Owned(string) => Cow::Owned(string),
4267            FlowScalarBuf::Borrowed {
4268                start,
4269                mut end,
4270                pending_ws_start,
4271                pending_ws_end,
4272            } => {
4273                // If we ended after a whitespace run, it is part of the output (no break followed).
4274                if pending_ws_start.is_some() {
4275                    end = pending_ws_end;
4276                }
4277                if let Some(slice) = self.try_borrow_slice(start, end) {
4278                    Cow::Borrowed(slice)
4279                } else {
4280                    let slice = self.input.slice_bytes(start, end).ok_or_else(|| {
4281                        ScanError::from_kind(start_mark, ErrorKind::InputOffsetsWithoutSlice)
4282                    })?;
4283                    Cow::Owned(slice.to_owned())
4284                }
4285            }
4286        };
4287
4288        Ok(Token(
4289            Span::new(start_mark, end_mark),
4290            TokenType::Scalar {
4291                style,
4292                value: contents,
4293            },
4294        ))
4295    }
4296
4297    /// Consume a printable run without per-character buffer and marker updates.
4298    fn consume_flow_scalar_chunk(&mut self, single: bool, buf: &mut FlowScalarBuf) -> bool {
4299        let (chunk, consumed) = self.input.take_quoted_scalar_chunk(single);
4300        if consumed == 0 {
4301            return false;
4302        }
4303
4304        match buf {
4305            FlowScalarBuf::Owned(string) => string.push_str(chunk),
4306            FlowScalarBuf::Borrowed { .. } => buf.commit_pending_ws(),
4307        }
4308
4309        // The input already consumed the run and counted its Unicode scalar values.
4310        self.mark.offsets.chars += consumed;
4311        self.mark.col += consumed;
4312        self.mark.offsets.bytes = self.input.byte_offset();
4313        self.leading_whitespace = false;
4314        if let (Some(new_end), FlowScalarBuf::Borrowed { end, .. }) = (self.mark.offsets.bytes, buf)
4315        {
4316            *end = new_end;
4317        }
4318        true
4319    }
4320
4321    /// Consume successive non-whitespace characters from a flow scalar.
4322    ///
4323    /// This function resolves escape sequences and stops upon encountering a whitespace, the end
4324    /// of the stream or the closing character for the scalar (`'` for single quoted scalars, `"`
4325    /// for double quoted scalars).
4326    ///
4327    /// # Errors
4328    /// Return an error if an invalid escape sequence is found.
4329    fn consume_flow_scalar_non_whitespace_chars(
4330        &mut self,
4331        single: bool,
4332        buf: &mut FlowScalarBuf,
4333        leading_blanks: &mut bool,
4334        start_mark: &Marker,
4335    ) -> Result<(), ScanError> {
4336        self.input.lookahead(2);
4337        loop {
4338            let character = self.input.peek();
4339            if is_blank_or_breakz(character) || !is_printable(character) {
4340                break;
4341            }
4342            match character {
4343                // Check for an escaped single quote.
4344                '\'' if self.input.peek_nth(1) == '\'' && single => {
4345                    if matches!(buf, FlowScalarBuf::Borrowed { .. }) {
4346                        buf.commit_pending_ws();
4347                        self.promote_flow_scalar_buf_to_owned(start_mark, buf)?;
4348                    }
4349                    let Some(string) = buf.as_owned_mut() else {
4350                        unreachable!()
4351                    };
4352                    string.push('\'');
4353                    self.skip_n_non_blank(2);
4354                }
4355                // Check for the right quote.
4356                '\'' if single => break,
4357                '"' if !single => break,
4358                // Check for an escaped line break.
4359                '\\' if !single && is_break(self.input.peek_nth(1)) => {
4360                    self.input.lookahead(3);
4361                    if matches!(buf, FlowScalarBuf::Borrowed { .. }) {
4362                        buf.commit_pending_ws();
4363                        self.promote_flow_scalar_buf_to_owned(start_mark, buf)?;
4364                    }
4365                    self.skip_non_blank();
4366                    self.skip_linebreak();
4367                    *leading_blanks = true;
4368                    break;
4369                }
4370                // Check for an escape sequence.
4371                '\\' if !single => {
4372                    if matches!(buf, FlowScalarBuf::Borrowed { .. }) {
4373                        buf.commit_pending_ws();
4374                        self.promote_flow_scalar_buf_to_owned(start_mark, buf)?;
4375                    }
4376                    let Some(string) = buf.as_owned_mut() else {
4377                        unreachable!()
4378                    };
4379                    string.push(self.resolve_flow_scalar_escape_sequence(start_mark)?);
4380                }
4381                c => {
4382                    if self.consume_flow_scalar_chunk(single, buf) {
4383                        self.input.lookahead(2);
4384                        continue;
4385                    }
4386                    match buf {
4387                        FlowScalarBuf::Owned(ref mut string) => {
4388                            string.push(c);
4389                        }
4390                        FlowScalarBuf::Borrowed { .. } => {
4391                            buf.commit_pending_ws();
4392                        }
4393                    }
4394                    self.skip_non_blank();
4395
4396                    if let Some(new_end) = self.input.byte_offset() {
4397                        if let FlowScalarBuf::Borrowed { end, .. } = buf {
4398                            *end = new_end;
4399                        }
4400                    }
4401                }
4402            }
4403            self.input.lookahead(2);
4404        }
4405        Ok(())
4406    }
4407
4408    /// Escape the sequence we encounter in a flow scalar.
4409    ///
4410    /// `self.input.peek()` must point to the `\` starting the escape sequence.
4411    ///
4412    /// # Errors
4413    /// Return an error if an invalid escape sequence is found.
4414    fn resolve_flow_scalar_escape_sequence(
4415        &mut self,
4416        start_mark: &Marker,
4417    ) -> Result<char, ScanError> {
4418        let mut code_length = 0usize;
4419        let mut ret = '\0';
4420
4421        match self.input.peek_nth(1) {
4422            '0' => ret = '\0',
4423            'a' => ret = '\x07',
4424            'b' => ret = '\x08',
4425            't' | '\t' => ret = '\t',
4426            'n' => ret = '\n',
4427            'v' => ret = '\x0b',
4428            'f' => ret = '\x0c',
4429            'r' => ret = '\x0d',
4430            'e' => ret = '\x1b',
4431            ' ' => ret = '\x20',
4432            '"' => ret = '"',
4433            '/' => ret = '/',
4434            '\\' => ret = '\\',
4435            // Unicode next line (#x85)
4436            'N' => ret = char::from_u32(0x85).unwrap(),
4437            // Unicode non-breaking space (#xA0)
4438            '_' => ret = char::from_u32(0xA0).unwrap(),
4439            // Unicode line separator (#x2028)
4440            'L' => ret = char::from_u32(0x2028).unwrap(),
4441            // Unicode paragraph separator (#x2029)
4442            'P' => ret = char::from_u32(0x2029).unwrap(),
4443            'x' => code_length = 2,
4444            'u' => code_length = 4,
4445            'U' => code_length = 8,
4446            _ => {
4447                return Err(ScanError::from_kind(
4448                    *start_mark,
4449                    ErrorKind::UnknownQuotedScalarEscape,
4450                ))
4451            }
4452        }
4453        self.skip_n_non_blank(2);
4454
4455        // Consume an arbitrary escape code.
4456        if code_length > 0 {
4457            self.input.lookahead(code_length);
4458            let mut value = 0u32;
4459            for i in 0..code_length {
4460                let c = self.input.peek_nth(i);
4461                if !is_hex(c) {
4462                    return Err(ScanError::from_kind(
4463                        *start_mark,
4464                        ErrorKind::InvalidQuotedScalarHexEscape,
4465                    ));
4466                }
4467                value = (value << 4) + as_hex(c);
4468            }
4469
4470            self.skip_n_non_blank(code_length);
4471
4472            // Handle JSON surrogate pairs: high surrogate followed by low surrogate
4473            if code_length == 4 && (0xD800..=0xDBFF).contains(&value) {
4474                self.input.lookahead(2);
4475                if self.input.peek() == '\\' && self.input.peek_nth(1) == 'u' {
4476                    self.skip_n_non_blank(2);
4477                    self.input.lookahead(4);
4478                    let mut low_value = 0u32;
4479                    for i in 0..4 {
4480                        let c = self.input.peek_nth(i);
4481                        if !is_hex(c) {
4482                            return Err(ScanError::from_kind(
4483                                *start_mark,
4484                                ErrorKind::InvalidLowSurrogateHexEscape,
4485                            ));
4486                        }
4487                        low_value = (low_value << 4) + as_hex(c);
4488                    }
4489                    if (0xDC00..=0xDFFF).contains(&low_value) {
4490                        value = 0x10000 + (((value - 0xD800) << 10) | (low_value - 0xDC00));
4491                        self.skip_n_non_blank(4);
4492                    } else {
4493                        return Err(ScanError::from_kind(
4494                            *start_mark,
4495                            ErrorKind::InvalidLowSurrogate,
4496                        ));
4497                    }
4498                } else {
4499                    return Err(ScanError::from_kind(
4500                        *start_mark,
4501                        ErrorKind::MissingLowSurrogate,
4502                    ));
4503                }
4504            } else if code_length == 4 && (0xDC00..=0xDFFF).contains(&value) {
4505                return Err(ScanError::from_kind(
4506                    *start_mark,
4507                    ErrorKind::UnpairedLowSurrogate,
4508                ));
4509            }
4510
4511            let Some(ch) = char::from_u32(value) else {
4512                return Err(ScanError::from_kind(
4513                    *start_mark,
4514                    ErrorKind::InvalidUnicodeEscape,
4515                ));
4516            };
4517            ret = ch;
4518        }
4519        Ok(ret)
4520    }
4521
4522    fn fetch_plain_scalar(&mut self) -> ScanResult {
4523        self.save_simple_key();
4524        self.disallow_simple_key();
4525
4526        let token_index = self.tokens.len();
4527        let tok = self.scan_plain_scalar()?;
4528
4529        self.insert_token(token_index, tok);
4530        Ok(())
4531    }
4532
4533    /// Scan for a plain scalar.
4534    ///
4535    /// Plain scalars are the most readable but restricted style. They may span multiple lines in
4536    /// some contexts.
4537    #[allow(clippy::too_many_lines)]
4538    fn scan_plain_scalar(&mut self) -> Result<Token<'input>, ScanError> {
4539        self.unroll_non_block_indents();
4540        let indent = self.indent + 1;
4541        let start_mark = self.mark;
4542
4543        let borrow_start = start_mark
4544            .byte_offset()
4545            .filter(|start| self.try_borrow_slice(*start, *start).is_some());
4546        let mut string = borrow_start.is_none().then(|| String::with_capacity(32));
4547        let mut has_content = false;
4548        self.buf_whitespaces.clear();
4549        self.buf_leading_break.clear();
4550        self.buf_trailing_breaks.clear();
4551        let mut end_mark = self.mark;
4552
4553        loop {
4554            self.input.lookahead(4);
4555            if (self.mark.col == 0 && self.input.next_is_document_indicator())
4556                || self.input.peek() == '#'
4557            {
4558                // BS4K: If a `#` starts a comment after some separation spaces following content
4559                // of a plain scalar in block context, and there is potential continuation on the
4560                // next line, this is invalid. We cannot decide yet if there will be continuation,
4561                // so record that a comment interrupted a plain scalar.
4562                if self.input.peek() == '#'
4563                    && has_content
4564                    && !self.buf_whitespaces.is_empty()
4565                    && self.flow_level == 0
4566                {
4567                    self.interrupted_plain_by_comment = Some(self.mark);
4568                }
4569                break;
4570            }
4571
4572            // The dash restriction applies only at the start of a plain scalar.
4573            if !has_content
4574                && self.flow_level > 0
4575                && self.input.peek() == '-'
4576                && is_flow(self.input.peek_nth(1))
4577            {
4578                return Err(self.scan_error(ErrorKind::PlainScalarStartsWithDashFlowIndicator));
4579            }
4580
4581            if !self.input.next_is_blank_or_breakz()
4582                && self.input.next_can_be_plain_scalar(self.flow_level > 0)
4583            {
4584                if self.leading_whitespace {
4585                    if has_content && string.is_none() {
4586                        let start = borrow_start.expect("borrowed scalar has a start offset");
4587                        let end = end_mark.byte_offset().ok_or_else(|| {
4588                            ScanError::from_kind(start_mark, ErrorKind::InputOffsetsWithoutSlice)
4589                        })?;
4590                        let prefix = self.try_borrow_slice(start, end).ok_or_else(|| {
4591                            ScanError::from_kind(start_mark, ErrorKind::InputOffsetsWithoutSlice)
4592                        })?;
4593                        string = Some(prefix.to_owned());
4594                    }
4595                    if self.buf_leading_break.is_empty() {
4596                        if let Some(output) = string.as_mut() {
4597                            output.push_str(&self.buf_leading_break);
4598                            output.push_str(&self.buf_trailing_breaks);
4599                        }
4600                        self.buf_trailing_breaks.clear();
4601                        self.buf_leading_break.clear();
4602                    } else {
4603                        if self.buf_trailing_breaks.is_empty() {
4604                            if let Some(output) = string.as_mut() {
4605                                output.push(' ');
4606                            }
4607                        } else {
4608                            if let Some(output) = string.as_mut() {
4609                                output.push_str(&self.buf_trailing_breaks);
4610                            }
4611                            self.buf_trailing_breaks.clear();
4612                        }
4613                        self.buf_leading_break.clear();
4614                    }
4615                    self.leading_whitespace = false;
4616                } else if !self.buf_whitespaces.is_empty() {
4617                    if let Some(output) = string.as_mut() {
4618                        output.push_str(&self.buf_whitespaces);
4619                    }
4620                    self.buf_whitespaces.clear();
4621                }
4622
4623                // We can unroll the first iteration of the loop.
4624                has_content = true;
4625                if let Some(output) = string.as_mut() {
4626                    output.push(self.input.peek());
4627                }
4628                self.skip_non_blank();
4629                if let Some(output) = string.as_mut() {
4630                    output.reserve(self.input.bufmaxlen());
4631                }
4632
4633                // Add content non-blank characters to the scalar.
4634                let mut end = false;
4635                while !end {
4636                    // Fill the buffer once and process all characters in the buffer until the next
4637                    // fetch. `next_can_be_plain_scalar` needs 2 lookahead characters, so keep one
4638                    // spare slot for normal inputs while still forcing progress for very small
4639                    // custom buffer lengths.
4640                    self.input.lookahead(self.input.bufmaxlen());
4641                    let chunk_len = self.input.bufmaxlen().saturating_sub(1).max(1);
4642                    let (stop, chars_consumed) = if let Some(output) = string.as_mut() {
4643                        self.input
4644                            .fetch_plain_scalar_chunk(output, chunk_len, self.flow_level > 0)
4645                    } else {
4646                        self.input
4647                            .skip_plain_scalar_chunk(chunk_len, self.flow_level > 0)
4648                    };
4649                    end = stop;
4650                    self.mark.offsets.chars += chars_consumed;
4651                    self.mark.col += chars_consumed;
4652                    self.mark.offsets.bytes = self.input.byte_offset();
4653                }
4654                end_mark = self.mark;
4655            }
4656
4657            // We may reach the end of a plain scalar if:
4658            //  - We reach eof
4659            //  - We reach ": "
4660            //  - We find a flow character in a flow context
4661            if !(self.input.next_is_blank() || self.input.next_is_break()) {
4662                break;
4663            }
4664
4665            // Process blank characters.
4666            self.input.lookahead(2);
4667            while self.input.next_is_blank_or_break() {
4668                if self.input.next_is_blank() {
4669                    if !self.leading_whitespace {
4670                        self.buf_whitespaces.push(self.input.peek());
4671                        self.skip_blank();
4672                    } else if (self.mark.col as isize) < indent && self.input.peek() == '\t' {
4673                        // Tabs in an indentation columns are allowed if and only if the line is
4674                        // empty. Skip to the end of the line.
4675                        self.skip_ws_to_eol(SkipTabs::Yes)?;
4676                        if !self.input.next_is_breakz() {
4677                            return Err(ScanError::from_kind(
4678                                start_mark,
4679                                ErrorKind::TabInPlainScalar,
4680                            ));
4681                        }
4682                    } else {
4683                        self.skip_blank();
4684                    }
4685                } else {
4686                    // Check if it is a first line break
4687                    if self.leading_whitespace {
4688                        self.skip_break();
4689                        self.buf_trailing_breaks.push('\n');
4690                    } else {
4691                        self.buf_whitespaces.clear();
4692                        self.skip_break();
4693                        self.buf_leading_break.push('\n');
4694                        self.leading_whitespace = true;
4695                    }
4696                }
4697                self.input.lookahead(2);
4698            }
4699
4700            // Stop before an under-indented continuation. In strict flow context the
4701            // next token fetch reports its indentation error without consuming the content.
4702            if (self.flow_level == 0 || self.options.strict_indentation)
4703                && (self.mark.col as isize) < indent
4704            {
4705                break;
4706            }
4707        }
4708
4709        if self.leading_whitespace {
4710            self.allow_simple_key();
4711        }
4712
4713        let borrowed_contents = if string.is_none() {
4714            let start = borrow_start.expect("borrowed scalar has a start offset");
4715            let end = end_mark.byte_offset().ok_or_else(|| {
4716                ScanError::from_kind(start_mark, ErrorKind::InputOffsetsWithoutSlice)
4717            })?;
4718            Some(self.try_borrow_slice(start, end).ok_or_else(|| {
4719                ScanError::from_kind(start_mark, ErrorKind::InputOffsetsWithoutSlice)
4720            })?)
4721        } else {
4722            None
4723        };
4724        let scalar_text = borrowed_contents.unwrap_or_else(|| {
4725            string
4726                .as_deref()
4727                .expect("owned plain scalar has an output buffer")
4728        });
4729        if let Some(character) = find_non_printable(scalar_text) {
4730            return Err(ScanError::from_kind(
4731                start_mark,
4732                ErrorKind::UnexpectedCharacter { character },
4733            ));
4734        }
4735        self.ensure_current_char_is_printable()?;
4736
4737        if has_content {
4738            let contents = if let Some(slice) = borrowed_contents {
4739                Cow::Borrowed(slice)
4740            } else {
4741                Cow::Owned(string.expect("owned plain scalar has an output buffer"))
4742            };
4743
4744            Ok(Token(
4745                Span::new(start_mark, end_mark),
4746                TokenType::Scalar {
4747                    style: ScalarStyle::plain(),
4748                    value: contents,
4749                },
4750            ))
4751        } else {
4752            // `fetch_plain_scalar` must absolutely consume at least one byte. Otherwise,
4753            // `fetch_next_token` will never stop calling it. An empty plain scalar may happen with
4754            // erroneous inputs such as "{...".
4755            Err(ScanError::from_kind(
4756                start_mark,
4757                ErrorKind::UnexpectedEndOfPlainScalar,
4758            ))
4759        }
4760    }
4761
4762    fn fetch_key(&mut self) -> ScanResult {
4763        let start_mark = self.mark;
4764        if self.flow_level == 0 {
4765            // Check if we are allowed to start a new key (not necessarily simple).
4766            if !self.simple_key_allowed {
4767                return Err(self.scan_error(ErrorKind::MappingKeyNotAllowed));
4768            }
4769            self.roll_indent(
4770                start_mark.col,
4771                None,
4772                TokenType::BlockMappingStart,
4773                start_mark,
4774            )?;
4775        } else {
4776            // The scanner, upon emitting a `Key`, will prepend a `MappingStart` event.
4777            self.set_current_flow_mapping_started(true);
4778        }
4779
4780        self.remove_simple_key()?;
4781
4782        if self.flow_level == 0 {
4783            self.allow_simple_key();
4784        } else {
4785            self.disallow_simple_key();
4786        }
4787
4788        self.skip_non_blank();
4789        let end_mark = self.mark;
4790        let token_index = self.tokens.len();
4791        self.explicit_key_tab_check_pending = false;
4792        // Block keys permit tab separation for scalar/flow nodes, but require spaces for
4793        // compact collections and indentation on subsequent lines. Keep that validation active
4794        // across comments, and across properties in strict mode. Flow collections use the
4795        // ordinary whitespace skipper.
4796        if self.flow_level == 0 {
4797            let stopped_after_comment = self.skip_yaml_whitespace()?;
4798            self.explicit_key_tab_check_pending = stopped_after_comment
4799                || (self.options.strict_indentation && matches!(self.input.peek(), '&' | '!'));
4800        }
4801        self.insert_token(
4802            token_index,
4803            Token(Span::new(start_mark, end_mark), TokenType::Key),
4804        );
4805        Ok(())
4806    }
4807
4808    /// Fetch a value in a mapping inside of a flow collection.
4809    ///
4810    /// This must not be called if [`self.flow_level`] is 0. This ensures the rules surrounding
4811    /// values in flow collections are respected prior to calling [`fetch_value`].
4812    ///
4813    /// [`self.flow_level`]: Self::flow_level
4814    /// [`fetch_value`]: Self::fetch_value
4815    fn fetch_flow_value(&mut self) -> ScanResult {
4816        let nc = self.input.peek_nth(1);
4817
4818        // If we encounter a ':' inside a flow collection and it is not immediately
4819        // followed by a blank or breakz:
4820        //   - We must check whether an adjacent value is allowed
4821        //     `["a":[]]` is valid. If the key is double-quoted, no need for a space. This
4822        //     is needed for JSON compatibility.
4823        //   - If not, we must ensure there is a space after the ':' and before its value.
4824        //     `[a: []]` is valid while `[a:[]]` isn't. `[a:b]` is treated as `["a:b"]`.
4825        //   - But if the value is empty (null), then it's okay.
4826        // The last line is for YAMLs like `[a:]`. The ':' is followed by a ']' (which is a
4827        // flow character), but the ']' is not the value. The value is an invisible empty
4828        // space which is represented as null ('~').
4829        if self.mark.index() != self.adjacent_value_allowed_at && (nc == '[' || nc == '{') {
4830            return Err(self.scan_error(ErrorKind::FlowMappingValueAdjacentCollection));
4831        }
4832
4833        self.fetch_value()
4834    }
4835
4836    /// Fetch a value from a mapping (after a `:`).
4837    fn fetch_value(&mut self) -> ScanResult {
4838        let sk = *self.simple_keys.last().unwrap();
4839        let start_mark = self.mark;
4840        let is_implicit_flow_mapping = self.current_flow_collection_is_sequence()
4841            && !self.current_flow_mapping_started()
4842            && !self.implicit_flow_mapping_states.is_empty();
4843        if is_implicit_flow_mapping {
4844            *self.implicit_flow_mapping_states.last_mut().unwrap() =
4845                ImplicitMappingState::Inside(self.flow_level);
4846        }
4847
4848        // Skip over ':'.
4849        self.skip_non_blank();
4850        // Tabs after ':' are separation whitespace. Queue any following comment after the
4851        // Value token; indentation on subsequent lines is checked by `skip_to_next_token`.
4852        let mut trailing_comment = None;
4853        let mut found_tabs = false;
4854        if matches!(self.input.look_ch(), ' ' | '\t') {
4855            let trailing_token_index = self.tokens.len();
4856            found_tabs = self.skip_ws_to_eol(SkipTabs::Yes)?.found_tabs();
4857            // Scanning to the end of this line can enqueue at most one comment.
4858            debug_assert!(self.tokens.len() <= trailing_token_index + 1);
4859            if self.tokens.len() > trailing_token_index {
4860                trailing_comment = self.tokens.pop_back();
4861            }
4862        }
4863
4864        if sk.possible {
4865            // Under-indented flow entries are a compatibility extension, but implicit keys
4866            // spanning lines are rejected by both PyYAML and ruamel.yaml. Keep that extension
4867            // limited to single-line keys; explicitly marked `?` keys may span lines.
4868            let block_indent = self.flow_block_indent();
4869            if self.flow_level > 0
4870                && sk.mark.line < start_mark.line
4871                && (sk.mark.col as isize) <= block_indent
4872            {
4873                return Err(ScanError::from_kind(
4874                    start_mark,
4875                    ErrorKind::InvalidColonPlacement,
4876                ));
4877            }
4878            let token_index = self.simple_key_token_index(&sk, start_mark)?;
4879            self.validate_flow_key_indentation(&sk, token_index, start_mark)?;
4880            // insert simple key
4881            let tok = Token(Span::empty(sk.mark), TokenType::Key);
4882            self.insert_token(token_index, tok);
4883            if is_implicit_flow_mapping {
4884                if sk.mark.line < start_mark.line {
4885                    return Err(ScanError::from_kind(
4886                        start_mark,
4887                        ErrorKind::InvalidColonPlacement,
4888                    ));
4889                }
4890                self.insert_token(
4891                    token_index,
4892                    Token(Span::empty(sk.mark), TokenType::FlowMappingStart),
4893                );
4894            }
4895
4896            // Add the BLOCK-MAPPING-START token if needed.
4897            self.roll_indent(
4898                sk.mark.col,
4899                Some(sk.token_number),
4900                TokenType::BlockMappingStart,
4901                sk.mark,
4902            )?;
4903            self.roll_one_col_indent();
4904
4905            self.clear_simple_key();
4906            self.disallow_simple_key();
4907        } else {
4908            if is_implicit_flow_mapping {
4909                self.tokens
4910                    .push_back(Token(Span::empty(start_mark), TokenType::FlowMappingStart).into());
4911            }
4912            // The ':' indicator follows a complex key.
4913            if self.flow_level == 0 {
4914                if !self.simple_key_allowed {
4915                    return Err(ScanError::from_kind(
4916                        start_mark,
4917                        ErrorKind::MappingValueNotAllowed,
4918                    ));
4919                }
4920
4921                self.roll_indent(
4922                    start_mark.col,
4923                    None,
4924                    TokenType::BlockMappingStart,
4925                    start_mark,
4926                )?;
4927            }
4928            self.roll_one_col_indent();
4929
4930            // An explicit value may start a compact block collection on this line only when
4931            // its indentation contains only spaces. Tabs still separate scalar and flow values.
4932            if self.flow_level == 0 && !found_tabs {
4933                self.allow_simple_key();
4934            } else {
4935                self.disallow_simple_key();
4936            }
4937        }
4938        self.tokens
4939            .push_back(Token(Span::empty(start_mark), TokenType::Value).into());
4940        if let Some(comment) = trailing_comment {
4941            self.tokens.push_back(comment);
4942        }
4943
4944        Ok(())
4945    }
4946
4947    /// Keep under-indented implicit flow keys on one line, including their properties.
4948    fn validate_flow_key_indentation(
4949        &self,
4950        key: &SimpleKey,
4951        token_index: usize,
4952        colon: Marker,
4953    ) -> ScanResult {
4954        if self.flow_level == 0 || key.mark.line == colon.line {
4955            return Ok(());
4956        }
4957
4958        let block_indent = self.flow_block_indent();
4959        // The saved key mark may point to an anchor or tag before the actual content.
4960        // Check each property and the first content token; comments do not indent a key.
4961        // Stop at the content token so a collection key's children are not checked here.
4962        let mut under_indented = [key.mark.col, colon.col]
4963            .iter()
4964            .any(|&col| (col as isize) <= block_indent);
4965        for token in self.tokens.iter().skip(token_index) {
4966            #[cfg(feature = "comments")]
4967            if matches!(token.1, QueuedTokenType::Comment(_)) {
4968                continue;
4969            }
4970            under_indented |= (token.0.start.col as isize) <= block_indent;
4971            if !matches!(
4972                token.1,
4973                QueuedTokenType::Anchor(_) | QueuedTokenType::Tag(..)
4974            ) {
4975                break;
4976            }
4977        }
4978        if under_indented {
4979            return Err(ScanError::from_kind(
4980                colon,
4981                ErrorKind::InvalidColonPlacement,
4982            ));
4983        }
4984        Ok(())
4985    }
4986
4987    /// Return the enclosing block indentation, excluding a temporary one-column indent.
4988    fn flow_block_indent(&self) -> isize {
4989        self.indents
4990            .last()
4991            .filter(|indent| !indent.needs_block_end)
4992            .map_or(self.indent, |indent| indent.indent)
4993    }
4994
4995    /// Add an indentation level to the stack with the given block token, if needed.
4996    ///
4997    /// An indentation level is added only if:
4998    ///   - We are not in a flow-style construct (which don't have indentation per-se).
4999    ///   - The current column is further indented than the last indent we have registered.
5000    fn roll_indent(
5001        &mut self,
5002        col: usize,
5003        number: Option<usize>,
5004        tok: TokenType<'input>,
5005        mark: Marker,
5006    ) -> ScanResult {
5007        if self.flow_level > 0 {
5008            return Ok(());
5009        }
5010
5011        // If the last indent was a non-block indent, remove it.
5012        // This means that we prepared an indent that we thought we wouldn't use, but realized just
5013        // now that it is a block indent.
5014        if self.indent <= col as isize {
5015            if let Some(indent) = self.indents.last() {
5016                if !indent.needs_block_end {
5017                    self.indent = indent.indent;
5018                    self.indents.pop();
5019                }
5020            }
5021        }
5022
5023        if self.indent < col as isize {
5024            if self.block_level >= self.options.block_nesting_limit {
5025                return Err(ScanError::from_kind(
5026                    mark,
5027                    ErrorKind::RecursionLimitExceeded,
5028                ));
5029            }
5030            self.indents.push(Indent {
5031                indent: self.indent,
5032                needs_block_end: true,
5033            });
5034            self.block_level += 1;
5035            self.indent = col as isize;
5036            let tokens_parsed = self.tokens_parsed;
5037            match number {
5038                Some(n) => self.insert_token(n - tokens_parsed, Token(Span::empty(mark), tok)),
5039                None => self.tokens.push_back(Token(Span::empty(mark), tok).into()),
5040            }
5041        }
5042        Ok(())
5043    }
5044
5045    /// Pop indentation levels from the stack as much as needed.
5046    ///
5047    /// Indentation levels are popped from the stack while they are further indented than `col`.
5048    /// If we are in a flow-style construct (which don't have indentation per-se), this function
5049    /// does nothing.
5050    fn unroll_indent(&mut self, col: isize) {
5051        if self.flow_level > 0 {
5052            return;
5053        }
5054        while self.indent > col {
5055            let indent = self.indents.pop().unwrap();
5056            self.indent = indent.indent;
5057            if indent.needs_block_end {
5058                debug_assert!(self.block_level > 0);
5059                self.block_level -= 1;
5060                self.tokens
5061                    .push_back(Token(Span::empty(self.mark), TokenType::BlockEnd).into());
5062            }
5063        }
5064    }
5065
5066    /// Add an indentation level of 1 column that does not start a block.
5067    ///
5068    /// See the documentation of [`Indent::needs_block_end`] for more details.
5069    /// An indentation is not added if we are inside a flow level or if the last indent is already
5070    /// a non-block indent.
5071    fn roll_one_col_indent(&mut self) {
5072        if self.flow_level == 0 && self.indents.last().is_some_and(|x| x.needs_block_end) {
5073            self.indents.push(Indent {
5074                indent: self.indent,
5075                needs_block_end: false,
5076            });
5077            self.indent += 1;
5078        }
5079    }
5080
5081    /// Unroll all last indents created with [`Self::roll_one_col_indent`].
5082    fn unroll_non_block_indents(&mut self) {
5083        while let Some(indent) = self.indents.last() {
5084            if indent.needs_block_end {
5085                break;
5086            }
5087            self.indent = indent.indent;
5088            self.indents.pop();
5089        }
5090    }
5091
5092    /// Mark the next token to be inserted as a potential simple key.
5093    fn save_simple_key(&mut self) {
5094        if self.simple_key_allowed {
5095            let required = self.flow_level == 0
5096                && self.indent == (self.mark.col as isize)
5097                && self.indents.last().unwrap().needs_block_end;
5098
5099            if let Some(last) = self.simple_keys.last_mut() {
5100                *last = SimpleKey {
5101                    mark: self.mark,
5102                    possible: true,
5103                    required,
5104                    token_number: self.tokens_parsed + self.tokens.len(),
5105                };
5106                self.first_simple_key.get_or_insert(self.flow_level);
5107            }
5108        }
5109    }
5110
5111    fn remove_simple_key(&mut self) -> ScanResult {
5112        let last = self.simple_keys.last().unwrap();
5113        if last.possible && last.required {
5114            return Err(Self::simple_key_expected(last.mark));
5115        }
5116
5117        self.clear_simple_key();
5118        Ok(())
5119    }
5120
5121    /// Clear the current key after it is resolved or checked to be optional.
5122    fn clear_simple_key(&mut self) {
5123        self.simple_keys.last_mut().unwrap().possible = false;
5124        if self.first_simple_key == Some(self.flow_level) {
5125            // This is the top level, so no other possible keys follow it.
5126            self.first_simple_key = None;
5127        }
5128    }
5129
5130    /// Return whether the scanner is inside a block but outside of a flow sequence.
5131    fn is_within_block(&self) -> bool {
5132        !self.indents.is_empty()
5133    }
5134
5135    /// If an implicit mapping had started, end it.
5136    ///
5137    /// This function does not pop the state in [`implicit_flow_mapping_states`].
5138    ///
5139    /// [`implicit_flow_mapping_states`]: Self::implicit_flow_mapping_states
5140    fn end_implicit_mapping(&mut self, mark: Marker, flow_level: usize) {
5141        if self
5142            .implicit_flow_mapping_states
5143            .last()
5144            .is_some_and(|state| *state == ImplicitMappingState::Inside(flow_level))
5145        {
5146            *self.implicit_flow_mapping_states.last_mut().unwrap() = ImplicitMappingState::Possible;
5147            self.set_current_flow_mapping_started(false);
5148            self.tokens
5149                .push_back(Token(Span::empty(mark), TokenType::FlowMappingEnd).into());
5150        }
5151    }
5152
5153    fn current_flow_collection_is_sequence(&self) -> bool {
5154        self.flow_markers
5155            .last()
5156            .is_some_and(|(_, bracket)| *bracket == '[')
5157    }
5158
5159    fn current_flow_mapping_started(&self) -> bool {
5160        self.flow_mapping_started.last().copied().unwrap_or(false)
5161    }
5162
5163    fn set_current_flow_mapping_started(&mut self, started: bool) {
5164        if let Some(current) = self.flow_mapping_started.last_mut() {
5165            *current = started;
5166        }
5167    }
5168}
5169
5170#[cfg(test)]
5171mod test {
5172    use alloc::{
5173        borrow::{Cow, ToOwned},
5174        rc::Rc,
5175        string::String,
5176        vec,
5177        vec::Vec,
5178    };
5179    use core::cell::Cell;
5180
5181    use crate::error::{ErrorKind, ScanError};
5182    #[cfg(feature = "comments")]
5183    use crate::scanner::{Comment, Placement};
5184    use crate::{
5185        input::{str::StrInput, BorrowedInput, BufferedInput, Input},
5186        scanner::{
5187            Marker, QueuedToken, QueuedTokenType, ScalarStyle, Scanner, Span, Token, TokenType,
5188        },
5189    };
5190
5191    #[test]
5192    fn tag_span_supports_the_full_u32_length_without_allocating() {
5193        let start = Marker::new(0, 1, 0).with_byte_offset(Some(0));
5194        let span = Span::empty(start).with_tag_span(Some((start, u32::MAX)));
5195        let tag_span = span.tag_span().unwrap();
5196        let length = usize::try_from(u32::MAX).unwrap();
5197        assert_eq!(tag_span.start, start);
5198        assert_eq!(tag_span.end.index(), length);
5199        assert_eq!(tag_span.end.col(), length);
5200        assert_eq!(tag_span.end.line(), 1);
5201        assert_eq!(tag_span.end.byte_offset(), Some(length));
5202    }
5203
5204    #[test]
5205    fn tag_span_rejects_overflow_in_each_reconstructed_coordinate() {
5206        for start in [
5207            Marker::new(usize::MAX, 1, 0),
5208            Marker::new(0, 1, usize::MAX),
5209            Marker::new(0, 1, 0).with_byte_offset(Some(usize::MAX)),
5210        ] {
5211            let span = Span::empty(start).with_tag_span(Some((start, 1)));
5212            assert_eq!(span.tag_span(), None);
5213        }
5214    }
5215
5216    #[test]
5217    fn recovery_ignores_invalid_document_marker_lookalikes() {
5218        let input = "@bad\n---# comment\n  ---\n---\0\n... trailing\n--- healthy\n";
5219        let mut scanner = Scanner::new(StrInput::new(input));
5220        assert!(matches!(
5221            scanner.next_token().unwrap().unwrap().1,
5222            TokenType::StreamStart
5223        ));
5224        assert!(scanner.next_token().is_err());
5225
5226        scanner.proceed_next_document(None).unwrap();
5227        let token = scanner.next_token().unwrap().unwrap();
5228        assert_eq!(token.1, TokenType::DocumentStart);
5229        assert_eq!(token.0.start.line(), 6);
5230        assert!(matches!(
5231            scanner.next_token().unwrap().unwrap().1,
5232            TokenType::Scalar { style: _, ref value } if value == "healthy"
5233        ));
5234    }
5235
5236    #[test]
5237    fn recovery_rejects_end_marker_queued_before_its_line_failed() {
5238        let mut scanner =
5239            Scanner::new(StrInput::new("... trailing\nnot_a_document\n--- healthy\n"));
5240        scanner.next_token().unwrap();
5241        assert_eq!(
5242            scanner.next_token().unwrap_err().kind(),
5243            &ErrorKind::InvalidDocumentEnd
5244        );
5245        assert!(scanner
5246            .tokens
5247            .iter()
5248            .any(|token| matches!(token.1, QueuedTokenType::DocumentEnd)));
5249
5250        scanner.proceed_next_document(None).unwrap();
5251        let token = scanner.next_token().unwrap().unwrap();
5252        assert_eq!(token.1, TokenType::DocumentStart);
5253        assert_eq!(token.0.start.line(), 3);
5254    }
5255
5256    #[test]
5257    fn recovery_preserves_boundary_already_held_by_parser() {
5258        let mut scanner = Scanner::new(StrInput::new("first\n--- second\n"));
5259        let boundary = loop {
5260            let token = scanner.next_queued_token().unwrap().unwrap();
5261            if matches!(token.1, QueuedTokenType::DocumentStart) {
5262                break token;
5263            }
5264        };
5265        let span = boundary.0;
5266        scanner.proceed_next_document(Some(boundary)).unwrap();
5267        assert_eq!(
5268            scanner.next_token().unwrap().unwrap(),
5269            Token(span, TokenType::DocumentStart)
5270        );
5271        assert!(matches!(
5272            scanner.next_token().unwrap().unwrap().1,
5273            TokenType::Scalar { style: _, ref value } if value == "second"
5274        ));
5275    }
5276
5277    #[test]
5278    fn recovery_retains_previously_reported_source_error() {
5279        let kind = ErrorKind::InputDecoding {
5280            message: "invalid encoding".into(),
5281        };
5282        let input = crate::FallibleBufferedInput::new(
5283            vec![Ok('['), Err(kind.clone()), Ok('\n')].into_iter(),
5284        );
5285        let mut scanner = Scanner::new(input);
5286        scanner.next_token().unwrap();
5287        let error = scanner.next_token().unwrap_err();
5288        assert_eq!(error.kind(), &kind);
5289        assert_eq!(scanner.proceed_next_document(None), Err(error));
5290    }
5291
5292    #[test]
5293    fn recovery_distinguishes_directive_header_errors_from_document_content() {
5294        for input in ["%YAML bad\n--- body\n", "%TAG invalid\n--- body\n"] {
5295            let mut scanner = Scanner::new(StrInput::new(input));
5296            scanner.next_token().unwrap();
5297            assert!(scanner.next_token().is_err());
5298            assert!(scanner.in_directive_prefix());
5299            scanner.proceed_next_document(None).unwrap();
5300            assert!(!scanner.in_directive_prefix());
5301        }
5302
5303        let mut scanner = Scanner::with_options(
5304            StrInput::new("%YAML 1.2\n--- body\n"),
5305            crate::options! { disallow_directives: true },
5306        );
5307        scanner.next_token().unwrap();
5308        assert!(scanner.next_token().is_err());
5309        assert!(scanner.in_directive_prefix());
5310
5311        for input in ["%YAML 1.2\n--- body\n", "%YAML 1.2\nbare\n"] {
5312            let mut scanner = Scanner::new(StrInput::new(input));
5313            scanner.next_token().unwrap();
5314            scanner.next_token().unwrap();
5315            assert!(scanner.in_directive_prefix());
5316            scanner.next_token().unwrap();
5317            assert!(!scanner.in_directive_prefix());
5318        }
5319    }
5320
5321    fn ignoring_comments_options() -> crate::Options {
5322        #[cfg(feature = "comments")]
5323        {
5324            crate::options! { emit_comments: false }
5325        }
5326        #[cfg(not(feature = "comments"))]
5327        {
5328            crate::Options::default()
5329        }
5330    }
5331
5332    struct CountingChars {
5333        chars: alloc::vec::IntoIter<char>,
5334        read: Rc<Cell<usize>>,
5335    }
5336
5337    impl Iterator for CountingChars {
5338        type Item = char;
5339
5340        fn next(&mut self) -> Option<Self::Item> {
5341            let next = self.chars.next();
5342            if next.is_some() {
5343                self.read.set(self.read.get() + 1);
5344            }
5345            next
5346        }
5347    }
5348
5349    struct SlicingOnlyInput<'input> {
5350        inner: StrInput<'input>,
5351        expose_slice: bool,
5352    }
5353
5354    impl<'input> SlicingOnlyInput<'input> {
5355        fn new(source: &'input str, expose_slice: bool) -> Self {
5356            Self {
5357                inner: StrInput::new(source),
5358                expose_slice,
5359            }
5360        }
5361    }
5362
5363    impl Input for SlicingOnlyInput<'_> {
5364        fn lookahead(&mut self, count: usize) {
5365            self.inner.lookahead(count);
5366        }
5367
5368        fn buflen(&self) -> usize {
5369            self.inner.buflen()
5370        }
5371
5372        fn bufmaxlen(&self) -> usize {
5373            self.inner.bufmaxlen()
5374        }
5375
5376        fn raw_read_ch(&mut self) -> char {
5377            self.inner.raw_read_ch()
5378        }
5379
5380        fn raw_read_non_breakz_ch(&mut self) -> Option<char> {
5381            self.inner.raw_read_non_breakz_ch()
5382        }
5383
5384        fn skip(&mut self) {
5385            self.inner.skip();
5386        }
5387
5388        fn skip_n(&mut self, count: usize) {
5389            self.inner.skip_n(count);
5390        }
5391
5392        fn peek(&self) -> char {
5393            self.inner.peek()
5394        }
5395
5396        fn peek_nth(&self, n: usize) -> char {
5397            self.inner.peek_nth(n)
5398        }
5399
5400        fn byte_offset(&self) -> Option<usize> {
5401            self.inner.byte_offset()
5402        }
5403
5404        fn slice_bytes(&self, start: usize, end: usize) -> Option<&str> {
5405            if self.expose_slice {
5406                self.inner.slice_bytes(start, end)
5407            } else {
5408                None
5409            }
5410        }
5411    }
5412
5413    impl<'input> BorrowedInput<'input> for SlicingOnlyInput<'input> {
5414        fn slice_borrowed(&self, _start: usize, _end: usize) -> Option<&'input str> {
5415            None
5416        }
5417    }
5418
5419    struct SmallReportedBufferInput<'input> {
5420        inner: StrInput<'input>,
5421        reported_bufmaxlen: usize,
5422    }
5423
5424    impl<'input> SmallReportedBufferInput<'input> {
5425        fn new(source: &'input str, reported_bufmaxlen: usize) -> Self {
5426            Self {
5427                inner: StrInput::new(source),
5428                reported_bufmaxlen,
5429            }
5430        }
5431    }
5432
5433    impl Input for SmallReportedBufferInput<'_> {
5434        fn lookahead(&mut self, count: usize) {
5435            self.inner.lookahead(count);
5436        }
5437
5438        fn buflen(&self) -> usize {
5439            self.inner.buflen()
5440        }
5441
5442        fn bufmaxlen(&self) -> usize {
5443            self.reported_bufmaxlen
5444        }
5445
5446        fn raw_read_ch(&mut self) -> char {
5447            self.inner.raw_read_ch()
5448        }
5449
5450        fn raw_read_non_breakz_ch(&mut self) -> Option<char> {
5451            self.inner.raw_read_non_breakz_ch()
5452        }
5453
5454        fn skip(&mut self) {
5455            self.inner.skip();
5456        }
5457
5458        fn skip_n(&mut self, count: usize) {
5459            self.inner.skip_n(count);
5460        }
5461
5462        fn peek(&self) -> char {
5463            self.inner.peek()
5464        }
5465
5466        fn peek_nth(&self, n: usize) -> char {
5467            self.inner.peek_nth(n)
5468        }
5469    }
5470
5471    impl<'input> BorrowedInput<'input> for SmallReportedBufferInput<'input> {
5472        fn slice_borrowed(&self, start: usize, end: usize) -> Option<&'input str> {
5473            self.inner.slice_borrowed(start, end)
5474        }
5475    }
5476
5477    #[test]
5478    fn anchor_character_set_allows_colon_and_rejects_flow_indicators() {
5479        use super::is_anchor_char;
5480
5481        assert!(is_anchor_char('x'));
5482        assert!(is_anchor_char('-'));
5483        assert!(is_anchor_char('_'));
5484        assert!(is_anchor_char(':'));
5485        assert!(is_anchor_char('#'));
5486        assert!(is_anchor_char('/'));
5487        assert!(is_anchor_char('?'));
5488
5489        for c in [',', '[', ']', '{', '}', ' ', '\t', '\n', '\r', '\0'] {
5490            assert!(
5491                !is_anchor_char(c),
5492                "character {c:?} must not be accepted in anchor/alias names"
5493            );
5494        }
5495    }
5496
5497    #[test]
5498    fn flow_simple_key_length_limit_bounds_buffering() {
5499        let mut yaml = String::from("[\n\"start\"\n");
5500        for _ in 0..600 {
5501            yaml.push_str("\"x\"\n");
5502        }
5503        let total_chars = yaml.chars().count();
5504        let read = Rc::new(Cell::new(0));
5505        let chars = yaml.chars().collect::<Vec<_>>().into_iter();
5506        let mut scanner = Scanner::new(BufferedInput::new(CountingChars {
5507            chars,
5508            read: Rc::clone(&read),
5509        }));
5510
5511        assert!(matches!(
5512            scanner.next_token().unwrap().unwrap().1,
5513            TokenType::StreamStart
5514        ));
5515
5516        let token = scanner.next_token().unwrap().unwrap();
5517        assert!(matches!(token.1, TokenType::FlowSequenceStart));
5518
5519        let token = scanner.next_token().unwrap().unwrap();
5520        assert!(matches!(
5521            token.1,
5522            TokenType::Scalar { style: _, ref value } if value == "start"
5523        ));
5524        assert!(
5525            read.get() < total_chars,
5526            "scanner consumed all {total_chars} chars before yielding the first flow scalar"
5527        );
5528        assert!(
5529            read.get() <= scanner.options.simple_key_max_lookahead + 128,
5530            "scanner read {} chars before yielding the first flow scalar",
5531            read.get()
5532        );
5533    }
5534
5535    #[test]
5536    fn block_scalar_indent_tolerates_small_reported_bufmaxlen() {
5537        let mut scanner = Scanner::new(SmallReportedBufferInput::new("|\n  value\n", 0));
5538
5539        let scalar = scanner
5540            .find_map(
5541                |token| match token.expect("valid YAML should scan without errors") {
5542                    Token(
5543                        _,
5544                        TokenType::Scalar {
5545                            style: ScalarStyle::Literal { .. },
5546                            value,
5547                        },
5548                    ) => Some(value.into_owned()),
5549                    _ => None,
5550                },
5551            )
5552            .expect("expected block scalar token");
5553
5554        assert_eq!(scalar, "value\n");
5555    }
5556
5557    #[test]
5558    fn plain_scalar_chunk_tolerates_small_reported_bufmaxlen() {
5559        let mut scanner = Scanner::new(SmallReportedBufferInput::new("plain\n", 0));
5560
5561        let scalar = scanner
5562            .find_map(
5563                |token| match token.expect("valid YAML should scan without errors") {
5564                    Token(
5565                        _,
5566                        TokenType::Scalar {
5567                            style: ScalarStyle::Plain { .. },
5568                            value,
5569                        },
5570                    ) => Some(value.into_owned()),
5571                    _ => None,
5572                },
5573            )
5574            .expect("expected plain scalar token");
5575
5576        assert_eq!(scalar, "plain");
5577    }
5578
5579    fn first_token_slice(
5580        yaml: &str,
5581        matches_token: impl Fn(&TokenType<'_>) -> bool,
5582    ) -> Option<String> {
5583        let mut scanner = Scanner::new(StrInput::new(yaml));
5584
5585        loop {
5586            let token = scanner
5587                .next_token()
5588                .expect("scanner should accept the test YAML")?;
5589            if matches_token(&token.1) {
5590                return token.0.slice(yaml).map(ToOwned::to_owned);
5591            }
5592        }
5593    }
5594
5595    #[test]
5596    fn flow_indicator_token_spans_cover_only_the_indicator() {
5597        assert_eq!(
5598            first_token_slice("[ # c\n  a]\n", |token| matches!(
5599                token,
5600                TokenType::FlowSequenceStart
5601            ))
5602            .as_deref(),
5603            Some("[")
5604        );
5605        assert_eq!(
5606            first_token_slice("{ # c\n  a: b}\n", |token| matches!(
5607                token,
5608                TokenType::FlowMappingStart
5609            ))
5610            .as_deref(),
5611            Some("{")
5612        );
5613        assert_eq!(
5614            first_token_slice("[a] # c\n", |token| matches!(
5615                token,
5616                TokenType::FlowSequenceEnd
5617            ))
5618            .as_deref(),
5619            Some("]")
5620        );
5621        assert_eq!(
5622            first_token_slice("{a: b} # c\n", |token| matches!(
5623                token,
5624                TokenType::FlowMappingEnd
5625            ))
5626            .as_deref(),
5627            Some("}")
5628        );
5629        assert_eq!(
5630            first_token_slice("[a, # c\nb]\n", |token| matches!(
5631                token,
5632                TokenType::FlowEntry
5633            ))
5634            .as_deref(),
5635            Some(",")
5636        );
5637    }
5638
5639    #[test]
5640    fn explicit_key_token_span_covers_only_the_indicator() {
5641        assert_eq!(
5642            first_token_slice("? # c\n: value\n", |token| matches!(token, TokenType::Key))
5643                .as_deref(),
5644            Some("?")
5645        );
5646    }
5647
5648    #[test]
5649    #[cfg(feature = "comments")]
5650    fn comment_capture_does_not_change_leading_whitespace() {
5651        let mut scanner = Scanner::new(StrInput::new("# comment\n"));
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 == " comment")
5658        );
5659
5660        let mut scanner = Scanner::new(BufferedInput::new("# streaming\n".chars()));
5661        scanner.input.lookahead(1);
5662
5663        let token = scanner.scan_comment_token().unwrap();
5664
5665        assert!(scanner.leading_whitespace);
5666        assert!(
5667            matches!(token.1, TokenType::Comment { ref comment } if comment.text == " streaming")
5668        );
5669    }
5670
5671    #[test]
5672    #[cfg(feature = "comments")]
5673    fn comment_capture_falls_back_to_owned_slice_when_borrow_unavailable() {
5674        let mut scanner = Scanner::new(SlicingOnlyInput::new("# sliced\n", true));
5675        scanner.input.lookahead(2);
5676        assert_eq!(scanner.input.peek_nth(1), ' ');
5677
5678        let token = scanner.scan_comment_token().unwrap();
5679
5680        assert!(matches!(token.1, TokenType::Comment { ref comment }
5681            if matches!(comment.text, Cow::Owned(ref text) if text == " sliced")));
5682    }
5683
5684    #[test]
5685    #[cfg(feature = "comments")]
5686    fn comment_capture_errors_when_offsets_have_no_slice() {
5687        let mut scanner = Scanner::new(SlicingOnlyInput::new("# broken\n", false));
5688
5689        let error = scanner.scan_comment_token().unwrap_err();
5690
5691        assert_eq!(error.kind(), &ErrorKind::InputOffsetsWithoutSlice);
5692    }
5693
5694    #[test]
5695    fn disabled_comments_do_not_require_input_slicing() {
5696        let options = ignoring_comments_options();
5697        let scanner = Scanner::with_options(
5698            SlicingOnlyInput::new("# ignored\nkey: value\n", false),
5699            options,
5700        );
5701
5702        let tokens = scanner
5703            .collect::<Result<Vec<_>, _>>()
5704            .expect("ignored comments should not capture their payload");
5705
5706        #[cfg(feature = "comments")]
5707        assert!(tokens
5708            .iter()
5709            .all(|token| !matches!(token.1, TokenType::Comment { comment: _ })));
5710        assert!(tokens.iter().any(|token| matches!(
5711            token.1,
5712            TokenType::Scalar { style: ScalarStyle::Plain { .. }, value: ref text } if text == "value"
5713        )));
5714    }
5715
5716    #[test]
5717    fn queued_token_roundtrips_public_token_variants() {
5718        let span = Span::new(Marker::new(0, 1, 0), Marker::new(7, 1, 7));
5719        let tokens = [
5720            Token(span, TokenType::StreamStart),
5721            Token(span, TokenType::StreamEnd),
5722            Token(span, TokenType::VersionDirective { major: 1, minor: 2 }),
5723            Token(
5724                span,
5725                TokenType::TagDirective {
5726                    handle: Cow::Borrowed("!app!"),
5727                    prefix: Cow::Borrowed("tag:app.example,"),
5728                },
5729            ),
5730            Token(span, TokenType::DocumentStart),
5731            Token(span, TokenType::DocumentEnd),
5732            Token(span, TokenType::BlockSequenceStart),
5733            Token(span, TokenType::BlockMappingStart),
5734            Token(span, TokenType::BlockEnd),
5735            Token(span, TokenType::FlowSequenceStart),
5736            Token(span, TokenType::FlowSequenceEnd),
5737            Token(span, TokenType::FlowMappingStart),
5738            Token(span, TokenType::FlowMappingEnd),
5739            Token(span, TokenType::BlockEntry),
5740            Token(span, TokenType::FlowEntry),
5741            Token(span, TokenType::Key),
5742            Token(span, TokenType::Value),
5743            Token(
5744                span,
5745                TokenType::Alias {
5746                    name: Cow::Borrowed("alias"),
5747                },
5748            ),
5749            Token(
5750                span,
5751                TokenType::Anchor {
5752                    name: Cow::Borrowed("anchor"),
5753                },
5754            ),
5755            Token(
5756                span,
5757                TokenType::Tag {
5758                    handle: Cow::Borrowed("!"),
5759                    suffix: Cow::Borrowed("tag"),
5760                },
5761            ),
5762            Token(
5763                span,
5764                TokenType::Scalar {
5765                    style: ScalarStyle::literal(),
5766                    value: Cow::Borrowed("scalar"),
5767                },
5768            ),
5769            #[cfg(feature = "comments")]
5770            Token(
5771                span,
5772                TokenType::Comment {
5773                    comment: Comment::new(Cow::Borrowed(" comment"))
5774                        .with_placement(Placement::Right),
5775                },
5776            ),
5777            Token(
5778                span,
5779                TokenType::ReservedDirective {
5780                    name: "reserved".to_owned(),
5781                    parameters: vec!["one".to_owned(), "two".to_owned()],
5782                },
5783            ),
5784        ];
5785
5786        for token in tokens {
5787            let queued: QueuedToken = token.clone().into();
5788
5789            assert_eq!(queued.into_public(), token);
5790        }
5791    }
5792
5793    #[test]
5794    fn comment_skipping_path_consumes_comment_without_tokenizing_it() {
5795        let mut scanner = Scanner::new(StrInput::new("# skipped\nnext: value\n"));
5796
5797        scanner.skip_yaml_whitespace().unwrap();
5798
5799        assert!(scanner.tokens.is_empty());
5800        assert_eq!(scanner.mark.line(), 2);
5801        assert_eq!(scanner.mark.col(), 0);
5802    }
5803
5804    #[test]
5805    #[cfg(feature = "comments")]
5806    fn yaml_whitespace_can_stop_after_queued_comment() {
5807        let mut scanner = Scanner::new(StrInput::new(" # queued\n# later\n"));
5808
5809        assert!(scanner.skip_yaml_whitespace().unwrap());
5810
5811        assert_eq!(scanner.tokens.len(), 1);
5812        assert!(matches!(
5813            scanner.tokens.front().unwrap().1,
5814            QueuedTokenType::Comment(ref comment) if comment.text == " queued"
5815        ));
5816        assert_eq!(scanner.mark.line(), 1);
5817        assert_eq!(scanner.mark.col(), 9);
5818    }
5819
5820    #[test]
5821    #[cfg(feature = "comments")]
5822    fn token_skip_can_stop_after_queued_comment() {
5823        let mut scanner = Scanner::new(StrInput::new("# first\n# second\n"));
5824
5825        assert!(scanner.skip_to_next_token().unwrap().queued_comment);
5826
5827        assert_eq!(scanner.tokens.len(), 1);
5828        assert!(matches!(
5829            scanner.tokens.front().unwrap().1,
5830            QueuedTokenType::Comment(ref comment) if comment.text == " first"
5831        ));
5832        assert_eq!(scanner.mark.line(), 2);
5833        assert_eq!(scanner.mark.col(), 0);
5834    }
5835
5836    #[test]
5837    fn token_skip_stops_after_one_ignored_comment_without_queuing_it() {
5838        let options = ignoring_comments_options();
5839        let mut scanner =
5840            Scanner::with_options(StrInput::new("# first\n# second\nvalue\n"), options);
5841
5842        let outcome = scanner.skip_to_next_token().unwrap();
5843
5844        assert!(outcome.saw_comment);
5845        #[cfg(feature = "comments")]
5846        assert!(!outcome.queued_comment);
5847        assert!(scanner.tokens.is_empty());
5848        assert_eq!((scanner.mark.line(), scanner.mark.col()), (2, 0));
5849        assert_eq!(scanner.input.look_ch(), '#');
5850    }
5851
5852    #[test]
5853    fn yaml_whitespace_stops_after_one_separated_ignored_comment() {
5854        let options = ignoring_comments_options();
5855        let mut scanner =
5856            Scanner::with_options(StrInput::new(" # first\n# second\nvalue\n"), options);
5857
5858        assert!(scanner.skip_yaml_whitespace().unwrap());
5859
5860        assert!(scanner.tokens.is_empty());
5861        assert_eq!((scanner.mark.line(), scanner.mark.col()), (1, 8));
5862        assert_eq!(scanner.input.look_ch(), '\n');
5863    }
5864
5865    #[test]
5866    fn scanner_skips_consecutive_leading_ignored_comments_before_next_token() {
5867        let options = ignoring_comments_options();
5868        let mut scanner =
5869            Scanner::with_options(StrInput::new("# first\n# second\nvalue\n"), options);
5870
5871        assert!(matches!(
5872            scanner.next_token().unwrap().unwrap().1,
5873            TokenType::StreamStart
5874        ));
5875        assert!(matches!(
5876            scanner.next_token().unwrap().unwrap().1,
5877            TokenType::Scalar { style: ScalarStyle::Plain { .. }, ref value } if value == "value"
5878        ));
5879        #[cfg(feature = "comments")]
5880        assert!(scanner
5881            .tokens
5882            .iter()
5883            .all(|QueuedToken(_, token)| !matches!(token, QueuedTokenType::Comment(_))));
5884    }
5885
5886    #[test]
5887    #[cfg(feature = "comments")]
5888    fn scanner_emits_first_leading_comment_before_scanning_next_comment() {
5889        let mut scanner = Scanner::new(StrInput::new("# first\n# second\nkey: value\n"));
5890
5891        assert!(matches!(
5892            scanner.next_token().unwrap().unwrap().1,
5893            TokenType::StreamStart
5894        ));
5895        assert!(matches!(
5896            scanner.next_token().unwrap().unwrap().1,
5897            TokenType::Comment { ref comment } if comment.text == " first"
5898        ));
5899        assert!(scanner.tokens.is_empty());
5900        assert!(matches!(
5901            scanner.next_token().unwrap().unwrap().1,
5902            TokenType::Comment { ref comment } if comment.text == " second"
5903        ));
5904    }
5905
5906    #[test]
5907    #[cfg(feature = "comments")]
5908    fn scanner_emits_quoted_scalar_comment_before_scanning_following_value() {
5909        let mut scanner = Scanner::new(StrInput::new("\"key\" # quoted\n: value\n"));
5910
5911        assert!(matches!(
5912            scanner.next_token().unwrap().unwrap().1,
5913            TokenType::StreamStart
5914        ));
5915        assert!(matches!(
5916            scanner.next_token().unwrap().unwrap().1,
5917            TokenType::Scalar { style: ScalarStyle::DoubleQuoted, ref value } if value == "key"
5918        ));
5919        assert!(matches!(
5920            scanner.next_token().unwrap().unwrap().1,
5921            TokenType::Comment { ref comment } if comment.text == " quoted"
5922        ));
5923    }
5924
5925    #[test]
5926    #[cfg(feature = "comments")]
5927    fn flow_scalar_comment_disables_adjacent_value_lookahead() {
5928        let mut scanner = Scanner::new(StrInput::new("\"key\"\n# quoted\n: value\n"));
5929
5930        scanner.fetch_flow_scalar(false).unwrap();
5931
5932        assert_eq!(scanner.adjacent_value_allowed_at, usize::MAX);
5933        assert!(matches!(
5934            scanner.tokens.front().unwrap().1,
5935            QueuedTokenType::Scalar(ScalarStyle::DoubleQuoted, ref value) if value == "key"
5936        ));
5937        assert!(scanner.tokens.iter().any(|QueuedToken(_, token)| matches!(
5938            token,
5939            QueuedTokenType::Comment(comment) if comment.text == " quoted"
5940        )));
5941    }
5942
5943    #[test]
5944    fn ignored_flow_scalar_comment_still_disables_adjacent_value_lookahead() {
5945        let options = ignoring_comments_options();
5946        let mut scanner =
5947            Scanner::with_options(StrInput::new("\"key\"\n# ignored\n: value\n"), options);
5948
5949        scanner.fetch_flow_scalar(false).unwrap();
5950
5951        assert_eq!(scanner.adjacent_value_allowed_at, usize::MAX);
5952        assert_eq!(scanner.tokens.len(), 1);
5953        assert!(matches!(
5954            scanner.tokens.front().unwrap().1,
5955            QueuedTokenType::Scalar(ScalarStyle::DoubleQuoted, ref value) if value == "key"
5956        ));
5957    }
5958
5959    #[test]
5960    #[cfg(feature = "comments")]
5961    fn deferred_error_waits_for_all_comment_tokens() {
5962        let mut scanner = Scanner::new(StrInput::new("# first\n# second\n@\n"));
5963
5964        assert!(matches!(
5965            scanner.next_token().unwrap().unwrap().1,
5966            TokenType::StreamStart
5967        ));
5968        assert!(matches!(
5969            scanner.next_token().unwrap().unwrap().1,
5970            TokenType::Comment { ref comment } if comment.text == " first"
5971        ));
5972        assert!(matches!(
5973            scanner.next_token().unwrap().unwrap().1,
5974            TokenType::Comment { ref comment } if comment.text == " second"
5975        ));
5976
5977        let error = scanner.next_token().unwrap_err();
5978
5979        assert_eq!(
5980            error.kind(),
5981            &ErrorKind::UnexpectedCharacter { character: '@' }
5982        );
5983    }
5984
5985    /// Ensure anchors scanned from `StrInput` are returned as `Cow::Borrowed`.
5986    #[test]
5987    fn anchor_name_is_borrowed_for_str_input() {
5988        let mut scanner = Scanner::new(StrInput::new("&anch\n"));
5989
5990        loop {
5991            let tok = scanner
5992                .next_token()
5993                .expect("valid YAML must scan without errors")
5994                .expect("scanner must eventually produce a token");
5995            if let TokenType::Anchor { name } = tok.1 {
5996                assert!(matches!(name, Cow::Borrowed("anch")));
5997                break;
5998            }
5999        }
6000    }
6001
6002    #[test]
6003    fn anchor_name_rejects_non_printable_control_chars() {
6004        let mut scanner = Scanner::new(StrInput::new("&foo\u{0001}\n"));
6005
6006        scanner.next_token().unwrap();
6007        assert_eq!(
6008            scanner.next_token().unwrap_err().kind(),
6009            &ErrorKind::UnexpectedCharacter {
6010                character: '\u{0001}'
6011            }
6012        );
6013    }
6014
6015    #[test]
6016    fn alias_name_rejects_non_printable_control_chars() {
6017        let mut scanner = Scanner::new(StrInput::new("*foo\u{0001}\n"));
6018
6019        scanner.next_token().unwrap();
6020        assert_eq!(
6021            scanner.next_token().unwrap_err().kind(),
6022            &ErrorKind::UnexpectedCharacter {
6023                character: '\u{0001}'
6024            }
6025        );
6026    }
6027
6028    #[test]
6029    fn alias_name_is_borrowed_for_str_input() {
6030        let mut scanner = Scanner::new(StrInput::new("*anch\n"));
6031
6032        loop {
6033            let tok = scanner
6034                .next_token()
6035                .expect("valid YAML must scan without errors")
6036                .expect("scanner must eventually produce a token");
6037            if let TokenType::Alias { name } = tok.1 {
6038                assert!(matches!(name, Cow::Borrowed("anch")));
6039                break;
6040            }
6041        }
6042    }
6043
6044    #[test]
6045    fn alias_name_scans_colon_as_part_of_name() {
6046        let mut scanner = Scanner::new(StrInput::new("*foo: bar\n"));
6047
6048        loop {
6049            let tok = scanner
6050                .next_token()
6051                .expect("scanner must not fail before alias token")
6052                .expect("scanner must eventually emit an alias token");
6053
6054            if let TokenType::Alias { name } = tok.1 {
6055                assert_eq!(name.as_ref(), "foo:");
6056                break;
6057            }
6058        }
6059    }
6060
6061    #[test]
6062    fn anchor_name_scans_colon_as_part_of_name() {
6063        let mut scanner = Scanner::new(StrInput::new("&foo: bar\n"));
6064
6065        loop {
6066            let tok = scanner
6067                .next_token()
6068                .expect("scanner must not fail before anchor token")
6069                .expect("scanner must eventually emit an anchor token");
6070
6071            if let TokenType::Anchor { name } = tok.1 {
6072                assert_eq!(name.as_ref(), "foo:");
6073                break;
6074            }
6075        }
6076    }
6077
6078    /// Ensure `%TAG` directive handle and prefix are borrowed when they are verbatim (no escapes).
6079    #[test]
6080    fn tag_directive_parts_are_borrowed_for_str_input() {
6081        let mut scanner = Scanner::new(StrInput::new("%TAG !e! tag:example.com,2000:app/\n"));
6082
6083        loop {
6084            let tok = scanner
6085                .next_token()
6086                .expect("valid YAML must scan without errors")
6087                .expect("scanner must eventually produce a token");
6088            if let TokenType::TagDirective { handle, prefix } = tok.1 {
6089                assert!(matches!(handle, Cow::Borrowed("!e!")));
6090                assert!(matches!(prefix, Cow::Borrowed("tag:example.com,2000:app/")));
6091                break;
6092            }
6093        }
6094    }
6095
6096    #[test]
6097    fn tag_directive_parts_are_owned_for_buffered_input() {
6098        let mut scanner = Scanner::new(BufferedInput::new(
6099            "%TAG !e! tag:example.com,2000:app/\n".chars(),
6100        ));
6101
6102        loop {
6103            let tok = scanner
6104                .next_token()
6105                .expect("valid YAML must scan without errors")
6106                .expect("scanner must eventually produce a token");
6107            if let TokenType::TagDirective { handle, prefix } = tok.1 {
6108                assert!(matches!(handle, Cow::Owned(_)));
6109                assert_eq!(&*handle, "!e!");
6110                assert!(matches!(prefix, Cow::Owned(_)));
6111                assert_eq!(&*prefix, "tag:example.com,2000:app/");
6112                break;
6113            }
6114        }
6115    }
6116
6117    #[test]
6118    fn buffered_tag_directive_decodes_prefix_escape() {
6119        let mut scanner = Scanner::new(BufferedInput::new(
6120            "%TAG !e! %74ag:example.com,2000:app/\n".chars(),
6121        ));
6122
6123        loop {
6124            let tok = scanner
6125                .next_token()
6126                .expect("valid YAML must scan without errors")
6127                .expect("scanner must eventually produce a token");
6128            if let TokenType::TagDirective { handle, prefix } = tok.1 {
6129                assert_eq!(&*handle, "!e!");
6130                assert!(matches!(prefix, Cow::Owned(_)));
6131                assert_eq!(&*prefix, "tag:example.com,2000:app/");
6132                break;
6133            }
6134        }
6135    }
6136
6137    #[test]
6138    fn local_tag_combines_handle_text_with_escaped_suffix() {
6139        let mut scanner = Scanner::new(StrInput::new("!foo%20bar value\n"));
6140
6141        loop {
6142            let tok = scanner
6143                .next_token()
6144                .expect("valid YAML must scan without errors")
6145                .expect("scanner must eventually produce a token");
6146            if let TokenType::Tag { handle, suffix } = tok.1 {
6147                assert!(matches!(handle, Cow::Borrowed("!")));
6148                assert!(matches!(suffix, Cow::Owned(_)));
6149                assert_eq!(&*suffix, "foo bar");
6150                break;
6151            }
6152        }
6153    }
6154
6155    #[test]
6156    fn secondary_tag_requires_suffix_in_borrowed_and_buffered_paths() {
6157        assert_eq!(
6158            first_scanner_error_kind("!! value\n"),
6159            ErrorKind::MissingTagUri
6160        );
6161        assert_eq!(
6162            first_buffered_scanner_error_kind("!! value\n"),
6163            ErrorKind::MissingTagUri
6164        );
6165    }
6166
6167    #[test]
6168    fn plain_scalar_is_borrowed_when_whitespace_free_for_str_input() {
6169        let mut scanner = Scanner::new(StrInput::new("foo\n"));
6170
6171        loop {
6172            let tok = scanner
6173                .next_token()
6174                .expect("valid YAML must scan without errors")
6175                .expect("scanner must eventually produce a token");
6176            if let TokenType::Scalar { style: _, value } = tok.1 {
6177                assert!(matches!(value, Cow::Borrowed("foo")));
6178                break;
6179            }
6180        }
6181    }
6182
6183    #[test]
6184    fn plain_scalar_is_borrowed_when_whitespace_present_for_str_input() {
6185        let mut scanner = Scanner::new(StrInput::new("foo bar\n"));
6186
6187        loop {
6188            let tok = scanner
6189                .next_token()
6190                .expect("valid YAML must scan without errors")
6191                .expect("scanner must eventually produce a token");
6192            if let TokenType::Scalar { style: _, value } = tok.1 {
6193                assert!(matches!(value, Cow::Borrowed("foo bar")));
6194                break;
6195            }
6196        }
6197    }
6198
6199    #[test]
6200    fn single_quoted_scalar_is_borrowed_when_verbatim_for_str_input() {
6201        let mut scanner = Scanner::new(StrInput::new("'foo bar'\n"));
6202
6203        loop {
6204            let tok = scanner
6205                .next_token()
6206                .expect("valid YAML must scan without errors")
6207                .expect("scanner must eventually produce a token");
6208            if let TokenType::Scalar { style: _, value } = tok.1 {
6209                assert!(matches!(value, Cow::Borrowed("foo bar")));
6210                break;
6211            }
6212        }
6213    }
6214
6215    #[test]
6216    fn single_quoted_scalar_is_owned_when_quote_is_escaped_for_str_input() {
6217        let mut scanner = Scanner::new(StrInput::new("'foo''bar'\n"));
6218
6219        loop {
6220            let tok = scanner
6221                .next_token()
6222                .expect("valid YAML must scan without errors")
6223                .expect("scanner must eventually produce a token");
6224            if let TokenType::Scalar { style: _, value } = tok.1 {
6225                assert!(matches!(value, Cow::Owned(_)));
6226                assert_eq!(&*value, "foo'bar");
6227                break;
6228            }
6229        }
6230    }
6231
6232    #[test]
6233    fn double_quoted_scalar_is_borrowed_when_verbatim_for_str_input() {
6234        let mut scanner = Scanner::new(StrInput::new("\"foo bar\"\n"));
6235
6236        loop {
6237            let tok = scanner
6238                .next_token()
6239                .expect("valid YAML must scan without errors")
6240                .expect("scanner must eventually produce a token");
6241            if let TokenType::Scalar { style: _, value } = tok.1 {
6242                assert!(matches!(value, Cow::Borrowed("foo bar")));
6243                break;
6244            }
6245        }
6246    }
6247
6248    #[test]
6249    fn double_quoted_scalar_is_owned_when_escape_sequence_present_for_str_input() {
6250        let mut scanner = Scanner::new(StrInput::new("\"foo\\nbar\"\n"));
6251
6252        loop {
6253            let tok = scanner
6254                .next_token()
6255                .expect("valid YAML must scan without errors")
6256                .expect("scanner must eventually produce a token");
6257            if let TokenType::Scalar { style: _, value } = tok.1 {
6258                assert!(matches!(value, Cow::Owned(_)));
6259                assert_eq!(&*value, "foo\nbar");
6260                break;
6261            }
6262        }
6263    }
6264
6265    #[test]
6266    fn plain_key_is_borrowed_for_str_input() {
6267        // Keys are just scalars in a key position; they should also be borrowed.
6268        let mut scanner = Scanner::new(StrInput::new("mykey: value\n"));
6269
6270        let mut found_key = false;
6271        let mut key_value: Option<Cow<'_, str>> = None;
6272
6273        loop {
6274            let tok = scanner
6275                .next_token()
6276                .expect("valid YAML must scan without errors");
6277            let Some(tok) = tok else { break };
6278
6279            if matches!(tok.1, TokenType::Key) {
6280                found_key = true;
6281            } else if found_key {
6282                if let TokenType::Scalar { style: _, value } = tok.1 {
6283                    key_value = Some(value);
6284                    break;
6285                }
6286            }
6287        }
6288
6289        assert!(found_key, "expected to find a Key token");
6290        let key_value = key_value.expect("expected to find a scalar after Key token");
6291        assert!(
6292            matches!(key_value, Cow::Borrowed("mykey")),
6293            "key should be borrowed, got: {key_value:?}"
6294        );
6295    }
6296
6297    #[test]
6298    fn quoted_key_is_borrowed_when_verbatim_for_str_input() {
6299        let mut scanner = Scanner::new(StrInput::new("\"mykey\": value\n"));
6300
6301        let mut found_key = false;
6302        let mut key_value: Option<Cow<'_, str>> = None;
6303
6304        loop {
6305            let tok = scanner
6306                .next_token()
6307                .expect("valid YAML must scan without errors");
6308            let Some(tok) = tok else { break };
6309
6310            if matches!(tok.1, TokenType::Key) {
6311                found_key = true;
6312            } else if found_key {
6313                if let TokenType::Scalar { style: _, value } = tok.1 {
6314                    key_value = Some(value);
6315                    break;
6316                }
6317            }
6318        }
6319
6320        assert!(found_key, "expected to find a Key token");
6321        let key_value = key_value.expect("expected to find a scalar after Key token");
6322        assert!(
6323            matches!(key_value, Cow::Borrowed("mykey")),
6324            "quoted key should be borrowed when verbatim, got: {key_value:?}"
6325        );
6326    }
6327
6328    #[test]
6329    fn tag_handle_and_suffix_are_borrowed_for_str_input() {
6330        // Test a tag like !!str which should have handle="!!" and suffix="str"
6331        let mut scanner = Scanner::new(StrInput::new("!!str foo\n"));
6332
6333        loop {
6334            let tok = scanner
6335                .next_token()
6336                .expect("valid YAML must scan without errors")
6337                .expect("scanner must eventually produce a token");
6338            if let TokenType::Tag { handle, suffix } = tok.1 {
6339                assert!(
6340                    matches!(handle, Cow::Borrowed("!!")),
6341                    "tag handle should be borrowed, got: {handle:?}"
6342                );
6343                assert!(
6344                    matches!(suffix, Cow::Borrowed("str")),
6345                    "tag suffix should be borrowed, got: {suffix:?}"
6346                );
6347                break;
6348            }
6349        }
6350    }
6351
6352    #[test]
6353    fn local_tag_suffix_is_borrowed_for_str_input() {
6354        // Test a local tag like !mytag which should have handle="!" and suffix="mytag"
6355        let mut scanner = Scanner::new(StrInput::new("!mytag foo\n"));
6356
6357        loop {
6358            let tok = scanner
6359                .next_token()
6360                .expect("valid YAML must scan without errors")
6361                .expect("scanner must eventually produce a token");
6362            if let TokenType::Tag { handle, suffix } = tok.1 {
6363                assert!(
6364                    matches!(handle, Cow::Borrowed("!")),
6365                    "local tag handle should be '!', got: {handle:?}"
6366                );
6367                assert!(
6368                    matches!(suffix, Cow::Borrowed("mytag")),
6369                    "local tag suffix should be borrowed, got: {suffix:?}"
6370                );
6371                break;
6372            }
6373        }
6374    }
6375
6376    #[test]
6377    fn local_tag_suffix_with_punctuation_is_borrowed_for_str_input() {
6378        let mut scanner = Scanner::new(StrInput::new("!mytag/part foo\n"));
6379
6380        loop {
6381            let tok = scanner
6382                .next_token()
6383                .expect("valid YAML must scan without errors")
6384                .expect("scanner must eventually produce a token");
6385            if let TokenType::Tag { handle, suffix } = tok.1 {
6386                assert!(matches!(handle, Cow::Borrowed("!")));
6387                assert!(matches!(suffix, Cow::Borrowed("mytag/part")));
6388                break;
6389            }
6390        }
6391    }
6392
6393    #[test]
6394    fn tag_with_uri_escape_is_owned_for_str_input() {
6395        // Test a tag with URI escape like !my%20tag - suffix must be owned due to decoding
6396        let mut scanner = Scanner::new(StrInput::new("!!my%20tag foo\n"));
6397
6398        loop {
6399            let tok = scanner
6400                .next_token()
6401                .expect("valid YAML must scan without errors")
6402                .expect("scanner must eventually produce a token");
6403            if let TokenType::Tag { handle, suffix } = tok.1 {
6404                assert!(
6405                    matches!(handle, Cow::Borrowed("!!")),
6406                    "tag handle should still be borrowed, got: {handle:?}"
6407                );
6408                assert!(
6409                    matches!(suffix, Cow::Owned(_)),
6410                    "tag suffix with URI escape should be owned, got: {suffix:?}"
6411                );
6412                assert_eq!(&*suffix, "my tag");
6413                break;
6414            }
6415        }
6416    }
6417
6418    #[test]
6419    fn flow_scalar_buffer_tracks_pending_whitespace() {
6420        let mut borrowed = super::FlowScalarBuf::new_borrowed(2);
6421
6422        borrowed.note_pending_ws(5, 8);
6423        borrowed.commit_pending_ws();
6424        assert!(matches!(
6425            borrowed,
6426            super::FlowScalarBuf::Borrowed {
6427                end: 8,
6428                pending_ws_start: None,
6429                pending_ws_end: 8,
6430                ..
6431            }
6432        ));
6433
6434        borrowed.note_pending_ws(9, 11);
6435        borrowed.discard_pending_ws();
6436        assert!(matches!(
6437            borrowed,
6438            super::FlowScalarBuf::Borrowed {
6439                end: 8,
6440                pending_ws_start: None,
6441                pending_ws_end: 8,
6442                ..
6443            }
6444        ));
6445        assert!(borrowed.as_owned_mut().is_none());
6446
6447        let mut owned = super::FlowScalarBuf::new_owned();
6448        owned.as_owned_mut().unwrap().push_str("owned");
6449        assert!(matches!(owned, super::FlowScalarBuf::Owned(ref s) if s == "owned"));
6450    }
6451
6452    fn first_scanner_error_kind(input: &str) -> ErrorKind {
6453        first_scanner_error(input).kind().clone()
6454    }
6455
6456    fn first_buffered_scanner_error_kind(input: &str) -> ErrorKind {
6457        let mut scanner = Scanner::new(BufferedInput::new(input.chars()));
6458        loop {
6459            match scanner.next_token() {
6460                Ok(Some(_)) => {}
6461                Ok(None) => panic!("expected scanner error"),
6462                Err(error) => return error.kind().clone(),
6463            }
6464        }
6465    }
6466
6467    fn first_scanner_error(input: &str) -> ScanError {
6468        let mut scanner = Scanner::new(StrInput::new(input));
6469        loop {
6470            match scanner.next_token() {
6471                Ok(Some(_)) => {}
6472                Ok(None) => panic!("expected scanner error"),
6473                Err(error) => return error,
6474            }
6475        }
6476    }
6477
6478    fn first_scalar_value(input: &str) -> String {
6479        let mut scanner = Scanner::new(StrInput::new(input));
6480        loop {
6481            match scanner.next_token().expect("scanner should not error") {
6482                Some(Token(_, TokenType::Scalar { style: _, value })) => return value.into_owned(),
6483                Some(_) => {}
6484                None => panic!("expected scalar token"),
6485            }
6486        }
6487    }
6488
6489    fn first_buffered_scalar_value(input: &str) -> String {
6490        let mut scanner = Scanner::new(BufferedInput::new(input.chars()));
6491        loop {
6492            match scanner.next_token().expect("scanner should not error") {
6493                Some(Token(_, TokenType::Scalar { style: _, value })) => return value.into_owned(),
6494                Some(_) => {}
6495                None => panic!("expected scalar token"),
6496            }
6497        }
6498    }
6499
6500    #[test]
6501    fn iterator_next_emits_error_and_then_stays_empty() {
6502        let mut scanner = Scanner::new(StrInput::new("\"unterminated"));
6503
6504        let error = scanner
6505            .by_ref()
6506            .find_map(Result::err)
6507            .expect("scanner should emit the error");
6508        assert_eq!(error.kind(), &ErrorKind::UnclosedQuotedScalar);
6509        assert!(scanner.next().is_none());
6510    }
6511
6512    #[test]
6513    fn next_token_returns_none_after_stream_end() {
6514        let mut scanner = Scanner::new(StrInput::new(""));
6515
6516        while let Some(token) = scanner.next_token().unwrap() {
6517            if matches!(token.1, TokenType::StreamEnd) {
6518                break;
6519            }
6520        }
6521
6522        assert!(scanner.stream_started());
6523        assert!(scanner.stream_ended());
6524        assert!(scanner.next_token().unwrap().is_none());
6525    }
6526
6527    #[test]
6528    fn directive_name_must_be_present() {
6529        assert_eq!(
6530            first_scanner_error_kind("%\n"),
6531            ErrorKind::MissingDirectiveName
6532        );
6533    }
6534
6535    #[test]
6536    fn yaml_directive_requires_dot_between_version_numbers() {
6537        assert_eq!(
6538            first_scanner_error_kind("%YAML 1\n"),
6539            ErrorKind::MissingYamlVersionSeparator
6540        );
6541    }
6542
6543    #[test]
6544    fn yaml_directive_requires_major_version_number() {
6545        assert_eq!(
6546            first_scanner_error_kind("%YAML .2\n"),
6547            ErrorKind::MissingYamlVersion
6548        );
6549    }
6550
6551    #[test]
6552    fn yaml_directive_rejects_extremely_long_version_number() {
6553        assert_eq!(
6554            first_scanner_error_kind("%YAML 1234567890.2\n"),
6555            ErrorKind::YamlVersionTooLong
6556        );
6557    }
6558
6559    #[test]
6560    fn tag_directive_handle_must_end_with_bang() {
6561        assert_eq!(
6562            first_scanner_error_kind("%TAG !bad tag:example.com,2024:\n"),
6563            ErrorKind::ExpectedTagDirectiveBang
6564        );
6565    }
6566
6567    #[test]
6568    fn tag_directive_handle_must_start_with_bang() {
6569        assert_eq!(
6570            first_scanner_error_kind("%TAG bad! tag:example.com,2024:\n"),
6571            ErrorKind::ExpectedTagBang
6572        );
6573        assert_eq!(
6574            first_buffered_scanner_error_kind("%TAG bad! tag:example.com,2024:\n"),
6575            ErrorKind::ExpectedTagBang
6576        );
6577    }
6578
6579    #[test]
6580    fn tag_directive_prefix_must_start_with_tag_character() {
6581        assert_eq!(
6582            first_scanner_error_kind("%TAG !e! `bad\n"),
6583            ErrorKind::InvalidGlobalTagCharacter
6584        );
6585    }
6586
6587    #[test]
6588    fn tag_directive_prefix_must_end_before_invalid_content() {
6589        assert_eq!(
6590            first_scanner_error_kind("%TAG !e! tag:example.com^suffix\n"),
6591            ErrorKind::InvalidTagDirectiveTerminator
6592        );
6593    }
6594
6595    #[test]
6596    fn tag_directive_prefix_with_uri_escape_is_owned_and_decoded() {
6597        let mut scanner =
6598            Scanner::new(StrInput::new("%TAG !e! tag:example.com,2024:some%20app/\n"));
6599
6600        loop {
6601            let token = scanner
6602                .next_token()
6603                .expect("valid directive should scan")
6604                .expect("scanner must produce a directive token");
6605            if let TokenType::TagDirective { handle, prefix } = token.1 {
6606                assert!(matches!(handle, Cow::Borrowed("!e!")));
6607                assert!(matches!(prefix, Cow::Owned(_)));
6608                assert_eq!(&*prefix, "tag:example.com,2024:some app/");
6609                break;
6610            }
6611        }
6612    }
6613
6614    #[test]
6615    fn bare_bang_tag_scans_as_non_specific_tag() {
6616        let mut scanner = Scanner::new(StrInput::new("! foo\n"));
6617
6618        loop {
6619            let token = scanner
6620                .next_token()
6621                .expect("valid tag should scan")
6622                .expect("scanner must produce a tag token");
6623            if let TokenType::Tag { handle, suffix } = token.1 {
6624                assert_eq!(&*handle, "");
6625                assert_eq!(&*suffix, "!");
6626                break;
6627            }
6628        }
6629    }
6630
6631    #[test]
6632    fn tag_requires_separation_after_suffix() {
6633        assert_eq!(
6634            first_scanner_error_kind("!foo,bar\n"),
6635            ErrorKind::InvalidTagTerminator
6636        );
6637    }
6638
6639    #[test]
6640    fn verbatim_tag_requires_uri() {
6641        assert_eq!(
6642            first_scanner_error_kind("!<> foo\n"),
6643            ErrorKind::MissingTagUri
6644        );
6645    }
6646
6647    #[test]
6648    fn verbatim_tag_requires_closing_angle_bracket() {
6649        assert_eq!(
6650            first_scanner_error_kind("!<tag:yaml.org,2002:str foo\n"),
6651            ErrorKind::UnclosedVerbatimTag
6652        );
6653    }
6654
6655    #[test]
6656    fn tag_uri_escape_requires_hex_digits() {
6657        assert_eq!(
6658            first_scanner_error_kind("!!bad%zz foo\n"),
6659            ErrorKind::InvalidTagEscape
6660        );
6661    }
6662
6663    #[test]
6664    fn tag_uri_escape_rejects_bad_leading_utf8_byte() {
6665        assert_eq!(
6666            first_scanner_error_kind("!!bad%80 foo\n"),
6667            ErrorKind::InvalidTagUtf8LeadingByte
6668        );
6669    }
6670
6671    #[test]
6672    fn tag_uri_escape_rejects_bad_trailing_utf8_byte() {
6673        assert_eq!(
6674            first_scanner_error_kind("!!bad%C2%41 foo\n"),
6675            ErrorKind::InvalidTagUtf8TrailingByte
6676        );
6677    }
6678
6679    #[test]
6680    fn tag_uri_escape_rejects_invalid_utf8_codepoint() {
6681        assert_eq!(
6682            first_scanner_error_kind("!!bad%F4%90%80%80 foo\n"),
6683            ErrorKind::InvalidTagUtf8
6684        );
6685    }
6686
6687    #[test]
6688    fn anchors_and_aliases_require_names() {
6689        assert_eq!(
6690            first_scanner_error_kind("& \n"),
6691            ErrorKind::MissingAnchorOrAliasName
6692        );
6693        assert_eq!(
6694            first_scanner_error_kind("* \n"),
6695            ErrorKind::MissingAnchorOrAliasName
6696        );
6697    }
6698
6699    #[test]
6700    fn document_end_marker_rejects_trailing_content() {
6701        assert_eq!(
6702            first_scanner_error_kind("... trailing\n"),
6703            ErrorKind::InvalidDocumentEnd
6704        );
6705    }
6706
6707    #[test]
6708    fn reserved_indicators_are_rejected_outside_directives() {
6709        let error = first_scanner_error(" @\n");
6710
6711        assert_eq!(
6712            error.kind(),
6713            &ErrorKind::UnexpectedCharacter { character: '@' }
6714        );
6715    }
6716
6717    #[test]
6718    fn flow_block_entry_indicator_is_rejected() {
6719        assert_eq!(
6720            first_scanner_error_kind("[- ]\n"),
6721            ErrorKind::BlockEntryInFlowCollection
6722        );
6723    }
6724
6725    #[test]
6726    fn block_entry_after_tabbed_separator_reports_specific_error() {
6727        assert_eq!(
6728            first_scanner_error_kind("-\t- value\n"),
6729            ErrorKind::InvalidBlockEntryWhitespace
6730        );
6731    }
6732
6733    #[test]
6734    fn document_indicator_reports_unclosed_flow_collection() {
6735        let error = first_scanner_error("[\n---\n");
6736
6737        assert_eq!(
6738            error.kind(),
6739            &ErrorKind::UnclosedFlowCollection { open: '[' }
6740        );
6741    }
6742
6743    #[test]
6744    fn block_scalar_header_rejects_trailing_content() {
6745        assert_eq!(
6746            first_scanner_error_kind("|+ trailing\n"),
6747            ErrorKind::InvalidBlockScalarHeader
6748        );
6749    }
6750
6751    #[test]
6752    fn block_scalar_rejects_zero_indent_indicator() {
6753        assert_eq!(
6754            first_scanner_error_kind("|0\n"),
6755            ErrorKind::ZeroBlockScalarIndent
6756        );
6757        assert_eq!(
6758            first_scanner_error_kind("|+0\n"),
6759            ErrorKind::ZeroBlockScalarIndent
6760        );
6761    }
6762
6763    #[test]
6764    fn empty_block_scalar_at_eof_honors_chomping() {
6765        assert_eq!(first_scalar_value("|\n"), "");
6766        assert_eq!(first_scalar_value("|-\n"), "");
6767        assert_eq!(first_scalar_value("|+\n"), "");
6768        assert_eq!(first_scalar_value("|+\n\n"), "\n");
6769        assert_eq!(first_scalar_value("|+\n   "), "\n");
6770    }
6771
6772    #[test]
6773    fn buffered_block_scalar_reads_content_past_lookahead_window() {
6774        assert_eq!(
6775            first_buffered_scalar_value("|\n  abcdefghijklmnopqrstuvwxyz\n"),
6776            "abcdefghijklmnopqrstuvwxyz\n"
6777        );
6778    }
6779
6780    #[test]
6781    fn explicit_indent_block_scalar_can_end_at_document_marker() {
6782        assert_eq!(first_scalar_value("|1\n...\n"), "");
6783    }
6784
6785    #[test]
6786    fn root_explicit_indent_block_scalar_rejects_underindented_content() {
6787        assert_eq!(
6788            first_scanner_error_kind("|2\nx\n"),
6789            ErrorKind::InvalidBlockScalarIndent
6790        );
6791    }
6792
6793    #[test]
6794    fn quoted_scalar_rejects_document_indicator_at_line_start() {
6795        assert_eq!(
6796            first_scanner_error_kind("\"one\n---\ntwo\"\n"),
6797            ErrorKind::DocumentIndicatorInQuotedScalar
6798        );
6799    }
6800
6801    #[test]
6802    fn strict_quoted_scalar_rejects_tab_indentation_after_line_break() {
6803        let error = Scanner::with_options(
6804            StrInput::new("a: \"one\n\tbad\"\n"),
6805            crate::options! { strict_indentation: true },
6806        )
6807        .find_map(Result::err)
6808        .expect("strict mode must reject a tab indenting a quoted continuation");
6809        assert_eq!(error.kind(), &ErrorKind::TabInIndentation);
6810    }
6811
6812    #[test]
6813    fn strict_quoted_scalar_rejects_underindented_continuation() {
6814        for input in ["a: \"one\nbad\"\n", "a:\n  b: 'one\n  bad'\n"] {
6815            let error = Scanner::with_options(
6816                StrInput::new(input),
6817                crate::options! { strict_indentation: true },
6818            )
6819            .find_map(Result::err)
6820            .expect("strict mode must reject underindented quoted continuations");
6821            assert_eq!(error.kind(), &ErrorKind::InvalidQuotedScalarIndent);
6822        }
6823    }
6824
6825    #[test]
6826    fn quoted_scalar_continuation_one_column_past_block_indent() {
6827        // s-flow-line-prefix(n): a continuation line needs only n spaces, where n is one more
6828        // than the indentation of the enclosing block mapping or sequence.
6829        for input in [
6830            "a: \"one\n two\"\n",
6831            "a: 'one\n two'\n",
6832            "a:\n  b: \"one\n   two\"\n",
6833            "- a: \"one\n   two\"\n",
6834            "? k\n: \"one\n two\"\n",
6835        ] {
6836            let mut scanner = Scanner::new(StrInput::new(input));
6837            loop {
6838                match scanner.next_token() {
6839                    Ok(Some(_)) => {}
6840                    Ok(None) => break,
6841                    Err(error) => panic!("{input:?}: {error}"),
6842                }
6843            }
6844        }
6845    }
6846
6847    #[test]
6848    fn quoted_scalar_trailing_content_error_names_quote_style() {
6849        assert_eq!(
6850            first_scanner_error_kind("'foo' trailing\n"),
6851            ErrorKind::InvalidTrailingSingleQuotedScalar
6852        );
6853        assert_eq!(
6854            first_scanner_error_kind("\"foo\" trailing\n"),
6855            ErrorKind::InvalidTrailingDoubleQuotedScalar
6856        );
6857    }
6858
6859    #[test]
6860    fn quoted_scalar_escape_errors_cover_hex_and_surrogate_edges() {
6861        assert_eq!(
6862            first_scanner_error_kind("\"\\xG0\"\n"),
6863            ErrorKind::InvalidQuotedScalarHexEscape
6864        );
6865        assert_eq!(
6866            first_scanner_error_kind("\"\\uD800\\uGGGG\"\n"),
6867            ErrorKind::InvalidLowSurrogateHexEscape
6868        );
6869        assert_eq!(
6870            first_scanner_error_kind("\"\\uD800\\u0041\"\n"),
6871            ErrorKind::InvalidLowSurrogate
6872        );
6873        assert_eq!(
6874            first_scanner_error_kind("\"\\U00110000\"\n"),
6875            ErrorKind::InvalidUnicodeEscape
6876        );
6877    }
6878
6879    #[test]
6880    fn under_indented_flow_scalar_is_accepted() {
6881        let tokens: Vec<_> = Scanner::new(StrInput::new("a:\n  [\nfoo]\n"))
6882            .map(|result| result.expect("under-indented flow entry should scan").1)
6883            .collect();
6884        assert_eq!(
6885            tokens,
6886            [
6887                TokenType::StreamStart,
6888                TokenType::BlockMappingStart,
6889                TokenType::Key,
6890                TokenType::Scalar {
6891                    style: ScalarStyle::plain(),
6892                    value: "a".into()
6893                },
6894                TokenType::Value,
6895                TokenType::FlowSequenceStart,
6896                TokenType::Scalar {
6897                    style: ScalarStyle::plain(),
6898                    value: "foo".into()
6899                },
6900                TokenType::FlowSequenceEnd,
6901                TokenType::BlockEnd,
6902                TokenType::StreamEnd,
6903            ]
6904        );
6905    }
6906
6907    #[test]
6908    fn required_simple_key_requires_value_at_stream_end() {
6909        let error = first_scanner_error("a:\n&b\n- c\n");
6910
6911        assert_eq!(error.kind(), &ErrorKind::SimpleKeyExpected);
6912        assert_eq!(error.marker().index(), 3);
6913        assert_eq!(error.marker().line(), 2);
6914        assert_eq!(error.marker().col(), 0);
6915    }
6916
6917    #[test]
6918    fn first_simple_key_tracks_ordered_possible_candidates() {
6919        let deep = alloc::format!(
6920            "{}{}{{[é, z]: v}}{}\n",
6921            "[".repeat(240),
6922            "a, ".repeat(400),
6923            "]".repeat(240)
6924        );
6925        for source in [
6926            "",
6927            "a: b\nmissing",
6928            "a: b\nmissing\n# after\nnext: value\n",
6929            "{[a, {b: c}]: [d, e], []: f}\n",
6930            "[&a !tag [x, y], *a, {z: []}]\n",
6931            "key: {\n&anchor\nname: value}\n",
6932            "---\n{[a, b]: c} # end\n...\n# next\n---\nx: y\n",
6933            "a: b\n[unterminated",
6934            &deep,
6935        ] {
6936            for limit in [0, 4, 1024, usize::MAX] {
6937                #[cfg(feature = "comments")]
6938                let emission_modes = [false, true].as_slice();
6939                #[cfg(not(feature = "comments"))]
6940                let emission_modes = [false].as_slice();
6941                for &emit_comments in emission_modes {
6942                    let options = crate::options! { simple_key_max_lookahead: limit };
6943                    #[cfg(feature = "comments")]
6944                    let options = {
6945                        let mut options = options;
6946                        options.emit_comments = emit_comments;
6947                        options
6948                    };
6949                    let mut scanner = Scanner::with_options(StrInput::new(source), options);
6950                    loop {
6951                        let result = scanner.next();
6952                        assert_eq!(
6953                            scanner.first_simple_key,
6954                            scanner.simple_keys.iter().position(|key| key.possible),
6955                            "source: {source:?}, limit: {limit}, comments: {emit_comments}"
6956                        );
6957                        let mut previous = None;
6958                        for key in scanner.simple_keys.iter().filter(|key| key.possible) {
6959                            assert!(key.token_number >= scanner.tokens_parsed);
6960                            if let Some((index, token_number)) = previous {
6961                                assert!(key.mark.index() >= index);
6962                                assert!(key.token_number >= token_number);
6963                            }
6964                            previous = Some((key.mark.index(), key.token_number));
6965                        }
6966                        if result.is_none() {
6967                            break;
6968                        }
6969                    }
6970                }
6971            }
6972        }
6973    }
6974
6975    #[test]
6976    fn plain_scalar_rejects_dash_before_flow_indicator() {
6977        assert_eq!(
6978            first_scanner_error_kind("[-]\n"),
6979            ErrorKind::PlainScalarStartsWithDashFlowIndicator
6980        );
6981    }
6982
6983    #[test]
6984    fn explicit_key_rejects_tab_used_as_indentation() {
6985        assert_eq!(
6986            first_scanner_error_kind("?\n\tfoo\n"),
6987            ErrorKind::TabNotAllowed
6988        );
6989    }
6990
6991    #[test]
6992    fn flow_mapping_rejects_adjacent_collection_value_after_plain_key() {
6993        assert_eq!(
6994            first_scanner_error_kind("[a:[]]\n"),
6995            ErrorKind::FlowMappingValueAdjacentCollection
6996        );
6997    }
6998
6999    #[test]
7000    fn implicit_flow_mapping_colon_cannot_move_to_next_line() {
7001        assert_eq!(
7002            first_scanner_error_kind("[foo\n: bar]\n"),
7003            ErrorKind::InvalidColonPlacement
7004        );
7005    }
7006
7007    #[test]
7008    fn invalid_simple_key_token_positions_are_scan_errors() {
7009        for (tokens_parsed, token_number) in [(1, 0), (0, 1)] {
7010            let mut scanner = Scanner::new(StrInput::new(": value\n"));
7011            scanner.fetch_stream_start();
7012            scanner.tokens.clear();
7013            scanner.tokens_parsed = tokens_parsed;
7014
7015            let simple_key = scanner
7016                .simple_keys
7017                .last_mut()
7018                .expect("stream start should create a simple key slot");
7019            simple_key.possible = true;
7020            simple_key.token_number = token_number;
7021
7022            let error = scanner
7023                .fetch_value()
7024                .expect_err("invalid simple key position should be reported as a scan error");
7025            assert_eq!(error.kind(), &ErrorKind::InvalidSimpleKey);
7026            assert_eq!(error.marker(), &Marker::new(0, 1, 0));
7027        }
7028    }
7029
7030    #[test]
7031    fn issue14_alias_scanner_consumes_colon_as_name_character() {
7032        let mut scanner = Scanner::new(StrInput::new("*foo: bar\n"));
7033
7034        assert!(matches!(
7035            scanner.next_token().unwrap().unwrap().1,
7036            TokenType::StreamStart
7037        ));
7038
7039        let token = scanner.next_token().unwrap().unwrap();
7040
7041        assert!(
7042            matches!(token.1, TokenType::Alias { ref name } if name.as_ref() == "foo:"),
7043            "expected `*foo: bar` to start with Alias(\"foo:\"), got {token:?}"
7044        );
7045    }
7046
7047    #[test]
7048    fn issue14_anchor_scanner_consumes_colon_as_name_character() {
7049        let mut scanner = Scanner::new(StrInput::new("&foo: bar\n"));
7050
7051        assert!(matches!(
7052            scanner.next_token().unwrap().unwrap().1,
7053            TokenType::StreamStart
7054        ));
7055
7056        let token = scanner.next_token().unwrap().unwrap();
7057
7058        assert!(
7059            matches!(token.1, TokenType::Anchor { ref name } if name.as_ref() == "foo:"),
7060            "expected `&foo: bar` to start with Anchor(\"foo:\"), got {token:?}"
7061        );
7062    }
7063}