rich_err/
label.rs

1use crate::span::Span;
2use ariadne::ReportBuilder;
3
4/// An additional error message associated with a specific area of the source code.
5///
6/// These are good for providing more context-sensitive error messages while keeping the actual
7/// error type general-use.
8#[derive(Clone, Debug, Eq, PartialEq)]
9pub struct Label {
10    /// The message to display to the user.
11    ///
12    /// If left blank, no space is wasted on displaying it.
13    pub message: String,
14    /// The [byte span](Span) within the source code that the label should refer to.
15    pub span: Span,
16}
17
18impl Label {
19    /// Constructs a new label without a message.
20    ///
21    /// To add a message, use the [`with_message`](Label::with_message) method.
22    pub const fn new(span: Span) -> Self {
23        Self {
24            message: String::new(),
25            span,
26        }
27    }
28
29    /// Adds a message to this label.
30    ///
31    /// If a message was already present, this overwrites it.
32    pub fn with_message<S>(mut self, message: S) -> Self
33    where
34        S: ToString,
35    {
36        self.message = message.to_string();
37        self
38    }
39
40    /// Adds this label to a [`ReportBuilder`].
41    pub fn add_to<Source>(
42        self,
43        builder: &mut ReportBuilder<'_, (Source, Span)>,
44        source_name: Source,
45    ) where
46        (Source, Span): ariadne::Span,
47    {
48        let label = ariadne::Label::new((source_name, self.span)).with_color(ariadne::Color::Red);
49        builder.add_label(if !self.message.is_empty() {
50            label.with_message(self.message)
51        } else {
52            label
53        });
54    }
55}