1 use crate::utils::ptr::get_spans;
3 get_trait_def_id, implements_trait, is_copy, is_self, is_type_diagnostic_item, multispan_sugg, paths, snippet,
4 snippet_opt, span_lint_and_then,
6 use if_chain::if_chain;
7 use rustc_ast::ast::Attribute;
8 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
9 use rustc_errors::{Applicability, DiagnosticBuilder};
10 use rustc_hir::intravisit::FnKind;
11 use rustc_hir::{BindingAnnotation, Body, FnDecl, GenericArg, HirId, ItemKind, Node, PatKind, QPath, TyKind};
12 use rustc_infer::infer::TyCtxtInferExt;
13 use rustc_lint::{LateContext, LateLintPass};
14 use rustc_middle::ty::{self, TypeFoldable};
15 use rustc_session::{declare_lint_pass, declare_tool_lint};
17 use rustc_target::spec::abi::Abi;
18 use rustc_trait_selection::traits;
19 use rustc_trait_selection::traits::misc::can_type_implement_copy;
20 use rustc_typeck::expr_use_visitor as euv;
23 declare_clippy_lint! {
24 /// **What it does:** Checks for functions taking arguments by value, but not
25 /// consuming them in its
28 /// **Why is this bad?** Taking arguments by reference is more flexible and can
30 /// unnecessary allocations.
32 /// **Known problems:**
33 /// * This lint suggests taking an argument by reference,
34 /// however sometimes it is better to let users decide the argument type
35 /// (by using `Borrow` trait, for example), depending on how the function is used.
39 /// fn foo(v: Vec<i32>) {
40 /// assert_eq!(v.len(), 42);
46 /// fn foo(v: &[i32]) {
47 /// assert_eq!(v.len(), 42);
50 pub NEEDLESS_PASS_BY_VALUE,
52 "functions taking arguments by value, but not consuming them in its body"
55 declare_lint_pass!(NeedlessPassByValue => [NEEDLESS_PASS_BY_VALUE]);
67 impl<'tcx> LateLintPass<'tcx> for NeedlessPassByValue {
68 #[allow(clippy::too_many_lines)]
71 cx: &LateContext<'tcx>,
73 decl: &'tcx FnDecl<'_>,
78 if span.from_expansion() {
83 FnKind::ItemFn(.., header, _, attrs) => {
84 if header.abi != Abi::Rust || requires_exact_signature(attrs) {
88 FnKind::Method(..) => (),
89 FnKind::Closure(..) => return,
92 // Exclude non-inherent impls
93 if let Some(Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_node(hir_id)) {
94 if matches!(item.kind, ItemKind::Impl{ of_trait: Some(_), .. } |
101 // Allow `Borrow` or functions to be taken by value
102 let borrow_trait = need!(get_trait_def_id(cx, &paths::BORROW_TRAIT));
103 let allowed_traits = [
104 need!(cx.tcx.lang_items().fn_trait()),
105 need!(cx.tcx.lang_items().fn_once_trait()),
106 need!(cx.tcx.lang_items().fn_mut_trait()),
107 need!(get_trait_def_id(cx, &paths::RANGE_ARGUMENT_TRAIT)),
110 let sized_trait = need!(cx.tcx.lang_items().sized_trait());
112 let fn_def_id = cx.tcx.hir().local_def_id(hir_id);
114 let preds = traits::elaborate_predicates(cx.tcx, cx.param_env.caller_bounds().iter())
115 .filter(|p| !p.is_global())
116 .filter_map(|obligation| {
117 if let ty::PredicateKind::Trait(poly_trait_ref, _) = obligation.predicate.kind() {
118 if poly_trait_ref.def_id() == sized_trait || poly_trait_ref.skip_binder().has_escaping_bound_vars()
127 .collect::<Vec<_>>();
129 // Collect moved variables and spans which will need dereferencings from the
131 let MovedVariablesCtxt {
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())
144 let fn_sig = cx.tcx.fn_sig(fn_def_id);
145 let fn_sig = cx.tcx.erase_late_bound_regions(&fn_sig);
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 {
155 if let PatKind::Binding(.., ident, _) = arg.pat.kind {
156 if ident.as_str() == "self" {
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) = {
169 .filter(|t| t.skip_binder().self_ty() == ty)
170 .collect::<Vec<_>>();
173 preds.iter().any(|t| t.def_id() == borrow_trait),
174 !preds.is_empty() && {
175 let ty_empty_region = cx.tcx.mk_imm_ref(cx.tcx.lifetimes.re_root_empty, ty);
176 preds.iter().all(|t| {
177 let ty_params = &t.skip_binder().trait_ref.substs.iter().skip(1).collect::<Vec<_>>();
178 implements_trait(cx, ty_empty_region, t.def_id(), ty_params)
186 if !ty.is_mutable_ptr();
188 if !allowed_traits.iter().any(|&t| implements_trait(cx, ty, t, &[]));
189 if !implements_borrow_trait;
190 if !all_borrowable_trait;
192 if let PatKind::Binding(mode, canonical_id, ..) = arg.pat.kind;
193 if !moved_vars.contains(&canonical_id);
195 if mode == BindingAnnotation::Mutable || mode == BindingAnnotation::RefMut {
199 // Dereference suggestion
200 let sugg = |diag: &mut DiagnosticBuilder<'_>| {
201 if let ty::Adt(def, ..) = ty.kind {
202 if let Some(span) = cx.tcx.hir().span_if_local(def.did) {
203 if can_type_implement_copy(cx.tcx, cx.param_env, ty).is_ok() {
204 diag.span_help(span, "consider marking this type as `Copy`");
209 let deref_span = spans_need_deref.get(&canonical_id);
211 if is_type_diagnostic_item(cx, ty, sym!(vec_type));
212 if let Some(clone_spans) =
213 get_spans(cx, Some(body.id()), idx, &[("clone", ".to_owned()")]);
214 if let TyKind::Path(QPath::Resolved(_, ref path)) = input.kind;
215 if let Some(elem_ty) = path.segments.iter()
216 .find(|seg| seg.ident.name == sym!(Vec))
217 .and_then(|ps| ps.args.as_ref())
218 .map(|params| params.args.iter().find_map(|arg| match arg {
219 GenericArg::Type(ty) => Some(ty),
223 let slice_ty = format!("&[{}]", snippet(cx, elem_ty.span, "_"));
224 diag.span_suggestion(
226 "consider changing the type to",
228 Applicability::Unspecified,
231 for (span, suggestion) in clone_spans {
232 diag.span_suggestion(
234 &snippet_opt(cx, span)
236 "change the call to".into(),
237 |x| Cow::from(format!("change `{}` to", x)),
240 Applicability::Unspecified,
244 // cannot be destructured, no need for `*` suggestion
245 assert!(deref_span.is_none());
250 if is_type_diagnostic_item(cx, ty, sym!(string_type)) {
251 if let Some(clone_spans) =
252 get_spans(cx, Some(body.id()), idx, &[("clone", ".to_string()"), ("as_str", "")]) {
253 diag.span_suggestion(
255 "consider changing the type to",
257 Applicability::Unspecified,
260 for (span, suggestion) in clone_spans {
261 diag.span_suggestion(
263 &snippet_opt(cx, span)
265 "change the call to".into(),
266 |x| Cow::from(format!("change `{}` to", x))
269 Applicability::Unspecified,
273 assert!(deref_span.is_none());
278 let mut spans = vec![(input.span, format!("&{}", snippet(cx, input.span, "_")))];
280 // Suggests adding `*` to dereference the added reference.
281 if let Some(deref_span) = deref_span {
286 .map(|span| (span, format!("*{}", snippet(cx, span, "<expr>")))),
288 spans.sort_by_key(|&(span, _)| span);
290 multispan_sugg(diag, "consider taking a reference instead", spans);
295 NEEDLESS_PASS_BY_VALUE,
297 "this argument is passed by value, but not consumed in the function body",
306 /// Functions marked with these attributes must have the exact signature.
307 fn requires_exact_signature(attrs: &[Attribute]) -> bool {
308 attrs.iter().any(|attr| {
309 [sym!(proc_macro), sym!(proc_macro_attribute), sym!(proc_macro_derive)]
311 .any(|&allow| attr.check_name(allow))
316 struct MovedVariablesCtxt {
317 moved_vars: FxHashSet<HirId>,
318 /// Spans which need to be prefixed with `*` for dereferencing the
319 /// suggested additional reference.
320 spans_need_deref: FxHashMap<HirId, FxHashSet<Span>>,
323 impl MovedVariablesCtxt {
324 fn move_common(&mut self, cmt: &euv::PlaceWithHirId<'_>) {
325 if let euv::PlaceBase::Local(vid) = cmt.place.base {
326 self.moved_vars.insert(vid);
331 impl<'tcx> euv::Delegate<'tcx> for MovedVariablesCtxt {
332 fn consume(&mut self, cmt: &euv::PlaceWithHirId<'tcx>, mode: euv::ConsumeMode) {
333 if let euv::ConsumeMode::Move = mode {
334 self.move_common(cmt);
338 fn borrow(&mut self, _: &euv::PlaceWithHirId<'tcx>, _: ty::BorrowKind) {}
340 fn mutate(&mut self, _: &euv::PlaceWithHirId<'tcx>) {}