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