beancount_parser/
error.rs

1#![allow(clippy::module_name_repetitions)]
2
3use std::fmt::Debug;
4
5#[cfg(feature = "miette")]
6use miette::{Diagnostic, SourceSpan};
7use thiserror::Error;
8
9use crate::Span;
10
11/// Error returned in case of invalid beancount syntax found
12///
13/// # Example
14/// ```
15/// # use beancount_parser::BeancountFile;
16/// let result: Result<BeancountFile<f64>, beancount_parser::Error> = "2022-05-21 oops".parse();
17/// assert!(result.is_err());
18/// let error = result.unwrap_err();
19/// assert_eq!(error.line_number(), 1);
20/// ```
21#[derive(Clone, Error)]
22#[cfg_attr(feature = "miette", derive(Diagnostic))]
23#[error("Invalid beancount syntax at line: {line_number}")]
24pub struct Error {
25    #[cfg(feature = "miette")]
26    #[source_code]
27    src: String,
28    #[cfg(feature = "miette")]
29    #[label]
30    span: SourceSpan,
31    line_number: u32,
32}
33
34impl Debug for Error {
35    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36        f.debug_struct("Error")
37            .field("line_number", &self.line_number())
38            .finish()
39    }
40}
41
42impl Error {
43    #[cfg(not(feature = "miette"))]
44    pub(crate) fn new(_: impl Into<String>, span: Span<'_>) -> Self {
45        Self {
46            line_number: span.location_line(),
47        }
48    }
49
50    #[cfg(feature = "miette")]
51    pub(crate) fn new(src: impl Into<String>, span: Span<'_>) -> Self {
52        Self {
53            src: src.into(),
54            span: span.location_offset().into(),
55            line_number: span.location_line(),
56        }
57    }
58
59    /// Line number at which the error was found in the input
60    #[must_use]
61    pub fn line_number(&self) -> u32 {
62        self.line_number
63    }
64}
65
66/// Error returned when reading a beancount file from disk
67#[allow(missing_docs)]
68#[derive(Debug, Error)]
69#[cfg_attr(feature = "miette", derive(Diagnostic))]
70pub enum ReadFileError {
71    #[error("IO error")]
72    Io(#[from] std::io::Error),
73    #[error("Syntax error")]
74    Syntax(#[from] Error),
75}
76
77/// Error that may be returned by the various `TryFrom`/`TryInto` implementation
78/// to signify that the value cannot be converted to the desired type
79#[derive(Debug, Clone, Error)]
80#[non_exhaustive]
81#[error("Cannot convert to the desired type")]
82pub struct ConversionError;