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