]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/needless_pass_by_value.rs
Auto merge of #4254 - lzutao:hiridification-62168, r=Manishearth
[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.tcx.hir().find(cx.tcx.hir().get_parent_node(hir_id)) {
92             if matches!(item.node, ItemKind::Impl(_, _, _, _, Some(_), _, _) |
93                 ItemKind::Trait(..))
94             {
95                 return;
96             }
97         }
98
99         // Allow `Borrow` or functions to be taken by value
100         let borrow_trait = need!(get_trait_def_id(cx, &paths::BORROW_TRAIT));
101         let whitelisted_traits = [
102             need!(cx.tcx.lang_items().fn_trait()),
103             need!(cx.tcx.lang_items().fn_once_trait()),
104             need!(cx.tcx.lang_items().fn_mut_trait()),
105             need!(get_trait_def_id(cx, &paths::RANGE_ARGUMENT_TRAIT)),
106         ];
107
108         let sized_trait = need!(cx.tcx.lang_items().sized_trait());
109
110         let fn_def_id = cx.tcx.hir().local_def_id(hir_id);
111
112         let preds = traits::elaborate_predicates(cx.tcx, cx.param_env.caller_bounds.to_vec())
113             .filter(|p| !p.is_global())
114             .filter_map(|pred| {
115                 if let ty::Predicate::Trait(poly_trait_ref) = pred {
116                     if poly_trait_ref.def_id() == sized_trait || poly_trait_ref.skip_binder().has_escaping_bound_vars()
117                     {
118                         return None;
119                     }
120                     Some(poly_trait_ref)
121                 } else {
122                     None
123                 }
124             })
125             .collect::<Vec<_>>();
126
127         // Collect moved variables and spans which will need dereferencings from the
128         // function body.
129         let MovedVariablesCtxt {
130             moved_vars,
131             spans_need_deref,
132             ..
133         } = {
134             let mut ctx = MovedVariablesCtxt::new(cx);
135             let region_scope_tree = &cx.tcx.region_scope_tree(fn_def_id);
136             euv::ExprUseVisitor::new(
137                 &mut ctx,
138                 cx.tcx,
139                 fn_def_id,
140                 cx.param_env,
141                 region_scope_tree,
142                 cx.tables,
143                 None,
144             )
145             .consume_body(body);
146             ctx
147         };
148
149         let fn_sig = cx.tcx.fn_sig(fn_def_id);
150         let fn_sig = cx.tcx.erase_late_bound_regions(&fn_sig);
151
152         for (idx, ((input, &ty), arg)) in decl.inputs.iter().zip(fn_sig.inputs()).zip(&body.arguments).enumerate() {
153             // All spans generated from a proc-macro invocation are the same...
154             if span == input.span {
155                 return;
156             }
157
158             // Ignore `self`s.
159             if idx == 0 {
160                 if let PatKind::Binding(.., ident, _) = arg.pat.node {
161                     if ident.as_str() == "self" {
162                         continue;
163                     }
164                 }
165             }
166
167             //
168             // * Exclude a type that is specifically bounded by `Borrow`.
169             // * Exclude a type whose reference also fulfills its bound. (e.g., `std::convert::AsRef`,
170             //   `serde::Serialize`)
171             let (implements_borrow_trait, all_borrowable_trait) = {
172                 let preds = preds
173                     .iter()
174                     .filter(|t| t.skip_binder().self_ty() == ty)
175                     .collect::<Vec<_>>();
176
177                 (
178                     preds.iter().any(|t| t.def_id() == borrow_trait),
179                     !preds.is_empty()
180                         && preds.iter().all(|t| {
181                             let ty_params = &t
182                                 .skip_binder()
183                                 .trait_ref
184                                 .substs
185                                 .iter()
186                                 .skip(1)
187                                 .cloned()
188                                 .collect::<Vec<_>>();
189                             implements_trait(cx, cx.tcx.mk_imm_ref(&RegionKind::ReEmpty, ty), t.def_id(), ty_params)
190                         }),
191                 )
192             };
193
194             if_chain! {
195                 if !is_self(arg);
196                 if !ty.is_mutable_pointer();
197                 if !is_copy(cx, ty);
198                 if !whitelisted_traits.iter().any(|&t| implements_trait(cx, ty, t, &[]));
199                 if !implements_borrow_trait;
200                 if !all_borrowable_trait;
201
202                 if let PatKind::Binding(mode, canonical_id, ..) = arg.pat.node;
203                 if !moved_vars.contains(&canonical_id);
204                 then {
205                     if mode == BindingAnnotation::Mutable || mode == BindingAnnotation::RefMut {
206                         continue;
207                     }
208
209                     // Dereference suggestion
210                     let sugg = |db: &mut DiagnosticBuilder<'_>| {
211                         if let ty::Adt(def, ..) = ty.sty {
212                             if let Some(span) = cx.tcx.hir().span_if_local(def.did) {
213                                 if cx.param_env.can_type_implement_copy(cx.tcx, ty).is_ok() {
214                                     db.span_help(span, "consider marking this type as Copy");
215                                 }
216                             }
217                         }
218
219                         let deref_span = spans_need_deref.get(&canonical_id);
220                         if_chain! {
221                             if match_type(cx, ty, &paths::VEC);
222                             if let Some(clone_spans) =
223                                 get_spans(cx, Some(body.id()), idx, &[("clone", ".to_owned()")]);
224                             if let TyKind::Path(QPath::Resolved(_, ref path)) = input.node;
225                             if let Some(elem_ty) = path.segments.iter()
226                                 .find(|seg| seg.ident.name == sym!(Vec))
227                                 .and_then(|ps| ps.args.as_ref())
228                                 .map(|params| params.args.iter().find_map(|arg| match arg {
229                                     GenericArg::Type(ty) => Some(ty),
230                                     _ => None,
231                                 }).unwrap());
232                             then {
233                                 let slice_ty = format!("&[{}]", snippet(cx, elem_ty.span, "_"));
234                                 db.span_suggestion(
235                                     input.span,
236                                     "consider changing the type to",
237                                     slice_ty,
238                                     Applicability::Unspecified,
239                                 );
240
241                                 for (span, suggestion) in clone_spans {
242                                     db.span_suggestion(
243                                         span,
244                                         &snippet_opt(cx, span)
245                                             .map_or(
246                                                 "change the call to".into(),
247                                                 |x| Cow::from(format!("change `{}` to", x)),
248                                             ),
249                                         suggestion.into(),
250                                         Applicability::Unspecified,
251                                     );
252                                 }
253
254                                 // cannot be destructured, no need for `*` suggestion
255                                 assert!(deref_span.is_none());
256                                 return;
257                             }
258                         }
259
260                         if match_type(cx, ty, &paths::STRING) {
261                             if let Some(clone_spans) =
262                                 get_spans(cx, Some(body.id()), idx, &[("clone", ".to_string()"), ("as_str", "")]) {
263                                 db.span_suggestion(
264                                     input.span,
265                                     "consider changing the type to",
266                                     "&str".to_string(),
267                                     Applicability::Unspecified,
268                                 );
269
270                                 for (span, suggestion) in clone_spans {
271                                     db.span_suggestion(
272                                         span,
273                                         &snippet_opt(cx, span)
274                                             .map_or(
275                                                 "change the call to".into(),
276                                                 |x| Cow::from(format!("change `{}` to", x))
277                                             ),
278                                         suggestion.into(),
279                                         Applicability::Unspecified,
280                                     );
281                                 }
282
283                                 assert!(deref_span.is_none());
284                                 return;
285                             }
286                         }
287
288                         let mut spans = vec![(input.span, format!("&{}", snippet(cx, input.span, "_")))];
289
290                         // Suggests adding `*` to dereference the added reference.
291                         if let Some(deref_span) = deref_span {
292                             spans.extend(
293                                 deref_span
294                                     .iter()
295                                     .cloned()
296                                     .map(|span| (span, format!("*{}", snippet(cx, span, "<expr>")))),
297                             );
298                             spans.sort_by_key(|&(span, _)| span);
299                         }
300                         multispan_sugg(db, "consider taking a reference instead".to_string(), spans);
301                     };
302
303                     span_lint_and_then(
304                         cx,
305                         NEEDLESS_PASS_BY_VALUE,
306                         input.span,
307                         "this argument is passed by value, but not consumed in the function body",
308                         sugg,
309                     );
310                 }
311             }
312         }
313     }
314 }
315
316 /// Functions marked with these attributes must have the exact signature.
317 fn requires_exact_signature(attrs: &[Attribute]) -> bool {
318     attrs.iter().any(|attr| {
319         [sym!(proc_macro), sym!(proc_macro_attribute), sym!(proc_macro_derive)]
320             .iter()
321             .any(|&allow| attr.check_name(allow))
322     })
323 }
324
325 struct MovedVariablesCtxt<'a, 'tcx> {
326     cx: &'a LateContext<'a, 'tcx>,
327     moved_vars: FxHashSet<HirId>,
328     /// Spans which need to be prefixed with `*` for dereferencing the
329     /// suggested additional reference.
330     spans_need_deref: FxHashMap<HirId, 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: HirId, _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.hir_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: HirId, 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.hir_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.hir_id, consume_pat.span, cmt);
417         }
418     }
419
420     fn borrow(
421         &mut self,
422         _: HirId,
423         _: Span,
424         _: &mc::cmt_<'tcx>,
425         _: ty::Region<'_>,
426         _: ty::BorrowKind,
427         _: euv::LoanCause,
428     ) {
429     }
430
431     fn mutate(&mut self, _: HirId, _: Span, _: &mc::cmt_<'tcx>, _: euv::MutateMode) {}
432
433     fn decl_without_init(&mut self, _: HirId, _: 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 }