Coverage Report

Created: 2026-08-14 08:14

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/regex-syntax-0.8.10/src/error.rs
Line
Count
Source
1
use alloc::{
2
    format,
3
    string::{String, ToString},
4
    vec,
5
    vec::Vec,
6
};
7
8
use crate::{ast, hir};
9
10
/// This error type encompasses any error that can be returned by this crate.
11
///
12
/// This error type is marked as `non_exhaustive`. This means that adding a
13
/// new variant is not considered a breaking change.
14
#[non_exhaustive]
15
#[derive(Clone, Debug, Eq, PartialEq)]
16
pub enum Error {
17
    /// An error that occurred while translating concrete syntax into abstract
18
    /// syntax (AST).
19
    Parse(ast::Error),
20
    /// An error that occurred while translating abstract syntax into a high
21
    /// level intermediate representation (HIR).
22
    Translate(hir::Error),
23
}
24
25
impl From<ast::Error> for Error {
26
16.3k
    fn from(err: ast::Error) -> Error {
27
16.3k
        Error::Parse(err)
28
16.3k
    }
29
}
30
31
impl From<hir::Error> for Error {
32
678
    fn from(err: hir::Error) -> Error {
33
678
        Error::Translate(err)
34
678
    }
35
}
36
37
#[cfg(feature = "std")]
38
impl std::error::Error for Error {}
39
40
impl core::fmt::Display for Error {
41
17.0k
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
42
17.0k
        match *self {
43
16.3k
            Error::Parse(ref x) => x.fmt(f),
44
678
            Error::Translate(ref x) => x.fmt(f),
45
        }
46
17.0k
    }
47
}
48
49
/// A helper type for formatting nice error messages.
50
///
51
/// This type is responsible for reporting regex parse errors in a nice human
52
/// readable format. Most of its complexity is from interspersing notational
53
/// markers pointing out the position where an error occurred.
54
#[derive(Debug)]
55
pub struct Formatter<'e, E> {
56
    /// The original regex pattern in which the error occurred.
57
    pattern: &'e str,
58
    /// The error kind. It must impl fmt::Display.
59
    err: &'e E,
60
    /// The primary span of the error.
61
    span: &'e ast::Span,
62
    /// An auxiliary and optional span, in case the error needs to point to
63
    /// two locations (e.g., when reporting a duplicate capture group name).
64
    aux_span: Option<&'e ast::Span>,
65
}
66
67
impl<'e> From<&'e ast::Error> for Formatter<'e, ast::ErrorKind> {
68
16.3k
    fn from(err: &'e ast::Error) -> Self {
69
16.3k
        Formatter {
70
16.3k
            pattern: err.pattern(),
71
16.3k
            err: err.kind(),
72
16.3k
            span: err.span(),
73
16.3k
            aux_span: err.auxiliary_span(),
74
16.3k
        }
75
16.3k
    }
76
}
77
78
impl<'e> From<&'e hir::Error> for Formatter<'e, hir::ErrorKind> {
79
678
    fn from(err: &'e hir::Error) -> Self {
80
678
        Formatter {
81
678
            pattern: err.pattern(),
82
678
            err: err.kind(),
83
678
            span: err.span(),
84
678
            aux_span: None,
85
678
        }
86
678
    }
87
}
88
89
impl<'e, E: core::fmt::Display> core::fmt::Display for Formatter<'e, E> {
90
17.0k
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
91
17.0k
        let spans = Spans::from_formatter(self);
92
17.0k
        if self.pattern.contains('\n') {
93
6.62k
            let divider = repeat_char('~', 79);
94
95
6.62k
            writeln!(f, "regex parse error:")?;
96
6.62k
            writeln!(f, "{divider}")?;
97
6.62k
            let notated = spans.notate();
98
6.62k
            write!(f, "{notated}")?;
99
6.62k
            writeln!(f, "{divider}")?;
100
            // If we have error spans that cover multiple lines, then we just
101
            // note the line numbers.
102
6.62k
            if !spans.multi_line.is_empty() {
103
616
                let mut notes = vec![];
104
616
                for span in &spans.multi_line {
105
616
                    notes.push(format!(
106
616
                        "on line {} (column {}) through line {} (column {})",
107
616
                        span.start.line,
108
616
                        span.start.column,
109
616
                        span.end.line,
110
616
                        span.end.column - 1
111
616
                    ));
112
616
                }
113
616
                writeln!(f, "{}", notes.join("\n"))?;
114
6.00k
            }
115
6.62k
            write!(f, "error: {}", self.err)?;
116
        } else {
117
10.4k
            writeln!(f, "regex parse error:")?;
118
10.4k
            let notated = Spans::from_formatter(self).notate();
119
10.4k
            write!(f, "{notated}")?;
120
10.4k
            write!(f, "error: {}", self.err)?;
121
        }
122
17.0k
        Ok(())
123
17.0k
    }
