]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/needless_pass_by_value.rs
Integrate suggestion spans
[rust.git] / clippy_lints / src / needless_pass_by_value.rs
1 use rustc::hir::*;
2 use rustc::hir::intravisit::FnKind;
3 use rustc::hir::def_id::DefId;
4 use rustc::lint::*;
5 use rustc::ty::{self, TypeFoldable};
6 use rustc::traits;
7 use rustc::middle::expr_use_visitor as euv;
8 use rustc::middle::mem_categorization as mc;
9 use syntax::ast::NodeId;
10 use syntax_pos::Span;
11 use syntax::errors::DiagnosticBuilder;
12 use utils::{in_macro, is_self, is_copy, implements_trait, get_trait_def_id, match_type, snippet, span_lint_and_then,
13             multispan_sugg, paths};
14 use std::collections::{HashSet, HashMap};
15
16 /// **What it does:** Checks for functions taking arguments by value, but not consuming them in its
17 /// body.
18 ///
19 /// **Why is this bad?** Taking arguments by reference is more flexible and can sometimes avoid
20 /// unnecessary allocations.
21 ///
22 /// **Known problems:** Hopefully none.
23 ///
24 /// **Example:**
25 /// ```rust
26 /// fn foo(v: Vec<i32>) {
27 ///     assert_eq!(v.len(), 42);
28 /// }
29 /// ```
30 declare_lint! {
31     pub NEEDLESS_PASS_BY_VALUE,
32     Warn,
33     "functions taking arguments by value, but not consuming them in its body"
34 }
35
36 pub struct NeedlessPassByValue;
37
38 impl LintPass for NeedlessPassByValue {
39     fn get_lints(&self) -> LintArray {
40         lint_array![NEEDLESS_PASS_BY_VALUE]
41     }
42 }
43
44 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessPassByValue {
45     fn check_fn(
46         &mut self,
47         cx: &LateContext<'a, 'tcx>,
48         kind: FnKind<'tcx>,
49         decl: &'tcx FnDecl,
50         body: &'tcx Body,
51         span: Span,
52         node_id: NodeId
53     ) {
54         if in_macro(cx, span) {
55             return;
56         }
57
58         if !matches!(kind, FnKind::ItemFn(..)) {
59             return;
60         }
61
62         // Allows these to be passed by value.
63         let fn_trait = cx.tcx.lang_items.fn_trait().expect("failed to find `Fn` trait");
64         let asref_trait = get_trait_def_id(cx, &paths::ASREF_TRAIT).expect("failed to find `AsRef` trait");
65         let borrow_trait = get_trait_def_id(cx, &paths::BORROW_TRAIT).expect("failed to find `Borrow` trait");
66
67         let preds: Vec<ty::Predicate> = {
68             let parameter_env = ty::ParameterEnvironment::for_item(cx.tcx, node_id);
69             traits::elaborate_predicates(cx.tcx, parameter_env.caller_bounds.clone())
70                 .filter(|p| !p.is_global())
71                 .collect()
72         };
73
74         // Collect moved variables and spans which will need dereferencings from the function body.
75         let MovedVariablesCtxt { moved_vars, spans_need_deref, .. } = {
76             let mut ctx = MovedVariablesCtxt::new(cx);
77             let infcx = cx.tcx.borrowck_fake_infer_ctxt(body.id());
78             {
79                 let mut v = euv::ExprUseVisitor::new(&mut ctx, &infcx);
80                 v.consume_body(body);
81             }
82             ctx
83         };
84
85         let fn_def_id = cx.tcx.hir.local_def_id(node_id);
86         let param_env = ty::ParameterEnvironment::for_item(cx.tcx, node_id);
87         let fn_sig = cx.tcx.item_type(fn_def_id).fn_sig();
88         let fn_sig = cx.tcx.liberate_late_bound_regions(param_env.free_id_outlive, fn_sig);
89
90         for ((input, ty), arg) in decl.inputs.iter().zip(fn_sig.inputs()).zip(&body.arguments) {
91
92             // Determines whether `ty` implements `Borrow<U>` (U != ty) specifically.
93             // This is needed due to the `Borrow<T> for T` blanket impl.
94             let implements_borrow_trait = preds.iter()
95                 .filter_map(|pred| if let ty::Predicate::Trait(ref poly_trait_ref) = *pred {
96                     Some(poly_trait_ref.skip_binder())
97                 } else {
98                     None
99                 })
100                 .filter(|tpred| tpred.def_id() == borrow_trait && &tpred.self_ty() == ty)
101                 .any(|tpred| &tpred.input_types().nth(1).expect("Borrow trait must have an parameter") != ty);
102
103             if_let_chain! {[
104                 !is_self(arg),
105                 !ty.is_mutable_pointer(),
106                 !is_copy(cx, ty, node_id),
107                 !implements_trait(cx, ty, fn_trait, &[], Some(node_id)),
108                 !implements_trait(cx, ty, asref_trait, &[], Some(node_id)),
109                 !implements_borrow_trait,
110
111                 let PatKind::Binding(mode, defid, ..) = arg.pat.node,
112                 !moved_vars.contains(&defid),
113             ], {
114                 // Note: `toplevel_ref_arg` warns if `BindByRef`
115                 let m = match mode {
116                     BindingMode::BindByRef(m) | BindingMode::BindByValue(m) => m,
117                 };
118                 if m == Mutability::MutMutable {
119                     continue;
120                 }
121
122                 // Suggestion logic
123                 let sugg = |db: &mut DiagnosticBuilder| {
124                     if_let_chain! {[
125                         match_type(cx, ty, &paths::VEC),
126                         let TyPath(QPath::Resolved(_, ref path)) = input.node,
127                         let Some(elem_ty) = path.segments.iter()
128                             .find(|seg| &*seg.name.as_str() == "Vec")
129                             .map(|ps| ps.parameters.types()[0]),
130                     ], {
131                         let slice_ty = format!("&[{}]", snippet(cx, elem_ty.span, "_"));
132                         db.span_suggestion(input.span,
133                                         &format!("consider changing the type to `{}`", slice_ty),
134                                         slice_ty);
135                         return; // `Vec` and `String` cannot be destructured - no need for `*` suggestion
136                     }}
137
138                     if match_type(cx, ty, &paths::STRING) {
139                         db.span_suggestion(input.span,
140                                            "consider changing the type to `&str`",
141                                            "&str".to_string());
142                         return;
143                     }
144
145                     let mut spans = vec![(input.span, format!("&{}", snippet(cx, input.span, "_")))];
146
147                     // Suggests adding `*` to dereference the added reference.
148                     if let Some(deref_span) = spans_need_deref.get(&defid) {
149                         spans.extend(deref_span.iter().cloned()
150                                      .map(|span| (span, format!("*{}", snippet(cx, span, "<expr>")))));
151                         spans.sort_by_key(|&(span, _)| span);
152                     }
153                     multispan_sugg(db, "consider taking a reference instead".to_string(), spans);
154                 };
155
156                 span_lint_and_then(cx,
157                           NEEDLESS_PASS_BY_VALUE,
158                           input.span,
159                           "this argument is passed by value, but not consumed in the function body",
160                           sugg);
161             }}
162         }
163     }
164 }
165
166 struct MovedVariablesCtxt<'a, 'tcx: 'a> {
167     cx: &'a LateContext<'a, 'tcx>,
168     moved_vars: HashSet<DefId>,
169     /// Spans which need to be prefixed with `*` for dereferencing the suggested additional
170     /// reference.
171     spans_need_deref: HashMap<DefId, HashSet<Span>>,
172 }
173
174 impl<'a, 'tcx: 'a> MovedVariablesCtxt<'a, 'tcx> {
175     fn new(cx: &'a LateContext<'a, 'tcx>) -> Self {
176         MovedVariablesCtxt {
177             cx: cx,
178             moved_vars: HashSet::new(),
179             spans_need_deref: HashMap::new(),
180         }
181     }
182
183     fn move_common(&mut self, _consume_id: NodeId, _span: Span, cmt: mc::cmt<'tcx>) {
184         let cmt = unwrap_downcast_or_interior(cmt);
185
186         if_let_chain! {[
187             let mc::Categorization::Local(vid) = cmt.cat,
188             let Some(def_id) = self.cx.tcx.hir.opt_local_def_id(vid),
189         ], {
190                 self.moved_vars.insert(def_id);
191         }}
192     }
193
194     fn non_moving_pat(&mut self, matched_pat: &Pat, cmt: mc::cmt<'tcx>) {
195         let cmt = unwrap_downcast_or_interior(cmt);
196
197         if_let_chain! {[
198             let mc::Categorization::Local(vid) = cmt.cat,
199             let Some(def_id) = self.cx.tcx.hir.opt_local_def_id(vid),
200         ], {
201             let mut id = matched_pat.id;
202             loop {
203                 let parent = self.cx.tcx.hir.get_parent_node(id);
204                 if id == parent {
205                     // no parent
206                     return;
207                 }
208                 id = parent;
209
210                 if let Some(node) = self.cx.tcx.hir.find(id) {
211                     match node {
212                         map::Node::NodeExpr(e) => {
213                             // `match` and `if let`
214                             if let ExprMatch(ref c, ..) = e.node {
215                                 self.spans_need_deref
216                                     .entry(def_id)
217                                     .or_insert_with(HashSet::new)
218                                     .insert(c.span);
219                             }
220                         }
221
222                         map::Node::NodeStmt(s) => {
223                             // `let <pat> = x;`
224                             if_let_chain! {[
225                                 let StmtDecl(ref decl, _) = s.node,
226                                 let DeclLocal(ref local) = decl.node,
227                             ], {
228                                 self.spans_need_deref
229                                     .entry(def_id)
230                                     .or_insert_with(HashSet::new)
231                                     .insert(local.init
232                                         .as_ref()
233                                         .map(|e| e.span)
234                                         .expect("`let` stmt without init aren't caught by match_pat"));
235                             }}
236                         }
237
238                         _ => {}
239                     }
240                 }
241             }
242         }}
243     }
244 }
245
246 impl<'a, 'tcx: 'a> euv::Delegate<'tcx> for MovedVariablesCtxt<'a, 'tcx> {
247     fn consume(&mut self, consume_id: NodeId, consume_span: Span, cmt: mc::cmt<'tcx>, mode: euv::ConsumeMode) {
248         if let euv::ConsumeMode::Move(_) = mode {
249             self.move_common(consume_id, consume_span, cmt);
250         }
251     }
252
253     fn matched_pat(&mut self, matched_pat: &Pat, cmt: mc::cmt<'tcx>, mode: euv::MatchMode) {
254         if let euv::MatchMode::MovingMatch = mode {
255             self.move_common(matched_pat.id, matched_pat.span, cmt);
256         } else {
257             self.non_moving_pat(matched_pat, cmt);
258         }
259     }
260
261     fn consume_pat(&mut self, consume_pat: &Pat, cmt: mc::cmt<'tcx>, mode: euv::ConsumeMode) {
262         if let euv::ConsumeMode::Move(_) = mode {
263             self.move_common(consume_pat.id, consume_pat.span, cmt);
264         }
265     }
266
267     fn borrow(
268         &mut self,
269         _: NodeId,
270         _: Span,
271         _: mc::cmt<'tcx>,
272         _: &'tcx ty::Region,
273         _: ty::BorrowKind,
274         _: euv::LoanCause
275     ) {
276     }
277
278     fn mutate(&mut self, _: NodeId, _: Span, _: mc::cmt<'tcx>, _: euv::MutateMode) {}
279
280     fn decl_without_init(&mut self, _: NodeId, _: Span) {}
281 }
282
283
284 fn unwrap_downcast_or_interior(mut cmt: mc::cmt) -> mc::cmt {
285     loop {
286         match cmt.cat.clone() {
287             mc::Categorization::Downcast(c, _) |
288             mc::Categorization::Interior(c, _) => {
289                 cmt = c;
290             },
291             _ => return cmt,
292         }
293     }
294 }