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, Diagnostic};
10 use rustc_hir::intravisit::FnKind;
12 BindingAnnotation, Body, FnDecl, GenericArg, HirId, Impl, ItemKind, Mutability, Node, PatKind, QPath, TyKind,
14 use rustc_hir::{HirIdMap, HirIdSet};
15 use rustc_infer::infer::TyCtxtInferExt;
16 use rustc_lint::{LateContext, LateLintPass};
17 use rustc_middle::mir::FakeReadCause;
18 use rustc_middle::ty::{self, TypeVisitable};
19 use rustc_session::{declare_lint_pass, declare_tool_lint};
20 use rustc_span::symbol::kw;
21 use rustc_span::{sym, Span};
22 use rustc_target::spec::abi::Abi;
23 use rustc_trait_selection::traits;
24 use rustc_trait_selection::traits::misc::can_type_implement_copy;
25 use rustc_typeck::expr_use_visitor as euv;
28 declare_clippy_lint! {
30 /// Checks for functions taking arguments by value, but not
31 /// consuming them in its
34 /// ### Why is this bad?
35 /// Taking arguments by reference is more flexible and can
37 /// unnecessary allocations.
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.
46 /// fn foo(v: Vec<i32>) {
47 /// assert_eq!(v.len(), 42);
52 /// fn foo(v: &[i32]) {
53 /// assert_eq!(v.len(), 42);
56 #[clippy::version = "pre 1.29.0"]
57 pub NEEDLESS_PASS_BY_VALUE,
59 "functions taking arguments by value, but not consuming them in its body"
62 declare_lint_pass!(NeedlessPassByValue => [NEEDLESS_PASS_BY_VALUE]);
74 impl<'tcx> LateLintPass<'tcx> for NeedlessPassByValue {
75 #[expect(clippy::too_many_lines)]
78 cx: &LateContext<'tcx>,
80 decl: &'tcx FnDecl<'_>,
85 if span.from_expansion() {
90 FnKind::ItemFn(.., header) => {
91 let attrs = cx.tcx.hir().attrs(hir_id);
92 if header.abi != Abi::Rust || requires_exact_signature(attrs) {
96 FnKind::Method(..) => (),
97 FnKind::Closure => return,
100 // Exclude non-inherent impls
101 if let Some(Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_node(hir_id)) {
104 ItemKind::Impl(Impl { of_trait: Some(_), .. }) | ItemKind::Trait(..)
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)),
118 let sized_trait = need!(cx.tcx.lang_items().sized_trait());
120 let fn_def_id = cx.tcx.hir().local_def_id(hir_id);
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),
131 .collect::<Vec<_>>();
133 // Collect moved variables and spans which will need dereferencings from the
135 let MovedVariablesCtxt {
140 let mut ctx = MovedVariablesCtxt::default();
141 cx.tcx.infer_ctxt().enter(|infcx| {
142 euv::ExprUseVisitor::new(&mut ctx, &infcx, fn_def_id, cx.param_env, cx.typeck_results())
148 let fn_sig = cx.tcx.fn_sig(fn_def_id);
149 let fn_sig = cx.tcx.erase_late_bound_regions(fn_sig);
151 for (idx, ((input, &ty), arg)) in decl.inputs.iter().zip(fn_sig.inputs()).zip(body.params).enumerate() {
152 // All spans generated from a proc-macro invocation are the same...
153 if span == input.span {
159 if let PatKind::Binding(.., ident, _) = arg.pat.kind {
160 if ident.name == kw::SelfLower {
167 // * Exclude a type that is specifically bounded by `Borrow`.
168 // * Exclude a type whose reference also fulfills its bound. (e.g., `std::convert::AsRef`,
169 // `serde::Serialize`)
170 let (implements_borrow_trait, all_borrowable_trait) = {
171 let preds = preds.iter().filter(|t| t.self_ty() == ty).collect::<Vec<_>>();
174 preds.iter().any(|t| cx.tcx.is_diagnostic_item(sym::Borrow, t.def_id())),
175 !preds.is_empty() && {
176 let ty_empty_region = cx.tcx.mk_imm_ref(cx.tcx.lifetimes.re_erased, ty);
177 preds.iter().all(|t| {
178 let ty_params = t.trait_ref.substs.iter().skip(1).collect::<Vec<_>>();
179 implements_trait(cx, ty_empty_region, t.def_id(), &ty_params)
187 if !ty.is_mutable_ptr();
189 if !allowed_traits.iter().any(|&t| implements_trait(cx, ty, t, &[]));
190 if !implements_borrow_trait;
191 if !all_borrowable_trait;
193 if let PatKind::Binding(BindingAnnotation(_, Mutability::Not), canonical_id, ..) = arg.pat.kind;
194 if !moved_vars.contains(&canonical_id);
196 // Dereference suggestion
197 let sugg = |diag: &mut Diagnostic| {
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(
204 traits::ObligationCause::dummy_with_span(span),
206 diag.span_help(span, "consider marking this type as `Copy`");
211 let deref_span = spans_need_deref.get(&canonical_id);
213 if is_type_diagnostic_item(cx, ty, sym::Vec);
214 if let Some(clone_spans) =
215 get_spans(cx, Some(body.id()), idx, &[("clone", ".to_owned()")]);
216 if let TyKind::Path(QPath::Resolved(_, path)) = input.kind;
217 if let Some(elem_ty) = path.segments.iter()
218 .find(|seg| seg.ident.name == sym::Vec)
219 .and_then(|ps| ps.args.as_ref())
220 .map(|params| params.args.iter().find_map(|arg| match arg {
221 GenericArg::Type(ty) => Some(ty),
225 let slice_ty = format!("&[{}]", snippet(cx, elem_ty.span, "_"));
226 diag.span_suggestion(
228 "consider changing the type to",
230 Applicability::Unspecified,
233 for (span, suggestion) in clone_spans {
234 diag.span_suggestion(
236 snippet_opt(cx, span)
238 "change the call to".into(),
239 |x| Cow::from(format!("change `{}` to", x)),
243 Applicability::Unspecified,
247 // cannot be destructured, no need for `*` suggestion
248 assert!(deref_span.is_none());
253 if is_type_diagnostic_item(cx, ty, sym::String) {
254 if let Some(clone_spans) =
255 get_spans(cx, Some(body.id()), idx, &[("clone", ".to_string()"), ("as_str", "")]) {
256 diag.span_suggestion(
258 "consider changing the type to",
260 Applicability::Unspecified,
263 for (span, suggestion) in clone_spans {
264 diag.span_suggestion(
266 snippet_opt(cx, span)
268 "change the call to".into(),
269 |x| Cow::from(format!("change `{}` to", x))
273 Applicability::Unspecified,
277 assert!(deref_span.is_none());
282 let mut spans = vec![(input.span, format!("&{}", snippet(cx, input.span, "_")))];
284 // Suggests adding `*` to dereference the added reference.
285 if let Some(deref_span) = deref_span {
290 .map(|span| (span, format!("*{}", snippet(cx, span, "<expr>")))),
292 spans.sort_by_key(|&(span, _)| span);
294 multispan_sugg(diag, "consider taking a reference instead", spans);
299 NEEDLESS_PASS_BY_VALUE,
301 "this argument is passed by value, but not consumed in the function body",
310 /// Functions marked with these attributes must have the exact signature.
311 fn requires_exact_signature(attrs: &[Attribute]) -> bool {
312 attrs.iter().any(|attr| {
313 [sym::proc_macro, sym::proc_macro_attribute, sym::proc_macro_derive]
315 .any(|&allow| attr.has_name(allow))
320 struct MovedVariablesCtxt {
321 moved_vars: HirIdSet,
322 /// Spans which need to be prefixed with `*` for dereferencing the
323 /// suggested additional reference.
324 spans_need_deref: HirIdMap<FxHashSet<Span>>,
327 impl MovedVariablesCtxt {
328 fn move_common(&mut self, cmt: &euv::PlaceWithHirId<'_>) {
329 if let euv::PlaceBase::Local(vid) = cmt.place.base {
330 self.moved_vars.insert(vid);
335 impl<'tcx> euv::Delegate<'tcx> for MovedVariablesCtxt {
336 fn consume(&mut self, cmt: &euv::PlaceWithHirId<'tcx>, _: HirId) {
337 self.move_common(cmt);
340 fn borrow(&mut self, _: &euv::PlaceWithHirId<'tcx>, _: HirId, _: ty::BorrowKind) {}
342 fn mutate(&mut self, _: &euv::PlaceWithHirId<'tcx>, _: HirId) {}
344 fn fake_read(&mut self, _: &rustc_typeck::expr_use_visitor::PlaceWithHirId<'tcx>, _: FakeReadCause, _: HirId) {}