1 use crate::utils::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};
9 /// **What it does:** Detects passing a mutable reference to a function that only
10 /// requires an immutable reference.
12 /// **Why is this bad?** The mutable reference rules out all other references to
13 /// the value. Also the code misleads about the intent of the call site.
15 /// **Known problems:** None.
20 /// my_vec.push(&mut value)
23 /// my_vec.push(&value)
25 pub UNNECESSARY_MUT_PASSED,
27 "an argument passed as a mutable reference although the callee only demands an immutable reference"
30 declare_lint_pass!(UnnecessaryMutPassed => [UNNECESSARY_MUT_PASSED]);
32 impl<'tcx> LateLintPass<'tcx> for UnnecessaryMutPassed {
33 fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
35 ExprKind::Call(ref fn_expr, ref arguments) => {
36 if let ExprKind::Path(ref path) = fn_expr.kind {
40 cx.typeck_results().expr_ty(fn_expr),
41 &rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false)),
46 ExprKind::MethodCall(ref path, _, ref arguments, _) => {
47 let def_id = cx.typeck_results().type_dependent_def_id(e.hir_id).unwrap();
48 let substs = cx.typeck_results().node_substs(e.hir_id);
49 let method_type = cx.tcx.type_of(def_id).subst(cx.tcx, substs);
50 check_arguments(cx, arguments, method_type, &path.ident.as_str(), "method")
57 fn check_arguments<'tcx>(
58 cx: &LateContext<'tcx>,
59 arguments: &[Expr<'_>],
60 type_definition: Ty<'tcx>,
64 match type_definition.kind() {
65 ty::FnDef(..) | ty::FnPtr(_) => {
66 let parameters = type_definition.fn_sig(cx.tcx).skip_binder().inputs();
67 for (argument, parameter) in arguments.iter().zip(parameters.iter()) {
68 match parameter.kind() {
69 ty::Ref(_, _, Mutability::Not)
70 | ty::RawPtr(ty::TypeAndMut {
71 mutbl: Mutability::Not, ..
73 if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Mut, _) = argument.kind {
76 UNNECESSARY_MUT_PASSED,
78 &format!("the {} `{}` doesn't need a mutable reference", fn_kind, name),