Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
54 changes: 48 additions & 6 deletions src/libsyntax/parse/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3154,13 +3154,55 @@ 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

let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
attrs.extend(iattrs);
// Save the state of the parser before parsing 'in'.
let parser_snapshot_before_in = self.clone();
match self.expect_keyword(keywords::In) {
Ok(()) => {
let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
attrs.extend(iattrs);

let hi = self.prev_span;
Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_ident), attrs))
let hi = self.prev_span;
Ok(self.mk_expr(
span_lo.to(hi),
ExprKind::ForLoop(pat, expr, loop_block, opt_ident),
attrs))
}
Err(mut in_err) => {
let parser_snapshot_after_in = self.clone();
// Rewind to before attempting to parse the 'in'.
mem::replace(self, parser_snapshot_before_in);

match self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None) {
Ok(expr) => {
// Successfully parsed the expr, print a nice error message.
Copy link
Contributor

Choose a reason for hiding this comment

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

Expand the comment with more explanation, stating the reasoning. Something along the lines of "successfully parsed the expr, which means that the in kw is missing" and even a simple code sample like for i 0..2 {.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I've added the example you suggested.

in_err.cancel();
let in_span = parser_snapshot_after_in.span;
Copy link
Contributor

Choose a reason for hiding this comment

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

in_span should probably be parser_snapshot_after_in.prev_span.end().to(parser_snapshot_after_in.prev_span.span.start()) to point at the empty space between the pat and the expr, regardless of how long it is:

12 |     for i   0..2 {
   |          ^^^
   |          |
   |          expected `in` here

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Ah, my understanding of spans was indeed pretty poor, hopefully it's getting better. I used between rather than exactly what you suggested but it seems to do the trick.

let mut err = self.sess.span_diagnostic
.struct_span_err(in_span, "missing `in` in `for` loop");
err.span_label(in_span, "expected `in` here");
let sugg = pprust::to_string(|s| {
s.s.word("for ")?;
s.print_pat(&pat)?;
s.s.word(" in ")?;
s.print_expr(&expr)
});
Copy link
Contributor

Choose a reason for hiding this comment

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

Can't all of this be format!("for {} in {}", path, expr)?

Copy link
Contributor

Choose a reason for hiding this comment

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

Also, it might be nice to try using tcx.sess.codemap().span_to_snippet(expr.span) and only use s.print_expr(&expr) if it couldn't be found. This way the expr is exactly as it was written in the original code, instead of as whatever print_expr prefers to output (think of cases like for i 0 .. 2 {, we want to keep the user's formatting).

Copy link
Contributor Author

@LaurentMazare LaurentMazare Oct 31, 2017

Choose a reason for hiding this comment

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

I went the easy way and replaced all this with a span_suggestion_short as mentioned below so all this should not apply anymore.

err.span_suggestion(
in_span,
Copy link
Contributor

Choose a reason for hiding this comment

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

This span has to cover from the entire suggestion. In this case, you're suggesting for {pat} in {expr}, so the span should cover from the beginning of the for span to the end of the expr.span. This is because suggestions should be able to be applied blindly by other tools to the code, so the replacement should always make sense and have a high degree of confidence (as you do here, because the parsing continued successfully).

Otherwise, instead of pointing at the entire for {pat} {expr} span, use a span_suggestion_short, which hides the actual suggestion in the cli output but is still available to code fixing tools like RLS, and suggest only the in in the span between the end of pat.span to the start of expr.span, which would give you the following output:

12 |     for i 0..2 {
   |          ^
   |          |
   |          expected `in` here
   |          help: try adding `in` here

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Switched to using span_suggestion_short.

"try adding `in`",
sugg);
Err(err)
}
Err(mut expr_err) => {
// Couldn't parse as an expr, return original error and parser state.
expr_err.cancel();
mem::replace(self, parser_snapshot_after_in);
Err(in_err)
}
}
}

}
}

/// Parse a 'while' or 'while let' expression ('while' token already eaten)
Expand Down
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 {
}
}

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

error: aborting due to previous error