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