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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
use std::fmt::Debug;

/// This error type accumulates errors and their position when backtracking
/// through a parse tree. This take a deepest error at `alt` combinator.
#[derive(Clone, Debug, PartialEq)]
pub struct GreedyError<I, E> {
    /// list of errors accumulated by `GreedyError`, containing the affected
    /// part of input data, and some context
    pub errors: Vec<(I, GreedyErrorKind<E>)>,
}

#[derive(Clone, Debug, PartialEq)]
/// error context for `GreedyError`
pub enum GreedyErrorKind<E> {
    /// static string added by the `context` function
    Context(&'static str),
    /// indicates which character was expected by the `char` function
    Char(char),
    /// error kind given by various nom parsers
    Nom(E),
}

impl<I> nom6::error::ParseError<I> for GreedyError<I, nom6::error::ErrorKind>
where
    I: Position,
{
    fn from_error_kind(input: I, kind: nom6::error::ErrorKind) -> Self {
        GreedyError {
            errors: vec![(input, GreedyErrorKind::Nom(kind))],
        }
    }

    fn append(input: I, kind: nom6::error::ErrorKind, mut other: Self) -> Self {
        other.errors.push((input, GreedyErrorKind::Nom(kind)));
        other
    }

    fn from_char(input: I, c: char) -> Self {
        GreedyError {
            errors: vec![(input, GreedyErrorKind::Char(c))],
        }
    }

    fn or(self, other: Self) -> Self {
        let pos_self = if let Some(x) = self.errors.first() {
            x.0.position()
        } else {
            0
        };
        let pos_other = if let Some(x) = other.errors.first() {
            x.0.position()
        } else {
            0
        };
        if pos_other > pos_self {
            other
        } else {
            self
        }
    }
}

impl<I> nom6::error::ContextError<I> for GreedyError<I, nom6::error::ErrorKind>
where
    I: Position,
{
    fn add_context(input: I, ctx: &'static str, mut other: Self) -> Self {
        other.errors.push((input, GreedyErrorKind::Context(ctx)));
        other
    }
}

impl<I> nom5::error::ParseError<I> for GreedyError<I, nom5::error::ErrorKind>
where
    I: Position,
{
    fn from_error_kind(input: I, kind: nom5::error::ErrorKind) -> Self {
        GreedyError {
            errors: vec![(input, GreedyErrorKind::Nom(kind))],
        }
    }

    fn append(input: I, kind: nom5::error::ErrorKind, mut other: Self) -> Self {
        other.errors.push((input, GreedyErrorKind::Nom(kind)));
        other
    }

    fn from_char(input: I, c: char) -> Self {
        GreedyError {
            errors: vec![(input, GreedyErrorKind::Char(c))],
        }
    }

    fn add_context(input: I, ctx: &'static str, mut other: Self) -> Self {
        other.errors.push((input, GreedyErrorKind::Context(ctx)));
        other
    }

    fn or(self, other: Self) -> Self {
        let pos_self = if let Some(x) = self.errors.first() {
            x.0.position()
        } else {
            0
        };
        let pos_other = if let Some(x) = other.errors.first() {
            x.0.position()
        } else {
            0
        };
        if pos_other > pos_self {
            other
        } else {
            self
        }
    }
}

/// get the deepest error position
pub fn error_position<T: Position, E>(e: &GreedyError<T, E>) -> Option<usize> {
    e.errors.first().map(|x| x.0.position())
}

pub trait Position {
    fn position(&self) -> usize;
}

impl<T, U> Position for nom_locate1::LocatedSpanEx<T, U> {
    fn position(&self) -> usize {
        self.offset
    }
}

impl<T: nom5::AsBytes, U> Position for nom_locate2::LocatedSpan<T, U> {
    fn position(&self) -> usize {
        self.location_offset()
    }
}

impl<T: nom6::AsBytes, U> Position for nom_locate3::LocatedSpan<T, U> {
    fn position(&self) -> usize {
        self.location_offset()
    }
}

pub trait AsStr {
    fn as_str(&self) -> &str;
}

impl<'a> AsStr for &'a str {
    #[inline(always)]
    fn as_str(&self) -> &str {
        self
    }
}

impl AsStr for str {
    #[inline(always)]
    fn as_str(&self) -> &str {
        self
    }
}

impl<T: AsStr, X> AsStr for nom_locate1::LocatedSpanEx<T, X> {
    #[inline]
    fn as_str(&self) -> &str {
        self.fragment.as_str()
    }
}

impl<T: AsStr + nom5::AsBytes, X> AsStr for nom_locate2::LocatedSpan<T, X> {
    #[inline]
    fn as_str(&self) -> &str {
        self.fragment().as_str()
    }
}

impl<T: AsStr + nom6::AsBytes, X> AsStr for nom_locate3::LocatedSpan<T, X> {
    #[inline]
    fn as_str(&self) -> &str {
        self.fragment().as_str()
    }
}

/// transforms a `GreedyError` into a trace with input position information
pub fn convert_error<T: AsStr, U: AsStr, V: Debug>(input: T, e: GreedyError<U, V>) -> String {
    use nom6::Offset;
    use std::iter::repeat;

    let lines: Vec<_> = input.as_str().lines().map(String::from).collect();

    let mut result = String::new();

    for (i, (substring, kind)) in e.errors.iter().enumerate() {
        let mut offset = input.as_str().offset(substring.as_str());

        if lines.is_empty() {
            match kind {
                GreedyErrorKind::Char(c) => {
                    result += &format!("{}: expected '{}', got empty input\n\n", i, c);
                }
                GreedyErrorKind::Context(s) => {
                    result += &format!("{}: in {}, got empty input\n\n", i, s);
                }
                GreedyErrorKind::Nom(e) => {
                    result += &format!("{}: in {:?}, got empty input\n\n", i, e);
                }
            }
        } else {
            let mut line = 0;
            let mut column = 0;

            for (j, l) in lines.iter().enumerate() {
                if offset <= l.len() {
                    line = j;
                    column = offset;
                    break;
                } else {
                    offset = offset - l.len() - 1;
                }
            }

            match kind {
                GreedyErrorKind::Char(c) => {
                    result += &format!("{}: at line {}:\n", i, line);
                    result += &lines[line];
                    result += "\n";

                    if column > 0 {
                        result += &repeat(' ').take(column).collect::<String>();
                    }
                    result += "^\n";
                    result += &format!(
                        "expected '{}', found {}\n\n",
                        c,
                        substring.as_str().chars().next().unwrap()
                    );
                }
                GreedyErrorKind::Context(s) => {
                    result += &format!("{}: at line {}, in {}:\n", i, line, s);
                    result += &lines[line];
                    result += "\n";
                    if column > 0 {
                        result += &repeat(' ').take(column).collect::<String>();
                    }
                    result += "^\n\n";
                }
                GreedyErrorKind::Nom(e) => {
                    result += &format!("{}: at line {}, in {:?}:\n", i, line, e);
                    result += &lines[line];
                    result += "\n";
                    if column > 0 {
                        result += &repeat(' ').take(column).collect::<String>();
                    }
                    result += "^\n\n";
                }
            }
        }
    }

    result
}

#[cfg(test)]
mod tests_nom6 {
    use super::*;
    use nom6::branch::alt;
    use nom6::character::complete::{alpha1, digit1};
    use nom6::error::{ErrorKind, ParseError, VerboseError};
    use nom6::sequence::tuple;
    use nom6::Err;
    use nom6::IResult;
    use nom_locate3::LocatedSpan;

