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