error_annotation/
ea.rs

1use std::fmt;
2
3/// Combine a source error with labeled diagnostic information.
4///
5/// `ErrorAnnotation` combines a `source` error of type `S` with diagnostic `info` of type `I`
6/// which will be labeled with `label` when displayed.
7#[derive(Debug)]
8pub struct ErrorAnnotation<S, I> {
9    pub source: S,
10    pub label: &'static str,
11    pub info: I,
12}
13
14impl<S, I> ErrorAnnotation<S, I> {
15    /// Transform the source while leaving the annotated info.
16    pub fn map_source<F, T>(self, f: F) -> ErrorAnnotation<T, I>
17    where
18        F: FnOnce(S) -> T,
19    {
20        ErrorAnnotation {
21            source: f(self.source),
22            label: self.label,
23            info: self.info,
24        }
25    }
26
27    /// Transform the info with a new label, leaving the original source.
28    pub fn map_info<F, J>(self, f: F) -> ErrorAnnotation<S, J>
29    where
30        F: FnOnce(I) -> (&'static str, J),
31    {
32        let (label, info) = f(self.info);
33        ErrorAnnotation {
34            source: self.source,
35            label,
36            info,
37        }
38    }
39}
40
41impl<S, I> fmt::Display for ErrorAnnotation<S, I>
42where
43    I: fmt::Display,
44    S: fmt::Display,
45{
46    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47        write!(f, "{}\n-with {}: {}", self.source, self.label, self.info)
48    }
49}