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