Skip to content

Improve the diagnostics for mistakes in for loops #16762

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 2 commits into from
Aug 29, 2014
Merged
Show file tree
Hide file tree
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
15 changes: 11 additions & 4 deletions src/librustc/middle/typeck/check/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2168,12 +2168,13 @@ fn lookup_method_for_for_loop(fcx: &FnCtxt,
}
};

let expr_type = fcx.expr_ty(&*iterator_expr);
let method = method::lookup_in_trait(fcx,
iterator_expr.span,
Some(&*iterator_expr),
token::intern("next"),
trait_did,
fcx.expr_ty(&*iterator_expr),
expr_type,
[],
DontAutoderefReceiver,
IgnoreStaticMethods);
Expand All @@ -2183,9 +2184,15 @@ fn lookup_method_for_for_loop(fcx: &FnCtxt,
let method_type = match method {
Some(ref method) => method.ty,
None => {
fcx.tcx().sess.span_err(iterator_expr.span,
"`for` loop expression does not \
implement the `Iterator` trait");
let true_expr_type = fcx.infcx().resolve_type_vars_if_possible(expr_type);

if !ty::type_is_error(true_expr_type) {
let ty_string = fcx.infcx().ty_to_string(true_expr_type);
fcx.tcx().sess.span_err(iterator_expr.span,
format!("`for` loop expression has type `{}` which does \
not implement the `Iterator` trait",
ty_string).as_slice());
}
ty::mk_err()
}
};
Expand Down
3 changes: 1 addition & 2 deletions src/test/compile-fail/for-loop-bogosity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,7 @@ pub fn main() {
x: 1,
y: 2,
};
for x in bogus { //~ ERROR does not implement the `Iterator` trait
for x in bogus { //~ ERROR has type `MyStruct` which does not implement the `Iterator` trait
drop(x);
}
}

16 changes: 16 additions & 0 deletions src/test/compile-fail/for-loop-type-error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Copyright 2014 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.

pub fn main() {
let x = () + (); //~ ERROR binary operation

// this shouldn't have a flow-on error:
for _ in x {}
}