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;
8 use rustc_lint::LateContext;
10 use super::USELESS_ASREF;
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
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;
33 let mut applicability = Applicability::MachineApplicable;
38 &format!("this call to `{}` does nothing", call_name),
40 snippet_with_applicability(cx, recvr.span, "..", &mut applicability).to_string(),