Debian Codegraph @

third_party/rust/regex-automata/src/util/captures.rs

raw
1 /*!
2 Provides types for dealing with capturing groups.
3
4 Capturing groups refer to sub-patterns of regexes that some regex engines can
5 report matching offsets for. For example, matching `[a-z]([0-9]+)` against
6 `a789` would give `a789` as the overall match (for the implicit capturing group
7 at index `0`) and `789` as the match for the capturing group `([0-9]+)` (an
8 explicit capturing group at index `1`).
9
10 Not all regex engines can report match offsets for capturing groups. Indeed,
11 to a first approximation, regex engines that can report capturing group offsets
12 tend to be quite a bit slower than regex engines that can't. This is because
13 tracking capturing groups at search time usually requires more "power" that
14 in turn adds overhead.
15
16 Other regex implementations might call capturing groups "submatches."
17
18 # Overview
19
20 The main types in this module are:
21
22 * [`Captures`] records the capturing group offsets found during a search. It
23 provides convenience routines for looking up capturing group offsets by either
24 index or name.
25 * [`GroupInfo`] records the mapping between capturing groups and "slots,"
26 where the latter are how capturing groups are recorded during a regex search.
27 This also keeps a mapping from capturing group name to index, and capture
28 group index to name. A `GroupInfo` is used by `Captures` internally to
29 provide a convenient API. It is unlikely that you'll use a `GroupInfo`
30 directly, but for example, if you've compiled an Thompson NFA, then you can use
31 [`thompson::NFA::group_info`](crate::nfa::thompson::NFA::group_info) to get its
32 underlying `GroupInfo`.
33 */
34
35 use alloc::{string::String, sync::Arc, vec, vec::Vec};
36
37 use crate::util::{
38 interpolate,
39 primitives::{
40 NonMaxUsize, PatternID, PatternIDError, PatternIDIter, SmallIndex,
41 },
42 search::{Match, Span},
43 };
44
45 /// The span offsets of capturing groups after a match has been found.
46 ///
47 /// This type represents the output of regex engines that can report the
48 /// offsets at which capturing groups matches or "submatches" occur. For
49 /// example, the [`PikeVM`](crate::nfa::thompson::pikevm::PikeVM). When a match
50 /// occurs, it will at minimum contain the [`PatternID`] of the pattern that
51 /// matched. Depending upon how it was constructed, it may also contain the
52 /// start/end offsets of the entire match of the pattern and the start/end
53 /// offsets of each capturing group that participated in the match.
54 ///
55 /// Values of this type are always created for a specific [`GroupInfo`]. It is
56 /// unspecified behavior to use a `Captures` value in a search with any regex
57 /// engine that has a different `GroupInfo` than the one the `Captures` were
58 /// created with.
59 ///
60 /// # Constructors
61 ///
62 /// There are three constructors for this type that control what kind of
63 /// information is available upon a match:
64 ///
65 /// * [`Captures::all`]: Will store overall pattern match offsets in addition
66 /// to the offsets of capturing groups that participated in the match.
67 /// * [`Captures::matches`]: Will store only the overall pattern
68 /// match offsets. The offsets of capturing groups (even ones that participated
69 /// in the match) are not available.
70 /// * [`Captures::empty`]: Will only store the pattern ID that matched. No
71 /// match offsets are available at all.
72 ///
73 /// If you aren't sure which to choose, then pick the first one. The first one
74 /// is what convenience routines like,
75 /// [`PikeVM::create_captures`](crate::nfa::thompson::pikevm::PikeVM::create_captures),
76 /// will use automatically.
77 ///
78 /// The main difference between these choices is performance. Namely, if you
79 /// ask for _less_ information, then the execution of regex search may be able
80 /// to run more quickly.
81 ///
82 /// # Notes
83 ///
84 /// It is worth pointing out that this type is not coupled to any one specific
85 /// regex engine. Instead, its coupling is with [`GroupInfo`], which is the
86 /// thing that is responsible for mapping capturing groups to "slot" offsets.
87 /// Slot offsets are indices into a single sequence of memory at which matching
88 /// haystack offsets for the corresponding group are written by regex engines.
89 ///
90 /// # Example
91 ///
92 /// This example shows how to parse a simple date and extract the components of
93 /// the date via capturing groups:
94 ///
95 /// ```
96 /// use regex_automata::{nfa::thompson::pikevm::PikeVM, Span};
97 ///
98 /// let re = PikeVM::new(r"^([0-9]{4})-([0-9]{2})-([0-9]{2})$")?;
99 /// let (mut cache, mut caps) = (re.create_cache(), re.create_captures());
100 ///
101 /// re.captures(&mut cache, "2010-03-14", &mut caps);
102 /// assert!(caps.is_match());
103 /// assert_eq!(Some(Span::from(0..4)), caps.get_group(1));
104 /// assert_eq!(Some(Span::from(5..7)), caps.get_group(2));
105 /// assert_eq!(Some(Span::from(8..10)), caps.get_group(3));
106 ///
107 /// # Ok::<(), Box<dyn std::error::Error>>(())
108 /// ```
109 ///
110 /// # Example: named capturing groups
111 ///
112 /// This example is like the one above, but leverages the ability to name
113 /// capturing groups in order to make the code a bit clearer:
114 ///
115 /// ```
116 /// use regex_automata::{nfa::thompson::pikevm::PikeVM, Span};
117 ///
118 /// let re = PikeVM::new(r"^(?P<y>[0-9]{4})-(?P<m>[0-9]{2})-(?P<d>[0-9]{2})$")?;
119 /// let (mut cache, mut caps) = (re.create_cache(), re.create_captures());
120 ///
121 /// re.captures(&mut cache, "2010-03-14", &mut caps);
122 /// assert!(caps.is_match());
123 /// assert_eq!(Some(Span::from(0..4)), caps.get_group_by_name("y"));
124 /// assert_eq!(Some(Span::from(5..7)), caps.get_group_by_name("m"));
125 /// assert_eq!(Some(Span::from(8..10)), caps.get_group_by_name("d"));
126 ///
127 /// # Ok::<(), Box<dyn std::error::Error>>(())
128 /// ```
129 #[derive(Clone)]
130 pub struct Captures {
131 /// The group info that these capture groups are coupled to. This is what
132 /// gives the "convenience" of the `Captures` API. Namely, it provides the
133 /// slot mapping and the name|-->index mapping for capture lookups by name.
134 group_info: GroupInfo,
135 /// The ID of the pattern that matched. Regex engines must set this to
136 /// None when no match occurs.
137 pid: Option<PatternID>,
138 /// The slot values, i.e., submatch offsets.
139 ///
140 /// In theory, the smallest sequence of slots would be something like
141 /// `max(groups(pattern) for pattern in regex) * 2`, but instead, we use
142 /// `sum(groups(pattern) for pattern in regex) * 2`. Why?
143 ///
144 /// Well, the former could be used in theory, because we don't generally
145 /// have any overlapping APIs that involve capturing groups. Therefore,
146 /// there's technically never any need to have slots set for multiple
147 /// patterns. However, this might change some day, in which case, we would
148 /// need to have slots available.
149 ///
150 /// The other reason is that during the execution of some regex engines,
151 /// there exists a point in time where multiple slots for different
152 /// patterns may be written to before knowing which pattern has matched.
153 /// Therefore, the regex engines themselves, in order to support multiple
154 /// patterns correctly, must have all slots available. If `Captures`
155 /// doesn't have all slots available, then regex engines can't write
156 /// directly into the caller provided `Captures` and must instead write
157 /// into some other storage and then copy the slots involved in the match
158 /// at the end of the search.
159 ///
160 /// So overall, at least as of the time of writing, it seems like the path
161 /// of least resistance is to just require allocating all possible slots
162 /// instead of the conceptual minimum. Another way to justify this is that
163 /// the most common case is a single pattern, in which case, there is no
164 /// inefficiency here since the 'max' and 'sum' calculations above are
165 /// equivalent in that case.
166 ///
167 /// N.B. The mapping from group index to slot is maintained by `GroupInfo`
168 /// and is considered an API guarantee. See `GroupInfo` for more details on
169 /// that mapping.
170 ///
171 /// N.B. `Option<NonMaxUsize>` has the same size as a `usize`.
172 slots: Vec<Option<NonMaxUsize>>,
173 }
174
175 impl Captures {
176 /// Create new storage for the offsets of all matching capturing groups.
177 ///
178 /// This routine provides the most information for matches---namely, the
179 /// spans of matching capturing groups---but also requires the regex search
180 /// routines to do the most work.
181 ///
182 /// It is unspecified behavior to use the returned `Captures` value in a
183 /// search with a `GroupInfo` other than the one that is provided to this
184 /// constructor.
185 ///
186 /// # Example
187 ///
188 /// This example shows that all capturing groups---but only ones that
189 /// participated in a match---are available to query after a match has
190 /// been found:
191 ///
192 /// ```
193 /// use regex_automata::{
194 /// nfa::thompson::pikevm::PikeVM,
195 /// util::captures::Captures,
196 /// Span, Match,
197 /// };
198 ///
199 /// let re = PikeVM::new(
200 /// r"^(?:(?P<lower>[a-z]+)|(?P<upper>[A-Z]+))(?P<digits>[0-9]+)$",
201 /// )?;
202 /// let mut cache = re.create_cache();
203 /// let mut caps = Captures::all(re.get_nfa().group_info().clone());
204 ///
205 /// re.captures(&mut cache, "ABC123", &mut caps);
206 /// assert!(caps.is_match());
207 /// assert_eq!(Some(Match::must(0, 0..6)), caps.get_match());
208 /// // The 'lower' group didn't match, so it won't have any offsets.
209 /// assert_eq!(None, caps.get_group_by_name("lower"));
210 /// assert_eq!(Some(Span::from(0..3)), caps.get_group_by_name("upper"));
211 /// assert_eq!(Some(Span::from(3..6)), caps.get_group_by_name("digits"));
212 ///
213 /// # Ok::<(), Box<dyn std::error::Error>>(())
214 /// ```
215 pub fn all(group_info: GroupInfo) -> Captures {
216 let slots = group_info.slot_len();
217 Captures { group_info, pid: None, slots: vec![None; slots] }
218 }
219
220 /// Create new storage for only the full match spans of a pattern. This
221 /// does not include any capturing group offsets.
222 ///
223 /// It is unspecified behavior to use the returned `Captures` value in a
224 /// search with a `GroupInfo` other than the one that is provided to this
225 /// constructor.
226 ///
227 /// # Example
228 ///
229 /// This example shows that only overall match offsets are reported when
230 /// this constructor is used. Accessing any capturing groups other than
231 /// the 0th will always return `None`.
232 ///
233 /// ```
234 /// use regex_automata::{
235 /// nfa::thompson::pikevm::PikeVM,
236 /// util::captures::Captures,
237 /// Match,
238 /// };
239 ///
240 /// let re = PikeVM::new(
241 /// r"^(?:(?P<lower>[a-z]+)|(?P<upper>[A-Z]+))(?P<digits>[0-9]+)$",
242 /// )?;
243 /// let mut cache = re.create_cache();
244 /// let mut caps = Captures::matches(re.get_nfa().group_info().clone());
245 ///
246 /// re.captures(&mut cache, "ABC123", &mut caps);
247 /// assert!(caps.is_match());
248 /// assert_eq!(Some(Match::must(0, 0..6)), caps.get_match());
249 /// // We didn't ask for capturing group offsets, so they aren't available.
250 /// assert_eq!(None, caps.get_group_by_name("lower"));
251 /// assert_eq!(None, caps.get_group_by_name("upper"));
252 /// assert_eq!(None, caps.get_group_by_name("digits"));
253 ///
254 /// # Ok::<(), Box<dyn std::error::Error>>(())
255 /// ```
256 pub fn matches(group_info: GroupInfo) -> Captures {
257 // This is OK because we know there are at least this many slots,
258 // and GroupInfo construction guarantees that the number of slots fits
259 // into a usize.
260 let slots = group_info.pattern_len().checked_mul(2).unwrap();
261 Captures { group_info, pid: None, slots: vec![None; slots] }
262 }
263
264 /// Create new storage for only tracking which pattern matched. No offsets
265 /// are stored at all.
266 ///
267 /// It is unspecified behavior to use the returned `Captures` value in a
268 /// search with a `GroupInfo` other than the one that is provided to this
269 /// constructor.
270 ///
271 /// # Example
272 ///
273 /// This example shows that only the pattern that matched can be accessed
274 /// from a `Captures` value created via this constructor.
275 ///
276 /// ```
277 /// use regex_automata::{
278 /// nfa::thompson::pikevm::PikeVM,
279 /// util::captures::Captures,
280 /// PatternID,
281 /// };
282 ///
283 /// let re = PikeVM::new_many(&[r"[a-z]+", r"[A-Z]+"])?;
284 /// let mut cache = re.create_cache();
285 /// let mut caps = Captures::empty(re.get_nfa().group_info().clone());
286 ///
287 /// re.captures(&mut cache, "aABCz", &mut caps);
288 /// assert!(caps.is_match());
289 /// assert_eq!(Some(PatternID::must(0)), caps.pattern());
290 /// // We didn't ask for any offsets, so they aren't available.
291 /// assert_eq!(None, caps.get_match());
292 ///
293 /// re.captures(&mut cache, &"aABCz"[1..], &mut caps);
294 /// assert!(caps.is_match());
295 /// assert_eq!(Some(PatternID::must(1)), caps.pattern());
296 /// // We didn't ask for any offsets, so they aren't available.
297 /// assert_eq!(None, caps.get_match());
298 ///
299 /// # Ok::<(), Box<dyn std::error::Error>>(())
300 /// ```
301 pub fn empty(group_info: GroupInfo) -> Captures {
302 Captures { group_info, pid: None, slots: vec![] }
303 }
304
305 /// Returns true if and only if this capturing group represents a match.
306 ///
307 /// This is a convenience routine for `caps.pattern().is_some()`.
308 ///
309 /// # Example
310 ///
311 /// When using the PikeVM (for example), the lightest weight way of
312 /// detecting whether a match exists is to create capturing groups that
313 /// only track the ID of the pattern that match (if any):
314 ///
315 /// ```
316 /// use regex_automata::{
317 /// nfa::thompson::pikevm::PikeVM,
318 /// util::captures::Captures,
319 /// };
320 ///
321 /// let re = PikeVM::new(r"[a-z]+")?;
322 /// let mut cache = re.create_cache();
323 /// let mut caps = Captures::empty(re.get_nfa().group_info().clone());
324 ///
325 /// re.captures(&mut cache, "aABCz", &mut caps);
326 /// assert!(caps.is_match());
327 ///
328 /// # Ok::<(), Box<dyn std::error::Error>>(())
329 /// ```
330 #[inline]
331 pub fn is_match(&self) -> bool {
332 self.pid.is_some()
333 }
334
335 /// Returns the identifier of the pattern that matched when this
336 /// capturing group represents a match. If no match was found, then this
337 /// always returns `None`.
338 ///
339 /// This returns a pattern ID in precisely the cases in which `is_match`
340 /// returns `true`. Similarly, the pattern ID returned is always the
341 /// same pattern ID found in the `Match` returned by `get_match`.
342 ///
343 /// # Example
344 ///
345 /// When using the PikeVM (for example), the lightest weight way of
346 /// detecting which pattern matched is to create capturing groups that only
347 /// track the ID of the pattern that match (if any):
348 ///
349 /// ```
350 /// use regex_automata::{
351 /// nfa::thompson::pikevm::PikeVM,
352 /// util::captures::Captures,
353 /// PatternID,
354 /// };
355 ///
356 /// let re = PikeVM::new_many(&[r"[a-z]+", r"[A-Z]+"])?;
357 /// let mut cache = re.create_cache();
358 /// let mut caps = Captures::empty(re.get_nfa().group_info().clone());
359 ///
360 /// re.captures(&mut cache, "ABC", &mut caps);
361 /// assert_eq!(Some(PatternID::must(1)), caps.pattern());
362 /// // Recall that offsets are only available when using a non-empty
363 /// // Captures value. So even though a match occurred, this returns None!
364 /// assert_eq!(None, caps.get_match());
365 ///
366 /// # Ok::<(), Box<dyn std::error::Error>>(())
367 /// ```
368 #[inline]
369 pub fn pattern(&self) -> Option<PatternID> {
370 self.pid
371 }
372
373 /// Returns the pattern ID and the span of the match, if one occurred.
374 ///
375 /// This always returns `None` when `Captures` was created with
376 /// [`Captures::empty`], even if a match was found.
377 ///
378 /// If this routine returns a non-`None` value, then `is_match` is
379 /// guaranteed to return `true` and `pattern` is also guaranteed to return
380 /// a non-`None` value.
381 ///
382 /// # Example
383 ///
384 /// This example shows how to get the full match from a search:
385 ///
386 /// ```
387 /// use regex_automata::{nfa::thompson::pikevm::PikeVM, Match};
388 ///
389 /// let re = PikeVM::new_many(&[r"[a-z]+", r"[A-Z]+"])?;
390 /// let (mut cache, mut caps) = (re.create_cache(), re.create_captures());
391 ///
392 /// re.captures(&mut cache, "ABC", &mut caps);
393 /// assert_eq!(Some(Match::must(1, 0..3)), caps.get_match());
394 ///
395 /// # Ok::<(), Box<dyn std::error::Error>>(())
396 /// ```
397 #[inline]
398 pub fn get_match(&self) -> Option<Match> {
399 Some(Match::new(self.pattern()?, self.get_group(0)?))
400 }
401
402 /// Returns the span of a capturing group match corresponding to the group
403 /// index given, only if both the overall pattern matched and the capturing
404 /// group participated in that match.
405 ///
406 /// This returns `None` if `index` is invalid. `index` is valid if and only
407 /// if it's less than [`Captures::group_len`] for the matching pattern.
408 ///
409 /// This always returns `None` when `Captures` was created with
410 /// [`Captures::empty`], even if a match was found. This also always
411 /// returns `None` for any `index > 0` when `Captures` was created with
412 /// [`Captures::matches`].
413 ///
414 /// If this routine returns a non-`None` value, then `is_match` is
415 /// guaranteed to return `true`, `pattern` is guaranteed to return a
416 /// non-`None` value and `get_match` is guaranteed to return a non-`None`
417 /// value.
418 ///
419 /// By convention, the 0th capture group will always return the same
420 /// span as the span returned by `get_match`. This is because the 0th
421 /// capture group always corresponds to the entirety of the pattern's
422 /// match. (It is similarly always unnamed because it is implicit.) This
423 /// isn't necessarily true of all regex engines. For example, one can
424 /// hand-compile a [`thompson::NFA`](crate::nfa::thompson::NFA) via a
425 /// [`thompson::Builder`](crate::nfa::thompson::Builder), which isn't
426 /// technically forced to make the 0th capturing group always correspond to
427 /// the entire match.
428 ///
429 /// # Example
430 ///
431 /// This example shows how to get the capturing groups, by index, from a
432 /// match:
433 ///
434 /// ```
435 /// # if cfg!(miri) { return Ok(()); } // miri takes too long
436 /// # if !cfg!(target_pointer_width = "64") { return Ok(()); } // see #1039
437 /// use regex_automata::{nfa::thompson::pikevm::PikeVM, Span, Match};
438 ///
439 /// let re = PikeVM::new(r"^(?P<first>\pL+)\s+(?P<last>\pL+)$")?;
440 /// let (mut cache, mut caps) = (re.create_cache(), re.create_captures());
441 ///
442 /// re.captures(&mut cache, "Bruce Springsteen", &mut caps);
443 /// assert_eq!(Some(Match::must(0, 0..17)), caps.get_match());
444 /// assert_eq!(Some(Span::from(0..5)), caps.get_group(1));
445 /// assert_eq!(Some(Span::from(6..17)), caps.get_group(2));
446 /// // Looking for a non-existent capturing group will return None:
447 /// assert_eq!(None, caps.get_group(3));
448 /// assert_eq!(None, caps.get_group(9944060567225171988));
449 ///
450 /// # Ok::<(), Box<dyn std::error::Error>>(())
451 /// ```
452 #[inline]
453 pub fn get_group(&self, index: usize) -> Option<Span> {
454 let pid = self.pattern()?;
455 // There's a little bit of work needed to map captures to slots in the
456 // fully general case. But in the overwhelming common case of a single
457 // pattern, we can just do some simple arithmetic.
458 let (slot_start, slot_end) = if self.group_info().pattern_len() == 1 {
459 (index.checked_mul(2)?, index.checked_mul(2)?.checked_add(1)?)
460 } else {
461 self.group_info().slots(pid, index)?
462 };
463 let start = self.slots.get(slot_start).copied()??;
464 let end = self.slots.get(slot_end).copied()??;
465 Some(Span { start: start.get(), end: end.get() })
466 }
467
468 /// Returns the span of a capturing group match corresponding to the group
469 /// name given, only if both the overall pattern matched and the capturing
470 /// group participated in that match.
471 ///
472 /// This returns `None` if `name` does not correspond to a valid capturing
473 /// group for the pattern that matched.
474 ///
475 /// This always returns `None` when `Captures` was created with
476 /// [`Captures::empty`], even if a match was found. This also always
477 /// returns `None` for any `index > 0` when `Captures` was created with
478 /// [`Captures::matches`].
479 ///
480 /// If this routine returns a non-`None` value, then `is_match` is
481 /// guaranteed to return `true`, `pattern` is guaranteed to return a
482 /// non-`None` value and `get_match` is guaranteed to return a non-`None`
483 /// value.
484 ///
485 /// # Example
486 ///
487 /// This example shows how to get the capturing groups, by name, from a
488 /// match:
489 ///
490 /// ```
491 /// # if cfg!(miri) { return Ok(()); } // miri takes too long
492 /// use regex_automata::{nfa::thompson::pikevm::PikeVM, Span, Match};
493 ///
494 /// let re = PikeVM::new(r"^(?P<first>\pL+)\s+(?P<last>\pL+)$")?;
495 /// let (mut cache, mut caps) = (re.create_cache(), re.create_captures());
496 ///
497 /// re.captures(&mut cache, "Bruce Springsteen", &mut caps);
498 /// assert_eq!(Some(Match::must(0, 0..17)), caps.get_match());
499 /// assert_eq!(Some(Span::from(0..5)), caps.get_group_by_name("first"));
500 /// assert_eq!(Some(Span::from(6..17)), caps.get_group_by_name("last"));
501 /// // Looking for a non-existent capturing group will return None:
502 /// assert_eq!(None, caps.get_group_by_name("middle"));
503 ///
504 /// # Ok::<(), Box<dyn std::error::Error>>(())
505 /// ```
506 pub fn get_group_by_name(&self, name: &str) -> Option<Span> {
507 let index = self.group_info().to_index(self.pattern()?, name)?;
508 self.get_group(index)
509 }
510
511 /// Returns an iterator of possible spans for every capturing group in the
512 /// matching pattern.
513 ///
514 /// If this `Captures` value does not correspond to a match, then the
515 /// iterator returned yields no elements.
516 ///
517 /// Note that the iterator returned yields elements of type `Option<Span>`.
518 /// A span is present if and only if it corresponds to a capturing group
519 /// that participated in a match.
520 ///
521 /// # Example
522 ///
523 /// This example shows how to collect all capturing groups:
524 ///
525 /// ```
526 /// # if cfg!(miri) { return Ok(()); } // miri takes too long
527 /// use regex_automata::{nfa::thompson::pikevm::PikeVM, Span};
528 ///
529 /// let re = PikeVM::new(
530 /// // Matches first/last names, with an optional middle name.
531 /// r"^(?P<first>\pL+)\s+(?:(?P<middle>\pL+)\s+)?(?P<last>\pL+)$",
532 /// )?;
533 /// let (mut cache, mut caps) = (re.create_cache(), re.create_captures());
534 ///
535 /// re.captures(&mut cache, "Harry James Potter", &mut caps);
536 /// assert!(caps.is_match());
537 /// let groups: Vec<Option<Span>> = caps.iter().collect();
538 /// assert_eq!(groups, vec![
539 /// Some(Span::from(0..18)),
540 /// Some(Span::from(0..5)),
541 /// Some(Span::from(6..11)),
542 /// Some(Span::from(12..18)),
543 /// ]);
544 ///
545 /// # Ok::<(), Box<dyn std::error::Error>>(())
546 /// ```
547 ///
548 /// This example uses the same regex as the previous example, but with a
549 /// haystack that omits the middle name. This results in a capturing group
550 /// that is present in the elements yielded by the iterator but without a
551 /// match:
552 ///
553 /// ```
554 /// # if cfg!(miri) { return Ok(()); } // miri takes too long
555 /// use regex_automata::{nfa::thompson::pikevm::PikeVM, Span};
556 ///
557 /// let re = PikeVM::new(
558 /// // Matches first/last names, with an optional middle name.
559 /// r"^(?P<first>\pL+)\s+(?:(?P<middle>\pL+)\s+)?(?P<last>\pL+)$",
560 /// )?;
561 /// let (mut cache, mut caps) = (re.create_cache(), re.create_captures());
562 ///
563 /// re.captures(&mut cache, "Harry Potter", &mut caps);
564 /// assert!(caps.is_match());
565 /// let groups: Vec<Option<Span>> = caps.iter().collect();
566 /// assert_eq!(groups, vec![
567 /// Some(Span::from(0..12)),
568 /// Some(Span::from(0..5)),
569 /// None,
570 /// Some(Span::from(6..12)),
571 /// ]);
572 ///
573 /// # Ok::<(), Box<dyn std::error::Error>>(())
574 /// ```
575 pub fn iter(&self) -> CapturesPatternIter<'_> {
576 let names = self
577 .pattern()
578 .map_or(GroupInfoPatternNames::empty().enumerate(), |pid| {
579 self.group_info().pattern_names(pid).enumerate()
580 });
581 CapturesPatternIter { caps: self, names }
582 }
583
584 /// Return the total number of capturing groups for the matching pattern.
585 ///
586 /// If this `Captures` value does not correspond to a match, then this
587 /// always returns `0`.
588 ///
589 /// This always returns the same number of elements yielded by
590 /// [`Captures::iter`]. That is, the number includes capturing groups even
591 /// if they don't participate in the match.
592 ///
593 /// # Example
594 ///
595 /// This example shows how to count the total number of capturing groups
596 /// associated with a pattern. Notice that it includes groups that did not
597 /// participate in a match (just like `Captures::iter` does).
598 ///
599 /// ```
600 /// # if cfg!(miri) { return Ok(()); } // miri takes too long
601 /// use regex_automata::nfa::thompson::pikevm::PikeVM;
602 ///
603 /// let re = PikeVM::new(
604 /// // Matches first/last names, with an optional middle name.
605 /// r"^(?P<first>\pL+)\s+(?:(?P<middle>\pL+)\s+)?(?P<last>\pL+)$",
606 /// )?;
607 /// let (mut cache, mut caps) = (re.create_cache(), re.create_captures());
608 ///
609 /// re.captures(&mut cache, "Harry Potter", &mut caps);
610 /// assert_eq!(4, caps.group_len());
611 ///
612 /// # Ok::<(), Box<dyn std::error::Error>>(())
613 /// ```
614 pub fn group_len(&self) -> usize {
615 let pid = match self.pattern() {
616 None => return 0,
617 Some(pid) => pid,
618 };
619 self.group_info().group_len(pid)
620 }
621
622 /// Returns a reference to the underlying group info on which these
623 /// captures are based.
624 ///
625 /// The difference between `GroupInfo` and `Captures` is that the former
626 /// defines the structure of capturing groups where as the latter is what
627 /// stores the actual match information. So where as `Captures` only gives
628 /// you access to the current match, `GroupInfo` lets you query any
629 /// information about all capturing groups, even ones for patterns that
630 /// weren't involved in a match.
631 ///
632 /// Note that a `GroupInfo` uses reference counting internally, so it may
633 /// be cloned cheaply.
634 ///
635 /// # Example
636 ///
637 /// This example shows how to get all capturing group names from the
638 /// underlying `GroupInfo`. Notice that we don't even need to run a
639 /// search.
640 ///
641 /// ```
642 /// use regex_automata::{nfa::thompson::pikevm::PikeVM, PatternID};
643 ///
644 /// let re = PikeVM::new_many(&[
645 /// r"(?P<foo>a)",
646 /// r"(a)(b)",
647 /// r"ab",
648 /// r"(?P<bar>a)(?P<quux>a)",
649 /// r"(?P<foo>z)",
650 /// ])?;
651 /// let caps = re.create_captures();
652 ///
653 /// let expected = vec![
654 /// (PatternID::must(0), 0, None),
655 /// (PatternID::must(0), 1, Some("foo")),
656 /// (PatternID::must(1), 0, None),
657 /// (PatternID::must(1), 1, None),
658 /// (PatternID::must(1), 2, None),
659 /// (PatternID::must(2), 0, None),
660 /// (PatternID::must(3), 0, None),
661 /// (PatternID::must(3), 1, Some("bar")),
662 /// (PatternID::must(3), 2, Some("quux")),
663 /// (PatternID::must(4), 0, None),
664 /// (PatternID::must(4), 1, Some("foo")),
665 /// ];
666 /// // We could also just use 're.get_nfa().group_info()'.
667 /// let got: Vec<(PatternID, usize, Option<&str>)> =
668 /// caps.group_info().all_names().collect();
669 /// assert_eq!(expected, got);
670 ///
671 /// # Ok::<(), Box<dyn std::error::Error>>(())
672 /// ```
673 pub fn group_info(&self) -> &GroupInfo {
674 &self.group_info
675 }
676
677 /// Interpolates the capture references in `replacement` with the
678 /// corresponding substrings in `haystack` matched by each reference. The
679 /// interpolated string is returned.
680 ///
681 /// See the [`interpolate` module](interpolate) for documentation on the
682 /// format of the replacement string.
683 ///
684 /// # Example
685 ///
686 /// This example shows how to use interpolation, and also shows how it
687 /// can work with multi-pattern regexes.
688 ///
689 /// ```
690 /// use regex_automata::{nfa::thompson::pikevm::PikeVM, PatternID};
691 ///
692 /// let re = PikeVM::new_many(&[
693 /// r"(?<day>[0-9]{2})-(?<month>[0-9]{2})-(?<year>[0-9]{4})",
694 /// r"(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2})",
695 /// ])?;
696 /// let mut cache = re.create_cache();
697 /// let mut caps = re.create_captures();
698 ///
699 /// let replacement = "year=$year, month=$month, day=$day";
700 ///
701 /// // This matches the first pattern.
702 /// let hay = "On 14-03-2010, I became a Tenneessee lamb.";
703 /// re.captures(&mut cache, hay, &mut caps);
704 /// let result = caps.interpolate_string(hay, replacement);
705 /// assert_eq!("year=2010, month=03, day=14", result);
706 ///
707 /// // And this matches the second pattern.
708 /// let hay = "On 2010-03-14, I became a Tenneessee lamb.";
709 /// re.captures(&mut cache, hay, &mut caps);
710 /// let result = caps.interpolate_string(hay, replacement);
711 /// assert_eq!("year=2010, month=03, day=14", result);
712 ///
713 /// # Ok::<(), Box<dyn std::error::Error>>(())
714 /// ```
715 pub fn interpolate_string(
716 &self,
717 haystack: &str,
718 replacement: &str,
719 ) -> String {
720 let mut dst = String::new();
721 self.interpolate_string_into(haystack, replacement, &mut dst);
722 dst
723 }
724
725 /// Interpolates the capture references in `replacement` with the
726 /// corresponding substrings in `haystack` matched by each reference. The
727 /// interpolated string is written to `dst`.
728 ///
729 /// See the [`interpolate` module](interpolate) for documentation on the
730 /// format of the replacement string.
731 ///
732 /// # Example
733 ///
734 /// This example shows how to use interpolation, and also shows how it
735 /// can work with multi-pattern regexes.
736 ///
737 /// ```
738 /// use regex_automata::{nfa::thompson::pikevm::PikeVM, PatternID};
739 ///
740 /// let re = PikeVM::new_many(&[
741 /// r"(?<day>[0-9]{2})-(?<month>[0-9]{2})-(?<year>[0-9]{4})",
742 /// r"(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2})",
743 /// ])?;
744 /// let mut cache = re.create_cache();
745 /// let mut caps = re.create_captures();
746 ///
747 /// let replacement = "year=$year, month=$month, day=$day";
748 ///
749 /// // This matches the first pattern.
750 /// let hay = "On 14-03-2010, I became a Tenneessee lamb.";
751 /// re.captures(&mut cache, hay, &mut caps);
752 /// let mut dst = String::new();
753 /// caps.interpolate_string_into(hay, replacement, &mut dst);
754 /// assert_eq!("year=2010, month=03, day=14", dst);
755 ///
756 /// // And this matches the second pattern.
757 /// let hay = "On 2010-03-14, I became a Tenneessee lamb.";
758 /// re.captures(&mut cache, hay, &mut caps);
759 /// let mut dst = String::new();
760 /// caps.interpolate_string_into(hay, replacement, &mut dst);
761 /// assert_eq!("year=2010, month=03, day=14", dst);
762 ///
763 /// # Ok::<(), Box<dyn std::error::Error>>(())
764 /// ```
765 pub fn interpolate_string_into(
766 &self,
767 haystack: &str,
768 replacement: &str,
769 dst: &mut String,
770 ) {
771 interpolate::string(
772 replacement,
773 |index, dst| {
774 let span = match self.get_group(index) {
775 None => return,
776 Some(span) => span,
777 };
778 dst.push_str(&haystack[span]);
779 },
780 |name| self.group_info().to_index(self.pattern()?, name),
781 dst,
782 );
783 }
784
785 /// Interpolates the capture references in `replacement` with the
786 /// corresponding substrings in `haystack` matched by each reference. The
787 /// interpolated byte string is returned.
788 ///
789 /// See the [`interpolate` module](interpolate) for documentation on the
790 /// format of the replacement string.
791 ///
792 /// # Example
793 ///
794 /// This example shows how to use interpolation, and also shows how it
795 /// can work with multi-pattern regexes.
796 ///
797 /// ```
798 /// use regex_automata::{nfa::thompson::pikevm::PikeVM, PatternID};
799 ///
800 /// let re = PikeVM::new_many(&[
801 /// r"(?<day>[0-9]{2})-(?<month>[0-9]{2})-(?<year>[0-9]{4})",
802 /// r"(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2})",
803 /// ])?;
804 /// let mut cache = re.create_cache();
805 /// let mut caps = re.create_captures();
806 ///
807 /// let replacement = b"year=$year, month=$month, day=$day";
808 ///
809 /// // This matches the first pattern.
810 /// let hay = b"On 14-03-2010, I became a Tenneessee lamb.";
811 /// re.captures(&mut cache, hay, &mut caps);
812 /// let result = caps.interpolate_bytes(hay, replacement);
813 /// assert_eq!(&b"year=2010, month=03, day=14"[..], result);
814 ///
815 /// // And this matches the second pattern.
816 /// let hay = b"On 2010-03-14, I became a Tenneessee lamb.";
817 /// re.captures(&mut cache, hay, &mut caps);
818 /// let result = caps.interpolate_bytes(hay, replacement);
819 /// assert_eq!(&b"year=2010, month=03, day=14"[..], result);
820 ///
821 /// # Ok::<(), Box<dyn std::error::Error>>(())
822 /// ```
823 pub fn interpolate_bytes(
824 &self,
825 haystack: &[u8],
826 replacement: &[u8],
827 ) -> Vec<u8> {
828 let mut dst = vec![];
829 self.interpolate_bytes_into(haystack, replacement, &mut dst);
830 dst
831 }
832
833 /// Interpolates the capture references in `replacement` with the
834 /// corresponding substrings in `haystack` matched by each reference. The
835 /// interpolated byte string is written to `dst`.
836 ///
837 /// See the [`interpolate` module](interpolate) for documentation on the
838 /// format of the replacement string.
839 ///
840 /// # Example
841 ///
842 /// This example shows how to use interpolation, and also shows how it
843 /// can work with multi-pattern regexes.
844 ///
845 /// ```
846 /// use regex_automata::{nfa::thompson::pikevm::PikeVM, PatternID};
847 ///
848 /// let re = PikeVM::new_many(&[
849 /// r"(?<day>[0-9]{2})-(?<month>[0-9]{2})-(?<year>[0-9]{4})",
850 /// r"(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2})",
851 /// ])?;
852 /// let mut cache = re.create_cache();
853 /// let mut caps = re.create_captures();
854 ///
855 /// let replacement = b"year=$year, month=$month, day=$day";
856 ///
857 /// // This matches the first pattern.
858 /// let hay = b"On 14-03-2010, I became a Tenneessee lamb.";
859 /// re.captures(&mut cache, hay, &mut caps);
860 /// let mut dst = vec![];
861 /// caps.interpolate_bytes_into(hay, replacement, &mut dst);
862 /// assert_eq!(&b"year=2010, month=03, day=14"[..], dst);
863 ///
864 /// // And this matches the second pattern.
865 /// let hay = b"On 2010-03-14, I became a Tenneessee lamb.";
866 /// re.captures(&mut cache, hay, &mut caps);
867 /// let mut dst = vec![];
868 /// caps.interpolate_bytes_into(hay, replacement, &mut dst);
869 /// assert_eq!(&b"year=2010, month=03, day=14"[..], dst);
870 ///
871 /// # Ok::<(), Box<dyn std::error::Error>>(())
872 /// ```
873 pub fn interpolate_bytes_into(
874 &self,
875 haystack: &[u8],
876 replacement: &[u8],
877 dst: &mut Vec<u8>,
878 ) {
879 interpolate::bytes(
880 replacement,
881 |index, dst| {
882 let span = match self.get_group(index) {
883 None => return,
884 Some(span) => span,
885 };
886 dst.extend_from_slice(&haystack[span]);
887 },
888 |name| self.group_info().to_index(self.pattern()?, name),
889 dst,
890 );
891 }
892
893 /// This is a convenience routine for extracting the substrings
894 /// corresponding to matching capture groups in the given `haystack`. The
895 /// `haystack` should be the same substring used to find the match spans in
896 /// this `Captures` value.
897 ///
898 /// This is identical to [`Captures::extract_bytes`], except it works with
899 /// `&str` instead of `&[u8]`.
900 ///
901 /// # Panics
902 ///
903 /// This panics if the number of explicit matching groups in this
904 /// `Captures` value is less than `N`. This also panics if this `Captures`
905 /// value does not correspond to a match.
906 ///
907 /// Note that this does *not* panic if the number of explicit matching
908 /// groups is bigger than `N`. In that case, only the first `N` matching
909 /// groups are extracted.
910 ///
911 /// # Example
912 ///
913 /// ```
914 /// use regex_automata::nfa::thompson::pikevm::PikeVM;
915 ///
916 /// let re = PikeVM::new(r"([0-9]{4})-([0-9]{2})-([0-9]{2})")?;
917 /// let mut cache = re.create_cache();
918 /// let mut caps = re.create_captures();
919 ///
920 /// let hay = "On 2010-03-14, I became a Tenneessee lamb.";
921 /// re.captures(&mut cache, hay, &mut caps);
922 /// assert!(caps.is_match());
923 /// let (full, [year, month, day]) = caps.extract(hay);
924 /// assert_eq!("2010-03-14", full);
925 /// assert_eq!("2010", year);
926 /// assert_eq!("03", month);
927 /// assert_eq!("14", day);
928 ///
929 /// // We can also ask for fewer than all capture groups.
930 /// let (full, [year]) = caps.extract(hay);
931 /// assert_eq!("2010-03-14", full);
932 /// assert_eq!("2010", year);
933 ///
934 /// # Ok::<(), Box<dyn std::error::Error>>(())
935 /// ```
936 pub fn extract<'h, const N: usize>(
937 &self,
938 haystack: &'h str,
939 ) -> (&'h str, [&'h str; N]) {
940 let mut matched = self.iter().flatten();
941 let whole_match = &haystack[matched.next().expect("a match")];
942 let group_matches = [0; N].map(|_| {
943 let sp = matched.next().expect("too few matching groups");
944 &haystack[sp]
945 });
946 (whole_match, group_matches)
947 }
948
949 /// This is a convenience routine for extracting the substrings
950 /// corresponding to matching capture groups in the given `haystack`. The
951 /// `haystack` should be the same substring used to find the match spans in
952 /// this `Captures` value.
953 ///
954 /// This is identical to [`Captures::extract`], except it works with
955 /// `&[u8]` instead of `&str`.
956 ///
957 /// # Panics
958 ///
959 /// This panics if the number of explicit matching groups in this
960 /// `Captures` value is less than `N`. This also panics if this `Captures`
961 /// value does not correspond to a match.
962 ///
963 /// Note that this does *not* panic if the number of explicit matching
964 /// groups is bigger than `N`. In that case, only the first `N` matching
965 /// groups are extracted.
966 ///
967 /// # Example
968 ///
969 /// ```
970 /// use regex_automata::nfa::thompson::pikevm::PikeVM;
971 ///
972 /// let re = PikeVM::new(r"([0-9]{4})-([0-9]{2})-([0-9]{2})")?;
973 /// let mut cache = re.create_cache();
974 /// let mut caps = re.create_captures();
975 ///
976 /// let hay = b"On 2010-03-14, I became a Tenneessee lamb.";
977 /// re.captures(&mut cache, hay, &mut caps);
978 /// assert!(caps.is_match());
979 /// let (full, [year, month, day]) = caps.extract_bytes(hay);
980 /// assert_eq!(b"2010-03-14", full);
981 /// assert_eq!(b"2010", year);
982 /// assert_eq!(b"03", month);
983 /// assert_eq!(b"14", day);
984 ///
985 /// // We can also ask for fewer than all capture groups.
986 /// let (full, [year]) = caps.extract_bytes(hay);
987 /// assert_eq!(b"2010-03-14", full);
988 /// assert_eq!(b"2010", year);
989 ///
990 /// # Ok::<(), Box<dyn std::error::Error>>(())
991 /// ```
992 pub fn extract_bytes<'h, const N: usize>(
993 &self,
994 haystack: &'h [u8],
995 ) -> (&'h [u8], [&'h [u8]; N]) {
996 let mut matched = self.iter().flatten();
997 let whole_match = &haystack[matched.next().expect("a match")];
998 let group_matches = [0; N].map(|_| {
999 let sp = matched.next().expect("too few matching groups");
1000 &haystack[sp]
1001 });
1002 (whole_match, group_matches)
1003 }
1004 }
1005
1006 /// Lower level "slot" oriented APIs. One does not typically need to use these
1007 /// when executing a search. They are instead mostly intended for folks that
1008 /// are writing their own regex engine while reusing this `Captures` type.
1009 impl Captures {
1010 /// Clear this `Captures` value.
1011 ///
1012 /// After clearing, all slots inside this `Captures` value will be set to
1013 /// `None`. Similarly, any pattern ID that it was previously associated
1014 /// with (for a match) is erased.
1015 ///
1016 /// It is not usually necessary to call this routine. Namely, a `Captures`
1017 /// value only provides high level access to the capturing groups of the
1018 /// pattern that matched, and only low level access to individual slots.
1019 /// Thus, even if slots corresponding to groups that aren't associated
1020 /// with the matching pattern are set, then it won't impact the higher
1021 /// level APIs. Namely, higher level APIs like [`Captures::get_group`] will
1022 /// return `None` if no pattern ID is present, even if there are spans set
1023 /// in the underlying slots.
1024 ///
1025 /// Thus, to "clear" a `Captures` value of a match, it is usually only
1026 /// necessary to call [`Captures::set_pattern`] with `None`.
1027 ///
1028 /// # Example
1029 ///
1030 /// This example shows what happens when a `Captures` value is cleared.
1031 ///
1032 /// ```
1033 /// # if cfg!(miri) { return Ok(()); } // miri takes too long
1034 /// use regex_automata::nfa::thompson::pikevm::PikeVM;
1035 ///
1036 /// let re = PikeVM::new(r"^(?P<first>\pL+)\s+(?P<last>\pL+)$")?;
1037 /// let (mut cache, mut caps) = (re.create_cache(), re.create_captures());
1038 ///
1039 /// re.captures(&mut cache, "Bruce Springsteen", &mut caps);
1040 /// assert!(caps.is_match());
1041 /// let slots: Vec<Option<usize>> =
1042 /// caps.slots().iter().map(|s| s.map(|x| x.get())).collect();
1043 /// // Note that the following ordering is considered an API guarantee.
1044 /// assert_eq!(slots, vec![
1045 /// Some(0),
1046 /// Some(17),
1047 /// Some(0),
1048 /// Some(5),
1049 /// Some(6),
1050 /// Some(17),
1051 /// ]);
1052 ///
1053 /// // Now clear the slots. Everything is gone and it is no longer a match.
1054 /// caps.clear();
1055 /// assert!(!caps.is_match());
1056 /// let slots: Vec<Option<usize>> =
1057 /// caps.slots().iter().map(|s| s.map(|x| x.get())).collect();
1058 /// assert_eq!(slots, vec![
1059 /// None,
1060 /// None,
1061 /// None,
1062 /// None,
1063 /// None,
1064 /// None,
1065 /// ]);
1066 ///
1067 /// # Ok::<(), Box<dyn std::error::Error>>(())
1068 /// ```
1069 #[inline]
1070 pub fn clear(&mut self) {
1071 self.pid = None;
1072 for slot in self.slots.iter_mut() {
1073 *slot = None;
1074 }
1075 }
1076
1077 /// Set the pattern on this `Captures` value.
1078 ///
1079 /// When the pattern ID is `None`, then this `Captures` value does not
1080 /// correspond to a match (`is_match` will return `false`). Otherwise, it
1081 /// corresponds to a match.
1082 ///
1083 /// This is useful in search implementations where you might want to
1084 /// initially call `set_pattern(None)` in order to avoid the cost of
1085 /// calling `clear()` if it turns out to not be necessary.
1086 ///
1087 /// # Example
1088 ///
1089 /// This example shows that `set_pattern` merely overwrites the pattern ID.
1090 /// It does not actually change the underlying slot values.
1091 ///
1092 /// ```
1093 /// # if cfg!(miri) { return Ok(()); } // miri takes too long
1094 /// use regex_automata::nfa::thompson::pikevm::PikeVM;
1095 ///
1096 /// let re = PikeVM::new(r"^(?P<first>\pL+)\s+(?P<last>\pL+)$")?;
1097 /// let (mut cache, mut caps) = (re.create_cache(), re.create_captures());
1098 ///
1099 /// re.captures(&mut cache, "Bruce Springsteen", &mut caps);
1100 /// assert!(caps.is_match());
1101 /// assert!(caps.pattern().is_some());
1102 /// let slots: Vec<Option<usize>> =
1103 /// caps.slots().iter().map(|s| s.map(|x| x.get())).collect();
1104 /// // Note that the following ordering is considered an API guarantee.
1105 /// assert_eq!(slots, vec![
1106 /// Some(0),
1107 /// Some(17),
1108 /// Some(0),
1109 /// Some(5),
1110 /// Some(6),
1111 /// Some(17),
1112 /// ]);
1113 ///
1114 /// // Now set the pattern to None. Note that the slot values remain.
1115 /// caps.set_pattern(None);
1116 /// assert!(!caps.is_match());
1117 /// assert!(!caps.pattern().is_some());
1118 /// let slots: Vec<Option<usize>> =
1119 /// caps.slots().iter().map(|s| s.map(|x| x.get())).collect();
1120 /// // Note that the following ordering is considered an API guarantee.
1121 /// assert_eq!(slots, vec![
1122 /// Some(0),
1123 /// Some(17),
1124 /// Some(0),
1125 /// Some(5),
1126 /// Some(6),
1127 /// Some(17),
1128 /// ]);
1129 ///
1130 /// # Ok::<(), Box<dyn std::error::Error>>(())
1131 /// ```
1132 #[inline]
1133 pub fn set_pattern(&mut self, pid: Option<PatternID>) {
1134 self.pid = pid;
1135 }
1136
1137 /// Returns the underlying slots, where each slot stores a single offset.
1138 ///
1139 /// Every matching capturing group generally corresponds to two slots: one
1140 /// slot for the starting position and another for the ending position.
1141 /// Typically, either both are present or neither are. (The weasel word
1142 /// "typically" is used here because it really depends on the regex engine
1143 /// implementation. Every sensible regex engine likely adheres to this
1144 /// invariant, and every regex engine in this crate is sensible.)
1145 ///
1146 /// Generally speaking, callers should prefer to use higher level routines
1147 /// like [`Captures::get_match`] or [`Captures::get_group`].
1148 ///
1149 /// An important note here is that a regex engine may not reset all of the
1150 /// slots to `None` values when no match occurs, or even when a match of
1151 /// a different pattern occurs. But this depends on how the regex engine
1152 /// implementation deals with slots.
1153 ///
1154 /// # Example
1155 ///
1156 /// This example shows how to get the underlying slots from a regex match.
1157 ///
1158 /// ```
1159 /// use regex_automata::{
1160 /// nfa::thompson::pikevm::PikeVM,
1161 /// util::primitives::{PatternID, NonMaxUsize},
1162 /// };
1163 ///
1164 /// let re = PikeVM::new_many(&[
1165 /// r"[a-z]+",
1166 /// r"[0-9]+",
1167 /// ])?;
1168 /// let (mut cache, mut caps) = (re.create_cache(), re.create_captures());
1169 ///
1170 /// re.captures(&mut cache, "123", &mut caps);
1171 /// assert_eq!(Some(PatternID::must(1)), caps.pattern());
1172 /// // Note that the only guarantee we have here is that slots 2 and 3
1173 /// // are set to correct values. The contents of the first two slots are
1174 /// // unspecified since the 0th pattern did not match.
1175 /// let expected = &[
1176 /// None,
1177 /// None,
1178 /// NonMaxUsize::new(0),
1179 /// NonMaxUsize::new(3),
1180 /// ];
1181 /// assert_eq!(expected, caps.slots());
1182 ///
1183 /// # Ok::<(), Box<dyn std::error::Error>>(())
1184 /// ```
1185 #[inline]
1186 pub fn slots(&self) -> &[Option<NonMaxUsize>] {
1187 &self.slots
1188 }
1189
1190 /// Returns the underlying slots as a mutable slice, where each slot stores
1191 /// a single offset.
1192 ///
1193 /// This tends to be most useful for regex engine implementations for
1194 /// writing offsets for matching capturing groups to slots.
1195 ///
1196 /// See [`Captures::slots`] for more information about slots.
1197 #[inline]
1198 pub fn slots_mut(&mut self) -> &mut [Option<NonMaxUsize>] {
1199 &mut self.slots
1200 }
1201 }
1202
1203 impl core::fmt::Debug for Captures {
1204 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1205 let mut dstruct = f.debug_struct("Captures");
1206 dstruct.field("pid", &self.pid);
1207 if let Some(pid) = self.pid {
1208 dstruct.field("spans", &CapturesDebugMap { pid, caps: self });
1209 }
1210 dstruct.finish()
1211 }
1212 }
1213
1214 /// A little helper type to provide a nice map-like debug representation for
1215 /// our capturing group spans.
1216 struct CapturesDebugMap<'a> {
1217 pid: PatternID,
1218 caps: &'a Captures,
1219 }
1220
1221 impl<'a> core::fmt::Debug for CapturesDebugMap<'a> {
1222 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1223 struct Key<'a>(usize, Option<&'a str>);
1224
1225 impl<'a> core::fmt::Debug for Key<'a> {
1226 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1227 write!(f, "{}", self.0)?;
1228 if let Some(name) = self.1 {
1229 write!(f, "/{:?}", name)?;
1230 }
1231 Ok(())
1232 }
1233 }
1234
1235 let mut map = f.debug_map();
1236 let names = self.caps.group_info().pattern_names(self.pid);
1237 for (group_index, maybe_name) in names.enumerate() {
1238 let key = Key(group_index, maybe_name);
1239 match self.caps.get_group(group_index) {
1240 None => map.entry(&key, &None::<()>),
1241 Some(span) => map.entry(&key, &span),
1242 };
1243 }
1244 map.finish()
1245 }
1246 }
1247
1248 /// An iterator over all capturing groups in a `Captures` value.
1249 ///
1250 /// This iterator includes capturing groups that did not participate in a
1251 /// match. See the [`Captures::iter`] method documentation for more details
1252 /// and examples.
1253 ///
1254 /// The lifetime parameter `'a` refers to the lifetime of the underlying
1255 /// `Captures` value.
1256 #[derive(Clone, Debug)]
1257 pub struct CapturesPatternIter<'a> {
1258 caps: &'a Captures,
1259 names: core::iter::Enumerate<GroupInfoPatternNames<'a>>,
1260 }
1261
1262 impl<'a> Iterator for CapturesPatternIter<'a> {
1263 type Item = Option<Span>;
1264
1265 fn next(&mut self) -> Option<Option<Span>> {
1266 let (group_index, _) = self.names.next()?;
1267 Some(self.caps.get_group(group_index))
1268 }
1269
1270 fn size_hint(&self) -> (usize, Option<usize>) {
1271 self.names.size_hint()
1272 }
1273
1274 fn count(self) -> usize {
1275 self.names.count()
1276 }
1277 }
1278
1279 impl<'a> ExactSizeIterator for CapturesPatternIter<'a> {}
1280 impl<'a> core::iter::FusedIterator for CapturesPatternIter<'a> {}
1281
1282 /// Represents information about capturing groups in a compiled regex.
1283 ///
1284 /// The information encapsulated by this type consists of the following. For
1285 /// each pattern:
1286 ///
1287 /// * A map from every capture group name to its corresponding capture group
1288 /// index.
1289 /// * A map from every capture group index to its corresponding capture group
1290 /// name.
1291 /// * A map from capture group index to its corresponding slot index. A slot
1292 /// refers to one half of a capturing group. That is, a capture slot is either
1293 /// the start or end of a capturing group. A slot is usually the mechanism
1294 /// by which a regex engine records offsets for each capturing group during a
1295 /// search.
1296 ///
1297 /// A `GroupInfo` uses reference counting internally and is thus cheap to
1298 /// clone.
1299 ///
1300 /// # Mapping from capture groups to slots
1301 ///
1302 /// One of the main responsibilities of a `GroupInfo` is to build a mapping
1303 /// from `(PatternID, u32)` (where the `u32` is a capture index) to something
1304 /// called a "slot." As mentioned above, a slot refers to one half of a
1305 /// capturing group. Both combined provide the start and end offsets of
1306 /// a capturing group that participated in a match.
1307 ///
1308 /// **The mapping between group indices and slots is an API guarantee.** That
1309 /// is, the mapping won't change within a semver compatible release.
1310 ///
1311 /// Slots exist primarily because this is a convenient mechanism by which
1312 /// regex engines report group offsets at search time. For example, the
1313 /// [`nfa::thompson::State::Capture`](crate::nfa::thompson::State::Capture)
1314 /// NFA state includes the slot index. When a regex engine transitions through
1315 /// this state, it will likely use the slot index to write the current haystack
1316 /// offset to some region of memory. When a match is found, those slots are
1317 /// then reported to the caller, typically via a convenient abstraction like a
1318 /// [`Captures`] value.
1319 ///
1320 /// Because this crate provides first class support for multi-pattern regexes,
1321 /// and because of some performance related reasons, the mapping between
1322 /// capturing groups and slots is a little complex. However, in the case of a
1323 /// single pattern, the mapping can be described very simply: for all capture
1324 /// group indices `i`, its corresponding slots are at `i * 2` and `i * 2 + 1`.
1325 /// Notice that the pattern ID isn't involved at all here, because it only
1326 /// applies to a single-pattern regex, it is therefore always `0`.
1327 ///
1328 /// In the multi-pattern case, the mapping is a bit more complicated. To talk
1329 /// about it, we must define what we mean by "implicit" vs "explicit"
1330 /// capturing groups:
1331 ///
1332 /// * An **implicit** capturing group refers to the capturing group that is
1333 /// present for every pattern automatically, and corresponds to the overall
1334 /// match of a pattern. Every pattern has precisely one implicit capturing
1335 /// group. It is always unnamed and it always corresponds to the capture group
1336 /// index `0`.
1337 /// * An **explicit** capturing group refers to any capturing group that
1338 /// appears in the concrete syntax of the pattern. (Or, if an NFA was hand
1339 /// built without any concrete syntax, it refers to any capturing group with an
1340 /// index greater than `0`.)
1341 ///
1342 /// Some examples:
1343 ///
1344 /// * `\w+` has one implicit capturing group and zero explicit capturing
1345 /// groups.
1346 /// * `(\w+)` has one implicit group and one explicit group.
1347 /// * `foo(\d+)(?:\pL+)(\d+)` has one implicit group and two explicit groups.
1348 ///
1349 /// Turning back to the slot mapping, we can now state it as follows:
1350 ///
1351 /// * Given a pattern ID `pid`, the slots for its implicit group are always
1352 /// at `pid * 2` and `pid * 2 + 1`.
1353 /// * Given a pattern ID `0`, the slots for its explicit groups start
1354 /// at `group_info.pattern_len() * 2`.
1355 /// * Given a pattern ID `pid > 0`, the slots for its explicit groups start
1356 /// immediately following where the slots for the explicit groups of `pid - 1`
1357 /// end.
1358 ///
1359 /// In particular, while there is a concrete formula one can use to determine
1360 /// where the slots for the implicit group of any pattern are, there is no
1361 /// general formula for determining where the slots for explicit capturing
1362 /// groups are. This is because each pattern can contain a different number
1363 /// of groups.
1364 ///
1365 /// The intended way of getting the slots for a particular capturing group
1366 /// (whether implicit or explicit) is via the [`GroupInfo::slot`] or
1367 /// [`GroupInfo::slots`] method.
1368 ///
1369 /// See below for a concrete example of how capturing groups get mapped to
1370 /// slots.
1371 ///
1372 /// # Example
1373 ///
1374 /// This example shows how to build a new `GroupInfo` and query it for
1375 /// information.
1376 ///
1377 /// ```
1378 /// use regex_automata::util::{captures::GroupInfo, primitives::PatternID};
1379 ///
1380 /// let info = GroupInfo::new(vec![
1381 /// vec![None, Some("foo")],
1382 /// vec![None],
1383 /// vec![None, None, None, Some("bar"), None],
1384 /// vec![None, None, Some("foo")],
1385 /// ])?;
1386 /// // The number of patterns being tracked.
1387 /// assert_eq!(4, info.pattern_len());
1388 /// // We can query the number of groups for any pattern.
1389 /// assert_eq!(2, info.group_len(PatternID::must(0)));
1390 /// assert_eq!(1, info.group_len(PatternID::must(1)));
1391 /// assert_eq!(5, info.group_len(PatternID::must(2)));
1392 /// assert_eq!(3, info.group_len(PatternID::must(3)));
1393 /// // An invalid pattern always has zero groups.
1394 /// assert_eq!(0, info.group_len(PatternID::must(999)));
1395 /// // 2 slots per group
1396 /// assert_eq!(22, info.slot_len());
1397 ///
1398 /// // We can map a group index for a particular pattern to its name, if
1399 /// // one exists.
1400 /// assert_eq!(Some("foo"), info.to_name(PatternID::must(3), 2));
1401 /// assert_eq!(None, info.to_name(PatternID::must(2), 4));
1402 /// // Or map a name to its group index.
1403 /// assert_eq!(Some(1), info.to_index(PatternID::must(0), "foo"));
1404 /// assert_eq!(Some(2), info.to_index(PatternID::must(3), "foo"));
1405 ///
1406 /// # Ok::<(), Box<dyn std::error::Error>>(())
1407 /// ```
1408 ///
1409 /// # Example: mapping from capture groups to slots
1410 ///
1411 /// This example shows the specific mapping from capture group indices for
1412 /// each pattern to their corresponding slots. The slot values shown in this
1413 /// example are considered an API guarantee.
1414 ///
1415 /// ```
1416 /// use regex_automata::util::{captures::GroupInfo, primitives::PatternID};
1417 ///
1418 /// let info = GroupInfo::new(vec![
1419 /// vec![None, Some("foo")],
1420 /// vec![None],
1421 /// vec![None, None, None, Some("bar"), None],
1422 /// vec![None, None, Some("foo")],
1423 /// ])?;
1424 ///
1425 /// // We first show the slots for each pattern's implicit group.
1426 /// assert_eq!(Some((0, 1)), info.slots(PatternID::must(0), 0));
1427 /// assert_eq!(Some((2, 3)), info.slots(PatternID::must(1), 0));
1428 /// assert_eq!(Some((4, 5)), info.slots(PatternID::must(2), 0));
1429 /// assert_eq!(Some((6, 7)), info.slots(PatternID::must(3), 0));
1430 ///
1431 /// // And now we show the slots for each pattern's explicit group.
1432 /// assert_eq!(Some((8, 9)), info.slots(PatternID::must(0), 1));
1433 /// assert_eq!(Some((10, 11)), info.slots(PatternID::must(2), 1));
1434 /// assert_eq!(Some((12, 13)), info.slots(PatternID::must(2), 2));
1435 /// assert_eq!(Some((14, 15)), info.slots(PatternID::must(2), 3));
1436 /// assert_eq!(Some((16, 17)), info.slots(PatternID::must(2), 4));
1437 /// assert_eq!(Some((18, 19)), info.slots(PatternID::must(3), 1));
1438 /// assert_eq!(Some((20, 21)), info.slots(PatternID::must(3), 2));
1439 ///
1440 /// // Asking for the slots for an invalid pattern ID or even for an invalid
1441 /// // group index for a specific pattern will return None. So for example,
1442 /// // you're guaranteed to not get the slots for a different pattern than the
1443 /// // one requested.
1444 /// assert_eq!(None, info.slots(PatternID::must(5), 0));
1445 /// assert_eq!(None, info.slots(PatternID::must(1), 1));
1446 ///
1447 /// # Ok::<(), Box<dyn std::error::Error>>(())
1448 /// ```
1449 #[derive(Clone, Debug, Default)]
1450 pub struct GroupInfo(Arc<GroupInfoInner>);
1451
1452 impl GroupInfo {
1453 /// Creates a new group info from a sequence of patterns, where each
1454 /// sequence of patterns yields a sequence of possible group names. The
1455 /// index of each pattern in the sequence corresponds to its `PatternID`,
1456 /// and the index of each group in each pattern's sequence corresponds to
1457 /// its corresponding group index.
1458 ///
1459 /// While this constructor is very generic and therefore perhaps hard to
1460 /// chew on, an example of a valid concrete type that can be passed to
1461 /// this constructor is `Vec<Vec<Option<String>>>`. The outer `Vec`
1462 /// corresponds to the patterns, i.e., one `Vec<Option<String>>` per
1463 /// pattern. The inner `Vec` corresponds to the capturing groups for
1464 /// each pattern. The `Option<String>` corresponds to the name of the
1465 /// capturing group, if present.
1466 ///
1467 /// It is legal to pass an empty iterator to this constructor. It will
1468 /// return an empty group info with zero slots. An empty group info is
1469 /// useful for cases where you have no patterns or for cases where slots
1470 /// aren't being used at all (e.g., for most DFAs in this crate).
1471 ///
1472 /// # Errors
1473 ///
1474 /// This constructor returns an error if the given capturing groups are
1475 /// invalid in some way. Those reasons include, but are not necessarily
1476 /// limited to:
1477 ///
1478 /// * Too many patterns (i.e., `PatternID` would overflow).
1479 /// * Too many capturing groups (e.g., `u32` would overflow).
1480 /// * A pattern is given that has no capturing groups. (All patterns must
1481 /// have at least an implicit capturing group at index `0`.)
1482 /// * The capturing group at index `0` has a name. It must be unnamed.
1483 /// * There are duplicate capturing group names within the same pattern.
1484 /// (Multiple capturing groups with the same name may exist, but they
1485 /// must be in different patterns.)
1486 ///
1487 /// An example below shows how to trigger some of the above error
1488 /// conditions.
1489 ///
1490 /// # Example
1491 ///
1492 /// This example shows how to build a new `GroupInfo` and query it for
1493 /// information.
1494 ///
1495 /// ```
1496 /// use regex_automata::util::captures::GroupInfo;
1497 ///
1498 /// let info = GroupInfo::new(vec![
1499 /// vec![None, Some("foo")],
1500 /// vec![None],
1501 /// vec![None, None, None, Some("bar"), None],
1502 /// vec![None, None, Some("foo")],
1503 /// ])?;
1504 /// // The number of patterns being tracked.
1505 /// assert_eq!(4, info.pattern_len());
1506 /// // 2 slots per group
1507 /// assert_eq!(22, info.slot_len());
1508 ///
1509 /// # Ok::<(), Box<dyn std::error::Error>>(())
1510 /// ```
1511 ///
1512 /// # Example: empty `GroupInfo`
1513 ///
1514 /// This example shows how to build a new `GroupInfo` and query it for
1515 /// information.
1516 ///
1517 /// ```
1518 /// use regex_automata::util::captures::GroupInfo;
1519 ///
1520 /// let info = GroupInfo::empty();
1521 /// // Everything is zero.
1522 /// assert_eq!(0, info.pattern_len());
1523 /// assert_eq!(0, info.slot_len());
1524 ///
1525 /// # Ok::<(), Box<dyn std::error::Error>>(())
1526 /// ```
1527 ///
1528 /// # Example: error conditions
1529 ///
1530 /// This example shows how to provoke some of the ways in which building
1531 /// a `GroupInfo` can fail.
1532 ///
1533 /// ```
1534 /// use regex_automata::util::captures::GroupInfo;
1535 ///
1536 /// // Either the group info is empty, or all patterns must have at least
1537 /// // one capturing group.
1538 /// assert!(GroupInfo::new(vec![
1539 /// vec![None, Some("a")], // ok
1540 /// vec![None], // ok
1541 /// vec![], // not ok
1542 /// ]).is_err());
1543 /// // Note that building an empty group info is OK.
1544 /// assert!(GroupInfo::new(Vec::<Vec<Option<String>>>::new()).is_ok());
1545 ///
1546 /// // The first group in each pattern must correspond to an implicit
1547 /// // anonymous group. i.e., One that is not named. By convention, this
1548 /// // group corresponds to the overall match of a regex. Every other group
1549 /// // in a pattern is explicit and optional.
1550 /// assert!(GroupInfo::new(vec![vec![Some("foo")]]).is_err());
1551 ///
1552 /// // There must not be duplicate group names within the same pattern.
1553 /// assert!(GroupInfo::new(vec![
1554 /// vec![None, Some("foo"), Some("foo")],
1555 /// ]).is_err());
1556 /// // But duplicate names across distinct patterns is OK.
1557 /// assert!(GroupInfo::new(vec![
1558 /// vec![None, Some("foo")],
1559 /// vec![None, Some("foo")],
1560 /// ]).is_ok());
1561 ///
1562 /// # Ok::<(), Box<dyn std::error::Error>>(())
1563 /// ```
1564 ///
1565 /// There are other ways for building a `GroupInfo` to fail but are
1566 /// difficult to show. For example, if the number of patterns given would
1567 /// overflow `PatternID`.
1568 pub fn new<P, G, N>(pattern_groups: P) -> Result<GroupInfo, GroupInfoError>
1569 where
1570 P: IntoIterator<Item = G>,
1571 G: IntoIterator<Item = Option<N>>,
1572 N: AsRef<str>,
1573 {
1574 let mut group_info = GroupInfoInner {
1575 slot_ranges: vec![],
1576 name_to_index: vec![],
1577 index_to_name: vec![],
1578 memory_extra: 0,
1579 };
1580 for (pattern_index, groups) in pattern_groups.into_iter().enumerate() {
1581 // If we can't convert the pattern index to an ID, then the caller
1582 // tried to build capture info for too many patterns.
1583 let pid = PatternID::new(pattern_index)
1584 .map_err(GroupInfoError::too_many_patterns)?;
1585
1586 let mut groups_iter = groups.into_iter().enumerate();
1587 match groups_iter.next() {
1588 None => return Err(GroupInfoError::missing_groups(pid)),
1589 Some((_, Some(_))) => {
1590 return Err(GroupInfoError::first_must_be_unnamed(pid))
1591 }
1592 Some((_, None)) => {}
1593 }
1594 group_info.add_first_group(pid);
1595 // Now iterate over the rest, which correspond to all of the
1596 // (conventionally) explicit capture groups in a regex pattern.
1597 for (group_index, maybe_name) in groups_iter {
1598 // Just like for patterns, if the group index can't be
1599 // converted to a "small" index, then the caller has given too
1600 // many groups for a particular pattern.
1601 let group = SmallIndex::new(group_index).map_err(|_| {
1602 GroupInfoError::too_many_groups(pid, group_index)
1603 })?;
1604 group_info.add_explicit_group(pid, group, maybe_name)?;
1605 }
1606 }
1607 group_info.fixup_slot_ranges()?;
1608 Ok(GroupInfo(Arc::new(group_info)))
1609 }
1610
1611 /// This creates an empty `GroupInfo`.
1612 ///
1613 /// This is a convenience routine for calling `GroupInfo::new` with an
1614 /// iterator that yields no elements.
1615 ///
1616 /// # Example
1617 ///
1618 /// This example shows how to build a new empty `GroupInfo` and query it
1619 /// for information.
1620 ///
1621 /// ```
1622 /// use regex_automata::util::captures::GroupInfo;
1623 ///
1624 /// let info = GroupInfo::empty();
1625 /// // Everything is zero.
1626 /// assert_eq!(0, info.pattern_len());
1627 /// assert_eq!(0, info.all_group_len());
1628 /// assert_eq!(0, info.slot_len());
1629 ///
1630 /// # Ok::<(), Box<dyn std::error::Error>>(())
1631 /// ```
1632 pub fn empty() -> GroupInfo {
1633 GroupInfo::new(core::iter::empty::<[Option<&str>; 0]>())
1634 .expect("empty group info is always valid")
1635 }
1636
1637 /// Return the capture group index corresponding to the given name in the
1638 /// given pattern. If no such capture group name exists in the given
1639 /// pattern, then this returns `None`.
1640 ///
1641 /// If the given pattern ID is invalid, then this returns `None`.
1642 ///
1643 /// This also returns `None` for all inputs if these captures are empty
1644 /// (e.g., built from an empty [`GroupInfo`]). To check whether captures
1645 /// are are present for a specific pattern, use [`GroupInfo::group_len`].
1646 ///
1647 /// # Example
1648 ///
1649 /// This example shows how to find the capture index for the given pattern
1650 /// and group name.
1651 ///
1652 /// Remember that capture indices are relative to the pattern, such that
1653 /// the same capture index value may refer to different capturing groups
1654 /// for distinct patterns.
1655 ///
1656 /// ```
1657 /// # if cfg!(miri) { return Ok(()); } // miri takes too long
1658 /// use regex_automata::{nfa::thompson::NFA, PatternID};
1659 ///
1660 /// let (pid0, pid1) = (PatternID::must(0), PatternID::must(1));
1661 ///
1662 /// let nfa = NFA::new_many(&[
1663 /// r"a(?P<quux>\w+)z(?P<foo>\s+)",
1664 /// r"a(?P<foo>\d+)z",
1665 /// ])?;
1666 /// let groups = nfa.group_info();
1667 /// assert_eq!(Some(2), groups.to_index(pid0, "foo"));
1668 /// // Recall that capture index 0 is always unnamed and refers to the
1669 /// // entire pattern. So the first capturing group present in the pattern
1670 /// // itself always starts at index 1.
1671 /// assert_eq!(Some(1), groups.to_index(pid1, "foo"));
1672 ///
1673 /// // And if a name does not exist for a particular pattern, None is
1674 /// // returned.
1675 /// assert!(groups.to_index(pid0, "quux").is_some());
1676 /// assert!(groups.to_index(pid1, "quux").is_none());
1677 ///
1678 /// # Ok::<(), Box<dyn std::error::Error>>(())
1679 /// ```
1680 #[inline]
1681 pub fn to_index(&self, pid: PatternID, name: &str) -> Option<usize> {
1682 let indices = self.0.name_to_index.get(pid.as_usize())?;
1683 indices.get(name).cloned().map(|i| i.as_usize())
1684 }
1685
1686 /// Return the capture name for the given index and given pattern. If the
1687 /// corresponding group does not have a name, then this returns `None`.
1688 ///
1689 /// If the pattern ID is invalid, then this returns `None`.
1690 ///
1691 /// If the group index is invalid for the given pattern, then this returns
1692 /// `None`. A group `index` is valid for a pattern `pid` in an `nfa` if and
1693 /// only if `index < nfa.pattern_capture_len(pid)`.
1694 ///
1695 /// This also returns `None` for all inputs if these captures are empty
1696 /// (e.g., built from an empty [`GroupInfo`]). To check whether captures
1697 /// are are present for a specific pattern, use [`GroupInfo::group_len`].
1698 ///
1699 /// # Example
1700 ///
1701 /// This example shows how to find the capture group name for the given
1702 /// pattern and group index.
1703 ///
1704 /// ```
1705 /// # if cfg!(miri) { return Ok(()); } // miri takes too long
1706 /// use regex_automata::{nfa::thompson::NFA, PatternID};
1707 ///
1708 /// let (pid0, pid1) = (PatternID::must(0), PatternID::must(1));
1709 ///
1710 /// let nfa = NFA::new_many(&[
1711 /// r"a(?P<foo>\w+)z(\s+)x(\d+)",
1712 /// r"a(\d+)z(?P<foo>\s+)",
1713 /// ])?;
1714 /// let groups = nfa.group_info();
1715 /// assert_eq!(None, groups.to_name(pid0, 0));
1716 /// assert_eq!(Some("foo"), groups.to_name(pid0, 1));
1717 /// assert_eq!(None, groups.to_name(pid0, 2));
1718 /// assert_eq!(None, groups.to_name(pid0, 3));
1719 ///
1720 /// assert_eq!(None, groups.to_name(pid1, 0));
1721 /// assert_eq!(None, groups.to_name(pid1, 1));
1722 /// assert_eq!(Some("foo"), groups.to_name(pid1, 2));
1723 /// // '3' is not a valid capture index for the second pattern.
1724 /// assert_eq!(None, groups.to_name(pid1, 3));
1725 ///
1726 /// # Ok::<(), Box<dyn std::error::Error>>(())
1727 /// ```
1728 #[inline]
1729 pub fn to_name(&self, pid: PatternID, group_index: usize) -> Option<&str> {
1730 let pattern_names = self.0.index_to_name.get(pid.as_usize())?;
1731 pattern_names.get(group_index)?.as_deref()
1732 }
1733
1734 /// Return an iterator of all capture groups and their names (if present)
1735 /// for a particular pattern.
1736 ///
1737 /// If the given pattern ID is invalid or if this `GroupInfo` is empty,
1738 /// then the iterator yields no elements.
1739 ///
1740 /// The number of elements yielded by this iterator is always equal to
1741 /// the result of calling [`GroupInfo::group_len`] with the same
1742 /// `PatternID`.
1743 ///
1744 /// # Example
1745 ///
1746 /// This example shows how to get a list of all capture group names for
1747 /// a particular pattern.
1748 ///
1749 /// ```
1750 /// use regex_automata::{nfa::thompson::NFA, PatternID};
1751 ///
1752 /// let nfa = NFA::new(r"(a)(?P<foo>b)(c)(d)(?P<bar>e)")?;
1753 /// // The first is the implicit group that is always unnammed. The next
1754 /// // 5 groups are the explicit groups found in the concrete syntax above.
1755 /// let expected = vec![None, None, Some("foo"), None, None, Some("bar")];
1756 /// let got: Vec<Option<&str>> =
1757 /// nfa.group_info().pattern_names(PatternID::ZERO).collect();
1758 /// assert_eq!(expected, got);
1759 ///
1760 /// // Using an invalid pattern ID will result in nothing yielded.
1761 /// let got = nfa.group_info().pattern_names(PatternID::must(999)).count();
1762 /// assert_eq!(0, got);
1763 ///
1764 /// # Ok::<(), Box<dyn std::error::Error>>(())
1765 /// ```
1766 #[inline]
1767 pub fn pattern_names(&self, pid: PatternID) -> GroupInfoPatternNames<'_> {
1768 GroupInfoPatternNames {
1769 it: self
1770 .0
1771 .index_to_name
1772 .get(pid.as_usize())
1773 .map(|indices| indices.iter())
1774 .unwrap_or([].iter()),
1775 }
1776 }
1777
1778 /// Return an iterator of all capture groups for all patterns supported by
1779 /// this `GroupInfo`. Each item yielded is a triple of the group's pattern
1780 /// ID, index in the pattern and the group's name, if present.
1781 ///
1782 /// # Example
1783 ///
1784 /// This example shows how to get a list of all capture groups found in
1785 /// one NFA, potentially spanning multiple patterns.
1786 ///
1787 /// ```
1788 /// use regex_automata::{nfa::thompson::NFA, PatternID};
1789 ///
1790 /// let nfa = NFA::new_many(&[
1791 /// r"(?P<foo>a)",
1792 /// r"a",
1793 /// r"(a)",
1794 /// ])?;
1795 /// let expected = vec![
1796 /// (PatternID::must(0), 0, None),
1797 /// (PatternID::must(0), 1, Some("foo")),
1798 /// (PatternID::must(1), 0, None),
1799 /// (PatternID::must(2), 0, None),
1800 /// (PatternID::must(2), 1, None),
1801 /// ];
1802 /// let got: Vec<(PatternID, usize, Option<&str>)> =
1803 /// nfa.group_info().all_names().collect();
1804 /// assert_eq!(expected, got);
1805 ///
1806 /// # Ok::<(), Box<dyn std::error::Error>>(())
1807 /// ```
1808 ///
1809 /// Unlike other capturing group related routines, this routine doesn't
1810 /// panic even if captures aren't enabled on this NFA:
1811 ///
1812 /// ```
1813 /// use regex_automata::nfa::thompson::{NFA, WhichCaptures};
1814 ///
1815 /// let nfa = NFA::compiler()
1816 /// .configure(NFA::config().which_captures(WhichCaptures::None))
1817 /// .build_many(&[
1818 /// r"(?P<foo>a)",
1819 /// r"a",
1820 /// r"(a)",
1821 /// ])?;
1822 /// // When captures aren't enabled, there's nothing to return.
1823 /// assert_eq!(0, nfa.group_info().all_names().count());
1824 ///
1825 /// # Ok::<(), Box<dyn std::error::Error>>(())
1826 /// ```
1827 #[inline]
1828 pub fn all_names(&self) -> GroupInfoAllNames<'_> {
1829 GroupInfoAllNames {
1830 group_info: self,
1831 pids: PatternID::iter(self.pattern_len()),
1832 current_pid: None,
1833 names: None,
1834 }
1835 }
1836
1837 /// Returns the starting and ending slot corresponding to the given
1838 /// capturing group for the given pattern. The ending slot is always one
1839 /// more than the starting slot returned.
1840 ///
1841 /// Note that this is like [`GroupInfo::slot`], except that it also returns
1842 /// the ending slot value for convenience.
1843 ///
1844 /// If either the pattern ID or the capture index is invalid, then this
1845 /// returns None.
1846 ///
1847 /// # Example
1848 ///
1849 /// This example shows that the starting slots for the first capturing
1850 /// group of each pattern are distinct.
1851 ///
1852 /// ```
1853 /// use regex_automata::{nfa::thompson::NFA, PatternID};
1854 ///
1855 /// let nfa = NFA::new_many(&["a", "b"])?;
1856 /// assert_ne!(
1857 /// nfa.group_info().slots(PatternID::must(0), 0),
1858 /// nfa.group_info().slots(PatternID::must(1), 0),
1859 /// );
1860 ///
1861 /// // Also, the start and end slot values are never equivalent.
1862 /// let (start, end) = nfa.group_info().slots(PatternID::ZERO, 0).unwrap();
1863 /// assert_ne!(start, end);
1864 ///
1865 /// # Ok::<(), Box<dyn std::error::Error>>(())
1866 /// ```
1867 #[inline]
1868 pub fn slots(
1869 &self,
1870 pid: PatternID,
1871 group_index: usize,
1872 ) -> Option<(usize, usize)> {
1873 // Since 'slot' only even returns valid starting slots, we know that
1874 // there must also be an end slot and that end slot is always one more
1875 // than the start slot.
1876 self.slot(pid, group_index).map(|start| (start, start + 1))
1877 }
1878
1879 /// Returns the starting slot corresponding to the given capturing group
1880 /// for the given pattern. The ending slot is always one more than the
1881 /// value returned.
1882 ///
1883 /// If either the pattern ID or the capture index is invalid, then this
1884 /// returns None.
1885 ///
1886 /// # Example
1887 ///
1888 /// This example shows that the starting slots for the first capturing
1889 /// group of each pattern are distinct.
1890 ///
1891 /// ```
1892 /// use regex_automata::{nfa::thompson::NFA, PatternID};
1893 ///
1894 /// let nfa = NFA::new_many(&["a", "b"])?;
1895 /// assert_ne!(
1896 /// nfa.group_info().slot(PatternID::must(0), 0),
1897 /// nfa.group_info().slot(PatternID::must(1), 0),
1898 /// );
1899 ///
1900 /// # Ok::<(), Box<dyn std::error::Error>>(())
1901 /// ```
1902 #[inline]
1903 pub fn slot(&self, pid: PatternID, group_index: usize) -> Option<usize> {
1904 if group_index >= self.group_len(pid) {
1905 return None;
1906 }
1907 // At this point, we know that 'pid' refers to a real pattern and that
1908 // 'group_index' refers to a real group. We therefore also know that
1909 // the pattern and group can be combined to return a correct slot.
1910 // That's why we don't need to use checked arithmetic below.
1911 if group_index == 0 {
1912 Some(pid.as_usize() * 2)
1913 } else {
1914 // As above, we don't need to check that our slot is less than the
1915 // end of our range since we already know the group index is a
1916 // valid index for the given pattern.
1917 let (start, _) = self.0.slot_ranges[pid];
1918 Some(start.as_usize() + ((group_index - 1) * 2))
1919 }
1920 }
1921
1922 /// Returns the total number of patterns in this `GroupInfo`.
1923 ///
1924 /// This may return zero if the `GroupInfo` was constructed with no
1925 /// patterns.
1926 ///
1927 /// This is guaranteed to be no bigger than [`PatternID::LIMIT`] because
1928 /// `GroupInfo` construction will fail if too many patterns are added.
1929 ///
1930 /// # Example
1931 ///
1932 /// ```
1933 /// use regex_automata::nfa::thompson::NFA;
1934 ///
1935 /// let nfa = NFA::new_many(&["[0-9]+", "[a-z]+", "[A-Z]+"])?;
1936 /// assert_eq!(3, nfa.group_info().pattern_len());
1937 ///
1938 /// let nfa = NFA::never_match();
1939 /// assert_eq!(0, nfa.group_info().pattern_len());
1940 ///
1941 /// let nfa = NFA::always_match();
1942 /// assert_eq!(1, nfa.group_info().pattern_len());
1943 ///
1944 /// # Ok::<(), Box<dyn std::error::Error>>(())
1945 /// ```
1946 #[inline]
1947 pub fn pattern_len(&self) -> usize {
1948 self.0.pattern_len()
1949 }
1950
1951 /// Return the number of capture groups in a pattern.
1952 ///
1953 /// If the pattern ID is invalid, then this returns `0`.
1954 ///
1955 /// # Example
1956 ///
1957 /// This example shows how the values returned by this routine may vary
1958 /// for different patterns and NFA configurations.
1959 ///
1960 /// ```
1961 /// use regex_automata::{nfa::thompson::{NFA, WhichCaptures}, PatternID};
1962 ///
1963 /// let nfa = NFA::new(r"(a)(b)(c)")?;
1964 /// // There are 3 explicit groups in the pattern's concrete syntax and
1965 /// // 1 unnamed and implicit group spanning the entire pattern.
1966 /// assert_eq!(4, nfa.group_info().group_len(PatternID::ZERO));
1967 ///
1968 /// let nfa = NFA::new(r"abc")?;
1969 /// // There is just the unnamed implicit group.
1970 /// assert_eq!(1, nfa.group_info().group_len(PatternID::ZERO));
1971 ///
1972 /// let nfa = NFA::compiler()
1973 /// .configure(NFA::config().which_captures(WhichCaptures::None))
1974 /// .build(r"abc")?;
1975 /// // We disabled capturing groups, so there are none.
1976 /// assert_eq!(0, nfa.group_info().group_len(PatternID::ZERO));
1977 ///
1978 /// let nfa = NFA::compiler()
1979 /// .configure(NFA::config().which_captures(WhichCaptures::None))
1980 /// .build(r"(a)(b)(c)")?;
1981 /// // We disabled capturing groups, so there are none, even if there are
1982 /// // explicit groups in the concrete syntax.
1983 /// assert_eq!(0, nfa.group_info().group_len(PatternID::ZERO));
1984 ///
1985 /// # Ok::<(), Box<dyn std::error::Error>>(())
1986 /// ```
1987 #[inline]
1988 pub fn group_len(&self, pid: PatternID) -> usize {
1989 self.0.group_len(pid)
1990 }
1991
1992 /// Return the total number of capture groups across all patterns.
1993 ///
1994 /// This includes implicit groups that represent the entire match of a
1995 /// pattern.
1996 ///
1997 /// # Example
1998 ///
1999 /// This example shows how the values returned by this routine may vary
2000 /// for different patterns and NFA configurations.
2001 ///
2002 /// ```
2003 /// use regex_automata::{nfa::thompson::{NFA, WhichCaptures}, PatternID};
2004 ///
2005 /// let nfa = NFA::new(r"(a)(b)(c)")?;
2006 /// // There are 3 explicit groups in the pattern's concrete syntax and
2007 /// // 1 unnamed and implicit group spanning the entire pattern.
2008 /// assert_eq!(4, nfa.group_info().all_group_len());
2009 ///
2010 /// let nfa = NFA::new(r"abc")?;
2011 /// // There is just the unnamed implicit group.
2012 /// assert_eq!(1, nfa.group_info().all_group_len());
2013 ///
2014 /// let nfa = NFA::new_many(&["(a)", "b", "(c)"])?;
2015 /// // Each pattern has one implicit groups, and two
2016 /// // patterns have one explicit group each.
2017 /// assert_eq!(5, nfa.group_info().all_group_len());
2018 ///
2019 /// let nfa = NFA::compiler()
2020 /// .configure(NFA::config().which_captures(WhichCaptures::None))
2021 /// .build(r"abc")?;
2022 /// // We disabled capturing groups, so there are none.
2023 /// assert_eq!(0, nfa.group_info().all_group_len());
2024 ///
2025 /// let nfa = NFA::compiler()
2026 /// .configure(NFA::config().which_captures(WhichCaptures::None))
2027 /// .build(r"(a)(b)(c)")?;
2028 /// // We disabled capturing groups, so there are none, even if there are
2029 /// // explicit groups in the concrete syntax.
2030 /// assert_eq!(0, nfa.group_info().group_len(PatternID::ZERO));
2031 ///
2032 /// # Ok::<(), Box<dyn std::error::Error>>(())
2033 /// ```
2034 #[inline]
2035 pub fn all_group_len(&self) -> usize {
2036 self.slot_len() / 2
2037 }
2038
2039 /// Returns the total number of slots in this `GroupInfo` across all
2040 /// patterns.
2041 ///
2042 /// The total number of slots is always twice the total number of capturing
2043 /// groups, including both implicit and explicit groups.
2044 ///
2045 /// # Example
2046 ///
2047 /// This example shows the relationship between the number of capturing
2048 /// groups and slots.
2049 ///
2050 /// ```
2051 /// use regex_automata::util::captures::GroupInfo;
2052 ///
2053 /// // There are 11 total groups here.
2054 /// let info = GroupInfo::new(vec![
2055 /// vec![None, Some("foo")],
2056 /// vec![None],
2057 /// vec![None, None, None, Some("bar"), None],
2058 /// vec![None, None, Some("foo")],
2059 /// ])?;
2060 /// // 2 slots per group gives us 11*2=22 slots.
2061 /// assert_eq!(22, info.slot_len());
2062 ///
2063 /// # Ok::<(), Box<dyn std::error::Error>>(())
2064 /// ```
2065 #[inline]
2066 pub fn slot_len(&self) -> usize {
2067 self.0.small_slot_len().as_usize()
2068 }
2069
2070 /// Returns the total number of slots for implicit capturing groups.
2071 ///
2072 /// This is like [`GroupInfo::slot_len`], except it doesn't include the
2073 /// explicit slots for each pattern. Since there are always exactly 2
2074 /// implicit slots for each pattern, the number of implicit slots is always
2075 /// equal to twice the number of patterns.
2076 ///
2077 /// # Example
2078 ///
2079 /// This example shows the relationship between the number of capturing
2080 /// groups, implicit slots and explicit slots.
2081 ///
2082 /// ```
2083 /// use regex_automata::util::captures::GroupInfo;
2084 ///
2085 /// // There are 11 total groups here.
2086 /// let info = GroupInfo::new(vec![vec![None, Some("foo"), Some("bar")]])?;
2087 /// // 2 slots per group gives us 11*2=22 slots.
2088 /// assert_eq!(6, info.slot_len());
2089 /// // 2 implicit slots per pattern gives us 2 implicit slots since there
2090 /// // is 1 pattern.
2091 /// assert_eq!(2, info.implicit_slot_len());
2092 /// // 2 explicit capturing groups gives us 2*2=4 explicit slots.
2093 /// assert_eq!(4, info.explicit_slot_len());
2094 ///
2095 /// # Ok::<(), Box<dyn std::error::Error>>(())
2096 /// ```
2097 #[inline]
2098 pub fn implicit_slot_len(&self) -> usize {
2099 self.pattern_len() * 2
2100 }
2101
2102 /// Returns the total number of slots for explicit capturing groups.
2103 ///
2104 /// This is like [`GroupInfo::slot_len`], except it doesn't include the
2105 /// implicit slots for each pattern. (There are always 2 implicit slots for
2106 /// each pattern.)
2107 ///
2108 /// For a non-empty `GroupInfo`, it is always the case that `slot_len` is
2109 /// strictly greater than `explicit_slot_len`. For an empty `GroupInfo`,
2110 /// both the total number of slots and the number of explicit slots is
2111 /// `0`.
2112 ///
2113 /// # Example
2114 ///
2115 /// This example shows the relationship between the number of capturing
2116 /// groups, implicit slots and explicit slots.
2117 ///
2118 /// ```
2119 /// use regex_automata::util::captures::GroupInfo;
2120 ///
2121 /// // There are 11 total groups here.
2122 /// let info = GroupInfo::new(vec![vec![None, Some("foo"), Some("bar")]])?;
2123 /// // 2 slots per group gives us 11*2=22 slots.
2124 /// assert_eq!(6, info.slot_len());
2125 /// // 2 implicit slots per pattern gives us 2 implicit slots since there
2126 /// // is 1 pattern.
2127 /// assert_eq!(2, info.implicit_slot_len());
2128 /// // 2 explicit capturing groups gives us 2*2=4 explicit slots.
2129 /// assert_eq!(4, info.explicit_slot_len());
2130 ///
2131 /// # Ok::<(), Box<dyn std::error::Error>>(())
2132 /// ```
2133 #[inline]
2134 pub fn explicit_slot_len(&self) -> usize {
2135 self.slot_len().saturating_sub(self.implicit_slot_len())
2136 }
2137
2138 /// Returns the memory usage, in bytes, of this `GroupInfo`.
2139 ///
2140 /// This does **not** include the stack size used up by this `GroupInfo`.
2141 /// To compute that, use `std::mem::size_of::<GroupInfo>()`.
2142 #[inline]
2143 pub fn memory_usage(&self) -> usize {
2144 use core::mem::size_of as s;
2145
2146 s::<GroupInfoInner>()
2147 + self.0.slot_ranges.len() * s::<(SmallIndex, SmallIndex)>()
2148 + self.0.name_to_index.len() * s::<CaptureNameMap>()
2149 + self.0.index_to_name.len() * s::<Vec<Option<Arc<str>>>>()
2150 + self.0.memory_extra
2151 }
2152 }
2153
2154 /// A map from capture group name to its corresponding capture group index.
2155 ///
2156 /// This type is actually wrapped inside a Vec indexed by pattern ID on a
2157 /// `GroupInfo`, since multiple patterns may have the same capture group name.
2158 /// That is, each pattern gets its own namespace of capture group names.
2159 ///
2160 /// Perhaps a more memory efficient representation would be
2161 /// HashMap<(PatternID, Arc<str>), usize>, but this makes it difficult to look
2162 /// up a capture index by name without producing a `Arc<str>`, which requires
2163 /// an allocation. To fix this, I think we'd need to define our own unsized
2164 /// type or something? Anyway, I didn't give this much thought since it
2165 /// probably doesn't matter much in the grand scheme of things. But it did
2166 /// stand out to me as mildly wasteful.
2167 #[cfg(feature = "std")]
2168 type CaptureNameMap = std::collections::HashMap<Arc<str>, SmallIndex>;
2169 #[cfg(not(feature = "std"))]
2170 type CaptureNameMap = alloc::collections::BTreeMap<Arc<str>, SmallIndex>;
2171
2172 /// The inner guts of `GroupInfo`. This type only exists so that it can
2173 /// be wrapped in an `Arc` to make `GroupInfo` reference counted.
2174 #[derive(Debug, Default)]
2175 struct GroupInfoInner {
2176 slot_ranges: Vec<(SmallIndex, SmallIndex)>,
2177 name_to_index: Vec<CaptureNameMap>,
2178 index_to_name: Vec<Vec<Option<Arc<str>>>>,
2179 memory_extra: usize,
2180 }
2181
2182 impl GroupInfoInner {
2183 /// This adds the first unnamed group for the given pattern ID. The given
2184 /// pattern ID must be zero if this is the first time this method is
2185 /// called, or must be exactly one more than the pattern ID supplied to the
2186 /// previous call to this method. (This method panics if this rule is
2187 /// violated.)
2188 ///
2189 /// This can be thought of as initializing the GroupInfo state for the
2190 /// given pattern and closing off the state for any previous pattern.
2191 fn add_first_group(&mut self, pid: PatternID) {
2192 assert_eq!(pid.as_usize(), self.slot_ranges.len());
2193 assert_eq!(pid.as_usize(), self.name_to_index.len());
2194 assert_eq!(pid.as_usize(), self.index_to_name.len());
2195 // This is the start of our slots for the explicit capturing groups.
2196 // Note that since the slots for the 0th group for every pattern appear
2197 // before any slots for the nth group (where n > 0) in any pattern, we
2198 // will have to fix up the slot ranges once we know how many patterns
2199 // we've added capture groups for.
2200 let slot_start = self.small_slot_len();
2201 self.slot_ranges.push((slot_start, slot_start));
2202 self.name_to_index.push(CaptureNameMap::new());
2203 self.index_to_name.push(vec![None]);
2204 self.memory_extra += core::mem::size_of::<Option<Arc<str>>>();
2205 }
2206
2207 /// Add an explicit capturing group for the given pattern with the given
2208 /// index. If the group has a name, then that must be given as well.
2209 ///
2210 /// Note that every capturing group except for the first or zeroth group is
2211 /// explicit.
2212 ///
2213 /// This returns an error if adding this group would result in overflowing
2214 /// slot indices or if a capturing group with the same name for this
2215 /// pattern has already been added.
2216 fn add_explicit_group<N: AsRef<str>>(
2217 &mut self,
2218 pid: PatternID,
2219 group: SmallIndex,
2220 maybe_name: Option<N>,
2221 ) -> Result<(), GroupInfoError> {
2222 // We also need to check that the slot index generated for
2223 // this group is also valid. Although, this is a little weird
2224 // because we offset these indices below, at which point, we'll
2225 // have to recheck them. Gosh this is annoying. Note that
2226 // the '+2' below is OK because 'end' is guaranteed to be less
2227 // than isize::MAX.
2228 let end = &mut self.slot_ranges[pid].1;
2229 *end = SmallIndex::new(end.as_usize() + 2).map_err(|_| {
2230 GroupInfoError::too_many_groups(pid, group.as_usize())
2231 })?;
2232 if let Some(name) = maybe_name {
2233 let name = Arc::<str>::from(name.as_ref());
2234 if self.name_to_index[pid].contains_key(&*name) {
2235 return Err(GroupInfoError::duplicate(pid, &name));
2236 }
2237 let len = name.len();
2238 self.name_to_index[pid].insert(Arc::clone(&name), group);
2239 self.index_to_name[pid].push(Some(name));
2240 // Adds the memory used by the Arc<str> in both maps.
2241 self.memory_extra +=
2242 2 * (len + core::mem::size_of::<Option<Arc<str>>>());
2243 // And also the value entry for the 'name_to_index' map.
2244 // This is probably an underestimate for 'name_to_index' since
2245 // hashmaps/btrees likely have some non-zero overhead, but we
2246 // assume here that they have zero overhead.
2247 self.memory_extra += core::mem::size_of::<SmallIndex>();
2248 } else {
2249 self.index_to_name[pid].push(None);
2250 self.memory_extra += core::mem::size_of::<Option<Arc<str>>>();
2251 }
2252 // This is a sanity assert that checks that our group index
2253 // is in line with the number of groups added so far for this
2254 // pattern.
2255 assert_eq!(group.one_more(), self.group_len(pid));
2256 // And is also in line with the 'index_to_name' map.
2257 assert_eq!(group.one_more(), self.index_to_name[pid].len());
2258 Ok(())
2259 }
2260
2261 /// This corrects the slot ranges to account for the slots corresponding
2262 /// to the zeroth group of each pattern. That is, every slot range is
2263 /// offset by 'pattern_len() * 2', since each pattern uses two slots to
2264 /// represent the zeroth group.
2265 fn fixup_slot_ranges(&mut self) -> Result<(), GroupInfoError> {
2266 use crate::util::primitives::IteratorIndexExt;
2267 // Since we know number of patterns fits in PatternID and
2268 // PatternID::MAX < isize::MAX, it follows that multiplying by 2 will
2269 // never overflow usize.
2270 let offset = self.pattern_len().checked_mul(2).unwrap();
2271 for (pid, &mut (ref mut start, ref mut end)) in
2272 self.slot_ranges.iter_mut().with_pattern_ids()
2273 {
2274 let group_len = 1 + ((end.as_usize() - start.as_usize()) / 2);
2275 let new_end = match end.as_usize().checked_add(offset) {
2276 Some(new_end) => new_end,
2277 None => {
2278 return Err(GroupInfoError::too_many_groups(
2279 pid, group_len,
2280 ))
2281 }
2282 };
2283 *end = SmallIndex::new(new_end).map_err(|_| {
2284 GroupInfoError::too_many_groups(pid, group_len)
2285 })?;
2286 // Since start <= end, if end is valid then start must be too.
2287 *start = SmallIndex::new(start.as_usize() + offset).unwrap();
2288 }
2289 Ok(())
2290 }
2291
2292 /// Return the total number of patterns represented by this capture slot
2293 /// info.
2294 fn pattern_len(&self) -> usize {
2295 self.slot_ranges.len()
2296 }
2297
2298 /// Return the total number of capturing groups for the given pattern. If
2299 /// the given pattern isn't valid for this capture slot info, then 0 is
2300 /// returned.
2301 fn group_len(&self, pid: PatternID) -> usize {
2302 let (start, end) = match self.slot_ranges.get(pid.as_usize()) {
2303 None => return 0,
2304 Some(range) => range,
2305 };
2306 // The difference between any two SmallIndex values always fits in a
2307 // usize since we know that SmallIndex::MAX <= isize::MAX-1. We also
2308 // know that start<=end by construction and that the number of groups
2309 // never exceeds SmallIndex and thus never overflows usize.
2310 1 + ((end.as_usize() - start.as_usize()) / 2)
2311 }
2312
2313 /// Return the total number of slots in this capture slot info as a
2314 /// "small index."
2315 fn small_slot_len(&self) -> SmallIndex {
2316 // Since slots are allocated in order of pattern (starting at 0) and
2317 // then in order of capture group, it follows that the number of slots
2318 // is the end of the range of slots for the last pattern. This is
2319 // true even when the last pattern has no capturing groups, since
2320 // 'slot_ranges' will still represent it explicitly with an empty
2321 // range.
2322 self.slot_ranges.last().map_or(SmallIndex::ZERO, |&(_, end)| end)
2323 }
2324 }
2325
2326 /// An error that may occur when building a `GroupInfo`.
2327 ///
2328 /// Building a `GroupInfo` does a variety of checks to make sure the
2329 /// capturing groups satisfy a number of invariants. This includes, but is not
2330 /// limited to, ensuring that the first capturing group is unnamed and that
2331 /// there are no duplicate capture groups for a specific pattern.
2332 #[derive(Clone, Debug)]
2333 pub struct GroupInfoError {
2334 kind: GroupInfoErrorKind,
2335 }
2336
2337 /// The kind of error that occurs when building a `GroupInfo` fails.
2338 ///
2339 /// We keep this un-exported because it's not clear how useful it is to
2340 /// export it.
2341 #[derive(Clone, Debug)]
2342 enum GroupInfoErrorKind {
2343 /// This occurs when too many patterns have been added. i.e., It would
2344 /// otherwise overflow a `PatternID`.
2345 TooManyPatterns { err: PatternIDError },
2346 /// This occurs when too many capturing groups have been added for a
2347 /// particular pattern.
2348 TooManyGroups {
2349 /// The ID of the pattern that had too many groups.
2350 pattern: PatternID,
2351 /// The minimum number of groups that the caller has tried to add for
2352 /// a pattern.
2353 minimum: usize,
2354 },
2355 /// An error that occurs when a pattern has no capture groups. Either the
2356 /// group info must be empty, or all patterns must have at least one group
2357 /// (corresponding to the unnamed group for the entire pattern).
2358 MissingGroups {
2359 /// The ID of the pattern that had no capturing groups.
2360 pattern: PatternID,
2361 },
2362 /// An error that occurs when one tries to provide a name for the capture
2363 /// group at index 0. This capturing group must currently always be
2364 /// unnamed.
2365 FirstMustBeUnnamed {
2366 /// The ID of the pattern that was found to have a named first
2367 /// capturing group.
2368 pattern: PatternID,
2369 },
2370 /// An error that occurs when duplicate capture group names for the same
2371 /// pattern are added.
2372 ///
2373 /// NOTE: At time of writing, this error can never occur if you're using
2374 /// regex-syntax, since the parser itself will reject patterns with
2375 /// duplicate capture group names. This error can only occur when the
2376 /// builder is used to hand construct NFAs.
2377 Duplicate {
2378 /// The pattern in which the duplicate capture group name was found.
2379 pattern: PatternID,
2380 /// The duplicate name.
2381 name: String,
2382 },
2383 }
2384
2385 impl GroupInfoError {
2386 fn too_many_patterns(err: PatternIDError) -> GroupInfoError {
2387 GroupInfoError { kind: GroupInfoErrorKind::TooManyPatterns { err } }
2388 }
2389
2390 fn too_many_groups(pattern: PatternID, minimum: usize) -> GroupInfoError {
2391 GroupInfoError {
2392 kind: GroupInfoErrorKind::TooManyGroups { pattern, minimum },
2393 }
2394 }
2395
2396 fn missing_groups(pattern: PatternID) -> GroupInfoError {
2397 GroupInfoError { kind: GroupInfoErrorKind::MissingGroups { pattern } }
2398 }
2399
2400 fn first_must_be_unnamed(pattern: PatternID) -> GroupInfoError {
2401 GroupInfoError {
2402 kind: GroupInfoErrorKind::FirstMustBeUnnamed { pattern },
2403 }
2404 }
2405
2406 fn duplicate(pattern: PatternID, name: &str) -> GroupInfoError {
2407 GroupInfoError {
2408 kind: GroupInfoErrorKind::Duplicate {
2409 pattern,
2410 name: String::from(name),
2411 },
2412 }
2413 }
2414 }
2415
2416 #[cfg(feature = "std")]
2417 impl std::error::Error for GroupInfoError {
2418 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
2419 match self.kind {
2420 GroupInfoErrorKind::TooManyPatterns { .. }
2421 | GroupInfoErrorKind::TooManyGroups { .. }
2422 | GroupInfoErrorKind::MissingGroups { .. }
2423 | GroupInfoErrorKind::FirstMustBeUnnamed { .. }
2424 | GroupInfoErrorKind::Duplicate { .. } => None,
2425 }
2426 }
2427 }
2428
2429 impl core::fmt::Display for GroupInfoError {
2430 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2431 use self::GroupInfoErrorKind::*;
2432
2433 match self.kind {
2434 TooManyPatterns { ref err } => {
2435 write!(f, "too many patterns to build capture info: {}", err)
2436 }
2437 TooManyGroups { pattern, minimum } => {
2438 write!(
2439 f,
2440 "too many capture groups (at least {}) were \
2441 found for pattern {}",
2442 minimum,
2443 pattern.as_usize()
2444 )
2445 }
2446 MissingGroups { pattern } => write!(
2447 f,
2448 "no capturing groups found for pattern {} \
2449 (either all patterns have zero groups or all patterns have \
2450 at least one group)",
2451 pattern.as_usize(),
2452 ),
2453 FirstMustBeUnnamed { pattern } => write!(
2454 f,
2455 "first capture group (at index 0) for pattern {} has a name \
2456 (it must be unnamed)",
2457 pattern.as_usize(),
2458 ),
2459 Duplicate { pattern, ref name } => write!(
2460 f,
2461 "duplicate capture group name '{}' found for pattern {}",
2462 name,
2463 pattern.as_usize(),
2464 ),
2465 }
2466 }
2467 }
2468
2469 /// An iterator over capturing groups and their names for a specific pattern.
2470 ///
2471 /// This iterator is created by [`GroupInfo::pattern_names`].
2472 ///
2473 /// The lifetime parameter `'a` refers to the lifetime of the `GroupInfo`
2474 /// from which this iterator was created.
2475 #[derive(Clone, Debug)]
2476 pub struct GroupInfoPatternNames<'a> {
2477 it: core::slice::Iter<'a, Option<Arc<str>>>,
2478 }
2479
2480 impl GroupInfoPatternNames<'static> {
2481 fn empty() -> GroupInfoPatternNames<'static> {
2482 GroupInfoPatternNames { it: [].iter() }
2483 }
2484 }
2485
2486 impl<'a> Iterator for GroupInfoPatternNames<'a> {
2487 type Item = Option<&'a str>;
2488
2489 fn next(&mut self) -> Option<Option<&'a str>> {
2490 self.it.next().map(|x| x.as_deref())
2491 }
2492
2493 fn size_hint(&self) -> (usize, Option<usize>) {
2494 self.it.size_hint()
2495 }
2496
2497 fn count(self) -> usize {
2498 self.it.count()
2499 }
2500 }
2501
2502 impl<'a> ExactSizeIterator for GroupInfoPatternNames<'a> {}
2503 impl<'a> core::iter::FusedIterator for GroupInfoPatternNames<'a> {}
2504
2505 /// An iterator over capturing groups and their names for a `GroupInfo`.
2506 ///
2507 /// This iterator is created by [`GroupInfo::all_names`].
2508 ///
2509 /// The lifetime parameter `'a` refers to the lifetime of the `GroupInfo`
2510 /// from which this iterator was created.
2511 #[derive(Debug)]
2512 pub struct GroupInfoAllNames<'a> {
2513 group_info: &'a GroupInfo,
2514 pids: PatternIDIter,
2515 current_pid: Option<PatternID>,
2516 names: Option<core::iter::Enumerate<GroupInfoPatternNames<'a>>>,
2517 }
2518
2519 impl<'a> Iterator for GroupInfoAllNames<'a> {
2520 type Item = (PatternID, usize, Option<&'a str>);
2521
2522 fn next(&mut self) -> Option<(PatternID, usize, Option<&'a str>)> {
2523 // If the group info has no captures, then we never have anything
2524 // to yield. We need to consider this case explicitly (at time of
2525 // writing) because 'pattern_capture_names' will panic if captures
2526 // aren't enabled.
2527 if self.group_info.0.index_to_name.is_empty() {
2528 return None;
2529 }
2530 if self.current_pid.is_none() {
2531 self.current_pid = Some(self.pids.next()?);
2532 }
2533 let pid = self.current_pid.unwrap();
2534 if self.names.is_none() {
2535 self.names = Some(self.group_info.pattern_names(pid).enumerate());
2536 }
2537 let (group_index, name) = match self.names.as_mut().unwrap().next() {
2538 Some((group_index, name)) => (group_index, name),
2539 None => {
2540 self.current_pid = None;
2541 self.names = None;
2542 return self.next();
2543 }
2544 };
2545 Some((pid, group_index, name))
2546 }
2547 }