Coverage Report

Created: 2025-11-24 06:19

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/regex-automata-0.4.13/src/util/interpolate.rs
Line
Count
Source
1
/*!
2
Provides routines for interpolating capture group references.
3
4
That is, if a replacement string contains references like `$foo` or `${foo1}`,
5
then they are replaced with the corresponding capture values for the groups
6
named `foo` and `foo1`, respectively. Similarly, syntax like `$1` and `${1}`
7
is supported as well, with `1` corresponding to a capture group index and not
8
a name.
9
10
This module provides the free functions [`string`] and [`bytes`], which
11
interpolate Rust Unicode strings and byte strings, respectively.
12
13
# Format
14
15
These routines support two different kinds of capture references: unbraced and
16
braced.
17
18
For the unbraced format, the format supported is `$ref` where `name` can be
19
any character in the class `[0-9A-Za-z_]`. `ref` is always the longest
20
possible parse. So for example, `$1a` corresponds to the capture group named
21
`1a` and not the capture group at index `1`. If `ref` matches `^[0-9]+$`, then
22
it is treated as a capture group index itself and not a name.
23
24
For the braced format, the format supported is `${ref}` where `ref` can be any
25
sequence of bytes except for `}`. If no closing brace occurs, then it is not
26
considered a capture reference. As with the unbraced format, if `ref` matches
27
`^[0-9]+$`, then it is treated as a capture group index and not a name.
28
29
The braced format is useful for exerting precise control over the name of the
30
capture reference. For example, `${1}a` corresponds to the capture group
31
reference `1` followed by the letter `a`, where as `$1a` (as mentioned above)
32
corresponds to the capture group reference `1a`. The braced format is also
33
useful for expressing capture group names that use characters not supported by
34
the unbraced format. For example, `${foo[bar].baz}` refers to the capture group
35
named `foo[bar].baz`.
36
37
If a capture group reference is found and it does not refer to a valid capture
38
group, then it will be replaced with the empty string.
39
40
To write a literal `$`, use `$$`.
41
42
To be clear, and as exhibited via the type signatures in the routines in this
43
module, it is impossible for a replacement string to be invalid. A replacement
44
string may not have the intended semantics, but the interpolation procedure
45
itself can never fail.
46
*/
47
48
use alloc::{string::String, vec::Vec};
49
50
use crate::util::memchr::memchr;
51
52
/// Accepts a replacement string and interpolates capture references with their
53
/// corresponding values.
54
///
55
/// `append` should be a function that appends the string value of a capture
56
/// group at a particular index to the string given. If the capture group
57
/// index is invalid, then nothing should be appended.
58
///
59
/// `name_to_index` should be a function that maps a capture group name to a
60
/// capture group index. If the given name doesn't exist, then `None` should
61
/// be returned.
62
///
63
/// Finally, `dst` is where the final interpolated contents should be written.
64
/// If `replacement` contains no capture group references, then `dst` will be
65
/// equivalent to `replacement`.
66
///
67
/// See the [module documentation](self) for details about the format
68
/// supported.
69
///
70
/// # Example
71
///
72
/// ```
73
/// use regex_automata::util::interpolate;
74
///
75
/// let mut dst = String::new();
76
/// interpolate::string(
77
///     "foo $bar baz",
78
///     |index, dst| {
79
///         if index == 0 {
80
///             dst.push_str("BAR");
81
///         }
82
///     },
83
///     |name| {
84
///         if name == "bar" {
85
///             Some(0)
86
///         } else {
87
///             None
88
///         }
89
///     },
90
///     &mut dst,
91
/// );
92
/// assert_eq!("foo BAR baz", dst);
93
/// ```
94
0
pub fn string(
95
0
    mut replacement: &str,
96
0
    mut append: impl FnMut(usize, &mut String),
97
0
    mut name_to_index: impl FnMut(&str) -> Option<usize>,
98
0
    dst: &mut String,
99
0
) {
100
0
    while !replacement.is_empty() {
101
0
        match memchr(b'$', replacement.as_bytes()) {
102
0
            None => break,
103
0
            Some(i) => {
104
0
                dst.push_str(&replacement[..i]);
105
0
                replacement = &replacement[i..];
106
0
            }
107
        }
108
        // Handle escaping of '$'.
109
0
        if replacement.as_bytes().get(1).map_or(false, |&b| b == b'$') {
110
0
            dst.push_str("$");
111
0
            replacement = &replacement[2..];
112
0
            continue;
113
0
        }
114
0
        debug_assert!(!replacement.is_empty());
115
0
        let cap_ref = match find_cap_ref(replacement.as_bytes()) {
116
0
            Some(cap_ref) => cap_ref,
117
            None => {
118
0
                dst.push_str("$");
119
0
                replacement = &replacement[1..];
120
0
                continue;
121
            }
122
        };
123
0
        replacement = &replacement[cap_ref.end..];
124
0
        match cap_ref.cap {
125
0
            Ref::Number(i) => append(i, dst),
126
0
            Ref::Named(name) => {
127
0
                if let Some(i) = name_to_index(name) {
128
0
                    append(i, dst);
129
0
                }
130
            }
131
        }
132
    }
133
0
    dst.push_str(replacement);
134
0
}
135
136
/// Accepts a replacement byte string and interpolates capture references with
137
/// their corresponding values.
138
///
139
/// `append` should be a function that appends the byte string value of a
140
/// capture group at a particular index to the byte string given. If the
141
/// capture group index is invalid, then nothing should be appended.
142
///
143
/// `name_to_index` should be a function that maps a capture group name to a
144
/// capture group index. If the given name doesn't exist, then `None` should
145
/// be returned.
146
///
147
/// Finally, `dst` is where the final interpolated contents should be written.
148
/// If `replacement` contains no capture group references, then `dst` will be
149
/// equivalent to `replacement`.
150
///
151
/// See the [module documentation](self) for details about the format
152
/// supported.
153
///
154
/// # Example
155
///
156
/// ```
157
/// use regex_automata::util::interpolate;
158
///
159
/// let mut dst = vec![];
160
/// interpolate::bytes(
161
///     b"foo $bar baz",
162
///     |index, dst| {
163
///         if index == 0 {
164
///             dst.extend_from_slice(b"BAR");
165
///         }
166
///     },
167
///     |name| {
168
///         if name == "bar" {
169
///             Some(0)
170
///         } else {
171
///             None
172
///         }
173
///     },
174
///     &mut dst,
175
/// );
176
/// assert_eq!(&b"foo BAR baz"[..], dst);
177
/// ```
178
0
pub fn bytes(
179
0
    mut replacement: &[u8],
180
0
    mut append: impl FnMut(usize, &mut Vec<u8>),
181
0
    mut name_to_index: impl FnMut(&str) -> Option<usize>,
182
0
    dst: &mut Vec<u8>,
183
0
) {
184
0
    while !replacement.is_empty() {
185
0
        match memchr(b'$', replacement) {
186
0
            None => break,
187
0
            Some(i) => {
188
0
                dst.extend_from_slice(&replacement[..i]);
189
0
                replacement = &replacement[i..];
190
0
            }
191
        }
192
        // Handle escaping of '$'.
193
0
        if replacement.get(1).map_or(false, |&b| b == b'$') {
194
0
            dst.push(b'$');
195
0
            replacement = &replacement[2..];
196
0
            continue;
197
0
        }
198
0
        debug_assert!(!replacement.is_empty());
199
0
        let cap_ref = match find_cap_ref(replacement) {
200
0
            Some(cap_ref) => cap_ref,
201
            None => {
202
0
                dst.push(b'$');
203
0
                replacement = &replacement[1..];
204
0
                continue;
205
            }
206
        };
207
0
        replacement = &replacement[cap_ref.end..];
208
0
        match cap_ref.cap {
209
0
            Ref::Number(i) => append(i, dst),
210
0
            Ref::Named(name) => {
211
0
                if let Some(i) = name_to_index(name) {
212
0
                    append(i, dst);
213
0
                }
214
            }
215
        }
216
    }
217
0
    dst.extend_from_slice(replacement);
218
0
}
219
220
/// `CaptureRef` represents a reference to a capture group inside some text.
221
/// The reference is either a capture group name or a number.
222
///
223
/// It is also tagged with the position in the text following the
224
/// capture reference.
225
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
226
struct CaptureRef<'a> {
227
    cap: Ref<'a>,
