Skip to main content

sql_splitter/
diagnostic.rs

1//! Structured diagnostics for the synthetic data generator.
2//!
3//! Config loading, compilation, heuristics, and verification all need to
4//! report problems without stopping at the first one: a config with three
5//! unknown tables should say so three times, not once. [`DiagnosticBag`] is
6//! the single home for collecting those problems, and [`Diagnostic`] is the
7//! stable shape shared by human (`Display`) and machine (JSON) reports.
8//!
9//! Codes are plain strings rather than an enum so that statically linked
10//! extensions can mint their own namespaced codes (e.g. `EXT-FOO-BAR`)
11//! without changing this crate.
12
13use std::fmt;
14
15use serde::{Deserialize, Serialize};
16
17pub mod codes;
18
19/// Canonical website page for built-in synthetic-generation diagnostics.
20pub const DIAGNOSTICS_DOCUMENTATION_URL: &str =
21    "https://sql-splitter.dev/commands/generate/diagnostics/";
22
23/// Stable diagnostic code, e.g. `GEN-MISSING-TABLE`.
24///
25/// Kept as a plain string (not an enum) so extensions can define their own
26/// namespaced codes without a dependency on this crate's enum.
27pub type DiagnosticCode = String;
28
29/// Area of the generate pipeline that owns a built-in diagnostic definition.
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
31#[serde(rename_all = "snake_case")]
32pub enum DiagnosticCategory {
33    Config,
34    Selection,
35    Generator,
36    Modifier,
37    Planner,
38    Inference,
39    Profiling,
40    Rendering,
41    Verification,
42    Runtime,
43    Registry,
44    Privacy,
45}
46
47/// Usual severity of a built-in diagnostic code.
48///
49/// A definition may be [`Variable`](TypicalSeverity::Variable) when policy
50/// selects the actual severity for each occurrence.
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
52#[serde(rename_all = "snake_case")]
53pub enum TypicalSeverity {
54    Info,
55    Advisory,
56    Warning,
57    Error,
58    Variable,
59}
60
61/// Stable metadata shared by every occurrence of a built-in diagnostic code.
62#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
63pub struct DiagnosticDefinition {
64    pub code: &'static str,
65    pub title: &'static str,
66    pub category: DiagnosticCategory,
67    pub typical_severity: TypicalSeverity,
68    pub summary: &'static str,
69}
70
71impl DiagnosticDefinition {
72    /// Canonical case-preserving anchor for this built-in diagnostic.
73    pub fn documentation_url(&self) -> String {
74        format!("{DIAGNOSTICS_DOCUMENTATION_URL}#{}", self.code)
75    }
76}
77
78impl From<&'static DiagnosticDefinition> for DiagnosticCode {
79    fn from(definition: &'static DiagnosticDefinition) -> Self {
80        definition.code.to_string()
81    }
82}
83
84/// How serious a [`Diagnostic`] is.
85#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
86#[serde(rename_all = "snake_case")]
87pub enum Severity {
88    Info,
89    Advisory,
90    Warning,
91    Error,
92}
93
94/// A named location related to a diagnostic, e.g. the other place a column
95/// is produced from.
96#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
97pub struct SourceLocation {
98    pub path: String,
99    #[serde(skip_serializing_if = "Option::is_none")]
100    pub description: Option<String>,
101}
102
103impl fmt::Display for SourceLocation {
104    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
105        match &self.description {
106            Some(description) => write!(f, "{} ({description})", self.path),
107            None => write!(f, "{}", self.path),
108        }
109    }
110}
111
112/// A single diagnostic: a stable code, severity, YAML path, message, and
113/// optional help/related locations.
114#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
115pub struct Diagnostic {
116    pub code: DiagnosticCode,
117    pub severity: Severity,
118    pub path: String,
119    pub message: String,
120    #[serde(skip_serializing_if = "Option::is_none")]
121    pub help: Option<String>,
122    #[serde(default, skip_serializing_if = "Vec::is_empty")]
123    pub related: Vec<SourceLocation>,
124}
125
126impl Diagnostic {
127    /// Creates a diagnostic occurrence with no help or related locations.
128    pub fn new(
129        severity: Severity,
130        code: impl Into<DiagnosticCode>,
131        path: impl Into<String>,
132        message: impl Into<String>,
133    ) -> Self {
134        Self {
135            code: code.into(),
136            severity,
137            path: path.into(),
138            message: message.into(),
139            help: None,
140            related: Vec::new(),
141        }
142    }
143
144    pub fn info(
145        code: impl Into<DiagnosticCode>,
146        path: impl Into<String>,
147        message: impl Into<String>,
148    ) -> Self {
149        Self::new(Severity::Info, code, path, message)
150    }
151
152    pub fn advisory(
153        code: impl Into<DiagnosticCode>,
154        path: impl Into<String>,
155        message: impl Into<String>,
156    ) -> Self {
157        Self::new(Severity::Advisory, code, path, message)
158    }
159
160    pub fn warning(
161        code: impl Into<DiagnosticCode>,
162        path: impl Into<String>,
163        message: impl Into<String>,
164    ) -> Self {
165        Self::new(Severity::Warning, code, path, message)
166    }
167
168    pub fn error(
169        code: impl Into<DiagnosticCode>,
170        path: impl Into<String>,
171        message: impl Into<String>,
172    ) -> Self {
173        Self::new(Severity::Error, code, path, message)
174    }
175
176    /// Canonical documentation URL for built-ins, or `None` for extension codes.
177    pub fn documentation_url(&self) -> Option<String> {
178        codes::find(&self.code).map(DiagnosticDefinition::documentation_url)
179    }
180}
181
182impl fmt::Display for Diagnostic {
183    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
184        let severity = match self.severity {
185            Severity::Info => "info",
186            Severity::Advisory => "advisory",
187            Severity::Error => "error",
188            Severity::Warning => "warning",
189        };
190        let mut lines = vec![
191            format!("{severity}[{}] {}", self.code, self.path),
192            format!("  {}", self.message),
193        ];
194        for location in &self.related {
195            lines.push(format!("    - {location}"));
196        }
197        if let Some(help) = &self.help {
198            lines.push(format!("  help: {help}"));
199        }
200        if let Some(definition) = codes::find(&self.code) {
201            lines.push(format!("  docs: {}", definition.documentation_url()));
202        }
203        write!(f, "{}", lines.join("\n"))
204    }
205}
206
207/// Collects independent diagnostics from a single compilation pass.
208#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
209pub struct DiagnosticBag {
210    pub diagnostics: Vec<Diagnostic>,
211}
212
213impl DiagnosticBag {
214    /// Records an informational diagnostic. Informational diagnostics never
215    /// block generation and are not promoted by strict mode.
216    pub fn info(
217        &mut self,
218        code: impl Into<String>,
219        path: impl Into<String>,
220        message: impl Into<String>,
221    ) -> &mut Diagnostic {
222        self.push(Severity::Info, code, path, message)
223    }
224
225    /// Records an advisory diagnostic. Advisories are non-fatal safety notices
226    /// that remain visible even when ordinary reporting is quiet.
227    pub fn advisory(
228        &mut self,
229        code: impl Into<String>,
230        path: impl Into<String>,
231        message: impl Into<String>,
232    ) -> &mut Diagnostic {
233        self.push(Severity::Advisory, code, path, message)
234    }
235
236    /// Records an error-severity diagnostic and returns it for further
237    /// customization (e.g. setting `help` or `related`).
238    pub fn error(
239        &mut self,
240        code: impl Into<String>,
241        path: impl Into<String>,
242        message: impl Into<String>,
243    ) -> &mut Diagnostic {
244        self.push(Severity::Error, code, path, message)
245    }
246
247    /// Records a warning-severity diagnostic and returns it for further
248    /// customization (e.g. setting `help` or `related`).
249    pub fn warning(
250        &mut self,
251        code: impl Into<String>,
252        path: impl Into<String>,
253        message: impl Into<String>,
254    ) -> &mut Diagnostic {
255        self.push(Severity::Warning, code, path, message)
256    }
257
258    fn push(
259        &mut self,
260        severity: Severity,
261        code: impl Into<String>,
262        path: impl Into<String>,
263        message: impl Into<String>,
264    ) -> &mut Diagnostic {
265        self.diagnostics
266            .push(Diagnostic::new(severity, code, path, message));
267        self.diagnostics
268            .last_mut()
269            .expect("just pushed a diagnostic")
270    }
271
272    /// Iterates over error-severity diagnostics only.
273    pub fn errors(&self) -> impl Iterator<Item = &Diagnostic> {
274        self.diagnostics
275            .iter()
276            .filter(|diagnostic| diagnostic.severity == Severity::Error)
277    }
278
279    /// True if any error-severity diagnostic has been recorded. Warnings
280    /// alone do not count.
281    pub fn has_errors(&self) -> bool {
282        self.errors().next().is_some()
283    }
284
285    /// True if any diagnostic (of any severity) carries `code`.
286    pub fn has_code(&self, code: &str) -> bool {
287        self.diagnostics
288            .iter()
289            .any(|diagnostic| diagnostic.code == code)
290    }
291
292    /// Converts the bag into a `Result`: `Ok(value)` if no error-severity
293    /// diagnostic was recorded, otherwise `Err(self)` with all diagnostics
294    /// (including warnings) intact for reporting.
295    pub fn into_result<T>(self, value: T) -> Result<T, DiagnosticBag> {
296        if self.has_errors() {
297            Err(self)
298        } else {
299            Ok(value)
300        }
301    }
302}
303
304impl fmt::Display for DiagnosticBag {
305    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
306        let rendered: Vec<String> = self.diagnostics.iter().map(Diagnostic::to_string).collect();
307        write!(f, "{}", rendered.join("\n"))
308    }
309}
310
311impl std::error::Error for DiagnosticBag {}
312
313#[cfg(test)]
314mod tests {
315    use super::*;
316
317    #[test]
318    fn error_defaults_to_no_help_or_related() {
319        let mut bag = DiagnosticBag::default();
320        bag.error("GEN-MISSING-TABLE", "tables.orders", "table does not exist");
321        let diagnostic = &bag.diagnostics[0];
322        assert_eq!(diagnostic.severity, Severity::Error);
323        assert!(diagnostic.help.is_none());
324        assert!(diagnostic.related.is_empty());
325    }
326
327    #[test]
328    fn has_errors_is_false_for_warnings_only() {
329        let mut bag = DiagnosticBag::default();
330        bag.warning(
331            "GEN-UNUSED-COLUMN",
332            "tables.orders.columns.legacy_flag",
333            "unused column",
334        );
335        assert!(!bag.has_errors());
336    }
337}