diff --git a/compiler/rustc_infer/src/infer/error_reporting/mod.rs b/compiler/rustc_infer/src/infer/error_reporting/mod.rs index e0894ed31bfc3..c7affaa17e9d2 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/mod.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/mod.rs @@ -2064,10 +2064,15 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { // If a string was expected and the found expression is a character literal, // perhaps the user meant to write `"s"` to specify a string literal. (ty::Ref(_, r, _), ty::Char) if r.is_str() => { - suggestions.push(TypeErrorAdditionalDiags::MeantStrLiteral { - start: span.with_hi(span.lo() + BytePos(1)), - end: span.with_lo(span.hi() - BytePos(1)), - }) + if let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span) + && code.starts_with("'") + && code.ends_with("'") + { + suggestions.push(TypeErrorAdditionalDiags::MeantStrLiteral { + start: span.with_hi(span.lo() + BytePos(1)), + end: span.with_lo(span.hi() - BytePos(1)), + }); + } } // For code `if Some(..) = expr `, the type mismatch may be expected `bool` but found `()`, // we try to suggest to add the missing `let` for `if let Some(..) = expr` diff --git a/tests/ui/inference/str-as-char-no-lit.rs b/tests/ui/inference/str-as-char-no-lit.rs new file mode 100644 index 0000000000000..d38b46630dcf1 --- /dev/null +++ b/tests/ui/inference/str-as-char-no-lit.rs @@ -0,0 +1,9 @@ +// Don't suggest double quotes when encountering an expr of type `char` where a `&str` +// is expected if the expr is not a char literal. +// issue: rust-lang/rust#125595 + +fn main() { + let _: &str = ('a'); //~ ERROR mismatched types + let token = || 'a'; + let _: &str = token(); //~ ERROR mismatched types +} diff --git a/tests/ui/inference/str-as-char-no-lit.stderr b/tests/ui/inference/str-as-char-no-lit.stderr new file mode 100644 index 0000000000000..aaaf0adf67d36 --- /dev/null +++ b/tests/ui/inference/str-as-char-no-lit.stderr @@ -0,0 +1,19 @@ +error[E0308]: mismatched types + --> $DIR/str-as-char-no-lit.rs:6:19 + | +LL | let _: &str = ('a'); + | ---- ^^^^^ expected `&str`, found `char` + | | + | expected due to this + +error[E0308]: mismatched types + --> $DIR/str-as-char-no-lit.rs:8:19 + | +LL | let _: &str = token(); + | ---- ^^^^^^^ expected `&str`, found `char` + | | + | expected due to this + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0308`.