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