228
    end: usize,
229
}
230
231
/// A reference to a capture group in some text.
232
///
233
/// e.g., `$2`, `$foo`, `${foo}`.
234
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
235
enum Ref<'a> {
236
    Named(&'a str),
237
    Number(usize),
238
}
239
240
impl<'a> From<&'a str> for Ref<'a> {
241
0
    fn from(x: &'a str) -> Ref<'a> {
242
0
        Ref::Named(x)
243
0
    }
244
}
245
246
impl From<usize> for Ref<'static> {
247
0
    fn from(x: usize) -> Ref<'static> {
248
0
        Ref::Number(x)
249
0
    }
250
}
251
252
/// Parses a possible reference to a capture group name in the given text,
253
/// starting at the beginning of `replacement`.
254
///
255
/// If no such valid reference could be found, None is returned.
256
///
257
/// Note that this returns a "possible" reference because this routine doesn't
258
/// know whether the reference is to a valid group or not. If it winds up not
259
/// being a valid reference, then it should be replaced with the empty string.
260
0
fn find_cap_ref(replacement: &[u8]) -> Option<CaptureRef<'_>> {
261
0
    let mut i = 0;
262
0
    let rep: &[u8] = replacement;
263
0
    if rep.len() <= 1 || rep[0] != b'$' {
264
0
        return None;
265
0
    }
