Skip to content

Commit f19387d

Browse files
committed
add checking type
adding test patterns cargo dev bless fix comment add ; delete : fix suggestion code and update stderr in tests. use match_def_path when checking method name
1 parent df1ec91 commit f19387d

File tree

5 files changed

+109
-29
lines changed

5 files changed

+109
-29
lines changed

clippy_lints/src/bytes_count_to_len.rs

+29-13
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,14 @@
1-
use clippy_utils::diagnostics::span_lint_and_note;
1+
use clippy_utils::diagnostics::span_lint_and_sugg;
2+
use clippy_utils::source::snippet_with_applicability;
3+
use clippy_utils::ty::is_type_diagnostic_item;
4+
use clippy_utils::{match_def_path, paths};
25
use if_chain::if_chain;
6+
use rustc_errors::Applicability;
37
use rustc_hir as hir;
48
use rustc_lint::{LateContext, LateLintPass};
9+
use rustc_middle::ty;
510
use rustc_session::{declare_lint_pass, declare_tool_lint};
11+
use rustc_span::sym;
612

713
declare_clippy_lint! {
814
/// ### What it does
@@ -16,37 +22,47 @@ declare_clippy_lint! {
1622
/// ### Example
1723
/// ```rust
1824
/// "hello".bytes().count();
25+
/// String::from("hello").bytes().count();
1926
/// ```
2027
/// Use instead:
2128
/// ```rust
2229
/// "hello".len();
30+
/// String::from("hello").len();
2331
/// ```
24-
#[clippy::version = "1.60.0"]
32+
#[clippy::version = "1.62.0"]
2533
pub BYTES_COUNT_TO_LEN,
2634
complexity,
27-
"Using bytest().count() when len() performs the same functionality"
35+
"Using `bytes().count()` when `len()` performs the same functionality"
2836
}
2937

3038
declare_lint_pass!(BytesCountToLen => [BYTES_COUNT_TO_LEN]);
3139

3240
impl<'tcx> LateLintPass<'tcx> for BytesCountToLen {
3341
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
3442
if_chain! {
35-
//check for method call called "count"
36-
if let hir::ExprKind::MethodCall(count_path, count_args, _) = &expr.kind;
37-
if count_path.ident.name == rustc_span::sym::count;
38-
if let [bytes_expr] = &**count_args;
39-
//check for method call called "bytes" that was linked to "count"
40-
if let hir::ExprKind::MethodCall(bytes_path, _, _) = &bytes_expr.kind;
41-
if bytes_path.ident.name.as_str() == "bytes";
43+
if let hir::ExprKind::MethodCall(_, expr_args, _) = &expr.kind;
44+
if let Some(expr_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id);
45+
if match_def_path(cx, expr_def_id, &paths::ITER_COUNT);
46+
47+
if let [bytes_expr] = &**expr_args;
48+
if let hir::ExprKind::MethodCall(_, bytes_args, _) = &bytes_expr.kind;
49+
if let Some(bytes_def_id) = cx.typeck_results().type_dependent_def_id(bytes_expr.hir_id);
50+
if match_def_path(cx, bytes_def_id, &paths::STR_BYTES);
51+
52+
if let [str_expr] = &**bytes_args;
53+
let ty = cx.typeck_results().expr_ty(str_expr).peel_refs();
54+
55+
if is_type_diagnostic_item(cx, ty, sym::String) || ty.kind() == &ty::Str;
4256
then {
43-
span_lint_and_note(
57+
let mut applicability = Applicability::MachineApplicable;
58+
span_lint_and_sugg(
4459
cx,
4560
BYTES_COUNT_TO_LEN,
4661
expr.span,
4762
"using long and hard to read `.bytes().count()`",
48-
None,
49-
"`.len()` achieves same functionality"
63+
"consider calling `.len()` instead",
64+
format!("{}.len()", snippet_with_applicability(cx, str_expr.span, "..", &mut applicability)),
65+
applicability
5066
);
5167
}
5268
};

clippy_utils/src/paths.rs

+2
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ pub const IO_READ: [&str; 3] = ["std", "io", "Read"];
6161
pub const IO_WRITE: [&str; 3] = ["std", "io", "Write"];
6262
pub const IPADDR_V4: [&str; 5] = ["std", "net", "ip", "IpAddr", "V4"];
6363
pub const IPADDR_V6: [&str; 5] = ["std", "net", "ip", "IpAddr", "V6"];
64+
pub const ITER_COUNT: [&str; 6] = ["core", "iter", "traits", "iterator", "Iterator", "count"];
6465
pub const ITER_REPEAT: [&str; 5] = ["core", "iter", "sources", "repeat", "repeat"];
6566
#[allow(clippy::invalid_paths)] // internal lints do not know about all external crates
6667
pub const ITERTOOLS_NEXT_TUPLE: [&str; 3] = ["itertools", "Itertools", "next_tuple"];
@@ -149,6 +150,7 @@ pub const STD_FS_CREATE_DIR: [&str; 3] = ["std", "fs", "create_dir"];
149150
pub const STRING_AS_MUT_STR: [&str; 4] = ["alloc", "string", "String", "as_mut_str"];
150151
pub const STRING_AS_STR: [&str; 4] = ["alloc", "string", "String", "as_str"];
151152
pub const STRING_NEW: [&str; 4] = ["alloc", "string", "String", "new"];
153+
pub const STR_BYTES: [&str; 4] = ["core", "str", "<impl str>", "bytes"];
152154
pub const STR_ENDS_WITH: [&str; 4] = ["core", "str", "<impl str>", "ends_with"];
153155
pub const STR_FROM_UTF8: [&str; 4] = ["core", "str", "converts", "from_utf8"];
154156
pub const STR_LEN: [&str; 4] = ["core", "str", "<impl str>", "len"];

tests/ui/bytes_count_to_len.fixed

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// run-rustfix
2+
#![warn(clippy::bytes_count_to_len)]
3+
use std::fs::File;
4+
use std::io::Read;
5+
6+
fn main() {
7+
// should fix, because type is String
8+
let _ = String::from("foo").len();
9+
10+
let s1 = String::from("foo");
11+
let _ = s1.len();
12+
13+
// should fix, because type is &str
14+
let _ = "foo".len();
15+
16+
let s2 = "foo";
17+
let _ = s2.len();
18+
19+
// make sure using count() normally doesn't trigger warning
20+
let vector = [0, 1, 2];
21+
let _ = vector.iter().count();
22+
23+
// The type is slice, so should not fix
24+
let _ = &[1, 2, 3].bytes().count();
25+
26+
let bytes: &[u8] = &[1, 2, 3];
27+
bytes.bytes().count();
28+
29+
// The type is File, so should not fix
30+
let _ = File::open("foobar").unwrap().bytes().count();
31+
32+
let f = File::open("foobar").unwrap();
33+
let _ = f.bytes().count();
34+
}

tests/ui/bytes_count_to_len.rs

+26-7
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,34 @@
1+
// run-rustfix
12
#![warn(clippy::bytes_count_to_len)]
3+
use std::fs::File;
4+
use std::io::Read;
25

36
fn main() {
4-
let s1 = String::from("world");
7+
// should fix, because type is String
8+
let _ = String::from("foo").bytes().count();
59

6-
//test warning against a string literal
7-
"hello".bytes().count();
10+
let s1 = String::from("foo");
11+
let _ = s1.bytes().count();
812

9-
//test warning against a string variable
10-
s1.bytes().count();
13+
// should fix, because type is &str
14+
let _ = "foo".bytes().count();
1115

12-
//make sure using count() normally doesn't trigger warning
16+
let s2 = "foo";
17+
let _ = s2.bytes().count();
18+
19+
// make sure using count() normally doesn't trigger warning
1320
let vector = [0, 1, 2];
14-
let size = vector.iter().count();
21+
let _ = vector.iter().count();
22+
23+
// The type is slice, so should not fix
24+
let _ = &[1, 2, 3].bytes().count();
25+
26+
let bytes: &[u8] = &[1, 2, 3];
27+
bytes.bytes().count();
28+
29+
// The type is File, so should not fix
30+
let _ = File::open("foobar").unwrap().bytes().count();
31+
32+
let f = File::open("foobar").unwrap();
33+
let _ = f.bytes().count();
1534
}

tests/ui/bytes_count_to_len.stderr

+18-9
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,28 @@
11
error: using long and hard to read `.bytes().count()`
2-
--> $DIR/bytes_count_to_len.rs:7:5
2+
--> $DIR/bytes_count_to_len.rs:8:13
33
|
4-
LL | "hello".bytes().count();
5-
| ^^^^^^^^^^^^^^^^^^^^^^^
4+
LL | let _ = String::from("foo").bytes().count();
5+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider calling `.len()` instead: `String::from("foo").len()`
66
|
77
= note: `-D clippy::bytes-count-to-len` implied by `-D warnings`
8-
= note: `.len()` achieves same functionality
98

109
error: using long and hard to read `.bytes().count()`
11-
--> $DIR/bytes_count_to_len.rs:10:5
10+
--> $DIR/bytes_count_to_len.rs:11:13
1211
|
13-
LL | s1.bytes().count();
14-
| ^^^^^^^^^^^^^^^^^^
12+
LL | let _ = s1.bytes().count();
13+
| ^^^^^^^^^^^^^^^^^^ help: consider calling `.len()` instead: `s1.len()`
14+
15+
error: using long and hard to read `.bytes().count()`
16+
--> $DIR/bytes_count_to_len.rs:14:13
17+
|
18+
LL | let _ = "foo".bytes().count();
19+
| ^^^^^^^^^^^^^^^^^^^^^ help: consider calling `.len()` instead: `"foo".len()`
20+
21+
error: using long and hard to read `.bytes().count()`
22+
--> $DIR/bytes_count_to_len.rs:17:13
1523
|
16-
= note: `.len()` achieves same functionality
24+
LL | let _ = s2.bytes().count();
25+
| ^^^^^^^^^^^^^^^^^^ help: consider calling `.len()` instead: `s2.len()`
1726

18-
error: aborting due to 2 previous errors
27+
error: aborting due to 4 previous errors
1928

0 commit comments

Comments
 (0)