]> git.proxmox.com Git - rustc.git/blob - src/tools/clippy/clippy_lints/src/methods/string_extend_chars.rs
New upstream version 1.67.1+dfsg1
[rustc.git] / src / tools / clippy / clippy_lints / src / methods / string_extend_chars.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::method_chain_args;
3 use clippy_utils::source::snippet_with_applicability;
4 use clippy_utils::ty::is_type_lang_item;
5 use rustc_errors::Applicability;
6 use rustc_hir as hir;
7 use rustc_lint::LateContext;
8 use rustc_middle::ty;
9
10 use super::STRING_EXTEND_CHARS;
11
12 pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, recv: &hir::Expr<'_>, arg: &hir::Expr<'_>) {
13 let obj_ty = cx.typeck_results().expr_ty(recv).peel_refs();
14 if !is_type_lang_item(cx, obj_ty, hir::LangItem::String) {
15 return;
16 }
17 if let Some(arglists) = method_chain_args(arg, &["chars"]) {
18 let target = &arglists[0].0;
19 let self_ty = cx.typeck_results().expr_ty(target).peel_refs();
20 let ref_str = if *self_ty.kind() == ty::Str {
21 if matches!(target.kind, hir::ExprKind::Index(..)) {
22 "&"
23 } else {
24 ""
25 }
26 } else if is_type_lang_item(cx, self_ty, hir::LangItem::String) {
27 "&"
28 } else {
29 return;
30 };
31
32 let mut applicability = Applicability::MachineApplicable;
33 span_lint_and_sugg(
34 cx,
35 STRING_EXTEND_CHARS,
36 expr.span,
37 "calling `.extend(_.chars())`",
38 "try this",
39 format!(
40 "{}.push_str({ref_str}{})",
41 snippet_with_applicability(cx, recv.span, "..", &mut applicability),
42 snippet_with_applicability(cx, target.span, "..", &mut applicability)
43 ),
44 applicability,
45 );
46 }
47 }