Skip to content

Commit 01ea49e

Browse files
committed
Don't suggest turning non-char-literal exprs of ty char into string literals
1 parent 0a59f11 commit 01ea49e

File tree

3 files changed

+37
-4
lines changed

3 files changed

+37
-4
lines changed

compiler/rustc_infer/src/infer/error_reporting/mod.rs

+9-4
Original file line numberDiff line numberDiff line change
@@ -2064,10 +2064,15 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
20642064
// If a string was expected and the found expression is a character literal,
20652065
// perhaps the user meant to write `"s"` to specify a string literal.
20662066
(ty::Ref(_, r, _), ty::Char) if r.is_str() => {
2067-
suggestions.push(TypeErrorAdditionalDiags::MeantStrLiteral {
2068-
start: span.with_hi(span.lo() + BytePos(1)),
2069-
end: span.with_lo(span.hi() - BytePos(1)),
2070-
})
2067+
if let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span)
2068+
&& code.starts_with("'")
2069+
&& code.ends_with("'")
2070+
{
2071+
suggestions.push(TypeErrorAdditionalDiags::MeantStrLiteral {
2072+
start: span.with_hi(span.lo() + BytePos(1)),
2073+
end: span.with_lo(span.hi() - BytePos(1)),
2074+
});
2075+
}
20712076
}
20722077
// For code `if Some(..) = expr `, the type mismatch may be expected `bool` but found `()`,
20732078
// we try to suggest to add the missing `let` for `if let Some(..) = expr`
+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
// Don't suggest double quotes when encountering an expr of type `char` where a `&str`
2+
// is expected if the expr is not a char literal.
3+
// issue: rust-lang/rust#125595
4+
5+
fn main() {
6+
let _: &str = ('a'); //~ ERROR mismatched types
7+
let token = || 'a';
8+
let _: &str = token(); //~ ERROR mismatched types
9+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
error[E0308]: mismatched types
2+
--> $DIR/str-as-char-no-lit.rs:6:19
3+
|
4+
LL | let _: &str = ('a');
5+
| ---- ^^^^^ expected `&str`, found `char`
6+
| |
7+
| expected due to this
8+
9+
error[E0308]: mismatched types
10+
--> $DIR/str-as-char-no-lit.rs:8:19
11+
|
12+
LL | let _: &str = token();
13+
| ---- ^^^^^^^ expected `&str`, found `char`
14+
| |
15+
| expected due to this
16+
17+
error: aborting due to 2 previous errors
18+
19+
For more information about this error, try `rustc --explain E0308`.

0 commit comments

Comments
 (0)