Repository navigation
Expand file tree
/
Copy pathmod.rs
More file actions
335 lines (308 loc) · 10.5 KB
/
Copy pathmod.rs
File metadata and controls
335 lines (308 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
use std::io::{stdout, Write};
use {
anyhow::Context,
lexopt::Parser,
regex_automata::{HalfMatch, Input, MatchError, PatternID},
};
use crate::{
args,
util::{self, Table},
};
mod dfa;
pub fn run(p: &mut Parser) -> anyhow::Result<()> {
const USAGE: &'static str = r#"\
Executes a search for "half" matches. That is, matches that only have the end
offset of a match (as well as the pattern that matched). This type of search
can be done by any regex engine, but for this command, we only expose regex
engines that can specifically do less work to report a half match.
For example, a DFA regex can report a half match by only searching with its
forward DFA. Indeed, if all we care about are half matches, we can avoid
compiling a reverse DFA entirely.
Also, since half matches cannot know the full bounds of a match, this only
prints the end offset of each match and not the matched contents. (Since the
start offset of each match is not known.)
USAGE:
regex-cli find half <engine>
ENGINES:
dense Search with the dense DFA regex engine.
hybrid Search with the lazy DFA regex engine.
meta Search with the meta regex engine.
regex Search with the top-level API regex engine.
sparse Search with the sparse DFA regex engine.
"#;
let cmd = args::next_as_command(USAGE, p)?;
match &*cmd {
"dense" => dfa::run_dense(p),
"hybrid" => dfa::run_hybrid(p),
"meta" => run_meta(p),
"regex" => run_regex(p),
"sparse" => dfa::run_sparse(p),
unk => anyhow::bail!("unrecognized command '{unk}'"),
}
}
fn run_regex(p: &mut lexopt::Parser) -> anyhow::Result<()> {
const USAGE: &'static str = "\
Executes a search for half matches using the top-level API regex engine.
USAGE:
regex-cli find half regex [-p <pattern> ...] <haystack-path>
regex-cli find half regex [-p <pattern> ...] -y <haystack>
TIP:
use -h for short docs and --help for long docs
OPTIONS:
%options%
";
let mut common = args::common::Config::default();
let mut patterns = args::patterns::Config::only_flags();
let mut haystack = args::haystack::Config::default();
let mut syntax = args::syntax::Config::default();
let mut api = args::api::Config::default();
let mut find = super::Config::default();
args::configure(
p,
USAGE,
&mut [
&mut common,
&mut patterns,
&mut haystack,
&mut syntax,
&mut api,
&mut find,
],
)?;
let pats = patterns.get(&syntax)?;
let syn = syntax.syntax()?;
let mut table = Table::empty();
let (re, time) = util::timeitr(|| api.from_patterns(&syn, &pats))?;
table.add("build regex time", time);
// The top-level API doesn't support regex-automata's more granular Input
// abstraction.
let input = args::input::Config::default();
let search = |input: &Input<'_>| {
Ok(re
.shortest_match_at(input.haystack(), input.start())
.map(|offset| HalfMatch::new(PatternID::ZERO, offset)))
};
if find.count {
run_counts(&mut table, &common, &find, &input, &haystack, 1, search)?;
} else {
run_search(&mut table, &common, &find, &input, &haystack, search)?;
}
Ok(())
}
fn run_meta(p: &mut lexopt::Parser) -> anyhow::Result<()> {
const USAGE: &'static str = "\
Executes a search for half matches using the meta regex engine.
USAGE:
regex-cli find half meta [-p <pattern> ...] <haystack-path>
regex-cli find half meta [-p <pattern> ...] -y <haystack>
TIP:
use -h for short docs and --help for long docs
OPTIONS:
%options%
";
let mut common = args::common::Config::default();
let mut input = args::input::Config::default();
let mut patterns = args::patterns::Config::only_flags();
let mut haystack = args::haystack::Config::default();
let mut syntax = args::syntax::Config::default();
let mut meta = args::meta::Config::default();
let mut find = super::Config::default();
args::configure(
p,
USAGE,
&mut [
&mut common,
&mut input,
&mut patterns,
&mut haystack,
&mut syntax,
&mut meta,
&mut find,
],
)?;
let pats = patterns.get(&syntax)?;
let mut table = Table::empty();
let re = if meta.build_from_patterns() {
let (re, time) = util::timeitr(|| meta.from_patterns(&syntax, &pats))?;
table.add("build meta time", time);
re
} else {
let (asts, time) = util::timeitr(|| syntax.asts(&pats))?;
table.add("parse time", time);
let (hirs, time) = util::timeitr(|| syntax.hirs(&pats, &asts))?;
table.add("translate time", time);
let (re, time) = util::timeitr(|| meta.from_hirs(&hirs))?;
table.add("build meta time", time);
re
};
let search = |input: &Input<'_>| Ok(re.search_half(input));
if find.count {
run_counts(
&mut table,
&common,
&find,
&input,
&haystack,
re.pattern_len(),
search,
)?;
} else {
run_search(&mut table, &common, &find, &input, &haystack, search)?;
}
Ok(())
}
/// A function that takes in a bunch of configuration, runs the given search
/// routine, and prints out a table of counts.
fn run_counts(
table: &mut Table,
common: &args::common::Config,
find: &super::Config,
input: &args::input::Config,
haystack: &args::haystack::Config,
pattern_len: usize,
mut search: impl FnMut(&Input<'_>) -> Result<Option<HalfMatch>, MatchError>,
) -> anyhow::Result<()> {
let mut out = stdout();
input.with(haystack, |input| {
let (counts, time) = util::timeitr(|| {
let mut counts = vec![0; pattern_len];
for _ in 0..find.repeat() {
let mut it =
regex_automata::util::iter::Searcher::new(input.clone());
while let Some(m) = it.try_advance_half(&mut search)? {
counts[m.pattern().as_usize()] += 1;
}
}
Ok::<_, anyhow::Error>(counts)
})?;
table.add("search time", time);
table.add("total matches", counts.iter().copied().sum::<u64>());
if common.table() {
table.print(&mut out)?;
}
if !common.quiet {
for (i, &count) in counts.iter().enumerate() {
let pid = PatternID::new(i).context("invalid pattern ID")?;
writeln!(out, "{}:{}", pid.as_usize(), count)?;
}
}
Ok(())
})
}
/// Like `run_counts`, but prints the actual matches instead.
fn run_search(
table: &mut Table,
common: &args::common::Config,
find: &super::Config,
input: &args::input::Config,
haystack: &args::haystack::Config,
mut search: impl FnMut(&Input<'_>) -> Result<Option<HalfMatch>, MatchError>,
) -> anyhow::Result<()> {
let mut out = stdout();
input.with(haystack, |input| {
let (matches, time) = util::timeitr(|| {
let mut matches = vec![];
for _ in 0..find.repeat() {
let mut it =
regex_automata::util::iter::Searcher::new(input.clone());
while let Some(m) = it.try_advance_half(&mut search)? {
matches.push(m);
}
}
Ok::<_, anyhow::Error>(matches)
})?;
table.add("search time", time);
table.add("total matches", matches.len());
if common.table() {
table.print(&mut out)?;
}
if !common.quiet {
for m in matches.iter() {
writeln!(out, "{}:{}", m.pattern().as_usize(), m.offset())?;
}
}
Ok(())
})
}
/// Like `run_counts`, but does an overlapping search.
fn run_counts_overlapping<S>(
table: &mut Table,
common: &args::common::Config,
find: &super::Config,
input: &args::input::Config,
haystack: &args::haystack::Config,
pattern_len: usize,
mut start_state: impl FnMut() -> S,
mut get_match: impl FnMut(&S) -> Option<HalfMatch>,
mut search: impl FnMut(&Input<'_>, &mut S) -> Result<(), MatchError>,
) -> anyhow::Result<()> {
let mut out = stdout();
input.with(haystack, |input| {
let (counts, time) = util::timeitr(|| {
let mut counts = vec![0; pattern_len];
for _ in 0..find.repeat() {
let mut state = start_state();
loop {
search(&input, &mut state)?;
match get_match(&state) {
None => break,
Some(hm) => counts[hm.pattern().as_usize()] += 1,
}
}
}
Ok::<_, anyhow::Error>(counts)
})?;
table.add("search time", time);
table.add("total matches", counts.iter().copied().sum::<u64>());
if common.table() {
table.print(&mut out)?;
}
if !common.quiet {
for (i, &count) in counts.iter().enumerate() {
let pid = PatternID::new(i).context("invalid pattern ID")?;
writeln!(out, "{}:{}", pid.as_usize(), count)?;
}
}
Ok(())
})
}
/// Like `run_search`, but does an overlapping search.
fn run_search_overlapping<S>(
table: &mut Table,
common: &args::common::Config,
find: &super::Config,
input: &args::input::Config,
haystack: &args::haystack::Config,
mut start_state: impl FnMut() -> S,
mut get_match: impl FnMut(&S) -> Option<HalfMatch>,
mut search: impl FnMut(&Input<'_>, &mut S) -> Result<(), MatchError>,
) -> anyhow::Result<()> {
let mut out = stdout();
input.with(haystack, |input| {
let (matches, time) = util::timeitr(|| {
let mut matches = vec![];
for _ in 0..find.repeat() {
let mut state = start_state();
loop {
search(&input, &mut state)?;
match get_match(&state) {
None => break,
Some(hm) => matches.push(hm),
}
}
}
Ok::<_, anyhow::Error>(matches)
})?;
table.add("search time", time);
table.add("total matches", matches.len());
if common.table() {
table.print(&mut out)?;
}
if !common.quiet {
for m in matches.iter() {
writeln!(out, "{}:{}", m.pattern().as_usize(), m.offset())?;
}
}
Ok(())
})
}