Skip to main content

granit_parser/
error.rs

1//! Parser and scanner error types.
2
3#[cfg(feature = "std")]
4use alloc::sync::Arc;
5use alloc::{
6    string::{String, ToString},
7    vec::Vec,
8};
9use core::fmt;
10
11use crate::scanner::Marker;
12
13/// Details of an I/O failure reported by an input adapter.
14///
15/// This error is primarily intended for terminal failures such as a missing file, insufficient
16/// permissions, or a failed read, where an exact character position is usually not meaningful.
17/// Streaming inputs may be read ahead by a small lookahead window. Once an adapter reports an I/O
18/// failure, the parser reports it at its current marker; consequently, a few successfully read
19/// characters that were already buffered ahead of that marker may not be scanned or emitted.
20///
21/// The human-readable message is available in every build. With the `std` feature enabled, an
22/// instance constructed from `std::io::Error` also retains that original error and exposes it
23/// through `InputIoError::io_error` and the standard error source chain.
24///
25/// Equality and hashing use the portable message. The optional retained `std` error does not
26/// participate, so these operations have the same behavior with and without the `std` feature.
27#[derive(Clone, Debug)]
28pub struct InputIoError {
29    message: String,
30    #[cfg(feature = "std")]
31    source: Option<Arc<std::io::Error>>,
32}
33
34impl InputIoError {
35    /// Create I/O error details from a portable message.
36    ///
37    /// This constructor is available in `no_std` builds. It does not retain a typed source error.
38    #[must_use]
39    pub fn from_message(message: impl Into<String>) -> Self {
40        Self {
41            message: message.into(),
42            #[cfg(feature = "std")]
43            source: None,
44        }
45    }
46
47    /// Create I/O error details while retaining the original [`std::io::Error`].
48    #[cfg(feature = "std")]
49    #[must_use]
50    pub fn from_io(error: std::io::Error) -> Self {
51        Self {
52            message: error.to_string(),
53            source: Some(Arc::new(error)),
54        }
55    }
56
57    /// Return the portable human-readable error message.
58    #[must_use]
59    pub fn message(&self) -> &str {
60        &self.message
61    }
62
63    /// Return the retained [`std::io::Error`], when one is available.
64    #[cfg(feature = "std")]
65    #[must_use]
66    pub fn io_error(&self) -> Option<&std::io::Error> {
67        self.source.as_deref()
68    }
69
70    /// Recover the retained [`std::io::Error`] when this is its only owner.
71    ///
72    /// # Errors
73    /// Returns the original `InputIoError` when it was created from a portable message or when
74    /// another clone still shares the retained error.
75    #[cfg(feature = "std")]
76    pub fn try_into_io_error(self) -> Result<std::io::Error, Self> {
77        let Self { message, source } = self;
78        let Some(source) = source else {
79            return Err(Self {
80                message,
81                source: None,
82            });
83        };
84
85        match Arc::try_unwrap(source) {
86            Ok(error) => Ok(error),
87            Err(source) => Err(Self {
88                message,
89                source: Some(source),
90            }),
91        }
92    }
93}
94
95#[cfg(feature = "std")]
96impl From<std::io::Error> for InputIoError {
97    fn from(error: std::io::Error) -> Self {
98        Self::from_io(error)
99    }
100}
101
102impl PartialEq for InputIoError {
103    fn eq(&self, other: &Self) -> bool {
104        self.message == other.message
105    }
106}
107
108impl Eq for InputIoError {}
109
110impl core::hash::Hash for InputIoError {
111    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
112        core::hash::Hash::hash(&self.message, state);
113    }
114}
115
116impl fmt::Display for InputIoError {
117    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118        f.write_str(&self.message)
119    }
120}
121
122impl core::error::Error for InputIoError {
123    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
124        #[cfg(feature = "std")]
125        {
126            self.source
127                .as_deref()
128                .map(|error| error as &(dyn core::error::Error + 'static))
129        }
130
131        #[cfg(not(feature = "std"))]
132        {
133            None
134        }
135    }
136}
137
138/// Machine-readable category for a [`ScanError`].
139#[derive(Clone, PartialEq, Debug, Eq, Hash)]
140#[non_exhaustive]
141pub enum ErrorKind {
142    /// Too many comments were buffered while looking ahead to a collection entry or document.
143    #[cfg(feature = "comments")]
144    TooManyComments,
145    /// Reading from the input source failed.
146    InputIo {
147        /// Portable details and, with the `std` feature, an optional retained I/O error.
148        error: InputIoError,
149    },
150    /// The input source was not valid text in the adapter's expected encoding.
151    InputDecoding {
152        /// Human-readable details supplied by the input adapter.
153        message: String,
154    },
155    /// The raw input exceeded a configured byte limit.
156    InputByteLimitExceeded {
157        /// Maximum number of raw input bytes accepted by the adapter.
158        limit: usize,
159    },
160    /// Input ended while parsing a flow sequence.
161    UnexpectedEofFlowSequence,
162    /// Input ended while parsing a flow mapping.
163    UnexpectedEofFlowMapping,
164    /// Input ended while parsing an implicit flow mapping.
165    UnexpectedEofImplicitFlowMapping,
166    /// Input ended while parsing a block sequence.
167    UnexpectedEofBlockSequence,
168    /// Input ended while parsing a block mapping.
169    UnexpectedEofBlockMapping,
170    /// Input ended unexpectedly in another parser state.
171    UnexpectedEof,
172    /// A stream-start token was expected.
173    ExpectedStreamStart,
174    /// More than one YAML version directive was found for a document.
175    DuplicateVersionDirective,
176    /// The YAML major version is unsupported.
177    UnsupportedYamlMajorVersion,
178    /// A tag directive handle was declared more than once for a document.
179    DuplicateTagDirective,
180    /// A document-start token was expected.
181    ExpectedDocumentStart,
182    /// A directive followed an implicit document without an explicit document end.
183    MissingDocumentEndBeforeDirective,
184    /// The parser ran out of representable anchor identifiers.
185    AnchorCountOverflow,
186    /// An anchor definition or alias from a primed parser used an ID reserved by the stack.
187    AnchorIdCollision {
188        /// The ID defined or referenced by the event.
189        anchor_id: usize,
190        /// The stack's next available anchor ID when the parser was pushed.
191        first_free_id: usize,
192    },
193    /// An alias referred to an unknown anchor.
194    UnknownAnchor,
195    /// The parser did not find expected node content.
196    ExpectedNodeContent,
197    /// A block mapping key was expected.
198    ExpectedBlockMappingKey,
199    /// A flow mapping separator or closing brace was expected.
200    ExpectedFlowMappingSeparator,
201    /// A flow sequence separator or closing bracket was expected.
202    ExpectedFlowSequenceSeparator,
203    /// A block sequence entry indicator was expected.
204    ExpectedBlockSequenceEntry,
205    /// A tag used a handle that was not declared.
206    UndeclaredTagHandle,
207    /// No include resolver was configured for a parser stack.
208    MissingIncludeResolver,
209    /// An error supplied by an external parser adapter or resolver.
210    Custom(String),
211    /// A parser-stack entry contained multiple documents where only one is supported.
212    MultipleDocumentsUnsupported,
213    /// An input advertised byte offsets but did not provide the requested slice.
214    InputOffsetsWithoutSlice,
215    /// An input advertised slicing but did not provide the requested slice.
216    InputSlicingUnavailable,
217    /// A tag did not begin with the expected exclamation mark.
218    ExpectedTagBang,
219    /// A tag directive handle did not end with the expected exclamation mark.
220    ExpectedTagDirectiveBang,
221    /// A global tag started with an invalid character.
222    InvalidGlobalTagCharacter,
223    /// A required simple key was not followed by a value indicator.
224    SimpleKeyExpected,
225    /// A previously saved simple key was no longer valid.
226    InvalidSimpleKey,
227    /// Invalid content followed a document-end marker.
228    InvalidDocumentEnd,
229    /// Indentation was invalid for the current parser context.
230    InvalidIndentation,
231    /// A byte-order mark appeared inside a document.
232    BomInsideDocument,
233    /// An unexpected reserved character was encountered.
234    UnexpectedCharacter {
235        /// The character that was encountered.
236        character: char,
237    },
238    /// A tab was used in a context where it is not allowed.
239    TabNotAllowed,
240    /// A tab was used in block indentation.
241    TabInBlockIndentation,
242    /// A comment interrupted a multiline plain scalar.
243    CommentInterceptedScalar,
244    /// Required whitespace was not found.
245    ExpectedWhitespace,
246    /// A comment was not separated from the preceding token by whitespace.
247    CommentNotSeparated,
248    /// A directive did not end with a comment or line break.
249    InvalidDirectiveTerminator,
250    /// A directive was encountered while [`crate::Options::disallow_directives`] was enabled.
251    DirectiveDisallowed,
252    /// A YAML version directive did not contain the expected digit or dot.
253    MissingYamlVersionSeparator,
254    /// A directive name was missing.
255    MissingDirectiveName,
256    /// A directive name contained an invalid character.
257    InvalidDirectiveName,
258    /// A retained directive name and payload exceeded the configured byte limit.
259    DirectiveByteLimitExceeded {
260        /// Maximum number of directive bytes accepted by the scanner.
261        limit: usize,
262    },
263    /// A reserved directive carried more parameters than the configured limit.
264    TooManyReservedDirectiveParams {
265        /// Maximum number of reserved directive parameters accepted by the scanner.
266        limit: usize,
267    },
268    /// A YAML version component exceeded the supported length.
269    YamlVersionTooLong,
270    /// A YAML version component was missing.
271    MissingYamlVersion,
272    /// A tag directive did not end with whitespace or a line break.
273    InvalidTagDirectiveTerminator,
274    /// A tag token did not end with valid separation whitespace.
275    InvalidTagTerminator,
276    /// A tag URI was missing.
277    MissingTagUri,
278    /// A verbatim tag was missing its closing angle bracket.
279    UnclosedVerbatimTag,
280    /// A tag contained an invalid percent escape.
281    InvalidTagEscape,
282    /// A tag escape started with an invalid UTF-8 byte.
283    InvalidTagUtf8LeadingByte,
284    /// A tag escape contained an invalid trailing UTF-8 byte.
285    InvalidTagUtf8TrailingByte,
286    /// A tag escape did not decode to one valid Unicode scalar value.
287    InvalidTagUtf8,
288    /// An anchor or alias name was missing.
289    MissingAnchorOrAliasName,
290    /// A flow collection closing bracket was misplaced.
291    MisplacedFlowCollectionEnd,
292    /// A flow collection was closed with the wrong bracket type.
293    MismatchedFlowCollectionEnd {
294        /// The bracket that opened the flow collection.
295        open: char,
296        /// The bracket that closed the flow collection.
297        close: char,
298    },
299    /// A flow collection was not closed.
300    UnclosedFlowCollection {
301        /// The bracket that opened the flow collection.
302        open: char,
303    },
304    /// A configured flow or block collection nesting limit was exceeded.
305    RecursionLimitExceeded,
306    /// A block entry indicator appeared inside a flow collection.
307    BlockEntryInFlowCollection,
308    /// A block sequence entry appeared in a context that does not allow it.
309    BlockSequenceEntryNotAllowed,
310    /// A block entry indicator was followed by invalid whitespace.
311    InvalidBlockEntryWhitespace,
312    /// A block scalar used an indentation indicator of zero.
313    ZeroBlockScalarIndent,
314    /// A block scalar header did not end with a comment or line break.
315    InvalidBlockScalarHeader,
316    /// A tab appeared where a block scalar line needed space indentation.
317    TabAtBlockScalarStart,
318    /// A block scalar content line had invalid indentation.
319    InvalidBlockScalarIndent,
320    /// A document indicator appeared inside a quoted scalar.
321    DocumentIndicatorInQuotedScalar,
322    /// A quoted scalar was not closed.
323    UnclosedQuotedScalar,
324    /// A tab was used as indentation.
325    TabInIndentation,
326    /// A multiline quoted scalar had invalid indentation.
327    InvalidQuotedScalarIndent,
328    /// Invalid content followed a single-quoted scalar.
329    InvalidTrailingSingleQuotedScalar,
330    /// Invalid content followed a double-quoted scalar.
331    InvalidTrailingDoubleQuotedScalar,
332    /// A quoted scalar contained an unknown escape character.
333    UnknownQuotedScalarEscape,
334    /// A quoted scalar escape did not contain the expected hexadecimal digits.
335    InvalidQuotedScalarHexEscape,
336    /// A low-surrogate escape did not contain the expected hexadecimal digits.
337    InvalidLowSurrogateHexEscape,
338    /// A surrogate pair contained an invalid low surrogate.
339    InvalidLowSurrogate,
340    /// A high surrogate was not followed by a low surrogate.
341    MissingLowSurrogate,
342    /// A low surrogate appeared without a preceding high surrogate.
343    UnpairedLowSurrogate,
344    /// A quoted scalar escape did not represent a valid Unicode scalar value.
345    InvalidUnicodeEscape,
346    /// A flow scalar started at invalid indentation.
347    InvalidFlowScalarIndent,
348    /// A plain scalar began with a dash followed by a flow indicator.
349    PlainScalarStartsWithDashFlowIndicator,
350    /// A tab appeared where a plain scalar could not accept it.
351    TabInPlainScalar,
352    /// A plain scalar ended before consuming any content.
353    UnexpectedEndOfPlainScalar,
354    /// A mapping key appeared in a context that does not allow one.
355    MappingKeyNotAllowed,
356    /// A flow mapping value indicator was adjacent to a collection start.
357    FlowMappingValueAdjacentCollection,
358    /// A mapping value indicator was followed by invalid whitespace.
359    InvalidMappingValueWhitespace,
360    /// A value indicator was placed illegally in an implicit flow mapping.
361    InvalidColonPlacement,
362    /// A mapping value appeared in a context that does not allow one.
363    MappingValueNotAllowed,
364}
365
366#[cfg(feature = "error_messages")]
367impl fmt::Display for ErrorKind {
368    #[allow(clippy::too_many_lines)]
369    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
370        match self {
371            #[cfg(feature = "comments")]
372            Self::TooManyComments => {
373                f.write_str("too many buffered comments while looking ahead")
374            }
375            Self::InputIo { error } => write!(f, "input I/O error: {error}"),
376            Self::InputDecoding { message } => {
377                write!(f, "input decoding error: {message}")
378            }
379            Self::InputByteLimitExceeded { limit } => {
380                write!(f, "input exceeds the configured limit of {limit} bytes")
381            }
382            Self::UnexpectedEofFlowSequence => {
383                f.write_str("unexpected EOF while parsing a flow sequence")
384            }
385            Self::UnexpectedEofFlowMapping => {
386                f.write_str("unexpected EOF while parsing a flow mapping")
387            }
388            Self::UnexpectedEofImplicitFlowMapping => {
389                f.write_str("unexpected EOF while parsing an implicit flow mapping")
390            }
391            Self::UnexpectedEofBlockSequence => {
392                f.write_str("unexpected EOF while parsing a block sequence")
393            }
394            Self::UnexpectedEofBlockMapping => {
395                f.write_str("unexpected EOF while parsing a block mapping")
396            }
397            Self::UnexpectedEof => f.write_str("unexpected eof"),
398            Self::ExpectedStreamStart => f.write_str("did not find expected <stream-start>"),
399            Self::DuplicateVersionDirective => f.write_str("duplicate version directive"),
400            Self::UnsupportedYamlMajorVersion => {
401                f.write_str("unsupported YAML major version")
402            }
403            Self::DuplicateTagDirective => f.write_str(
404                "the TAG directive must only be given at most once per handle in the same document",
405            ),
406            Self::ExpectedDocumentStart => {
407                f.write_str("did not find expected <document start>")
408            }
409            Self::MissingDocumentEndBeforeDirective => {
410                f.write_str("missing explicit document end marker before directive")
411            }
412            Self::AnchorCountOverflow => {
413                f.write_str("while parsing anchor, anchor count exceeded supported limit")
414            }
415            Self::AnchorIdCollision {
416                anchor_id,
417                first_free_id,
418            } => write!(
419                f,
420                "anchor ID {anchor_id} is below the stack's first free ID {first_free_id}. \
421                 Seed the child parser with the stack's anchor offset before reading from it"
422            ),
423            Self::UnknownAnchor => f.write_str("while parsing node, found unknown anchor"),
424            Self::ExpectedNodeContent => {
425                f.write_str("while parsing a node, did not find expected node content")
426            }
427            Self::ExpectedBlockMappingKey => {
428                f.write_str("while parsing a block mapping, did not find expected key")
429            }
430            Self::ExpectedFlowMappingSeparator => {
431                f.write_str("while parsing a flow mapping, did not find expected ',' or '}'")
432            }
433            Self::ExpectedFlowSequenceSeparator => {
434                f.write_str("while parsing a flow sequence, expected ',' or ']'")
435            }
436            Self::ExpectedBlockSequenceEntry => f.write_str(
437                "while parsing a block collection, did not find expected '-' indicator",
438            ),
439            Self::UndeclaredTagHandle => f.write_str("the handle wasn't declared"),
440            Self::MissingIncludeResolver => {
441                f.write_str("No include resolver set for parser stack.")
442            }
443            Self::Custom(message) => f.write_str(message),
444            Self::MultipleDocumentsUnsupported => {
445                f.write_str("multiple documents not supported here")
446            }
447            Self::InputOffsetsWithoutSlice => f.write_str(
448                "internal error: input advertised offsets but did not provide a slice",
449            ),
450            Self::InputSlicingUnavailable => f.write_str(
451                "internal error: input advertised slicing but did not provide a slice",
452            ),
453            Self::ExpectedTagBang => {
454                f.write_str("while scanning a tag, did not find expected '!'")
455            }
456            Self::ExpectedTagDirectiveBang => {
457                f.write_str("while parsing a tag directive, did not find expected '!'")
458            }
459            Self::InvalidGlobalTagCharacter => f.write_str("invalid global tag character"),
460            Self::SimpleKeyExpected => f.write_str("simple key expected ':'"),
461            Self::InvalidSimpleKey => f.write_str("simple key is no longer valid"),
462            Self::InvalidDocumentEnd => {
463                f.write_str("invalid content after document end marker")
464            }
465            Self::InvalidIndentation => f.write_str("invalid indentation"),
466            Self::BomInsideDocument => {
467                f.write_str("a BOM must not appear inside a document")
468            }
469            Self::UnexpectedCharacter { character } => {
470                write!(f, "unexpected character: `{}'", character.escape_default())
471            }
472            Self::TabNotAllowed => f.write_str("tabs disallowed in this context"),
473            Self::TabInBlockIndentation => {
474                f.write_str("tabs disallowed within this context (block indentation)")
475            }
476            Self::CommentInterceptedScalar => {
477                f.write_str("comment intercepting the multiline text")
478            }
479            Self::ExpectedWhitespace => f.write_str("expected whitespace"),
480            Self::CommentNotSeparated => {
481                f.write_str("comments must be separated from other tokens by whitespace")
482            }
483            Self::InvalidDirectiveTerminator => f.write_str(
484                "while scanning a directive, did not find expected comment or line break",
485            ),
486            Self::DirectiveDisallowed => f.write_str("YAML directives are disallowed"),
487            Self::MissingYamlVersionSeparator => f.write_str(
488                "while scanning a YAML directive, did not find expected digit or '.' character",
489            ),
490            Self::MissingDirectiveName => f.write_str(
491                "while scanning a directive, could not find expected directive name",
492            ),
493            Self::InvalidDirectiveName => f.write_str(
494                "while scanning a directive, found unexpected non-alphabetical character",
495            ),
496            Self::DirectiveByteLimitExceeded { limit } => write!(
497                f,
498                "directive exceeds the configured limit of {limit} bytes"
499            ),
500            Self::TooManyReservedDirectiveParams { limit } => write!(
501                f,
502                "reserved directive exceeds the configured limit of {limit} parameters"
503            ),
504            Self::YamlVersionTooLong => {
505                f.write_str("while scanning a YAML directive, found extremely long version number")
506            }
507            Self::MissingYamlVersion => f.write_str(
508                "while scanning a YAML directive, did not find expected version number",
509            ),
510            Self::InvalidTagDirectiveTerminator => {
511                f.write_str("while scanning TAG, did not find expected whitespace or line break")
512            }
513            Self::InvalidTagTerminator => f.write_str(
514                "while scanning a tag, did not find expected whitespace or line break",
515            ),
516            Self::MissingTagUri => {
517                f.write_str("while parsing a tag, did not find expected tag URI")
518            }
519            Self::UnclosedVerbatimTag => {
520                f.write_str("while scanning a verbatim tag, did not find the expected '>'")
521            }
522            Self::InvalidTagEscape => {
523                f.write_str("while parsing a tag, found an invalid escape sequence")
524            }
525            Self::InvalidTagUtf8LeadingByte => {
526                f.write_str("while parsing a tag, found an incorrect leading UTF-8 byte")
527            }
528            Self::InvalidTagUtf8TrailingByte => {
529                f.write_str("while parsing a tag, found an incorrect trailing UTF-8 byte")
530            }
531            Self::InvalidTagUtf8 => {
532                f.write_str("while parsing a tag, found an invalid UTF-8 codepoint")
533            }
534            Self::MissingAnchorOrAliasName => f.write_str(
535                "while scanning an anchor or alias, did not find expected alphabetic or numeric character",
536            ),
537            Self::MisplacedFlowCollectionEnd => f.write_str("misplaced bracket"),
538            Self::MismatchedFlowCollectionEnd { open, close } => {
539                write!(f, "mismatched bracket '{open}' closed by '{close}'")
540            }
541            Self::UnclosedFlowCollection { open } => {
542                write!(f, "unclosed bracket '{open}'")
543            }
544            Self::RecursionLimitExceeded => f.write_str("recursion limit exceeded"),
545            Self::BlockEntryInFlowCollection => {
546                f.write_str(r#""-" is only valid inside a block"#)
547            }
548            Self::BlockSequenceEntryNotAllowed => {
549                f.write_str("block sequence entries are not allowed in this context")
550            }
551            Self::InvalidBlockEntryWhitespace => {
552                f.write_str("'-' must be followed by a valid YAML whitespace")
553            }
554            Self::ZeroBlockScalarIndent => f.write_str(
555                "while scanning a block scalar, found an indentation indicator equal to 0",
556            ),
557            Self::InvalidBlockScalarHeader => f.write_str(
558                "while scanning a block scalar, did not find expected comment or line break",
559            ),
560            Self::TabAtBlockScalarStart => {
561                f.write_str("a tab cannot be used to indent a block scalar line")
562            }
563            Self::InvalidBlockScalarIndent => {
564                f.write_str("wrongly indented line in block scalar")
565            }
566            Self::DocumentIndicatorInQuotedScalar => f.write_str(
567                "while scanning a quoted scalar, found unexpected document indicator",
568            ),
569            Self::UnclosedQuotedScalar => f.write_str("unclosed quote"),
570            Self::TabInIndentation => f.write_str("tab cannot be used as indentation"),
571            Self::InvalidQuotedScalarIndent => {
572                f.write_str("invalid indentation in multiline quoted scalar")
573            }
574            Self::InvalidTrailingSingleQuotedScalar => {
575                f.write_str("invalid trailing content after single-quoted scalar")
576            }
577            Self::InvalidTrailingDoubleQuotedScalar => {
578                f.write_str("invalid trailing content after double-quoted scalar")
579            }
580            Self::UnknownQuotedScalarEscape => {
581                f.write_str("while parsing a quoted scalar, found unknown escape character")
582            }
583            Self::InvalidQuotedScalarHexEscape => f.write_str(
584                "while parsing a quoted scalar, did not find expected hexadecimal number",
585            ),
586            Self::InvalidLowSurrogateHexEscape => f.write_str(
587                "while parsing a quoted scalar, did not find expected hexadecimal number for low surrogate",
588            ),
589            Self::InvalidLowSurrogate => {
590                f.write_str("while parsing a quoted scalar, found invalid low surrogate")
591            }
592            Self::MissingLowSurrogate => f.write_str(
593                "while parsing a quoted scalar, found high surrogate without following low surrogate",
594            ),
595            Self::UnpairedLowSurrogate => {
596                f.write_str("while parsing a quoted scalar, found unpaired low surrogate")
597            }
598            Self::InvalidUnicodeEscape => f.write_str(
599                "while parsing a quoted scalar, found invalid Unicode character escape code",
600            ),
601            Self::InvalidFlowScalarIndent => {
602                f.write_str("invalid indentation in flow construct")
603            }
604            Self::PlainScalarStartsWithDashFlowIndicator => {
605                f.write_str("plain scalar cannot start with '-' followed by ,[]{}")
606            }
607            Self::TabInPlainScalar => {
608                f.write_str("while scanning a plain scalar, found a tab")
609            }
610            Self::UnexpectedEndOfPlainScalar => f.write_str("unexpected end of plain scalar"),
611            Self::MappingKeyNotAllowed => {
612                f.write_str("mapping keys are not allowed in this context")
613            }
614            Self::FlowMappingValueAdjacentCollection => {
615                f.write_str("':' may not precede any of `[{` in flow mapping")
616            }
617            Self::InvalidMappingValueWhitespace => {
618                f.write_str("':' must be followed by a valid YAML whitespace")
619            }
620            Self::InvalidColonPlacement => f.write_str("illegal placement of ':' indicator"),
621            Self::MappingValueNotAllowed => {
622                f.write_str("mapping values are not allowed in this context")
623            }
624        }
625    }
626}
627
628#[cfg(not(feature = "error_messages"))]
629impl fmt::Display for ErrorKind {
630    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
631        f.write_str("")
632    }
633}
634
635/// An error that occurred while reading, scanning, or parsing YAML.
636#[derive(Clone, PartialEq, Debug, Eq)]
637pub struct ScanError {
638    /// The position at which the error happened in the source.
639    mark: Marker,
640    /// Machine-readable error category.
641    kind: ErrorKind,
642    /// Source names captured by a parser stack before its failing entry is removed.
643    source_stack: Vec<String>,
644}
645
646impl ScanError {
647    /// Create an externally supplied error from a location and message.
648    ///
649    /// The message is stored in [`ErrorKind::Custom`]. This is useful for adapters that
650    /// participate in parser APIs, such as a custom [`ParserTrait`](crate::ParserTrait)
651    /// implementation or a [`ParserStack`](crate::ParserStack) include resolver.
652    #[must_use]
653    #[cold]
654    pub fn new(loc: Marker, message: impl Into<String>) -> ScanError {
655        Self::from_kind(loc, ErrorKind::Custom(message.into()))
656    }
657
658    #[must_use]
659    #[cold]
660    pub(crate) fn from_kind(loc: Marker, kind: ErrorKind) -> ScanError {
661        ScanError {
662            mark: loc,
663            kind,
664            source_stack: Vec::new(),
665        }
666    }
667
668    #[must_use]
669    pub(crate) fn with_source_stack(mut self, source_stack: Vec<String>) -> Self {
670        self.source_stack = source_stack;
671        self
672    }
673
674    #[cold]
675    pub(crate) fn into_result<T>(self) -> Result<T, ScanError> {
676        Err(self)
677    }
678
679    /// Return the marker pointing to the error in the source.
680    #[must_use]
681    pub fn marker(&self) -> &Marker {
682        &self.mark
683    }
684
685    /// Return the machine-readable error category.
686    #[must_use]
687    pub fn kind(&self) -> &ErrorKind {
688        &self.kind
689    }
690
691    /// Extract the input I/O error details without cloning them.
692    ///
693    /// # Errors
694    /// Returns the original scan error unchanged when it has a different error category.
695    pub fn try_into_input_io_error(self) -> Result<InputIoError, Self> {
696        let Self {
697            mark,
698            kind,
699            source_stack,
700        } = self;
701
702        match kind {
703            ErrorKind::InputIo { error } => Ok(error),
704            kind => Err(Self {
705                mark,
706                kind,
707                source_stack,
708            }),
709        }
710    }
711
712    /// Return source names captured by a parser stack, from bottom to top.
713    #[must_use]
714    pub fn source_stack(&self) -> &[String] {
715        &self.source_stack
716    }
717
718    /// Render the error as a human-readable description.
719    ///
720    /// Parser-stack errors include their nested source names. The result remains
721    /// empty when the `error_messages` feature is disabled.
722    #[must_use]
723    pub fn info(&self) -> String {
724        let mut info = self.kind.to_string();
725        if !info.is_empty() && self.source_stack().len() > 1 {
726            info.push_str("\nwhile parsing ");
727            info.push_str(&self.source_stack().join(" -> "));
728        }
729        info
730    }
731}
732
733impl fmt::Display for ScanError {
734    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
735        write!(
736            f,
737            "{} at char {} line {} column {}",
738            self.info(),
739            self.mark.index(),
740            self.mark.line(),
741            self.mark.col() + 1
742        )
743    }
744}
745
746impl core::error::Error for ScanError {
747    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
748        match &self.kind {
749            ErrorKind::InputIo { error } => Some(error),
750            _ => None,
751        }
752    }
753}
754
755#[cfg(test)]
756mod tests {
757    #[cfg(feature = "error_messages")]
758    use alloc::format;
759    #[cfg(feature = "error_messages")]
760    use alloc::string::String;
761    use alloc::string::ToString;
762
763    use super::{ErrorKind, InputIoError, ScanError};
764    use crate::scanner::Marker;
765
766    #[cfg(feature = "error_messages")]
767    #[test]
768    fn constructor_retains_kind_and_derives_info() {
769        let marker = Marker::new(3, 2, 1);
770        let error = ScanError::from_kind(marker, ErrorKind::ExpectedWhitespace);
771
772        assert_eq!(error.kind(), &ErrorKind::ExpectedWhitespace);
773        assert_eq!(error.kind().to_string(), "expected whitespace");
774        assert_eq!(error.info(), "expected whitespace");
775    }
776
777    #[cfg(feature = "error_messages")]
778    #[test]
779    fn parameterized_kind_constructs_info() {
780        let marker = Marker::new(3, 2, 1);
781        let error = ScanError::from_kind(
782            marker,
783            ErrorKind::MismatchedFlowCollectionEnd {
784                open: '[',
785                close: '}',
786            },
787        );
788
789        assert_eq!(error.info(), "mismatched bracket '[' closed by '}'");
790        assert_eq!(
791            format!("{error}"),
792            "mismatched bracket '[' closed by '}' at char 3 line 2 column 2"
793        );
794    }
795
796    #[cfg(feature = "error_messages")]
797    #[test]
798    fn input_error_kinds_construct_info() {
799        assert_eq!(
800            ErrorKind::InputIo {
801                error: InputIoError::from_message("connection reset")
802            }
803            .to_string(),
804            "input I/O error: connection reset"
805        );
806        assert_eq!(
807            ErrorKind::InputDecoding {
808                message: String::from("invalid utf-8")
809            }
810            .to_string(),
811            "input decoding error: invalid utf-8"
812        );
813        assert_eq!(
814            ErrorKind::InputByteLimitExceeded { limit: 4096 }.to_string(),
815            "input exceeds the configured limit of 4096 bytes"
816        );
817    }
818
819    #[test]
820    fn message_only_input_io_error_has_no_source() {
821        use core::error::Error as _;
822
823        let error = InputIoError::from_message("portable failure");
824
825        assert_eq!(error.message(), "portable failure");
826        assert!(error.source().is_none());
827    }
828
829    #[cfg(feature = "std")]
830    #[test]
831    fn std_input_io_error_is_retained_in_scan_error_source_chain() {
832        use core::error::Error as _;
833        use std::io;
834
835        let details = InputIoError::from(io::Error::new(io::ErrorKind::BrokenPipe, "pipe closed"));
836        assert_eq!(details.message(), "pipe closed");
837        assert_eq!(
838            details
839                .io_error()
840                .expect("std construction should retain io::Error")
841                .kind(),
842            io::ErrorKind::BrokenPipe
843        );
844
845        let error = ScanError::from_kind(
846            Marker::new(3, 2, 1),
847            ErrorKind::InputIo {
848                error: details.clone(),
849            },
850        );
851        let input_error = error
852            .source()
853            .and_then(|source| source.downcast_ref::<InputIoError>())
854            .expect("ScanError should expose InputIoError as its source");
855        let io_error = input_error
856            .source()
857            .and_then(|source| source.downcast_ref::<io::Error>())
858            .expect("InputIoError should expose the retained io::Error");
859
860        assert_eq!(io_error.kind(), io::ErrorKind::BrokenPipe);
861        assert_eq!(details, *input_error);
862    }
863
864    #[cfg(feature = "std")]
865    #[test]
866    fn unique_std_input_io_error_can_be_recovered() {
867        use std::io;
868
869        let details = InputIoError::from(io::Error::from_raw_os_error(12_345));
870        let error = details
871            .try_into_io_error()
872            .expect("a uniquely owned io::Error should be recoverable");
873
874        assert_eq!(error.raw_os_error(), Some(12_345));
875    }
876
877    #[cfg(feature = "std")]
878    #[test]
879    fn shared_std_input_io_error_can_be_recovered_after_other_clone_is_dropped() {
880        use std::io;
881
882        let details = InputIoError::from(io::Error::from_raw_os_error(12_345));
883        let other = details.clone();
884        let details = details
885            .try_into_io_error()
886            .expect_err("a shared io::Error cannot be moved out");
887
888        drop(other);
889
890        let error = details
891            .try_into_io_error()
892            .expect("the last owner should recover the io::Error");
893        assert_eq!(error.raw_os_error(), Some(12_345));
894    }
895
896    #[cfg(feature = "std")]
897    #[test]
898    fn scan_error_moves_input_io_error_out_without_cloning() {
899        use std::io;
900
901        let error = ScanError::from_kind(
902            Marker::new(3, 2, 1),
903            ErrorKind::InputIo {
904                error: InputIoError::from(io::Error::from_raw_os_error(12_345)),
905            },
906        );
907        let details = error
908            .try_into_input_io_error()
909            .expect("input I/O details should be extractable");
910        let error = details
911            .try_into_io_error()
912            .expect("extracting the scan error should retain unique ownership");
913
914        assert_eq!(error.raw_os_error(), Some(12_345));
915    }
916
917    #[test]
918    fn extracting_input_io_error_preserves_other_scan_errors() {
919        let error = ScanError::from_kind(Marker::new(3, 2, 1), ErrorKind::ExpectedWhitespace);
920        let error = error
921            .try_into_input_io_error()
922            .expect_err("a non-I/O scan error should be returned unchanged");
923
924        assert_eq!(error.marker(), &Marker::new(3, 2, 1));
925        assert_eq!(error.kind(), &ErrorKind::ExpectedWhitespace);
926    }
927
928    #[cfg(feature = "error_messages")]
929    #[test]
930    fn public_constructor_copies_custom_message() {
931        let marker = Marker::new(3, 2, 1);
932        let mut message = String::from("adapter failed");
933        let error = ScanError::new(marker, &message);
934        message.clear();
935
936        assert_eq!(
937            error.kind(),
938            &ErrorKind::Custom(String::from("adapter failed"))
939        );
940        assert_eq!(error.info(), "adapter failed");
941    }
942
943    #[cfg(not(feature = "error_messages"))]
944    #[test]
945    fn disabled_error_messages_are_empty() {
946        let marker = Marker::new(3, 2, 1);
947        let error = ScanError::from_kind(
948            marker,
949            ErrorKind::MismatchedFlowCollectionEnd {
950                open: '[',
951                close: '}',
952            },
953        );
954
955        assert_eq!(error.kind().to_string(), "");
956        assert_eq!(error.info(), "");
957    }
958}