Skip to content

Commit 6601d85

Browse files
committed
Flag bufreader.lines().filter_map(Result::ok) as suspicious
1 parent 799732c commit 6601d85

File tree

8 files changed

+215
-0
lines changed

8 files changed

+215
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4647,6 +4647,7 @@ Released 2018-09-13
46474647
[`let_underscore_untyped`]: https://rust-lang.github.io/rust-clippy/master/index.html#let_underscore_untyped
46484648
[`let_unit_value`]: https://rust-lang.github.io/rust-clippy/master/index.html#let_unit_value
46494649
[`let_with_type_underscore`]: https://rust-lang.github.io/rust-clippy/master/index.html#let_with_type_underscore
4650+
[`lines_filter_map_ok`]: https://rust-lang.github.io/rust-clippy/master/index.html#lines_filter_map_ok
46504651
[`linkedlist`]: https://rust-lang.github.io/rust-clippy/master/index.html#linkedlist
46514652
[`logic_bug`]: https://rust-lang.github.io/rust-clippy/master/index.html#logic_bug
46524653
[`lossy_float_literal`]: https://rust-lang.github.io/rust-clippy/master/index.html#lossy_float_literal

clippy_lints/src/declared_lints.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -232,6 +232,7 @@ pub(crate) static LINTS: &[&crate::LintInfo] = &[
232232
crate::let_with_type_underscore::LET_WITH_TYPE_UNDERSCORE_INFO,
233233
crate::lifetimes::EXTRA_UNUSED_LIFETIMES_INFO,
234234
crate::lifetimes::NEEDLESS_LIFETIMES_INFO,
235+
crate::lines_filter_map_ok::LINES_FILTER_MAP_OK_INFO,
235236
crate::literal_representation::DECIMAL_LITERAL_REPRESENTATION_INFO,
236237
crate::literal_representation::INCONSISTENT_DIGIT_GROUPING_INFO,
237238
crate::literal_representation::LARGE_DIGIT_GROUPS_INFO,

clippy_lints/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,7 @@ mod let_if_seq;
171171
mod let_underscore;
172172
mod let_with_type_underscore;
173173
mod lifetimes;
174+
mod lines_filter_map_ok;
174175
mod literal_representation;
175176
mod loops;
176177
mod macro_use;
@@ -949,6 +950,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
949950
avoid_breaking_exported_api,
950951
))
951952
});
953+
store.register_late_pass(|_| Box::new(lines_filter_map_ok::LinesFilterMapOk));
952954
// add lints here, do not remove this comment, it's used in `new_lint`
953955
}
954956

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
use clippy_utils::{
2+
diagnostics::span_lint_and_then, is_diag_item_method, is_trait_method, match_def_path, path_to_local_id, paths,
3+
ty::match_type,
4+
};
5+
use rustc_errors::Applicability;
6+
use rustc_hir::{Body, Closure, Expr, ExprKind};
7+
use rustc_lint::{LateContext, LateLintPass};
8+
use rustc_session::{declare_lint_pass, declare_tool_lint};
9+
use rustc_span::sym;
10+
11+
declare_clippy_lint! {
12+
/// ### What it does
13+
/// Detect uses of `lines.filter_map(Result::ok)` or `lines.flat_map(Result::ok)`
14+
/// when `lines` has type `std::io::Lines`.
15+
///
16+
/// ### Why is this bad?
17+
/// `Lines` instances might produce a never-ending stream of `Err`, in which case
18+
/// `filter_map(Result::ok)` will enter an infinite loop while waiting for an
19+
/// `Ok` variant. Calling `next()` once is sufficient to enter the infinite loop,
20+
/// even in the absence of explicit loops in the user code.
21+
///
22+
/// This situation can arise when working with user-provided paths. On some platforms,
23+
/// `std::fs::File::open(path)` might return `Ok(fs)` even when `path` is a directory,
24+
/// but any later attempt to read from `fs` will return an error.
25+
///
26+
/// ### Known problems
27+
/// This lint suggests replacing `filter_map()` or `flat_map()` applied to a `Lines`
28+
/// instance in all cases. There two cases where the suggestion might not be
29+
/// appropriate or necessary:
30+
///
31+
/// - If the `Lines` instance can never produce any error, or if an error is produced
32+
/// only once just before terminating the iterator, using `map_while()` is not
33+
/// necessary but will not do any harm.
34+
/// - If the `Lines` instance can produce intermittent errors then recover and produce
35+
/// successful results, using `map_while()` would stop at the first error.
36+
///
37+
/// ### Example
38+
/// ```rust
39+
/// # use std::{fs::File, io::{self, BufRead, BufReader}};
40+
/// # let _ = || -> io::Result<()> {
41+
/// let mut lines = BufReader::new(File::open("some-path")?).lines().filter_map(Result::ok);
42+
/// // If "some-path" points to a directory, the next statement never terminates:
43+
/// let first_line: Option<String> = lines.next();
44+
/// # Ok(()) };
45+
/// ```
46+
/// Use instead:
47+
/// ```rust
48+
/// # use std::{fs::File, io::{self, BufRead, BufReader}};
49+
/// # let _ = || -> io::Result<()> {
50+
/// let mut lines = BufReader::new(File::open("some-path")?).lines().map_while(Result::ok);
51+
/// let first_line: Option<String> = lines.next();
52+
/// # Ok(()) };
53+
/// ```
54+
#[clippy::version = "1.70.0"]
55+
pub LINES_FILTER_MAP_OK,
56+
suspicious,
57+
"filtering `std::io::Lines` with `filter_map()` or `flat_map()` might cause an infinite loop"
58+
}
59+
declare_lint_pass!(LinesFilterMapOk => [LINES_FILTER_MAP_OK]);
60+
61+
impl LateLintPass<'_> for LinesFilterMapOk {
62+
fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
63+
if let ExprKind::MethodCall(fm_method, fm_receiver, [fm_arg], fm_span) = expr.kind &&
64+
is_trait_method(cx, expr, sym::Iterator) &&
65+
(fm_method.ident.as_str() == "filter_map" || fm_method.ident.as_str() == "flat_map") &&
66+
match_type(cx, cx.typeck_results().expr_ty_adjusted(fm_receiver), &paths::STD_IO_LINES)
67+
{
68+
let lint = match &fm_arg.kind {
69+
// Detect `Result::ok`
70+
ExprKind::Path(qpath) =>
71+
cx.qpath_res(qpath, fm_arg.hir_id).opt_def_id().map(|did|
72+
match_def_path(cx, did, &paths::CORE_RESULT_OK_METHOD)).unwrap_or_default(),
73+
// Detect `|x| x.ok()`
74+
ExprKind::Closure(Closure { body, .. }) =>
75+
if let Body { params: [param], value, .. } = cx.tcx.hir().body(*body) &&
76+
let ExprKind::MethodCall(method, receiver, [], _) = value.kind &&
77+
path_to_local_id(receiver, param.pat.hir_id) &&
78+
let Some(method_did) = cx.typeck_results().type_dependent_def_id(value.hir_id)
79+
{
80+
is_diag_item_method(cx, method_did, sym::Result) && method.ident.as_str() == "ok"
81+
} else {
82+
false
83+
}
84+
_ => false,
85+
};
86+
if lint {
87+
span_lint_and_then(cx,
88+
LINES_FILTER_MAP_OK,
89+
fm_span,
90+
&format!("`{}()` will run forever if the iterator repeatedly produces an `Err`", fm_method.ident),
91+
|diag| {
92+
diag.span_note(
93+
fm_receiver.span,
94+
"this expression returning a `std::io::Lines` may produce an infinite number of `Err` in case of a read error");
95+
diag.span_suggestion(fm_span, "replace with", "map_while(Result::ok)", Applicability::MaybeIncorrect);
96+
});
97+
}
98+
}
99+
}
100+
}

