1 use crate::utils::span_lint;
2 use rustc::declare_lint_pass;
4 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
5 use rustc::ty::subst::Subst;
6 use rustc::ty::{self, Ty};
7 use rustc_session::declare_tool_lint;
10 /// **What it does:** Detects giving a mutable reference to a function that only
11 /// requires an immutable reference.
13 /// **Why is this bad?** The immutable reference rules out all other references
14 /// to the value. Also the code misleads about the intent of the call site.
16 /// **Known problems:** None.
20 /// my_vec.push(&mut value)
22 pub UNNECESSARY_MUT_PASSED,
24 "an argument passed as a mutable reference although the callee only demands an immutable reference"
27 declare_lint_pass!(UnnecessaryMutPassed => [UNNECESSARY_MUT_PASSED]);
29 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnnecessaryMutPassed {
30 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
32 ExprKind::Call(ref fn_expr, ref arguments) => {
33 if let ExprKind::Path(ref path) = fn_expr.kind {
37 cx.tables.expr_ty(fn_expr),
38 &print::to_string(print::NO_ANN, |s| s.print_qpath(path, false)),
42 ExprKind::MethodCall(ref path, _, ref arguments) => {
43 let def_id = cx.tables.type_dependent_def_id(e.hir_id).unwrap();
44 let substs = cx.tables.node_substs(e.hir_id);
45 let method_type = cx.tcx.type_of(def_id).subst(cx.tcx, substs);
46 check_arguments(cx, arguments, method_type, &path.ident.as_str())
53 fn check_arguments<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, arguments: &[Expr], type_definition: Ty<'tcx>, name: &str) {
54 match type_definition.kind {
55 ty::FnDef(..) | ty::FnPtr(_) => {
56 let parameters = type_definition.fn_sig(cx.tcx).skip_binder().inputs();
57 for (argument, parameter) in arguments.iter().zip(parameters.iter()) {
58 match parameter.kind {
59 ty::Ref(_, _, Mutability::Immutable)
60 | ty::RawPtr(ty::TypeAndMut {
61 mutbl: Mutability::Immutable,
64 if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Mutable, _) = argument.kind {
67 UNNECESSARY_MUT_PASSED,
69 &format!("The function/method `{}` doesn't need a mutable reference", name),