]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/methods/string_extend_chars.rs
ast/hir: Rename field-related structures
[rust.git] / clippy_lints / src / methods / string_extend_chars.rs
1 use crate::utils::{is_type_diagnostic_item, method_chain_args, snippet_with_applicability, span_lint_and_sugg};
2 use rustc_errors::Applicability;
3 use rustc_hir as hir;
4 use rustc_lint::LateContext;
5 use rustc_middle::ty;
6 use rustc_span::symbol::sym;
7
8 use super::STRING_EXTEND_CHARS;
9
10 pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
11     let obj_ty = cx.typeck_results().expr_ty(&args[0]).peel_refs();
12     if is_type_diagnostic_item(cx, obj_ty, sym::string_type) {
13         let arg = &args[1];
14         if let Some(arglists) = method_chain_args(arg, &["chars"]) {
15             let target = &arglists[0][0];
16             let self_ty = cx.typeck_results().expr_ty(target).peel_refs();
17             let ref_str = if *self_ty.kind() == ty::Str {
18                 ""
19             } else if is_type_diagnostic_item(cx, self_ty, sym::string_type) {
20                 "&"
21             } else {
22                 return;
23             };
24
25             let mut applicability = Applicability::MachineApplicable;
26             span_lint_and_sugg(
27                 cx,
28                 STRING_EXTEND_CHARS,
29                 expr.span,
30                 "calling `.extend(_.chars())`",
31                 "try this",
32                 format!(
33                     "{}.push_str({}{})",
34                     snippet_with_applicability(cx, args[0].span, "..", &mut applicability),
35                     ref_str,
36                     snippet_with_applicability(cx, target.span, "..", &mut applicability)
37                 ),
38                 applicability,
39             );
40         }
41     }
42 }