clippy_utils/src/paths.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ pub const CLONE_TRAIT_METHOD: [&str; 4] = ["core", "clone", "Clone", "clone"];
2323
pub const CORE_ITER_CLONED: [&str; 6] = ["core", "iter", "traits", "iterator", "Iterator", "cloned"];
2424
pub const CORE_ITER_COPIED: [&str; 6] = ["core", "iter", "traits", "iterator", "Iterator", "copied"];
2525
pub const CORE_ITER_FILTER: [&str; 6] = ["core", "iter", "traits", "iterator", "Iterator", "filter"];
26+
pub const CORE_RESULT_OK_METHOD: [&str; 4] = ["core", "result", "Result", "ok"];
2627
pub const CSTRING_AS_C_STR: [&str; 5] = ["alloc", "ffi", "c_str", "CString", "as_c_str"];
2728
pub const DEFAULT_TRAIT_METHOD: [&str; 4] = ["core", "default", "Default", "default"];
2829
pub const DEREF_MUT_TRAIT_METHOD: [&str; 5] = ["core", "ops", "deref", "DerefMut", "deref_mut"];
@@ -113,6 +114,7 @@ pub const STDERR: [&str; 4] = ["std", "io", "stdio", "stderr"];
113114
pub const STDOUT: [&str; 4] = ["std", "io", "stdio", "stdout"];
114115
pub const CONVERT_IDENTITY: [&str; 3] = ["core", "convert", "identity"];
115116
pub const STD_FS_CREATE_DIR: [&str; 3] = ["std", "fs", "create_dir"];
117+
pub const STD_IO_LINES: [&str; 3] = ["std", "io", "Lines"];
116118
pub const STD_IO_SEEK: [&str; 3] = ["std", "io", "Seek"];
117119
pub const STD_IO_SEEK_FROM_CURRENT: [&str; 4] = ["std", "io", "SeekFrom", "Current"];
118120
pub const STD_IO_SEEKFROM_START: [&str; 4] = ["std", "io", "SeekFrom", "Start"];

