Debian Codegraph @

debian/rust-vendor/fancy-regex/examples/toy.rs

raw
1 // Copyright 2016 The Fancy Regex Authors.
2 //
3 // Permission is hereby granted, free of charge, to any person obtaining a copy
4 // of this software and associated documentation files (the "Software"), to deal
5 // in the Software without restriction, including without limitation the rights
6 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 // copies of the Software, and to permit persons to whom the Software is
8 // furnished to do so, subject to the following conditions:
9 //
10 // The above copyright notice and this permission notice shall be included in
11 // all copies or substantial portions of the Software.
12 //
13 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19 // THE SOFTWARE.
20
21 //! A simple test app for exercising and debugging the regex engine.
22
23 use fancy_regex::internal::{
24 analyze, can_compile_as_anchored, compile, optimize, run_trace, AnalyzeContext, CompileOptions,
25 Insn, Prog,
26 };
27 use fancy_regex::*;
28 use std::env;
29 use std::fmt::{Display, Formatter, Result};
30 use std::io;
31 use std::io::Write;
32 use std::str::FromStr;
33
34 fn main() {
35 let mut args = env::args().skip(1);
36 if let Some(cmd) = args.next() {
37 if cmd == "parse" {
38 let re = args.next().expect("expected regexp argument");
39 let e = Expr::parse_tree(&re);
40 println!("{:#?}", e);
41 } else if cmd == "optimize" {
42 let re = args.next().expect("expected regexp argument");
43 let mut e = Expr::parse_tree(&re).expect("expected regexp to be parsed successfully");
44 let explicit_capture_group0 = optimize(&mut e);
45 println!("explicit capture group 0: {:?}", explicit_capture_group0);
46 println!("{:#?}", e);
47 } else if cmd == "analyze" {
48 let re = args.next().expect("expected regexp argument");
49 let stdout = io::stdout();
50 let mut handle = stdout.lock();
51 write!(&mut handle, "{}", AnalyzeFormatterWrapper { regex: &re })
52 .expect("error analyzing regexp");
53 } else if cmd == "compile" {
54 let re = args.next().expect("expected regexp argument");
55 let stdout = io::stdout();
56 let mut handle = stdout.lock();
57 write!(&mut handle, "{}", CompileFormatterWrapper { regex: &re })
58 .expect("error compiling regexp");
59 } else if cmd == "run" {
60 let re = args.next().expect("expected regexp argument");
61 let r = Regex::new(&re).unwrap();
62 let text = args.next().expect("expected text argument");
63 let mut pos = 0;
64 if let Some(pos_str) = args.next() {
65 pos = usize::from_str(&pos_str).unwrap();
66 }
67 if let Some(caps) = r.captures_from_pos(&text, pos).unwrap() {
68 print!("captures:");
69 for i in 0..caps.len() {
70 print!(" {}:", i);
71 if let Some(m) = caps.get(i) {
72 print!("[{}..{}] \"{}\"", m.start(), m.end(), m.as_str());
73 } else {
74 print!("_");
75 }
76 }
77 println!("");
78 for cap in caps.iter() {
79 println!("iterate {:?}", cap);
80 }
81 } else {
82 println!("no match");
83 }
84 } else if cmd == "trace" {
85 let re = args.next().expect("expected regexp argument");
86 let prog = prog(&re);
87 let text = args.next().expect("expected text argument");
88 run_trace(&prog, &text, 0).unwrap();
89 } else if cmd == "trace-inner" {
90 let re = args.next().expect("expected regexp argument");
91 let tree = Expr::parse_tree(&re).unwrap();
92 let text = args.next().expect("expected text argument");
93 let a = analyze(&tree, AnalyzeContext::default()).unwrap();
94 let p = compile(
95 &a,
96 CompileOptions {
97 anchored: true,
98 contains_subroutines: tree.contains_subroutines,
99 ..CompileOptions::default()
100 },
101 )
102 .unwrap();
103 run_trace(&p, &text, 0).unwrap();
104 } else if cmd == "graph" {
105 let re = args.next().expect("expected regexp argument");
106 graph(&re, &mut io::stdout()).expect("error making graph");
107 } else {
108 println!("commands: parse|analyze|compile|graph <expr>, run|trace|trace-inner <expr> <input>");
109 }
110 }
111 }
112
113 fn graph(re: &str, writer: &mut dyn std::io::Write) -> std::io::Result<()> {
114 let prog = prog(re);
115 write!(writer, "digraph G {{\n")?;
116 for (i, insn) in prog.body.iter().enumerate() {
117 let label = format!("{:?}", insn)
118 .replace(r#"\"#, r#"\\"#)
119 .replace(r#"""#, r#"\""#);
120 write!(writer, r#"{:3} [label="{}: {}"];{}"#, i, i, label, "\n")?;
121 match *insn {
122 Insn::Split(a, b) | Insn::SplitUnanchored(a, b) => {
123 write!(writer, "{:3} -> {};\n", i, a)?;
124 write!(writer, "{:3} -> {};\n", i, b)?;
125 }
126 Insn::Jmp(target) => {
127 write!(writer, "{:3} -> {};\n", i, target)?;
128 }
129 Insn::End => {}
130 _ => {
131 write!(writer, "{:3} -> {};\n", i, i + 1)?;
132 }
133 }
134 }
135 write!(writer, "}}\n")?;
136 Ok(())
137 }
138
139 fn show_analysis(re: &str, writer: &mut Formatter<'_>) -> Result {
140 let mut tree = Expr::parse_tree(&re).unwrap();
141 let requires_capture_group_fixup = optimize(&mut tree);
142 let a = analyze(
143 &tree,
144 AnalyzeContext {
145 explicit_capture_group_0: requires_capture_group_fixup,
146 ..Default::default()
147 },
148 );
149 writeln!(writer, "{:#?}", a)
150 }
151
152 fn show_compiled_program(re: &str, writer: &mut Formatter<'_>) -> Result {
153 let r = Regex::new(re).unwrap();
154 r.debug_print(writer)
155 }
156
157 fn prog(re: &str) -> Prog {
158 // one thing to note here is that we want the prog, but in lib.rs,
159 // constructing a regex might not produce a prog - it may be wrapped Regex instead,
160 // which means that "toy" behaves differently to tests etc.
161 let mut tree = Expr::parse_tree(re).expect("Expected parsing regex to work");
162 let requires_capture_group_fixup = optimize(&mut tree);
163 let result = analyze(
164 &tree,
165 AnalyzeContext {
166 explicit_capture_group_0: requires_capture_group_fixup,
167 ..Default::default()
168 },
169 )
170 .expect("Expected analyze to succeed");
171 compile(
172 &result,
173 CompileOptions {
174 anchored: can_compile_as_anchored(&tree.expr),
175 contains_subroutines: tree.contains_subroutines,
176 ..CompileOptions::default()
177 },
178 )
179 .expect("Expected compile to succeed")
180 }
181
182 struct AnalyzeFormatterWrapper<'a> {
183 regex: &'a str,
184 }
185
186 impl<'a> Display for AnalyzeFormatterWrapper<'a> {
187 fn fmt(&self, f: &mut Formatter) -> Result {
188 show_analysis(self.regex, f)
189 }
190 }
191
192 struct CompileFormatterWrapper<'a> {
193 regex: &'a str,
194 }
195
196 impl<'a> Display for CompileFormatterWrapper<'a> {
197 fn fmt(&self, f: &mut Formatter) -> Result {
198 show_compiled_program(self.regex, f)
199 }
200 }
201
202 #[cfg(test)]
203 mod tests {
204 use crate::RegexBuilder;
205 use crate::Write;
206
207 #[test]
208 fn test_simple_graph() {
209 assert_graph(
210 "^a+bc?",
211 "\
212 digraph G {
213 0 [label=\"0: Save(0)\"];
214 0 -> 1;
215 1 [label=\"1: Delegate(Delegate { pattern: \\\"^a+bc?\\\", capture_groups: None })\"];
216 1 -> 2;
217 2 [label=\"2: Save(1)\"];
218 2 -> 3;
219 3 [label=\"3: End\"];
220 }
221 ",
222 );
223 }
224
225 #[test]
226 fn test_backref_graph() {
227 assert_graph(
228 r"a+(?<b>b*)(?=c)\k<b>",
229 "\
230 digraph G {
231 0 [label=\"0: SplitUnanchored(3, 1)\"];
232 0 -> 3;
233 0 -> 1;
234 1 [label=\"1: Any\"];
235 1 -> 2;
236 2 [label=\"2: Jmp(0)\"];
237 2 -> 0;
238 3 [label=\"3: Save(0)\"];
239 3 -> 4;
240 4 [label=\"4: Lit(\\\"a\\\")\"];
241 4 -> 5;
242 5 [label=\"5: Split(4, 6)\"];
243 5 -> 4;
244 5 -> 6;
245 6 [label=\"6: SaveCaptureGroupStart(1)\"];
246 6 -> 7;
247 7 [label=\"7: Split(8, 10)\"];
248 7 -> 8;
249 7 -> 10;
250 8 [label=\"8: Lit(\\\"b\\\")\"];
251 8 -> 9;
252 9 [label=\"9: Jmp(7)\"];
253 9 -> 7;
254 10 [label=\"10: Save(3)\"];
255 10 -> 11;
256 11 [label=\"11: Save(4)\"];
257 11 -> 12;
258 12 [label=\"12: Lit(\\\"c\\\")\"];
259 12 -> 13;
260 13 [label=\"13: Restore(4)\"];
261 13 -> 14;
262 14 [label=\"14: Backref { slot: 2, casei: false, unicode: true }\"];
263 14 -> 15;
264 15 [label=\"15: Save(1)\"];
265 15 -> 16;
266 16 [label=\"16: End\"];
267 }
268 ",
269 );
270 }
271
272 #[test]
273 fn test_meta_char_class_graph() {
274 assert_graph(
275 r"(?i)hello(?<!\w)",
276 "\
277 digraph G {
278 0 [label=\"0: SplitUnanchored(3, 1)\"];
279 0 -> 3;
280 0 -> 1;
281 1 [label=\"1: Any\"];
282 1 -> 2;
283 2 [label=\"2: Jmp(0)\"];
284 2 -> 0;
285 3 [label=\"3: Save(0)\"];
286 3 -> 4;
287 4 [label=\"4: LitCasei(CaseiLiteral { chars: [[('H', 'H'), ('h', 'h')], [('E', 'E'), ('e', 'e')], [('L', 'L'), ('l', 'l')], [('L', 'L'), ('l', 'l')], [('O', 'O'), ('o', 'o')]] })\"];
288 4 -> 5;
289 5 [label=\"5: Split(6, 9)\"];
290 5 -> 6;
291 5 -> 9;
292 6 [label=\"6: GoBack(1)\"];
293 6 -> 7;
294 7 [label=\"7: CharClass(Codepoint \\\\w)\"];
295 7 -> 8;
296 8 [label=\"8: FailNegativeLookAround\"];
297 8 -> 9;
298 9 [label=\"9: Save(1)\"];
299 9 -> 10;
300 10 [label=\"10: End\"];
301 }
302 ",
303 );
304 }
305
306 #[test]
307 fn test_simple_analysis() {
308 assert_analysis_succeeds("a+bc?");
309 }
310
311 #[test]
312 fn test_backref_analysis() {
313 assert_analysis_succeeds("a+(?<b>b*)(?=c)\\k<b>");
314 }
315
316 #[test]
317 fn test_compilation_fancy_debug_output() {
318 // With seek enabled (default): the SplitUnanchored preamble is replaced by a Seek
319 // instruction that pre-filters positions before running the full VM.
320 let expected_with_seek = " ".to_owned()
321 + "\
322 0: Seek(Seek { pattern: \"a+b*b*\" })
323 1: Save(0)
324 2: Lit(\"a\")
325 3: Split(2, 4)
326 4: SaveCaptureGroupStart(1)
327 5: Split(6, 8)
328 6: Lit(\"b\")
329 7: Jmp(5)
330 8: Save(3)
331 9: Save(4)
332 10: Lit(\"c\")
333 11: Restore(4)
334 12: Backref { slot: 2, casei: false, unicode: true }
335 13: Save(1)
336 14: End
337 ";
338
339 assert_compiled_prog_with_seek("a+(?<b>b*)(?=c)\\k<b>", &expected_with_seek);
340
341 // With seek disabled: the classic SplitUnanchored preamble is used.
342 let expected_no_seek = " ".to_owned()
343 + "\
344 0: SplitUnanchored(3, 1)
345 1: Any
346 2: Jmp(0)
347 3: Save(0)
348 4: Lit(\"a\")
349 5: Split(4, 6)
350 6: SaveCaptureGroupStart(1)
351 7: Split(8, 10)
352 8: Lit(\"b\")
353 9: Jmp(7)
354 10: Save(3)
355 11: Save(4)
356 12: Lit(\"c\")
357 13: Restore(4)
358 14: Backref { slot: 2, casei: false, unicode: true }
359 15: Save(1)
360 16: End
361 ";
362
363 assert_compiled_prog_no_seek("a+(?<b>b*)(?=c)\\k<b>", &expected_no_seek);
364 }
365
366 #[test]
367 #[cfg(feature = "variable-lookbehinds")]
368 fn test_compilation_variable_lookbehind_debug_output() {
369 // With seek enabled (default): the SplitUnanchored preamble is replaced by a Seek
370 // instruction that pre-filters positions before running the full VM.
371 let expected_with_seek = " ".to_owned()
372 + "\
373 0: Seek(Seek { pattern: \"x\" })
374 1: Save(0)
375 2: Save(2)
376 3: BackwardsDelegate(ReverseBackwardsDelegate { pattern: \"ab+\", capture_groups: None })
377 4: Restore(2)
378 5: Lit(\"x\")
379 6: Save(1)
380 7: End
381 ";
382
383 assert_compiled_prog_with_seek("(?<=ab+)x", &expected_with_seek);
384
385 // With seek disabled: the classic SplitUnanchored preamble is used.
386 let expected_no_seek = " ".to_owned()
387 + "\
388 0: SplitUnanchored(3, 1)
389 1: Any
390 2: Jmp(0)
391 3: Save(0)
392 4: Save(2)
393 5: BackwardsDelegate(ReverseBackwardsDelegate { pattern: \"ab+\", capture_groups: None })
394 6: Restore(2)
395 7: Lit(\"x\")
396 8: Save(1)
397 9: End
398 ";
399
400 assert_compiled_prog_no_seek("(?<=ab+)x", &expected_no_seek);
401 }
402
403 #[test]
404 fn test_compilation_wrapped_debug_output() {
405 let expected = "wrapped Regex \"a+bc?\", explicit_capture_group_0: false";
406
407 assert_compiled_prog_with_seek("a+bc?", &expected);
408 }
409
410 #[test]
411 fn test_compilation_wrapped_debug_output_explict_capture_group_zero() {
412 let expected = "wrapped Regex \"(a+b)c\", explicit_capture_group_0: true";
413
414 assert_compiled_prog_no_seek("a+b(?=c)", &expected);
415 }
416
417 #[test]
418 fn test_compilation_wrapped_debug_output_explict_capture_group_zero_with_non_capture_group() {
419 let expected = "wrapped Regex \"(a+b)(?:c|d)\", explicit_capture_group_0: true";
420
421 assert_compiled_prog_no_seek("a+b(?=c|d)", &expected);
422 }
423
424 fn assert_graph(re: &str, expected: &str) {
425 use crate::graph;
426 let mut buf = Vec::new();
427 graph(&re, &mut buf).expect("error compiling regexp and building graph");
428 let output = String::from_utf8(buf).expect("string not utf8");
429 assert_eq!(&output, &expected);
430 }
431
432 fn assert_compiled_prog_with_seek(re: &str, expected: &str) {
433 use std::fmt::{Display, Formatter};
434 struct DebugPrintWrapper<'a>(&'a fancy_regex::Regex);
435 impl<'a> Display for DebugPrintWrapper<'a> {
436 fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
437 self.0.debug_print(f)
438 }
439 }
440 let r = RegexBuilder::new(re)
441 .seek(true)
442 .build()
443 .expect("error compiling regexp");
444 let output = format!("{}", DebugPrintWrapper(&r));
445 assert_eq!(&output, &expected);
446 }
447
448 fn assert_compiled_prog_no_seek(re: &str, expected: &str) {
449 use std::fmt::{Display, Formatter};
450 struct DebugPrintWrapper<'a>(&'a fancy_regex::Regex);
451 impl<'a> Display for DebugPrintWrapper<'a> {
452 fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
453 self.0.debug_print(f)
454 }
455 }
456 let r = RegexBuilder::new(re)
457 .seek(false)
458 .build()
459 .expect("error compiling regexp");
460 let output = format!("{}", DebugPrintWrapper(&r));
461 assert_eq!(&output, &expected);
462 }
463
464 fn assert_analysis_succeeds(re: &str) {
465 use crate::AnalyzeFormatterWrapper;
466 let mut buf = Vec::new();
467 write!(&mut buf, "{}", AnalyzeFormatterWrapper { regex: &re })
468 .expect("error analyzing regexp");
469 let output = String::from_utf8(buf).expect("string not utf8");
470 println!("{}", output);
471 assert!(&output.starts_with("Ok(\n Info {"));
472 }
473 }