266
0
    i += 1;
267
0
    if rep[i] == b'{' {
268
0
        return find_cap_ref_braced(rep, i + 1);
269
0
    }
270
0
    let mut cap_end = i;
271
0
    while rep.get(cap_end).copied().map_or(false, is_valid_cap_letter) {
272
0
        cap_end += 1;
273
0
    }
274
0
    if cap_end == i {
275
0
        return None;
276
0
    }
277
    // We just verified that the range 0..cap_end is valid ASCII, so it must
278
    // therefore be valid UTF-8. If we really cared, we could avoid this UTF-8
279
    // check via an unchecked conversion or by parsing the number straight from
280
    // &[u8].
281
0
    let cap = core::str::from_utf8(&rep[i..cap_end])
282
0
        .expect("valid UTF-8 capture name");
283
    Some(CaptureRef {
284
0
        cap: match cap.parse::<usize>() {
285
0
            Ok(i) => Ref::Number(i),
286
0
            Err(_) => Ref::Named(cap),
287
        },
288
0
        end: cap_end,
289
    })
290
0
}
291
292
/// Looks for a braced reference, e.g., `${foo1}`. This assumes that an opening
293
/// brace has been found at `i-1` in `rep`. This then looks for a closing
294
/// brace and returns the capture reference within the brace.
295
0
fn find_cap_ref_braced(rep: &[u8], mut i: usize) -> Option<CaptureRef<'_>> {
296
0
    assert_eq!(b'{', rep[i.checked_sub(1).unwrap()]);
297
0
    let start = i;
298
0
    while rep.get(i).map_or(false, |&b| b != b'}') {
299
0
        i += 1;
300
0
    }
301
0
    if !rep.get(i).map_or(false, |&b| b == b'}') {
302
0
        return None;
303
0
    }
304
    // When looking at braced names, we don't put any restrictions on the name,
305
    // so it's possible it could be invalid UTF-8. But a capture group name
306
    // can never be invalid UTF-8, so if we have invalid UTF-8, then we can
307
    // safely return None.
308
0
    let cap = match core::str::from_utf8(&rep[start..i]) {
309
0
        Err(_) => return None,
310
0
        Ok(cap) => cap,
311
    };
312
    Some(CaptureRef {
313
0
        cap: match cap.parse::<usize>() {
314
0
            Ok(i) => Ref::Number(i),
315
0
            Err(_) => Ref::Named(cap),
316
        },
317
0
        end: i + 1,
318
    })
