Skip to main content

brush_parser/
error.rs

1use crate::tokenizer;
2
3/// Represents an error that occurred while parsing tokens.
4#[derive(thiserror::Error, Debug)]
5#[non_exhaustive]
6pub enum ParseError {
7    /// A parsing error occurred near the given position.
8    #[error("syntax error at line {} col {}", .0.line, .0.column)]
9    ParsingNear(crate::SourcePosition),
10
11    /// A parsing error occurred at the end of the input.
12    #[error("syntax error at end of input")]
13    ParsingAtEndOfInput,
14
15    /// An error occurred while tokenizing the input stream.
16    #[error("{} (detected near {})", .inner, .position.as_ref().map_or_else(|| String::from("<unknown position>"), |p| std::format!("line {} col {}", p.line, p.column)))]
17    Tokenizing {
18        /// The inner error.
19        inner: tokenizer::TokenizerError,
20        /// Optionally provides the position of the error.
21        position: Option<crate::SourcePosition>,
22    },
23}
24
25#[cfg(feature = "diagnostics")]
26#[allow(clippy::cast_sign_loss)]
27#[allow(unused)] // Workaround unused warnings in nightly versions of the compiler
28pub mod miette {
29    use super::ParseError;
30    use miette::SourceOffset;
31
32    impl ParseError {
33        /// Convert the original error to one miette can pretty print
34        pub fn to_pretty_error(self, input: impl Into<String>) -> PrettyError {
35            let input = input.into();
36            let location = match self {
37                Self::ParsingNear(ref pos) => {
38                    Some(SourceOffset::from_location(&input, pos.line, pos.column))
39                }
40                Self::Tokenizing { ref position, .. } => position
41                    .as_ref()
42                    .map(|p| SourceOffset::from_location(&input, p.line, p.column)),
43                Self::ParsingAtEndOfInput => {
44                    Some(SourceOffset::from_location(&input, usize::MAX, usize::MAX))
45                }
46            };
47
48            PrettyError {
49                cause: self,
50                input,
51                location,
52            }
53        }
54    }
55
56    /// Represents an error that occurred while parsing tokens.
57    #[derive(thiserror::Error, Debug, miette::Diagnostic)]
58    #[error("Cannot parse the input script")]
59    pub struct PrettyError {
60        cause: ParseError,
61        #[source_code]
62        input: String,
63        #[label("{cause}")]
64        location: Option<SourceOffset>,
65    }
66}
67
68/// Represents a parsing error with its location information
69#[derive(Debug, thiserror::Error)]
70#[error(transparent)]
71pub struct ParseErrorLocation {
72    #[from]
73    inner: peg::error::ParseError<peg::str::LineCol>,
74}
75
76/// Represents an error that occurred while parsing a word.
77#[derive(Debug, thiserror::Error)]
78#[non_exhaustive]
79pub enum WordParseError {
80    /// An error occurred while parsing an arithmetic expression.
81    #[error("failed to parse arithmetic expression")]
82    ArithmeticExpression(ParseErrorLocation),
83
84    /// An error occurred while parsing a shell pattern.
85    #[error("failed to parse pattern")]
86    Pattern(ParseErrorLocation),
87
88    /// An error occurred while parsing a prompt string.
89    #[error("failed to parse prompt string")]
90    Prompt(ParseErrorLocation),
91
92    /// An error occurred while parsing a parameter.
93    #[error("failed to parse parameter '{0}'")]
94    Parameter(String, ParseErrorLocation),
95
96    /// An error occurred while parsing for brace expansion.
97    #[error("failed to parse for brace expansion: '{0}'")]
98    BraceExpansion(String, ParseErrorLocation),
99
100    /// An error occurred while parsing a word.
101    #[error("failed to parse word '{0}'")]
102    Word(String, ParseErrorLocation),
103}
104
105/// Represents an error that occurred while parsing a (non-extended) test command.
106#[derive(Debug, thiserror::Error)]
107#[error(transparent)]
108pub struct TestCommandParseError(#[from] peg::error::ParseError<usize>);
109
110/// Represents an error that occurred while parsing a key-binding specification.
111#[derive(Debug, thiserror::Error)]
112#[non_exhaustive]
113pub enum BindingParseError {
114    /// An unknown error occurred while parsing a key-binding specification.
115    #[error("unknown error while parsing key-binding: '{0}'")]
116    Unknown(String),
117
118    /// A key code was missing from the key-binding specification.
119    #[error("missing key code in key-binding")]
120    MissingKeyCode,
121}
122
123pub(crate) fn convert_peg_parse_error(
124    err: &peg::error::ParseError<usize>,
125    tokens: &[crate::Token],
126) -> ParseError {
127    let approx_token_index = err.location;
128
129    if approx_token_index < tokens.len() {
130        let token = &tokens[approx_token_index];
131        ParseError::ParsingNear((*token.location().start).clone())
132    } else {
133        ParseError::ParsingAtEndOfInput
134    }
135}