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.
21 /// my_vec.push(&mut value)
24 /// my_vec.push(&value)
26 #[clippy::version = "pre 1.29.0"]
27 pub UNNECESSARY_MUT_PASSED,
29 "an argument passed as a mutable reference although the callee only demands an immutable reference"
32 declare_lint_pass!(UnnecessaryMutPassed => [UNNECESSARY_MUT_PASSED]);
34 impl<'tcx> LateLintPass<'tcx> for UnnecessaryMutPassed {
35 fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
37 ExprKind::Call(fn_expr, arguments) => {
38 if let ExprKind::Path(ref path) = fn_expr.kind {
42 cx.typeck_results().expr_ty(fn_expr),
43 &rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false)),
48 ExprKind::MethodCall(path, _, arguments, _) => {
49 let def_id = cx.typeck_results().type_dependent_def_id(e.hir_id).unwrap();
50 let substs = cx.typeck_results().node_substs(e.hir_id);
51 let method_type = cx.tcx.type_of(def_id).subst(cx.tcx, substs);
52 check_arguments(cx, arguments, method_type, &path.ident.as_str(), "method");
59 fn check_arguments<'tcx>(
60 cx: &LateContext<'tcx>,
61 arguments: &[Expr<'_>],
62 type_definition: Ty<'tcx>,
66 match type_definition.kind() {
67 ty::FnDef(..) | ty::FnPtr(_) => {
68 let parameters = type_definition.fn_sig(cx.tcx).skip_binder().inputs();
69 for (argument, parameter) in iter::zip(arguments, parameters) {
70 match parameter.kind() {
71 ty::Ref(_, _, Mutability::Not)
72 | ty::RawPtr(ty::TypeAndMut {
73 mutbl: Mutability::Not, ..
75 if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Mut, _) = argument.kind {
78 UNNECESSARY_MUT_PASSED,
80 &format!("the {} `{}` doesn't need a mutable reference", fn_kind, name),