319
0
}
320
321
/// Returns true if and only if the given byte is allowed in a capture name
322
/// written in non-brace form.
323
0
fn is_valid_cap_letter(b: u8) -> bool {
324
0
    matches!(b, b'0'..=b'9' | b'a'..=b'z' | b'A'..=b'Z' | b'_')
325
0
}
326
327
#[cfg(test)]
328
mod tests {
329
    use alloc::{string::String, vec, vec::Vec};
330
331
    use super::{find_cap_ref, CaptureRef};
332
333
    macro_rules! find {
334
        ($name:ident, $text:expr) => {
335
            #[test]
336
            fn $name() {
337
                assert_eq!(None, find_cap_ref($text.as_bytes()));
338
            }
339
        };
340
        ($name:ident, $text:expr, $capref:expr) => {
341
            #[test]
342
            fn $name() {
343
                assert_eq!(Some($capref), find_cap_ref($text.as_bytes()));
344
            }
345
        };
346
    }
347
348
    macro_rules! c {
349
        ($name_or_number:expr, $pos:expr) => {
350
            CaptureRef { cap: $name_or_number.into(), end: $pos }
351
        };
352
    }
353
354
    find!(find_cap_ref1, "$foo", c!("foo", 4));
355
    find!(find_cap_ref2, "${foo}", c!("foo", 6));
356
    find!(find_cap_ref3, "$0", c!(0, 2));
357
    find!(find_cap_ref4, "$5", c!(5, 2));
358
    find!(find_cap_ref5, "$10", c!(10, 3));
359
    // See https://github.com/rust-lang/regex/pull/585
360
    // for more on characters following numbers
361
    find!(find_cap_ref6, "$42a", c!("42a", 4));
362
    find!(find_cap_ref7, "${42}a", c!(42, 5));
363
    find!(find_cap_ref8, "${42");
364
    find!(find_cap_ref9, "${42 ");
365
    find!(find_cap_ref10, " $0 ");
366
    find!(find_cap_ref11, "$");
367
    find!(find_cap_ref12, " ");
368
    find!(find_cap_ref13, "");
369
    find!(find_cap_ref14, "$1-$2", c!(1, 2));
370
    find!(find_cap_ref15, "$1_$2", c!("1_", 3));
371
    find!(find_cap_ref16, "$x-$y", c!("x", 2));
372
    find!(find_cap_ref17, "$x_$y", c!("x_", 3));
373
    find!(find_cap_ref18, "${#}", c!("#", 4));
374
    find!(find_cap_ref19, "${Z[}", c!("Z[", 5));
375
    find!(find_cap_ref20, "${¾}", c!("¾", 5));
376
    find!(find_cap_ref21, "${¾a}", c!("¾a", 6));
377
    find!(find_cap_ref22, "${a¾}", c!("a¾", 6));
378
    find!(find_cap_ref23, "${☃}", c!("☃", 6));
379
    find!(find_cap_ref24, "${a☃}", c!("a☃", 7));
380
    find!(find_cap_ref25, "${☃a}", c!("☃a", 7));
381
    find!(find_cap_ref26, "${名字}", c!("名字", 9));
382
383
    fn interpolate_string(
384
        mut name_to_index: Vec<(&'static str, usize)>,
385
        caps: Vec<&'static str>,
386
        replacement: &str,
387
    ) -> String {
388
        name_to_index.sort_by_key(|x| x.0);
389
390
        let mut dst = String::new();
391
        super::string(
392
            replacement,
393
            |i, dst| {
394
                if let Some(&s) = caps.get(i) {
395
                    dst.push_str(s);
396
                }
397
            },
398
            |name| -> Option<usize> {
399
                name_to_index
400
                    .binary_search_by_key(&name, |x| x.0)
401
                    .ok()
402
                    .map(|i| name_to_index[i].1)
403
            },
404
            &mut dst,
405
        );
406
        dst
407
    }
408
409
    fn interpolate_bytes(
410
        mut name_to_index: Vec<(&'static str, usize)>,
411
        caps: Vec<&'static str>,
412
        replacement: &str,
413
    ) -> String {
414
        name_to_index.sort_by_key(|x| x.0);
415
416
        let mut dst = vec![];
417
        super::bytes(
418
            replacement.as_bytes(),
419
            |i, dst| {
420
                if let Some(&s) = caps.get(i) {
421
                    dst.extend_from_slice(s.as_bytes());
422
                }
423
            },
424
            |name| -> Option<usize> {
425
                name_to_index
426
                    .binary_search_by_key(&name, |x| x.0)
427
                    .ok()
428
                    .map(|i| name_to_index[i].1)
429
            },
430
            &mut dst,
431
        );
432
        String::from_utf8(dst).unwrap()
433
    }
434
435
    macro_rules! interp {
436
        ($name:ident, $map:expr, $caps:expr, $hay:expr, $expected:expr $(,)*) => {
437
            #[test]
438
            fn $name() {
439
                assert_eq!(
440
                    $expected,
441
                    interpolate_string($map, $caps, $hay),
442
                    "interpolate::string failed",
443
                );
444
                assert_eq!(
445
                    $expected,
446
                    interpolate_bytes($map, $caps, $hay),
447
                    "interpolate::bytes failed",
448
                );
449
            }
450
        };
451
    }
452
453
    interp!(
454
        interp1,
455
        vec![("foo", 2)],
456
        vec!["", "", "xxx"],
457
        "test $foo test",
458
        "test xxx test",
459
    );
460
461
    interp!(
462
        interp2,
463
        vec![("foo", 2)],
464
        vec!["", "", "xxx"],
465
        "test$footest",
466
        "test",
467
    );
468
469
    interp!(
470
        interp3,
471
        vec![("foo", 2)],
472
        vec!["", "", "xxx"],
473
        "test${foo}test",
474
        "testxxxtest",
475
    );
476
477
    interp!(
478
        interp4,
479
        vec![("foo", 2)],
480
        vec!["", "", "xxx"],
481
        "test$2test",
482
        "test",
483
    );
484
485
    interp!(
486
        interp5,
487
        vec![("foo", 2)],
488
        vec!["", "", "xxx"],
489
        "test${2}test",
490
        "testxxxtest",
491
    );
492
493
    interp!(
494
        interp6,
495
        vec![("foo", 2)],
496
        vec!["", "", "xxx"],
497
        "test $$foo test",
498
        "test $foo test",
499
    );
500
501
    interp!(
502
        interp7,
503
        vec![("foo", 2)],
504
        vec!["", "", "xxx"],
505
        "test $foo",
506
        "test xxx",
507
    );
508
509
    interp!(
510
        interp8,
511
        vec![("foo", 2)],
512
        vec!["", "", "xxx"],
513
        "$foo test",
514
        "xxx test",
515
    );
516
517
    interp!(
518
        interp9,
519
        vec![("bar", 1), ("foo", 2)],
520
        vec!["", "yyy", "xxx"],
521
        "test $bar$foo",
522
        "test yyyxxx",
523
    );
524
525
    interp!(
526
        interp10,
527
        vec![("bar", 1), ("foo", 2)],
528
        vec!["", "yyy", "xxx"],
529
        "test $ test",
530
        "test $ test",
531
    );
532
533
    interp!(
534
        interp11,
535
        vec![("bar", 1), ("foo", 2)],
536
        vec!["", "yyy", "xxx"],
537
        "test ${} test",
538
        "test  test",
539
    );
540
541
    interp!(
542
        interp12,
543
        vec![("bar", 1), ("foo", 2)],
544
        vec!["", "yyy", "xxx"],
545
        "test ${ } test",
546
        "test  test",
547
    );
548
549
    interp!(
550
        interp13,
551
        vec![("bar", 1), ("foo", 2)],
552
        vec!["", "yyy", "xxx"],
553
        "test ${a b} test",
554
        "test  test",
555
    );
556
557
    interp!(
558
        interp14,
559
        vec![("bar", 1), ("foo", 2)],
560
        vec!["", "yyy", "xxx"],
561
        "test ${a} test",
562
        "test  test",
563
    );
564
565
    // This is a funny case where a braced reference is never closed, but
566
    // within the unclosed braced reference, there is an unbraced reference.
567
    // In this case, the braced reference is just treated literally and the
568
    // unbraced reference is found.
569
    interp!(
570
        interp15,
571
        vec![("bar", 1), ("foo", 2)],
572
        vec!["", "yyy", "xxx"],
573
        "test ${wat $bar ok",
574
        "test ${wat yyy ok",
575
    );
576
}