]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/needless_pass_by_value.rs
needless_pass_by_value: Ignore for extern funcs (fixes #1844)
[rust.git] / clippy_lints / src / needless_pass_by_value.rs
1 use rustc::hir::*;
2 use rustc::hir::map::*;
3 use rustc::hir::intravisit::FnKind;
4 use rustc::lint::*;
5 use rustc::ty::{self, RegionKind, 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::abi::Abi;
10 use syntax::ast::NodeId;
11 use syntax_pos::Span;
12 use syntax::errors::DiagnosticBuilder;
13 use utils::{get_trait_def_id, implements_trait, in_macro, is_copy, is_self, match_type, multispan_sugg, paths,
14             snippet, snippet_opt, span_lint_and_then};
15 use utils::ptr::get_spans;
16 use std::collections::{HashMap, HashSet};
17 use std::borrow::Cow;
18
19 /// **What it does:** Checks for functions taking arguments by value, but not
20 /// consuming them in its
21 /// body.
22 ///
23 /// **Why is this bad?** Taking arguments by reference is more flexible and can
24 /// sometimes avoid
25 /// unnecessary allocations.
26 ///
27 /// **Known problems:**
28 /// * This lint suggests taking an argument by reference,
29 /// however sometimes it is better to let users decide the argument type
30 /// (by using `Borrow` trait, for example), depending on how the function is used.
31 ///
32 /// **Example:**
33 /// ```rust
34 /// fn foo(v: Vec<i32>) {
35 ///     assert_eq!(v.len(), 42);
36 /// }
37 /// // should be
38 /// fn foo(v: &[i32]) {
39 ///     assert_eq!(v.len(), 42);
40 /// }
41 /// ```
42 declare_lint! {
43     pub NEEDLESS_PASS_BY_VALUE,
44     Warn,
45     "functions taking arguments by value, but not consuming them in its body"
46 }
47
48 pub struct NeedlessPassByValue;
49
50 impl LintPass for NeedlessPassByValue {
51     fn get_lints(&self) -> LintArray {
52         lint_array![NEEDLESS_PASS_BY_VALUE]
53     }
54 }
55
56 macro_rules! need {
57     ($e: expr) => { if let Some(x) = $e { x } else { return; } };
58 }
59
60 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessPassByValue {
61     fn check_fn(
62         &mut self,
63         cx: &LateContext<'a, 'tcx>,
64         kind: FnKind<'tcx>,
65         decl: &'tcx FnDecl,
66         body: &'tcx Body,
67         span: Span,
68         node_id: NodeId,
69     ) {
70         if in_macro(span) {
71             return;
72         }
73
74         match kind {
75             FnKind::ItemFn(.., abi, _, attrs) => {
76                 if abi != Abi::Rust {
77                     return;
78                 }
79                 for a in attrs {
80                     if_chain! {
81                         if a.meta_item_list().is_some();
82                         if let Some(name) = a.name();
83                         if name == "proc_macro_derive";
84                         then {
85                             return;
86                         }
87                     }
88                 }
89             },
90             FnKind::Method(..) => (),
91             _ => return,
92         }
93
94         // Exclude non-inherent impls
95         if let Some(NodeItem(item)) = cx.tcx.hir.find(cx.tcx.hir.get_parent_node(node_id)) {
96             if matches!(item.node, ItemImpl(_, _, _, _, Some(_), _, _) |
97                 ItemTrait(..))
98             {
99                 return;
100             }
101         }
102
103         // Allow `Borrow` or functions to be taken by value
104         let borrow_trait = need!(get_trait_def_id(cx, &paths::BORROW_TRAIT));
105         let fn_traits = [
106             need!(cx.tcx.lang_items().fn_trait()),
107             need!(cx.tcx.lang_items().fn_once_trait()),
108             need!(cx.tcx.lang_items().fn_mut_trait()),
109         ];
110
111         let sized_trait = need!(cx.tcx.lang_items().sized_trait());
112
113         let fn_def_id = cx.tcx.hir.local_def_id(node_id);
114
115         let preds = traits::elaborate_predicates(cx.tcx, cx.param_env.caller_bounds.to_vec())
116             .filter(|p| !p.is_global())
117             .filter_map(|pred| {
118                 if let ty::Predicate::Trait(poly_trait_ref) = pred {
119                     if poly_trait_ref.def_id() == sized_trait || poly_trait_ref.skip_binder().has_escaping_regions() {
120                         return None;
121                     }
122                     Some(poly_trait_ref)
123                 } else {
124                     None
125                 }
126             })
127             .collect::<Vec<_>>();
128
129         // Collect moved variables and spans which will need dereferencings from the
130         // function body.
131         let MovedVariablesCtxt {
132             moved_vars,
133             spans_need_deref,
134             ..
135         } = {
136             let mut ctx = MovedVariablesCtxt::new(cx);
137             let region_scope_tree = &cx.tcx.region_scope_tree(fn_def_id);
138             euv::ExprUseVisitor::new(&mut ctx, cx.tcx, cx.param_env, region_scope_tree, cx.tables, None)
139                 .consume_body(body);
140             ctx
141         };
142
143         let fn_sig = cx.tcx.fn_sig(fn_def_id);
144         let fn_sig = cx.tcx.erase_late_bound_regions(&fn_sig);
145
146         for (idx, ((input, &ty), arg)) in decl.inputs
147             .iter()
148             .zip(fn_sig.inputs())
149             .zip(&body.arguments)
150             .enumerate()
151         {
152             // All spans generated from a proc-macro invocation are the same...
153             if span == input.span {
154                 return;
155             }
156
157             // Ignore `self`s.
158             if idx == 0 {
159                 if let PatKind::Binding(_, _, name, ..) = arg.pat.node {
160                     if name.node.as_str() == "self" {
161                         continue;
162                     }
163                 }
164             }
165
166             // * Exclude a type that is specifically bounded by `Borrow`.
167             // * Exclude a type whose reference also fulfills its bound.
168             //   (e.g. `std::convert::AsRef`, `serde::Serialize`)
169             let (implements_borrow_trait, all_borrowable_trait) = {
170                 let preds = preds
171                     .iter()
172                     .filter(|t| t.skip_binder().self_ty() == ty)
173                     .collect::<Vec<_>>();
174
175                 (
176                     preds.iter().any(|t| t.def_id() == borrow_trait),
177                     !preds.is_empty() && preds.iter().all(|t| {
178                         implements_trait(
179                             cx,
180                             cx.tcx.mk_imm_ref(&RegionKind::ReErased, ty),
181                             t.def_id(),
182                             &t.skip_binder().input_types().skip(1).collect::<Vec<_>>(),
183                         )
184                     }),
185                 )
186             };
187
188             if_chain! {
189                 if !is_self(arg);
190                 if !ty.is_mutable_pointer();
191                 if !is_copy(cx, ty);
192                 if !fn_traits.iter().any(|&t| implements_trait(cx, ty, t, &[]));
193                 if !implements_borrow_trait;
194                 if !all_borrowable_trait;
195
196                 if let PatKind::Binding(mode, canonical_id, ..) = arg.pat.node;
197                 if !moved_vars.contains(&canonical_id);
198                 then {
199                     if mode == BindingAnnotation::Mutable || mode == BindingAnnotation::RefMut {
200                         continue;
201                     }
202
203                     // Dereference suggestion
204                     let sugg = |db: &mut DiagnosticBuilder| {
205                         let deref_span = spans_need_deref.get(&canonical_id);
206                         if_chain! {
207                             if match_type(cx, ty, &paths::VEC);
208                             if let Some(clone_spans) =
209                                 get_spans(cx, Some(body.id()), idx, &[("clone", ".to_owned()")]);
210                             if let TyPath(QPath::Resolved(_, ref path)) = input.node;
211                             if let Some(elem_ty) = path.segments.iter()
212                                 .find(|seg| seg.name == "Vec")
213                                 .and_then(|ps| ps.parameters.as_ref())
214                                 .map(|params| &params.types[0]);
215                             then {
216                                 let slice_ty = format!("&[{}]", snippet(cx, elem_ty.span, "_"));
217                                 db.span_suggestion(input.span,
218                                                 "consider changing the type to",
219                                                 slice_ty);
220
221                                 for (span, suggestion) in clone_spans {
222                                     db.span_suggestion(
223                                         span,
224                                         &snippet_opt(cx, span)
225                                             .map_or(
226                                                 "change the call to".into(),
227                                                 |x| Cow::from(format!("change `{}` to", x)),
228                                             ),
229                                         suggestion.into()
230                                     );
231                                 }
232
233                                 // cannot be destructured, no need for `*` suggestion
234                                 assert!(deref_span.is_none());
235                                 return;
236                             }
237                         }
238
239                         if match_type(cx, ty, &paths::STRING) {
240                             if let Some(clone_spans) =
241                                 get_spans(cx, Some(body.id()), idx, &[("clone", ".to_string()"), ("as_str", "")]) {
242                                 db.span_suggestion(input.span, "consider changing the type to", "&str".to_string());
243
244                                 for (span, suggestion) in clone_spans {
245                                     db.span_suggestion(
246                                         span,
247                                         &snippet_opt(cx, span)
248                                             .map_or(
249                                                 "change the call to".into(),
250                                                 |x| Cow::from(format!("change `{}` to", x))
251                                             ),
252                                         suggestion.into(),
253                                     );
254                                 }
255
256                                 assert!(deref_span.is_none());
257                                 return;
258                             }
259                         }
260
261                         let mut spans = vec![(input.span, format!("&{}", snippet(cx, input.span, "_")))];
262
263                         // Suggests adding `*` to dereference the added reference.
264                         if let Some(deref_span) = deref_span {
265                             spans.extend(
266                                 deref_span
267                                     .iter()
268                                     .cloned()
269                                     .map(|span| (span, format!("*{}", snippet(cx, span, "<expr>")))),
270                             );
271                             spans.sort_by_key(|&(span, _)| span);
272                         }
273                         multispan_sugg(db, "consider taking a reference instead".to_string(), spans);
274                     };
275
276                     span_lint_and_then(
277                         cx,
278                         NEEDLESS_PASS_BY_VALUE,
279                         input.span,
280                         "this argument is passed by value, but not consumed in the function body",
281                         sugg,
282                     );
283                 }
284             }
285         }
286     }
287 }
288
289 struct MovedVariablesCtxt<'a, 'tcx: 'a> {
290     cx: &'a LateContext<'a, 'tcx>,
291     moved_vars: HashSet<NodeId>,
292     /// Spans which need to be prefixed with `*` for dereferencing the
293     /// suggested additional reference.
294     spans_need_deref: HashMap<NodeId, HashSet<Span>>,
295 }
296
297 impl<'a, 'tcx> MovedVariablesCtxt<'a, 'tcx> {
298     fn new(cx: &'a LateContext<'a, 'tcx>) -> Self {
299         Self {
300             cx: cx,
301             moved_vars: HashSet::new(),
302             spans_need_deref: HashMap::new(),
303         }
304     }
305
306     fn move_common(&mut self, _consume_id: NodeId, _span: Span, cmt: mc::cmt<'tcx>) {
307         let cmt = unwrap_downcast_or_interior(cmt);
308
309         if let mc::Categorization::Local(vid) = cmt.cat {
310             self.moved_vars.insert(vid);
311         }
312     }
313
314     fn non_moving_pat(&mut self, matched_pat: &Pat, cmt: mc::cmt<'tcx>) {
315         let cmt = unwrap_downcast_or_interior(cmt);
316
317         if let mc::Categorization::Local(vid) = cmt.cat {
318             let mut id = matched_pat.id;
319             loop {
320                 let parent = self.cx.tcx.hir.get_parent_node(id);
321                 if id == parent {
322                     // no parent
323                     return;
324                 }
325                 id = parent;
326
327                 if let Some(node) = self.cx.tcx.hir.find(id) {
328                     match node {
329                         map::Node::NodeExpr(e) => {
330                             // `match` and `if let`
331                             if let ExprMatch(ref c, ..) = e.node {
332                                 self.spans_need_deref
333                                     .entry(vid)
334                                     .or_insert_with(HashSet::new)
335                                     .insert(c.span);
336                             }
337                         },
338
339                         map::Node::NodeStmt(s) => {
340                             // `let <pat> = x;`
341                             if_chain! {
342                                 if let StmtDecl(ref decl, _) = s.node;
343                                 if let DeclLocal(ref local) = decl.node;
344                                 then {
345                                     self.spans_need_deref
346                                         .entry(vid)
347                                         .or_insert_with(HashSet::new)
348                                         .insert(local.init
349                                             .as_ref()
350                                             .map(|e| e.span)
351                                             .expect("`let` stmt without init aren't caught by match_pat"));
352                                 }
353                             }
354                         },
355
356                         _ => {},
357                     }
358                 }
359             }
360         }
361     }
362 }
363
364 impl<'a, 'tcx> euv::Delegate<'tcx> for MovedVariablesCtxt<'a, 'tcx> {
365     fn consume(&mut self, consume_id: NodeId, consume_span: Span, cmt: mc::cmt<'tcx>, mode: euv::ConsumeMode) {
366         if let euv::ConsumeMode::Move(_) = mode {
367             self.move_common(consume_id, consume_span, cmt);
368         }
369     }
370
371     fn matched_pat(&mut self, matched_pat: &Pat, cmt: mc::cmt<'tcx>, mode: euv::MatchMode) {
372         if let euv::MatchMode::MovingMatch = mode {
373             self.move_common(matched_pat.id, matched_pat.span, cmt);
374         } else {
375             self.non_moving_pat(matched_pat, cmt);
376         }
377     }
378
379     fn consume_pat(&mut self, consume_pat: &Pat, cmt: mc::cmt<'tcx>, mode: euv::ConsumeMode) {
380         if let euv::ConsumeMode::Move(_) = mode {
381             self.move_common(consume_pat.id, consume_pat.span, cmt);
382         }
383     }
384
385     fn borrow(&mut self, _: NodeId, _: Span, _: mc::cmt<'tcx>, _: ty::Region, _: ty::BorrowKind, _: euv::LoanCause) {}
386
387     fn mutate(&mut self, _: NodeId, _: Span, _: mc::cmt<'tcx>, _: euv::MutateMode) {}
388
389     fn decl_without_init(&mut self, _: NodeId, _: Span) {}
390 }
391
392
393 fn unwrap_downcast_or_interior(mut cmt: mc::cmt) -> mc::cmt {
394     loop {
395         match cmt.cat.clone() {
396             mc::Categorization::Downcast(c, _) | mc::Categorization::Interior(c, _) => {
397                 cmt = c;
398             },
399             _ => return cmt,
400         }
401     }
402 }