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
//! Errors that can be returned from the parsing process

use std::fmt::{self, Display, Formatter, Write};
use std::{convert::TryInto, error::Error};

use itertools::{Itertools, Position::*};
use nom::error::{ErrorKind, FromExternalError, ParseError};
use pretty_lint::{Position, PrettyLint, Span};

/// Extension trait for nom::error::ParseError that allows for collecting the
/// failed tag in the event of a mismatch, similar to ParseError::from_char.
pub(crate) trait WithTagError<I> {
    /// Construct the error from the given input and tag
    fn from_tag(input: I, tag: &'static str) -> Self;
}

impl<I> WithTagError<I> for () {
    fn from_tag(_: I, _: &'static str) -> Self {}
}

/// Different kinds of things that can be expected at a given location
#[derive(Debug, Clone, Copy)]
pub enum Expected {
    /// Expected EoF (End of File)
    Eof,
    /// Expected a character
    Char(char),
    /// Expected a tag
    ///
    /// A tag is a particular string token (such as "upper").
    Tag(&'static str),
    /// Expected a number
    Number,
}

impl Display for Expected {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Expected::Eof => write!(f, "EoF"),
            Expected::Number => write!(f, "a number"),
            Expected::Char(c) => write!(f, "{:?}", c),
            Expected::Tag(tag) => write!(f, "{:?}", tag),
        }
    }
}

/// A single parse failure at a location– reports what was expected at what
/// location
#[derive(Debug, Clone, Copy)]
pub struct ExpectedAt {
    /// The character index of the error location
    pub index: usize,

    /// The line number (starting with 1) of the error location
    pub line: u32,

    /// The column number (starting with 1) of the error location
    pub column: u32,

    /// The specific element that was expected
    pub expected: Expected,
}

/// This error type is used while parsing is running; it knows only the tail
/// end of the input at the time an error occurred. It can be combined with the
/// original input to produce an absolute error location via `ExpectedAt`.
#[derive(Debug, Clone)]
pub(crate) struct ExpectedContext<'a> {
    input_tail: &'a str,
    expected: Expected,
}

impl<'a> ExpectedContext<'a> {
    /// Given the original input string, extract the absolute error location of
    /// an ErrorContext
    pub fn extract_context(self, input: &'a str) -> ExpectedAt {
        let offset = input
            .len()
            .checked_sub(self.input_tail.len())
            .expect("input size was smaller than the tail size");

        let prefix = &input[..offset];

        let line_number = prefix.chars().filter(|&c| c == '\n').count() + 1;
        let last_line_start = prefix
            .char_indices()
            .rev()
            .find(|&(_, c)| c == '\n')
            .map(|(index, _)| index + 1)
            .unwrap_or(0);
        let column_number = (offset - last_line_start) + 1;

        ExpectedAt {
            line: line_number
                .try_into()
                .expect("More than 4 billion lines of input"),
            column: column_number
                .try_into()
                .expect("More than 4 billion columns of input"),
            index: offset,
            expected: self.expected,
        }
    }
}

/// This error type is used while parsing is running; it knows only the tail
/// end of the input at the time an error occurred. It can be combined with the
/// original input to produce a absolute error locations in `PasswordRulesError`.
#[derive(Debug, Clone)]
pub(crate) struct PasswordRulesErrorContext<'a> {
    expectations: Vec<ExpectedContext<'a>>,
}

impl<'a> PasswordRulesErrorContext<'a> {
    /// Given the original input string, extract the absolute error location of
    /// an all the errors
    pub fn extract_context(self, input: &'a str) -> PasswordRulesError {
        let mut expectations: Vec<ExpectedAt> = self
            .expectations
            .into_iter()
            .map(|exp| exp.extract_context(input))
            .collect();

        expectations.sort_unstable_by_key(|exp| exp.index);

        PasswordRulesError { expectations }
    }
}

impl<'a> ParseError<&'a str> for PasswordRulesErrorContext<'a> {
    fn from_error_kind(input: &'a str, kind: ErrorKind) -> Self {
        match kind {
            ErrorKind::Eof => Self {
                expectations: vec![ExpectedContext {
                    input_tail: input,
                    expected: Expected::Eof,
                }],
            },
            ErrorKind::Digit => Self {
                expectations: vec![ExpectedContext {
                    input_tail: input,
                    expected: Expected::Number,
                }],
            },
            _ => Self {
                expectations: vec![],
            },
        }
    }

    fn append(input: &'a str, kind: nom::error::ErrorKind, other: Self) -> Self {
        Self::from_error_kind(input, kind).or(other)
    }

    fn or(mut self, other: Self) -> Self {
        self.expectations.extend(other.expectations);
        self
    }

    fn from_char(input: &'a str, c: char) -> Self {
        Self {
            expectations: vec![ExpectedContext {
                input_tail: input,
                expected: Expected::Char(c),
            }],
        }
    }
}

