]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/needless_pass_by_value.rs
Merge pull request #1627 from Manishearth/dont-panic
[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(cx, span) {
59             return;
60         }
61
62         if !matches!(kind, FnKind::ItemFn(..)) {
63             return;
64         }
65
66         // Allows these to be passed by value.
67         let fn_trait = need!(cx.tcx.lang_items.fn_trait());
68         let asref_trait = need!(get_trait_def_id(cx, &paths::ASREF_TRAIT));
69         let borrow_trait = need!(get_trait_def_id(cx, &paths::BORROW_TRAIT));
70
71         let preds: Vec<ty::Predicate> = {
72             let parameter_env = ty::ParameterEnvironment::for_item(cx.tcx, node_id);
73             traits::elaborate_predicates(cx.tcx, parameter_env.caller_bounds.clone())
74                 .filter(|p| !p.is_global())
75                 .collect()
76         };
77
78         // Collect moved variables and spans which will need dereferencings from the function body.
79         let MovedVariablesCtxt { moved_vars, spans_need_deref, .. } = {
80             let mut ctx = MovedVariablesCtxt::new(cx);
81             let infcx = cx.tcx.borrowck_fake_infer_ctxt(body.id());
82             {
83                 let mut v = euv::ExprUseVisitor::new(&mut ctx, &infcx);
84                 v.consume_body(body);
85             }
86             ctx
87         };
88
89         let fn_def_id = cx.tcx.hir.local_def_id(node_id);
90         let param_env = ty::ParameterEnvironment::for_item(cx.tcx, node_id);
91         let fn_sig = cx.tcx.item_type(fn_def_id).fn_sig();
92         let fn_sig = cx.tcx.liberate_late_bound_regions(param_env.free_id_outlive, &fn_sig);
93
94         for ((input, ty), arg) in decl.inputs.iter().zip(fn_sig.inputs()).zip(&body.arguments) {
95
96             // Determines whether `ty` implements `Borrow<U>` (U != ty) specifically.
97             // This is needed due to the `Borrow<T> for T` blanket impl.
98             let implements_borrow_trait = preds.iter()
99                 .filter_map(|pred| if let ty::Predicate::Trait(ref poly_trait_ref) = *pred {
100                     Some(poly_trait_ref.skip_binder())
101                 } else {
102                     None
103                 })
104                 .filter(|tpred| tpred.def_id() == borrow_trait && &tpred.self_ty() == ty)
105                 .any(|tpred| &tpred.input_types().nth(1).expect("Borrow trait must have an parameter") != ty);
106
107             if_let_chain! {[
108                 !is_self(arg),
109                 !ty.is_mutable_pointer(),
110                 !is_copy(cx, ty, node_id),
111                 !implements_trait(cx, ty, fn_trait, &[], Some(node_id)),
112                 !implements_trait(cx, ty, asref_trait, &[], Some(node_id)),
113                 !implements_borrow_trait,
114
115                 let PatKind::Binding(mode, defid, ..) = arg.pat.node,
116                 !moved_vars.contains(&defid),
117             ], {
118                 // Note: `toplevel_ref_arg` warns if `BindByRef`
119                 let m = match mode {
120                     BindingMode::BindByRef(m) | BindingMode::BindByValue(m) => m,
121                 };
122                 if m == Mutability::MutMutable {
123                     continue;
124                 }
125
126                 // Suggestion logic
127                 let sugg = |db: &mut DiagnosticBuilder| {
128                     let deref_span = spans_need_deref.get(&defid);
129                     if_let_chain! {[
130                         match_type(cx, ty, &paths::VEC),
131                         let TyPath(QPath::Resolved(_, ref path)) = input.node,
132                         let Some(elem_ty) = path.segments.iter()
133                             .find(|seg| &*seg.name.as_str() == "Vec")
134                             .map(|ps| ps.parameters.types()[0]),
135                     ], {
136                         let slice_ty = format!("&[{}]", snippet(cx, elem_ty.span, "_"));
137                         db.span_suggestion(input.span,
138                                         &format!("consider changing the type to `{}`", slice_ty),
139                                         slice_ty);
140                         assert!(deref_span.is_none());
141                         return; // `Vec` and `String` cannot be destructured - no need for `*` suggestion
142                     }}
143
144                     if match_type(cx, ty, &paths::STRING) {
145                         db.span_suggestion(input.span,
146                                            "consider changing the type to `&str`",
147                                            "&str".to_string());
148                         assert!(deref_span.is_none());
149                         return;
150                     }
151
152                     let mut spans = vec![(input.span, format!("&{}", snippet(cx, input.span, "_")))];
153
154                     // Suggests adding `*` to dereference the added reference.
155                     if let Some(deref_span) = deref_span {
156                         spans.extend(deref_span.iter().cloned()
157                                      .map(|span| (span, format!("*{}", snippet(cx, span, "<expr>")))));
158                         spans.sort_by_key(|&(span, _)| span);
159                     }
160                     multispan_sugg(db, "consider taking a reference instead".to_string(), spans);
161                 };
162
163                 span_lint_and_then(cx,
164                           NEEDLESS_PASS_BY_VALUE,
165                           input.span,
166                           "this argument is passed by value, but not consumed in the function body",
167                           sugg);
168             }}
169         }
170     }
171 }
172
173 struct MovedVariablesCtxt<'a, 'tcx: 'a> {
174     cx: &'a LateContext<'a, 'tcx>,
175     moved_vars: HashSet<DefId>,
176     /// Spans which need to be prefixed with `*` for dereferencing the suggested additional
177     /// reference.
178     spans_need_deref: HashMap<DefId, HashSet<Span>>,
179 }
180
181 impl<'a, 'tcx: 'a> MovedVariablesCtxt<'a, 'tcx> {
182     fn new(cx: &'a LateContext<'a, 'tcx>) -> Self {
183         MovedVariablesCtxt {
184             cx: cx,
185             moved_vars: HashSet::new(),
186             spans_need_deref: HashMap::new(),
187         }
188     }
189
190     fn move_common(&mut self, _consume_id: NodeId, _span: Span, cmt: mc::cmt<'tcx>) {
191         let cmt = unwrap_downcast_or_interior(cmt);
192
193         if_let_chain! {[
194             let mc::Categorization::Local(vid) = cmt.cat,
195             let Some(def_id) = self.cx.tcx.hir.opt_local_def_id(vid),
196         ], {
197                 self.moved_vars.insert(def_id);
198         }}
199     }
200
201     fn non_moving_pat(&mut self, matched_pat: &Pat, cmt: mc::cmt<'tcx>) {
202         let cmt = unwrap_downcast_or_interior(cmt);
203
204         if_let_chain! {[
205             let mc::Categorization::Local(vid) = cmt.cat,
206             let Some(def_id) = self.cx.tcx.hir.opt_local_def_id(vid),
207         ], {
208             let mut id = matched_pat.id;
209             loop {
210                 let parent = self.cx.tcx.hir.get_parent_node(id);
211                 if id == parent {
212                     // no parent
213                     return;
214                 }
215                 id = parent;
216
217                 if let Some(node) = self.cx.tcx.hir.find(id) {
218                     match node {
219                         map::Node::NodeExpr(e) => {
220                             // `match` and `if let`
221                             if let ExprMatch(ref c, ..) = e.node {
222                                 self.spans_need_deref
223                                     .entry(def_id)
224                                     .or_insert_with(HashSet::new)
225                                     .insert(c.span);
226                             }
227                         }
228
229                         map::Node::NodeStmt(s) => {
230                             // `let <pat> = x;`
231                             if_let_chain! {[
232                                 let StmtDecl(ref decl, _) = s.node,
233                                 let DeclLocal(ref local) = decl.node,
234                             ], {
235                                 self.spans_need_deref
236                                     .entry(def_id)
237                                     .or_insert_with(HashSet::new)
238                                     .insert(local.init
239                                         .as_ref()
240                                         .map(|e| e.span)
241                                         .expect("`let` stmt without init aren't caught by match_pat"));
242                             }}
243                         }
244
245                         _ => {}
246                     }
247                 }
248             }
249         }}
250     }
251 }
252
253 impl<'a, 'tcx: 'a> euv::Delegate<'tcx> for MovedVariablesCtxt<'a, 'tcx> {
254     fn consume(&mut self, consume_id: NodeId, consume_span: Span, cmt: mc::cmt<'tcx>, mode: euv::ConsumeMode) {
255         if let euv::ConsumeMode::Move(_) = mode {
256             self.move_common(consume_id, consume_span, cmt);
257         }
258     }
259
260     fn matched_pat(&mut self, matched_pat: &Pat, cmt: mc::cmt<'tcx>, mode: euv::MatchMode) {
261         if let euv::MatchMode::MovingMatch = mode {
262             self.move_common(matched_pat.id, matched_pat.span, cmt);
263         } else {
264             self.non_moving_pat(matched_pat, cmt);
265         }
266     }
267
268     fn consume_pat(&mut self, consume_pat: &Pat, cmt: mc::cmt<'tcx>, mode: euv::ConsumeMode) {
269         if let euv::ConsumeMode::Move(_) = mode {
270             self.move_common(consume_pat.id, consume_pat.span, cmt);
271         }
272     }
273
274     fn borrow(
275         &mut self,
276         _: NodeId,
277         _: Span,
278         _: mc::cmt<'tcx>,
279         _: &'tcx ty::Region,
280         _: ty::BorrowKind,
281         _: euv::LoanCause
282     ) {
283     }
284
285     fn mutate(&mut self, _: NodeId, _: Span, _: mc::cmt<'tcx>, _: euv::MutateMode) {}
286
287     fn decl_without_init(&mut self, _: NodeId, _: Span) {}
288 }
289
290
291 fn unwrap_downcast_or_interior(mut cmt: mc::cmt) -> mc::cmt {
292     loop {
293         match cmt.cat.clone() {
294             mc::Categorization::Downcast(c, _) |
295             mc::Categorization::Interior(c, _) => {
296                 cmt = c;
297             },
298             _ => return cmt,
299         }
300     }
301 }