1 use crate::utils::ptr::get_spans;
3 get_trait_def_id, implements_trait, is_copy, is_self, is_type_diagnostic_item, match_type, multispan_sugg, paths,
4 snippet, snippet_opt, span_lint_and_then,
6 use if_chain::if_chain;
8 use rustc::hir::intravisit::FnKind;
10 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
11 use rustc::middle::expr_use_visitor as euv;
12 use rustc::middle::mem_categorization as mc;
14 use rustc::ty::{self, RegionKind, TypeFoldable};
15 use rustc::{declare_lint_pass, declare_tool_lint};
16 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
17 use rustc_errors::Applicability;
18 use rustc_target::spec::abi::Abi;
20 use syntax::ast::Attribute;
21 use syntax::errors::DiagnosticBuilder;
22 use syntax_pos::{Span, Symbol};
24 declare_clippy_lint! {
25 /// **What it does:** Checks for functions taking arguments by value, but not
26 /// consuming them in its
29 /// **Why is this bad?** Taking arguments by reference is more flexible and can
31 /// unnecessary allocations.
33 /// **Known problems:**
34 /// * This lint suggests taking an argument by reference,
35 /// however sometimes it is better to let users decide the argument type
36 /// (by using `Borrow` trait, for example), depending on how the function is used.
40 /// fn foo(v: Vec<i32>) {
41 /// assert_eq!(v.len(), 42);
47 /// fn foo(v: &[i32]) {
48 /// assert_eq!(v.len(), 42);
51 pub NEEDLESS_PASS_BY_VALUE,
53 "functions taking arguments by value, but not consuming them in its body"
56 declare_lint_pass!(NeedlessPassByValue => [NEEDLESS_PASS_BY_VALUE]);
68 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessPassByValue {
69 #[allow(clippy::too_many_lines)]
72 cx: &LateContext<'a, 'tcx>,
79 if span.from_expansion() {
84 FnKind::ItemFn(.., header, _, attrs) => {
85 if header.abi != Abi::Rust || requires_exact_signature(attrs) {
89 FnKind::Method(..) => (),
93 // Exclude non-inherent impls
94 if let Some(Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_node(hir_id)) {
95 if matches!(item.kind, ItemKind::Impl(_, _, _, _, Some(_), _, _) |
102 // Allow `Borrow` or functions to be taken by value
103 let borrow_trait = need!(get_trait_def_id(cx, &paths::BORROW_TRAIT));
104 let whitelisted_traits = [
105 need!(cx.tcx.lang_items().fn_trait()),
106 need!(cx.tcx.lang_items().fn_once_trait()),
107 need!(cx.tcx.lang_items().fn_mut_trait()),
108 need!(get_trait_def_id(cx, &paths::RANGE_ARGUMENT_TRAIT)),
111 let sized_trait = need!(cx.tcx.lang_items().sized_trait());
113 let fn_def_id = cx.tcx.hir().local_def_id(hir_id);
115 let preds = traits::elaborate_predicates(cx.tcx, cx.param_env.caller_bounds.to_vec())
116 .filter(|p| !p.is_global())
118 if let ty::Predicate::Trait(poly_trait_ref) = pred {
119 if poly_trait_ref.def_id() == sized_trait || poly_trait_ref.skip_binder().has_escaping_bound_vars()
128 .collect::<Vec<_>>();
130 // Collect moved variables and spans which will need dereferencings from the
132 let MovedVariablesCtxt {
137 let mut ctx = MovedVariablesCtxt::default();
138 let region_scope_tree = &cx.tcx.region_scope_tree(fn_def_id);
139 euv::ExprUseVisitor::new(
151 let fn_sig = cx.tcx.fn_sig(fn_def_id);
152 let fn_sig = cx.tcx.erase_late_bound_regions(&fn_sig);
154 for (idx, ((input, &ty), arg)) in decl.inputs.iter().zip(fn_sig.inputs()).zip(&body.params).enumerate() {
155 // All spans generated from a proc-macro invocation are the same...
156 if span == input.span {
162 if let PatKind::Binding(.., ident, _) = arg.pat.kind {
163 if ident.as_str() == "self" {
170 // * Exclude a type that is specifically bounded by `Borrow`.
171 // * Exclude a type whose reference also fulfills its bound. (e.g., `std::convert::AsRef`,
172 // `serde::Serialize`)
173 let (implements_borrow_trait, all_borrowable_trait) = {
176 .filter(|t| t.skip_binder().self_ty() == ty)
177 .collect::<Vec<_>>();
180 preds.iter().any(|t| t.def_id() == borrow_trait),
182 && preds.iter().all(|t| {
190 .collect::<Vec<_>>();
191 implements_trait(cx, cx.tcx.mk_imm_ref(&RegionKind::ReEmpty, ty), t.def_id(), ty_params)
198 if !ty.is_mutable_ptr();
200 if !whitelisted_traits.iter().any(|&t| implements_trait(cx, ty, t, &[]));
201 if !implements_borrow_trait;
202 if !all_borrowable_trait;
204 if let PatKind::Binding(mode, canonical_id, ..) = arg.pat.kind;
205 if !moved_vars.contains(&canonical_id);
207 if mode == BindingAnnotation::Mutable || mode == BindingAnnotation::RefMut {
211 // Dereference suggestion
212 let sugg = |db: &mut DiagnosticBuilder<'_>| {
213 if let ty::Adt(def, ..) = ty.kind {
214 if let Some(span) = cx.tcx.hir().span_if_local(def.did) {
215 if cx.param_env.can_type_implement_copy(cx.tcx, ty).is_ok() {
216 db.span_help(span, "consider marking this type as Copy");
221 let deref_span = spans_need_deref.get(&canonical_id);
223 if is_type_diagnostic_item(cx, ty, Symbol::intern("vec_type"));
224 if let Some(clone_spans) =
225 get_spans(cx, Some(body.id()), idx, &[("clone", ".to_owned()")]);
226 if let TyKind::Path(QPath::Resolved(_, ref path)) = input.kind;
227 if let Some(elem_ty) = path.segments.iter()
228 .find(|seg| seg.ident.name == sym!(Vec))
229 .and_then(|ps| ps.args.as_ref())
230 .map(|params| params.args.iter().find_map(|arg| match arg {
231 GenericArg::Type(ty) => Some(ty),
235 let slice_ty = format!("&[{}]", snippet(cx, elem_ty.span, "_"));
238 "consider changing the type to",
240 Applicability::Unspecified,
243 for (span, suggestion) in clone_spans {
246 &snippet_opt(cx, span)
248 "change the call to".into(),
249 |x| Cow::from(format!("change `{}` to", x)),
252 Applicability::Unspecified,
256 // cannot be destructured, no need for `*` suggestion
257 assert!(deref_span.is_none());
262 if match_type(cx, ty, &paths::STRING) {
263 if let Some(clone_spans) =
264 get_spans(cx, Some(body.id()), idx, &[("clone", ".to_string()"), ("as_str", "")]) {
267 "consider changing the type to",
269 Applicability::Unspecified,
272 for (span, suggestion) in clone_spans {
275 &snippet_opt(cx, span)
277 "change the call to".into(),
278 |x| Cow::from(format!("change `{}` to", x))
281 Applicability::Unspecified,
285 assert!(deref_span.is_none());
290 let mut spans = vec![(input.span, format!("&{}", snippet(cx, input.span, "_")))];
292 // Suggests adding `*` to dereference the added reference.
293 if let Some(deref_span) = deref_span {
298 .map(|span| (span, format!("*{}", snippet(cx, span, "<expr>")))),
300 spans.sort_by_key(|&(span, _)| span);
302 multispan_sugg(db, "consider taking a reference instead".to_string(), spans);
307 NEEDLESS_PASS_BY_VALUE,
309 "this argument is passed by value, but not consumed in the function body",
318 /// Functions marked with these attributes must have the exact signature.
319 fn requires_exact_signature(attrs: &[Attribute]) -> bool {
320 attrs.iter().any(|attr| {
321 [sym!(proc_macro), sym!(proc_macro_attribute), sym!(proc_macro_derive)]
323 .any(|&allow| attr.check_name(allow))
328 struct MovedVariablesCtxt {
329 moved_vars: FxHashSet<HirId>,
330 /// Spans which need to be prefixed with `*` for dereferencing the
331 /// suggested additional reference.
332 spans_need_deref: FxHashMap<HirId, FxHashSet<Span>>,
335 impl MovedVariablesCtxt {
336 fn move_common(&mut self, cmt: &mc::cmt_<'_>) {
337 let cmt = unwrap_downcast_or_interior(cmt);
339 if let mc::Categorization::Local(vid) = cmt.cat {
340 self.moved_vars.insert(vid);
345 impl<'tcx> euv::Delegate<'tcx> for MovedVariablesCtxt {
346 fn consume(&mut self, cmt: &mc::cmt_<'tcx>, mode: euv::ConsumeMode) {
347 if let euv::ConsumeMode::Move = mode {
348 self.move_common(cmt);
359 fn mutate(&mut self, _: &mc::cmt_<'tcx>) {}
362 fn unwrap_downcast_or_interior<'a, 'tcx>(mut cmt: &'a mc::cmt_<'tcx>) -> mc::cmt_<'tcx> {
365 mc::Categorization::Downcast(ref c, _) | mc::Categorization::Interior(ref c, _) => {
368 _ => return (*cmt).clone(),