]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/needless_pass_by_value.rs
Rustup to rust-lang/rust#67979
[rust.git] / clippy_lints / src / needless_pass_by_value.rs
1 use crate::utils::ptr::get_spans;
2 use crate::utils::{
3     get_trait_def_id, implements_trait, is_copy, is_self, is_type_diagnostic_item, match_type, multispan_sugg, paths,
4     snippet, snippet_opt, span_lint_and_then,
5 };
6 use if_chain::if_chain;
7 use matches::matches;
8 use rustc::declare_lint_pass;
9 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
10 use rustc::traits;
11 use rustc::traits::misc::can_type_implement_copy;
12 use rustc::ty::{self, RegionKind, TypeFoldable};
13 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
14 use rustc_errors::Applicability;
15 use rustc_hir::intravisit::FnKind;
16 use rustc_hir::*;
17 use rustc_session::declare_tool_lint;
18 use rustc_span::{Span, Symbol};
19 use rustc_target::spec::abi::Abi;
20 use rustc_typeck::expr_use_visitor as euv;
21 use std::borrow::Cow;
22 use syntax::ast::Attribute;
23 use syntax::errors::DiagnosticBuilder;
24
25 declare_clippy_lint! {
26     /// **What it does:** Checks for functions taking arguments by value, but not
27     /// consuming them in its
28     /// body.
29     ///
30     /// **Why is this bad?** Taking arguments by reference is more flexible and can
31     /// sometimes avoid
32     /// unnecessary allocations.
33     ///
34     /// **Known problems:**
35     /// * This lint suggests taking an argument by reference,
36     /// however sometimes it is better to let users decide the argument type
37     /// (by using `Borrow` trait, for example), depending on how the function is used.
38     ///
39     /// **Example:**
40     /// ```rust
41     /// fn foo(v: Vec<i32>) {
42     ///     assert_eq!(v.len(), 42);
43     /// }
44     /// ```
45     ///
46     /// ```rust
47     /// // should be
48     /// fn foo(v: &[i32]) {
49     ///     assert_eq!(v.len(), 42);
50     /// }
51     /// ```
52     pub NEEDLESS_PASS_BY_VALUE,
53     pedantic,
54     "functions taking arguments by value, but not consuming them in its body"
55 }
56
57 declare_lint_pass!(NeedlessPassByValue => [NEEDLESS_PASS_BY_VALUE]);
58
59 macro_rules! need {
60     ($e: expr) => {
61         if let Some(x) = $e {
62             x
63         } else {
64             return;
65         }
66     };
67 }
68
69 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessPassByValue {
70     #[allow(clippy::too_many_lines)]
71     fn check_fn(
72         &mut self,
73         cx: &LateContext<'a, 'tcx>,
74         kind: FnKind<'tcx>,
75         decl: &'tcx FnDecl<'_>,
76         body: &'tcx Body<'_>,
77         span: Span,
78         hir_id: HirId,
79     ) {
80         if span.from_expansion() {
81             return;
82         }
83
84         match kind {
85             FnKind::ItemFn(.., header, _, attrs) => {
86                 if header.abi != Abi::Rust || requires_exact_signature(attrs) {
87                     return;
88                 }
89             },
90             FnKind::Method(..) => (),
91             _ => return,
92         }
93
94         // Exclude non-inherent impls
95         if let Some(Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_node(hir_id)) {
96             if matches!(item.kind, ItemKind::Impl(_, _, _, _, Some(_), _, _) |
97                 ItemKind::Trait(..))
98             {
99                 return;
100             }
101         }
102
103         // Allow `Borrow` or functions to be taken by value
104         let borrow_trait = need!(get_trait_def_id(cx, &paths::BORROW_TRAIT));
105         let whitelisted_traits = [
106             need!(cx.tcx.lang_items().fn_trait()),
107             need!(cx.tcx.lang_items().fn_once_trait()),
108             need!(cx.tcx.lang_items().fn_mut_trait()),
109             need!(get_trait_def_id(cx, &paths::RANGE_ARGUMENT_TRAIT)),
110         ];
111
112         let sized_trait = need!(cx.tcx.lang_items().sized_trait());
113
114         let fn_def_id = cx.tcx.hir().local_def_id(hir_id);
115
116         let preds = traits::elaborate_predicates(cx.tcx, cx.param_env.caller_bounds.to_vec())
117             .filter(|p| !p.is_global())
118             .filter_map(|pred| {
119                 if let ty::Predicate::Trait(poly_trait_ref) = pred {
120                     if poly_trait_ref.def_id() == sized_trait || poly_trait_ref.skip_binder().has_escaping_bound_vars()
121                     {
122                         return None;
123                     }
124                     Some(poly_trait_ref)
125                 } else {
126                     None
127                 }
128             })
129             .collect::<Vec<_>>();
130
131         // Collect moved variables and spans which will need dereferencings from the
132         // function body.
133         let MovedVariablesCtxt {
134             moved_vars,
135             spans_need_deref,
136             ..
137         } = {
138             let mut ctx = MovedVariablesCtxt::default();
139             cx.tcx.infer_ctxt().enter(|infcx| {
140                 euv::ExprUseVisitor::new(&mut ctx, &infcx, fn_def_id, cx.param_env, cx.tables).consume_body(body);
141             });
142             ctx
143         };
144
145         let fn_sig = cx.tcx.fn_sig(fn_def_id);
146         let fn_sig = cx.tcx.erase_late_bound_regions(&fn_sig);
147
148         for (idx, ((input, &ty), arg)) in decl.inputs.iter().zip(fn_sig.inputs()).zip(body.params).enumerate() {
149             // All spans generated from a proc-macro invocation are the same...
150             if span == input.span {
151                 return;
152             }
153
154             // Ignore `self`s.
155             if idx == 0 {
156                 if let PatKind::Binding(.., ident, _) = arg.pat.kind {
157                     if ident.as_str() == "self" {
158                         continue;
159                     }
160                 }
161             }
162
163             //
164             // * Exclude a type that is specifically bounded by `Borrow`.
165             // * Exclude a type whose reference also fulfills its bound. (e.g., `std::convert::AsRef`,
166             //   `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()
176                         && preds.iter().all(|t| {
177                             let ty_params = &t
178                                 .skip_binder()
179                                 .trait_ref
180                                 .substs
181                                 .iter()
182                                 .skip(1)
183                                 .cloned()
184                                 .collect::<Vec<_>>();
185                             implements_trait(cx, cx.tcx.mk_imm_ref(&RegionKind::ReEmpty, ty), t.def_id(), ty_params)
186                         }),
187                 )
188             };
189
190             if_chain! {
191                 if !is_self(arg);
192                 if !ty.is_mutable_ptr();
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.kind;
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::Adt(def, ..) = ty.kind {
208                             if let Some(span) = cx.tcx.hir().span_if_local(def.did) {
209                                 if can_type_implement_copy(cx.tcx, cx.param_env, 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 is_type_diagnostic_item(cx, ty, Symbol::intern("vec_type"));
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.kind;
221                             if let Some(elem_ty) = path.segments.iter()
222                                 .find(|seg| seg.ident.name == sym!(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                                     _ => None,
227                                 }).unwrap());
228                             then {
229                                 let slice_ty = format!("&[{}]", snippet(cx, elem_ty.span, "_"));
230                                 db.span_suggestion(
231                                     input.span,
232                                     "consider changing the type to",
233                                     slice_ty,
234                                     Applicability::Unspecified,
235                                 );
236
237                                 for (span, suggestion) in clone_spans {
238                                     db.span_suggestion(
239                                         span,
240                                         &snippet_opt(cx, span)
241                                             .map_or(
242                                                 "change the call to".into(),
243                                                 |x| Cow::from(format!("change `{}` to", x)),
244                                             ),
245                                         suggestion.into(),
246                                         Applicability::Unspecified,
247                                     );
248                                 }
249
250                                 // cannot be destructured, no need for `*` suggestion
251                                 assert!(deref_span.is_none());
252                                 return;
253                             }
254                         }
255
256                         if match_type(cx, ty, &paths::STRING) {
257                             if let Some(clone_spans) =
258                                 get_spans(cx, Some(body.id()), idx, &[("clone", ".to_string()"), ("as_str", "")]) {
259                                 db.span_suggestion(
260                                     input.span,
261                                     "consider changing the type to",
262                                     "&str".to_string(),
263                                     Applicability::Unspecified,
264                                 );
265
266                                 for (span, suggestion) in clone_spans {
267                                     db.span_suggestion(
268                                         span,
269                                         &snippet_opt(cx, span)
270                                             .map_or(
271                                                 "change the call to".into(),
272                                                 |x| Cow::from(format!("change `{}` to", x))
273                                             ),
274                                         suggestion.into(),
275                                         Applicability::Unspecified,
276                                     );
277                                 }
278
279                                 assert!(deref_span.is_none());
280                                 return;
281                             }
282                         }
283
284                         let mut spans = vec![(input.span, format!("&{}", snippet(cx, input.span, "_")))];
285
286                         // Suggests adding `*` to dereference the added reference.
287                         if let Some(deref_span) = deref_span {
288                             spans.extend(
289                                 deref_span
290                                     .iter()
291                                     .cloned()
292                                     .map(|span| (span, format!("*{}", snippet(cx, span, "<expr>")))),
293                             );
294                             spans.sort_by_key(|&(span, _)| span);
295                         }
296                         multispan_sugg(db, "consider taking a reference instead".to_string(), spans);
297                     };
298
299                     span_lint_and_then(
300                         cx,
301                         NEEDLESS_PASS_BY_VALUE,
302                         input.span,
303                         "this argument is passed by value, but not consumed in the function body",
304                         sugg,
305                     );
306                 }
307             }
308         }
309     }
310 }
311
312 /// Functions marked with these attributes must have the exact signature.
313 fn requires_exact_signature(attrs: &[Attribute]) -> bool {
314     attrs.iter().any(|attr| {
315         [sym!(proc_macro), sym!(proc_macro_attribute), sym!(proc_macro_derive)]
316             .iter()
317             .any(|&allow| attr.check_name(allow))
318     })
319 }
320
321 #[derive(Default)]
322 struct MovedVariablesCtxt {
323     moved_vars: FxHashSet<HirId>,
324     /// Spans which need to be prefixed with `*` for dereferencing the
325     /// suggested additional reference.
326     spans_need_deref: FxHashMap<HirId, FxHashSet<Span>>,
327 }
328
329 impl MovedVariablesCtxt {
330     fn move_common(&mut self, cmt: &euv::Place<'_>) {
331         if let euv::PlaceBase::Local(vid) = cmt.base {
332             self.moved_vars.insert(vid);
333         }
334     }
335 }
336
337 impl<'tcx> euv::Delegate<'tcx> for MovedVariablesCtxt {
338     fn consume(&mut self, cmt: &euv::Place<'tcx>, mode: euv::ConsumeMode) {
339         if let euv::ConsumeMode::Move = mode {
340             self.move_common(cmt);
341         }
342     }
343
344     fn borrow(&mut self, _: &euv::Place<'tcx>, _: ty::BorrowKind) {}
345
346     fn mutate(&mut self, _: &euv::Place<'tcx>) {}
347 }