Skip to content

Commit d091d26

Browse files
committed
regex: better formatting for syntax errors
This commit adds an explicit Debug impl for regex's main Error type. The purpose of this impl is to format parse errors in normal panic messages more nicely. This is slightly idiosyncratic, but the default Debug impl prints the full string anyway, we might as well format it nicely. See also: #450
1 parent 9442d6b commit d091d26

File tree

1 file changed

+30
-1
lines changed

1 file changed

+30
-1
lines changed

src/error.rs

+30-1
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,12 @@
99
// except according to those terms.
1010

1111
use std::fmt;
12+
use std::iter::repeat;
1213

1314
use syntax;
1415

1516
/// An error that occurred during parsing or compiling a regular expression.
16-
#[derive(Clone, Debug, PartialEq)]
17+
#[derive(Clone, PartialEq)]
1718
pub enum Error {
1819
/// A syntax error.
1920
Syntax(String),
@@ -56,6 +57,34 @@ impl fmt::Display for Error {
5657
}
5758
}
5859

60+
// We implement our own Debug implementation so that we show nicer syntax
61+
// errors when people use `Regex::new(...).unwrap()`. It's a little weird,
62+
// but the `Syntax` variant is already storing a `String` anyway, so we might
63+
// as well format it nicely.
64+
impl fmt::Debug for Error {
65+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
66+
match *self {
67+
Error::Syntax(ref err) => {
68+
let hr: String = repeat('~').take(79).collect();
69+
try!(writeln!(f, "Syntax("));
70+
try!(writeln!(f, "{}", hr));
71+
try!(writeln!(f, "{}", err));
72+
try!(writeln!(f, "{}", hr));
73+
try!(write!(f, ")"));
74+
Ok(())
75+
}
76+
Error::CompiledTooBig(limit) => {
77+
f.debug_tuple("CompiledTooBig")
78+
.field(&limit)
79+
.finish()
80+
}
81+
Error::__Nonexhaustive => {
82+
f.debug_tuple("__Nonexhaustive").finish()
83+
}
84+
}
85+
}
86+
}
87+
5988
impl From<syntax::Error> for Error {
6089
fn from(err: syntax::Error) -> Error {
6190
Error::Syntax(err.to_string())

0 commit comments

Comments
 (0)