Skip to main content

antlr_rust_codegen/
error.rs

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