miette/
miette_diagnostic.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
use std::{
    error::Error,
    fmt::{Debug, Display},
};

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

use crate::{Diagnostic, LabeledSpan, Severity};

/// Diagnostic that can be created at runtime.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct MietteDiagnostic {
    /// Displayed diagnostic message
    pub message: String,
    /// Unique diagnostic code to look up more information
    /// about this Diagnostic. Ideally also globally unique, and documented
    /// in the toplevel crate's documentation for easy searching.
    /// Rust path format (`foo::bar::baz`) is recommended, but more classic
    /// codes like `E0123` will work just fine
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub code: Option<String>,
    /// [`Diagnostic`] severity. Intended to be used by
    /// [`ReportHandler`](crate::ReportHandler)s to change the way different
    /// [`Diagnostic`]s are displayed. Defaults to [`Severity::Error`]
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub severity: Option<Severity>,
    /// Additional help text related to this Diagnostic
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub help: Option<String>,
    /// URL to visit for a more detailed explanation/help about this
    /// [`Diagnostic`].
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub url: Option<String>,
    /// Labels to apply to this `Diagnostic`'s [`Diagnostic::source_code`]
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub labels: Option<Vec<LabeledSpan>>,
}

impl Display for MietteDiagnostic {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", &self.message)
    }
}

impl Error for MietteDiagnostic {}

impl Diagnostic for MietteDiagnostic {
    fn code<'a>(&'a self) -> Option<Box<dyn Display + 'a>> {
        self.code
            .as_ref()
            .map(Box::new)
            .map(|c| c as Box<dyn Display>)
    }

    fn severity(&self) -> Option<Severity> {
        self.severity
    }

    fn help<'a>(&'a self) -> Option<Box<dyn Display + 'a>> {
        self.help
            .as_ref()
            .map(Box::new)
            .map(|c| c as Box<dyn Display>)
    }

    fn url<'a>(&'a self) -> Option<Box<dyn Display + 'a>> {
        self.url
            .as_ref()
            .map(Box::new)
            .map(|c| c as Box<dyn Display>)
    }

    fn labels(&self) -> Option<Box<dyn Iterator<Item = LabeledSpan> + '_>> {
        self.labels
            .as_ref()
            .map(|ls| ls.iter().cloned())
            .map(Box::new)
            .map(|b| b as Box<dyn Iterator<Item = LabeledSpan>>)
    }
}

