Skip to content

Commit 24c7770

Browse files
committed
syntax: fix printing bug for HIR
This commit fixes a bug in the HIR printer where it would not correctly escape meta characters in character classes.
1 parent 7ebe4ae commit 24c7770

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

regex-syntax/src/hir/print.rs

+18-2
Original file line numberDiff line numberDiff line change
@@ -228,7 +228,7 @@ impl<'p, W: fmt::Write> Writer<'p, W> {
228228
fn write_literal_byte(&mut self, b: u8) -> fmt::Result {
229229
let c = b as char;
230230
if c <= 0x7F as char && !c.is_control() && !c.is_whitespace() {
231-
self.wtr.write_char(c)
231+
self.write_literal_char(c)
232232
} else {
233233
write!(self.wtr, "(?-u:\\x{:02X})", b)
234234
}
@@ -237,7 +237,7 @@ impl<'p, W: fmt::Write> Writer<'p, W> {
237237
fn write_literal_class_byte(&mut self, b: u8) -> fmt::Result {
238238
let c = b as char;
239239
if c <= 0x7F as char && !c.is_control() && !c.is_whitespace() {
240-
self.wtr.write_char(c)
240+
self.write_literal_char(c)
241241
} else {
242242
write!(self.wtr, "\\x{:02X}", b)
243243
}
@@ -267,6 +267,10 @@ mod tests {
267267
let mut printer = Printer::new();
268268
let mut dst = String::new();
269269
printer.print(&hir, &mut dst).unwrap();
270+
271+
// Check that the result is actually valid.
272+
builder.build().parse(&dst).unwrap();
273+
270274
assert_eq!(expected, dst);
271275
}
272276

@@ -291,6 +295,18 @@ mod tests {
291295
roundtrip(r"(?-u)[a]", r"(?-u:[a])");
292296
roundtrip(r"(?-u)[a-z]", r"(?-u:[a-z])");
293297
roundtrip_bytes(r"(?-u)[a-\xFF]", r"(?-u:[a-\xFF])");
298+
299+
// The following test that the printer escapes meta characters
300+
// in character classes.
301+
roundtrip(r"[\[]", r"[\[]");
302+
roundtrip(r"[Z-_]", r"[Z-_]");
303+
roundtrip(r"[Z-_--Z]", r"[\[-_]");
304+
305+
// The following test that the printer escapes meta characters
306+
// in byte oriented character classes.
307+
roundtrip_bytes(r"(?-u)[\[]", r"(?-u:[\[])");
308+
roundtrip_bytes(r"(?-u)[Z-_]", r"(?-u:[Z-_])");
309+
roundtrip_bytes(r"(?-u)[Z-_--Z]", r"(?-u:[\[-_])");
294310
}
295311

296312
#[test]

0 commit comments

Comments
 (0)