Skip to content

Commit 039af9c

Browse files
committed
Auto merge of #9667 - dorublanzeanu:master, r=giraffate
add new lint `seek_to_start_instead_of_rewind ` changelog: `seek_to_start_instead_of_rewind`: new lint to suggest using `rewind` instead of `seek` to start Resolve #8600
2 parents b698a15 + b9b9d6a commit 039af9c

10 files changed

+406
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4200,6 +4200,7 @@ Released 2018-09-13
42004200
[`same_item_push`]: https://rust-lang.github.io/rust-clippy/master/index.html#same_item_push
42014201
[`same_name_method`]: https://rust-lang.github.io/rust-clippy/master/index.html#same_name_method
42024202
[`search_is_some`]: https://rust-lang.github.io/rust-clippy/master/index.html#search_is_some
4203+
[`seek_to_start_instead_of_rewind`]: https://rust-lang.github.io/rust-clippy/master/index.html#seek_to_start_instead_of_rewind
42034204
[`self_assignment`]: https://rust-lang.github.io/rust-clippy/master/index.html#self_assignment
42044205
[`self_named_constructors`]: https://rust-lang.github.io/rust-clippy/master/index.html#self_named_constructors
42054206
[`self_named_module_files`]: https://rust-lang.github.io/rust-clippy/master/index.html#self_named_module_files

