rich_err/
note.rs

1//! [Note]s provide a clean and easy way to make error messages more useful to the user.
2
3use crate::span::Span;
4use ariadne::ReportBuilder;
5
6/// Specifies a [note](Note)'s kind.
7#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
8pub enum NoteKind {
9    /// An ordinary note.
10    ///
11    /// These are useful for statements that add context to an error.
12    #[default]
13    Note,
14    /// A note designed to assist the user.
15    ///
16    /// These are useful for suggestions that would help the user address the error.
17    Help,
18}
19
20/// A message meant to provide extra context and/or assistance within an error message.
21#[derive(Clone, Debug, Eq, Hash, PartialEq)]
22pub struct Note {
23    /// What kind of note this is.
24    ///
25    /// This is used to customize the error reporting when [`Note::add_to`] is inevitably called.
26    pub kind: NoteKind,
27    /// The note's contents.
28    pub message: String,
29}
30
31impl Note {
32    /// Creates a new note with the given message.
33    ///
34    /// # Examples
35    ///
36    /// ```
37    /// # use rich_err::note::{Note, NoteKind};
38    /// assert_eq!(
39    ///     Note::new_note("foo"),
40    ///     Note {
41    ///         kind: NoteKind::Note,
42    ///         message: "foo".to_string(),
43    ///     },
44    /// );
45    /// ```
46    pub fn new_note<S>(message: S) -> Self
47    where
48        S: ToString,
49    {
50        Self {
51            kind: NoteKind::Note,
52            message: message.to_string(),
53        }
54    }
55
56    /// Creates a new note with the given help message.
57    ///
58    /// # Examples
59    ///
60    /// ```
61    /// # use rich_err::note::{Note, NoteKind};
62    /// assert_eq!(
63    ///     Note::new_help("foo"),
64    ///     Note {
65    ///         kind: NoteKind::Help,
66    ///         message: "foo".to_string(),
67    ///     },
68    /// );
69    /// ```
70    pub fn new_help<S>(message: S) -> Self
71    where
72        S: ToString,
73    {
74        Self {
75            kind: NoteKind::Help,
76            message: message.to_string(),
77        }
78    }
79
80    /// Adds this note to a [`ReportBuilder`].
81    pub fn add_to<Source>(self, builder: &mut ReportBuilder<'_, (Source, Span)>)
82    where
83        (Source, Span): ariadne::Span,
84    {
85        match self.kind {
86            NoteKind::Note => builder.add_note(self.message),
87            NoteKind::Help => builder.add_help(self.message),
88        }
89    }
90}