<regex_syntax::error::Formatter<regex_syntax::ast::ErrorKind> as core::fmt::Display>::fmt
Line
Count
Source
90
16.3k
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
91
16.3k
        let spans = Spans::from_formatter(self);
92
16.3k
        if self.pattern.contains('\n') {
93
6.53k
            let divider = repeat_char('~', 79);
94
95
6.53k
            writeln!(f, "regex parse error:")?;
96
6.53k
            writeln!(f, "{divider}")?;
97
6.53k
            let notated = spans.notate();
98
6.53k
            write!(f, "{notated}")?;
99
6.53k
            writeln!(f, "{divider}")?;
100
            // If we have error spans that cover multiple lines, then we just
101
            // note the line numbers.
102
6.53k
            if !spans.multi_line.is_empty() {
103
584
                let mut notes = vec![];
104
584
                for span in &spans.multi_line {
105
584
                    notes.push(format!(
106
584
                        "on line {} (column {}) through line {} (column {})",
107
584
                        span.start.line,
108
584
                        span.start.column,
109
584
                        span.end.line,
110
584
                        span.end.column - 1
111
584
                    ));
112
584
                }
113
584
                writeln!(f, "{}", notes.join("\n"))?;
114
5.95k
            }
115
6.53k
            write!(f, "error: {}", self.err)?;
116
        } else {
117
9.84k
            writeln!(f, "regex parse error:")?;
118
9.84k
            let notated = Spans::from_formatter(self).notate();
119
9.84k
            write!(f, "{notated}")?;
120
9.84k
            write!(f, "error: {}", self.err)?;
121
        }
122
16.3k
        Ok(())
123
16.3k
    }
<regex_syntax::error::Formatter<regex_syntax::hir::ErrorKind> as core::fmt::Display>::fmt
Line
Count
Source
90
678
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
91
678
        let spans = Spans::from_formatter(self);
92
678
        if self.pattern.contains('\n') {
93
84
            let divider = repeat_char('~', 79);
94
95
84
            writeln!(f, "regex parse error:")?;
96
84
            writeln!(f, "{divider}")?;
97
84
            let notated = spans.notate();
98
84
            write!(f, "{notated}")?;
99
84
            writeln!(f, "{divider}")?;
100
            // If we have error spans that cover multiple lines, then we just
101
            // note the line numbers.
102
84
            if !spans.multi_line.is_empty() {
103
32
                let mut notes = vec![];
104
32
                for span in &spans.multi_line {
105
32
                    notes.push(format!(
106
32
                        "on line {} (column {}) through line {} (column {})",
107
32
                        span.start.line,
108
32
                        span.start.column,
109
32
                        span.end.line,
110
32
                        span.end.column - 1
111
32
                    ));
112
32
                }
113
32
                writeln!(f, "{}", notes.join("\n"))?;
114
52
            }
115
84
            write!(f, "error: {}", self.err)?;
116
        } else {
117
594
            writeln!(f, "regex parse error:")?;
118
594
            let notated = Spans::from_formatter(self).notate();
119
594
            write!(f, "{notated}")?;
120
594
            write!(f, "error: {}", self.err)?;
121
        }
122
678
        Ok(())
123
678
    }
124
}
125
126
/// This type represents an arbitrary number of error spans in a way that makes
127
/// it convenient to notate the regex pattern. ("Notate" means "point out
128
/// exactly where the error occurred in the regex pattern.")
129
///
130
/// Technically, we can only ever have two spans given our current error
131
/// structure. However, after toiling with a specific algorithm for handling
132
/// two spans, it became obvious that an algorithm to handle an arbitrary
133
/// number of spans was actually much simpler.
134
struct Spans<'p> {
135
    /// The original regex pattern string.
136
    pattern: &'p str,
137
    /// The total width that should be used for line numbers. The width is
138
    /// used for left padding the line numbers for alignment.
139
    ///
140
    /// A value of `0` means line numbers should not be displayed. That is,
141
    /// the pattern is itself only one line.
142
    line_number_width: usize,
143
    /// All error spans that occur on a single line. This sequence always has
144
    /// length equivalent to the number of lines in `pattern`, where the index
145
    /// of the sequence represents a line number, starting at `0`. The spans
146
    /// in each line are sorted in ascending order.
147
    by_line: Vec<Vec<ast::Span>>,
148
    /// All error spans that occur over one or more lines. That is, the start
149
    /// and end position of the span have different line numbers. The spans are
