Skip to content

Commit 4cdd205

Browse files
committed
Auto merge of rust-lang#121657 - estebank:issue-119665, r=davidtwco
Detect more cases of `=` to `:` typo When a `Local` is fully parsed, but not followed by a `;`, keep the `:` span arround and mention it. If the type could continue being parsed as an expression, suggest replacing the `:` with a `=`. ``` error: expected one of `!`, `+`, `->`, `::`, `;`, or `=`, found `.` --> file.rs:2:32 | 2 | let _: std::env::temp_dir().join("foo"); | - ^ expected one of `!`, `+`, `->`, `::`, `;`, or `=` | | | while parsing the type for `_` | help: use `=` if you meant to assign ``` Fix rust-lang#119665.
2 parents 1dc5f73 + bde2dfb commit 4cdd205

17 files changed

+146
-57
lines changed

Diff for: compiler/rustc_ast/src/ast.rs

+12-1
Original file line numberDiff line numberDiff line change
@@ -671,6 +671,16 @@ impl Pat {
671671
});
672672
contains_never_pattern
673673
}
674+
675+
/// Return a name suitable for diagnostics.
676+
pub fn descr(&self) -> Option<String> {
677+
match &self.kind {
678+
PatKind::Wild => Some("_".to_string()),
679+
PatKind::Ident(BindingAnnotation::NONE, ident, None) => Some(format!("{ident}")),
680+
PatKind::Ref(pat, mutbl) => pat.descr().map(|d| format!("&{}{d}", mutbl.prefix_str())),
681+
_ => None,
682+
}
683+
}
674684
}
675685

676686
/// A single field in a struct pattern.
@@ -1053,6 +1063,7 @@ pub struct Local {
10531063
pub ty: Option<P<Ty>>,
10541064
pub kind: LocalKind,
10551065
pub span: Span,
1066+
pub colon_sp: Option<Span>,
10561067
pub attrs: AttrVec,
10571068
pub tokens: Option<LazyAttrTokenStream>,
10581069
}
@@ -3337,7 +3348,7 @@ mod size_asserts {
33373348
static_assert_size!(Item, 136);
33383349
static_assert_size!(ItemKind, 64);
33393350
static_assert_size!(LitKind, 24);
3340-
static_assert_size!(Local, 72);
3351+
static_assert_size!(Local, 80);
33413352
static_assert_size!(MetaItemLit, 40);
33423353
static_assert_size!(Param, 40);
33433354
static_assert_size!(Pat, 72);

Diff for: compiler/rustc_ast/src/mut_visit.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -609,7 +609,7 @@ pub fn noop_visit_parenthesized_parameter_data<T: MutVisitor>(
609609
}
610610

611611
pub fn noop_visit_local<T: MutVisitor>(local: &mut P<Local>, vis: &mut T) {
612-
let Local { id, pat, ty, kind, span, attrs, tokens } = local.deref_mut();
612+
let Local { id, pat, ty, kind, span, colon_sp, attrs, tokens } = local.deref_mut();
613613
vis.visit_id(id);
614614
vis.visit_pat(pat);
615615
visit_opt(ty, |ty| vis.visit_ty(ty));
@@ -624,6 +624,7 @@ pub fn noop_visit_local<T: MutVisitor>(local: &mut P<Local>, vis: &mut T) {
624624
}
625625
}
626626
vis.visit_span(span);
627+
visit_opt(colon_sp, |sp| vis.visit_span(sp));
627628
visit_attrs(attrs, vis);
628629
visit_lazy_tts(tokens, vis);
629630
}

Diff for: compiler/rustc_expand/src/build.rs

+3
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,7 @@ impl<'a> ExtCtxt<'a> {
165165
id: ast::DUMMY_NODE_ID,
166166
kind: LocalKind::Init(ex),
167167
span: sp,
168+
colon_sp: None,
168169
attrs: AttrVec::new(),
169170
tokens: None,
170171
});
@@ -194,6 +195,7 @@ impl<'a> ExtCtxt<'a> {
194195
id: ast::DUMMY_NODE_ID,
195196
kind: LocalKind::Init(ex),
196197
span: sp,
198+
colon_sp: None,
197199
attrs: AttrVec::new(),
198200
tokens: None,
199201
});
@@ -208,6 +210,7 @@ impl<'a> ExtCtxt<'a> {
208210
id: ast::DUMMY_NODE_ID,
209211
kind: LocalKind::Decl,
210212
span,
213+
colon_sp: None,
211214
attrs: AttrVec::new(),
212215
tokens: None,
213216
});

