2 use rustc_front::hir::*;
4 use rustc::middle::ty::{TypeAndMut, TypeVariants, MethodCall, TyS};
7 /// **What it does:** This lint detects giving a mutable reference to a function that only requires an immutable reference.
9 /// **Why is this bad?** The immutable reference rules out all other references to the value. Also the code misleads about the intent of the call site.
11 /// **Known problems:** None
13 /// **Example** `my_vec.push(&mut value)`
15 pub UNNECESSARY_MUT_PASSED,
17 "an argument is passed as a mutable reference although the function/method only demands an \
23 pub struct UnnecessaryMutPassed;
25 impl LintPass for UnnecessaryMutPassed {
26 fn get_lints(&self) -> LintArray {
27 lint_array!(UNNECESSARY_MUT_PASSED)
31 impl LateLintPass for UnnecessaryMutPassed {
32 fn check_expr(&mut self, cx: &LateContext, e: &Expr) {
33 let borrowed_table = cx.tcx.tables.borrow();
35 ExprCall(ref fn_expr, ref arguments) => {
36 match borrowed_table.node_types.get(&fn_expr.id) {
37 Some(function_type) => {
38 if let ExprPath(_, ref path) = fn_expr.node {
39 check_arguments(cx, &arguments, function_type,
40 &format!("{}", path));
43 None => unreachable!(), // A function with unknown type is called.
44 // If this happened the compiler would have aborted the
45 // compilation long ago.
50 ExprMethodCall(ref name, _, ref arguments) => {
51 let method_call = MethodCall::expr(e.id);
52 match borrowed_table.method_map.get(&method_call) {
53 Some(method_type) => check_arguments(cx, &arguments, method_type.ty,
54 &format!("{}", name.node.as_str())),
55 None => unreachable!(), // Just like above, this should never happen.
63 fn check_arguments(cx: &LateContext, arguments: &[P<Expr>], type_definition: &TyS, name: &str) {
64 if let TypeVariants::TyBareFn(_, ref fn_type) = type_definition.sty {
65 let parameters = &fn_type.sig.skip_binder().inputs;
66 for (argument, parameter) in arguments.iter().zip(parameters.iter()) {
68 TypeVariants::TyRef(_, TypeAndMut {mutbl: MutImmutable, ..}) |
69 TypeVariants::TyRawPtr(TypeAndMut {mutbl: MutImmutable, ..}) => {
70 if let ExprAddrOf(MutMutable, _) = argument.node {
71 span_lint(cx, UNNECESSARY_MUT_PASSED,
72 argument.span, &format!("The function/method \"{}\" \
73 doesn't need a mutable reference",