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