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