]> git.lizzy.rs Git - rust.git/blobdiff - compiler/rustc_parse/src/lexer/unescape_error_reporting.rs
Properly escape quotes when suggesting switching between char/string literals
[rust.git] / compiler / rustc_parse / src / lexer / unescape_error_reporting.rs
index 77c4fadab45eacc9f61d5fd4cb4d361cedc62666..f075de714267688eb0711fe0e631f14cb9c485d3 100644 (file)
@@ -113,11 +113,26 @@ pub(crate) fn emit_unescape_error(
                 } else {
                     ("", "if you meant to write a `str` literal, use double quotes")
                 };
-
+                let mut escaped = String::with_capacity(lit.len());
+                let mut chrs = lit.chars().peekable();
+                while let Some(first) = chrs.next() {
+                    match (first, chrs.peek()) {
+                        ('\\', Some('"')) => {
+                            escaped.push('\\');
+                            escaped.push('"');
+                            chrs.next();
+                        }
+                        ('"', _) => {
+                            escaped.push('\\');
+                            escaped.push('"')
+                        }
+                        (c, _) => escaped.push(c),
+                    };
+                }
                 handler.span_suggestion(
                     span_with_quotes,
                     msg,
-                    format!("{}\"{}\"", prefix, lit),
+                    format!("{prefix}\"{escaped}\""),
                     Applicability::MachineApplicable,
                 );
             }