    type Span<'a> = LocatedSpan<&'a str>;

    fn parser<'a, E: ParseError<Span<'a>>>(
        input: Span<'a>,
    ) -> IResult<Span<'a>, (Span<'a>, Span<'a>, Span<'a>), E> {
        alt((
            tuple((alpha1, digit1, alpha1)),
            tuple((digit1, alpha1, digit1)),
        ))(input)
    }

    #[test]
    fn test_position() {
        // VerboseError failed at
        //   abc012:::
        //   ^
        let error = parser::<VerboseError<Span>>(Span::new("abc012:::"));
        match error {
            Err(Err::Error(e)) => assert_eq!(e.errors.first().map(|x| x.0.position()), Some(0)),
            _ => (),
        };

        // GreedyError failed at
        //   abc012:::
        //         ^
        let error = parser::<GreedyError<Span, ErrorKind>>(Span::new("abc012:::"));
        match error {
            Err(Err::Error(e)) => assert_eq!(error_position(&e), Some(6)),
            _ => (),
        };
    }

    #[test]
    fn test_convert_error() {
        let error = parser::<GreedyError<Span, ErrorKind>>(Span::new("abc012:::"));
        let msg = r##"0: at line 0, in Alpha:
abc012:::
      ^

1: at line 0, in Alt:
abc012:::
^

"##;
        match error {
            Err(Err::Error(e)) => assert_eq!(convert_error("abc012:::", e), String::from(msg)),
            _ => (),
        };
    }
}

#[cfg(test)]
mod tests_nom5 {
    use super::*;
    use nom5::branch::alt;
    use nom5::character::complete::{alpha1, digit1};
    use nom5::error::{ParseError, VerboseError};
    use nom5::sequence::tuple;
    use nom5::IResult;
    use nom_locate2::LocatedSpan;

    type Span<'a> = LocatedSpan<&'a str>;

    fn parser<'a, E: ParseError<Span<'a>>>(
        input: Span<'a>,
    ) -> IResult<Span<'a>, (Span<'a>, Span<'a>, Span<'a>), E> {
        alt((
            tuple((alpha1, digit1, alpha1)),
            tuple((digit1, alpha1, digit1)),
        ))(input)
    }

    #[test]
    fn test_position() {
        // VerboseError failed at
        //   abc012:::
        //   ^
        let error = parser::<VerboseError<Span>>(Span::new("abc012:::"));
        match error {
            Err(nom5::Err::Error(e)) => {
                assert_eq!(e.errors.first().map(|x| x.0.position()), Some(0))
            }
            _ => (),
        };

        // GreedyError failed at
        //   abc012:::
        //         ^
        let error = parser::<GreedyError<Span, nom5::error::ErrorKind>>(Span::new("abc012:::"));
        match error {
            Err(nom5::Err::Error(e)) => assert_eq!(error_position(&e), Some(6)),
            _ => (),
        };
    }

    #[test]
    fn test_convert_error() {
        let error = parser::<GreedyError<Span, nom5::error::ErrorKind>>(Span::new("abc012:::"));
        let msg = r##"0: at line 0, in Alpha:
abc012:::
      ^

1: at line 0, in Alt:
abc012:::
^

"##;
        match error {
            Err(nom5::Err::Error(e)) => {
                assert_eq!(convert_error("abc012:::", e), String::from(msg))
            }
            _ => (),
        };
    }
}