]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/methods/no_effect_replace.rs
Auto merge of #99422 - Dylan-DPC:rollup-htjofm6, r=Dylan-DPC
[rust.git] / src / tools / clippy / clippy_lints / src / methods / no_effect_replace.rs
1 use clippy_utils::diagnostics::span_lint;
2 use clippy_utils::ty::is_type_diagnostic_item;
3 use clippy_utils::SpanlessEq;
4 use if_chain::if_chain;
5 use rustc_ast::LitKind;
6 use rustc_hir::ExprKind;
7 use rustc_lint::LateContext;
8 use rustc_span::sym;
9
10 use super::NO_EFFECT_REPLACE;
11
12 pub(super) fn check<'tcx>(
13     cx: &LateContext<'tcx>,
14     expr: &'tcx rustc_hir::Expr<'_>,
15     arg1: &'tcx rustc_hir::Expr<'_>,
16     arg2: &'tcx rustc_hir::Expr<'_>,
17 ) {
18     let ty = cx.typeck_results().expr_ty(expr).peel_refs();
19     if !(ty.is_str() || is_type_diagnostic_item(cx, ty, sym::String)) {
20         return;
21     }
22
23     if_chain! {
24         if let ExprKind::Lit(spanned) = &arg1.kind;
25         if let Some(param1) = lit_string_value(&spanned.node);
26
27         if let ExprKind::Lit(spanned) = &arg2.kind;
28         if let LitKind::Str(param2, _) = &spanned.node;
29         if param1 == param2.as_str();
30
31         then {
32             span_lint(cx, NO_EFFECT_REPLACE, expr.span, "replacing text with itself");
33         }
34     }
35
36     if SpanlessEq::new(cx).eq_expr(arg1, arg2) {
37         span_lint(cx, NO_EFFECT_REPLACE, expr.span, "replacing text with itself");
38     }
39 }
40
41 fn lit_string_value(node: &LitKind) -> Option<String> {
42     match node {
43         LitKind::Char(value) => Some(value.to_string()),
44         LitKind::Str(value, _) => Some(value.as_str().to_owned()),
45         _ => None,
46     }
47 }