clippy_lints/src/declared_lints.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -363,6 +363,7 @@ pub(crate) static LINTS: &[&crate::LintInfo] = &[
363363
crate::methods::REPEAT_ONCE_INFO,
364364
crate::methods::RESULT_MAP_OR_INTO_OPTION_INFO,
365365
crate::methods::SEARCH_IS_SOME_INFO,
366+
crate::methods::SEEK_TO_START_INSTEAD_OF_REWIND_INFO,
366367
crate::methods::SHOULD_IMPLEMENT_TRAIT_INFO,
367368
crate::methods::SINGLE_CHAR_ADD_STR_INFO,
368369
crate::methods::SINGLE_CHAR_PATTERN_INFO,

clippy_lints/src/methods/mod.rs

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ mod path_buf_push_overwrite;
6969
mod range_zip_with_len;
7070
mod repeat_once;
7171
mod search_is_some;
72+
mod seek_to_start_instead_of_rewind;
7273
mod single_char_add_str;
7374
mod single_char_insert_string;
7475
mod single_char_pattern;
@@ -3066,6 +3067,37 @@ declare_clippy_lint! {
30663067
"iterating on map using `iter` when `keys` or `values` would do"
30673068
}
30683069

3070+
declare_clippy_lint! {
3071+
/// ### What it does
3072+
///
3073+
/// Checks for jumps to the start of a stream that implements `Seek`
3074+
/// and uses the `seek` method providing `Start` as parameter.
3075+
///
3076+
/// ### Why is this bad?
3077+
///
3078+
/// Readability. There is a specific method that was implemented for
3079+
/// this exact scenario.
3080+
///
3081+
/// ### Example
3082+
/// ```rust
3083+
/// # use std::io;
3084+
/// fn foo<T: io::Seek>(t: &mut T) {
3085+
/// t.seek(io::SeekFrom::Start(0));
3086+
/// }
3087+
/// ```
3088+
/// Use instead:
3089+
/// ```rust
3090+
/// # use std::io;
3091+
/// fn foo<T: io::Seek>(t: &mut T) {
3092+
/// t.rewind();
3093+
/// }
3094+
/// ```
3095+
#[clippy::version = "1.66.0"]
3096+
pub SEEK_TO_START_INSTEAD_OF_REWIND,
3097+
complexity,
3098+
"jumping to the start of stream using `seek` method"
3099+
}
3100+
30693101
pub struct Methods {
30703102
avoid_breaking_exported_api: bool,
30713103
msrv: Option<RustcVersion>,
@@ -3190,6 +3222,7 @@ impl_lint_pass!(Methods => [
31903222
VEC_RESIZE_TO_ZERO,
31913223
VERBOSE_FILE_READS,
31923224
ITER_KV_MAP,
3225+
SEEK_TO_START_INSTEAD_OF_REWIND,
31933226
]);
31943227

31953228
/// Extracts a method call name, args, and `Span` of the method name.
@@ -3604,6 +3637,11 @@ impl Methods {
36043637
("resize", [count_arg, default_arg]) => {
36053638
vec_resize_to_zero::check(cx, expr, count_arg, default_arg, span);
36063639
},
3640+
("seek", [arg]) => {
3641+
if meets_msrv(self.msrv, msrvs::SEEK_REWIND) {
3642+
seek_to_start_instead_of_rewind::check(cx, expr, recv, arg, span);
3643+
}
3644+
},
36073645
("sort", []) => {
36083646
stable_sort_primitive::check(cx, expr, recv);
36093647
},
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
use clippy_utils::diagnostics::span_lint_and_then;
2+
use clippy_utils::ty::implements_trait;
3+
use clippy_utils::{get_trait_def_id, match_def_path, paths};
4+
use rustc_ast::ast::{LitIntType, LitKind};
5+
use rustc_errors::Applicability;
6+
use rustc_hir::{Expr, ExprKind};
7+
use rustc_lint::LateContext;
8+
use rustc_span::Span;
9+
10+
use super::SEEK_TO_START_INSTEAD_OF_REWIND;
11+
12+
pub(super) fn check<'tcx>(
13+
cx: &LateContext<'tcx>,
14+
expr: &'tcx Expr<'_>,
15+
recv: &'tcx Expr<'_>,
16+
arg: &'tcx Expr<'_>,
17+
name_span: Span,
18+
) {
19+
// Get receiver type
20+
let ty = cx.typeck_results().expr_ty(recv).peel_refs();
21+
22+
if let Some(seek_trait_id) = get_trait_def_id(cx, &paths::STD_IO_SEEK) &&
23+
implements_trait(cx, ty, seek_trait_id, &[]) &&
24+
let ExprKind::Call(func, args1) = arg.kind &&
25+
let ExprKind::Path(ref path) = func.kind &&
26+
let Some(def_id) = cx.qpath_res(path, func.hir_id).opt_def_id() &&
27+
match_def_path(cx, def_id, &paths::STD_IO_SEEKFROM_START) &&
28+
args1.len() == 1 &&
29+
let ExprKind::Lit(ref lit) = args1[0].kind &&
30+
let LitKind::Int(0, LitIntType::Unsuffixed) = lit.node
31+
{
32+
let method_call_span = expr.span.with_lo(name_span.lo());
33+
span_lint_and_then(
34+
cx,
35+
SEEK_TO_START_INSTEAD_OF_REWIND,
36+
method_call_span,
37+
"used `seek` to go to the start of the stream",
38+
|diag| {
39+
let app = Applicability::MachineApplicable;
40+
41+
diag.span_suggestion(method_call_span, "replace with", "rewind()", app);
42+
},
43+
);
44+
}
45+
}

clippy_utils/src/msrvs.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,4 +38,5 @@ msrv_aliases! {
3838
1,18,0 { HASH_MAP_RETAIN, HASH_SET_RETAIN }
3939
1,17,0 { FIELD_INIT_SHORTHAND, STATIC_IN_CONST, EXPECT_ERR }
4040
1,16,0 { STR_REPEAT }
41+
1,55,0 { SEEK_REWIND }
4142
}

clippy_utils/src/paths.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,8 @@ pub const STDERR: [&str; 4] = ["std", "io", "stdio", "stderr"];
115115
pub const STDOUT: [&str; 4] = ["std", "io", "stdio", "stdout"];
116116
pub const CONVERT_IDENTITY: [&str; 3] = ["core", "convert", "identity"];
117117
pub const STD_FS_CREATE_DIR: [&str; 3] = ["std", "fs", "create_dir"];
118+
pub const STD_IO_SEEK: [&str; 3] = ["std", "io", "Seek"];
119+
pub const STD_IO_SEEKFROM_START: [&str; 4] = ["std", "io", "SeekFrom", "Start"];
118120
pub const STRING_AS_MUT_STR: [&str; 4] = ["alloc", "string", "String", "as_mut_str"];
119121
pub const STRING_AS_STR: [&str; 4] = ["alloc", "string", "String", "as_str"];
120122
pub const STRING_NEW: [&str; 4] = ["alloc", "string", "String", "new"];
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
### What it does
2+
3+
Checks for jumps to the start of a stream that implements `Seek`
4+
and uses the `seek` method providing `Start` as parameter.
5+
6+
### Why is this bad?
7+
8+
Readability. There is a specific method that was implemented for
9+
this exact scenario.
10+
11+
### Example
12+
```
13+
fn foo<T: io::Seek>(t: &mut T) {
14+
t.seek(io::SeekFrom::Start(0));
15+
}
16+
```
17+
Use instead:
18+
```
19+
fn foo<T: io::Seek>(t: &mut T) {
20+
t.rewind();
21+
}
22+
```
Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
// run-rustfix
2+
#![allow(unused)]
3+
#![feature(custom_inner_attributes)]
4+
#![warn(clippy::seek_to_start_instead_of_rewind)]
5+
6+
use std::fs::OpenOptions;
7+
use std::io::{Read, Seek, SeekFrom, Write};
8+
9+
struct StructWithSeekMethod {}
10+
11+
impl StructWithSeekMethod {
12+
fn seek(&mut self, from: SeekFrom) {}
13+
}
14+
15+
trait MySeekTrait {
16+
fn seek(&mut self, from: SeekFrom) {}
17+
}
18+
19+
struct StructWithSeekTrait {}
20+
impl MySeekTrait for StructWithSeekTrait {}
21+
22+
// This should NOT trigger clippy warning because
23+
// StructWithSeekMethod does not implement std::io::Seek;
24+
fn seek_to_start_false_method(t: &mut StructWithSeekMethod) {
25+
t.seek(SeekFrom::Start(0));
26+
}
27+
28+
// This should NOT trigger clippy warning because
29+
// StructWithSeekMethod does not implement std::io::Seek;
30+
fn seek_to_start_method_owned_false<T>(mut t: StructWithSeekMethod) {
31+
t.seek(SeekFrom::Start(0));
32+
}
33+
34+
// This should NOT trigger clippy warning because
35+
// StructWithSeekMethod does not implement std::io::Seek;
36+
fn seek_to_start_false_trait(t: &mut StructWithSeekTrait) {
37+
t.seek(SeekFrom::Start(0));
38+
}
39+
40+
// This should NOT trigger clippy warning because
41+
// StructWithSeekMethod does not implement std::io::Seek;
42+
fn seek_to_start_false_trait_owned<T>(mut t: StructWithSeekTrait) {
43+
t.seek(SeekFrom::Start(0));
44+
}
45+
46+
// This should NOT trigger clippy warning because
47+
// StructWithSeekMethod does not implement std::io::Seek;
48+
fn seek_to_start_false_trait_bound<T: MySeekTrait>(t: &mut T) {
49+
t.seek(SeekFrom::Start(0));
50+
}
51+
52+
// This should trigger clippy warning
53+
fn seek_to_start<T: Seek>(t: &mut T) {
54+
t.rewind();
55+
}
56+
57+
// This should trigger clippy warning
58+
fn owned_seek_to_start<T: Seek>(mut t: T) {
59+
t.rewind();
60+
}
61+
62+
// This should NOT trigger clippy warning because
63+
// it does not seek to start
64+
fn seek_to_5<T: Seek>(t: &mut T) {
65+
t.seek(SeekFrom::Start(5));
66+
}
67+
68+
// This should NOT trigger clippy warning because
69+
// it does not seek to start
70+
fn seek_to_end<T: Seek>(t: &mut T) {
71+
t.seek(SeekFrom::End(0));
72+
}
73+
74+
fn main() {
75+
let mut f = OpenOptions::new()
76+
.write(true)
77+
.read(true)
78+
.create(true)
79+
.open("foo.txt")
80+
.unwrap();
81+
82+
let mut my_struct_trait = StructWithSeekTrait {};
83+
seek_to_start_false_trait_bound(&mut my_struct_trait);
84+
85+
let hello = "Hello!\n";
86+
write!(f, "{hello}").unwrap();
87+
seek_to_5(&mut f);
88+
seek_to_end(&mut f);
89+
seek_to_start(&mut f);
90+
91+
let mut buf = String::new();
92+
f.read_to_string(&mut buf).unwrap();
93+
94+
assert_eq!(&buf, hello);
95+
}
96+
97+
fn msrv_1_54() {
98+
#![clippy::msrv = "1.54"]
99+
100+
let mut f = OpenOptions::new()
101+
.write(true)
102+
.read(true)
103+
.create(true)
104+
.open("foo.txt")
105+
.unwrap();
106+
107+
let hello = "Hello!\n";
108+
write!(f, "{hello}").unwrap();
109+
110+
f.seek(SeekFrom::Start(0));
111+
112+
let mut buf = String::new();
113+
f.read_to_string(&mut buf).unwrap();
114+
115+
assert_eq!(&buf, hello);
116+
}
117+
118+
fn msrv_1_55() {
119+
#![clippy::msrv = "1.55"]
120+
121+
let mut f = OpenOptions::new()
122+
.write(true)
123+
.read(true)
124+
.create(true)
125+
.open("foo.txt")
126+
.unwrap();
127+
128+
let hello = "Hello!\n";
129+
write!(f, "{hello}").unwrap();
130+
131+
f.rewind();
132+
133+
let mut buf = String::new();
134+
f.read_to_string(&mut buf).unwrap();
135+
136+
assert_eq!(&buf, hello);
137+
}

0 commit comments

Comments
 (0)