Skip to content

Commit f22b04e

Browse files
committed
fix: make sure byte and string literals are escaped
1 parent 2c09e14 commit f22b04e

2 files changed

Lines changed: 17 additions & 4 deletions

File tree

src/unparser.rs

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1039,12 +1039,22 @@ impl Unparser {
10391039
}
10401040
Constant::Bytes(value) => {
10411041
let utf8 = String::from_utf8(value.to_owned());
1042-
self.write_str("b\"");
1043-
self.write_str(&utf8.unwrap());
1044-
self.write_str("\"");
1042+
self.write_str("b");
1043+
let escaped = rustpython_literal::escape::UnicodeEscape::new_repr(&utf8.unwrap())
1044+
.str_repr()
1045+
.to_string()
1046+
.unwrap();
1047+
self.write_str(&escaped);
10451048
}
10461049
Constant::Int(value) => self.write_str(&value.to_string()),
1047-
Constant::Str(value) => self.write_str(&format!("\"{}\"", value)),
1050+
Constant::Str(value) => {
1051+
let escaped = rustpython_literal::escape::UnicodeEscape::new_repr(value)
1052+
.str_repr()
1053+
.to_string()
1054+
.unwrap();
1055+
1056+
self.write_str(&escaped);
1057+
}
10481058
Constant::None => self.write_str("None"),
10491059
Constant::Complex { real, imag: _ } => self.write_str(&real.to_string()),
10501060
Constant::Float(value) => self.write_str(&value.to_string()),

test_files/constants.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
escaped_string_expr = "'\"'''\"\"\"{}\\"
2+
escaped_unicode_expr = u"'\"'''\"\"\"{}\\" # fmt: skip
3+
escaped_bytes_expr = b"'\"'''\"\"\"{}\\"

0 commit comments

Comments
 (0)