tests/ui/lines_filter_map_ok.fixed

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// run-rustfix
2+
3+
#![allow(unused, clippy::map_identity)]
4+
#![warn(clippy::lines_filter_map_ok)]
5+
6+
use std::io::{self, BufRead, BufReader};
7+
8+
fn main() -> io::Result<()> {
9+
let f = std::fs::File::open("/")?;
10+
// Lint
11+
BufReader::new(f).lines().map_while(Result::ok).for_each(|_| ());
12+
// Lint
13+
let f = std::fs::File::open("/")?;
14+
BufReader::new(f).lines().map_while(Result::ok).for_each(|_| ());
15+
let s = "foo\nbar\nbaz\n";
16+
// Lint
17+
io::stdin().lines().map_while(Result::ok).for_each(|_| ());
18+
// Lint
19+
io::stdin().lines().map_while(Result::ok).for_each(|_| ());
20+
// Do not lint (not a `Lines` iterator)
21+
io::stdin()
22+
.lines()
23+
.map(std::convert::identity)
24+
.filter_map(|x| x.ok())
25+
.for_each(|_| ());
26+
// Do not lint (not a `Result::ok()` extractor)
27+
io::stdin().lines().filter_map(|x| x.err()).for_each(|_| ());
28+
Ok(())
29+
}

