Skip to content

Commit

Permalink
syntax: fix bug in error printer
Browse files Browse the repository at this point in the history
This fixes an off-by-one bug in the error formatter. Namely, if a regex
ends with a literal `\n` *and* an error is reported that contains a span
at the end of the regex, then this trips a bug in the formatter because
its line count ends up being wrong. We fix this by tweaking the line
count. The actual error message is still a little wonky, but given the
literal `\n`, it's hard not to make it wonky.

Fixes #464
  • Loading branch information
BurntSushi committed Apr 14, 2018
1 parent 2b1fc27 commit 9ba9a75
Showing 1 changed file with 20 additions and 1 deletion.
21 changes: 20 additions & 1 deletion regex-syntax/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,13 @@ impl<'p> Spans<'p> {
fn from_formatter<'e, E: fmt::Display>(
fmter: &'p Formatter<'e, E>,
) -> Spans<'p> {
let line_count = fmter.pattern.lines().count();
let mut line_count = fmter.pattern.lines().count();
// If the pattern ends with a `\n` literal, then our line count is
// off by one, since a span can occur immediately after the last `\n`,
// which is consider to be an additional line.
if fmter.pattern.ends_with('\n') {
line_count += 1;
}
let line_number_width =
if line_count <= 1 {
0
Expand Down Expand Up @@ -276,3 +282,16 @@ impl<'p> Spans<'p> {
fn repeat_char(c: char, count: usize) -> String {
::std::iter::repeat(c).take(count).collect()
}

#[cfg(test)]
mod tests {
use ast::parse::Parser;

// See: https://github.com/rust-lang/regex/issues/464
#[test]
fn regression_464() {
let err = Parser::new().parse("a{\n").unwrap_err();
// This test checks that the error formatter doesn't panic.
assert!(!err.to_string().is_empty());
}
}

0 comments on commit 9ba9a75

Please sign in to comment.