1 use crate::utils::ptr::get_spans;
3 get_trait_def_id, implements_trait, in_macro, is_copy, is_self, match_type, multispan_sugg, paths, snippet,
4 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_tool_lint, lint_array};
16 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
17 use rustc_errors::Applicability;
18 use rustc_target::spec::abi::Abi;
20 use syntax::ast::NodeId;
21 use syntax::errors::DiagnosticBuilder;
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);
43 /// fn foo(v: &[i32]) {
44 /// assert_eq!(v.len(), 42);
47 declare_clippy_lint! {
48 pub NEEDLESS_PASS_BY_VALUE,
50 "functions taking arguments by value, but not consuming them in its body"
53 pub struct NeedlessPassByValue;
55 impl LintPass for NeedlessPassByValue {
56 fn get_lints(&self) -> LintArray {
57 lint_array![NEEDLESS_PASS_BY_VALUE]
60 fn name(&self) -> &'static str {
75 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessPassByValue {
76 #[allow(clippy::too_many_lines)]
79 cx: &LateContext<'a, 'tcx>,
91 FnKind::ItemFn(.., header, _, attrs) => {
92 if header.abi != Abi::Rust {
96 if a.meta_item_list().is_some() && a.name() == "proc_macro_derive" {
101 FnKind::Method(..) => (),
105 // Exclude non-inherent impls
106 if let Some(Node::Item(item)) = cx
109 .find_by_hir_id(cx.tcx.hir().get_parent_node_by_hir_id(hir_id))
111 if matches!(item.node, ItemKind::Impl(_, _, _, _, Some(_), _, _) |
118 // Allow `Borrow` or functions to be taken by value
119 let borrow_trait = need!(get_trait_def_id(cx, &paths::BORROW_TRAIT));
120 let whitelisted_traits = [
121 need!(cx.tcx.lang_items().fn_trait()),
122 need!(cx.tcx.lang_items().fn_once_trait()),
123 need!(cx.tcx.lang_items().fn_mut_trait()),
124 need!(get_trait_def_id(cx, &paths::RANGE_ARGUMENT_TRAIT)),
127 let sized_trait = need!(cx.tcx.lang_items().sized_trait());
129 let fn_def_id = cx.tcx.hir().local_def_id_from_hir_id(hir_id);
131 let preds = traits::elaborate_predicates(cx.tcx, cx.param_env.caller_bounds.to_vec())
132 .filter(|p| !p.is_global())
134 if let ty::Predicate::Trait(poly_trait_ref) = pred {
135 if poly_trait_ref.def_id() == sized_trait || poly_trait_ref.skip_binder().has_escaping_bound_vars()
144 .collect::<Vec<_>>();
146 // Collect moved variables and spans which will need dereferencings from the
148 let MovedVariablesCtxt {
153 let mut ctx = MovedVariablesCtxt::new(cx);
154 let region_scope_tree = &cx.tcx.region_scope_tree(fn_def_id);
155 euv::ExprUseVisitor::new(&mut ctx, cx.tcx, cx.param_env, region_scope_tree, cx.tables, None)
160 let fn_sig = cx.tcx.fn_sig(fn_def_id);
161 let fn_sig = cx.tcx.erase_late_bound_regions(&fn_sig);
163 for (idx, ((input, &ty), arg)) in decl.inputs.iter().zip(fn_sig.inputs()).zip(&body.arguments).enumerate() {
164 // All spans generated from a proc-macro invocation are the same...
165 if span == input.span {
171 if let PatKind::Binding(.., ident, _) = arg.pat.node {
172 if ident.as_str() == "self" {
179 // * Exclude a type that is specifically bounded by `Borrow`.
180 // * Exclude a type whose reference also fulfills its bound. (e.g. `std::convert::AsRef`,
181 // `serde::Serialize`)
182 let (implements_borrow_trait, all_borrowable_trait) = {
185 .filter(|t| t.skip_binder().self_ty() == ty)
186 .collect::<Vec<_>>();
189 preds.iter().any(|t| t.def_id() == borrow_trait),
191 && preds.iter().all(|t| {
199 .collect::<Vec<_>>();
200 implements_trait(cx, cx.tcx.mk_imm_ref(&RegionKind::ReEmpty, ty), t.def_id(), ty_params)
207 if !ty.is_mutable_pointer();
209 if !whitelisted_traits.iter().any(|&t| implements_trait(cx, ty, t, &[]));
210 if !implements_borrow_trait;
211 if !all_borrowable_trait;
213 if let PatKind::Binding(mode, canonical_id, ..) = arg.pat.node;
214 if !moved_vars.contains(&canonical_id);
216 if mode == BindingAnnotation::Mutable || mode == BindingAnnotation::RefMut {
220 // Dereference suggestion
221 let sugg = |db: &mut DiagnosticBuilder<'_>| {
222 if let ty::Adt(def, ..) = ty.sty {
223 if let Some(span) = cx.tcx.hir().span_if_local(def.did) {
224 if cx.param_env.can_type_implement_copy(cx.tcx, ty).is_ok() {
225 db.span_help(span, "consider marking this type as Copy");
230 let deref_span = spans_need_deref.get(&canonical_id);
232 if match_type(cx, ty, &paths::VEC);
233 if let Some(clone_spans) =
234 get_spans(cx, Some(body.id()), idx, &[("clone", ".to_owned()")]);
235 if let TyKind::Path(QPath::Resolved(_, ref path)) = input.node;
236 if let Some(elem_ty) = path.segments.iter()
237 .find(|seg| seg.ident.name == "Vec")
238 .and_then(|ps| ps.args.as_ref())
239 .map(|params| params.args.iter().find_map(|arg| match arg {
240 GenericArg::Type(ty) => Some(ty),
244 let slice_ty = format!("&[{}]", snippet(cx, elem_ty.span, "_"));
247 "consider changing the type to",
249 Applicability::Unspecified,
252 for (span, suggestion) in clone_spans {
255 &snippet_opt(cx, span)
257 "change the call to".into(),
258 |x| Cow::from(format!("change `{}` to", x)),
261 Applicability::Unspecified,
265 // cannot be destructured, no need for `*` suggestion
266 assert!(deref_span.is_none());
271 if match_type(cx, ty, &paths::STRING) {
272 if let Some(clone_spans) =
273 get_spans(cx, Some(body.id()), idx, &[("clone", ".to_string()"), ("as_str", "")]) {
276 "consider changing the type to",
278 Applicability::Unspecified,
281 for (span, suggestion) in clone_spans {
284 &snippet_opt(cx, span)
286 "change the call to".into(),
287 |x| Cow::from(format!("change `{}` to", x))
290 Applicability::Unspecified,
294 assert!(deref_span.is_none());
299 let mut spans = vec![(input.span, format!("&{}", snippet(cx, input.span, "_")))];
301 // Suggests adding `*` to dereference the added reference.
302 if let Some(deref_span) = deref_span {
307 .map(|span| (span, format!("*{}", snippet(cx, span, "<expr>")))),
309 spans.sort_by_key(|&(span, _)| span);
311 multispan_sugg(db, "consider taking a reference instead".to_string(), spans);
316 NEEDLESS_PASS_BY_VALUE,
318 "this argument is passed by value, but not consumed in the function body",
327 struct MovedVariablesCtxt<'a, 'tcx: 'a> {
328 cx: &'a LateContext<'a, 'tcx>,
329 moved_vars: FxHashSet<NodeId>,
330 /// Spans which need to be prefixed with `*` for dereferencing the
331 /// suggested additional reference.
332 spans_need_deref: FxHashMap<NodeId, FxHashSet<Span>>,
335 impl<'a, 'tcx> MovedVariablesCtxt<'a, 'tcx> {
336 fn new(cx: &'a LateContext<'a, 'tcx>) -> Self {
339 moved_vars: FxHashSet::default(),
340 spans_need_deref: FxHashMap::default(),
344 fn move_common(&mut self, _consume_id: HirId, _span: Span, cmt: &mc::cmt_<'tcx>) {
345 let cmt = unwrap_downcast_or_interior(cmt);
347 if let mc::Categorization::Local(vid) = cmt.cat {
348 self.moved_vars.insert(vid);
352 fn non_moving_pat(&mut self, matched_pat: &Pat, cmt: &mc::cmt_<'tcx>) {
353 let cmt = unwrap_downcast_or_interior(cmt);
355 if let mc::Categorization::Local(vid) = cmt.cat {
356 let mut id = matched_pat.id;
358 let parent = self.cx.tcx.hir().get_parent_node(id);
365 if let Some(node) = self.cx.tcx.hir().find(id) {
368 // `match` and `if let`
369 if let ExprKind::Match(ref c, ..) = e.node {
370 self.spans_need_deref
372 .or_insert_with(FxHashSet::default)
380 if let StmtKind::Local(ref local) = s.node;
382 self.spans_need_deref
384 .or_insert_with(FxHashSet::default)
388 .expect("`let` stmt without init aren't caught by match_pat"));
401 impl<'a, 'tcx> euv::Delegate<'tcx> for MovedVariablesCtxt<'a, 'tcx> {
402 fn consume(&mut self, consume_id: HirId, consume_span: Span, cmt: &mc::cmt_<'tcx>, mode: euv::ConsumeMode) {
403 if let euv::ConsumeMode::Move(_) = mode {
404 self.move_common(consume_id, consume_span, cmt);
408 fn matched_pat(&mut self, matched_pat: &Pat, cmt: &mc::cmt_<'tcx>, mode: euv::MatchMode) {
409 if let euv::MatchMode::MovingMatch = mode {
410 self.move_common(matched_pat.hir_id, matched_pat.span, cmt);
412 self.non_moving_pat(matched_pat, cmt);
416 fn consume_pat(&mut self, consume_pat: &Pat, cmt: &mc::cmt_<'tcx>, mode: euv::ConsumeMode) {
417 if let euv::ConsumeMode::Move(_) = mode {
418 self.move_common(consume_pat.hir_id, consume_pat.span, cmt);
433 fn mutate(&mut self, _: HirId, _: Span, _: &mc::cmt_<'tcx>, _: euv::MutateMode) {}
435 fn decl_without_init(&mut self, _: NodeId, _: Span) {}
438 fn unwrap_downcast_or_interior<'a, 'tcx>(mut cmt: &'a mc::cmt_<'tcx>) -> mc::cmt_<'tcx> {
441 mc::Categorization::Downcast(ref c, _) | mc::Categorization::Interior(ref c, _) => {
444 _ => return (*cmt).clone(),