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