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