impl MietteDiagnostic {
    /// Create a new dynamic diagnostic with the given message.
    ///
    /// # Examples
    /// ```
    /// use miette::{Diagnostic, MietteDiagnostic, Severity};
    ///
    /// let diag = MietteDiagnostic::new("Oops, something went wrong!");
    /// assert_eq!(diag.to_string(), "Oops, something went wrong!");
    /// assert_eq!(diag.message, "Oops, something went wrong!");
    /// ```
    pub fn new(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
            labels: None,
            severity: None,
            code: None,
            help: None,
            url: None,
        }
    }

    /// Return new diagnostic with the given code.
    ///
    /// # Examples
    /// ```
    /// use miette::{Diagnostic, MietteDiagnostic};
    ///
    /// let diag = MietteDiagnostic::new("Oops, something went wrong!").with_code("foo::bar::baz");
    /// assert_eq!(diag.message, "Oops, something went wrong!");
    /// assert_eq!(diag.code, Some("foo::bar::baz".to_string()));
    /// ```
    pub fn with_code(mut self, code: impl Into<String>) -> Self {
        self.code = Some(code.into());
        self
    }

    /// Return new diagnostic with the given severity.
    ///
    /// # Examples
    /// ```
    /// use miette::{Diagnostic, MietteDiagnostic, Severity};
    ///
    /// let diag = MietteDiagnostic::new("I warn you to stop!").with_severity(Severity::Warning);
    /// assert_eq!(diag.message, "I warn you to stop!");
    /// assert_eq!(diag.severity, Some(Severity::Warning));
    /// ```
    pub fn with_severity(mut self, severity: Severity) -> Self {
        self.severity = Some(severity);
        self
    }

    /// Return new diagnostic with the given help message.
    ///
    /// # Examples
    /// ```
    /// use miette::{Diagnostic, MietteDiagnostic};
    ///
    /// let diag = MietteDiagnostic::new("PC is not working").with_help("Try to reboot it again");
    /// assert_eq!(diag.message, "PC is not working");
    /// assert_eq!(diag.help, Some("Try to reboot it again".to_string()));
    /// ```
    pub fn with_help(mut self, help: impl Into<String>) -> Self {
        self.help = Some(help.into());
        self
    }

    /// Return new diagnostic with the given URL.
    ///
    /// # Examples
    /// ```
    /// use miette::{Diagnostic, MietteDiagnostic};
    ///
    /// let diag = MietteDiagnostic::new("PC is not working")
    ///     .with_url("https://letmegooglethat.com/?q=Why+my+pc+doesn%27t+work");
    /// assert_eq!(diag.message, "PC is not working");
    /// assert_eq!(
    ///     diag.url,
    ///     Some("https://letmegooglethat.com/?q=Why+my+pc+doesn%27t+work".to_string())
    /// );
    /// ```
    pub fn with_url(mut self, url: impl Into<String>) -> Self {
        self.url = Some(url.into());
        self
    }

    /// Return new diagnostic with the given label.
    ///
    /// Discards previous labels
    ///
    /// # Examples
    /// ```
    /// use miette::{Diagnostic, LabeledSpan, MietteDiagnostic};
    ///
    /// let source = "cpp is the best language";
    ///
    /// let label = LabeledSpan::at(0..3, "This should be Rust");
    /// let diag = MietteDiagnostic::new("Wrong best language").with_label(label.clone());
    /// assert_eq!(diag.message, "Wrong best language");
    /// assert_eq!(diag.labels, Some(vec![label]));
    /// ```
    pub fn with_label(mut self, label: impl Into<LabeledSpan>) -> Self {
        self.labels = Some(vec![label.into()]);
        self
    }

    /// Return new diagnostic with the given labels.
    ///
    /// Discards previous labels
    ///
    /// # Examples
    /// ```
    /// use miette::{Diagnostic, LabeledSpan, MietteDiagnostic};
    ///
    /// let source = "helo wrld";
    ///
    /// let labels = vec![
    ///     LabeledSpan::at_offset(3, "add 'l'"),
    ///     LabeledSpan::at_offset(6, "add 'r'"),
    /// ];
    /// let diag = MietteDiagnostic::new("Typos in 'hello world'").with_labels(labels.clone());
    /// assert_eq!(diag.message, "Typos in 'hello world'");
    /// assert_eq!(diag.labels, Some(labels));
    /// ```
    pub fn with_labels(mut self, labels: impl IntoIterator<Item = LabeledSpan>) -> Self {
        self.labels = Some(labels.into_iter().collect());
        self
    }

    /// Return new diagnostic with new label added to the existing ones.
    ///
    /// # Examples
    /// ```
    /// use miette::{Diagnostic, LabeledSpan, MietteDiagnostic};
    ///
    /// let source = "helo wrld";
    ///
    /// let label1 = LabeledSpan::at_offset(3, "add 'l'");
    /// let label2 = LabeledSpan::at_offset(6, "add 'r'");
    /// let diag = MietteDiagnostic::new("Typos in 'hello world'")
    ///     .and_label(label1.clone())
    ///     .and_label(label2.clone());
    /// assert_eq!(diag.message, "Typos in 'hello world'");
    /// assert_eq!(diag.labels, Some(vec![label1, label2]));
    /// ```
    pub fn and_label(mut self, label: impl Into<LabeledSpan>) -> Self {
        let mut labels = self.labels.unwrap_or_default();
        labels.push(label.into());
        self.labels = Some(labels);
        self
    }

    /// Return new diagnostic with new labels added to the existing ones.
    ///
    /// # Examples
    /// ```
    /// use miette::{Diagnostic, LabeledSpan, MietteDiagnostic};
    ///
    /// let source = "helo wrld";
    ///
    /// let label1 = LabeledSpan::at_offset(3, "add 'l'");
    /// let label2 = LabeledSpan::at_offset(6, "add 'r'");
    /// let label3 = LabeledSpan::at_offset(9, "add '!'");
    /// let diag = MietteDiagnostic::new("Typos in 'hello world!'")
    ///     .and_label(label1.clone())
    ///     .and_labels([label2.clone(), label3.clone()]);
    /// assert_eq!(diag.message, "Typos in 'hello world!'");
    /// assert_eq!(diag.labels, Some(vec![label1, label2, label3]));
    /// ```
    pub fn and_labels(mut self, labels: impl IntoIterator<Item = LabeledSpan>) -> Self {
        let mut all_labels = self.labels.unwrap_or_default();
        all_labels.extend(labels);
        self.labels = Some(all_labels);
        self
    }
}

#[cfg(feature = "serde")]
#[test]
fn test_serialize_miette_diagnostic() {
    use serde_json::json;

    use crate::diagnostic;

    let diag = diagnostic!("message");
    let json = json!({ "message": "message" });
    assert_eq!(json!(diag), json);

    let diag = diagnostic!(
        code = "code",
        help = "help",
        url = "url",
        labels = [
            LabeledSpan::at_offset(0, "label1"),
            LabeledSpan::at(1..3, "label2")
        ],
        severity = Severity::Warning,
        "message"
    );
    let json = json!({
        "message": "message",
        "code": "code",
        "help": "help",
        "url": "url",
        "severity": "Warning",
        "labels": [
            {
                "span": {
                    "offset": 0,
                    "length": 0
                },
                "label": "label1",
                "primary": false
            },
            {
                "span": {
                    "offset": 1,
                    "length": 2
                },
                "label": "label2",
                "primary": false
            }
        ]
    });
    assert_eq!(json!(diag), json);
}

#[cfg(feature = "serde")]
#[test]
fn test_deserialize_miette_diagnostic() {
    use serde_json::json;

    use crate::diagnostic;

    let json = json!({ "message": "message" });
    let diag = diagnostic!("message");
    assert_eq!(diag, serde_json::from_value(json).unwrap());

    let json = json!({
        "message": "message",
        "help": null,
        "code": null,
        "severity": null,
        "url": null,
        "labels": null
    });
    assert_eq!(diag, serde_json::from_value(json).unwrap());

    let diag = diagnostic!(
        code = "code",
        help = "help",
        url = "url",
        labels = [
            LabeledSpan::at_offset(0, "label1"),
            LabeledSpan::at(1..3, "label2")
        ],
        severity = Severity::Warning,
        "message"
    );
    let json = json!({
        "message": "message",
        "code": "code",
        "help": "help",
        "url": "url",
        "severity": "Warning",
        "labels": [
            {
                "span": {
                    "offset": 0,
                    "length": 0
                },
                "label": "label1",
                "primary": false
            },
            {
                "span": {
                    "offset": 1,
                    "length": 2
                },
                "label": "label2",
                "primary": false
            }
        ]
    });
    assert_eq!(diag, serde_json::from_value(json).unwrap());
}