tests/ui/lines_filter_map_ok.rs

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// run-rustfix
2+
3+
#![allow(unused, clippy::map_identity)]
4+
#![warn(clippy::lines_filter_map_ok)]
5+
6+
use std::io::{self, BufRead, BufReader};
7+
8+
fn main() -> io::Result<()> {
9+
let f = std::fs::File::open("/")?;
10+
// Lint
11+
BufReader::new(f).lines().filter_map(Result::ok).for_each(|_| ());
12+
// Lint
13+
let f = std::fs::File::open("/")?;
14+
BufReader::new(f).lines().flat_map(Result::ok).for_each(|_| ());
15+
let s = "foo\nbar\nbaz\n";
16+
// Lint
17+
io::stdin().lines().filter_map(Result::ok).for_each(|_| ());
18+
// Lint
19+
io::stdin().lines().filter_map(|x| x.ok()).for_each(|_| ());
20+
// Do not lint (not a `Lines` iterator)
21+
io::stdin()
22+
.lines()
23+
.map(std::convert::identity)
24+
.filter_map(|x| x.ok())
25+
.for_each(|_| ());
26+
// Do not lint (not a `Result::ok()` extractor)
27+
io::stdin().lines().filter_map(|x| x.err()).for_each(|_| ());
28+
Ok(())
29+
}

tests/ui/lines_filter_map_ok.stderr

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
error: `filter_map()` will run forever if the iterator repeatedly produces an `Err`
2+
--> $DIR/lines_filter_map_ok.rs:11:31
3+
|
4+
LL | BufReader::new(f).lines().filter_map(Result::ok).for_each(|_| ());
5+
| ^^^^^^^^^^^^^^^^^^^^^^ help: replace with: `map_while(Result::ok)`
6+
|
7+
note: this expression returning a `std::io::Lines` may produce an infinite number of `Err` in case of a read error
8+
--> $DIR/lines_filter_map_ok.rs:11:5
9+
|
10+
LL | BufReader::new(f).lines().filter_map(Result::ok).for_each(|_| ());
11+
| ^^^^^^^^^^^^^^^^^^^^^^^^^
12+
= note: `-D clippy::lines-filter-map-ok` implied by `-D warnings`
13+
14+
error: `flat_map()` will run forever if the iterator repeatedly produces an `Err`
15+
--> $DIR/lines_filter_map_ok.rs:14:31
16+
|
17+
LL | BufReader::new(f).lines().flat_map(Result::ok).for_each(|_| ());
18+
| ^^^^^^^^^^^^^^^^^^^^ help: replace with: `map_while(Result::ok)`
19+
|
20+
note: this expression returning a `std::io::Lines` may produce an infinite number of `Err` in case of a read error
21+
--> $DIR/lines_filter_map_ok.rs:14:5
22+
|
23+
LL | BufReader::new(f).lines().flat_map(Result::ok).for_each(|_| ());
24+
| ^^^^^^^^^^^^^^^^^^^^^^^^^
25+
26+
error: `filter_map()` will run forever if the iterator repeatedly produces an `Err`
27+
--> $DIR/lines_filter_map_ok.rs:17:25
28+
|
29+
LL | io::stdin().lines().filter_map(Result::ok).for_each(|_| ());
30+
| ^^^^^^^^^^^^^^^^^^^^^^ help: replace with: `map_while(Result::ok)`
31+
|
32+
note: this expression returning a `std::io::Lines` may produce an infinite number of `Err` in case of a read error
33+
--> $DIR/lines_filter_map_ok.rs:17:5
34+
|
35+
LL | io::stdin().lines().filter_map(Result::ok).for_each(|_| ());
36+
| ^^^^^^^^^^^^^^^^^^^
37+
38+
error: `filter_map()` will run forever if the iterator repeatedly produces an `Err`
39+
--> $DIR/lines_filter_map_ok.rs:19:25
40+
|
41+
LL | io::stdin().lines().filter_map(|x| x.ok()).for_each(|_| ());
42+
| ^^^^^^^^^^^^^^^^^^^^^^ help: replace with: `map_while(Result::ok)`
43+
|
44+
note: this expression returning a `std::io::Lines` may produce an infinite number of `Err` in case of a read error
45+
--> $DIR/lines_filter_map_ok.rs:19:5
46+
|
47+
LL | io::stdin().lines().filter_map(|x| x.ok()).for_each(|_| ());
48+
| ^^^^^^^^^^^^^^^^^^^
49+
50+
error: aborting due to 4 previous errors
51+

0 commit comments

Comments
 (0)