]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/needless_pass_by_value.rs
Remove intermediate vec
[rust.git] / clippy_lints / src / needless_pass_by_value.rs
1 use rustc::hir::*;
2 use rustc::hir::intravisit::FnKind;
3 use rustc::lint::*;
4 use rustc::ty::{self, RegionKind, TypeFoldable};
5 use rustc::traits;
6 use rustc::middle::expr_use_visitor as euv;
7 use rustc::middle::mem_categorization as mc;
8 use syntax::ast::NodeId;
9 use syntax_pos::Span;
10 use syntax::errors::DiagnosticBuilder;
11 use utils::{get_trait_def_id, implements_trait, in_macro, is_copy, is_self, match_type, multispan_sugg, paths,
12             snippet, snippet_opt, span_lint_and_then};
13 use utils::ptr::get_spans;
14 use std::collections::{HashMap, HashSet};
15 use std::borrow::Cow;
16
17 /// **What it does:** Checks for functions taking arguments by value, but not
18 /// consuming them in its
19 /// body.
20 ///
21 /// **Why is this bad?** Taking arguments by reference is more flexible and can
22 /// sometimes avoid
23 /// unnecessary allocations.
24 ///
25 /// **Known problems:** Hopefully none.
26 ///
27 /// **Example:**
28 /// ```rust
29 /// fn foo(v: Vec<i32>) {
30 ///     assert_eq!(v.len(), 42);
31 /// }
32 /// ```
33 declare_lint! {
34     pub NEEDLESS_PASS_BY_VALUE,
35     Warn,
36     "functions taking arguments by value, but not consuming them in its body"
37 }
38
39 pub struct NeedlessPassByValue;
40
41 impl LintPass for NeedlessPassByValue {
42     fn get_lints(&self) -> LintArray {
43         lint_array![NEEDLESS_PASS_BY_VALUE]
44     }
45 }
46
47 macro_rules! need {
48     ($e: expr) => { if let Some(x) = $e { x } else { return; } };
49 }
50
51 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessPassByValue {
52     fn check_fn(
53         &mut self,
54         cx: &LateContext<'a, 'tcx>,
55         kind: FnKind<'tcx>,
56         decl: &'tcx FnDecl,
57         body: &'tcx Body,
58         span: Span,
59         node_id: NodeId,
60     ) {
61         if in_macro(span) {
62             return;
63         }
64
65         match kind {
66             FnKind::ItemFn(.., attrs) => for a in attrs {
67                 if_let_chain!{[
68                     a.meta_item_list().is_some(),
69                     let Some(name) = a.name(),
70                     name == "proc_macro_derive",
71                 ], {
72                     return;
73                 }}
74             },
75             _ => return,
76         }
77
78         // Allow `Borrow` or functions to be taken by value
79         let borrow_trait = need!(get_trait_def_id(cx, &paths::BORROW_TRAIT));
80         let fn_traits = [
81             need!(cx.tcx.lang_items().fn_trait()),
82             need!(cx.tcx.lang_items().fn_once_trait()),
83             need!(cx.tcx.lang_items().fn_mut_trait()),
84         ];
85
86         let sized_trait = need!(cx.tcx.lang_items().sized_trait());
87
88         let fn_def_id = cx.tcx.hir.local_def_id(node_id);
89
90         let preds = traits::elaborate_predicates(cx.tcx, cx.param_env.caller_bounds.to_vec())
91             .filter(|p| !p.is_global())
92             .filter_map(|pred| if let ty::Predicate::Trait(poly_trait_ref) = pred {
93                 if poly_trait_ref.def_id() == sized_trait || poly_trait_ref.skip_binder().has_escaping_regions() {
94                     return None;
95                 }
96                 Some(poly_trait_ref)
97             } else {
98                 None
99             })
100             .collect::<Vec<_>>();
101
102         // Collect moved variables and spans which will need dereferencings from the
103         // function body.
104         let MovedVariablesCtxt {
105             moved_vars,
106             spans_need_deref,
107             ..
108         } = {
109             let mut ctx = MovedVariablesCtxt::new(cx);
110             let region_scope_tree = &cx.tcx.region_scope_tree(fn_def_id);
111             euv::ExprUseVisitor::new(&mut ctx, cx.tcx, cx.param_env, region_scope_tree, cx.tables).consume_body(body);
112             ctx
113         };
114
115         let fn_sig = cx.tcx.fn_sig(fn_def_id);
116         let fn_sig = cx.tcx.erase_late_bound_regions(&fn_sig);
117
118         for (idx, ((input, &ty), arg)) in decl.inputs
119             .iter()
120             .zip(fn_sig.inputs())
121             .zip(&body.arguments)
122             .enumerate()
123         {
124             // * Exclude a type that is specifically bounded by `Borrow`.
125             // * Exclude a type whose reference also fulfills its bound.
126             //   (e.g. `std::convert::AsRef`, `serde::Serialize`)
127             let (implements_borrow_trait, all_borrowable_trait) = {
128                 let preds = preds
129                     .iter()
130                     .filter(|t| t.skip_binder().self_ty() == ty)
131                     .collect::<Vec<_>>();
132
133                 (
134                     preds.iter().any(|t| t.def_id() == borrow_trait),
135                     !preds.is_empty() && preds.iter().all(|t| {
136                         implements_trait(
137                             cx,
138                             cx.tcx.mk_imm_ref(&RegionKind::ReErased, ty),
139                             t.def_id(),
140                             &t.skip_binder().input_types().skip(1).collect::<Vec<_>>(),
141                         )
142                     }),
143                 )
144             };
145
146             if_let_chain! {[
147                 !is_self(arg),
148                 !ty.is_mutable_pointer(),
149                 !is_copy(cx, ty),
150                 !fn_traits.iter().any(|&t| implements_trait(cx, ty, t, &[])),
151                 !implements_borrow_trait,
152                 !all_borrowable_trait,
153
154                 let PatKind::Binding(mode, canonical_id, ..) = arg.pat.node,
155                 !moved_vars.contains(&canonical_id),
156             ], {
157                 if mode == BindingAnnotation::Mutable || mode == BindingAnnotation::RefMut {
158                     continue;
159                 }
160
161                 // Dereference suggestion
162                 let sugg = |db: &mut DiagnosticBuilder| {
163                     let deref_span = spans_need_deref.get(&canonical_id);
164                     if_let_chain! {[
165                         match_type(cx, ty, &paths::VEC),
166                         let Some(clone_spans) =
167                             get_spans(cx, Some(body.id()), idx, &[("clone", ".to_owned()")]),
168                         let TyPath(QPath::Resolved(_, ref path)) = input.node,
169                         let Some(elem_ty) = path.segments.iter()
170                             .find(|seg| seg.name == "Vec")
171                             .and_then(|ps| ps.parameters.as_ref())
172                             .map(|params| &params.types[0]),
173                     ], {
174                         let slice_ty = format!("&[{}]", snippet(cx, elem_ty.span, "_"));
175                         db.span_suggestion(input.span,
176                                         "consider changing the type to",
177                                         slice_ty);
178
179                         for (span, suggestion) in clone_spans {
180                             db.span_suggestion(
181                                 span,
182                                 &snippet_opt(cx, span)
183                                     .map_or(
184                                         "change the call to".into(),
185                                         |x| Cow::from(format!("change `{}` to", x)),
186                                     ),
187                                 suggestion.into()
188                             );
189                         }
190
191                         // cannot be destructured, no need for `*` suggestion
192                         assert!(deref_span.is_none());
193                         return;
194                     }}
195
196                     if match_type(cx, ty, &paths::STRING) {
197                         if let Some(clone_spans) =
198                             get_spans(cx, Some(body.id()), idx, &[("clone", ".to_string()"), ("as_str", "")]) {
199                             db.span_suggestion(input.span, "consider changing the type to", "&str".to_string());
200
201                             for (span, suggestion) in clone_spans {
202                                 db.span_suggestion(
203                                     span,
204                                     &snippet_opt(cx, span)
205                                         .map_or(
206                                             "change the call to".into(),
207                                             |x| Cow::from(format!("change `{}` to", x))
208                                         ),
209                                     suggestion.into(),
210                                 );
211                             }
212
213                             assert!(deref_span.is_none());
214                             return;
215                         }
216                     }
217
218                     let mut spans = vec![(input.span, format!("&{}", snippet(cx, input.span, "_")))];
219
220                     // Suggests adding `*` to dereference the added reference.
221                     if let Some(deref_span) = deref_span {
222                         spans.extend(
223                             deref_span
224                                 .iter()
225                                 .cloned()
226                                 .map(|span| (span, format!("*{}", snippet(cx, span, "<expr>")))),
227                         );
228                         spans.sort_by_key(|&(span, _)| span);
229                     }
230                     multispan_sugg(db, "consider taking a reference instead".to_string(), spans);
231                 };
232
233                 span_lint_and_then(
234                     cx,
235                     NEEDLESS_PASS_BY_VALUE,
236                     input.span,
237                     "this argument is passed by value, but not consumed in the function body",
238                     sugg,
239                 );
240             }}
241         }
242     }
243 }
244
245 struct MovedVariablesCtxt<'a, 'tcx: 'a> {
246     cx: &'a LateContext<'a, 'tcx>,
247     moved_vars: HashSet<NodeId>,
248     /// Spans which need to be prefixed with `*` for dereferencing the
249     /// suggested additional reference.
250     spans_need_deref: HashMap<NodeId, HashSet<Span>>,
251 }
252
253 impl<'a, 'tcx> MovedVariablesCtxt<'a, 'tcx> {
254     fn new(cx: &'a LateContext<'a, 'tcx>) -> Self {
255         Self {
256             cx: cx,
257             moved_vars: HashSet::new(),
258             spans_need_deref: HashMap::new(),
259         }
260     }
261
262     fn move_common(&mut self, _consume_id: NodeId, _span: Span, cmt: mc::cmt<'tcx>) {
263         let cmt = unwrap_downcast_or_interior(cmt);
264
265         if let mc::Categorization::Local(vid) = cmt.cat {
266             self.moved_vars.insert(vid);
267         }
268     }
269
270     fn non_moving_pat(&mut self, matched_pat: &Pat, cmt: mc::cmt<'tcx>) {
271         let cmt = unwrap_downcast_or_interior(cmt);
272
273         if let mc::Categorization::Local(vid) = cmt.cat {
274             let mut id = matched_pat.id;
275             loop {
276                 let parent = self.cx.tcx.hir.get_parent_node(id);
277                 if id == parent {
278                     // no parent
279                     return;
280                 }
281                 id = parent;
282
283                 if let Some(node) = self.cx.tcx.hir.find(id) {
284                     match node {
285                         map::Node::NodeExpr(e) => {
286                             // `match` and `if let`
287                             if let ExprMatch(ref c, ..) = e.node {
288                                 self.spans_need_deref
289                                     .entry(vid)
290                                     .or_insert_with(HashSet::new)
291                                     .insert(c.span);
292                             }
293                         },
294
295                         map::Node::NodeStmt(s) => {
296                             // `let <pat> = x;`
297                             if_let_chain! {[
298                                 let StmtDecl(ref decl, _) = s.node,
299                                 let DeclLocal(ref local) = decl.node,
300                             ], {
301                                 self.spans_need_deref
302                                     .entry(vid)
303                                     .or_insert_with(HashSet::new)
304                                     .insert(local.init
305                                         .as_ref()
306                                         .map(|e| e.span)
307                                         .expect("`let` stmt without init aren't caught by match_pat"));
308                             }}
309                         },
310
311                         _ => {},
312                     }
313                 }
314             }
315         }
316     }
317 }
318
319 impl<'a, 'tcx> euv::Delegate<'tcx> for MovedVariablesCtxt<'a, 'tcx> {
320     fn consume(&mut self, consume_id: NodeId, consume_span: Span, cmt: mc::cmt<'tcx>, mode: euv::ConsumeMode) {
321         if let euv::ConsumeMode::Move(_) = mode {
322             self.move_common(consume_id, consume_span, cmt);
323         }
324     }
325
326     fn matched_pat(&mut self, matched_pat: &Pat, cmt: mc::cmt<'tcx>, mode: euv::MatchMode) {
327         if let euv::MatchMode::MovingMatch = mode {
328             self.move_common(matched_pat.id, matched_pat.span, cmt);
329         } else {
330             self.non_moving_pat(matched_pat, cmt);
331         }
332     }
333
334     fn consume_pat(&mut self, consume_pat: &Pat, cmt: mc::cmt<'tcx>, mode: euv::ConsumeMode) {
335         if let euv::ConsumeMode::Move(_) = mode {
336             self.move_common(consume_pat.id, consume_pat.span, cmt);
337         }
338     }
339
340     fn borrow(&mut self, _: NodeId, _: Span, _: mc::cmt<'tcx>, _: ty::Region, _: ty::BorrowKind, _: euv::LoanCause) {}
341
342     fn mutate(&mut self, _: NodeId, _: Span, _: mc::cmt<'tcx>, _: euv::MutateMode) {}
343
344     fn decl_without_init(&mut self, _: NodeId, _: Span) {}
345 }
346
347
348 fn unwrap_downcast_or_interior(mut cmt: mc::cmt) -> mc::cmt {
349     loop {
350         match cmt.cat.clone() {
351             mc::Categorization::Downcast(c, _) | mc::Categorization::Interior(c, _) => {
352                 cmt = c;
353             },
354             _ => return cmt,
355         }
356     }
357 }