fix: escape when displaying string literals

This commit is contained in:
Shunsuke Shibayama 2023-05-20 00:37:28 +09:00
parent 5e8d1b987a
commit b04429b3fd
2 changed files with 20 additions and 1 deletions

View file

@ -200,6 +200,7 @@ impl Str {
Str::rc(&self.chars().rev().collect::<String>())
}
/// Note that replacements may be chained because it attempt to rewrite in sequence
pub fn multi_replace(&self, paths: &[(&str, &str)]) -> Self {
let mut self_ = self.to_string();
for (from, to) in paths {
@ -232,6 +233,24 @@ impl Str {
pub fn find_sub<'a>(&self, pats: &[&'a str]) -> Option<&'a str> {
pats.iter().find(|&&pat| self.contains(pat)).copied()
}
/// ```
/// # use erg_common::str::Str;
/// let s = Str::rc("\n");
/// assert_eq!(&s.escape()[..], "\\n");
/// let s = Str::rc("\\");
/// assert_eq!(&s.escape()[..], "\\\\");
/// ```
pub fn escape(&self) -> Str {
self.multi_replace(&[
("\\", "\\\\"),
("\0", "\\0"),
("\r", "\\r"),
("\n", "\\n"),
("\"", "\\\""),
("\'", "\\'"),
])
}
}
#[cfg(test)]

View file

@ -487,7 +487,7 @@ impl fmt::Debug for ValueObj {
}
Ok(())
}
Self::Str(s) => write!(f, "\"{s}\""),
Self::Str(s) => write!(f, "\"{}\"", s.escape()),
Self::Bool(b) => {
if *b {
write!(f, "True")