|
1 | | -use clippy_config::Conf; |
2 | 1 | use clippy_utils::diagnostics::span_lint_and_then; |
3 | 2 | use clippy_utils::msrvs::{self, Msrv}; |
4 | 3 | use clippy_utils::res::{MaybeDef, MaybeResPath, MaybeTypeckRes}; |
5 | 4 | use clippy_utils::sym; |
6 | 5 | use rustc_errors::Applicability; |
7 | 6 | use rustc_hir::{Body, Closure, Expr, ExprKind}; |
8 | | -use rustc_lint::{LateContext, LateLintPass}; |
9 | | -use rustc_session::impl_lint_pass; |
10 | | -use rustc_span::Symbol; |
| 7 | +use rustc_lint::LateContext; |
| 8 | +use rustc_span::Span; |
11 | 9 |
|
12 | | -pub struct LinesFilterMapOk { |
13 | | - msrv: Msrv, |
14 | | -} |
| 10 | +use super::LINES_FILTER_MAP_OK; |
15 | 11 |
|
16 | | -impl LinesFilterMapOk { |
17 | | - pub fn new(conf: &Conf) -> Self { |
18 | | - Self { msrv: conf.msrv } |
| 12 | +pub(super) fn check_flatten(cx: &LateContext<'_>, expr: &Expr<'_>, recv: &Expr<'_>, call_span: Span, msrv: Msrv) { |
| 13 | + if cx.ty_based_def(expr).opt_parent(cx).is_diag_item(cx, sym::Iterator) |
| 14 | + && cx |
| 15 | + .typeck_results() |
| 16 | + .expr_ty_adjusted(recv) |
| 17 | + .is_diag_item(cx, sym::IoLines) |
| 18 | + && msrv.meets(cx, msrvs::MAP_WHILE) |
| 19 | + { |
| 20 | + emit(cx, recv, "flatten", call_span); |
19 | 21 | } |
20 | 22 | } |
21 | 23 |
|
22 | | -declare_clippy_lint! { |
23 | | - /// ### What it does |
24 | | - /// Checks for usage of `lines.filter_map(Result::ok)` or `lines.flat_map(Result::ok)` |
25 | | - /// when `lines` has type `std::io::Lines`. |
26 | | - /// |
27 | | - /// ### Why is this bad? |
28 | | - /// `Lines` instances might produce a never-ending stream of `Err`, in which case |
29 | | - /// `filter_map(Result::ok)` will enter an infinite loop while waiting for an |
30 | | - /// `Ok` variant. Calling `next()` once is sufficient to enter the infinite loop, |
31 | | - /// even in the absence of explicit loops in the user code. |
32 | | - /// |
33 | | - /// This situation can arise when working with user-provided paths. On some platforms, |
34 | | - /// `std::fs::File::open(path)` might return `Ok(fs)` even when `path` is a directory, |
35 | | - /// but any later attempt to read from `fs` will return an error. |
36 | | - /// |
37 | | - /// ### Known problems |
38 | | - /// This lint suggests replacing `filter_map()` or `flat_map()` applied to a `Lines` |
39 | | - /// instance in all cases. There are two cases where the suggestion might not be |
40 | | - /// appropriate or necessary: |
41 | | - /// |
42 | | - /// - If the `Lines` instance can never produce any error, or if an error is produced |
43 | | - /// only once just before terminating the iterator, using `map_while()` is not |
44 | | - /// necessary but will not do any harm. |
45 | | - /// - If the `Lines` instance can produce intermittent errors then recover and produce |
46 | | - /// successful results, using `map_while()` would stop at the first error. |
47 | | - /// |
48 | | - /// ### Example |
49 | | - /// ```no_run |
50 | | - /// # use std::{fs::File, io::{self, BufRead, BufReader}}; |
51 | | - /// # let _ = || -> io::Result<()> { |
52 | | - /// let mut lines = BufReader::new(File::open("some-path")?).lines().filter_map(Result::ok); |
53 | | - /// // If "some-path" points to a directory, the next statement never terminates: |
54 | | - /// let first_line: Option<String> = lines.next(); |
55 | | - /// # Ok(()) }; |
56 | | - /// ``` |
57 | | - /// Use instead: |
58 | | - /// ```no_run |
59 | | - /// # use std::{fs::File, io::{self, BufRead, BufReader}}; |
60 | | - /// # let _ = || -> io::Result<()> { |
61 | | - /// let mut lines = BufReader::new(File::open("some-path")?).lines().map_while(Result::ok); |
62 | | - /// let first_line: Option<String> = lines.next(); |
63 | | - /// # Ok(()) }; |
64 | | - /// ``` |
65 | | - #[clippy::version = "1.70.0"] |
66 | | - pub LINES_FILTER_MAP_OK, |
67 | | - suspicious, |
68 | | - "filtering `std::io::Lines` with `filter_map()`, `flat_map()`, or `flatten()` might cause an infinite loop" |
69 | | -} |
70 | | - |
71 | | -impl_lint_pass!(LinesFilterMapOk => [LINES_FILTER_MAP_OK]); |
72 | | - |
73 | | -impl LateLintPass<'_> for LinesFilterMapOk { |
74 | | - fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) { |
75 | | - if let ExprKind::MethodCall(fm_method, fm_receiver, fm_args, fm_span) = expr.kind |
76 | | - && cx.ty_based_def(expr).opt_parent(cx).is_diag_item(cx, sym::Iterator) |
77 | | - && let fm_method_name = fm_method.ident.name |
78 | | - && matches!(fm_method_name, sym::filter_map | sym::flat_map | sym::flatten) |
79 | | - && cx |
80 | | - .typeck_results() |
81 | | - .expr_ty_adjusted(fm_receiver) |
82 | | - .is_diag_item(cx, sym::IoLines) |
83 | | - && should_lint(cx, fm_args, fm_method_name) |
84 | | - && self.msrv.meets(cx, msrvs::MAP_WHILE) |
85 | | - { |
86 | | - span_lint_and_then( |
87 | | - cx, |
88 | | - LINES_FILTER_MAP_OK, |
89 | | - fm_span, |
90 | | - format!("`{fm_method_name}()` will run forever if the iterator repeatedly produces an `Err`"), |
91 | | - |diag| { |
92 | | - diag.span_note( |
93 | | - fm_receiver.span, |
94 | | - "this expression returning a `std::io::Lines` may produce \ |
95 | | - an infinite number of `Err` in case of a read error", |
96 | | - ); |
97 | | - diag.span_suggestion( |
98 | | - fm_span, |
99 | | - "replace with", |
100 | | - "map_while(Result::ok)", |
101 | | - Applicability::MaybeIncorrect, |
102 | | - ); |
103 | | - }, |
104 | | - ); |
| 24 | +pub(super) fn check_filter_or_flat_map( |
| 25 | + cx: &LateContext<'_>, |
| 26 | + expr: &Expr<'_>, |
| 27 | + recv: &Expr<'_>, |
| 28 | + method_name: &'static str, |
| 29 | + method_arg: &Expr<'_>, |
| 30 | + call_span: Span, |
| 31 | + msrv: Msrv, |
| 32 | +) { |
| 33 | + if cx.ty_based_def(expr).opt_parent(cx).is_diag_item(cx, sym::Iterator) |
| 34 | + && cx |
| 35 | + .typeck_results() |
| 36 | + .expr_ty_adjusted(recv) |
| 37 | + .is_diag_item(cx, sym::IoLines) |
| 38 | + && match method_arg.kind { |
| 39 | + // Detect `Result::ok` |
| 40 | + ExprKind::Path(ref qpath) => cx |
| 41 | + .qpath_res(qpath, method_arg.hir_id) |
| 42 | + .is_diag_item(cx, sym::result_ok_method), |
| 43 | + // Detect `|x| x.ok()` |
| 44 | + ExprKind::Closure(&Closure { body, .. }) => { |
| 45 | + if let Body { |
| 46 | + params: [param], value, .. |
| 47 | + } = cx.tcx.hir_body(body) |
| 48 | + && let ExprKind::MethodCall(method, receiver, [], _) = value.kind |
| 49 | + { |
| 50 | + method.ident.name == sym::ok |
| 51 | + && receiver.res_local_id() == Some(param.pat.hir_id) |
| 52 | + && cx.ty_based_def(*value).is_diag_item(cx, sym::result_ok_method) |
| 53 | + } else { |
| 54 | + false |
| 55 | + } |
| 56 | + }, |
| 57 | + _ => false, |
105 | 58 | } |
| 59 | + && msrv.meets(cx, msrvs::MAP_WHILE) |
| 60 | + { |
| 61 | + emit(cx, recv, method_name, call_span); |
106 | 62 | } |
107 | 63 | } |
108 | 64 |
|
109 | | -fn should_lint(cx: &LateContext<'_>, args: &[Expr<'_>], method_name: Symbol) -> bool { |
110 | | - match args { |
111 | | - [] => method_name == sym::flatten, |
112 | | - [fm_arg] => { |
113 | | - match fm_arg.kind { |
114 | | - // Detect `Result::ok` |
115 | | - ExprKind::Path(ref qpath) => cx |
116 | | - .qpath_res(qpath, fm_arg.hir_id) |
117 | | - .is_diag_item(cx, sym::result_ok_method), |
118 | | - // Detect `|x| x.ok()` |
119 | | - ExprKind::Closure(&Closure { body, .. }) => { |
120 | | - if let Body { |
121 | | - params: [param], value, .. |
122 | | - } = cx.tcx.hir_body(body) |
123 | | - && let ExprKind::MethodCall(method, receiver, [], _) = value.kind |
124 | | - { |
125 | | - method.ident.name == sym::ok |
126 | | - && receiver.res_local_id() == Some(param.pat.hir_id) |
127 | | - && cx.ty_based_def(*value).is_diag_item(cx, sym::result_ok_method) |
128 | | - } else { |
129 | | - false |
130 | | - } |
131 | | - }, |
132 | | - _ => false, |
133 | | - } |
| 65 | +fn emit(cx: &LateContext<'_>, recv: &Expr<'_>, method_name: &'static str, call_span: Span) { |
| 66 | + span_lint_and_then( |
| 67 | + cx, |
| 68 | + LINES_FILTER_MAP_OK, |
| 69 | + call_span, |
| 70 | + format!("`{method_name}()` will run forever if the iterator repeatedly produces an `Err`"), |
| 71 | + |diag| { |
| 72 | + diag.span_note( |
| 73 | + recv.span, |
| 74 | + "this expression returning a `std::io::Lines` may produce \ |
| 75 | + an infinite number of `Err` in case of a read error", |
| 76 | + ); |
| 77 | + diag.span_suggestion( |
| 78 | + call_span, |
| 79 | + "replace with", |
| 80 | + "map_while(Result::ok)", |
| 81 | + Applicability::MaybeIncorrect, |
| 82 | + ); |
134 | 83 | }, |
135 | | - _ => false, |
136 | | - } |
| 84 | + ); |
137 | 85 | } |
0 commit comments