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::{self, Ty};
5 use rustc_session::{declare_lint_pass, declare_tool_lint};
10 /// Detects passing a mutable reference to a function that only
11 /// requires an immutable reference.
13 /// ### Why is this bad?
14 /// The mutable reference rules out all other references to
15 /// the value. Also the code misleads about the intent of the call site.
19 /// # let mut vec = Vec::new();
20 /// # let mut value = 5;
21 /// vec.push(&mut value);
26 /// # let mut vec = Vec::new();
30 #[clippy::version = "pre 1.29.0"]
31 pub UNNECESSARY_MUT_PASSED,
33 "an argument passed as a mutable reference although the callee only demands an immutable reference"
36 declare_lint_pass!(UnnecessaryMutPassed => [UNNECESSARY_MUT_PASSED]);
38 impl<'tcx> LateLintPass<'tcx> for UnnecessaryMutPassed {
39 fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
41 ExprKind::Call(fn_expr, arguments) => {
42 if let ExprKind::Path(ref path) = fn_expr.kind {
45 arguments.iter().collect(),
46 cx.typeck_results().expr_ty(fn_expr),
47 &rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false)),
52 ExprKind::MethodCall(path, receiver, arguments, _) => {
53 let def_id = cx.typeck_results().type_dependent_def_id(e.hir_id).unwrap();
54 let substs = cx.typeck_results().node_substs(e.hir_id);
55 let method_type = cx.tcx.bound_type_of(def_id).subst(cx.tcx, substs);
58 std::iter::once(receiver).chain(arguments.iter()).collect(),
69 fn check_arguments<'tcx>(
70 cx: &LateContext<'tcx>,
71 arguments: Vec<&Expr<'_>>,
72 type_definition: Ty<'tcx>,
76 match type_definition.kind() {
77 ty::FnDef(..) | ty::FnPtr(_) => {
78 let parameters = type_definition.fn_sig(cx.tcx).skip_binder().inputs();
79 for (argument, parameter) in iter::zip(arguments, parameters) {
80 match parameter.kind() {
81 ty::Ref(_, _, Mutability::Not)
82 | ty::RawPtr(ty::TypeAndMut {
83 mutbl: Mutability::Not, ..
85 if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Mut, _) = argument.kind {
88 UNNECESSARY_MUT_PASSED,
90 &format!("the {fn_kind} `{name}` doesn't need a mutable reference"),