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