Skip to main content

antlr_rust_codegen/
error.rs

1use std::fmt;
2use std::io;
3use std::ops::Range;
4use std::path::PathBuf;
5
6/// Broad category of a generator failure.
7#[derive(Clone, Copy, Debug, Eq, PartialEq)]
8#[non_exhaustive]
9pub enum ErrorKind {
10    Configuration,
11    Compilation,
12    Generation,
13    Filesystem,
14}
15
16/// Severity of one grammar diagnostic.
17#[derive(Clone, Copy, Debug, Eq, PartialEq)]
18pub enum Severity {
19    Warning,
20    Error,
21}
22
23/// A grammar compiler diagnostic.
24#[derive(Clone, Debug, Eq, PartialEq)]
25pub struct Diagnostic {
26    code: &'static str,
27    severity: Severity,
28    message: String,
29    path: PathBuf,
30    line: Option<usize>,
31    column: Option<usize>,
32    byte_span: Option<Range<usize>>,
33}
34
35impl Diagnostic {
36    pub(crate) fn new(
37        code: &'static str,
38        severity: Severity,
39        message: String,
40        path: PathBuf,
41        position: Option<(usize, usize)>,
42        byte_span: Option<Range<usize>>,
43    ) -> Self {
44        Self {
45            code,
46            severity,
47            message,
48            path,
49            line: position.map(|(line, _)| line),
50            column: position.map(|(_, column)| column),
51            byte_span,
52        }
53    }
54
55    pub const fn code(&self) -> &'static str {
56        self.code
57    }
58
59    pub const fn severity(&self) -> Severity {
60        self.severity
61    }
62
63    pub fn message(&self) -> &str {
64        &self.message
65    }
66
67    pub fn path(&self) -> &std::path::Path {
68        &self.path
69    }
70
71    pub const fn line(&self) -> Option<usize> {
72        self.line
73    }
74
75    pub const fn column(&self) -> Option<usize> {
76        self.column
77    }
78
79    /// Half-open UTF-8 byte range of the primary subject within [`Self::path`].
80    ///
81    /// Returns `None` when the diagnostic has no source-backed primary subject.
82    pub fn byte_span(&self) -> Option<Range<usize>> {
83        self.byte_span.clone()
84    }
85}
86
87/// Structured error returned by [`crate::Builder`].
88#[derive(Debug)]
89pub struct Error {
90    kind: ErrorKind,
91    message: String,
92    diagnostics: Vec<Diagnostic>,
93    source: Option<io::Error>,
94}
95
96impl Error {
97    pub(crate) fn configuration(message: impl Into<String>) -> Self {
98        Self {
99            kind: ErrorKind::Configuration,
100            message: message.into(),
101            diagnostics: Vec::new(),
102            source: None,
103        }
104    }
105
106    pub(crate) const fn compilation(message: String, diagnostics: Vec<Diagnostic>) -> Self {
107        Self {
108            kind: ErrorKind::Compilation,
109            message,
110            diagnostics,
111            source: None,
112        }
113    }
114
115    pub(crate) fn generation(source: io::Error) -> Self {
116        let kind = if matches!(
117            source.kind(),
118            io::ErrorKind::NotFound
119                | io::ErrorKind::PermissionDenied
120                | io::ErrorKind::AlreadyExists
121                | io::ErrorKind::ReadOnlyFilesystem
122        ) {
123            ErrorKind::Filesystem
124        } else {
125            ErrorKind::Generation
126        };
127        Self {
128            kind,
129            message: source.to_string(),
130            diagnostics: Vec::new(),
131            source: Some(source),
132        }
133    }
134
135    pub const fn kind(&self) -> ErrorKind {
136        self.kind
137    }
138
139    pub fn diagnostics(&self) -> &[Diagnostic] {
140        &self.diagnostics
141    }
142
143    pub(crate) fn into_io_error(mut self) -> io::Error {
144        self.source.take().unwrap_or_else(|| {
145            let kind =
146                if self.kind == ErrorKind::Configuration || self.kind == ErrorKind::Compilation {
147                    io::ErrorKind::InvalidInput
148                } else {
149                    io::ErrorKind::Other
150                };
151            io::Error::new(kind, self.message)
152        })
153    }
154}
155
156impl fmt::Display for Error {
157    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
158        formatter.write_str(&self.message)
159    }
160}
161
162impl std::error::Error for Error {
163    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
164        self.source
165            .as_ref()
166            .map(|source| -> &(dyn std::error::Error + 'static) { source })
167    }
168}
169
170impl From<io::Error> for Error {
171    fn from(source: io::Error) -> Self {
172        Self::generation(source)
173    }
174}