]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/needless_pass_by_value.rs
Trigger `wrong_self_convention` only if it has implicit self
[rust.git] / clippy_lints / src / needless_pass_by_value.rs
1 use clippy_utils::diagnostics::{multispan_sugg, span_lint_and_then};
2 use clippy_utils::ptr::get_spans;
3 use clippy_utils::source::{snippet, snippet_opt};
4 use clippy_utils::ty::{implements_trait, is_copy, is_type_diagnostic_item};
5 use clippy_utils::{get_trait_def_id, is_self, paths};
6 use if_chain::if_chain;
7 use rustc_ast::ast::Attribute;
8 use rustc_data_structures::fx::FxHashSet;
9 use rustc_errors::{Applicability, DiagnosticBuilder};
10 use rustc_hir::intravisit::FnKind;
11 use rustc_hir::{BindingAnnotation, Body, FnDecl, GenericArg, HirId, Impl, ItemKind, Node, PatKind, QPath, TyKind};
12 use rustc_hir::{HirIdMap, HirIdSet};
13 use rustc_infer::infer::TyCtxtInferExt;
14 use rustc_lint::{LateContext, LateLintPass};
15 use rustc_middle::mir::FakeReadCause;
16 use rustc_middle::ty::{self, TypeFoldable};
17 use rustc_session::{declare_lint_pass, declare_tool_lint};
18 use rustc_span::symbol::kw;
19 use rustc_span::{sym, Span};
20 use rustc_target::spec::abi::Abi;
21 use rustc_trait_selection::traits;
22 use rustc_trait_selection::traits::misc::can_type_implement_copy;
23 use rustc_typeck::expr_use_visitor as euv;
24 use std::borrow::Cow;
25
26 declare_clippy_lint! {
27     /// **What it does:** Checks for functions taking arguments by value, but not
28     /// consuming them in its
29     /// body.
30     ///
31     /// **Why is this bad?** Taking arguments by reference is more flexible and can
32     /// sometimes avoid
33     /// unnecessary allocations.
34     ///
35     /// **Known problems:**
36     /// * This lint suggests taking an argument by reference,
37     /// however sometimes it is better to let users decide the argument type
38     /// (by using `Borrow` trait, for example), depending on how the function is used.
39     ///
40     /// **Example:**
41     /// ```rust
42     /// fn foo(v: Vec<i32>) {
43     ///     assert_eq!(v.len(), 42);
44     /// }
45     /// ```
46     /// should be
47     /// ```rust
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<'tcx> LateLintPass<'tcx> for NeedlessPassByValue {
70     #[allow(clippy::too_many_lines)]
71     fn check_fn(
72         &mut self,
73         cx: &LateContext<'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, _) => {
86                 let attrs = cx.tcx.hir().attrs(hir_id);
87                 if header.abi != Abi::Rust || requires_exact_signature(attrs) {
88                     return;
89                 }
90             },
91             FnKind::Method(..) => (),
92             FnKind::Closure => return,
93         }
94
95         // Exclude non-inherent impls
96         if let Some(Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_node(hir_id)) {
97             if matches!(
98                 item.kind,
99                 ItemKind::Impl(Impl { of_trait: Some(_), .. }) | ItemKind::Trait(..)
100             ) {
101                 return;
102             }
103         }
104
105         // Allow `Borrow` or functions to be taken by value
106         let borrow_trait = need!(get_trait_def_id(cx, &paths::BORROW_TRAIT));
107         let allowed_traits = [
108             need!(cx.tcx.lang_items().fn_trait()),
109             need!(cx.tcx.lang_items().fn_once_trait()),
110             need!(cx.tcx.lang_items().fn_mut_trait()),
111             need!(get_trait_def_id(cx, &paths::RANGE_ARGUMENT_TRAIT)),
112         ];
113
114         let sized_trait = need!(cx.tcx.lang_items().sized_trait());
115
116         let fn_def_id = cx.tcx.hir().local_def_id(hir_id);
117
118         let preds = traits::elaborate_predicates(cx.tcx, cx.param_env.caller_bounds().iter())
119             .filter(|p| !p.is_global())
120             .filter_map(|obligation| {
121                 // Note that we do not want to deal with qualified predicates here.
122                 match obligation.predicate.kind().no_bound_vars() {
123                     Some(ty::PredicateKind::Trait(pred, _)) if pred.def_id() != sized_trait => Some(pred),
124                     _ => None,
125                 }
126             })
127             .collect::<Vec<_>>();
128
129         // Collect moved variables and spans which will need dereferencings from the
130         // function body.
131         let MovedVariablesCtxt {
132             moved_vars,
133             spans_need_deref,
134             ..
135         } = {
136             let mut ctx = MovedVariablesCtxt::default();
137             cx.tcx.infer_ctxt().enter(|infcx| {
138                 euv::ExprUseVisitor::new(&mut ctx, &infcx, fn_def_id, cx.param_env, cx.typeck_results())
139                     .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.name == kw::SelfLower {
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.iter().filter(|t| t.self_ty() == ty).collect::<Vec<_>>();
168
169                 (
170                     preds.iter().any(|t| t.def_id() == borrow_trait),
171                     !preds.is_empty() && {
172                         let ty_empty_region = cx.tcx.mk_imm_ref(cx.tcx.lifetimes.re_root_empty, ty);
173                         preds.iter().all(|t| {
174                             let ty_params = t.trait_ref.substs.iter().skip(1).collect::<Vec<_>>();
175                             implements_trait(cx, ty_empty_region, t.def_id(), &ty_params)
176                         })
177                     },
178                 )
179             };
180
181             if_chain! {
182                 if !is_self(arg);
183                 if !ty.is_mutable_ptr();
184                 if !is_copy(cx, ty);
185                 if !allowed_traits.iter().any(|&t| implements_trait(cx, ty, t, &[]));
186                 if !implements_borrow_trait;
187                 if !all_borrowable_trait;
188
189                 if let PatKind::Binding(mode, canonical_id, ..) = arg.pat.kind;
190                 if !moved_vars.contains(&canonical_id);
191                 then {
192                     if mode == BindingAnnotation::Mutable || mode == BindingAnnotation::RefMut {
193                         continue;
194                     }
195
196                     // Dereference suggestion
197                     let sugg = |diag: &mut DiagnosticBuilder<'_>| {
198                         if let ty::Adt(def, ..) = ty.kind() {
199                             if let Some(span) = cx.tcx.hir().span_if_local(def.did) {
200                                 if can_type_implement_copy(cx.tcx, cx.param_env, ty).is_ok() {
201                                     diag.span_help(span, "consider marking this type as `Copy`");
202                                 }
203                             }
204                         }
205
206                         let deref_span = spans_need_deref.get(&canonical_id);
207                         if_chain! {
208                             if is_type_diagnostic_item(cx, ty, sym::vec_type);
209                             if let Some(clone_spans) =
210                                 get_spans(cx, Some(body.id()), idx, &[("clone", ".to_owned()")]);
211                             if let TyKind::Path(QPath::Resolved(_, path)) = input.kind;
212                             if let Some(elem_ty) = path.segments.iter()
213                                 .find(|seg| seg.ident.name == sym::Vec)
214                                 .and_then(|ps| ps.args.as_ref())
215                                 .map(|params| params.args.iter().find_map(|arg| match arg {
216                                     GenericArg::Type(ty) => Some(ty),
217                                     _ => None,
218                                 }).unwrap());
219                             then {
220                                 let slice_ty = format!("&[{}]", snippet(cx, elem_ty.span, "_"));
221                                 diag.span_suggestion(
222                                     input.span,
223                                     "consider changing the type to",
224                                     slice_ty,
225                                     Applicability::Unspecified,
226                                 );
227
228                                 for (span, suggestion) in clone_spans {
229                                     diag.span_suggestion(
230                                         span,
231                                         &snippet_opt(cx, span)
232                                             .map_or(
233                                                 "change the call to".into(),
234                                                 |x| Cow::from(format!("change `{}` to", x)),
235                                             ),
236                                         suggestion.into(),
237                                         Applicability::Unspecified,
238                                     );
239                                 }
240
241                                 // cannot be destructured, no need for `*` suggestion
242                                 assert!(deref_span.is_none());
243                                 return;
244                             }
245                         }
246
247                         if is_type_diagnostic_item(cx, ty, sym::string_type) {
248                             if let Some(clone_spans) =
249                                 get_spans(cx, Some(body.id()), idx, &[("clone", ".to_string()"), ("as_str", "")]) {
250                                 diag.span_suggestion(
251                                     input.span,
252                                     "consider changing the type to",
253                                     "&str".to_string(),
254                                     Applicability::Unspecified,
255                                 );
256
257                                 for (span, suggestion) in clone_spans {
258                                     diag.span_suggestion(
259                                         span,
260                                         &snippet_opt(cx, span)
261                                             .map_or(
262                                                 "change the call to".into(),
263                                                 |x| Cow::from(format!("change `{}` to", x))
264                                             ),
265                                         suggestion.into(),
266                                         Applicability::Unspecified,
267                                     );
268                                 }
269
270                                 assert!(deref_span.is_none());
271                                 return;
272                             }
273                         }
274
275                         let mut spans = vec![(input.span, format!("&{}", snippet(cx, input.span, "_")))];
276
277                         // Suggests adding `*` to dereference the added reference.
278                         if let Some(deref_span) = deref_span {
279                             spans.extend(
280                                 deref_span
281                                     .iter()
282                                     .copied()
283                                     .map(|span| (span, format!("*{}", snippet(cx, span, "<expr>")))),
284                             );
285                             spans.sort_by_key(|&(span, _)| span);
286                         }
287                         multispan_sugg(diag, "consider taking a reference instead", spans);
288                     };
289
290                     span_lint_and_then(
291                         cx,
292                         NEEDLESS_PASS_BY_VALUE,
293                         input.span,
294                         "this argument is passed by value, but not consumed in the function body",
295                         sugg,
296                     );
297                 }
298             }
299         }
300     }
301 }
302
303 /// Functions marked with these attributes must have the exact signature.
304 fn requires_exact_signature(attrs: &[Attribute]) -> bool {
305     attrs.iter().any(|attr| {
306         [sym::proc_macro, sym::proc_macro_attribute, sym::proc_macro_derive]
307             .iter()
308             .any(|&allow| attr.has_name(allow))
309     })
310 }
311
312 #[derive(Default)]
313 struct MovedVariablesCtxt {
314     moved_vars: HirIdSet,
315     /// Spans which need to be prefixed with `*` for dereferencing the
316     /// suggested additional reference.
317     spans_need_deref: HirIdMap<FxHashSet<Span>>,
318 }
319
320 impl MovedVariablesCtxt {
321     fn move_common(&mut self, cmt: &euv::PlaceWithHirId<'_>) {
322         if let euv::PlaceBase::Local(vid) = cmt.place.base {
323             self.moved_vars.insert(vid);
324         }
325     }
326 }
327
328 impl<'tcx> euv::Delegate<'tcx> for MovedVariablesCtxt {
329     fn consume(&mut self, cmt: &euv::PlaceWithHirId<'tcx>, _: HirId, mode: euv::ConsumeMode) {
330         if let euv::ConsumeMode::Move = mode {
331             self.move_common(cmt);
332         }
333     }
334
335     fn borrow(&mut self, _: &euv::PlaceWithHirId<'tcx>, _: HirId, _: ty::BorrowKind) {}
336
337     fn mutate(&mut self, _: &euv::PlaceWithHirId<'tcx>, _: HirId) {}
338
339     fn fake_read(&mut self, _: rustc_typeck::expr_use_visitor::Place<'tcx>, _: FakeReadCause, _: HirId) {}
340 }