1use std::fmt;
14
15use serde::{Deserialize, Serialize};
16
17pub mod codes;
18
19pub const DIAGNOSTICS_DOCUMENTATION_URL: &str =
21 "https://sql-splitter.dev/commands/generate/diagnostics/";
22
23pub type DiagnosticCode = String;
28
29#[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#[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#[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 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#[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#[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#[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 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 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#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
209pub struct DiagnosticBag {
210 pub diagnostics: Vec<Diagnostic>,
211}
212
213impl DiagnosticBag {
214 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 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 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 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 pub fn errors(&self) -> impl Iterator<Item = &Diagnostic> {
274 self.diagnostics
275 .iter()
276 .filter(|diagnostic| diagnostic.severity == Severity::Error)
277 }
278
279 pub fn has_errors(&self) -> bool {
282 self.errors().next().is_some()
283 }
284
285 pub fn has_code(&self, code: &str) -> bool {
287 self.diagnostics
288 .iter()
289 .any(|diagnostic| diagnostic.code == code)
290 }
291
292 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}