]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/mut_reference.rs
Auto merge of #89123 - the8472:push_in_capacity, r=amanieu
[rust.git] / src / tools / clippy / clippy_lints / src / mut_reference.rs
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};
6 use std::iter;
7
8 declare_clippy_lint! {
9     /// ### What it does
10     /// Detects passing a mutable reference to a function that only
11     /// requires an immutable reference.
12     ///
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.
16     ///
17     /// ### Example
18     /// ```rust
19     /// # let mut vec = Vec::new();
20     /// # let mut value = 5;
21     /// vec.push(&mut value);
22     /// ```
23     ///
24     /// Use instead:
25     /// ```rust
26     /// # let mut vec = Vec::new();
27     /// # let value = 5;
28     /// vec.push(&value);
29     /// ```
30     #[clippy::version = "pre 1.29.0"]
31     pub UNNECESSARY_MUT_PASSED,
32     style,
33     "an argument passed as a mutable reference although the callee only demands an immutable reference"
34 }
35
36 declare_lint_pass!(UnnecessaryMutPassed => [UNNECESSARY_MUT_PASSED]);
37
38 impl<'tcx> LateLintPass<'tcx> for UnnecessaryMutPassed {
39     fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
40         match e.kind {
41             ExprKind::Call(fn_expr, arguments) => {
42                 if let ExprKind::Path(ref path) = fn_expr.kind {
43                     check_arguments(
44                         cx,
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)),
48                         "function",
49                     );
50                 }
51             },
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);
56                 check_arguments(
57                     cx,
58                     std::iter::once(receiver).chain(arguments.iter()).collect(),
59                     method_type,
60                     path.ident.as_str(),
61                     "method",
62                 );
63             },
64             _ => (),
65         }
66     }
67 }
68
69 fn check_arguments<'tcx>(
70     cx: &LateContext<'tcx>,
71     arguments: Vec<&Expr<'_>>,
72     type_definition: Ty<'tcx>,
73     name: &str,
74     fn_kind: &str,
75 ) {
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, ..
84                     }) => {
85                         if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Mut, _) = argument.kind {
86                             span_lint(
87                                 cx,
88                                 UNNECESSARY_MUT_PASSED,
89                                 argument.span,
90                                 &format!("the {fn_kind} `{name}` doesn't need a mutable reference"),
91                             );
92                         }
93                     },
94                     _ => (),
95                 }
96             }
97         },
98         _ => (),
99     }
100 }