Skip to content

Commit ea57265

Browse files
authored
Rollup merge of rust-lang#45639 - LaurentMazare:master, r=petrochenkov
Add a nicer error message for missing in for loop, fixes rust-lang#40782. As suggested by @estebank in issue rust-lang#40782, this works in the same way as rust-lang#42578: if the in keyword is missing, we continue parsing the expression and if this works correctly an adapted error message is produced. Otherwise we return the old error. A specific test case has also been added. This is my first PR on rust-lang/rust so any feedback is very welcome.
2 parents ae512c4 + ed20f3b commit ea57265

File tree

3 files changed

+30
-1
lines changed

3 files changed

+30
-1
lines changed

src/libsyntax/parse/parser.rs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3154,7 +3154,13 @@ impl<'a> Parser<'a> {
31543154
// Parse: `for <src_pat> in <src_expr> <src_loop_block>`
31553155

31563156
let pat = self.parse_pat()?;
3157-
self.expect_keyword(keywords::In)?;
3157+
if !self.eat_keyword(keywords::In) {
3158+
let in_span = self.prev_span.between(self.span);
3159+
let mut err = self.sess.span_diagnostic
3160+
.struct_span_err(in_span, "missing `in` in `for` loop");
3161+
err.span_suggestion_short(in_span, "try adding `in` here", " in ".into());
3162+
err.emit();
3163+
}
31583164
let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
31593165
let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
31603166
attrs.extend(iattrs);

src/test/ui/issue-40782.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
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+
fn main() {
12+
for i 0..2 {
13+
}
14+
}
15+

src/test/ui/issue-40782.stderr

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
error: missing `in` in `for` loop
2+
--> $DIR/issue-40782.rs:12:10
3+
|
4+
12 | for i 0..2 {
5+
| ^ help: try adding `in` here
6+
7+
error: aborting due to previous error
8+

0 commit comments

Comments
 (0)