2021-06-03 01:41:37 -05:00
|
|
|
use clippy_utils::consts::{constant, Constant};
|
2021-03-25 13:29:11 -05:00
|
|
|
use clippy_utils::diagnostics::{multispan_sugg, span_lint_and_then};
|
2022-12-01 11:29:38 -06:00
|
|
|
use clippy_utils::msrvs::{self, Msrv};
|
2021-03-25 13:29:11 -05:00
|
|
|
use clippy_utils::source::snippet;
|
|
|
|
use clippy_utils::usage::mutated_variables;
|
2022-12-01 11:29:38 -06:00
|
|
|
use clippy_utils::{eq_expr_value, higher, match_def_path, paths};
|
2020-09-24 07:49:22 -05:00
|
|
|
use if_chain::if_chain;
|
|
|
|
use rustc_ast::ast::LitKind;
|
|
|
|
use rustc_hir::def::Res;
|
2022-01-15 16:07:52 -06:00
|
|
|
use rustc_hir::intravisit::{walk_expr, Visitor};
|
2023-07-17 03:19:29 -05:00
|
|
|
use rustc_hir::{BinOpKind, BorrowKind, Expr, ExprKind};
|
2021-12-04 09:09:15 -06:00
|
|
|
use rustc_lint::{LateContext, LateLintPass};
|
2020-09-24 07:49:22 -05:00
|
|
|
use rustc_middle::ty;
|
2020-12-06 08:01:03 -06:00
|
|
|
use rustc_session::{declare_tool_lint, impl_lint_pass};
|
2020-09-24 07:49:22 -05:00
|
|
|
use rustc_span::source_map::Spanned;
|
|
|
|
use rustc_span::Span;
|
|
|
|
|
|
|
|
declare_clippy_lint! {
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### What it does
|
2020-09-24 07:49:22 -05:00
|
|
|
/// Suggests using `strip_{prefix,suffix}` over `str::{starts,ends}_with` and slicing using
|
|
|
|
/// the pattern's length.
|
|
|
|
///
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### Why is this bad?
|
2020-09-24 07:49:22 -05:00
|
|
|
/// Using `str:strip_{prefix,suffix}` is safer and may have better performance as there is no
|
|
|
|
/// slicing which may panic and the compiler does not need to insert this panic code. It is
|
|
|
|
/// also sometimes more readable as it removes the need for duplicating or storing the pattern
|
|
|
|
/// used by `str::{starts,ends}_with` and in the slicing.
|
|
|
|
///
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### Example
|
2023-10-23 08:49:18 -05:00
|
|
|
/// ```no_run
|
2020-09-24 07:49:22 -05:00
|
|
|
/// let s = "hello, world!";
|
|
|
|
/// if s.starts_with("hello, ") {
|
|
|
|
/// assert_eq!(s["hello, ".len()..].to_uppercase(), "WORLD!");
|
|
|
|
/// }
|
|
|
|
/// ```
|
|
|
|
/// Use instead:
|
2023-10-23 08:49:18 -05:00
|
|
|
/// ```no_run
|
2020-09-24 07:49:22 -05:00
|
|
|
/// let s = "hello, world!";
|
|
|
|
/// if let Some(end) = s.strip_prefix("hello, ") {
|
|
|
|
/// assert_eq!(end.to_uppercase(), "WORLD!");
|
|
|
|
/// }
|
|
|
|
/// ```
|
2021-12-06 05:33:31 -06:00
|
|
|
#[clippy::version = "1.48.0"]
|
2020-09-24 07:49:22 -05:00
|
|
|
pub MANUAL_STRIP,
|
|
|
|
complexity,
|
|
|
|
"suggests using `strip_{prefix,suffix}` over `str::{starts,ends}_with` and slicing"
|
|
|
|
}
|
|
|
|
|
2020-12-06 08:01:03 -06:00
|
|
|
pub struct ManualStrip {
|
2022-12-01 11:29:38 -06:00
|
|
|
msrv: Msrv,
|
2020-12-06 08:01:03 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
impl ManualStrip {
|
|
|
|
#[must_use]
|
2022-12-01 11:29:38 -06:00
|
|
|
pub fn new(msrv: Msrv) -> Self {
|
2020-12-06 08:01:03 -06:00
|
|
|
Self { msrv }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl_lint_pass!(ManualStrip => [MANUAL_STRIP]);
|
2020-09-24 07:49:22 -05:00
|
|
|
|
|
|
|
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
|
|
|
enum StripKind {
|
|
|
|
Prefix,
|
|
|
|
Suffix,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'tcx> LateLintPass<'tcx> for ManualStrip {
|
|
|
|
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
|
2022-12-01 11:29:38 -06:00
|
|
|
if !self.msrv.meets(msrvs::STR_STRIP_PREFIX) {
|
2020-12-06 08:01:03 -06:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2020-09-24 07:49:22 -05:00
|
|
|
if_chain! {
|
2021-08-08 09:49:13 -05:00
|
|
|
if let Some(higher::If { cond, then, .. }) = higher::If::hir(expr);
|
2022-09-01 04:43:35 -05:00
|
|
|
if let ExprKind::MethodCall(_, target_arg, [pattern], _) = cond.kind;
|
2020-09-24 07:49:22 -05:00
|
|
|
if let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(cond.hir_id);
|
|
|
|
if let ExprKind::Path(target_path) = &target_arg.kind;
|
|
|
|
then {
|
|
|
|
let strip_kind = if match_def_path(cx, method_def_id, &paths::STR_STARTS_WITH) {
|
|
|
|
StripKind::Prefix
|
|
|
|
} else if match_def_path(cx, method_def_id, &paths::STR_ENDS_WITH) {
|
|
|
|
StripKind::Suffix
|
|
|
|
} else {
|
|
|
|
return;
|
|
|
|
};
|
2021-04-08 10:50:13 -05:00
|
|
|
let target_res = cx.qpath_res(target_path, target_arg.hir_id);
|
2020-09-24 07:49:22 -05:00
|
|
|
if target_res == Res::Err {
|
|
|
|
return;
|
|
|
|
};
|
|
|
|
|
|
|
|
if_chain! {
|
|
|
|
if let Res::Local(hir_id) = target_res;
|
|
|
|
if let Some(used_mutably) = mutated_variables(then, cx);
|
|
|
|
if used_mutably.contains(&hir_id);
|
|
|
|
then {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
let strippings = find_stripping(cx, strip_kind, target_res, pattern, then);
|
|
|
|
if !strippings.is_empty() {
|
|
|
|
|
|
|
|
let kind_word = match strip_kind {
|
|
|
|
StripKind::Prefix => "prefix",
|
|
|
|
StripKind::Suffix => "suffix",
|
|
|
|
};
|
|
|
|
|
|
|
|
let test_span = expr.span.until(then.span);
|
2022-10-06 02:44:38 -05:00
|
|
|
span_lint_and_then(cx, MANUAL_STRIP, strippings[0], &format!("stripping a {kind_word} manually"), |diag| {
|
2022-12-29 07:28:34 -06:00
|
|
|
diag.span_note(test_span, format!("the {kind_word} was tested here"));
|
2020-09-24 07:49:22 -05:00
|
|
|
multispan_sugg(
|
|
|
|
diag,
|
2022-10-06 02:44:38 -05:00
|
|
|
&format!("try using the `strip_{kind_word}` method"),
|
2020-09-24 07:49:22 -05:00
|
|
|
vec![(test_span,
|
2022-10-06 02:44:38 -05:00
|
|
|
format!("if let Some(<stripped>) = {}.strip_{kind_word}({}) ",
|
2020-09-24 07:49:22 -05:00
|
|
|
snippet(cx, target_arg.span, ".."),
|
|
|
|
snippet(cx, pattern.span, "..")))]
|
|
|
|
.into_iter().chain(strippings.into_iter().map(|span| (span, "<stripped>".into()))),
|
2021-06-03 01:41:37 -05:00
|
|
|
);
|
2020-09-24 07:49:22 -05:00
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-12-06 08:01:03 -06:00
|
|
|
|
|
|
|
extract_msrv_attr!(LateContext);
|
2020-09-24 07:49:22 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// Returns `Some(arg)` if `expr` matches `arg.len()` and `None` otherwise.
|
|
|
|
fn len_arg<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<&'tcx Expr<'tcx>> {
|
|
|
|
if_chain! {
|
2022-09-01 04:43:35 -05:00
|
|
|
if let ExprKind::MethodCall(_, arg, [], _) = expr.kind;
|
2020-09-24 07:49:22 -05:00
|
|
|
if let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id);
|
|
|
|
if match_def_path(cx, method_def_id, &paths::STR_LEN);
|
|
|
|
then {
|
|
|
|
Some(arg)
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Returns the length of the `expr` if it's a constant string or char.
|
|
|
|
fn constant_length(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<u128> {
|
2023-05-20 08:39:26 -05:00
|
|
|
let value = constant(cx, cx.typeck_results(), expr)?;
|
2020-09-24 07:49:22 -05:00
|
|
|
match value {
|
|
|
|
Constant::Str(value) => Some(value.len() as u128),
|
|
|
|
Constant::Char(value) => Some(value.len_utf8() as u128),
|
|
|
|
_ => None,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Tests if `expr` equals the length of the pattern.
|
|
|
|
fn eq_pattern_length<'tcx>(cx: &LateContext<'tcx>, pattern: &Expr<'_>, expr: &'tcx Expr<'_>) -> bool {
|
|
|
|
if let ExprKind::Lit(Spanned {
|
|
|
|
node: LitKind::Int(n, _),
|
|
|
|
..
|
|
|
|
}) = expr.kind
|
|
|
|
{
|
2023-03-25 05:12:35 -05:00
|
|
|
constant_length(cx, pattern).map_or(false, |length| length == *n)
|
2020-09-24 07:49:22 -05:00
|
|
|
} else {
|
|
|
|
len_arg(cx, expr).map_or(false, |arg| eq_expr_value(cx, pattern, arg))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Tests if `expr` is a `&str`.
|
|
|
|
fn is_ref_str(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
|
2021-04-08 10:50:13 -05:00
|
|
|
match cx.typeck_results().expr_ty_adjusted(expr).kind() {
|
2020-09-24 07:49:22 -05:00
|
|
|
ty::Ref(_, ty, _) => ty.is_str(),
|
|
|
|
_ => false,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Removes the outer `AddrOf` expression if needed.
|
|
|
|
fn peel_ref<'a>(expr: &'a Expr<'_>) -> &'a Expr<'a> {
|
|
|
|
if let ExprKind::AddrOf(BorrowKind::Ref, _, unref) = &expr.kind {
|
|
|
|
unref
|
|
|
|
} else {
|
|
|
|
expr
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Find expressions where `target` is stripped using the length of `pattern`.
|
|
|
|
// We'll suggest replacing these expressions with the result of the `strip_{prefix,suffix}`
|
|
|
|
// method.
|
|
|
|
fn find_stripping<'tcx>(
|
|
|
|
cx: &LateContext<'tcx>,
|
|
|
|
strip_kind: StripKind,
|
|
|
|
target: Res,
|
|
|
|
pattern: &'tcx Expr<'_>,
|
|
|
|
expr: &'tcx Expr<'_>,
|
|
|
|
) -> Vec<Span> {
|
|
|
|
struct StrippingFinder<'a, 'tcx> {
|
|
|
|
cx: &'a LateContext<'tcx>,
|
|
|
|
strip_kind: StripKind,
|
|
|
|
target: Res,
|
|
|
|
pattern: &'tcx Expr<'tcx>,
|
|
|
|
results: Vec<Span>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a, 'tcx> Visitor<'tcx> for StrippingFinder<'a, 'tcx> {
|
|
|
|
fn visit_expr(&mut self, ex: &'tcx Expr<'_>) {
|
|
|
|
if_chain! {
|
|
|
|
if is_ref_str(self.cx, ex);
|
|
|
|
let unref = peel_ref(ex);
|
2023-08-03 14:43:17 -05:00
|
|
|
if let ExprKind::Index(indexed, index, _) = &unref.kind;
|
2021-08-08 09:49:13 -05:00
|
|
|
if let Some(higher::Range { start, end, .. }) = higher::Range::hir(index);
|
2020-09-24 07:49:22 -05:00
|
|
|
if let ExprKind::Path(path) = &indexed.kind;
|
2021-01-18 13:36:32 -06:00
|
|
|
if self.cx.qpath_res(path, ex.hir_id) == self.target;
|
2020-09-24 07:49:22 -05:00
|
|
|
then {
|
|
|
|
match (self.strip_kind, start, end) {
|
|
|
|
(StripKind::Prefix, Some(start), None) => {
|
|
|
|
if eq_pattern_length(self.cx, self.pattern, start) {
|
|
|
|
self.results.push(ex.span);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
},
|
|
|
|
(StripKind::Suffix, None, Some(end)) => {
|
|
|
|
if_chain! {
|
|
|
|
if let ExprKind::Binary(Spanned { node: BinOpKind::Sub, .. }, left, right) = end.kind;
|
|
|
|
if let Some(left_arg) = len_arg(self.cx, left);
|
|
|
|
if let ExprKind::Path(left_path) = &left_arg.kind;
|
2021-01-18 13:36:32 -06:00
|
|
|
if self.cx.qpath_res(left_path, left_arg.hir_id) == self.target;
|
2020-09-24 07:49:22 -05:00
|
|
|
if eq_pattern_length(self.cx, self.pattern, right);
|
|
|
|
then {
|
|
|
|
self.results.push(ex.span);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
},
|
|
|
|
_ => {}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
walk_expr(self, ex);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
let mut finder = StrippingFinder {
|
|
|
|
cx,
|
|
|
|
strip_kind,
|
|
|
|
target,
|
|
|
|
pattern,
|
|
|
|
results: vec![],
|
|
|
|
};
|
|
|
|
walk_expr(&mut finder, expr);
|
|
|
|
finder.results
|
|
|
|
}
|