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 {
46 arguments.iter().collect(),
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, receiver, 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);
59 std::iter::once(receiver).chain(arguments.iter()).collect(),
70 fn check_arguments<'tcx>(
71 cx: &LateContext<'tcx>,
72 arguments: Vec<&Expr<'_>>,
73 type_definition: Ty<'tcx>,
77 match type_definition.kind() {
78 ty::FnDef(..) | ty::FnPtr(_) => {
79 let parameters = type_definition.fn_sig(cx.tcx).skip_binder().inputs();
80 for (argument, parameter) in iter::zip(arguments, parameters) {
81 match parameter.kind() {
82 ty::Ref(_, _, Mutability::Not)
83 | ty::RawPtr(ty::TypeAndMut {
84 mutbl: Mutability::Not, ..
86 if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Mut, _) = argument.kind {
89 UNNECESSARY_MUT_PASSED,
91 &format!("the {} `{}` doesn't need a mutable reference", fn_kind, name),