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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
use std::cmp::Ordering;
use std::collections::BinaryHeap;
use std::fmt::Display;

/// The reason parsing failed
#[non_exhaustive]
#[derive(Debug, PartialOrd, Ord, PartialEq, Eq)]
pub enum Reason {
    /// A predicate evaluated to `false`
    PredicateFailed,
    /// The `not` combinator failed  
    NotFailed,
    /// Expected to see the end of input, but didn't
    NotEndOfInput,
    /// Expected more input, but saw the end of input
    EndOfInput,
    /// The [`Debug`] representation of what we expected to find in the input.
    Mismatch(String),
    /// The description of an operation that failed while parsing. Only
    /// [`.and_then()`](crate::Parser::and_then) uses this reason
    Error(String),
    /// A user-provided label describing the item we tried and failed to parse. Only
    /// [`.label()`](crate::Parser::label) uses this reason
    Label(&'static str),
}

impl Reason {
    // We use these weights to tie break when we have multiple `ParserFailure`s at the same input
    // position
    fn weight(&self) -> usize {
        match self {
            Reason::PredicateFailed => 0,
            Reason::NotFailed => 10,
            Reason::NotEndOfInput => 20,
            Reason::EndOfInput => 30,
            Reason::Mismatch(_) => 40,
            Reason::Error(_) => 50,
            Reason::Label(_) => 60,
        }
    }
}

impl Display for Reason {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Reason::PredicateFailed => {
                write!(f, "predicate evaluated to false")
            }
            Reason::NotFailed => {
                write!(f, "unexpected parser success")
            }
            Reason::NotEndOfInput => {
                write!(f, "expected end of input")
            }
            Reason::EndOfInput => {
                write!(f, "unexpected end of input")
            }
            Reason::Mismatch(s) => {
                write!(f, "expected \"{}\"", s)
            }
            Reason::Error(e) => {
                write!(f, "unexpected error: {}", e)
            }
            Reason::Label(l) => {
                write!(f, "expected {}", l)
            }
        }
    }
}

/// A parsing error
#[derive(Debug, PartialEq, Eq)]
pub struct ParserFailure {
    pub position: usize,
    pub reason: Reason,
}

impl ParserFailure {
    fn new(reason: Reason, position: usize) -> Self {
        Self { position, reason }
    }
}

impl Ord for ParserFailure {
    fn cmp(&self, other: &Self) -> Ordering {
        let res = self.position.cmp(&other.position);

        if res == Ordering::Equal {
            self.reason.weight().cmp(&other.reason.weight())
        } else {
            res
        }
    }
}

impl PartialOrd for ParserFailure {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Display for ParserFailure {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{} at position {}", self.reason, self.position)
    }
}

/// A log of parser failures sorted by input position in descending order.
///
/// This is returned when [when parsers fail](crate::Res).
#[derive(Debug)]
pub struct FailureLog {
    heap: BinaryHeap<ParserFailure>,
}

impl Default for FailureLog {
    fn default() -> Self {
        Self::new()
    }
}

impl FailureLog {
    /// Creates a new log of failures
    pub fn new() -> Self {
        FailureLog {
            heap: BinaryHeap::new(),
        }
    }

    /// Record a new parser failure at a given input position
    pub fn add(&mut self, reason: Reason, position: usize) {
        self.heap.push(ParserFailure::new(reason, position));
    }

    /// Pops [`ParserFailure`]s from the log in descending order of input position
    ///
    /// Returns `None` if the log is empty
    pub fn pop(&mut self) -> Option<ParserFailure> {
        self.heap.pop()
    }

    /// Peeks the next [`ParserFailure`] from the log in descending order of input position
    ///
    /// Returns `None` if the log is empty
    pub fn peek(&self) -> Option<&ParserFailure> {
        self.heap.peek()
    }

    /// Consumes the log and returns a vector of [`ParserFailure`]s sorted in ascending order of
    /// input position
    pub fn to_vec(self) -> Vec<ParserFailure> {
        self.heap.into_sorted_vec()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_comparing_parser_failure() {
        let a = ParserFailure::new(Reason::EndOfInput, 12);
        let b = ParserFailure::new(Reason::EndOfInput, 1);
        let c = ParserFailure::new(Reason::EndOfInput, 3);
        let d = ParserFailure::new(Reason::EndOfInput, 12);

        assert!(a > b);
        assert!(c > b);
        assert_eq!(a, d);
    }

    #[test]
    fn test_parser_failure_reason_ordering() {
        let mut log = FailureLog::new();

        log.add(Reason::PredicateFailed, 1);
        log.add(Reason::Label("digit"), 1);
        log.add(Reason::EndOfInput, 1);
        log.add(Reason::Mismatch("9".into()), 1);
        log.add(Reason::NotFailed, 1);
        log.add(Reason::Error("err".into()), 1);
        log.add(Reason::NotEndOfInput, 1);

        // The order in which the failures should be pop()ed should be deterministic
        let label = log.pop().unwrap();
        let err = log.pop().unwrap();
        let mismatch = log.pop().unwrap();
        let eoi = log.pop().unwrap();
        let neoi = log.pop().unwrap();
        let notfailed = log.pop().unwrap();
        let predicate = log.pop().unwrap();

        assert!(matches!(
            label,
            ParserFailure {
                reason: Reason::Label(_),
                ..
            }
        ));
        assert!(matches!(
            err,
            ParserFailure {
                reason: Reason::Error(_),
                ..
            }
        ));
        assert!(matches!(
            mismatch,
            ParserFailure {
                reason: Reason::Mismatch(_),
                ..
            }
        ));
        assert!(matches!(
            eoi,
            ParserFailure {
                reason: Reason::EndOfInput,
                ..
            }
        ));
        assert!(matches!(
            neoi,
            ParserFailure {
                reason: Reason::NotEndOfInput,
                ..
            }
        ));
        assert!(matches!(
            notfailed,
            ParserFailure {
                reason: Reason::NotFailed,
                ..
            }
        ));
        assert!(matches!(
            predicate,
            ParserFailure {
                reason: Reason::PredicateFailed,
                ..
            }
        ));
    }

    #[test]
    fn test_parser_failure_ordering() {
        let mut log = FailureLog::new();

        log.add(Reason::NotFailed, 1);
        log.add(Reason::NotFailed, 100);
        log.add(Reason::NotFailed, 34);

        let first = log.pop().unwrap();
        let second = log.pop().unwrap();
        let third = log.pop().unwrap();

        assert!(matches!(first, ParserFailure { position: 100, .. }));
        assert!(matches!(second, ParserFailure { position: 34, .. }));
        assert!(matches!(third, ParserFailure { position: 1, .. }));
    }
}