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