about summary refs log tree commit diff
path: root/clippy_lints/src/methods/single_char_push_string.rs
blob: bc271d593925ecf4f271bfeba02087becbc2df58 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::source::{snippet_with_applicability, str_literal_to_char_literal};
use rustc_ast::BorrowKind;
use rustc_errors::Applicability;
use rustc_hir::{self as hir, ExprKind};
use rustc_lint::LateContext;

use super::SINGLE_CHAR_ADD_STR;

/// lint for length-1 `str`s as argument for `push_str`
pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, receiver: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
    let mut applicability = Applicability::MachineApplicable;
    if let Some(extension_string) = str_literal_to_char_literal(cx, &args[0], &mut applicability, false) {
        let base_string_snippet =
            snippet_with_applicability(cx, receiver.span.source_callsite(), "..", &mut applicability);
        let sugg = format!("{base_string_snippet}.push({extension_string})");
        span_lint_and_sugg(
            cx,
            SINGLE_CHAR_ADD_STR,
            expr.span,
            "calling `push_str()` using a single-character string literal",
            "consider using `push` with a character literal",
            sugg,
            applicability,
        );
    }

    if let ExprKind::AddrOf(BorrowKind::Ref, _, arg) = &args[0].kind
        && let ExprKind::MethodCall(path_segment, method_arg, [], _) = &arg.kind
        && path_segment.ident.name == rustc_span::sym::to_string
        && (is_ref_char(cx, method_arg) || is_char(cx, method_arg))
    {
        let base_string_snippet =
            snippet_with_applicability(cx, receiver.span.source_callsite(), "..", &mut applicability);
        let extension_string =
            snippet_with_applicability(cx, method_arg.span.source_callsite(), "..", &mut applicability);
        let deref_string = if is_ref_char(cx, method_arg) { "*" } else { "" };

        let sugg = format!("{base_string_snippet}.push({deref_string}{extension_string})");
        span_lint_and_sugg(
            cx,
            SINGLE_CHAR_ADD_STR,
            expr.span,
            "calling `push_str()` using a single-character converted to string",
            "consider using `push` without `to_string()`",
            sugg,
            applicability,
        );
    }
}

fn is_ref_char(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> bool {
    if cx.typeck_results().expr_ty(expr).is_ref()
        && let rustc_middle::ty::Ref(_, ty, _) = cx.typeck_results().expr_ty(expr).kind()
        && ty.is_char()
    {
        return true;
    }

    false
}

fn is_char(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> bool {
    cx.typeck_results().expr_ty(expr).is_char()
}