]> git.lizzy.rs Git - rust.git/commitdiff
Fix ast::String::value not properly escaping in some cases
authorLukas Wirth <lukastw97@gmail.com>
Sat, 30 Jan 2021 15:31:19 +0000 (16:31 +0100)
committerLukas Wirth <lukastw97@gmail.com>
Sat, 30 Jan 2021 15:31:19 +0000 (16:31 +0100)
crates/syntax/src/ast/token_ext.rs

index 5e07ec7d15939f764ef362cba031df640f3f0324..044e3e5e8494f48761cec12717ed18ebc0a3f18a 100644 (file)
@@ -173,7 +173,7 @@ pub fn value(&self) -> Option<Cow<'_, str>> {
             buf.capacity() == 0,
         ) {
             (Ok(c), false) => buf.push(c),
-            (Ok(c), true) if Some(c) == text_iter.next() => (),
+            (Ok(c), true) if char_range.len() == 1 && Some(c) == text_iter.next() => (),
             (Ok(c), true) => {
                 buf.reserve_exact(text.len());
                 buf.push_str(&text[..char_range.start]);
@@ -659,7 +659,7 @@ const fn prefix_len(&self) -> usize {
 
 #[cfg(test)]
 mod tests {
-    use crate::ast::{make, FloatNumber, IntNumber};
+    use crate::ast::{self, make, FloatNumber, IntNumber};
 
     fn check_float_suffix<'a>(lit: &str, expected: impl Into<Option<&'a str>>) {
         assert_eq!(FloatNumber { syntax: make::tokens::literal(lit) }.suffix(), expected.into());
@@ -692,4 +692,21 @@ fn test_int_number_suffix() {
         check_int_suffix("0o11u32", "u32");
         check_int_suffix("0xffu32", "u32");
     }
+
+    fn check_string_value<'a>(lit: &str, expected: impl Into<Option<&'a str>>) {
+        assert_eq!(
+            ast::String { syntax: make::tokens::literal(&format!("\"{}\"", lit)) }
+                .value()
+                .as_deref(),
+            expected.into()
+        );
+    }
+
+    #[test]
+    fn test_string_escape() {
+        check_string_value(r"foobar", "foobar");
+        check_string_value(r"\foobar", None);
+        check_string_value(r"\nfoobar", "\nfoobar");
+        check_string_value(r"C:\\Windows\\System32\\", "C:\\Windows\\System32\\");
+    }
 }