]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/methods/suspicious_to_owned.rs
Merge commit '7f27e2e74ef957baa382dc05cf08df6368165c74' into clippyup
[rust.git] / src / tools / clippy / clippy_lints / src / methods / suspicious_to_owned.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::is_diag_trait_item;
3 use clippy_utils::source::snippet_with_context;
4 use if_chain::if_chain;
5 use rustc_errors::Applicability;
6 use rustc_hir as hir;
7 use rustc_lint::LateContext;
8 use rustc_middle::ty::{self, print::with_forced_trimmed_paths};
9 use rustc_span::sym;
10
11 use super::SUSPICIOUS_TO_OWNED;
12
13 pub fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, recv: &hir::Expr<'_>) -> bool {
14     if_chain! {
15         if let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id);
16         if is_diag_trait_item(cx, method_def_id, sym::ToOwned);
17         let input_type = cx.typeck_results().expr_ty(expr);
18         if let ty::Adt(adt, _) = cx.typeck_results().expr_ty(expr).kind();
19         if cx.tcx.is_diagnostic_item(sym::Cow, adt.did());
20         then {
21             let mut app = Applicability::MaybeIncorrect;
22             let recv_snip = snippet_with_context(cx, recv.span, expr.span.ctxt(), "..", &mut app).0;
23             span_lint_and_sugg(
24                 cx,
25                 SUSPICIOUS_TO_OWNED,
26                 expr.span,
27                 &with_forced_trimmed_paths!(format!(
28                     "this `to_owned` call clones the {input_type} itself and does not cause the {input_type} contents to become owned"
29                 )),
30                 "consider using, depending on intent",
31                 format!("{recv_snip}.clone()` or `{recv_snip}.into_owned()"),
32                 app,
33             );
34             return true;
35         }
36     }
37     false
38 }