miette/
diagnostic_chain.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
/*!
Iterate over error `.diagnostic_source()` chains.
*/

use crate::protocol::Diagnostic;

/// Iterator of a chain of cause errors.
#[derive(Clone, Default)]
#[allow(missing_debug_implementations)]
pub(crate) struct DiagnosticChain<'a> {
    state: Option<ErrorKind<'a>>,
}

impl<'a> DiagnosticChain<'a> {
    pub(crate) fn from_diagnostic(head: &'a dyn Diagnostic) -> Self {
        DiagnosticChain {
            state: Some(ErrorKind::Diagnostic(head)),
        }
    }

    pub(crate) fn from_stderror(head: &'a (dyn std::error::Error + 'static)) -> Self {
        DiagnosticChain {
            state: Some(ErrorKind::StdError(head)),
        }
    }
}

impl<'a> Iterator for DiagnosticChain<'a> {
    type Item = ErrorKind<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        if let Some(err) = self.state.take() {
            self.state = err.get_nested();
            Some(err)
        } else {
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let len = self.len();
        (len, Some(len))
    }
}

impl ExactSizeIterator for DiagnosticChain<'_> {
    fn len(&self) -> usize {
        fn depth(d: Option<&ErrorKind<'_>>) -> usize {
            match d {
                Some(d) => 1 + depth(d.get_nested().as_ref()),
                None => 0,
            }
        }

        depth(self.state.as_ref())
    }
}

#[derive(Clone)]
pub(crate) enum ErrorKind<'a> {
    Diagnostic(&'a dyn Diagnostic),
    StdError(&'a (dyn std::error::Error + 'static)),
}

impl<'a> ErrorKind<'a> {
    fn get_nested(&self) -> Option<ErrorKind<'a>> {
        match self {
            ErrorKind::Diagnostic(d) => d
                .diagnostic_source()
                .map(ErrorKind::Diagnostic)
                .or_else(|| d.source().map(ErrorKind::StdError)),
            ErrorKind::StdError(e) => e.source().map(ErrorKind::StdError),
        }
    }
}

impl<'a> std::fmt::Debug for ErrorKind<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ErrorKind::Diagnostic(d) => d.fmt(f),
            ErrorKind::StdError(e) => e.fmt(f),
        }
    }
}

impl<'a> std::fmt::Display for ErrorKind<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ErrorKind::Diagnostic(d) => d.fmt(f),
            ErrorKind::StdError(e) => e.fmt(f),
        }
    }
}