@@ -2271,6 +2271,25 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
22712271 struct_span_err ! ( self . tcx. sess, span, E0580 , "{}" , failure_str)
22722272 }
22732273 FailureCode :: Error0308 ( failure_str) => {
2274+ fn escape_literal ( s : & str ) -> String {
2275+ let mut escaped = String :: with_capacity ( s. len ( ) ) ;
2276+ let mut chrs = s. chars ( ) . peekable ( ) ;
2277+ while let Some ( first) = chrs. next ( ) {
2278+ match ( first, chrs. peek ( ) ) {
2279+ ( '\\' , Some ( & delim @ '"' ) | Some ( & delim @ '\'' ) ) => {
2280+ escaped. push ( '\\' ) ;
2281+ escaped. push ( delim) ;
2282+ chrs. next ( ) ;
2283+ }
2284+ ( '"' | '\'' , _) => {
2285+ escaped. push ( '\\' ) ;
2286+ escaped. push ( first)
2287+ }
2288+ ( c, _) => escaped. push ( c) ,
2289+ } ;
2290+ }
2291+ escaped
2292+ }
22742293 let mut err = struct_span_err ! ( self . tcx. sess, span, E0308 , "{}" , failure_str) ;
22752294 if let Some ( ( expected, found) ) = trace. values . ty ( ) {
22762295 match ( expected. kind ( ) , found. kind ( ) ) {
@@ -2292,7 +2311,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
22922311 err. span_suggestion (
22932312 span,
22942313 "if you meant to write a `char` literal, use single quotes" ,
2295- format ! ( "'{}'" , code) ,
2314+ format ! ( "'{}'" , escape_literal ( code) ) ,
22962315 Applicability :: MachineApplicable ,
22972316 ) ;
22982317 }
@@ -2307,7 +2326,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
23072326 err. span_suggestion (
23082327 span,
23092328 "if you meant to write a `str` literal, use double quotes" ,
2310- format ! ( "\" {}\" " , code) ,
2329+ format ! ( "\" {}\" " , escape_literal ( code) ) ,
23112330 Applicability :: MachineApplicable ,
23122331 ) ;
23132332 }
0 commit comments