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