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