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