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;
15 use rustc_semver::RustcVersion;
16 use rustc_session::{declare_tool_lint, impl_lint_pass};
17 use rustc_span::source_map::Spanned;
20 declare_clippy_lint! {
22 /// Suggests using `strip_{prefix,suffix}` over `str::{starts,ends}_with` and slicing using
23 /// the pattern's length.
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.
31 /// **Known problems:**
37 /// let s = "hello, world!";
38 /// if s.starts_with("hello, ") {
39 /// assert_eq!(s["hello, ".len()..].to_uppercase(), "WORLD!");
44 /// let s = "hello, world!";
45 /// if let Some(end) = s.strip_prefix("hello, ") {
46 /// assert_eq!(end.to_uppercase(), "WORLD!");
51 "suggests using `strip_{prefix,suffix}` over `str::{starts,ends}_with` and slicing"
54 pub struct ManualStrip {
55 msrv: Option<RustcVersion>,
60 pub fn new(msrv: Option<RustcVersion>) -> Self {
65 impl_lint_pass!(ManualStrip => [MANUAL_STRIP]);
67 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
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) {
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;
85 let strip_kind = if match_def_path(cx, method_def_id, &paths::STR_STARTS_WITH) {
87 } else if match_def_path(cx, method_def_id, &paths::STR_ENDS_WITH) {
92 let target_res = cx.qpath_res(target_path, target_arg.hir_id);
93 if target_res == Res::Err {
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);
106 let strippings = find_stripping(cx, strip_kind, target_res, pattern, then);
107 if !strippings.is_empty() {
109 let kind_word = match strip_kind {
110 StripKind::Prefix => "prefix",
111 StripKind::Suffix => "suffix",
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));
119 &format!("try using the `strip_{}` method", kind_word),
121 format!("if let Some(<stripped>) = {}.strip_{}({}) ",
122 snippet(cx, target_arg.span, ".."),
124 snippet(cx, pattern.span, "..")))]
125 .into_iter().chain(strippings.into_iter().map(|span| (span, "<stripped>".into()))),
133 extract_msrv_attr!(LateContext);
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>> {
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);
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)?;
154 Constant::Str(value) => Some(value.len() as u128),
155 Constant::Char(value) => Some(value.len_utf8() as u128),
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, _),
167 constant_length(cx, pattern).map_or(false, |length| length == n)
169 len_arg(cx, expr).map_or(false, |arg| eq_expr_value(cx, pattern, arg))
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(),
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 {
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}`
193 fn find_stripping<'tcx>(
194 cx: &LateContext<'tcx>,
195 strip_kind: StripKind,
197 pattern: &'tcx Expr<'_>,
198 expr: &'tcx Expr<'_>,
200 struct StrippingFinder<'a, 'tcx> {
201 cx: &'a LateContext<'tcx>,
202 strip_kind: StripKind,
204 pattern: &'tcx Expr<'tcx>,
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
214 fn visit_expr(&mut self, ex: &'tcx Expr<'_>) {
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;
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);
230 (StripKind::Suffix, None, Some(end)) => {
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);
238 self.results.push(ex.span);
252 let mut finder = StrippingFinder {
259 walk_expr(&mut finder, expr);