150
    /// sorted in ascending order.
151
    multi_line: Vec<ast::Span>,
152
}
153
154
impl<'p> Spans<'p> {
155
    /// Build a sequence of spans from a formatter.
156
27.5k
    fn from_formatter<'e, E: core::fmt::Display>(
157
27.5k
        fmter: &'p Formatter<'e, E>,
158
27.5k
    ) -> Spans<'p> {
159
27.5k
        let mut line_count = fmter.pattern.lines().count();
160
        // If the pattern ends with a `\n` literal, then our line count is
161
        // off by one, since a span can occur immediately after the last `\n`,
162
        // which is consider to be an additional line.
163
27.5k
        if fmter.pattern.ends_with('\n') {
164
421
            line_count += 1;
165
27.0k
        }
166
27.5k
        let line_number_width =
167
27.5k
            if line_count <= 1 { 0 } else { line_count.to_string().len() };
168
27.5k
        let mut spans = Spans {
169
27.5k
            pattern: &fmter.pattern,
170
27.5k
            line_number_width,
171
27.5k
            by_line: vec![vec![]; line_count],
172
27.5k
            multi_line: vec![],
173
27.5k
        };
174
27.5k
        spans.add(fmter.span.clone());
175
27.5k
        if let Some(span) = fmter.aux_span {
176
1.58k
            spans.add(span.clone());
177
25.9k
        }
178
27.5k
        spans
179
27.5k
    }
<regex_syntax::error::Spans>::from_formatter::<regex_syntax::ast::ErrorKind>
Line
Count
Source
156
26.2k
    fn from_formatter<'e, E: core::fmt::Display>(
157
26.2k
        fmter: &'p Formatter<'e, E>,
158
26.2k
    ) -> Spans<'p> {
159
26.2k
        let mut line_count = fmter.pattern.lines().count();
160
        // If the pattern ends with a `\n` literal, then our line count is
161
        // off by one, since a span can occur immediately after the last `\n`,
162
        // which is consider to be an additional line.
163
26.2k
        if fmter.pattern.ends_with('\n') {
164
415
            line_count += 1;
165
25.8k
        }
166
26.2k
        let line_number_width =
167
26.2k
            if line_count <= 1 { 0 } else { line_count.to_string().len() };
168
26.2k
        let mut spans = Spans {
169
26.2k
            pattern: &fmter.pattern,
170
26.2k
            line_number_width,
171
26.2k
            by_line: vec![vec![]; line_count],
172
26.2k
            multi_line: vec![],
173
26.2k
        };
174
26.2k
        spans.add(fmter.span.clone());
175
26.2k
        if let Some(span) = fmter.aux_span {
176
1.58k
            spans.add(span.clone());
177
24.6k
        }
178
26.2k
        spans
179
26.2k
    }
<regex_syntax::error::Spans>::from_formatter::<regex_syntax::hir::ErrorKind>
Line
Count
Source
156
1.27k
    fn from_formatter<'e, E: core::fmt::Display>(
157
1.27k
        fmter: &'p Formatter<'e, E>,
158
1.27k
    ) -> Spans<'p> {
159
1.27k
        let mut line_count = fmter.pattern.lines().count();
160
        // If the pattern ends with a `\n` literal, then our line count is
161
        // off by one, since a span can occur immediately after the last `\n`,
162
        // which is consider to be an additional line.
163
1.27k
        if fmter.pattern.ends_with('\n') {
164
6
            line_count += 1;
165
1.26k
        }
166
1.27k
        let line_number_width =
167
1.27k
            if line_count <= 1 { 0 } else { line_count.to_string().len() };
168
1.27k
        let mut spans = Spans {
169
1.27k
            pattern: &fmter.pattern,
170
1.27k
            line_number_width,
171
1.27k
            by_line: vec![vec![]; line_count],
172
1.27k
            multi_line: vec![],
173
1.27k
        };
174
1.27k
        spans.add(fmter.span.clone());
175
1.27k
        if let Some(span) = fmter.aux_span {
176
0
            spans.add(span.clone());
177
1.27k
        }
178
1.27k
        spans
179
1.27k
    }
180
181
    /// Add the given span to this sequence, putting it in the right place.
182
29.0k
    fn add(&mut self, span: ast::Span) {
183
        // This is grossly inefficient since we sort after each add, but right
184
        // now, we only ever add two spans at most.
185
29.0k
        if span.is_one_line() {
186
28.4k
            let i = span.start.line - 1; // because lines are 1-indexed
187
28.4k
            self.by_line[i].push(span);
188
28.4k
            self.by_line[i].sort();
189
28.4k
        } else {
190
616
            self.multi_line.push(span);
191
616
            self.multi_line.sort();
192
616
        }
193
29.0k
    }
