Skip to content

Commit f60d373

Browse files
committed
Auto merge of #43489 - petrochenkov:mutref, r=GuillaumeGomez
Better diagnostics and recovery for `mut ref` in patterns Fixes #43286 Supersedes #43451 r? @GuillaumeGomez
2 parents da4d490 + dda30f6 commit f60d373

File tree

3 files changed

+36
-2
lines changed

3 files changed

+36
-2
lines changed

src/libsyntax/parse/parser.rs

+12-2
Original file line numberDiff line numberDiff line change
@@ -3523,8 +3523,18 @@ impl<'a> Parser<'a> {
35233523
}
35243524
// At this point, token != _, &, &&, (, [
35253525
_ => if self.eat_keyword(keywords::Mut) {
3526-
// Parse mut ident @ pat
3527-
pat = self.parse_pat_ident(BindingMode::ByValue(Mutability::Mutable))?;
3526+
// Parse mut ident @ pat / mut ref ident @ pat
3527+
let mutref_span = self.prev_span.to(self.span);
3528+
let binding_mode = if self.eat_keyword(keywords::Ref) {
3529+
self.diagnostic()
3530+
.struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
3531+
.span_suggestion(mutref_span, "try switching the order", "ref mut".into())
3532+
.emit();
3533+
BindingMode::ByRef(Mutability::Mutable)
3534+
} else {
3535+
BindingMode::ByValue(Mutability::Mutable)
3536+
};
3537+
pat = self.parse_pat_ident(binding_mode)?;
35283538
} else if self.eat_keyword(keywords::Ref) {
35293539
// Parse ref ident @ pat / ref mut ident @ pat
35303540
let mutbl = self.parse_mutability();

src/test/ui/mut-ref.rs

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
// compile-flags: -Z parse-only
12+
13+
fn main() {
14+
let mut ref x = 10;
15+
let ref mut y = 11;
16+
}

src/test/ui/mut-ref.stderr

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
error: the order of `mut` and `ref` is incorrect
2+
--> $DIR/mut-ref.rs:14:9
3+
|
4+
14 | let mut ref x = 10;
5+
| ^^^^^^^ help: try switching the order: `ref mut`
6+
7+
error: aborting due to previous error
8+

0 commit comments

Comments
 (0)