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