impl<'a> WithTagError<&'a str> for PasswordRulesErrorContext<'a> {
    fn from_tag(input: &'a str, tag: &'static str) -> Self {
        Self {
            expectations: vec![ExpectedContext {
                input_tail: input,
                expected: Expected::Tag(tag),
            }],
        }
    }
}

impl<'a> FromExternalError<&'a str, std::num::ParseIntError> for PasswordRulesErrorContext<'a> {
    fn from_external_error(input: &'a str, kind: ErrorKind, _: std::num::ParseIntError) -> Self {
        Self::from_error_kind(input, kind)
    }
}

/// Error that can result from parsing password rules
#[derive(Debug, Clone)]
pub struct PasswordRulesError {
    /// Elements (like a character, string tag, or EoF) that the parser was expecting,
    /// along with the location where the element was expected
    pub expectations: Vec<ExpectedAt>,
}

impl PasswordRulesError {
    pub(crate) fn empty() -> Self {
        Self {
            expectations: vec![],
        }
    }

    /// Build a pretty version of the error given the original input string.
    ///
    /// The default `Display` implementation produces helpful output:
    ///
    /// ```text
    /// Error: expected one of:
    ///   "required", "allowed", "max-consecutive", "minlength", "maxlength", or EoF at 1:71
    /// ```
    ///
    /// It doesn't have access to the original input string, however, so it's limited
    /// in what it can do.
    ///
    /// This method produces pretty output with colors if you're able to provide that:
    ///
    /// ```text
    /// error: parsing failed
    ///  --> 1:71
    ///   |
    /// 1 | minlength: 8; maxlength: 32; required: lower, upper; required: digit; allow
    ///   |                                                                       ^ expected one of "required", "allowed", "max-consecutive", "minlength", "maxlength", or EoF
    /// ```
    pub fn to_string_pretty(&self, s: &str) -> Result<String, fmt::Error> {
        let lint_base = PrettyLint::error(s).with_message("parsing failed");

        Ok(match self.expectations.as_slice() {
            [] => lint_base.with_inline_message("unknown error").to_string(),
            [exp] => lint_base
                .with_inline_message(&format!("expected {}", exp.expected))
                .at(Span {
                    start: Position {
                        line: exp.line as usize,
                        col: exp.column as usize,
                    },
                    end: Position {
                        line: exp.line as usize,
                        col: exp.column as usize,
                    },
                })
                .to_string(),
            expectations => {
                // Group the expectations by location, so that several expectations at the same
                // location can be shown together
                let groups = expectations.iter().group_by(|exp| (exp.line, exp.column));
                let mut lint_string = String::new();

                groups.into_iter().try_for_each(|((line, column), group)| {
                    let mut inline_message = String::from("expected one of ");

                    group
                        .with_position()
                        .try_for_each(|positioned_exp| match positioned_exp {
                            Only(exp) => write!(inline_message, "{}", exp.expected),
                            First(exp) | Middle(exp) => {
                                write!(inline_message, "{}, ", exp.expected)
                            }
                            Last(exp) => write!(inline_message, "or {}", exp.expected),
                        })?;

                    let lint = PrettyLint::error(s)
                        .with_message("parsing failed")
                        .with_inline_message(&inline_message)
                        .at(Span {
                            start: Position {
                                line: line as usize,
                                col: column as usize,
                            },
                            end: Position {
                                line: line as usize,
                                col: column as usize,
                            },
                        });

                    write!(lint_string, "{}", lint)
                })?;

                lint_string
            }
        })
    }
}

impl Display for PasswordRulesError {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        match self.expectations.as_slice() {
            [] => write!(f, "unknown error"),
            [exp] => write!(
                f,
                "expected {} at {}:{}",
                exp.expected, exp.line, exp.column
            ),
            expectations => {
                // Group the expectations by location, so that several expectations at the same
                // location can be shown together
                writeln!(f, "expected one of:")?;

                let groups = expectations.iter().group_by(|exp| (exp.line, exp.column));

                groups.into_iter().try_for_each(|((line, column), group)| {
                    write!(f, "  ")?;

                    group
                        .with_position()
                        .try_for_each(|positioned_exp| match positioned_exp {
                            Only(exp) => write!(f, "{}", exp.expected),
                            First(exp) | Middle(exp) => write!(f, "{}, ", exp.expected),
                            Last(exp) => write!(f, "or {}", exp.expected),
                        })?;

                    writeln!(f, " at {}:{}", line, column)
                })
            }
        }
    }
}

impl Error for PasswordRulesError {}