194
195
    /// Notate the pattern string with carets (`^`) pointing at each span
196
    /// location. This only applies to spans that occur within a single line.
197
17.0k
    fn notate(&self) -> String {
198
17.0k
        let mut notated = String::new();
199
7.69M
        for (i, line) in self.pattern.lines().enumerate() {
200
7.69M
            if self.line_number_width > 0 {
201
7.68M
                notated.push_str(&self.left_pad_line_number(i + 1));
202
7.68M
                notated.push_str(": ");
203
7.68M
            } else {
204
10.4k
                notated.push_str("    ");
205
10.4k
            }
206
7.69M
            notated.push_str(line);
207
7.69M
            notated.push('\n');
208
7.69M
            if let Some(notes) = self.notate_line(i) {
209
16.4k
                notated.push_str(&notes);
210
16.4k
                notated.push('\n');
211
7.67M
            }
212
        }
213
17.0k
        notated
214
17.0k
    }
215
216
    /// Return notes for the line indexed at `i` (zero-based). If there are no
217
    /// spans for the given line, then `None` is returned. Otherwise, an
218
    /// appropriately space padded string with correctly positioned `^` is
219
    /// returned, accounting for line numbers.
220
7.69M
    fn notate_line(&self, i: usize) -> Option<String> {
221
7.69M
        let spans = &self.by_line[i];
222
7.69M
        if spans.is_empty() {
223
7.67M
            return None;
224
16.4k
        }
225
16.4k
        let mut notes = String::new();
226
61.2k
        for _ in 0..self.line_number_padding() {
227
61.2k
            notes.push(' ');
228
61.2k
        }
229
16.4k
        let mut pos = 0;
230
17.8k
        for span in spans {
231
12.8M
            for _ in pos..(span.start.column - 1) {
232
12.8M
                notes.push(' ');
233
12.8M
                pos += 1;
234
12.8M
            }
235
17.8k
            let note_len = span.end.column.saturating_sub(span.start.column);
236
4.83M
            for _ in 0..core::cmp::max(1, note_len) {
237
4.83M
                notes.push('^');
238
4.83M
                pos += 1;
239
4.83M
            }
240
        }
241
16.4k
        Some(notes)
242
7.69M
    }
243
244
    /// Left pad the given line number with spaces such that it is aligned with
245
    /// other line numbers.
246
7.68M
    fn left_pad_line_number(&self, n: usize) -> String {
247
7.68M
        let n = n.to_string();
248
7.68M
        let pad = self.line_number_width.checked_sub(n.len()).unwrap();
249
7.68M
        let mut result = repeat_char(' ', pad);
250
7.68M
        result.push_str(&n);
251
7.68M
        result
252
7.68M
    }
253
254
    /// Return the line number padding beginning at the start of each line of
255
    /// the pattern.
256
    ///
257
    /// If the pattern is only one line, then this returns a fixed padding
258
    /// for visual indentation.
259
16.4k
    fn line_number_padding(&self) -> usize {
260
16.4k
        if self.line_number_width == 0 {
261
10.4k
            4
262
        } else {
263
6.01k
            2 + self.line_number_width
264
        }
265
16.4k
    }
266
}
267
268
7.69M
fn repeat_char(c: char, count: usize) -> String {
269
7.69M
    core::iter::repeat(c).take(count).collect()
270
7.69M
}
271
272
#[cfg(test)]
273
mod tests {
274
    use alloc::string::ToString;
275
276
    use crate::ast::parse::Parser;
277
278
    fn assert_panic_message(pattern: &str, expected_msg: &str) {
279
        let result = Parser::new().parse(pattern);
280
        match result {
281
            Ok(_) => {
282
                panic!("regex should not have parsed");
283
            }
284
            Err(err) => {
285
                assert_eq!(err.to_string(), expected_msg.trim());
286
            }
287
        }
288
    }
289
290
    // See: https://github.com/rust-lang/regex/issues/464
291
    #[test]
292
    fn regression_464() {
293
        let err = Parser::new().parse("a{\n").unwrap_err();
294
        // This test checks that the error formatter doesn't panic.
295
        assert!(!err.to_string().is_empty());
296
    }
297
298
    // See: https://github.com/rust-lang/regex/issues/545
299
    #[test]
300
    fn repetition_quantifier_expects_a_valid_decimal() {
301
        assert_panic_message(
302
            r"\\u{[^}]*}",
303
            r#"
304
regex parse error:
305
    \\u{[^}]*}
306
        ^
307
error: repetition quantifier expects a valid decimal
308
"#,
309
        );
310
    }
311
}