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