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