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