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
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> nom7::error::ParseError<I> for GreedyError<I, nom7::error::ErrorKind>
where
    I: Position,
{
    fn from_error_kind(input: I, kind: nom7::error::ErrorKind) -> Self {
        GreedyError {
            errors: vec![(input, GreedyErrorKind::Nom(kind))],
        }
    }

    fn append(input: I, kind: nom7::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> nom7::error::ContextError<I> for GreedyError<I, nom7::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
    }
}

/// 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: nom7::AsBytes, U> Position for nom_locate4::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 + nom7::AsBytes, X> AsStr for nom_locate4::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 nom7::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_nom7 {
    use super::*;
    use nom7::branch::alt;
    use nom7::character::complete::{alpha1, digit1};
    use nom7::error::{ErrorKind, ParseError, VerboseError};
    use nom7::sequence::tuple;
    use nom7::Err;
    use nom7::IResult;
    use nom_locate4::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)),
            _ => (),
        };
    }
}