refactor string_extend_chars: return when obj type is not string

This commit is contained in:
Takayuki Maeda 2021-03-13 17:36:04 +09:00
parent 058d8c878a
commit c07c046b31

View File

@ -12,34 +12,35 @@ use super::STRING_EXTEND_CHARS;
pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) { pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
let obj_ty = cx.typeck_results().expr_ty(&args[0]).peel_refs(); let obj_ty = cx.typeck_results().expr_ty(&args[0]).peel_refs();
if is_type_diagnostic_item(cx, obj_ty, sym::string_type) { if !is_type_diagnostic_item(cx, obj_ty, sym::string_type) {
let arg = &args[1]; return;
if let Some(arglists) = method_chain_args(arg, &["chars"]) { }
let target = &arglists[0][0]; let arg = &args[1];
let self_ty = cx.typeck_results().expr_ty(target).peel_refs(); if let Some(arglists) = method_chain_args(arg, &["chars"]) {
let ref_str = if *self_ty.kind() == ty::Str { let target = &arglists[0][0];
"" let self_ty = cx.typeck_results().expr_ty(target).peel_refs();
} else if is_type_diagnostic_item(cx, self_ty, sym::string_type) { let ref_str = if *self_ty.kind() == ty::Str {
"&" ""
} else { } else if is_type_diagnostic_item(cx, self_ty, sym::string_type) {
return; "&"
}; } else {
return;
};
let mut applicability = Applicability::MachineApplicable; let mut applicability = Applicability::MachineApplicable;
span_lint_and_sugg( span_lint_and_sugg(
cx, cx,
STRING_EXTEND_CHARS, STRING_EXTEND_CHARS,
expr.span, expr.span,
"calling `.extend(_.chars())`", "calling `.extend(_.chars())`",
"try this", "try this",
format!( format!(
"{}.push_str({}{})", "{}.push_str({}{})",
snippet_with_applicability(cx, args[0].span, "..", &mut applicability), snippet_with_applicability(cx, args[0].span, "..", &mut applicability),
ref_str, ref_str,
snippet_with_applicability(cx, target.span, "..", &mut applicability) snippet_with_applicability(cx, target.span, "..", &mut applicability)
), ),
applicability, applicability,
); );
}
} }
} }