]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/needless_pass_by_value.rs
Use span_suggestion_with_applicability instead of span_suggestion
[rust.git] / clippy_lints / src / needless_pass_by_value.rs
1 use matches::matches;
2 use crate::rustc::hir::*;
3 use crate::rustc::hir::intravisit::FnKind;
4 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
5 use crate::rustc::{declare_tool_lint, lint_array};
6 use if_chain::if_chain;
7 use crate::rustc::ty::{self, RegionKind, TypeFoldable};
8 use crate::rustc::traits;
9 use crate::rustc::middle::expr_use_visitor as euv;
10 use crate::rustc::middle::mem_categorization as mc;
11 use crate::rustc_target::spec::abi::Abi;
12 use crate::rustc_data_structures::fx::{FxHashMap, FxHashSet};
13 use crate::syntax::ast::NodeId;
14 use crate::syntax_pos::Span;
15 use crate::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 use crate::rustc_errors::Applicability;
21
22 /// **What it does:** Checks for functions taking arguments by value, but not
23 /// consuming them in its
24 /// body.
25 ///
26 /// **Why is this bad?** Taking arguments by reference is more flexible and can
27 /// sometimes avoid
28 /// unnecessary allocations.
29 ///
30 /// **Known problems:**
31 /// * This lint suggests taking an argument by reference,
32 /// however sometimes it is better to let users decide the argument type
33 /// (by using `Borrow` trait, for example), depending on how the function is used.
34 ///
35 /// **Example:**
36 /// ```rust
37 /// fn foo(v: Vec<i32>) {
38 ///     assert_eq!(v.len(), 42);
39 /// }
40 /// // should be
41 /// fn foo(v: &[i32]) {
42 ///     assert_eq!(v.len(), 42);
43 /// }
44 /// ```
45 declare_clippy_lint! {
46     pub NEEDLESS_PASS_BY_VALUE,
47     style,
48     "functions taking arguments by value, but not consuming them in its body"
49 }
50
51 pub struct NeedlessPassByValue;
52
53 impl LintPass for NeedlessPassByValue {
54     fn get_lints(&self) -> LintArray {
55         lint_array![NEEDLESS_PASS_BY_VALUE]
56     }
57 }
58
59 macro_rules! need {
60     ($e: expr) => { if let Some(x) = $e { x } else { return; } };
61 }
62
63 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessPassByValue {
64     fn check_fn(
65         &mut self,
66         cx: &LateContext<'a, 'tcx>,
67         kind: FnKind<'tcx>,
68         decl: &'tcx FnDecl,
69         body: &'tcx Body,
70         span: Span,
71         node_id: NodeId,
72     ) {
73         if in_macro(span) {
74             return;
75         }
76
77         match kind {
78             FnKind::ItemFn(.., header, _, attrs) => {
79                 if header.abi != Abi::Rust {
80                     return;
81                 }
82                 for a in attrs {
83                     if a.meta_item_list().is_some() && a.name() == "proc_macro_derive" {
84                         return;
85                     }
86                 }
87             },
88             FnKind::Method(..) => (),
89             _ => return,
90         }
91
92         // Exclude non-inherent impls
93         if let Some(Node::Item(item)) = cx.tcx.hir.find(cx.tcx.hir.get_parent_node(node_id)) {
94             if matches!(item.node, ItemKind::Impl(_, _, _, _, Some(_), _, _) |
95                 ItemKind::Trait(..))
96             {
97                 return;
98             }
99         }
100
101         // Allow `Borrow` or functions to be taken by value
102         let borrow_trait = need!(get_trait_def_id(cx, &paths::BORROW_TRAIT));
103         let whitelisted_traits = [
104             need!(cx.tcx.lang_items().fn_trait()),
105             need!(cx.tcx.lang_items().fn_once_trait()),
106             need!(cx.tcx.lang_items().fn_mut_trait()),
107             need!(get_trait_def_id(cx, &paths::RANGE_ARGUMENT_TRAIT))
108         ];
109
110         let sized_trait = need!(cx.tcx.lang_items().sized_trait());
111
112         let fn_def_id = cx.tcx.hir.local_def_id(node_id);
113
114         let preds = traits::elaborate_predicates(cx.tcx, cx.param_env.caller_bounds.to_vec())
115             .filter(|p| !p.is_global())
116             .filter_map(|pred| {
117                 if let ty::Predicate::Trait(poly_trait_ref) = pred {
118                     if poly_trait_ref.def_id() == sized_trait || poly_trait_ref.skip_binder().has_escaping_regions() {
119                         return None;
120                     }
121                     Some(poly_trait_ref)
122                 } else {
123                     None
124                 }
125             })
126             .collect::<Vec<_>>();
127
128         // Collect moved variables and spans which will need dereferencings from the
129         // function body.
130         let MovedVariablesCtxt {
131             moved_vars,
132             spans_need_deref,
133             ..
134         } = {
135             let mut ctx = MovedVariablesCtxt::new(cx);
136             let region_scope_tree = &cx.tcx.region_scope_tree(fn_def_id);
137             euv::ExprUseVisitor::new(&mut ctx, cx.tcx, cx.param_env, region_scope_tree, cx.tables, None)
138                 .consume_body(body);
139             ctx
140         };
141
142         let fn_sig = cx.tcx.fn_sig(fn_def_id);
143         let fn_sig = cx.tcx.erase_late_bound_regions(&fn_sig);
144
145         for (idx, ((input, &ty), arg)) in decl.inputs
146             .iter()
147             .zip(fn_sig.inputs())
148             .zip(&body.arguments)
149             .enumerate()
150         {
151             // All spans generated from a proc-macro invocation are the same...
152             if span == input.span {
153                 return;
154             }
155
156             // Ignore `self`s.
157             if idx == 0 {
158                 if let PatKind::Binding(_, _, ident, ..) = arg.pat.node {
159                     if ident.as_str() == "self" {
160                         continue;
161                     }
162                 }
163             }
164
165             // * Exclude a type that is specifically bounded by `Borrow`.
166             // * Exclude a type whose reference also fulfills its bound.
167             //   (e.g. `std::convert::AsRef`, `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() && preds.iter().all(|t| {
177                         implements_trait(
178                             cx,
179                             cx.tcx.mk_imm_ref(&RegionKind::ReErased, ty),
180                             t.def_id(),
181                             &t.skip_binder()
182                                 .input_types()
183                                 .skip(1)
184                                 .map(|ty| ty.into())
185                                 .collect::<Vec<_>>(),
186                         )
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::TyKind::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, &[("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 == "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                                     GenericArg::Lifetime(_) => None,
228                                 }).unwrap());
229                             then {
230                                 let slice_ty = format!("&[{}]", snippet(cx, elem_ty.span, "_"));
231                                 db.span_suggestion_with_applicability(
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_with_applicability(
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, &[("clone", ".to_string()"), ("as_str", "")]) {
260                                 db.span_suggestion_with_applicability(
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_with_applicability(
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 struct MovedVariablesCtxt<'a, 'tcx: 'a> {
314     cx: &'a LateContext<'a, 'tcx>,
315     moved_vars: FxHashSet<NodeId>,
316     /// Spans which need to be prefixed with `*` for dereferencing the
317     /// suggested additional reference.
318     spans_need_deref: FxHashMap<NodeId, FxHashSet<Span>>,
319 }
320
321 impl<'a, 'tcx> MovedVariablesCtxt<'a, 'tcx> {
322     fn new(cx: &'a LateContext<'a, 'tcx>) -> Self {
323         Self {
324             cx,
325             moved_vars: FxHashSet::default(),
326             spans_need_deref: FxHashMap::default(),
327         }
328     }
329
330     fn move_common(&mut self, _consume_id: NodeId, _span: Span, cmt: &mc::cmt_<'tcx>) {
331         let cmt = unwrap_downcast_or_interior(cmt);
332
333         if let mc::Categorization::Local(vid) = cmt.cat {
334             self.moved_vars.insert(vid);
335         }
336     }
337
338     fn non_moving_pat(&mut self, matched_pat: &Pat, cmt: &mc::cmt_<'tcx>) {
339         let cmt = unwrap_downcast_or_interior(cmt);
340
341         if let mc::Categorization::Local(vid) = cmt.cat {
342             let mut id = matched_pat.id;
343             loop {
344                 let parent = self.cx.tcx.hir.get_parent_node(id);
345                 if id == parent {
346                     // no parent
347                     return;
348                 }
349                 id = parent;
350
351                 if let Some(node) = self.cx.tcx.hir.find(id) {
352                     match node {
353                         Node::Expr(e) => {
354                             // `match` and `if let`
355                             if let ExprKind::Match(ref c, ..) = e.node {
356                                 self.spans_need_deref
357                                     .entry(vid)
358                                     .or_insert_with(FxHashSet::default)
359                                     .insert(c.span);
360                             }
361                         },
362
363                         Node::Stmt(s) => {
364                             // `let <pat> = x;`
365                             if_chain! {
366                                 if let StmtKind::Decl(ref decl, _) = s.node;
367                                 if let DeclKind::Local(ref local) = decl.node;
368                                 then {
369                                     self.spans_need_deref
370                                         .entry(vid)
371                                         .or_insert_with(FxHashSet::default)
372                                         .insert(local.init
373                                             .as_ref()
374                                             .map(|e| e.span)
375                                             .expect("`let` stmt without init aren't caught by match_pat"));
376                                 }
377                             }
378                         },
379
380                         _ => {},
381                     }
382                 }
383             }
384         }
385     }
386 }
387
388 impl<'a, 'tcx> euv::Delegate<'tcx> for MovedVariablesCtxt<'a, 'tcx> {
389     fn consume(&mut self, consume_id: NodeId, consume_span: Span, cmt: &mc::cmt_<'tcx>, mode: euv::ConsumeMode) {
390         if let euv::ConsumeMode::Move(_) = mode {
391             self.move_common(consume_id, consume_span, cmt);
392         }
393     }
394
395     fn matched_pat(&mut self, matched_pat: &Pat, cmt: &mc::cmt_<'tcx>, mode: euv::MatchMode) {
396         if let euv::MatchMode::MovingMatch = mode {
397             self.move_common(matched_pat.id, matched_pat.span, cmt);
398         } else {
399             self.non_moving_pat(matched_pat, cmt);
400         }
401     }
402
403     fn consume_pat(&mut self, consume_pat: &Pat, cmt: &mc::cmt_<'tcx>, mode: euv::ConsumeMode) {
404         if let euv::ConsumeMode::Move(_) = mode {
405             self.move_common(consume_pat.id, consume_pat.span, cmt);
406         }
407     }
408
409     fn borrow(&mut self, _: NodeId, _: Span, _: &mc::cmt_<'tcx>, _: ty::Region<'_>, _: ty::BorrowKind, _: euv::LoanCause) {}
410
411     fn mutate(&mut self, _: NodeId, _: Span, _: &mc::cmt_<'tcx>, _: euv::MutateMode) {}
412
413     fn decl_without_init(&mut self, _: NodeId, _: Span) {}
414 }
415
416
417 fn unwrap_downcast_or_interior<'a, 'tcx>(mut cmt: &'a mc::cmt_<'tcx>) -> mc::cmt_<'tcx> {
418     loop {
419         match cmt.cat {
420             mc::Categorization::Downcast(ref c, _) | mc::Categorization::Interior(ref c, _) => {
421                 cmt = c;
422             },
423             _ => return (*cmt).clone(),
424         }
425     };
426 }