@@ -2271,6 +2271,25 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
2271
2271
struct_span_err ! ( self . tcx. sess, span, E0580 , "{}" , failure_str)
2272
2272
}
2273
2273
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
+ }
2274
2293
let mut err = struct_span_err ! ( self . tcx. sess, span, E0308 , "{}" , failure_str) ;
2275
2294
if let Some ( ( expected, found) ) = trace. values . ty ( ) {
2276
2295
match ( expected. kind ( ) , found. kind ( ) ) {
@@ -2292,7 +2311,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
2292
2311
err. span_suggestion (
2293
2312
span,
2294
2313
"if you meant to write a `char` literal, use single quotes" ,
2295
- format ! ( "'{}'" , code) ,
2314
+ format ! ( "'{}'" , escape_literal ( code) ) ,
2296
2315
Applicability :: MachineApplicable ,
2297
2316
) ;
2298
2317
}
@@ -2307,7 +2326,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
2307
2326
err. span_suggestion (
2308
2327
span,
2309
2328
"if you meant to write a `str` literal, use double quotes" ,
2310
- format ! ( "\" {}\" " , code) ,
2329
+ format ! ( "\" {}\" " , escape_literal ( code) ) ,
2311
2330
Applicability :: MachineApplicable ,
2312
2331
) ;
2313
2332
}
0 commit comments