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};
7 use std::iter;
8
9 declare_clippy_lint! {
10 /// ### What it does
11 /// Detects passing a mutable reference to a function that only
12 /// requires an immutable reference.
13 ///
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.
17 ///
18 /// ### Example
19 /// ```ignore
20 /// // Bad
21 /// my_vec.push(&mut value)
22 ///
23 /// // Good
24 /// my_vec.push(&value)
25 /// ```
26 pub UNNECESSARY_MUT_PASSED,
27 style,
28 "an argument passed as a mutable reference although the callee only demands an immutable reference"
29 }
30
31 declare_lint_pass!(UnnecessaryMutPassed => [UNNECESSARY_MUT_PASSED]);
32
33 impl<'tcx> LateLintPass<'tcx> for UnnecessaryMutPassed {
check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>)34 fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
35 match e.kind {
36 ExprKind::Call(fn_expr, arguments) => {
37 if let ExprKind::Path(ref path) = fn_expr.kind {
38 check_arguments(
39 cx,
40 arguments,
41 cx.typeck_results().expr_ty(fn_expr),
42 &rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false)),
43 "function",
44 );
45 }
46 },
47 ExprKind::MethodCall(path, _, arguments, _) => {
48 let def_id = cx.typeck_results().type_dependent_def_id(e.hir_id).unwrap();
49 let substs = cx.typeck_results().node_substs(e.hir_id);
50 let method_type = cx.tcx.type_of(def_id).subst(cx.tcx, substs);
51 check_arguments(cx, arguments, method_type, &path.ident.as_str(), "method");
52 },
53 _ => (),
54 }
55 }
56 }
57
check_arguments<'tcx>( cx: &LateContext<'tcx>, arguments: &[Expr<'_>], type_definition: Ty<'tcx>, name: &str, fn_kind: &str, )58 fn check_arguments<'tcx>(
59 cx: &LateContext<'tcx>,
60 arguments: &[Expr<'_>],
61 type_definition: Ty<'tcx>,
62 name: &str,
63 fn_kind: &str,
64 ) {
65 match type_definition.kind() {
66 ty::FnDef(..) | ty::FnPtr(_) => {
67 let parameters = type_definition.fn_sig(cx.tcx).skip_binder().inputs();
68 for (argument, parameter) in iter::zip(arguments, parameters) {
69 match parameter.kind() {
70 ty::Ref(_, _, Mutability::Not)
71 | ty::RawPtr(ty::TypeAndMut {
72 mutbl: Mutability::Not, ..
73 }) => {
74 if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Mut, _) = argument.kind {
75 span_lint(
76 cx,
77 UNNECESSARY_MUT_PASSED,
78 argument.span,
79 &format!("the {} `{}` doesn't need a mutable reference", fn_kind, name),
80 );
81 }
82 },
83 _ => (),
84 }
85 }
86 },
87 _ => (),
88 }
89 }
90