]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/manual_strip.rs
Fix FN in `iter_cloned_collect` with a large array
[rust.git] / clippy_lints / src / manual_strip.rs
1 use crate::consts::{constant, Constant};
2 use clippy_utils::diagnostics::{multispan_sugg, span_lint_and_then};
3 use clippy_utils::source::snippet;
4 use clippy_utils::usage::mutated_variables;
5 use clippy_utils::{eq_expr_value, higher, match_def_path, meets_msrv, paths};
6 use if_chain::if_chain;
7 use rustc_ast::ast::LitKind;
8 use rustc_hir::def::Res;
9 use rustc_hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
10 use rustc_hir::BinOpKind;
11 use rustc_hir::{BorrowKind, Expr, ExprKind};
12 use rustc_lint::{LateContext, LateLintPass, LintContext};
13 use rustc_middle::hir::map::Map;
14 use rustc_middle::ty;
15 use rustc_semver::RustcVersion;
16 use rustc_session::{declare_tool_lint, impl_lint_pass};
17 use rustc_span::source_map::Spanned;
18 use rustc_span::Span;
19
20 const MANUAL_STRIP_MSRV: RustcVersion = RustcVersion::new(1, 45, 0);
21
22 declare_clippy_lint! {
23     /// **What it does:**
24     /// Suggests using `strip_{prefix,suffix}` over `str::{starts,ends}_with` and slicing using
25     /// the pattern's length.
26     ///
27     /// **Why is this bad?**
28     /// Using `str:strip_{prefix,suffix}` is safer and may have better performance as there is no
29     /// slicing which may panic and the compiler does not need to insert this panic code. It is
30     /// also sometimes more readable as it removes the need for duplicating or storing the pattern
31     /// used by `str::{starts,ends}_with` and in the slicing.
32     ///
33     /// **Known problems:**
34     /// None.
35     ///
36     /// **Example:**
37     ///
38     /// ```rust
39     /// let s = "hello, world!";
40     /// if s.starts_with("hello, ") {
41     ///     assert_eq!(s["hello, ".len()..].to_uppercase(), "WORLD!");
42     /// }
43     /// ```
44     /// Use instead:
45     /// ```rust
46     /// let s = "hello, world!";
47     /// if let Some(end) = s.strip_prefix("hello, ") {
48     ///     assert_eq!(end.to_uppercase(), "WORLD!");
49     /// }
50     /// ```
51     pub MANUAL_STRIP,
52     complexity,
53     "suggests using `strip_{prefix,suffix}` over `str::{starts,ends}_with` and slicing"
54 }
55
56 pub struct ManualStrip {
57     msrv: Option<RustcVersion>,
58 }
59
60 impl ManualStrip {
61     #[must_use]
62     pub fn new(msrv: Option<RustcVersion>) -> Self {
63         Self { msrv }
64     }
65 }
66
67 impl_lint_pass!(ManualStrip => [MANUAL_STRIP]);
68
69 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
70 enum StripKind {
71     Prefix,
72     Suffix,
73 }
74
75 impl<'tcx> LateLintPass<'tcx> for ManualStrip {
76     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
77         if !meets_msrv(self.msrv.as_ref(), &MANUAL_STRIP_MSRV) {
78             return;
79         }
80
81         if_chain! {
82             if let ExprKind::If(cond, then, _) = &expr.kind;
83             if let ExprKind::MethodCall(_, _, [target_arg, pattern], _) = cond.kind;
84             if let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(cond.hir_id);
85             if let ExprKind::Path(target_path) = &target_arg.kind;
86             then {
87                 let strip_kind = if match_def_path(cx, method_def_id, &paths::STR_STARTS_WITH) {
88                     StripKind::Prefix
89                 } else if match_def_path(cx, method_def_id, &paths::STR_ENDS_WITH) {
90                     StripKind::Suffix
91                 } else {
92                     return;
93                 };
94                 let target_res = cx.qpath_res(target_path, target_arg.hir_id);
95                 if target_res == Res::Err {
96                     return;
97                 };
98
99                 if_chain! {
100                     if let Res::Local(hir_id) = target_res;
101                     if let Some(used_mutably) = mutated_variables(then, cx);
102                     if used_mutably.contains(&hir_id);
103                     then {
104                         return;
105                     }
106                 }
107
108                 let strippings = find_stripping(cx, strip_kind, target_res, pattern, then);
109                 if !strippings.is_empty() {
110
111                     let kind_word = match strip_kind {
112                         StripKind::Prefix => "prefix",
113                         StripKind::Suffix => "suffix",
114                     };
115
116                     let test_span = expr.span.until(then.span);
117                     span_lint_and_then(cx, MANUAL_STRIP, strippings[0], &format!("stripping a {} manually", kind_word), |diag| {
118                         diag.span_note(test_span, &format!("the {} was tested here", kind_word));
119                         multispan_sugg(
120                             diag,
121                             &format!("try using the `strip_{}` method", kind_word),
122                             vec![(test_span,
123                                   format!("if let Some(<stripped>) = {}.strip_{}({}) ",
124                                           snippet(cx, target_arg.span, ".."),
125                                           kind_word,
126                                           snippet(cx, pattern.span, "..")))]
127                             .into_iter().chain(strippings.into_iter().map(|span| (span, "<stripped>".into()))),
128                         )
129                     });
130                 }
131             }
132         }
133     }
134
135     extract_msrv_attr!(LateContext);
136 }
137
138 // Returns `Some(arg)` if `expr` matches `arg.len()` and `None` otherwise.
139 fn len_arg<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<&'tcx Expr<'tcx>> {
140     if_chain! {
141         if let ExprKind::MethodCall(_, _, [arg], _) = expr.kind;
142         if let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id);
143         if match_def_path(cx, method_def_id, &paths::STR_LEN);
144         then {
145             Some(arg)
146         } else {
147             None
148         }
149     }
150 }
151
152 // Returns the length of the `expr` if it's a constant string or char.
153 fn constant_length(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<u128> {
154     let (value, _) = constant(cx, cx.typeck_results(), expr)?;
155     match value {
156         Constant::Str(value) => Some(value.len() as u128),
157         Constant::Char(value) => Some(value.len_utf8() as u128),
158         _ => None,
159     }
160 }
161
162 // Tests if `expr` equals the length of the pattern.
163 fn eq_pattern_length<'tcx>(cx: &LateContext<'tcx>, pattern: &Expr<'_>, expr: &'tcx Expr<'_>) -> bool {
164     if let ExprKind::Lit(Spanned {
165         node: LitKind::Int(n, _),
166         ..
167     }) = expr.kind
168     {
169         constant_length(cx, pattern).map_or(false, |length| length == n)
170     } else {
171         len_arg(cx, expr).map_or(false, |arg| eq_expr_value(cx, pattern, arg))
172     }
173 }
174
175 // Tests if `expr` is a `&str`.
176 fn is_ref_str(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
177     match cx.typeck_results().expr_ty_adjusted(expr).kind() {
178         ty::Ref(_, ty, _) => ty.is_str(),
179         _ => false,
180     }
181 }
182
183 // Removes the outer `AddrOf` expression if needed.
184 fn peel_ref<'a>(expr: &'a Expr<'_>) -> &'a Expr<'a> {
185     if let ExprKind::AddrOf(BorrowKind::Ref, _, unref) = &expr.kind {
186         unref
187     } else {
188         expr
189     }
190 }
191
192 // Find expressions where `target` is stripped using the length of `pattern`.
193 // We'll suggest replacing these expressions with the result of the `strip_{prefix,suffix}`
194 // method.
195 fn find_stripping<'tcx>(
196     cx: &LateContext<'tcx>,
197     strip_kind: StripKind,
198     target: Res,
199     pattern: &'tcx Expr<'_>,
200     expr: &'tcx Expr<'_>,
201 ) -> Vec<Span> {
202     struct StrippingFinder<'a, 'tcx> {
203         cx: &'a LateContext<'tcx>,
204         strip_kind: StripKind,
205         target: Res,
206         pattern: &'tcx Expr<'tcx>,
207         results: Vec<Span>,
208     }
209
210     impl<'a, 'tcx> Visitor<'tcx> for StrippingFinder<'a, 'tcx> {
211         type Map = Map<'tcx>;
212         fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
213             NestedVisitorMap::None
214         }
215
216         fn visit_expr(&mut self, ex: &'tcx Expr<'_>) {
217             if_chain! {
218                 if is_ref_str(self.cx, ex);
219                 let unref = peel_ref(ex);
220                 if let ExprKind::Index(indexed, index) = &unref.kind;
221                 if let Some(higher::Range { start, end, .. }) = higher::range(index);
222                 if let ExprKind::Path(path) = &indexed.kind;
223                 if self.cx.qpath_res(path, ex.hir_id) == self.target;
224                 then {
225                     match (self.strip_kind, start, end) {
226                         (StripKind::Prefix, Some(start), None) => {
227                             if eq_pattern_length(self.cx, self.pattern, start) {
228                                 self.results.push(ex.span);
229                                 return;
230                             }
231                         },
232                         (StripKind::Suffix, None, Some(end)) => {
233                             if_chain! {
234                                 if let ExprKind::Binary(Spanned { node: BinOpKind::Sub, .. }, left, right) = end.kind;
235                                 if let Some(left_arg) = len_arg(self.cx, left);
236                                 if let ExprKind::Path(left_path) = &left_arg.kind;
237                                 if self.cx.qpath_res(left_path, left_arg.hir_id) == self.target;
238                                 if eq_pattern_length(self.cx, self.pattern, right);
239                                 then {
240                                     self.results.push(ex.span);
241                                     return;
242                                 }
243                             }
244                         },
245                         _ => {}
246                     }
247                 }
248             }
249
250             walk_expr(self, ex);
251         }
252     }
253
254     let mut finder = StrippingFinder {
255         cx,
256         strip_kind,
257         target,
258         pattern,
259         results: vec![],
260     };
261     walk_expr(&mut finder, expr);
262     finder.results
263 }