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