Skip to main content

mads_core/
diagnostic.rs

1//! Structured diagnostics and framework errors emitted by MADS.rs.
2
3use std::fmt;
4
5/// A stable identifier for a MADS.rs diagnostic.
6#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
7pub struct DiagnosticCode(&'static str);
8
9impl DiagnosticCode {
10    /// Creates a diagnostic code from a static string.
11    pub const fn new(value: &'static str) -> Self {
12        Self(value)
13    }
14
15    /// Returns the string representation of this diagnostic code.
16    pub const fn as_str(self) -> &'static str {
17        self.0
18    }
19}
20
21impl fmt::Display for DiagnosticCode {
22    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
23        formatter.write_str(self.0)
24    }
25}
26
27/// Duplicate provider registration.
28pub const MADS001: DiagnosticCode = DiagnosticCode::new("MADS001");
29
30/// Ambiguous provider binding.
31pub const MADS002: DiagnosticCode = DiagnosticCode::new("MADS002");
32
33/// Missing provider registration.
34pub const MADS003: DiagnosticCode = DiagnosticCode::new("MADS003");
35
36/// Provider registry type mismatch.
37pub const MADS004: DiagnosticCode = DiagnosticCode::new("MADS004");
38
39/// Dependency cycle.
40pub const MADS005: DiagnosticCode = DiagnosticCode::new("MADS005");
41
42/// Provider construction failure.
43pub const MADS006: DiagnosticCode = DiagnosticCode::new("MADS006");
44
45/// Auto-configuration failure.
46pub const MADS007: DiagnosticCode = DiagnosticCode::new("MADS007");
47
48/// Invalid rooted module graph.
49pub const MADS008: DiagnosticCode = DiagnosticCode::new("MADS008");
50
51/// Inaccessible provider across a module boundary.
52pub const MADS009: DiagnosticCode = DiagnosticCode::new("MADS009");
53
54/// Invalid lifecycle state transition.
55pub const MADS010: DiagnosticCode = DiagnosticCode::new("MADS010");
56
57/// Lifecycle hook failure.
58pub const MADS011: DiagnosticCode = DiagnosticCode::new("MADS011");
59
60/// Configuration source failure.
61pub const MADS020: DiagnosticCode = DiagnosticCode::new("MADS020");
62
63/// Conflicting integration route declarations.
64pub const MADS030: DiagnosticCode = DiagnosticCode::new("MADS030");
65
66/// The source position associated with a diagnostic.
67#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
68pub struct SourceLocation {
69    /// The source file path.
70    pub file: &'static str,
71    /// The one-based source line.
72    pub line: u32,
73    /// The one-based source column.
74    pub column: u32,
75}
76
77impl SourceLocation {
78    /// Creates a source location from a file, line, and column.
79    pub const fn new(file: &'static str, line: u32, column: u32) -> Self {
80        Self { file, line, column }
81    }
82}
83
84/// A structured diagnostic with optional source context and suggestions.
85#[derive(Clone, Debug, Eq, Hash, PartialEq)]
86pub struct Diagnostic {
87    code: DiagnosticCode,
88    title: String,
89    message: String,
90    subject: Option<String>,
91    location: Option<SourceLocation>,
92    suggestions: Vec<String>,
93}
94
95impl Diagnostic {
96    /// Creates a diagnostic with a code, short title, and detailed message.
97    pub fn new(code: DiagnosticCode, title: impl Into<String>, message: impl Into<String>) -> Self {
98        Self {
99            code,
100            title: title.into(),
101            message: message.into(),
102            subject: None,
103            location: None,
104            suggestions: Vec::new(),
105        }
106    }
107
108    /// Adds the subject associated with this diagnostic.
109    pub fn with_subject(mut self, subject: impl Into<String>) -> Self {
110        self.subject = Some(subject.into());
111        self
112    }
113
114    /// Adds the source location associated with this diagnostic.
115    pub fn with_location(mut self, location: SourceLocation) -> Self {
116        self.location = Some(location);
117        self
118    }
119
120    /// Adds a remediation suggestion to this diagnostic.
121    pub fn with_suggestion(mut self, suggestion: impl Into<String>) -> Self {
122        self.suggestions.push(suggestion.into());
123        self
124    }
125
126    /// Returns this diagnostic's stable code.
127    pub const fn code(&self) -> DiagnosticCode {
128        self.code
129    }
130
131    /// Returns this diagnostic's short title.
132    pub fn title(&self) -> &str {
133        &self.title
134    }
135
136    /// Returns this diagnostic's detailed message.
137    pub fn message(&self) -> &str {
138        &self.message
139    }
140
141    /// Returns the subject associated with this diagnostic, when present.
142    pub fn subject(&self) -> Option<&str> {
143        self.subject.as_deref()
144    }
145
146    /// Returns the source location associated with this diagnostic, when present.
147    pub const fn location(&self) -> Option<SourceLocation> {
148        self.location
149    }
150
151    /// Returns remediation suggestions in insertion order.
152    pub fn suggestions(&self) -> &[String] {
153        &self.suggestions
154    }
155}
156
157impl fmt::Display for Diagnostic {
158    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
159        write!(formatter, "error[{}]: {}", self.code, self.title)?;
160        if let Some(location) = self.location {
161            write!(
162                formatter,
163                "\n  --> {}:{}:{}",
164                location.file, location.line, location.column
165            )?;
166        }
167        if let Some(subject) = &self.subject {
168            write!(formatter, "\n  = subject: {subject}")?;
169        }
170        write!(formatter, "\n  = {}", self.message)?;
171        for suggestion in &self.suggestions {
172            write!(formatter, "\n  help: {suggestion}")?;
173        }
174        Ok(())
175    }
176}
177
178/// A framework error containing a structured diagnostic and optional cause.
179#[derive(Debug)]
180pub struct Error {
181    diagnostics: Vec<Diagnostic>,
182    source: Option<Box<dyn std::error::Error + Send + Sync>>,
183}
184
185impl Error {
186    /// Creates an error from a structured diagnostic.
187    pub fn new(diagnostic: Diagnostic) -> Self {
188        Self {
189            diagnostics: vec![diagnostic],
190            source: None,
191        }
192    }
193
194    /// Creates an error from a primary diagnostic and ordered related diagnostics.
195    pub fn from_diagnostics(
196        primary: Diagnostic,
197        related: impl IntoIterator<Item = Diagnostic>,
198    ) -> Self {
199        let mut diagnostics = vec![primary];
200        diagnostics.extend(related);
201        Self {
202            diagnostics,
203            source: None,
204        }
205    }
206
207    pub(crate) fn with_related_diagnostics(
208        mut self,
209        related: impl IntoIterator<Item = Diagnostic>,
210    ) -> Self {
211        self.diagnostics.extend(related);
212        self
213    }
214
215    /// Creates an error from a structured diagnostic and an underlying cause.
216    pub fn with_source<E>(diagnostic: Diagnostic, source: E) -> Self
217    where
218        E: std::error::Error + Send + Sync + 'static,
219    {
220        Self {
221            diagnostics: vec![diagnostic],
222            source: Some(Box::new(source)),
223        }
224    }
225
226    /// Returns this error's stable diagnostic code.
227    pub fn code(&self) -> DiagnosticCode {
228        self.diagnostics[0].code()
229    }
230
231    /// Returns the structured diagnostic carried by this error.
232    pub fn diagnostic(&self) -> &Diagnostic {
233        &self.diagnostics[0]
234    }
235
236    /// return every diagnostic in deterministic report order.
237    pub fn diagnostics(&self) -> &[Diagnostic] {
238        &self.diagnostics
239    }
240}
241
242impl fmt::Display for Error {
243    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
244        for (index, diagnostic) in self.diagnostics.iter().enumerate() {
245            if index > 0 {
246                formatter.write_str("\n\n")?;
247            }
248            diagnostic.fmt(formatter)?;
249        }
250        Ok(())
251    }
252}
253
254impl std::error::Error for Error {
255    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
256        self.source
257            .as_deref()
258            .map(|source| source as &(dyn std::error::Error + 'static))
259    }
260}
261
262/// The result type used by MADS.rs framework APIs.
263pub type Result<T> = std::result::Result<T, Error>;