Skip to main content

shuck_parser/
error.rs

1//! Error types for shuck
2
3/// Result type alias using shuck's Error.
4pub type Result<T> = std::result::Result<T, Error>;
5
6/// Shuck error types.
7#[derive(Debug, Clone)]
8pub enum Error {
9    /// Parse error occurred while parsing the script.
10    ///
11    /// When `line` and `column` are 0, the error has no source location.
12    Parse {
13        /// Human-readable error message.
14        message: String,
15        /// 1-based source line, or `0` when unknown.
16        line: usize,
17        /// 1-based source column, or `0` when unknown.
18        column: usize,
19    },
20}
21
22impl std::fmt::Display for Error {
23    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24        let Self::Parse {
25            message,
26            line,
27            column,
28        } = self;
29        if *line > 0 {
30            write!(f, "parse error at line {line}, column {column}: {message}")
31        } else {
32            write!(f, "parse error: {message}")
33        }
34    }
35}
36
37impl std::error::Error for Error {}
38
39impl Error {
40    /// Create a parse error with source location.
41    pub fn parse_at(message: impl Into<String>, line: usize, column: usize) -> Self {
42        Self::Parse {
43            message: message.into(),
44            line,
45            column,
46        }
47    }
48
49    /// Create a parse error without source location.
50    pub fn parse(message: impl Into<String>) -> Self {
51        Self::Parse {
52            message: message.into(),
53            line: 0,
54            column: 0,
55        }
56    }
57}