Skip to main content

dbt_antlr_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    #[cfg(feature = "generator")]
39    pub(crate) fn new(
40        code: &'static str,
41        severity: Severity,
42        message: String,
43        path: PathBuf,
44        position: Option<(usize, usize)>,
45        byte_span: Option<Range<usize>>,
46    ) -> Self {
47        Self {
48            code,
49            severity,
50            message,
51            path,
52            line: position.map(|(line, _)| line),
53            column: position.map(|(_, column)| column),
54            byte_span,
55        }
56    }
57
58    pub const fn code(&self) -> &'static str {
59        self.code
60    }
61
62    pub const fn severity(&self) -> Severity {
63        self.severity
64    }
65
66    pub fn message(&self) -> &str {
67        &self.message
68    }
69
70    pub fn path(&self) -> &std::path::Path {
71        &self.path
72    }
73
74    pub const fn line(&self) -> Option<usize> {
75        self.line
76    }
77
78    pub const fn column(&self) -> Option<usize> {
79        self.column
80    }
81
82    /// Half-open UTF-8 byte range of the primary subject within [`Self::path`].
83    ///
84    /// Returns `None` when the diagnostic has no source-backed primary subject.
85    pub fn byte_span(&self) -> Option<Range<usize>> {
86        self.byte_span.clone()
87    }
88}
89
90/// Shows the diagnostic as `warning[G4S078]: path:line:column: message`, the
91/// format that the command line writes to stderr.
92impl fmt::Display for Diagnostic {
93    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
94        let severity = match self.severity {
95            Severity::Warning => "warning",
96            Severity::Error => "error",
97        };
98        write!(
99            formatter,
100            "{severity}[{}]: {}",
101            self.code,
102            self.path.display()
103        )?;
104        if let (Some(line), Some(column)) = (self.line, self.column) {
105            write!(formatter, ":{line}:{column}")?;
106        }
107        write!(formatter, ": {}", self.message)
108    }
109}
110
111/// Structured error returned by the emission entry points.
112#[derive(Debug)]
113pub struct Error {
114    kind: ErrorKind,
115    message: String,
116    diagnostics: Vec<Diagnostic>,
117    source: Option<io::Error>,
118}
119
120impl Error {
121    #[cfg(feature = "generator")]
122    pub(crate) const fn compilation(message: String, diagnostics: Vec<Diagnostic>) -> Self {
123        Self {
124            kind: ErrorKind::Compilation,
125            message,
126            diagnostics,
127            source: None,
128        }
129    }
130
131    pub(crate) fn generation(source: io::Error) -> Self {
132        let kind = if matches!(
133            source.kind(),
134            io::ErrorKind::NotFound
135                | io::ErrorKind::PermissionDenied
136                | io::ErrorKind::AlreadyExists
137                | io::ErrorKind::ReadOnlyFilesystem
138        ) {
139            ErrorKind::Filesystem
140        } else {
141            ErrorKind::Generation
142        };
143        Self {
144            kind,
145            message: source.to_string(),
146            diagnostics: Vec::new(),
147            source: Some(source),
148        }
149    }
150
151    pub const fn kind(&self) -> ErrorKind {
152        self.kind
153    }
154
155    pub fn diagnostics(&self) -> &[Diagnostic] {
156        &self.diagnostics
157    }
158}
159
160impl fmt::Display for Error {
161    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
162        formatter.write_str(&self.message)
163    }
164}
165
166impl std::error::Error for Error {
167    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
168        self.source
169            .as_ref()
170            .map(|source| -> &(dyn std::error::Error + 'static) { source })
171    }
172}
173
174impl From<io::Error> for Error {
175    fn from(source: io::Error) -> Self {
176        Self::generation(source)
177    }
178}
179
180/// Errors of the emission layer.
181#[derive(Debug, thiserror::Error)]
182pub enum EmitError {
183    /// The grammar failed to compile.
184    #[cfg(feature = "generator")]
185    #[error("grammar compilation failed: {0}")]
186    Compile(#[from] Error),
187    /// The template failed to load or render.
188    #[cfg(feature = "generator")]
189    #[error("template rendering failed: {0}")]
190    Template(#[from] minijinja::Error),
191    /// The grammar uses a construct the emission layer does not support
192    /// yet (left recursion, embedded actions, sempreds, labels).
193    #[cfg(feature = "generator")]
194    #[error("unsupported grammar construct: {0}")]
195    Unsupported(String),
196    /// The generator configuration is invalid.
197    #[error("invalid generator configuration: {0}")]
198    Config(String),
199    /// A pinned release binary could not be downloaded, verified, or run.
200    #[cfg(feature = "download")]
201    #[error("pinned release binary failed: {0}")]
202    Download(String),
203    /// An output directory or file could not be written.
204    #[error("cannot write {path}: {source}")]
205    Write {
206        /// Path that could not be written.
207        path: PathBuf,
208        /// Underlying I/O error.
209        source: io::Error,
210    },
211}