Skip to content

Add a nicer error message for missing in for loop, fixes #40782. #45639

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Nov 4, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion src/libsyntax/parse/parser.rs
Original file line number Diff line number Diff line change
@@ -3154,7 +3154,13 @@ impl<'a> Parser<'a> {
// Parse: `for <src_pat> in <src_expr> <src_loop_block>`

let pat = self.parse_pat()?;
self.expect_keyword(keywords::In)?;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This can be done in much simpler way without parser snapshots (please don't overuse the trick from #42578).

if !self.eat_keyword(keywords::In) {
    span_err(/*missing `in`*/) // Non-fatal error
}
let expr = self.parse_expr_res(...); // Then parse as usual as if `in` were written

if !self.eat_keyword(keywords::In) {
let in_span = self.prev_span.between(self.span);
let mut err = self.sess.span_diagnostic
.struct_span_err(in_span, "missing `in` in `for` loop");
err.span_suggestion_short(in_span, "try adding `in` here", " in ".into());
err.emit();
}
let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
attrs.extend(iattrs);
15 changes: 15 additions & 0 deletions src/test/ui/issue-40782.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

fn main() {
for i 0..2 {
}
}

8 changes: 8 additions & 0 deletions src/test/ui/issue-40782.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
error: missing `in` in `for` loop
--> $DIR/issue-40782.rs:12:10
|
12 | for i 0..2 {
| ^ help: try adding `in` here

error: aborting due to previous error