1 use clippy_utils::diagnostics::span_lint;
2 use rustc_hir::{BorrowKind, Expr, ExprKind, Mutability};
3 use rustc_lint::{LateContext, LateLintPass};
4 use rustc_middle::ty::subst::Subst;
5 use rustc_middle::ty::{self, Ty};
6 use rustc_session::{declare_lint_pass, declare_tool_lint};
11 /// Detects passing a mutable reference to a function that only
12 /// requires an immutable reference.
14 /// ### Why is this bad?
15 /// The mutable reference rules out all other references to
16 /// the value. Also the code misleads about the intent of the call site.
20 /// # let mut vec = Vec::new();
21 /// # let mut value = 5;
22 /// vec.push(&mut value);
27 /// # let mut vec = Vec::new();
31 #[clippy::version = "pre 1.29.0"]
32 pub UNNECESSARY_MUT_PASSED,
34 "an argument passed as a mutable reference although the callee only demands an immutable reference"
37 declare_lint_pass!(UnnecessaryMutPassed => [UNNECESSARY_MUT_PASSED]);
39 impl<'tcx> LateLintPass<'tcx> for UnnecessaryMutPassed {
40 fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
42 ExprKind::Call(fn_expr, arguments) => {
43 if let ExprKind::Path(ref path) = fn_expr.kind {
47 cx.typeck_results().expr_ty(fn_expr),
48 &rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false)),
53 ExprKind::MethodCall(path, arguments, _) => {
54 let def_id = cx.typeck_results().type_dependent_def_id(e.hir_id).unwrap();
55 let substs = cx.typeck_results().node_substs(e.hir_id);
56 let method_type = cx.tcx.bound_type_of(def_id).subst(cx.tcx, substs);
57 check_arguments(cx, arguments, method_type, path.ident.as_str(), "method");
64 fn check_arguments<'tcx>(
65 cx: &LateContext<'tcx>,
66 arguments: &[Expr<'_>],
67 type_definition: Ty<'tcx>,
71 match type_definition.kind() {
72 ty::FnDef(..) | ty::FnPtr(_) => {
73 let parameters = type_definition.fn_sig(cx.tcx).skip_binder().inputs();
74 for (argument, parameter) in iter::zip(arguments, parameters) {
75 match parameter.kind() {
76 ty::Ref(_, _, Mutability::Not)
77 | ty::RawPtr(ty::TypeAndMut {
78 mutbl: Mutability::Not, ..
80 if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Mut, _) = argument.kind {
83 UNNECESSARY_MUT_PASSED,
85 &format!("the {} `{}` doesn't need a mutable reference", fn_kind, name),