Debian Codegraph @

third_party/rust/regex-syntax/src/hir/print.rs

raw
1 /*!
2 This module provides a regular expression printer for `Hir`.
3 */
4
5 use core::fmt;
6
7 use crate::{
8 hir::{
9 self,
10 visitor::{self, Visitor},
11 Hir, HirKind,
12 },
13 is_meta_character,
14 };
15
16 /// A builder for constructing a printer.
17 ///
18 /// Note that since a printer doesn't have any configuration knobs, this type
19 /// remains unexported.
20 #[derive(Clone, Debug)]
21 struct PrinterBuilder {
22 _priv: (),
23 }
24
25 impl Default for PrinterBuilder {
26 fn default() -> PrinterBuilder {
27 PrinterBuilder::new()
28 }
29 }
30
31 impl PrinterBuilder {
32 fn new() -> PrinterBuilder {
33 PrinterBuilder { _priv: () }
34 }
35
36 fn build(&self) -> Printer {
37 Printer { _priv: () }
38 }
39 }
40
41 /// A printer for a regular expression's high-level intermediate
42 /// representation.
43 ///
44 /// A printer converts a high-level intermediate representation (HIR) to a
45 /// regular expression pattern string. This particular printer uses constant
46 /// stack space and heap space proportional to the size of the HIR.
47 ///
48 /// Since this printer is only using the HIR, the pattern it prints will likely
49 /// not resemble the original pattern at all. For example, a pattern like
50 /// `\pL` will have its entire class written out.
51 ///
52 /// The purpose of this printer is to provide a means to mutate an HIR and then
53 /// build a regular expression from the result of that mutation. (A regex
54 /// library could provide a constructor from this HIR explicitly, but that
55 /// creates an unnecessary public coupling between the regex library and this
56 /// specific HIR representation.)
57 #[derive(Debug)]
58 pub struct Printer {
59 _priv: (),
60 }
61
62 impl Printer {
63 /// Create a new printer.
64 pub fn new() -> Printer {
65 PrinterBuilder::new().build()
66 }
67
68 /// Print the given `Ast` to the given writer. The writer must implement
69 /// `fmt::Write`. Typical implementations of `fmt::Write` that can be used
70 /// here are a `fmt::Formatter` (which is available in `fmt::Display`
71 /// implementations) or a `&mut String`.
72 pub fn print<W: fmt::Write>(&mut self, hir: &Hir, wtr: W) -> fmt::Result {
73 visitor::visit(hir, Writer { wtr })
74 }
75 }
76
77 #[derive(Debug)]
78 struct Writer<W> {
79 wtr: W,
80 }
81
82 impl<W: fmt::Write> Visitor for Writer<W> {
83 type Output = ();
84 type Err = fmt::Error;
85
86 fn finish(self) -> fmt::Result {
87 Ok(())
88 }
89
90 fn visit_pre(&mut self, hir: &Hir) -> fmt::Result {
91 match *hir.kind() {
92 HirKind::Empty => {
93 // Technically an empty sub-expression could be "printed" by
94 // just ignoring it, but in practice, you could have a
95 // repetition operator attached to an empty expression, and you
96 // really need something in the concrete syntax to make that
97 // work as you'd expect.
98 self.wtr.write_str(r"(?:)")?;
99 }
100 // Repetition operators are strictly suffix oriented.
101 HirKind::Repetition(_) => {}
102 HirKind::Literal(hir::Literal(ref bytes)) => {
103 // See the comment on the 'Concat' and 'Alternation' case below
104 // for why we put parens here. Literals are, conceptually,
105 // a special case of concatenation where each element is a
106 // character. The HIR flattens this into a Box<[u8]>, but we
107 // still need to treat it like a concatenation for correct
108 // printing. As a special case, we don't write parens if there
109 // is only one character. One character means there is no
110 // concat so we don't need parens. Adding parens would still be
111 // correct, but we drop them here because it tends to create
112 // rather noisy regexes even in simple cases.
113 let result = core::str::from_utf8(bytes);
114 let len = result.map_or(bytes.len(), |s| s.chars().count());
115 if len > 1 {
116 self.wtr.write_str(r"(?:")?;
117 }
118 match result {
119 Ok(string) => {
120 for c in string.chars() {
121 self.write_literal_char(c)?;
122 }
123 }
124 Err(_) => {
125 for &b in bytes.iter() {
126 self.write_literal_byte(b)?;
127 }
128 }
129 }
130 if len > 1 {
131 self.wtr.write_str(r")")?;
132 }
133 }
134 HirKind::Class(hir::Class::Unicode(ref cls)) => {
135 if cls.ranges().is_empty() {
136 return self.wtr.write_str("[a&&b]");
137 }
138 self.wtr.write_str("[")?;
139 for range in cls.iter() {
140 if range.start() == range.end() {
141 self.write_literal_char(range.start())?;
142 } else if u32::from(range.start()) + 1
143 == u32::from(range.end())
144 {
145 self.write_literal_char(range.start())?;
146 self.write_literal_char(range.end())?;
147 } else {
148 self.write_literal_char(range.start())?;
149 self.wtr.write_str("-")?;
150 self.write_literal_char(range.end())?;
151 }
152 }
153 self.wtr.write_str("]")?;
154 }
155 HirKind::Class(hir::Class::Bytes(ref cls)) => {
156 if cls.ranges().is_empty() {
157 return self.wtr.write_str("[a&&b]");
158 }
159 self.wtr.write_str("(?-u:[")?;
160 for range in cls.iter() {
161 if range.start() == range.end() {
162 self.write_literal_class_byte(range.start())?;
163 } else if range.start() + 1 == range.end() {
164 self.write_literal_class_byte(range.start())?;
165 self.write_literal_class_byte(range.end())?;
166 } else {
167 self.write_literal_class_byte(range.start())?;
168 self.wtr.write_str("-")?;
169 self.write_literal_class_byte(range.end())?;
170 }
171 }
172 self.wtr.write_str("])")?;
173 }
174 HirKind::Look(ref look) => match *look {
175 hir::Look::Start => {
176 self.wtr.write_str(r"\A")?;
177 }
178 hir::Look::End => {
179 self.wtr.write_str(r"\z")?;
180 }
181 hir::Look::StartLF => {
182 self.wtr.write_str("(?m:^)")?;
183 }
184 hir::Look::EndLF => {
185 self.wtr.write_str("(?m:$)")?;
186 }
187 hir::Look::StartCRLF => {
188 self.wtr.write_str("(?mR:^)")?;
189 }
190 hir::Look::EndCRLF => {
191 self.wtr.write_str("(?mR:$)")?;
192 }
193 hir::Look::WordAscii => {
194 self.wtr.write_str(r"(?-u:\b)")?;
195 }
196 hir::Look::WordAsciiNegate => {
197 self.wtr.write_str(r"(?-u:\B)")?;
198 }
199 hir::Look::WordUnicode => {
200 self.wtr.write_str(r"\b")?;
201 }
202 hir::Look::WordUnicodeNegate => {
203 self.wtr.write_str(r"\B")?;
204 }
205 },
206 HirKind::Capture(hir::Capture { ref name, .. }) => {
207 self.wtr.write_str("(")?;
208 if let Some(ref name) = *name {
209 write!(self.wtr, "?P<{}>", name)?;
210 }
211 }
212 // Why do this? Wrapping concats and alts in non-capturing groups
213 // is not *always* necessary, but is sometimes necessary. For
214 // example, 'concat(a, alt(b, c))' should be written as 'a(?:b|c)'
215 // and not 'ab|c'. The former is clearly the intended meaning, but
216 // the latter is actually 'alt(concat(a, b), c)'.
217 //
218 // It would be possible to only group these things in cases where
219 // it's strictly necessary, but it requires knowing the parent
220 // expression. And since this technique is simpler and always
221 // correct, we take this route. More to the point, it is a non-goal
222 // of an HIR printer to show a nice easy-to-read regex. Indeed,
223 // its construction forbids it from doing so. Therefore, inserting
224 // extra groups where they aren't necessary is perfectly okay.
225 HirKind::Concat(_) | HirKind::Alternation(_) => {
226 self.wtr.write_str(r"(?:")?;
227 }
228 }
229 Ok(())
230 }
231
232 fn visit_post(&mut self, hir: &Hir) -> fmt::Result {
233 match *hir.kind() {
234 // Handled during visit_pre
235 HirKind::Empty
236 | HirKind::Literal(_)
237 | HirKind::Class(_)
238 | HirKind::Look(_) => {}
239 HirKind::Repetition(ref x) => {
240 match (x.min, x.max) {
241 (0, Some(1)) => {
242 self.wtr.write_str("?")?;
243 }
244 (0, None) => {
245 self.wtr.write_str("*")?;
246 }
247 (1, None) => {
248 self.wtr.write_str("+")?;
249 }
250 (1, Some(1)) => {
251 // 'a{1}' and 'a{1}?' are exactly equivalent to 'a'.
252 return Ok(());
253 }
254 (m, None) => {
255 write!(self.wtr, "{{{},}}", m)?;
256 }
257 (m, Some(n)) if m == n => {
258 write!(self.wtr, "{{{}}}", m)?;
259 // a{m} and a{m}? are always exactly equivalent.
260 return Ok(());
261 }
262 (m, Some(n)) => {
263 write!(self.wtr, "{{{},{}}}", m, n)?;
264 }
265 }
266 if !x.greedy {
267 self.wtr.write_str("?")?;
268 }
269 }
270 HirKind::Capture(_)
271 | HirKind::Concat(_)
272 | HirKind::Alternation(_) => {
273 self.wtr.write_str(r")")?;
274 }
275 }
276 Ok(())
277 }
278
279 fn visit_alternation_in(&mut self) -> fmt::Result {
280 self.wtr.write_str("|")
281 }
282 }
283
284 impl<W: fmt::Write> Writer<W> {
285 fn write_literal_char(&mut self, c: char) -> fmt::Result {
286 if is_meta_character(c) {
287 self.wtr.write_str("\\")?;
288 }
289 self.wtr.write_char(c)
290 }
291
292 fn write_literal_byte(&mut self, b: u8) -> fmt::Result {
293 if b <= 0x7F && !b.is_ascii_control() && !b.is_ascii_whitespace() {
294 self.write_literal_char(char::try_from(b).unwrap())
295 } else {
296 write!(self.wtr, "(?-u:\\x{:02X})", b)
297 }
298 }
299
300 fn write_literal_class_byte(&mut self, b: u8) -> fmt::Result {
301 if b <= 0x7F && !b.is_ascii_control() && !b.is_ascii_whitespace() {
302 self.write_literal_char(char::try_from(b).unwrap())
303 } else {
304 write!(self.wtr, "\\x{:02X}", b)
305 }
306 }
307 }
308
309 #[cfg(test)]
310 mod tests {
311 use alloc::{
312 boxed::Box,
313 string::{String, ToString},
314 };
315
316 use crate::ParserBuilder;
317
318 use super::*;
319
320 fn roundtrip(given: &str, expected: &str) {
321 roundtrip_with(|b| b, given, expected);
322 }
323
324 fn roundtrip_bytes(given: &str, expected: &str) {
325 roundtrip_with(|b| b.utf8(false), given, expected);
326 }
327
328 fn roundtrip_with<F>(mut f: F, given: &str, expected: &str)
329 where
330 F: FnMut(&mut ParserBuilder) -> &mut ParserBuilder,
331 {
332 let mut builder = ParserBuilder::new();
333 f(&mut builder);
334 let hir = builder.build().parse(given).unwrap();
335
336 let mut printer = Printer::new();
337 let mut dst = String::new();
338 printer.print(&hir, &mut dst).unwrap();
339
340 // Check that the result is actually valid.
341 builder.build().parse(&dst).unwrap();
342
343 assert_eq!(expected, dst);
344 }
345
346 #[test]
347 fn print_literal() {
348 roundtrip("a", "a");
349 roundtrip(r"\xff", "\u{FF}");
350 roundtrip_bytes(r"\xff", "\u{FF}");
351 roundtrip_bytes(r"(?-u)\xff", r"(?-u:\xFF)");
352 roundtrip("☃", "☃");
353 }
354
355 #[test]
356 fn print_class() {
357 roundtrip(r"[a]", r"a");
358 roundtrip(r"[ab]", r"[ab]");
359 roundtrip(r"[a-z]", r"[a-z]");
360 roundtrip(r"[a-z--b-c--x-y]", r"[ad-wz]");
361 roundtrip(r"[^\x01-\u{10FFFF}]", "\u{0}");
362 roundtrip(r"[-]", r"\-");
363 roundtrip(r"[☃-⛄]", r"[☃-⛄]");
364
365 roundtrip(r"(?-u)[a]", r"a");
366 roundtrip(r"(?-u)[ab]", r"(?-u:[ab])");
367 roundtrip(r"(?-u)[a-z]", r"(?-u:[a-z])");
368 roundtrip_bytes(r"(?-u)[a-\xFF]", r"(?-u:[a-\xFF])");
369
370 // The following test that the printer escapes meta characters
371 // in character classes.
372 roundtrip(r"[\[]", r"\[");
373 roundtrip(r"[Z-_]", r"[Z-_]");
374 roundtrip(r"[Z-_--Z]", r"[\[-_]");
375
376 // The following test that the printer escapes meta characters
377 // in byte oriented character classes.
378 roundtrip_bytes(r"(?-u)[\[]", r"\[");
379 roundtrip_bytes(r"(?-u)[Z-_]", r"(?-u:[Z-_])");
380 roundtrip_bytes(r"(?-u)[Z-_--Z]", r"(?-u:[\[-_])");
381
382 // This tests that an empty character class is correctly roundtripped.
383 #[cfg(feature = "unicode-gencat")]
384 roundtrip(r"\P{any}", r"[a&&b]");
385 roundtrip_bytes(r"(?-u)[^\x00-\xFF]", r"[a&&b]");
386 }
387
388 #[test]
389 fn print_anchor() {
390 roundtrip(r"^", r"\A");
391 roundtrip(r"$", r"\z");
392 roundtrip(r"(?m)^", r"(?m:^)");
393 roundtrip(r"(?m)$", r"(?m:$)");
394 }
395
396 #[test]
397 fn print_word_boundary() {
398 roundtrip(r"\b", r"\b");
399 roundtrip(r"\B", r"\B");
400 roundtrip(r"(?-u)\b", r"(?-u:\b)");
401 roundtrip_bytes(r"(?-u)\B", r"(?-u:\B)");
402 }
403
404 #[test]
405 fn print_repetition() {
406 roundtrip("a?", "a?");
407 roundtrip("a??", "a??");
408 roundtrip("(?U)a?", "a??");
409
410 roundtrip("a*", "a*");
411 roundtrip("a*?", "a*?");
412 roundtrip("(?U)a*", "a*?");
413
414 roundtrip("a+", "a+");
415 roundtrip("a+?", "a+?");
416 roundtrip("(?U)a+", "a+?");
417
418 roundtrip("a{1}", "a");
419 roundtrip("a{2}", "a{2}");
420 roundtrip("a{1,}", "a+");
421 roundtrip("a{1,5}", "a{1,5}");
422 roundtrip("a{1}?", "a");
423 roundtrip("a{2}?", "a{2}");
424 roundtrip("a{1,}?", "a+?");
425 roundtrip("a{1,5}?", "a{1,5}?");
426 roundtrip("(?U)a{1}", "a");
427 roundtrip("(?U)a{2}", "a{2}");
428 roundtrip("(?U)a{1,}", "a+?");
429 roundtrip("(?U)a{1,5}", "a{1,5}?");
430
431 // Test that various zero-length repetitions always translate to an
432 // empty regex. This is more a property of HIR's smart constructors
433 // than the printer though.
434 roundtrip("a{0}", "(?:)");
435 roundtrip("(?:ab){0}", "(?:)");
436 #[cfg(feature = "unicode-gencat")]
437 {
438 roundtrip(r"\p{any}{0}", "(?:)");
439 roundtrip(r"\P{any}{0}", "(?:)");
440 }
441 }
442
443 #[test]
444 fn print_group() {
445 roundtrip("()", "((?:))");
446 roundtrip("(?P<foo>)", "(?P<foo>(?:))");
447 roundtrip("(?:)", "(?:)");
448
449 roundtrip("(a)", "(a)");
450 roundtrip("(?P<foo>a)", "(?P<foo>a)");
451 roundtrip("(?:a)", "a");
452
453 roundtrip("((((a))))", "((((a))))");
454 }
455
456 #[test]
457 fn print_alternation() {
458 roundtrip("|", "(?:(?:)|(?:))");
459 roundtrip("||", "(?:(?:)|(?:)|(?:))");
460
461 roundtrip("a|b", "[ab]");
462 roundtrip("ab|cd", "(?:(?:ab)|(?:cd))");
463 roundtrip("a|b|c", "[a-c]");
464 roundtrip("ab|cd|ef", "(?:(?:ab)|(?:cd)|(?:ef))");
465 roundtrip("foo|bar|quux", "(?:(?:foo)|(?:bar)|(?:quux))");
466 }
467
468 // This is a regression test that stresses a peculiarity of how the HIR
469 // is both constructed and printed. Namely, it is legal for a repetition
470 // to directly contain a concatenation. This particular construct isn't
471 // really possible to build from the concrete syntax directly, since you'd
472 // be forced to put the concatenation into (at least) a non-capturing
473 // group. Concurrently, the printer doesn't consider this case and just
474 // kind of naively prints the child expression and tacks on the repetition
475 // operator.
476 //
477 // As a result, if you attached '+' to a 'concat(a, b)', the printer gives
478 // you 'ab+', but clearly it really should be '(?:ab)+'.
479 //
480 // This bug isn't easy to surface because most ways of building an HIR
481 // come directly from the concrete syntax, and as mentioned above, it just
482 // isn't possible to build this kind of HIR from the concrete syntax.
483 // Nevertheless, this is definitely a bug.
484 //
485 // See: https://github.com/rust-lang/regex/issues/731
486 #[test]
487 fn regression_repetition_concat() {
488 let expr = Hir::concat(alloc::vec![
489 Hir::literal("x".as_bytes()),
490 Hir::repetition(hir::Repetition {
491 min: 1,
492 max: None,
493 greedy: true,
494 sub: Box::new(Hir::literal("ab".as_bytes())),
495 }),
496 Hir::literal("y".as_bytes()),
497 ]);
498 assert_eq!(r"(?:x(?:ab)+y)", expr.to_string());
499
500 let expr = Hir::concat(alloc::vec![
501 Hir::look(hir::Look::Start),
502 Hir::repetition(hir::Repetition {
503 min: 1,
504 max: None,
505 greedy: true,
506 sub: Box::new(Hir::concat(alloc::vec![
507 Hir::look(hir::Look::Start),
508 Hir::look(hir::Look::End),
509 ])),
510 }),
511 Hir::look(hir::Look::End),
512 ]);
513 assert_eq!(r"(?:\A\A\z\z)", expr.to_string());
514 }
515
516 // Just like regression_repetition_concat, but with the repetition using
517 // an alternation as a child expression instead.
518 //
519 // See: https://github.com/rust-lang/regex/issues/731
520 #[test]
521 fn regression_repetition_alternation() {
522 let expr = Hir::concat(alloc::vec![
523 Hir::literal("ab".as_bytes()),
524 Hir::repetition(hir::Repetition {
525 min: 1,
526 max: None,
527 greedy: true,
528 sub: Box::new(Hir::alternation(alloc::vec![
529 Hir::literal("cd".as_bytes()),
530 Hir::literal("ef".as_bytes()),
531 ])),
532 }),
533 Hir::literal("gh".as_bytes()),
534 ]);
535 assert_eq!(r"(?:(?:ab)(?:(?:cd)|(?:ef))+(?:gh))", expr.to_string());
536
537 let expr = Hir::concat(alloc::vec![
538 Hir::look(hir::Look::Start),
539 Hir::repetition(hir::Repetition {
540 min: 1,
541 max: None,
542 greedy: true,
543 sub: Box::new(Hir::alternation(alloc::vec![
544 Hir::look(hir::Look::Start),
545 Hir::look(hir::Look::End),
546 ])),
547 }),
548 Hir::look(hir::Look::End),
549 ]);
550 assert_eq!(r"(?:\A(?:\A|\z)\z)", expr.to_string());
551 }
552
553 // This regression test is very similar in flavor to
554 // regression_repetition_concat in that the root of the issue lies in a
555 // peculiarity of how the HIR is represented and how the printer writes it
556 // out. Like the other regression, this one is also rooted in the fact that
557 // you can't produce the peculiar HIR from the concrete syntax. Namely, you
558 // just can't have a 'concat(a, alt(b, c))' because the 'alt' will normally
559 // be in (at least) a non-capturing group. Why? Because the '|' has very
560 // low precedence (lower that concatenation), and so something like 'ab|c'
561 // is actually 'alt(ab, c)'.
562 //
563 // See: https://github.com/rust-lang/regex/issues/516
564 #[test]
565 fn regression_alternation_concat() {
566 let expr = Hir::concat(alloc::vec![
567 Hir::literal("ab".as_bytes()),
568 Hir::alternation(alloc::vec![
569 Hir::literal("mn".as_bytes()),
570 Hir::literal("xy".as_bytes()),
571 ]),
572 ]);
573 assert_eq!(r"(?:(?:ab)(?:(?:mn)|(?:xy)))", expr.to_string());
574
575 let expr = Hir::concat(alloc::vec![
576 Hir::look(hir::Look::Start),
577 Hir::alternation(alloc::vec![
578 Hir::look(hir::Look::Start),
579 Hir::look(hir::Look::End),
580 ]),
581 ]);
582 assert_eq!(r"(?:\A(?:\A|\z))", expr.to_string());
583 }
584 }