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