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