]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/methods/useless_asref.rs
Auto merge of #7546 - mgeier:patch-1, r=giraffate
[rust.git] / clippy_lints / src / methods / useless_asref.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::source::snippet_with_applicability;
3 use clippy_utils::ty::walk_ptrs_ty_depth;
4 use clippy_utils::{get_parent_expr, match_trait_method, paths};
5 use if_chain::if_chain;
6 use rustc_errors::Applicability;
7 use rustc_hir as hir;
8 use rustc_lint::LateContext;
9
10 use super::USELESS_ASREF;
11
12 /// Checks for the `USELESS_ASREF` lint.
13 pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, call_name: &str, recvr: &hir::Expr<'_>) {
14     // when we get here, we've already checked that the call name is "as_ref" or "as_mut"
15     // check if the call is to the actual `AsRef` or `AsMut` trait
16     if match_trait_method(cx, expr, &paths::ASREF_TRAIT) || match_trait_method(cx, expr, &paths::ASMUT_TRAIT) {
17         // check if the type after `as_ref` or `as_mut` is the same as before
18         let rcv_ty = cx.typeck_results().expr_ty(recvr);
19         let res_ty = cx.typeck_results().expr_ty(expr);
20         let (base_res_ty, res_depth) = walk_ptrs_ty_depth(res_ty);
21         let (base_rcv_ty, rcv_depth) = walk_ptrs_ty_depth(rcv_ty);
22         if base_rcv_ty == base_res_ty && rcv_depth >= res_depth {
23             // allow the `as_ref` or `as_mut` if it is followed by another method call
24             if_chain! {
25                 if let Some(parent) = get_parent_expr(cx, expr);
26                 if let hir::ExprKind::MethodCall(_, ref span, _, _) = parent.kind;
27                 if span != &expr.span;
28                 then {
29                     return;
30                 }
31             }
32
33             let mut applicability = Applicability::MachineApplicable;
34             span_lint_and_sugg(
35                 cx,
36                 USELESS_ASREF,
37                 expr.span,
38                 &format!("this call to `{}` does nothing", call_name),
39                 "try this",
40                 snippet_with_applicability(cx, recvr.span, "..", &mut applicability).to_string(),
41                 applicability,
42             );
43         }
44     }
45 }