Debian Codegraph @

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

raw
1 /*!
2 Provides some helpers for dealing with start state configurations in DFAs.
3
4 [`Start`] represents the possible starting configurations, while
5 [`StartByteMap`] represents a way to retrieve the `Start` configuration for a
6 given position in a haystack.
7 */
8
9 use crate::util::{
10 look::LookMatcher,
11 search::Input,
12 wire::{self, DeserializeError, SerializeError},
13 };
14
15 /// A map from every possible byte value to its corresponding starting
16 /// configuration.
17 ///
18 /// This map is used in order to lookup the start configuration for a particular
19 /// position in a haystack. This start configuration is then used in
20 /// combination with things like the anchored mode and pattern ID to fully
21 /// determine the start state.
22 ///
23 /// Generally speaking, this map is only used for fully compiled DFAs and lazy
24 /// DFAs. For NFAs (including the one-pass DFA), the start state is generally
25 /// selected by virtue of traversing the NFA state graph. DFAs do the same
26 /// thing, but at build time and not search time. (Well, technically the lazy
27 /// DFA does it at search time, but it does enough work to cache the full
28 /// result of the epsilon closure that the NFA engines tend to need to do.)
29 #[derive(Clone)]
30 pub(crate) struct StartByteMap {
31 map: [Start; 256],
32 }
33
34 impl StartByteMap {
35 /// Create a new map from byte values to their corresponding starting
36 /// configurations. The map is determined, in part, by how look-around
37 /// assertions are matched via the matcher given.
38 pub(crate) fn new(lookm: &LookMatcher) -> StartByteMap {
39 let mut map = [Start::NonWordByte; 256];
40 map[usize::from(b'\n')] = Start::LineLF;
41 map[usize::from(b'\r')] = Start::LineCR;
42 map[usize::from(b'_')] = Start::WordByte;
43
44 let mut byte = b'0';
45 while byte <= b'9' {
46 map[usize::from(byte)] = Start::WordByte;
47 byte += 1;
48 }
49 byte = b'A';
50 while byte <= b'Z' {
51 map[usize::from(byte)] = Start::WordByte;
52 byte += 1;
53 }
54 byte = b'a';
55 while byte <= b'z' {
56 map[usize::from(byte)] = Start::WordByte;
57 byte += 1;
58 }
59
60 let lineterm = lookm.get_line_terminator();
61 // If our line terminator is normal, then it is already handled by
62 // the LineLF and LineCR configurations. But if it's weird, then we
63 // overwrite whatever was there before for that terminator with a
64 // special configuration. The trick here is that if the terminator
65 // is, say, a word byte like `a`, then callers seeing this start
66 // configuration need to account for that and build their DFA state as
67 // if it *also* came from a word byte.
68 if lineterm != b'\r' && lineterm != b'\n' {
69 map[usize::from(lineterm)] = Start::CustomLineTerminator;
70 }
71 StartByteMap { map }
72 }
73
74 /// Return the forward starting configuration for the given `input`.
75 #[cfg_attr(feature = "perf-inline", inline(always))]
76 pub(crate) fn fwd(&self, input: &Input) -> Start {
77 match input
78 .start()
79 .checked_sub(1)
80 .and_then(|i| input.haystack().get(i))
81 {
82 None => Start::Text,
83 Some(&byte) => self.get(byte),
84 }
85 }
86
87 /// Return the reverse starting configuration for the given `input`.
88 #[cfg_attr(feature = "perf-inline", inline(always))]
89 pub(crate) fn rev(&self, input: &Input) -> Start {
90 match input.haystack().get(input.end()) {
91 None => Start::Text,
92 Some(&byte) => self.get(byte),
93 }
94 }
95
96 #[cfg_attr(feature = "perf-inline", inline(always))]
97 fn get(&self, byte: u8) -> Start {
98 self.map[usize::from(byte)]
99 }
100
101 /// Deserializes a byte class map from the given slice. If the slice is of
102 /// insufficient length or otherwise contains an impossible mapping, then
103 /// an error is returned. Upon success, the number of bytes read along with
104 /// the map are returned. The number of bytes read is always a multiple of
105 /// 8.
106 pub(crate) fn from_bytes(
107 slice: &[u8],
108 ) -> Result<(StartByteMap, usize), DeserializeError> {
109 wire::check_slice_len(slice, 256, "start byte map")?;
110 let mut map = [Start::NonWordByte; 256];
111 for (i, &repr) in slice[..256].iter().enumerate() {
112 map[i] = match Start::from_usize(usize::from(repr)) {
113 Some(start) => start,
114 None => {
115 return Err(DeserializeError::generic(
116 "found invalid starting configuration",
117 ))
118 }
119 };
120 }
121 Ok((StartByteMap { map }, 256))
122 }
123
124 /// Writes this map to the given byte buffer. if the given buffer is too
125 /// small, then an error is returned. Upon success, the total number of
126 /// bytes written is returned. The number of bytes written is guaranteed to
127 /// be a multiple of 8.
128 pub(crate) fn write_to(
129 &self,
130 dst: &mut [u8],
131 ) -> Result<usize, SerializeError> {
132 let nwrite = self.write_to_len();
133 if dst.len() < nwrite {
134 return Err(SerializeError::buffer_too_small("start byte map"));
135 }
136 for (i, &start) in self.map.iter().enumerate() {
137 dst[i] = start.as_u8();
138 }
139 Ok(nwrite)
140 }
141
142 /// Returns the total number of bytes written by `write_to`.
143 pub(crate) fn write_to_len(&self) -> usize {
144 256
145 }
146 }
147
148 impl core::fmt::Debug for StartByteMap {
149 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
150 use crate::util::escape::DebugByte;
151
152 write!(f, "StartByteMap{{")?;
153 for byte in 0..=255 {
154 if byte > 0 {
155 write!(f, ", ")?;
156 }
157 let start = self.map[usize::from(byte)];
158 write!(f, "{:?} => {:?}", DebugByte(byte), start)?;
159 }
160 write!(f, "}}")?;
161 Ok(())
162 }
163 }
164
165 /// Represents the six possible starting configurations of a DFA search.
166 ///
167 /// The starting configuration is determined by inspecting the the beginning
168 /// of the haystack (up to 1 byte). Ultimately, this along with a pattern ID
169 /// (if specified) and the type of search (anchored or not) is what selects the
170 /// start state to use in a DFA.
171 ///
172 /// As one example, if a DFA only supports unanchored searches and does not
173 /// support anchored searches for each pattern, then it will have at most 6
174 /// distinct start states. (Some start states may be reused if determinization
175 /// can determine that they will be equivalent.) If the DFA supports both
176 /// anchored and unanchored searches, then it will have a maximum of 12
177 /// distinct start states. Finally, if the DFA also supports anchored searches
178 /// for each pattern, then it can have up to `12 + (N * 6)` start states, where
179 /// `N` is the number of patterns.
180 ///
181 /// Handling each of these starting configurations in the context of DFA
182 /// determinization can be *quite* tricky and subtle. But the code is small
183 /// and can be found at `crate::util::determinize::set_lookbehind_from_start`.
184 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
185 pub(crate) enum Start {
186 /// This occurs when the starting position is not any of the ones below.
187 NonWordByte = 0,
188 /// This occurs when the byte immediately preceding the start of the search
189 /// is an ASCII word byte.
190 WordByte = 1,
191 /// This occurs when the starting position of the search corresponds to the
192 /// beginning of the haystack.
193 Text = 2,
194 /// This occurs when the byte immediately preceding the start of the search
195 /// is a line terminator. Specifically, `\n`.
196 LineLF = 3,
197 /// This occurs when the byte immediately preceding the start of the search
198 /// is a line terminator. Specifically, `\r`.
199 LineCR = 4,
200 /// This occurs when a custom line terminator has been set via a
201 /// `LookMatcher`, and when that line terminator is neither a `\r` or a
202 /// `\n`.
203 ///
204 /// If the custom line terminator is a word byte, then this start
205 /// configuration is still selected. DFAs that implement word boundary
206 /// assertions will likely need to check whether the custom line terminator
207 /// is a word byte, in which case, it should behave as if the byte
208 /// satisfies `\b` in addition to multi-line anchors.
209 CustomLineTerminator = 5,
210 }
211
212 impl Start {
213 /// Return the starting state corresponding to the given integer. If no
214 /// starting state exists for the given integer, then None is returned.
215 pub(crate) fn from_usize(n: usize) -> Option<Start> {
216 match n {
217 0 => Some(Start::NonWordByte),
218 1 => Some(Start::WordByte),
219 2 => Some(Start::Text),
220 3 => Some(Start::LineLF),
221 4 => Some(Start::LineCR),
222 5 => Some(Start::CustomLineTerminator),
223 _ => None,
224 }
225 }
226
227 /// Returns the total number of starting state configurations.
228 pub(crate) fn len() -> usize {
229 6
230 }
231
232 /// Return this starting configuration as `u8` integer. It is guaranteed to
233 /// be less than `Start::len()`.
234 #[cfg_attr(feature = "perf-inline", inline(always))]
235 pub(crate) fn as_u8(&self) -> u8 {
236 // AFAIK, 'as' is the only way to zero-cost convert an int enum to an
237 // actual int.
238 *self as u8
239 }
240
241 /// Return this starting configuration as a `usize` integer. It is
242 /// guaranteed to be less than `Start::len()`.
243 #[cfg_attr(feature = "perf-inline", inline(always))]
244 pub(crate) fn as_usize(&self) -> usize {
245 usize::from(self.as_u8())
246 }
247 }
248
249 #[cfg(test)]
250 mod tests {
251 use super::*;
252
253 #[test]
254 fn start_fwd_done_range() {
255 let smap = StartByteMap::new(&LookMatcher::default());
256 assert_eq!(Start::Text, smap.fwd(&Input::new("").range(1..0)));
257 }
258
259 #[test]
260 fn start_rev_done_range() {
261 let smap = StartByteMap::new(&LookMatcher::default());
262 assert_eq!(Start::Text, smap.rev(&Input::new("").range(1..0)));
263 }
264
265 #[test]
266 fn start_fwd() {
267 let f = |haystack, start, end| {
268 let smap = StartByteMap::new(&LookMatcher::default());
269 let input = &Input::new(haystack).range(start..end);
270 smap.fwd(input)
271 };
272
273 assert_eq!(Start::Text, f("", 0, 0));
274 assert_eq!(Start::Text, f("abc", 0, 3));
275 assert_eq!(Start::Text, f("\nabc", 0, 3));
276
277 assert_eq!(Start::LineLF, f("\nabc", 1, 3));
278
279 assert_eq!(Start::LineCR, f("\rabc", 1, 3));
280
281 assert_eq!(Start::WordByte, f("abc", 1, 3));
282
283 assert_eq!(Start::NonWordByte, f(" abc", 1, 3));
284 }
285
286 #[test]
287 fn start_rev() {
288 let f = |haystack, start, end| {
289 let smap = StartByteMap::new(&LookMatcher::default());
290 let input = &Input::new(haystack).range(start..end);
291 smap.rev(input)
292 };
293
294 assert_eq!(Start::Text, f("", 0, 0));
295 assert_eq!(Start::Text, f("abc", 0, 3));
296 assert_eq!(Start::Text, f("abc\n", 0, 4));
297
298 assert_eq!(Start::LineLF, f("abc\nz", 0, 3));
299
300 assert_eq!(Start::LineCR, f("abc\rz", 0, 3));
301
302 assert_eq!(Start::WordByte, f("abc", 0, 2));
303
304 assert_eq!(Start::NonWordByte, f("abc ", 0, 3));
305 }
306 }