]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/needless_pass_by_value.rs
Merge branch 'master' into issue_2741
[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 rustc_target::spec::abi::Abi;
10 use syntax::ast::NodeId;
11 use syntax_pos::Span;
12 use syntax::errors::DiagnosticBuilder;
13 use crate::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 crate::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_clippy_lint! {
43     pub NEEDLESS_PASS_BY_VALUE,
44     style,
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(.., header, _, attrs) => {
76                 if header.abi != Abi::Rust {
77                     return;
78                 }
79                 for a in attrs {
80                     if a.meta_item_list().is_some() && a.name() == "proc_macro_derive" {
81                         return;
82                     }
83                 }
84             },
85             FnKind::Method(..) => (),
86             _ => return,
87         }
88
89         // Exclude non-inherent impls
90         if let Some(NodeItem(item)) = cx.tcx.hir.find(cx.tcx.hir.get_parent_node(node_id)) {
91             if matches!(item.node, ItemImpl(_, _, _, _, Some(_), _, _) |
92                 ItemTrait(..))
93             {
94                 return;
95             }
96         }
97
98         // Allow `Borrow` or functions to be taken by value
99         let borrow_trait = need!(get_trait_def_id(cx, &paths::BORROW_TRAIT));
100         let whitelisted_traits = [
101             need!(cx.tcx.lang_items().fn_trait()),
102             need!(cx.tcx.lang_items().fn_once_trait()),
103             need!(cx.tcx.lang_items().fn_mut_trait()),
104             need!(get_trait_def_id(cx, &paths::RANGE_ARGUMENT_TRAIT))
105         ];
106
107         let sized_trait = need!(cx.tcx.lang_items().sized_trait());
108
109         let fn_def_id = cx.tcx.hir.local_def_id(node_id);
110
111         let preds = traits::elaborate_predicates(cx.tcx, cx.param_env.caller_bounds.to_vec())
112             .filter(|p| !p.is_global())
113             .filter_map(|pred| {
114                 if let ty::Predicate::Trait(poly_trait_ref) = pred {
115                     if poly_trait_ref.def_id() == sized_trait || poly_trait_ref.skip_binder().has_escaping_regions() {
116                         return None;
117                     }
118                     Some(poly_trait_ref)
119                 } else {
120                     None
121                 }
122             })
123             .collect::<Vec<_>>();
124
125         // Collect moved variables and spans which will need dereferencings from the
126         // function body.
127         let MovedVariablesCtxt {
128             moved_vars,
129             spans_need_deref,
130             ..
131         } = {
132             let mut ctx = MovedVariablesCtxt::new(cx);
133             let region_scope_tree = &cx.tcx.region_scope_tree(fn_def_id);
134             euv::ExprUseVisitor::new(&mut ctx, cx.tcx, cx.param_env, region_scope_tree, cx.tables, None)
135                 .consume_body(body);
136             ctx
137         };
138
139         let fn_sig = cx.tcx.fn_sig(fn_def_id);
140         let fn_sig = cx.tcx.erase_late_bound_regions(&fn_sig);
141
142         for (idx, ((input, &ty), arg)) in decl.inputs
143             .iter()
144             .zip(fn_sig.inputs())
145             .zip(&body.arguments)
146             .enumerate()
147         {
148             // All spans generated from a proc-macro invocation are the same...
149             if span == input.span {
150                 return;
151             }
152
153             // Ignore `self`s.
154             if idx == 0 {
155                 if let PatKind::Binding(_, _, name, ..) = arg.pat.node {
156                     if name.node.as_str() == "self" {
157                         continue;
158                     }
159                 }
160             }
161
162             // * Exclude a type that is specifically bounded by `Borrow`.
163             // * Exclude a type whose reference also fulfills its bound.
164             //   (e.g. `std::convert::AsRef`, `serde::Serialize`)
165             let (implements_borrow_trait, all_borrowable_trait) = {
166                 let preds = preds
167                     .iter()
168                     .filter(|t| t.skip_binder().self_ty() == ty)
169                     .collect::<Vec<_>>();
170
171                 (
172                     preds.iter().any(|t| t.def_id() == borrow_trait),
173                     !preds.is_empty() && preds.iter().all(|t| {
174                         implements_trait(
175                             cx,
176                             cx.tcx.mk_imm_ref(&RegionKind::ReErased, ty),
177                             t.def_id(),
178                             &t.skip_binder()
179                                 .input_types()
180                                 .skip(1)
181                                 .map(|ty| ty.into())
182                                 .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 !whitelisted_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                         if let ty::TypeVariants::TyAdt(def, ..) = ty.sty {
206                             if let Some(span) = cx.tcx.hir.span_if_local(def.did) {
207                                 if cx.param_env.can_type_implement_copy(cx.tcx, ty).is_ok() {
208                                     db.span_help(span, "consider marking this type as Copy");
209                                 }
210                             }
211                         }
212
213                         let deref_span = spans_need_deref.get(&canonical_id);
214                         if_chain! {
215                             if match_type(cx, ty, &paths::VEC);
216                             if let Some(clone_spans) =
217                                 get_spans(cx, Some(body.id()), idx, &[("clone", ".to_owned()")]);
218                             if let TyPath(QPath::Resolved(_, ref path)) = input.node;
219                             if let Some(elem_ty) = path.segments.iter()
220                                 .find(|seg| seg.name == "Vec")
221                                 .and_then(|ps| ps.args.as_ref())
222                                 .map(|params| params.args.iter().find_map(|arg| match arg {
223                                     GenericArg::Type(ty) => Some(ty),
224                                     GenericArg::Lifetime(_) => None,
225                                 }).unwrap());
226                             then {
227                                 let slice_ty = format!("&[{}]", snippet(cx, elem_ty.span, "_"));
228                                 db.span_suggestion(input.span,
229                                                 "consider changing the type to",
230                                                 slice_ty);
231
232                                 for (span, suggestion) in clone_spans {
233                                     db.span_suggestion(
234                                         span,
235                                         &snippet_opt(cx, span)
236                                             .map_or(
237                                                 "change the call to".into(),
238                                                 |x| Cow::from(format!("change `{}` to", x)),
239                                             ),
240                                         suggestion.into()
241                                     );
242                                 }
243
244                                 // cannot be destructured, no need for `*` suggestion
245                                 assert!(deref_span.is_none());
246                                 return;
247                             }
248                         }
249
250                         if match_type(cx, ty, &paths::STRING) {
251                             if let Some(clone_spans) =
252                                 get_spans(cx, Some(body.id()), idx, &[("clone", ".to_string()"), ("as_str", "")]) {
253                                 db.span_suggestion(input.span, "consider changing the type to", "&str".to_string());
254
255                                 for (span, suggestion) in clone_spans {
256                                     db.span_suggestion(
257                                         span,
258                                         &snippet_opt(cx, span)
259                                             .map_or(
260                                                 "change the call to".into(),
261                                                 |x| Cow::from(format!("change `{}` to", x))
262                                             ),
263                                         suggestion.into(),
264                                     );
265                                 }
266
267                                 assert!(deref_span.is_none());
268                                 return;
269                             }
270                         }
271
272                         let mut spans = vec![(input.span, format!("&{}", snippet(cx, input.span, "_")))];
273
274                         // Suggests adding `*` to dereference the added reference.
275                         if let Some(deref_span) = deref_span {
276                             spans.extend(
277                                 deref_span
278                                     .iter()
279                                     .cloned()
280                                     .map(|span| (span, format!("*{}", snippet(cx, span, "<expr>")))),
281                             );
282                             spans.sort_by_key(|&(span, _)| span);
283                         }
284                         multispan_sugg(db, "consider taking a reference instead".to_string(), spans);
285                     };
286
287                     span_lint_and_then(
288                         cx,
289                         NEEDLESS_PASS_BY_VALUE,
290                         input.span,
291                         "this argument is passed by value, but not consumed in the function body",
292                         sugg,
293                     );
294                 }
295             }
296         }
297     }
298 }
299
300 struct MovedVariablesCtxt<'a, 'tcx: 'a> {
301     cx: &'a LateContext<'a, 'tcx>,
302     moved_vars: HashSet<NodeId>,
303     /// Spans which need to be prefixed with `*` for dereferencing the
304     /// suggested additional reference.
305     spans_need_deref: HashMap<NodeId, HashSet<Span>>,
306 }
307
308 impl<'a, 'tcx> MovedVariablesCtxt<'a, 'tcx> {
309     fn new(cx: &'a LateContext<'a, 'tcx>) -> Self {
310         Self {
311             cx,
312             moved_vars: HashSet::new(),
313             spans_need_deref: HashMap::new(),
314         }
315     }
316
317     fn move_common(&mut self, _consume_id: NodeId, _span: Span, cmt: &mc::cmt_<'tcx>) {
318         let cmt = unwrap_downcast_or_interior(cmt);
319
320         if let mc::Categorization::Local(vid) = cmt.cat {
321             self.moved_vars.insert(vid);
322         }
323     }
324
325     fn non_moving_pat(&mut self, matched_pat: &Pat, cmt: &mc::cmt_<'tcx>) {
326         let cmt = unwrap_downcast_or_interior(cmt);
327
328         if let mc::Categorization::Local(vid) = cmt.cat {
329             let mut id = matched_pat.id;
330             loop {
331                 let parent = self.cx.tcx.hir.get_parent_node(id);
332                 if id == parent {
333                     // no parent
334                     return;
335                 }
336                 id = parent;
337
338                 if let Some(node) = self.cx.tcx.hir.find(id) {
339                     match node {
340                         map::Node::NodeExpr(e) => {
341                             // `match` and `if let`
342                             if let ExprMatch(ref c, ..) = e.node {
343                                 self.spans_need_deref
344                                     .entry(vid)
345                                     .or_insert_with(HashSet::new)
346                                     .insert(c.span);
347                             }
348                         },
349
350                         map::Node::NodeStmt(s) => {
351                             // `let <pat> = x;`
352                             if_chain! {
353                                 if let StmtDecl(ref decl, _) = s.node;
354                                 if let DeclLocal(ref local) = decl.node;
355                                 then {
356                                     self.spans_need_deref
357                                         .entry(vid)
358                                         .or_insert_with(HashSet::new)
359                                         .insert(local.init
360                                             .as_ref()
361                                             .map(|e| e.span)
362                                             .expect("`let` stmt without init aren't caught by match_pat"));
363                                 }
364                             }
365                         },
366
367                         _ => {},
368                     }
369                 }
370             }
371         }
372     }
373 }
374
375 impl<'a, 'tcx> euv::Delegate<'tcx> for MovedVariablesCtxt<'a, 'tcx> {
376     fn consume(&mut self, consume_id: NodeId, consume_span: Span, cmt: &mc::cmt_<'tcx>, mode: euv::ConsumeMode) {
377         if let euv::ConsumeMode::Move(_) = mode {
378             self.move_common(consume_id, consume_span, cmt);
379         }
380     }
381
382     fn matched_pat(&mut self, matched_pat: &Pat, cmt: &mc::cmt_<'tcx>, mode: euv::MatchMode) {
383         if let euv::MatchMode::MovingMatch = mode {
384             self.move_common(matched_pat.id, matched_pat.span, cmt);
385         } else {
386             self.non_moving_pat(matched_pat, cmt);
387         }
388     }
389
390     fn consume_pat(&mut self, consume_pat: &Pat, cmt: &mc::cmt_<'tcx>, mode: euv::ConsumeMode) {
391         if let euv::ConsumeMode::Move(_) = mode {
392             self.move_common(consume_pat.id, consume_pat.span, cmt);
393         }
394     }
395
396     fn borrow(&mut self, _: NodeId, _: Span, _: &mc::cmt_<'tcx>, _: ty::Region, _: ty::BorrowKind, _: euv::LoanCause) {}
397
398     fn mutate(&mut self, _: NodeId, _: Span, _: &mc::cmt_<'tcx>, _: euv::MutateMode) {}
399
400     fn decl_without_init(&mut self, _: NodeId, _: Span) {}
401 }
402
403
404 fn unwrap_downcast_or_interior<'a, 'tcx>(mut cmt: &'a mc::cmt_<'tcx>) -> mc::cmt_<'tcx> {
405     loop {
406         match cmt.cat {
407             mc::Categorization::Downcast(ref c, _) | mc::Categorization::Interior(ref c, _) => {
408                 cmt = c;
409             },
410             _ => return (*cmt).clone(),
411         }
412     };
413 }