Diff for: compiler/rustc_parse/src/parser/expr.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -430,7 +430,7 @@ impl<'a> Parser<'a> {
430430
/// The method does not advance the current token.
431431
///
432432
/// Also performs recovery for `and` / `or` which are mistaken for `&&` and `||` respectively.
433-
fn check_assoc_op(&self) -> Option<Spanned<AssocOp>> {
433+
pub fn check_assoc_op(&self) -> Option<Spanned<AssocOp>> {
434434
let (op, span) = match (AssocOp::from_token(&self.token), self.token.ident()) {
435435
// When parsing const expressions, stop parsing when encountering `>`.
436436
(
@@ -994,7 +994,7 @@ impl<'a> Parser<'a> {
994994
}
995995
}
996996

997-
fn parse_dot_suffix_expr(&mut self, lo: Span, base: P<Expr>) -> PResult<'a, P<Expr>> {
997+
pub fn parse_dot_suffix_expr(&mut self, lo: Span, base: P<Expr>) -> PResult<'a, P<Expr>> {
998998
match self.token.uninterpolate().kind {
999999
token::Ident(..) => self.parse_dot_suffix(base, lo),
10001000
token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) => {

Diff for: compiler/rustc_parse/src/parser/stmt.rs

+64-10
Original file line numberDiff line numberDiff line change
@@ -294,17 +294,22 @@ impl<'a> Parser<'a> {
294294
let (pat, colon) =
295295
self.parse_pat_before_ty(None, RecoverComma::Yes, PatternLocation::LetBinding)?;
296296

297-
let (err, ty) = if colon {
297+
let (err, ty, colon_sp) = if colon {
298298
// Save the state of the parser before parsing type normally, in case there is a `:`
299299
// instead of an `=` typo.
300300
let parser_snapshot_before_type = self.clone();
301301
let colon_sp = self.prev_token.span;
302302
match self.parse_ty() {
303-
Ok(ty) => (None, Some(ty)),
303+
Ok(ty) => (None, Some(ty), Some(colon_sp)),
304304
Err(mut err) => {
305-
if let Ok(snip) = self.span_to_snippet(pat.span) {
306-
err.span_label(pat.span, format!("while parsing the type for `{snip}`"));
307-
}
305+
err.span_label(
306+
colon_sp,
307+
format!(
308+
"while parsing the type for {}",
309+
pat.descr()
310+
.map_or_else(|| "the binding".to_string(), |n| format!("`{n}`"))
311+
),
312+
);
308313
// we use noexpect here because we don't actually expect Eq to be here
309314
// but we are still checking for it in order to be able to handle it if
310315
// it is there
@@ -317,11 +322,11 @@ impl<'a> Parser<'a> {
317322
mem::replace(self, parser_snapshot_before_type);
318323
Some((parser_snapshot_after_type, colon_sp, err))
319324
};
320-
(err, None)
325+
(err, None, Some(colon_sp))
321326
}
322327
}
323328
} else {
324-
(None, None)
329+
(None, None, None)
325330
};
326331
let init = match (self.parse_initializer(err.is_some()), err) {
327332
(Ok(init), None) => {
@@ -380,7 +385,16 @@ impl<'a> Parser<'a> {
380385
}
381386
};
382387
let hi = if self.token == token::Semi { self.token.span } else { self.prev_token.span };
383-
Ok(P(ast::Local { ty, pat, kind, id: DUMMY_NODE_ID, span: lo.to(hi), attrs, tokens: None }))
388+
Ok(P(ast::Local {
389+
ty,
390+
pat,
391+
kind,
392+
id: DUMMY_NODE_ID,
393+
span: lo.to(hi),
394+
colon_sp,
395+
attrs,
396+
tokens: None,
397+
}))
384398
}
385399

386400
fn check_let_else_init_bool_expr(&self, init: &ast::Expr) {
@@ -750,15 +764,55 @@ impl<'a> Parser<'a> {
750764
}
751765
}
752766
StmtKind::Expr(_) | StmtKind::MacCall(_) => {}
753-
StmtKind::Local(local) if let Err(e) = self.expect_semi() => {
767+
StmtKind::Local(local) if let Err(mut e) = self.expect_semi() => {
754768
// We might be at the `,` in `let x = foo<bar, baz>;`. Try to recover.
755769
match &mut local.kind {
756770
LocalKind::Init(expr) | LocalKind::InitElse(expr, _) => {
757771
self.check_mistyped_turbofish_with_multiple_type_params(e, expr)?;
758772
// We found `foo<bar, baz>`, have we fully recovered?
759773
self.expect_semi()?;
760774
}
761-
LocalKind::Decl => return Err(e),
775+
LocalKind::Decl => {
776+
if let Some(colon_sp) = local.colon_sp {
777+
e.span_label(
778+
colon_sp,
779+
format!(
780+
"while parsing the type for {}",
781+
local.pat.descr().map_or_else(
782+
|| "the binding".to_string(),
783+
|n| format!("`{n}`")
784+
)
785+
),
786+
);
787+
let suggest_eq = if self.token.kind == token::Dot
788+
&& let _ = self.bump()
789+
&& let mut snapshot = self.create_snapshot_for_diagnostic()
790+
&& let Ok(_) = snapshot.parse_dot_suffix_expr(
791+
colon_sp,
792+
self.mk_expr_err(
793+
colon_sp,
794+
self.dcx().delayed_bug("error during `:` -> `=` recovery"),
795+
),
796+
) {
797+
true
798+
} else if let Some(op) = self.check_assoc_op()
799+
&& op.node.can_continue_expr_unambiguously()
800+
{
801+
true
802+
} else {
803+
false
804+
};
805+
if suggest_eq {
806+
e.span_suggestion_short(
807+
colon_sp,
808+
"use `=` if you meant to assign",
809+
"=",
810+
Applicability::MaybeIncorrect,
811+
);
812+
}
813+
}
814+
return Err(e);
815+
}
762816
}
763817
eat_semi = false;
764818
}

Diff for: tests/ui/const-generics/bad-const-generic-exprs.stderr

+3-3
Original file line numberDiff line numberDiff line change
@@ -146,9 +146,9 @@ error: expected one of `,` or `>`, found `0`
146146
--> $DIR/bad-const-generic-exprs.rs:43:17
147147
|
148148
LL | let _: Wow<!0>;
149-
| - ^ expected one of `,` or `>`
150-
| |
151-
| while parsing the type for `_`
149+
| - ^ expected one of `,` or `>`
150+
| |
151+
| while parsing the type for `_`
152152
|
153153
help: you might have meant to end the type parameters here
154154
|

Diff for: tests/ui/issues/issue-34334.stderr

+3-3
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@ error: expected one of `,`, `:`, or `>`, found `=`
22
--> $DIR/issue-34334.rs:2:29
33
|
44
LL | let sr: Vec<(u32, _, _) = vec![];
5-
| -- ^ expected one of `,`, `:`, or `>`
6-
| |
7-
| while parsing the type for `sr`
5+
| - ^ expected one of `,`, `:`, or `>`
6+
| |
7+
| while parsing the type for `sr`
88
|
99
help: you might have meant to end the type parameters here
1010
|

Diff for: tests/ui/parser/better-expected.stderr

+3-3
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@ error: expected one of `!`, `(`, `+`, `::`, `;`, `<`, or `]`, found `3`
22
--> $DIR/better-expected.rs:2:19
33
|
44
LL | let x: [isize 3];
5-
| - ^ expected one of 7 possible tokens
6-
| |
7-
| while parsing the type for `x`
5+
| - ^ expected one of 7 possible tokens
6+
| |
7+
| while parsing the type for `x`
88

99
error: aborting due to 1 previous error
1010

Diff for: tests/ui/parser/issues/issue-84117.stderr

+7-7
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@ error: expected one of `>`, a const expression, lifetime, or type, found `}`
22
--> $DIR/issue-84117.rs:2:67
33
|
44
LL | let outer_local:e_outer<&str, { let inner_local:e_inner<&str, }
5-
| ----------- ^ expected one of `>`, a const expression, lifetime, or type
6-
| |
7-
| while parsing the type for `inner_local`
5+
| - ^ expected one of `>`, a const expression, lifetime, or type
6+
| |
7+
| while parsing the type for `inner_local`
88
|
99
help: you might have meant to end the type parameters here
1010
|
@@ -25,7 +25,7 @@ error: expected one of `,` or `>`, found `}`
2525
--> $DIR/issue-84117.rs:8:1
2626
|
2727
LL | let outer_local:e_outer<&str, { let inner_local:e_inner<&str, }
28-
| ----------- while parsing the type for `outer_local` - expected one of `,` or `>`
28+
| - while parsing the type for `outer_local` - expected one of `,` or `>`
2929
...
3030
LL | }
3131
| ^ unexpected token
@@ -43,9 +43,9 @@ error: expected one of `>`, a const expression, lifetime, or type, found `}`
4343
--> $DIR/issue-84117.rs:2:67
4444
|
4545
LL | let outer_local:e_outer<&str, { let inner_local:e_inner<&str, }
46-
| ----------- ^ expected one of `>`, a const expression, lifetime, or type
47-
| |
48-
| while parsing the type for `inner_local`
46+
| - ^ expected one of `>`, a const expression, lifetime, or type
47+
| |
48+
| while parsing the type for `inner_local`
4949
|
5050
= note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no`
5151
help: you might have meant to end the type parameters here

Diff for: tests/ui/parser/missing-closing-angle-bracket-eq-constraint.stderr

+9-9
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@ error: expected one of `,`, `:`, or `>`, found `=`
22
--> $DIR/missing-closing-angle-bracket-eq-constraint.rs:7:23
33
|
44
LL | let v : Vec<(u32,_) = vec![];
5-
| - ^ expected one of `,`, `:`, or `>`
6-
| |
7-
| while parsing the type for `v`
5+
| - ^ expected one of `,`, `:`, or `>`
6+
| |
7+
| while parsing the type for `v`
88
|
99
help: you might have meant to end the type parameters here
1010
|
@@ -15,9 +15,9 @@ error: expected one of `!`, `(`, `+`, `,`, `::`, `<`, or `>`, found `{`
1515
--> $DIR/missing-closing-angle-bracket-eq-constraint.rs:13:32
1616
|
1717
LL | let foo : Foo::<T1, T2 = Foo {_a : arg1, _b : arg2};
18-
| --- ^ expected one of 7 possible tokens
19-
| |
20-
| while parsing the type for `foo`
18+
| - ^ expected one of 7 possible tokens
19+
| |
20+
| while parsing the type for `foo`
2121
|
2222
help: you might have meant to end the type parameters here
2323
|
@@ -28,9 +28,9 @@ error: expected one of `,`, `:`, or `>`, found `=`
2828
--> $DIR/missing-closing-angle-bracket-eq-constraint.rs:18:18
2929
|
3030
LL | let v : Vec<'a = vec![];
31-
| - ^ expected one of `,`, `:`, or `>`
32-
| |
33-
| while parsing the type for `v`
31+
| - ^ expected one of `,`, `:`, or `>`
32+
| |
33+
| while parsing the type for `v`
3434
|
3535
help: you might have meant to end the type parameters here
3636
|

Diff for: tests/ui/parser/nested-missing-closing-angle-bracket.stderr

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ error: expected one of `,` or `>`, found `;`
22
--> $DIR/nested-missing-closing-angle-bracket.rs:2:46
33
|
44
LL | let v : Vec::<Vec<(u32,_,_)> = vec![vec![]];
5-
| - while parsing the type for `v` ^ expected one of `,` or `>`
5+
| - while parsing the type for `v` ^ expected one of `,` or `>`
66

77
error: aborting due to 1 previous error
88

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
fn main() {
2+
let _: std::env::temp_dir().join("foo"); //~ ERROR expected one of
3+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
error: expected one of `!`, `+`, `->`, `::`, `;`, or `=`, found `.`
2+
--> $DIR/recover-colon-instead-of-eq-in-local.rs:2:32
3+
|
4+
LL | let _: std::env::temp_dir().join("foo");
5+
| - ^ expected one of `!`, `+`, `->`, `::`, `;`, or `=`
6+
| |
7+
| while parsing the type for `_`
8+
| help: use `=` if you meant to assign
9+
10+
error: aborting due to 1 previous error
11+

Diff for: tests/ui/parser/removed-syntax/removed-syntax-fn-sigil.stderr

+3-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,9 @@ error: expected one of `->`, `;`, or `=`, found `~`
88
--> $DIR/removed-syntax-fn-sigil.rs:2:14
99
|
1010
LL | let x: fn~() = || ();
11-
| ^ expected one of `->`, `;`, or `=`
11+
| - ^ expected one of `->`, `;`, or `=`
12+
| |
13+
| while parsing the type for `x`
1214

1315
error: aborting due to 2 previous errors
1416

Diff for: tests/ui/pattern/bindings-after-at/nested-type-ascription-syntactically-invalid.stderr

+6-2
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@ error: expected one of `!`, `(`, `+`, `::`, `;`, `<`, or `=`, found `@`
22
--> $DIR/nested-type-ascription-syntactically-invalid.rs:18:15
33
|
44
LL | let a: u8 @ b = 0;
5-
| ^ expected one of 7 possible tokens
5+
| - ^ expected one of 7 possible tokens
6+
| |
7+
| while parsing the type for `a`
68

79
error: expected one of `)`, `,`, `@`, or `|`, found `:`
810
--> $DIR/nested-type-ascription-syntactically-invalid.rs:24:15
@@ -16,7 +18,9 @@ error: expected one of `!`, `(`, `+`, `::`, `;`, `<`, or `=`, found `@`
1618
--> $DIR/nested-type-ascription-syntactically-invalid.rs:30:15
1719
|
1820
LL | let a: T1 @ Outer(b: T2);
19-
| ^ expected one of 7 possible tokens
21+
| - ^ expected one of 7 possible tokens
22+
| |
23+
| while parsing the type for `a`
2024

2125
error: aborting due to 3 previous errors
2226

0 commit comments

Comments
 (0)