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