maybe_fatal/context.rs
1use ariadne::ReportBuilder;
2
3/// Some contextual information about a [diagnostic](crate::Diagnostic).
4///
5/// Consumers of this crate generally should not need to explicitly use this type. It is only made
6/// public to provide the ability to [filter](crate::sink::Filter) diagnostics by their context on
7/// the off-chance that is necessary.
8#[derive(Clone, Debug, Eq, Hash, PartialEq)]
9pub enum Context<S> {
10 /// A labeled subspan of a [diagnostic](crate::Diagnostic), optionally with an attached message.
11 Label(ariadne::Label<S>),
12
13 /// A message that provides specialized information concerning the overall
14 /// [diagnostic](crate::Diagnostic).
15 Note(Box<str>),
16
17 /// Advice concerning the overall [diagnostic](crate::Diagnostic).
18 Help(Box<str>),
19}
20
21impl<S> Context<S> {
22 /// Constructs a new note.
23 ///
24 /// If you already have a [`Box<str>`], you could also construct the note directly from the
25 /// [`Note`](Context::Note) variant.
26 pub fn new_note(note: impl ToString) -> Self {
27 Self::new_note_owned(note.to_string())
28 }
29
30 /// Constructs a new note from an owned [`String`].
31 pub fn new_note_owned(note: String) -> Self {
32 Self::Note(note.into_boxed_str())
33 }
34
35 /// Constructs a new help message.
36 ///
37 /// If you already have a [`Box<str>`], you could also construct the help message directly from
38 /// the [`Help`](Context::Help) variant.
39 pub fn new_help(help: impl ToString) -> Self {
40 Self::new_help_owned(help.to_string())
41 }
42
43 /// Constructs a new help message from an owned [`String`].
44 pub fn new_help_owned(help: String) -> Self {
45 Self::Help(help.into_boxed_str())
46 }
47
48 /// Adds this context to a [`ReportBuilder`].
49 pub(super) fn add_to_report_builder(self, builder: &mut ReportBuilder<S>)
50 where
51 S: ariadne::Span,
52 {
53 match self {
54 Self::Label(label) => builder.add_label(label),
55 Self::Note(note) => builder.add_note(note),
56 Self::Help(help) => builder.add_help(help),
57 }
58 }
59}