Skip to content

Commit 3a530ba

Browse files
committed
For E0277 on for loops, point at first line
When E0277's span points at a `for` loop, the actual issue is in the element being iterated. Instead of pointing at the entire loop, point only at the first line (when possible) so that the span ends in the element for which E0277 was triggered.
1 parent 3a39b2a commit 3a530ba

File tree

3 files changed

+50
-0
lines changed

3 files changed

+50
-0
lines changed

src/librustc/traits/error_reporting.rs

+18
Original file line numberDiff line numberDiff line change
@@ -551,6 +551,24 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
551551
let OnUnimplementedNote { message, label }
552552
= self.on_unimplemented_note(trait_ref, obligation);
553553
let have_alt_message = message.is_some() || label.is_some();
554+
let span = match self.tcx.sess.codemap().span_to_snippet(span) {
555+
Ok(ref s) if s.starts_with("for ") => {
556+
// On for loops, this error is caused by the element being iterated
557+
// on, but the span points at the entire for loop. Instead of:
558+
//
559+
// / for c in "asdf" {
560+
// | ...
561+
// | }
562+
// |_^ `&str` is not an iterator
563+
//
564+
// lets point at:
565+
//
566+
// for c in "asdf" {
567+
// ^^^^^^^^^^^^^^^ `&str` is not an iterator
568+
self.tcx.sess.codemap().span_until_char(span, '{')
569+
}
570+
_ => span,
571+
};
554572

555573
let mut err = struct_span_err!(
556574
self.tcx.sess,
+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// Copyright 2018 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+
// E0277 should point exclusively at line 14, not the entire for loop span
12+
13+
fn main() {
14+
for c in "asdf" {
15+
//~^ ERROR the trait bound `&str: std::iter::Iterator` is not satisfied
16+
//~| NOTE `&str` is not an iterator
17+
//~| HELP the trait `std::iter::Iterator` is not implemented for `&str`
18+
//~| NOTE required by `std::iter::IntoIterator::into_iter`
19+
println!("");
20+
}
21+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
error[E0277]: the trait bound `&str: std::iter::Iterator` is not satisfied
2+
--> $DIR/for-c-in-str.rs:14:5
3+
|
4+
14 | for c in "asdf" {
5+
| ^^^^^^^^^^^^^^^ `&str` is not an iterator; maybe try calling `.iter()` or a similar method
6+
|
7+
= help: the trait `std::iter::Iterator` is not implemented for `&str`
8+
= note: required by `std::iter::IntoIterator::into_iter`
9+
10+
error: aborting due to previous error
11+

0 commit comments

Comments
 (0)