Skip to content

Commit 2e4a21c

Browse files
committed
Mention type of for exprs that don't implement Iterator.
This improves the error message by telling the user the exact type of `x` if it doesn't implement `Iterator` in `for ... in x {}`. Closes #16043.
1 parent e3549ee commit 2e4a21c

File tree

2 files changed

+6
-5
lines changed

2 files changed

+6
-5
lines changed

src/librustc/middle/typeck/check/mod.rs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2168,12 +2168,13 @@ fn lookup_method_for_for_loop(fcx: &FnCtxt,
21682168
}
21692169
};
21702170

2171+
let expr_type = fcx.expr_ty(&*iterator_expr);
21712172
let method = method::lookup_in_trait(fcx,
21722173
iterator_expr.span,
21732174
Some(&*iterator_expr),
21742175
token::intern("next"),
21752176
trait_did,
2176-
fcx.expr_ty(&*iterator_expr),
2177+
expr_type,
21772178
[],
21782179
DontAutoderefReceiver,
21792180
IgnoreStaticMethods);
@@ -2184,8 +2185,9 @@ fn lookup_method_for_for_loop(fcx: &FnCtxt,
21842185
Some(ref method) => method.ty,
21852186
None => {
21862187
fcx.tcx().sess.span_err(iterator_expr.span,
2187-
"`for` loop expression does not \
2188-
implement the `Iterator` trait");
2188+
format!("`for` loop expression has type `{}` which does \
2189+
not implement the `Iterator` trait",
2190+
fcx.infcx().ty_to_string(expr_type)).as_slice());
21892191
ty::mk_err()
21902192
}
21912193
};

src/test/compile-fail/for-loop-bogosity.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,7 @@ pub fn main() {
2424
x: 1,
2525
y: 2,
2626
};
27-
for x in bogus { //~ ERROR does not implement the `Iterator` trait
27+
for x in bogus { //~ ERROR has type `MyStruct` which does not implement the `Iterator` trait
2828
drop(x);
2929
}
3030
}
31-

0 commit comments

Comments
 (0)